diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index fdec613767..83c583649f 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -29,11 +29,12 @@ next to them. | `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index ef75464c4f..ba7a27f507 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5047,6 +5047,7 @@ dependencies = [ "photocraft-engine", "photocraft-format", "photocraft-io", + "photocraft-raster", "photocraft-raw", "rmcp", "rustix 1.1.5", @@ -5247,6 +5248,7 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "miniz_oxide 0.9.1", "photocraft-affinity", "photocraft-algo", "photocraft-cms", diff --git a/Cargo.toml b/Cargo.toml index 3ddad59987..1bf644923d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,7 +51,7 @@ clap_complete = "4.6.11" clap_mangen = { version = "0.3.3", features = ["env"] } arc-swap = "1" bytemuck = { version = "1", features = ["derive"] } -flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } image = { version = "0.25", default-features = false } # Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg. zune-core = "0.5" diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index bf78919740..48d78aa922 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -18,10 +18,10 @@ mod recovery_tests; /// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl), swatches (.aco, .act, .ase) and keyboard shortcut sets /// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts. const OPEN_EXTS: &[&str] = &[ - "pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", - "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", "iff", "lbm", - "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act", - "ase", "kys", "af", "afdesign", "afphoto", "afpub", + "pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "dib", "tga", + "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pnm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", + "iff", "lbm", "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", + "aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; @@ -54,14 +54,14 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[ ("TIFF", &["tif", "tiff"]), ("WebP", &["webp"]), ("GIF", &["gif"]), - ("BMP", &["bmp"]), + ("BMP", &["bmp", "dib"]), ("Targa", &["tga"]), ("ICO", &["ico"]), ("QOI", &["qoi"]), ("PCX", &["pcx"]), ("DDS", &["dds"]), ("XPM", &["xpm"]), - ("Portable Bitmap", &["pbm", "pgm", "ppm", "pam", "pfm"]), + ("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]), ("OpenEXR", &["exr"]), ("Radiance HDR", &["hdr"]), ("FITS", &["fits", "fit", "fts"]), @@ -91,15 +91,19 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("PhotoCraft", &["pcraft"]), ("OpenRaster", &["ora"]), ("PNG", &["png"]), - ("JPEG", &["jpg"]), + ("JPEG", &["jpg", "jpeg"]), ("WebP", &["webp"]), - ("TIFF", &["tif"]), + ("TIFF", &["tif", "tiff"]), ("Targa", &["tga"]), // Also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to 256×256, with alpha. - ("BMP", &["bmp"]), + ("BMP", &["bmp", "dib"]), ("GIF", &["gif"]), ("ICO", &["ico"]), ("OpenEXR", &["exr"]), + // The encoder picks P5, P6, P7 or PFM from the image, not from the name, so only the neutral + // .pnm is offered: a .pbm or .pgm name would hold pixmap data (CodeRabbit on #9775). + ("Netpbm", &["pnm"]), + ("Radiance HDR", &["hdr"]), ("FITS", &["fits", "fit"]), ("DPX", &["dpx"]), // Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327). @@ -112,9 +116,21 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ /// never swaps their extension for a document format's. const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ("Color Table", &["act"]), ("Swatch Exchange", &["ase"])]; +/// `suggested` with a Netpbm subtype's extension (an opened .pgm) as the neutral .pnm, the name +/// every save dialog starts from: the encoder picks P5, P6, P7 or PFM from the image, so the old +/// suffix could name other data, and macOS and rfd keep the suggested name as it is. +fn netpbm_as_pnm(suggested: &str) -> String { + let path = Path::new(suggested); + let subtype = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).is_some_and(|e| ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&e.as_str())); + if subtype { path.with_extension("pnm").to_string_lossy().into_owned() } else { suggested.to_string() } +} + /// Lists the save dialog's file types with the `suggested` type first (added if unlisted), so the dialog keeps that extension instead of .psd. fn save_filters(suggested: &str) -> Vec<(String, Vec)> { let ext = Path::new(suggested).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + // A Netpbm subtype's name (an opened .pgm) starts on the Netpbm type as .pnm: the encoder picks + // the subtype from the image, so the old name could describe other data (CodeRabbit on #9775). + let ext = if ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&ext.as_str()) { "pnm".to_string() } else { ext }; if let Some((name, exts)) = OTHER_SAVE_FILTERS.iter().find(|(_, exts)| exts.contains(&ext.as_str())) { return vec![(name.to_string(), exts.iter().map(|e| e.to_string()).collect())]; } @@ -216,6 +232,7 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>, Box::pin(async move { picked.await.map(|folder| answer_one(folder.path(), true, FileDialogAnswer::FolderTo)) }) } FileDialogRequest::Save { suggested } => { + let suggested = netpbm_as_pnm(&suggested); let filters = save_filters(&suggested); let name = dialog_file_name(&suggested, cfg!(windows)); let dir = Path::new(&suggested).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf); diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index c04b8171df..c71074572e 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -294,9 +294,33 @@ fn save_as_offers_only_writable_formats_including_ico() { assert!(format.caps().write, "{name}: .{ext} can't be written"); } } - for ext in ["ico", "gif", "bmp", "dds"] { + for ext in ["ico", "gif", "bmp", "dds", "pnm", "hdr", "dib", "jpeg", "tiff"] { assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); } + // The codec writes P5/P6/P7/PF from the image, never from the name, so Netpbm offers only the + // neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data. + let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts); + assert_eq!(netpbm, Some(vec!["pnm".to_string()])); + // The suggested name itself becomes .pnm, as macOS and rfd keep it (CodeRabbit on #9775). + assert_eq!(netpbm_as_pnm("scans/image.pgm"), Path::new("scans/image.pnm").to_string_lossy()); + assert_eq!(netpbm_as_pnm("image.PFM"), "image.pnm"); + assert_eq!(netpbm_as_pnm("image.png"), "image.png"); + assert_eq!(netpbm_as_pnm("Untitled-1"), "Untitled-1"); + // Also when Save As starts from a subtype's name: no filter offers that subtype again. + for name in ["image.pbm", "image.pgm", "image.ppm", "image.pam", "image.pfm"] { + let filters = save_filters(name); + assert_eq!(filters[0], ("Netpbm".to_string(), vec!["pnm".to_string()]), "{name}"); + let subtype = name.rsplit('.').next().unwrap_or_default(); + assert!(!filters.iter().any(|(_, exts)| exts.iter().any(|e| e == subtype)), "{name}: .{subtype} is offered"); + } + // File › Open lists every file Save As writes, also in that format's own type (PDF is written + // but not read yet). + for (name, exts) in SAVE_FILTERS { + for ext in exts.iter().filter(|e| **e != "pdf") { + assert!(OPEN_EXTS.contains(ext), "{name}: Open's All Formats lacks .{ext}"); + assert!(OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: no Open type lists .{ext}"); + } + } assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); // What Save As writes there: an icon up to 256×256, and a clear error past that. let doc = |side: u32| { @@ -307,6 +331,11 @@ fn save_as_offers_only_writable_formats_including_ico() { let opts = export_options(&photocraft_ui_egui::ExportSettings::default()); let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap(); assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header"); + // And what the Netpbm and Radiance rows write. + let pnm = photocraft_io::export(&doc(4), "x.pnm", &opts).unwrap(); + assert_eq!(pnm.bytes[..2], *b"P6", "an RGB document saves as a binary pixmap"); + let hdr = photocraft_io::export(&doc(4), "x.hdr", &opts).unwrap(); + assert!(hdr.bytes.starts_with(b"#?RADIANCE"), "a Radiance header"); let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string(); assert!(err.contains("256"), "{err}"); } diff --git a/assets/icons/font-similar.svg b/assets/icons/font-similar.svg new file mode 100644 index 0000000000..e2399f7ab0 --- /dev/null +++ b/assets/icons/font-similar.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/font-variable.svg b/assets/icons/font-variable.svg new file mode 100644 index 0000000000..4415bcd32a --- /dev/null +++ b/assets/icons/font-variable.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs index 76ffb69f7d..96fdbd706c 100644 --- a/crates/affinity/src/container.rs +++ b/crates/affinity/src/container.rs @@ -332,7 +332,7 @@ fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { } fn inflate(data: &[u8], size: usize) -> Result, Error> { - read_bounded(flate2::read::ZlibDecoder::new(data), size) + read_bounded(flate2::bufread::ZlibDecoder::new(data), size) } fn unzstd(data: &[u8], size: usize) -> Result, Error> { diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 13ab9c527b..ba073af2ff 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] photocraft-doc = { workspace = true } +photocraft-raster = { workspace = true } photocraft-compose = { workspace = true } photocraft-codecs = { workspace = true } photocraft-io = { workspace = true } diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index fc4526eedb..0b8ff103aa 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -33,9 +33,23 @@ pub fn open(path: &Path) -> Result { let document = photocraft_format::load_path(path)?; return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); } - let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - open_bytes(&name, &bytes) + // A PSD/PSB is parsed from the open file (channel data read as it is decoded), so a CLI + // convert or info of a 2 GB file does not hold the file in memory next to the document. + #[cfg(any(unix, windows))] + { + let r = + photocraft_io::import_file(&name, path, &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE).map_err(|e| match e { + photocraft_io::IoError::Read(msg) => AutomationError::Io(msg), + e => e.into(), + })?; + Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) + } + #[cfg(not(any(unix, windows)))] + { + let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + open_bytes(&name, &bytes) + } } /// Previews for a `.pcraft` bundle. diff --git a/crates/codecs/src/codecs/deep_exr.rs b/crates/codecs/src/codecs/deep_exr.rs index 4fe9def532..0652112bf1 100644 --- a/crates/codecs/src/codecs/deep_exr.rs +++ b/crates/codecs/src/codecs/deep_exr.rs @@ -187,7 +187,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s // `read_to_end`, whose doubling reserves past `expected`. Once `expected` bytes are // in, a one-byte read checks that the stream ends there. let malformed = || err(format!("{what}: zlib data is malformed")); - let mut zlib = flate2::read::ZlibDecoder::new(packed); + let mut zlib = flate2::bufread::ZlibDecoder::new(packed); let mut out = Vec::new(); let mut filled = 0; while filled < expected { @@ -756,6 +756,7 @@ mod tests { let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); z.write_all(&p).expect("write to a Vec"); let zips = z.finish().expect("finish a Vec"); + assert!(decompress(Compression::ZIP1, &zips[..zips.len() - 1], n, "the table").is_err()); // RLE: the first byte as a literal, then runs of up to 128 copies of the next. let mut rle = vec![0xFF, p[0]]; for run in p[1..].chunks(128) { diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index 2b32a2b7c4..e179b13044 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -39,16 +39,30 @@ pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result limits.max_alloc { return Err(CodecError::LimitExceeded(format!("{total} bytes across {} parts exceed max_alloc {}", meta.headers.len(), limits.max_alloc))); } + // The `exr` crate allocates a flat part's samples before reading its chunks, so the file + // must be able to hold them (#8597). The other compressions stay far below 2^16:1 even + // against this f32 budget. DWA's run-length channels are zlib-packed on top and reach about + // 132000:1, so DWA parts get 2^18:1. Deep parts size their samples from the file's own counts. + if !meta.requirements.has_deep_data { + Limits::check_plausible(total.saturating_sub(dwa).saturating_add(dwa / 4), bytes.len(), 1 << 16)?; + } Ok(meta) } diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index 3e533ccd08..f2c4d4b9ee 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -150,8 +150,13 @@ fn data_end(b: &[u8]) -> (DataEnd, u64) { loop { let Some(&byte) = b.get(i) else { return cut(scan_data, scanned) }; if byte != 0xFF { - // Not where a marker should be: too odd to judge. - return (DataEnd::Complete, scanned); + // Not where a marker should be: skip to the next one, as a lenient decoder does, so + // segments after the stray bytes (padding among them) are still recognised. Stray + // bytes are not scan data, so they never count (junk would buy budget as padding + // did); with no marker left, the image data ends here. + let Some(p) = b.get(i..).and_then(|r| r.iter().position(|&v| v == 0xFF)) else { return cut(scan_data, scanned) }; + i += p; + continue; } let Some(&code) = b.get(i + 1) else { return cut(scan_data, scanned) }; match code { @@ -232,9 +237,10 @@ fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option) Ok((img, d.damaged)) } -/// Most pixels one byte of truncated scan data may account for. Even a flat image costs a few -/// bits per 8×8 block, and truncated photographs are far above this. -const MAX_TRUNCATED_PIXELS_PER_BYTE: u64 = 2048; +/// Most pixels one byte of a JPEG may account for. Every 8×8 block of a frame needs at least a +/// one-bit DC code (512 pixels a byte for a flat image under ideal Huffman tables), and real files, +/// truncated or not, are far above this. +const MAX_PIXELS_PER_BYTE: u64 = 2048; pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { let (end, scan_bytes) = data_end(bytes); @@ -252,7 +258,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result } if let Some((w, h, _)) = meta.frame && end == DataEnd::Truncated - && u64::from(w) * u64::from(h) / MAX_TRUNCATED_PIXELS_PER_BYTE > scan_bytes + // Only truncated scans: arithmetic coding (SOF9–SOF11) can spend well under a bit on + // a flat block, so a complete scan may be shorter than this bound. + && u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > scan_bytes { return Err(err("the truncated scan is too short for the frame it declares")); } @@ -277,12 +285,14 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result _ => (ColorSpace::RGB, ChannelLayout::Rgb), }; limits.check(w, h, layout, SampleType::U8)?; - // The backend fills whatever the scan no longer describes, so a short scan under a large - // frame is a gigabyte of synthesized output from a few kilobytes of file. The budget is - // measured on the scan data itself: APP padding can inflate `bytes.len()` arbitrarily - // without describing one more pixel. - if end == DataEnd::Truncated && u64::from(w) * u64::from(h) / MAX_TRUNCATED_PIXELS_PER_BYTE > scan_bytes { - return Err(err("the truncated scan is too short for the frame it declares")); + // The backend fills whatever the scan no longer describes, and allocates the whole output + // once a scan holds a byte, so a short scan under a large frame is a gigabyte of synthesized + // output from a few kilobytes of file (#8597), truncated or not. The budget is the scan data + // itself, not `bytes.len()`, which APP padding can inflate without describing one more pixel; + // where the walk stops early on an odd layout, what it couldn't read counts as scan data. + if u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > scan_bytes { + let what = if end == DataEnd::Truncated { "the truncated scan" } else { "the scan data" }; + return Err(err(format!("{what} is too short for the frame it declares"))); } dec.set_options(dec.options().jpeg_set_out_colorspace(out_cs)); let mut px = dec.decode().map_err(err)?; @@ -552,7 +562,7 @@ mod tests { assert_eq!(data_end(&padded).0, DataEnd::Truncated); // Well above the frame's pixels / budget, yet far above the scan data: the old // file-length bound admitted this frame. - assert!(padded.len() > (u64::from(20_000u32) * u64::from(20_000u32) / MAX_TRUNCATED_PIXELS_PER_BYTE) as usize, "padding too small"); + assert!(padded.len() > (u64::from(20_000u32) * u64::from(20_000u32) / MAX_PIXELS_PER_BYTE) as usize, "padding too small"); assert!(crate::decode_as(Format::Jpeg, &padded).is_ok()); let sof = padded.windows(2).position(|w| w == [0xFF, 0xC0] || w == [0xFF, 0xC2]).unwrap(); let mut huge = padded.clone(); @@ -561,6 +571,57 @@ mod tests { assert!(e.to_string().contains("too short"), "{e}"); } + /// A complete file is measured on its scan data too: padding can't admit an oversized frame. + /// The same padded file at its real size decodes, and so does an odd layout whose unread tail + /// counts as scan data. + #[test] + fn app_padding_cannot_admit_an_oversized_complete_frame() { + let img = Image::from_raw(16, 16, ChannelLayout::Rgb, SampleType::U8, vec![128; 16 * 16 * 3]).unwrap(); + let full = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap(); + let fill = [b'p'; 65533]; + let mut padded = full[..2].to_vec(); + for _ in 0..4 { + padded.extend_from_slice(&[0xFF, 0xFE]); + padded.extend_from_slice(&0xFFFFu16.to_be_bytes()); + padded.extend_from_slice(&fill); + } + padded.extend_from_slice(&full[2..]); + let (end, scanned) = data_end(&padded); + assert_eq!(end, DataEnd::Complete); + assert!(scanned < 1024, "the padding isn't scan data: {scanned}"); + assert!(padded.len() as u64 > u64::from(20_000u32) * 20_000 / MAX_PIXELS_PER_BYTE, "padding too small"); + assert!(crate::decode_as(Format::Jpeg, &padded).is_ok()); + let sof = padded.windows(2).position(|w| w == [0xFF, 0xC0] || w == [0xFF, 0xC2]).unwrap(); + let mut huge = padded.clone(); + huge[sof + 5..sof + 9].copy_from_slice(&[0x4E, 0x20, 0x4E, 0x20]); + let e = crate::decode_as(Format::Jpeg, &huge).unwrap_err(); + assert!(e.to_string().contains("too short"), "{e}"); + // A stray byte where a marker should be, before the padding: the walk skips it and still + // recognises the padding, so an oversized frame is refused there too. + let mut odd = huge.clone(); + odd.insert(2, 0x00); + let (end, scanned) = data_end(&odd); + assert_eq!(end, DataEnd::Complete); + assert!(scanned < 1024, "the padding after a stray byte isn't scan data: {scanned}"); + let e = crate::decode_as(Format::Jpeg, &odd).unwrap_err(); + assert!(e.to_string().contains("too short"), "{e}"); + // Stray bytes never count: 256 KiB of junk where a marker should be (the decoder skips + // it), then the oversized frame's segments, is refused. (Bytes after a scan starts are + // entropy-coded data, any value, and count as such.) + let mut junk = huge[..2].to_vec(); + junk.extend(std::iter::repeat_n(0x00u8, 4 * 65536)); + junk.extend_from_slice(&huge[2..]); + let (end, scanned) = data_end(&junk); + assert_eq!(end, DataEnd::Complete); + assert!(scanned < 1024, "junk isn't scan data: {scanned}"); + let e = crate::decode_as(Format::Jpeg, &junk).unwrap_err(); + assert!(e.to_string().contains("too short"), "{e}"); + // Junk with no marker after it: no image data at all. + let mut tail = vec![0xFF, 0xD8]; + tail.extend(std::iter::repeat_n(0x00u8, 4096)); + assert_eq!(data_end(&tail), (DataEnd::Empty, 0)); + } + /// CMYK JPEG output must omit JFIF while retaining Adobe's CMYK marker. #[test] fn cmyk_jpeg_omits_jfif_but_keeps_adobe_cmyk_marker() { diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 7fbbbc69db..e09115416c 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -419,7 +419,7 @@ fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression } let lvl = match level { PngCompression::None => flate2::Compression::none(), - PngCompression::Fast => flate2::Compression::fast(), + PngCompression::Fast => FAST, PngCompression::Default => flate2::Compression::default(), PngCompression::Best => flate2::Compression::best(), }; @@ -428,6 +428,11 @@ fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression z.finish().map_err(|e| CodecError::encode(F, e)) } +/// The deflate level of [`PngCompression::Fast`]: zlib-rs level 1 writes static Huffman blocks +/// only (20-30% bigger on filtered photos); level 3 is the lowest that is never bigger than +/// miniz's level 1 was, at about twice its time. +const FAST: flate2::Compression = flate2::Compression::new(3); + /// Images at least this large (bytes) are filtered and deflated on all cores. const PARALLEL_MIN_BYTES: usize = 4 << 20; @@ -456,7 +461,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio let band_rows = (BAND_BYTES / stride.saturating_add(1)).max(1); let bands: Vec<(usize, usize)> = (0..h).step_by(band_rows).map(|y| (y, (y + band_rows).min(h))).collect(); let lvl = match level { - PngCompression::Fast => flate2::Compression::fast(), + PngCompression::Fast => FAST, PngCompression::Best => flate2::Compression::best(), _ => flate2::Compression::default(), }; @@ -494,7 +499,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio let mut out = Vec::with_capacity(parts.iter().map(|p| p.1.len()).sum::() + 6); // zlib header: deflate, 32 K window; FLEVEL only advertises the effort. out.extend_from_slice(match level { - PngCompression::Fast => &[0x78, 0x01], + PngCompression::Fast => &[0x78, 0x5E], PngCompression::Best => &[0x78, 0xDA], _ => &[0x78, 0x9C], }); @@ -509,7 +514,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio /// Raw deflate of one band: ends on a sync flush, or finishes the stream for the `last` band. /// The output buffer is sized past deflate's worst case so that one call takes the whole band -/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's Rust +/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust /// backend) can return before compressing the last lookahead bytes, and the next call only /// drains the pending output, so a resumed flush silently drops data. `None` (the caller then /// uses the serial encoder) if the single call did not finish. diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs index 81f4a369ca..0cb0bd4202 100644 --- a/crates/codecs/src/codecs/via_image.rs +++ b/crates/codecs/src/codecs/via_image.rs @@ -93,7 +93,25 @@ fn open<'a>(f: Format, bytes: &'a [u8], limits: &Limits) -> Result u64::from(fw).saturating_mul(u64::from(fh)).saturating_mul(bpp).max(declared.saturating_sub(1 << 28)), + _ => declared, + }; + if !matches!(f, Format::Avif | Format::Hdr) && !(f == Format::Bmp && bmp_is_rle(bytes)) { + Limits::check_plausible(declared, bytes.len(), 1 << 14)?; + } Ok(dec) } @@ -123,9 +141,36 @@ pub(crate) fn probe(f: Format, bytes: &[u8], limits: &Limits) -> Result<(u32, u3 Ok((w, h, dec.exif_metadata().ok().flatten())) } +/// Whether a BMP's `biCompression` is RLE8 or RLE4 (only headers of 40 bytes or more have one). +fn bmp_is_rle(b: &[u8]) -> bool { + let u32_at = |at: usize| b.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + u32_at(14).is_some_and(|n| n >= 40) && matches!(u32_at(30), Some(1 | 2)) +} + +/// The width and height of a GIF's first image descriptor, if the blocks reach one. +fn gif_first_frame(b: &[u8]) -> Option<(u32, u32)> { + let mut at = None; + gif_walk(b, |i| { + at = Some(i); + false + }); + let u16_at = |at: usize| b.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + // Descriptor: separator, left, top, width, height (little-endian u16s), packed fields. + let i = at?; + Some((u32::from(u16_at(i + 5)?), u32::from(u16_at(i + 7)?))) +} + /// Counts a GIF's frames (image descriptors) by walking its blocks, without decompressing any. /// The total is unknown when the blocks end before the trailer or break off. fn gif_more_frames(b: &[u8]) -> Option { + let (frames, total) = gif_walk(b, |_| true); + (frames > 1).then_some(DecodeWarning::MoreFrames { total }) +} + +/// Walks a GIF's blocks without decompressing any, handing `frame` the offset of each image +/// descriptor until it returns false. Gives the descriptors seen, and the frame count if the +/// blocks reached the trailer. +fn gif_walk(b: &[u8], mut frame: impl FnMut(usize) -> bool) -> (u32, Option) { // Size of the colour table a packed-fields byte announces. let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 }; // Skips the data sub-blocks starting at `i` (each length-prefixed, ended by a zero length). @@ -139,7 +184,10 @@ fn gif_more_frames(b: &[u8]) -> Option { } }; // Header (6 bytes), logical screen descriptor (7) and the global colour table. - let mut i = 13 + table(*b.get(10)?); + let Some(&flags) = b.get(10) else { + return (0, None); + }; + let mut i = 13 + table(flags); let mut frames = 0u32; let total = loop { let next = match b.get(i) { @@ -147,6 +195,9 @@ fn gif_more_frames(b: &[u8]) -> Option { Some(0x21) => skip(i + 2), Some(0x2C) => { frames = frames.saturating_add(1); + if !frame(i) { + break None; + } // Descriptor (10 bytes, packed fields last), local colour table, LZW code size. b.get(i + 9).and_then(|&flags| skip(i + 11 + table(flags))) } @@ -157,7 +208,7 @@ fn gif_more_frames(b: &[u8]) -> Option { None => break None, } }; - (frames > 1).then_some(DecodeWarning::MoreFrames { total }) + (frames, total) } pub(crate) fn from_dynamic(f: Format, d: DynamicImage) -> Result { diff --git a/crates/codecs/tests/it/limits.rs b/crates/codecs/tests/it/limits.rs index c1873771f6..536e303039 100644 --- a/crates/codecs/tests/it/limits.rs +++ b/crates/codecs/tests/it/limits.rs @@ -398,6 +398,12 @@ fn pnm_header_alone_reserves_nothing_without_limits() { } } +#[test] +fn hdr_header_sizes_that_overflow_u64_are_errors_without_limits() { + let b = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 2147483648 +X 2147483648\n"; + assert!(decode_with(b, &opts(Limits::none())).is_err()); +} + #[test] fn pnm_header_sizes_that_overflow_usize_are_errors_without_limits() { let m = u32::MAX; @@ -456,3 +462,179 @@ fn limits_check_api() { assert!(l.check(10, 10, ChannelLayout::Rgba, SampleType::U8).is_err()); assert!(l.check(10, 10, ChannelLayout::Rgb, SampleType::U8).is_ok()); } + +/// #8597: a small file whose header declares about 3 GB, inside the default limits, is refused +/// by the size-against-file check before the decoder allocates its output. +fn refused_as_implausible(f: Format, b: &[u8]) { + match decode(b) { + Err(CodecError::LimitExceeded(m)) => assert!(m.contains("cannot hold"), "{f:?}: {m}"), + other => panic!("{f:?}: expected an implausible-size refusal, got {:?}", other.map(|i| (i.width(), i.height()))), + } +} + +fn find(b: &[u8], needle: &[u8]) -> usize { + b.windows(needle.len()).position(|w| w == needle).unwrap() +} + +#[test] +fn jpeg_header_declaring_gigabytes_needs_a_plausible_file_size() { + let mut b = encoded(Format::Jpeg); + // SOF0: marker, length, precision, then height and width (big-endian). + let sof = find(&b, &[0xFF, 0xC0]); + b[sof + 5..sof + 7].copy_from_slice(&16000u16.to_be_bytes()); + b[sof + 7..sof + 9].copy_from_slice(&65000u16.to_be_bytes()); + // The decoder's own scan-size guard refuses it (one refusal path for truncated and complete + // files alike), before the backend allocates the frame. + match decode(&b) { + Err(e) => assert!(e.to_string().contains("too short for the frame"), "{e}"), + Ok(i) => panic!("decoded a {}×{} frame from {} bytes", i.width(), i.height(), b.len()), + } +} + +#[test] +fn image_crate_headers_declaring_gigabytes_need_a_plausible_file_size() { + let side = 30000u32; + let mut bmp = encoded(Format::Bmp); + bmp[18..22].copy_from_slice(&(side as i32).to_le_bytes()); + bmp[22..26].copy_from_slice(&(side as i32).to_le_bytes()); + refused_as_implausible(Format::Bmp, &bmp); + let mut qoi = encoded(Format::Qoi); + // The qoi crate refuses more than 400 M pixels itself, so 20000 x 20000 (1.6 GB). + qoi[4..8].copy_from_slice(&20000u32.to_be_bytes()); + qoi[8..12].copy_from_slice(&20000u32.to_be_bytes()); + refused_as_implausible(Format::Qoi, &qoi); + let mut gif = encoded(Format::Gif); + gif[6..8].copy_from_slice(&(side as u16).to_le_bytes()); + gif[8..10].copy_from_slice(&(side as u16).to_le_bytes()); + refused_as_implausible(Format::Gif, &gif); + // The frame too. Descriptor: separator, left, top, width, height. + let frame = find(&gif, &[0x2C, 0, 0, 0, 0, 64, 0, 48, 0]); + gif[frame + 5..frame + 7].copy_from_slice(&(side as u16).to_le_bytes()); + gif[frame + 7..frame + 9].copy_from_slice(&(side as u16).to_le_bytes()); + refused_as_implausible(Format::Gif, &gif); +} + +/// GIF89a with a two-colour global table and one frame at the top left holding no pixels or +/// one pixel (LZW minimum code size 2: clear, index 0, end of information). +fn tiny_gif(screen: (u16, u16), frame: (u16, u16)) -> Vec { + let mut b = b"GIF89a".to_vec(); + for v in [screen.0, screen.1] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(&[0x80, 0, 0, 0, 0, 0, 255, 255, 255, 0x2C, 0, 0, 0, 0]); + for v in [frame.0, frame.1] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(&[0, 2, 2, 0x44, 0x01, 0, 0x3B]); + b +} + +#[test] +fn a_gif_frame_much_smaller_than_its_screen_still_decodes() { + let img = decode(&tiny_gif((4000, 4000), (1, 1))).unwrap(); + assert_eq!((img.width(), img.height()), (4000, 4000)); +} + +#[test] +fn a_tiny_gif_frame_does_not_admit_a_gigabyte_screen() { + refused_as_implausible(Format::Gif, &tiny_gif((30000, 30000), (1, 1))); + // 324 MB of screen: past the 256 MiB that needs no data. + refused_as_implausible(Format::Gif, &tiny_gif((9000, 9000), (1, 1))); + refused_as_implausible(Format::Gif, &tiny_gif((30000, 30000), (0, 0))); + // A frame bigger than its screen is decoded at its own size. + refused_as_implausible(Format::Gif, &tiny_gif((100, 100), (40000, 40000))); +} + +#[test] +fn an_rle_bmp_ending_early_still_decodes() { + // 4000x4000 RLE8 whose only data is the end-of-bitmap escape: every pixel is left at index 0. + let data = 14 + 40 + 1024; + let mut b = b"BM".to_vec(); + for v in [data + 2, 0, data, 40, 4000, 4000] { + b.extend_from_slice(&(v as u32).to_le_bytes()); + } + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&8u16.to_le_bytes()); + for v in [1, 2, 0, 0, 0, 0] { + b.extend_from_slice(&(v as u32).to_le_bytes()); + } + b.resize(data, 0); + b.extend_from_slice(&[0, 1]); + let img = decode(&b).unwrap(); + assert_eq!((img.width(), img.height()), (4000, 4000)); +} + +#[test] +fn pcx_header_declaring_gigabytes_needs_a_plausible_file_size() { + // 24-bit (three 8-bit planes) 65535 x 16384, with one row of data. + let mut b = vec![0u8; 128]; + b[0] = 0x0a; + b[1] = 5; + b[2] = 1; + b[3] = 8; + b[8..10].copy_from_slice(&65534u16.to_le_bytes()); + b[10..12].copy_from_slice(&16383u16.to_le_bytes()); + b[65] = 3; + b[66..68].copy_from_slice(&65535u16.to_le_bytes()); + b[68..70].copy_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&[0xff, 0]); + // PCX's own minimum-packet check refuses it before the output is allocated. + match decode(&b) { + Err(CodecError::Malformed { message, .. }) => assert!(message.contains("too short"), "{message}"), + other => panic!("expected a too-short refusal, got {:?}", other.map(|i| (i.width(), i.height()))), + } +} + +#[test] +fn xpm_rows_shorter_than_the_header_declares_are_refused_before_allocating() { + let b = b"/* XPM */\nstatic char *x[] = {\n\"30000 30000 1 1\",\n\". c #000000\",\n\".\",\n};\n".to_vec(); + match decode(&b) { + Err(CodecError::Malformed { .. }) => {} + other => panic!("expected a malformed-row error, got {:?}", other.map(|i| (i.width(), i.height()))), + } +} + +#[test] +fn exr_header_declaring_gigabytes_needs_a_plausible_file_size() { + let mut b = encoded(Format::OpenExr); + // dataWindow: name, type, size, then xMin, yMin, xMax, yMax (little-endian i32). + let at = find(&b, b"dataWindow\0box2i\0") + b"dataWindow\0box2i\0".len() + 4; + b[at + 8..at + 12].copy_from_slice(&15999i32.to_le_bytes()); + b[at + 12..at + 16].copy_from_slice(&15999i32.to_le_bytes()); + refused_as_implausible(Format::OpenExr, &b); +} + +#[test] +fn a_dwab_exr_gets_a_looser_file_size_bound() { + // DWA passes 2^16:1 (a flat 8K frame with 12 alpha-scheme mattes is about 30 KB), so a DWAB + // part may declare 4 times more than a ZIP part from the same file, and no more. + let img = synth(1, 1, ChannelLayout::Rgba, SampleType::U8, 1, 0.1); + let mut b = encode(&img, Format::OpenExr, &EncodeOptions::default()).unwrap(); + let at = find(&b, b"dataWindow\0box2i\0") + b"dataWindow\0box2i\0".len() + 4; + let c = find(&b, b"compression\0compression\0") + b"compression\0compression\0".len() + 4; + // RGBA as f32: 16 bytes a pixel against a file of a few hundred bytes. + let size = |b: &mut Vec, side: i32| { + b[at + 8..at + 12].copy_from_slice(&(side - 1).to_le_bytes()); + b[at + 12..at + 16].copy_from_slice(&(side - 1).to_le_bytes()); + }; + let refused = |b: &[u8]| matches!(exr_info(b, &Limits::default()), Err(CodecError::LimitExceeded(m)) if m.contains("cannot hold")); + size(&mut b, 2048); + b[c] = 3; // ZIP + assert!(refused(&b), "{} bytes", b.len()); + for dwa in [8, 9] { + b[c] = dwa; // DWAA, DWAB + let parts = exr_info(&b, &Limits::default()).unwrap(); + assert_eq!((parts[0].width, parts[0].height), (2048, 2048)); + } + size(&mut b, 4096); + assert!(refused(&b), "{} bytes", b.len()); +} + +#[test] +fn highly_compressible_jpeg_and_gif_still_decode() { + let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap(); + for f in [Format::Jpeg, Format::Gif, Format::Qoi, Format::OpenExr] { + let b = encode(&img, f, &EncodeOptions::default()).unwrap(); + assert_eq!(decode(&b).unwrap().width(), 3000, "{f:?}"); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dde9acc16f..fc8442d67a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -82,6 +82,7 @@ pub mod file_cmds; pub mod fill_cmds; pub mod fill_key_cmds; pub mod float_cmds; +pub mod font_library_cmds; pub(super) mod frame_cmds; pub mod fx_view_cmds; pub mod fx_visibility_cmds; @@ -438,26 +439,41 @@ fn build() -> Vec { "Layer…", ["Layer", "New"], Some("Cmd+Shift+N"), - r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)}"##, + r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##, has_doc, crate::new_layer::run ), - cmd!("layer.new.group", "Group…", ["Layer", "New"], None, r##"{"name":str?}"##, has_doc, |s, p| { - let id = s.edit("New Group", |doc, active| { - let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| doc.next_layer_name("Group")); - let id = doc.insert_above(*active, Layer::group(name, vec![])); - *active = Some(id); - Ok(id) - })?; - crate::layer_multi_cmds::note_inert_insert(s, id); - Ok(json!({ "layer": id.0 })) - }), + cmd!( + "layer.new.group", + "Group…", + ["Layer", "New"], + None, + r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##, + has_doc, + |s, p| { + let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; + let below = crate::group_options::below("layer.new.group", p)?; + let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; + let id = s.edit("New Group", |doc, active| { + let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); + let mut group = Layer::group(name, vec![]); + opts.apply(&mut group); + let bg = crate::background_cmds::background_id(doc); + let id = crate::layer_place::insert_new(doc, *active, group, place); + crate::background_cmds::keep_background_at_bottom(bg, doc)?; + *active = Some(id); + Ok(id) + })?; + crate::layer_multi_cmds::note_inert_insert(s, id); + Ok(json!({ "layer": id.0 })) + } + ), cmd!( "layer.groupLayers", "Group Layers", ["Layer"], Some("Cmd+G"), - r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##, + r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, has_layer, crate::layer_multi_cmds::group_layers ), @@ -778,7 +794,7 @@ fn build() -> Vec { let fill = Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode); let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; @@ -810,7 +826,7 @@ fn build() -> Vec { .in_mode(doc.mode); let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; @@ -902,7 +918,7 @@ fn build() -> Vec { "Brush Stroke", [], None, - r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, has_paintable, crate::brush_cmds::paint_stroke ), @@ -1277,6 +1293,7 @@ fn build() -> Vec { v.extend(crate::distort_cmds::specs()); v.extend(crate::analysis_cmds::specs()); v.extend(crate::notes_cmds::specs()); + v.extend(crate::font_library_cmds::specs()); v.extend(crate::history_cmds::specs()); v.extend(crate::history_options_cmds::specs()); v.extend(crate::history_menu_cmds::specs()); diff --git a/crates/engine/src/cmd/adjust_params.rs b/crates/engine/src/cmd/adjust_params.rs index d70ff79dcb..50a2fec992 100644 --- a/crates/engine/src/cmd/adjust_params.rs +++ b/crates/engine/src/cmd/adjust_params.rs @@ -9,7 +9,7 @@ pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: & let id = s.edit(&label, |doc, active| { let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj)); mask_new_layer(doc, &mut l, p, cmd, true)?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/align_cmds.rs b/crates/engine/src/cmd/align_cmds.rs index 869d29b724..1cddbb51cd 100644 --- a/crates/engine/src/cmd/align_cmds.rs +++ b/crates/engine/src/cmd/align_cmds.rs @@ -313,7 +313,7 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result { surf.write_region(area, px); surf.prune(); } - below = doc.insert_above(Some(below), l); + below = crate::layer_place::insert_new(doc, Some(below), l, crate::layer_place::Place::Above); below }); let Some(px) = &blended else { @@ -327,7 +327,7 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result { surf.write_region(area, px); surf.prune(); } - let nid = doc.insert_above(Some(below), l); + let nid = crate::layer_place::insert_new(doc, Some(below), l, crate::layer_place::Place::Above); *active = Some(nid); Ok((Some(nid), depth_id)) })?; diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 5394c0193c..2f05ddfae0 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -320,12 +320,35 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// The layers' union bounds, or the canvas when they have none: the board Artboard from Layers +/// makes when no size is given. +fn union_bounds<'a>(layers: impl IntoIterator, canvas: Rect) -> Rect { + layers.into_iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas) +} + +/// What Artboard from Layers' dialog opens with, as in the reference application: the name the +/// board would get and the selected top-level layers' size (`None` without a document). +pub fn from_layers_defaults(s: &Session) -> Option<(String, [i64; 2])> { + let d = s.active()?; + let ids = crate::layer_multi_cmds::top_level(&d.doc, &crate::layer_multi_cmds::selected(s)); + let [_, _, w, h] = xywh(union_bounds(ids.iter().filter_map(|id| d.doc.layer(*id)), d.doc.bounds())); + Some((next_artboard_name(&d.doc), [w, h])) +} + fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { let sel = crate::layer_multi_cmds::selected(s); let d = s.active().ok_or(EngineError::NoDocument)?; let canvas = d.doc.bounds(); - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let background = background_param(p, "layer.new.artboardFromLayers")?.unwrap_or_default(); + let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); + let cmd = "layer.new.artboardFromLayers"; + let background = background_param(p, cmd)?.unwrap_or_default(); + // `int` rounds, so a small negative (-0.4) would pass as 0, "keep the bounds". + if ["width", "height"].iter().any(|k| p.get(*k).and_then(Value::as_f64).is_some_and(|v| v < 0.0)) { + return Err(bad(cmd, "the artboard width and height must not be negative")); + } + // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps + // their bounds on that axis (#9087). + let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; let (gid, rect) = s.edit("Artboard from Layers", |doc, active| { let ids = crate::layer_multi_cmds::top_level(doc, &sel); if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) { @@ -335,7 +358,8 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { for id in &ids { children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); } - let rect = children.iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas); + let [x, y, w, h] = xywh(union_bounds(&children, canvas)); + let rect = board_rect(cmd, [x, y, size[0].unwrap_or(w), size[1].unwrap_or(h)])?; let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), children); set_artboard(&mut g, Artboard { rect, background, preset: String::new() }); let gid = doc.insert_above(None, g); @@ -687,7 +711,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromLayers", "Artboard from Layers…", &["Layer", "New"], - r##"{"name":str?,"background":…?} (the selected layers) → {layer, rect}"##, + r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 0 keeps their bounds) → {layer, rect}"##, has_free_layers, artboard_from_layers ), diff --git a/crates/engine/src/cmd/artboard_cmds/tests.rs b/crates/engine/src/cmd/artboard_cmds/tests.rs index ad3f7a46d0..d21011a71b 100644 --- a/crates/engine/src/cmd/artboard_cmds/tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/tests.rs @@ -690,3 +690,43 @@ fn new_document_with_an_artboard() { assert!(doc(&s).artboards().is_empty()); assert!(s.execute("file.new", json!({"artboard": "yes"})).is_err()); } + +/// #9087: Artboard from Layers takes a size of the user's own, from the layers' top left; 0 or +/// none keeps their bounds on that axis, and a negative size is refused. +#[test] +fn artboard_from_layers_takes_a_custom_size() { + for (params, want) in [ + (json!({"width": 108, "height": 135}), [10, 10, 108, 135]), + (json!({"width": 0, "height": 0}), [10, 10, 20, 20]), + (json!({"width": 60}), [10, 10, 60, 20]), + ] { + let mut s = session(8); + add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); + let r = s.execute("layer.new.artboardFromLayers", params.clone()).unwrap(); + assert_eq!(r["rect"], json!(want), "{params}"); + } + let mut s = session(8); + add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); + assert!(s.execute("layer.new.artboardFromLayers", json!({"width": -5})).is_err()); + // `int` rounds -0.4 to 0, which would otherwise keep the bounds. + assert!(s.execute("layer.new.artboardFromLayers", json!({"height": -0.4})).is_err()); + assert!(doc(&s).artboards().is_empty(), "a refused size changes nothing"); + assert_eq!(s.execute("layer.new.artboardFromLayers", json!({"name": ""})).unwrap()["rect"], json!([10, 10, 20, 20])); + assert_eq!(doc(&s).artboards()[0].1, "Artboard 1", "an empty name gives Artboard N"); +} + +/// The dialog's defaults (#9087): the selected layers' size and the board's name, as the command +/// makes it with no size; the canvas when the layers have no pixels. +#[test] +fn from_layers_defaults_are_the_selected_layers_size() { + let mut s = session(8); + add_square(&mut s, Rect::new(10, 10, 30, 40), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(from_layers_defaults(&s), Some(("Artboard 1".to_string(), [20, 30]))); + s.execute("layer.new.artboardFromLayers", json!({})).unwrap(); + add_square(&mut s, Rect::new(50, 5, 60, 10), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(from_layers_defaults(&s), Some(("Artboard 2".to_string(), [10, 5]))); + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(from_layers_defaults(&s), Some(("Artboard 1".to_string(), [100, 80])), "an empty layer: the canvas"); + assert_eq!(from_layers_defaults(&Session::new()), None); +} diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 49d55f3e09..05af865ddc 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -422,9 +422,93 @@ pub fn paint_stroke(s: &mut Session, p: &Value) -> Result { let pts = parse_points(p, "paint.stroke")?; let brush = with_blend_mode(resolve_brush(s, p, "paint.stroke")?, p); let label = if brush.erase && !clear_mode(p) { "Eraser" } else { "Brush Tool" }; + if flag(p, "fill", false) { + return fill_region(s, p, label, brush, pts); + } stroke_with(s, "paint.stroke", p, label, brush, pts, false) } +/// `paint.stroke {fill: true}`: fill the region enclosed by `points` (their polygon) with the +/// brush's colour and opacity, its edge anti-aliased and softened by the brush hardness, instead of +/// stamping the outline. A closed gesture then paints a filled dab, not a ring (#3659). +fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec) -> Result { + if clear_mode(p) { + // `clear` maps onto the eraser; a clear fill would erase the region the outline encloses, + // which a selection + delete does deliberately (#3659). Reject before the eraser check so + // the message names the real conflict. + return Err(bad("paint.stroke", "\"fill\" cannot be combined with \"mode\":\"clear\"; select the enclosed region and delete it instead")); + } + if brush.erase { + return Err(bad("paint.stroke", "\"fill\" does not support the Eraser")); + } + if pts.len() < 3 { + return Err(bad("paint.stroke", "\"fill\" needs at least three points (a closed region)")); + } + let (id, brush, _zoom) = stroke_target(s, p, brush)?; + // A hard brush (hardness 1) keeps the anti-aliased polygon edge; a soft one feathers it by half + // the brush width, the way its tip fades. + let feather_px = ((1.0 - brush.hardness.clamp(0.0, 1.0)) * brush.size * 0.5).max(0.0); + let (color, opacity, mode) = (brush.color, brush.opacity.clamp(0.0, 1.0), brush.mode); + // A colour picked as CMYK fills with its inks in a CMYK target where it covers fully, as + // Edit › Fill does (blend_color_mask blends partial coverage through the colour's RGB). + let picked = brush.color_cmyk.filter(|(rgb, _)| *rgb == [color[0], color[1], color[2]]).map(|(_, inks)| inks); + let cmyk = doc_cmyk_space(s); + let dmg = photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + let canvas = doc.bounds(); + let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; + // The polygon's whole-pixel bounds, grown by the feather's reach (3σ) so a soft edge + // fades out instead of being clipped. + let (mut bx0, mut by0, mut bx1, mut by1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for sp in &pts { + if !(sp.x.is_finite() && sp.y.is_finite()) { + return Err(bad("paint.stroke", "non-finite point in a fill")); + } + bx0 = bx0.min(sp.x); + by0 = by0.min(sp.y); + bx1 = bx1.max(sp.x); + by1 = by1.max(sp.y); + } + let ix = |v: f64| v.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32; + let reach = photocraft_algo::selection::feather_reach(feather_px); + let pad = i32::try_from(reach).unwrap_or(i32::MAX).saturating_add(2); + let bounds = Rect::new( + ix(bx0.floor()).saturating_sub(pad), + ix(by0.floor()).saturating_sub(pad), + ix(bx1.ceil()).saturating_add(pad), + ix(by1.ceil()).saturating_add(pad), + ) + .intersect(&canvas); + if bounds.is_empty() { + return Ok(Rect::new(0, 0, 0, 0)); + } + let (w, h) = (bounds.width() as usize, bounds.height() as usize); + // The coverage, its feathered copy (and the blur's scratch), the selection read and + // the mask are each a buffer over the whole region, which can be the whole canvas: + // reserve that peak first, so a region too big for memory is an error, not an abort. + const FILL: &str = "filling a painted region"; + let peak = w.checked_mul(h).and_then(|n| n.checked_mul(5)).ok_or_else(|| crate::allocation::error(FILL, "requested size overflowed"))?; + drop(crate::allocation::capacity::(peak, FILL)?); + let xy: Vec<(f32, f32)> = pts.iter().map(|sp| (sp.x as f32, sp.y as f32)).collect(); + let mut cov = photocraft_algo::selection::polygon(&xy, bounds, true); + if feather_px > 0.01 { + cov = photocraft_algo::selection::feather(&cov, w, h, feather_px); + } + if let Some(sel) = sel.as_ref() { + let sv = crate::allocation::read_region(sel, bounds, FILL)?; + for (c, s) in cov.iter_mut().zip(&sv) { + *c *= s.clamp(0.0, 1.0); + } + } + let coverage = photocraft_algo::selection::mask_to_surface(&cov, bounds); + crate::fill_cmds::blend_color_mask(surf, bounds, color, picked, &coverage, mode, opacity, lock)?; + Ok(bounds) + }) + })?; + Ok(damage_json(s, dmg)) +} + /// A `paint.stroke` rendered while it is drawn, onto a copy of the active document, so the canvas /// shows the real dabs before the stroke commits. Committing the same params and points with /// `"seed": live.seed` gives the same pixels. diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 87504dc0e9..3a3041c4a6 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -31,6 +31,93 @@ fn stroke_backwards_compatible() { assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } +#[test] +fn fill_fills_the_enclosed_region_not_the_outline() { + // #3659: a closed gesture with `fill` paints the interior, not a ring. + let mut s = session(60, 60); + s.execute( + "paint.stroke", + json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "size": 4, "color": "#ff0000", "brush": {"hardness": 1.0}}), + ) + .unwrap(); + assert!(rgba(&s, 30, 30)[0] > 0.9 && rgba(&s, 30, 30)[3] > 0.9, "interior filled: {:?}", rgba(&s, 30, 30)); + assert_eq!(rgba(&s, 5, 30)[3], 0.0, "outside untouched"); + assert_eq!(rgba(&s, 30, 5)[3], 0.0, "outside untouched"); + // A soft brush feathers the edge outside the polygon; a hard one keeps a crisp edge. + let mut soft = session(60, 60); + soft.execute( + "paint.stroke", + json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "size": 40, "color": "#ff0000", "brush": {"hardness": 0.0}}), + ) + .unwrap(); + assert!(rgba(&soft, 8, 30)[3] > 0.0, "a soft edge paints outside the polygon: {:?}", rgba(&soft, 8, 30)); + // Graceful failures: fewer than three points, and the Eraser. + assert!(s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10]], "fill": true})).is_err()); + assert!(s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10], [50, 50]], "fill": true, "erase": true})).is_err()); + // One history step, like a normal stroke. + let before = s.active().unwrap().history.past_len(); + s.execute("paint.stroke", json!({"points": [[12, 12], [48, 12], [48, 48], [12, 48]], "fill": true, "color": "#0000ff"})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "fill is one history step"); +} + +#[test] +fn fill_is_rejected_with_clear_mode() { + // #3659 review: `"mode":"clear"` maps onto the eraser, so a clear fill would erase the region + // the outline encloses. Reject it; a selection + delete does that deliberately. + let mut s = session(60, 60); + let poly = json!([[10, 10], [50, 10], [50, 50], [10, 50]]); + assert!(s.execute("paint.stroke", json!({"points": poly.clone(), "fill": true, "mode": "clear"})).is_err()); + // `clear` without `fill` still erases along the outline (main's behaviour), unchanged. + s.execute("paint.stroke", json!({"points": poly, "fill": true, "size": 4, "color": "#ff0000"})).unwrap(); + assert!(rgba(&s, 30, 30)[3] > 0.9, "the region is filled first"); + s.execute("paint.stroke", json!({"points": [[30, 2], [30, 58]], "size": 10, "mode": "clear"})).unwrap(); + assert!(rgba(&s, 30, 30)[3] < 0.01, "a clear stroke erased what it crossed"); + assert!(rgba(&s, 12, 30)[3] > 0.9, "pixels the clear stroke missed remain"); +} + +#[test] +fn fill_soft_edge_has_no_step() { + // #3779: the feather (σ = 20 here) reaches 3σ = 60 px past the square; the fill's working + // bounds must reach as far, or the soft edge ends in a hard step where they clip it. + let mut s = session(200, 200); + s.execute( + "paint.stroke", + json!({"points": [[80, 80], [120, 80], [120, 120], [80, 120]], "fill": true, "size": 40, "color": "#ff0000", "brush": {"hardness": 0.0}}), + ) + .unwrap(); + assert!(rgba(&s, 57, 100)[3] > 0.0, "the fade continues past 1σ: {:?}", rgba(&s, 57, 100)); + for x in 0..199 { + let (a, b) = (rgba(&s, x, 100)[3], rgba(&s, x + 1, 100)[3]); + assert!((a - b).abs() < 0.03, "step between x={x} ({a}) and x={} ({b})", x + 1); + } +} + +#[test] +fn fill_paints_a_cmyk_pick_with_the_picked_inks() { + // #3779: like a plain stroke (#4344), a fill paints a colour picked as CMYK as its inks. + let cyan = [1.0f32, 0.0, 0.0, 0.0]; + let mut s = session(16, 16); + s.execute("image.mode.cmyk", json!({})).unwrap(); + let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap(); + s.execute("paint.stroke", json!({"points": [[2, 2], [14, 2], [14, 14], [2, 14]], "fill": true, "hardness": 1.0})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let got: Vec = surf.read_region(Rect::new(8, 8, 9, 9)).into_iter().take(4).collect(); + assert!(got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02), "{got:?}"); +} + +#[test] +fn fill_works_on_cmyk_and_16_and_32_bit() { + for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 30, "mode": mode, "depth": depth})).unwrap(); + s.execute("paint.stroke", json!({"points": [[10, 5], [50, 5], [50, 25], [10, 25]], "fill": true, "color": "#000000", "hardness": 1.0})).unwrap(); + assert!(rgba(&s, 30, 15)[0] < 0.2, "{mode}/{depth}: {:?}", rgba(&s, 30, 15)); + assert!(rgba(&s, 5, 15)[0] > 0.8, "{mode}/{depth} outside: {:?}", rgba(&s, 5, 15)); + } +} + #[test] fn stroke_accepts_full_points_brush_and_preset() { let mut s = session(200, 100); @@ -493,6 +580,23 @@ fn define_brush_from_selection() { assert!(rgba(&s, 30, 32)[3] > 0.9); } +#[test] +fn fill_survives_allocation_failure() { + // CodeRabbit on #9775: a fill's buffers span the region, up to the whole canvas. Their peak is + // reserved through the fallible allocator before any of them is built, so running out of + // memory is the fill's own error, leaving the pixels and history alone, never an abort. + let mut s = session(60, 60); + let pixels_before = surface(&s); + let history_before = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "color": "#ff0000"})); + let _ = crate::allocation::capacity::(0, "reset failpoint"); + let err = result.expect_err("an allocation failure must be reported, not panic").to_string(); + assert!(err.contains("filling a painted region"), "the fill reserves its buffers first: {err}"); + assert_eq!(surface(&s), pixels_before, "no pixels changed"); + assert_eq!(s.active().unwrap().history.past_len(), history_before, "no history step was recorded"); +} + #[test] fn define_brush_from_selection_survives_allocation_failure() { // The sampled tip is one f32 buffer over the whole selection, and the selection mask is a diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs index fc3eb3226d..71800c63c6 100644 --- a/crates/engine/src/cmd/edit_cmds.rs +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -403,7 +403,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { let id = s.edit("Paste", |doc, active| { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = surf; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); doc.selection = None; Ok(id) @@ -445,9 +445,13 @@ fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result< let id = s.edit("Paste", |doc, active| { doc.patterns.extend(patterns); doc.metadata.psd_global_blocks.extend(linked); + // The first pasted layer goes where a new layer would; the rest stack above it. + let mut place = crate::layer_place::Place::AutoEditable; for l in copies.layers { - *active = Some(doc.insert_above(*active, l)); + *active = Some(crate::layer_place::insert_new(doc, *active, l, place)); + place = crate::layer_place::Place::Above; } + crate::cmd::layer_multi_cmds::check_group_depth(doc, "Paste")?; doc.selection = None; active.ok_or(EngineError::Other("nothing to paste".into())) })?; @@ -587,7 +591,7 @@ fn layer_via(s: &mut Session, cut: bool) -> Result { } let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format()); *crate::pixels_mut(&mut l)? = clip.surface; - let nid = doc.insert_above(Some(id), l); + let nid = crate::layer_place::insert_new(doc, Some(id), l, crate::layer_place::Place::Above); *active = Some(nid); // Photoshop deselects: a following Free Transform moves the whole new layer (#1096). doc.selection = None; diff --git a/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs index 0fe3cedd3f..e15cc6e080 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs @@ -503,7 +503,7 @@ fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: & s.write_region(window, &px); s.prune(); } - let nid = doc.insert_above(Some(id), l); + let nid = crate::layer_place::insert_new(doc, Some(id), l, crate::layer_place::Place::Above); *active = Some(nid); return Ok(nid); } diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 24685387f0..05d2214186 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -138,12 +138,16 @@ pub(crate) fn process_tree( /// The extension a batch output takes with Format "Same": the input's own, except for formats /// PhotoCraft opens but can't write, camera raws above all (#5799: a folder of ARWs failed on -/// every file). Those are saved as PSD, the format Photoshop's Save As offers for a raw. An input -/// whose file name has no extension (a dot in a folder name doesn't count) is saved as PNG. +/// every file), GIMP files (`gz` is the last extension of `.xcf.gz`), Photoshop templates and the +/// codec formats without a writer in this build. Those are saved as PSD, the format Photoshop's +/// Save As offers for a raw. An input whose file name has no extension (a dot in a folder name +/// doesn't count) is saved as PNG. pub(super) fn same_format(path: &str) -> String { - const IMPORT_ONLY: &[&str] = &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm"]; + const IMPORT_ONLY: &[&str] = + &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm", "xcf", "xcfgz", "gz", "psdt"]; let ext = extension(path).unwrap_or_else(|| "png".into()); - if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) { "psd".into() } else { ext } + let no_writer = photocraft_codecs::from_extension(&ext).is_some_and(|f| !f.caps().write); + if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) || no_writer { "psd".into() } else { ext } } #[cfg(test)] @@ -155,6 +159,17 @@ fn same_format_takes_the_file_names_extension() { assert_eq!(same_format("/in/IMG_0001.HEIC"), "psd"); assert_eq!(same_format("/in/logo.svg"), "psd"); assert_eq!(same_format("/in/scan.cin"), "psd"); + // Formats PhotoCraft opens and does not write are saved as PSD. + for name in ["/in/scan.dcm", "/in/scan.DICOM", "/in/scan.dc3", "/in/page.xcf", "/in/page.xcf.gz", "/in/page.xcfgz", "/in/card.psdt"] { + assert_eq!(same_format(name), "psd", "{name}"); + } + for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read && !f.caps().write) { + for ext in f.extensions() { + assert_eq!(same_format(&format!("/in/a.{ext}")), "psd", "{f:?} .{ext}"); + } + } + assert_eq!(same_format("/in/a.pam"), "pam"); + assert_eq!(same_format("/in/a.dds"), "dds"); // No extension in the file name: PNG, not the path after a dot in a folder name. assert_eq!(same_format("/in/v1.2/scan"), "png"); assert_eq!(same_format("C:\\in.d\\scan"), "png"); diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index d95174ad9d..ff73c338e5 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -202,7 +202,7 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option Result> { Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) } -/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, or GIMP's -/// gzipped `.xcf.gz`, whose last extension alone says nothing. +/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, an extension +/// of a format `photocraft-codecs` reads in this build, or GIMP's gzipped `.xcf.gz`, whose last +/// extension alone says nothing. #[cfg(not(target_arch = "wasm32"))] pub(super) fn openable_name(path: &str) -> bool { let lower = file_name(path).to_ascii_lowercase(); - lower.ends_with(".xcf.gz") || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext)) + lower.ends_with(".xcf.gz") + || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext) || photocraft_codecs::from_extension(ext).is_some_and(|f| f.caps().read)) } -/// Extensions the batch commands pick up from a folder. +/// Extensions the batch commands pick up from a folder besides the codec formats: the document +/// and vector formats `photocraft_io::import` reads outside `photocraft-codecs`, and the camera +/// raws whose usual files `photocraft_raw::decode` develops. Not CR3, ORF, RAF, RW2, SRF or SR2: +/// CR3, compressed ORF and RAF and RW2 raw formats other than 3, 4 and 5 aren't decoded yet, and +/// import falls back to the embedded JPEG preview with only a warning, which a batch must not +/// process silently. #[cfg(not(target_arch = "wasm32"))] const OPENABLE: &[&str] = &[ - "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", - "ico", "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", - "afphoto", "afpub", + "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "af", "afdesign", "afphoto", "afpub", "dng", "cr2", "nef", + "nrw", "arw", "pef", ]; pub(crate) fn file_name(path: &str) -> String { diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 2a23dde9f1..7eb770d844 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1835,6 +1835,50 @@ fn folder_listing_recognises_gzipped_xcf_by_its_double_extension() { assert!(!super::openable_name("notes.txt")); } +/// A folder batch picks up every extension that the codecs open: Cineon, DICOM, Amiga IFF, PCX, +/// XPM, DDS, the Netpbm family, and Photoshop templates. Not the raws whose usual files open only +/// as the embedded JPEG preview (CR3, compressed ORF and RAF, RW2 other than raw formats 3, 4 and +/// 5): a batch would process the thumbnail without a word. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn folder_listing_takes_every_format_photocraft_opens() { + let codecs = ["a.cin", "a.dcm", "a.dicom", "a.dc3", "a.iff", "a.lbm", "a.ilbm", "a.pcx", "a.xpm", "a.dds", "a.pbm", "a.pam", "a.pfm", "a.psdt", "A.PCX"]; + let raws = ["a.dng", "IMG_0001.CR2", "a.nef", "a.nrw", "a.arw", "a.pef"]; + for name in codecs.into_iter().chain(raws) { + assert!(super::openable_name(name), "{name}"); + } + for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read) { + for ext in f.extensions() { + assert!(super::openable_name(&format!("a.{ext}")), "{f:?} .{ext}"); + } + } + for name in ["a.cr3", "IMG_0001.CR3", "a.orf", "a.raf", "a.rw2", "a.srf", "a.sr2"] { + assert!(!super::openable_name(name), "{name}"); + } + // PhotoCraft does not read AVIF. + assert!(!super::openable_name("a.avif")); +} + +/// A batch over a folder processes PAM, PFM and DDS files instead of skipping them. +#[test] +fn batch_folder_processes_netpbm_and_dds_files() { + let dir = tmp("batch-folder-formats"); + let src = join(&dir, "in"); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "#ff0000"})).unwrap(); + for name in ["a.pam", "b.pfm", "c.dds"] { + save_doc(doc(&s), &join(&src, name), None).unwrap(); + } + std::fs::write(join(&src, "notes.txt"), b"not an image").unwrap(); + let out = join(&dir, "out"); + let r = Session::new().execute("file.automate.batch", json!({"steps": [], "input": src, "output": out, "format": "png"})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let mut files: Vec = r["files"].as_array().unwrap().iter().map(|f| file_name(f.as_str().unwrap())).collect(); + files.sort(); + assert_eq!(files, ["a.png", "b.png", "c.png"], "{r}"); +} + /// The Compression tag (259) of a TIFF's first directory. fn tiff_compression_tag(b: &[u8]) -> Option { let le = b.get(..2)? == b"II"; diff --git a/crates/engine/src/cmd/font_library_cmds.rs b/crates/engine/src/cmd/font_library_cmds.rs new file mode 100644 index 0000000000..7b3fb271ae --- /dev/null +++ b/crates/engine/src/cmd/font_library_cmds.rs @@ -0,0 +1,105 @@ +//! The font menu's favourite font families: the star beside each font, kept until un-starred. They +//! live in the preferences, so they survive a restart, and are plain family names: a favourite +//! whose font is uninstalled is kept, though the menu lists installed fonts only, and shows it +//! again once the font is back (`type.font.favorite` with `"on": false` removes it). (The +//! recently used fonts are the shell's, `PhotocraftApp::note_recent_font`.) + +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +/// The most favourites kept (a hand-edited preferences file can't grow the menu without bound). +pub const MAX_FAVORITE_FONTS: usize = 1000; +/// The longest family name accepted, in characters. +const MAX_FAMILY_CHARS: usize = 256; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +/// The `family` param: a non-empty name without control characters, trimmed. +fn family(p: &Value, cmd: &str) -> Result { + let name = p.get("family").and_then(Value::as_str).ok_or_else(|| bad(cmd, "pass `family`, a font family name"))?.trim(); + if name.is_empty() { + return Err(bad(cmd, "`family` is empty")); + } + if name.chars().count() > MAX_FAMILY_CHARS { + return Err(bad(cmd, format!("`family` is longer than {MAX_FAMILY_CHARS} characters"))); + } + if name.chars().any(char::is_control) { + return Err(bad(cmd, "`family` contains control characters")); + } + Ok(name.to_string()) +} + +/// The favourites as the menu shows them: valid names, once each, at most [`MAX_FAVORITE_FONTS`]. +pub fn favorite_fonts(s: &Session) -> Vec { + let mut out: Vec = Vec::new(); + for f in &s.prefs().type_.favorite_fonts { + if out.len() >= MAX_FAVORITE_FONTS { + break; + } + if !f.trim().is_empty() && !out.contains(f) { + out.push(f.clone()); + } + } + out +} + +/// Star or un-star a family (`on` sets it; without it the star toggles). +fn favorite(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "type.font.favorite"; + let name = family(p, CMD)?; + let mut list = favorite_fonts(s); + let on = match p.get("on") { + None => !list.contains(&name), + Some(v) => v.as_bool().ok_or_else(|| bad(CMD, "`on` must be true or false"))?, + }; + list.retain(|f| *f != name); + if on { + if list.len() >= MAX_FAVORITE_FONTS { + return Err(bad(CMD, format!("at most {MAX_FAVORITE_FONTS} favourite fonts"))); + } + list.push(name.clone()); + } + let stored = list.clone(); + s.prefs.edit(|p| p.type_.favorite_fonts = stored); + Ok(json!({"family": name, "favorite": on, "favorites": list})) +} + +fn library(s: &mut Session, _: &Value) -> Result { + Ok(json!({"favorites": favorite_fonts(s)})) +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "type.font.favorite", + label: "Add to Favorites", + menu: &[], + shortcut: None, + params: r#"{"family":str,"on":bool?=toggle} → family, favorite, favorites"#, + enabled: always, + run: favorite, + journal: false, + }, + CommandSpec { + id: "type.font.library", + label: "Font Library", + menu: &[], + shortcut: None, + params: "{} → favorites", + enabled: always, + run: library, + journal: false, + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/font_library_cmds/tests.rs b/crates/engine/src/cmd/font_library_cmds/tests.rs new file mode 100644 index 0000000000..c31c65353a --- /dev/null +++ b/crates/engine/src/cmd/font_library_cmds/tests.rs @@ -0,0 +1,79 @@ +use serde_json::json; + +use super::*; + +fn session() -> Session { + Session::new() +} + +#[test] +fn starring_toggles_and_on_sets_a_favourite() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap(); + assert_eq!(favorite_fonts(&s), ["Arial", "Bebas Neue"]); + // Toggling again removes it; `on` sets it either way. + let r = s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + assert_eq!(r["favorite"], false); + s.execute("type.font.favorite", json!({"family": "Bebas Neue", "on": true})).unwrap(); + assert_eq!(favorite_fonts(&s), ["Bebas Neue"], "on: true doesn't duplicate"); + s.execute("type.font.favorite", json!({"family": "Bebas Neue", "on": false})).unwrap(); + assert!(favorite_fonts(&s).is_empty()); +} + +#[test] +fn resetting_the_type_preferences_keeps_the_favourites() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap(); + s.execute("prefs.set", json!({"path": "type.smartQuotes", "value": false})).unwrap(); + s.execute("prefs.reset", json!({"path": "type"})).unwrap(); + assert!(s.prefs().type_.smart_quotes, "the Type settings are reset"); + assert_eq!(favorite_fonts(&s), ["Bebas Neue"], "the favourites are the user's library, not a setting"); + // Asked for by name, or with everything, they go. + s.execute("prefs.reset", json!({"path": "type.favoriteFonts"})).unwrap(); + assert!(favorite_fonts(&s).is_empty()); + s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap(); + s.execute("prefs.reset", json!({})).unwrap(); + assert!(favorite_fonts(&s).is_empty()); +} + +#[test] +fn the_library_survives_a_preferences_round_trip_and_hostile_lists_are_tidied() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + let saved = serde_json::to_value(s.prefs()).unwrap(); + assert_eq!(saved["type"]["favoriteFonts"], json!(["Arial"])); + let mut t = session(); + let prefs = serde_json::from_value(saved).unwrap(); + t.prefs.edit(|p| *p = prefs); + let lib = t.execute("type.font.library", json!({})).unwrap(); + assert_eq!(lib, json!({"favorites": ["Arial"]})); + // Duplicates, blanks and an oversized list from a hand-edited file are tidied on read. + t.prefs.edit(|p| p.type_.favorite_fonts = (0..5000).map(|i| format!("F{}", i % 1200)).chain([String::new()]).collect()); + assert_eq!(favorite_fonts(&t).len(), MAX_FAVORITE_FONTS); +} + +#[test] +fn bad_params_are_errors_and_change_nothing() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + for (id, p) in [ + ("type.font.favorite", json!({})), + ("type.font.favorite", json!({"family": 42})), + ("type.font.favorite", json!({"family": " "})), + ("type.font.favorite", json!({"family": "a\u{0}b"})), + ("type.font.favorite", json!({"family": "x".repeat(300)})), + ("type.font.favorite", json!({"family": "Arial", "on": "yes"})), + ] { + assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); + } + assert_eq!(favorite_fonts(&s), ["Arial"]); +} + +#[test] +fn font_library_edits_are_not_recorded_into_actions() { + // Playing an action back must not rewrite the user's favourite fonts. + for id in ["type.font.favorite", "type.font.library"] { + assert!(!crate::actions_cmds::replayable(id), "{id}"); + } +} diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index c006b730cd..c2cd6283a7 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -146,9 +146,15 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { crate::layer_multi_cmds::check_group_depth(doc, "New Frame")?; gid } - None => doc.insert_above(*active, Layer::group(name, vec![])), + None => crate::layer_place::insert_new(doc, *active, Layer::group(name, vec![]), crate::layer_place::Place::AutoEditable), }; - doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?.mask = Some(mask); + let frame = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; + frame.mask = Some(mask); + // A frame is one row, as in Photoshop: closed, so the next new layer goes above it rather + // than into it. + if let LayerContent::Group(g) = &mut frame.content { + g.expanded = false; + } *active = Some(gid); Ok(gid) })?; diff --git a/crates/engine/src/cmd/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs index 138be5bbeb..41f91f8bbb 100644 --- a/crates/engine/src/cmd/gradient_fill_cmds.rs +++ b/crates/engine/src/cmd/gradient_fill_cmds.rs @@ -322,7 +322,7 @@ fn create(s: &mut Session, p: &Value) -> Result { new_layer(s, &d.doc, p)? }; let id = s.edit("New Gradient Fill Layer", |doc, active| { - let id = doc.insert_above(*active, layer); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs index 78e72f0a7b..631cceac65 100644 --- a/crates/engine/src/cmd/layer_copy_cmds.rs +++ b/crates/engine/src/cmd/layer_copy_cmds.rs @@ -216,8 +216,11 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result { doc.patterns.extend(patterns); let mut above = *active; let mut new = Vec::with_capacity(copies.layers.len()); + // The first copy goes where a new layer would; the rest stack above it. + let mut place = crate::layer_place::Place::AutoEditable; for l in copies.layers { - let id = doc.insert_above(above, l); + let id = crate::layer_place::insert_new(doc, above, l, place); + place = crate::layer_place::Place::Above; above = Some(id); new.push(id); } diff --git a/crates/engine/src/cmd/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs index 3966432975..52f36b9ffa 100644 --- a/crates/engine/src/cmd/layer_multi_cmds.rs +++ b/crates/engine/src/cmd/layer_multi_cmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Group from Layers…", &["Layer", "New"], None, - r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##, + r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, has_layer, group_layers ), diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index c8146901bc..60d193c6d3 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -97,7 +97,7 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { /// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves /// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is -/// preserved. +/// preserved. The New Group dialog's colour, mode and opacity are set in the same history step. pub fn group_layers(s: &mut Session, p: &Value) -> Result { let ids = match crate::commands::explicit_layer(s, p)? { Some(id) => vec![id], @@ -106,11 +106,15 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(EngineError::Other("no layer selected".into())); } - let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let opts = crate::group_options::GroupOptions::parse("layer.groupLayers", p)?; let gid = s.edit("Group Layers", |doc, active| { let ids = top_level(doc, &ids); + // Artboards stay at the top level: inside a group they would stop being boards. + if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) { + return Err(EngineError::Other("artboards can't go into a group".into())); + } let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; - let name = name.unwrap_or_else(|| doc.next_layer_name("Group")); + let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); // Photoshop creates the group collapsed, so the panel shows one row in place of the layers. let mut group = Layer::group(name, vec![]); if let LayerContent::Group(g) = &mut group.content { @@ -121,7 +125,9 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result { for id in &ids { children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); } - *doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children; + let group = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; + *group.children_mut().ok_or(EngineError::NoLayer(gid))? = children; + opts.apply(group); check_group_depth(doc, "Group Layers")?; *active = Some(gid); Ok(gid) diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs index e8dd5a98f3..e03081a598 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -918,6 +918,31 @@ fn group_from_layers_preserves_order() { assert!(matches!(&doc(&s).layer(g).unwrap().content, LayerContent::Group(gr) if !gr.expanded)); } +/// Artboards are top-level groups; grouping them (now a plain click on the Layers panel's New +/// Group button with two boards selected) is refused and leaves them as they were. +#[test] +fn grouping_artboards_is_refused() { + let mut s = session(8); + let a = LayerId(s.execute("layer.new.artboard", json!({"rect": [0, 0, 100, 80]})).unwrap()["layer"].as_u64().unwrap()); + let b = LayerId(s.execute("layer.new.artboard", json!({"rect": [120, 0, 100, 80]})).unwrap()["layer"].as_u64().unwrap()); + select_all(&mut s, &[a, b]); + let before = doc(&s).clone(); + let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); + assert!(err.to_string().contains("artboards"), "{err}"); + assert!(s.execute("layer.groupLayers", json!({"layer": a.0})).is_err(), "one board is refused too"); + assert_eq!(doc(&s).layers.iter().map(|l| l.id).collect::>(), before.layers.iter().map(|l| l.id).collect::>()); + assert_eq!(doc(&s).artboards().len(), 2); + // A layer inside a board still groups, inside its board. (Made with no layer selected: a + // new layer with a board selected goes into that board, as in Photoshop.) + s.execute("select.deselectLayers", json!({})).unwrap(); + let inner = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[inner]); + let c = LayerId(s.execute("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(doc(&s).artboard_of(inner), Some(c)); + let g = LayerId(s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(doc(&s).artboard_of(g), Some(c)); +} + #[test] fn grouping_is_capped_at_the_document_nesting_limit() { let mut s = session(8); diff --git a/crates/engine/src/cmd/layer_nav_cmds.rs b/crates/engine/src/cmd/layer_nav_cmds.rs index b41a18b590..bf02936418 100644 --- a/crates/engine/src/cmd/layer_nav_cmds.rs +++ b/crates/engine/src/cmd/layer_nav_cmds.rs @@ -118,8 +118,10 @@ mod tests { s.execute("layer.select", json!({"layer": c.0, "mode": "add"})).unwrap(); s.execute("layer.groupLayers", json!({})).unwrap(); let group = s.active().unwrap().doc.layers.iter().find(|l| l.is_group()).unwrap().id; - s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})).unwrap(); + // D goes above the closed group (an open one would take it inside, as in Photoshop). let d = id(&mut s, "layer.new.layer", json!({"name": "D"})); + // Group Layers makes a collapsed group; open it so the panel shows B and C. + s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})).unwrap(); (s, [bg, a, group, b, c, d]) } diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index 503ac8efae..d06b0fb29c 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -6,7 +6,8 @@ //! //! Every command targets a path like `path.transform`: `"name":"work"` (default), a saved path's //! name, or `"layer"` with `"layer":id?` for a shape layer's path (re-rendered; it stops being a -//! live shape) or a layer's vector mask. Knots are addressed by `subpath` and `knot` index, as +//! live shape), a layer's vector mask, or type on a path's Type Path (`"typePath":true` when the +//! type layer also has a vector mask). Knots are addressed by `subpath` and `knot` index, as //! listed by `path.info`, and the result is `{name, path}` in the compact JSON form. use photocraft_doc::{LayerContent, Path}; @@ -49,6 +50,23 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> { fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result { let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); let layer = if name == "layer" { Some(layer_id(s, p)?) } else { None }; + // Type on a path: its own path, the text laid along it again (#9114). A vector mask on the + // layer stays what `"layer"` edits, as with `path.info`, unless `"typePath": true`. + let type_path = p.get("typePath").and_then(Value::as_bool).unwrap_or(false); + let typed = layer.filter(|id| { + s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| { + matches!(&l.content, LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some()) && (type_path || l.vector_mask.is_none()) + }) + }); + if let Some(id) = typed { + let path = crate::type_extra_cmds::with_text(s, &json!({"layer": id.0}), label, |t, _| { + let mut path = crate::type_extra_cmds::type_path(t).ok_or_else(|| bad(cmd, "the type layer is not on a path"))?; + f(&mut path).map_err(|e| bad(cmd, e))?; + crate::type_extra_cmds::set_type_path(t, &path)?; + Ok(path_json(&path)) + })?; + return Ok(json!({ "name": name, "path": path })); + } let shape = layer.filter(|id| s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)))); let path = match shape { Some(id) => with_shape(s, id, label, |sh, _| { @@ -149,7 +167,7 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result { } pub fn specs() -> Vec { - const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#; + const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path, a vector mask, or else type on a path's Type Path),"typePath":bool=false (with "layer": the Type Path even when the type layer has a vector mask)"#; let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result| CommandSpec { id, label, diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index 5aab2887f0..4bc972556a 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -348,7 +348,7 @@ pub(crate) fn insert_fill_layer( let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase }; let mut l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill)); crate::commands::mask_new_layer(doc, &mut l, p, "layer.newFillLayer.pattern", default_mask)?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) } diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index 9b26b637c0..37b4e78e92 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -508,8 +508,10 @@ fn pdf_string(s: &str) -> String { } fn deflate(data: &[u8]) -> Vec { - // Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default. - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static + // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger + // than miniz's level 1 was, at about twice its time. + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3)); let _ = e.write_all(data); e.finish().unwrap_or_default() } diff --git a/crates/engine/src/cmd/render_cmds.rs b/crates/engine/src/cmd/render_cmds.rs index c6e4318e3d..cc27304fdc 100644 --- a/crates/engine/src/cmd/render_cmds.rs +++ b/crates/engine/src/cmd/render_cmds.rs @@ -109,7 +109,7 @@ fn draw(s: &mut Session, label: &str, p: &Value, prims: Vec, extra: Value) let raster = id.and_then(|i| doc.layer(i)).is_some_and(|l| matches!(l.content, LayerContent::Raster(_))); let (id, created) = if want_new || !raster { let l = Layer::new(label.trim_end_matches('…'), LayerContent::Raster(Surface::new(doc.pixel_format()))); - let nid = doc.insert_above(*active, l); + let nid = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(nid); (nid, true) } else { diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index d7283e247d..da9183169f 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","strokes":[[[x,y,pressure?],…],…]? (several strokes removed together, as one job and one undo step; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"# + r#","strokes":[[[x,y,pressure?],…]|{"points":[…],"size"?,"hardness"?,"spacing"?},…]? (several strokes removed together, as one job and one undo step, each with its own size, hardness and spacing when given; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"# ), enabled: has_pixel_layer, run: remove::remove, diff --git a/crates/engine/src/cmd/retouch_cmds/remove.rs b/crates/engine/src/cmd/retouch_cmds/remove.rs index d298e8f02c..7444826eba 100644 --- a/crates/engine/src/cmd/retouch_cmds/remove.rs +++ b/crates/engine/src/cmd/retouch_cmds/remove.rs @@ -74,17 +74,32 @@ fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec, Option reject_huge_stroke(CMD, &stroke)?; return Ok((vec![stroke], id)); }; - let list = list.as_array().ok_or_else(|| bad(CMD, "`strokes` is a list of point lists"))?; + const ENTRY: &str = "each `strokes` entry is a point list or {\"points\", \"size\"?, \"hardness\"?, \"spacing\"?}"; + let list = list.as_array().ok_or_else(|| bad(CMD, ENTRY))?; if list.is_empty() { return Err(bad(CMD, "`strokes` is empty")); } let mut strokes = Vec::with_capacity(list.len()); let mut id = None; - for points in list { + for entry in list { let mut one = p.clone(); - if let Some(o) = one.as_object_mut() { - o.remove("strokes"); - o.insert("points".into(), points.clone()); + let Some(o) = one.as_object_mut() else { return Err(bad(CMD, "params must be an object")) }; + o.remove("strokes"); + match entry { + // A stroke drawn with another brush than the rest (the waiting strokes of Remove after + // each stroke off keep the size, hardness and spacing each was drawn with). + Value::Object(e) => { + let points = e.get("points").ok_or_else(|| bad(CMD, ENTRY))?; + o.insert("points".into(), points.clone()); + for k in ["size", "hardness", "spacing"] { + if let Some(v) = e.get(k) { + o.insert(k.into(), v.clone()); + } + } + } + points => { + o.insert("points".into(), points.clone()); + } } let (stroke, layer) = parse_brush(s, &one, CMD)?; reject_huge_stroke(CMD, &stroke)?; @@ -201,7 +216,8 @@ fn fill_to_new_layer(doc: &mut Document, id: Option, out: &Region, hole } let mut l = Layer::raster(doc.next_layer_name("Layer"), fmt); crate::pixels_mut(&mut l)?.write_region(out.rect, &data); - let nid = doc.insert_above(id, l); + // Above the sampled layer and in its clipping mask, like Layer via Copy. + let nid = crate::layer_place::insert_new(doc, id, l, crate::layer_place::Place::Above); Ok((out.rect, nid)) } diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index b0d5c7bb18..a1329064d2 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2156,6 +2156,27 @@ fn remove_several_strokes_apply_as_one_job_and_one_undo_step() { } } +/// A `strokes` entry may carry its own size, hardness and spacing: the Remove Tool's waiting +/// strokes keep the brush each was drawn with, whatever the brush is when they are applied. +#[test] +fn remove_strokes_each_keep_their_own_brush() { + let entry = |pts: Value, size: f64| json!({"points": pts, "size": size, "hardness": 100, "spacing": 25}); + let removed = |strokes: Value, size: f64| { + let mut s = square_session(8, "rgb"); + let bg = rgba(&s, 10, 10); + s.execute("paint.remove", json!({"strokes": strokes, "size": size})).unwrap(); + [(41, 30), (46, 30), (51, 30)].iter().all(|&(x, y)| near(rgba(&s, x, y), bg, 0.03)) + }; + let (a, b) = (json!([[38, 30], [45, 30]]), json!([[47, 30], [54, 30]])); + assert!(removed(json!([entry(a.clone(), 16.0), entry(b.clone(), 16.0)]), 2.0), "each entry's 16 px, not the 2 px of the call"); + assert!(!removed(json!([entry(a.clone(), 2.0), entry(b.clone(), 2.0)]), 16.0), "each entry's 2 px, not the 16 px of the call"); + assert!(removed(json!([entry(a, 16.0), b]), 16.0), "a plain point list takes the call's brush"); + let mut s = square_session(8, "rgb"); + for strokes in [json!([{"size": 16}]), json!([{"points": "x"}]), json!([{"points": []}]), json!([7])] { + assert!(s.execute("paint.remove", json!({"strokes": strokes, "size": 16})).is_err(), "{strokes}"); + } +} + #[test] fn remove_to_a_new_layer_leaves_the_target_untouched() { let mut s = square_session(8, "rgb"); diff --git a/crates/engine/src/cmd/stamp_cmds.rs b/crates/engine/src/cmd/stamp_cmds.rs index 76af35627a..b5c6a21120 100644 --- a/crates/engine/src/cmd/stamp_cmds.rs +++ b/crates/engine/src/cmd/stamp_cmds.rs @@ -74,7 +74,7 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result { return Ok(empty); } let layer = stamp_layer(doc, doc.next_layer_name("Layer"))?; - let id = doc.insert_above(*active, layer); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Above); *active = Some(id); Ok(id) })?; @@ -156,7 +156,7 @@ fn stamp_selected(s: &mut Session, sel: &[LayerId]) -> Result { } let name = format!("{} (merged)", doc.layer(top).map_or("Layer", |l| l.name.as_str())); let layer = stamp_layer(&solo, name)?; - let id = doc.insert_above(Some(top), layer); + let id = crate::layer_place::insert_new(doc, Some(top), layer, crate::layer_place::Place::Above); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index 67fc34be60..af90faf5fa 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -906,7 +906,7 @@ pub fn specs() -> Vec { let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| layer_name(&t.text)); let id = s.edit("New Type Layer", |doc, active| { refresh(doc, &mut t); - let id = doc.insert_above(*active, Layer::new(name, LayerContent::Text(t))); + let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/type_extra_cmds.rs b/crates/engine/src/cmd/type_extra_cmds.rs index 99538edb70..d8c11a52d6 100644 --- a/crates/engine/src/cmd/type_extra_cmds.rs +++ b/crates/engine/src/cmd/type_extra_cmds.rs @@ -415,6 +415,38 @@ fn attach_to_path(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "start": start, "flip": flip})) } +/// Type on a path's own path in document space (#9114): what the Direct Selection tool shows and +/// edits, as Photoshop's Type Path. `None` unless `t` is type on a path. +pub fn type_path(t: &TextLayer) -> Option { + let TextShape::Path { path, .. } = &t.shape else { return None }; + let map = |q: Point| t.transform.apply(q); + let knots = path.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect(); + Some(Path::new(vec![Subpath { closed: path.closed, knots, op: path.op }])) +} + +/// Puts an edited [`type_path`] back into `t` (its text space), keeping where the type starts and +/// which side it runs on. It must still be one subpath with two or more points. +pub(crate) fn set_type_path(t: &mut TextLayer, edited: &Path) -> Result<()> { + let TextShape::Path { start, flip, .. } = &t.shape else { return Err(EngineError::Other("the type layer is not on a path".into())) }; + let (start, flip) = (*start, *flip); + let [sub] = edited.subpaths.as_slice() else { return Err(EngineError::Other("type on a path follows one path".into())) }; + if sub.knots.len() < 2 { + return Err(EngineError::Other("type on a path needs a path of two or more points".into())); + } + if sub.knots.len() > MAX_TYPE_PATH_KNOTS { + return Err(EngineError::Other("the type path has too many anchor points".into())); + } + let inv = t.transform.inverse().ok_or_else(|| EngineError::Other("the type layer's transform cannot be inverted".into()))?; + let map = |q: Point| inv.apply(q); + let knots: Vec = + sub.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect(); + if !knots.iter().all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|q| q.x.is_finite() && q.y.is_finite())) { + return Err(EngineError::Other("the path cannot be mapped into the type layer".into())); + } + t.shape = TextShape::Path { path: Subpath { closed: sub.closed, knots, op: sub.op }, start, flip }; + Ok(()) +} + fn is_path_text(s: &Session) -> std::result::Result<(), String> { match active_text(s)?.shape { TextShape::Path { .. } | TextShape::Area { .. } => Ok(()), diff --git a/crates/engine/src/cmd/type_extra_cmds/tests.rs b/crates/engine/src/cmd/type_extra_cmds/tests.rs index d1bc3c39f1..8ae504cfa1 100644 --- a/crates/engine/src/cmd/type_extra_cmds/tests.rs +++ b/crates/engine/src/cmd/type_extra_cmds/tests.rs @@ -314,6 +314,80 @@ fn type_attaches_to_a_path_and_releases_it() { assert!(matches!(text(&s, id).shape, TextShape::Path { .. })); } +/// #9114: type on a path follows its own path when the path is edited (Direct Selection's +/// `path.*` commands with `"name": "layer"`), as Photoshop's Type Path does; the Paths list names +/// it, an edit is one undo step, and an edit that leaves no path is refused. +#[test] +fn type_follows_its_path_when_the_path_is_edited() { + let mut s = session(8); + let id = text_layer(&mut s, "Hello path"); + s.edit("path", |doc, _| { + doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); + Ok(()) + }) + .unwrap(); + s.execute("type.attachToPath", json!({"start": 4})).unwrap(); + // In document space, the type path is where the work path was. + let path = crate::type_extra_cmds::type_path(text(&s, id)).unwrap(); + let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect(); + assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}"); + let listed = s.execute("path.list", json!({})).unwrap(); + assert_eq!(listed["typePath"]["kind"], "typePath", "{listed}"); + // Swing the path's end to the right: the type now runs down and to the right. + let before = ink(&s, id); + let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap(); + assert_eq!(r["name"], "layer"); + let after = ink(&s, id); + assert!(after.width() > before.width() + 20, "{before:?} → {after:?}"); + assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0), "where the type starts is kept"); + // The work path it came from is untouched; Undo puts the type path back. + assert_eq!(s.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor.x, 150.0); + assert!(s.undo()); + assert_eq!(ink(&s, id), before); + // An edit that would leave fewer than two points is refused and changes nothing. + assert!(s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id.0, "subpath": 0, "knot": 0})).is_err()); + assert_eq!(ink(&s, id), before); +} + +/// #9114: a type-on-a-path layer's vector mask is still what `"name": "layer"` edits, as on main +/// and as `path.info` reads it; `"typePath": true` edits the Type Path; `path.list` reports both. +#[test] +fn a_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { + let mut s = session(8); + let id = text_layer(&mut s, "Hello path"); + s.edit("path", |doc, _| { + doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); + Ok(()) + }) + .unwrap(); + s.execute("type.attachToPath", json!({})).unwrap(); + let rect = json!({"subpaths": [{"closed": true, "knots": [[10, 10], [200, 10], [200, 100], [10, 100]]}]}); + s.execute("layer.vectorMask.add", json!({"layer": id.0, "path": rect})).unwrap(); + let listed = s.execute("path.list", json!({})).unwrap(); + assert_eq!((listed["layerPath"]["kind"].as_str(), listed["typePath"]["kind"].as_str()), (Some("vectorMask"), Some("typePath")), "{listed}"); + let type_path = |s: &Session| crate::type_extra_cmds::type_path(text(s, id)).unwrap(); + let before = type_path(&s); + let mask = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths[0].knots[0].anchor; + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 0]], "move": [10, 0]})).unwrap(); + assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask's corner moved"); + assert_eq!(type_path(&s), before, "the Type Path stays"); + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "typePath": true, "anchors": [[0, 1]], "move": [20, 0]})).unwrap(); + assert!((type_path(&s).subpaths[0].knots[1].anchor.x - before.subpaths[0].knots[1].anchor.x - 20.0).abs() < 1e-6, "the Type Path moved"); + assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask stays"); +} + +/// An edit can't grow the Type Path past the cap `type.attachToPath` keeps. +#[test] +fn an_edited_type_path_keeps_the_knot_cap() { + let mut s = session(8); + let id = text_layer(&mut s, "Hi"); + let knots: Vec<(f64, f64)> = (0..=MAX_TYPE_PATH_KNOTS).map(|i| (i as f64 * 0.001, 50.0)).collect(); + let mut t = text(&s, id).clone(); + t.shape = TextShape::Path { path: Subpath::polyline(&knots[..2]), start: 0.0, flip: false }; + assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots[..MAX_TYPE_PATH_KNOTS])])).is_ok()); + assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots)])).is_err()); +} + /// The Type tool's click on a path: `"at"` starts the type where the path passes nearest the /// click, and the paragraph alignment is kept about that point, as in Photoshop. #[test] diff --git a/crates/engine/src/cmd/type_styles_cmds/tests.rs b/crates/engine/src/cmd/type_styles_cmds/tests.rs index 0a5761d58b..6f6f735ff0 100644 --- a/crates/engine/src/cmd/type_styles_cmds/tests.rs +++ b/crates/engine/src/cmd/type_styles_cmds/tests.rs @@ -243,3 +243,14 @@ fn preview_options_validates_without_mutating_source() { assert_ne!(shown.text_styles, before); assert_eq!(doc.text_styles, before); } + +#[test] +fn style_options_take_a_family_with_the_style_picked_under_it() { + // The font menu's ">" picks a family in one of its styles: Style Options sends both. + let (mut s, _) = session("Hello"); + let cs = s.execute("type.characterStyle.new", json!({"attrs": {"size": 20}, "fromSelection": false})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.characterStyle.set", json!({"id": cs, "attrs": {"font": "Arial", "fontStyle": "Bold Italic"}})).unwrap(); + let attrs = s.execute("type.characterStyle.list", json!({})).unwrap()["styles"][1]["attrs"].clone(); + assert_eq!(attrs["font_family"], "Arial", "{attrs}"); + assert_eq!(attrs["font_style"], "Bold Italic", "{attrs}"); +} diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 7f3753e24e..5a53d5ae07 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec { label: "List Paths", menu: &[], shortcut: None, - params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##, + params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask),typePath (active type layer's Type Path, if it is on a path)}"##, enabled: has_doc, run: |s, _| paths_list(s), journal: false, diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index c737ea8d69..868f2e8313 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -49,7 +49,8 @@ pub(super) fn paths_list(s: &Session) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let doc = &d.doc; let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::(); - let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content { + let active = d.active_layer.and_then(|id| doc.layer(id)); + let layer = active.and_then(|l| match &l.content { LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })), _ => { l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) })) @@ -60,6 +61,12 @@ pub(super) fn paths_list(s: &Session) -> Result { "workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })), "clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })), "layerPath": layer, + // Type on a path: Photoshop's Type Path, which Direct Selection edits (#9114). + "typePath": active.and_then(|l| match &l.content { + LayerContent::Text(t) => crate::type_extra_cmds::type_path(t) + .map(|p| json!({ "kind": "typePath", "layer": l.id.0, "name": format!("{} Type Path", l.name), "knots": knots(&p) })), + _ => None, + }), })) } diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 70af631e91..cdd4885ae0 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -338,7 +338,7 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { let id = s.edit("New Shape Layer", |doc, active| { refresh_shape(doc, &mut sh); let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind))); - let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh))); + let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Shape(sh)), crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 9917522d06..3aec55b837 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -127,7 +127,7 @@ fn new_blank(s: &mut Session, _p: &Value) -> Result { let name = doc.next_layer_name("Video Layer"); let mut l = Layer::raster(name, fmt); l.video = Some(VideoData::new(frames, fps)); - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); sync(doc); Ok(id) @@ -366,8 +366,13 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result { let mut v = VideoData::new(frames, fps); v.original_frames = Some(v.frames.clone()); v.source = photocraft_doc::VideoSource::File { path: path.clone() }; + // The first frame is the layer's content before it is placed: an active artboard takes + // the layer only when its content is on the board, as `frames_to_layers` does. + if let (Some(first), LayerContent::Raster(surf)) = (v.frames.first(), &mut l.content) { + *surf = first.clone(); + } l.video = Some(v); - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); sync(doc); Ok(id) @@ -438,12 +443,14 @@ fn frames_to_layers(s: &mut Session, p: &Value) -> Result { let n = frames.len(); s.edit("Video Frames to Layers", |doc, active| { let mut above = *active; + let mut place = crate::layer_place::Place::AutoEditable; for (i, f) in frames.into_iter().enumerate() { let mut l = Layer::raster(format!("Frame {}", i + 1), fmt); if let LayerContent::Raster(surf) = &mut l.content { *surf = f; } - above = Some(doc.insert_above(above, l)); + above = Some(crate::layer_place::insert_new(doc, above, l, place)); + place = crate::layer_place::Place::Above; } *active = above; Ok(()) diff --git a/crates/engine/src/cmd/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs index 3560c5f2c3..7e8c05a9b4 100644 --- a/crates/engine/src/cmd/video_cmds/tests.rs +++ b/crates/engine/src/cmd/video_cmds/tests.rs @@ -83,6 +83,21 @@ fn new_video_layer_from_image_sequence() { assert!(s.active().unwrap().doc.timeline.as_ref().unwrap().duration >= 3); } +/// CodeRabbit on #9775: footage that isn't on the active artboard stays out of it, as a placed +/// image does; the board would clip it. Before, the layer was placed while still empty. +#[test] +fn footage_off_the_active_artboard_stays_out_of_it() { + let dir = tmpdir("board"); + write_png(&format!("{dir}/f01.png"), 16, 12, "#ff0000"); + write_png(&format!("{dir}/f02.png"), 16, 12, "#00ff00"); + let mut s = session(); + let board = s.execute("layer.new.artboard", json!({"rect": [0, 0, 4, 4]})).unwrap(); + assert!(board["layer"].as_u64().is_some(), "{board}"); + let r = s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": dir})).unwrap(); + let id = LayerId(r["layer"].as_u64().unwrap()); + assert_eq!(s.active().unwrap().doc.artboard_of(id), None, "the footage is centred off the board"); +} + #[test] fn frames_to_layers_and_render_video() { let dir = tmpdir("ftl"); diff --git a/crates/engine/src/cmd/vp_cmds.rs b/crates/engine/src/cmd/vp_cmds.rs index eb713d9141..1a3ac8e0ca 100644 --- a/crates/engine/src/cmd/vp_cmds.rs +++ b/crates/engine/src/cmd/vp_cmds.rs @@ -252,7 +252,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { let on = layer.or(*active); let id = if new_layer { let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format()); - let nid = doc.insert_above(on, l); + let nid = crate::layer_place::insert_new(doc, on, l, crate::layer_place::Place::AutoEditable); *active = Some(nid); nid } else { diff --git a/crates/engine/src/group_options.rs b/crates/engine/src/group_options.rs new file mode 100644 index 0000000000..dd2ddee02f --- /dev/null +++ b/crates/engine/src/group_options.rs @@ -0,0 +1,264 @@ +//! The options of Photoshop's New Group dialog (Name, Color, Mode, Opacity), shared by +//! Layer › New › Group… (`layer.new.group`) and Group from Layers (`layer.new.groupFromLayers`, +//! `layer.groupLayers`), so the dialog's OK is a single history step. + +use photocraft_color::BlendMode; +use photocraft_doc::{LabelColor, Layer}; +use serde_json::Value; + +use crate::{EngineError, Result}; + +/// New Group options parsed from command params; an absent (or `null`) key keeps the default. +#[derive(Debug, Default)] +pub(crate) struct GroupOptions { + /// `None` (or an empty name) takes the next "Group N". + pub name: Option, + color: Option, + blend: Option, + opacity: Option, +} + +impl GroupOptions { + /// Parses `name`, `color` (a layer colour id), `mode` (a blend mode, Pass Through included) + /// and `opacity` (percent, clamped to 0..100). Validates everything before any edit runs. + pub(crate) fn parse(cmd: &str, p: &Value) -> Result { + let bad = |msg: &str| EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }; + let get = |key: &str| p.get(key).filter(|v| !v.is_null()); + let name = match get("name") { + None => None, + Some(v) => Some(v.as_str().ok_or_else(|| bad("`name` must be a string"))?.to_string()).filter(|n| !n.trim().is_empty()), + }; + let color = match get("color") { + None => None, + Some(v) => Some(v.as_str().and_then(LabelColor::from_id).ok_or_else(|| { + bad("`color` must be a layer colour id (none, red, orange, yellow, green, seafoam, blue, indigo, magenta, fuchsia, violet, gray)") + })?), + }; + let blend = match get("mode") { + None => None, + Some(v) => Some( + v.as_str() + .and_then(crate::commands::blend_from_str) + .ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?, + ), + }; + let opacity = match get("opacity") { + None => None, + Some(v) => { + let o = v.as_f64().filter(|o| o.is_finite()).ok_or_else(|| bad("`opacity` must be a number (percent, 0..100)"))?; + Some((o.clamp(0.0, 100.0) / 100.0) as f32) + } + }; + Ok(Self { name, color, blend, opacity }) + } + + /// Sets the mode, opacity and colour of a new `group`. A colour also reaches every layer inside + /// it, as Layer › Layer Color does on a group; "No Color" leaves the layers' own colours alone. + pub(crate) fn apply(&self, group: &mut Layer) { + if let Some(blend) = self.blend { + group.blend = blend; + } + if let Some(opacity) = self.opacity { + group.opacity = opacity; + } + match self.color { + Some(LabelColor::None) | None => {} + Some(color) => { + // Explicit stack: documents can nest groups deeply. + let mut stack = vec![group]; + while let Some(l) = stack.pop() { + l.label = color; + if let Some(children) = l.children_mut() { + stack.extend(children.iter_mut()); + } + } + } + } + } +} + +/// `layer.new.group`'s `position`: `below` (the Layers panel's ⌘/Ctrl-click) or `above` (the default). +pub(crate) fn below(cmd: &str, p: &Value) -> Result { + match p.get("position").filter(|v| !v.is_null()) { + None => Ok(false), + Some(v) => match v.as_str() { + Some("above") => Ok(false), + Some("below") => Ok(true), + _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "`position` must be above or below".into() }), + }, + } +} + +#[cfg(test)] +mod tests { + use photocraft_color::BlendMode; + use photocraft_doc::{Document, LabelColor, Layer, LayerContent, LayerId}; + use serde_json::{Value, json}; + + use crate::Session; + + /// Background, then `A` and `B` (`B` active). + fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let a = id(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()); + let b = id(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()); + (s, a, b) + } + + fn id(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) + } + + fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc + } + + fn layer(s: &Session, id: LayerId) -> &Layer { + doc(s).layer(id).unwrap() + } + + fn expanded(s: &Session, id: LayerId) -> bool { + matches!(&layer(s, id).content, LayerContent::Group(g) if g.expanded) + } + + fn steps(s: &Session) -> usize { + s.active().unwrap().history.entries().len() + } + + fn top(s: &Session) -> Vec { + doc(s).layers.iter().map(|l| l.id).collect() + } + + #[test] + fn new_group_defaults_and_dialog_options() { + let (mut s, _, _) = session(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Group 1", BlendMode::PassThrough, 1.0, LabelColor::None)); + assert!(expanded(&s, g), "an empty new group stays open"); + let before = steps(&s); + let g = id(s.execute("layer.new.group", json!({"name": "Sky", "color": "red", "mode": "multiply", "opacity": 40})).unwrap()); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.label), ("Sky", BlendMode::Multiply, LabelColor::Red)); + assert!((l.opacity - 0.4).abs() < 1e-6); + assert_eq!(steps(&s), before + 1, "the dialog's OK is one history step"); + // Labels as shown in the dialog work too; opacity is clamped to 0..100 %, a blank name is "Group N". + let g = id(s.execute("layer.new.group", json!({"name": " ", "mode": "Linear Dodge (Add)", "opacity": 250})).unwrap()); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.opacity), ("Group 2", BlendMode::LinearDodge, 1.0)); + let g = id(s.execute("layer.new.group", json!({"opacity": -5, "name": null, "color": null, "mode": null, "position": null})).unwrap()); + assert_eq!(layer(&s, g).opacity, 0.0); + } + + #[test] + fn group_from_layers_is_collapsed_and_takes_the_dialog_options() { + let (mut s, a, b) = session(); + s.execute("layer.setLabelColor", json!({"layer": a.0, "color": "red"})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let before = steps(&s); + let g = id(s.execute("layer.new.groupFromLayers", json!({"name": "Pair", "color": "none", "mode": "normal", "opacity": 50})).unwrap()); + assert_eq!(steps(&s), before + 1, "one history step"); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Pair", BlendMode::Normal, 0.5, LabelColor::None)); + assert!(!expanded(&s, g), "Photoshop shows a group made from layers closed"); + assert_eq!(layer(&s, a).label, LabelColor::Red, "No Color leaves the layers' own colours alone"); + let inspect = s.execute("document.inspect", json!({})).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == json!(g.0)).unwrap().clone(); + assert_eq!(row["expanded"], false, "document.inspect reports it"); + // Undo removes the group; redo brings it back closed. + s.undo(); + assert!(doc(&s).layer(g).is_none()); + s.redo(); + assert!(!expanded(&s, g)); + // ⌘G with a colour labels the group and every layer in it, like Layer › Layer Color. + s.undo(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let g = id(s.execute("layer.groupLayers", json!({"color": "green"})).unwrap()); + assert!(!expanded(&s, g)); + for l in [g, a, b] { + assert_eq!(layer(&s, l).label, LabelColor::Green); + } + } + + #[test] + fn below_puts_the_new_group_under_the_active_layer() { + let (mut s, a, b) = session(); + let bg = top(&s)[0]; + let g = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap()); + assert_eq!(top(&s), vec![bg, a, g, b]); + // Inside a group it stays inside, under the active layer. + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let outer = id(s.execute("layer.groupLayers", json!({})).unwrap()); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let inner = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap()); + let children: Vec = layer(&s, outer).children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![inner, b]); + // Nothing goes under the Background: the group goes above it instead. + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + let g2 = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap()); + assert_eq!(top(&s)[..2], [bg, g2]); + // With no active layer it goes to the top, like a plain New Group. + s.execute("select.deselectLayers", json!({})).unwrap(); + let g3 = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap()); + assert_eq!(top(&s).last(), Some(&g3)); + } + + /// A group added inside a clipping mask (⌘-click under a clipped layer, or a plain New Group + /// on the base) joins the mask, as in Photoshop: the clipped layers keep their base and stay + /// visible, and nothing needs recompositing. + #[test] + fn a_group_added_inside_a_clipping_mask_joins_it() { + let (mut s, a, b) = session(); + s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap(); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let g = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap()); + assert_eq!(top(&s)[1..], [a, g, b]); + assert!(layer(&s, g).clipped, "under a clipped layer the group is clipped too"); + assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY), "B still clips to A"); + // On the base itself: the new group goes between A and its clipped layers. + s.undo(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + assert_eq!(top(&s)[1..], [a, g, b]); + assert!(layer(&s, g).clipped); + // Outside a clipping mask nothing changes. + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + assert!(!layer(&s, g).clipped); + } + + #[test] + fn bad_options_fail_without_touching_the_document() { + let (mut s, a, b) = session(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + for cmd in ["layer.new.group", "layer.new.groupFromLayers", "layer.groupLayers"] { + let mut bad = vec![ + json!({"name": 7}), + json!({"color": 5}), + json!({"color": "pink"}), + json!({"color": "Red"}), + json!({"mode": ""}), + json!({"mode": 3}), + json!({"mode": "sparkle"}), + json!({"opacity": "x"}), + json!({"opacity": [50]}), + ]; + if cmd == "layer.new.group" { + bad.push(json!({"position": "yes"})); + } + for p in bad { + let before = (doc(&s).clone(), s.active().unwrap().revision, steps(&s)); + assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p} must be refused"); + assert_eq!((doc(&s).clone(), s.active().unwrap().revision, steps(&s)), before, "{cmd} {p} changed nothing"); + } + // A huge but finite opacity clamps to 100 % instead of failing. + let g = id(s.execute(cmd, json!({"opacity": f64::MAX})).unwrap()); + assert_eq!(layer(&s, g).opacity, 1.0); + s.undo(); + } + } +} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 6799640bad..bf3560eb9f 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -331,14 +331,25 @@ fn independent_of_document(id: &str) -> bool { } #[cfg(not(target_arch = "wasm32"))] -fn read_path(path: &str) -> Result> { - // Bounded reads, and a clear error for a file larger than memory (#375). - photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +fn import_path( + name: &str, + path: &str, + opts: &photocraft_io::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> { + // Bounded reads, and a clear error for a file larger than memory (#375); a PSD/PSB is + // parsed from the open file instead of being read whole. + photocraft_io::import_file_for_open_with(name, std::path::Path::new(path), opts, ctl) } #[cfg(target_arch = "wasm32")] -fn read_path(path: &str) -> Result> { - Err(EngineError::Other(format!("cannot open paths on the web: {path}"))) +fn import_path( + _: &str, + path: &str, + _: &photocraft_io::ImportOptions, + _: &photocraft_raster::Interrupt, +) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> { + Err(photocraft_io::IoError::Read(format!("cannot open paths on the web: {path}"))) } /// Run a job-capable command's heavy part. `work` runs on a worker thread when the command was @@ -555,17 +566,19 @@ impl Session { false, move |ctx| { ctx.progress(0.0, "Reading"); - let bytes = match source { - OpenSource::Bytes(b) => b, - OpenSource::Path(p) => Arc::new(read_path(&p)?), - }; - ctx.check()?; - ctx.progress(0.02, "Decoding"); - let imported = - ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)).map_err(|e| match e { - photocraft_io::IoError::Cancelled => EngineError::Cancelled, - e => EngineError::Other(e.to_string()), - })?; + let imported = match source { + OpenSource::Bytes(bytes) => { + ctx.check()?; + ctx.progress(0.02, "Decoding"); + ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)) + } + // A PSD/PSB is decoded straight from the file, which is never read whole. + OpenSource::Path(p) => ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, ctl)), + } + .map_err(|e| match e { + photocraft_io::IoError::Cancelled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + })?; ctx.progress(0.95, "Preparing layers"); warm_layer_bounds(&imported.0.document, || ctx.check())?; // Type layers need the shared text engine, whose first use waits for the diff --git a/crates/engine/src/layer_place.rs b/crates/engine/src/layer_place.rs new file mode 100644 index 0000000000..3cb9c1e854 --- /dev/null +++ b/crates/engine/src/layer_place.rs @@ -0,0 +1,113 @@ +//! Where a new layer goes, as in Photoshop. Above the active layer, or as the top layer inside the +//! active group when that group is open (an artboard, open or closed, when the layer's content is +//! on the board); with nothing active, at the top of the stack. A layer that lands inside a clipping mask joins it: it is clipped when the layer +//! just above its slot is clipped, the rule Photoshop follows on every insert (#2203), so a new +//! layer (or group) between a base and its clipped layers never becomes their (empty) base. +//! Artboards are never nested or clipped: a new one goes to the top level. + +use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerPath, MAX_GROUP_DEPTH}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Place { + /// New Layer, New Group, new adjustment and fill layers: inside the anchor when it is an open + /// group (or an artboard the content is on), else directly above it. A locked group takes the + /// layer too, as in Photoshop (checked with Lock All): the layer is locked through it. + Auto, + /// [`Place::Auto`] for a layer that is edited right after it is made (Type, Shape, Place's + /// transform box, Paste, the Gradient tool's live gradient, video layers, Render and Vanishing + /// Point drawing, a new frame): never inside a group with a lock of its own (all, pixels, + /// transparency or position) that would refuse that edit; the layer goes above the group. + AutoEditable, + /// Directly above the anchor, never inside it: a layer made from another layer, or the second + /// and later of several new layers. + Above, + /// Directly below the anchor (⌘-click on the Layers panel's New Layer or New Group button). Never + /// under the Background, where it goes above instead. + Below, +} + +/// The slot `layer` would take: its parent's path (empty for the root) and its index among the +/// parent's children (bottom to top). A missing or stale `anchor` means the top of the stack. +pub fn insertion_point(doc: &Document, anchor: Option, layer: &Layer, place: Place) -> (LayerPath, usize) { + let root_top = (Vec::new(), doc.layers.len()); + let Some(path) = anchor.and_then(|a| doc.path_of(a)) else { return root_top }; + // An artboard stays at the top level: beside the anchor's top-level layer. + let path = if layer.artboard().is_some() { path.get(..1).map(<[usize]>::to_vec).unwrap_or_default() } else { path }; + let (Some((&k, parent)), Some(target)) = (path.split_last(), doc.layer_at(&path)) else { return root_top }; + let locks = &target.locks; + let editable = !(locks.all || locks.pixels || locks.transparency || locks.position); + match place { + Place::Auto | Place::AutoEditable if takes_new_layers(target, path.len(), layer) && (place == Place::Auto || editable) => { + (path.clone(), target.children().map_or(0, <[Layer]>::len)) + } + Place::Below if crate::background_cmds::background_id(doc) != Some(target.id) => (parent.to_vec(), k), + _ => (parent.to_vec(), k + 1), + } +} + +/// Inserts `layer` at its [`insertion_point`], clipped when it lands inside a clipping mask (a +/// flag it already has is kept unless nothing is below it to clip to; an artboard is never +/// clipped); returns its id. Never fails: a slot that can't be reached puts +/// the layer on top of the stack. +pub fn insert_new(doc: &mut Document, anchor: Option, mut layer: Layer, place: Place) -> LayerId { + let id = layer.id; + let (parent, index) = insertion_point(doc, anchor, &layer, place); + let sib = if parent.is_empty() { Some(&mut doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) }; + if let Some(sib) = sib { + let mut index = index.min(sib.len()); + if layer.artboard().is_some() { + // Past the clipped layers above the slot, so their clipping mask stays whole. + while sib.get(index).is_some_and(|above| above.clipped) { + index += 1; + } + layer.clipped = false; + } else if sib.get(index).is_some_and(|above| above.clipped) { + layer.clipped = true; + } else if index == 0 { + // Nothing below to clip to (a copied clipped layer pasted into an empty group). + layer.clipped = false; + } + sib.insert(index, layer); + } else { + doc.layers.push(layer); + } + id +} + +/// Does the group `target` at depth `depth` (its path length) take a new `layer` as its top +/// child? An open group or an artboard does, locked or not (Photoshop puts a new layer inside a +/// group locked with Lock All), unless nesting would pass [`MAX_GROUP_DEPTH`]. An artboard +/// takes a layer with content only when that content is centred on the board, as callers place +/// it for the canvas (Place, Paste, a Type or Shape click): elsewhere the board would clip it. +fn takes_new_layers(target: &Layer, depth: usize, layer: &Layer) -> bool { + let LayerContent::Group(g) = &target.content else { return false }; + let on_board = |rect: photocraft_geom::Rect| { + crate::layer_multi_cmds::layer_bounds(layer).is_none_or(|b| { + let (cx, cy) = (b.x0 / 2 + b.x1 / 2, b.y0 / 2 + b.y1 / 2); + rect.contains(cx, cy) + }) + }; + let open = match &g.artboard { + Some(board) => on_board(board.rect), + None => g.expanded, + }; + open && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH +} + +/// Group nesting inside `layer` itself: 0 for a layer or an empty group, as +/// [`Document::max_group_depth`] counts it. Explicit stack: pasted groups can be deep. +fn subtree_depth(layer: &Layer) -> usize { + let mut max = 0; + let mut stack: Vec<(&Layer, usize)> = vec![(layer, 0)]; + while let Some((l, depth)) = stack.pop() { + if let Some(children) = l.children().filter(|c| !c.is_empty()) { + max = max.max(depth + 1); + stack.extend(children.iter().map(|c| (c, depth + 1))); + } + } + max +} + +#[cfg(test)] +#[path = "layer_place_tests.rs"] +mod tests; diff --git a/crates/engine/src/layer_place_tests.rs b/crates/engine/src/layer_place_tests.rs new file mode 100644 index 0000000000..5a84035426 --- /dev/null +++ b/crates/engine/src/layer_place_tests.rs @@ -0,0 +1,357 @@ +use photocraft_doc::{Document, Layer, LayerContent, LayerId, MAX_GROUP_DEPTH}; +use serde_json::{Value, json}; + +use super::*; +use crate::Session; + +/// Background, then `A` and `B` (`B` active). +fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let a = id(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()); + let b = id(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()); + (s, a, b) +} + +fn id(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn top(s: &Session) -> Vec { + doc(s).layers.iter().map(|l| l.id).collect() +} + +fn children(s: &Session, group: LayerId) -> Vec { + doc(s).layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect() +} + +fn set_expanded(s: &mut Session, group: LayerId, expanded: bool) { + s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": expanded})).unwrap(); +} + +fn select(s: &mut Session, layer: LayerId) { + s.execute("layer.select", json!({"layer": layer.0})).unwrap(); +} + +#[test] +fn a_new_layer_goes_inside_an_open_active_group_and_above_a_closed_one() { + let (mut s, a, b) = session(); + select(&mut s, a); + let g = id(s.execute("layer.groupLayers", json!({})).unwrap()); + // A group made from layers starts closed: the new layer goes above it. + let above = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(top(&s)[1..], [g, above, b]); + assert_eq!(children(&s, g), vec![a]); + // Opened, it takes the new layer as its top layer. + select(&mut s, g); + set_expanded(&mut s, g, true); + let inside = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![a, inside]); + // A new empty group is open, so the next new layer goes into it (New Group, then New Layer). + s.execute("select.deselectLayers", json!({})).unwrap(); + let empty = id(s.execute("layer.new.group", json!({})).unwrap()); + let first = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, empty), vec![first]); + // The same goes for the other new layers: adjustment, fill, type and shape layers. + select(&mut s, empty); + for (cmd, p) in [ + ("layer.newAdjustmentLayer.invert", json!({})), + ("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})), + ("type.create", json!({"x": 2, "y": 10, "text": "Hi"})), + ("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5]})), + ] { + select(&mut s, empty); + let l = id(s.execute(cmd, p).unwrap()); + assert_eq!(children(&s, empty).last(), Some(&l), "{cmd} goes inside the open group"); + } +} + +#[test] +fn artboards_and_locked_groups_take_new_layers() { + let (mut s, _, b) = session(); + let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 16, 16]})).unwrap()); + set_expanded(&mut s, board, false); + select(&mut s, board); + let l = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(doc(&s).artboard_of(l), Some(board), "an artboard takes the layer even when closed"); + // Photoshop puts a new layer inside an open group locked with Lock All too; the layer is + // locked through the group. + select(&mut s, b); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + s.execute("layer.setProps", json!({"layer": g.0, "locks": {"all": true}})).unwrap(); + select(&mut s, g); + let inside = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![inside]); + assert!(doc(&s).effective_locks(inside).all); +} + +#[test] +fn below_puts_the_new_layer_under_the_active_layer() { + let (mut s, a, b) = session(); + let bg = top(&s)[0]; + let l = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap()); + assert_eq!(top(&s), vec![bg, a, l, b]); + // Never under the Background, and never inside an open group. + select(&mut s, bg); + let l2 = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap()); + assert_eq!(top(&s)[..2], [bg, l2]); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + let l3 = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap()); + assert!(children(&s, g).is_empty()); + let root = top(&s); + assert_eq!(root.iter().position(|x| *x == l3).unwrap() + 1, root.iter().position(|x| *x == g).unwrap()); + assert!(s.execute("layer.new.layer", json!({"position": "yes"})).is_err()); +} + +/// The clipping rule Photoshop follows on every insert (#2203): a new layer is clipped exactly +/// when the layer just above its slot is clipped. +#[test] +fn a_new_layer_joins_the_clipping_mask_it_lands_in() { + let (mut s, base, c1) = session(); + let c2 = id(s.execute("layer.new.layer", json!({"name": "C2"})).unwrap()); + for c in [c1, c2] { + s.execute("layer.setProps", json!({"layer": c.0, "clipped": true})).unwrap(); + } + let clipped = |s: &Session, l: LayerId| doc(s).layer(l).unwrap().clipped; + // On the base: between the base and its clipped layers. + select(&mut s, base); + let on_base = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(clipped(&s, on_base)); + // In the middle of the chain. + select(&mut s, c1); + let mid = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(clipped(&s, mid)); + // Above the top clipped layer it is outside the mask. + select(&mut s, c2); + let above = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(!clipped(&s, above)); + // ⌘-click New Layer under a clipped layer joins it too; under the base it does not. + select(&mut s, c2); + let l = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap()); + assert!(clipped(&s, l)); + select(&mut s, base); + let l = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap()); + assert!(!clipped(&s, l)); + // A group joins as well (Photoshop clips groups too), and so do the other new layers. + select(&mut s, base); + let l = id(s.execute("layer.new.group", json!({})).unwrap()); + assert!(clipped(&s, l)); + select(&mut s, base); + let l = id(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()); + assert!(clipped(&s, l)); + // A layer made from a clipped layer (Layer via Copy) stays in its mask. + select(&mut s, c1); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + let l = id(s.execute("layer.new.layerViaCopy", json!({})).unwrap()); + assert!(clipped(&s, l)); +} + +#[test] +fn a_pasted_layer_goes_into_an_open_group() { + let (mut s, a, _) = session(); + // A whole pixel layer on the clipboard (no selection). + select(&mut s, a); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let into = id(s.execute("layer.new.group", json!({"name": "Into"})).unwrap()); + let pasted = id(s.execute("edit.paste", json!({})).unwrap()); + assert_eq!(children(&s, into), vec![pasted]); +} + +/// The second and later of several new layers stack above the first, even when the first is an +/// open group: it must not swallow them. +#[test] +fn later_layers_of_a_batch_go_above_the_first() { + let (s, _, b) = session(); + let mut d = doc(&s).clone(); + let first = insert_new(&mut d, Some(b), Layer::group("open", vec![]), Place::Auto); + let next = Layer::raster("next", d.pixel_format()); + let second = insert_new(&mut d, Some(first), next, Place::Above); + let root: Vec = d.layers.iter().map(|l| l.id).collect(); + assert_eq!(root[root.len() - 2..], [first, second]); + assert!(d.layer(first).unwrap().children().unwrap().is_empty()); +} + +#[test] +fn nesting_stops_at_the_group_depth_limit() { + let mut doc = Document::new("deep", photocraft_doc::Size::new(8, 8), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + // A chain of open groups as deep as allowed, with a layer at the bottom. + let mut inner = Layer::raster("deep", doc.pixel_format()); + let deep_id = inner.id; + let mut ids = Vec::new(); + for i in 0..MAX_GROUP_DEPTH { + let g = Layer::group(format!("g{i}"), vec![inner]); + ids.push(g.id); + inner = g; + } + doc.layers.push(inner); + assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH); + let innermost = *ids.first().unwrap(); + // A plain layer fits beside `deep`, inside the innermost group (the depth stays the same)… + let layer = Layer::raster("fits", doc.pixel_format()); + let l = insert_new(&mut doc, Some(innermost), layer, Place::Auto); + assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH); + assert!(doc.layer(innermost).unwrap().children().unwrap().iter().any(|c| c.id == l)); + // …but a group with a layer in it would go one deeper: it goes beside the group instead. + let nested = Layer::group("nested", vec![Layer::raster("x", doc.pixel_format())]); + let n = insert_new(&mut doc, Some(innermost), nested, Place::Auto); + assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH); + assert!(!doc.layer(innermost).unwrap().children().unwrap().iter().any(|c| c.id == n)); + assert!(doc.layer(deep_id).is_some()); +} + +#[test] +fn a_missing_or_stale_anchor_means_the_top_of_the_stack() { + let (s, _, _) = session(); + let mut d = doc(&s).clone(); + for anchor in [None, Some(LayerId(u64::MAX))] { + for place in [Place::Auto, Place::Above, Place::Below] { + let layer = Layer::raster("x", d.pixel_format()); + let l = insert_new(&mut d, anchor, layer, place); + assert_eq!(d.layers.last().map(|x| x.id), Some(l), "{anchor:?} {place:?}"); + } + } + assert!(matches!(d.layers.last().unwrap().content, LayerContent::Raster(_))); +} + +/// Any lock on an open group still lets New Layer, New Group and new adjustment and fill layers in, +/// as in Photoshop (checked with Lock All). A layer that is edited right after it is made (Type, +/// Shape, Paste, Render…) goes above a group whose lock would refuse that edit, +/// so it never comes out locked. +#[test] +fn locked_groups_take_new_layers_but_not_the_ones_edited_at_once() { + for locks in [json!({"all": true}), json!({"pixels": true}), json!({"transparency": true}), json!({"position": true})] { + let (mut s, _, b) = session(); + select(&mut s, b); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + s.execute("layer.setProps", json!({"layer": g.0, "locks": locks})).unwrap(); + for (cmd, p) in [ + ("layer.new.layer", json!({})), + ("layer.new.group", json!({})), + ("layer.newAdjustmentLayer.invert", json!({})), + ("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})), + ] { + select(&mut s, g); + let l = id(s.execute(cmd, p).unwrap()); + assert_eq!(children(&s, g).last(), Some(&l), "{cmd} goes inside the group locked with {locks}"); + } + for (cmd, p) in [ + ("type.create", json!({"x": 2, "y": 10, "text": "Hi"})), + ("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5]})), + ("edit.paste", json!({})), + ("filter.render.tree", json!({})), + ("gradient.fill.create", json!({"from": [0, 0], "to": [16, 16]})), + ] { + select(&mut s, g); + let l = id(s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd} with {locks}: {e}"))); + assert!(!children(&s, g).contains(&l), "{cmd} stays out of the group locked with {locks}"); + assert_eq!(top(&s).iter().position(|x| *x == l), top(&s).iter().position(|x| *x == g).map(|i| i + 1), "{cmd} directly above the group"); + assert!(!doc(&s).effective_locks(l).any(), "{cmd}: the new layer is not locked"); + if cmd == "filter.render.tree" { + assert!(doc(&s).layer(l).unwrap().surface().unwrap().tile_count() > 0, "Render drew the tree with {locks}"); + } + } + } + // An open group inside a locked one still takes New Layer (the lock reaches it through the outer group). + let (mut s, _, b) = session(); + select(&mut s, b); + let outer = id(s.execute("layer.new.group", json!({})).unwrap()); + let inner = id(s.execute("layer.new.group", json!({})).unwrap()); + assert_eq!(children(&s, outer), vec![inner]); + s.execute("layer.setProps", json!({"layer": outer.0, "locks": {"pixels": true}})).unwrap(); + select(&mut s, inner); + let plain = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, inner), vec![plain]); +} + +/// Stamp Visible goes directly above an open active group, never inside it: the stamp is the +/// composite already, and inside it the group's opacity, mode or mask would apply to it again. +/// With a layer inside a group active, it still lands above that layer, inside the group. +#[test] +fn stamp_visible_goes_above_an_open_group() { + let (mut s, a, b) = session(); + select(&mut s, a); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let g = id(s.execute("layer.groupLayers", json!({})).unwrap()); + set_expanded(&mut s, g, true); + s.execute("layer.setProps", json!({"layer": g.0, "opacity": 0.5})).unwrap(); + select(&mut s, g); + let stamp = id(s.execute("layer.stampVisible", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![a], "the stamp stays out of the group"); + assert_eq!(top(&s)[1..], [g, stamp, b]); + // A layer inside the group active: the stamp goes above it, inside the group. + select(&mut s, a); + let inside = id(s.execute("layer.stampVisible", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![a, inside]); +} + +/// An artboard takes a new layer whose content is centred on it, and a new empty layer; content +/// placed elsewhere (Place and Paste centre on the canvas) stays at the top level instead of +/// being clipped away by the board. +#[test] +fn an_artboard_takes_only_content_that_is_on_it() { + let (mut s, _, _) = session(); + let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 8, 8]})).unwrap()); + let mut d = doc(&s).clone(); + let raster = |d: &Document, r: photocraft_geom::Rect| { + let mut l = Layer::raster("content", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + l + }; + let on = raster(&d, photocraft_geom::Rect::new(1, 1, 5, 5)); + let on = insert_new(&mut d, Some(board), on, Place::Auto); + assert_eq!(d.artboard_of(on), Some(board)); + let off = raster(&d, photocraft_geom::Rect::new(10, 10, 16, 16)); + let off = insert_new(&mut d, Some(board), off, Place::Auto); + assert_eq!(d.artboard_of(off), None); + let root: Vec = d.layers.iter().map(|l| l.id).collect(); + assert_eq!(root.iter().position(|x| *x == off), root.iter().position(|x| *x == board).map(|i| i + 1)); +} + +/// An artboard is never nested or clipped: a copied board goes beside the anchor's top-level +/// layer, even after a first copy went into a group, and never joins a clipping mask. +#[test] +fn artboards_stay_at_the_top_level_and_unclipped() { + let (mut s, a, b) = session(); + let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 8, 8]})).unwrap()); + s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap(); + let mut d = doc(&s).clone(); + let copy = d.layer(board).unwrap().duplicate(); + // On a clipping base: at the top level above its clipping mask (B keeps A as its base), not + // clipped. + let c = insert_new(&mut d, Some(a), copy.duplicate(), Place::Auto); + let root: Vec = d.layers.iter().map(|l| l.id).collect(); + let at = |id: LayerId| root.iter().position(|x| *x == id).unwrap(); + assert_eq!((at(b), at(c)), (at(a) + 1, at(a) + 2)); + assert!(!d.layer(c).unwrap().clipped); + // After a layer that went into an open group: beside the group, not inside it. + let g = insert_new(&mut d, Some(a), Layer::group("open", vec![]), Place::Above); + let first = Layer::raster("first", d.pixel_format()); + let first = insert_new(&mut d, Some(g), first, Place::Auto); + assert!(d.layer(g).unwrap().children().unwrap().iter().any(|l| l.id == first)); + let second = insert_new(&mut d, Some(first), copy, Place::Above); + assert!(d.layers.iter().any(|l| l.id == second), "the board is not nested in the group"); + assert_eq!(d.artboards().len(), 3); +} + +/// A copied clipped layer pasted into an empty group has nothing below it to clip to. +#[test] +fn a_clipped_layer_with_nothing_below_is_released() { + let (s, _, b) = session(); + let mut d = doc(&s).clone(); + let g = insert_new(&mut d, Some(b), Layer::group("empty", vec![]), Place::Auto); + let mut l = Layer::raster("was clipped", d.pixel_format()); + l.clipped = true; + let l = insert_new(&mut d, Some(g), l, Place::Auto); + assert!(d.layer(g).unwrap().children().unwrap().iter().any(|c| c.id == l)); + assert!(!d.layer(l).unwrap().clipped); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e94e5fcd90..c88ae3bfaf 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,12 +18,14 @@ pub mod display_color; pub mod doc_path; pub mod filters; pub mod filters_ext; +mod group_options; pub mod guide_layout; pub mod hidden_target; pub mod inspect; pub mod installed_profiles; pub mod jobs; pub mod kys; +pub mod layer_place; pub mod layer_style; pub mod link_watch; pub mod new_layer; @@ -88,6 +90,7 @@ pub use cmd::file_cmds; pub use cmd::fill_cmds; pub use cmd::fill_key_cmds; pub use cmd::float_cmds; +pub use cmd::font_library_cmds; use cmd::frame_cmds; pub use cmd::fx_view_cmds; pub use cmd::fx_visibility_cmds; diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rs index cb1b151aba..4cba7f0c52 100644 --- a/crates/engine/src/new_layer.rs +++ b/crates/engine/src/new_layer.rs @@ -35,10 +35,12 @@ pub(crate) struct NewLayer { name: Option, } -/// `layer.new.layer`: a pixel layer above the active one (below it with `position: below`, the -/// Layers panel's ⌘/Ctrl-click), joining the clip group it lands in. +/// `layer.new.layer`: a pixel layer where Photoshop puts a new one ([`crate::layer_place`]: above +/// the active layer, inside it when it is an open group, below it with `position: below`, the Layers +/// panel's ⌘/Ctrl-click), joining the clip group it lands in. pub fn run(s: &mut Session, p: &Value) -> Result { let NewLayer { clip, mode, opacity, label, neutral, below, name } = parse(p)?; + let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; let id = s.edit("New Layer", |doc, active| { let name = name.clone().unwrap_or_else(|| doc.next_layer_name("Layer")); let mut layer = Layer::raster(name, doc.pixel_format()); @@ -51,11 +53,7 @@ pub fn run(s: &mut Session, p: &Value) -> Result { let px = photocraft_raster::from_rgba(&surface.format(), [rgb[0], rgb[1], rgb[2], 1.0]); surface.fill_rect(bounds, &px); } - // Nothing may sit under the Background: below it the layer lands above it instead. - let id = match *active { - Some(a) if below && doc.layer(a).is_some() && !doc.is_background(a) => doc.insert_below(Some(a), layer), - _ => doc.insert_above(*active, layer), - }; + let id = crate::layer_place::insert_new(doc, *active, layer, place); crate::clip_group::settle(doc, &[id], &Default::default(), clip); *active = Some(id); Ok(id) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 22f82002b7..38401ff468 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -870,6 +870,9 @@ pub struct TypePrefs { pub font_preview: FontPreview, pub fill_new_type_layers_with_placeholder: bool, pub recent_fonts: u32, + /// Favourite font families, starred in the font menu (`type.font.favorite`), in the order + /// they were added. + pub favorite_fonts: Vec, } impl Default for TypePrefs { @@ -883,6 +886,7 @@ impl Default for TypePrefs { font_preview: FontPreview::Medium, fill_new_type_layers_with_placeholder: true, recent_fonts: 10, + favorite_fonts: Vec::new(), } } } @@ -1242,9 +1246,15 @@ impl Preferences { self.shortcuts.clear(); return Ok(()); } + // The favourite fonts are the user's library, not a Type setting: resetting the Type + // section keeps them (only `type.favoriteFonts` itself, or Reset All, clears them). + let favorites = (path == "type").then(|| self.type_.favorite_fonts.clone()); let mut root = self.to_json(); set_path(&mut root, path, def)?; *self = serde_json::from_value(root).map_err(|e| e.to_string())?; + if let Some(favorites) = favorites { + self.type_.favorite_fonts = favorites; + } Ok(()) } diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index a065e48e6d..92ad78e5dd 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -254,7 +254,8 @@ pub fn encode_tip(t: &GrayTile) -> Vec { out.push(if eight { 8 } else { 16 }); out.extend_from_slice(&t.width.to_le_bytes()); out.extend_from_slice(&t.height.to_le_bytes()); - let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::fast()); + // Level 3: zlib-rs level 1 writes static Huffman blocks only, 13-30% bigger than miniz's level 1. + let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3)); let mut buf = Vec::with_capacity(8192); let mut ok = true; for chunk in t.data.chunks(4096) { diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index 4105ceb1c0..20cb95d95b 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -641,7 +641,8 @@ fn apply(s: &mut Session, p: &Value) -> Result { let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); let id = s.edit("New Gradient Fill Layer", |doc, active| { let fill = Fill::gradient(stops, angle, scale, style, reverse).in_mode(doc.mode); - let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill))); + let layer = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 25f0b9f7f7..d0f7071fc9 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -69,6 +69,12 @@ impl Session { if id == "layer.new.layer" { crate::new_layer::parse(params)?; } + if id == "layer.new.group" { + crate::group_options::below(id, params)?; + } + if id == "layer.new.group" || id == "layer.new.groupFromLayers" { + crate::group_options::GroupOptions::parse(id, params)?; + } // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the // document doesn't have. if spec.params.contains("\"layer\":id") diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 954d0c4635..a55e696e17 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1160,7 +1160,8 @@ fn move_selected_layers_keeps_selected_group_children_and_supports_above_below() let b = s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap(); let c = s.execute("layer.new.layer", json!({"name": "C"})).unwrap()["layer"].as_u64().unwrap(); let group = s.execute("layer.new.group", json!({"name": "G"})).unwrap()["layer"].as_u64().unwrap(); - // Made before B moves into G: a new group goes above the active layer, which would then be inside G. + // Made from C, not from G: like Photoshop a new group goes inside an open active group. + s.execute("layer.select", json!({"layer": c})).unwrap(); let target = s.execute("layer.new.group", json!({"name": "Target"})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.moveTo", json!({"layer": b, "target": group, "position": "into"})).unwrap(); diff --git a/crates/engine/tests/it/layer_range_panel_order.rs b/crates/engine/tests/it/layer_range_panel_order.rs index d442d35198..86b4ad81c8 100644 --- a/crates/engine/tests/it/layer_range_panel_order.rs +++ b/crates/engine/tests/it/layer_range_panel_order.rs @@ -20,8 +20,10 @@ fn shift_range_follows_visible_rows_on_both_sides_of_an_expanded_group() { select(&mut s, b, "replace"); select(&mut s, c, "add"); let group = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap(); + // D goes above the closed group (an open one would take it inside, as in Photoshop). let d = s.execute("layer.new.layer", json!({"name": "D"})).unwrap()["layer"].as_u64().unwrap(); + // Group Layers makes a collapsed group, as in Photoshop; open it so B and C are visible rows. + s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap(); for (anchor, target, wanted) in [(d, group, vec![d, group]), (group, d, vec![d, group]), (group, b, vec![group, c, b]), (b, group, vec![group, c, b]), (c, b, vec![c, b])] diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index e9c1bf1022..97e285a573 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -952,13 +952,20 @@ impl PcraftWriter { let (p, mut fresh) = prepared?; let previews = previews?; let mut stats = p.stats; - let mut z = ZipWriter::new(); + let mut next = HashMap::with_capacity(p.objects.len()); + let mut cached_bytes = 0usize; + // The archive is sized for every entry up front (#7689): previews, then reused and fresh + // objects at their compressed sizes. + let entries = + std::iter::once((MANIFEST, p.manifest.len())).chain(previews.iter().map(|(name, data)| (*name, data.len()))).chain(p.objects.keys().map(|path| { + let size = self.compressed.get(path).or_else(|| fresh.get(path)).map_or(0, |data| data.len()); + (path.as_str(), size) + })); + let mut z = ZipWriter::with_entries(entries)?; z.add(MANIFEST, &p.manifest)?; for (name, data) in &previews { z.add(name, data)?; } - let mut next = HashMap::with_capacity(p.objects.len()); - let mut cached_bytes = 0usize; for (path, obj) in &p.objects { let (key, data) = match self.compressed.remove_entry(path) { Some((key, data)) => { diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs index 5057e52168..2452f87903 100644 --- a/crates/format/src/zip.rs +++ b/crates/format/src/zip.rs @@ -3,6 +3,7 @@ //! unzipped and re-zipped by another tool still loads). No ZIP64, no //! encryption, no multi-disk archives. +use std::borrow::Cow; use std::collections::HashMap; use std::io::Read; @@ -31,18 +32,41 @@ impl Default for ZipWriter { } impl ZipWriter { + /// Creates an empty archive of STORE entries. pub fn new() -> Self { ZipWriter { out: Vec::new(), central: Vec::new(), count: 0 } } + /// Reserves the complete archive from its entry names and payload sizes. + pub(crate) fn with_entries<'a>(entries: impl IntoIterator) -> Result { + let (size, directory) = entries.into_iter().try_fold((22usize, 0usize), |(size, directory), (name, bytes)| { + let directory = directory.checked_add(46 + name.len()); + let size = size.checked_add(76).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(bytes)); + size.zip(directory).ok_or_else(|| FormatError::Unsupported("zip size overflow".into())) + })?; + let mut writer = Self::new(); + writer.out.try_reserve_exact(size).map_err(|_| FormatError::LimitExceeded("not enough memory for zip".into()))?; + writer.central.try_reserve_exact(directory).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?; + Ok(writer) + } + + /// Adds a STORE entry, rejecting names or data that exceed ZIP field limits. + /// The entry path has a 16-bit byte length, independent of filesystem limits. pub fn add(&mut self, name: &str, data: &[u8]) -> Result<(), FormatError> { if self.count == u16::MAX { return Err(FormatError::Unsupported("more than 65535 zip entries (ZIP64 not supported)".into())); } let size = u32::try_from(data.len()).map_err(|_| FormatError::Unsupported("zip entry over 4 GiB".into()))?; let offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?; - let crc = crc32(data); let name_b = name.as_bytes(); + let name_len = u16::try_from(name_b.len()).map_err(|_| FormatError::Unsupported("zip entry path exceeds the 65535-byte format limit".into()))?; + let local_len = 30usize + .checked_add(name_b.len()) + .and_then(|n| n.checked_add(data.len())) + .ok_or_else(|| FormatError::Unsupported("zip entry size overflow".into()))?; + self.out.try_reserve(local_len).map_err(|_| FormatError::LimitExceeded("not enough memory for zip entry".into()))?; + self.central.try_reserve(46 + name_b.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?; + let crc = crc32(data); // Local file header. let o = &mut self.out; o.extend_from_slice(&LOCAL_SIG.to_le_bytes()); @@ -54,7 +78,7 @@ impl ZipWriter { o.extend_from_slice(&crc.to_le_bytes()); o.extend_from_slice(&size.to_le_bytes()); o.extend_from_slice(&size.to_le_bytes()); - o.extend_from_slice(&(name_b.len() as u16).to_le_bytes()); + o.extend_from_slice(&name_len.to_le_bytes()); o.extend_from_slice(&0u16.to_le_bytes()); o.extend_from_slice(name_b); o.extend_from_slice(data); @@ -70,7 +94,7 @@ impl ZipWriter { c.extend_from_slice(&crc.to_le_bytes()); c.extend_from_slice(&size.to_le_bytes()); c.extend_from_slice(&size.to_le_bytes()); - c.extend_from_slice(&(name_b.len() as u16).to_le_bytes()); + c.extend_from_slice(&name_len.to_le_bytes()); c.extend_from_slice(&[0; 8]); // extra len, comment len, disk, internal attrs c.extend_from_slice(&0u32.to_le_bytes()); // external attrs c.extend_from_slice(&offset.to_le_bytes()); @@ -79,9 +103,11 @@ impl ZipWriter { Ok(()) } + /// Appends the central directory and returns the complete archive. pub fn finish(mut self) -> Result, FormatError> { let cd_offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?; - let cd_size = self.central.len() as u32; + let cd_size = u32::try_from(self.central.len()).map_err(|_| FormatError::Unsupported("zip directory over 4 GiB".into()))?; + self.out.try_reserve(self.central.len().saturating_add(22)).map_err(|_| FormatError::LimitExceeded("not enough memory to finish zip".into()))?; self.out.extend_from_slice(&self.central); self.out.extend_from_slice(&EOCD_SIG.to_le_bytes()); self.out.extend_from_slice(&[0; 4]); // disk numbers @@ -112,7 +138,7 @@ pub struct ZipReader<'a> { pub entries: Vec, /// Name -> index of the first entry with that name, so `find` is O(1) /// instead of a scan per lookup (a bundle reads one entry per tile). - by_name: HashMap, + by_name: HashMap, usize>, } fn u16_at(b: &[u8], o: usize) -> Result { @@ -123,6 +149,7 @@ fn u32_at(b: &[u8], o: usize) -> Result { } impl<'a> ZipReader<'a> { + /// Checks ZIP record bounds and indexes the first entry for each name. pub fn new(bytes: &'a [u8]) -> Result { if bytes.len() < 22 { return Err(FormatError::corrupt("not a zip archive (too short)")); @@ -150,7 +177,8 @@ impl<'a> ZipReader<'a> { let cd_size = u32_at(bytes, eocd + 12)? as usize; let cd_off = u32_at(bytes, eocd + 16)? as usize; let cd_end = cd_off.checked_add(cd_size).filter(|end| *end <= eocd).ok_or_else(|| FormatError::corrupt("zip central directory out of range"))?; - let mut entries = Vec::with_capacity(count.min(bytes.len() / 46)); + let mut entries = Vec::with_capacity(count.min(cd_size / 46)); + let mut by_name = HashMap::with_capacity(entries.capacity()); let mut p = cd_off; for _ in 0..count { let header_end = p.checked_add(46).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("truncated zip central directory entry"))?; @@ -168,7 +196,7 @@ impl<'a> ZipReader<'a> { let local = u32_at(bytes, p + 42)? as usize; let name_end = header_end.checked_add(nlen).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("zip entry name out of range"))?; let name = bytes.get(header_end..name_end).ok_or_else(|| FormatError::corrupt("truncated zip name"))?; - let name = String::from_utf8_lossy(name).into_owned(); + let name = String::from_utf8_lossy(name); if flags & 1 != 0 { return Err(FormatError::Unsupported("encrypted zip entries".into())); } @@ -194,14 +222,11 @@ impl<'a> ZipReader<'a> { if data_offset.checked_add(compressed).is_none_or(|end| end > bytes.len()) { return Err(FormatError::corrupt(format!("zip entry `{name}` out of range"))); } - entries.push(Entry { name, method, crc, compressed, uncompressed, data_offset }); + // The index borrows valid UTF-8 names; duplicate names keep the first entry. + by_name.entry(name.clone()).or_insert(entries.len()); + entries.push(Entry { name: name.into_owned(), method, crc, compressed, uncompressed, data_offset }); p = entry_end; } - let mut by_name = HashMap::with_capacity(entries.len()); - for (i, e) in entries.iter().enumerate() { - // Duplicate names: the first entry wins, as with a front-to-back scan. - by_name.entry(e.name.clone()).or_insert(i); - } Ok(ZipReader { bytes, entries, by_name }) } @@ -227,8 +252,9 @@ impl<'a> ZipReader<'a> { // small forged archive must not reserve gigabytes up front, so the // preallocation is capped (DEFLATE expands at most ~1032x). let mut out = Vec::with_capacity(e.uncompressed.min(raw.len().saturating_mul(1032)).min(64 << 20)); - flate2::read::DeflateDecoder::new(raw) - .take((max as u64).saturating_add(1)) + // One surplus byte proves a false size without expanding to the caller's larger budget. + flate2::bufread::DeflateDecoder::new(raw) + .take((e.uncompressed as u64).saturating_add(1)) .read_to_end(&mut out) .map_err(|err| FormatError::corrupt(format!("zip entry `{}`: {err}", e.name)))?; out @@ -261,6 +287,20 @@ mod tests { assert_eq!(crc32(b"123456789"), 0xCBF4_3926); } + /// ZIP entry paths have a format limit even when each component is short. + #[test] + fn entry_path_length_is_checked_before_writing() { + let mut writer = ZipWriter::new(); + for name in ["dir/".repeat(16384), "é/".repeat(21846)] { + assert!(matches!(writer.add(&name, b"invalid"), Err(FormatError::Unsupported(_)))); + assert!(writer.out.is_empty() && writer.central.is_empty()); + } + let name = "dir/".repeat(16383) + "end"; + writer.add(&name, b"valid").unwrap(); + let bytes = writer.finish().unwrap(); + assert_eq!(ZipReader::new(&bytes).unwrap().read_by_name(&name, 5).unwrap(), b"valid"); + } + #[test] fn roundtrip() { let mut w = ZipWriter::new(); @@ -274,6 +314,7 @@ mod tests { assert_eq!(r.read_by_name("dir/b.bin", 100).unwrap(), [0, 1, 2, 3]); assert!(r.read_by_name("empty", 0).unwrap().is_empty()); assert!(matches!(r.read_by_name("a.txt", 3), Err(FormatError::LimitExceeded(_)))); + assert!(r.by_name.keys().all(|name| matches!(name, Cow::Borrowed(_)))); } fn archive_with_comment(comment: &[u8]) -> Vec { @@ -379,6 +420,46 @@ mod tests { assert_eq!(r.read_by_name("b", 100).unwrap(), b"other"); } + /// Reservation changes neither entry bytes nor final output, and avoids growth. + #[test] + fn whole_archive_reservation_preserves_output() { + let entries = [("层/é.png", &b"image"[..]), ("empty", &b""[..]), ("empty", &b"duplicate"[..])]; + for entries in [&entries[..0], &entries[..]] { + let mut previous = ZipWriter::new(); + let mut reserved = ZipWriter::with_entries(entries.iter().map(|(name, data)| (*name, data.len()))).unwrap(); + let (capacity, directory) = (reserved.out.capacity(), reserved.central.capacity()); + for (name, data) in entries { + previous.add(name, data).unwrap(); + reserved.add(name, data).unwrap(); + } + assert_eq!(reserved.central.capacity(), directory); + let bytes = reserved.finish().unwrap(); + assert_eq!(bytes.capacity(), capacity); + assert_eq!(bytes, previous.finish().unwrap()); + } + assert!(matches!(ZipWriter::with_entries([("x", usize::MAX)]), Err(FormatError::Unsupported(_)))); + assert!(matches!(ZipWriter::with_entries([("x", isize::MAX as usize)]), Err(FormatError::LimitExceeded(_)))); + } + + /// Invalid UTF-8 names retain their lossy spelling and first-entry lookup. + #[test] + fn name_index_borrows_unicode_and_owns_lossy_names() { + let mut writer = ZipWriter::new(); + for name in ["层/é.png", "a", "b"] { + writer.add(name, name.as_bytes()).unwrap(); + } + let mut bytes = writer.finish().unwrap(); + let mut p = u32_at(&bytes, bytes.len() - 6).unwrap() as usize; + p += 46 + "层/é.png".len(); + bytes[p + 46] = 0xff; + bytes[p + 47 + 46] = 0xfe; + let reader = ZipReader::new(&bytes).unwrap(); + assert_eq!(reader.read_by_name("层/é.png", 100).unwrap(), "层/é.png".as_bytes()); + assert!(matches!(reader.by_name.get_key_value("层/é.png").unwrap().0, Cow::Borrowed(_))); + assert!(matches!(reader.by_name.get_key_value("�").unwrap().0, Cow::Owned(_))); + assert_eq!(reader.read_by_name("�", 1).unwrap(), b"a"); + } + #[test] fn crc_mismatch_detected() { let mut w = ZipWriter::new(); @@ -390,9 +471,63 @@ mod tests { assert!(r.read_by_name("a", 100).is_err()); } - /// A valid DEFLATE-compressed bundle may be read with an effectively - /// unlimited caller budget (e.g. corruption/round-trip checks). On 64-bit - /// targets `usize::MAX as u64 + 1` overflows, so the decoder must saturate. + #[test] + fn slice_deflate_matches_buffered_reader_and_preserves_checks() { + use std::io::Write as _; + + let content = b"PhotoCraft ZIP payload".repeat(5000); + let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::none()); + encoder.write_all(&content).unwrap(); + let compressed = encoder.finish().unwrap(); + assert!(compressed.len() > 32 * 1024); + let mut previous = Vec::new(); + flate2::read::DeflateDecoder::new(compressed.as_slice()).read_to_end(&mut previous).unwrap(); + let mut writer = ZipWriter::new(); + writer.add("payload", &compressed).unwrap(); + let bytes = writer.finish().unwrap(); + let reader = ZipReader::new(&bytes).unwrap(); + let mut entry = reader.entries[0].clone(); + entry.method = 8; + entry.uncompressed = content.len(); + entry.crc = crc32(&content); + assert_eq!(reader.read(&entry, content.len()).unwrap(), previous); + assert!(matches!(reader.read(&entry, content.len() - 1), Err(FormatError::LimitExceeded(_)))); + entry.crc ^= 1; + assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_)))); + entry.crc ^= 1; + entry.compressed /= 2; + assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_)))); + } + + /// A false small size must stop expansion before decoding the rest of the stream. + #[test] + fn deflate_surplus_stops_before_a_corrupt_suffix() { + // Exceed miniz's internal 32 KiB output buffer before the corrupt block. + let raw = [&[0, 0xff, 0xff, 0, 0][..], &[b'x'; 65535], &[7]].concat(); + let reader = ZipReader { bytes: &raw, entries: Vec::new(), by_name: HashMap::new() }; + for declared in [0, 7] { + let entry = Entry { name: "surplus".into(), method: 8, crc: 0, compressed: raw.len(), uncompressed: declared, data_offset: 0 }; + let err = reader.read(&entry, usize::MAX).unwrap_err(); + assert!(err.to_string().contains("wrong size"), "{err}"); + } + } + + /// Correct output length and CRC do not replace the final DEFLATE block. + #[test] + fn deflate_requires_a_complete_stream_including_empty_entries() { + for (raw, content) in [(&[0, 1, 0, 0xfe, 0xff, b'x', 1, 0, 0, 0xff, 0xff][..], &b"x"[..]), (&[3, 0][..], &b""[..])] { + let reader = ZipReader { bytes: raw, entries: Vec::new(), by_name: HashMap::new() }; + let mut entry = + Entry { name: "complete".into(), method: 8, crc: crc32(content), compressed: raw.len(), uncompressed: content.len(), data_offset: 0 }; + assert_eq!(reader.read(&entry, content.len()).unwrap(), content); + for cut in 0..raw.len() { + entry.compressed = cut; + assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_))), "cut at {cut}"); + } + } + } + + /// An unlimited caller budget still checks a DEFLATE entry's declared size. #[test] fn deflated_entry_with_unbounded_limit_round_trips() { use std::io::Write as _; diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 31f2561619..32ef503139 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -280,10 +280,11 @@ fn text_run_baseline_roundtrips() { fn zip_incremental_only_new_tiles() { let mut doc = rich_doc(ColorMode::Rgb, SampleType::U16); let mut w = PcraftWriter::new(); - let (_, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); + let (first, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); assert!(s1.tiles_total > 5); assert_eq!(s1.tiles_written, s1.tiles_total); - let (_, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); + let (cached, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); + assert_eq!(first, cached); assert_eq!(s2.tiles_written, 0); assert_eq!(s2.tiles_reused, s2.tiles_total); assert_eq!(s2.blobs_written, 0); @@ -293,6 +294,7 @@ fn zip_incremental_only_new_tiles() { let (bytes, s3) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); assert_eq!(s3.tiles_written, 1); assert_eq!(load_from_bytes(&bytes).unwrap(), doc); + assert_eq!(bytes, PcraftWriter::new().save_zip(&doc, &SaveOptions::default()).unwrap().0); } #[test] diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 83ccd3b784..4eb91fb728 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -49,6 +49,7 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } [dev-dependencies] +miniz_oxide = "0.9" crc32fast = "1.5" photocraft-affinity = { workspace = true, features = ["synth"] } flate2 = { workspace = true } diff --git a/crates/io/examples/psd_open_mem.rs b/crates/io/examples/psd_open_mem.rs new file mode 100644 index 0000000000..903eb35af9 --- /dev/null +++ b/crates/io/examples/psd_open_mem.rs @@ -0,0 +1,56 @@ +//! Opens a file the way the app's background open does and reports the time. Run it under +//! `/usr/bin/time -l` for the peak memory. `--read` reads the whole file first and imports the +//! bytes, as opens did before `import_file` (to compare). +//! +//! `cargo run --release -p photocraft-io --example psd_open_mem -- [--read]` + +fn main() { + let Some(path) = std::env::args().nth(1).filter(|a| a != "--read") else { + eprintln!("usage: psd_open_mem "); + std::process::exit(2); + }; + if std::env::args().any(|a| a == "--read") { + read_then_import(&path); + return; + } + let t = std::time::Instant::now(); + let res = + match photocraft_io::import_file(&path, std::path::Path::new(&path), &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE) { + Ok(r) => r, + Err(e) => { + eprintln!("{path}: open failed: {e}"); + std::process::exit(1); + } + }; + report(&path, &format!("open {:.2}s", t.elapsed().as_secs_f64()), &res); +} + +fn read_then_import(path: &str) { + let t = std::time::Instant::now(); + let bytes = match photocraft_format::read_file(std::path::Path::new(path)) { + Ok(b) => b, + Err(e) => { + eprintln!("{path}: read failed: {e}"); + std::process::exit(1); + } + }; + let read_s = t.elapsed().as_secs_f64(); + let t = std::time::Instant::now(); + let res = match photocraft_io::import_with(path, &bytes, &photocraft_raster::Interrupt::NONE) { + Ok(r) => r, + Err(e) => { + eprintln!("{path}: open failed: {e}"); + std::process::exit(1); + } + }; + drop(bytes); + report(path, &format!("read {read_s:.2}s, import {:.2}s", t.elapsed().as_secs_f64()), &res); +} + +fn report(path: &str, times: &str, res: &photocraft_io::ImportResult) { + let doc = &res.document; + println!("{path}: {times}, {} layers ({} top level)", doc.walk().len(), doc.layers.len()); + for w in &res.warnings { + println!(" warning: {w}"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 76b39e9270..612cd6dd3b 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -126,6 +126,9 @@ pub enum IoError { /// An SVG that does not parse (or is too large to rasterise). #[error("SVG: {0}")] Svg(String), + /// The file could not be read. + #[error("{0}")] + Read(String), /// A background import or save was cancelled ([`import_with`], [`export_with`]). #[error("cancelled")] Cancelled, @@ -374,26 +377,82 @@ pub fn import_for_open_with(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: Ok((result, damaged)) } -fn import_psd(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, damaged: &mut bool) -> Result { +/// The PSD/PSB part of an import, from a parse that takes [`PsdFile::from_bytes_and_merged_recovering`]'s +/// `want` and `recover`: of the file's bytes, or of the file itself ([`import_file_for_open_with`]). +fn import_psd( + name: &str, + ctl: &photocraft_raster::Interrupt, + damaged: &mut bool, + parse: impl FnOnce(&dyn Fn(&PsdFile) -> bool, &dyn Fn(&PsdFile) -> bool) -> photocraft_psd::Result<(PsdFile, Option>>)>, +) -> Result { // A merged image the import reads is decoded with the parse: a ZIP one is inflated once. - let (file, merged) = PsdFile::from_bytes_and_merged_recovering( - bytes, - |f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f), - psd_import::can_recover_layers, - )?; + // A failed read of the file (one parsed from its source) is a read error, as reading the + // whole file first would report it. + let (file, merged) = + parse(&|f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f), &psd_import::can_recover_layers).map_err(|e| match e { + photocraft_psd::PsdError::Read(msg) => IoError::Read(msg), + e => e.into(), + })?; // Nesting past the document model's cap could never be saved; reject the file with the // actionable limit. psd_import::check_group_depth(&file)?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(0.05); - let (mut document, warnings, psd_damaged) = psd_import::psd_to_document_decoded_integrity(&file, ctl, merged).ok_or(IoError::Cancelled)?; + // Read before the conversion, which moves the global blocks into the document. + let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); + let (mut document, warnings, psd_damaged, read_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?; + // The file became unreadable while its layers were read from it (`import_file_for_open_with`): + // the open fails, rather than opening with those layers empty. + if let Some(e) = read_error { + return Err(IoError::Read(e)); + } *damaged = psd_damaged; document.name = name.to_string(); - let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); text_import::prepare(&mut document, txt2.as_ref()); Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false }) } +/// [`import_for_open_with`] for the file at `path`. A PSD/PSB is parsed from the open file +/// ([`PsdFile::from_source`]) rather than read whole: its channel data is read layer by layer as +/// it is decoded, so opening it needs memory for the document, not for the document plus the +/// file. A read that fails meanwhile (the file is truncated or rewritten, its drive goes away) +/// fails the open. Other formats are read whole. +#[cfg(any(unix, windows))] +pub fn import_file_for_open_with( + name: &str, + path: &std::path::Path, + opts: &ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result<(ImportResult, bool), IoError> { + let read_failed = |e: std::io::Error| IoError::Read(format!("{}: {e}", path.display())); + ctl.check().map_err(|_| IoError::Cancelled)?; + let source = photocraft_psd::FileSource::open(path).map_err(read_failed)?; + let mut magic = [0u8; 4]; + let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic); + if !psd { + drop(source); + let bytes = photocraft_format::read_file(path).map_err(read_failed)?; + return import_for_open_with(name, &bytes, opts, ctl); + } + import_source_for_open_with(name, photocraft_psd::Source::new(source), ctl) +} + +/// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source. +pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut damaged = false; + let r = import_psd(name, ctl, &mut damaged, |want, recover| PsdFile::from_source_and_merged_recovering(source, want, recover))?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(1.0); + Ok((r, damaged)) +} + +/// [`import_file_for_open_with`] without the damage flag. +#[cfg(any(unix, windows))] +pub fn import_file(name: &str, path: &std::path::Path, opts: &ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result { + import_file_for_open_with(name, path, opts, ctl).map(|(result, _)| result) +} + /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { @@ -405,7 +464,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus // preview_never_saves_back_to_its_native_or_renamed_source). if is_psd(bytes) { - return import_psd(name, bytes, ctl, damaged); + return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover)); } if affinity::is_affinity(bytes) || affinity::has_extension(name) { return affinity::import(name, bytes); @@ -438,7 +497,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of // `codec: unrecognized image format` (#5258). Magic already returned above. if is_psd_input(name, bytes) { - return import_psd(name, bytes, ctl, damaged); + return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover)); } flat::import_flat(name, bytes) } diff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rs index e200b875ea..dcf7ecd98d 100644 --- a/crates/io/src/linked.rs +++ b/crates/io/src/linked.rs @@ -118,7 +118,30 @@ pub fn find_in_blocks<'a>(blocks: impl IntoIterator(blocks: impl IntoIterator, uuid: &str) -> Option<(String, String, &'a [u8])> { + if uuid.is_empty() { + return None; + } + blocks.into_iter().filter(|(k, _)| matches!(*k, b"lnk2" | b"lnk3" | b"lnkD")).find_map(|(_, d)| { + let mut r = Rd { d, p: 0 }; + while let Some(len) = r.u64() { + let Ok(len) = usize::try_from(len) else { return None }; + let item = r.take(len)?; + let found = item_header(item).filter(|h| h.0 == uuid).and_then(|(id, name, start, n)| Some((id, name, item.get(start..start.checked_add(n)?)?))); + if found.is_some() { + return found; + } + r.p = r.p.next_multiple_of(4); + } + None + }) } /// The size of embedded file `uuid` among PSD global blocks given as (key, data), when it is there @@ -128,11 +151,11 @@ pub(crate) fn source_size_in_blocks<'a>( uuid: &str, ctl: &photocraft_raster::Interrupt, ) -> Option<(f64, f64)> { - let f = find_in_blocks(blocks, uuid)?; + let (_, _, bytes) = find_slice_in_blocks(blocks, uuid)?; if ctl.cancelled() { return None; } - source_size_probe(&f.bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0) + source_size_probe(bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0) } /// Pixel size of an embedded source file from its header: PSD/PSB, TIFF (the default page's diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index e877276198..441e2295a9 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -115,7 +115,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: Optio let header = Header::new(version, doc.size.width, doc.size.height, channels.len().max(1) as u16, psd_depth(sample), PsdMode::Multichannel); let image_data = ImageData::encode(Compression::Rle, &planes, &header) .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + .unwrap_or(ImageData::new(Compression::Raw, planes)); let mut resources = vec![ ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index 8a20d7477b..e1729dcce0 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -45,7 +45,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: Optio let header = Header::new(version, doc.size.width, doc.size.height, 1, depth, mode); let image_data = ImageData::encode(Compression::Rle, &plane, &header) .or_else(|_| ImageData::encode(Compression::Raw, &plane, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: plane }); + .unwrap_or(ImageData::new(Compression::Raw, plane)); let mut resources = vec![ ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 4f992bc8fd..92a5a05850 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -59,8 +59,10 @@ fn pdf_string(s: &str) -> String { } fn deflate(data: &[u8]) -> Vec { - // Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default. - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static + // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger + // than miniz's level 1 was, at about twice its time. + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3)); let _ = e.write_all(data); e.finish().unwrap_or_default() } diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 20207e44eb..c6f8539106 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -188,7 +188,7 @@ impl Ex { let compression = if w == 0 || h == 0 { Compression::Raw } else { self.compression() }; ChannelData::encode(id, compression, plane, w, h, depth, self.version) .or_else(|_| ChannelData::encode(id, Compression::Raw, plane, w, h, depth, self.version)) - .unwrap_or(ChannelData { id, compression: Some(Compression::Raw), data: plane.to_vec() }) + .unwrap_or(ChannelData::new(id, Some(Compression::Raw), plane.to_vec())) } fn empty_channels(&self) -> Vec { diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 50ec2088a0..396d830423 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -208,7 +208,7 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; let image_data = ImageData::encode(mcomp, &planes, &header) .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + .unwrap_or(ImageData::new(Compression::Raw, planes)); ctl.progress(1.0); // Resources. diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index f26574153f..28073ad4e0 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -4,7 +4,8 @@ use std::sync::Arc; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{ - AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer, + AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, PsdGlobalBlock, ShapeLayer, SmartContentsId, SmartObject, SmartSource, + TextLayer, }; use photocraft_geom::{Rect, Size, TILE_SIZE}; use photocraft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK}; @@ -46,6 +47,8 @@ pub(crate) const REGENERATED: [&[u8; 4]; 9] = [b"luni", b"lyid", b"lsct", b"lsdk pub(crate) struct Ctx<'a> { pub file: &'a PsdFile, + /// The file's global blocks, as the document keeps them. + pub global: Vec, pub fmt: PixelFormat, pub mask_fmt: PixelFormat, pub cc: usize, @@ -53,6 +56,9 @@ pub(crate) struct Ctx<'a> { pub warnings: Vec, /// Decoding encountered damaged PSD data; interactive opens ask whether to continue. pub damaged: bool, + /// Reading the file's channel data failed (it is read as it is decoded: see + /// `PsdFile::from_source`): the open fails with it, rather than leaving layers empty. + pub read_error: Option, /// Document resolution (type sizes are converted to points with it). pub dpi: f32, /// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning). @@ -74,9 +80,35 @@ pub(crate) struct Ctx<'a> { pub ctl: photocraft_raster::Interrupt<'a>, /// Layer records decoded so far, out of `total` (progress). pub done: usize, + /// Tiles of one pixel value, shared by every surface the import decodes. + pub uniform: photocraft_raster::TileInterner, pub total: usize, } +/// Bytes of interleaved pixels a band decoded into tiles at once aims at: whole layers up to this +/// size decode in one band, larger ones in bands of whole tile rows. +const BAND_BYTES: usize = 32 << 20; + +/// Row ranges (`0..h`, relative to a layer whose first row is at document row `top`) to decode a +/// layer in: each ends on a tile row boundary, so no tile is written by two bands, and holds +/// about [`BAND_BYTES`] of `row_bytes`-byte rows. +fn band_rows(top: i32, h: usize, row_bytes: usize) -> Vec<(usize, usize)> { + let tile = TILE_SIZE as usize; + let rows = (BAND_BYTES / row_bytes.max(1)).max(tile) / tile * tile; + // The first band ends at the first tile boundary at least `rows` rows in. + let into_tile = usize::try_from(top.rem_euclid(TILE_SIZE)).unwrap_or(0); + let mut out = Vec::new(); + let mut r0 = 0; + let mut r1 = rows - into_tile; + while r0 < h { + let end = r1.min(h); + out.push((r0, end)); + r0 = end; + r1 = end + rows; + } + out +} + fn doc_mode(m: PsdMode) -> Option { Some(match m { PsdMode::Bitmap => ColorMode::Bitmap, @@ -148,6 +180,17 @@ impl Ctx<'_> { self.warn(s); } + /// A channel that failed to decode: a failed read of the file is kept to fail the open + /// (`true`); damaged data is warned about, its layer left empty (`false`). + fn channel_failed(&mut self, name: &str, id: i16, e: &photocraft_psd::PsdError) -> bool { + if let photocraft_psd::PsdError::Read(msg) = e { + self.read_error.get_or_insert_with(|| format!("layer \"{name}\": {msg}")); + return true; + } + self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty")); + false + } + /// Source id, transform, (Distort/Perspective) projective placement and warp of a placed /// layer that has only a `PlLd` block, as Photoshop CS2 and older write it (#2465). `PlLd` /// stores the placed corners but not the source size, which comes from the embedded file. @@ -168,11 +211,11 @@ impl Ctx<'_> { return Placement::default(); } }; - let (file, ctl) = (self.file, self.ctl); + let (global, ctl) = (&self.global, self.ctl); let size = *self .plld_sizes .entry(id.clone()) - .or_insert_with(|| crate::linked::source_size_in_blocks(file.global_blocks.iter().map(|b| (&b.key, b.data.as_slice())), &id, &ctl)); + .or_insert_with(|| crate::linked::source_size_in_blocks(global.iter().map(|(_, k, d)| (k, d.as_slice())), &id, &ctl)); // Without the source (missing or unreadable), it is taken as placed at 100 %. let (transform, perspective) = blocks::plld_transform(&p, size, warp.as_ref()); Placement { id, transform, perspective, warp } @@ -181,72 +224,83 @@ impl Ctx<'_> { /// Decodes a PSD layer channel, marking the document damaged if its data is unreadable. fn channel_plane(&mut self, rec: &LayerRecord, id: i16, name: &str) -> Option> { rec.channel(id)?; + if self.read_error.is_some() { + return None; + } match rec.decode_channel(id, self.file.header.depth, self.file.header.version) { Ok(p) => Some(p), Err(e) => { - self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty")); + self.channel_failed(name, id, &e); None } } } - /// [`Self::channel_plane`] without the warnings sink, so a layer's channels decode - /// concurrently (their RLE rows are the bulk of the open time on full-canvas layers). - fn channel_plane_decoded(&self, rec: &LayerRecord, id: i16) -> Option> { - rec.channel(id)?; - rec.decode_channel(id, self.file.header.depth, self.file.header.version).ok() - } - /// Builds a raster surface from the layer channels, leaving the surface empty if /// any present channel fails to decode rather than inventing replacement pixels. fn record_surface(&mut self, rec: &LayerRecord, name: &str) -> Surface { let r = rec.rect; - if r.is_empty() || r.size().is_err() { + // Once the file couldn't be read the open fails: nothing more is decoded. + if r.is_empty() || r.size().is_err() || self.read_error.is_some() { return Surface::new(self.fmt); } let (w, h) = r.size().unwrap_or((0, 0)); let s = self.fmt.sample; + let (depth, version) = (self.file.header.depth, self.file.header.version); let ids: Vec = (0..self.cc as i16).chain([CHANNEL_TRANSPARENCY]).collect(); - let planes: Vec>> = if cfg!(target_arch = "wasm32") { - ids.iter().map(|&id| self.channel_plane(rec, id, name)).collect() - } else { - // The channels decode independently; their RLE rows are the bulk of the open - // time for full-canvas layers, so they run side by side and the warnings land - // in the same order afterwards. - // par_map reuses the crate's worker pool (one OS thread per channel per layer - // would spawn thousands on a file with many layers). - let decoded: Vec>> = crate::pixels::par_map(ids.to_vec(), |id| self.channel_plane_decoded(rec, id)); - let mut planes: Vec>> = Vec::with_capacity(decoded.len()); - for (&id, p) in ids.iter().zip(decoded) { - if p.is_none() && rec.channel(id).is_some() { - self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded; treated as empty")); - } - planes.push(p); + // A decoder per channel present (a ZIP channel is inflated here, the channels side by + // side); the rows are then decoded and interleaved a band at a time straight into the + // tiles, so no buffer of the whole layer (planes or interleaved) is ever held. + // par_map reuses the crate's worker pool (one OS thread per channel per layer would + // spawn thousands on a file with many layers). + let decoders: Vec>>> = + crate::pixels::par_map(ids.to_vec(), |id| rec.channel(id).map(|ch| ch.row_decoder(w, h, depth, version))); + let mut failed = false; + for (&id, d) in ids.iter().zip(&decoders) { + if let Some(Err(e)) = d { + self.channel_failed(name, id, e); + failed = true; } - planes - }; + } // A channel that is in the file but could not be decoded leaves the layer empty, as the // warning says. Filling in for it would paint an opaque black layer over the document. - if ids.iter().zip(planes.iter()).any(|(&id, p)| p.is_none() && rec.channel(id).is_some()) { + if failed { return Surface::new(self.fmt); } // Only decoded channel data justifies a buffer: the decoders bound their output by the // bytes in the file, but a bare rectangle can declare 300000² pixels in a few bytes (#755). - if planes.iter().all(Option::is_none) { + if decoders.iter().all(Option::is_none) { self.warn_unreadable_data(format!("layer \"{name}\": no channel data for its {w}x{h} bounds; treated as empty")); return Surface::new(self.fmt); } - let refs: Vec> = planes.iter().map(|p| p.as_deref()).collect(); let mut fill: Vec> = vec![zero_sample(s); self.cc]; fill.push(max_sample(s)); let mut invert = vec![self.cmyk; self.cc]; invert.push(false); - let mut bytes = interleave(&refs, &fill, w * h, s, &invert); - if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 { - crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true); + let mut surf = Surface::new(self.fmt); + for (b0, b1) in band_rows(r.top, h, w * (self.cc + 1) * s.bytes()) { + let planes: Vec>>> = + crate::pixels::par_map(decoders.iter().collect(), |d| d.as_ref().and_then(|d| d.as_ref().ok()).map(|d| d.rows(b0, b1))); + let mut refs: Vec> = Vec::with_capacity(planes.len()); + for (&id, p) in ids.iter().zip(&planes) { + match p { + Some(Err(e)) => { + self.channel_failed(name, id, e); + return Surface::new(self.fmt); + } + Some(Ok(p)) => refs.push(Some(p)), + None => refs.push(None), + } + } + let mut bytes = interleave(&refs, &fill, w * (b1 - b0), s, &invert); + if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 { + crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true); + } + surf.write_interleaved(Rect::new(r.left, r.top + b0 as i32, r.right, r.top + b1 as i32), &bytes); } - let mut surf = Surface::from_interleaved(self.fmt, Rect::new(r.left, r.top, r.right, r.bottom), &bytes); surf.prune(); + // A white background, a solid fill's cache: one tile per value, shared across layers. + surf.share_uniform_tiles(&mut self.uniform); surf } @@ -270,6 +324,7 @@ impl Ctx<'_> { let bytes = interleave(&[Some(&plane)], &[zero_sample(s)], w * h, s, &[false]); surface.write_interleaved(Rect::new(rect.left, rect.top, rect.right, rect.bottom), &bytes); surface.prune(); + surface.share_uniform_tiles(&mut self.uniform); } let params = m.parameters; Some(LayerMask { @@ -982,6 +1037,38 @@ pub(crate) fn psd_to_document_decoded_integrity( ctl: &photocraft_raster::Interrupt, decoded: Option>>, ) -> Option<(Document, Vec, bool)> { + let global = file.global_blocks.iter().map(|b| (b.signature, b.key, Arc::new(b.data.clone()))).collect(); + psd_to_document_global(file, ctl, decoded, global).map(|(document, warnings, damaged, _)| (document, warnings, damaged)) +} + +/// [`psd_to_document_decoded_integrity`] taking the file: its global blocks move into the +/// document rather than being copied (an embedded smart object's `lnk2` block can be most of a +/// file). The file's channel data may still be in its source ([`PsdFile::from_source`]): the +/// fourth value is a failure to read it, which fails the open (a layer is never left empty +/// because its file became unreadable while it opened). +pub(crate) fn psd_to_document_owned( + mut file: PsdFile, + ctl: &photocraft_raster::Interrupt, + decoded: Option>>, +) -> Option<(Document, Vec, bool, Option)> { + let global = file + .global_blocks + .iter_mut() + .map(|b| { + // A layer block is still read by `unreadable_layer_block` (to say why it failed). + let data = if matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr") { b.data.clone() } else { std::mem::take(&mut b.data) }; + (b.signature, b.key, Arc::new(data)) + }) + .collect(); + psd_to_document_global(&file, ctl, decoded, global) +} + +fn psd_to_document_global( + file: &PsdFile, + ctl: &photocraft_raster::Interrupt, + decoded: Option>>, + global: Vec, +) -> Option<(Document, Vec, bool, Option)> { let h = &file.header; let mut warnings = Vec::new(); let mode = doc_mode(h.color_mode).unwrap_or_else(|| { @@ -1046,9 +1133,7 @@ pub(crate) fn psd_to_document_decoded_integrity( } } crate::guides_map::apply_colors(&mut doc); - for b in &file.global_blocks { - doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone()))); - } + doc.metadata.psd_global_blocks.extend(global.iter().cloned()); // A 16/32-bit file whose layer block can't be parsed would otherwise open as a flattened // file without a word (#2700). The raw block is kept, but a PSD save writes the document's // own layers in its place (see `psd_export`). @@ -1074,14 +1159,16 @@ pub(crate) fn psd_to_document_decoded_integrity( let cc = fmt.mode.color_channels(); let mut cx = Ctx { file, + global: global.clone(), fmt, mask_fmt: PixelFormat::new(ColorMode::Grayscale, depth, false), cc, cmyk: fmt.mode == ColorMode::Cmyk, warnings, damaged, + read_error: None, dpi: doc.resolution_dpi, - txt2: file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)), + txt2: global.iter().find(|(_, k, _)| k == b"Txt2").and_then(|(_, _, d)| photocraft_text::psd::parse_txt2(d)), filter_effects: Vec::new(), filter_masks: Default::default(), unfiltered: Default::default(), @@ -1090,16 +1177,17 @@ pub(crate) fn psd_to_document_decoded_integrity( plld_sizes: Default::default(), ctl: *ctl, done: 0, + uniform: Default::default(), total: file.layers().len(), }; - for b in file.global_blocks.iter().filter(|b| matches!(&b.key, b"FEid" | b"FXid")) { + for (_, key, data) in cx.global.clone().iter().filter(|(_, k, _)| matches!(k, b"FEid" | b"FXid")) { // Smart-filter caches can be large: a cancelled open stops between blocks. if ctl.cancelled() { return None; } - match photocraft_psd::filter_effects::FilterEffects::parse(&b.data) { + match photocraft_psd::filter_effects::FilterEffects::parse(data) { Ok(fx) => cx.filter_effects.extend(fx.items), - Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", b.key_str())), + Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", String::from_utf8_lossy(key))), } } if ctl.cancelled() { @@ -1331,7 +1419,7 @@ pub(crate) fn psd_to_document_decoded_integrity( return None; } ctl.progress(1.0); - Some((doc, cx.warnings, cx.damaged)) + Some((doc, cx.warnings, cx.damaged, cx.read_error)) } #[cfg(test)] diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs index 66c3bb3cdd..3bb19e3ef8 100644 --- a/crates/io/src/psd_import/tests.rs +++ b/crates/io/src/psd_import/tests.rs @@ -367,3 +367,24 @@ fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { assert_eq!(photoshop_identified_channels(&file), 0, "0 is the transparency's"); assert!(!earlier_photocraft_spot_planes(&file), "no channel left unlisted"); } + +#[test] +fn layer_bands_end_on_tile_rows_and_cover_the_layer() { + let t = TILE_SIZE as usize; + for (top, h, row_bytes) in [(0, 2000, 8000), (-37, 15000, 80_000), (100, 5, 4), (255, 1, 4), (-256, 40_000, 1 << 20), (7, 0, 4)] { + let bands = band_rows(top, h, row_bytes); + let mut next = 0; + for &(a, b) in &bands { + assert_eq!(a, next); + assert!(b > a); + if b < h { + assert_eq!((top + b as i32).rem_euclid(TILE_SIZE), 0, "{top} {h}: band ends inside a tile row"); + assert!((b - a) * row_bytes <= BAND_BYTES + t * row_bytes || b - a <= t); + } + next = b; + } + assert_eq!(next, h); + } + // A small layer is one band. + assert_eq!(band_rows(0, 2000, 8000), vec![(0, 2000)]); +} diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 2cf5342980..72adbe1291 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -37,6 +37,10 @@ use serde_json::{Map, Value as J, json}; use crate::blocks::{enum_of, get_desc, num}; +#[cfg(test)] +#[path = "smart_map/halftone_tests.rs"] +mod halftone_tests; + #[path = "camera_raw_map.rs"] mod camera_raw; #[path = "displace_map.rs"] diff --git a/crates/io/src/smart_map/export.rs b/crates/io/src/smart_map/export.rs index 810d1f49d5..7020fabec1 100644 --- a/crates/io/src/smart_map/export.rs +++ b/crates/io/src/smart_map/export.rs @@ -37,7 +37,7 @@ pub(super) fn pi(p: &J, key: &str, default: f64) -> Value { /// A whole-number setting as a long, clamped to `range` like the engine clamps it; a fraction /// has no PSD equivalent (Photoshop stores these as integers). -fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result { +pub(super) fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result { if v.fract() != 0.0 { return Err(format!("{what} ({v}) is not a whole number")); } diff --git a/crates/io/src/smart_map/halftone_tests.rs b/crates/io/src/smart_map/halftone_tests.rs new file mode 100644 index 0000000000..931483c55b --- /dev/null +++ b/crates/io/src/smart_map/halftone_tests.rs @@ -0,0 +1,207 @@ +//! Halftone Pattern descriptors with the keys from the reference application's Filter Gallery plug-in terminology (#8940): +//! `HlSz` size, `Cntr` contrast and a `ScrT` enum (`ScrD` dot, `ScrC` circle, `ScrL` line). +use super::import::{GALLERY_CLASS, GALLERY_COMMAND, colour_rgbc}; +use super::*; + +/// Builds an editable Halftone Pattern filter with explicit foreground/background colours. +fn filter(pattern: &str, size: i32, contrast: i32) -> SmartFilter { + SmartFilter { + command: GALLERY_COMMAND.into(), + params: json!({ + "effects": [{"filter": "halftonePattern", "params": {"size": size, "contrast": contrast, "patternType": pattern}, "visible": true}], + "foreground": [0.2, 0.4, 0.6, 1.0], "background": [0.8, 0.6, 0.4, 1.0], + }), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + } +} + +/// Builds the inline Halftone descriptor as the reference application writes it. +fn native_effect(pattern: &str, size: i32, contrast: i32) -> Descriptor { + let mut d = Descriptor::new("GEfc") + .with("GEfk", enumv("GEft", "HlfS")) + .with("HlSz", Value::Integer(size)) + .with("Cntr", Value::Integer(contrast)) + .with("ScrT", enumv("ScrT", pattern)); + d.name = UnicodeString::new_nul("Filter Gallery"); + d +} + +/// Wraps a Gallery descriptor in a Photoshop smart-filter item. +fn native_item(effect: Descriptor) -> Descriptor { + let f = filter("dot", 2, 5); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) + .with("blendOptions", blend_options(&f)) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", colour_rgbc(f.params.get("foreground"), 0.0).unwrap()) + .with("BckC", colour_rgbc(f.params.get("background"), 1.0).unwrap()) + .with("Fltr", Value::Descriptor(effect)) + .with("filterID", Value::Integer(code(b"GEfc"))) +} + +/// Checks the pattern enums and editable settings in both mapping directions. +#[test] +fn halftone_pattern_reads_and_writes_photoshop_inline_descriptors() { + for (pattern, native) in [("dot", "ScrD"), ("circle", "ScrC"), ("line", "ScrL")] { + for (size, contrast) in [(1, 0), (2, 5), (7, 31), (12, 50)] { + let expected = filter(pattern, size, contrast); + let native = native_item(native_effect(native, size, contrast)); + assert_eq!(filter_from_item(&native), expected); + let written = item_for_filter(&expected).unwrap(); + assert_eq!(get_desc(&written, "Fltr"), get_desc(&native, "Fltr")); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&written.to_bytes()).unwrap()), expected); + } + } +} + +/// Keeps defaults, hidden effects, stack order, and blending intact on round trip. +#[test] +fn halftone_pattern_defaults_and_mixed_hidden_stack_round_trip() { + let defaults = SmartFilter { params: json!({"effects": [{"filter": "halftonePattern"}]}), ..filter("dot", 1, 5) }; + assert_eq!(filter_from_item(&item_for_filter(&defaults).unwrap()).params["effects"][0]["params"], json!({"size": 1, "contrast": 5, "patternType": "dot"})); + let mut f = filter("circle", 8, 22); + f.params["effects"][0]["visible"] = json!(false); + f.params["effects"].as_array_mut().unwrap().push(json!({"filter": "chrome", "params": {"detail": 4, "smoothness": 7}, "visible": true})); + f.opacity = 0.5; + f.blend = BlendMode::Multiply; + f.visible = false; + let item = item_for_filter(&f).unwrap(); + assert!(get_desc(&item, "Fltr").unwrap().get("GEfs").is_some()); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()), f); +} + +/// A default Halftone Pattern as the reference application saves it (size 1, contrast 5, Dot) opens editable. +#[test] +fn halftone_pattern_photoshop_default_imports_editable() { + let f = filter_from_item(&native_item(native_effect("ScrD", 1, 5))); + assert_eq!(f.command, GALLERY_COMMAND); + assert_eq!(f.params["effects"][0]["filter"], json!("halftonePattern")); + assert_eq!(f.params["effects"][0]["params"], json!({"size": 1, "contrast": 5, "patternType": "dot"})); +} + +/// Keys the reference application's Filter Gallery doesn't use (`Sz `, `Ptrn` of type `HlfT`) are not taken for +/// Halftone settings: the item stays opaque and is written back as it was read. +#[test] +fn halftone_pattern_foreign_keys_stay_verbatim() { + for (pattern, shape) in [("Dt ", "dot"), ("Crc ", "circle"), ("Ln ", "line")] { + let mut d = Descriptor::new("GEfc") + .with("GEfk", enumv("GEft", "HlfS")) + .with("Sz ", Value::Integer(2)) + .with("Cntr", Value::Integer(5)) + .with("Ptrn", enumv("HlfT", pattern)); + d.name = UnicodeString::new_nul("Filter Gallery"); + let item = native_item(d); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{shape}"); + assert_eq!(item_for_filter(&f).unwrap(), item, "{shape}"); + } +} + +/// Preserves unfamiliar and malformed settings instead of substituting editable defaults. +#[test] +fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { + let valid = native_effect("ScrD", 2, 5); + let mut invalid = vec![ + valid.clone().with("futureSetting", Value::Integer(1)), + valid.clone().with("HlSz", Value::Integer(3)), // repeated key + ]; + for (key, value) in [ + ("GEfk", enumv("wrong", "HlfS")), + ("ScrT", enumv("ScrT", "????")), + ("ScrT", enumv("wrong", "ScrD")), + ("ScrT", Value::Integer(0)), + ("HlSz", Value::Integer(0)), + ("HlSz", Value::Integer(13)), + ("HlSz", Value::Double(2.0)), + ("Cntr", Value::Integer(-1)), + ("Cntr", Value::Integer(51)), + ("GELv", Value::Integer(1)), + ] { + let mut effect = valid.clone(); + effect.items.retain(|(id, _)| !id.is(key)); + effect.items.push((Id::new(key), value)); + invalid.push(effect); + } + for missing in ["HlSz", "Cntr", "ScrT"] { + let mut effect = valid.clone(); + effect.items.retain(|(id, _)| !id.is(missing)); + invalid.push(effect); + } + for effect in invalid { + let item = native_item(effect); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +/// Keeps a whole Gallery stack opaque when a Halftone entry has an unfamiliar class ID. +#[test] +fn halftone_pattern_unknown_nested_class_stays_verbatim() { + let valid = native_effect("ScrD", 2, 5); + let mut unknown = valid.clone(); + unknown.class_id = Id::new("Xxxx"); + for effects in [vec![unknown.clone()], vec![valid.clone(), unknown.clone()], vec![unknown, valid]] { + let gallery = Descriptor::new(GALLERY_CLASS).with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect())); + let item = native_item(gallery); + let parsed = Descriptor::from_bytes(&item.to_bytes()).unwrap(); + let filter = filter_from_item(&parsed); + assert_eq!(filter.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&filter).unwrap().to_bytes(), item.to_bytes()); + } +} + +/// Rejects unsupported export values instead of silently changing their meaning. +#[test] +fn halftone_pattern_invalid_export_settings_are_reported() { + for (key, value) in [ + ("patternType", json!("triangle")), + ("patternType", json!(2)), + ("size", json!(0)), + ("size", json!(13)), + ("size", json!("2")), + ("size", json!(2.5)), + ("contrast", json!(-1)), + ("contrast", json!(51)), + ("contrast", json!(1e100)), + ("contrast", json!(5.5)), + ("futureSetting", json!(1)), + ] { + let mut f = filter("dot", 2, 5); + f.params["effects"][0]["params"][key] = value; + assert!(item_for_filter(&f).is_err(), "{key}: {}", f.params); + } +} + +/// Checks complete PSD/PSB round trips for every pattern at 8-, 16-, and 32-bit depth. +#[test] +fn halftone_pattern_survives_complete_psd_and_psb_export() { + use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource}; + use photocraft_geom::Size; + use std::sync::Arc; + + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for pattern in ["dot", "circle", "line"] { + let mut source = Document::new("synthetic contents", Size::new(2, 2), ColorMode::Rgb, sample); + let mut pixels = Surface::new(source.pixel_format()); + pixels.fill_rect(source.bounds(), &[0.5, 0.5, 0.5, 1.0]); + source.layers.push(Layer::new("pixels", LayerContent::Raster(pixels.clone()))); + let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).unwrap(); + let mut smart = + SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, Some(pixels)); + smart.smart_filters.push(filter(pattern, 2, 5)); + let mut doc = Document::new("halftone", Size::new(2, 2), ColorMode::Rgb, sample); + doc.layers.push(Layer::new("halftone", LayerContent::Smart(smart))); + for ext in ["psd", "psb"] { + let out = crate::export(&doc, ext, &crate::ExportOptions::default()).unwrap(); + assert!(!out.warnings.iter().any(|w| w.contains("smart filter")), "{ext}: {:?}", out.warnings); + let back = crate::import(ext, &out.bytes).unwrap().document; + let LayerContent::Smart(smart) = &back.layers[0].content else { panic!("smart object lost") }; + assert_eq!(smart.smart_filters, vec![filter(pattern, 2, 5)], "{ext} {sample:?} {pattern}"); + } + } + } +} diff --git a/crates/io/src/smart_map/import.rs b/crates/io/src/smart_map/import.rs index 341d1d533e..41fce38a0d 100644 --- a/crates/io/src/smart_map/import.rs +++ b/crates/io/src/smart_map/import.rs @@ -1,4 +1,4 @@ -use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc}; +use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc, whole}; use super::placed::enumv; use super::*; @@ -596,7 +596,7 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto // `FrgC`/`BckC` are the colours the Sketch effects read. Only effects whose settings we know are // mapped; a stack with any other effect (or setting) stays an [`UNSUPPORTED_FILTER`]. -const GALLERY_CLASS: &str = "GEfc"; +pub(super) const GALLERY_CLASS: &str = "GEfc"; pub(super) const GALLERY_COMMAND: &str = "filter.filterGallery"; @@ -609,7 +609,13 @@ pub(super) struct GalleryCode { pub(super) settings: &'static [(&'static str, &'static str)], } -pub(super) const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }]; +pub(super) const GALLERY_EFFECTS: [GalleryCode; 2] = [ + GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }, + GalleryCode { key: "halftonePattern", code: "HlfS", settings: &[("HlSz", "size"), ("Cntr", "contrast")] }, +]; + +// Halftone Pattern's shape is a `ScrT` enum (Filter Gallery terminology: Dot, Circle, Line). +const HALFTONE_PATTERNS: [(&[u8; 4], &str); 3] = [(b"ScrD", "dot"), (b"ScrC", "circle"), (b"ScrL", "line")]; /// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. fn rgbc_colour(d: &Descriptor) -> Option { @@ -669,8 +675,22 @@ fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { let code = enum_of(e, "GEfk")?; let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?; let mut params = Map::new(); + if g.key == "halftonePattern" { + // Do not turn an unfamiliar shape or malformed setting into the engine's defaults: + // keeping the whole item opaque preserves it through a subsequent save. + if !e.class_id.is(GALLERY_CLASS) + || !only_keys(e, &["GEfk", "HlSz", "Cntr", "ScrT", "GELv"]) + || !matches!(e.get("GEfk"), Some(Value::Enumerated { type_id, .. }) if type_id.is("GEft")) + || e.get("GELv").is_some_and(|v| !matches!(v, Value::Boolean(_))) + { + return None; + } + int_in(e, "HlSz", 1, 12)?; + int_in(e, "Cntr", 0, 50)?; + params.insert("patternType".into(), json!(enum_name(e, "ScrT", "ScrT", &HALFTONE_PATTERNS)?)); + } for (k, v) in &e.items { - if k.is("GEfk") || k.is("GELv") { + if k.is("GEfk") || k.is("GELv") || g.key == "halftonePattern" && k.is("ScrT") { continue; } let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; @@ -723,13 +743,25 @@ pub(super) fn gallery_item(f: &SmartFilter) -> Result { let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?; let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e); if let Some(k) = params.as_object().and_then(|o| { - o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k)) + o.keys().find(|k| { + !is_meta(k) + && !["filter", "params", "visible"].contains(&k.as_str()) + && !g.settings.iter().any(|(_, ours)| ours == k) + && !(key == "halftonePattern" && *k == "patternType") + }) }) { return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent")); } let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); - let settings: Vec<(&str, Value)> = - g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect(); + let settings: Vec<(&str, Value)> = if key == "halftonePattern" { + vec![ + ("HlSz", whole(pf_range(params, "size", 1.0, 1.0, 12.0)?, (1, 12), "size")?), + ("Cntr", whole(pf_range(params, "contrast", 5.0, 0.0, 50.0)?, (0, 50), "contrast")?), + ("ScrT", enum_param(params, "patternType", "dot", "ScrT", &HALFTONE_PATTERNS)?), + ] + } else { + g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect() + }; out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true))); } let gallery = || { diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 5b3bf5e272..27b536d996 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -376,7 +376,7 @@ fn inflate(bytes: &[u8]) -> Result, IoError> { return Ok(std::borrow::Cow::Borrowed(bytes)); } let mut out = Vec::new(); - let mut reader = flate2::read::MultiGzDecoder::new(bytes).take(MAX_INFLATED_BYTES.saturating_add(1)); + let mut reader = flate2::bufread::MultiGzDecoder::new(bytes).take(MAX_INFLATED_BYTES.saturating_add(1)); reader.read_to_end(&mut out).map_err(|e| IoError::Svg(format!("the compressed SVG couldn't be inflated: {e}")))?; if u64::try_from(out.len()).unwrap_or(u64::MAX) > MAX_INFLATED_BYTES { return Err(IoError::Svg(format!("the compressed SVG inflates past {} MB", MAX_INFLATED_BYTES >> 20))); diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index fc08d76452..ba35e53fed 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -118,7 +118,7 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result Document { + let mut doc = Document::new("compatibility", size, ColorMode::Rgb, depth); + doc.layers.push(Layer::new("pixels", LayerContent::Raster(common::pattern(doc.pixel_format(), doc.bounds(), 3, false)))); + doc +} + +/// Compare both decoders and generate a legacy stream without flate2 compression. +fn old_and_new_inflate(bytes: &[u8]) -> (Vec, Vec) { + let old = miniz_oxide::inflate::decompress_to_vec_zlib(bytes) + .unwrap_or_else(|e| panic!("old decoder: {:?}, header {:?}", e.status, &bytes[..bytes.len().min(8)])); + let legacy = miniz_oxide::deflate::compress_to_vec_zlib(&old, 6); + for stream in [bytes, legacy.as_slice()] { + let mut new = Vec::new(); + flate2::read::ZlibDecoder::new(stream).read_to_end(&mut new).unwrap(); + assert_eq!(new, old); + } + (old, legacy) +} + +/// Read new PNGs and PNGs with legacy-miniz IDAT data through the codec. +fn check_png(bytes: &[u8], image: &Image) { + assert_eq!(photocraft_codecs::decode(bytes).unwrap().data(), image.data()); + let mut idat = Vec::new(); + let mut legacy_png = bytes[..8].to_vec(); + let mut idat_offset = None; + let mut offset = 8; + while offset < bytes.len() { + let len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize; + let end = offset + 12 + len; + if &bytes[offset + 4..offset + 8] == b"IDAT" { + idat_offset.get_or_insert(legacy_png.len()); + idat.extend_from_slice(&bytes[offset + 8..offset + 8 + len]); + } else { + legacy_png.extend_from_slice(&bytes[offset..end]); + } + offset = end; + } + let (_, legacy) = old_and_new_inflate(&idat); + let mut chunk = (legacy.len() as u32).to_be_bytes().to_vec(); + chunk.extend_from_slice(b"IDAT"); + chunk.extend_from_slice(&legacy); + chunk.extend_from_slice(&crc32fast::hash(&chunk[4..]).to_be_bytes()); + let at = idat_offset.unwrap(); + legacy_png.splice(at..at, chunk); + assert_eq!(photocraft_codecs::decode(&legacy_png).unwrap().data(), image.data()); +} + +/// New zlib-rs streams and legacy-miniz streams preserve the same document samples. +#[test] +fn png_psd_and_pcraft_decode_identically() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let doc = document(depth, Size::new(257, 131)); + let pixels = doc.layers[0].surface().unwrap().read_region(doc.bounds()); + if depth != SampleType::F32 { + let sample = if depth == SampleType::U8 { CodecSample::U8 } else { CodecSample::U16 }; + let image = Image::from_normalized(257, 131, ChannelLayout::Rgba, sample, &pixels).unwrap(); + check_png(&photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(), &image); + } + let raw_opts = PsdExportOptions { merged_compression: Compression::Raw, merged_matte: false, ..Default::default() }; + let merged = document_to_psd_with(&doc, &raw_opts).0.image_data.data; + for compression in [Compression::Zip, Compression::ZipPrediction] { + let opts = PsdExportOptions { merged_compression: compression, merged_matte: false, ..Default::default() }; + let mut file = document_to_psd_with(&doc, &opts).0; + // The IO exporter normally chooses Raw for float composites; also cover ZIP here. + if depth == SampleType::F32 { + file.image_data = photocraft_psd::ImageData::encode(compression, &merged, &file.header).unwrap(); + } + let bytes = file.to_bytes().unwrap(); + let parsed = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(parsed.image_data.compression, compression); + let (inflated, legacy) = old_and_new_inflate(&parsed.image_data.data); + // The PSD streaming helper uses a different flate2 reader from plane decoding. + assert_eq!(photocraft_psd::compression::zip_decompress(&legacy, inflated.len()).unwrap(), inflated); + file.image_data.data = legacy; + for fixture in [bytes, file.to_bytes().unwrap()] { + let parsed = photocraft_psd::PsdFile::from_bytes(&fixture).unwrap(); + assert_eq!(parsed.image_data.decode(&parsed.header).unwrap(), merged); + let back = import("compatibility.psd", &fixture).unwrap().document; + assert_eq!(back.layers[0].surface().unwrap().read_region(doc.bounds()), pixels); + } + } + let mut thumbnail = Rgba8Image::new(7, 3); + thumbnail.pixels = (0..84).map(|i| (i * 37) as u8).collect(); + let opts = SaveOptions { thumbnail: Some(thumbnail.clone()), ..Default::default() }; + let bytes = save_to_bytes(&doc, &opts).unwrap(); + assert!(load_from_bytes(&bytes).unwrap() == doc, "all tile bytes, {depth:?}"); + let image = Image::from_u8(7, 3, ChannelLayout::Rgba, thumbnail.pixels).unwrap(); + check_png(&read_thumbnail(&bytes).unwrap().unwrap(), &image); + } +} + +/// PDF export writes its image at the old backend's size or smaller: zlib-rs level 1 +/// (`Compression::fast()`) writes static Huffman blocks only, which made PDFs of photos +/// 5-30% bigger than miniz's level 1 did. +#[test] +fn pdf_image_stream_is_no_bigger_than_miniz_fast() { + let (w, h) = (512u32, 384u32); + let mut doc = Document::new("photo", Size::new(w, h), ColorMode::Rgb, SampleType::U8); + // A noisy gradient: smooth like a photo, with sensor-like grain. + let mut x32 = 0x9E37_79B9u32; + let mut samples = Vec::with_capacity((w * h * 3) as usize); + let mut vals = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + for c in 0..3 { + x32 ^= x32 << 13; + x32 ^= x32 >> 17; + x32 ^= x32 << 5; + let base = (x * 160 / w + y * 80 / h + c * 20) as i32; + let v = (base + (x32 % 9) as i32 - 4).clamp(0, 255) as u8; + samples.push(v); + vals.push(common::g(v)); + } + vals.push(1.0); + } + } + let mut surface = photocraft_raster::Surface::new(doc.pixel_format()); + surface.write_region(doc.bounds(), &vals); + doc.layers.push(Layer::new("photo", LayerContent::Raster(surface))); + let pdf = photocraft_io::export(&doc, "photo.pdf", &Default::default()).unwrap().bytes; + let at = pdf.windows(15).position(|s| s == b"/Subtype /Image").unwrap(); + let dict = &pdf[at..]; + let len_at = dict.windows(8).position(|s| s == b"/Length ").unwrap() + 8; + let digits = dict[len_at..].iter().take_while(|b| b.is_ascii_digit()).count(); + let len: usize = std::str::from_utf8(&dict[len_at..len_at + digits]).unwrap().parse().unwrap(); + let start = dict.windows(7).position(|s| s == b"stream\n").unwrap() + 7; + let stream = &dict[start..start + len]; + assert_eq!(miniz_oxide::inflate::decompress_to_vec_zlib(stream).unwrap(), samples); + let old = miniz_oxide::deflate::compress_to_vec_zlib(&samples, 1).len(); + assert!(len <= old, "PDF image stream {len} bytes, miniz level 1 wrote {old}"); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 27b7b9b4ef..40154335d0 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -20,6 +20,7 @@ mod comps_artboards; mod corpus; mod corpus_regressions; mod cylinder_warp; +mod deflate_compatibility; mod effects_multi; mod exif_resolution; mod export_progress; @@ -51,6 +52,7 @@ mod psd_damaged_merged; mod psd_empty_channels; mod psd_font_identity; mod psd_frame_stroke; +mod psd_import_file; mod psd_kerning; mod psd_layer_block_length; mod psd_maximize_compatibility; diff --git a/crates/io/tests/it/psd_damaged_merged.rs b/crates/io/tests/it/psd_damaged_merged.rs index e3d0970dd9..8e20687bb5 100644 --- a/crates/io/tests/it/psd_damaged_merged.rs +++ b/crates/io/tests/it/psd_damaged_merged.rs @@ -89,7 +89,7 @@ fn modes_imported_flattened_do_not_recover_from_unusable_layer_records() { for mode in [photocraft_psd::ColorMode::Indexed, photocraft_psd::ColorMode::Multichannel, photocraft_psd::ColorMode::Duotone] { let mut file = layered(SampleType::U8, "x.psd"); file.header.color_mode = mode; - file.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: Vec::new() }; + file.image_data = photocraft_psd::ImageData::new(Compression::Raw, Vec::new()); assert!(import("flat-mode.psd", &file.to_bytes().unwrap()).is_err(), "{mode:?}"); } } @@ -98,7 +98,7 @@ fn modes_imported_flattened_do_not_recover_from_unusable_layer_records() { fn lost_extra_channels_are_reported_while_layers_remain_usable() { let mut file = layered(SampleType::U8, "x.psd"); file.header.channels = 5; - file.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: Vec::new() }; + file.image_data = photocraft_psd::ImageData::new(Compression::Raw, Vec::new()); let result = import("extra-channel.psd", &file.to_bytes().unwrap()).unwrap(); assert_eq!(result.document.layer_count(), 1); assert!(result.document.channels.is_empty()); diff --git a/crates/io/tests/it/psd_import_file.rs b/crates/io/tests/it/psd_import_file.rs new file mode 100644 index 0000000000..f8e9243cc1 --- /dev/null +++ b/crates/io/tests/it/psd_import_file.rs @@ -0,0 +1,155 @@ +//! `import_file` parses a PSD/PSB from the open file (channel data read as it is decoded) and must +//! open the same document, with the same warnings, as importing the file's bytes. + +use photocraft_io::{ImportResult, import, import_file}; +use photocraft_psd::testgen; +use photocraft_raster::Interrupt; + +struct TempDir(std::path::PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("photocraft-import-file-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } + + fn write(&self, name: &str, bytes: &[u8]) -> std::path::PathBuf { + let path = self.0.join(name); + std::fs::write(&path, bytes).unwrap(); + path + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The document's debug form with every `…Id(n)` number blanked. +fn without_ids(doc: &photocraft_doc::Document) -> String { + let s = format!("{doc:?}"); + let mut out = String::with_capacity(s.len()); + let mut rest = s.as_str(); + while let Some(at) = rest.find("Id(") { + out.push_str(&rest[..at + 3]); + rest = rest[at + 3..].trim_start_matches(|c: char| c.is_ascii_digit()); + } + out.push_str(rest); + out +} + +fn open(name: &str, path: &std::path::Path) -> Result { + import_file(name, path, &photocraft_io::ImportOptions::default(), &Interrupt::NONE) +} + +#[test] +fn import_file_opens_what_importing_the_bytes_opens() { + let dir = TempDir::new("same"); + let mut checked = 0; + for case in testgen::all_cases() { + let ext = if case.file.header.version.is_psb() { "psb" } else { "psd" }; + let name = format!("case.{ext}"); + let bytes = case.file.to_bytes().unwrap(); + let path = dir.write(&name, &bytes); + let from_bytes = import(&name, &bytes); + let from_file = open(&name, &path); + match (from_bytes, from_file) { + (Ok(a), Ok(b)) => { + // Ids come from a process-wide counter, so the two opens differ only there. + assert!(without_ids(&b.document) == without_ids(&a.document), "{}", case.name); + assert_eq!(b.warnings, a.warnings, "{}", case.name); + checked += 1; + } + (Err(_), Err(_)) => {} + (a, b) => panic!("{}: bytes {:?}, file {:?}", case.name, a.map(|r| r.warnings), b.map(|r| r.warnings)), + } + } + assert!(checked > 50, "only {checked} cases opened"); +} + +#[test] +fn import_file_reads_other_formats_whole() { + let dir = TempDir::new("other"); + let doc = photocraft_doc::Document::new("x", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let png = photocraft_io::export(&doc, "x.png", &Default::default()).unwrap().bytes; + let path = dir.write("x.png", &png); + let r = open("x.png", &path).unwrap(); + assert_eq!(r.document.size, doc.size); +} + +#[test] +fn import_file_fails_cleanly() { + let dir = TempDir::new("fail"); + assert!(open("missing.psd", &dir.0.join("missing.psd")).is_err()); + let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Rle).to_bytes().unwrap(); + // Cut inside the layer records, inside the channel data, and inside the merged image. + for cut in [10, 60, bytes.len() / 2, bytes.len() - 5] { + let name = format!("cut{cut}.psd"); + let path = dir.write(&name, &bytes[..cut]); + let from_bytes = import(&name, &bytes[..cut]); + let from_file = open(&name, &path); + // The merged image is not read when the layers are what opens, so a file cut inside it + // can open from the file where the strict parse of its bytes refused it. + if from_bytes.is_ok() { + assert!(from_file.is_ok(), "cut at {cut}"); + } + } +} + +#[test] +fn a_cancelled_import_file_reports_cancelled() { + let dir = TempDir::new("cancel"); + let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap(); + let path = dir.write("c.psd", &bytes); + let cancel = || true; + let ctl = Interrupt::cancel_only(&cancel); + assert!(matches!(import_file("c.psd", &path, &photocraft_io::ImportOptions::default(), &ctl), Err(photocraft_io::IoError::Cancelled))); +} + +/// A read that fails while the layers are decoded from the file (it is truncated or rewritten, +/// its drive goes away) fails the open: no layer is left empty for a save to lose. +#[test] +fn a_read_failing_while_layers_decode_fails_the_open() { + use photocraft_psd::ReadAt; + /// The file's bytes, failing every read of channel data (as a dropped network share or a + /// truncated file would) except the 2-byte compression fields the parse reads. + struct Failing { + bytes: Vec, + data: Vec<(u64, u64)>, + } + impl ReadAt for Failing { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + let end = offset + buf.len() as u64; + if self.data.iter().any(|&(a, b)| offset < b && end > a) { + return Err(photocraft_psd::PsdError::Read("the drive went away".into())); + } + self.bytes.as_slice().read_at(offset, buf) + } + } + for c in [photocraft_psd::Compression::Rle, photocraft_psd::Compression::Raw, photocraft_psd::Compression::Zip] { + let file = testgen::layered(photocraft_psd::Version::Psd, photocraft_psd::ColorMode::Rgb, 8, c); + let bytes = file.to_bytes().unwrap(); + let lazy = photocraft_psd::PsdFile::from_source(photocraft_psd::Source::new(bytes.clone())).unwrap(); + let data: Vec<(u64, u64)> = lazy + .layers() + .iter() + .flat_map(|l| &l.channels) + .filter_map(|ch| ch.stored.as_ref()) + .filter(|s| s.len > 0) + .map(|s| (s.offset, s.offset + s.len)) + .collect(); + assert!(!data.is_empty()); + // Opening the same file whole succeeds: only the failed reads fail the open. + assert!(import("x.psd", &bytes).is_ok()); + let r = photocraft_io::import_source_for_open_with("x.psd", photocraft_psd::Source::new(Failing { bytes, data }), &Interrupt::NONE); + match r { + Err(photocraft_io::IoError::Read(msg)) => assert!(msg.contains("the drive went away"), "{c:?}: {msg}"), + r => panic!("{c:?}: the open didn't fail: {:?}", r.map(|(r, damaged)| (r.warnings, damaged))), + } + } +} diff --git a/crates/io/tests/it/psd_structure.rs b/crates/io/tests/it/psd_structure.rs index a110fbd367..e263f83a6b 100644 --- a/crates/io/tests/it/psd_structure.rs +++ b/crates/io/tests/it/psd_structure.rs @@ -658,7 +658,7 @@ fn fill_layer_keeps_photoshop_pixels() { VersionedDescriptor::new(Descriptor::new("null").with("Clr ", Value::Descriptor(c))).to_bytes() }; // Photoshop-rendered pixels deliberately differ from the parametric fill. - let plane = |v: u8| ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![v; 4] }; + let plane = |v: u8| ChannelData::new(0, Some(Compression::Raw), vec![v; 4]); let mut chans = vec![plane(255), plane(10), plane(20), plane(30)]; for (i, c) in chans.iter_mut().enumerate() { c.id = i as i16 - 1; @@ -762,7 +762,7 @@ fn merged_composite_unmattes_photoshop_white() { let mut f = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1); f.header.channels = 4; // straight red at alpha 0.5, matted: r = 1, g = b = 0.5 - f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: vec![255, 128, 128, 128] }; + f.image_data = photocraft_psd::ImageData::new(Compression::Raw, vec![255, 128, 128, 128]); let m = merged_composite(&f).unwrap(); assert!((m[0][0] - 1.0).abs() < 0.01 && m[0][1] < 0.01 && m[0][2] < 0.01, "{:?}", m[0]); let (d, _) = psd_to_document(&f); @@ -772,8 +772,7 @@ fn merged_composite_unmattes_photoshop_white() { // HDR and negative straight samples must survive the actual F32 PSD import boundary. let mut hdr = testgen::merged_only(Version::Psd, ColorMode::Rgb, 32, Compression::Raw, 1, 1); hdr.header.channels = 4; - hdr.image_data = - photocraft_psd::ImageData { compression: Compression::Raw, data: [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect() }; + hdr.image_data = photocraft_psd::ImageData::new(Compression::Raw, [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect()); assert_eq!(merged_composite(&hdr).unwrap(), vec![[2.0, -0.5, 0.0, 0.5]]); let mut deep = testgen::merged_only(Version::Psd, ColorMode::Rgb, 16, Compression::Raw, 1, 1); deep.header.channels = 4; @@ -793,7 +792,7 @@ fn vector_rendered_mask_not_doubled_on_shapes() { f.layers_mut().push(LayerRecord { name: b"shape".to_vec(), mask: photocraft_psd::MaskData::Mask(mask), - channels: vec![photocraft_psd::ChannelData { id: -2, compression: Some(Compression::Raw), data: vec![] }], + channels: vec![photocraft_psd::ChannelData::new(-2, Some(Compression::Raw), vec![])], blocks: vec![TaggedBlock::unicode_name("shape"), TaggedBlock::new(*b"SoCo", vec![]), TaggedBlock::new(*b"vmsk", vec![0; 8])], ..Default::default() }); @@ -805,7 +804,7 @@ fn vector_rendered_mask_not_doubled_on_shapes() { let record = f.layers_mut().last_mut().unwrap(); let photocraft_psd::MaskData::Mask(mask) = &mut record.mask else { panic!("fixture has a mask") }; mask.real = Some(photocraft_psd::RealMask { flags: 0, background: 255, rect: photocraft_psd::Rect { top: 0, left: 0, bottom: 1, right: 1 } }); - record.channels.push(photocraft_psd::ChannelData { id: -3, compression: Some(Compression::Raw), data: vec![64] }); + record.channels.push(photocraft_psd::ChannelData::new(-3, Some(Compression::Raw), vec![64])); let (imported, _) = psd_to_document(&f); assert_eq!(imported.layers.last().unwrap().content.kind_name(), "Shape"); let mask = imported.layers.last().unwrap().mask.as_ref().expect("selected real mask must survive synthetic cleanup"); diff --git a/crates/io/tests/it/psd_unknown_adjustment.rs b/crates/io/tests/it/psd_unknown_adjustment.rs index 8b1f0cbdd3..58bc909c57 100644 --- a/crates/io/tests/it/psd_unknown_adjustment.rs +++ b/crates/io/tests/it/psd_unknown_adjustment.rs @@ -77,7 +77,7 @@ fn pixel_layers_with_unknown_blocks_stay_pixel_layers() { // A normal pixel layer (pixels, flag clear) carrying an unknown block. f.layers_mut()[0].blocks.push(extra()); // Flagged but with pixels: never dropped for an adjustment. - let plane = |id: i16| ChannelData { id, compression: Some(Compression::Raw), data: vec![200; 4] }; + let plane = |id: i16| ChannelData::new(id, Some(Compression::Raw), vec![200; 4]); let mut painted = adjustment_record("painted", vec![extra()]); painted.rect = Rect::from_xywh(0, 0, 2, 2); painted.channels = (-1..3).map(plane).collect(); diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index cd533321ec..5c695d1526 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -432,6 +432,9 @@ fn svgz_is_inflated_with_a_size_cap() { let r = import("drawing.svgz", &gzip(plain.as_bytes())).unwrap(); assert_eq!(r.document.layers.len(), 1); assert!(close(px(&r.document, 4, 4), [0.0, 0.0, 1.0, 1.0])); + let split = plain.len() / 2; + let members = [gzip(&plain.as_bytes()[..split]), gzip(&plain.as_bytes()[split..])].concat(); + assert!(close(px(&import("members.svgz", &members).unwrap().document, 4, 4), [0.0, 0.0, 1.0, 1.0])); // A bomb: a few hundred KB of gzip holding more than the cap of whitespace. let mut bomb = format!("").into_bytes(); bomb.resize(usize::try_from(svg::MAX_INFLATED_BYTES).unwrap() + 1024, b' '); diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index d573e7cb3f..f384d527bb 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -1887,3 +1887,38 @@ fn resizing_with_bad_sizes_leaves_the_dual_tip_alone() { b.resize_with_dual_brush(50.0); assert_eq!(b.dual_brush.size, 20.0); } + +/// `touches` is true wherever `coverage_at` can be above 0, false only where it is 0 for sure. +#[test] +fn touches_covers_every_pixel_with_coverage() { + let b = BrushSettings { size: 6.0, ..brush() }; + let mut r = StrokeRenderer::new(&b, None, 1.0); + r.push(&line(100.0, 300.0, 200.0)); + r.finish(); + for y in (0..400).step_by(3) { + for x in (0..500).step_by(3) { + if r.coverage_at(x, y) > 0.0 { + assert!(r.touches(Rect::new(x, y, x + 1, y + 1)), "({x}, {y})"); + } + } + } + // Across the origin and tile edges (64 px): every pixel, both sides of each edge. + let mut o = StrokeRenderer::new(&b, None, 1.0); + o.push(&[StrokePoint::new(-70.0, -70.0, 1.0), StrokePoint::new(70.0, 70.0, 1.0)]); + o.finish(); + for y in -140..140 { + for x in -140..140 { + if o.coverage_at(x, y) > 0.0 { + assert!(o.touches(Rect::new(x, y, x + 1, y + 1)), "({x}, {y})"); + } + } + } + assert!(!o.touches(Rect::new(-128, 64, -64, 128)), "a tile the diagonal misses"); + assert!(!o.touches(Rect::new(-200, -200, -128, -128)), "ends exactly at a tile edge"); + assert!(o.touches(Rect::new(-200, -200, -127, -127)), "one pixel into the next tile"); + assert!(r.touches(Rect::new(150, 199, 151, 201))); + assert!(!r.touches(Rect::new(0, 0, 50, 50)), "far from the stroke"); + assert!(!r.touches(Rect::new(400, 400, 400, 400)), "empty"); + assert!(r.touches(Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX)), "huge, without a huge scan"); + assert!(!r.touches(Rect::new(1_000_000, 1_000_000, i32::MAX, i32::MAX))); +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index cf0835d2dd..24f7259a76 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -1044,6 +1044,21 @@ impl StrokeRenderer { self.ctx.stroke_mask_wet(c, self.cov.depth(x, y), self.dual.as_ref().map(|d| d.get(x, y)), x, y) } + /// Whether any coverage tile overlaps `r`: outside them [`coverage_at`](Self::coverage_at) is + /// 0, so a caller scanning a big area can skip it. + pub fn touches(&self, r: Rect) -> bool { + if r.is_empty() { + return false; + } + let (t0x, t0y) = (r.x0.div_euclid(COV_TILE), r.y0.div_euclid(COV_TILE)); + let (t1x, t1y) = ((r.x1 - 1).div_euclid(COV_TILE), (r.y1 - 1).div_euclid(COV_TILE)); + let span = (i64::from(t1x) - i64::from(t0x) + 1).saturating_mul(i64::from(t1y) - i64::from(t0y) + 1); + if span > self.cov.tiles.len() as i64 { + return self.cov.tiles.keys().any(|&(tx, ty)| (t0x..=t1x).contains(&tx) && (t0y..=t1y).contains(&ty)); + } + (t0y..=t1y).any(|ty| (t0x..=t1x).any(|tx| self.cov.tiles.contains_key(&(tx, ty)))) + } + /// Dense final coverage over the stroke bounds. pub fn dense_coverage(&self) -> (Rect, Vec) { let b = self.bounds(); diff --git a/crates/psd/README.md b/crates/psd/README.md index 421d706ab7..71d12e9f12 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -13,6 +13,7 @@ A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB | `PsdFile::from_bytes(b)?.to_bytes()? == b` for unmodified files | Channel data keeps its original encoding. Unknown blocks and resources are stored raw. Exact padding is recorded wherever it can vary: tagged blocks, layer info, section trailers. | | `from_bytes(to_bytes(f)) == f` for any model `f` | Canonical defaults: `padding: None` means "zero-pad to even", and the parser yields `None` whenever the file used that default. | | Lazy decoding | The parser only copies encoded bytes. Channels are decoded when asked (`ChannelData::decode`, `ImageData::decode`). | +| Lazy reading | `PsdFile::from_source` reads only the structure. Channel data and the merged image stay in the source as `Stored` ranges and are read when decoded, so opening a 2 GB file doesn't need 2 GB for the file itself. The model equals what `from_bytes` builds, and it writes back the same bytes. | | No compositing | `PsdBuilder` takes the merged image from the caller. Without one, it writes a white placeholder and sets `has_real_merged_data = false` in resource 1057. | ## Public API (overview) @@ -22,6 +23,8 @@ A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB PsdFile::from_bytes(&[u8]) -> Result PsdFile::from_bytes_and_merged(&[u8], want) -> Result<(PsdFile, Option>>)> // + decode_merged() when want(&file): ZIP inflated once +PsdFile::from_source(Source) -> Result // channel data and merged image left in the source +PsdFile::from_source_and_merged_recovering(Source, want, recover) PsdFile::to_bytes(&self) -> Result> PsdFile::open(path) / save(path) // native only PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement, @@ -36,6 +39,11 @@ PsdFile::composite_rgba8() -> Result PsdFile::resource(id), global_block(key), icc_profile(), resolution(), has_real_merged_data(), merged_has_alpha(), validate() +// Sources (lazy reading) +trait ReadAt { len(), read_at(offset, buf) } // [u8], Vec, Arc, FileSource (pread / seek_read) +Source::new(impl ReadAt) / read_vec(offset, len) // shared handle; equal when the same source +Stored { source, offset, len }::read() / read_part(at, len) + // Header Header { version: Version::{Psd,Psb}, channels, width, height, depth, color_mode, reserved } ColorMode::{Bitmap, Grayscale, Indexed, Rgb, Cmyk, Multichannel, Duotone, Lab, Unknown(u16)} @@ -47,7 +55,8 @@ LayerRecord { rect, channels: Vec, blend_mode, opacity, clipping, f LayerRecord::name() // prefers `luni` LayerRecord::section_divider(), section_type(), layer_id(), fill_opacity(), is_visible(), block(key), block_mut(key), channel(id), channel_rect(id), decode_channel(id, depth, version) -ChannelData { id, compression: Option, data } // encoded bytes kept verbatim +ChannelData { id, compression: Option, data, stored: Option } // encoded bytes kept verbatim +ChannelData::new(id, compression, data); encoded() -> Cow<[u8]>; encoded_len(); load() ChannelData::encode(id, compression, decoded, w, h, depth, version) ChannelData::decode(w, h, depth, version); set_decoded(...) MaskData::{None, Mask(LayerMask), Raw(Vec)} diff --git a/crates/psd/examples/bench_layer_block.rs b/crates/psd/examples/bench_layer_block.rs index 4d34f9b8f3..2b48de1d28 100644 --- a/crates/psd/examples/bench_layer_block.rs +++ b/crates/psd/examples/bench_layer_block.rs @@ -11,12 +11,12 @@ fn main() -> Result<()> { let plane_bytes = 6000 * 4000 * usize::from(depth / 8); let mut layer = LayerRecord { rect: Rect::from_xywh(0, 0, 6000, 4000), name: b"RGB".to_vec(), ..Default::default() }; for id in 0..3 { - layer.channels.push(ChannelData { id, compression: Some(Compression::Raw), data: vec![0; plane_bytes] }); + layer.channels.push(ChannelData::new(id, Some(Compression::Raw), vec![0; plane_bytes])); } file.layer_info = Some(LayerInfo { merged_alpha: false, layers: vec![layer], padding: None }); file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: if depth == 16 { *b"Lr16" } else { *b"Lr32" }, padding: None }; - file.image_data = ImageData { compression: Compression::Raw, data: vec![0; plane_bytes * 3] }; + file.image_data = ImageData::new(Compression::Raw, vec![0; plane_bytes * 3]); black_box(file.to_bytes()?); let mut samples = Vec::new(); let mut size = 0; diff --git a/crates/psd/src/error.rs b/crates/psd/src/error.rs index da519e6698..a1fc1a5c98 100644 --- a/crates/psd/src/error.rs +++ b/crates/psd/src/error.rs @@ -37,6 +37,9 @@ pub enum PsdError { /// A compressed stream could not be decoded. #[error("decompression failed: {0}")] Decompress(String), + /// Reading from a [`crate::source::ReadAt`] source failed. + #[error("read failed: {0}")] + Read(String), /// An operation is not supported for this data (e.g. unknown compression). #[error("unsupported: {0}")] Unsupported(String), diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs index ccc1e7ba0d..828e7bc032 100644 --- a/crates/psd/src/file.rs +++ b/crates/psd/src/file.rs @@ -189,7 +189,7 @@ impl PsdFile { layer_mask_trailing = s.peek_rest().to_vec(); } } - let image_data = ImageData { compression: Compression::Raw, data: Vec::new() }; + let image_data = ImageData::new(Compression::Raw, Vec::new()); let mut file = PsdFile { header, color_mode_data, @@ -202,11 +202,24 @@ impl PsdFile { image_data, write_as_psb: false, }; + let want = want(&file); + let merged = file.read_merged_section(&mut r, want, recover)?; + Ok((file, merged)) + } + + /// Reads the merged image section from `rest` (the bytes after the layer and mask section) as + /// [`Self::from_bytes_and_merged_recovering`] does, decoding it. + pub(crate) fn read_merged_recovering(&mut self, rest: &[u8], recover: impl FnOnce(&PsdFile) -> bool) -> Result>>> { + self.read_merged_section(&mut Reader::new(rest), true, recover) + } + + fn read_merged_section(&mut self, r: &mut Reader<'_>, want: bool, recover: impl FnOnce(&PsdFile) -> bool) -> Result>>> { + let file = self; let mut encoded = r.clone(); - let merged = if want(&file) { - file.read_merged_decoded(&mut r).map(Some) + let merged = if want { + file.read_merged_decoded(r).map(Some) } else { - ImageData::read(&mut r, &file.header).map(|image| { + ImageData::read(r, &file.header).map(|image| { file.image_data = image; None }) @@ -214,7 +227,7 @@ impl PsdFile { let merged = match merged { Ok(merged) => merged, Err(error) => { - if matches!(error, PsdError::LimitExceeded(_)) || !recover(&file) { + if matches!(error, PsdError::LimitExceeded(_)) || !recover(file) { return Err(error); } let compression = Compression::from_u16(encoded.u16()?); @@ -222,11 +235,11 @@ impl PsdFile { let mut data = Vec::new(); data.try_reserve_exact(source.len()).map_err(|_| PsdError::LimitExceeded("not enough memory to retain the damaged merged image"))?; data.extend_from_slice(source); - file.image_data = ImageData { compression, data }; + file.image_data = ImageData::new(compression, data); Some(Err(error)) } }; - Ok((file, merged)) + Ok(merged) } /// Reads the merged image into `self.image_data` and decodes it. A ZIP stream within the @@ -249,7 +262,7 @@ impl PsdFile { if decoded.is_err() { validate_planes(compression, data, &layout)?; } - self.image_data = ImageData { compression, data: data.to_vec() }; + self.image_data = ImageData::new(compression, data.to_vec()); r.skip(data.len())?; Ok(decoded) } @@ -265,7 +278,7 @@ impl PsdFile { .layer_info .as_ref() .map_or(0, LayerInfo::channel_data_len) - .saturating_add(self.image_data.data.len()) + .saturating_add(usize::try_from(self.image_data.encoded_len()).unwrap_or(usize::MAX)) .saturating_add(usize::try_from(widened).unwrap_or(usize::MAX)); let mut out = Vec::new(); out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?; @@ -325,8 +338,8 @@ impl PsdFile { out.put_u16(self.image_data.compression.as_u16()); match self.merged_widened_rows(widen)? { - 0 => out.put(&self.image_data.data), - rows => put_widened_rle(&mut out, &self.image_data.data, rows)?, + 0 => out.put(&self.image_data.encoded()?), + rows => put_widened_rle(&mut out, &self.image_data.encoded()?, rows)?, } Ok(out) } @@ -357,13 +370,13 @@ impl PsdFile { for c in &layer.channels { match layer.widened_rows(c, true)? { 0 => {} - rows => n = n.saturating_add(rle_widening(&c.data, rows)?), + rows => n = n.saturating_add(rle_widening(&c.encoded()?, rows)?), } } } match self.merged_widened_rows(true)? { 0 => Ok(n), - rows => Ok(n.saturating_add(rle_widening(&self.image_data.data, rows)?)), + rows => Ok(n.saturating_add(rle_widening(&self.image_data.encoded()?, rows)?)), } } @@ -406,9 +419,9 @@ impl PsdFile { } let merged = match self.merged_widened_rows(widen)? { 0 => 0, - rows => rle_widening(&self.image_data.data, rows)?, + rows => rle_widening(&self.image_data.encoded()?, rows)?, }; - Ok(n.saturating_add(2).saturating_add(self.image_data.data.len() as u64).saturating_add(merged)) + Ok(n.saturating_add(2).saturating_add(self.image_data.encoded_len()).saturating_add(merged)) } /// Marks a PSD model to be written as the equivalent PSB ([`Self::write_as_psb`]) without diff --git a/crates/psd/src/image_data.rs b/crates/psd/src/image_data.rs index 864486b4ac..9e27af2917 100644 --- a/crates/psd/src/image_data.rs +++ b/crates/psd/src/image_data.rs @@ -1,13 +1,20 @@ //! Merged (composite) image data section. +use std::borrow::Cow; + use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, validate_planes}; use crate::error::Result; use crate::header::Header; use crate::io::Reader; +use crate::source::Stored; /// The merged image: compression plus the encoded bytes of all channels /// (to the end of the file), kept verbatim. -#[derive(Debug, Clone, PartialEq, Eq)] +/// +/// As with [`crate::ChannelData`], a file parsed by +/// [`PsdFile::from_source`](crate::PsdFile::from_source) may leave the bytes in the source +/// (`stored`, with `data` empty); equality compares the bytes wherever they are. +#[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ImageData { /// Compression method for the whole image. @@ -15,9 +22,50 @@ pub struct ImageData { /// Encoded data. For RLE: the byte-count table for every row of every /// channel followed by the rows. pub data: Vec, + /// Where the encoded bytes are when they were left in the source. (Not serialized.) + #[cfg_attr(feature = "serde", serde(skip))] + pub stored: Option, } +impl PartialEq for ImageData { + fn eq(&self, other: &Self) -> bool { + if self.compression != other.compression || self.encoded_len() != other.encoded_len() { + return false; + } + match (self.encoded(), other.encoded()) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } + } +} + +impl Eq for ImageData {} + impl ImageData { + /// A merged image whose encoded bytes are in memory. + pub fn new(compression: Compression, data: Vec) -> Self { + ImageData { compression, data, stored: None } + } + + /// The encoded bytes: borrowed from `data`, or read from the source. + pub fn encoded(&self) -> Result> { + crate::source::encoded(&self.data, self.stored.as_ref()) + } + + /// Number of encoded bytes, wherever they are. + pub fn encoded_len(&self) -> u64 { + self.stored.as_ref().map_or(self.data.len() as u64, |s| s.len) + } + + /// Reads bytes left in the source into `data`. + pub fn load(&mut self) -> Result<()> { + if let Some(s) = &self.stored { + self.data = s.read()?; + self.stored = None; + } + Ok(()) + } + /// Plane layout for the merged image described by `header`. pub fn layout(header: &Header) -> PlaneLayout { PlaneLayout { @@ -31,12 +79,12 @@ impl ImageData { /// Encodes planar data (`channels × height × row_bytes`). pub fn encode(compression: Compression, decoded: &[u8], header: &Header) -> Result { - Ok(ImageData { compression, data: encode_planes(compression, decoded, &Self::layout(header))? }) + Ok(ImageData::new(compression, encode_planes(compression, decoded, &Self::layout(header))?)) } /// Decodes all channels into planar big-endian samples. pub fn decode(&self, header: &Header) -> Result> { - decode_planes(self.compression, &self.data, &Self::layout(header)) + decode_planes(self.compression, &self.encoded()?, &Self::layout(header)) } pub(crate) fn read(r: &mut Reader<'_>, header: &Header) -> Result { @@ -45,6 +93,6 @@ impl ImageData { validate_planes(compression, data, &Self::layout(header))?; let data = data.to_vec(); r.skip(data.len())?; - Ok(ImageData { compression, data }) + Ok(ImageData::new(compression, data)) } } diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index 7756be4a6c..cbc4ccb424 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -1,10 +1,13 @@ //! Layer records, layer masks, blending ranges and per-layer channel data. +use std::borrow::Cow; + use crate::blend::BlendMode; use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, put_widened_rle, rle_widening}; use crate::error::{PsdError, Result}; use crate::header::{MAX_DIMENSION, Version}; use crate::io::{Reader, WriteExt, decode_legacy_name, read_pascal, write_pascal}; +use crate::source::Stored; use crate::tagged::{BlockData, SectionDivider, SectionType, TaggedBlock, read_blocks, uses_long_length, write_blocks}; /// Channel id of the transparency mask. @@ -368,7 +371,12 @@ impl BlendingRanges { } /// Encoded image data for one layer channel. -#[derive(Debug, Clone, PartialEq, Eq)] +/// +/// The encoded bytes are in `data`, or, for a file parsed by +/// [`PsdFile::from_source`](crate::PsdFile::from_source), still in the source at `stored` (and +/// `data` is empty). Every method here reads them from wherever they are; two channels are equal +/// when their bytes are, wherever each one keeps them. +#[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ChannelData { /// Channel id: 0.. color channels, -1 transparency, -2 user mask, @@ -377,22 +385,65 @@ pub struct ChannelData { /// Compression; `None` when the stored length was 0 (no compression /// field at all). pub compression: Option, - /// Encoded bytes following the compression field, kept verbatim. + /// Encoded bytes following the compression field, kept verbatim (empty while `stored`). pub data: Vec, + /// Where the encoded bytes are when they were left in the source: see [`Self::load`]. + /// (Not serialized: load the channel first.) + #[cfg_attr(feature = "serde", serde(skip))] + pub stored: Option, } +impl PartialEq for ChannelData { + fn eq(&self, other: &Self) -> bool { + if self.id != other.id || self.compression != other.compression || self.encoded_len() != other.encoded_len() { + return false; + } + match (self.encoded(), other.encoded()) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } + } +} + +impl Eq for ChannelData {} + impl ChannelData { /// Encodes planar samples (`height × row_bytes`). pub fn encode(id: i16, compression: Compression, decoded: &[u8], width: usize, height: usize, depth: u16, version: Version) -> Result { let layout = PlaneLayout { planes: 1, width, height, depth, version }; - Ok(ChannelData { id, compression: Some(compression), data: encode_planes(compression, decoded, &layout)? }) + Ok(ChannelData::new(id, Some(compression), encode_planes(compression, decoded, &layout)?)) + } + + /// A channel whose encoded bytes are in memory. + pub fn new(id: i16, compression: Option, data: Vec) -> Self { + ChannelData { id, compression, data, stored: None } + } + + /// The encoded bytes (after the compression field): borrowed from `data`, or read from the + /// source when they were left there. + pub fn encoded(&self) -> Result> { + crate::source::encoded(&self.data, self.stored.as_ref()) + } + + /// Number of encoded bytes, wherever they are. + pub fn encoded_len(&self) -> u64 { + self.stored.as_ref().map_or(self.data.len() as u64, |s| s.len) + } + + /// Reads bytes left in the source into `data`, so the channel no longer needs its source. + pub fn load(&mut self) -> Result<()> { + if let Some(s) = &self.stored { + self.data = s.read()?; + self.stored = None; + } + Ok(()) } /// Decodes into planar big-endian samples. pub fn decode(&self, width: usize, height: usize, depth: u16, version: Version) -> Result> { let layout = PlaneLayout { planes: 1, width, height, depth, version }; match self.compression { - Some(c) => decode_planes(c, &self.data, &layout), + Some(c) => decode_planes(c, &self.encoded()?, &layout), None => { if layout.decoded_len()? == 0 { Ok(Vec::new()) @@ -412,7 +463,7 @@ impl ChannelData { fn stored_len(&self) -> u64 { match self.compression { - Some(_) => 2 + self.data.len() as u64, + Some(_) => 2 + self.encoded_len(), None => 0, } } @@ -556,7 +607,7 @@ impl LayerRecord { ch.decode(w, h, depth, version) } - fn read(r: &mut Reader<'_>, version: Version) -> Result<(Self, Vec)> { + pub(crate) fn read(r: &mut Reader<'_>, version: Version) -> Result<(Self, Vec)> { let rect = Rect::read(r)?; let nch = r.u16()?; if nch > MAX_LAYER_CHANNELS { @@ -567,7 +618,7 @@ impl LayerRecord { for _ in 0..nch { let id = r.i16()?; let len = r.len_field(version.is_psb())?; - channels.push(ChannelData { id, compression: None, data: Vec::new() }); + channels.push(ChannelData::new(id, None, Vec::new())); lens.push(len); } let sig = r.array::<4>()?; @@ -641,7 +692,7 @@ impl LayerRecord { for c in &self.channels { out.put_i16(c.id); let rows = self.widened_rows(c, widen)?; - let grown = if rows == 0 { 0 } else { rle_widening(&c.data, rows)? }; + let grown = if rows == 0 { 0 } else { rle_widening(&c.encoded()?, rows)? }; out.put_len(c.stored_len().saturating_add(grown), version.is_psb())?; } out.put(b"8BIM"); @@ -732,8 +783,8 @@ impl LayerInfo { for l in &self.layers { for c in l.channels.iter().filter(|c| c.compression.is_some()) { let rows = l.widened_rows(c, widen)?; - let grown = if rows == 0 { 0 } else { rle_widening(&c.data, rows)? }; - n = n.saturating_add(2).saturating_add(c.data.len() as u64).saturating_add(grown); + let grown = if rows == 0 { 0 } else { rle_widening(&c.encoded()?, rows)? }; + n = n.saturating_add(2).saturating_add(c.encoded_len()).saturating_add(grown); } } Ok(n) @@ -763,7 +814,11 @@ impl LayerInfo { /// Bytes of channel data and their compression fields: the part of the body worth reserving up /// front (the records are small next to the pixels). Saturates instead of overflowing. pub(crate) fn channel_data_len(&self) -> usize { - self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()).fold(0usize, |n, c| n.saturating_add(2).saturating_add(c.data.len())) + self.layers + .iter() + .flat_map(|l| &l.channels) + .filter(|c| c.compression.is_some()) + .fold(0usize, |n, c| n.saturating_add(2).saturating_add(usize::try_from(c.encoded_len()).unwrap_or(usize::MAX))) } /// Serializes the body without any trailing padding (the padding field is ignored). @@ -784,8 +839,8 @@ impl LayerInfo { if let Some(comp) = c.compression { out.put_u16(comp.as_u16()); match l.widened_rows(c, widen)? { - 0 => out.put(&c.data), - rows => put_widened_rle(out, &c.data, rows)?, + 0 => out.put(&c.encoded()?), + rows => put_widened_rle(out, &c.encoded()?, rows)?, } } } diff --git a/crates/psd/src/layer/tests.rs b/crates/psd/src/layer/tests.rs index a5ad06efbb..c831b1c6d2 100644 --- a/crates/psd/src/layer/tests.rs +++ b/crates/psd/src/layer/tests.rs @@ -54,7 +54,7 @@ fn record_roundtrip_psd_psb() { #[test] fn psb_channel_lengths_are_8_bytes() { let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![] }); + rec.channels.push(ChannelData::new(0, Some(Compression::Raw), vec![])); let info = LayerInfo { layers: vec![rec], ..Default::default() }; let psd = rt(&info, Version::Psd); let psb = rt(&info, Version::Psb); @@ -294,7 +294,7 @@ fn too_many_layers_rejected() { #[test] fn zero_length_channel() { let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: None, data: vec![] }); + rec.channels.push(ChannelData::new(0, None, vec![])); let info = LayerInfo { layers: vec![rec], ..Default::default() }; rt(&info, Version::Psd); assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); diff --git a/crates/psd/src/lazy.rs b/crates/psd/src/lazy.rs new file mode 100644 index 0000000000..d81d102d11 --- /dev/null +++ b/crates/psd/src/lazy.rs @@ -0,0 +1,437 @@ +//! Parsing from a [`Source`] without reading the whole file: [`PsdFile::from_source`]. +//! +//! The structure (header, resources, layer records, global blocks) is read into memory as +//! [`PsdFile::from_bytes`] would hold it. The bulk of a layered file is left in the source: every +//! channel's encoded bytes and the merged image become [`Stored`] ranges, read when they are +//! decoded. Apart from those ranges, the model is the one `from_bytes` builds from the same bytes +//! (the parse tests hold the two to that), with one difference: a merged image the caller does +//! not ask for is not read, so it is not checked either. + +use crate::compression::Compression; +use crate::error::{PsdError, Result}; +use crate::file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; +use crate::header::{Header, Version}; +use crate::image_data::ImageData; +use crate::io::Reader; +use crate::layer::{LayerInfo, LayerRecord}; +use crate::resources::ImageResource; +use crate::source::{Source, Stored}; +use crate::tagged::{TaggedBlock, is_sig, uses_long_length}; + +/// Bytes read per attempt at the layer records; doubled until they all fit. (Small in tests, so +/// they grow it.) +const RECORDS_CHUNK: u64 = if cfg!(test) { 64 } else { 1 << 20 }; + +/// A bounds-checked cursor over `start..end` of a source. +struct Cursor<'a> { + src: &'a Source, + pos: u64, + end: u64, +} + +impl<'a> Cursor<'a> { + fn new(src: &'a Source) -> Self { + Cursor { src, pos: 0, end: src.get().len() } + } + + fn remaining(&self) -> u64 { + self.end.saturating_sub(self.pos) + } + + fn is_empty(&self) -> bool { + self.remaining() == 0 + } + + fn eof(&self, needed: u64) -> PsdError { + PsdError::UnexpectedEof { + offset: usize::try_from(self.pos).unwrap_or(usize::MAX), + needed: usize::try_from(needed.saturating_sub(self.remaining())).unwrap_or(usize::MAX), + } + } + + fn need(&self, n: u64) -> Result<()> { + if n > self.remaining() { Err(self.eof(n)) } else { Ok(()) } + } + + /// Reads `n` bytes. + fn bytes(&mut self, n: u64) -> Result> { + self.need(n)?; + let v = self.src.read_vec(self.pos, n)?; + self.pos += n; + Ok(v) + } + + /// Up to `n` bytes from the current position, without consuming. + fn peek(&self, n: u64) -> Result> { + self.src.read_vec(self.pos, n.min(self.remaining())) + } + + fn array(&mut self) -> Result<[u8; N]> { + self.need(N as u64)?; + let mut b = [0u8; N]; + self.src.get().read_at(self.pos, &mut b)?; + self.pos += N as u64; + Ok(b) + } + + fn u16(&mut self) -> Result { + self.array().map(u16::from_be_bytes) + } + + fn i16(&mut self) -> Result { + self.array().map(i16::from_be_bytes) + } + + fn u32(&mut self) -> Result { + self.array().map(u32::from_be_bytes) + } + + fn len_field(&mut self, long: bool) -> Result { + if long { self.array().map(u64::from_be_bytes) } else { self.u32().map(u64::from) } + } + + /// The next `n` bytes as a cursor of their own; this one moves past them. + fn sub(&mut self, n: u64) -> Result> { + self.need(n)?; + let sub = Cursor { src: self.src, pos: self.pos, end: self.pos + n }; + self.pos += n; + Ok(sub) + } + + fn skip(&mut self, n: u64) -> Result<()> { + self.need(n)?; + self.pos += n; + Ok(()) + } + + fn rest(&mut self) -> Result> { + self.bytes(self.remaining()) + } + + /// The rest as a stored range; the cursor moves to the end. + fn stored_rest(&mut self) -> Stored { + let s = Stored { source: self.src.clone(), offset: self.pos, len: self.remaining() }; + self.pos = self.end; + s + } +} + +impl PsdFile { + /// Parses a file from `source`, leaving channel data and the merged image in it: see + /// [`crate::source`]. Decoding a channel then reads its bytes from the source, which must + /// stay unchanged while the model is in use. + pub fn from_source(source: Source) -> Result { + Self::from_source_and_merged_recovering(source, |_| false, |_| false).map(|(file, _)| file) + } + + /// [`Self::from_bytes_and_merged_recovering`] for a [`Source`]: the merged image is read only + /// when `want` asks for it (and is then decoded as there, with the same recovery); otherwise + /// it stays in the source, unread and unchecked. + pub fn from_source_and_merged_recovering( + source: Source, + want: impl FnOnce(&PsdFile) -> bool, + recover: impl FnOnce(&PsdFile) -> bool, + ) -> Result<(Self, Option>>)> { + let mut c = Cursor::new(&source); + let header = Header::read(&mut Reader::new(&c.bytes(26)?))?; + let version = header.version; + let psb = version.is_psb(); + let cmd_len = c.u32()?; + let color_mode_data = c.bytes(u64::from(cmd_len))?; + let res_len = c.u32()?; + let res = c.bytes(u64::from(res_len))?; + let mut rr = Reader::new(&res); + let mut resources = Vec::new(); + while !rr.is_empty() { + resources.push(ImageResource::read(&mut rr)?); + } + + let lm_len = c.len_field(psb)?; + let mut s = c.sub(lm_len)?; + let mut layer_info = None; + let mut global_layer_mask = None; + let mut global_blocks = Vec::new(); + let mut layer_mask_trailing = Vec::new(); + let mut layer_info_placement = LayerInfoPlacement::Section; + if !s.is_empty() { + let li_len = s.len_field(psb)?; + if li_len > 0 { + layer_info = Some(read_layer_info(s.sub(li_len)?, version)?); + } + if s.remaining() >= 4 { + let n = s.u32()?; + global_layer_mask = Some(GlobalLayerMask { data: s.bytes(u64::from(n))? }); + let target_key = match header.depth { + 16 => Some(b"Lr16"), + 32 => Some(b"Lr32"), + _ => None, + }; + let mut candidate_seen = match target_key { + Some(_) => false, + None => layer_info.as_ref().is_some_and(|i: &LayerInfo| !i.layers.is_empty()), + }; + let trailing = read_blocks( + &mut s, + version, + |index, signature, key, data, padding| { + let is_candidate = match target_key { + Some(k) => &key == k, + None => matches!(&key, b"Layr" | b"Lr16" | b"Lr32"), + }; + if candidate_seen || !is_candidate { + return Ok(None); + } + candidate_seen = true; + let info = match read_layer_info(data, version) { + Ok(info) => info, + // A failed read of the source is not damage: fail the parse, as + // reading the whole file would. + Err(e @ PsdError::Read(_)) => return Err(e), + Err(_) => { + if target_key.is_some() { + layer_info = None; + } + return Ok(None); + } + }; + layer_info = Some(info); + layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature, key, padding: padding.clone() }; + Ok(Some(())) + }, + &mut global_blocks, + )?; + layer_mask_trailing = trailing; + } else { + layer_mask_trailing = s.rest()?; + } + } + let mut file = PsdFile { + header, + color_mode_data, + resources, + layer_info, + layer_info_placement, + global_layer_mask, + global_blocks, + layer_mask_trailing, + image_data: ImageData::new(Compression::Raw, Vec::new()), + write_as_psb: false, + }; + if !want(&file) { + let compression = Compression::from_u16(c.u16()?); + file.image_data = ImageData { compression, data: Vec::new(), stored: Some(c.stored_rest()) }; + return Ok((file, None)); + } + // The merged image is wanted: read it and decode it as `from_bytes` does. + let rest = c.rest()?; + let merged = file.read_merged_recovering(&rest, recover)?; + Ok((file, merged)) + } +} + +/// Reads tagged blocks as [`crate::tagged::read_blocks_with`] does, from a cursor: `consume` +/// sees each block's data as a cursor and returns `Some` when it took the block; the others are +/// read into memory and pushed to `blocks`. Returns the trailing bytes. +fn read_blocks<'a>( + r: &mut Cursor<'a>, + version: Version, + mut consume: impl FnMut(usize, [u8; 4], [u8; 4], Cursor<'a>, &Option>) -> Result>, + blocks: &mut Vec, +) -> Result> { + const ALIGNMENT: usize = 4; + loop { + let head = r.peek(12)?; + if head.len() < 12 || !is_sig(&head) { + return r.rest(); + } + let signature = r.array::<4>()?; + let key = r.array::<4>()?; + let len = r.len_field(uses_long_length(version, &key))?; + let data = r.sub(len)?; + // Padding as `read_blocks_with` detects it: the smallest k in 0..=3 such that the next + // signature (or the end of the region) follows k bytes later. + let rest = r.peek(7)?; + let mut pad = None; + for k in 0..=3usize { + if k == rest.len() || rest.get(k..).is_some_and(is_sig) { + pad = Some(k); + break; + } + } + let default = TaggedBlock::default_padding((len % ALIGNMENT as u64) as usize, ALIGNMENT); + let pad = pad.unwrap_or_else(|| if rest.get(..default).is_some_and(|p| p.iter().all(|&b| b == 0)) { default } else { 0 }); + let pad_bytes = rest.get(..pad).map(<[u8]>::to_vec).unwrap_or_default(); + r.skip(pad as u64)?; + let padding = if pad_bytes.len() == default && pad_bytes.iter().all(|&b| b == 0) { None } else { Some(pad_bytes) }; + let (start, end) = (data.pos, data.end); + if consume(blocks.len(), signature, key, data, &padding)?.is_none() { + let data = Cursor { src: r.src, pos: start, end }.rest()?; + blocks.push(TaggedBlock { signature, key, data, padding }); + } + } +} + +/// [`LayerInfo::read_body`] from a cursor over the body: the records are read into memory, and +/// each channel's encoded bytes become a [`Stored`] range after its compression field. +fn read_layer_info(mut r: Cursor<'_>, version: Version) -> Result { + let body_start = r.pos; + let count = r.i16()?; + let merged_alpha = count < 0; + let n = count.unsigned_abs(); + // Minimum record size, as `read_body` checks it. + if u64::from(n) * 34 > r.remaining() { + return Err(r.eof(u64::from(n) * 34)); + } + // The records' total size is only known once they are parsed: read a chunk and grow it until + // they all fit (or the body is exhausted, when their error is the body's). + let mut chunk = RECORDS_CHUNK.min(r.remaining()); + let (layers, all_lens, used) = loop { + let buf = r.peek(chunk)?; + let mut rr = Reader::new(&buf); + let mut layers = Vec::with_capacity(usize::from(n)); + let mut all_lens = Vec::with_capacity(usize::from(n)); + let parsed = (0..n).try_for_each(|_| { + let (rec, lens) = LayerRecord::read(&mut rr, version)?; + layers.push(rec); + all_lens.push(lens); + Ok::<_, PsdError>(()) + }); + match parsed { + Ok(()) => break (layers, all_lens, rr.pos() as u64), + Err(PsdError::UnexpectedEof { .. }) if chunk < r.remaining() => chunk = chunk.saturating_mul(2).min(r.remaining()), + Err(e) => return Err(e), + } + }; + r.skip(used)?; + let mut layers = layers; + for (rec, lens) in layers.iter_mut().zip(all_lens) { + for (ch, len) in rec.channels.iter_mut().zip(lens) { + if len == 0 { + continue; + } + if len == 1 { + return Err(PsdError::invalid("channel data length 1")); + } + ch.compression = Some(Compression::from_u16(r.u16()?)); + let data = r.sub(len - 2)?; + ch.stored = Some(Stored { source: data.src.clone(), offset: data.pos, len: data.remaining() }); + } + } + let body_len = r.pos - body_start; + let rest = r.rest()?; + let padding = if rest.len() as u64 == body_len % 2 && rest.iter().all(|&b| b == 0) { None } else { Some(rest) }; + Ok(LayerInfo { merged_alpha, layers, padding }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testgen; + + /// Every generated file, plus the layered 16/32-bit ones with their layers in a global block. + fn samples() -> Vec> { + let mut v = Vec::new(); + for case in testgen::all_cases() { + let mut file = case.file; + v.push(file.to_bytes().unwrap()); + let key = match file.header.depth { + 16 => *b"Lr16", + 32 => *b"Lr32", + _ => continue, + }; + if file.layer_info.as_ref().is_some_and(|i| !i.layers.is_empty()) { + file.global_layer_mask.get_or_insert_with(GlobalLayerMask::default); + file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key, padding: None }; + v.push(file.to_bytes().unwrap()); + } + } + v + } + + fn same(bytes: Vec) { + let eager = PsdFile::from_bytes(&bytes).unwrap(); + let lazy = PsdFile::from_source(Source::new(bytes.clone())).unwrap(); + assert_eq!(lazy, eager); + assert_eq!(lazy.to_bytes().unwrap(), bytes); + assert!(lazy.layers().iter().flat_map(|l| &l.channels).all(|c| c.data.is_empty())); + assert!(lazy.image_data.data.is_empty() && lazy.image_data.stored.is_some()); + } + + #[test] + fn lazy_parse_matches_the_eager_one() { + for bytes in samples() { + same(bytes); + } + } + + /// A PSD read lazily and written as PSB widens the RLE count tables of channels still in the + /// source, byte for byte as an eager read does (main's PSB promotion, #5285, on #6583's reader). + #[test] + fn a_lazy_psd_promotes_to_the_same_psb_as_an_eager_one() { + let bytes = testgen::layered(Version::Psd, crate::ColorMode::Rgb, 8, Compression::Rle).to_bytes().unwrap(); + let mut eager = PsdFile::from_bytes(&bytes).unwrap(); + let mut lazy = PsdFile::from_source(Source::new(bytes)).unwrap(); + eager.promote_to_psb().unwrap(); + lazy.promote_to_psb().unwrap(); + let written = eager.to_bytes().unwrap(); + assert_eq!(lazy.encoded_len().unwrap(), written.len() as u64); + assert!(lazy.to_bytes().unwrap() == written, "the lazily read PSD writes another PSB"); + } + + #[test] + fn lazy_parse_fails_where_the_eager_one_does() { + for bytes in samples() { + for cut in [1, 2, 7, 26, 40, bytes.len() / 3, bytes.len() / 2, bytes.len() - 3] { + let Some(b) = bytes.get(..cut) else { continue }; + let eager = PsdFile::from_bytes(b); + let lazy = PsdFile::from_source(Source::new(b.to_vec())); + // A truncated merged image is only noticed when it is read. + match eager { + Ok(eager) => assert_eq!(lazy.unwrap(), eager, "cut at {cut}"), + Err(e) => { + let records_ok = PsdFile::from_bytes_and_merged_recovering(b, |_| false, |_| true).is_ok(); + assert!(lazy.is_err() || records_ok, "cut at {cut}: eager {e:?}"); + } + } + } + } + } + + /// A source whose `fail_at`-th read fails once. + struct FailOnce { + bytes: Vec, + fail_at: usize, + reads: std::sync::atomic::AtomicUsize, + } + + impl crate::source::ReadAt for FailOnce { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + if self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == self.fail_at { + return Err(PsdError::Read("injected".into())); + } + self.bytes.read_at(offset, buf) + } + } + + #[test] + fn a_failed_read_fails_the_parse_instead_of_dropping_the_layers() { + for bytes in samples() { + let eager = PsdFile::from_bytes(&bytes).unwrap(); + let clean = std::sync::Arc::new(FailOnce { bytes: bytes.clone(), fail_at: usize::MAX, reads: 0.into() }); + PsdFile::from_source(Source::from_arc(clean.clone())).unwrap(); + let reads = clean.reads.load(std::sync::atomic::Ordering::SeqCst); + for fail_at in 0..reads { + let src = FailOnce { bytes: bytes.clone(), fail_at, reads: 0.into() }; + match PsdFile::from_source(Source::new(src)) { + Err(PsdError::Read(_)) => {} + Ok(lazy) => assert_eq!(lazy, eager, "read {fail_at} failed silently"), + Err(e) => panic!("read {fail_at}: {e:?}"), + } + } + } + } +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 5248456d52..f5ffbed8b7 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -61,13 +61,16 @@ pub mod header; pub mod image_data; mod io; pub mod layer; +mod lazy; pub mod metadata; pub mod path; pub mod patterns; pub mod pixels; pub mod resources; +pub mod rows; pub mod shc; pub mod slices; +pub mod source; pub mod tagged; #[cfg(any(test, feature = "testgen"))] // Test-data generator (tests and fuzz seeds only): failing loudly is the point. @@ -87,5 +90,9 @@ pub use image_data::ImageData; pub use layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask, LayerRecord, MaskData, MaskParameters, RealMask, Rect}; pub use pixels::{GrayImage, Layer, RgbaImage}; pub use resources::{ImageResource, ResolutionInfo, ResourceData}; +pub use rows::RowDecoder; +#[cfg(any(unix, windows))] +pub use source::FileSource; +pub use source::{ReadAt, Source, Stored}; pub use tagged::{BlockData, SectionDivider, SectionType, TaggedBlock}; pub use tree::LayerNode; diff --git a/crates/psd/src/rows.rs b/crates/psd/src/rows.rs new file mode 100644 index 0000000000..6413c801df --- /dev/null +++ b/crates/psd/src/rows.rs @@ -0,0 +1,234 @@ +//! Decoding a channel a band of rows at a time: [`ChannelData::row_decoder`]. +//! +//! [`ChannelData::decode`] returns the whole plane, so turning a layer into tiles holds every +//! channel's plane plus an interleaved copy at once: for a 20000×15000 RGBA layer that is 2.4 GB +//! on top of the tiles. A [`RowDecoder`] hands out any band of rows instead. RLE and raw channels +//! are read band by band (a channel still in its [`Stored`](crate::Stored) source reads only the +//! band's bytes: RLE's per-row byte counts give each row's offset); ZIP streams cannot be entered +//! part way, so a ZIP channel is inflated once, when the decoder is made. + +use std::borrow::Cow; + +use crate::compression::{Compression, MAX_DECODED_BYTES, PlaneLayout, decode_planes, packbits}; +use crate::error::{PsdError, Result}; +use crate::header::Version; +use crate::layer::ChannelData; +use crate::source::Stored; + +/// Where a channel's encoded bytes are. +enum Bytes<'a> { + Memory(&'a [u8]), + Source(&'a Stored), +} + +impl Bytes<'_> { + fn len(&self) -> u64 { + match self { + Bytes::Memory(b) => b.len() as u64, + Bytes::Source(s) => s.len, + } + } + + fn get(&self, at: u64, len: u64) -> Result> { + match self { + Bytes::Memory(b) => { + let range = usize::try_from(at).ok().zip(usize::try_from(len).ok()).and_then(|(a, n)| b.get(a..a.checked_add(n)?)); + range + .map(Cow::Borrowed) + .ok_or(PsdError::UnexpectedEof { offset: usize::try_from(at).unwrap_or(usize::MAX), needed: usize::try_from(len).unwrap_or(usize::MAX) }) + } + Bytes::Source(s) => { + if at.checked_add(len).is_none_or(|end| end > s.len) { + return Err(PsdError::UnexpectedEof { + offset: usize::try_from(at).unwrap_or(usize::MAX), + needed: usize::try_from(len).unwrap_or(usize::MAX), + }); + } + s.read_part(at, len).map(Cow::Owned) + } + } + } +} + +enum Kind<'a> { + /// Rows at `row * row_bytes`. + Raw(Bytes<'a>), + /// `offsets[r]..offsets[r + 1]` are row `r`'s PackBits bytes (offsets from the start of the + /// data, after the count table). + Rle { bytes: Bytes<'a>, offsets: Vec }, + /// The whole decoded plane. + Decoded(Vec), + /// No data and no rows. + Empty, +} + +/// Decodes bands of rows of one channel: see the [module docs](self). +pub struct RowDecoder<'a> { + kind: Kind<'a>, + row_bytes: usize, + height: usize, +} + +impl ChannelData { + /// A decoder of this channel's rows, for a `width × height` plane. Fails where + /// [`Self::decode`] would on everything it can check without decoding the rows (sizes, the + /// RLE count table, the whole of a ZIP stream); a damaged row fails when its band is decoded. + pub fn row_decoder(&self, width: usize, height: usize, depth: u16, version: Version) -> Result> { + let layout = PlaneLayout { planes: 1, width, height, depth, version }; + let total = layout.decoded_len()?; + let row_bytes = layout.row_bytes(); + let bytes = match &self.stored { + Some(s) => Bytes::Source(s), + None => Bytes::Memory(&self.data), + }; + let kind = match self.compression { + None if total == 0 => Kind::Empty, + None => return Err(PsdError::invalid("channel has no data")), + Some(Compression::Raw) => { + if bytes.len() < total as u64 { + return Err(PsdError::UnexpectedEof { offset: usize::try_from(bytes.len()).unwrap_or(usize::MAX), needed: total - bytes.len() as usize }); + } + Kind::Raw(bytes) + } + Some(Compression::Rle) => { + let size: u64 = if version.is_psb() { 4 } else { 2 }; + let table_len = (height as u64).saturating_mul(size); + if table_len > bytes.len() { + return Err(PsdError::UnexpectedEof { offset: 0, needed: usize::try_from(table_len - bytes.len()).unwrap_or(usize::MAX) }); + } + let table = bytes.get(0, table_len)?; + let mut offsets = Vec::new(); + offsets.try_reserve_exact(height + 1).map_err(|_| PsdError::LimitExceeded("not enough memory for the RLE row table"))?; + let mut at = table_len; + offsets.push(at); + for c in table.chunks_exact(size as usize) { + let n = match *c { + [a, b] => u64::from(u16::from_be_bytes([a, b])), + [a, b, c, d] => u64::from(u32::from_be_bytes([a, b, c, d])), + _ => 0, + }; + at = at.saturating_add(n); + offsets.push(at); + } + let data_len = bytes.len() - table_len; + // As `decode_planes` checks: PackBits expands at most 64x. + if (total as u64) > data_len.saturating_mul(64) { + return Err(PsdError::Decompress("RLE data too short for declared size".into())); + } + if at > bytes.len() { + return Err(PsdError::UnexpectedEof { + offset: usize::try_from(bytes.len()).unwrap_or(usize::MAX), + needed: usize::try_from(at - bytes.len()).unwrap_or(usize::MAX), + }); + } + Kind::Rle { bytes, offsets } + } + Some(c) => Kind::Decoded(decode_planes(c, &self.encoded()?, &layout)?), + }; + Ok(RowDecoder { kind, row_bytes, height }) + } +} + +impl RowDecoder<'_> { + /// Bytes per decoded row. + pub fn row_bytes(&self) -> usize { + self.row_bytes + } + + /// Number of rows. + pub fn height(&self) -> usize { + self.height + } + + /// Rows `r0..r1` as planar big-endian samples (`(r1 - r0) × row_bytes` bytes). + pub fn rows(&self, r0: usize, r1: usize) -> Result> { + if r0 > r1 || r1 > self.height { + return Err(PsdError::invalid(format!("rows {r0}..{r1} outside 0..{}", self.height))); + } + let n = (r1 - r0).checked_mul(self.row_bytes).ok_or(PsdError::LimitExceeded("band size overflow"))?; + if n as u64 > MAX_DECODED_BYTES { + return Err(PsdError::LimitExceeded("decoded channel data exceeds MAX_DECODED_BYTES")); + } + let mut out = Vec::new(); + out.try_reserve_exact(n).map_err(|_| PsdError::LimitExceeded("not enough memory for the decoded channel data"))?; + match &self.kind { + Kind::Empty => {} + Kind::Raw(bytes) => out.extend_from_slice(&bytes.get((r0 * self.row_bytes) as u64, n as u64)?), + Kind::Decoded(plane) => { + out.extend_from_slice(plane.get(r0 * self.row_bytes..r1 * self.row_bytes).ok_or_else(|| PsdError::invalid("decoded plane too short"))?) + } + Kind::Rle { bytes, offsets } => { + let (Some(&start), Some(&end)) = (offsets.get(r0), offsets.get(r1)) else { + return Err(PsdError::invalid("RLE row table too short")); + }; + let band = bytes.get(start, end - start)?; + for r in r0..r1 { + let (Some(&a), Some(&b)) = (offsets.get(r), offsets.get(r + 1)) else { + return Err(PsdError::invalid("RLE row table too short")); + }; + let row = band.get((a - start) as usize..(b - start) as usize).ok_or_else(|| PsdError::invalid("RLE row outside its band"))?; + packbits::decode_into(row, self.row_bytes, &mut out)?; + } + } + } + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use crate::source::Source; + use crate::{PsdFile, testgen}; + + /// Every channel of every generated file, decoded in uneven bands from memory and from a + /// source, is its whole-plane decode. + #[test] + fn bands_join_up_to_the_whole_plane() { + let mut checked = 0; + for case in testgen::all_cases() { + let bytes = case.file.to_bytes().unwrap(); + let eager = PsdFile::from_bytes(&bytes).unwrap(); + let lazy = PsdFile::from_source(Source::new(bytes)).unwrap(); + let (d, v) = (eager.header.depth, eager.header.version); + for file in [&eager, &lazy] { + for rec in file.layers() { + for ch in &rec.channels { + let (w, h) = rec.channel_rect(ch.id).size().unwrap(); + let whole = ch.decode(w, h, d, v); + let dec = ch.row_decoder(w, h, d, v); + let (Ok(whole), Ok(dec)) = (whole, dec) else { continue }; + let mut joined = Vec::new(); + let mut r = 0; + for step in [1, 3, 2, 7].iter().cycle() { + if r >= h { + break; + } + let r1 = (r + step).min(h); + joined.extend(dec.rows(r, r1).unwrap()); + r = r1; + } + assert_eq!(joined, whole, "{}", case.name); + assert!(dec.rows(0, h + 1).is_err()); + checked += 1; + } + } + } + } + assert!(checked > 100, "{checked}"); + } + + #[test] + fn a_damaged_rle_row_fails_its_band() { + use crate::Compression; + use crate::layer::ChannelData; + // Two rows of 4 bytes: a valid row, then one that ends early. + let mut data = vec![0, 2, 0, 2]; + data.extend([0xFD, 7]); // header -3: 1 - (-3) = 4 copies of 7 + data.extend([0x01, 9]); // a literal of 2 bytes, only 1 present + let ch = ChannelData::new(0, Some(Compression::Rle), data); + let dec = ch.row_decoder(4, 2, 8, crate::Version::Psd).unwrap(); + assert_eq!(dec.rows(0, 1).unwrap(), vec![7; 4]); + assert!(dec.rows(1, 2).is_err()); + assert!(ch.decode(4, 2, 8, crate::Version::Psd).is_err()); + } +} diff --git a/crates/psd/src/source.rs b/crates/psd/src/source.rs new file mode 100644 index 0000000000..2e7c8039dd --- /dev/null +++ b/crates/psd/src/source.rs @@ -0,0 +1,270 @@ +//! Random-access byte sources, for parsing a file without reading all of it. +//! +//! [`PsdFile::from_source`](crate::PsdFile::from_source) reads the structure of a file (header, +//! resources, layer records, tagged blocks) and leaves the bulk of it, the encoded channel data +//! and the merged image, where it is: each [`ChannelData`](crate::ChannelData) records a +//! [`Stored`] range instead of a copy, and the bytes are read when the channel is decoded. A +//! 2 GB layered file then never needs 2 GB of memory just to be opened. + +use std::borrow::Cow; +use std::fmt; +use std::sync::Arc; + +use crate::error::{PsdError, Result}; + +/// Bytes that can be read at any offset, from any thread. +/// +/// Implemented for byte buffers and, on native targets, for [`std::fs::File`] (as +/// [`FileSource`]). The source must not change while a file parsed from it is in use: a +/// [`Stored`] range is an offset into it. +pub trait ReadAt: Send + Sync { + /// Total length in bytes. + fn len(&self) -> u64; + + /// `true` when the source holds no bytes. + fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Fills `buf` with the bytes at `offset..offset + buf.len()`. Fails, without a partial + /// result, when the range is not all inside the source or the read fails. + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()>; +} + +fn out_of_range(offset: u64, needed: usize, len: u64) -> PsdError { + PsdError::UnexpectedEof { + offset: usize::try_from(offset).unwrap_or(usize::MAX), + needed: needed.saturating_sub(usize::try_from(len.saturating_sub(offset)).unwrap_or(usize::MAX)), + } +} + +impl ReadAt for [u8] { + fn len(&self) -> u64 { + <[u8]>::len(self) as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + let src = usize::try_from(offset) + .ok() + .and_then(|start| self.get(start..start.checked_add(buf.len())?)) + .ok_or_else(|| out_of_range(offset, buf.len(), ReadAt::len(self)))?; + buf.copy_from_slice(src); + Ok(()) + } +} + +impl ReadAt for Vec { + fn len(&self) -> u64 { + self.as_slice().len() as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + self.as_slice().read_at(offset, buf) + } +} + +impl ReadAt for Arc { + fn len(&self) -> u64 { + (**self).len() + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + (**self).read_at(offset, buf) + } +} + +/// Largest single read from a [`FileSource`]. +#[cfg(any(unix, windows))] +const MAX_READ: usize = 64 << 20; + +/// An open file read at offsets (`pread` on Unix, `seek_read` on Windows), with its length taken +/// when it was opened. Reads from several threads at once need no lock. +#[cfg(any(unix, windows))] +#[derive(Debug)] +pub struct FileSource { + file: std::fs::File, + len: u64, +} + +#[cfg(any(unix, windows))] +impl FileSource { + /// Opens `path` for reading. + pub fn open(path: &std::path::Path) -> std::io::Result { + Self::new(std::fs::File::open(path)?) + } + + /// Wraps an open file. + pub fn new(file: std::fs::File) -> std::io::Result { + let len = file.metadata()?.len(); + Ok(FileSource { file, len }) + } + + /// The file. + pub fn file(&self) -> &std::fs::File { + &self.file + } +} + +#[cfg(any(unix, windows))] +impl ReadAt for FileSource { + fn len(&self) -> u64 { + self.len + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) { + return Err(out_of_range(offset, buf.len(), self.len)); + } + let n = buf.len(); + let failed = |e: std::io::Error| PsdError::Read(format!("reading {n} bytes at offset {offset}: {e}")); + // Bounded reads, as `photocraft-format`'s `read_file` makes them: some Windows file + // systems reject a single read of gigabytes (#375). + let mut done = 0usize; + while done < n { + let Some(rest) = buf.get_mut(done..n.min(done + MAX_READ)) else { break }; + let at = offset + done as u64; + #[cfg(unix)] + let read = { + use std::os::unix::fs::FileExt; + self.file.read_at(rest, at) + }; + #[cfg(windows)] + let read = { + use std::os::windows::fs::FileExt; + self.file.seek_read(rest, at) + }; + match read { + Ok(0) => return Err(failed(std::io::ErrorKind::UnexpectedEof.into())), + Ok(k) => done += k, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(failed(e)), + } + } + Ok(()) + } +} + +/// A shared [`ReadAt`]: what [`Stored`] ranges point into. Two handles are equal when they are +/// the same source. +#[derive(Clone)] +pub struct Source(Arc); + +impl Source { + /// Shares `source`. + pub fn new(source: impl ReadAt + 'static) -> Self { + Source(Arc::new(source)) + } + + /// Shares an already shared source. + pub fn from_arc(source: Arc) -> Self { + Source(source) + } + + /// The source. + pub fn get(&self) -> &dyn ReadAt { + &*self.0 + } + + /// Reads `len` bytes at `offset` into a new buffer. The buffer is reserved fallibly: a + /// range larger than memory is an error, not an abort. + pub fn read_vec(&self, offset: u64, len: u64) -> Result> { + let n = usize::try_from(len).map_err(|_| PsdError::LimitExceeded("length exceeds address space"))?; + if offset.checked_add(len).is_none_or(|end| end > self.0.len()) { + return Err(out_of_range(offset, n, self.0.len())); + } + let mut out = Vec::new(); + out.try_reserve_exact(n).map_err(|_| PsdError::LimitExceeded("not enough memory to read the data"))?; + out.resize(n, 0); + self.0.read_at(offset, &mut out)?; + Ok(out) + } +} + +impl fmt::Debug for Source { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Source({} bytes)", self.0.len()) + } +} + +impl PartialEq for Source { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for Source {} + +/// Encoded bytes left in their [`Source`] by a lazy parse: `len` bytes at `offset`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Stored { + /// Where the bytes are. + pub source: Source, + /// Offset of the first byte. + pub offset: u64, + /// Number of bytes. + pub len: u64, +} + +impl Stored { + /// Reads the bytes. + pub fn read(&self) -> Result> { + self.source.read_vec(self.offset, self.len) + } + + /// Reads `len` bytes starting `at` bytes into the range. + pub fn read_part(&self, at: u64, len: u64) -> Result> { + if at.checked_add(len).is_none_or(|end| end > self.len) { + return Err(PsdError::invalid("read past the end of stored data")); + } + self.source.read_vec(self.offset + at, len) + } +} + +/// The bytes of a value that is either in memory (`data`) or still in its source (`stored`). +pub(crate) fn encoded<'a>(data: &'a [u8], stored: Option<&Stored>) -> Result> { + match stored { + Some(s) => s.read().map(Cow::Owned), + None => Ok(Cow::Borrowed(data)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slice_reads_are_bounds_checked() { + let v = vec![1u8, 2, 3, 4]; + let mut b = [0u8; 2]; + v.read_at(2, &mut b).unwrap(); + assert_eq!(b, [3, 4]); + assert!(v.read_at(3, &mut b).is_err()); + assert!(v.read_at(u64::MAX, &mut b).is_err()); + let s = Source::new(v); + assert_eq!(s.read_vec(1, 2).unwrap(), vec![2, 3]); + assert!(s.read_vec(1, u64::MAX).is_err()); + let st = Stored { source: s.clone(), offset: 1, len: 3 }; + assert_eq!(st.read().unwrap(), vec![2, 3, 4]); + assert_eq!(st.read_part(1, 2).unwrap(), vec![3, 4]); + assert!(st.read_part(2, 2).is_err()); + assert_eq!(st.source, s); + assert_ne!(st.source, Source::new(vec![1u8, 2, 3, 4])); + } + + #[cfg(any(unix, windows))] + #[test] + fn file_source_reads_at_offsets() { + use std::io::Write; + let dir = std::env::temp_dir().join(format!("photocraft-psd-source-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("f.bin"); + std::fs::File::create(&path).unwrap().write_all(&[9, 8, 7, 6, 5]).unwrap(); + let f = FileSource::open(&path).unwrap(); + assert_eq!(ReadAt::len(&f), 5); + let mut b = [0u8; 3]; + f.read_at(2, &mut b).unwrap(); + assert_eq!(b, [7, 6, 5]); + assert!(f.read_at(3, &mut b).is_err()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 098b720a22..6fce19bbe9 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -168,7 +168,7 @@ impl TaggedBlock { String::from_utf8_lossy(&self.key).into_owned() } - fn default_padding(len: usize, alignment: usize) -> usize { + pub(crate) fn default_padding(len: usize, alignment: usize) -> usize { (alignment - len % alignment) % alignment } @@ -449,7 +449,7 @@ fn parse_section(d: &[u8]) -> Result { /// `8BIM` / `8B64`, or the markers `MIB8` / `46B8` that [`crate::tiff`] gives a block kept /// verbatim from a little-endian TIFF when its layout is unknown (its data is in that order). -fn is_sig(b: &[u8]) -> bool { +pub(crate) fn is_sig(b: &[u8]) -> bool { b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b) } diff --git a/crates/psd/src/testgen.rs b/crates/psd/src/testgen.rs index 818c33bae0..4898984445 100644 --- a/crates/psd/src/testgen.rs +++ b/crates/psd/src/testgen.rs @@ -113,7 +113,7 @@ pub fn merged_only(version: Version, mode: ColorMode, depth: u16, compression: C for c in 0..channels { planes.extend(pattern_plane(w as usize, h as usize, depth, u32::from(c))); } - let image_data = ImageData::encode(compression, &planes, &header).unwrap_or(ImageData { compression, data: Vec::new() }); + let image_data = ImageData::encode(compression, &planes, &header).unwrap_or(ImageData::new(compression, Vec::new())); PsdFile { header, color_mode_data: color_mode_data(mode), @@ -180,7 +180,7 @@ fn raster_layer(g: LayerGen<'_>) -> LayerRecord { fn group_record(header: &Header, name: &str, kind: SectionType, blend: BlendMode, id: u32) -> LayerRecord { let cc = mode_channels(header.color_mode) as i16; - let channels = (-1..cc).map(|c| ChannelData { id: c, compression: Some(Compression::Raw), data: Vec::new() }).collect(); + let channels = (-1..cc).map(|c| ChannelData::new(c, Some(Compression::Raw), Vec::new())).collect(); let lsct = if kind == SectionType::BoundingDivider { TaggedBlock::section_divider(kind, None, None) } else { diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 4aa50c5a60..af3c6d48e2 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -35,6 +35,24 @@ impl fmt::Display for AllocationError { impl std::error::Error for AllocationError {} +/// One shared tile per pixel value (and tile size), for [`Surface::share_uniform_tiles`]. +#[derive(Debug, Default)] +pub struct TileInterner { + tiles: std::collections::HashMap, Arc>>, +} + +impl TileInterner { + /// Number of distinct uniform tiles held. + pub fn len(&self) -> usize { + self.tiles.values().map(|m| m.len()).sum() + } + + /// `true` when no tile is held. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + /// Pixel storage for one tile: `TILE_SIZE² × bytes_per_pixel`, row-major, interleaved channels. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Tile { @@ -465,6 +483,28 @@ impl Surface { out } + /// Makes every tile that holds one pixel value throughout share the interner's tile for that + /// value: a white background, an opaque mask or a solid fill then costs one tile however + /// large it is, and across every surface that shares `interner`. Tiles are copy-on-write, so + /// editing one splits it off again. Returns the bytes no longer held by this surface alone. + pub fn share_uniform_tiles(&mut self, interner: &mut TileInterner) -> usize { + let bpp = self.format.bytes_per_pixel(); + let mut saved = 0; + for t in self.tiles.values_mut() { + let mut px = t.data.chunks_exact(bpp); + let Some(p0) = px.next() else { continue }; + if !px.all(|p| p == p0) { + continue; + } + let shared = interner.tiles.entry(t.data.len()).or_default().entry(p0.to_vec()).or_insert_with(|| t.clone()); + if !Arc::ptr_eq(shared, t) { + saved += t.data.len(); + *t = shared.clone(); + } + } + saved + } + /// Drop tiles that are entirely the default pixel. pub fn prune(&mut self) { let dp = self.default_pixel.as_ref(); diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index 1e8cf30ec7..47e78008fd 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -59,6 +59,38 @@ fn distinct_tiles(s: &Surface) -> usize { seen.len() } +/// Uniform tiles written pixel by pixel end up as one shared tile per value, across +/// surfaces, with every pixel unchanged; editing one splits it off. +#[test] +fn uniform_tiles_are_shared() { + let mut interner = TileInterner::default(); + let r = Rect::new(0, 0, 1024, 600); + let mut bytes = Vec::new(); + for y in 0..600 { + for x in 0..1024 { + // White, except a gradient in the tiles of column 3. + bytes.extend(if x >= 768 { [x as u8, y as u8, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let mut a = Surface::from_interleaved(PixelFormat::RGBA8, r, &bytes); + let mut b = Surface::from_interleaved(PixelFormat::RGBA8, r, &bytes); + let before = a.to_interleaved(r); + assert_eq!(distinct_tiles(&a), 12); + // Rows 512..600 cover only part of their tiles: the rest is the default pixel, so those + // tiles are not uniform. + let saved = a.share_uniform_tiles(&mut interner); + assert_eq!(distinct_tiles(&a), 1 + 3 + 3); + assert_eq!(saved, 5 * TILE_SIZE as usize * TILE_SIZE as usize * 4); + b.share_uniform_tiles(&mut interner); + assert_eq!(interner.len(), 1); + assert!(Arc::ptr_eq(a.tile(TileCoord { tx: 0, ty: 0 }).unwrap(), b.tile(TileCoord { tx: 2, ty: 1 }).unwrap())); + assert_eq!(a.to_interleaved(r), before); + a.write_pixel(5, 5, &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(b.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]); + assert_eq!(a.pixel(5, 5), vec![0.0, 0.0, 0.0, 1.0]); + assert_eq!(a.pixel(300, 5), vec![1.0, 1.0, 1.0, 1.0]); +} + /// Converting or tone-mapping a surface keeps a shared tile shared (#4531) and gives the /// same pixels as converting each pixel: a filled background is one tile across the grid, /// plus some distinct tiles. diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index fa703b2bb4..6303931811 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -101,6 +101,11 @@ impl Padded { Padded { data: vec![0.0; stride * (h + 2 * PAD)], w, h, stride } } + /// Whether the plane is non-empty and holds all its rows. + fn fits(&self) -> bool { + self.w != 0 && self.h != 0 && self.data.len() >= self.stride * (self.h + 2 * PAD) + } + /// From an unpadded plane (tests and small inputs). #[cfg(test)] pub fn from_plane(plane: &[f32], w: usize, h: usize) -> Self { @@ -190,51 +195,174 @@ fn kernels(phase: [u8; 4], method: Demosaic, stride: usize) -> [[Vec<(isize, f32 pub(crate) fn demosaic(p: &Padded, phase: [u8; 4], method: Demosaic, to_xyz: &Mat3, ahd_jobs: usize) -> Vec { let (w, h, s) = (p.w, p.h, p.stride); let mut out = vec![0.0f32; w * h * 3]; - if w == 0 || h == 0 || p.data.len() < s * (h + 2 * PAD) { + if !p.fits() { return out; } if method == Demosaic::Ahd { - ahd(p, phase, to_xyz, &mut out, ahd_jobs); + let (d, m, labf) = (&p.data, ahd_matrix(to_xyz), LabF::new()); + for_bands_grouped( + &mut out, + AHD_BAND * w * 3, + ahd_bands(h), + ahd_jobs, + 1, + || AhdScratch::for_image(h, s), + |band, chunk, sc| { + ahd_band(d, w, s, phase, &m, &labf, band, chunk, sc); + }, + ); return out; } let ks = kernels(phase, method, s); let rows = par::band_rows(w); - let d = &p.data; - par::chunks_mut(&mut out, rows * w * 3, |band, chunk| { - let y0 = band * rows; - for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { - let y = y0 + r; - let base = (y + PAD) * s + PAD; - for (x, o) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { - let pos = (y & 1) * 2 + (x & 1); - let i = base + x; - if method == Demosaic::Bilinear { - // Direct Bayer bilinear (the kernels' result without the tap loops). - let own = usize::from(phase[pos]).min(2); - let (n, so, e, wv) = (d[i - s], d[i + s], d[i + 1], d[i - 1]); - if own == 1 { - let hc = usize::from(phase[(y & 1) * 2 + ((x + 1) & 1)]).min(2); - o[1] = d[i]; - o[hc] = (e + wv) * 0.5; - o[2 - hc] = (n + so) * 0.5; - } else { - o[own] = d[i]; - o[1] = (n + so + e + wv) * 0.25; - o[2 - own] = (d[i - s - 1] + d[i - s + 1] + d[i + s - 1] + d[i + s + 1]) * 0.25; - } - continue; - } - for (c, k) in ks[pos].iter().enumerate() { - let mut v = 0.0f32; - for &(off, wt) in k { - v += wt * d[(i as isize + off) as usize]; - } - o[c] = v.clamp(0.0, 1.0); - } + par::chunks_mut(&mut out, rows * w * 3, |band, chunk| linear_band(&p.data, w, s, phase, method, &ks, band * rows, 0, chunk)); + out +} + +/// [`demosaic`] without the full RGB frame and without the padded plane: every band loads the +/// rows it reads (`fill(y, row)` writes the normalized CFA row `y` of the image, `w` samples; +/// the mirrored borders are added here), demosaics into a band buffer, and `emit(rgb, out)` +/// turns it into the band's `out` samples (the same rows, `w * 3` per row). Each pixel depends +/// only on the plane around it, never on how rows are split or ordered, so the result is that +/// of `emit` over [`demosaic`] of the filled plane. +#[allow(clippy::too_many_arguments)] +pub(crate) fn demosaic_fused( + w: usize, + h: usize, + phase: [u8; 4], + method: Demosaic, + to_xyz: &Mat3, + jobs: usize, + fill: &(impl Fn(usize, &mut [f32]) + Sync), + out: &mut [u16], + emit: &(impl Fn(&[f32], &mut [u16]) + Sync), +) { + if w == 0 || h == 0 || out.len() < w * h * 3 { + return; + } + let s = w + 2 * PAD; + let out = &mut out[..w * h * 3]; + // Padded rows of the output rows `y0..y0 + rows` (`rows + 2 * PAD` of them, row `PAD` is `y0`) + // with the mirror reflection `Padded::fill_borders` applies. + let load = |win: &mut [f32], y0: usize, rows: usize| { + for (j, prow) in win.chunks_exact_mut(s).take(rows + 2 * PAD).enumerate() { + fill(reflect((y0 + j) as isize - PAD as isize, h), &mut prow[PAD..PAD + w]); + for px in (0..PAD).chain(PAD + w..s) { + prow[px] = prow[PAD + reflect(px as isize - PAD as isize, w)]; } } + }; + if method == Demosaic::Ahd { + let (m, labf) = (ahd_matrix(to_xyz), LabF::new()); + // The rows of the tallest band, as `develop`'s memory check counts them. + let rows = h.min(AHD_BAND); + let init = || (AhdScratch::for_image(h, s), vec![0.0f32; rows * w * 3], vec![0.0f32; (rows + 2 * PAD) * s]); + for_bands_grouped(out, AHD_BAND * w * 3, ahd_bands(h), jobs, 1, init, |band, chunk, (sc, buf, win)| { + load(win, band * AHD_BAND, chunk.len() / (w * 3)); + let buf = &mut buf[..chunk.len()]; + // The window starts at a multiple of AHD_BAND (even), so it is band 0 of its own rows. + ahd_band(win, w, s, phase, &m, &labf, 0, buf, sc); + emit(buf, chunk); + }); + return; + } + let ks = kernels(phase, method, s); + let rows = h.min(FUSED_ROWS); + let init = || (vec![0.0f32; rows * w * 3], vec![0.0f32; (rows + 2 * PAD) * s]); + for_bands(out, FUSED_ROWS * w * 3, h.div_ceil(FUSED_ROWS), jobs, init, |band, chunk, (buf, win)| { + load(win, band * FUSED_ROWS, chunk.len() / (w * 3)); + let buf = &mut buf[..chunk.len()]; + linear_band(win, w, s, phase, method, &ks, band * FUSED_ROWS, band * FUSED_ROWS, buf); + emit(buf, chunk); + }); +} + +/// Output rows per band of the fused bilinear / MHC path (the window adds `2 * PAD` rows). +pub(crate) const FUSED_ROWS: usize = 32; + +/// Rows `y0..` of bilinear or MHC output (`chunk.len() / (w * 3)` of them); `d` is the padded +/// plane from image row `dy` on (`dy` 0: all of it). +#[allow(clippy::too_many_arguments)] +fn linear_band(d: &[f32], w: usize, s: usize, phase: [u8; 4], method: Demosaic, ks: &[[Vec<(isize, f32)>; 3]; 4], y0: usize, dy: usize, chunk: &mut [f32]) { + for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { + let y = y0 + r; + let base = (y - dy + PAD) * s + PAD; + for (x, o) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { + let pos = (y & 1) * 2 + (x & 1); + let i = base + x; + if method == Demosaic::Bilinear { + // Direct Bayer bilinear (the kernels' result without the tap loops). + let own = usize::from(phase[pos]).min(2); + let (n, so, e, wv) = (d[i - s], d[i + s], d[i + 1], d[i - 1]); + if own == 1 { + let hc = usize::from(phase[(y & 1) * 2 + ((x + 1) & 1)]).min(2); + o[1] = d[i]; + o[hc] = (e + wv) * 0.5; + o[2 - hc] = (n + so) * 0.5; + } else { + o[own] = d[i]; + o[1] = (n + so + e + wv) * 0.25; + o[2 - own] = (d[i - s - 1] + d[i - s + 1] + d[i + s - 1] + d[i + s + 1]) * 0.25; + } + continue; + } + for (c, k) in ks[pos].iter().enumerate() { + let mut v = 0.0f32; + for &(off, wt) in k { + v += wt * d[(i as isize + off) as usize]; + } + o[c] = v.clamp(0.0, 1.0); + } + } + } +} + +/// Runs `f(band, chunk, scratch)` over the `unit`-sized chunks of `out` (`bands` of them), with +/// at most `jobs` scratch values alive. When every worker may hold one, each band is its own +/// rayon task and borrows a scratch from a pool (one per worker at most); otherwise a few groups +/// of consecutive bands per job run, `jobs` at a time, each building its scratch once. +pub(crate) fn for_bands( + out: &mut [T], + unit: usize, + bands: usize, + jobs: usize, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(usize, &mut [T], &mut S) + Sync + Send, +) { + for_bands_grouped(out, unit, bands, jobs, 4, init, f); +} + +/// Bands per group when `bands` are split into `per_worker` groups for each worker (at most `jobs`). +fn bands_per_group(bands: usize, jobs: usize, per_worker: usize) -> usize { + let groups = (par::workers().min(jobs.max(1)) * per_worker).clamp(1, bands.max(1)); + bands.div_ceil(groups).max(1) +} + +/// [`for_bands`] with `per_worker` groups of consecutive bands for each of the `jobs` workers when +/// fewer than all may hold a scratch. A large scratch (AHD: 16 planes) wants one group per job: +/// with more groups each would build and zero its own scratch for a band or two. +fn for_bands_grouped( + out: &mut [T], + unit: usize, + bands: usize, + jobs: usize, + per_worker: usize, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(usize, &mut [T], &mut S) + Sync + Send, +) { + // One task per band keeps rayon's stealing, so a busy or slow worker doesn't hold up a + // static share of the bands (as `par::chunks_mut_limited` does for the same reason). + if jobs >= par::workers() { + par::chunks_mut_pooled(out, unit, init, |sc, band, chunk| f(band, chunk, sc)); + return; + } + let per_group = bands_per_group(bands, jobs, per_worker); + par::chunks_mut_limited(out, per_group * unit, jobs, |group, gchunk| { + let mut sc = init(); + for (j, chunk) in gchunk.chunks_mut(unit).enumerate() { + f(group * per_group + j, chunk, &mut sc); + } }); - out } /// A CFA repeat as seen from the plane's origin: colour of plane pixel @@ -318,10 +446,36 @@ fn phase_taps(pat: &Pattern, px: isize, py: isize) -> Taps { /// without the edge-directed weights it is no faster and leaves zipper /// artefacts along every edge of an X-Trans image. pub(crate) fn demosaic_cfa(p: &Padded, pat: &Pattern) -> Vec { - let (w, h, s) = (p.w, p.h, p.stride); + let (w, h) = (p.w, p.h); let mut out = vec![0.0f32; w * h * 3]; - if w == 0 || h == 0 || pat.w == 0 || pat.h == 0 || pat.colors.len() < pat.w * pat.h || p.data.len() < s * (h + 2 * PAD) { - return out; + let band = par::band_rows(w); + cfa_with(p, pat, |rows| par::chunks_mut(&mut out, band * w * 3, |b, chunk| rows(b * band, chunk))); + out +} + +/// [`demosaic_cfa`] without the full RGB frame (the green plane stays): see [`demosaic_fused`]. +pub(crate) fn demosaic_cfa_fused(p: &Padded, pat: &Pattern, jobs: usize, out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync)) { + let (w, h) = (p.w, p.h); + if out.len() < w * h * 3 { + return; + } + let band = par::band_rows(w); + let init = || vec![0.0f32; band.min(h) * w * 3]; + cfa_with(p, pat, |rows| { + for_bands(&mut out[..w * h * 3], band * w * 3, h.div_ceil(band), jobs, init, |b, chunk, buf| { + let buf = &mut buf[..chunk.len()]; + rows(b * band, buf); + emit(buf, chunk); + }); + }); +} + +/// The generic demosaic's green plane, then `run` with a function that fills the RGB rows +/// `y0..` of a chunk (`chunk.len() / (w * 3)` of them). Not called for an unusable plane or pattern. +fn cfa_with(p: &Padded, pat: &Pattern, run: impl FnOnce(&(dyn Fn(usize, &mut [f32]) + Sync))) { + let (w, h, s) = (p.w, p.h, p.stride); + if !p.fits() || pat.w == 0 || pat.h == 0 || pat.colors.len() < pat.w * pat.h { + return; } let taps: Vec = (0..pat.w * pat.h).map(|i| phase_taps(pat, (i % pat.w) as isize, (i / pat.w) as isize)).collect(); let tap_at = |x: usize, y: usize| &taps[(y % pat.h) * pat.w + x % pat.w]; @@ -389,9 +543,9 @@ pub(crate) fn demosaic_cfa(p: &Padded, pat: &Pattern) -> Vec { // 2. Red and blue from colour differences. let gref = &green; let gat = |x: usize, y: usize, o: Off| get(gref, w, 0, x, y, o); - par::chunks_mut(&mut out, band * w * 3, |b, chunk| { + run(&|y0: usize, chunk: &mut [f32]| { for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { - let y = b * band + r; + let y = y0 + r; for (x, o) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { let t = tap_at(x, y); let g = gref.get(y * w + x).copied().unwrap_or(0.0); @@ -418,7 +572,6 @@ pub(crate) fn demosaic_cfa(p: &Padded, pat: &Pattern) -> Vec { } } }); - out } /// Regularizes the inverse-gradient weights (normalized units, about 1/256 of full scale). @@ -426,9 +579,10 @@ const GRAD_EPS: f32 = 1.0 / 256.0; /// Regularizes the green-similarity weights of the colour differences. const DIFF_EPS: f32 = 1.0 / 64.0; -/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. +/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. Each entry holds the +/// sample and the step to the next one (one load per lookup; the same `a + (b - a) * f`). struct LabF { - table: Vec, + pairs: Vec<[f32; 2]>, } const LABF_STEPS: usize = 1 << 14; @@ -436,7 +590,8 @@ const LABF_RANGE: f32 = 2.0; impl LabF { fn new() -> Self { - LabF { table: (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect() } + let table: Vec = (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect(); + LabF { pairs: table.windows(2).map(|p| [p[0], p[1] - p[0]]).collect() } } fn exact(t: f32) -> f32 { @@ -450,27 +605,36 @@ impl LabF { } let x = t * (LABF_STEPS as f32 / LABF_RANGE); let i = (x as usize).min(LABF_STEPS); - let a = self.table[i]; - a + (self.table[i + 1] - a) * (x - i as f32) + let [a, step] = self.pairs[i]; + a + step * (x - i as f32) } } /// Output rows per AHD band. -const AHD_BAND: usize = 32; +pub(crate) const AHD_BAND: usize = 32; /// Extra band rows above and below the output rows. const M: usize = 3; -/// Maximum scratch allocation of one AHD band: two green, RGB and Lab float -/// planes and two byte homogeneity planes, including their border rows. +/// Scratch rows one AHD worker allocates: the output rows of the tallest band +/// this image has, plus their border rows. +fn ahd_scratch_rows(h: usize) -> usize { + h.min(AHD_BAND) + 2 * M +} + +/// Scratch allocation of one AHD worker ([`AhdScratch::for_image`]): two green, +/// RGB and Lab float planes and two byte homogeneity planes over +/// [`ahd_scratch_rows`], plus the two `u32` rows of vertical sums. pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 { - w.saturating_add(2 * PAD as u64).saturating_mul(h.min(AHD_BAND as u64).saturating_add(2 * M as u64)).saturating_mul(58) + let s = w.saturating_add(2 * PAD as u64); + let rows = h.min(AHD_BAND as u64).saturating_add(2 * M as u64); + s.saturating_mul(rows.saturating_mul(58).saturating_add(8)) } pub(crate) fn ahd_bands(h: usize) -> usize { h.div_ceil(AHD_BAND) } -pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 2) * 4; +pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 1) * 8; /// `v` limited to `lo..=hi` like `f32::clamp`, without its panic on NaN bounds (hostile black /// levels can put NaN in the plane): same result for every non-NaN bound. @@ -480,7 +644,198 @@ fn clampf(v: f32, lo: f32, hi: f32) -> f32 { if v > hi { hi } else { v } } -fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) { +/// One AHD band's working planes, reused for every band a worker runs (sized for the tallest band). +struct AhdScratch { + /// Green interpolated horizontally (0) and vertically (1). + g: [Vec; 2], + /// Per direction, the RGB candidate (planar). + rgb: [[Vec; 3]; 2], + /// Per direction, its CIELAB (planar). + lab: [[Vec; 3]; 2], + hom: [Vec; 2], + /// Vertical 3-row sums of `hom`, one output row. + vs: [Vec; 2], +} + +impl AhdScratch { + fn new(len: usize, s: usize) -> Self { + let f = || vec![0.0f32; len]; + AhdScratch { + g: [f(), f()], + rgb: [[f(), f(), f()], [f(), f(), f()]], + lab: [[f(), f(), f()], [f(), f(), f()]], + hom: [vec![0u8; len], vec![0u8; len]], + vs: [vec![0u32; s], vec![0u32; s]], + } + } + + /// The scratch for an image `h` rows tall with stride `s`: the size [`ahd_scratch`] budgets. + fn for_image(h: usize, s: usize) -> Self { + AhdScratch::new(ahd_scratch_rows(h) * s, s) + } +} + +/// The camera → XYZ matrix with the rows divided by the white point. +fn ahd_matrix(to_xyz: &Mat3) -> [[f32; 3]; 3] { + let white = [0.9642f32, 1.0, 0.8249]; + std::array::from_fn(|i| std::array::from_fn(|j| to_xyz[i][j] as f32 / white[i])) +} + +/// One AHD band (see [`ahd_ref`] for the plain statement): the same arithmetic in the same +/// order, per row on slices, planar scratch reused across a worker's bands. Every scratch cell +/// a stage reads was written earlier in the same band, so the planes are never cleared between +/// bands. +#[allow(clippy::too_many_arguments)] +fn ahd_band(d: &[f32], w: usize, s: usize, phase: [u8; 4], m: &[[f32; 3]; 3], labf: &LabF, band: usize, chunk: &mut [f32], sc: &mut AhdScratch) { + let rows = chunk.len() / (w * 3); + let n = rows + 2 * M; + let py = |b: usize| band * AHD_BAND + PAD - M + b; + let drow = |y: usize| &d[y * s..(y + 1) * s]; + // 1. Green interpolated horizontally (0) and vertically (1), columns 2..s-2. + { + let [g0, g1] = &mut sc.g; + for b in 0..n { + let y = py(b); + let (rm2, rm1, r0, rp1, rp2) = (drow(y - 2), drow(y - 1), drow(y), drow(y + 1), drow(y + 2)); + let gh_row = &mut g0[b * s..(b + 1) * s]; + let gv_row = &mut g1[b * s..(b + 1) * s]; + let green = [phase[(y & 1) * 2] == 1, phase[(y & 1) * 2 + 1] == 1]; + for x in 2..s - 2 { + let c = r0[x]; + if green[x & 1] { + gh_row[x] = c; + gv_row[x] = c; + continue; + } + let (l, r) = (r0[x - 1], r0[x + 1]); + let gh = (l + r) * 0.5 + (2.0 * c - r0[x - 2] - r0[x + 2]) * 0.25; + gh_row[x] = clampf(gh, l.min(r), l.max(r)); + let (u, dn) = (rm1[x], rp1[x]); + let gv = (u + dn) * 0.5 + (2.0 * c - rm2[x] - rp2[x]) * 0.25; + gv_row[x] = clampf(gv, u.min(dn), u.max(dn)); + } + } + } + // 2. RGB candidates and their Lab, band rows 1..n-1, columns 3..s-3. + for dir in 0..2 { + let gd = &sc.g[dir]; + let [cr, cg, cb] = &mut sc.rgb[dir]; + let [ll, la, lb] = &mut sc.lab[dir]; + for b in 1..n - 1 { + let y = py(b); + let (dm1, d0, dp1) = (drow(y - 1), drow(y), drow(y + 1)); + let (gm1, g0, gp1) = (&gd[(b - 1) * s..b * s], &gd[b * s..(b + 1) * s], &gd[(b + 1) * s..(b + 2) * s]); + let at = b * s; + let (orr, org, orb) = (&mut cr[at..at + s], &mut cg[at..at + s], &mut cb[at..at + s]); + let (ol, oa, ob) = (&mut ll[at..at + s], &mut la[at..at + s], &mut lb[at..at + s]); + let pr = (y & 1) * 2; + for x in 3..s - 3 { + let own = phase[pr + (x & 1)]; + let gv = g0[x]; + // `va` goes to channel `ch`, `vb` to `2 - ch` (as `px[ch] = va; px[2 - ch] = vb`, + // built from values: an indexed store into `px` stalls store forwarding). + let (ch, va, vb) = if own == 1 { + ( + phase[pr + ((x + 1) & 1)].min(2), + gv + 0.5 * ((d0[x - 1] - g0[x - 1]) + (d0[x + 1] - g0[x + 1])), + gv + 0.5 * ((dm1[x] - gm1[x]) + (dp1[x] - gp1[x])), + ) + } else { + ( + own.min(2), + d0[x], + gv + 0.25 * ((dm1[x - 1] - gm1[x - 1]) + (dm1[x + 1] - gm1[x + 1]) + (dp1[x - 1] - gp1[x - 1]) + (dp1[x + 1] - gp1[x + 1])), + ) + }; + let px = match ch { + 0 => [va, gv, vb], + 2 => [vb, gv, va], + _ => [gv, vb, gv], + }; + let px = px.map(|v| v.clamp(0.0, 1.0)); + orr[x] = px[0]; + org[x] = px[1]; + orb[x] = px[2]; + let xyz: [f32; 3] = std::array::from_fn(|k| m[k][0] * px[0] + m[k][1] * px[1] + m[k][2] * px[2]); + let (fx, fy, fz) = (labf.f(xyz[0]), labf.f(xyz[1]), labf.f(xyz[2])); + ol[x] = 116.0 * fy - 16.0; + oa[x] = 500.0 * (fx - fy); + ob[x] = 200.0 * (fy - fz); + } + } + } + // 3. Homogeneity maps, band rows 2..n-2, columns 4..s-4. + { + let [l0, a0, b0] = &sc.lab[0]; + let [l1, a1, b1] = &sc.lab[1]; + let [h0, h1] = &mut sc.hom; + for b in 2..n - 2 { + fn row(pl: &[f32], bb: usize, s: usize) -> &[f32] { + &pl[bb * s..(bb + 1) * s] + } + let (l0u, l0c, l0d) = (row(l0, b - 1, s), row(l0, b, s), row(l0, b + 1, s)); + let (a0u, a0c, a0d) = (row(a0, b - 1, s), row(a0, b, s), row(a0, b + 1, s)); + let (b0u, b0c, b0d) = (row(b0, b - 1, s), row(b0, b, s), row(b0, b + 1, s)); + let (l1u, l1c, l1d) = (row(l1, b - 1, s), row(l1, b, s), row(l1, b + 1, s)); + let (a1u, a1c, a1d) = (row(a1, b - 1, s), row(a1, b, s), row(a1, b + 1, s)); + let (b1u, b1c, b1d) = (row(b1, b - 1, s), row(b1, b, s), row(b1, b + 1, s)); + let (h0r, h1r) = (&mut h0[b * s..(b + 1) * s], &mut h1[b * s..(b + 1) * s]); + for x in 4..s - 4 { + // Neighbours left, right, up, down; (|ΔL|, Δa² + Δb²) from the centre. + let dist = |lc: f32, ac: f32, bc: f32, ln: f32, an: f32, bn: f32| ((lc - ln).abs(), (ac - an) * (ac - an) + (bc - bn) * (bc - bn)); + let (lc, ac, bc) = (l0c[x], a0c[x], b0c[x]); + let dh = [ + dist(lc, ac, bc, l0c[x - 1], a0c[x - 1], b0c[x - 1]), + dist(lc, ac, bc, l0c[x + 1], a0c[x + 1], b0c[x + 1]), + dist(lc, ac, bc, l0u[x], a0u[x], b0u[x]), + dist(lc, ac, bc, l0d[x], a0d[x], b0d[x]), + ]; + let (lc, ac, bc) = (l1c[x], a1c[x], b1c[x]); + let dv = [ + dist(lc, ac, bc, l1c[x - 1], a1c[x - 1], b1c[x - 1]), + dist(lc, ac, bc, l1c[x + 1], a1c[x + 1], b1c[x + 1]), + dist(lc, ac, bc, l1u[x], a1u[x], b1u[x]), + dist(lc, ac, bc, l1d[x], a1d[x], b1d[x]), + ]; + let eps_l = dh[0].0.max(dh[1].0).min(dv[2].0.max(dv[3].0)); + let eps_c = dh[0].1.max(dh[1].1).min(dv[2].1.max(dv[3].1)); + let count = |v: &[(f32, f32); 4]| v.iter().map(|(l, c)| u8::from(*l <= eps_l && *c <= eps_c)).sum::(); + h0r[x] = count(&dh); + h1r[x] = count(&dv); + } + } + } + // 4. Per pixel, the candidate with the larger 3×3 homogeneity sum. + let [vs0, vs1] = &mut sc.vs; + for r in 0..rows { + let b = r + M; + for (hm, vs) in [(&sc.hom[0], &mut *vs0), (&sc.hom[1], &mut *vs1)] { + let (u, c, dn) = (&hm[(b - 1) * s..b * s], &hm[b * s..(b + 1) * s], &hm[(b + 1) * s..(b + 2) * s]); + for x in PAD - 1..PAD + w + 1 { + vs[x] = u32::from(u[x]) + u32::from(c[x]) + u32::from(dn[x]); + } + } + let at = b * s; + let (r0, g0, b0) = (&sc.rgb[0][0][at..at + s], &sc.rgb[0][1][at..at + s], &sc.rgb[0][2][at..at + s]); + let (r1, g1, b1) = (&sc.rgb[1][0][at..at + s], &sc.rgb[1][1][at..at + s], &sc.rgb[1][2][at..at + s]); + let orow = &mut chunk[r * w * 3..(r + 1) * w * 3]; + for (x, o) in orow.as_chunks_mut::<3>().0.iter_mut().enumerate() { + let px = x + PAD; + let sh = vs0[px - 1] + vs0[px] + vs0[px + 1]; + let sv = vs1[px - 1] + vs1[px] + vs1[px + 1]; + let (c0, c1) = ([r0[px], g0[px], b0[px]], [r1[px], g1[px], b1[px]]); + *o = match sh.cmp(&sv) { + std::cmp::Ordering::Greater => c0, + std::cmp::Ordering::Less => c1, + std::cmp::Ordering::Equal => [0.5 * (c0[0] + c1[0]), 0.5 * (c0[1] + c1[1]), 0.5 * (c0[2] + c1[2])], + }; + } + } +} + +/// The plain AHD statement the optimized [`ahd`] must match bit for bit. +#[cfg(test)] +fn ahd_ref(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) { let (w, s) = (p.w, p.stride); let d = &p.data; // Colour at padded coordinates (PAD is even, so the phase is unchanged). @@ -596,6 +951,8 @@ fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) mod tests { use super::*; use crate::color::IDENTITY; + use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use std::time::{Duration, Instant}; #[test] fn ahd_band_concurrency_does_not_change_pixels() { @@ -614,6 +971,213 @@ mod tests { assert_eq!(demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, 1).len(), 192); } + #[test] + fn ahd_matches_reference_bit_for_bit() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + for (w, h) in [(1, 1), (2, 3), (7, 5), (53, 103), (64, 70), (33, 31)] { + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + for jobs in [1, 3, 64] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert_eq!( + want.iter().map(|v| v.to_bits()).collect::>(), + got.iter().map(|v| v.to_bits()).collect::>(), + "{w}x{h} {phase:?} {jobs}" + ); + } + } + } + } + + #[test] + fn fused_demosaic_matches_the_full_frame_demosaic() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + // Sizes around the bands (AHD 32 rows, bilinear / MHC 32 rows) and the padding. + for (w, h) in [(1, 1), (2, 3), (7, 5), (53, 103), (64, 64), (33, 31), (5, 70), (31, 65)] { + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + let fill = |y: usize, row: &mut [f32]| row.copy_from_slice(&cfa[y * w..(y + 1) * w]); + // Any per-sample map stands in for the encode. + let emit = |rgb: &[f32], out: &mut [u16]| { + for (o, v) in out.iter_mut().zip(rgb) { + *o = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; + } + }; + for method in [Demosaic::Bilinear, Demosaic::Mhc, Demosaic::Ahd] { + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + for jobs in [1, 3, 64] { + let full = demosaic(&p, phase, method, &m, jobs); + let mut want = vec![0u16; w * h * 3]; + emit(&full, &mut want); + let mut got = vec![0u16; w * h * 3]; + demosaic_fused(w, h, phase, method, &m, jobs, &fill, &mut got, &emit); + assert_eq!(want, got, "{w}x{h} {method:?} {phase:?} {jobs}"); + } + } + } + } + } + + /// Bytes the scratch planes actually hold. + fn scratch_bytes(sc: &AhdScratch) -> u64 { + let f = sc.g.iter().chain(sc.rgb.iter().flatten()).chain(sc.lab.iter().flatten()).map(|v| v.capacity() * 4).sum::(); + let b = sc.hom.iter().map(Vec::capacity).sum::(); + let u = sc.vs.iter().map(|v| v.capacity() * 4).sum::(); + (f + b + u) as u64 + } + + /// The memory check in `develop` admits a file on [`ahd_scratch`] per worker; the scratch + /// `ahd` allocates must not exceed it. A short wide strip used to allocate the 38 rows of a + /// full band against a budget of `h + 6` rows (5.4x at `h = 1`). + #[test] + fn ahd_scratch_fits_its_budget() { + for w in [1usize, 2, 33, 4000] { + for h in [1usize, 2, 7, 31, 32, 33, 100, 5000] { + let s = w + 2 * PAD; + let sc = AhdScratch::for_image(h, s); + let budget = ahd_scratch(w as u64, h as u64); + assert_eq!(scratch_bytes(&sc), budget, "{w}x{h}: allocated vs budgeted bytes"); + // The tallest band `ahd` hands out (at most 32 rows, plus 3 above and below) fits. + assert!(sc.g[0].len() >= (h.min(32) + 6) * s, "{w}x{h}"); + } + } + } + + /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over one scratch + /// with jobs 1 and two with jobs 2 on a bigger pool), so a stage reading a cell left over from + /// an earlier band would show. + #[test] + fn ahd_matches_reference_with_reused_scratch() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + for jobs in [1, 2] { + assert!(bands_per_group(ahd_bands(h), jobs, 1) >= 2, "jobs {jobs}: each scratch must serve several bands"); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert_eq!(want.len(), got.len()); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{w}x{h} {phase:?} jobs {jobs}"); + } + } + } + + /// On a 4-worker pool with room for 3 scratches, 35 bands go in groups of 12 (the last of 11), + /// so groups after the first start at band `group * 12` and every scratch is reused for several + /// bands; with room for 4, every band is its own task and most borrow a used scratch. A wrong band + /// index or a stale scratch cell would change pixels. The split does not depend on the machine. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn ahd_groups_of_several_bands_match_reference() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + assert_eq!(par::workers(), 4); + assert_eq!(bands_per_group(ahd_bands(h), 3, 1), 12); + // One group per job, never more groups than jobs, however many bands there are. + assert_eq!(bands_per_group(126, 3, 1), 42); + for jobs in [3, 4] { + for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?} jobs {jobs}"); + } + } + }); + } + + /// A scratch that counts how many are alive at once. + struct Live<'a>(&'a AtomicUsize); + + impl<'a> Live<'a> { + fn new(now: &'a AtomicUsize, peak: &AtomicUsize) -> Self { + peak.fetch_max(now.fetch_add(1, SeqCst) + 1, SeqCst); + Live(now) + } + } + + impl Drop for Live<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, SeqCst); + } + } + + /// Every band runs once with its own index, and no more than `jobs` scratches (what `develop`'s + /// memory check admits) or one per worker are alive at once, on either side of `jobs == workers`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn for_bands_keeps_at_most_jobs_scratches_alive() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap(); + pool.install(|| { + for jobs in [1, 2, 3, 7, 8, 9, usize::MAX] { + for per_worker in [1, 4] { + let (now, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mut out = vec![0usize; 37 * 10 - 4]; + for_bands_grouped( + &mut out, + 10, + 37, + jobs, + per_worker, + || Live::new(&now, &peak), + |band, chunk, _| { + std::thread::sleep(Duration::from_millis(1)); + chunk.iter_mut().for_each(|v| *v += band + 1); + }, + ); + assert!(out.iter().enumerate().all(|(i, &v)| v == i / 10 + 1), "jobs {jobs}"); + let peak = peak.load(SeqCst); + assert!((1..=jobs.min(8)).contains(&peak), "jobs {jobs} per_worker {per_worker}: {peak} scratches alive"); + assert_eq!(now.load(SeqCst), 0); + } + } + }); + } + + /// With room for a scratch on every worker, the bands are separate rayon tasks: a worker held up + /// on band 0 (by other work on the shared pool, or a slow core) leaves the bands after it to + /// the others. With a fixed share of 9 bands per worker, 8 of them would wait for band 0, so at + /// most 26 of the other 34 could finish meanwhile. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_slow_band_does_not_hold_up_the_bands_after_it() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + let (done, seen) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mut out = vec![0u8; 35]; + for_bands_grouped( + &mut out, + 1, + 35, + 4, + 1, + || (), + |band, _, _| { + if band > 0 { + done.fetch_add(1, SeqCst); + return; + } + let start = Instant::now(); + while done.load(SeqCst) <= 26 && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + seen.store(done.load(SeqCst), SeqCst); + }, + ); + assert_eq!(done.load(SeqCst), 34); + assert!(seen.load(SeqCst) > 26, "only {} bands ran while band 0 was held up", seen.load(SeqCst)); + }); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index ca08846a85..aaeb390eff 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -5,7 +5,7 @@ //! orientation. use crate::color::{self, Mat3}; -use crate::demosaic::{Demosaic, PAD, Padded, Pattern, demosaic, demosaic_cfa}; +use crate::demosaic::{Demosaic, PAD, Padded, Pattern, demosaic, demosaic_cfa, demosaic_cfa_fused, demosaic_fused, for_bands}; use crate::error::{RawError, Result}; use crate::look::{CameraLook, ToneCurve}; use crate::sensor::Sensor; @@ -194,6 +194,12 @@ pub(crate) fn resolve_neutral(s: &Sensor, opts: &DevelopOptions, sc: &Scale, war /// Develops sensor data. pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result { + develop(s, opts, true) +} + +/// [`develop_sensor`]; `allow_fused` false keeps the full-frame path (what the tests compare the +/// fused one against). +fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result { let c = s.crop; let samples = s.width.checked_mul(s.height).and_then(|n| n.checked_mul(s.samples)); if c.is_empty() @@ -219,7 +225,12 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result { return Err(RawError::malformed("invalid sensor CFA pattern")); } let bayer = s.cfa.as_ref().is_none_or(|cfa| cfa.is_bayer()); - let ahd_jobs = working_memory(c.width, c.height, s.cfa.is_some(), bayer, opts, par::workers())?; + // The default rendering (no Dehaze, no local tone, no black point) needs no statistic of + // the whole frame: demosaic and encode band by band, with no full RGB frame (the same + // condition under which `Haze::new` and `ToneMap::new` return `None`). + let fused = allow_fused && opts.tone.is_neutral() && s.black_point <= 0.0; + let orient_copy = opts.orient && (2..=8).contains(&s.orientation); + let jobs = working_memory(c.width, c.height, s.cfa.is_some(), bayer, Shape { fused, orient_copy }, opts, par::workers())?; let mut warnings = s.warnings.clone(); let sc = Scale::new(s); @@ -256,161 +267,207 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result { let grey_gain = gain as f32; let (w, h) = (c.width, c.height); let band = par::band_rows(w); - let mut rgb: Vec; - let pattern: Option; - match &s.cfa { - Some(cfa) => { - // Normalized, balanced, clipped CFA plane. - let mut plane = Padded::new(w, h); - let stride = plane.stride; - // Fast path: black varies at most per 2×2 position, so black and gain - // repeat every `period` columns (the CFA width, made even). - let bl = &s.black; - let periodic = bl.delta_h.is_empty() && bl.delta_v.is_empty() && matches!(bl.rows, 1 | 2) && matches!(bl.cols, 1 | 2) && cfa.width <= 16; - let period = if cfa.width % 2 == 0 { cfa.width.max(2) } else { cfa.width * 2 }; - plane.fill_rows(band, |y0, chunk| { - for (r, prow) in chunk.chunks_exact_mut(stride).enumerate() { - let row = &mut prow[PAD..PAD + w]; - let y = c.y + y0 + r; - if periodic { - // Per column of the period: black and the combined scale × white-balance gain. - let k: Vec<(f32, f32)> = (0..period) - .map(|p| { - let x = c.x + p; - let black = bl.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), 0, 1); - let range = s.white[0] - black; - // A non-finite black (a BlackLevel DOUBLE beyond f32) gives 0, as - // `Scale::value` does, instead of (raw - inf) * 0 = NaN. - if !(range >= 1.0 && black.is_finite()) { - return (0.0, 0.0); - } - (black, mult[usize::from(cfa.color(x, y)).min(2)] / range) - }) - .collect(); - let src = &s.data[y * s.width + c.x..y * s.width + c.x + w]; - let ks = k.iter().cycle(); - match &sc.lin { - None => { - for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); - } - } - Some(l) => { - for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); - *v = ((lin - black) * gain).clamp(0.0, 1.0); - } - } - } - } else { - for (i, v) in row.iter_mut().enumerate() { - let x = c.x + i; - let ch = usize::from(cfa.color(x, y)).min(2); - *v = (sc.value(x, y, 0) * mult[ch]).clamp(0.0, 1.0); - } - } - // Lens-shading gain maps, after the white-balance clip so clipped - // highlights stay neutral. - if let Some(g) = gain_row(s, y, c.x, w, 0) { - for (v, g) in row.iter_mut().zip(g) { - *v = (*v * g).clamp(0.0, 1.0); - } - } - } - }); - plane.fill_borders(); - let names = |p: &[u8]| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect::(); - if bayer { - let p = cfa.phase(c.x, c.y); - pattern = Some(names(&p)); - rgb = demosaic(&plane, p, opts.demosaic, &to_xyz, ahd_jobs); - } else { - let pat = Pattern::of(cfa, c.x, c.y); - pattern = Some(pat.colors.chunks(pat.w.max(1)).map(names).collect::>().join("/")); - rgb = demosaic_cfa(&plane, &pat); - } - drop(plane); - } - None => { - pattern = None; - rgb = vec![0.0f32; w * h * 3]; - par::chunks_mut(&mut rgb, band * w * 3, |b, chunk| { - for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { - let y = c.y + b * band + r; - for i in 0..w { - for k in 0..3 { - // Monochrome: the one sample in all three channels. - let sample = k.min(s.samples.saturating_sub(1)); - row[i * 3 + k] = (sc.value(c.x + i, y, sample) * mult[k]).clamp(0.0, 1.0); - } - } - for k in 0..s.samples.min(3) { - if let Some(g) = gain_row(s, y, c.x, w, k) { - for (i, g) in g.into_iter().enumerate() { - row[i * 3 + k] = (row[i * 3 + k] * g).clamp(0.0, 1.0); - } - } - } - } - }); - } - } - // Camera → ProPhoto, exposure, Dehaze, Shadows / Highlights / Clarity / Texture and the black // point, the look's (or the profile's) tone curve, gamma 1.8, 16 bits. let y_row = color::rgb_to_xyz(color::ROMM, color::D50_XY)[1].map(|v| v as f32); let lum = |v: &[f32; 3]| y_row[0] * v[0] + y_row[1] * v[1] + y_row[2] * v[2]; // Monochrome: the one sample, grey; no colour matrix. let pro = |p: &[f32]| if mono { [grey_gain * p[0]; 3] } else { [0, 1, 2].map(|k| out_m[k][0] * p[0] + out_m[k][1] * p[1] + out_m[k][2] * p[2]) }; - let haze = Haze::new(w, h, |i| pro(&rgb[i * 3..i * 3 + 3]), opts.tone.dehaze); - // Linear ProPhoto of pixel `i` after Dehaze. - let linear = |i: usize, p: &[f32]| { - let v = pro(p); - haze.as_ref().map_or(v, |z| z.apply(i % w, i / w, v)) - }; - let mut map = ToneMap::new(w, h, |i| lum(&linear(i, &rgb[i * 3..i * 3 + 3])), opts.tone, s.black_point); - if let (Some(m), Some(_)) = (&mut map, &haze) { - // The black point belongs to the default rendering: Dehaze does not move it (taken after - // Dehaze it fell to almost 0, and Dehaze darkened less than Photoshop's). - m.black = black_level(w, h, |i| lum(&pro(&rgb[i * 3..i * 3 + 3])), s.black_point); - } - let mut out = vec![0u16; w * h * 3]; let lut = match look { Some(l) => GammaLut::with_tone(l.tone.as_ref()), None => GammaLut::with_curve(&s.tone_curve), }; - // The default rendering (no Dehaze, no local tone): matrix then encode, in blocks so the - // encode's clamp and square root run over whole slices. - let plain = map.is_none() && haze.is_none(); - par::chunks_mut(&mut out, band * w * 3, |b, chunk| { - let start = b * band * w * 3; - let src = &rgb[start..start + chunk.len()]; - if plain { - let mut buf = [0.0f32; ENCODE_BLOCK]; - for (oc, sc) in chunk.chunks_mut(ENCODE_BLOCK).zip(src.chunks(ENCODE_BLOCK)) { - let n = sc.len(); - for (t, p) in buf[..n].as_chunks_mut::<3>().0.iter_mut().zip(sc.as_chunks::<3>().0) { - *t = pro(p); + // The default rendering: matrix then encode, in blocks so the encode's clamp and square root + // run over whole slices. + let encode_plain = |src: &[f32], dst: &mut [u16]| { + let mut buf = [0.0f32; ENCODE_BLOCK]; + for (oc, sc) in dst.chunks_mut(ENCODE_BLOCK).zip(src.chunks(ENCODE_BLOCK)) { + let n = sc.len(); + for (t, p) in buf[..n].as_chunks_mut::<3>().0.iter_mut().zip(sc.as_chunks::<3>().0) { + *t = pro(p); + } + lut.encode_into(&buf[..n], oc); + } + }; + // Rows `y0..` of a LinearRaw (3-sample or monochrome) frame, balanced and clipped. + let linear_rows = |y0: usize, chunk: &mut [f32]| { + for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { + let y = c.y + y0 + r; + for i in 0..w { + for k in 0..3 { + // Monochrome: the one sample in all three channels. + let sample = k.min(s.samples.saturating_sub(1)); + row[i * 3 + k] = (sc.value(c.x + i, y, sample) * mult[k]).clamp(0.0, 1.0); } - lut.encode_into(&buf[..n], oc); } - return; - } - for (i, (o, p)) in chunk.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<3>().0).enumerate() { - let mut v = linear(b * band * w + i, p); - if let Some(m) = &map { - let g = m.gain(i % w, b * band + i / w, lum(&v)); - // The black point first, as Camera Raw: lifting before it would flatten the - // deepest shadows' contrast. - v = v.map(|c| m.unblack(c) * g); - } - for k in 0..3 { - o[k] = lut.encode(v[k]); + for k in 0..s.samples.min(3) { + if let Some(g) = gain_row(s, y, c.x, w, k) { + for (i, g) in g.into_iter().enumerate() { + row[i * 3 + k] = (row[i * 3 + k] * g).clamp(0.0, 1.0); + } + } } } - }); - rgb.clear(); - rgb.shrink_to_fit(); + }; + let mut rgb: Vec = Vec::new(); + // The encoded frame, when the fused path made it. + let mut fused_out: Option> = None; + let pattern: Option; + match &s.cfa { + Some(cfa) => { + // One normalized, balanced, clipped CFA row (image row `iy` of the crop). + // Fast path: black varies at most per 2×2 position, so black and gain + // repeat every `period` columns (the CFA width, made even). + let bl = &s.black; + let periodic = bl.delta_h.is_empty() && bl.delta_v.is_empty() && matches!(bl.rows, 1 | 2) && matches!(bl.cols, 1 | 2) && cfa.width <= 16; + let period = if cfa.width % 2 == 0 { cfa.width.max(2) } else { cfa.width * 2 }; + let fill_row = |iy: usize, row: &mut [f32]| { + let y = c.y + iy; + if periodic { + // Per column of the period: black and the combined scale × white-balance gain. + let k: Vec<(f32, f32)> = (0..period) + .map(|p| { + let x = c.x + p; + let black = bl.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), 0, 1); + let range = s.white[0] - black; + // A non-finite black (a BlackLevel DOUBLE beyond f32) gives 0, as + // `Scale::value` does, instead of (raw - inf) * 0 = NaN. + if !(range >= 1.0 && black.is_finite()) { + return (0.0, 0.0); + } + (black, mult[usize::from(cfa.color(x, y)).min(2)] / range) + }) + .collect(); + let src = &s.data[y * s.width + c.x..y * s.width + c.x + w]; + let ks = k.iter().cycle(); + match &sc.lin { + None => { + for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { + *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); + } + } + Some(l) => { + for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { + let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); + *v = ((lin - black) * gain).clamp(0.0, 1.0); + } + } + } + } else { + for (i, v) in row.iter_mut().enumerate() { + let x = c.x + i; + let ch = usize::from(cfa.color(x, y)).min(2); + *v = (sc.value(x, y, 0) * mult[ch]).clamp(0.0, 1.0); + } + } + // Lens-shading gain maps, after the white-balance clip so clipped + // highlights stay neutral. + if let Some(g) = gain_row(s, y, c.x, w, 0) { + for (v, g) in row.iter_mut().zip(g) { + *v = (*v * g).clamp(0.0, 1.0); + } + } + }; + let names = |p: &[u8]| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect::(); + if bayer && fused { + // No padded plane either: every band normalizes its own rows. + let p = cfa.phase(c.x, c.y); + pattern = Some(names(&p)); + let mut o = vec![0u16; w * h * 3]; + demosaic_fused(w, h, p, opts.demosaic, &to_xyz, jobs, &fill_row, &mut o, &encode_plain); + fused_out = Some(o); + } else { + let mut plane = Padded::new(w, h); + let stride = plane.stride; + plane.fill_rows(band, |y0, chunk| { + for (r, prow) in chunk.chunks_exact_mut(stride).enumerate() { + fill_row(y0 + r, &mut prow[PAD..PAD + w]); + } + }); + plane.fill_borders(); + if bayer { + let p = cfa.phase(c.x, c.y); + pattern = Some(names(&p)); + rgb = demosaic(&plane, p, opts.demosaic, &to_xyz, jobs); + } else { + let pat = Pattern::of(cfa, c.x, c.y); + pattern = Some(pat.colors.chunks(pat.w.max(1)).map(names).collect::>().join("/")); + if fused { + let mut o = vec![0u16; w * h * 3]; + demosaic_cfa_fused(&plane, &pat, jobs, &mut o, &encode_plain); + fused_out = Some(o); + } else { + rgb = demosaic_cfa(&plane, &pat); + } + } + } + } + None => { + pattern = None; + if fused { + let mut o = vec![0u16; w * h * 3]; + for_bands( + &mut o, + band * w * 3, + h.div_ceil(band), + jobs, + || vec![0.0f32; band.min(h) * w * 3], + |b, chunk, buf| { + let buf = &mut buf[..chunk.len()]; + linear_rows(b * band, buf); + encode_plain(buf, chunk); + }, + ); + fused_out = Some(o); + } else { + rgb = vec![0.0f32; w * h * 3]; + par::chunks_mut(&mut rgb, band * w * 3, |b, chunk| linear_rows(b * band, chunk)); + } + } + } + + let out = match fused_out { + Some(out) => out, + None => { + let haze = Haze::new(w, h, |i| pro(&rgb[i * 3..i * 3 + 3]), opts.tone.dehaze); + // Linear ProPhoto of pixel `i` after Dehaze. + let linear = |i: usize, p: &[f32]| { + let v = pro(p); + haze.as_ref().map_or(v, |z| z.apply(i % w, i / w, v)) + }; + let mut map = ToneMap::new(w, h, |i| lum(&linear(i, &rgb[i * 3..i * 3 + 3])), opts.tone, s.black_point); + if let (Some(m), Some(_)) = (&mut map, &haze) { + // The black point belongs to the default rendering: Dehaze does not move it (taken after + // Dehaze it fell to almost 0, and Dehaze darkened less than Photoshop's). + m.black = black_level(w, h, |i| lum(&pro(&rgb[i * 3..i * 3 + 3])), s.black_point); + } + let mut out = vec![0u16; w * h * 3]; + let plain = map.is_none() && haze.is_none(); + par::chunks_mut(&mut out, band * w * 3, |b, chunk| { + let start = b * band * w * 3; + let src = &rgb[start..start + chunk.len()]; + if plain { + encode_plain(src, chunk); + return; + } + for (i, (o, p)) in chunk.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<3>().0).enumerate() { + let mut v = linear(b * band * w + i, p); + if let Some(m) = &map { + let g = m.gain(i % w, b * band + i / w, lum(&v)); + // The black point first, as Camera Raw: lifting before it would flatten the + // deepest shadows' contrast. + v = v.map(|c| m.unblack(c) * g); + } + for k in 0..3 { + o[k] = lut.encode(v[k]); + } + } + }); + rgb.clear(); + rgb.shrink_to_fit(); + out + } + }; let (out, ow, oh) = if opts.orient { orient(out, w, h, s.orientation) } else { (out, w, h) }; let nmax = mult.iter().cloned().fold(f32::MAX, f32::min).max(1e-6); @@ -433,29 +490,79 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result { }) } +/// How the frame is developed, for [`working_memory`]. +#[derive(Clone, Copy)] +struct Shape { + /// Demosaic and encode band by band (no full RGB frame). + fused: bool, + /// The orientation copies the encoded frame. + orient_copy: bool, +} + +/// Bytes one worker of the fused path holds for a band of `band_rows` rows: the f32 RGB band +/// and, for a Bayer sensor, the padded CFA window it reads. +fn fused_band_bytes(w: usize, h: usize, band_rows: usize, window: bool) -> u64 { + let rows = band_rows.min(h) as u64; + let rgb = rows.saturating_mul(w as u64).saturating_mul(12); + let window = if window { (rows + 2 * PAD as u64).saturating_mul((w + 2 * PAD) as u64).saturating_mul(4) } else { 0 }; + rgb.saturating_add(window) +} + /// Checks the peak of the two development phases. The CFA and non-Bayer green -/// planes are freed before the u16 output is allocated; AHD scratch is bounded -/// by reducing simultaneous bands when needed. Sensor storage belongs to the -/// caller and is checked separately by the decoder. -fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, opts: &DevelopOptions, workers: usize) -> Result { +/// planes are freed before the u16 output is allocated; the AHD scratch and the fused band +/// buffers are bounded by reducing simultaneous bands when needed. The fused path never holds +/// the f32 RGB frame: it has the u16 output (6 bytes a pixel) next to the CFA plane, plus a band +/// buffer and the scratch per simultaneous band, and an orientation copy of the output afterwards. Sensor storage belongs +/// to the caller and is checked separately by the decoder. +fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts: &DevelopOptions, workers: usize) -> Result { let limits = &opts.limits; - limits.check(w as u64, h as u64, 18)?; + let Shape { fused, orient_copy } = shape; + limits.check(w as u64, h as u64, if fused { 6 } else { 18 })?; let pixels = (w as u64).saturating_mul(h as u64); - let output = pixels.saturating_mul(18).saturating_add((GAMMA_STEPS as u64 + 2) * 4); - let mut peak = output; + let table = (GAMMA_STEPS as u64 + 2) * 4; + // Encode phase: the f32 RGB frame and the output, or (fused) the output and its oriented copy. + let output = pixels.saturating_mul(match (fused, orient_copy) { + (false, _) => 18, + (true, false) => 6, + (true, true) => 12, + }); + let mut peak = output.saturating_add(table); let mut jobs = workers.max(1); + // Fused: the u16 output and, per worker running a band, one band of f32 RGB. + let band_of = |rows: usize, window: bool| if fused { fused_band_bytes(w, h, rows, window) } else { 0 }; + // Fewer bands at once when the bands of every worker don't fit next to `base` (at least one). + let with_bands = |jobs: &mut usize, base: u64, rows: usize, band: u64| { + let available = limits.max_alloc.saturating_sub(base) / band.max(1); + *jobs = (*jobs).min(h.div_ceil(rows.max(1))).min(usize::try_from(available).unwrap_or(usize::MAX)).max(1); + base.saturating_add(band.saturating_mul(*jobs as u64)) + }; if cfa { let plane = (w as u64).saturating_add(2 * PAD as u64).saturating_mul((h as u64).saturating_add(2 * PAD as u64)).saturating_mul(4); - let mut mosaic = pixels.saturating_mul(if bayer { 12 } else { 16 }).saturating_add(plane); + // Bytes a pixel next to the plane: the f32 RGB frame (and the non-Bayer green plane), or + // the u16 output (and the green plane, which the fused path keeps). + let frame = match (fused, bayer) { + (false, true) => 12, + (false, false) => 16, + (true, true) => 6, + (true, false) => 10, + }; + // The fused Bayer path has no whole plane: each worker's window is counted with its band. + let plane = if fused && bayer { 0 } else { plane }; + let mut mosaic = pixels.saturating_mul(frame).saturating_add(plane).saturating_add(table); if bayer && opts.demosaic == Demosaic::Ahd { mosaic = mosaic.saturating_add(crate::demosaic::AHD_TABLE_BYTES); - let scratch = crate::demosaic::ahd_scratch(w as u64, h as u64); - let available = limits.max_alloc.saturating_sub(mosaic) / scratch.max(1); - jobs = jobs.min(crate::demosaic::ahd_bands(h)).min(usize::try_from(available).unwrap_or(usize::MAX)); + let scratch = crate::demosaic::ahd_scratch(w as u64, h as u64).saturating_add(band_of(crate::demosaic::AHD_BAND, true)); // At least one band must fit, even when no parallelism is available. - mosaic = mosaic.saturating_add(scratch.saturating_mul(jobs.max(1) as u64)); + mosaic = with_bands(&mut jobs, mosaic, crate::demosaic::AHD_BAND, scratch); + } else { + let rows = if bayer { crate::demosaic::FUSED_ROWS } else { par::band_rows(w) }; + mosaic = with_bands(&mut jobs, mosaic, rows, band_of(rows, bayer)); } peak = peak.max(mosaic); + } else if fused { + // LinearRaw: the output and the bands. + let rows = par::band_rows(w); + peak = peak.max(with_bands(&mut jobs, pixels.saturating_mul(6), rows, band_of(rows, false))); } if peak > limits.max_alloc || usize::try_from(peak).is_err() { return Err(RawError::LimitExceeded(format!("{peak} bytes of RAW working memory exceed {}", limits.max_alloc))); @@ -634,6 +741,138 @@ pub(crate) fn orient(src: Vec, w: usize, h: usize, o: u16) -> (Vec, us mod tests { use super::*; + const FULL: Shape = Shape { fused: false, orient_copy: false }; + const FUSED: Shape = Shape { fused: true, orient_copy: false }; + + /// A `w × h` sensor with a pseudo-random gradient, black 64, white 4000. + fn test_sensor(w: usize, h: usize, cfa: Option, samples: usize) -> Sensor { + use crate::*; + let data = (0..w * h * samples).map(|i| 64 + ((i * 7919 + i / w * 104_729 + i / 5 * 31) % 4100) as u16).collect(); + Sensor { + format: RawFormat::Dng, + make: None, + model: None, + width: w, + height: h, + samples, + data, + cfa, + linearization: None, + black: BlackLevels::uniform(64.0), + white: [4000.0; 3], + active: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + color: ColorInfo::default(), + camera_wb: None, + orientation: 1, + baseline_exposure: 0.0, + gain_maps: Vec::new(), + tone_curve: vec![[0.18, 0.3], [1.0, 1.0]], + black_point: 0.0, + warnings: Vec::new(), + } + } + + /// `f` on a pool of `n` threads (the browser builds have none). + fn with_threads(n: usize, f: impl FnOnce() -> R + Send) -> R { + #[cfg(not(target_arch = "wasm32"))] + return rayon::ThreadPoolBuilder::new().num_threads(n).build().unwrap().install(f); + #[cfg(target_arch = "wasm32")] + { + let _ = n; + f() + } + } + + fn assert_fused_matches_full(s: &Sensor, opts: &DevelopOptions, what: &str) { + let full = develop(s, opts, false).unwrap(); + for threads in [1, 3, 16] { + let fused = with_threads(threads, || develop(s, opts, true).unwrap()); + assert_eq!((full.width, full.height), (fused.width, fused.height), "{what} {threads}"); + assert!(full.rgb == fused.rgb, "{what} {threads} threads: fused output differs"); + } + } + + #[test] + fn fused_development_matches_the_full_frame_path() { + use crate::Cfa; + // Odd sizes, tiny images, band borders (AHD bands are 32 rows) and several bands. + let sizes = [(1, 1), (2, 3), (5, 3), (33, 31), (64, 64), (65, 97), (70, 131), (3, 300)]; + for (w, h) in sizes { + for method in [Demosaic::Ahd, Demosaic::Bilinear, Demosaic::Mhc] { + for orientation in [1, 6] { + for pattern in ["RGGB", "BGGR", "GRBG"] { + let mut s = test_sensor(w, h, Cfa::bayer(pattern), 1); + s.orientation = orientation; + let opts = DevelopOptions { demosaic: method, ..Default::default() }; + assert_fused_matches_full(&s, &opts, &format!("{w}x{h} {method:?} o{orientation} {pattern}")); + } + } + } + } + } + + #[test] + fn fused_development_matches_for_every_orientation_and_look() { + use crate::Cfa; + for orientation in 1..=8 { + let mut s = test_sensor(67, 45, Cfa::bayer("RGGB"), 1); + s.orientation = orientation; + s.baseline_exposure = 0.5; + s.linearization = Some((0..4100u32).map(|v| (v * 15 / 16) as u16).collect()); + assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("orientation {orientation}")); + } + } + + #[test] + fn fused_development_matches_for_xtrans_and_linear_raw() { + use crate::Cfa; + // 6 × 6 X-Trans repeat. + let rows = ["GGRGGB", "GGBGGR", "BRGRBG", "GGBGGR", "GGRGGB", "RBGBRG"]; + let colors: Vec = rows + .iter() + .flat_map(|r| { + r.bytes().map(|c| match c { + b'R' => 0, + b'G' => 1, + _ => 2, + }) + }) + .collect(); + // 600 samples wide: bands of 109 rows, so 350 rows are four (the last short) and 50 rows + // are less than one. + for (w, h) in [(6, 6), (37, 41), (80, 150), (600, 350), (600, 50)] { + let mut s = test_sensor(w, h, Some(Cfa { width: 6, height: 6, colors: colors.clone(), origin_x: 0, origin_y: 0 }), 1); + s.orientation = 8; + assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("xtrans {w}x{h}")); + } + for samples in [1, 3] { + for (w, h) in [(1, 1), (7, 5), (90, 111), (600, 350), (600, 50)] { + let mut s = test_sensor(w, h, None, samples); + s.orientation = 3; + assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("linear {samples} {w}x{h}")); + } + } + } + + #[test] + fn fused_only_where_no_whole_frame_statistic_is_needed() { + use crate::Cfa; + // The condition for the fused path is exactly "Haze and ToneMap are None". + let px = |_: usize| [0.5f32; 3]; + for tone in [Tone::NEUTRAL, Tone { shadows: 10.0, ..Tone::NEUTRAL }, Tone { dehaze: 5.0, ..Tone::NEUTRAL }, Tone { texture: 1.0, ..Tone::NEUTRAL }] { + for black_point in [0.0, 0.5] { + let none = Haze::new(8, 8, px, tone.dehaze).is_none() && ToneMap::new(8, 8, |_| 0.5, tone, black_point).is_none(); + assert_eq!(none, tone.is_neutral() && black_point <= 0.0, "{tone:?} {black_point}"); + } + } + // A tone slider or a black point is still developed (differently from the plain rendering). + let s = test_sensor(40, 40, Cfa::bayer("RGGB"), 1); + let plain = develop_sensor(&s, &DevelopOptions::default()).unwrap(); + let toned = develop_sensor(&s, &DevelopOptions { tone: Tone { shadows: 50.0, ..Tone::NEUTRAL }, ..Default::default() }).unwrap(); + assert!(plain.rgb != toned.rgb); + } + #[test] fn block_encode_matches_per_sample_encode() { let lut = GammaLut::with_curve(&[[0.25, 0.5], [1.0, 1.0]]); @@ -650,27 +889,86 @@ mod tests { let mut opts = DevelopOptions::default(); for method in [Demosaic::Bilinear, Demosaic::Mhc, Demosaic::Ahd] { opts.demosaic = method; - for workers in [1, 10, 32, 128] { - let jobs = working_memory(11648, 8736, true, true, &opts, workers).unwrap(); - assert!(jobs <= workers); - if method == Demosaic::Ahd && workers >= 32 { - assert!(jobs < workers); + for (fused, orient_copy) in [(false, false), (true, false), (true, true)] { + let shape = Shape { fused, orient_copy }; + for workers in [1, 10, 32, 128] { + let jobs = working_memory(11648, 8736, true, true, shape, &opts, workers).unwrap(); + assert!(jobs <= workers); + if method == Demosaic::Ahd && workers >= 32 && !fused { + assert!(jobs < workers); + } } } } opts.limits.max_alloc = 1 << 30; - assert!(working_memory(11648, 8736, true, true, &opts, 1).is_err()); + assert!(working_memory(11648, 8736, true, true, FULL, &opts, 1).is_err()); + // Fused: the u16 output and the CFA plane (+ one band) is about 10 bytes a pixel. + opts.demosaic = Demosaic::Bilinear; + assert!(working_memory(11648, 8736, true, true, FUSED, &opts, 1).is_ok()); + } + + /// The fused bilinear / MHC, X-Trans and LinearRaw paths run fewer bands at once when the bands + /// of every worker don't fit next to the output, as AHD does. A very wide, short Bayer frame + /// (262144 x 455: 15 bands of 32 rows, about 147 MB a band with its window) needs 2.92 GB + /// with all 15 at once against the default 2 GiB, and develops with 9. + #[test] + fn fused_bands_at_once_are_capped_by_the_memory_limit() { + let opts = DevelopOptions { demosaic: Demosaic::Bilinear, ..Default::default() }; + let table = (GAMMA_STEPS as u64 + 2) * 4; + let (w, h) = (262144usize, 455usize); + let band = 32 * 262144 * 12 + (32 + 2 * PAD as u64) * (262144 + 2 * PAD as u64) * 4; + for (workers, want) in [(1, 1), (8, 8), (9, 9), (10, 9), (16, 9), (32, 9)] { + assert_eq!(working_memory(w, h, true, true, FUSED, &opts, workers).unwrap(), want, "{workers} workers"); + } + // Never more jobs than bands, and one when only one band fits. + assert_eq!(working_memory(1000, 40, true, true, FUSED, &opts, 32).unwrap(), 2); + let mut tight = opts.clone(); + tight.limits.max_alloc = 262144 * 455 * 6 + table + band; + assert_eq!(working_memory(w, h, true, true, FUSED, &tight, 32).unwrap(), 1); + tight.limits.max_alloc -= 1; + assert!(working_memory(w, h, true, true, FUSED, &tight, 32).is_err()); + // X-Trans (bands of `band_rows(1000)` = 65 rows next to its planes) and LinearRaw likewise. + let plane = (1000 + 2 * PAD as u64) * (2000 + 2 * PAD as u64) * 4; + let mut x = opts.clone(); + x.limits.max_alloc = 1000 * 2000 * 10 + plane + table + 3 * 65 * 1000 * 12; + assert_eq!(working_memory(1000, 2000, true, false, FUSED, &x, 32).unwrap(), 3); + x.limits.max_alloc = 1000 * 2000 * 6 + 5 * 65 * 1000 * 12; + assert_eq!(working_memory(1000, 2000, false, true, FUSED, &x, 32).unwrap(), 5); } #[test] fn working_memory_accounts_for_padding_and_at_least_one_ahd_band() { let mut opts = DevelopOptions { demosaic: Demosaic::Ahd, ..Default::default() }; opts.limits.max_alloc = 100 * 100 * 22; - assert!(working_memory(100, 100, true, true, &opts, 1).is_err()); + assert!(working_memory(100, 100, true, true, FULL, &opts, 1).is_err()); opts.demosaic = Demosaic::Mhc; - assert!(working_memory(100, 100, true, true, &opts, 1).is_ok()); + assert!(working_memory(100, 100, true, true, FULL, &opts, 1).is_ok()); opts.limits.max_alloc = 100 * 100 * 18; - assert!(working_memory(100, 100, false, true, &opts, 1).is_err()); + assert!(working_memory(100, 100, false, true, FULL, &opts, 1).is_err()); + } + + #[test] + fn fused_working_memory_charges_the_output_the_window_and_the_bands() { + let mut opts = DevelopOptions { demosaic: Demosaic::Mhc, ..Default::default() }; + let (w, h) = (1000u64, 1000u64); + let table = (GAMMA_STEPS as u64 + 2) * 4; + let plane = (w + 2 * PAD as u64) * (h + 2 * PAD as u64) * 4; + let pad = PAD as u64; + let exact = |opts: &mut DevelopOptions, cfa: bool, bayer: bool, shape: Shape, need: u64| { + opts.limits.max_alloc = need - 1; + assert!(working_memory(1000, 1000, cfa, bayer, shape, opts, 1).is_err(), "{need} - 1"); + opts.limits.max_alloc = need; + assert!(working_memory(1000, 1000, cfa, bayer, shape, opts, 1).is_ok(), "{need}"); + }; + // Bayer: the u16 output and one band with its padded window, no whole plane. + let band = 32 * w * 12 + (32 + 2 * pad) * (w + 2 * pad) * 4; + exact(&mut opts, true, true, FUSED, w * h * 6 + table + band); + // An oriented frame needs the output twice; a monochrome sensor has no plane. + let mono_band = 65 * w * 12; + exact(&mut opts, false, true, Shape { fused: true, orient_copy: true }, w * h * 12 + table); + exact(&mut opts, false, true, FUSED, w * h * 6 + mono_band); + // X-Trans keeps its plane and its green plane. + exact(&mut opts, true, false, FUSED, w * h * 10 + plane + table + mono_band); } #[test] diff --git a/crates/raw/src/par.rs b/crates/raw/src/par.rs index 6d23fd70c4..d966d94f52 100644 --- a/crates/raw/src/par.rs +++ b/crates/raw/src/par.rs @@ -1,5 +1,7 @@ //! Data-parallel helpers: rayon on native targets, sequential on wasm. +use std::sync::{Mutex, PoisonError}; + /// Calls `f(index, chunk)` for each `chunk`-sized piece of `buf`. pub(crate) fn chunks_mut(buf: &mut [T], chunk: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) { let chunk = chunk.max(1); @@ -12,6 +14,36 @@ pub(crate) fn chunks_mut(buf: &mut [T], chunk: usize, f: impl Fn(usize, buf.chunks_mut(chunk).enumerate().for_each(|(i, c)| f(i, c)); } +/// Like [`chunks_mut`], with `f(state, index, chunk)` borrowing a state: a chunk takes a free one +/// or makes one with `init`, and gives it back when done, so rayon keeps its fine-grained +/// splitting and stealing while at most one state per worker is ever made (`f` must not itself +/// wait on rayon work). Rayon's `for_each_init` would make one per stolen piece, which on an idle +/// pool is often every chunk. A state no chunk still waiting can take is dropped at once, so +/// near the end they go as their workers finish rather than all at the very end. +pub(crate) fn chunks_mut_pooled( + buf: &mut [T], + chunk: usize, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(&mut S, usize, &mut [T]) + Sync + Send, +) { + let chunk = chunk.max(1); + // The free states and the number of chunks that have not taken one yet. + let pool = Mutex::new((Vec::new(), buf.len().div_ceil(chunk))); + chunks_mut(buf, chunk, |i, c| { + let taken = { + let mut pool = pool.lock().unwrap_or_else(PoisonError::into_inner); + pool.1 = pool.1.saturating_sub(1); + pool.0.pop() + }; + let mut state = taken.unwrap_or_else(&init); + f(&mut state, i, c); + let mut pool = pool.lock().unwrap_or_else(PoisonError::into_inner); + if pool.0.len() < pool.1 { + pool.0.push(state); + } + }); +} + /// Native worker count (the browser builds run sequentially). pub(crate) fn workers() -> usize { #[cfg(not(target_arch = "wasm32"))] @@ -56,3 +88,37 @@ pub(crate) fn map(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Ve pub(crate) fn band_rows(width: usize) -> usize { (65536 / width.max(1)).clamp(1, 256) } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every chunk is visited once with its own index (the last one short), and the chunks share + /// the states: a 4-worker pool makes at most 4 for 101 chunks, an empty buffer none. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn chunks_mut_pooled_makes_one_state_per_worker_at_most() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + let mut buf = vec![0usize; 1003]; + let inits = AtomicUsize::new(0); + let runs = AtomicUsize::new(0); + let init = || { + inits.fetch_add(1, Ordering::Relaxed); + 0usize + }; + chunks_mut_pooled(&mut buf, 10, init, |used, i, c| { + *used += 1; + runs.fetch_add(1, Ordering::Relaxed); + c.iter_mut().for_each(|v| *v += i + 1); + }); + assert!(buf.iter().enumerate().all(|(k, &v)| v == k / 10 + 1)); + assert_eq!(runs.load(Ordering::Relaxed), 101); + let n = inits.load(Ordering::Relaxed); + assert!((1..=4).contains(&n), "{n} states for 101 chunks on 4 workers"); + chunks_mut_pooled(&mut [0u8; 0], 4, init, |_, _, _| {}); + assert_eq!(inits.load(Ordering::Relaxed), n, "no state for an empty buffer"); + }); + } +} diff --git a/crates/raw/tests/it/development_limits.rs b/crates/raw/tests/it/development_limits.rs index 4e5e1636d3..394ec9db20 100644 --- a/crates/raw/tests/it/development_limits.rs +++ b/crates/raw/tests/it/development_limits.rs @@ -8,13 +8,25 @@ fn small_sensor() -> Sensor { #[test] fn checks_peak_live_buffers_instead_of_summing_disjoint_phases() { - let sensor = decode(&DngSpec::cfa(128, 96, vec![1000; 128 * 96]).build(), &Limits::default()).unwrap(); + let (w, h) = (128u64, 96u64); + let sensor = decode(&DngSpec::cfa(w as usize, h as usize, vec![1000; (w * h) as usize]).build(), &Limits::default()).unwrap(); + let table = (4096 + 2) * 4; + // Exactly `max_alloc` must work and one byte less must fail. + let check = |opts: &mut DevelopOptions, max_alloc: u64| { + let expected = develop_sensor(&sensor, opts).unwrap(); + opts.limits.max_alloc = max_alloc; + assert_eq!(develop_sensor(&sensor, opts).unwrap().rgb, expected.rgb); + opts.limits.max_alloc -= 1; + assert!(matches!(develop_sensor(&sensor, opts), Err(RawError::LimitExceeded(_)))); + }; + // A tone slider needs the f32 RGB frame next to the output (18 bytes a pixel) ... + let mut opts = DevelopOptions { demosaic: Demosaic::Mhc, tone: Tone { shadows: 20.0, ..Tone::NEUTRAL }, ..Default::default() }; + check(&mut opts, w * h * 18 + table); + // ... the default rendering the u16 output and, per worker, one band (32 rows) of f32 RGB with + // the 12 rows more of padded CFA it reads, but no whole plane. let mut opts = DevelopOptions { demosaic: Demosaic::Mhc, ..Default::default() }; - opts.limits.max_alloc = 128 * 96 * 18 + (4096 + 2) * 4; - let expected = develop_sensor(&sensor, &DevelopOptions { demosaic: Demosaic::Mhc, ..Default::default() }).unwrap(); - assert_eq!(develop_sensor(&sensor, &opts).unwrap().rgb, expected.rgb); - opts.limits.max_alloc -= 1; - assert!(matches!(develop_sensor(&sensor, &opts), Err(RawError::LimitExceeded(_)))); + let band = 32 * w * 12 + (32 + 12) * (w + 12) * 4; + rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap().install(|| check(&mut opts, w * h * 6 + table + band)); } #[test] diff --git a/crates/text/src/embolden.rs b/crates/text/src/embolden.rs new file mode 100644 index 0000000000..a33711996d --- /dev/null +++ b/crates/text/src/embolden.rs @@ -0,0 +1,397 @@ +//! Faux bold by thickening the glyph outline itself: every point moves outward along the bisector +//! of its two edges, so the stroke grows by the same amount everywhere and curves stay curves (the +//! approach of FreeType's `FT_Outline_EmboldenXY`). Stamping the glyph at several offsets instead +//! leaves stair-step notches on curves and corners at large sizes. + +use skrifa::outline::OutlinePen; + +/// One recorded outline segment; its points are in [`Contour::pts`]. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Verb { + Line, + Quad, + Cubic, +} + +/// A closed contour: `pts[0]` is its start, then each segment's points in order. +#[derive(Clone, Debug, Default, PartialEq)] +struct Contour { + verbs: Vec, + pts: Vec<(f64, f64)>, +} + +/// A glyph outline in font units at the drawn size (y up), recorded to be thickened and replayed. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Outline { + contours: Vec, +} + +impl OutlinePen for Outline { + fn move_to(&mut self, x: f32, y: f32) { + self.contours.push(Contour { verbs: Vec::new(), pts: vec![(f64::from(x), f64::from(y))] }); + } + fn line_to(&mut self, x: f32, y: f32) { + self.push(Verb::Line, &[(x, y)]); + } + fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + self.push(Verb::Quad, &[(cx0, cy0), (x, y)]); + } + fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + self.push(Verb::Cubic, &[(cx0, cy0), (cx1, cy1), (x, y)]); + } + fn close(&mut self) {} +} + +impl Outline { + fn push(&mut self, verb: Verb, pts: &[(f32, f32)]) { + // A segment before any move starts a contour at the origin, as a pen would. + if self.contours.is_empty() { + self.contours.push(Contour { verbs: Vec::new(), pts: vec![(0.0, 0.0)] }); + } + if let Some(c) = self.contours.last_mut() { + c.verbs.push(verb); + c.pts.extend(pts.iter().map(|&(x, y)| (f64::from(x), f64::from(y)))); + } + } + + /// Twice the signed area of all contours (shoelace over every point): positive when the outer + /// contours run counter-clockwise (y up, PostScript order), negative for TrueType's clockwise. + fn signed_area(&self) -> f64 { + let mut a = 0.0; + for c in &self.contours { + // Each point with the next, the last with the first. + for (p, q) in c.pts.iter().zip(c.pts.iter().cycle().skip(1)) { + a += p.0 * q.1 - q.0 * p.1; + } + } + a + } + + /// Grow the ink by `r` on every side (the stems get `2r` heavier, counters `2r` smaller). + /// Points, on and off the curve, move along the bisector of their neighbouring edges by + /// `r / cos(half the turn)`, capped by the shorter neighbouring edge so short segments and + /// sharp inner corners can't spike; a pointed tip (an A apex) never moves further than `2r`, + /// so it grows a little instead of a long miter. Nothing moves for a non-finite or non-positive `r`, or an + /// outline without area. + pub(crate) fn embolden(&mut self, r: f64) { + if !(r.is_finite() && r > 0.0) { + return; + } + let area = self.signed_area(); + if !area.is_finite() || area == 0.0 { + return; + } + // Outward is right of travel for counter-clockwise ink, left for clockwise. + let sign = if area > 0.0 { 1.0 } else { -1.0 }; + for c in &mut self.contours { + let shifts = shifts(&c.pts, r, sign); + for (p, s) in c.pts.iter_mut().zip(shifts) { + p.0 += s.0; + p.1 += s.1; + } + } + } + + /// Draw the outline into `pen`. + pub(crate) fn replay(&self, pen: &mut impl OutlinePen) { + let f = |v: f64| v as f32; + for c in &self.contours { + let Some(start) = c.pts.first() else { continue }; + pen.move_to(f(start.0), f(start.1)); + let mut i = 1; + for verb in &c.verbs { + let n = match verb { + Verb::Line => 1, + Verb::Quad => 2, + Verb::Cubic => 3, + }; + let Some(p) = c.pts.get(i..i + n) else { break }; + match (verb, p) { + (Verb::Line, [a]) => pen.line_to(f(a.0), f(a.1)), + (Verb::Quad, [a, b]) => pen.quad_to(f(a.0), f(a.1), f(b.0), f(b.1)), + (Verb::Cubic, [a, b, d]) => pen.curve_to(f(a.0), f(a.1), f(b.0), f(b.1), f(d.0), f(d.1)), + _ => break, + } + i += n; + } + pen.close(); + } + } +} + +/// How far each point of one closed contour moves (see [`Outline::embolden`]). No point moves +/// further than [`MAX_SHIFT`] times `r`: an uncapped miter puts a long spike on every pointed tip +/// (an A apex), and a tip past FreeType's spike threshold would not move at all. +fn shifts(pts: &[(f64, f64)], r: f64, sign: f64) -> Vec<(f64, f64)> { + let n = pts.len(); + let mut out = vec![(0.0, 0.0); n]; + if n < 2 { + return out; + } + // Runs of coincident points (or points that can't be measured) share their neighbours: the + // last point of the run before and the first of the run after. Found in one pass, so a + // contour of many repeated points (a hostile font) costs O(n), not O(n²). + let apart = |p: (f64, f64), q: (f64, f64)| { + let len = (q.0 - p.0).hypot(q.1 - p.1); + len > 1e-9 && len.is_finite() + }; + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut run_of = vec![0usize; n]; + for (i, &p) in pts.iter().enumerate() { + match runs.last_mut() { + Some(run) if !pts.get(run.0).is_some_and(|&a| apart(a, p)) => run.1 = i, + _ => runs.push((i, i)), + } + run_of[i] = runs.len().saturating_sub(1); + } + // The contour is closed: a last run back at the start point is the first run. + if runs.len() > 1 + && let (Some(&(first, _)), Some(&(last, _))) = (runs.first(), runs.last()) + && !apart(pts[first], pts[last]) + { + runs.pop(); + for k in &mut run_of[last..] { + *k = 0; + } + runs[0].0 = last; + } + let m = runs.len(); + if m < 2 { + return out; + } + // The edge from `pts[i]` to `pts[j]` (or from `pts[j]` when `into`), as a unit vector and length. + let edge = |i: usize, j: usize, into: bool| -> Option<(f64, f64, f64)> { + let (p, q) = (pts[i], pts[j]); + let (dx, dy) = if into { (p.0 - q.0, p.1 - q.1) } else { (q.0 - p.0, q.1 - p.1) }; + let len = dx.hypot(dy); + (len > 1e-9 && len.is_finite()).then(|| (dx / len, dy / len, len)) + }; + let cap = MAX_SHIFT * r; + for (i, shift) in out.iter_mut().enumerate() { + let k = run_of[i]; + let prev = runs[(k + m - 1) % m].1; + let next = runs[(k + 1) % m].0; + let (Some((ix, iy, l_in)), Some((ox, oy, l_out))) = (edge(i, prev, true), edge(i, next, false)) else { continue }; + let dot = ix * ox + iy * oy; + let d = 1.0 + dot; + let (sx, sy) = (sign * (iy + oy), -sign * (ix + ox)); + let len = sx.hypot(sy); + // An exact reversal has no bisector, and no side to call outward: leave it. + if !(len > 1e-9 && len.is_finite()) { + continue; + } + // How sharply the contour turns towards the ink at this point (negative: away). + let q = sign * (ox * iy - oy * ix); + let l = l_in.min(l_out); + let scale = if r * q <= l * d { r / d } else { l / q }; + // A pointed tip (turning away from the ink) moves no more than the cap along the bisector + // (`len` is the bisector's length, √(2d)). An inner corner keeps its exact miter, already + // limited by the shorter edge above: capping it would thin the strokes meeting there. + let scale = if q < 0.0 { scale.min(cap / len) } else { scale }; + if scale.is_finite() { + *shift = (sx * scale, sy * scale); + } + } + out +} + +/// The longest move of an emboldened point, in radii: a square corner moves √2, and a tip moves +/// `1 / sin(half its angle)`, so only tips sharper than 60° are capped. +const MAX_SHIFT: f64 = 2.0; + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: f32, y0: f32, x1: f32, y1: f32, ccw: bool) -> Outline { + let mut o = Outline::default(); + add_square(&mut o, x0, y0, x1, y1, ccw); + o + } + + fn add_square(o: &mut Outline, x0: f32, y0: f32, x1: f32, y1: f32, ccw: bool) { + o.move_to(x0, y0); + if ccw { + o.line_to(x1, y0); + o.line_to(x1, y1); + o.line_to(x0, y1); + } else { + o.line_to(x0, y1); + o.line_to(x1, y1); + o.line_to(x1, y0); + } + o.line_to(x0, y0); + o.close(); + } + + fn bounds(o: &Outline) -> [f64; 4] { + let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN]; + for c in &o.contours { + for p in &c.pts { + b = [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)]; + } + } + b + } + + fn close(a: [f64; 4], b: [f64; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6) + } + + #[test] + fn a_square_grows_by_the_radius_on_every_side_in_either_winding() { + for ccw in [true, false] { + let mut o = square(0.0, 0.0, 10.0, 10.0, ccw); + o.embolden(1.0); + assert!(close(bounds(&o), [-1.0, -1.0, 11.0, 11.0]), "ccw {ccw}: {:?}", bounds(&o)); + } + } + + #[test] + fn counters_shrink_while_the_outer_edge_grows() { + // A ring: outer counter-clockwise, hole clockwise (y up, as fonts are drawn). + let mut o = square(0.0, 0.0, 20.0, 20.0, true); + add_square(&mut o, 5.0, 5.0, 15.0, 15.0, false); + o.embolden(1.0); + let hole = &o.contours[1]; + let xs: Vec = hole.pts.iter().map(|p| p.0).collect(); + let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); + assert!((lo - 6.0).abs() < 1e-6 && (hi - 14.0).abs() < 1e-6, "the hole narrows: {lo}..{hi}"); + assert!(close(bounds(&o), [-1.0, -1.0, 21.0, 21.0])); + } + + #[test] + fn curves_keep_their_segments_and_move_their_control_points() { + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(10.0, 0.0); + o.quad_to(15.0, 5.0, 10.0, 10.0); + o.curve_to(7.0, 12.0, 3.0, 12.0, 0.0, 10.0); + o.line_to(0.0, 0.0); + o.close(); + let before = o.clone(); + o.embolden(0.5); + assert_eq!(o.contours[0].verbs, before.contours[0].verbs, "the same segments, not stamped copies"); + assert_ne!(o.contours[0].pts, before.contours[0].pts); + let mut replayed = Outline::default(); + o.replay(&mut replayed); + // Pens take f32 points, so the replay matches to f32 precision. + let (a, b) = (&replayed.contours[0], &o.contours[0]); + assert_eq!(a.verbs, b.verbs, "replay draws the thickened outline's segments"); + let near = |p: &(f64, f64), q: &(f64, f64)| (p.0 - q.0).abs() < 1e-4 && (p.1 - q.1).abs() < 1e-4; + assert!(a.pts.len() == b.pts.len() && a.pts.iter().zip(&b.pts).all(|(p, q)| near(p, q))); + } + + #[test] + fn degenerate_outlines_and_hostile_radii_change_nothing_and_never_produce_nan() { + let line = { + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(5.0, 0.0); + o.line_to(0.0, 0.0); + o + }; + let dots = { + let mut o = Outline::default(); + o.move_to(3.0, 3.0); + o.line_to(3.0, 3.0); + o.line_to(3.0, 3.0); + o + }; + for base in [line, dots, Outline::default()] { + for r in [1.0, 0.0, -1.0, f64::NAN, f64::INFINITY] { + let mut o = base.clone(); + o.embolden(r); + assert_eq!(o, base, "r {r}"); + } + } + // A square with repeated points still grows cleanly. + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + o.line_to(x, y); + } + o.embolden(1.0); + assert!(close(bounds(&o), [-1.0, -1.0, 11.0, 11.0]), "{:?}", bounds(&o)); + assert!(o.contours.iter().flat_map(|c| c.pts.iter()).all(|p| p.0.is_finite() && p.1.is_finite())); + } + + #[test] + fn a_sharp_inner_corner_is_capped_by_its_short_edge() { + // A thin spike: its tip turns almost back on itself and stays put. + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(10.0, 0.0); + o.line_to(0.0, 0.2); + o.line_to(0.0, 0.0); + o.embolden(5.0); + let b = bounds(&o); + assert!(b.iter().all(|v| v.abs() < 60.0), "no runaway miter: {b:?}"); + } + + /// How far the tip of an isosceles triangle with a `deg`-degree tip (long sides) moves. + fn tip_shift(deg: f64, r: f64) -> f64 { + let half = (deg / 2.0).to_radians(); + let (a, b) = ((1000.0 * half.sin()) as f32, (1000.0 * half.cos()) as f32); + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(a, b); + o.line_to(-a, b); + o.line_to(0.0, 0.0); + o.embolden(r); + let tip = o.contours[0].pts[0]; + tip.0.hypot(tip.1) + } + + #[test] + fn pointed_tips_grow_by_at_most_twice_the_radius_and_never_stop_growing() { + // 30°: an uncapped miter moves 1/sin(15°) = 3.86 r. 20.5° is just short of the spike + // threshold (5.6 r uncapped); 20° and 10° are past it, where the tip used to stay put. + for deg in [30.0, 20.5, 20.0, 10.0] { + let moved = tip_shift(deg, 1.0); + assert!(moved > 0.0 && moved <= 2.0 + 1e-9, "{deg}° tip moved {moved}"); + } + // Blunt corners keep their exact miter: a square corner √2, a 90° tip too. + assert!((tip_shift(90.0, 1.0) - std::f64::consts::SQRT_2).abs() < 1e-3); + } + + #[test] + fn inner_corners_keep_their_exact_miter() { + // A 40° notch (the crotch of a V) between long edges: its corner moves r / sin(20°), so the + // edges meeting there grow by r like the rest of the outline. The tip cap must not clip it. + let half = 20f64.to_radians(); + let (a, b) = ((1000.0 * half.sin()) as f32, (1000.0 * half.cos()) as f32); + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(-a, b); + o.line_to(-a - 1000.0, b); + o.line_to(-a - 1000.0, -1000.0); + o.line_to(a + 1000.0, -1000.0); + o.line_to(a + 1000.0, b); + o.line_to(a, b); + o.line_to(0.0, 0.0); + o.embolden(1.0); + let corner = o.contours[0].pts[0]; + let want = 1.0 / half.sin(); + assert!((corner.0.hypot(corner.1) - want).abs() < 1e-2, "{corner:?}, want {want}"); + } + + #[test] + fn many_repeated_points_are_thickened_in_linear_time() { + // A hostile glyph: a contour of 50 000 copies of one point, then a square. Finding each + // point's neighbours by scanning past the copies cost ~10⁹ steps. + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + for _ in 0..50_000 { + o.line_to(0.0, 0.0); + } + for (x, y) in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + o.line_to(x, y); + } + let start = std::time::Instant::now(); + o.embolden(1.0); + let took = start.elapsed(); + assert!(took < std::time::Duration::from_secs(2), "took {took:?}"); + assert!(close(bounds(&o), [-1.0, -1.0, 11.0, 11.0]), "{:?}", bounds(&o)); + } +} diff --git a/crates/text/src/font_class.rs b/crates/text/src/font_class.rs new file mode 100644 index 0000000000..edf518d9e7 --- /dev/null +++ b/crates/text/src/font_class.rs @@ -0,0 +1,295 @@ +//! What a font menu filters and sorts by: a family's classification (Serif, Sans Serif, Script…), +//! its outline format and whether it is variable, read from the font's own tables (OS/2 +//! `sFamilyClass` and PANOSE, `post.isFixedPitch`, `fvar`, `CFF `/`glyf`) and, where those say +//! nothing, from its name. Photoshop's font menu offers the same classes. + +use skrifa::raw::{FontRef, TableProvider}; + +/// A family's classification, as the font menu's class filter lists them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum FontClass { + Serif, + SlabSerif, + SansSerif, + Script, + Monospace, + Handwritten, + Blackletter, + Decorative, +} + +impl FontClass { + /// Every class, in menu order. + pub const ALL: [FontClass; 8] = [ + FontClass::Serif, + FontClass::SlabSerif, + FontClass::SansSerif, + FontClass::Script, + FontClass::Monospace, + FontClass::Handwritten, + FontClass::Blackletter, + FontClass::Decorative, + ]; + + /// The English menu label (translated by the UI). + pub fn label(self) -> &'static str { + match self { + FontClass::Serif => "Serif", + FontClass::SlabSerif => "Slab Serif", + FontClass::SansSerif => "Sans Serif", + FontClass::Script => "Script", + FontClass::Monospace => "Monospace", + FontClass::Handwritten => "Handwritten", + FontClass::Blackletter => "Blackletter", + FontClass::Decorative => "Decorative", + } + } + + /// The stable key for commands and saved filters (`"slabSerif"`). + pub fn key(self) -> &'static str { + match self { + FontClass::Serif => "serif", + FontClass::SlabSerif => "slabSerif", + FontClass::SansSerif => "sansSerif", + FontClass::Script => "script", + FontClass::Monospace => "monospace", + FontClass::Handwritten => "handwritten", + FontClass::Blackletter => "blackletter", + FontClass::Decorative => "decorative", + } + } + + /// The class with this [`Self::key`]. + pub fn from_key(key: &str) -> Option { + Self::ALL.into_iter().find(|c| c.key() == key) + } +} + +/// How a family's outlines are stored, as the font menu's format badge shows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FontFormat { + /// OpenType with PostScript (CFF) outlines. + OpenType, + /// TrueType outlines (`glyf`), including OpenType fonts that use them. + TrueType, + /// A variable font (`fvar`), whatever its outlines. + Variable, +} + +impl FontFormat { + /// The badge text: Photoshop's "O", "TT" and "VAR". + pub fn badge(self) -> &'static str { + match self { + FontFormat::OpenType => "O", + FontFormat::TrueType => "TT", + FontFormat::Variable => "VAR", + } + } +} + +/// What the font menu knows about a family, from its representative (regular) face. +#[derive(Clone, Debug, PartialEq)] +pub struct FamilyTraits { + pub class: Option, + pub format: FontFormat, + /// The 10 PANOSE digits (all 0 when the font doesn't say). + pub panose: [u8; 10], + /// `usWeightClass` (400 when absent). + pub weight: u16, +} + +impl FamilyTraits { + pub fn variable(&self) -> bool { + self.format == FontFormat::Variable + } +} + +/// Read a face's traits. Missing or malformed tables fall back to "unknown", never to an error. +pub fn traits_of(family: &str, font: &FontRef) -> FamilyTraits { + let os2 = font.os2().ok(); + let family_class = os2.as_ref().map_or(0, |t| t.s_family_class()); + let mut panose = [0u8; 10]; + if let Some(bytes) = os2.as_ref().map(|t| t.panose_10()) { + for (slot, b) in panose.iter_mut().zip(bytes.iter()) { + *slot = *b; + } + } + let weight = os2.as_ref().map_or(400, |t| t.us_weight_class()).clamp(1, 1000); + let fixed_pitch = font.post().ok().is_some_and(|p| p.is_fixed_pitch() != 0); + let format = if font.fvar().is_ok() { + FontFormat::Variable + } else if font.cff().is_ok() || font.cff2().is_ok() { + FontFormat::OpenType + } else { + FontFormat::TrueType + }; + FamilyTraits { class: classify(family, family_class, panose, fixed_pitch), format, panose, weight } +} + +/// Name fragments (lowercase) that mark a blackletter face; the tables have no class for it. +const BLACKLETTER: [&str; 7] = ["fraktur", "blackletter", "black letter", "textura", "old english", "schwabacher", "rotunda"]; + +/// Classify from the OS/2 `sFamilyClass` (high byte: the IBM class), the PANOSE digits, the +/// `post` fixed-pitch flag and, last, the family name. +pub fn classify(family: &str, family_class: i16, panose: [u8; 10], fixed_pitch: bool) -> Option { + let name = family.to_lowercase(); + let has = |words: &[&str]| words.iter().any(|w| name.contains(w)); + // Whole words of the name, so "Encode Sans" isn't read as a "code" font. + let words: Vec<&str> = name.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect(); + // PANOSE Latin Text proportion 9 is monospaced. + if fixed_pitch || (panose[0] == 2 && panose[3] == 9) { + return Some(FontClass::Monospace); + } + if has(&BLACKLETTER) { + return Some(FontClass::Blackletter); + } + // PANOSE family kind: 3 Latin Hand Written, 4 Latin Decoratives, 5 Latin Symbol. + match panose[0] { + 3 => return Some(if family_class >> 8 == 10 { FontClass::Script } else { FontClass::Handwritten }), + 4 | 5 => return Some(FontClass::Decorative), + _ => {} + } + match family_class >> 8 { + // 4 is Clarendon: bracketed serifs (Georgia), not slabs. + 1..=4 | 7 => return Some(FontClass::Serif), + 5 => return Some(FontClass::SlabSerif), + 8 => return Some(FontClass::SansSerif), + 9 | 12 => return Some(FontClass::Decorative), + 10 => return Some(if has(&["hand", "marker", "brush", "pen", "chalk"]) { FontClass::Handwritten } else { FontClass::Script }), + _ => {} + } + // PANOSE Latin Text serif style: 11-15 are sans (normal, obtuse, perpendicular, flared, + // rounded); square (6) is a slab; the rest, the square coves (bracketed serifs, as Georgia's) + // included, are serifs. + if panose[0] == 2 { + match panose[1] { + 11..=15 => return Some(FontClass::SansSerif), + 6 => return Some(FontClass::SlabSerif), + 2..=10 => return Some(FontClass::Serif), + _ => {} + } + } + // Last, the name. + if words.iter().any(|w| matches!(*w, "mono" | "monospace" | "monospaced" | "code" | "courier") || w.starts_with("consol")) { + Some(FontClass::Monospace) + } else if has(&["slab"]) { + Some(FontClass::SlabSerif) + } else if has(&["sans", "grotesk", "grotesque", "gothic"]) { + Some(FontClass::SansSerif) + } else if has(&["serif", "roman", "garamond", "times", "bodoni", "baskerville", "caslon"]) { + Some(FontClass::Serif) + } else if has(&["hand", "marker", "brush", "chalk"]) { + Some(FontClass::Handwritten) + } else if has(&["script"]) { + Some(FontClass::Script) + } else { + None + } +} + +/// How unlike `b` is to `a`: 0 for the same traits, larger the more they differ. Used to list +/// similar fonts (Photoshop's "Show similar fonts"): the class matters most, then the PANOSE +/// digits both fonts state (serif style, weight, proportion, contrast…), then the weight. +pub fn difference(a: &FamilyTraits, b: &FamilyTraits) -> f32 { + let mut d = 0.0; + if a.class != b.class { + d += 20.0; + } + // Digits 1..=9; 0 and 1 mean "any"/"no fit", so only stated digits count. + for (x, y) in a.panose.iter().zip(b.panose.iter()).skip(1) { + if *x > 1 && *y > 1 { + d += f32::from(x.abs_diff(*y)).min(6.0); + } + } + d + f32::from(a.weight.abs_diff(b.weight)) / 100.0 +} + +#[cfg(test)] +mod tests { + use super::*; + + const NONE: [u8; 10] = [0; 10]; + + #[test] + fn the_os2_class_wins_over_the_name() { + assert_eq!(classify("Georgia", 0x0105, NONE, false), Some(FontClass::Serif)); + assert_eq!(classify("Georgia", 0x0405, NONE, false), Some(FontClass::Serif), "Clarendon is a serif"); + assert_eq!(classify("Rockwell", 0x0501, NONE, false), Some(FontClass::SlabSerif)); + assert_eq!(classify("Arial", 0x0805, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Edwardian Script ITC", 0x0a05, NONE, false), Some(FontClass::Script)); + assert_eq!(classify("Wingdings", 0x0c00, NONE, false), Some(FontClass::Decorative)); + } + + #[test] + fn panose_classifies_fonts_without_an_os2_class() { + let sans = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4]; + let slab = [2, 6, 6, 3, 2, 2, 2, 2, 2, 4]; + let serif = [2, 2, 6, 3, 5, 4, 5, 2, 3, 4]; + let hand = [3, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + let deco = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + let mono = [2, 11, 6, 9, 2, 2, 2, 2, 2, 4]; + assert_eq!(classify("A", 0, sans, false), Some(FontClass::SansSerif)); + assert_eq!(classify("B", 0, slab, false), Some(FontClass::SlabSerif)); + assert_eq!(classify("C", 0, serif, false), Some(FontClass::Serif)); + assert_eq!(classify("D", 0, hand, false), Some(FontClass::Handwritten)); + assert_eq!(classify("E", 0, deco, false), Some(FontClass::Decorative)); + assert_eq!(classify("F", 0, mono, false), Some(FontClass::Monospace)); + // Georgia: square cove serifs are bracketed serifs, not slabs. + assert_eq!(classify("Georgia", 0, [2, 4, 5, 2, 5, 4, 5, 2, 3, 3], false), Some(FontClass::Serif)); + } + + #[test] + fn fixed_pitch_and_names_decide_the_rest() { + assert_eq!(classify("Anything", 0x0805, NONE, true), Some(FontClass::Monospace), "fixed pitch beats the class"); + assert_eq!(classify("UnifrakturMaguntia", 0, NONE, false), Some(FontClass::Blackletter)); + assert_eq!(classify("Old English Text MT", 0x0805, NONE, false), Some(FontClass::Blackletter)); + assert_eq!(classify("Roboto Slab", 0, NONE, false), Some(FontClass::SlabSerif)); + assert_eq!(classify("Noto Serif", 0, NONE, false), Some(FontClass::Serif)); + assert_eq!(classify("Noto Sans", 0, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Fira Code", 0, NONE, false), Some(FontClass::Monospace)); + assert_eq!(classify("Space Mono", 0, NONE, false), Some(FontClass::Monospace)); + // "code" inside a word, or a name the tables contradict, doesn't make a monospace. + assert_eq!(classify("Encode Sans", 0, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Encode Sans", 0x0805, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Code Pro Sans", 0x0805, NONE, false), Some(FontClass::SansSerif), "the class beats the name"); + assert_eq!(classify("Permanent Marker", 0, NONE, false), Some(FontClass::Handwritten)); + assert_eq!(classify("Unknowable", 0, NONE, false), None); + // Out-of-range or garbage table values don't panic or misfile. + assert_eq!(classify("X", i16::MIN, [255; 10], false), None); + assert_eq!(classify("X", -1, [2, 200, 0, 0, 0, 0, 0, 0, 0, 0], false), None); + } + + #[test] + fn similar_fonts_share_class_shape_and_weight() { + let t = |class, panose, weight| FamilyTraits { class: Some(class), format: FontFormat::TrueType, panose, weight }; + let arial = t(FontClass::SansSerif, [2, 11, 6, 4, 2, 2, 2, 2, 2, 4], 400); + let helvetica = t(FontClass::SansSerif, [2, 11, 6, 4, 2, 2, 2, 2, 2, 4], 400); + let arial_black = t(FontClass::SansSerif, [2, 11, 10, 4, 2, 1, 2, 2, 2, 4], 900); + let times = t(FontClass::Serif, [2, 2, 6, 3, 5, 4, 5, 2, 3, 4], 400); + assert_eq!(difference(&arial, &helvetica), 0.0); + assert!(difference(&arial, &arial_black) < difference(&arial, ×)); + assert!(difference(&arial, ×) >= 20.0, "another class is far away"); + } + + #[test] + fn bundled_families_are_read_from_their_tables() { + let mut db = crate::FontDb::new(); + let mono = db.family_traits(crate::fonts::MONO_FAMILY).expect("the bundled mono font"); + assert_eq!(mono.class, Some(FontClass::Monospace)); + // Inter states no class or PANOSE: it is read, but left unclassified rather than guessed. + let sans = db.family_traits(crate::fonts::DEFAULT_FAMILY).expect("the bundled UI font"); + assert!(sans.class.is_none() || sans.class == Some(FontClass::SansSerif), "{:?}", sans.class); + assert!((1..=1000).contains(&sans.weight)); + assert_eq!(db.family_traits("No Such Family"), None); + assert_eq!(db.family_traits(crate::fonts::DEFAULT_FAMILY), Some(sans), "cached"); + } + + #[test] + fn class_keys_round_trip() { + for c in FontClass::ALL { + assert_eq!(FontClass::from_key(c.key()), Some(c)); + } + assert_eq!(FontClass::from_key("slabSerif"), Some(FontClass::SlabSerif)); + assert_eq!(FontClass::from_key("nope"), None); + } +} diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 506f83dacd..416ae7834c 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -196,6 +196,9 @@ pub struct FontDb { /// [`Self::fallback_stack`] (#1909). Off, only the default family shapes the text. missing_glyph_protection: bool, face_cache: HashMap>, + /// Each family's [`crate::FamilyTraits`] (font menu filters), filled lazily; `None` for a + /// family whose fonts can't be read. + traits_cache: HashMap>, face_aliases: HashMap<(String, usize), String>, /// This is the shared engine's database: registrations also move [`shared_generation`]. shared: bool, @@ -218,6 +221,7 @@ impl FontDb { fallbacks: Vec::new(), missing_glyph_protection: true, face_cache: HashMap::new(), + traits_cache: HashMap::new(), face_aliases: HashMap::new(), shared: false, }; @@ -281,6 +285,7 @@ impl FontDb { } self.ps_cache.clear(); self.face_cache.clear(); + self.traits_cache.clear(); self.refresh_generics(); } } @@ -316,6 +321,7 @@ impl FontDb { names.sort_by_key(|n| (is_hidden_family(n), n.to_lowercase())); self.ps_cache.clear(); self.face_cache.clear(); + self.traits_cache.clear(); self.refresh_generics(); GENERATION.fetch_add(1, Ordering::Relaxed); if self.shared { @@ -475,6 +481,24 @@ impl FontDb { faces } + /// What the font menu filters and sorts a family by ([`crate::font_class`]), read from its + /// regular face (the upright face nearest weight 400). `None` when the family is unknown or + /// none of its fonts can be read. + pub fn family_traits(&mut self, family: &str) -> Option { + if let Some(t) = self.traits_cache.get(family) { + return t.clone(); + } + let traits = (|| { + let info = self.fcx.collection.family_by_name(family)?; + let face = info.fonts().iter().min_by_key(|f| (!matches!(f.style(), FontStyle::Normal), (f.weight().value() - 400.0).abs() as u32))?.clone(); + let blob = face.load(Some(&mut self.fcx.source_cache))?; + let font = skrifa::FontRef::from_index(blob.as_ref(), face.index()).ok()?; + Some(crate::font_class::traits_of(family, &font)) + })(); + self.traits_cache.insert(family.to_string(), traits.clone()); + traits + } + /// Resolve a menu style to its actual metadata instead of guessing from its spelling. pub fn named_face(&mut self, family: &str, style: &str) -> Option { self.faces(family).into_iter().find(|f| f.style.eq_ignore_ascii_case(style)) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a19588439f..4a4219e143 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -20,7 +20,9 @@ pub mod area; pub mod cjk; pub mod craft_fonts; +mod embolden; pub mod engine_data; +pub mod font_class; pub mod fonts; pub mod glyphs; pub mod layout; @@ -39,6 +41,7 @@ use photocraft_color::PixelFormat; use photocraft_doc::TextLayer; pub use craft_fonts::{CRAFT_FONTS, CraftFont}; +pub use font_class::{FamilyTraits, FontClass, FontFormat}; pub use fonts::{FaceInfo, FontDb, ResolvedFont}; pub use layout::{ ClusterInfo, LineInfo, PlacedGlyph, TextLayout, byte_index, char_index, hit_char, line_edge, line_index, line_step, text_point_inside, word_boundary, diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index c7cd3960b4..dacd120dcd 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -17,24 +17,25 @@ use rayon::prelude::*; /// Faux-italic slant in degrees (Photoshop-like). pub const FAUX_ITALIC_DEG: f32 = 12.0; -/// Faux-bold ring radius as a fraction of the font size (tuned so stem weight stays close to the old summed-coverage look). +/// How far faux bold grows the outline on every side, as a fraction of the font size +/// ([`crate::embolden`]): stems get twice this heavier, close to the weight of the earlier +/// faux bold, which stamped the glyph at offsets of this radius. pub const FAUX_BOLD_RADIUS: f32 = 0.036; /// Largest raster we produce (pixels), as a guard against absurd sizes. const MAX_PIXELS: u64 = 256 * 1024 * 1024; -/// Cumulative coverage-pixel work budget across all colour and faux-bold passes of one render. +/// Cumulative coverage-pixel work budget across the colour passes of one render. const MAX_PASS_PIXELS: u64 = MAX_PIXELS * 4; /// Peak working bytes one rasterization may keep live. [`MAX_PIXELS`] does not bound them: the -/// accumulator and the output surface are both `stride` deep, and a faux-bold pass keeps one more -/// coverage buffer live, so a CMYK bold render reserves several times what a plain grey one does -/// for the same pixels. +/// accumulator and the output surface are both `stride` deep, so a CMYK render reserves several +/// times what a plain grey one does for the same pixels. const MAX_RASTER_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 }; /// Whether a `w` x `h` render's peak working bytes fit `max_bytes`: the f32 accumulator and the -/// output surface (both `stride` deep), plus the coverage buffers live at the peak. A plain pass -/// peaks inside `Coverage::finish`, which holds its accumulator and the vector it builds beside -/// it; a faux-bold pass peaks one buffer higher, since the resolved plain coverage is kept while -/// the bold pass resolves into it. `false` when the arithmetic overflows, so an absurd size is -/// refused rather than wrapping. +/// output surface (both `stride` deep), plus the coverage buffers live at the peak. A pass peaks +/// inside `Coverage::finish`, which holds its accumulator and the vector it builds beside it. +/// Faux bold draws its thickened outlines in that same pass; a `bold` render is still budgeted +/// one buffer higher, as when it was stamped into a buffer of its own, which leaves it headroom. +/// `false` when the arithmetic overflows, so an absurd size is refused rather than wrapping. fn fits_raster_budget(w: usize, h: usize, stride: usize, sample: SampleType, bold: bool, max_bytes: u64) -> bool { let f32s = size_of::() as u64; let peak = (w as u64).checked_mul(h as u64).and_then(|px| { @@ -110,28 +111,6 @@ impl LineSink for WarpSink<'_, S> { } } -/// Draws every glyph and decoration of `layout` whose style colour is `color` (or all of them -/// when `color` is `None`) into `sink`, through `transform` (text space → sink space), bending -/// the outlines with `warp` first (in text space). -fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_color: Option<&Color>, warp: Option<&Warp>) { - draw_pass(layout, transform, sink, only_color, warp, Pass::All); -} - -/// Which part of the layout [`draw_pass`] emits. Faux bold draws each glyph at several offsets; -/// summing those into one coverage buffer saturates the antialiased edge pixels (hard, pixelated -/// stems), so the rasteriser draws every offset into its own buffer and merges them with `max`. -#[derive(Clone, Copy, PartialEq)] -enum Pass { - /// Everything, all offsets (bounds, outlines). - All, - /// Non-bold glyphs and decorations. - Plain, - /// Bold glyphs at one offset (index into [`BOLD_OFFSETS`]). - Bold(usize), -} - -const BOLD_OFFSETS: [(f64, f64); 8] = [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, -0.7), (0.7, -0.7), (-0.7, 0.7)]; - fn is_bold(layout: &TextLayout, g: &PlacedGlyph) -> bool { let face_bold = layout.faces.get(g.face as usize).is_some_and(|f| f.embolden); layout.styles.get(g.style as usize).is_some_and(|s| s.faux_bold) || face_bold @@ -185,7 +164,11 @@ fn visible_color_passes(layout: &TextLayout, warp: Option<&Warp>) -> Vec<(Color, colors } -fn draw_pass(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_color: Option<&Color>, warp: Option<&Warp>, pass: Pass) { +/// Draws every glyph and decoration of `layout` whose style colour is `color` (or all of them +/// when `color` is `None`) into `sink`, through `transform` (text space → sink space), bending +/// the outlines with `warp` first (in text space). Faux bold glyphs are drawn from their outline +/// thickened by [`FAUX_BOLD_RADIUS`] ([`crate::embolden`]). +fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_color: Option<&Color>, warp: Option<&Warp>) { for g in &layout.glyphs { let st = &layout.styles[g.style as usize]; if only_color.is_some_and(|c| c != &st.color) { @@ -212,41 +195,27 @@ fn draw_pass(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, o } } } - let bold = st.faux_bold || face.embolden; - let r = (face.size_px * FAUX_BOLD_RADIUS) as f64; - let single = [(0.0, 0.0)]; - let offsets: &[(f64, f64)] = match (pass, bold) { - (Pass::Plain, true) => continue, - (Pass::Bold(_), false) => continue, - (Pass::Bold(k), true) => match BOLD_OFFSETS.get(k..=k) { - Some(o) => o, - None => continue, - }, - (Pass::All, true) => &BOLD_OFFSETS, - (_, false) => &single, - }; - for &(ox, oy) in offsets { - let local = glyph.mul(&Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r])); - let settings = DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords)); - match bend { - Some(w) => { - let mut ws = WarpSink { inner: &mut *sink, warp: w, post: *transform }; - let mut pen = Pen::new(&mut ws, local); - if outline.draw(settings, &mut pen).is_ok() { - skrifa::outline::OutlinePen::close(&mut pen); - } - } - None => { - let mut pen = Pen::new(&mut *sink, transform.mul(&local)); - if outline.draw(settings, &mut pen).is_ok() { - skrifa::outline::OutlinePen::close(&mut pen); - } - } + let settings = || DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords)); + // Faux bold thickens the outline in font units, before faux italic and scaling, so the + // slant and proportions apply to the bold shape as they do to a real bold face. Other + // glyphs draw straight into the pen. + let mut bold = None; + if st.faux_bold || face.embolden { + let mut shape = crate::embolden::Outline::default(); + if outline.draw(settings(), &mut shape).is_err() { + continue; } + shape.embolden(f64::from(face.size_px * FAUX_BOLD_RADIUS)); + bold = Some(shape); + } + let settings = settings(); + match bend { + Some(w) => { + let mut ws = WarpSink { inner: &mut *sink, warp: w, post: *transform }; + draw_glyph(&outline, settings, bold.as_ref(), &mut Pen::new(&mut ws, glyph)); + } + None => draw_glyph(&outline, settings, bold.as_ref(), &mut Pen::new(&mut *sink, transform.mul(&glyph))), } - } - if matches!(pass, Pass::Bold(_)) { - return; } for d in &layout.decorations { let st = &layout.styles[d.style as usize]; @@ -263,6 +232,23 @@ fn draw_pass(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, o } } +/// One glyph into `pen`: its thickened `bold` outline when there is one, else the font's own. +fn draw_glyph( + outline: &skrifa::outline::OutlineGlyph, + settings: DrawSettings, + bold: Option<&crate::embolden::Outline>, + pen: &mut impl skrifa::outline::OutlinePen, +) { + match bold { + Some(shape) => shape.replay(pen), + None => { + if outline.draw(settings, &mut *pen).is_ok() { + pen.close(); + } + } + } +} + /// Font units (scaled to px, y up) → text space for a placed glyph: scales, faux italic, /// baseline shift, and the vertical-type orientation. fn glyph_xform(layout: &TextLayout, g: &PlacedGlyph, face_skew_deg: f32) -> Xform { @@ -397,13 +383,13 @@ pub(crate) fn rasterize_passes( let xf = Xform([1.0, 0.0, 0.0, 1.0, -rect.x0 as f64, -rect.y0 as f64]).mul(&Xform(transform.m)); let whole = Rect::new(0, 0, w as i32, h as i32); let mut pass_pixels = 0u64; - for &(c, color_bold) in &colors { - // Rasterise each colour only over its own glyphs (every offset of faux bold included): + for &(c, _) in &colors { + // Rasterise each colour only over its own glyphs (faux bold's thickened outlines included): // a full-size pass per colour made text with many coloured runs cost colours x area // (#8602). Outside its ink a colour's coverage is zero, so the result is the same. let sub = if per_colour { let mut b = Bounds::default(); - draw_pass(layout, &xf, &mut b, Some(&c), warp, Pass::All); + draw(layout, &xf, &mut b, Some(&c), warp); b.rect.map(rect_from_bounds).unwrap_or(Rect::EMPTY).intersect(&whole) } else { whole @@ -412,8 +398,8 @@ pub(crate) fn rasterize_passes( continue; } let (sw, sh) = (sub.width() as usize, sub.height() as usize); - let passes = 1 + if color_bold { BOLD_OFFSETS.len() } else { 0 }; - let Some(cost) = (sw as u64).checked_mul(sh as u64).and_then(|px| px.checked_mul(passes as u64)) else { + // One pass per colour: faux bold draws thickened outlines in it (`draw`). + let Some(cost) = (sw as u64).checked_mul(sh as u64) else { return nothing(format); }; let Some(total) = pass_pixels.checked_add(cost).filter(|&t| t <= MAX_PASS_PIXELS) else { @@ -424,24 +410,10 @@ pub(crate) fn rasterize_passes( let Some(mut cov) = Coverage::try_new(sw, sh) else { return nothing(format); }; - draw_pass(layout, &xf, &mut cov, Some(&c), warp, Pass::Plain); - let Some(mut cov) = cov.finish() else { + draw(layout, &xf, &mut cov, Some(&c), warp); + let Some(cov) = cov.finish() else { return nothing(format); }; - if color_bold { - for k in 0..BOLD_OFFSETS.len() { - let Some(mut bc) = Coverage::try_new(sw, sh) else { - return nothing(format); - }; - draw_pass(layout, &xf, &mut bc, Some(&c), warp, Pass::Bold(k)); - let Some(bold_cov) = bc.finish() else { - return nothing(format); - }; - for (a, b) in cov.iter_mut().zip(bold_cov) { - *a = a.max(b); - } - } - } let comps = color_in(&format, &c); let a = c.alpha.clamp(0.0, 1.0); composite(&mut acc, w, sub, &cov, stride, &comps, a, antialias); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4fe9709942..9dd58a55d4 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2613,6 +2613,53 @@ fn hyphenless_postscript_names_split_trailing_styles() { } } +/// Thickening moves each outline point along its bisector; this guards that curves stay as smooth +/// as the regular glyph's at a large size (the bend of a bold "O"'s edge between rows matches the +/// regular one's). See also `faux_bold_keeps_square_corners_square`. +#[test] +fn faux_bold_curves_stay_smooth_at_large_sizes() { + let mut e = TextEngine::new(); + // The largest bend of the left edge between consecutive rows, in pixels (second difference + // of its sub-pixel position), over the middle of the glyph's height. + let bumpiness = |e: &mut TextEngine, bold: bool| -> f64 { + let style = CharStyle { size_pt: 600.0, faux_bold: bold, ..Default::default() }; + let (_, r) = e.render(&TextLayer { transform: Affine::translate(60.0, 640.0), ..styled("O", style) }, 72.0, PixelFormat::RGBA8); + let alpha = |x: i32, y: i32| alpha_sum(&r.surface, photocraft_geom::Rect::new(x, y, x + 1, y + 1)); + let h = r.rect.height() as i32; + let mut edges = Vec::new(); + for y in (r.rect.y0 + h * 15 / 100)..(r.rect.y0 + h * 85 / 100) { + if let Some(x) = (r.rect.x0..r.rect.x1).find(|&x| alpha(x, y) > 0.01) { + edges.push(f64::from(x) + 1.0 - alpha(x, y)); + } + } + edges.windows(3).map(|w| (w[2] - 2.0 * w[1] + w[0]).abs()).fold(0.0, f64::max) + }; + let plain = bumpiness(&mut e, false); + let bold = bumpiness(&mut e, true); + eprintln!("bumpiness plain {plain} bold {bold}"); + assert!(bold < plain + 0.5, "faux bold's edge is notched: bends {bold} px vs {plain} px regular"); +} + +/// The notches showed most at corners and stroke ends: eight stamped copies leave a stepped bite +/// out of a square corner. Thickened outlines keep corners square, as a bold "l" shows. +#[test] +fn faux_bold_keeps_square_corners_square() { + let mut e = TextEngine::new(); + for bold in [false, true] { + let style = CharStyle { size_pt: 600.0, faux_bold: bold, ..Default::default() }; + let (_, r) = e.render(&TextLayer { transform: Affine::translate(60.0, 640.0), ..styled("l", style) }, 72.0, PixelFormat::RGBA8); + let alpha = |x: i32, y: i32| alpha_sum(&r.surface, photocraft_geom::Rect::new(x, y, x + 1, y + 1)); + // The ink's own top-left and top-right corners (the raster rect pads the ink by a pixel). + let top = (r.rect.y0..r.rect.y1).find(|&y| (r.rect.x0..r.rect.x1).any(|x| alpha(x, y) > 0.5)).unwrap(); + let left = (r.rect.x0..r.rect.x1).find(|&x| (r.rect.y0..r.rect.y1).any(|y| alpha(x, y) > 0.5)).unwrap(); + let right = (r.rect.x0..r.rect.x1).rev().find(|&x| (r.rect.y0..r.rect.y1).any(|y| alpha(x, y) > 0.5)).unwrap(); + for (x, corner) in [(left + 1, "top-left"), (right - 1, "top-right")] { + let a = alpha(x, top + 1); + assert!(a > 0.9, "bold {bold}: the {corner} corner is cut away (alpha {a})"); + } + } +} + #[test] fn text_rebuild_preserves_imported_font_metadata() { use crate::engine_data::Value as E; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 75ecf186f2..6912a149e6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1352,9 +1352,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // it is stale, so no tool cursor or brush outline is painted at it. } else if let Some((vertical, _)) = guide_hover { ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(&xf, vertical)); - } else if let Some(p) = response.hover_pos() - && let Some(c) = crate::transform_tool::cursor(app, &xf, xf.to_doc(p), ui.input(|i| i.modifiers.alt || i.modifiers.command)) - { + } else if let Some((p, mods, c)) = response.hover_pos().and_then(|p| { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + let c = crate::transform_tool::cursor(app, &xf, xf.to_doc(p), mods)?; + Some((p, mods, c)) + }) { ui.ctx().set_cursor_icon(c); // CursorIcon::None hides the pointer; the curved arrow has to be drawn or the // rotate zone looks like a plain cursor (#4050). @@ -1362,6 +1364,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + } else if c == egui::CursorIcon::None { + // Likewise the distort and skew pointers over a handle (#5405). + crate::transform_tool::draw_handle_cursor(app, &ctx, &xf, p, mods); } } else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, &xf, xf.to_doc(p))) { ui.ctx().set_cursor_icon(c); diff --git a/crates/ui-egui/src/canvas/gpu_canvas.rs b/crates/ui-egui/src/canvas/gpu_canvas.rs index 7f16afd5ce..fc9c520a1f 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -43,12 +43,14 @@ mod setup; mod shaders; mod texels; -#[cfg(test)] -use budget::drm_video_memory; +#[cfg(all(test, target_os = "linux"))] +use budget::nvidia_video_memory; pub use budget::{ DEFER_PX, MIN_GPU_BUDGET, OVER_BUDGET, OVER_CANVAS_BUDGET, REFRESH_DEFERRED, REFRESH_OVER_BUDGET, canvas_budget, canvas_texture_bytes, memory_budget, physical_memory, video_memory, vram_share, }; +#[cfg(test)] +use budget::{NVIDIA_VENDOR, bounded_output, drm_video_memory, parse_nvidia_smi}; #[cfg(all(test, windows))] use budget::{detect_physical_memory, detect_video_memory}; use callback::CanvasCallback; diff --git a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs index c98870130f..c735918576 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs @@ -120,11 +120,11 @@ fn detect_physical_memory() -> Option { } /// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports -/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size on Linux. `None` for -/// integrated and software adapters, whose textures live in system memory (the RAM-based -/// budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` overrides it -/// for any adapter, simulating a discrete card of that size: on an integrated GPU the budget then -/// stops charging the document's pixels too, as for a real card (a development switch). +/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size or `nvidia-smi`'s report on +/// Linux. `None` for integrated and software adapters, whose textures live in system memory (the +/// RAM-based budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` +/// overrides it for any adapter, simulating a discrete card of that size: on an integrated GPU the +/// budget then stops charging the document's pixels too, as for a real card (a development switch). pub fn video_memory(adapter: &wgpu::AdapterInfo) -> Option { if let Some(mb) = std::env::var("PHOTOCRAFT_VRAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { return mb.checked_mul(1 << 20).filter(|b| *b > 0); @@ -161,7 +161,103 @@ pub(super) fn detect_video_memory(vendor: u32, device: u32) -> Option { #[cfg(target_os = "linux")] fn detect_video_memory(vendor: u32, device: u32) -> Option { - drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device) + drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device).or_else(|| nvidia_video_memory(vendor, device)) +} + +/// PCI vendor id of NVIDIA, whose proprietary Linux driver writes none of amdgpu's +/// `mem_info_vram_total` sysfs files (a card of its own still reads as [`None`] above): without +/// this, a discrete NVIDIA card was charged for the document's pixels like an integrated one, +/// `memory_budget` shrank to Memory Usage minus them, and a many-layer document whose pages then +/// missed that budget redrew whole-document edits on the CPU every time (P60/P61 on an NVIDIA +/// Linux box: 1.5 s where the fix's own benchmark measures tens of milliseconds elsewhere). +#[cfg(any(target_os = "linux", test))] +pub(super) const NVIDIA_VENDOR: u32 = 0x10de; + +/// How long `nvidia-smi` gets to answer: it runs on the UI thread while the window opens, and a +/// driver that hangs the query must not keep PhotoCraft from starting. +#[cfg(target_os = "linux")] +const NVIDIA_SMI_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2); + +/// NVIDIA's own memory size on Linux, from `nvidia-smi` (installed with the driver that put this +/// adapter there in the first place): absent, slower than [`NVIDIA_SMI_DEADLINE`] or odd output +/// all read as `None`, never a hang or a panic. +#[cfg(target_os = "linux")] +pub(super) fn nvidia_video_memory(vendor: u32, device: u32) -> Option { + if vendor != NVIDIA_VENDOR { + return None; + } + let mut cmd = std::process::Command::new("nvidia-smi"); + cmd.args(["--query-gpu=pci.device_id,memory.total", "--format=csv,noheader,nounits"]); + let out = bounded_output(cmd, NVIDIA_SMI_DEADLINE)?; + parse_nvidia_smi(&String::from_utf8_lossy(&out), vendor, device) +} + +/// The first 64 KiB of `cmd`'s stdout when it exits successfully within `deadline`; `None` when +/// it can't start, fails or is still running by then. A late one is killed and reaped on a thread +/// of its own (a process stuck in the driver may not die at once), so the caller waits about +/// `deadline` at most. +#[cfg(any(target_os = "linux", test))] +pub(super) fn bounded_output(mut cmd: std::process::Command, deadline: std::time::Duration) -> Option> { + use std::io::Read; + use std::process::{Child, Stdio}; + use std::time::{Duration, Instant}; + fn abandon(mut child: Child) { + let _ = child.kill(); + let _ = std::thread::Builder::new().name("reap".into()).spawn(move || child.wait()); + } + let end = Instant::now().checked_add(deadline)?; + let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let Some(stdout) = child.stdout.take() else { + abandon(child); + return None; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let reader = std::thread::Builder::new().name("child-stdout".into()).spawn(move || { + let mut buf = Vec::new(); + let _ = stdout.take(64 << 10).read_to_end(&mut buf); + let _ = tx.send(buf); + }); + if reader.is_err() { + abandon(child); + return None; + } + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if Instant::now() < end => std::thread::sleep(Duration::from_millis(10)), + _ => { + abandon(child); + return None; + } + } + }; + if !status.success() { + return None; + } + // The child has exited, so its stdout is at EOF unless it handed the pipe on to a process of + // its own: bounded too, rather than joining the reader. + rx.recv_timeout(end.saturating_duration_since(Instant::now()).max(Duration::from_millis(50))).ok() +} + +/// `nvidia-smi --query-gpu=pci.device_id,memory.total --format=csv,noheader,nounits`'s own +/// format: one `0xDDDDVVVV, size-in-MiB` line per card (device id the high half, vendor id the +/// low, as `lspci -n` and wgpu's own ids read them). The matching line's size, in bytes, and the +/// smallest when several cards share those ids (the ids can't tell which one wgpu picked, so the +/// budget assumes the smaller); `None` when no line names this `vendor`/`device`, or the output +/// isn't shaped like that at all. +#[cfg(any(target_os = "linux", test))] +pub(super) fn parse_nvidia_smi(output: &str, vendor: u32, device: u32) -> Option { + output + .lines() + .filter_map(|line| { + let (id, mb) = line.split_once(',')?; + let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?; + if id & 0xffff != vendor || id >> 16 != device { + return None; + } + mb.trim().parse::().ok()?.checked_mul(1 << 20).filter(|b| *b > 0) + }) + .min() } /// amdgpu's VRAM size (`/device/mem_info_vram_total`, bytes) of the card under `drm` (the diff --git a/crates/ui-egui/src/canvas/gpu_canvas/tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/tests.rs index 7402f5026f..74305c024b 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/tests.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/tests.rs @@ -210,6 +210,86 @@ fn drm_video_memory_reads_the_matching_cards_vram() { std::fs::remove_dir_all(&drm).unwrap(); } +/// #P60/P61: amdgpu's sysfs files have no NVIDIA equivalent, so a discrete NVIDIA card's own +/// memory comes from `nvidia-smi`'s CSV instead (real output: `0x2C0510DE, 16303`, device id +/// the high half of the hex, vendor the low). A second card, an upper-case `0X` prefix, extra +/// spaces, a non-matching id, a missing comma, a non-numeric size, empty output and a size +/// that would overflow all give nothing rather than the wrong (or a panicking) answer. +#[test] +fn parses_nvidia_smis_own_report_of_the_cards_memory() { + let two = "0x2C0510DE, 16303\n0x061C10DE, 24576\n"; + assert_eq!(parse_nvidia_smi(two, NVIDIA_VENDOR, 0x2c05), Some(16303 << 20)); + assert_eq!(parse_nvidia_smi(two, NVIDIA_VENDOR, 0x061c), Some(24576 << 20)); + assert_eq!(parse_nvidia_smi("0X2C0510DE, 16303 \n", NVIDIA_VENDOR, 0x2c05), Some(16303 << 20), "upper-case prefix, loose spacing"); + assert_eq!(parse_nvidia_smi(two, NVIDIA_VENDOR, 0xdead), None, "no such device id"); + assert_eq!(parse_nvidia_smi(two, 0x1002, 0x2c05), None, "no such vendor id"); + assert_eq!(parse_nvidia_smi("not csv at all", NVIDIA_VENDOR, 0x2c05), None); + assert_eq!(parse_nvidia_smi("0x2C0510DE 16303\n", NVIDIA_VENDOR, 0x2c05), None, "no comma"); + assert_eq!(parse_nvidia_smi("0x2C0510DE, lots\n", NVIDIA_VENDOR, 0x2c05), None, "not a number"); + assert_eq!(parse_nvidia_smi("", NVIDIA_VENDOR, 0x2c05), None, "empty output"); + assert_eq!(parse_nvidia_smi(&format!("0x2C0510DE, {}\n", u64::MAX), NVIDIA_VENDOR, 0x2c05), None, "would overflow"); +} + +/// Two cards of one model (same vendor and device id) with different memory: wgpu's ids can't +/// tell which one it picked, so the budget assumes the smaller rather than whichever came first. +#[test] +fn nvidia_smi_cards_sharing_an_id_report_the_smaller_memory() { + assert_eq!(parse_nvidia_smi("0x2C0510DE, 16303\n0x2C0510DE, 8192\n", NVIDIA_VENDOR, 0x2c05), Some(8192 << 20)); + assert_eq!(parse_nvidia_smi("0x2C0510DE, 8192\n0x2C0510DE, 16303\n", NVIDIA_VENDOR, 0x2c05), Some(8192 << 20)); + assert_eq!(parse_nvidia_smi("0x2C0510DE, lots\n0x2C0510DE, 16303\n", NVIDIA_VENDOR, 0x2c05), Some(16303 << 20), "a bad line is skipped"); + assert_eq!(parse_nvidia_smi("0x2C0510DE, 0\n0x2C0510DE, 16303\n", NVIDIA_VENDOR, 0x2c05), Some(16303 << 20), "a zero size is no answer"); +} + +/// `nvidia-smi` runs on the UI thread at startup, so a query the driver never answers must +/// give up at the deadline instead of keeping the window from opening. +#[cfg(any(unix, windows))] +#[test] +fn a_child_that_never_answers_gives_up_at_the_deadline() { + let slow = if cfg!(windows) { + let mut c = std::process::Command::new("ping"); + c.args(["-n", "11", "127.0.0.1"]); + c + } else { + let mut c = std::process::Command::new("sleep"); + c.arg("10"); + c + }; + let start = std::time::Instant::now(); + assert_eq!(bounded_output(slow, std::time::Duration::from_millis(200)), None); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed()); + + let quick = if cfg!(windows) { + let mut c = std::process::Command::new("cmd"); + c.args(["/C", "echo 0x2C0510DE, 16303"]); + c + } else { + let mut c = std::process::Command::new("printf"); + c.arg("0x2C0510DE, 16303\n"); + c + }; + let out = bounded_output(quick, std::time::Duration::from_secs(10)).expect("a quick command answers"); + assert_eq!(parse_nvidia_smi(&String::from_utf8_lossy(&out), NVIDIA_VENDOR, 0x2c05), Some(16303 << 20)); + + let failing = if cfg!(windows) { + let mut c = std::process::Command::new("cmd"); + c.args(["/C", "exit 3"]); + c + } else { + std::process::Command::new("false") + }; + assert_eq!(bounded_output(failing, std::time::Duration::from_secs(10)), None, "a failed run"); + assert_eq!(bounded_output(std::process::Command::new("photocraft-no-such-tool"), std::time::Duration::from_secs(1)), None, "not installed"); +} + +/// Only a discrete NVIDIA adapter asks `nvidia-smi`: nothing else spawns a process whose +/// answer it would then ignore anyway (`nvidia_video_memory` gates on the vendor id first). +#[cfg(target_os = "linux")] +#[test] +fn nvidia_video_memory_only_asks_for_an_nvidia_vendor_id() { + assert_eq!(nvidia_video_memory(0x1002, 0x73bf), None, "an AMD id never runs nvidia-smi"); + assert_eq!(nvidia_video_memory(0x8086, 0x9a49), None, "an Intel id never runs nvidia-smi"); +} + /// Windows used to report no RAM at all, so the budget assumed 16 GB on every machine. #[cfg(windows)] #[test] diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs index bcec552b4d..b9a040257e 100644 --- a/crates/ui-egui/src/canvas/paint.rs +++ b/crates/ui-egui/src/canvas/paint.rs @@ -528,11 +528,16 @@ pub(super) fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter let size = [st.doc.size.width, st.doc.size.height]; let doc_rect = xf.doc_rect(st.doc.bounds()); let trail = app.trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)); - if t == Tool::SpotHealing { - // What the heal covers, dab by dab: soft edges, pressure and shape dynamics (#2364). - trail.feed_dabs(&d.points, || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({}))); - } else { - trail.feed(&d.points, app.session.tools.brush.size); + let brush = || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + match t { + // Quick Selection reads the brush's size alone (`select.quick`). + Tool::QuickSelection => trail.feed(&d.points, app.session.tools.brush.size), + // Remove removes every pixel a dab touches, so its whole reach is tinted: a soft + // tip's reaches well past the nominal radius. + Tool::Remove => trail.feed_reach(&d.points, brush), + // What the stroke covers, dab by dab: soft edges, pressure and shape dynamics + // (Spot Healing #2364; the Mixer Brush, and a tool whose live stroke didn't start). + _ => trail.feed_dabs(&d.points, brush), } trail.draw(painter, doc_rect, xf.flip, col); } diff --git a/crates/ui-egui/src/canvas/select_mask_view.rs b/crates/ui-egui/src/canvas/select_mask_view.rs index a06c78e468..e60da1054d 100644 --- a/crates/ui-egui/src/canvas/select_mask_view.rs +++ b/crates/ui-egui/src/canvas/select_mask_view.rs @@ -197,12 +197,25 @@ pub fn controls(ui: &mut egui::Ui, fields: &mut Map) { fields.insert(field.into(), json!(on)); } ui.label(egui::RichText::new(tl!("F cycles the views; hold X to see the image")).color(t.text_dim).small()); + // Photoshop's Remember Settings, off by default: the next Select and Mask starts from these + // settings instead of the defaults (#9423). + let mut remember = remembers(fields); + crate::widgets::checkbox(ui, &mut remember, tl!("Remember Settings")); + fields.insert(REMEMBER.into(), json!(remember)); ui.add_space(4.0); crate::widgets::hairline(ui); ui.add_space(6.0); brush_controls(ui, fields); } +/// The dialog field behind Remember Settings. +pub const REMEMBER: &str = "__remember"; + +/// Whether Remember Settings is on in `fields` (a dialog's, or the remembered ones). +pub fn remembers(fields: &Map) -> bool { + flag(fields, REMEMBER) +} + /// The Refine Edge Brush (R): painting on the canvas sets where edge refinement happens. fn brush_controls(ui: &mut egui::Ui, fields: &mut Map) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a2ec365f80..a90df6af98 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2639,43 +2639,48 @@ fn smoothed_brush_drag_draws_the_string_from_brush_to_pointer() { #[test] fn retouch_drags_show_the_footprint_without_wedges() { // The retouching tools' trail was the same brush-wide polyline (#189): now a mask of the - // footprint, with nothing outside the brush radius of the path, however small the steps. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 30}})).unwrap(); - // Remove: the dab tools draw their stroke live instead of a trail, and Spot Healing's - // trail is its dabs' coverage. - app.ui.tool = Tool::Remove; - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - let mut pts = vec![[20.0, 30.0]]; - for i in 1..80 { - let t = f64::from(i) * 0.5; - let p = [20.0 + t, 30.0 + (t / 2.0).sin() * 3.0]; - tool_event(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE); - pts.push(p); - if i % 20 == 0 { - // One mesh for the trail, however long the drag. - let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); - assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); - } - } - drag_preview_shapes(&mut app, &ctx, 12.0); - let trail = app.trail.as_ref().unwrap(); - assert_eq!(trail.scale(), 1.0); - for y in 0..60 { - for x in 0..120 { - let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min); - if d < 14.0 { - assert_eq!(trail.coverage(x, y), 255, "({x}, {y}) inside the footprint"); - } else if d > 16.0 { - assert_eq!(trail.coverage(x, y), 0, "({x}, {y}) outside the footprint"); + // footprint, with nothing outside it, however small the steps. The Remove Tool's is where + // the stroke's dabs reach at all, which is what it removes, so a soft tip's whole reach + // past the radius is tinted. + for hardness in [1.0, 0.0] { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": hardness}})).unwrap(); + app.ui.tool = Tool::Remove; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for i in 1..80 { + let t = f64::from(i) * 0.5; + tool_event(&mut app, ToolEvent::Move { x: 20.0 + t, y: 30.0 + (t / 2.0).sin() * 3.0, pressure: 1.0 }, egui::Modifiers::NONE); + if i % 20 == 0 { + // One mesh for the trail, however long the drag. + let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); } } + drag_preview_shapes(&mut app, &ctx, 12.0); + // The stroke the removal gets on release, and the pixels its hole takes. + let points = app.drag.as_ref().unwrap().points.iter().map(|p| photocraft_paint::StrokePoint::new(p[0], p[1], p[2] as f32)).collect(); + let brush = photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + let (b, cov) = photocraft_paint::retouch::stroke_coverage(&photocraft_paint::Stroke { brush, points }); + let trail = app.trail.as_ref().unwrap(); + assert_eq!(trail.scale(), 1.0); + let mut beyond = 0; + for y in 0..60 { + for x in 0..120 { + let removed = b.contains(x, y) && cov[(y - b.y0) as usize * b.width() as usize + (x - b.x0) as usize] > 0.0; + assert_eq!(trail.coverage(x as usize, y as usize), if removed { 255 } else { 0 }, "hardness {hardness}: ({x}, {y})"); + // Past the 15 px radius of the path's ends and sides (y 27..33). + beyond += usize::from(removed && !(12..=48).contains(&y)); + } + } + if hardness == 0.0 { + assert!(beyond > 100, "a soft tip's removal reaches past its radius: {beyond} px"); + } + tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); + drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(app.trail.is_none(), "the trail ends with the drag"); } - tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); - drag_preview_shapes(&mut app, &ctx, 12.0); - assert!(app.trail.is_none(), "the trail ends with the drag"); } #[test] diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index 5dd64cb77b..a3c1f4b9b0 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -226,6 +226,38 @@ fn web_sliders_snap_and_take_hex() { assert_eq!(bytes(h.state().session.tools.foreground), [0x66, 0xCC, 0]); } +#[test] +fn cube_modes_warn_when_the_colour_cannot_print() { + // #8672: Photoshop's Hue and Brightness Cube show the ⚠ and the nearest printable colour under + // the chips, as the slider modes do; a click takes that colour. + const GAMUT: &str = "Out of gamut for printing: click for the nearest printable colour"; + for mode in [ColorPanelMode::HueCube, ColorPanelMode::BrightnessCube] { + let mut h = color_tab(ThemeKind::Classic, mode, [0.0, 1.0, 0.0, 1.0]); + let near = crate::color_picker_ui::out_of_gamut([0.0, 1.0, 0.0]).expect("pure green can't print"); + let alert = h.get_by_label(GAMUT).rect().center(); + press(&mut h, alert, Modifiers::NONE); + let fg = h.state().session.tools.foreground; + assert_eq!(bytes(fg), bytes([near[0], near[1], near[2], 1.0]), "{mode:?}"); + h.run_steps(2); + assert!(h.query_by_label(GAMUT).is_none(), "{mode:?}: the printable colour still warns"); + // A printable colour shows no alert. + let h = color_tab(ThemeKind::Classic, mode, [0.5, 0.5, 0.5, 1.0]); + assert!(h.query_by_label(GAMUT).is_none(), "{mode:?}"); + // CodeRabbit on #9154: with the background chip active, the click sets the background. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.5, 0.5, 0.5, 1.0]; + app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; + app.ui.color_panel.mode = mode; + app.ui.color_panel.background = true; + let mut h = color_tab_of(ThemeKind::Classic, app); + let alert = h.get_by_label(GAMUT).rect().center(); + press(&mut h, alert, Modifiers::NONE); + let tools = &h.state().session.tools; + assert_eq!(bytes(tools.background), bytes([near[0], near[1], near[2], 1.0]), "{mode:?}: background"); + assert_eq!(bytes(tools.foreground), bytes([0.5, 0.5, 0.5, 1.0]), "{mode:?}: the foreground is left alone"); + } +} + #[test] fn ramp_picks_and_shift_click_cycles_and_alt_picks_the_other_colour() { let mut h = color_tab(ThemeKind::BreezeDark, ColorPanelMode::RgbSliders, [0.0, 0.0, 0.0, 1.0]); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b752dbd2d6..ef22e21c76 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -441,6 +441,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields), + DialogKind::Command if crate::new_group_ui::owns(&fields) => crate::new_group_ui::body(ui, &mut fields), DialogKind::Command if crate::snapshot_dialog::owns(&fields) => crate::snapshot_dialog::body(ui, &mut fields), DialogKind::Command if crate::channel_options_ui::owns(&fields) => crate::channel_options_ui::body(ui, &mut fields), DialogKind::Command if crate::channel_options_ui::owns_new_spot(&fields) => crate::channel_options_ui::new_spot_body(ui, &mut fields), @@ -759,6 +760,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::disk_change_prompt::owns, crate::actions::owns_insert_stop, crate::new_layer_ui::owns, + crate::new_group_ui::owns, crate::mask_trash_prompt::owns, crate::rasterize_prompt::owns, crate::duplicate_layer_ui::owns, @@ -844,6 +846,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), + DialogKind::Command if crate::new_group_ui::owns(&d.fields) => crate::new_group_ui::confirm(app, &d.fields), DialogKind::Command if crate::snapshot_dialog::owns(&d.fields) => crate::snapshot_dialog::confirm(app, &d.fields), DialogKind::Command if crate::channel_options_ui::owns(&d.fields) => crate::channel_options_ui::confirm(app, &d.fields), DialogKind::Command if crate::channel_options_ui::owns_new_spot(&d.fields) => crate::channel_options_ui::confirm_new_spot(app, &d.fields), @@ -969,6 +972,9 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) if command == crate::stroke_ui::COMMAND { return crate::stroke_ui::open(app); } + if crate::new_group_ui::fronts(command) { + return crate::new_group_ui::open(app, command); + } if command == crate::color_range_ui::COMMAND { return crate::color_range_ui::open(app); } @@ -1028,6 +1034,7 @@ pub mod layer_style; pub mod liquify_ui; pub mod mask_trash_prompt; pub mod new_doc_ui; +pub mod new_group_ui; pub mod new_guide_ui; pub mod new_layer_ui; pub mod open_prompt; diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs index 3f9e8ba19b..8af538511d 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs @@ -101,6 +101,16 @@ fn tint_stops() -> Vec { } /// One labelled slider; marks the dialog dirty when it moves. +/// The track of Color Mixer band `k` on `tab` (0 Hue, 1 Saturation, 2 Luminance). A Hue slider +/// turns its band towards the neighbouring bands, so its track runs from the previous band's hue +/// through its own to the next one's (Reds: magenta, red, orange; #9550); Saturation and Luminance +/// run from grey to the band's colour. +pub(super) fn mixer_gradient(tab: usize, k: usize) -> Vec { + let bands = &photocraft_algo::camera_raw::HSL_BANDS; + let hue = |i: usize| widgets::hue_color(bands.get(i % bands.len()).copied().unwrap_or(0.0)); + if tab == 0 { vec![hue(k + bands.len() - 1), hue(k), hue(k + 1)] } else { vec![Color32::from_gray(128), hue(k)] } +} + fn row(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive, grad: Option<&[Color32]>) { let _ = slider(ui, dirty, label, v, range, grad); } @@ -398,9 +408,7 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { _ => &mut p.hsl_lum, }; for (k, name) in BANDS.iter().enumerate() { - let c = photocraft_algo::camera_raw::HSL_BANDS[k]; - let base = widgets::hue_color(c); - let grad = [Color32::from_gray(128), base]; + let grad = mixer_gradient(d.mixer_tab, k); row(ui, &mut dirty, name, &mut arr[k], -100.0..=100.0, Some(&grad)); } }); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index fd3fc82869..bcae932f5e 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -1,5 +1,19 @@ use super::*; +/// #9550: a Color Mixer Hue track runs through the neighbouring bands' hues (Reds: magenta to +/// orange, wrapping round), not from grey; Saturation and Luminance keep grey to the colour. +#[test] +fn hue_tracks_run_between_the_neighbouring_bands() { + use super::controls::mixer_gradient; + let hue = |d: f32| widgets::hue_color(d); + assert_eq!(mixer_gradient(0, 0), vec![hue(300.0), hue(0.0), hue(30.0)], "Reds"); + assert_eq!(mixer_gradient(0, 7), vec![hue(270.0), hue(300.0), hue(0.0)], "Magentas"); + assert_eq!(mixer_gradient(0, 3), vec![hue(60.0), hue(120.0), hue(180.0)], "Greens"); + for tab in [1, 2] { + assert_eq!(mixer_gradient(tab, 3), vec![Color32::from_gray(128), hue(120.0)]); + } +} + #[test] fn preview_texture_uses_linear_document_display_encoding() { let mut doc = photocraft_doc::Document::new("test", photocraft_geom::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::F32); diff --git a/crates/ui-egui/src/dialogs/dialog_blend_ui.rs b/crates/ui-egui/src/dialogs/dialog_blend_ui.rs index 8ff086cebe..927f82891c 100644 --- a/crates/ui-egui/src/dialogs/dialog_blend_ui.rs +++ b/crates/ui-egui/src/dialogs/dialog_blend_ui.rs @@ -54,7 +54,7 @@ fn label(ui: &mut egui::Ui, text: &str) { } /// The `mode` param naming a blend mode ("normal", "colorBurn"…), parsed by the engine. -fn mode_key(m: photocraft_color::BlendMode) -> String { +pub(crate) fn mode_key(m: photocraft_color::BlendMode) -> String { let s = format!("{m:?}"); let mut c = s.chars(); c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default() diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 24b9609b20..d042a1fb6b 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -325,6 +325,7 @@ pub fn has_dialog(command: &str) -> bool { | "image.mode.colorTable" | "edit.definePattern" | "select.convertToShape" + | "layer.new.artboardFromLayers" )) && photocraft_engine::commands::find(command).is_some_and(|c| !parse_spec(c.params).is_empty()) } @@ -343,6 +344,15 @@ fn rememberable(kind: &Kind, value: &Value) -> bool { fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &mut Map) { let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(command) else { return }; + // Select and Mask starts from its defaults unless Remember Settings was on, as in Photoshop + // (#9423). + if command == crate::select_mask_view::COMMAND { + let remember = crate::select_mask_view::remembers(saved); + fields.insert(crate::select_mask_view::REMEMBER.into(), json!(remember)); + if !remember { + return; + } + } for p in parse_spec(spec) { if let Some(v) = saved.get(&p.key).filter(|v| rememberable(&p.kind, v)) { fields.insert(p.key, v.clone()); @@ -356,8 +366,17 @@ pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map = + let mut saved: Map = parse_spec(spec.params).into_iter().filter_map(|p| fields.get(&p.key).filter(|v| rememberable(&p.kind, v)).map(|v| (p.key, v.clone()))).collect(); + // Select and Mask with Remember Settings off keeps only that choice, so the next one starts + // from the defaults (#9423). + if command == crate::select_mask_view::COMMAND { + let remember = crate::select_mask_view::remembers(fields); + if !remember { + saved.clear(); + } + saved.insert(crate::select_mask_view::REMEMBER.into(), json!(remember)); + } if !saved.is_empty() { app.session.prefs.edit(|prefs| prefs.dialogs.insert(command.into(), Value::Object(saved))); } @@ -404,6 +423,17 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map) -> bool { + fields.contains_key(MARK) +} + +/// Whether the dialog fronts command `id`. +pub fn fronts(id: &str) -> bool { + id == NEW_GROUP || id == FROM_LAYERS +} + +/// Photoshop's defaults: the next "Group N", no colour, Pass Through, 100 %. Unlike Stroke the +/// choices are not remembered, as in Photoshop. +pub fn fields(app: &PhotocraftApp, command: &str) -> Map { + let name = app.session.active().map(|st| st.doc.next_layer_name("Group")).unwrap_or_else(|| "Group 1".into()); + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!(if command == FROM_LAYERS { FROM_LAYERS } else { NEW_GROUP })); + // The window title, as in Photoshop. + f.insert("__label".into(), json!(if command == FROM_LAYERS { "New Group from Layers…" } else { "New Group…" })); + f.insert("name".into(), json!(name)); + f.insert("color".into(), json!(LabelColor::None.id())); + f.insert("mode".into(), json!(crate::dialog_blend_ui::mode_key(BlendMode::PassThrough))); + f.insert("opacity".into(), json!(100.0)); + f +} + +pub fn open(app: &mut PhotocraftApp, command: &str) -> u64 { + let f = fields(app, command); + app.ui.open_dialog(crate::state::DialogKind::Command, f) +} + +/// Only the New Group params are passed to the engine; private UI markers are ignored. +pub fn params(f: &Map) -> Value { + Value::Object(KEYS.iter().filter_map(|k| f.get(*k).map(|v| (k.to_string(), v.clone()))).collect()) +} + +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + let command = f.get("__command").and_then(Value::as_str).filter(|c| fronts(c)).unwrap_or(NEW_GROUP).to_string(); + app.run(&command, params(f)) +} + +fn label(ui: &mut egui::Ui, text: &str) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(64.0, 22.0), Sense::hover()); + ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim); +} + +/// The label colour's swatch beside its menu: a crossed box for No Color, as in the layer menu. +fn swatch(ui: &mut egui::Ui, color: LabelColor) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); + let p = ui.painter(); + if let Some((fill, _)) = t.layer_label_colors(color) { + p.rect_filled(r, t.radius_sm, fill); + } else { + let stroke = egui::Stroke::new(1.0, t.text_dim); + p.rect_stroke(r, t.radius_sm, stroke, egui::StrokeKind::Inside); + let x = r.shrink(4.0); + p.line_segment([x.left_top(), x.right_bottom()], stroke); + p.line_segment([x.right_top(), x.left_bottom()], stroke); + } +} + +pub fn body(ui: &mut egui::Ui, f: &mut Map) { + ui.spacing_mut().item_spacing.y = 8.0; + ui.horizontal(|ui| { + label(ui, tl!("Name:")); + let mut name = f.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(252.0)); + if r.changed() { + f.insert("name".into(), json!(name)); + } + crate::field_tab::register(ui.ctx(), r.id); + // Photoshop opens the dialog with the name selected, so typing replaces it. + if !f.contains_key("__focused") { + f.insert("__focused".into(), json!(true)); + crate::field_tab::focus(ui.ctx(), r.id); + } + if r.gained_focus() { + crate::field_tab::select_all(ui.ctx(), r.id, &name); + } + }); + ui.horizontal(|ui| { + label(ui, tl!("Color:")); + let mut color = f.get("color").and_then(Value::as_str).and_then(LabelColor::from_id).unwrap_or(LabelColor::None); + let options: Vec<(LabelColor, &str)> = LabelColor::ALL.iter().map(|c| (*c, crate::layer_menu_ui::color_name(*c))).collect(); + if crate::widgets::dropdown(ui, "new-group-color", tl!("Color"), &mut color, &options, 130.0) { + f.insert("color".into(), json!(color.id())); + } + swatch(ui, color); + }); + ui.horizontal(|ui| { + label(ui, tl!("Mode:")); + let mut mode = f.get("mode").and_then(Value::as_str).and_then(photocraft_engine::commands::blend_from_str).unwrap_or(BlendMode::PassThrough); + let options = crate::panels::blend_options(true, mode); + if crate::widgets::dropdown(ui, "new-group-mode", tl!("Mode"), &mut mode, &options, 130.0) { + f.insert("mode".into(), json!(crate::dialog_blend_ui::mode_key(mode))); + } + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Opacity:")).size(12.0).color(Tokens::get(ui.ctx()).text_dim)); + let mut opacity = f.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32; + if crate::widgets::value_field(ui, &mut opacity, 0.0..=100.0, "%", 64.0).changed() { + f.insert("opacity".into(), json!(opacity.round())); + } + }); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/new_group_ui/tests.rs b/crates/ui-egui/src/dialogs/new_group_ui/tests.rs new file mode 100644 index 0000000000..2ff93afd3d --- /dev/null +++ b/crates/ui-egui/src/dialogs/new_group_ui/tests.rs @@ -0,0 +1,136 @@ +use photocraft_color::BlendMode; +use photocraft_doc::{LabelColor, Layer, LayerContent, LayerId}; +use serde_json::json; + +use super::*; + +/// Background, then `A` and `B` (`B` active). +fn app() -> (PhotocraftApp, LayerId, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + let a = LayerId(app.run("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap()); + let b = LayerId(app.run("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + (app, a, b) +} + +fn groups(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).cloned().collect() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn menu_invocations_open_the_dialog_but_explicit_params_run_directly() { + let (mut app, _, _) = app(); + let ctx = egui::Context::default(); + for (command, title) in [(NEW_GROUP, "New Group…"), (FROM_LAYERS, "New Group from Layers…")] { + let opened = crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); + let id = opened["dialog"].as_u64().unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert!(owns(fields)); + assert_eq!((fields["__command"].as_str(), fields["__label"].as_str()), (Some(command), Some(title))); + assert!(groups(&app).is_empty(), "nothing happens until OK"); + app.ui.close_dialog(id); + // `ui.dialog.open {kind: "command"}` gets the same dialog. + let id = crate::dialogs::open_command_dialog(&mut app, command, "Group…"); + assert!(owns(&app.ui.dialogs.last().unwrap().fields)); + app.ui.close_dialog(id); + } + // Explicit params (Actions, CLI, MCP) run the engine without asking. + crate::menus::invoke(&mut app, &ctx, NEW_GROUP, json!({"name": "Direct"})).unwrap(); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(groups(&app)[0].name, "Direct"); + // Group Layers (⌘G) never asks. + crate::menus::invoke(&mut app, &ctx, "layer.groupLayers", json!({})).unwrap(); + assert!(app.ui.dialogs.is_empty()); + // Without a document nothing opens. + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert!(crate::menus::invoke(&mut empty, &ctx, NEW_GROUP, json!({})).is_err()); + assert!(crate::menus::invoke(&mut empty, &ctx, FROM_LAYERS, json!({})).is_err()); + assert!(empty.ui.dialogs.is_empty()); +} + +#[test] +fn defaults_are_photoshops_and_private_fields_do_not_leak() { + let (app, _, _) = app(); + let f = fields(&app, NEW_GROUP); + let out = params(&f); + assert_eq!(out, json!({"name": "Group 1", "color": "none", "mode": "passThrough", "opacity": 100.0})); + assert!(out.as_object().unwrap().keys().all(|k| !k.starts_with("__"))); +} + +#[test] +fn ok_creates_the_group_with_the_options_in_one_step_and_cancel_changes_nothing() { + let (mut app, _, b) = app(); + let initial = steps(&app); + let cancelled = open(&mut app, NEW_GROUP); + app.ui.dialog_mut(cancelled).unwrap().fields.insert("name".into(), json!("Nope")); + app.ui.close_dialog(cancelled); + assert_eq!(steps(&app), initial); + assert!(groups(&app).is_empty()); + + let id = open(&mut app, NEW_GROUP); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("name".into(), json!("Sky")); + d.fields.insert("color".into(), json!("blue")); + d.fields.insert("mode".into(), json!("multiply")); + d.fields.insert("opacity".into(), json!(60.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(steps(&app), initial + 1, "one history step"); + let g = &groups(&app)[0]; + assert_eq!((g.name.as_str(), g.label, g.blend), ("Sky", LabelColor::Blue, BlendMode::Multiply)); + assert!((g.opacity - 0.6).abs() < 1e-6); + let top: Vec = app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top.last(), Some(&g.id), "an empty group above the active layer B"); + assert_eq!(top[top.len() - 2], b); +} + +#[test] +fn ok_from_layers_groups_the_selection_collapsed() { + let (mut app, a, b) = app(); + app.run("layer.select", json!({"layer": a.0})).unwrap(); + app.run("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let id = open(&mut app, FROM_LAYERS); + app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("Pair")); + crate::dialogs::confirm(&mut app, id).unwrap(); + let g = &groups(&app)[0]; + assert_eq!(g.name, "Pair"); + assert_eq!(g.children().unwrap().iter().map(|l| l.id).collect::>(), vec![a, b]); + assert!(matches!(&g.content, LayerContent::Group(g) if !g.expanded), "collapsed, as in Photoshop"); +} + +/// The dialog draws its fields, opens with the name selected so typing replaces it, and Enter +/// runs OK. +#[test] +fn typing_replaces_the_selected_name_and_enter_confirms() { + use egui_kittest::kittest::Queryable; + let (app, _, _) = app(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), NEW_GROUP); + h.run_steps(4); + for label in ["OK", "Cancel"] { + assert!(h.query_by_label(label).is_some(), "{label} is shown"); + } + let name = h.get_by_role(egui::accesskit::Role::TextInput); + assert!(name.is_focused(), "the dialog opens on the name"); + name.type_text("Clouds"); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.last().unwrap().fields["name"], "Clouds"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(groups(h.state())[0].name, "Clouds"); +} + +#[test] +fn new_group_dialog_labels_are_translated_in_every_catalog() { + const LABELS: &[&str] = &["New Group…", "New Group from Layers…", "Name:", "Color:", "Mode:", "Opacity:", "Pass Through"]; + for lang in crate::i18n::Lang::all().filter(|lang| lang.complete_menus()) { + for label in LABELS { + assert!(crate::i18n::has(lang, label), "{} is missing New Group dialog label: {label}", lang.code()); + } + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3d40d04d18..ad024ccd97 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -312,6 +312,7 @@ Layer… Vrstva… Group… Skupina… Group from Layers… Skupina z vrstev… + New Group from Layers… Nová skupina z vrstev… Artboard… Kreslicí plocha… Artboard from Group… Kreslicí plocha ze skupiny… Artboard from Layers… Kreslicí plocha z vrstev… @@ -3863,6 +3864,33 @@ navigator Zoom Zvětšení Sent to {printer} Odesláno do {printer} set in Print Settings… nastavuje se v nastavení tisku… ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů + Show Favorite Fonts Zobrazit oblíbená písma + No favorite fonts yet: click the star beside a font to add it. Zatím žádná oblíbená písma: přidejte písmo kliknutím na hvězdičku vedle něj. + Favorite fonts Oblíbená písma + Add to Favorites Přidat do oblíbených + Remove from Favorites Odebrat z oblíbených + Show All Fonts Zobrazit všechna písma + All Classes Všechny třídy + Blackletter Lomená písma + Decorative Dekorativní + Font preview: Náhled písma: + Handwritten Ručně psaná + Hide Font Classes Skrýt třídy písem + Hide Styles Skrýt řezy + Monospace Neproporcionální + No fonts match these filters. Filtrům neodpovídají žádná písma. + No similar fonts: the current font doesn't say what it looks like. Žádná podobná písma: u aktuálního písma chybí popis vzhledu. + OpenType font Písmo OpenType + Sans Serif Bezpatková + Script Skriptová + Serif Patková + Show Font Classes Zobrazit třídy písem + Show Similar Fonts Zobrazit podobná písma + Show Styles Zobrazit řezy + Show Variable Fonts Zobrazit variabilní písma + Slab Serif Slabová patková + TrueType font Písmo TrueType + Variable font Variabilní písmo Calibration Kalibrace Red Primary Červená základní Green Primary Zelená základní @@ -4204,3 +4232,6 @@ cameraRaw Dehaze Odstranění oparu # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Poměr stran + Font size presets Předvolby velikosti písma + Leading presets Předvolby prokladu + Tracking presets Předvolby prostrkání diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 418125859b..c1dfc027ed 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -311,6 +311,7 @@ Layer… Ebene… Group… Gruppe… Group from Layers… Gruppe aus Ebenen… + New Group from Layers… Neue Gruppe aus Ebenen… Artboard… Zeichenbereich… Artboard from Group… Zeichenbereich aus Gruppe… Artboard from Layers… Zeichenbereich aus Ebenen… @@ -3267,6 +3268,33 @@ curves Smooth Glätten Sent to {printer} An {printer} gesendet set in Print Settings… in den Druckeinstellungen festlegen… ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt + Show Favorite Fonts Favorisierte Schriften anzeigen + No favorite fonts yet: click the star beside a font to add it. Noch keine favorisierten Schriften: Klicken Sie auf den Stern neben einer Schrift, um sie hinzuzufügen. + Favorite fonts Favorisierte Schriften + Add to Favorites Zu Favoriten hinzufügen + Remove from Favorites Aus Favoriten entfernen + Show All Fonts Alle Schriften anzeigen + All Classes Alle Klassen + Blackletter Gebrochene Schriften + Decorative Dekorativ + Font preview: Schriftvorschau: + Handwritten Handschriftlich + Hide Font Classes Schriftklassen ausblenden + Hide Styles Schnitte ausblenden + Monospace Nichtproportional + No fonts match these filters. Keine Schriften entsprechen diesen Filtern. + No similar fonts: the current font doesn't say what it looks like. Keine ähnlichen Schriften: Die aktuelle Schrift beschreibt ihr Aussehen nicht. + OpenType font OpenType-Schrift + Sans Serif Serifenlos + Script Schreibschrift + Serif Serifen + Show Font Classes Schriftklassen einblenden + Show Similar Fonts Ähnliche Schriften anzeigen + Show Styles Schnitte einblenden + Show Variable Fonts Variable Schriften anzeigen + Slab Serif Serifenbetont + TrueType font TrueType-Schrift + Variable font Variable Schrift Calibration Kalibrierung Red Primary Rot-Primärfarbe Green Primary Grün-Primärfarbe @@ -3478,3 +3506,6 @@ curves Smooth Glätten Interpolation Interpolation Target Ziel Units Einheiten + Font size presets Schriftgrößen-Vorgaben + Leading presets Zeilenabstand-Vorgaben + Tracking presets Laufweiten-Vorgaben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3e7e7390fa..b2b35dbbdc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -224,6 +224,7 @@ Tools… Εργαλεία… History Log… Καταγραφή ιστορικού… Group from Layers… Ομαδοποίηση από επίπεδα… + New Group from Layers… Νέα ομάδα από επίπεδα… Artboard from Layers… Πίνακας σχεδίασης από επίπεδα… Delete Filter Mask Διαγραφή μάσκας φίλτρου Disable Filter Mask Απενεργοποίηση μάσκας φίλτρου @@ -3949,6 +3950,33 @@ curves Smooth Εξομάλυνση Sent to {printer} Στάλθηκε στον {printer} set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης… ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία + Show Favorite Fonts Εμφάνιση αγαπημένων γραμματοσειρών + No favorite fonts yet: click the star beside a font to add it. Δεν υπάρχουν ακόμη αγαπημένες γραμματοσειρές: κάντε κλικ στο αστέρι δίπλα σε μια γραμματοσειρά για να την προσθέσετε. + Favorite fonts Αγαπημένες γραμματοσειρές + Add to Favorites Προσθήκη στα αγαπημένα + Remove from Favorites Αφαίρεση από τα αγαπημένα + Show All Fonts Εμφάνιση όλων των γραμματοσειρών + All Classes Όλες οι κατηγορίες + Blackletter Γοτθικές + Decorative Διακοσμητικές + Font preview: Προεπισκόπηση γραμματοσειράς: + Handwritten Χειρόγραφες + Hide Font Classes Απόκρυψη κατηγοριών γραμματοσειρών + Hide Styles Απόκρυψη στυλ + Monospace Σταθερού πλάτους + No fonts match these filters. Καμία γραμματοσειρά δεν ταιριάζει με αυτά τα φίλτρα. + No similar fonts: the current font doesn't say what it looks like. Καμία παρόμοια γραμματοσειρά: η τρέχουσα γραμματοσειρά δεν περιγράφει την εμφάνισή της. + OpenType font Γραμματοσειρά OpenType + Sans Serif Χωρίς πατούρες + Script Καλλιγραφικές + Serif Με πατούρες + Show Font Classes Εμφάνιση κατηγοριών γραμματοσειρών + Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών + Show Styles Εμφάνιση στυλ + Show Variable Fonts Εμφάνιση μεταβλητών γραμματοσειρών + Slab Serif Με πλακοειδείς πατούρες + TrueType font Γραμματοσειρά TrueType + Variable font Μεταβλητή γραμματοσειρά Calibration Βαθμονόμηση Red Primary Κόκκινο πρωτεύον Green Primary Πράσινο πρωτεύον @@ -4157,3 +4185,6 @@ curves Smooth Εξομάλυνση # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Στόχος + Font size presets Προεπιλογές μεγέθους γραμματοσειράς + Leading presets Προεπιλογές διάστιχου + Tracking presets Προεπιλογές διαστήματος χαρακτήρων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index acacb0402a..b42f3be02c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -308,6 +308,7 @@ Layer… Capa… Group… Grupo… Group from Layers… Grupo a partir de capas… + New Group from Layers… Nuevo grupo a partir de capas… Artboard… Mesa de trabajo… Artboard from Group… Mesa de trabajo a partir de grupo… Artboard from Layers… Mesa de trabajo a partir de capas… @@ -4212,6 +4213,33 @@ navigator Zoom Zoom Sent to {printer} Enviado a {printer} set in Print Settings… se establece en Ajustes de impresión… ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles + Show Favorite Fonts Mostrar fuentes favoritas + No favorite fonts yet: click the star beside a font to add it. Aún no hay fuentes favoritas: haz clic en la estrella junto a una fuente para añadirla. + Favorite fonts Fuentes favoritas + Add to Favorites Añadir a favoritos + Remove from Favorites Quitar de favoritos + Show All Fonts Mostrar todas las fuentes + All Classes Todas las clases + Blackletter Gótica + Decorative Decorativa + Font preview: Vista previa de fuente: + Handwritten Manuscrita + Hide Font Classes Ocultar clases de fuente + Hide Styles Ocultar estilos + Monospace Monoespaciada + No fonts match these filters. Ninguna fuente coincide con estos filtros. + No similar fonts: the current font doesn't say what it looks like. No hay fuentes similares: la fuente actual no describe su aspecto. + OpenType font Fuente OpenType + Sans Serif Sans serif + Script Caligráfica + Serif Serif + Show Font Classes Mostrar clases de fuente + Show Similar Fonts Mostrar fuentes similares + Show Styles Mostrar estilos + Show Variable Fonts Mostrar fuentes variables + Slab Serif Serif egipcia + TrueType font Fuente TrueType + Variable font Fuente variable Calibration Calibración Red Primary Primario rojo Green Primary Primario verde @@ -4416,3 +4444,6 @@ navigator Zoom Zoom Tight Curl Rizo apretado Loose Curl Rizo suelto Stylized dabs from a history state Toques estilizados desde un estado del historial + Font size presets Valores predefinidos de tamaño de fuente + Leading presets Valores predefinidos de interlineado + Tracking presets Valores predefinidos de tracking diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4b481366ed..3bad30d474 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -304,6 +304,7 @@ Layer… Calque… Group… Groupe… Group from Layers… Groupe d'après des calques… + New Group from Layers… Nouveau groupe d'après des calques… Artboard… Plan de travail… Artboard from Group… Plan de travail d'après un groupe… Artboard from Layers… Plan de travail d'après des calques… @@ -3259,6 +3260,33 @@ curves Smooth Lisser Sent to {printer} Envoyé à {printer} set in Print Settings… défini dans les paramètres d’impression… ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels + Show Favorite Fonts Afficher les polices favorites + No favorite fonts yet: click the star beside a font to add it. Aucune police favorite pour l’instant : cliquez sur l’étoile à côté d’une police pour l’ajouter. + Favorite fonts Polices favorites + Add to Favorites Ajouter aux favoris + Remove from Favorites Retirer des favoris + Show All Fonts Afficher toutes les polices + All Classes Toutes les classes + Blackletter Gothique + Decorative Décorative + Font preview: Aperçu de la police : + Handwritten Manuscrite + Hide Font Classes Masquer les classes de polices + Hide Styles Masquer les styles + Monospace Chasse fixe + No fonts match these filters. Aucune police ne correspond à ces filtres. + No similar fonts: the current font doesn't say what it looks like. Aucune police similaire : la police actuelle ne décrit pas son apparence. + OpenType font Police OpenType + Sans Serif Sans empattement + Script Scripte + Serif Avec empattement + Show Font Classes Afficher les classes de polices + Show Similar Fonts Afficher les polices similaires + Show Styles Afficher les styles + Show Variable Fonts Afficher les polices variables + Slab Serif Égyptienne + TrueType font Police TrueType + Variable font Police variable Calibration Étalonnage Red Primary Primaire rouge Green Primary Primaire verte @@ -4496,3 +4524,6 @@ shape Appearance Apparence Tight Curl Boucle serrée Loose Curl Boucle lâche Stylized dabs from a history state Touches stylisées depuis un état d'historique + Font size presets Tailles de police prédéfinies + Leading presets Interlignages prédéfinis + Tracking presets Approches prédéfinies diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9fb897d482..d632cb52f1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3419,6 +3419,7 @@ cameraRaw Yellow Sárga New Document With Mask Új dokumentum maszkkal New document… Új dokumentum… New Group Új csoport + New Group from Layers… Új csoport rétegekből… New Guide Új segédvonal New Layer Új réteg New Layer Comp Új rétegkompozíció @@ -4156,6 +4157,33 @@ cameraRaw Yellow Sárga Kept {name}: written by another application {name} megtartva: egy másik alkalmazás írta Shadow Tint Árnyék színezet Redrawing Újrarajzolás + Show Favorite Fonts Kedvenc betűtípusok megjelenítése + No favorite fonts yet: click the star beside a font to add it. Még nincsenek kedvenc betűtípusok: kattintson a betűtípus melletti csillagra a hozzáadáshoz. + Favorite fonts Kedvenc betűtípusok + Add to Favorites Hozzáadás a kedvencekhez + Remove from Favorites Eltávolítás a kedvencek közül + Show All Fonts Összes betűtípus megjelenítése + All Classes Összes osztály + Blackletter Gót betűs + Decorative Díszítő + Font preview: Betűtípus előnézete: + Handwritten Kézírásos + Hide Font Classes Betűtípus-osztályok elrejtése + Hide Styles Stílusok elrejtése + Monospace Fix szélességű + No fonts match these filters. Egy betűtípus sem felel meg ezeknek a szűrőknek. + No similar fonts: the current font doesn't say what it looks like. Nincsenek hasonló betűtípusok: a jelenlegi betűtípus nem írja le a megjelenését. + OpenType font OpenType betűtípus + Sans Serif Talpatlan + Script Írott + Serif Talpas + Show Font Classes Betűtípus-osztályok megjelenítése + Show Similar Fonts Hasonló betűtípusok megjelenítése + Show Styles Stílusok megjelenítése + Show Variable Fonts Változó betűtípusok megjelenítése + Slab Serif Talpas (szögletes) + TrueType font TrueType betűtípus + Variable font Változó betűtípus # Bevel & Emboss shading controls. Highlight Mode Csúcsfény módja Highlight Color Csúcsfény színe @@ -4368,3 +4396,6 @@ cameraRaw Yellow Sárga Tight Curl Szoros göndör Loose Curl Laza göndör Stylized dabs from a history state Stilizált pöttyök egy előzményállapotból + Font size presets Betűméret-előbeállítások + Leading presets Sorköz-előbeállítások + Tracking presets Betűköz-előbeállítások diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0fa31a8ebd..771e04e80a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -297,6 +297,7 @@ Layer… Layer… Group… Grup… Group from Layers… Grup dari Layer… + New Group from Layers… Grup Baru dari Layer… Artboard… Artboard… Artboard from Group… Artboard dari Grup… Artboard from Layers… Artboard dari Layer… @@ -3262,6 +3263,33 @@ curves Smooth Haluskan Sent to {printer} Dikirim ke {printer} set in Print Settings… diatur di Pengaturan Cetak… ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel + Show Favorite Fonts Tampilkan Font Favorit + No favorite fonts yet: click the star beside a font to add it. Belum ada font favorit: klik bintang di samping font untuk menambahkannya. + Favorite fonts Font favorit + Add to Favorites Tambahkan ke Favorit + Remove from Favorites Hapus dari Favorit + Show All Fonts Tampilkan Semua Font + All Classes Semua Kelas + Blackletter Blackletter + Decorative Dekoratif + Font preview: Pratinjau font: + Handwritten Tulisan tangan + Hide Font Classes Sembunyikan Kelas Font + Hide Styles Sembunyikan Gaya + Monospace Monospasi + No fonts match these filters. Tidak ada font yang cocok dengan filter ini. + No similar fonts: the current font doesn't say what it looks like. Tidak ada font serupa: font saat ini tidak menjelaskan tampilannya. + OpenType font Font OpenType + Sans Serif Sans Serif + Script Skrip + Serif Serif + Show Font Classes Tampilkan Kelas Font + Show Similar Fonts Tampilkan Font Serupa + Show Styles Tampilkan Gaya + Show Variable Fonts Tampilkan Font Variabel + Slab Serif Slab Serif + TrueType font Font TrueType + Variable font Font variabel Calibration Kalibrasi Red Primary Primer merah Green Primary Primer hijau @@ -3476,3 +3504,6 @@ curves Smooth Haluskan Gamma Gamma Profile Profil Target Target + Font size presets Preset ukuran font + Leading presets Preset leading + Tracking presets Preset tracking diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ea51deccb5..b1598ac237 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -305,6 +305,7 @@ Layer… Livello… Group… Gruppo… Group from Layers… Gruppo da livelli… + New Group from Layers… Nuovo gruppo da livelli… Artboard… Tavola da disegno… Artboard from Group… Tavola da gruppo… Artboard from Layers… Tavola da livelli… @@ -4215,6 +4216,33 @@ navigator Zoom Zoom Sent to {printer} Inviato a {printer} set in Print Settings… impostato nelle impostazioni di stampa… ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel + Show Favorite Fonts Mostra font preferiti + No favorite fonts yet: click the star beside a font to add it. Ancora nessun font preferito: fai clic sulla stella accanto a un font per aggiungerlo. + Favorite fonts Font preferiti + Add to Favorites Aggiungi ai preferiti + Remove from Favorites Rimuovi dai preferiti + Show All Fonts Mostra tutti i font + All Classes Tutte le classi + Blackletter Gotico + Decorative Decorativo + Font preview: Anteprima font: + Handwritten Scrittura a mano + Hide Font Classes Nascondi classi di font + Hide Styles Nascondi stili + Monospace Monospaziato + No fonts match these filters. Nessun font corrisponde a questi filtri. + No similar fonts: the current font doesn't say what it looks like. Nessun font simile: il font corrente non descrive il proprio aspetto. + OpenType font Font OpenType + Sans Serif Senza grazie + Script Corsivo calligrafico + Serif Con grazie + Show Font Classes Mostra classi di font + Show Similar Fonts Mostra font simili + Show Styles Mostra stili + Show Variable Fonts Mostra font variabili + Slab Serif Egiziano + TrueType font Font TrueType + Variable font Font variabile Calibration Calibrazione Red Primary Primario rosso Green Primary Primario verde @@ -4571,3 +4599,6 @@ shape Appearance Aspetto Tight Curl Riccio stretto Loose Curl Riccio largo Stylized dabs from a history state Tocchi stilizzati da uno stato della storia + Font size presets Predefiniti dimensione font + Leading presets Predefiniti interlinea + Tracking presets Predefiniti spaziatura diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6d96eeaa2d..435813b0c7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -307,6 +307,7 @@ Layer… レイヤー… Group… グループ… Group from Layers… レイヤーからグループ… + New Group from Layers… レイヤーから新規グループ… Artboard… アートボード… Artboard from Group… グループからアートボード… Artboard from Layers… レイヤーからアートボード… @@ -3930,6 +3931,33 @@ curves Smooth スムーズ Reset All Locked Settings ロックされた設定をすべて初期化 Copy Texture to Other Tools テクスチャを他のツールにコピー ICO is limited to 256 × 256 pixels ICO は 256 × 256 ピクセルまでです + Show Favorite Fonts お気に入りのフォントを表示 + No favorite fonts yet: click the star beside a font to add it. お気に入りのフォントはまだありません。フォントの横の星をクリックして追加してください。 + Favorite fonts お気に入りのフォント + Add to Favorites お気に入りに追加 + Remove from Favorites お気に入りから削除 + Show All Fonts すべてのフォントを表示 + All Classes すべての分類 + Blackletter ブラックレター + Decorative 装飾 + Font preview: フォントのプレビュー: + Handwritten 手書き + Hide Font Classes フォントの分類を隠す + Hide Styles スタイルを隠す + Monospace 等幅 + No fonts match these filters. このフィルターに一致するフォントはありません。 + No similar fonts: the current font doesn't say what it looks like. 類似フォントはありません。現在のフォントは外観の情報を持っていません。 + OpenType font OpenType フォント + Sans Serif サンセリフ + Script スクリプト + Serif セリフ + Show Font Classes フォントの分類を表示 + Show Similar Fonts 類似フォントを表示 + Show Styles スタイルを表示 + Show Variable Fonts バリアブルフォントを表示 + Slab Serif スラブセリフ + TrueType font TrueType フォント + Variable font バリアブルフォント Calibration キャリブレーション Red Primary レッド原色 Green Primary グリーン原色 @@ -4133,3 +4161,6 @@ curves Smooth スムーズ Tight Curl タイトカール Loose Curl ルーズカール Stylized dabs from a history state 履歴状態から様式化したダブを描きます + Font size presets フォントサイズのプリセット + Leading presets 行送りのプリセット + Tracking presets トラッキングのプリセット diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 85abdc30ec..30ab8cb165 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -294,6 +294,7 @@ Layer… 레이어… Group… 그룹… Group from Layers… 레이어로 그룹 만들기… + New Group from Layers… 레이어에서 새 그룹… Artboard… 아트보드… Artboard from Group… 그룹으로 아트보드 만들기… Artboard from Layers… 레이어로 아트보드 만들기… @@ -3454,6 +3455,33 @@ curves Smooth 매끄럽게 Sent to {printer} {printer}(으)로 전송됨 set in Print Settings… 인쇄 설정에서 지정… ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 + Show Favorite Fonts 즐겨찾는 글꼴 표시 + No favorite fonts yet: click the star beside a font to add it. 아직 즐겨찾는 글꼴이 없습니다. 글꼴 옆의 별을 클릭하여 추가하세요. + Favorite fonts 즐겨찾는 글꼴 + Add to Favorites 즐겨찾기에 추가 + Remove from Favorites 즐겨찾기에서 제거 + Show All Fonts 모든 글꼴 표시 + All Classes 모든 분류 + Blackletter 블랙레터 + Decorative 장식 + Font preview: 글꼴 미리 보기: + Handwritten 손글씨 + Hide Font Classes 글꼴 분류 숨기기 + Hide Styles 스타일 숨기기 + Monospace 고정폭 + No fonts match these filters. 이 필터와 일치하는 글꼴이 없습니다. + No similar fonts: the current font doesn't say what it looks like. 비슷한 글꼴 없음: 현재 글꼴에 모양 정보가 없습니다. + OpenType font OpenType 글꼴 + Sans Serif 산세리프 + Script 스크립트 + Serif 세리프 + Show Font Classes 글꼴 분류 표시 + Show Similar Fonts 비슷한 글꼴 표시 + Show Styles 스타일 표시 + Show Variable Fonts 가변 글꼴 표시 + Slab Serif 슬래브 세리프 + TrueType font TrueType 글꼴 + Variable font 가변 글꼴 Calibration 보정 Red Primary 빨강 원색 Green Primary 녹색 원색 @@ -3673,3 +3701,6 @@ curves Smooth 매끄럽게 Category 카테고리 Target 대상 Units 단위 + Font size presets 글꼴 크기 사전 설정 + Leading presets 행간 사전 설정 + Tracking presets 자간 사전 설정 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3fb8ee4399..d03260ecaf 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -298,6 +298,7 @@ Layer… Laag… Group… Groep… Group from Layers… Groep uit lagen… + New Group from Layers… Nieuwe groep uit lagen… Artboard… Tekengebied… Artboard from Group… Tekengebied uit groep… Artboard from Layers… Tekengebied uit lagen… @@ -4011,6 +4012,33 @@ curves Smooth Vloeiend maken Sent to {printer} Verzonden naar {printer} set in Print Settings… instellen in de afdrukinstellingen… ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels + Show Favorite Fonts Favoriete lettertypen tonen + No favorite fonts yet: click the star beside a font to add it. Nog geen favoriete lettertypen: klik op de ster naast een lettertype om het toe te voegen. + Favorite fonts Favoriete lettertypen + Add to Favorites Toevoegen aan favorieten + Remove from Favorites Verwijderen uit favorieten + Show All Fonts Alle lettertypen tonen + All Classes Alle klassen + Blackletter Gebroken letter + Decorative Decoratief + Font preview: Lettertypevoorbeeld: + Handwritten Handgeschreven + Hide Font Classes Lettertypeklassen verbergen + Hide Styles Stijlen verbergen + Monospace Monospace + No fonts match these filters. Geen lettertypen voldoen aan deze filters. + No similar fonts: the current font doesn't say what it looks like. Geen vergelijkbare lettertypen: het huidige lettertype beschrijft zijn uiterlijk niet. + OpenType font OpenType-lettertype + Sans Serif Schreefloos + Script Script + Serif Schreef + Show Font Classes Lettertypeklassen tonen + Show Similar Fonts Vergelijkbare lettertypen tonen + Show Styles Stijlen tonen + Show Variable Fonts Variabele lettertypen tonen + Slab Serif Slab-schreef + TrueType font TrueType-lettertype + Variable font Variabel lettertype Calibration Kalibratie Red Primary Primair rood Green Primary Primair groen @@ -4214,3 +4242,6 @@ curves Smooth Vloeiend maken Tight Curl Strakke krul Loose Curl Losse krul Stylized dabs from a history state Gestileerde tikken uit een historiestatus + Font size presets Voorinstellingen lettergrootte + Leading presets Voorinstellingen interlinie + Tracking presets Voorinstellingen spatiëring diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fdd468523a..ba41a4e34d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -305,6 +305,7 @@ Layer… Warstwa… Group… Grupa… Group from Layers… Grupa z warstw… + New Group from Layers… Nowa grupa z warstw… Artboard… Obszar roboczy… Artboard from Group… Obszar roboczy z grupy… Artboard from Layers… Obszar roboczy z warstw… @@ -3866,6 +3867,33 @@ curves Smooth Wygładź Sent to {printer} Wysłano do {printer} set in Print Settings… ustawiane w ustawieniach druku… ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli + Show Favorite Fonts Pokaż ulubione czcionki + No favorite fonts yet: click the star beside a font to add it. Brak ulubionych czcionek: kliknij gwiazdkę obok czcionki, aby ją dodać. + Favorite fonts Ulubione czcionki + Add to Favorites Dodaj do ulubionych + Remove from Favorites Usuń z ulubionych + Show All Fonts Pokaż wszystkie czcionki + All Classes Wszystkie klasy + Blackletter Pismo gotyckie + Decorative Ozdobne + Font preview: Podgląd czcionki: + Handwritten Odręczne + Hide Font Classes Ukryj klasy czcionek + Hide Styles Ukryj style + Monospace O stałej szerokości + No fonts match these filters. Żadna czcionka nie pasuje do tych filtrów. + No similar fonts: the current font doesn't say what it looks like. Brak podobnych czcionek: bieżąca czcionka nie opisuje swojego wyglądu. + OpenType font Czcionka OpenType + Sans Serif Bezszeryfowe + Script Pisane + Serif Szeryfowe + Show Font Classes Pokaż klasy czcionek + Show Similar Fonts Pokaż podobne czcionki + Show Styles Pokaż style + Show Variable Fonts Pokaż czcionki zmienne + Slab Serif Szeryfowe prostokątne + TrueType font Czcionka TrueType + Variable font Czcionka zmienna Calibration Kalibracja Red Primary Czerwień podstawowa Green Primary Zieleń podstawowa @@ -4074,3 +4102,6 @@ curves Smooth Wygładź # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Cel + Font size presets Ustawienia wstępne rozmiaru czcionki + Leading presets Ustawienia wstępne interlinii + Tracking presets Ustawienia wstępne światła diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f3e38e1e27..f3335cd9c6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -299,6 +299,7 @@ Layer… Camada… Group… Grupo… Group from Layers… Grupo a partir de camadas… + New Group from Layers… Novo grupo a partir de camadas… Artboard… Prancheta… Artboard from Group… Prancheta a partir de grupo… Artboard from Layers… Prancheta a partir de camadas… @@ -4041,6 +4042,33 @@ layerLabel No Color Sem cor Sent to {printer} Enviado para {printer} set in Print Settings… definido nas configurações de impressão… ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels + Show Favorite Fonts Mostrar fontes favoritas + No favorite fonts yet: click the star beside a font to add it. Ainda não há fontes favoritas: clique na estrela ao lado de uma fonte para adicioná-la. + Favorite fonts Fontes favoritas + Add to Favorites Adicionar aos favoritos + Remove from Favorites Remover dos favoritos + Show All Fonts Mostrar todas as fontes + All Classes Todas as classes + Blackletter Gótica + Decorative Decorativa + Font preview: Visualização da fonte: + Handwritten Manuscrita + Hide Font Classes Ocultar classes de fonte + Hide Styles Ocultar estilos + Monospace Monoespaçada + No fonts match these filters. Nenhuma fonte corresponde a estes filtros. + No similar fonts: the current font doesn't say what it looks like. Nenhuma fonte semelhante: a fonte atual não descreve sua aparência. + OpenType font Fonte OpenType + Sans Serif Sem serifa + Script Cursiva + Serif Com serifa + Show Font Classes Mostrar classes de fonte + Show Similar Fonts Mostrar fontes semelhantes + Show Styles Mostrar estilos + Show Variable Fonts Mostrar fontes variáveis + Slab Serif Serifa egípcia + TrueType font Fonte TrueType + Variable font Fonte variável Calibration Calibração Red Primary Primária vermelha Green Primary Primária verde @@ -4384,3 +4412,6 @@ layerLabel No Color Sem cor Tight Curl Curva cerrada Loose Curl Curva solta Stylized dabs from a history state Toques estilizados a partir de um estado do histórico + Font size presets Predefinições de tamanho da fonte + Leading presets Predefinições de entrelinha + Tracking presets Predefinições de tracking diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8d86a06979..b74c398312 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -190,9 +190,10 @@ Background from Layer Фон из слоя Background From Layer Фон из слоя Group Layers Сгруппировать слои - Group… Группировать… + Group… Группа… Ungroup Layers Разгруппировать слои Group from Layers… Группа из слоёв… + New Group from Layers… Новая группа из слоёв… Hide Layers Скрыть слои Arrange Упорядочить Bring to Front На передний план @@ -3239,6 +3240,33 @@ curves Smooth Сгладить Gray Value (Median) Уровень серого (медиана) Integrated Density Интегральная плотность Length Длина + Show Favorite Fonts Показать избранные шрифты + No favorite fonts yet: click the star beside a font to add it. Избранных шрифтов пока нет: нажмите на звёздочку рядом со шрифтом, чтобы добавить его. + Favorite fonts Избранные шрифты + Add to Favorites Добавить в избранное + Remove from Favorites Удалить из избранного + Show All Fonts Показать все шрифты + All Classes Все классы + Blackletter Готические + Decorative Декоративные + Font preview: Предпросмотр шрифта: + Handwritten Рукописные + Hide Font Classes Скрыть классы шрифтов + Hide Styles Скрыть начертания + Monospace Моноширинные + No fonts match these filters. Нет шрифтов, подходящих под эти фильтры. + No similar fonts: the current font doesn't say what it looks like. Нет похожих шрифтов: текущий шрифт не описывает свой вид. + OpenType font Шрифт OpenType + Sans Serif Без засечек + Script Каллиграфические + Serif С засечками + Show Font Classes Показать классы шрифтов + Show Similar Fonts Показать похожие шрифты + Show Styles Показать начертания + Show Variable Fonts Показать вариативные шрифты + Slab Serif С брусковыми засечками + TrueType font Шрифт TrueType + Variable font Вариативный шрифт # Bevel & Emboss shading controls. Highlight Mode Режим светлых тонов Highlight Color Цвет светлых тонов @@ -4657,3 +4685,6 @@ shape Appearance Оформление Tight Curl Плотный завиток Loose Curl Свободный завиток Stylized dabs from a history state Стилизованные мазки из состояния истории + Font size presets Наборы размеров шрифта + Leading presets Наборы интерлиньяжа + Tracking presets Наборы трекинга diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 3a62b455ab..a81eb06da2 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2238,6 +2238,7 @@ Create new set Napravi novi skup Technology Previews Probne tehnologije New Group Nova grupa + New Group from Layers… Nova grupa od slojeva… Layer Comp Kompozicija slojeva Create new layer Napravi novi sloj Group · {n} layer Grupa · slojeva: {n} @@ -4290,6 +4291,33 @@ shape Appearance Izgled Kept {name}: written by another application {name} je zadržan: upisala ga je druga aplikacija Shadow Tint Nijansa senki Redrawing Ponovno iscrtavanje + Show Favorite Fonts Прикажи омиљене фонтове + No favorite fonts yet: click the star beside a font to add it. Још нема омиљених фонтова: кликните на звездицу поред фонта да бисте га додали. + Favorite fonts Омиљени фонтови + Add to Favorites Додај у омиљене + Remove from Favorites Уклони из омиљених + Show All Fonts Прикажи све фонтове + All Classes Све класе + Blackletter Готица + Decorative Декоративни + Font preview: Преглед фонта: + Handwritten Рукописни + Hide Font Classes Сакриј класе фонтова + Hide Styles Сакриј стилове + Monospace Фиксне ширине + No fonts match these filters. Ниједан фонт не одговара овим филтерима. + No similar fonts: the current font doesn't say what it looks like. Нема сличних фонтова: тренутни фонт не описује свој изглед. + OpenType font OpenType фонт + Sans Serif Без серифа + Script Скрипт + Serif Са серифима + Show Font Classes Прикажи класе фонтова + Show Similar Fonts Прикажи сличне фонтове + Show Styles Прикажи стилове + Show Variable Fonts Прикажи варијабилне фонтове + Slab Serif Плочасти серифи + TrueType font TrueType фонт + Variable font Варијабилни фонт # Bevel & Emboss shading controls. Highlight Mode Режим осветљења @@ -4526,3 +4554,6 @@ shape Appearance Izgled Tight Curl Usko uvijeno Loose Curl Labavo uvijeno Stylized dabs from a history state Stilizovane mrlje iz stanja istorije + Font size presets Unapred podešene veličine fonta + Leading presets Unapred podešeni proredi + Tracking presets Unapred podešeni razmaci slova diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b9938796b4..f5b9d13fd6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2204,6 +2204,7 @@ Sets the source for the history brush Geçmiş fırçasının kaynağını ayarlar Color Replacement Renk Değiştirme New Group Yeni Grup + New Group from Layers… Katmanlardan Yeni Grup… Layer Comp Katman Kompozisyonu Alpha Alfa Make Üretici @@ -3968,6 +3969,33 @@ cameraData Lens Lens Kept {name}: written by another application {name} korundu: başka bir uygulama tarafından yazılmış Shadow Tint Gölge tonu Redrawing Yeniden çiziliyor + Show Favorite Fonts Favori yazı tiplerini göster + No favorite fonts yet: click the star beside a font to add it. Henüz favori yazı tipi yok: eklemek için bir yazı tipinin yanındaki yıldıza tıklayın. + Favorite fonts Favori yazı tipleri + Add to Favorites Favorilere ekle + Remove from Favorites Favorilerden kaldır + Show All Fonts Tüm yazı tiplerini göster + All Classes Tüm sınıflar + Blackletter Gotik + Decorative Dekoratif + Font preview: Yazı tipi önizlemesi: + Handwritten El yazısı + Hide Font Classes Yazı tipi sınıflarını gizle + Hide Styles Stilleri gizle + Monospace Eş aralıklı + No fonts match these filters. Bu filtrelerle eşleşen yazı tipi yok. + No similar fonts: the current font doesn't say what it looks like. Benzer yazı tipi yok: geçerli yazı tipi görünümünü tanımlamıyor. + OpenType font OpenType yazı tipi + Sans Serif Tırnaksız + Script Kaligrafik + Serif Tırnaklı + Show Font Classes Yazı tipi sınıflarını göster + Show Similar Fonts Benzer yazı tiplerini göster + Show Styles Stilleri göster + Show Variable Fonts Değişken yazı tiplerini göster + Slab Serif Kalın tırnaklı + TrueType font TrueType yazı tipi + Variable font Değişken yazı tipi # Bevel & Emboss shading controls. Highlight Mode Vurgu Modu Highlight Color Vurgu Rengi @@ -4182,3 +4210,6 @@ cameraData Lens Lens Tight Curl Sıkı Kıvrım Loose Curl Gevşek Kıvrım Stylized dabs from a history state Bir geçmiş durumundan stilize benekler + Font size presets Yazı tipi boyutu hazır ayarları + Leading presets Satır aralığı hazır ayarları + Tracking presets İzleme hazır ayarları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8db5ac0dcf..8d911b19a8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -182,6 +182,7 @@ Group… Група… Ungroup Layers Розгрупувати шари Group from Layers… Група із шарів… + New Group from Layers… Нова група із шарів… Hide Layers Приховати шари Arrange Упорядкувати Bring to Front На передній план @@ -3951,6 +3952,33 @@ curves Smooth Згладити Sent to {printer} Надіслано на {printer} set in Print Settings… задається в параметрах друку… ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів + Show Favorite Fonts Показати вибрані шрифти + No favorite fonts yet: click the star beside a font to add it. Вибраних шрифтів ще немає: натисніть зірочку біля шрифту, щоб додати його. + Favorite fonts Вибрані шрифти + Add to Favorites Додати до вибраного + Remove from Favorites Видалити з вибраного + Show All Fonts Показати всі шрифти + All Classes Усі класи + Blackletter Готичні + Decorative Декоративні + Font preview: Попередній перегляд шрифту: + Handwritten Рукописні + Hide Font Classes Сховати класи шрифтів + Hide Styles Сховати накреслення + Monospace Моноширинні + No fonts match these filters. Жоден шрифт не відповідає цим фільтрам. + No similar fonts: the current font doesn't say what it looks like. Немає схожих шрифтів: поточний шрифт не описує свій вигляд. + OpenType font Шрифт OpenType + Sans Serif Без засічок + Script Каліграфічні + Serif Із засічками + Show Font Classes Показати класи шрифтів + Show Similar Fonts Показати схожі шрифти + Show Styles Показати накреслення + Show Variable Fonts Показати варіативні шрифти + Slab Serif Із брускуватими засічками + TrueType font Шрифт TrueType + Variable font Варіативний шрифт Calibration Калібрування Red Primary Червоний основний Green Primary Зелений основний @@ -4167,3 +4195,6 @@ curves Smooth Згладити # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Ціль + Font size presets Набори розмірів шрифту + Leading presets Набори інтерліньяжу + Tracking presets Набори трекінгу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1b14d41a05..f348662975 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -290,6 +290,7 @@ Gradient… Chuyển sắc… Grayscale Thang xám Group from Layers… Nhóm từ các lớp… + New Group from Layers… Nhóm mới từ các lớp… Group Layers Nhóm các lớp Group… Nhóm… HDR Toning… Tông HDR… @@ -3715,6 +3716,33 @@ curves Smooth Làm mượt Sent to {printer} Đã gửi tới {printer} set in Print Settings… đặt trong thiết lập in… ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel + Show Favorite Fonts Hiển thị phông chữ yêu thích + No favorite fonts yet: click the star beside a font to add it. Chưa có phông chữ yêu thích: nhấp vào ngôi sao bên cạnh phông chữ để thêm. + Favorite fonts Phông chữ yêu thích + Add to Favorites Thêm vào mục yêu thích + Remove from Favorites Xóa khỏi mục yêu thích + Show All Fonts Hiển thị tất cả phông chữ + All Classes Tất cả các lớp + Blackletter Blackletter + Decorative Trang trí + Font preview: Xem trước phông chữ: + Handwritten Viết tay + Hide Font Classes Ẩn lớp phông chữ + Hide Styles Ẩn kiểu + Monospace Đơn cách + No fonts match these filters. Không có phông chữ nào khớp với các bộ lọc này. + No similar fonts: the current font doesn't say what it looks like. Không có phông chữ tương tự: phông chữ hiện tại không mô tả hình dáng của nó. + OpenType font Phông chữ OpenType + Sans Serif Không chân + Script Viết tay nghệ thuật + Serif Có chân + Show Font Classes Hiện lớp phông chữ + Show Similar Fonts Hiện phông chữ tương tự + Show Styles Hiện kiểu + Show Variable Fonts Hiện phông chữ biến thiên + Slab Serif Chân vuông + TrueType font Phông chữ TrueType + Variable font Phông chữ biến thiên Calibration Hiệu chuẩn Red Primary Màu đỏ cơ bản Green Primary Màu lục cơ bản @@ -3952,3 +3980,6 @@ curves Smooth Làm mượt # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Tỷ lệ khung hình + Font size presets Cỡ chữ đặt sẵn + Leading presets Giãn dòng đặt sẵn + Tracking presets Khoảng cách chữ đặt sẵn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c45d9c4431..d9f437214a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -311,6 +311,7 @@ Layer… 图层… Group… 组… Group from Layers… 从图层创建组… + New Group from Layers… 从图层新建组… Artboard… 画板… Artboard from Group… 从组创建画板… Artboard from Layers… 从图层创建画板… @@ -2902,6 +2903,33 @@ curves Smooth 平滑 Sent to {printer} 已发送到 {printer} set in Print Settings… 在打印设置中设置… ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 + Show Favorite Fonts 显示收藏的字体 + No favorite fonts yet: click the star beside a font to add it. 还没有收藏的字体:点击字体旁边的星标即可添加。 + Favorite fonts 收藏的字体 + Add to Favorites 添加到收藏 + Remove from Favorites 从收藏中移除 + Show All Fonts 显示所有字体 + All Classes 所有类别 + Blackletter 哥特体 + Decorative 装饰体 + Font preview: 字体预览: + Handwritten 手写体 + Hide Font Classes 隐藏字体类别 + Hide Styles 隐藏样式 + Monospace 等宽 + No fonts match these filters. 没有符合这些筛选条件的字体。 + No similar fonts: the current font doesn't say what it looks like. 没有相似字体:当前字体没有描述其外观。 + OpenType font OpenType 字体 + Sans Serif 无衬线 + Script 手写花体 + Serif 衬线 + Show Font Classes 显示字体类别 + Show Similar Fonts 显示相似字体 + Show Styles 显示样式 + Show Variable Fonts 显示可变字体 + Slab Serif 粗衬线 + TrueType font TrueType 字体 + Variable font 可变字体 Calibration 校准 Red Primary 红原色 Green Primary 绿原色 @@ -3137,3 +3165,6 @@ curves Smooth 平滑 Profile 配置文件 Target 目标 Units 单位 + Font size presets 字号预设 + Leading presets 行距预设 + Tracking presets 字距调整预设 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e002fb3a6b..9d46dcb21e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -316,6 +316,7 @@ Layer… 圖層… Group… 群組… Group from Layers… 從圖層建立群組… + New Group from Layers… 從圖層新增群組… Artboard… 工作區域… Artboard from Group… 從群組建立工作區域… Artboard from Layers… 從圖層建立工作區域… @@ -2866,6 +2867,33 @@ curves Smooth 平滑 Sent to {printer} 已傳送至 {printer} set in Print Settings… 在列印設定中設定… ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 + Show Favorite Fonts 顯示我的最愛字體 + No favorite fonts yet: click the star beside a font to add it. 尚無我的最愛字體:按一下字體旁的星號即可加入。 + Favorite fonts 我的最愛字體 + Add to Favorites 加入我的最愛 + Remove from Favorites 從我的最愛移除 + Show All Fonts 顯示所有字體 + All Classes 所有類別 + Blackletter 哥德體 + Decorative 裝飾體 + Font preview: 字體預覽: + Handwritten 手寫體 + Hide Font Classes 隱藏字體類別 + Hide Styles 隱藏樣式 + Monospace 等寬 + No fonts match these filters. 沒有符合這些篩選條件的字體。 + No similar fonts: the current font doesn't say what it looks like. 沒有相似字體:目前的字體沒有描述其外觀。 + OpenType font OpenType 字體 + Sans Serif 無襯線 + Script 手寫花體 + Serif 襯線 + Show Font Classes 顯示字體類別 + Show Similar Fonts 顯示相似字體 + Show Styles 顯示樣式 + Show Variable Fonts 顯示可變字體 + Slab Serif 粗襯線 + TrueType font TrueType 字體 + Variable font 可變字體 Calibration 校準 Red Primary 紅原色 Green Primary 綠原色 @@ -3093,3 +3121,6 @@ curves Smooth 平滑 Profile 描述檔 Target 目標 Units 單位 + Font size presets 字體大小預設 + Leading presets 行距預設 + Tracking presets 字距調整預設 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index a255fe094b..18101a5903 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -144,6 +144,9 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("stamp", include_bytes!("../../../assets/icons/stamp.svg")), ("star", include_bytes!("../../../assets/icons/star.svg")), ("star-filled", include_bytes!("../../../assets/icons/star-filled.svg")), + // PhotoCraft originals: the font menu's Show Similar Fonts and Show Variable Fonts filters. + ("font-similar", include_bytes!("../../../assets/icons/font-similar.svg")), + ("font-variable", include_bytes!("../../../assets/icons/font-variable.svg")), ("sun", include_bytes!("../../../assets/icons/sun.svg")), ("symmetry-diagonal", include_bytes!("../../../assets/icons/symmetry-diagonal.svg")), ("symmetry-dual", include_bytes!("../../../assets/icons/symmetry-dual.svg")), diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index c09ebb2b12..df8eb96608 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -21,13 +21,14 @@ fn realistic() -> photocraft_engine::Session { s.execute("file.new", json!({"width": 240, "height": 160})).unwrap(); s.execute("layer.new.layer", json!({"name": "in-group"})).unwrap(); s.execute("layer.groupLayers", json!({"name": "group"})).unwrap(); - // Group Layers creates collapsed groups (#5571); the walk below expects it open. - s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello"})).unwrap(); let paint = s.execute("layer.new.layer", json!({"name": "paint"})).unwrap()["layer"].as_u64().unwrap(); s.execute("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 60})).unwrap(); s.execute("edit.fill", json!({"color": "#3070c0"})).unwrap(); s.execute("layer.select", json!({"layer": paint})).unwrap(); + // Group Layers makes a collapsed group; open it so the panel shows the layer inside. (Opened + // last: an open active group would take the new layers above inside it, as in Photoshop.) + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ef7269dbaa..190d9e5603 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -139,6 +139,7 @@ pub use dialogs::layer_style; pub use dialogs::liquify_ui; pub use dialogs::mask_trash_prompt; pub use dialogs::new_doc_ui; +pub use dialogs::new_group_ui; pub use dialogs::new_guide_ui; pub use dialogs::new_layer_ui; pub use dialogs::open_prompt; @@ -237,6 +238,7 @@ pub use text::bidi_text; pub use text::cjk_fonts; pub use text::direction; pub use text::egui_fonts; +use text::font_filters; use text::font_preview; pub use text::served_fonts; use tools::align_bar; @@ -346,7 +348,9 @@ pub struct PhotocraftApp { trail: Option, /// Remove tool strokes waiting to be applied together (Remove after each stroke off), the /// document, layer and channel they belong to, and their tint on the canvas (`retouch_ui`). - pub(crate) remove_pending: Vec>, + /// Each as a `paint.remove` `strokes` entry: its points and the size, hardness and spacing it + /// was drawn with, which its tint shows and its removal uses. + pub(crate) remove_pending: Vec, pub(crate) remove_pending_target: Option, pub(crate) remove_trail: Option, /// The open menus' items, reused between frames (`menus::ItemCache`). diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index e1f05a28bd..7ae1d8dea4 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -436,6 +436,15 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } Ok(json!({"dialog": crate::stroke_ui::open(app)})) } + // Layer › New › Group… / Group from Layers… (and the Layers panel's menu, ⌥-click on its + // New Group button): Photoshop's New Group dialog. Explicit params run the engine directly, + // and Group Layers (⌘G) never asks. + _ if crate::new_group_ui::fronts(id) && params.as_object().is_none_or(|o| o.is_empty()) => { + if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) { + return Err(why); + } + Ok(json!({"dialog": crate::new_group_ui::open(app, id)})) + } // Channels › Channel Options… without params: the dialog on the targeted alpha/spot // channel, Layer Mask Display Options on a targeted layer mask, or Quick Mask Options while // in Quick Mask (with params: the engine directly). diff --git a/crates/ui-egui/src/new_group_button_tests.rs b/crates/ui-egui/src/new_group_button_tests.rs index 529972a418..54d8ff42a2 100644 --- a/crates/ui-egui/src/new_group_button_tests.rs +++ b/crates/ui-egui/src/new_group_button_tests.rs @@ -1,13 +1,154 @@ -//! The Layers panel New Group button groups multiple selected layers on a plain click. -//! Shift-click also groups a single selected layer; otherwise it creates an empty group. +//! #2561: the Layers panel New Group button. Like Photoshop CC 2014 and later, a click with two or +//! more layers selected puts them in a new, collapsed group, and with one layer it adds an empty +//! group. Shift-click (the older way) groups the selection too, ⌥-click asks in the New Group +//! dialog first and ⌘-click adds the empty group below the active layer. use egui::Modifiers; use egui_kittest::kittest::Queryable; -use photocraft_doc::{Layer, LayerId}; +use photocraft_doc::{Layer, LayerContent, LayerId}; use serde_json::json; use crate::PhotocraftApp; +/// Background, then `A` and `B` on top of it; `A` and `B` are selected when `both`, otherwise +/// only `B` is (`B` active either way). +fn selected(both: bool) -> (egui_kittest::Harness<'static, PhotocraftApp>, LayerId, LayerId) { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let a = LayerId(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap()); + let b = LayerId(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + if both { + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + } + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + h.run_steps(4); + (h, a, b) +} + +fn groups(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Vec { + h.state().session.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).cloned().collect() +} + +/// The one group holds `[a, b]` in order, sits next to the background, is the only selected layer +/// and, as in Photoshop, is collapsed: its layers' rows are not drawn. +fn assert_grouped(h: &egui_kittest::Harness<'static, PhotocraftApp>, a: LayerId, b: LayerId) { + let groups = groups(h); + assert_eq!(groups.len(), 1); + let children: Vec = groups[0].children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![a, b]); + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc.layers.len(), 2, "background and the new group stay at the top level"); + assert_eq!(st.selected_layers(), vec![groups[0].id], "the new group is selected"); + assert!(matches!(&groups[0].content, LayerContent::Group(g) if !g.expanded), "the new group is collapsed"); + let rows: Vec = crate::layer_row_ui::recorded(&h.ctx).into_iter().map(|r| r.layer).collect(); + assert!(rows.contains(&groups[0].id.0) && !rows.contains(&a.0) && !rows.contains(&b.0), "only the group's row shows: {rows:?}"); +} + +#[test] +fn plain_click_groups_the_selected_layers_in_order() { + let (mut h, a, b) = selected(true); + h.get_by_label("Create a new group").click(); + h.run_steps(4); + assert_grouped(&h, a, b); + // One step: a single undo puts both layers back where they were. + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert!(groups(&h).is_empty()); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top[1..], [a, b]); +} + +#[test] +fn shift_click_groups_the_selected_layers_in_order() { + let (mut h, a, b) = selected(true); + h.get_by_label("Create a new group").click_modifiers(Modifiers::SHIFT); + h.run_steps(4); + assert_grouped(&h, a, b); +} + +#[test] +fn plain_click_with_one_selected_layer_adds_an_empty_group() { + let (mut h, a, b) = selected(false); + h.get_by_label("Create a new group").click(); + h.run_steps(4); + let groups = groups(&h); + assert_eq!(groups.len(), 1); + assert!(groups[0].children().unwrap().is_empty()); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top[1..], [a, b, groups[0].id], "the layers stay where they were; the group goes above the active one"); +} + +/// Selecting a layer inside the collapsed group opens it, as in Photoshop. +#[test] +fn selecting_a_grouped_layer_opens_the_group() { + let (mut h, a, b) = selected(true); + h.get_by_label("Create a new group").click(); + h.run_steps(4); + assert_grouped(&h, a, b); + h.state_mut().run("layer.select", json!({"layer": a.0})).unwrap(); + h.run_steps(4); + let rows: Vec = crate::layer_row_ui::recorded(&h.ctx).into_iter().map(|r| r.layer).collect(); + assert!(rows.contains(&a.0) && rows.contains(&b.0), "{rows:?}"); +} + +/// ⌥-click asks in the New Group dialog first: New Group from Layers with several layers +/// selected, New Group with one. Nothing changes until OK. +#[test] +fn alt_click_opens_the_new_group_dialog() { + for (both, command) in [(true, "layer.new.groupFromLayers"), (false, "layer.new.group")] { + let (mut h, a, b) = selected(both); + h.get_by_label("Create a new group").click_modifiers(Modifiers::ALT); + h.run_steps(4); + assert!(groups(&h).is_empty(), "nothing happens before OK"); + let (id, fields) = h.state().ui.dialogs.last().map(|d| (d.id, d.fields.clone())).expect("the New Group dialog opened"); + assert!(crate::new_group_ui::owns(&fields)); + assert_eq!(fields["__command"], command); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(4); + if both { + assert_grouped(&h, a, b); + } else { + let groups = groups(&h); + assert_eq!(groups.len(), 1); + assert!(groups[0].children().unwrap().is_empty()); + } + } +} + +/// ⌘-click adds an empty group below the active layer, even with several layers selected. +#[test] +fn command_click_adds_an_empty_group_below_the_active_layer() { + for both in [true, false] { + let (mut h, a, b) = selected(both); + h.get_by_label("Create a new group").click_modifiers(Modifiers::COMMAND); + h.run_steps(4); + let groups = groups(&h); + assert_eq!(groups.len(), 1); + assert!(groups[0].children().unwrap().is_empty()); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top[1..], [a, groups[0].id, b]); + } +} + +/// Its neighbour, the New Layer button: ⌘-click adds the layer below the active one, a plain +/// click above it, as in Photoshop. +#[test] +fn command_click_on_new_layer_adds_it_below_the_active_layer() { + for (modifiers, below) in [(Modifiers::COMMAND, true), (Modifiers::NONE, false)] { + let (mut h, a, b) = selected(false); + h.get_by_label("Create a new layer").click_modifiers(modifiers); + h.run_steps(4); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top.len(), 4); + let new = *top.iter().find(|id| ![a, b].contains(id) && **id != top[0]).unwrap(); + assert_eq!(top[1..], if below { [a, new, b] } else { [a, b, new] }); + } +} + /// Background, then `A` and `B` on top of it with both selected (`B` active). fn two_selected() -> (egui_kittest::Harness<'static, PhotocraftApp>, LayerId, LayerId) { let mut s = photocraft_engine::Session::new(); @@ -24,23 +165,6 @@ fn two_selected() -> (egui_kittest::Harness<'static, PhotocraftApp>, LayerId, La (h, a, b) } -fn groups(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Vec { - h.state().session.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).cloned().collect() -} - -#[test] -fn shift_click_groups_the_selected_layers_in_order() { - let (mut h, a, b) = two_selected(); - h.get_by_label("Create a new group").click_modifiers(Modifiers::SHIFT); - h.run_steps(4); - let groups = groups(&h); - assert_eq!(groups.len(), 1); - let children: Vec = groups[0].children().unwrap().iter().map(|l| l.id).collect(); - assert_eq!(children, vec![a, b]); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.layers.len(), 2, "background and the new group stay at the top level"); -} - #[test] fn plain_click_groups_all_selected_layers_in_order_and_undoes_in_one_step() { for active in ["A", "B"] { @@ -72,19 +196,3 @@ fn plain_click_groups_all_selected_layers_in_order_and_undoes_in_one_step() { assert_eq!(children, vec![a, b]); } } - -#[test] -fn plain_click_with_one_selected_layer_still_adds_an_empty_group() { - let (mut h, a, b) = two_selected(); - h.state_mut().session.execute("layer.select", json!({"layer": a.0})).unwrap(); - h.run_steps(4); - h.get_by_label("Create a new group").click(); - h.run_steps(4); - let groups = groups(&h); - assert_eq!(groups.len(), 1); - assert!(groups[0].children().unwrap().is_empty()); - let doc = &h.state().session.active().unwrap().doc; - let top: Vec = doc.layers.iter().map(|l| l.id).collect(); - assert_eq!(top[1], a, "the selected layer stays where it was"); - assert_eq!(top[3], b, "the unselected layer stays above the new group"); -} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 366145f381..2fcf3fee80 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -87,6 +87,7 @@ pub(crate) use layer_drag::{dropped_on, layer_drag_edge_scroll}; pub(crate) use layer_row::thumb_load_badge; #[cfg(test)] use layer_row::{layer_thumb_fit, paint_clipping_indicator}; +pub(crate) use layers::blend_options; #[cfg(test)] use layers::{layers, opacity_row_layout, simple_lock_toggle}; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 592e4a902b..273893ae5a 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -91,6 +91,12 @@ pub(crate) fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.x = 8.0; let (chips, _) = ui.allocate_exact_size(vec2(38.0, h), Sense::hover()); field_chips(app, ui, chips); + // Photoshop's ⚠ under the chips when the colour can't print, as in the slider modes + // (#8672); a compact field too short to hold it below the chips leaves it out. + if chips.height() >= 38.0 + 15.0 { + let rgb = crate::color_panel_ui::active(app); + crate::color_panel_ui::alerts(app, ui, chips, rgb, false); + } // Hue Cube: saturation across and brightness up, hue on the strip. Brightness Cube (the // Color Picker's B mode): hue across and saturation up, brightness on the strip. let brightness = app.ui.color_panel.mode == crate::state::ColorPanelMode::BrightnessCube; diff --git a/crates/ui-egui/src/panels/color_panel_ui.rs b/crates/ui-egui/src/panels/color_panel_ui.rs index 952176e61a..798e24dea1 100644 --- a/crates/ui-egui/src/panels/color_panel_ui.rs +++ b/crates/ui-egui/src/panels/color_panel_ui.rs @@ -109,7 +109,7 @@ impl Model { } /// The colour the panel edits. -fn active(app: &PhotocraftApp) -> [f32; 3] { +pub(crate) fn active(app: &PhotocraftApp) -> [f32; 3] { let c = if app.ui.color_panel.background { app.session.tools.background } else { app.session.tools.foreground }; [c[0], c[1], c[2]].map(|x| x.clamp(0.0, 1.0)) } @@ -347,7 +347,7 @@ fn sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, mode: ColorPanelMode) { /// Photoshop's alerts under the chips: ⚠ when the colour can't print (click: the nearest CMYK /// colour) and, for Web Color sliders, the cube when it isn't a web colour (click: the nearest). -fn alerts(app: &mut PhotocraftApp, ui: &mut egui::Ui, col: Rect, rgb: [f32; 3], web: bool) { +pub(crate) fn alerts(app: &mut PhotocraftApp, ui: &mut egui::Ui, col: Rect, rgb: [f32; 3], web: bool) { let t = Tokens::get(ui.ctx()); let background = app.ui.color_panel.background; let mut y = col.top() + CHIPS_W + 2.0; diff --git a/crates/ui-egui/src/panels/layer_filter_ui/tests.rs b/crates/ui-egui/src/panels/layer_filter_ui/tests.rs index aeeb63e7cc..89e1a6a0b9 100644 --- a/crates/ui-egui/src/panels/layer_filter_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_filter_ui/tests.rs @@ -17,7 +17,6 @@ fn session() -> photocraft_engine::Session { s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); s.execute("layer.new.layer", json!({"name": "Paper"})).unwrap(); s.execute("layer.groupLayers", json!({"name": "Sheets"})).unwrap(); - s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); let paper = layer(&s.active().unwrap().doc, "Paper"); s.execute("layer.select", json!({"layer": paper})).unwrap(); let ink = s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap()["layer"].as_u64().unwrap(); @@ -26,6 +25,8 @@ fn session() -> photocraft_engine::Session { s.execute("layer.select", json!({"layer": sheets})).unwrap(); let text = s.execute("type.create", json!({"text": "ink notes", "x": 4, "y": 20, "size": 12})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.setProps", json!({"layer": text, "name": "ink notes"})).unwrap(); + // Opened last: an open active group would take the type layer inside it, as in Photoshop. + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s } diff --git a/crates/ui-egui/src/panels/layer_menu_ui.rs b/crates/ui-egui/src/panels/layer_menu_ui.rs index 7ad844027a..f274e28620 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui.rs @@ -55,9 +55,9 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec { v.push(None); v.push(Some((if multi { tl!("Duplicate Layers…") } else { tl!("Duplicate Layer…") }, "layer.duplicate"))); v.push(Some((if multi { tl!("Delete Layers") } else { tl!("Delete Layer") }, "layer.delete"))); - if !multi { - v.push(Some((tl!("Group from Layers…"), "layer.groupLayers"))); - } + // Groups the clicked layer, or the whole selection when several layers are selected, after + // Photoshop's New Group dialog. + v.push(Some((tl!("Group from Layers…"), "layer.new.groupFromLayers"))); v.push(None); v.push(Some((tl!("Quick Export As PNG"), "layer.quickExportAsPng"))); v.push(Some((tl!("Export As…"), "layer.exportAs"))); diff --git a/crates/ui-egui/src/panels/layer_menu_ui/tests.rs b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs index f0b0b237e5..a7ab70a76e 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs @@ -360,6 +360,29 @@ fn rasterize_from_the_menu_converts_every_selected_layer() { assert_eq!(h.state().session.active().unwrap().selected_layers().len(), 2, "the selection survives"); } +/// Group from Layers is offered for a multi-layer selection too (it used to be dropped from +/// the menu then). As in Photoshop it asks in the New Group from Layers dialog first; OK puts +/// every selected layer in one new group, leaving the rest alone. +#[test] +fn group_from_layers_groups_every_selected_layer() { + use egui_kittest::kittest::Queryable; + use photocraft_doc::LayerId; + let (mut h, [text, shape, other]) = open_multi_selection_menu(); + let at = h.get_by_label("Group from Layers…").rect().center(); + click(&mut h, at, egui::PointerButton::Primary); + let dialog = h.state().ui.dialogs.last().map(|d| (d.id, d.fields.clone())).expect("the New Group dialog opened"); + assert!(crate::new_group_ui::owns(&dialog.1)); + assert_eq!(dialog.1["__command"], "layer.new.groupFromLayers"); + crate::dialogs::confirm(h.state_mut(), dialog.0).unwrap(); + h.run_steps(2); + let doc = &h.state().session.active().unwrap().doc; + let groups: Vec<_> = doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).collect(); + assert_eq!(groups.len(), 1); + let children: Vec = groups[0].children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![LayerId(text), LayerId(shape)], "both selected layers, in order"); + assert!(doc.layers.iter().any(|l| l.id == LayerId(other)), "an unselected layer stays at the top level"); +} + /// Items with no single target are greyed for a multi-layer selection (they used to run on /// whichever layer happened to be active, not the one right-clicked); the ones that act on the /// whole selection, including adding a mask, stay available. @@ -376,6 +399,7 @@ fn multi_selection_menu_greys_what_acts_on_one_layer() { "Add Layer Mask", "Duplicate Layers…", "Delete Layers", + "Group from Layers…", "Convert to Smart Object", "Rasterize Layers", "Link Layers", @@ -407,6 +431,7 @@ fn single_layer_only_covers_the_per_layer_commands() { "layer.exportAs", "layer.duplicate", "layer.delete", + "layer.new.groupFromLayers", "layer.rasterize.layer", "layer.smartObjects.convertToSmartObject", "layer.createClippingMask", diff --git a/crates/ui-egui/src/panels/layer_row_ui.rs b/crates/ui-egui/src/panels/layer_row_ui.rs index 0aa8341c4f..7e89c50519 100644 --- a/crates/ui-egui/src/panels/layer_row_ui.rs +++ b/crates/ui-egui/src/panels/layer_row_ui.rs @@ -265,9 +265,16 @@ pub fn panel_menu(app: &mut crate::PhotocraftApp, ui: &mut egui::Ui) { app.ui.layers_panel_dialog = Some(LayersPanelDialog::NewLayer(String::new())); ui.close(); } - if ui.add_enabled(has_doc, egui::Button::new(tl!("New Group…"))).clicked() { - app.ui.layers_panel_dialog = Some(LayersPanelDialog::NewGroup(String::new())); - ui.close(); + // New Group… and New Group from Layers… open the New Group dialog, like their Layer › New twins. + for (label, id) in [(tl!("New Group…"), crate::new_group_ui::NEW_GROUP), (tl!("New Group from Layers…"), crate::new_group_ui::FROM_LAYERS)] { + if ui.add_enabled(crate::menus::is_enabled(app, id), egui::Button::new(label)).clicked() { + let ctx = ui.ctx().clone(); + if let Err(e) = crate::menus::invoke(app, &ctx, id, json!({})) { + app.ui.status = e; + app.ui.status_error = true; + } + ui.close(); + } } ui.separator(); run_menu_command(app, ui, tl!("Flatten Image"), "layer.flattenImage"); diff --git a/crates/ui-egui/src/panels/layer_row_ui/tests.rs b/crates/ui-egui/src/panels/layer_row_ui/tests.rs index 70496fb0dd..d1a3dec1e0 100644 --- a/crates/ui-egui/src/panels/layer_row_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_row_ui/tests.rs @@ -116,9 +116,10 @@ fn a_groups_layers_indent_past_the_group() { s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); let child = s.execute("layer.new.layer", json!({"name": "Child"})).unwrap()["layer"].as_u64().unwrap(); let group = s.execute("layer.groupLayers", json!({"name": "Group"})).unwrap()["layer"].as_u64().unwrap(); + // Top goes above the closed group (an open one would take it inside, as in Photoshop). + let top = s.execute("layer.new.layer", json!({"name": "Top"})).unwrap()["layer"].as_u64().unwrap(); // Group Layers creates the group collapsed; open it so the panel lists its layers. s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap(); - let top = s.execute("layer.new.layer", json!({"name": "Top"})).unwrap()["layer"].as_u64().unwrap(); let h = harness(s, 1.0, "promedium", 290.0); let rows = recorded(&h.ctx); let left = |id: u64| rows.iter().find(|r| r.layer == id).and_then(|r| r.name).map(|n| n.left()).unwrap_or_else(|| panic!("layer {id} drawn")); @@ -249,6 +250,24 @@ fn collapse_all_groups_from_the_panel_menu_and_it_is_saved() { } } +/// Photoshop's panel menu has New Group… and New Group from Layers… just above Collapse All +/// Groups; both open the New Group dialog. +#[test] +fn new_group_items_in_the_panel_menu_open_the_dialog() { + for (label, command) in [("New Group…", "layer.new.group"), ("New Group from Layers…", "layer.new.groupFromLayers")] { + let mut h = harness(busy(), 1.0, "promedium", 290.0); + let group = crate::panel_docking::probe::group_rect(h.state(), &h.ctx, "layers").expect("layers group"); + let menu = h.query_all_by_label("Panel menu").map(|n| n.rect()).find(|r| group.contains(r.center())).expect("Layers panel menu"); + click(&mut h, menu.center()); + let item = h.get_by_label(label).rect(); + assert!(item.top() < h.get_by_label("Collapse All Groups").rect().top(), "{label} comes before Collapse All Groups"); + click(&mut h, item.center()); + let fields = h.state().ui.dialogs.last().map(|d| d.fields.clone()).expect("the New Group dialog opened"); + assert!(crate::new_group_ui::owns(&fields)); + assert_eq!(fields["__command"], command); + } +} + /// Dragging down the eye column hides (or shows) every layer swept over, in one history step, and /// never reorders the layers, even when one pointer move jumps several rows; a hidden layer's eye /// box is empty and a click shows it again. diff --git a/crates/ui-egui/src/panels/layer_tree_ui/tests.rs b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs index 0b3d4c2724..dfc1f44fb0 100644 --- a/crates/ui-egui/src/panels/layer_tree_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs @@ -17,7 +17,7 @@ fn layered() -> photocraft_engine::Session { let inner = s.execute("layer.groupLayers", json!({"name": "inner"})).unwrap()["layer"].as_u64().unwrap(); let outer = s.execute("layer.groupLayers", json!({"layer": inner, "name": "outer"})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.select", json!({"layer": inner})).unwrap(); - // `layer.new.layer` lands above the active layer, inside `outer`. + // `layer.new.layer` lands above the active (closed) group `inner`, inside `outer`. s.execute("layer.new.layer", json!({"name": "in-outer"})).unwrap(); s.execute("layer.select", json!({"layer": outer})).unwrap(); s.execute("layer.new.layer", json!({"name": "top"})).unwrap(); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 11251902e8..1d548ce270 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -28,7 +28,7 @@ pub(super) fn simple_lock_toggle(background: bool, l: &Layer, targets: &Value) - /// The Layers panel's blend modes: Photoshop's, plus the layer's own Paint.NET mode when it has one /// (an imported `.pdn`), so the menu matches Photoshop's for every other layer. -fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> { +pub(crate) fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> { let own = Some(current).filter(|m| !m.has_psd_equivalent()); std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect() } @@ -425,10 +425,23 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate")); let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group")); if group.clicked() { - // Multiple selected layers share one group. Shift also groups a single selection. - let shift = ui.input(|i| i.modifiers.shift); - let cmd = if (shift || selection.len() > 1) && active_layer.is_some() { "layer.groupLayers" } else { "layer.new.group" }; - actions.push((cmd.into(), json!({}))); + // Like Photoshop CC 2014 and later, a click with two or more layers selected puts them + // in the new group (Layer › Group Layers); with one layer or none it adds an empty + // group above the active layer. Shift-click, the older way, groups the selection too + // (#2561). ⌥-click asks first in the New Group dialog, ⌘-click adds an empty group + // below the active layer. + let m = ui.input(|i| i.modifiers); + let groups = (m.shift || selection.len() > 1) && active_layer.is_some(); + if m.alt { + // Null params go through the menu path, which opens the dialog. + let cmd = if groups { crate::new_group_ui::FROM_LAYERS } else { crate::new_group_ui::NEW_GROUP }; + actions.push((cmd.into(), Value::Null)); + } else if m.command { + actions.push(("layer.new.group".into(), json!({"position": "below"}))); + } else { + let cmd = if groups { "layer.groupLayers" } else { "layer.new.group" }; + actions.push((cmd.into(), json!({}))); + } } actions.extend(footer_drop(ui, &group, footer_drag, "layer.groupLayers")); let adj = footer_menu_button(ui, "adjustment-layer", 26.0, tl!("Create new fill or adjustment layer")); diff --git a/crates/ui-egui/src/panels/props_layout/tests.rs b/crates/ui-egui/src/panels/props_layout/tests.rs index 62e9423f44..88a61c518c 100644 --- a/crates/ui-egui/src/panels/props_layout/tests.rs +++ b/crates/ui-egui/src/panels/props_layout/tests.rs @@ -174,14 +174,14 @@ fn type_controls_fill_the_panel_at_every_width_and_scale() { .filter(|r| r.top() >= transform.bottom() && r.bottom() <= header.top()) .map(|r| r.right()) .fold(f32::MIN, f32::max); - // (Both rows have a unit suffix: compare with the size/leading row.) - // Variable-font axes can precede the size/leading row and have no unit suffix. - // Compare the intended point-valued controls, retaining the same edge tolerance. - let lead = ["Font size", "Leading (set to the font size × auto-leading when Auto)"] - .into_iter() - .map(|label| h.get_by_role_and_label(egui::accesskit::Role::SpinButton, label).rect().right()) - .fold(f32::MIN, f32::max); - assert!((t_right - lead).abs() < 0.5, "{what}: Transform fields end at {t_right}, Character at {lead}"); + // The size/leading row ends in the leading presets chevron at the panel's right edge, + // where Transform's field boxes end. The leading box ends where the chevron starts: + // its number stops one unit suffix ("pt", like Transform's "px") short of it. + let chevron = h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Leading presets").rect(); + let lead = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Leading (set to the font size × auto-leading when Auto)").rect(); + assert!((chevron.right() - header.right()).abs() < 0.5, "{what}: Character controls end at {}, panel {}", chevron.right(), header.right()); + let (t_suffix, lead_suffix) = (header.right() - t_right, chevron.left() - lead.right()); + assert!((t_suffix - lead_suffix).abs() < 0.5, "{what}: Transform's suffix slot {t_suffix}, the leading field's {lead_suffix} (overlap or gap)"); // Quick Actions buttons span the panel too. let qa = h.get_by_label("Rasterize Type").rect(); assert!(qa.right() >= header.right() - 2.0 && qa.right() <= header.right() + 1.0, "{what}: {qa:?}"); diff --git a/crates/ui-egui/src/panels/type_panels_ui.rs b/crates/ui-egui/src/panels/type_panels_ui.rs index 02c99b9dd4..d95c22addb 100644 --- a/crates/ui-egui/src/panels/type_panels_ui.rs +++ b/crates/ui-egui/src/panels/type_panels_ui.rs @@ -373,8 +373,8 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s let defined = |attrs: &Value, k: &str| attrs.get(k).is_some(); // Preferences ▸ Type ▸ Font Preview Size sizes the family picker's samples. let preview = app.session.prefs().type_.font_preview; - // The fonts the pickers hoist to the top (Preferences ▸ Type ▸ Recent Fonts). - let recents = app.ui.recent_fonts.clone(); + // The font picker's favourites and recent fonts; a star clicked in it is applied below. + let mut library = crate::type_tool::FontLibrary::of(app); // Preferences ▸ Units & Rulers ▸ Type: the model stores points; the fields may show pixels // (by the document's resolution) or millimetres. let (type_unit, unit_label) = crate::type_tool::type_unit(app); @@ -402,8 +402,12 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s ui.add_enabled_ui(on, |ui| match kind { "font" => { let mut f = v.as_str().unwrap_or("").to_string(); - if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f, preview, &recents) { - set = Some(json!({ panel: f })); + if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f, preview, &mut library) { + // A style picked under the family's ">" comes with it. + set = Some(match library.picked_style.take() { + Some(style) => json!({ panel: f, "fontStyle": style }), + None => json!({ panel: f }), + }); } } "pt" | "num" | "leading" => { @@ -502,6 +506,7 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s } } }); + library.finish(app); if let Some(attrs) = set { let _ = run(app, &format!("{prefix}.set"), json!({ "id": id, "attrs": attrs })); } @@ -524,13 +529,19 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s } } -/// Searchable family combo box. -fn family_picker(ui: &mut egui::Ui, salt: &str, current: &mut String, preview: photocraft_engine::prefs::FontPreview, recents: &[String]) -> bool { +/// Searchable family combo box, starring and listing first the fonts of `library`. +fn family_picker( + ui: &mut egui::Ui, + salt: &str, + current: &mut String, + preview: photocraft_engine::prefs::FontPreview, + library: &mut crate::type_tool::FontLibrary, +) -> bool { if !crate::type_tool::fonts_ready(ui, 140.0) { return false; } let mut shown = if current.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { current.clone() }; - let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families(), preview, recents); + let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families(), preview, library); if changed { *current = shown; } @@ -624,10 +635,14 @@ pub fn glyphs_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Font family + style. ui.horizontal(|ui| { let mut f = family.clone(); - if family_picker(ui, "glyph-family", &mut f, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { + let mut library = crate::type_tool::FontLibrary::of(app); + let picked = family_picker(ui, "glyph-family", &mut f, app.session.prefs().type_.font_preview, &mut library); + let picked_style = library.picked_style.take(); + library.finish(app); + if picked { app.note_recent_font(&f); app.ui.type_panels.glyph_family = f; - app.ui.type_panels.glyph_style = tl!("Regular").into(); + app.ui.type_panels.glyph_style = picked_style.unwrap_or_else(|| tl!("Regular").into()); } let styles = crate::type_tool::styles(&family); let mut s = style.clone(); diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 88e383ce9b..cd1c867521 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -249,8 +249,16 @@ fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option, + pub favorites: bool, + pub variable: bool, + /// Fonts like the current one, most alike first. + pub similar: bool, + /// The class list is collapsed (the « button). + pub hide_classes: bool, +} + +impl FontFilters { + /// Whether any filter narrows the list (Clear All is enabled). + pub fn any(&self) -> bool { + self.class.is_some() || self.favorites || self.variable || self.similar + } + + /// Clear All: every filter off; the class list stays as it was. + pub fn clear(&mut self) { + *self = FontFilters { hide_classes: self.hide_classes, ..Default::default() }; + } +} + +/// Family traits by family name; `None` for a family that can't be read (or a served font not +/// fetched yet). +pub(crate) type TraitsMap = HashMap>; + +/// The traits of `family` from the shared font database, cached until fonts are registered. +pub(crate) fn traits(family: &str) -> Option { + type Cached = Option<(u64, TraitsMap)>; + static CACHE: std::sync::Mutex = std::sync::Mutex::new(None); + let generation = photocraft_text::fonts::shared_generation(); + let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); + if cache.as_ref().is_none_or(|(g, _)| *g != generation) { + *cache = Some((generation, HashMap::new())); + } + let (_, map) = cache.as_mut()?; + if let Some(t) = map.get(family) { + return t.clone(); + } + // Only once the background font scan is done: never block the UI on it. + let t = photocraft_text::try_shared()?.lock().unwrap_or_else(PoisonError::into_inner).fonts.family_traits(family); + map.insert(family.to_string(), t.clone()); + t +} + +/// Narrow and order the menu's `rows` by `filters`. `current` is the font Show Similar Fonts +/// compares with; `lookup` gives a family's traits. Returns false when Show Similar Fonts is on +/// but the current font has nothing to compare (its rows are then left as they were). +pub(crate) fn apply<'a>( + rows: &mut Vec<(&'a String, &'a str)>, + filters: &FontFilters, + favorites: &[String], + current: &str, + lookup: &dyn Fn(&str) -> Option, +) -> bool { + if filters.favorites { + rows.retain(|(f, _)| favorites.contains(f)); + } + if filters.variable { + rows.retain(|(f, _)| lookup(f).is_some_and(|t| t.variable())); + } + if let Some(class) = filters.class { + rows.retain(|(f, _)| lookup(f).is_some_and(|t| t.class == Some(class))); + } + if !filters.similar { + return true; + } + let Some(reference) = lookup(current).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1)) else { + return false; + }; + let mut scored: Vec<(f32, (&String, &str))> = rows + .drain(..) + .filter_map(|row| lookup(row.0).map(|t| (if row.0 == current { -1.0 } else { photocraft_text::font_class::difference(&reference, &t) }, row))) + .collect(); + scored.sort_by(|a, b| a.0.total_cmp(&b.0)); + rows.extend(scored.into_iter().take(SIMILAR_COUNT).map(|(_, row)| row)); + true +} + +/// The translated class name. +pub(crate) fn class_label(class: FontClass) -> &'static str { + match class { + FontClass::Serif => tl!("Serif"), + FontClass::SlabSerif => tl!("Slab Serif"), + FontClass::SansSerif => tl!("Sans Serif"), + FontClass::Script => tl!("Script"), + FontClass::Monospace => tl!("Monospace"), + FontClass::Handwritten => tl!("Handwritten"), + FontClass::Blackletter => tl!("Blackletter"), + FontClass::Decorative => tl!("Decorative"), + } +} + +/// The format badge's tooltip. +pub(crate) fn format_tip(format: FontFormat) -> &'static str { + match format { + FontFormat::OpenType => tl!("OpenType font"), + FontFormat::TrueType => tl!("TrueType font"), + FontFormat::Variable => tl!("Variable font"), + } +} + +/// The class list's width; the filter buttons sit above it. +pub(crate) const CLASS_COLUMN_WIDTH: f32 = 118.0; + +/// The filter buttons: the class-list toggle and the three filters. Returns true when a filter +/// changed. +pub(crate) fn filter_buttons(ui: &mut egui::Ui, filters: &mut FontFilters) -> bool { + let before = filters.clone(); + let (icon, tip) = if filters.hide_classes { ("chevrons-right", tl!("Show Font Classes")) } else { ("chevrons-left", tl!("Hide Font Classes")) }; + if crate::icons::button(ui, icon, 22.0, false, tip).clicked() { + filters.hide_classes = !filters.hide_classes; + } + if crate::icons::button(ui, "font-variable", 22.0, filters.variable, tl!("Show Variable Fonts")).clicked() { + filters.variable = !filters.variable; + } + let tip = if filters.favorites { tl!("Show All Fonts") } else { tl!("Show Favorite Fonts") }; + if crate::icons::button(ui, if filters.favorites { "star-filled" } else { "star" }, 22.0, filters.favorites, tip).clicked() { + filters.favorites = !filters.favorites; + } + if crate::icons::button(ui, "font-similar", 22.0, filters.similar, tl!("Show Similar Fonts")).clicked() { + filters.similar = !filters.similar; + } + *filters != before +} + +/// Clear All: turns every filter off. Returns true when it did. +pub(crate) fn clear_all(ui: &mut egui::Ui, filters: &mut FontFilters) -> bool { + let clicked = ui.add_enabled(filters.any(), egui::Button::new(tl!("Clear All")).small()).clicked(); + if clicked { + filters.clear(); + } + clicked +} + +/// The preview banner's height. +pub(crate) const PREVIEW_HEIGHT: f32 = 64.0; + +/// The preview at the top of the font menu: `family` (the font under the pointer, else the +/// current one) named and set large, `width` wide. It sets `text`, the user's own type, when +/// there is some, else a sample. +pub(crate) fn preview_banner(ui: &mut egui::Ui, family: &str, label: &str, text: Option<&str>, width: f32) { + let (rect, response) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_HEIGHT), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{} {label}", tl!("Font preview:")))); + if !ui.is_rect_visible(rect) { + return; + } + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, t.radius_sm, t.canvas); + ui.painter().text(rect.left_top() + egui::vec2(10.0, 8.0), egui::Align2::LEFT_TOP, label, egui::FontId::proportional(11.0), t.text_dim); + if let Some(text) = text { + let line = egui::Rect::from_min_max(rect.left_top() + egui::vec2(10.0, 20.0), rect.right_bottom() - egui::vec2(10.0, 2.0)); + crate::font_preview::paint_text(ui, family, text, line, 30.0); + return; + } + let Some((size, _)) = crate::font_preview::sample(photocraft_engine::prefs::FontPreview::Huge) else { return }; + crate::font_preview::paint(ui, family, rect.translate(egui::vec2(0.0, 6.0)), size); +} + +/// The class list beside the fonts. Returns true when the class changed. +pub(crate) fn class_list(ui: &mut egui::Ui, filters: &mut FontFilters) -> bool { + let before = filters.class; + ui.vertical(|ui| { + ui.set_width(CLASS_COLUMN_WIDTH); + if ui.add(egui::Button::selectable(filters.class.is_none(), tl!("All Classes")).truncate()).clicked() { + filters.class = None; + } + for class in FontClass::ALL { + if ui.add(egui::Button::selectable(filters.class == Some(class), class_label(class)).truncate()).clicked() { + filters.class = Some(class); + } + } + }); + filters.class != before +} + +/// Traits a test hands the menu instead of reading installed fonts. +pub(crate) fn lookup_in(map: Option>) -> impl Fn(&str) -> Option { + move |family| match &map { + Some(map) => map.get(family).cloned().flatten(), + None => traits(family), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn t(class: FontClass, format: FontFormat, panose: [u8; 10], weight: u16) -> Option { + Some(FamilyTraits { class: Some(class), format, panose, weight }) + } + + fn fixture() -> (Vec, TraitsMap) { + let sans = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4]; + let serif = [2, 2, 6, 3, 5, 4, 5, 2, 3, 4]; + let map: TraitsMap = [ + ("Arial", t(FontClass::SansSerif, FontFormat::TrueType, sans, 400)), + ("Arial Black", t(FontClass::SansSerif, FontFormat::TrueType, [2, 11, 10, 4, 2, 1, 2, 2, 2, 4], 900)), + ("Bahnschrift", t(FontClass::SansSerif, FontFormat::Variable, sans, 400)), + ("Consolas", t(FontClass::Monospace, FontFormat::TrueType, [2, 11, 6, 9, 2, 2, 4, 3, 2, 4], 400)), + ("Georgia", t(FontClass::Serif, FontFormat::TrueType, serif, 400)), + ("Minion", t(FontClass::Serif, FontFormat::OpenType, serif, 400)), + ("Mystery", None), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let mut families: Vec = map.keys().cloned().collect(); + families.sort(); + (families, map) + } + + fn run(filters: &FontFilters, favorites: &[&str], current: &str) -> (Vec, bool) { + let (families, map) = fixture(); + let mut rows: Vec<(&String, &str)> = families.iter().map(|f| (f, f.as_str())).collect(); + let favorites: Vec = favorites.iter().map(|s| s.to_string()).collect(); + let lookup = lookup_in(Some(Arc::new(map))); + let ok = apply(&mut rows, filters, &favorites, current, &lookup); + (rows.into_iter().map(|(f, _)| f.clone()).collect(), ok) + } + + #[test] + fn class_variable_and_favorite_filters_narrow_and_combine() { + let class = |c| FontFilters { class: Some(c), ..Default::default() }; + assert_eq!(run(&class(FontClass::Serif), &[], "Arial").0, ["Georgia", "Minion"]); + assert_eq!(run(&class(FontClass::Monospace), &[], "Arial").0, ["Consolas"]); + assert!(run(&class(FontClass::Blackletter), &[], "Arial").0.is_empty()); + let variable = FontFilters { variable: true, ..Default::default() }; + assert_eq!(run(&variable, &[], "Arial").0, ["Bahnschrift"]); + let both = FontFilters { favorites: true, class: Some(FontClass::SansSerif), ..Default::default() }; + assert_eq!(run(&both, &["Georgia", "Arial Black"], "Arial").0, ["Arial Black"]); + // Nothing on: every font, unknown ones too. + assert_eq!(run(&FontFilters::default(), &[], "Arial").0.len(), 7); + } + + #[test] + fn similar_fonts_start_with_the_current_one_most_alike_first() { + let similar = FontFilters { similar: true, ..Default::default() }; + let (rows, ok) = run(&similar, &[], "Arial"); + assert!(ok); + assert_eq!(rows[0], "Arial", "the current font first"); + assert_eq!(rows[1], "Bahnschrift", "same class and shape"); + let georgia = rows.iter().position(|f| f == "Georgia").unwrap(); + let black = rows.iter().position(|f| f == "Arial Black").unwrap(); + assert!(black < georgia, "another weight of the class is nearer than another class"); + assert!(!rows.contains(&"Mystery".to_string()), "unreadable fonts can't be compared"); + // A current font with nothing to compare leaves the list alone and says so. + let (rows, ok) = run(&similar, &[], "Mystery"); + assert!(!ok); + assert_eq!(rows.len(), 7); + } + + #[test] + fn clear_all_keeps_the_class_list_state() { + let mut f = FontFilters { class: Some(FontClass::Script), favorites: true, variable: true, similar: true, hide_classes: true }; + assert!(f.any()); + f.clear(); + assert_eq!(f, FontFilters { hide_classes: true, ..Default::default() }); + assert!(!f.any()); + } +} diff --git a/crates/ui-egui/src/text/font_preview.rs b/crates/ui-egui/src/text/font_preview.rs index 58b1b20b15..8e9a5639a3 100644 --- a/crates/ui-egui/src/text/font_preview.rs +++ b/crates/ui-egui/src/text/font_preview.rs @@ -174,6 +174,44 @@ pub(crate) fn paint(ui: &egui::Ui, family: &str, row: Rect, size: f32) { } } +/// The few lines of the user's own text the font menu's preview keeps rendered: family, text, +/// display scale, font generation, point size and width. +type TextKey = (String, String, u32, u64, u32, u32); +#[derive(Clone, Default)] +struct TextCache(VecDeque<(TextKey, Option)>); +const TEXT_CACHE_LIMIT: usize = 16; + +/// `text` set in `family` at `size`, from the left of `rect` and vertically centred; what doesn't +/// fit is cut at the right. The font menu's preview of the user's own text. +pub(crate) fn paint_text(ui: &egui::Ui, family: &str, text: &str, rect: Rect, size: f32) { + let ctx = ui.ctx(); + let scale = ctx.pixels_per_point().ceil().clamp(1.0, 4.0) as u32; + let slot = rect.width().clamp(1.0, 4096.0); + let key: TextKey = (family.to_owned(), text.to_owned(), scale, photocraft_text::fonts::shared_generation(), size as u32, slot as u32); + let id = egui::Id::unique("font-menu-text-previews"); + let cached = ctx.data_mut(|d| d.get_temp_mut_or_default::(id).0.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone())); + let texture = cached.unwrap_or_else(|| { + let mut engine = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner); + let image = engine.fonts.has_family(family).then(|| render(&mut engine, family, text, slot, scale, size)).flatten(); + drop(engine); + let texture = image.map(|image| ctx.load_texture(format!("font-text-{family}"), image, TextureOptions::LINEAR)); + ctx.data_mut(|d| { + let cache = d.get_temp_mut_or_default::(id); + if cache.0.len() >= TEXT_CACHE_LIMIT { + cache.0.pop_front(); + } + cache.0.push_back((key, texture.clone())); + }); + texture + }); + if let Some(texture) = texture { + let h = scaled(HEIGHT, size); + let at = Rect::from_min_size(pos2(rect.left(), rect.center().y - h / 2.0), vec2(slot, h)); + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + ui.painter().image(texture.id(), at, uv, crate::theme::Tokens::get(ctx).text); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index c8f441ac33..577ecda468 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -1,7 +1,7 @@ //! Direct Selection tool (A, #790), the Convert Point tool (#3204), the Pens' ⌘/Ctrl (Direct //! Selection: the Pen, Freeform Pen and Curvature Pen) and the Pen's ⌥/Alt (Convert Point) -//! modifiers, as in Photoshop. It edits the paths the canvas shows: the targeted vector mask or -//! the active shape layer's path, and the work path. +//! modifiers, as in Photoshop. It edits the paths the canvas shows: the targeted vector mask, the +//! active shape layer's path or the active type layer's Type Path, and the work path. //! //! * Click an anchor to select it (⇧ adds or removes, ⌥ selects its whole subpath), drag on empty //! canvas to marquee-select anchors, click empty canvas to deselect. @@ -39,6 +39,8 @@ pub enum PathRef { Work, /// A layer's shape path, or its vector mask. Layer(u64), + /// A type layer's Type Path (#9114), apart from a vector mask the layer may have. + TypePath(u64), /// The Pen path being drawn (`ui.pen`): edited in place, not through the engine. Pen, } @@ -49,6 +51,7 @@ impl PathRef { match self { PathRef::Work => json!({"name": "work"}), PathRef::Layer(id) => json!({"name": "layer", "layer": id}), + PathRef::TypePath(id) => json!({"name": "layer", "layer": id, "typePath": true}), // Never sent: edits to the Pen path being drawn don't go through the engine. PathRef::Pen => json!({}), } @@ -163,12 +166,16 @@ pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool { || matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint) } -/// The active paths, front first: the targeted vector mask or the active shape layer's path, then -/// the work path. The Pen's Auto Add/Delete edits these (`anchor_tools::pen_auto`). +/// The active paths, front first: the targeted vector mask, the active shape layer's path or the +/// active type layer's Type Path (#9114), then the work path. The Pen's Auto Add/Delete edits these +/// (`anchor_tools::pen_auto`). pub(crate) fn active_paths(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { - let layer = crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app)); + let layer = crate::vector_ui::targeted_vector_mask(app) + .or_else(|| crate::vector_ui::active_shape_path(app)) + .map(|(id, p)| (PathRef::Layer(id), p)) + .or_else(|| crate::vector_ui::active_type_path(app).map(|(id, p)| (PathRef::TypePath(id), p))); let work = app.session.active().and_then(|st| st.doc.work_path.clone()).filter(|_| crate::vector_ui::work_path_shown(app)); - layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() + layer.into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() } /// The paths Direct Selection edits, front first: the Pen path being drawn, the active paths, then @@ -301,7 +308,7 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - app.ui.direct_selection.drag = Some(Drag::Marquee { start: p, end: p, add: mods.shift }); return true; }; - if let PathRef::Layer(id) = target + if let PathRef::Layer(id) | PathRef::TypePath(id) = target && app.session.active().and_then(|st| st.active_layer).map(|l| l.0) != Some(id) { let _ = app.run("layer.select", json!({"layer": id})); diff --git a/crates/ui-egui/src/tools/direct_select/tests.rs b/crates/ui-egui/src/tools/direct_select/tests.rs index 31a16bfcda..27a9fc59d8 100644 --- a/crates/ui-egui/src/tools/direct_select/tests.rs +++ b/crates/ui-egui/src/tools/direct_select/tests.rs @@ -517,3 +517,55 @@ fn a_curvature_pen_double_click_through_the_canvas_rounds_a_corner() { assert!(k.smooth && k.in_ctrl != k.anchor, "the double-clicked corner is smooth: {k:?}"); assert!(h.state().ui.pen.is_none(), "and no path was started"); } + +/// #9114: with type on a path selected, Direct Selection reshapes the type's own path (in front of +/// the work path it was made from) and the type follows, in one undoable step. +#[test] +fn dragging_an_anchor_of_type_on_a_path_moves_the_type() { + let mut app = app(Tool::DirectSelection); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap(); + let id = app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + app.run("type.attachToPath", json!({})).unwrap(); + let type_path = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + photocraft_doc::LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).unwrap(), + _ => panic!("not a type layer"), + }; + let n = steps(&app); + drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::TypePath(id)), "the type path, in front of the work path"); + let end = type_path(&app).subpaths[0].knots[1].anchor; + assert!((end.x - 160.0).abs() < 1e-6 && (end.y - 180.0).abs() < 1e-6, "{end:?}"); + assert_eq!(work(&app).subpaths[0].knots[1].anchor, Point::new(100.0, 180.0), "the work path stays"); + assert_eq!(steps(&app), n + 1); + assert!(app.session.undo()); + assert_eq!(type_path(&app).subpaths[0].knots[1].anchor.x.round(), 100.0); +} + +/// #9114: with a type-on-a-path layer's vector mask targeted, Direct Selection edits the mask, not +/// the Type Path; untargeted, it edits the Type Path and the mask stays. +#[test] +fn a_targeted_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { + let mut app = app(Tool::DirectSelection); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap(); + let id = app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + app.run("type.attachToPath", json!({})).unwrap(); + let rect = json!({"subpaths": [{"closed": true, "knots": [[20, 20], [180, 20], [180, 160], [20, 160]]}]}); + app.run("layer.vectorMask.add", json!({"layer": id, "path": rect})).unwrap(); + app.ui.vector_mask_target = true; + let layer = |app: &PhotocraftApp| app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().clone(); + let type_path = |app: &PhotocraftApp| match &layer(app).content { + photocraft_doc::LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).unwrap(), + _ => panic!("not a type layer"), + }; + let before = type_path(&app); + drag(&mut app, [20.2, 20.2], [40.2, 30.2], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(id))); + assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0), "the mask's corner moved"); + assert_eq!(type_path(&app), before, "the Type Path stays"); + // With the mask no longer targeted, the Type Path is in front again and the mask stays. + app.ui.vector_mask_target = false; + drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::TypePath(id))); + assert!((type_path(&app).subpaths[0].knots[1].anchor.x - 160.0).abs() < 1e-6); + assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0)); +} diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index 729a24dc67..4ea5da8a72 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -394,8 +394,9 @@ pub fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc if cmd == cmds::CREATE { let mut l = cmds::new_layer(&app.session, &doc, &p).ok()?; l.id = PREVIEW_LAYER; - let above = app.session.active().and_then(|s| s.active_layer); - shown.insert_above(above, l); + // Where the committed layer will go, so the preview doesn't jump on release. + let active = app.session.active().and_then(|s| s.active_layer); + photocraft_engine::layer_place::insert_new(&mut shown, active, l, photocraft_engine::layer_place::Place::AutoEditable); } else { let l = doc.layer(layer)?; let f = edited_fill(app, l, doc.bounds(), cmd, &p)?; diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 78fb6c3548..b8c56bf497 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -228,9 +228,13 @@ pub fn remove_pending_add(app: &mut PhotocraftApp, points: &[[f64; 3]]) { app.remove_trail = None; app.remove_pending_target = Some(target); } - let diameter = app.session.tools.brush.size; - app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed_stroke(points, diameter); - app.remove_pending.push(points.to_vec()); + // The brush it was drawn with goes with it: the tint shows it, the removal uses it, however + // the brush changes before ↩. + let b = &app.session.tools.brush; + let entry = json!({"points": points, "size": b.size, "hardness": b.hardness * 100.0, "spacing": b.spacing * 100.0}); + let brush = || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &entry); + app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed_stroke_reach(points, brush); + app.remove_pending.push(entry); app.ui.status = crate::i18n::fmt(tl!("Strokes to remove: {n} (Enter applies, Esc cancels)"), &[("n", &app.remove_pending.len().to_string())]); app.ui.status_error = false; } diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index d7d07d6e9f..d157336960 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -531,6 +531,35 @@ fn remove_tool_stroke_removes_what_it_covers() { assert!(px.iter().zip(bg).all(|(a, b)| (a - b).abs() < 0.02), "{px:?} vs {bg:?}"); } +/// A waiting Remove stroke keeps the brush it was drawn with (#8923 review): changing the brush +/// before ↩ neither changes its tint nor what its removal takes. +#[test] +fn waiting_remove_strokes_keep_their_own_brush() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + let m = egui::Modifiers::NONE; + let stroke = |app: &mut PhotocraftApp, x: f64| { + tool_event(app, ToolEvent::Down { x, y: 20.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x, y: 40.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x, y: 40.0 }, m); + }; + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap(); + stroke(&mut app, 25.0); + let tint = |app: &PhotocraftApp| app.remove_trail.as_ref().map(|t| (0..100).filter(|&x| t.coverage(x, 30) > 0).count()); + let first = tint(&app); + app.run("tools.setBrush", json!({"brush": {"size": 4, "hardness": 1.0}})).unwrap(); + stroke(&mut app, 75.0); + assert!(tint(&app).unwrap() > first.unwrap(), "the second stroke adds its tint"); + assert!((0..100).filter(|&x| app.remove_trail.as_ref().unwrap().coverage(x, 30) > 0).any(|x| x < 25 - 10), "the first keeps its soft 20 px reach"); + assert!(remove_pending_commit(&mut app)); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (_, p) = app.session.journal.last().cloned().expect("a journaled command"); + let sizes: Vec<_> = p["strokes"].as_array().unwrap().iter().map(|e| (e["size"].as_f64(), e["hardness"].as_f64())).collect(); + assert_eq!(sizes, [(Some(20.0), Some(0.0)), (Some(4.0), Some(100.0))], "each stroke is removed with its own brush"); +} + #[test] fn remove_after_each_stroke_off_collects_strokes_until_enter_or_escape() { let mut app = app(); @@ -657,7 +686,7 @@ fn queued_remove_starts_a_new_queue_after_target_switch() { app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); remove_pending_add(&mut app, &[[40.0, 10.0, 1.0], [44.0, 12.0, 1.0]]); assert_eq!(app.remove_pending.len(), 1, "strokes from different layers must not be combined"); - assert_eq!(app.remove_pending[0][0][0], 40.0); + assert_eq!(app.remove_pending[0]["points"][0][0], 40.0); assert!(remove_pending_live(&mut app)); } diff --git a/crates/ui-egui/src/tools/stroke_trail.rs b/crates/ui-egui/src/tools/stroke_trail.rs index af09fca1c4..4a087be890 100644 --- a/crates/ui-egui/src/tools/stroke_trail.rs +++ b/crates/ui-egui/src/tools/stroke_trail.rs @@ -4,7 +4,8 @@ //! It is a coverage mask in document space, stamped segment by segment as the pointer moves and //! drawn as one texture over the document. The Spot Healing Brush's trail is instead the coverage //! of the brush's own dabs ([`Trail::feed_dabs`]): hardness, pressure and shape dynamics show as -//! they heal (#2364). It used to be an egui polyline as wide as the brush: +//! they heal (#2364). The Remove Tool's is where those dabs reach at all ([`Trail::feed_reach`]), +//! which is what it removes. It used to be an egui polyline as wide as the brush: //! egui tessellates a polyline whose width is much larger than its steps (any zoomed-in drag) //! into hard pie wedges fanning out across the canvas (#189), and translucent overlaps doubled up. @@ -31,11 +32,16 @@ pub struct Trail { tex: Option, /// The stroke's dabs, when the trail shows their coverage ([`Self::feed_dabs`]). dabs: Option, + /// Coverage earlier strokes in the same mask left (the Remove Tool's waiting strokes); empty + /// when there are none. A dab stroke's restamp keeps the larger of the two. + base: Vec, } /// The brush stroke behind a [`Trail::feed_dabs`] trail. struct Dabs { renderer: StrokeRenderer, + /// Any coverage counts in full ([`Trail::feed_reach`]). + reach: bool, /// Document pixels the last "finish now" tail (a lone first dab, smoothing catch-up) covered. tail: photocraft_geom::Rect, } @@ -44,7 +50,7 @@ impl Trail { pub fn new(doc: [u32; 2]) -> Self { let k = doc[0].max(doc[1]).div_ceil(MAX_SIDE).max(1); let (w, h) = (doc[0].div_ceil(k).max(1) as usize, doc[1].div_ceil(k).max(1) as usize); - Self { doc, k: k as f32, w, h, cov: vec![0; w * h], fed: 0, dirty: None, tex: None, dabs: None } + Self { doc, k: k as f32, w, h, cov: vec![0; w * h], fed: 0, dirty: None, tex: None, dabs: None, base: Vec::new() } } /// Coverage at a mask pixel (tests). @@ -74,22 +80,36 @@ impl Trail { self.fed = points.len(); } - /// Stamp a whole new drag into the same mask (the Remove tool's waiting strokes, #6555): its - /// points are counted from its own start, not from where the previous drag ended. - pub fn feed_stroke(&mut self, points: &[[f64; 3]], diameter: f32) { - self.fed = 0; - self.feed(points, diameter); - } - /// Show the coverage the brush's own dabs leave along the drag, as the stroke commit renders /// it (`photocraft_paint::retouch::stroke_coverage`): soft edges for a soft brush, the size and /// shape each dab takes from pen pressure and dynamics. `brush` is asked for once, on the first /// call. What finishing the stroke now would add (the press's lone first dab) shows too. pub fn feed_dabs(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings) { + self.feed_dabs_with(points, brush, false); + } + + /// Show where the brush's own dabs reach at all, in full: the Remove Tool removes every pixel a + /// dab covers, however faintly (`retouch_cmds::remove`'s hole), so a soft tip's whole reach is + /// tinted, not just its nominal radius or its opaque core. + pub fn feed_reach(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings) { + self.feed_dabs_with(points, brush, true); + } + + /// [`Self::feed_reach`] for a whole new drag into the same mask (the Remove Tool's waiting + /// strokes, #6555): the earlier strokes' tint stays under it. + pub fn feed_stroke_reach(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings) { + self.base.clone_from(&self.cov); + self.dabs = None; + self.fed = 0; + self.feed_reach(points, brush); + } + + fn feed_dabs_with(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings, reach: bool) { if self.dabs.is_some() && self.fed >= points.len() { return; } - let mut dabs = self.dabs.take().unwrap_or_else(|| Dabs { renderer: StrokeRenderer::new(&brush(), None, 1.0), tail: photocraft_geom::Rect::EMPTY }); + let mut dabs = + self.dabs.take().unwrap_or_else(|| Dabs { renderer: StrokeRenderer::new(&brush(), None, 1.0), reach, tail: photocraft_geom::Rect::EMPTY }); let new: Vec = points .get(self.fed..) .unwrap_or(&[]) @@ -105,13 +125,20 @@ impl Trail { changed = changed.union(&dabs.tail); let tail = tail.map(|(_, t)| t); let renderer = &dabs.renderer; - self.restamp(changed, |x, y| renderer.coverage_at(x, y).max(tail.as_ref().map_or(0.0, |t| t.coverage_at(x, y)))); + let full = |c: f32| if dabs.reach && c > 0.0 { 1.0 } else { c }; + let reach = dabs.reach; + let touches = |r| renderer.touches(r) || tail.as_ref().is_some_and(|t| t.touches(r)); + self.restamp(changed, reach, touches, |x, y| full(renderer.coverage_at(x, y).max(tail.as_ref().map_or(0.0, |t| t.coverage_at(x, y))))); self.dabs = Some(dabs); } /// Recompute the mask pixels over the document rectangle `r` from `cov` (document pixel → - /// coverage 0..=1), sampled at each mask pixel's centre. - fn restamp(&mut self, r: photocraft_geom::Rect, cov: impl Fn(i32, i32) -> f32) { + /// coverage 0..=1), sampled at each mask pixel's centre. With `block`, a mask pixel takes the + /// largest coverage of all the document pixels it stands for instead: on a big document (one + /// mask pixel per k x k) a thin Remove stroke can fall between the centres, and every pixel it + /// touches is removed. `touches` says whether `cov` can be above 0 anywhere in a document + /// rectangle, so blocks the stroke never reached aren't scanned pixel by pixel. + fn restamp(&mut self, r: photocraft_geom::Rect, block: bool, touches: impl Fn(photocraft_geom::Rect) -> bool, cov: impl Fn(i32, i32) -> f32) { if r.is_empty() { return; } @@ -123,13 +150,40 @@ impl Trail { if x1 <= x0 || y1 <= y0 { return; } + // Document pixels of mask pixel `i` along a side `n` long: its centre, or its whole span + // clipped to the document (at least one pixel). + let span = |i: usize, n: u32| -> (i32, i32) { + if block { + let lo = (i as f64 * k) as i64; + let hi = (((i + 1) as f64 * k) as i64).min(i64::from(n)).max(lo + 1); + (i32::try_from(lo).unwrap_or(i32::MAX), i32::try_from(hi).unwrap_or(i32::MAX)) + } else { + let c = ((i as f64 + 0.5) * k).floor() as i32; + (c, c.saturating_add(1)) + } + }; for y in y0..y1 { - let dy = ((y as f64 + 0.5) * k).floor() as i32; + let (dy0, dy1) = span(y, self.doc[1]); for x in x0..x1 { - let dx = ((x as f64 + 0.5) * k).floor() as i32; - let c = cov(dx, dy); + let (dx0, dx1) = span(x, self.doc[0]); + let i = y * self.w + x; + let base = self.base.get(i).copied().unwrap_or(0); + let mut c = 0.0f32; + let skip = base == u8::MAX || !touches(photocraft_geom::Rect::new(dx0, dy0, dx1, dy1)); + 'block: for dy in if skip { 0..0 } else { dy0..dy1 } { + for dx in dx0..dx1 { + let v = cov(dx, dy); + if v > c { + c = v; + if c >= 1.0 { + break 'block; + } + } + } + } let c = if c.is_finite() { (c.clamp(0.0, 1.0) * 255.0).round() as u8 } else { 0 }; - if let Some(v) = self.cov.get_mut(y * self.w + x) { + let c = c.max(base); + if let Some(v) = self.cov.get_mut(i) { *v = c; } } @@ -239,8 +293,9 @@ mod tests { &[[50.0, 120.0, 1.0], [120.0, 120.0, 1.0]], &[[50.0, 200.0, 1.0], [80.0, 200.0, 1.0], [120.0, 200.0, 1.0], [160.0, 200.0, 1.0], [200.0, 200.0, 1.0], [260.0, 200.0, 1.0]], ]; + let brush = BrushSettings { size: 10.0, ..Default::default() }; for s in strokes { - t.feed_stroke(s, 10.0); + t.feed_stroke_reach(s, || brush.clone()); } for (x, y) in [(50, 50), (85, 50), (199, 50), (50, 120), (85, 120), (119, 120), (50, 200), (65, 200), (100, 200), (259, 200)] { assert_eq!(t.coverage(x, y), 255, "({x}, {y}) lies on a stroke"); @@ -249,6 +304,80 @@ mod tests { assert_eq!(t.coverage(150, 160), 0); } + /// The Remove Tool removes every pixel a dab touches: its trail is the dabs' whole reach in + /// full, a soft tip's well past the nominal radius, and never less than the coverage itself. + #[test] + fn a_reach_trail_tints_all_a_soft_tip_touches() { + let pts = [[50.0, 50.0, 1.0], [150.0, 50.0, 1.0]]; + let brush = BrushSettings { size: 20.0, hardness: 0.0, ..Default::default() }; + let mut reach = Trail::new([200, 100]); + reach.feed_reach(&pts, || brush.clone()); + let mut soft = Trail::new([200, 100]); + soft.feed_dabs(&pts, || brush.clone()); + let r = photocraft_paint::tip_reach(10.0, 0.0); + assert!(r > 15.0, "a soft tip reaches past its 10 px radius: {r}"); + assert_eq!(reach.coverage(100, 50 + 14), 255, "4 px past the radius, still removed"); + assert!(soft.coverage(100, 50 + 14) < 128, "where the soft coverage is faint"); + assert_eq!(reach.coverage(100, 50 + r.ceil() as usize + 2), 0, "nothing past the reach"); + // Where the soft trail shows anything the reach is tinted in full (it also takes coverage + // too faint to show as a soft trail's 8 bits). + for y in 0..100 { + for x in 0..200 { + assert!(soft.coverage(x, y) == 0 || reach.coverage(x, y) == 255, "({x}, {y})"); + assert!(matches!(reach.coverage(x, y), 0 | 255), "({x}, {y}): all or nothing"); + } + } + } + + /// A waiting Remove stroke keeps its tint where a later one crosses it (each restamps only the + /// area it changed, over what was there). + #[test] + fn a_later_reach_stroke_keeps_the_earlier_ones_tint() { + let mut t = Trail::new([200, 200]); + let brush = BrushSettings { size: 20.0, ..Default::default() }; + t.feed_stroke_reach(&[[20.0, 100.0, 1.0], [180.0, 100.0, 1.0]], || brush.clone()); + t.feed_stroke_reach(&[[100.0, 20.0, 1.0], [100.0, 180.0, 1.0]], || brush.clone()); + for (x, y) in [(40, 100), (95, 100), (100, 100), (105, 100), (160, 100), (100, 40), (100, 160)] { + assert_eq!(t.coverage(x, y), 255, "({x}, {y}) lies on a stroke"); + } + assert_eq!(t.coverage(40, 40), 0); + } + + /// On a big document one mask pixel stands for k x k document pixels. A thin Remove stroke + /// that falls between the mask pixels' centres still removes what it touches, so it still + /// shows. + #[test] + fn a_thin_reach_stroke_on_a_big_document_still_shows() { + // A 2 px brush reaches document rows 10-14, a 4 px one rows 9-16; the mask's centres + // sample rows 9 and 15 at k = 6, rows 6 and 18 at k = 12. + for (doc, size) in [([6000, 4000], 2.0), ([12000, 8000], 4.0)] { + let brush = BrushSettings { size, hardness: 1.0, ..Default::default() }; + let pts = [[300.0, 12.5, 1.0], [3000.0, 12.5, 1.0]]; + let mut t = Trail::new(doc); + t.feed_reach(&pts, || brush.clone()); + let x = (1500.0 / t.scale()) as usize; + assert!((0..3).any(|y| t.coverage(x, y) == 255), "{size} px on {doc:?}: the stroke shows"); + assert_eq!(t.coverage(x, 3), 0, "{size} px on {doc:?}: nothing below it"); + let mut s = Trail::new(doc); + s.feed_stroke_reach(&pts, || brush.clone()); + assert!((0..3).any(|y| s.coverage(x, y) == 255), "{size} px on {doc:?}: a waiting stroke too"); + } + } + + /// A later stroke restamps its whole dirty rectangle, earlier strokes' tint included, also + /// off its own path. + #[test] + fn a_crossing_reach_stroke_keeps_the_earlier_tint_inside_its_rect() { + let mut t = Trail::new([200, 200]); + let brush = BrushSettings { size: 20.0, ..Default::default() }; + t.feed_stroke_reach(&[[20.0, 100.0, 1.0], [180.0, 100.0, 1.0]], || brush.clone()); + t.feed_stroke_reach(&[[20.0, 20.0, 1.0], [180.0, 180.0, 1.0]], || brush.clone()); + assert_eq!(t.coverage(150, 100), 255, "the first stroke, off the second, inside its rect"); + assert_eq!(t.coverage(50, 100), 255); + assert_eq!(t.coverage(150, 150), 255, "the second stroke"); + assert_eq!(t.coverage(150, 40), 0); + } + #[test] fn hostile_points_and_huge_documents_are_safe() { let mut t = Trail::new([300_000, 2]); diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 1aac4e1854..672bd82868 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -35,11 +35,14 @@ pub(crate) use begin::begin_content_aware; pub use begin::{begin, begin_copy, begin_placed, begin_selection, begin_warp, enter_warp, leave_warp, warps_type}; pub(crate) use commit::{SAVE_FOR_WEB, committing, nudge}; pub use commit::{cancel, commit, end_if_left, follow_edits, intercept, is_enabled, on_job_event, track_steps}; +#[cfg(test)] +use drag_modes::{HandleIndicator, handle_indicator, keep_convex, turns}; pub(crate) use drag_modes::{apply_drag, corner_distorts, legacy_mods}; #[cfg(test)] pub(crate) use drag_modes::{apply_mode_drag, unlinked_mods}; +pub(crate) use draw::draw_handle_cursor; #[cfg(test)] -use drag_modes::{keep_convex, turns}; +use draw::scale_values; #[cfg(test)] pub(crate) use draw::{Readout, live_readout, styled_frame}; pub(crate) use draw::{carries_selection_of, draw_selection}; diff --git a/crates/ui-egui/src/tools/transform_tool/drag_modes.rs b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs index 8800df7e04..49f594e08f 100644 --- a/crates/ui-egui/src/tools/transform_tool/drag_modes.rs +++ b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs @@ -21,6 +21,33 @@ pub(crate) fn corner_distorts(app: &PhotocraftApp, index: usize, mods: egui::Mod mods.command && !(mods.alt && mods.shift) } +/// The pointer a handle shows for a drag that distorts or skews the box rather than scaling or +/// rotating it (#5405). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum HandleIndicator { + Distort, + Skew, +} + +/// What dragging handle `h` with `mods` does, worked out by the same rules as the drag itself +/// ([`drag_mods`], [`mode_mods`], [`apply_mode_drag`]): ⌘ on a corner distorts (⌘⌥⇧ adds +/// perspective) and on an edge skews, Distort and Perspective modes distort from the corners, +/// Skew mode skews from the edges. Rotate mode turns the box whatever the keys, a Skew-mode corner +/// slides along an edge, editable type refuses Distort and Content-Aware Scale only scales: `None`. +pub(super) fn handle_indicator(app: &PhotocraftApp, t: &TransformSession, h: Hit, mods: egui::Modifiers) -> Option { + if t.warp.is_some() || t.content_aware.is_some() || !mode_allows(t.mode, h) { + return None; + } + let (mode, mods) = drag_mods(app, t, h, mods); + match (mode, h) { + (TransformMode::Rotate, _) | (TransformMode::Skew, Hit::Corner(_)) => None, + (TransformMode::Skew, Hit::Edge(_)) => Some(HandleIndicator::Skew), + (_, Hit::Corner(_)) if mode_mods(mode, h, mods).command => Some(HandleIndicator::Distort), + (_, Hit::Edge(_)) if mods.command => Some(HandleIndicator::Skew), + _ => None, + } +} + /// Editable type can be scaled, rotated and skewed but not distorted (#2630): the rule that greys /// Distort and Perspective in `enable_rules::disabled`, for the box's own layer. A box on a path, /// on the selection outline or on a lone mask or channel moves no type. diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 2dce211108..6c70e029fd 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -1,9 +1,78 @@ use super::begin::warps_type; +use super::drag_modes::{HandleIndicator, handle_indicator}; use super::options_bar::{quad_scale, readout}; -use super::pointer::{Hit, rotate_dir, rotation_degrees}; +use super::pointer::{Hit, handle_at, rotate_dir, rotation_degrees}; use super::warp::{on_section_edge, quick_split_kind, single_patch}; use super::*; +/// The distort or skew pointer at screen point `at`, where [`super::cursor`] hid the system +/// pointer over a handle. The canvas calls it from its cursor branch, so nothing is drawn where a +/// guide, a pan or a zoom set the cursor instead. +pub(crate) fn draw_handle_cursor(app: &PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, at: Pos2, mods: egui::Modifiers) { + let Some(t) = &app.ui.transform else { return }; + let h = handle_at(app, t, xf.to_doc(at), super::handle_tolerance(app)); + let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + match (h, handle_indicator(app, t, h, mods)) { + (Hit::Corner(i), Some(HandleIndicator::Distort)) => { + if let Some(q) = t.quad.get(i) { + draw_distort_cursor(ctx, at, scr(*q) - scr(t.pivot)); + } + } + (Hit::Edge(i), Some(HandleIndicator::Skew)) => { + if let (Some(a), Some(b)) = (t.quad.get(i), t.quad.get((i + 1) % 4)) { + draw_skew_cursor(ctx, at, scr(*b) - scr(*a)); + } + } + _ => {} + } +} + +/// Draws the Free Distort cursor at `at`: a high-contrast vector pointer pointing toward +/// or outward through the corner, with shadow outline for contrast on any canvas background. +fn draw_distort_cursor(ctx: &egui::Context, at: Pos2, toward: egui::Vec2) { + let len = toward.length(); + let u = if len.is_finite() && len > 1e-6 { toward / len } else { vec2(-1.0, -1.0).normalized() }; + let perp = vec2(-u.y, u.x); + let tokens = crate::theme::Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("transform-distort-cursor"))); + + // An arrowhead dart pointing along `u` with tip at `at`. + let tip = at; + const LENGTH: f32 = 16.0; + const HALF_WIDTH: f32 = 7.0; + let base = tip - u * LENGTH; + let left = base + perp * HALF_WIDTH; + let right = base - perp * HALF_WIDTH; + let notch = tip - u * (LENGTH * 0.65); + + // Convex decomposition: two triangles meeting along [tip, notch]. + painter.add(egui::Shape::convex_polygon(vec![tip, left, notch], tokens.accent_text, Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(vec![tip, notch, right], tokens.accent_text, Stroke::NONE)); + painter.add(egui::Shape::closed_line(vec![tip, left, notch, right], Stroke::new(1.5, tokens.shadow))); +} + +/// Draws the Skew cursor at `at`: opposing parallel arrows aligned with the edge tangent `tangent`. +fn draw_skew_cursor(ctx: &egui::Context, at: Pos2, tangent: egui::Vec2) { + let len = tangent.length(); + let u = if len.is_finite() && len > 1e-6 { tangent / len } else { vec2(1.0, 0.0) }; + let perp = vec2(-u.y, u.x); + let tokens = crate::theme::Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("transform-skew-cursor"))); + + for (offset, dir) in [(4.0f32, 1.0f32), (-4.0f32, -1.0f32)] { + let center = at + perp * offset; + let p_start = center - u * (dir * 9.0); + let p_end = center + u * (dir * 9.0); + painter.line_segment([p_start, p_end], Stroke::new(3.5, tokens.shadow)); + painter.line_segment([p_start, p_end], Stroke::new(1.5, tokens.accent_text)); + + let tip = p_end + u * (dir * 3.5); + let wing1 = p_end - u * (dir * 2.5) + perp * 3.5; + let wing2 = p_end - u * (dir * 2.5) - perp * 3.5; + painter.add(egui::Shape::convex_polygon(vec![tip, wing1, wing2], tokens.accent_text, Stroke::new(1.0, tokens.shadow))); + } +} + /// For each vertex of the preview's `n` × `n` grid over the unit square (row by row), whether it /// maps to the front side of `h`'s horizon. A Distort dragged past the horizon sends the rest of /// the image to the far side, where its cells would wrap round infinity; the preview leaves them @@ -83,7 +152,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some(w) = &t.warp { let over_canvas = painter.ctx().input(|i| i.pointer.hover_pos()).filter(|p| xf.rect.contains(*p)).map(|p| xf.to_doc(p)); let at = pv.split_pointer.or(over_canvas); - let alt = painter.ctx().input(|i| i.modifiers.alt || i.modifiers.command); + // The same keys as `cursor`, sticky ones included, so the guide matches the pointer. + let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); + let alt = mods.alt || mods.command; let guide = at.filter(|_| !warps_type(app)).and_then(|p| { let tool = pv.split_tool.or_else(|| { (alt || pv.split_quick).then(|| { @@ -136,7 +207,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform } // Preferences › Tools › Show Transformation Values off hides it, as in Photoshop (#204). if let Some(r) = live_readout(app).filter(|_| app.session.prefs().tools.show_transformation_values) { - draw_live_readout(painter.ctx(), at, r); + draw_live_readout(app, painter.ctx(), at, r); } } } @@ -237,8 +308,11 @@ pub(crate) fn styled_frame(app: &PhotocraftApp, zoom: f32, dragging: bool) -> Op pub(crate) enum Readout { /// Clockwise degrees in document space (`rotation_degrees`), whatever the view's turn or flip. Angle(f64), - /// Width and height in percent of the original box. - Scale([f64; 2]), + /// Width and height in percent of the original box, and the box's size in document pixels. + /// The size is the scaled width and height (what W and H 100 % mean in the options bar), + /// not the edge lengths: a skew leans the sides, which lengthens them but not the height + /// between the top and bottom edges. + Scale { percent: [f64; 2], px: [f64; 2] }, /// Document pixels moved since the press. Offset([f64; 2]), } @@ -253,7 +327,8 @@ pub(crate) fn live_readout(app: &PhotocraftApp) -> Option { Hit::Inside => Some(Readout::Offset([t.quad[0][0] - g.quad0[0][0], t.quad[0][1] - g.quad0[0][1]])), Hit::Corner(_) | Hit::Edge(_) if parallelogram(&t.quad) => { let (w, h, _, _) = readout(t); - (w.is_finite() && h.is_finite()).then_some(Readout::Scale([w, h])) + let px = [w / 100.0 * (t.rect[2] - t.rect[0]), h / 100.0 * (t.rect[3] - t.rect[1])]; + (w.is_finite() && h.is_finite()).then_some(Readout::Scale { percent: [w, h], px }) } Hit::Corner(_) | Hit::Edge(_) | Hit::Pivot => None, } @@ -267,21 +342,32 @@ fn parallelogram(q: &[[f64; 2]; 4]) -> bool { } /// [`live_readout`] as the rounded label beside the pointer (the marquee's and Crop's readout). -fn draw_live_readout(ctx: &egui::Context, at: Pos2, r: Readout) { - // Round first so a hair below zero never reads "-0". - let fixed = |v: f64, places: i32| { - let k = 10f64.powi(places); - let v = (v * k).round() / k; - if v == 0.0 { 0.0 } else { v } - }; +fn draw_live_readout(app: &PhotocraftApp, ctx: &egui::Context, at: Pos2, r: Readout) { let id = "transform-readout"; match r { Readout::Angle(a) => crate::canvas::draw_readout(ctx, id, at, ["Angle:"], [format!("{:.1}°", fixed(a, 1))]), - Readout::Scale([w, h]) => crate::canvas::draw_readout(ctx, id, at, ["W:", "H:"], [w, h].map(|v| format!("{:.1}%", fixed(v, 1)))), + Readout::Scale { percent, px } => crate::canvas::draw_readout(ctx, id, at, ["W:", "H:"], scale_values(app, percent, px)), Readout::Offset([dx, dy]) => crate::canvas::draw_readout(ctx, id, at, ["ΔX:", "ΔY:"], [dx, dy].map(|v| format!("{:.0} px", fixed(v, 0)))), } } +/// `v` rounded to `places` decimals, so a hair below zero never reads "-0". +fn fixed(v: f64, places: i32) -> f64 { + let k = 10f64.powi(places); + let v = (v * k).round() / k; + if v == 0.0 { 0.0 } else { v } +} + +/// The W and H rows of the scale readout: the box's size in the Units & Rulers unit at the +/// document's resolution, as Photoshop shows it (cm when the rulers are in centimeters, #9400); +/// the scale of the original box when the rulers are in percent. +pub(crate) fn scale_values(app: &PhotocraftApp, percent: [f64; 2], px: [f64; 2]) -> [String; 2] { + if app.session.prefs().units_and_rulers.rulers == photocraft_engine::prefs::Unit::Percent { + return percent.map(|v| format!("{:.1}%", fixed(v, 1))); + } + crate::canvas::size_readout(app, [0.0, 0.0, px[0], px[1]]) +} + /// Width and height of the document being transformed, in document pixels. fn canvas_size(pv: &TransformPreview) -> [f32; 2] { [pv.doc.size.width as f32, pv.doc.size.height as f32] diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index 7df9bfa6f1..e11f0c97c9 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -1,6 +1,6 @@ use super::begin::warps_type; use super::commit::{commit, committing, moves_type}; -use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, mode_allows, mode_mods}; +use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, handle_indicator, mode_allows, mode_mods}; use super::warp::{quick_split_kind, split_cursor, surface_at, warp_hit, warp_pointer}; use super::*; @@ -239,9 +239,13 @@ pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: { return None; } - let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); - if !rotating && !near_rotate_corner(t, p, tol) { - return None; + // During a drag the arrow shows only while it rotates: not when a handle that scales, skews + // or distorts strays past a corner (#5405). + match pv.and_then(|pv| pv.gesture) { + Some(g) if g.hit == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(g.hit, Hit::Corner(_) | Hit::Edge(_))) => {} + Some(_) => return None, + None if !near_rotate_corner(t, p, tol) => return None, + None => {} } let dist = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); let i = (0..4).min_by(|&a, &b| dist(t.quad[a]).total_cmp(&dist(t.quad[b])))?; @@ -256,9 +260,14 @@ pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: (l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l]) } +/// The handle a drag in progress holds, else the one under document point `p`. +pub(super) fn handle_at(app: &PhotocraftApp, t: &TransformSession, p: [f64; 2], tol: f64) -> Hit { + app.transform_preview.as_ref().and_then(|pv| pv.gesture.map(|g| g.hit)).unwrap_or_else(|| hit(t, p, tol)) +} + /// Cursor for hovering a document point while transforming. `xf` is the canvas's view; -/// `quick_split` is Ctrl or Option, which arms a quick split while a warp is active. -pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], quick_split: bool) -> Option { +/// `mods` provides modifier keys (Command for Distort on corners / Skew on edges; Alt/Command for quick split in warp). +pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modifiers) -> Option { let t = app.ui.transform.as_ref()?; let tol = handle_tolerance(app); if let Some(w) = &t.warp { @@ -266,6 +275,7 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], quick_split: boo return Some(CursorIcon::Default); } let armed = app.transform_preview.as_ref().and_then(|pv| pv.split_tool); + let quick_split = mods.alt || mods.command; if armed.is_some() || quick_split { // One search for the grid position under the pointer, for both the kind and the arrow. let m = w.to_mesh(1, 1); @@ -278,14 +288,18 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], quick_split: boo } return Some(if w.mesh.as_ref().and_then(|m| surface_at(m, p)).is_some() { CursorIcon::Grab } else { CursorIcon::Default }); } - let h = hit(t, p, tol); + let h = handle_at(app, t, p, tol); if !mode_allows(t.mode, h) || (t.content_aware.is_some() && h == Hit::Outside) { return Some(CursorIcon::Default); } + // A ⌘-drag outside the box still rotates, so ⌘ keeps the curved arrow there. if rotate_cursor_dir(app, p).is_some() { - // The overlay draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. + // The canvas draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. return Some(CursorIcon::None); } + // The canvas draws the distort or skew pointer in place of the hidden one + // (`draw_handle_cursor`); not while the box is being applied, when it draws no handles. + let indicator = handle_indicator(app, t, h, mods).filter(|_| committing(app).is_none()); // The box's corners run clockwise from the top-left; edge k joins corners k and k + 1. let corner = |k: usize| t.quad[k % 4]; let edge_mid = |k: usize| { @@ -295,6 +309,7 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], quick_split: boo // A handle resizes the box away from the opposite handle. let resize = |from: [f64; 2], to: [f64; 2]| crate::tool_cursor::resize([to[0] - from[0], to[1] - from[1]], xf); Some(match h { + Hit::Corner(_) | Hit::Edge(_) if indicator.is_some() => CursorIcon::None, Hit::Corner(i) => crate::tool_cursor::corner_resize(&t.quad, i, xf), Hit::Edge(i) => resize(edge_mid(i + 2), edge_mid(i)), Hit::Pivot => CursorIcon::Crosshair, diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 57d323b84a..1646fa0775 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1571,10 +1571,10 @@ fn hovering_just_outside_a_corner_asks_for_the_rotate_cursor() { let h = std::f64::consts::FRAC_1_SQRT_2; let (tl, br) = ([32.0 - tol * 1.5, 32.0 - tol * 1.5], [160.0 + tol * 1.5, 160.0 + tol * 1.5]); let xf = ViewXform::active(&app).unwrap(); - assert_eq!(cursor(&app, &xf, tl, false), Some(CursorIcon::None), "the arrow is drawn instead"); + assert_eq!(cursor(&app, &xf, tl, egui::Modifiers::NONE), Some(CursorIcon::None), "the arrow is drawn instead"); assert!(near2(rotate_cursor_dir(&app, tl), [h, h]), "{:?}", rotate_cursor_dir(&app, tl)); assert!(near2(rotate_cursor_dir(&app, br), [-h, -h]), "bends round the bottom-right corner"); - assert_eq!(cursor(&app, &xf, [60.0, 60.0], false), Some(CursorIcon::Move)); + assert_eq!(cursor(&app, &xf, [60.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::Move)); assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0]), None, "inside moves"); assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0]), None, "the corner handle scales"); assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0]), None); @@ -1657,7 +1657,10 @@ fn resize_cursors_turn_with_the_box_and_the_view() { let t = app.ui.transform.clone().unwrap(); let xf = ViewXform::active(&app).unwrap(); let mid = |i: usize| [(t.quad[i][0] + t.quad[(i + 1) % 4][0]) / 2.0, (t.quad[i][1] + t.quad[(i + 1) % 4][1]) / 2.0]; - let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], false)).chain((0..4).map(|i| cursor(&app, &xf, mid(i), false))).collect(); + let got: Vec<_> = (0..4) + .map(|i| cursor(&app, &xf, t.quad[i], egui::Modifiers::NONE)) + .chain((0..4).map(|i| cursor(&app, &xf, mid(i), egui::Modifiers::NONE))) + .collect(); let want = [want[0], want[1], want[0], want[1], want[2], want[3], want[2], want[3]].map(Some); assert_eq!(got, want, "box {deg}°, view {view}°, flip {flip}"); } @@ -1673,7 +1676,7 @@ fn corner_cursors_stay_diagonal_on_a_long_box() { crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); let t = app.ui.transform.clone().unwrap(); let xf = ViewXform::active(&app).unwrap(); - let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], false)).collect(); + let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], egui::Modifiers::NONE)).collect(); assert_eq!(got, [NwSe, NeSw, NwSe, NeSw].map(Some), "{rect:?}"); } } @@ -1724,8 +1727,39 @@ fn the_live_readout_follows_the_drag() { // The right edge doubles the width (proportional by default: the height too). ev(&mut app, ToolEvent::Down { x: 165.0, y: 93.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Move { x: 293.0, y: 93.0, pressure: 1.0 }); - let Some(Readout::Scale([w, h])) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; + let Some(Readout::Scale { percent: [w, h], px }) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; assert!((w - 200.0).abs() < 1e-6 && (h - 200.0).abs() < 1e-6, "{w} {h}"); + assert!((px[0] - 256.0).abs() < 1e-6 && (px[1] - 256.0).abs() < 1e-6, "{px:?}"); +} + +/// #9400: the W/H readout shows the box's size in the ruler unit, as Photoshop does, and +/// the scale of the original box when the rulers are in percent. +#[test] +fn the_scale_readout_follows_the_ruler_unit() { + use photocraft_engine::prefs::Unit; + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let ev = |app: &mut PhotocraftApp, e| crate::canvas::tool_event(app, e, egui::Modifiers::NONE); + // The right edge from 160 to 288: the 128 px box doubles (proportionally). + ev(&mut app, ToolEvent::Down { x: 160.0, y: 96.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 288.0, y: 96.0, pressure: 1.0 }); + let Some(Readout::Scale { percent, px }) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; + let shown = |app: &mut PhotocraftApp, unit: Unit| { + app.session.prefs.edit(|p| p.units_and_rulers.rulers = unit); + scale_values(app, percent, px) + }; + let dpi = app.session.active().unwrap().doc.resolution_dpi; + assert_eq!(dpi, 72.0, "the expected values below are at 72 ppi"); + assert_eq!(shown(&mut app, Unit::Pixels), ["256 px".to_string(), "256 px".to_string()]); + assert_eq!(shown(&mut app, Unit::Inches), ["3.556 in".to_string(), "3.556 in".to_string()]); + assert_eq!(shown(&mut app, Unit::Centimeters), ["9.03 cm".to_string(), "9.03 cm".to_string()]); + assert_eq!(shown(&mut app, Unit::Millimeters), ["90.31 mm".to_string(), "90.31 mm".to_string()]); + assert_eq!(shown(&mut app, Unit::Percent), ["200.0%".to_string(), "200.0%".to_string()]); + // A flipped box reads as a negative width, as in the options bar. + assert_eq!(scale_values(&app, [-50.0, 50.0], [-64.0, 64.0]), ["-50.0%".to_string(), "50.0%".to_string()]); + app.session.prefs.edit(|p| p.units_and_rulers.rulers = Unit::Pixels); + assert_eq!(scale_values(&app, [-50.0, 50.0], [-64.0, 64.0]), ["-64 px".to_string(), "64 px".to_string()]); } #[test] @@ -2988,3 +3022,180 @@ fn anchor_grid_point_on_quad_and_carry_pivot() { assert_eq!(matching_anchor(quad, [12.3, 45.6]), None); assert_eq!(matching_anchor(quad, [50.0, 30.0]), None); } + +#[test] +fn hovering_corner_with_ctrl_shows_distort_cursor() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let tol = handle_tolerance(&app); + let corner = [32.0, 32.0]; + let mut command = egui::Modifiers::NONE; + command.command = true; + let xf = ViewXform::active(&app).unwrap(); + + // Without Ctrl: corner handle gives standard diagonal scale cursor. + assert_eq!(cursor(&app, &xf, corner, egui::Modifiers::NONE), Some(CursorIcon::ResizeNwSe)); + + // With Ctrl: corner handle arms free distort, hiding OS cursor so custom pointer is drawn. + assert_eq!(cursor(&app, &xf, corner, command), Some(CursorIcon::None)); + + // A Cmd-drag just outside a corner still rotates, so the curved arrow stays. + let near_corner = [32.0 - tol * 1.5, 32.0 - tol * 1.5]; + assert_eq!(cursor(&app, &xf, near_corner, command), Some(CursorIcon::None)); + assert!(rotate_cursor_dir(&app, near_corner).is_some()); + assert_eq!(cursor(&app, &xf, near_corner, egui::Modifiers::NONE), Some(CursorIcon::None)); +} + +#[test] +fn hovering_edge_with_ctrl_shows_skew_cursor() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let edge = [96.0, 32.0]; // top edge midpoint + let mut command = egui::Modifiers::NONE; + command.command = true; + let xf = ViewXform::active(&app).unwrap(); + + // Without Ctrl: edge handle gives axis resize cursor. + assert_eq!(cursor(&app, &xf, edge, egui::Modifiers::NONE), Some(CursorIcon::ResizeVertical)); + + // With Ctrl: edge handle arms skew, hiding OS cursor so custom skew indicator is drawn. + assert_eq!(cursor(&app, &xf, edge, command), Some(CursorIcon::None)); +} + +#[test] +fn hovering_corner_on_text_layer_with_ctrl_retains_resize_cursor() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.run("type.create", json!({"x": 10, "y": 60, "text": "Hello"})).unwrap(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + + let t = app.ui.transform.as_ref().unwrap(); + let corner = t.quad[0]; + let mut command = egui::Modifiers::NONE; + command.command = true; + let xf = ViewXform::active(&app).unwrap(); + + // Editable type refuses distort, so holding Ctrl retains standard resize cursor on corners. + let without_ctrl = cursor(&app, &xf, corner, egui::Modifiers::NONE); + let with_ctrl = cursor(&app, &xf, corner, command); + assert_ne!(with_ctrl, Some(CursorIcon::None)); + assert_eq!(with_ctrl, without_ctrl, "text layer must retain resize cursor"); +} + +#[test] +fn cursor_during_drag_stays_stable() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let mut command = egui::Modifiers::NONE; + command.command = true; + let xf = ViewXform::active(&app).unwrap(); + + // Start dragging corner [32.0, 32.0] with Command held. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, command); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 60.0, pressure: 1.0 }, command); + + // While dragging, cursor anywhere stays CursorIcon::None (distort custom cursor). + assert_eq!(cursor(&app, &xf, [50.0, 60.0], command), Some(CursorIcon::None)); + assert_eq!(cursor(&app, &xf, [200.0, 200.0], command), Some(CursorIcon::None)); + + // Release drag + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 60.0 }, command); + + // Once released, dragging has ended: far outside returns the commit-on-click cursor, + // and hovering the corner without Command restores normal resize cursor. + assert_eq!(cursor(&app, &xf, [200.0, 200.0], command), Some(CursorIcon::Alias)); + assert_ne!(cursor(&app, &xf, [50.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::None)); +} + +fn cmd() -> egui::Modifiers { + egui::Modifiers { command: true, ..Default::default() } +} + +/// The indicator each handle shows in `mode` with `mods`: corner 0 and edge 0 (top) of a square. +fn indicators(mode: &str, mods: egui::Modifiers) -> (Option, Option) { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), mode, json!({})).unwrap(); + let t = app.ui.transform.clone().unwrap(); + (handle_indicator(&app, &t, Hit::Corner(0), mods), handle_indicator(&app, &t, Hit::Edge(0), mods)) +} + +#[test] +fn handle_pointers_follow_what_the_drag_does() { + use HandleIndicator::{Distort, Skew}; + let none = egui::Modifiers::NONE; + let persp = egui::Modifiers { command: true, alt: true, shift: true, ..Default::default() }; + assert_eq!(indicators("edit.freeTransform", none), (None, None), "plain drags scale"); + assert_eq!(indicators("edit.freeTransform", cmd()), (Some(Distort), Some(Skew))); + assert_eq!(indicators("edit.freeTransform", persp), (Some(Distort), Some(Skew))); + // Rotate mode turns the box from every handle, whatever the keys. + assert_eq!(indicators("edit.transform.rotate", cmd()), (None, None)); + // A Skew-mode corner slides along one edge, with or without Cmd; its edges skew. + assert_eq!(indicators("edit.transform.skew", cmd()), (None, Some(Skew))); + assert_eq!(indicators("edit.transform.skew", none), (None, Some(Skew))); + // Distort mode leaves the edges alone, Cmd or not. + assert_eq!(indicators("edit.transform.distort", none), (Some(Distort), None)); + assert_eq!(indicators("edit.transform.distort", cmd()), (Some(Distort), None)); + // Perspective mode: corners move in pairs; Cmd on an edge skews (`apply_drag`). + assert_eq!(indicators("edit.transform.perspective", none), (Some(Distort), None)); + assert_eq!(indicators("edit.transform.perspective", cmd()), (Some(Distort), Some(Skew))); + assert_eq!(indicators("edit.transform.scale", cmd()), (Some(Distort), Some(Skew))); +} + +#[test] +fn ctrl_in_rotate_mode_keeps_the_rotate_pointer() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.rotate", json!({})).unwrap(); + let xf = ViewXform::active(&app).unwrap(); + let corner = [32.0, 32.0]; + assert_eq!(cursor(&app, &xf, corner, cmd()), Some(CursorIcon::None)); + assert!(rotate_cursor_dir(&app, corner).is_some(), "a Rotate-mode corner drag rotates: the turn arrow stays"); + // An edge drag rotates too: Cmd draws no skew pointer there. + let edge = [96.0, 32.0]; + assert_eq!(cursor(&app, &xf, edge, cmd()), cursor(&app, &xf, edge, egui::Modifiers::NONE)); +} + +#[test] +fn rotate_mode_handle_drag_keeps_the_arrow_away_from_the_corners() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.rotate", json!({})).unwrap(); + let xf = ViewXform::active(&app).unwrap(); + let none = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, none); + // Far from every corner of the turned box, past the hover zone. + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 250.0, y: 96.0, pressure: 1.0 }, none); + let t = app.ui.transform.clone().unwrap(); + let tol = handle_tolerance(&app); + assert!(t.quad.iter().all(|q| (250.0 - q[0]).hypot(96.0 - q[1]) > tol * 4.0), "{:?}", t.quad); + assert!(rotate_cursor_dir(&app, [250.0, 96.0]).is_some(), "the corner drag rotates"); + assert_eq!(cursor(&app, &xf, [250.0, 96.0], none), Some(CursorIcon::None)); +} + +#[test] +fn scale_drag_past_a_corner_shows_no_rotate_arrow() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let none = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 160.0, y: 160.0, pressure: 1.0 }, none); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 150.0, pressure: 1.0 }, none); + let t = app.ui.transform.clone().unwrap(); + let tol = handle_tolerance(&app); + // Just outside another corner, where a hover would show the turn arrow. + let past = [t.quad[0][0] - tol * 1.5, t.quad[0][1] - tol * 1.5]; + assert_eq!(rotate_cursor_dir(&app, past), None, "the drag scales"); +} + +#[test] +fn applying_the_box_hides_no_pointer() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let xf = ViewXform::active(&app).unwrap(); + app.transform_preview.as_mut().unwrap().committing = Some(JobId(1)); + // The overlay draws no handles while the box is applied, so no drawn pointer either. + assert_eq!(cursor(&app, &xf, [32.0, 32.0], cmd()), Some(CursorIcon::ResizeNwSe)); + assert_eq!(cursor(&app, &xf, [96.0, 32.0], cmd()), Some(CursorIcon::ResizeVertical)); +} diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 2789a2b48f..d5a1bc6b77 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -44,9 +44,9 @@ use editing::{insert, insert_typed, smart_quotes}; #[cfg(test)] pub(crate) use fonts::{Axis, axis_value, slider_axes}; #[cfg(test)] -use fonts::{FONT_MENU_HEIGHT, font_labels_id, font_menu_rows, font_picker_in, style_names, wheel_family_index}; +use fonts::{FONT_MENU_HEIGHT, font_labels_id, font_menu_rows, font_picker_in, preview_text, style_names, wheel_family_index}; +pub(crate) use fonts::{FontLibrary, family_picker_in, fonts_ready, selected_style}; pub use fonts::{families, style_label, styles, sync_font_names, warm_fonts}; -pub(crate) use fonts::{family_picker_in, fonts_ready, selected_style}; pub(crate) use ime::{ImeState, controls_only, finish_reset_logic, finish_reset_pass, in_ui_pass, install_reset_hooks}; #[cfg(test)] use ime::{IncomingComposition, ResetPhase}; 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 cf0aeb4970..a6dd09e44a 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -127,6 +127,28 @@ mod panel_defaults { h } + /// Without a type target the preset chevrons set the next layer's defaults, with no + /// document edit. + #[test] + fn presets_without_a_type_layer_set_the_defaults() { + let app = new_app(); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = panels(app); + h.get_by_role_and_label(Role::ComboBox, "Font size presets").click(); + h.run(); + h.get_by_label("72 pt").scroll_to_me(); + h.run(); + h.get_by_label("72 pt").click(); + h.run(); + assert_eq!(h.state().ui.tool_options.type_size, 72.0); + h.get_by_role_and_label(Role::ComboBox, "Leading presets").click(); + h.run(); + h.get_by_label("Auto").click(); + h.run(); + assert_eq!(h.state().ui.tool_options.type_style_defaults.get("leading"), Some(&json!("auto"))); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "defaults are not a document edit"); + } + fn number(h: &mut Harness<'static, PhotocraftApp>, label: &str, value: &str) { h.get_by_role_and_label(Role::SpinButton, label).click(); h.run(); @@ -1952,6 +1974,44 @@ mod multi_layer_formatting { h.run(); } + fn preset(h: &mut Harness<'static, PhotocraftApp>, label: &str) { + // Presets near the end of the popup can be below its scroll viewport. + h.get_by_label(label).scroll_to_me(); + h.run(); + h.get_by_label(label).click(); + h.run(); + } + + /// Opens a preset chevron by its accessible name and picks `label`. + fn pick(h: &mut Harness<'static, PhotocraftApp>, menu: &str, label: &str) { + h.get_by_role_and_label(Role::ComboBox, menu).click(); + h.run(); + preset(h, label); + } + + /// The open preset popup's item labels, top to bottom, with "|" where a separator splits + /// them (a gap clearly larger than the row pitch). `any` is one item's label. + fn menu_items(h: &Harness<'static, PhotocraftApp>, any: &str) -> Vec { + use egui_kittest::kittest::NodeT; + let role = h.get_by_label(any).accesskit_node().role(); + let left = h.get_by_label(any).rect().left(); + let mut items: Vec<(f32, String)> = h + .query_all_by_role(role) + .filter(|n| (n.rect().left() - left).abs() < 1.0) + .filter_map(|n| Some((n.rect().top(), n.accesskit_node().label()?))) + .collect(); + items.sort_by(|a, b| a.0.total_cmp(&b.0)); + let pitch = items.windows(2).map(|w| w[1].0 - w[0].0).fold(f32::MAX, f32::min); + let mut out = Vec::new(); + for (i, (top, label)) in items.iter().enumerate() { + if i > 0 && top - items[i - 1].0 > pitch + 2.0 { + out.push("|".to_owned()); + } + out.push(label.clone()); + } + out + } + fn editing(app: &mut PhotocraftApp, id: LayerId) { app.ui.text_edit = Some(crate::state::TextEdit { layer: id.0, @@ -2023,6 +2083,97 @@ mod multi_layer_formatting { assert_eq!(text(h.state(), id).paragraph_runs()[0].style.direction, TextDirection::Rtl, "new type starts right to left"); } + /// The size, leading and tracking chevrons offer the reference application's lists: Leading + /// starts with Auto, Tracking splits tightening, 0 and loosening with separators. + #[test] + fn character_panel_preset_menus_list_the_reference_values() { + let (app, _) = fixture(); + let mut h = controls(app, true); + let sizes = [ + "6 pt", "8 pt", "9 pt", "10 pt", "11 pt", "12 pt", "14 pt", "16 pt", "18 pt", "24 pt", "30 pt", "36 pt", "48 pt", "60 pt", "72 pt", "150 pt", + "300 pt", + ]; + h.get_by_role_and_label(Role::ComboBox, "Font size presets").click(); + h.run(); + assert_eq!(menu_items(&h, "72 pt"), sizes); + h.key_press(egui::Key::Escape); + h.run(); + h.get_by_role_and_label(Role::ComboBox, "Leading presets").click(); + h.run(); + let leading: Vec<&str> = std::iter::once("Auto").chain(sizes).collect(); + assert_eq!(menu_items(&h, "72 pt"), leading); + h.key_press(egui::Key::Escape); + h.run(); + h.get_by_role_and_label(Role::ComboBox, "Tracking presets").click(); + h.run(); + let tracking = ["-100", "-75", "-50", "-25", "-10", "-5", "|", "0", "|", "5", "10", "25", "50", "75", "100", "200"]; + assert_eq!(menu_items(&h, "200"), tracking); + } + + #[test] + fn character_panel_preset_menus_edit_size_leading_and_tracking() { + let (app, ids) = fixture(); + let untouched = style(&app, ids[2], 0); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = controls(app, true); + + // The chevrons use the same setStyle path as the editable fields beside them. + pick(&mut h, "Font size presets", "72 pt"); + pick(&mut h, "Leading presets", "Auto"); + pick(&mut h, "Tracking presets", "-5"); + + for id in &ids[..2] { + let c = style(h.state(), *id, 0); + assert_eq!(c.size_pt, 72.0); + assert_eq!(c.leading_pt, None, "Auto restores font-relative line spacing"); + assert_eq!(c.tracking, -5.0); + } + assert_eq!(style(h.state(), ids[2], 0), untouched, "unselected type layers are unchanged"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 3, "one step per pick"); + + // The numeric spin boxes must remain usable beside their preset chevrons. + number(&mut h, "Font size", "40"); + assert_eq!(style(h.state(), ids[0], 0).size_pt, 40.0); + assert_eq!(style(h.state(), ids[1], 0).size_pt, 40.0); + } + + /// While typing, a preset changes only the selected characters, like a typed value. + #[test] + fn character_panel_presets_edit_only_the_selected_span() { + let (app, ids) = fixture(); + let mut h = controls(app, true); + let peer = text(h.state(), ids[1]).char_runs(); + editing(h.state_mut(), ids[0]); + h.run(); + pick(&mut h, "Font size presets", "150 pt"); + assert_eq!((size_at(h.state(), ids[0], 0), size_at(h.state(), ids[0], 1), size_at(h.state(), ids[0], 3)), (12.0, 150.0, 12.0)); + assert_eq!(text(h.state(), ids[1]).char_runs(), peer); + } + + /// Type units in millimetres: the lists show converted values with at most two decimals, + /// and a picked preset stores its exact point value (not 12.000001 from a unit round trip). + #[test] + fn character_panel_presets_in_millimetres_round_labels_and_store_exact_points() { + let mut app = new_app(); + app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "mm"})).unwrap(); + let id = LayerId(app.run("type.create", json!({"text": "AéBCD", "font": "Inter", "size": 30, "color": "#000000"})).unwrap()["layer"].as_u64().unwrap()); + selected(&mut app, &[id]); + let mut h = controls(app, true); + h.get_by_role_and_label(Role::ComboBox, "Font size presets").click(); + h.run(); + let items = menu_items(&h, "25.4 mm"); + assert_eq!(items.len(), 17, "{items:?}"); + for item in &items { + let n = item.strip_suffix(" mm").unwrap_or_else(|| panic!("{item}")); + assert!(n.split('.').nth(1).is_none_or(|d| d.len() <= 2 && !d.ends_with('0')), "{item}"); + } + assert_eq!(items[0], "2.12 mm", "6 pt"); + preset(&mut h, "4.23 mm"); + assert_eq!(style(h.state(), id, 0).size_pt, 12.0, "12 pt exactly"); + pick(&mut h, "Leading presets", "105.83 mm"); + assert_eq!(style(h.state(), id, 0).leading_pt, Some(300.0)); + } + #[test] fn options_font_family_preserves_peer_faces_and_batches_layer_flags() { let (app, ids) = fixture(); @@ -2094,6 +2245,29 @@ mod multi_layer_formatting { h.run_steps(2); } + /// A style picked under a family's ">" in the Character section's font menu, with type + /// 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 (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"); + assert_ne!(app.ui.tool_options.type_style, pick); + let mut h = controls(app, true); + h.get_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run(); + h.get_all_by_role(Role::TextInput).find(|n| n.is_focused()).expect("the search field has the focus").type_text("Inter"); + h.run(); + h.get_all_by_label("Show Styles").next().unwrap().click(); + h.run(); + h.get_by_label(&super::super::style_label(&pick)).click(); + h.run(); + assert_eq!(h.state().ui.tool_options.type_style, pick, "new type takes the picked style"); + for id in &ids[..2] { + assert_eq!(style(h.state(), *id, 0).font_style, pick, "the selected layers are set in it"); + } + } + #[test] fn hyphenate_is_not_shown_while_layout_does_not_hyphenate() { // #6710: layout never hyphenates; the control must stay hidden until it does. @@ -2163,6 +2337,11 @@ mod multi_layer_formatting { let c = style(h.state(), ids[0], 0); assert_eq!((c.size_pt, c.leading_pt, c.baseline_shift_pt), (30.0, Some(42.0), 5.0)); assert_eq!(text(h.state(), ids[0]).paragraph_runs()[0].style.start_indent_pt, 4.5); + + pick(&mut h, "Font size presets", "144 px"); + pick(&mut h, "Leading presets", "300 px"); + let c = style(h.state(), ids[0], 0); + assert_eq!((c.size_pt, c.leading_pt), (72.0, Some(150.0)), "presets preserve point values in pixel display units"); } /// #5717: a layer scaled so its shown size or leading is past a field's range (2400 pt, or diff --git a/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs index 0022057f86..7d24fbef42 100644 --- a/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs @@ -1,5 +1,7 @@ //! The Type tool's searchable font menu (#1369): it grows back after a search and focuses its search field. +use std::collections::HashMap; + use super::font_picker_in; use egui::accesskit::Role; use egui::{Key, Modifiers, Rect, vec2}; @@ -31,11 +33,15 @@ fn harness_with(preview: FontPreview) -> Harness<'static, State> { } fn harness_with_recents(preview: FontPreview, recents: Vec) -> Harness<'static, State> { + harness_sized(preview, recents, vec2(600.0, 900.0)) +} + +fn harness_sized(preview: FontPreview, recents: Vec, size: egui::Vec2) -> Harness<'static, State> { // Enough families that the unfiltered menu hits its maximum height and scrolls. let mut families: Vec = (0..60).map(|i| format!("Family {i:02}")).collect(); families.push("Zeta Sans".into()); let state = State { current: "Family 00".into(), families, button: egui::Id::NULL, popup: egui::Id::NULL, preview, recents }; - let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).with_max_steps(SETTLE_STEPS).build_ui_state( + let mut h = Harness::builder().with_size(size).with_max_steps(SETTLE_STEPS).build_ui_state( |ui, s: &mut State| { s.button = ui.make_persistent_id(egui::IdSalt::new("type-font")); s.popup = s.button.with("popup"); @@ -155,6 +161,33 @@ fn the_search_field_stays_put_while_the_list_scrolls() { assert!(popup.contains(after.center()), "the search field left the menu"); } +/// The wheel past the end of the list, or over the class list, leaves the preview, filters and +/// search field in place, also in a window too short for the menu's full height: the lists stay +/// within the room the menu leaves them, so the menu itself has nothing to scroll. +#[test] +fn the_wheel_past_the_end_of_the_list_leaves_the_header_in_place() { + // Over the font list, and over the class list beside it, which has no scroll area of its own. + for (size, over) in + [(vec2(600.0, 900.0), "Family 02"), (vec2(600.0, 900.0), "All Classes"), (vec2(600.0, 420.0), "Family 02"), (vec2(600.0, 420.0), "All Classes")] + { + let mut h = harness_sized(FontPreview::Medium, Vec::new(), size); + open(&mut h); + let search = h.get_by_role(Role::TextInput).rect(); + h.hover_at(h.get_by_label(over).rect().center()); + for _ in 0..40 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -10.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run(); + } + assert_eq!(search, h.get_by_role(Role::TextInput).rect(), "{size:?} over {over}: the search field moved under the wheel"); + } +} + /// #7792: the arrow keys scroll the list to the selected family without moving the search /// field: they scroll the list, not the whole menu. #[test] @@ -173,8 +206,9 @@ fn the_search_field_stays_put_while_the_arrows_scroll_the_list() { assert_eq!(search, h.get_by_role(Role::TextInput).rect(), "the search field scrolled away with the list"); } -/// A query matching no family shrinks the menu; clearing it grows the menu back to its full -/// height (egui#5225), and the search field stays where it was throughout. +/// A query matching no family shrinks the menu to its header and the class list beside the +/// list; clearing it grows the menu back to its full height (egui#5225), and the search field +/// stays where it was throughout. #[test] fn clearing_a_query_that_matches_nothing_grows_the_menu_back() { let mut h = harness(); @@ -185,7 +219,9 @@ fn clearing_a_query_that_matches_nothing_grows_the_menu_back() { h.run(); assert!(h.query_by_label("Family 00").is_none(), "the query matches no family"); let none = popup_rect(&h).expect("still open").height(); - assert!(none < full / 2.0, "no matches shrink the menu: {none} vs {full}"); + let classes = h.get_by_label("Decorative").rect(); + let menu = popup_rect(&h).expect("still open"); + assert!(none < full - 100.0 && menu.bottom() < classes.bottom() + 20.0, "no matches shrink the menu to the class list: {menu:?}, {classes:?}, full {full}"); assert_eq!(search, h.get_by_role(Role::TextInput).rect(), "the search field moved when the list emptied"); for _ in 0.."xxxx".len() { h.key_press(Key::Backspace); @@ -881,7 +917,7 @@ fn open_menu_shows_the_recent_group_when_the_marked_row_fits_below_it() { let row = h.query_all_by_label("Family 12").find(|n| n.accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)).expect("its marked row").rect(); assert!(popup.contains_rect(row) && row.top() >= search.bottom(), "recent #3 is in view: {row:?} in {popup:?}"); assert!( - popup.contains_rect(first) && (0.0..=12.0).contains(&(first.top() - search.bottom())), + popup.contains_rect(first) && (0.0..=16.0).contains(&(first.top() - search.bottom())), "the group's first row sits just below the search field: {first:?} under {search:?}" ); } @@ -1042,6 +1078,370 @@ fn wheel_family_index_clamps_to_the_ends() { assert_eq!(super::wheel_family_index(0, 0, -1.0), None); } +/// A picker over the test families with a recent/favourite library; the library is kept in the +/// state so a test can read the star that was clicked. +struct LibState { + current: String, + families: Vec, + library: super::FontLibrary, + popup: egui::Id, +} + +fn library_harness(recent: &[&str], favorites: &[&str]) -> Harness<'static, LibState> { + library_harness_with(recent, favorites, None, None) +} + +fn library_harness_with( + recent: &[&str], + favorites: &[&str], + traits: Option, + styles: Option>>, +) -> Harness<'static, LibState> { + let mut families: Vec = (0..20).map(|i| format!("Family {i:02}")).collect(); + families.push("Zeta Sans".into()); + let library = super::FontLibrary { + recent: recent.iter().map(|s| s.to_string()).collect(), + favorites: favorites.iter().map(|s| s.to_string()).collect(), + traits: traits.map(std::sync::Arc::new), + styles: styles.map(std::sync::Arc::new), + ..Default::default() + }; + let state = LibState { current: "Family 00".into(), families, library, popup: egui::Id::NULL }; + let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state( + |ui, s: &mut LibState| { + let fams = s.families.clone(); + s.popup = ui.make_persistent_id(egui::IdSalt::new("type-font")).with("popup"); + super::family_picker_in(ui, "type-font", &mut s.current, 170.0, &fams, FontPreview::Medium, &mut s.library); + }, + state, + ); + h.run(); + h.query_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run(); + h +} + +/// The tops of every row labelled `label`, top to bottom. +fn row_tops(h: &Harness<'static, LibState>, label: &str) -> Vec { + let mut tops: Vec = h.query_all_by_label(label).map(|n| n.rect().top()).collect(); + tops.sort_by(f32::total_cmp); + tops +} + +#[test] +fn recent_fonts_come_first_and_stay_in_the_alphabetical_list() { + let h = library_harness(&["Zeta Sans", "Family 05", "Not Installed"], &[]); + let zeta = row_tops(&h, "Zeta Sans"); + let five = row_tops(&h, "Family 05"); + let first = row_tops(&h, "Family 00"); + assert_eq!(zeta.len(), 2, "Zeta Sans is listed as recent and in its alphabetical place"); + assert_eq!(five.len(), 2); + assert!(zeta[0] < five[0] && five[0] < first[0], "recent first, most recent on top: {zeta:?} {five:?} {first:?}"); + assert!(h.query_by_label("Not Installed").is_none(), "a recent font that is no longer installed isn't listed"); +} + +#[test] +fn a_search_hides_the_recent_section() { + let mut h = library_harness(&["Zeta Sans"], &[]); + h.get_by_role(Role::TextInput).type_text("zeta"); + h.run(); + assert_eq!(row_tops(&h, "Zeta Sans").len(), 1); +} + +#[test] +fn clicking_a_star_marks_the_font_without_picking_it_or_closing_the_menu() { + let mut h = library_harness(&[], &[]); + let row = h.get_by_label("Family 03").rect(); + // The star sits left of the style expander's slot, which is left of the row's button. + let star = egui::pos2(row.left() - 2.0 - 16.0 - 2.0 - 11.0, row.center().y); + h.hover_at(star); + h.run(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: star, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run(); + } + assert_eq!(h.state().library.toggled.as_deref(), Some("Family 03")); + assert_eq!(h.state().current, "Family 00", "the star doesn't pick the font"); + assert!(h.query_by_label("Family 10").is_some(), "the menu stays open"); +} + +#[test] +fn the_favorites_filter_lists_only_starred_fonts() { + let mut h = library_harness(&["Family 01"], &["Zeta Sans", "Family 07"]); + assert_eq!(h.query_all_by_label("Remove from Favorites").count(), 2, "starred rows show a filled star"); + h.get_by_label("Show Favorite Fonts").click(); + h.run(); + assert!(h.query_by_label("Zeta Sans").is_some() && h.query_by_label("Family 07").is_some()); + assert!(h.query_by_label("Family 01").is_none(), "neither other fonts nor the recent section show"); + assert!(h.query_by_label("Family 02").is_none()); +} + +#[test] +fn the_favorites_filter_explains_an_empty_library() { + let mut h = library_harness(&[], &[]); + h.get_by_label("Show Favorite Fonts").click(); + h.run(); + assert!(h.query_by_label_contains("No favorite fonts yet").is_some()); +} + +#[test] +fn a_clicked_star_is_saved_to_the_preferences_library() { + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let mut library = super::FontLibrary::of(&app); + library.toggled = Some("Bebas Neue".into()); + library.finish(&mut app); + assert_eq!(app.session.prefs().type_.favorite_fonts, ["Bebas Neue"]); + assert_eq!(super::FontLibrary::of(&app).favorites, ["Bebas Neue"]); + app.note_recent_font("Arial"); + assert_eq!(super::FontLibrary::of(&app).recent, ["Arial"]); +} + +fn traits(class: photocraft_text::FontClass, format: photocraft_text::FontFormat, panose: [u8; 10]) -> Option { + Some(photocraft_text::FamilyTraits { class: Some(class), format, panose, weight: 400 }) +} + +/// Family 00-02 serif, 03 a variable sans, 04 monospace, Zeta Sans a sans like 03; the rest +/// unknown. Family 01 has three styles. +fn filter_harness() -> Harness<'static, LibState> { + use photocraft_text::{FontClass, FontFormat}; + let serif = [2, 2, 6, 3, 5, 4, 5, 2, 3, 4]; + let sans = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4]; + let map: crate::font_filters::TraitsMap = [ + ("Family 00", traits(FontClass::Serif, FontFormat::TrueType, serif)), + ("Family 01", traits(FontClass::Serif, FontFormat::OpenType, serif)), + ("Family 02", traits(FontClass::Serif, FontFormat::TrueType, serif)), + ("Family 03", traits(FontClass::SansSerif, FontFormat::Variable, sans)), + ("Family 04", traits(FontClass::Monospace, FontFormat::TrueType, [2, 11, 6, 9, 2, 2, 2, 2, 2, 4])), + ("Zeta Sans", traits(FontClass::SansSerif, FontFormat::TrueType, sans)), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let styles: HashMap> = + [("Family 01".to_string(), vec!["Regular".to_string(), "Bold".to_string(), "Italic".to_string()])].into_iter().collect(); + library_harness_with(&[], &[], Some(map), Some(styles)) +} + +#[test] +fn the_class_list_narrows_the_fonts_and_all_classes_brings_them_back() { + let mut h = filter_harness(); + h.get_by_label("Serif").click(); + h.run(); + for f in ["Family 00", "Family 01", "Family 02"] { + assert!(h.query_by_label(f).is_some(), "{f} is a serif"); + } + assert!(h.query_by_label("Family 03").is_none() && h.query_by_label("Zeta Sans").is_none()); + h.get_by_label("Monospace").click(); + h.run(); + assert!(h.query_by_label("Family 04").is_some() && h.query_by_label("Family 00").is_none()); + h.get_by_label("All Classes").click(); + h.run(); + assert!(h.query_by_label("Family 10").is_some(), "unclassified fonts are back"); +} + +#[test] +fn variable_and_similar_filters_and_clear_all() { + let mut h = filter_harness(); + h.get_by_label("Show Variable Fonts").click(); + h.run(); + assert!(h.query_by_label("Family 03").is_some()); + assert!(h.query_by_label("Family 00").is_none() && h.query_by_label("Zeta Sans").is_none()); + h.get_by_label("Clear All").click(); + h.run(); + assert!(h.query_by_label("Family 10").is_some(), "Clear All turns every filter off"); + // Similar to the current Family 00 (a serif): the serifs first, sans after, unknown never. + h.get_by_label("Show Similar Fonts").click(); + h.run(); + let top = |label: &str| h.query_by_label(label).map(|n| n.rect().top()); + let (current, serif, sans) = (top("Family 00").unwrap(), top("Family 02").unwrap(), top("Zeta Sans").unwrap()); + assert!(current < serif && serif < sans, "{current} {serif} {sans}"); + assert!(h.query_by_label("Family 10").is_none(), "fonts that can't be compared aren't listed"); +} + +/// With Show Similar Fonts on, the arrows step down the list made for the font current when it +/// was turned on: re-sorting around each font stepped to sent the next step back. +#[test] +fn the_arrows_walk_down_the_similar_fonts_list() { + let mut h = filter_harness(); + h.get_by_label("Show Similar Fonts").click(); + h.run(); + let order: Vec = { + let mut rows: Vec<(f32, String)> = ["Family 00", "Family 01", "Family 02", "Family 03", "Family 04", "Zeta Sans"] + .iter() + .filter_map(|f| h.query_by_label(f).map(|n| (n.rect().top(), f.to_string()))) + .collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + rows.into_iter().map(|(_, f)| f).collect() + }; + assert_eq!(order[0], "Family 00", "the current font first"); + for step in 1..4 { + h.key_press(egui::Key::ArrowDown); + h.run(); + assert_eq!(h.state().current, order[step], "step {step} through {order:?}"); + } +} + +#[test] +fn a_style_picked_under_the_expander_picks_the_family_in_that_style() { + let mut h = filter_harness(); + assert_eq!(h.query_all_by_label("Show Styles").count(), 1, "only a family with several styles expands"); + h.get_by_label("Show Styles").click(); + h.run(); + h.get_by_label("Bold").click(); + h.run(); + assert_eq!(h.state().current, "Family 01"); + assert_eq!(h.state().library.picked_style.as_deref(), Some("Bold")); + assert!(h.query_by_label("Family 10").is_none(), "picking a style closes the menu"); +} + +/// An expanded family's style rows stay listed while the list scrolls its own row out of view: +/// they used to vanish then, so the rows below jumped up. +#[test] +fn an_expanded_familys_styles_stay_listed_when_its_row_scrolls_away() { + let mut h = filter_harness(); + let top = h.get_by_label("Family 00").rect().top(); + h.get_by_label("Show Styles").click(); + h.run(); + assert!(h.query_by_label("Italic").is_some(), "Family 01 lists its styles"); + let over = h.get_by_label("Family 05").rect().center(); + h.hover_at(over); + h.run(); + let mut styles_without_family_row = false; + for _ in 0..40 { + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -6.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }); + h.run_steps(3); + let family_gone = h.query_by_label("Family 01").is_none_or(|n| n.rect().bottom() <= top); + let italic = h.query_by_label("Italic").map(|n| n.rect()); + styles_without_family_row |= family_gone && italic.is_some_and(|r| r.bottom() > top); + } + assert!(styles_without_family_row, "the style rows show below the family row scrolled out of view"); +} + +#[test] +fn the_search_field_stays_in_place_while_the_list_scrolls() { + let mut h = library_harness(&[], &[]); + let search = h.get_by_role(Role::TextInput).rect(); + let row = h.get_by_label("Family 01").rect(); + h.hover_at(row.center()); + h.run(); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -300.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }); + h.run_steps(4); + assert_eq!(h.get_by_role(Role::TextInput).rect(), search, "the field doesn't scroll away"); + assert!(h.query_by_label("Family 01").is_none_or(|n| n.rect().top() < row.top()), "the list scrolled"); +} + +#[test] +fn the_preview_follows_the_font_under_the_pointer_and_the_menu_keeps_its_width() { + let mut h = library_harness(&[], &[]); + assert!(h.query_by_label("Font preview: Family 00").is_some(), "the current font first"); + let width = popup_width(&h); + h.hover_at(h.get_by_label("Family 03").rect().center()); + h.run_steps(3); + assert!(h.query_by_label("Font preview: Family 03").is_some()); + // Filtering never widens the menu past its list (no empty strip). + h.get_by_label("Show Favorite Fonts").click(); + h.run_steps(3); + assert!((popup_width(&h) - width).abs() < 1.0, "{} vs {width}", popup_width(&h)); +} + +fn popup_width(h: &Harness<'static, LibState>) -> f32 { + let preview = h.query_all_by_label_contains("Font preview:").next().unwrap().rect(); + preview.width() +} + +#[test] +fn the_preview_sets_the_type_layers_text_or_the_selection_being_typed() { + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert_eq!(super::preview_text(&app), None, "no document"); + app.run("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + let id = app.run("type.create", serde_json::json!({"text": "Hello\rworld ", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", serde_json::json!({"id": id})).ok(); + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id, + document: None, + caret: 0, + anchor: 0, + session: "s".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + assert_eq!(super::preview_text(&app).as_deref(), Some("Hello world"), "the whole text, on one line"); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 6; + ed.caret = 11; + } + assert_eq!(super::preview_text(&app).as_deref(), Some("world"), "only the selection while typing"); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 50; + ed.caret = 400; + } + assert_eq!(super::preview_text(&app), None, "an out-of-range selection is blank, not a panic"); +} + +/// Minimizing the window (a zero-size screen for a few frames) and restoring it must not leave +/// the menu wider than its lists: an empty strip appeared beside the list after a minimize. +#[test] +fn minimizing_and_restoring_the_window_keeps_the_menu_as_wide_as_its_lists() { + let mut h = library_harness(&[], &[]); + h.set_size(vec2(1286.0, 900.0)); + h.run_steps(3); + let width = |h: &Harness<'static, LibState>| h.ctx.memory(|m| m.area_rect(h.state().popup)).map(|r| r.width()); + let before = width(&h).expect("menu open"); + for size in [vec2(1.0, 1.0), vec2(0.0, 0.0), vec2(1286.0, 900.0)] { + h.set_size(size); + h.run_steps(3); + } + let after = width(&h).expect("menu still open"); + assert!((after - before).abs() < 1.0, "menu width {after} after a minimize, {before} before"); +} + +/// The same with the font button near the right edge, as in the Character panel, where the +/// popup is pushed left against the window's edge. +#[test] +fn a_menu_opened_from_the_right_edge_stays_narrow_after_a_minimize() { + let mut families: Vec = (0..20).map(|i| format!("Family {i:02}")).collect(); + families.push("Zeta Sans".into()); + let state = LibState { current: "Family 00".into(), families, library: Default::default(), popup: egui::Id::NULL }; + let mut h = Harness::builder().with_size(vec2(1286.0, 900.0)).build_ui_state( + |ui, s: &mut LibState| { + ui.horizontal(|ui| { + ui.add_space(940.0); + s.popup = ui.make_persistent_id(egui::IdSalt::new("type-font")).with("popup"); + let fams = s.families.clone(); + super::family_picker_in(ui, "type-font", &mut s.current, 300.0, &fams, FontPreview::Medium, &mut s.library); + }); + }, + state, + ); + h.run(); + h.query_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run_steps(4); + let width = |h: &Harness<'static, LibState>| h.ctx.memory(|m| m.area_rect(h.state().popup)).map(|r| r.width()); + let before = width(&h).expect("menu open"); + for size in [vec2(0.0, 0.0), vec2(300.0, 200.0), vec2(1286.0, 900.0)] { + h.set_size(size); + h.run_steps(4); + } + h.run_steps(4); + let after = width(&h).expect("menu open again"); + assert!(after <= before + 1.0, "menu width {after} after a minimize, {before} before"); +} + /// #5152: in the full app the Properties panel's Character section draws a second font picker /// after the options bar; hovering a font in the options bar still previews it on the canvas. #[test] diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index d81530063c..9035387c1e 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -260,13 +260,96 @@ pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool { false } -/// Searchable font-family combo box. -pub(super) fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32, preview: photocraft_engine::prefs::FontPreview, recents: &[String]) -> bool { - family_picker_in(ui, "type-font", current, width, &families(), preview, recents) +/// 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 +/// picked from a family's expanded styles. +#[derive(Clone, Debug, Default)] +pub(crate) struct FontLibrary { + pub recent: Vec, + pub favorites: Vec, + pub toggled: Option, + /// The style picked under a family's ">" (with the family), for the caller to apply. + pub picked_style: Option, + /// Family traits to filter by instead of the installed fonts' (tests). + pub traits: Option>, + /// Each family's style names instead of the installed fonts' (tests). + pub styles: Option>>>, + /// The user's own text for the preview at the top of the menu (else it shows a sample). + pub preview_text: Option, } -/// Maximum height of the font menu. -pub(super) const FONT_MENU_HEIGHT: f32 = 460.0; +/// The text the font menu's preview sets: the selected characters while typing, else the type +/// target's whole text, on one line and at most 60 characters. `None` without a type target or +/// with blank text (the preview then shows its sample). +pub(super) fn preview_text(app: &PhotocraftApp) -> Option { + let (layer, range) = target(app)?; + let text = &text_layer(&app.session.active()?.doc, LayerId(layer))?.text; + let chosen: String = match range { + Some([a, b]) => text.chars().skip(a).take(b.saturating_sub(a)).collect(), + None => text.clone(), + }; + let line = chosen.split(['\n', '\r', '\u{2028}', '\u{2029}']).map(str::trim).filter(|s| !s.is_empty()).collect::>().join(" "); + let line: String = line.chars().take(60).collect(); + (!line.is_empty()).then_some(line) +} + +impl FontLibrary { + pub(crate) fn of(app: &PhotocraftApp) -> Self { + use photocraft_engine::font_library_cmds as lib; + // The recent fonts are the shell's (`PhotocraftApp::note_recent_font`), the favourites the engine's. + Self { recent: app.ui.recent_fonts.clone(), favorites: lib::favorite_fonts(&app.session), ..Default::default() } + } + + /// The style names a family's ">" expands to. + fn styles_of(&self, family: &str) -> Vec { + match &self.styles { + Some(map) => map.get(family).cloned().unwrap_or_else(|| vec!["Regular".into()]), + None => styles(family), + } + } + + /// Star or un-star the clicked font, through the engine command. + pub(crate) fn finish(self, app: &mut PhotocraftApp) { + if let Some(family) = self.toggled + && let Err(e) = app.run("type.font.favorite", json!({"family": family})) + { + app.ui.status = e; + app.ui.status_error = true; + } + } +} + +/// Searchable font-family combo box, with the recent and favourite fonts of `app`. `Some` when a +/// family was picked, holding the style when it was picked from the family's expanded styles. +pub(super) fn font_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, current: &mut String, width: f32) -> Option> { + let preview = app.session.prefs().type_.font_preview; + let mut library = FontLibrary { preview_text: preview_text(app), ..FontLibrary::of(app) }; + let changed = family_picker_in(ui, "type-font", current, width, &families(), preview, &mut library); + let style = library.picked_style.take(); + library.finish(app); + if !changed { + return None; + } + // Each family applied is recorded, an arrow step too, as `PhotocraftApp::note_recent_font` says. + app.note_recent_font(current); + Some(style) +} + +/// Maximum height of the font menu: room for the search/filter bar over the font list, so only +/// the list scrolls. +pub(super) const FONT_MENU_HEIGHT: f32 = 520.0; +/// The font list's height (it scrolls inside the menu, under the fixed search field). +const FONT_LIST_HEIGHT: f32 = 440.0; +/// The font list's width: star, style expander, name, format badge and sample. +const FONT_LIST_WIDTH: f32 = 420.0; +/// Room the search row keeps for Clear All, and for the filter buttons when they follow the field. +const FONT_CLEAR_WIDTH: f32 = 84.0; +const FONT_BUTTONS_WIDTH: f32 = 112.0; +/// Room right of the font list's viewport for its scroll bar. +const FONT_SCROLL_BAR_WIDTH: f32 = 14.0; +/// Room for the format badge (O, TT, VAR) left of the sample. +const FONT_BADGE_WIDTH: f32 = 28.0; /// [`font_picker`] over a given family list (tests pass their own). #[cfg(test)] @@ -278,7 +361,7 @@ pub(super) fn font_picker_in( preview: photocraft_engine::prefs::FontPreview, recents: &[String], ) -> bool { - family_picker_in(ui, "type-font", current, width, families, preview, recents) + family_picker_in(ui, "type-font", current, width, families, preview, &mut FontLibrary { recent: recents.to_vec(), ..FontLibrary::default() }) } /// Shared by the Type options, Character, style and Glyphs panels. Selection changes still @@ -290,7 +373,7 @@ pub(crate) fn family_picker_in( width: f32, families: &[String], preview: photocraft_engine::prefs::FontPreview, - recents: &[String], + library: &mut FontLibrary, ) -> bool { let mut changed = false; // A font picked from the open menu (click or Enter): the field keeps the focus afterwards. @@ -313,8 +396,16 @@ pub(crate) fn family_picker_in( // picking a font closes it explicitly below. .close_behavior(if matches!(close, egui::PopupCloseBehavior::IgnoreClicks) { close } else { egui::PopupCloseBehavior::CloseOnClickOutside }); - // The search field is the menu's header: only the list scrolls under it. - let header = |ui: &mut egui::Ui| { + let mut response = combo.show_ui(ui, |ui| { + // Positions kept between frames are relative to the menu's left edge: the menu moves + // (the window's edge pushes it after a resize), and screen positions from an earlier + // frame would pad the search row out and widen the menu, an empty strip beside the list. + let origin = ui.cursor().min.x; + // Freshly opened (not drawn last pass): the preview starts on the current font. + let pass_id = search_id.with("pass"); + let pass = ui.ctx().cumulative_pass_nr(); + let opened = ui.data(|d| d.get_temp::(pass_id)).is_none_or(|p| p.saturating_add(1) < pass); + ui.data_mut(|d| d.insert_temp(pass_id, pass)); // Each opening focuses the search, including a reopen on the very next pass. Keep // asking through the invisible sizing pass, until the field receives focus. let mut focus = ui.data(|d| d.get_temp(focus_id)).unwrap_or(true); @@ -323,10 +414,61 @@ pub(crate) fn family_picker_in( let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); let enter = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); - if focus { - ui.memory_mut(|m| m.request_focus(search_id.with("input"))); + // The filter bar beside the search field, as in Photoshop: the class list toggle, Show + // Variable / Favorite / Similar Fonts and Clear All (`font_filters`). + let filters_id = search_id.with("filters"); + let mut filters: crate::font_filters::FontFilters = ui.data(|d| d.get_temp(filters_id)).unwrap_or_default(); + // The preview on top: the font last under the pointer, else the current one. + let preview_id = search_id.with("preview-font"); + if opened { + ui.data_mut(|d| d.remove::(preview_id)); } - let r = ui.add(egui::TextEdit::singleline(&mut q).id(search_id.with("input")).hint_text(tl!("Search fonts")).desired_width(200.0)); + let previewed: String = ui.data(|d| d.get_temp(preview_id)).unwrap_or_else(|| current.clone()); + let previewed_label = labels.and_then(|l| l.get(previewed.as_str())).map_or(previewed.as_str(), String::as_str).to_string(); + // Everything above the list is as wide as the class and font lists below, measured last + // frame: never wider, so the menu has no empty strip beside the list. + let (list_left_id, body_id) = (search_id.with("list-left"), search_id.with("body")); + let class_w = crate::font_filters::CLASS_COLUMN_WIDTH; + let estimate = FONT_LIST_WIDTH + 16.0 + if filters.hide_classes { 0.0 } else { class_w + 14.0 }; + let body: Option = ui.data(|d| d.get_temp(body_id)); + let menu_width = body.map_or(estimate, |b| b.width()); + // Divider lines span the space they are given: cap it, or they stretch the menu. + if body.is_some() { + ui.set_max_width(menu_width); + } + crate::font_filters::preview_banner(ui, &previewed, &previewed_label, library.preview_text.as_deref(), menu_width); + // The filter buttons over the class list, and the search field over the fonts, starting + // where the list does. + let list_left: Option = ui.data(|d| d.get_temp::(list_left_id)).map(|x| origin + x); + let menu_right = body.map(|b| origin + b.right()); + let r = ui + .horizontal(|ui| { + if !filters.hide_classes { + ui.allocate_ui_with_layout(egui::vec2(class_w, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + crate::font_filters::filter_buttons(ui, &mut filters); + }); + } + if let Some(x) = list_left.filter(|_| !filters.hide_classes) { + let pad = x - ui.cursor().min.x; + if pad > 0.0 { + ui.add_space(pad); + } + } + // The field fills the row up to Clear All (and the buttons, which follow it when + // the class list is hidden). + let trailing = FONT_CLEAR_WIDTH + if filters.hide_classes { FONT_BUTTONS_WIDTH } else { 0.0 }; + let search_w = menu_right.map_or(FONT_LIST_WIDTH - trailing, |right| right - ui.cursor().min.x - trailing).clamp(120.0, FONT_LIST_WIDTH); + if focus { + ui.memory_mut(|m| m.request_focus(search_id.with("input"))); + } + let r = ui.add(egui::TextEdit::singleline(&mut q).id(search_id.with("input")).hint_text(tl!("Search fonts")).desired_width(search_w)); + if filters.hide_classes { + crate::font_filters::filter_buttons(ui, &mut filters); + } + crate::font_filters::clear_all(ui, &mut filters); + r + }) + .inner; if focus { // The opening click can release after several focused frames. Keep the request // pending through that release, which can hand focus back to the combo button. @@ -336,15 +478,25 @@ pub(crate) fn family_picker_in( d.insert_temp(focus_id, focus); d.insert_temp(search_id, q.clone()); }); - (q, down, up, enter) - }; - let mut response = combo.show_ui_with_header(ui, header, |ui, (q, down, up, enter)| { let ql = q.to_lowercase(); + let lookup = crate::font_filters::lookup_in(library.traits.clone()); // The recent group stays as it was when the menu opened: each arrow step applies (and so // records) a family, and moving it to the top would send the next step back up. let opening = ui.data(|d| d.get_temp::>(recents_id).is_none()); - let open_recents: Vec = ui.data_mut(|d| d.get_temp_mut_or_insert_with(recents_id, || recents.to_vec()).clone()); - let (rows, n_recent) = font_menu_rows(families, labels, &ql, &open_recents); + let open_recents: Vec = ui.data_mut(|d| d.get_temp_mut_or_insert_with(recents_id, || library.recent.clone()).clone()); + // No recent group while a filter is on: the filters narrow the alphabetical list alone. + let (mut rows, n_recent) = font_menu_rows(families, labels, &ql, if filters.any() { &[] } else { &open_recents }); + // Show Similar Fonts compares with the font current when it was turned on (or the menu + // opened), as the recent group stays put: each arrow step applies a font, and sorting + // around that one sent the next step back to the font before. + let similar_id = search_id.with("similar-to"); + let reference: String = if filters.similar { + ui.data_mut(|d| d.get_temp_mut_or_insert_with(similar_id, || current.clone()).clone()) + } else { + ui.data_mut(|d| d.remove::(similar_id)); + current.clone() + }; + let comparable = crate::font_filters::apply(&mut rows, &filters, &library.favorites, &reference, &lookup); // A recent family is listed twice. The current family's row is the one the last arrow // selected while it still shows that family, else its first copy: as in Photoshop, the // one in the recent group when it has one (#9160), and the arrows walk on from there. @@ -393,60 +545,182 @@ pub(crate) fn family_picker_in( } let preview = crate::font_preview::sample(preview); let row_h = preview.map_or(28.0, |(_, [_, h])| (h + 4.0).max(28.0)); - + let expanded_id = search_id.with("expanded"); + let mut expanded: Vec = ui.data(|d| d.get_temp(expanded_id)).unwrap_or_default(); let mut hovered: Option = None; let reveal = if stepped.is_some() { None } else { reveal }; let mut reveal_top: Option = None; - for (i, (f, label)) in rows.into_iter().enumerate() { - if i == n_recent && n_recent > 0 { - ui.separator(); - } - // Highlighted by its fill alone, as Photoshop's font menu is. A selectable button lays - // out its frame's stroke only once hovered or selected, so with the theme's stroke the - // row under the pointer (and the selected one) grew and pushed the rows below down: - // the list jumped as the pointer moved (#7406). One row only, though a recent - // family is listed twice. - let mut button = egui::Button::selectable(selected == Some(i), label).truncate().stroke(egui::Stroke::NONE); - if let Some((size, [_, h])) = preview { - button = button - .right_text(egui::Atom::custom(egui::IdSalt::new(("font-sample", f)), egui::vec2(crate::font_preview::slot_width(ui.ctx(), f, size), h))); - } - let response = ui.add_sized([330.0, row_h], button); - if stepped == Some(i) { - response.scroll_to_me(Some(egui::Align::Center)); - } else if reveal.is_some() { - if reveal_from == Some(i) { - reveal_top = Some(response.rect); - } - if reveal == Some(i) { - // Jump, not glide: the menu opens with its current family in view. Arrow - // steps above keep the animation. A recent row too far below the top of - // the group (large previews, many recents) is brought up to the bottom. - let top = reveal_top.unwrap_or(response.rect); - let (rect, align) = - if response.rect.bottom() - top.top() <= ui.clip_rect().height() { (top, egui::Align::Min) } else { (response.rect, egui::Align::Max) }; - ui.scroll_to_rect_animation(rect, Some(align), egui::style::ScrollAnimation::none()); - } - } - if let Some((size, _)) = preview - && ui.is_rect_visible(response.rect) - { - crate::font_preview::paint(ui, f, response.rect, size); - } - if response.hovered() { - hovered = Some(f.clone()); - } - if press.chosen(ui, &response) { - *current = f.clone(); - // A served family not fetched yet: start now, before any text needs it. - photocraft_text::served::request(f); - changed = true; - picked = true; - ui.data_mut(|d| d.remove::(search_id)); - hovered = None; - ui.close(); + ui.separator(); + // The line between the class list and the font list. A separator in the row would take + // the row's whole available height and hold the menu at its full height under a short + // search result, so the row keeps its room and the line is drawn once the row is laid out. + let mut divider: Option = None; + let body = ui.horizontal_top(|ui| { + if !filters.hide_classes { + crate::font_filters::class_list(ui, &mut filters); + divider = Some(ui.cursor().min.x + 3.0); + ui.add_space(6.0 + ui.spacing().item_spacing.x); } + // The list scrolls under the fixed search field and filters, and shrinks to a short + // search result: the menu grows back with it (craft_ui::ComboBox, #9849). + let list = egui::ScrollArea::vertical().id_salt(search_id.with("list")).max_height(FONT_LIST_HEIGHT).auto_shrink([true, true]); + // Top to bottom, though the list sits beside the class list. + let shown = list.show(ui, |ui| { + ui.vertical(|ui| { + ui.set_width(FONT_LIST_WIDTH); + let weak = |ui: &mut egui::Ui, text: &str| { + ui.label(egui::RichText::new(text).weak()); + }; + if filters.similar && !comparable { + weak(ui, tl!("No similar fonts: the current font doesn't say what it looks like.")); + } + if rows.is_empty() { + weak( + ui, + if filters.favorites && library.favorites.is_empty() { + tl!("No favorite fonts yet: click the star beside a font to add it.") + } else { + tl!("No fonts match these filters.") + }, + ); + } + // The first `n_recent` rows are the recent group, above a line (`font_menu_rows`). + for (i, &(f, label)) in rows.iter().enumerate() { + let recent_row = i < n_recent; + if i == n_recent && n_recent > 0 { + ui.separator(); + } + // Only rows on screen read their font's format and styles, and an expanded + // family: its style rows stay listed when its own row scrolls out of view. + let visible = ui.is_rect_visible(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(FONT_LIST_WIDTH, row_h))); + let format = if visible { lookup(f).map(|t| t.format) } else { None }; + let open = !recent_row && expanded.contains(f); + let styles = if visible || open { library.styles_of(f) } else { Vec::new() }; + let favorite = library.favorites.contains(f); + // Highlighted by its fill alone, as Photoshop's font menu is: a hovered or selected + // row's stroke grew it and pushed the rows below down (#7406). + let slot = preview.map_or(0.0, |(size, _)| crate::font_preview::slot_width(ui.ctx(), f, size)); + // One row lit, though a recent family is listed twice. + let mut button = egui::Button::selectable(selected == Some(i), label).truncate().stroke(egui::Stroke::NONE); + let [_, h] = preview.map_or([0.0, 16.0], |(_, b)| b); + button = + button.right_text(egui::Atom::custom(egui::IdSalt::new(("font-sample", f, recent_row)), egui::vec2(slot + FONT_BADGE_WIDTH, h))); + let response = ui + .allocate_ui_with_layout(egui::vec2(FONT_LIST_WIDTH, row_h), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 2.0; + // The star adds the font to (or removes it from) the favourites; it never picks it. + let tip = if favorite { tl!("Remove from Favorites") } else { tl!("Add to Favorites") }; + if crate::icons::button(ui, if favorite { "star-filled" } else { "star" }, 22.0, false, tip).clicked() { + library.toggled = Some(f.clone()); + } + // A family with several styles expands to list them (">"). + if styles.len() > 1 && !recent_row { + let (icon, tip) = if open { ("chevron-down", tl!("Hide Styles")) } else { ("chevron-right", tl!("Show Styles")) }; + if crate::icons::button(ui, icon, 16.0, false, tip).clicked() { + if open { + expanded.retain(|e| e != f); + } else { + expanded.push(f.clone()); + } + } + } else { + ui.add_space(16.0); + } + ui.add_sized([ui.available_width(), row_h], button) + }) + .inner; + if stepped == Some(i) { + response.scroll_to_me(Some(egui::Align::Center)); + } else if reveal.is_some() { + if reveal_from == Some(i) { + reveal_top = Some(response.rect); + } + if reveal == Some(i) { + // Jump, not glide: the menu opens with its current family in view. Arrow + // steps above keep the animation. A recent row too far below the top of + // the group (large previews, many recents) is brought up to the bottom. + let top = reveal_top.unwrap_or(response.rect); + let (rect, align) = if response.rect.bottom() - top.top() <= ui.clip_rect().height() { + (top, egui::Align::Min) + } else { + (response.rect, egui::Align::Max) + }; + ui.scroll_to_rect_animation(rect, Some(align), egui::style::ScrollAnimation::none()); + } + } + if let Some((size, _)) = preview + && ui.is_rect_visible(response.rect) + { + crate::font_preview::paint(ui, f, response.rect, size); + } + // The format badge (O, TT, VAR) just left of the sample. + if let Some(format) = format { + let center = egui::pos2(response.rect.right() - 8.0 - slot - FONT_BADGE_WIDTH / 2.0, response.rect.center().y); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().text(center, egui::Align2::CENTER_CENTER, format.badge(), egui::FontId::proportional(10.0), t.text_dim); + let tip = egui::Rect::from_center_size(center, egui::vec2(FONT_BADGE_WIDTH, 14.0)); + ui.interact(tip, ui.scope_id().with(("font-format", f, recent_row)), egui::Sense::hover()) + .on_hover_text(crate::font_filters::format_tip(format)); + } + if response.hovered() { + hovered = Some(f.clone()); + } + if press.chosen(ui, &response) { + *current = f.clone(); + // A served family not fetched yet: start now, before any text needs it. + photocraft_text::served::request(f); + changed = true; + picked = true; + ui.data_mut(|d| d.remove::(search_id)); + hovered = None; + ui.close(); + } + if !open { + continue; + } + // The family's styles, each picking the family in that style. + for style in &styles { + let style_row = ui + .horizontal(|ui| { + ui.add_space(46.0); + ui.add_sized( + [ui.available_width(), 22.0], + egui::Button::selectable(false, style_label(style)).truncate().stroke(egui::Stroke::NONE), + ) + }) + .inner; + if style_row.clicked() { + *current = f.clone(); + photocraft_text::served::request(f); + library.picked_style = Some(style.clone()); + changed = true; + picked = true; + ui.data_mut(|d| d.remove::(search_id)); + hovered = None; + ui.close(); + } + } + } + }) + }); + ui.data_mut(|d| d.insert_temp(list_left_id, shown.inner_rect.left() - origin)); + shown.inner_rect.right() + }); + if let Some(x) = divider { + ui.painter().vline(x, body.response.rect.y_range(), ui.visuals().widgets.noninteractive.bg_stroke); } + // The lists' own extent, from the class list to the font list's scroll bar: the row + // itself stretches with the popup, so it can't tell when the popup is too wide. + let list_right = body.inner + FONT_SCROLL_BAR_WIDTH; + let body = egui::Rect::from_min_max(body.response.rect.min, egui::pos2(list_right.min(body.response.rect.right()), body.response.rect.bottom())); + ui.data_mut(|d| { + d.insert_temp(filters_id, filters); + d.insert_temp(expanded_id, expanded); + d.insert_temp(body_id, body.translate(egui::vec2(-origin, 0.0))); + if let Some(f) = &hovered { + d.insert_temp(preview_id, f.clone()); + } + }); if accept { None } else { hovered } }); response.response = response.response.accessible_name(tl!("Font")); @@ -457,6 +731,7 @@ pub(crate) fn family_picker_in( d.remove::>(recents_id); d.remove::(row_id); d.remove::(search_id.with("reveal")); + d.remove::(search_id.with("similar-to")); }); } let hovered_font = response.inner.unwrap_or_default(); diff --git a/crates/ui-egui/src/tools/type_tool/ime_tests.rs b/crates/ui-egui/src/tools/type_tool/ime_tests.rs index 02913f7c94..71fab4c0f7 100644 --- a/crates/ui-egui/src/tools/type_tool/ime_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/ime_tests.rs @@ -1038,14 +1038,14 @@ fn reset_harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, ResetHarn 170.0, &["Family 00".into(), "Family 01".into()], photocraft_engine::prefs::FontPreview::Medium, - &[], + &mut FontLibrary::default(), ); let search = ui.scope_id().with(("font-search", "reset-font")); state.search = ui.data(|d| d.get_temp::(search)).unwrap_or_default(); let input = search.with("input"); state.search_input = Some(input); state.search_focused = ui.memory(|m| m.has_focus(input)); - state.search_height = ui.memory(|m| m.area_rect(button.with("popup"))).map(|r| r.height()); + state.search_height = ui.data(|d| d.get_temp::(search.with("body"))).map(|r| r.height()); }); } if state.picker_button { 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 1eb8868190..55ff499ca3 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -33,13 +33,22 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // 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 font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { - app.note_recent_font(&fam); + if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { app.ui.tool_options.type_font = fam.clone(); let st = styles(&fam); - style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) }; + 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(); - apply(app, ui.ctx(), json!({"font": fam})); + // 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})), + } } let opts: Vec<(String, String)> = styles(&fam).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(); diff --git a/crates/ui-egui/src/tools/type_tool/panel.rs b/crates/ui-egui/src/tools/type_tool/panel.rs index 53e1ed31d1..7211b17f3d 100644 --- a/crates/ui-egui/src/tools/type_tool/panel.rs +++ b/crates/ui-egui/src/tools/type_tool/panel.rs @@ -117,6 +117,86 @@ fn cell_width(avail: f32, n: usize) -> f32 { ((avail - (n - 1.0) * 2.0) / n).floor().max(20.0) } +/// The reference application's Character panel size list (points); Leading offers Auto, then +/// the same values. The reference app's options bar offers the same size list. +pub(crate) const SIZE_PRESETS: [f32; 17] = [6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0, 150.0, 300.0]; +/// Tracking presets (1/1000 em), in groups split by separators: tightening, none, loosening. +const TRACKING_PRESETS: [&[f32]; 3] = [&[-100.0, -75.0, -50.0, -25.0, -10.0, -5.0], &[0.0], &[5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 200.0]]; + +/// What a [`metric_field`] produced: a typed value in the display unit, a preset in the model's +/// unit (points; converting it through the display unit and back would store 12.000001), or Auto. +#[derive(Clone, Copy, Debug, PartialEq)] +enum MetricChoice { + Typed(f32), + Preset(f32), + Auto, +} + +/// A preset as the list shows it: the value in the display unit, at most two decimals. +fn preset_label(v: f32, unit: &str) -> String { + let n = format!("{v:.2}"); + let n = n.trim_end_matches('0').trim_end_matches('.'); + let n = if n == "-0" { "0" } else { n }; + if unit.is_empty() { n.to_owned() } else { format!("{n} {unit}") } +} + +/// A Character panel [`num_field`] with a preset chevron in the same cell, which still ends at +/// the column's right edge. The value stays editable: presets are shortcuts, not limits. +/// `presets` are groups of model values (split by separators), shown multiplied by `u`; `auto` +/// adds an Auto item first (`Some(true)` when Auto is current). +#[allow(clippy::too_many_arguments)] +fn metric_field( + ui: &mut egui::Ui, + (label, tip, menu): (&str, &str, &str), + value: f32, + range: std::ops::RangeInclusive, + (u, unit): (f32, &str), + width: f32, + presets: &[&[f32]], + auto: Option, +) -> Option { + let sp = ui.spacing().clone(); + let pad = sp.button_padding.x; + let combo_w = (sp.icon_spacing + sp.icon_width).max(16.0 - 2.0 * pad) + 2.0 * pad; + let mut chosen = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + if let Some(v) = num_field(ui, label, tip, value, range, unit, (width - combo_w).max(24.0)) { + chosen = Some(MetricChoice::Typed(v)); + } + let near = |p: f32| (p * u - value).abs() <= 1e-4 * value.abs().max(1.0); + let (press, close) = crate::press_menu::PressCombo::before(ui, menu); + let combo = craft_ui::ComboBox::from_id_salt(menu) + .selected_text("") + .width(combo_w) + .height(420.0) + .icon(crate::widgets::chevron_icon) + .close_behavior(close) + .show_ui(ui, |ui| { + if let Some(on) = auto { + let item = ui.selectable_label(on, tl!("Auto")); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Auto); + } + } + for (i, group) in presets.iter().enumerate() { + if i > 0 { + ui.separator(); + } + for &p in *group { + let item = ui.selectable_label(auto != Some(true) && near(p), preset_label(p * u, unit)); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Preset(p)); + } + } + } + }); + press.after(&combo.response); + combo.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), tl!(menu))); + }); + chosen +} + /// Properties panel sections for a type layer: Character, Paragraph and Type Options (#155). pub fn type_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { type_sections(app, ui, true, true, false); @@ -153,10 +233,16 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa let mut ready = true; row(ui, &mut |ui| { ready = fonts_ready(ui, full); - if ready && font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { - app.note_recent_font(&fam); + if ready && let Some(picked) = font_picker(app, ui, &mut fam, full) { app.ui.tool_options.type_font = fam.clone(); - apply(app, ui.ctx(), json!({"font": fam})); + match picked { + Some(style) => { + // New type takes the style too, as from the options bar's menu. + app.ui.tool_options.type_style = style.clone(); + apply(app, ui.ctx(), json!({"font": fam, "fontStyle": style})); + } + None => apply(app, ui.ctx(), json!({"font": fam})), + } } }); row(ui, &mut |ui| { @@ -175,13 +261,24 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa let k = shown_scale(app); // Hover tips stay English until wired through `tl!` in a multi-locale change // (`every_tl_literal_is_translated` requires every complete catalog). - if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k * u, 0.1 * u..=1296.0 * u, unit, w) { - app.ui.tool_options.type_size = v / u; - apply(app, ui.ctx(), json!({"size": v / u, "metricsAsShown": true})); + let size = + metric_field(ui, ("tT", "Font size", "Font size presets"), c.size_pt * k * u, 0.1 * u..=1296.0 * u, (u, unit), w, &[&SIZE_PRESETS], None); + if let Some(pt) = match size { + Some(MetricChoice::Typed(v)) => Some(v / u), + Some(MetricChoice::Preset(pt)) => Some(pt), + _ => None, + } { + app.ui.tool_options.type_size = pt; + apply(app, ui.ctx(), json!({"size": pt, "metricsAsShown": true})); } let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; - if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead * u, 0.1 * u..=5000.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})); + let tip = "Leading (set to the font size × auto-leading when Auto)"; + match metric_field(ui, ("A↕", tip, "Leading presets"), lead * u, 0.1 * u..=5000.0 * u, (u, unit), w, &[&SIZE_PRESETS], Some(c.leading_pt.is_none())) + { + Some(MetricChoice::Typed(v)) => apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})), + Some(MetricChoice::Preset(pt)) => apply(app, ui.ctx(), json!({"leading": pt, "metricsAsShown": true})), + Some(MetricChoice::Auto) => apply(app, ui.ctx(), json!({"leading": "auto"})), + None => {} } }); row(ui, &mut |ui| { @@ -193,7 +290,9 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa apply_kerning(app, ui.ctx(), v); } }); - if let Some(v) = num_field(ui, "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w) { + if let Some(MetricChoice::Typed(v) | MetricChoice::Preset(v)) = + metric_field(ui, ("VA", "Tracking (1/1000 em)", "Tracking presets"), c.tracking, -1000.0..=10000.0, (1.0, ""), w, &TRACKING_PRESETS, None) + { apply(app, ui.ctx(), json!({"tracking": v})); } }); diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index eab436fd07..301db9b63b 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -40,7 +40,8 @@ pub(crate) use overlay::{draw_anchor, draw_handle, draw_outline}; use path_ops::target_path; pub use path_ops::{active_path_name, path_selection_finish, path_to_selection, pick_shape_at, selected_document_path, takes_path_mask, with_active_path}; pub(crate) use path_ops::{ - active_shape_path, delete_key_deletes_work_path, deselect_loaded_path, free_transform_path, targeted_vector_mask, work_path_shown, work_path_shown_in, + active_shape_path, active_type_path, delete_key_deletes_work_path, deselect_loaded_path, free_transform_path, targeted_vector_mask, work_path_shown, + work_path_shown_in, }; #[cfg(test)] use paths_panel::path_context_actions; diff --git a/crates/ui-egui/src/tools/vector_ui/overlay.rs b/crates/ui-egui/src/tools/vector_ui/overlay.rs index 6f394c6828..9649b1365d 100644 --- a/crates/ui-egui/src/tools/vector_ui/overlay.rs +++ b/crates/ui-egui/src/tools/vector_ui/overlay.rs @@ -1,5 +1,5 @@ use super::curvature::curvature_refresh; -use super::path_ops::targeted_vector_mask; +use super::path_ops::{active_type_path, targeted_vector_mask}; use super::pen::{closing, over_first_anchor, shift_45}; use super::*; @@ -166,6 +166,10 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some((_, p)) = targeted_vector_mask(app) { draw_path(&p, anchors); } + // So does type on a path's Type Path, which the Pen's Auto Add/Delete edits (#9114). + if let Some((_, p)) = active_type_path(app) { + draw_path(&p, anchors); + } crate::corner_radius::draw(app, painter, &to_scr, accent); } // Pen path in progress, with handles of the last knot and a rubber band to the pointer. While diff --git a/crates/ui-egui/src/tools/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs index 30feea8dc2..a50708c6ae 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -127,6 +127,16 @@ pub(crate) fn targeted_vector_mask(app: &PhotocraftApp) -> Option<(u64, Path)> { l.vector_mask.as_ref().map(|m| (l.id.0, m.path.clone())) } +/// The active type layer's path in document space, if it is type on a path (#9114). +pub(crate) fn active_type_path(app: &PhotocraftApp) -> Option<(u64, Path)> { + let st = app.session.active()?; + let l = st.active_layer.and_then(|id| st.doc.layer(id))?; + match &l.content { + LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).map(|p| (l.id.0, p)), + _ => None, + } +} + /// The active shape layer's path, if the active layer is a shape layer. pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> { let st = app.session.active()?; diff --git a/crates/ui-egui/src/tools/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs index 50c14a2570..202c2fd184 100644 --- a/crates/ui-egui/src/tools/vector_ui/tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/tests.rs @@ -285,6 +285,19 @@ fn an_unselected_work_path_is_not_drawn_over_the_canvas() { } } +/// #9114: the active type layer's Type Path shows with the Pen, whose Auto Add/Delete edits it. +#[test] +fn the_type_path_of_type_on_a_path_is_drawn_with_the_pen() { + let ctx = egui::Context::default(); + let mut app = app(); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap(); + app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap(); + app.run("type.attachToPath", json!({})).unwrap(); + app.run("path.delete", json!({"name": "work"})).unwrap(); + app.ui.tool = Tool::Pen; + assert!(overlay_shapes(&app, &ctx) > 0, "the Type Path is drawn"); +} + #[test] fn show_target_path_and_extras_hide_the_path_outlines() { // #1119: View › Show › Target Path only flipped its checkmark; the canvas kept drawing the diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 2c90cf7981..e8d8b334ba 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -29,6 +29,7 @@ mod pattern_preview_canvas; mod radial_blur_center; mod remove_channel_target; mod system_locale; +mod transform_readout_units; mod ui_scale_canvas; mod variables_data_sets; mod workspace_presets; diff --git a/crates/ui-egui/tests/it/transform_readout_units.rs b/crates/ui-egui/tests/it/transform_readout_units.rs new file mode 100644 index 0000000000..9dd848e46a --- /dev/null +++ b/crates/ui-egui/tests/it/transform_readout_units.rs @@ -0,0 +1,116 @@ +//! #9400: while a Free Transform handle is dragged, the W/H readout beside the pointer shows the +//! box's size in the Units & Rulers unit (as Photoshop does), not always its scale in percent. +//! +//! The real app runs offscreen on wgpu with real egui pointer events. Skips when no GPU adapter +//! exists (like `drag_preview_canvas.rs`). Set `PHOTOCRAFT_TRANSFORM_READOUT_EVIDENCE_DIR` to save +//! the frames, mid-drag, as PNGs. + +use egui::{Modifiers, PointerButton, Pos2}; +use egui_kittest::kittest::Queryable; +use photocraft_engine::prefs::Unit; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::canvas::ViewXform; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +fn harness() -> Option { + let built = std::panic::catch_unwind(|| { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_max_steps(64).wgpu().build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + // The queries below use English labels; don't follow the system locale. + app.session.prefs.edit(|p| p.interface.language = "en".into()); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +fn xf(h: &Harness) -> ViewXform { + ViewXform::active(h.state()).expect("a view") +} + +fn press(h: &mut Harness, p: Pos2, pressed: bool) { + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); +} + +/// A 400 × 300 px document at 72 ppi, 100 %, with a 100 × 50 px box on its own layer at +/// (100, 100) and Free Transform open on it. +fn setup() -> Option { + let mut h = harness()?; + h.run_steps(4); + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).expect("new"); + app.run("layer.new.layer", json!({})).expect("layer"); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 50})).expect("select"); + app.run("edit.fill", json!({"color": "#3366cc"})).expect("fill"); + app.run("select.deselect", json!({})).expect("deselect"); + app.sync_views(); + app.ui.extras.rulers = true; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + } + control(&mut h, "ui.set", json!({"tool": "move", "zoom": 1.0, "center": [200, 150]})); + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + assert!(h.state().ui.transform.is_some(), "the box is open"); + Some(h) +} + +#[test] +fn the_scale_readout_shows_the_size_in_the_ruler_unit() { + // Windows WARP can access-violate when GPU harnesses initialize or tear down concurrently: + // hold the GPU lock for the whole test, harness included. + let _gpu = photocraft_testkit::gpu_lock(); + // The right edge from x 200 to 300 doubles the box (proportionally): 200 × 100 px, which at + // 72 ppi is 7.06 × 3.53 cm; 200 % of the original box with the rulers in percent. + for (unit, name, w, h_text) in + [(Unit::Pixels, "pixels", "200 px", "100 px"), (Unit::Centimeters, "centimeters", "7.06 cm", "3.53 cm"), (Unit::Percent, "percent", "200.0%", "200.0%")] + { + let Some(mut h) = setup() else { return }; + h.state_mut().session.prefs.edit(|p| p.units_and_rulers.rulers = unit); + let x = xf(&h); + let (from, to) = (x.to_screen(200.0, 125.0), x.to_screen(300.0, 125.0)); + press(&mut h, from, true); + for i in 1..=8 { + h.event(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.step(); + } + h.run_steps(2); + // `query_all`: in percent W and H both read 200.0%. + assert!(h.query_all_by_label(w).next().is_some(), "{name}: W reads {w}"); + assert!(h.query_all_by_label(h_text).next().is_some(), "{name}: H reads {h_text}"); + // The readout used to show percent whatever the ruler unit. + if unit != Unit::Percent { + assert!(h.query_all_by_label("200.0%").next().is_none(), "{name}: no percent readout"); + } + if let Some(dir) = std::env::var_os("PHOTOCRAFT_TRANSFORM_READOUT_EVIDENCE_DIR") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).expect("evidence directory"); + h.render().expect("render").save(dir.join(format!("transform-readout-{name}.png"))).expect("save evidence"); + } + press(&mut h, to, false); + h.key_press(egui::Key::Escape); + h.run_steps(3); + } +} diff --git a/docs/context-menu-inventory.md b/docs/context-menu-inventory.md index a932a58b20..e4c69c8e72 100644 --- a/docs/context-menu-inventory.md +++ b/docs/context-menu-inventory.md @@ -29,7 +29,7 @@ Canvas invariant: secondary click must not accidentally start a paint stroke, co | Surface | Current entries or behavior | Command route / gap | |---|---|---| -| Layers panel row | Blending Options; Duplicate/Delete; Group from Layers; Quick Export PNG / Export As; Artboard/Frame from Layers; Convert to Smart Object; content-specific Rasterize; Add/Disable/Apply/Delete Layer Mask; Create/Release Clipping Mask; Link/Select Linked; Copy/Paste/Clear Layer Style; Merge Layers/Down, Merge Visible, Flatten Image; Rename Layer. Multi-select changes duplicate/delete/merge labels and target. | `layer_menu_ui::entries` supplies IDs for all except inline rename, then `menus::invoke` or engine dispatch. Missing or disabled commands are filtered/greyed. Check menu visibility and enabled state for groups, backgrounds, masks, type, adjustment/fill, smart objects, and multi-selection. | +| Layers panel row | Blending Options; Duplicate/Delete; Group from Layers (New Group from Layers dialog, also for a multi-selection); Quick Export PNG / Export As; Artboard/Frame from Layers; Convert to Smart Object; content-specific Rasterize; Add/Disable/Apply/Delete Layer Mask; Create/Release Clipping Mask; Link/Select Linked; Copy/Paste/Clear Layer Style; Merge Layers/Down, Merge Visible, Flatten Image; Rename Layer. Multi-select changes duplicate/delete/merge labels and target. | `layer_menu_ui::entries` supplies IDs for all except inline rename, then `menus::invoke` or engine dispatch. Missing or disabled commands are filtered/greyed. Check menu visibility and enabled state for groups, backgrounds, masks, type, adjustment/fill, smart objects, and multi-selection. | | Channels panel row | Alpha: Duplicate/Delete/Rename, spot conversion or merge, selection-display and overlay controls. Quick Mask: Exit, display and overlay. Composite/color: Duplicate. Layer mask: Enable/Disable, Delete, Layer Mask Display Options… (also on double-click). Common: New Channel, New Spot Channel, Split, Merge. | `channel.*`, `layer.layerMask.*`, `select.editInQuickMaskMode`, `ui.renameChannel`. Check selection loading/saving, channel options, and per-row enablement against Photoshop. | | Brushes panel preset | Rename Brush, Delete Brush. | Routed through `brush.presets.*` panel actions. Check duplicate/export/import and library organization. | | Brushes panel group | Rename Group, Delete Group. | Routed through preset panel actions; confirm group deletion consequences. | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d291f45d3b..cd8f370ce6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -63,7 +63,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `ui.set` also accepts `cropFill` (`background`, Photoshop's Background (Default), or `contentAware`), the Crop tool's Fill dropdown (#3823): with `contentAware`, committing a turned or extending frame passes `contentAware: true` to `image.crop`, which fills the area the image doesn't cover from its surroundings. `ui.inspect` reports it as `toolOptions.crop_content_aware`. Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them. - `ui.set` also accepts the Crop tool's gear menu (#1919) as `cropShield`, an object patching any of `show_cropped_area` (Show Cropped Area; off hides everything outside the box behind the canvas colour, H in the app), `enabled` (Enable Crop Shield), `color` (`matchCanvas`, the pasteboard colour, or `custom`), `custom_color` (`[r, g, b]`, 0..255), `opacity` (0..100, default 75), `auto_adjust` (Auto Adjust Opacity: half the opacity while the box is dragged), `classic_mode` (Use Classic Mode, default off: the box turns and moves over the image; off is Photoshop's default mode, where the box stays upright and the view turns and pans the image behind it while the Crop tool shows a frame, P in the app; in both modes picking the tool turns a rotated view upright about its centre, Classic Mode keeping the camera upright with the frame drawn turned, and the view stays upright after a commit or cancel; Classic Mode greys out Show Cropped Area, which then acts as on, and Auto Center Preview) and `auto_center_preview` (default on: in default mode a box being resized keeps its centre where it is on screen, also after a pan, a drawn one moves to the middle of the canvas, and X re-centres it; a move never re-centres the box). `ui.inspect` reports it as `toolOptions.crop_shield`. The pending frame (`crop_rect`, `crop_angle`: its turn on the image) and the `image.crop` a commit runs are the same in both modes. -- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`, `newCropPreset` / `deleteCropPreset`: the Crop tool's New / Delete Crop Preset… dialogs, fields `name` and `selected: [names]`; crop presets are `crop` tool presets, so `tool.presets.new/list/edit {"tool":"crop"}` drive them too) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once +- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}` (`layer.new.group` / `layer.new.groupFromLayers` open the New Group dialog: fields `name`, `color`, `mode`, `opacity`), `newCropPreset` / `deleteCropPreset`: the Crop tool's New / Delete Crop Preset… dialogs, fields `name` and `selected: [names]`; crop presets are `crop` tool presets, so `tool.presets.new/list/edit {"tool":"crop"}` drive them too) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once - A Layer Style color field opens the shared picker with `ui.dialog.open {"kind":"colorPicker","parent":12,"effect":"fx2","field":"color"}`. `parent` is the Layer Style dialog id; `effect` is its effect instance id. `field` must be one of that instance's color parameters (`color`, or `from`/`to` for Gradient Overlay). The picker previews over the pending style without changing the document. Picker OK changes only the parent parameter; Cancel discards the preview. Confirm the parent afterwards to apply the style. Parent confirmation is refused while its picker is open; parent cancellation closes both. The binding is exposed in `ui.inspect` as `__layerStyleColor`; changed/closed targets or a document switch invalidate it. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md new file mode 100644 index 0000000000..af05ebae0f --- /dev/null +++ b/docs/deflate-zlib-rs-performance.md @@ -0,0 +1,97 @@ +# Deflate backend comparison + +Replace the workspace flate2 Rust backend with zlib-rs and runtime CPU detection. Tiles in .pcraft remain Zstandard; deflate changes its PNG previews. + +Size, import-speed and dependency tradeoffs remain maintainer decisions. +Some PSD ZIP files grow by up to 0.71%. The macOS 16-bit city PSD import is about 6% slower in confirmation. +The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 25 bytes. +Real photo PNGs become smaller and encode faster. The default and best levels are unchanged; callers that +used level 1 (PDF export and print, brush tips, PNG Fast) now use level 3, because zlib-rs level 1 writes +static Huffman blocks only (13-32% bigger on photos). Level 3 is never bigger than miniz's level 1 on the +docs/images photos (0-16% smaller) and takes 1.2-3.4 times as long. +There is no native-format tile speedup from deflate. + +The timings below measure only the backend switch. They exclude the later ZIP allocation, validation and slice decoder changes. + +Measured on 2026-10-19 against main `d95fdf31`, independently of the other performance changes. +Host: Apple M4 Max, 16 CPUs, 128 GiB RAM, macOS arm64, rustc 1.99.1. +Release settings: optimization level 3, no LTO, 16 codegen units and no debug information. +Builds finish before measurement. Measurements use default priority without concurrent builds or profiling. +Five alternating pairs follow a warmup. Confirmation uses nine pairs. +Time changes compare medians, and intervals resample paired ratios. Negative changes mean less elapsed time. +Small differences are not automatically established improvements or regressions. + +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. + +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. + +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| canon-16 | psd-import (confirm) | 168.891 | 178.614 | +5.8% | +3.5..+5.9% | 140,673,004 / 140,673,004 | +| panasonic-8 | save | 166.659 | 162.322 | -2.6% | -3.9..-1.0% | 49,643,217 / 49,643,242 | +| panasonic-8 | load-common | 410.794 | 409.622 | -0.3% | -0.5..+0.3% | 49,643,217 / 49,643,217 | +| panasonic-8 | png-encode | 373.880 | 165.381 | -55.8% | -56.3..-47.4% | 24,569,965 / 24,238,416 | +| panasonic-8 | png-decode | 168.141 | 167.247 | -0.5% | -2.0..+1.0% | 24,569,965 / 24,569,965 | +| panasonic-8 | psd-export | 2938.276 | 1115.740 | -62.0% | -62.3..-61.6% | 98,823,859 / 98,837,585 | +| panasonic-8 | psd-import | 275.713 | 174.046 | -36.9% | -38.8..-34.7% | 98,823,859 / 98,823,859 | +| panasonic-16 | save | 357.998 | 355.900 | -0.6% | -1.8..+0.5% | 175,681,852 / 175,681,844 | +| panasonic-16 | load-common | 387.986 | 391.411 | +0.9% | -1.3..+1.1% | 175,681,852 / 175,681,852 | +| panasonic-16 | png-encode | 354.924 | 288.664 | -18.7% | -27.8..-14.2% | 111,583,441 / 109,241,690 | +| panasonic-16 | png-decode | 434.083 | 433.645 | -0.1% | -1.0..+1.7% | 111,583,441 / 111,583,441 | +| panasonic-16 | psd-export | 2645.838 | 2249.281 | -15.0% | -15.6..-13.8% | 274,409,683 / 275,654,405 | +| panasonic-16 | psd-import | 371.291 | 374.777 | +0.9% | -1.1..+1.8% | 274,409,683 / 274,409,683 | +| panasonic-32 | save | 639.677 | 631.556 | -1.3% | -5.2..+1.8% | 252,231,671 / 252,231,663 | +| panasonic-32 | load-common | 1338.160 | 1326.936 | -0.8% | -1.1..-0.2% | 252,231,671 / 252,231,671 | +| panasonic-32 | psd-export | 2522.700 | 1352.144 | -46.4% | -49.6..-44.6% | 461,042,978 / 459,545,262 | +| panasonic-32 | psd-import | 356.077 | 310.425 | -12.8% | -20.2..-4.7% | 461,042,978 / 461,042,978 | +| canon-8 | save | 89.139 | 85.965 | -3.6% | -8.9..+2.7% | 26,151,631 / 26,151,203 | +| canon-8 | load-common | 219.711 | 219.088 | -0.3% | -0.3..+1.0% | 26,151,631 / 26,151,631 | +| canon-8 | png-encode | 179.944 | 80.123 | -55.5% | -60.8..-40.0% | 13,720,268 / 13,551,023 | +| canon-8 | png-decode | 69.704 | 70.040 | +0.5% | -0.4..+0.6% | 13,720,268 / 13,720,268 | +| canon-8 | psd-export | 1074.094 | 475.802 | -55.7% | -56.1..-55.4% | 56,209,597 / 56,608,401 | +| canon-8 | psd-import | 142.523 | 96.323 | -32.4% | -34.4..-26.9% | 56,209,597 / 56,209,597 | +| canon-16 | save | 185.898 | 183.472 | -1.3% | -2.8..-0.2% | 88,750,003 / 88,749,555 | +| canon-16 | load-common | 193.409 | 193.704 | +0.2% | -0.2..+0.8% | 88,750,003 / 88,750,003 | +| canon-16 | png-encode | 169.432 | 135.364 | -20.1% | -26.2..-15.4% | 58,279,529 / 57,568,207 | +| canon-16 | png-decode | 211.947 | 211.829 | -0.1% | -0.4..+0.5% | 58,279,529 / 58,279,529 | +| canon-16 | psd-export | 1295.076 | 1130.697 | -12.7% | -13.5..-9.9% | 140,673,004 / 141,105,829 | +| canon-32 | save | 340.781 | 334.426 | -1.9% | -5.3..+0.7% | 120,957,984 / 120,957,536 | +| canon-32 | load-common | 774.663 | 778.401 | +0.5% | -1.3..+8.5% | 120,957,984 / 120,957,984 | +| canon-32 | psd-export | 1028.651 | 647.483 | -37.1% | -40.5..-36.1% | 228,234,238 / 227,497,106 | +| canon-32 | psd-import | 177.500 | 146.373 | -17.5% | -18.5..-17.1% | 228,234,238 / 228,234,238 | +| layout-masks | save | 18.588 | 18.268 | -1.7% | -2.7..+0.6% | 433,949 / 433,924 | +| layout-masks | load-common | 16.099 | 16.080 | -0.1% | -1.5..+0.6% | 433,949 / 433,949 | +| layout-masks | png-encode | 3.911 | 2.557 | -34.6% | -36.0..-32.3% | 42,842 / 43,440 | +| layout-masks | png-decode | 0.781 | 0.767 | -1.8% | -2.5..+2.2% | 42,842 / 42,842 | +| layout-masks | psd-export | 56.043 | 46.949 | -16.2% | -18.5..-15.9% | 493,006 / 493,145 | +| layout-masks | psd-import | 12.324 | 12.334 | +0.1% | -4.8..+2.3% | 493,006 / 493,006 | +| layout-mask-index | save | 7.367 | 7.202 | -2.2% | -5.5..-0.7% | 344,892 / 344,746 | +| layout-mask-index | load-common | 6.601 | 6.602 | +0.0% | -2.8..+4.7% | 344,892 / 344,892 | +| layout-mask-index | png-encode | 11.520 | 5.971 | -48.2% | -49.5..-46.0% | 115,229 / 114,892 | +| layout-mask-index | png-decode | 1.451 | 1.444 | -0.5% | -4.2..+0.5% | 115,229 / 115,229 | +| layout-mask-index | psd-export | 19.135 | 12.721 | -33.5% | -34.0..-31.5% | 411,435 / 411,594 | +| layout-mask-index | psd-import | 3.362 | 2.721 | -19.1% | -21.3..-11.2% | 411,435 / 411,435 | + +Every PNG encode decodes to identical source pixels, each PSD operation produces the same decoded layer/mask samples as main, and complete .pcraft documents compare equal at every depth. Compressed bytes may differ. The committed compatibility test independently inflates PNG IDAT and PSD ZIP/ZIP-prediction data using old miniz_oxide and checks .pcraft tiles plus thumbnails. + +## Allocation and validation changes + +ZIP lookup keys borrow valid UTF-8 entry paths, avoiding a second string allocation per entry. Invalid names keep their previous lossy spelling and duplicate-name lookup still selects the first entry. The bundle writer reserves the complete archive after compression, including its central directory. It rejects entry paths that exceed ZIP's 65,535-byte field before writing and checks that the central-directory size fits its ZIP field. These archive paths are independent of filesystem path limits. + +Affinity zlib entries, deep EXR ZIP chunks and compressed SVG input now decode directly from their byte slices. This removes flate2's 32 KiB input-buffer allocation and copy for each decoder. Output bounds, checksums and SVG concatenated gzip members remain covered by tests. These are structural allocation reductions, not measured timing gains. + +## Linux and Windows x86-64 validation + +[GitHub Actions run](https://github.com/reneleonhardt/photocraft/actions/runs/39444647224) passed the deflate compatibility test, +the full IO/codecs/format package tests and `cargo xtask wasm` on Ubuntu 24.04 and Windows 2022 x86-64. +The temporary `ci/deflate-zlib-rs-x86` branch at `46232997` contains the workflow and benchmark setup. +The run's `deflate-x86-results` artifact contains all raw samples, the full table, input and binary hashes, backend features and host details. + +The timing host used an Intel Xeon 6973P-C with four vCPUs and rustc 1.99.1. +Main at `d95fdf31` and the backend change at `a37198d4` used matching release settings. +One warmup preceded nine alternating pairs on the same 12/24 MP photos at U8/U16. +Both importers received the same baseline-encoded PSD files. Loading, conversion, hashes and checks stayed outside the elapsed-time measurements. +PNG encode time fell 23.8–56.8%, PSD export time 18.1–58.2%, and PSD import time 7.8–21.6%. +The 16-bit city import fell from 440.733 to 402.057 ms (-8.78%); the macOS slowdown did not recur on this runner. +Photo PNGs became 1.2–2.1% smaller. Exported PSDs grew by 0.014–0.709%. +All decoded pixels, dimensions, depths and profiles matched. These results cover this Linux host; Windows and F32 were not timed. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dc5975cc0b..f49fa461de 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,8 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-24 · **Change:** minor (Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-24 · **Change:** minor (PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 + +**PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write @@ -148,6 +150,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | 2026-10-23 | minor | TIFF: alpha and spot channels are written and read as extra samples (at most 16) with Photoshop's channel resources (1006, 1045, 1077, 1053), spot ink stored 0 = solid as Photoshop 27.11's TIFFs store it; PSD output is unchanged. FILE-215-7 done, FILE-215-17 partial (its TIFF part) (#7415, supersedes #3121) | | 2026-10-23 | patch | PSD and layered TIFF: the `MTrn` block Photoshop writes in a layered TIFF saved with Save Transparency (a positive layer count, `nrTM` in an `II` file) marks the merged image's first extra channel as its transparency, like `Mtrn`/`Mt16`/`Mt32`: such a file no longer opens with its transparency also as an alpha channel (named "Transparency" in Photoshop 27.11's file), and a PSD save no longer writes it twice. A PSD save with an opaque composite drops any of these markers kept from the opened file, so its first alpha channel no longer reopens as transparency and vanishes (split from #7415; credit #3121) | | 2026-10-23 | minor | Amiga IFF write: Save As `.iff` stores a 24-plane ILBM (ByteRun1, alpha as a 1-bit mask plane), and 24-plane ILBMs open | +| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`); PSD/PSB round trips at 8/16/32 bits, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | 32-bit Hue/Saturation as Photoshop does it: the raised saturation isn't clipped (saturated colours leave 0..1), the chroma is scaled around the lightness by Photoshop's saturation factor (measured at every whole percent), so colours at or above lightness 1 keep their hue, and Colorize builds its colour with the saturation times 1 − \|Lightness\| (8 and 16 bits unchanged): photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-19 | minor | JPEG Options on File › Save, Save As and Save a Copy (FILE-215-19 partial: no Matte, progressive Scans or size preview) | | 2026-10-18 | minor | Scripted TIFF saves take `tiffCompression` (none, LZW, ZIP), and the CLI `--tiff-compression` (#5301) | diff --git a/docs/gaps.md b/docs/gaps.md index a23e79b649..0c94561436 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 181 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -40,6 +40,7 @@ what an agent can't finish alone. ## Feature gaps ### G1. PSD fidelity and Photoshop acceptance +- **Done 2026-10-23 (#8940):** Filter Gallery Halftone Pattern preserves size, contrast and dot/circle/line through PSD/PSB import/export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`). Malformed descriptors stay verbatim. Other unsupported gallery effects remain opaque on import or produce an export warning. - **Missing:** PSDs we write are not always accepted by Photoshop, and Photoshop-authored files don't always render as Photoshop renders them. - **Partial (2026-10-15, #5972 A1):** `GdFl` noise fills render when all three RGB ranges are @@ -285,7 +286,7 @@ what an agent can't finish alone. - **Progress (2026-10-15):** the Color panel has Photoshop's panel-menu modes (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), its colour ramp and copy commands, the same in every theme (UI-217-17, #2569, #6000; `ui-egui/src/color_panel_ui.rs`). -- **Missing:** 12 of 178 preferences do nothing (scorecard prefs audit, 2026-10-25); panel groups can't +- **Missing:** 12 of 181 preferences do nothing (scorecard prefs audit, 2026-10-27); panel groups can't float or tear off into OS windows (UI-217-5, #1828, #1213, #2305); more themes (UI-217-11, #2661); a single pixel layer copies without its mask and styles (UI-217-23; fill and adjustment layers copy whole, #2344); tool-specific context menus beyond brushes, selections, Pen and Crop @@ -395,6 +396,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | G9: 12 of 181 preferences do nothing, the scorecard's count with integration batch 9 (#9775) on main; no estimate changed | | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | @@ -402,6 +404,7 @@ what an agent can't finish alone. | 2026-10-23 | minor | G10: PSD stores and reads spot channels as Photoshop does (ink 0 = solid) with their identifiers (1053); PSDs from PhotoCraft 0.1.0–0.16.0 keep their ink (#7415 split, part 4); FILE-215-17 stays partial; estimate unchanged | | 2026-10-23 | minor | G10: TIFF alpha and spot channels written and read as extra samples with Photoshop's channel resources, PSD output unchanged (#7415); FILE-215-7 leaves the list, FILE-215-17 narrows to RGB/CMYK spot preview and PDF Separation | | 2026-10-23 | minor | G10: Amiga IFF write landed (24-plane ILBM, Save As `.iff`) and 24-plane ILBMs open | +| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`); PSD/PSB round trips at 8/16/32 bits, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | G17: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; estimate unchanged | | 2026-10-22 | minor | G1: 32-bit Hue/Saturation unclipped with Photoshop's saturation factor, bright colours keep their hue, Colorize's saturation scaled by 1 − \|Lightness\|; photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-21 | minor | G9: adjustment clipping remains visible in compact Properties (#5231); no readiness percentage or estimate changed | diff --git a/docs/scorecard.md b/docs/scorecard.md index 8045086f6b..70b08b831b 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 31 | 65 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 27 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 180 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 181 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -187,7 +187,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 180** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 12 of 181** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 81b0ab81d6..4490d693c2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -224,18 +224,24 @@ Paragraph; the rest open as in-app floating windows. | Panel groups float and tear off into OS windows | missing | UI-217-5, #1828, #1213 | | Drag panels to reorder and regroup | partial | #2272, #2305 | | Docked resize pushes the neighbour | partial | #2573 | -| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000 | +| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | | Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar | -| Every preference takes effect | partial | 12 of 178 do nothing (scorecard, 2026-10-25) | +| Every preference takes effect | partial | 12 of 181 do nothing (scorecard, 2026-10-27) | | UI scale presets | done | UI-217-9; 75–125% in 5% steps (#2492, #3222) | | History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; the snapshot History Options and History Brush sources to come (#2966) | | Themes: Photoshop's four greys | partial | five themes; #2661 | | Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 | | Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 | +| Layers panel New Group button: click with 2+ layers selected groups them (CC 2014+), ⇧-click groups, one layer gives an empty group, ⌥-click opens the New Group dialog, ⌘-click adds the group below the active layer | done | #2561, `new_group_button_tests.rs` | +| New Group dialog (Name, Color, Mode, Opacity) for Layer › New › Group… / Group from Layers…, the Layers panel menu and the row menu; ⌘G stays immediate | done | `dialogs/new_group_ui.rs`, `dialogs/new_group_ui/tests.rs` | +| Groups made from layers (⌘G, New Group button, Group from Layers) start collapsed; selecting a layer inside opens the group | done | `group_options.rs` tests, `new_group_button_tests.rs` | +| New layers (New Layer/Group, adjustment, fill, type, shape, paste, place…) go in as the top layer of an open active group (or an artboard the new content is on), above a closed one; type, shapes, pastes, placed files and frames go above a group whose lock (all, pixels, transparency or position) would refuse them; a new frame starts closed | done | `layer_place.rs`, `layer_place_tests.rs` | +| A new layer or group inside a clipping mask joins it (clipped when the layer above its slot is), so the clipped layers keep their base | done | `layer_place_tests.rs` (#2203) | +| Layers panel New Layer button: ⌘-click adds the layer below the active one (never under the Background) | done | `layer_place_tests.rs`, `new_group_button_tests.rs` | | Layers panel filter-type dropdown (Kind, Name, Effect, Mode, Attribute, Color, Smart Object, Selected, Artboard) | partial | Kind, Name and Mode; the other six missing. `layer_filter_ui.rs`, `ui.set {layerFilter}` (#5048) | | Adjustment scope: clipping control visible above tall Properties editors in a compact dock | done (2026-10-21) | `panels.rs`, `clipping_indicator_tests.rs`; #5231; stack-wide default retained | | Smart filter rows: click selects, drag onto another smart object moves, ⌥-drag copies, drag onto Delete removes; with a row selected, the Delete button and the ⌫/Delete key remove that filter, not the smart object | done | `smart_ui.rs`, `layer.smartFilter.transfer` (#4271), `smart_ui::keys` (#4751) | @@ -246,8 +252,10 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Every preference takes effect: 12 of 181 do nothing, the scorecard's count with integration batch 9 (#9775) on main; new layers go above a group whose lock would refuse them (#4329) | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | +| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. | | 2026-10-24 | minor | Type options bar: the alignment and paragraph-direction buttons show the edited or selected type layer's paragraph instead of the tool defaults, as Photoshop's bar does. Scores unchanged. | | 2026-10-24 | minor | Font menus (options bar, Character panel): the current family is marked in the recent group when it is a recent one, and the menu opens showing it, as Photoshop's does, scrolled to the marked row when it sits below the fold; the arrows walk on from the marked row (#9160). Scores unchanged. | @@ -269,6 +277,8 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-13 | minor | Stale "missing tool" rows corrected against main: Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (the P flyout cycle) are live toolbar tools, so only Art History Brush is missing; no percentage or estimate changed | | 2026-10-13 | minor | Smart object perspective (non-affine) corrected to done: #426 landed four-corner placements with PSD round trip; scorecard FILE-215-6 flipped | | 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues | +| 2026-10-12 | minor | New Group button groups two or more selected layers (CC 2014+); New Group dialog (Layer › New, Layers panel menu, row menu, ⌥-click); ⌘-click New Group adds the group below; groups made from layers start collapsed (#2561) | +| 2026-10-12 | minor | New layers go into an open active group (or the artboard their content is on) and join the clip group they land in (#2203); ⌘-click New Layer adds below | | 2026-10-12 | minor | Closed #3632: Distort and Ctrl/Cmd corner drags snap actual corners to guides and intersections; shared guide snapping respects Extras and Canvas Guides visibility, with offset, visibility and constrained-alignment regressions | | 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions | | 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning |