diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5343c51805..42ef6f3aa3 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -105,6 +105,7 @@ The other built-in ICC profiles and the generated LUT looks are produced by code | `docs/brand/` (all files) | ArtCraft name, wordmark and mark | ArtCraft Team | getartcraft.com | Not open source; trademarks of the ArtCraft Team, [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt) | | `docs/images/photocraft-*.jpg` | PhotoCraft screenshots | PhotoCraft contributors (UI) | Rendered offscreen with the `snapshot` example | MIT OR Apache-2.0 (UI); the artwork in each is public domain, listed below | | `docs/images/preferences-apply-*.png` | Preferences before and after adding Apply (no artwork) | PhotoCraft contributors | PhotoCraft control-channel capture and offscreen `snapshot` example | MIT OR Apache-2.0 | +| `docs/images/guide-position-*-tab.png` | New Guide before and after focusing Position with Tab (no artwork) | PhotoCraft contributors | Offscreen `snapshot` example with `ui.key Tab` | MIT OR Apache-2.0 | | `docs/images/embedded-vector-editor-en.png` | Embedded AI/PDF/EPS conversion warning and editor chooser (no artwork) | Don Omondi | Offscreen `smart_svg_ui::tests::capture_embedded_vector_conversion_prompt` with authored bytes and mock services | MIT OR Apache-2.0 | | `docs/images/embedded-vector-tabs-linux.png` | Shared VectorCraft window after a portal editor save and ordinary document launch | Don Omondi | Local Linux GUI acceptance with authored orange rectangle/blue circle SVGs; no private artwork | MIT OR Apache-2.0 | | `docs/images/gradient-overlay-method-*.png` | Gradient Overlay Method selector, before and after (synthetic gradient) | @oRE-o | Rendered offscreen with the `snapshot` example; no external artwork | MIT OR Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index faa215496b..cec58ffb71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5247,6 +5247,7 @@ dependencies = [ "photocraft-engine", "photocraft-format", "photocraft-io", + "photocraft-psd", "photocraft-raster", "photocraft-raw", "serde", diff --git a/ROADMAP.md b/ROADMAP.md index 16943f6767..70637897d8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~30 points (ready for real work ~45% → ~75%, with reliable PSD) and ~1,100–1,800 h away -> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (Object Finder retains large enclosed foregrounds (#6548); Russian catalog covers every dynamic label; previously minor: oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-22 · **Change:** minor (Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; previously: Object Finder retains large enclosed foregrounds (#6548); Russian catalog covers every dynamic label; previously minor: oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026 PhotoCraft's one-page summary of how close it is to Adobe Photoshop 2026 (27.11.0, measured from the installed app on 2026-10-10) at version 0.6.0. Detail: [target-app parity](docs/target-app-parity.md) @@ -122,8 +122,10 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md). | Date | Entry | |---|---| +| 2026-11-02 | Layer Style: with Gradient Overlay selected, a drag on the image moves the gradient (its centre as a fraction of the layer's bounds, `params.offset`), as a drag moves a shadow (#10763) | | 2026-11-02 | Load Actions: Mac Roman step names with é ä ö ü Ä or ° read as Mac Roman instead of windows-1252 or Cyrillic (#10774): windows-1252's rare 0x80–0x9F letters and a lone Cyrillic letter in a Latin word no longer count as common text, the degree sign does, and the file's own Unicode text settles a word-initial rare letter and breaks exact ties toward windows-1252 or Mac Roman | | 2026-10-21 | Linux can use font-free Adwaita controls when System Title Bar is selected, while the integrated CSD title bar remains the default (as in #4439). Saved preferences are respected; startup and preference-dialog regressions cover both choices (#6266). | +| 2026-10-22 | Print paper sizes: はがき (100 × 148 mm), 往復はがき (148 × 200), JIS B5 (182 × 257), JIS B4 (257 × 364), A6, L判 (89 × 127), 2L判 (127 × 178), KG判 (102 × 152), 六切 (203 × 254) and 四切 (254 × 305) are selectable in the Print dialog and `file.print`, matched by their customary names (`はがき`, `L判`, `JIS B5`…), and the PDF page takes their exact size. Existing papers unchanged. | | 2026-10-17 | Object Finder classifies background by boundary coverage, retaining large enclosed foregrounds and rejecting surrounding backdrop (#6548); learned segmentation remains open (#2788) | | 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. | | 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus | @@ -138,6 +140,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | Print: Japanese paper sizes (はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切) in the Print dialog, `file.print` and the PDF output | | 2026-10-17 | minor | Object Finder retains large enclosed foregrounds (#6548) | | 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/it/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) | | 2026-10-15 | minor | Russian catalog covers every dynamic UI label the other catalogs translate | diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index db256c2726..4542a71da9 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -45,6 +45,8 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros"] } [dev-dependencies] serde = { workspace = true } tempfile = "3" +# Reading back a saved PSD's merged-image flag (#8064). +photocraft-psd = { workspace = true } # Synthetic camera raws (#7789). photocraft-raw = { workspace = true, features = ["testgen"] } # Shell completions and man pages (examples/man-and-completions.rs, for the packages); not in diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 3f29309ad5..87c0b5599c 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -87,6 +87,12 @@ pub(crate) struct ExportArgs { /// composite/full.png; it may be omitted. Check the manifest's full_composite member. #[arg(long)] pub(crate) pcraft_full_composite: bool, + /// A layered PSD/PSB stores Photoshop's white placeholder instead of the merged image + /// (Maximize Compatibility off): a smaller file and a faster save, but readers that show only + /// the merged image see white. Bitmap, Indexed Color and Duotone documents still write the + /// real image + #[arg(long)] + pub(crate) no_maximize_compatibility: bool, } /// Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …) diff --git a/apps/photocraft-cli/src/output.rs b/apps/photocraft-cli/src/output.rs index bedab3dc78..05861d7477 100644 --- a/apps/photocraft-cli/src/output.rs +++ b/apps/photocraft-cli/src/output.rs @@ -33,6 +33,7 @@ impl From<&ExportArgs> for ExportOptions { o.encode.dds.compression = c; } o.encode.dds.mipmaps = a.dds_mipmaps; + o.psd_maximize_compatibility = !a.no_maximize_compatibility; o } } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index d7cb7b299a..a0c72c39b2 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -867,6 +867,24 @@ fn dds_converts_both_ways_with_the_compression_asked_for() { } } +/// #8064: `--no-maximize-compatibility` writes a layered PSD/PSB with Photoshop's placeholder +/// instead of the merged image, flagged in resource 1057; without it, the real image. +#[test] +fn no_maximize_compatibility_writes_the_psd_placeholder() { + let d = tmp("maximize-compat"); + let a = d.join("a.png"); + write_png(&a, 32, 16, 3); + for (args, ext, real) in + [(&[][..], "psd", true), (&["--no-maximize-compatibility"][..], "psd", false), (&["--no-maximize-compatibility"][..], "psb", false)] + { + let out = d.join(format!("a.{ext}")); + ok(bin().arg("run").arg(&a).args(["--cmd", "layer.new.layer"]).arg("--out").arg(&out).args(args)); + let psd = photocraft_psd::PsdFile::from_bytes(&std::fs::read(&out).unwrap()).unwrap(); + assert_eq!(psd.has_real_merged_data(), Some(real), "{args:?} {ext}"); + } + std::fs::remove_dir_all(d).unwrap(); +} + /// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is a /// usage error and nothing is written. #[test] diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 7d9f4f4e03..5461c4cc19 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -681,6 +681,7 @@ fn main() -> eframe::Result { #[cfg(target_os = "linux")] tablet::spawn_x11(&app.stylus.feed, display); app.services.right_button_down = tablet::right_button_service(); + app.services.pen_end = tablet::pen_end_service(); // Paths on the command line (Linux/Windows file associations, `photocraft a.psd`). app.open_paths(&files); if !unreadable_paths.is_empty() { diff --git a/apps/photocraft/src/tablet.rs b/apps/photocraft/src/tablet.rs index 224b682075..51f7b333ef 100644 --- a/apps/photocraft/src/tablet.rs +++ b/apps/photocraft/src/tablet.rs @@ -1,14 +1,14 @@ //! Pen tablet pressure, tilt, rotation and eraser end on macOS and Linux X11 (issue #79), and -//! barrel button on Windows (#5905). +//! barrel button (#5905) and eraser end (#2285) on Windows. //! //! winit 0.30 drops tablet data on both macOS and X11, so `photocraft-tablet` reads it beside winit //! (an AppKit local event monitor; XInput2 raw events on a second X connection) and this module writes //! each sample into the UI's [`StylusFeed`], where the canvas reads it exactly like the web runner's //! Pointer Events and automation's simulated pen. On Windows, winit forwards `WM_POINTER` pressure -//! as touch force, but drops `PEN_FLAG_BARREL` (`0x0001`); `photocraft-tablet` recovers the barrel -//! button through a thread-local message hook beside winit. With Windows Ink disabled for the -//! tablet, the optional WinTab mode reads pressure, tilt, rotation and the eraser end from a -//! WinTab 1.4 system context instead ([`install_wintab`]). +//! as touch force, but drops `PEN_FLAG_BARREL` (`0x0001`) and the eraser end (`PEN_FLAG_INVERTED`); +//! `photocraft-tablet` recovers them through thread-local message hooks beside winit. With Windows +//! Ink disabled for the tablet, the optional WinTab mode reads pressure, tilt, rotation and the +//! eraser end from a WinTab 1.4 system context instead ([`install_wintab`]). //! //! Wayland compositors give a pen only to clients that bind the tablet protocol //! (`zwp_tablet_v2`), which winit 0.30 doesn't (and binding it on winit's connection needs @@ -34,11 +34,15 @@ pub fn sink(feed: StylusFeed) -> impl Fn(Option) + Send + 'static { move |s| feed.set(s.map(pen_sample)) } -/// Install the Windows pointer message hook (main thread; keep the result until the event loop -/// returns). On failure this logs why: the pen barrel button is then missed. +/// Install the Windows pointer message hooks (main thread; keep the result until the event loop +/// returns). On failure this logs why: the pen barrel button and eraser end are then missed. #[cfg(target_os = "windows")] pub fn install_windows() -> Option { - photocraft_tablet::windows::Monitor::install().map_err(|e| log::warn!("{e}")).ok() + let monitor = photocraft_tablet::windows::Monitor::install().map_err(|e| log::warn!("{e}")).ok()?; + if !monitor.tracks_leave() { + log::warn!("tablet input: the WH_CALLWNDPROC hook did not install, so the pen leaving the window may be missed"); + } + Some(monitor) } /// Installs the WinTab backend on the real PhotoCraft window and returns its per-frame poll. @@ -88,6 +92,18 @@ pub fn right_button_service() -> Option { None } +/// Which end of the pen is in use (Windows): flipping the pen to its eraser end selects the +/// Eraser (#2285). Elsewhere the end arrives with the samples in the stylus feed. +#[cfg(target_os = "windows")] +pub fn pen_end_service() -> Option { + Some(Box::new(photocraft_tablet::windows::take_pen_end)) +} + +#[cfg(not(target_os = "windows"))] +pub fn pen_end_service() -> Option { + None +} + /// Install the AppKit tablet monitor (main thread, once winit created the shared application: /// from eframe's app creation, not before the event loop). Keep the result until the event loop /// returns. On failure this logs why: pens then paint like a mouse. @@ -419,4 +435,40 @@ mod tests { assert!(photocraft_ui_egui::stylus::Stylus::sync_eraser_tool(&mut app)); assert_eq!(app.ui.tool, Tool::Brush); } + + /// Windows: what the pointer hooks record reaches the Eraser switch through the service the + /// app installs (#2285). + #[cfg(target_os = "windows")] + #[test] + fn windows_eraser_end_switches_to_the_eraser_and_back() { + use photocraft_tablet::windows::{ + PEN_FLAG_ERASER, PEN_FLAG_INVERTED, WM_POINTERDOWN, WM_POINTERLEAVE, WM_POINTERUP, WM_POINTERUPDATE, handle_pointer_message, + }; + use photocraft_ui_egui::stylus::Stylus; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.services.pen_end = pen_end_service(); + app.ui.tool = Tool::Brush; + let hover = |pen_flags: u32| handle_pointer_message(WM_POINTERUPDATE, 1, move |_| Some(pen_flags)); + hover(0); + assert!(!Stylus::sync_eraser_tool(&mut app), "the tip changes nothing"); + hover(PEN_FLAG_ERASER); + assert!(!Stylus::sync_eraser_tool(&mut app), "an eraser button on the barrel is not the eraser end"); + handle_pointer_message(WM_POINTERLEAVE, 1, |_| None); + hover(PEN_FLAG_INVERTED); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Eraser); + handle_pointer_message(WM_POINTERLEAVE, 1, |_| None); + assert!(!Stylus::sync_eraser_tool(&mut app), "out of range"); + hover(0); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Brush, "the tip restores the Brush"); + // An eraser-end tap and the pen leaving, all before the next frame: the frame that + // handles the queued click still selects the Eraser. + handle_pointer_message(WM_POINTERDOWN, 1, |_| Some(PEN_FLAG_INVERTED | PEN_FLAG_ERASER)); + handle_pointer_message(WM_POINTERUP, 1, |_| None); + handle_pointer_message(WM_POINTERLEAVE, 1, |_| None); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Eraser); + assert!(!Stylus::sync_eraser_tool(&mut app), "out of range"); + } } diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs index 569ab65c03..11e862ffa6 100644 --- a/crates/affinity/src/container.rs +++ b/crates/affinity/src/container.rs @@ -296,7 +296,31 @@ impl<'a> Archive<'a> { /// Extract an entry by name: decompress, undo the byte predictor and verify the CRC. pub fn read(&mut self, name: &str) -> Result, Error> { - let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone(); + self.claim(name)?.decode() + } + + /// Extract several entries, decoding them on worker threads. The entries are charged one + /// after the other exactly as the same number of [`read`](Self::read) calls would charge + /// them, and the first error in that order is the one returned. + pub(crate) fn read_many(&mut self, names: &[&str]) -> Result>, Error> { + let mut claimed = Vec::with_capacity(names.len()); + let mut refused = None; + for name in names { + match self.claim(name) { + Ok(c) => claimed.push(c), + Err(e) => { + refused = Some(e); + break; + } + } + } + let decoded = decode_all(&claimed).into_iter().collect::, _>>()?; + refused.map_or(Ok(decoded), Err) + } + + /// Check an entry against the limits, count it as extracted and locate its stored bytes. + fn claim(&mut self, name: &str) -> Result, Error> { + let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?; let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?; if size > self.limits.max_entry { return Err(Error::Limit("archive entry too large")); @@ -315,22 +339,79 @@ impl<'a> Archive<'a> { let method = e.compression & 3; let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; let data = c.take(offset(stored_len)?)?; - let mut out = match method { - 1 => inflate(data, size)?, - 2 => unzstd(data, size)?, - _ => data.to_vec(), + Ok(Claimed { data, size, compression: e.compression, crc: e.crc }) + } +} + +/// An entry that is charged and located but not yet decoded. +struct Claimed<'a> { + data: &'a [u8], + size: usize, + compression: u8, + crc: u32, +} + +impl Claimed<'_> { + fn decode(&self) -> Result, Error> { + let mut out = match self.compression & 3 { + 1 => inflate(self.data, self.size)?, + 2 => unzstd(self.data, self.size)?, + _ => self.data.to_vec(), }; - if out.len() != size { + if out.len() != self.size { return Err(Error::Malformed("archive entry size mismatch")); } - unpredict(&mut out, e.compression)?; - if crc32fast::hash(&out) != e.crc { + unpredict(&mut out, self.compression)?; + if crc32fast::hash(&out) != self.crc { return Err(Error::Malformed("archive entry checksum mismatch")); } Ok(out) } } +/// Most threads decoding entries at once; each zstd frame may reserve its declared window. +const MAX_DECODE_THREADS: usize = 8; +/// Fewer entries than this are decoded in place: starting a thread costs more than they do. +const MIN_PARALLEL_ENTRIES: usize = 4; + +/// Decode every entry, in parallel when there are enough of them. The results are in order. +fn decode_all(jobs: &[Claimed<'_>]) -> Vec, Error>> { + static THREADS: std::sync::OnceLock = std::sync::OnceLock::new(); + // The browser build has no threads to start. + let threads = if jobs.len() < MIN_PARALLEL_ENTRIES || cfg!(target_arch = "wasm32") { + 1 + } else { + (*THREADS.get_or_init(|| std::thread::available_parallelism().map_or(1, usize::from).min(MAX_DECODE_THREADS))).min(jobs.len()) + }; + if threads <= 1 { + return jobs.iter().map(Claimed::decode).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + // The workers and this thread take the next undecoded entry until none is left. + let work = || { + let mut done = Vec::new(); + loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some(job) = jobs.get(i) else { break }; + done.push((i, job.decode())); + } + done + }; + let mut slots: Vec, Error>>> = jobs.iter().map(|_| None).collect(); + std::thread::scope(|sc| { + // A thread that cannot be started just leaves its share to the others. + let workers: Vec<_> = (1..threads).filter_map(|_| std::thread::Builder::new().spawn_scoped(sc, work).ok()).collect(); + let mut finished = vec![work()]; + finished.extend(workers.into_iter().map(|w| w.join().unwrap_or_default())); + for (i, result) in finished.into_iter().flatten() { + if let Some(slot) = slots.get_mut(i) { + *slot = Some(result); + } + } + }); + slots.into_iter().map(|r| r.unwrap_or(Err(Error::Malformed("tile decoder stopped")))).collect() +} + /// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught /// without unbounded allocation. fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs index b0a8c2daab..3749862891 100644 --- a/crates/affinity/src/raster.rs +++ b/crates/affinity/src/raster.rs @@ -2,7 +2,7 @@ //! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of //! 256 bytes × 256 rows per channel, each its own archive entry. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use crate::Error; use crate::model::{Affine, Image, Pixels, Reader}; @@ -123,35 +123,78 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi let scratch = pixels.checked_mul(channels * bps).ok_or(Error::Limit("pixel layer size"))?; r.admit_pixels(pixels.checked_mul(4).ok_or(Error::Limit("pixel layer size"))?, scratch)?; let mut planes = Vec::with_capacity(channels); - let mut cache = HashMap::new(); + let mut cache = Cache::new(); for c in 1..=channels { planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), &mut cache)?); } - let n = (w as usize) * (h as usize); - let mut rgba = vec![0u8; n * 4]; - let sample = |p: &Vec, i: usize| -> f64 { - if bps == 2 { - f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0 - } else { - f64::from(p.get(i).copied().unwrap_or(0)) / 255.0 - } - }; - for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let v: Vec = planes.iter().map(|p| sample(p, i)).collect(); - let (r2, g, b, a) = if channels == 1 { - (v[0], v[0], v[0], 1.0) - } else if channels == 5 { - let k = 1.0 - v[3]; - ((1.0 - v[0]) * k, (1.0 - v[1]) * k, (1.0 - v[2]) * k, v[4]) - } else { - (v[0], v[1], v[2], v[3]) - }; - px.copy_from_slice(&[r2, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); - } + let rgba = interleave(&planes, channels, bps, pixels); let transform = Affine([1.0, 0.0, 0.0, 1.0, f64::from(x0), f64::from(y0)]).then(world); Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform })) } +/// Quantize a unit-range sample to a byte: the one conversion every format goes through. +fn quant(v: f64) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// Interleave the decoded planes (`n` samples of `bps` bytes each) into RGBA8. +/// +/// The samples used to be widened to `f64` one pixel at a time. The tables below hold the same +/// expressions evaluated once per input value, so the bytes are identical: an 8-bit sample +/// `x / 255 * 255` rounds back to `x`, a 16-bit one goes through a 64 Ki table, and CMYK's +/// `(1 - c)(1 - k)` through a table over the 256 x 256 `(c, k)` pairs. +pub(crate) fn interleave(planes: &[Vec], channels: usize, bps: usize, n: usize) -> Vec { + let mut rgba = vec![0u8; n * 4]; + let out = rgba.as_chunks_mut::<4>().0.iter_mut(); + let p = |c: usize| planes.get(c).map_or(&[][..], Vec::as_slice); + match (channels, bps) { + (1, 1) => { + for (o, &v) in out.zip(p(0)) { + *o = [v, v, v, 255]; + } + } + (4, 1) => { + let (r, g, b, a) = (p(0), p(1), p(2), p(3)); + for ((((o, &r), &g), &b), &a) in out.zip(r).zip(g).zip(b).zip(a) { + *o = [r, g, b, a]; + } + } + (5, 1) => { + let lut = cmyk_table(); + let (c, m, y, k, a) = (p(0), p(1), p(2), p(3), p(4)); + for (((((o, &c), &m), &y), &k), &a) in out.zip(c).zip(m).zip(y).zip(k).zip(a) { + let k = usize::from(k) << 8; + *o = [lut[k | usize::from(c)], lut[k | usize::from(m)], lut[k | usize::from(y)], a]; + } + } + (_, _) => { + let lut: Vec = (0..=u16::MAX).map(|v| quant(f64::from(v) / 65535.0)).collect(); + let s16 = |c: usize| p(c).as_chunks::<2>().0.iter().map(|b| lut[usize::from(u16::from_le_bytes(*b))]); + if channels == 1 { + for (o, g) in out.zip(s16(0)) { + *o = [g, g, g, 255]; + } + } else { + for ((((o, r), g), b), a) in out.zip(s16(0)).zip(s16(1)).zip(s16(2)).zip(s16(3)) { + *o = [r, g, b, a]; + } + } + } + } + rgba +} + +/// `(1 - c)(1 - k)` quantized, indexed by `k << 8 | c`. +fn cmyk_table() -> Vec { + let mut lut = Vec::with_capacity(256 * 256); + for k in 0..=255u8 { + for c in 0..=255u8 { + lut.push(quant((1.0 - f64::from(c) / 255.0) * (1.0 - f64::from(k) / 255.0))); + } + } + lut +} + /// The original image file: entry `c/N` is a stream whose root (`Blck`) holds it as `Data`. fn original(r: &mut Reader, name: &str) -> Result, Error> { let bytes = r.archive.read(name)?; @@ -167,14 +210,24 @@ fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] { [prefix[0], prefix[1], prefix[2], b'0' + c as u8] } +/// Decoded tiles by archive entry name: a tile shared by several grid cells or channels is +/// extracted (and charged to the archive's budget) once. +type Cache<'s> = HashMap<&'s str, Vec>; + +/// A tile to copy into a plane once its entry is decoded: pixel column and row of its corner. +struct Place<'s> { + name: &'s str, + at: (usize, usize), +} + /// One channel of level 0, cropped to (x0, y0, w, h) pixels; `bps` bytes per sample. -fn plane( - r: &mut Reader, +fn plane<'s>( + r: &mut Reader<'s, '_, '_>, bitmap: ObjId, c: usize, bps: usize, (x0, y0, w, h): (u32, u32, u32, u32), - cache: &mut HashMap>, + cache: &mut Cache<'s>, ) -> Result, Error> { let s = r.s; let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0); @@ -199,6 +252,15 @@ fn plane( let mut out = vec![0u8; row * h as usize]; let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps); let (py0, py1) = (y0 as usize, (y0 + h) as usize); + let crop = (bx0, py0, bx1, py1); + // First walk the grid: flat cells are filled right away (cells never overlap, so the order + // of the copies does not matter) and the tiles that show are collected. They are extracted + // together below, on several threads, then copied. A walk that fails still extracts the + // tiles before the failing cell, as a tile-by-tile walk would have. + let mut places: Vec> = Vec::new(); + let mut wanted: Vec<&'s str> = Vec::new(); + let mut queued: HashSet<&'s str> = HashSet::new(); + let mut failure = None; for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) { let state = &if let Value::UInt(u) = state { u8::try_from(*u).unwrap_or(255) } else { 255 }; let (ty, tx) = (t / tw.max(1), t % tw.max(1)); @@ -208,30 +270,28 @@ fn plane( 4 => { let Some(at) = tiles.iter().position(|v| matches!(v, Value::Obj(Some(_)))) else { r.charge_slots(tiles.len())?; - return Err(Error::Malformed("missing pixel tile")); + failure = Some(Error::Malformed("missing pixel tile")); + break; }; r.charge_slots(at + 1)?; - let Some(Value::Obj(Some(blck))) = tiles.get(at) else { return Err(Error::Malformed("missing pixel tile")) }; + let Some(Value::Obj(Some(blck))) = tiles.get(at) else { + failure = Some(Error::Malformed("missing pixel tile")); + break; + }; let blck = *blck; tiles = tiles.get(at + 1..).unwrap_or_default(); let (ox, oy) = (tx * TILE, ty * TILE); if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 { continue; } - let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string(); - if !cache.contains_key(&name) { - let mut data = r.archive.read(&name)?; - // Older files wrap a tile in a one-field stream: header, then a 64 KiB blob. - if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") { - data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec(); - } - if data.len() != TILE_BYTES { - return Err(Error::Malformed("pixel tile size")); - } - cache.insert(name.clone(), data); + let Some(name) = s.entry(blck, b"Data") else { + failure = Some(Error::Malformed("pixel tile without data")); + break; + }; + if !cache.contains_key(name) && queued.insert(name) { + wanted.push(name); } - let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?; - copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); + places.push(Place { name, at: (ox, oy) }); continue; } 3 => { @@ -242,22 +302,50 @@ fn plane( r.warn("pixel layers drawn from an embedded image (left empty)"); None } - _ => return Err(Error::Malformed("unknown pixel tile state")), + _ => { + failure = Some(Error::Malformed("unknown pixel tile state")); + break; + } }; if let Some(v) = fill { - copy(&mut out, row, (bx0, py0, bx1, py1), (tx * TILE, ty * TILE), |_, _| v); + copy(&mut out, row, crop, (tx * TILE, ty * TILE), None, v); } } + let decoded = r.archive.read_many(&wanted); + // A tile that fails to extract is reported before the failure of the walk after it. + for (name, mut data) in wanted.into_iter().zip(decoded?) { + // Older files wrap a tile in a one-field stream: header, then a 64 KiB blob. + if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") { + data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec(); + } + if data.len() != TILE_BYTES { + return Err(Error::Malformed("pixel tile size")); + } + cache.insert(name, data); + } + if let Some(e) = failure { + return Err(e); + } + for place in &places { + let tile = cache.get(place.name).ok_or(Error::Malformed("pixel tile"))?; + copy(&mut out, row, crop, place.at, Some(tile), 0); + } Ok(out) } -/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane. -fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) { +/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane. `tile` is +/// the tile's bytes, or `None` to fill the overlap with `fill`. +pub(crate) fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), tile: Option<&[u8]>, fill: u8) { + let (xa, xb) = (ox.max(bx0), (ox + TILE).min(bx1)); + if xa >= xb { + return; + } for y in oy.max(py0)..(oy + TILE).min(py1) { - for x in ox.max(bx0)..(ox + TILE).min(bx1) { - if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) { - *b = at(x - ox, y - oy); - } + let start = (y - py0) * row + (xa - bx0); + let Some(dst) = out.get_mut(start..start + (xb - xa)) else { continue }; + match tile.and_then(|t| t.get((y - oy) * TILE + (xa - ox)..(y - oy) * TILE + (xb - ox))) { + Some(src) => dst.copy_from_slice(src), + None => dst.fill(if tile.is_some() { 0 } else { fill }), } } } diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index a8a1187da5..1afb5d29f8 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -808,6 +808,192 @@ mod spot_colours { } } +/// The raster fast paths against the code they replaced. +mod raster_identity { + use crate::raster::{copy, interleave}; + + /// Deterministic filler (xorshift). + fn bytes(n: usize, mut x: u64) -> Vec { + (0..n) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 24) as u8 + }) + .collect() + } + + /// The per-pixel `f64` conversion `decode` used before the tables. + fn reference(planes: &[Vec], channels: usize, bps: usize, n: usize) -> Vec { + let sample = |p: &Vec, i: usize| -> f64 { + if bps == 2 { + f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0 + } else { + f64::from(p.get(i).copied().unwrap_or(0)) / 255.0 + } + }; + let mut rgba = vec![0u8; n * 4]; + for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let v: Vec = planes.iter().map(|p| sample(p, i)).collect(); + let (r, g, b, a) = if channels == 1 { + (v[0], v[0], v[0], 1.0) + } else if channels == 5 { + let k = 1.0 - v[3]; + ((1.0 - v[0]) * k, (1.0 - v[1]) * k, (1.0 - v[2]) * k, v[4]) + } else { + (v[0], v[1], v[2], v[3]) + }; + px.copy_from_slice(&[r, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); + } + rgba + } + + #[test] + fn eight_bit_samples_round_trip() { + // Every byte through every position of the 4-channel and the grey path. + let ramp: Vec = (0..=255).collect(); + let planes = vec![ramp.clone(), ramp.iter().rev().copied().collect(), ramp.clone(), ramp.iter().rev().copied().collect()]; + assert_eq!(interleave(&planes, 4, 1, 256), reference(&planes, 4, 1, 256)); + assert_eq!(interleave(&planes[..1], 1, 1, 256), reference(&planes[..1], 1, 1, 256)); + } + + #[test] + fn sixteen_bit_samples_are_exhaustive() { + // All 65536 values in each channel position (rotated so the channels differ). + let all: Vec = (0..=u16::MAX).flat_map(u16::to_le_bytes).collect(); + let rot = |k: usize| -> Vec { (0..=u16::MAX).flat_map(|v| v.wrapping_add((k * 4099) as u16).to_le_bytes()).collect() }; + let planes = vec![all, rot(1), rot(2), rot(3)]; + assert_eq!(interleave(&planes, 4, 2, 65536), reference(&planes, 4, 2, 65536)); + assert_eq!(interleave(&planes[..1], 1, 2, 65536), reference(&planes[..1], 1, 2, 65536)); + } + + #[test] + fn cmyk_is_exhaustive_over_colour_and_black() { + // Every (c, k) pair in each of the c, m and y positions; alpha is arbitrary. + let n = 256 * 256; + let k: Vec = (0..n).map(|i| (i >> 8) as u8).collect(); + let c: Vec = (0..n).map(|i| i as u8).collect(); + let m: Vec = (0..n).map(|i| (i as u8).wrapping_mul(7).wrapping_add(3)).collect(); + let y: Vec = (0..n).map(|i| (i as u8).wrapping_mul(13).wrapping_add(250)).collect(); + let planes = vec![c, m, y, k, bytes(n, 9)]; + assert_eq!(interleave(&planes, 5, 1, n), reference(&planes, 5, 1, n)); + } + + #[test] + fn random_planes_match_for_every_format() { + for (channels, bps) in [(1, 1), (1, 2), (4, 1), (4, 2), (5, 1)] { + let n = 5000; + let planes: Vec> = (0..channels).map(|c| bytes(n * bps, 1 + c as u64)).collect(); + assert_eq!(interleave(&planes, channels, bps, n), reference(&planes, channels, bps, n), "{channels}x{bps}"); + } + } + + /// The per-byte closure copy `plane` used before the row copies. + fn copy_reference( + out: &mut [u8], + row: usize, + (bx0, py0, bx1, py1): (usize, usize, usize, usize), + (ox, oy): (usize, usize), + at: impl Fn(usize, usize) -> u8, + ) { + for y in oy.max(py0)..(oy + 256).min(py1) { + for x in ox.max(bx0)..(ox + 256).min(bx1) { + if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) { + *b = at(x - ox, y - oy); + } + } + } + } + + #[test] + fn tile_copy_matches_the_byte_loop_for_every_crop() { + let tile = bytes(256 * 256, 77); + // Crops that cut the tile on each side, sit inside it, and miss it. + for &(bx0, bx1, py0, py1) in + &[(0, 600, 0, 600), (10, 300, 20, 200), (100, 150, 100, 130), (256, 512, 0, 256), (0, 256, 300, 400), (255, 257, 255, 257), (300, 301, 0, 1)] + { + for &(ox, oy) in &[(0, 0), (256, 0), (0, 256), (256, 256), (512, 256)] { + let row = bx1 - bx0; + let mut old = vec![0xAAu8; row * (py1 - py0)]; + let mut new = old.clone(); + copy_reference(&mut old, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| tile[y * 256 + x]); + copy(&mut new, row, (bx0, py0, bx1, py1), (ox, oy), Some(&tile), 0); + assert_eq!(old, new, "tile {ox},{oy} crop {bx0}..{bx1} x {py0}..{py1}"); + copy_reference(&mut old, row, (bx0, py0, bx1, py1), (ox, oy), |_, _| 0xFF); + copy(&mut new, row, (bx0, py0, bx1, py1), (ox, oy), None, 0xFF); + assert_eq!(old, new, "fill {ox},{oy} crop {bx0}..{bx1} x {py0}..{py1}"); + } + } + } +} + +/// `Archive::read_many` against the same reads made one at a time. +mod read_many { + use crate::synth::{self, Method}; + use crate::{Archive, Error, Limits}; + + fn entry(i: usize) -> Vec { + (0..4096 + i * 37).map(|b| (b * 31 + i * 7) as u8).collect() + } + + fn archive(count: usize, method: Method) -> Vec { + let datas: Vec> = (0..count).map(entry).collect(); + let names: Vec = (0..count).map(|i| format!("d/{i}")).collect(); + let entries: Vec<(&str, &[u8], Method)> = names.iter().zip(&datas).map(|(n, d)| (n.as_str(), d.as_slice(), method)).collect(); + synth::container(&entries, None) + } + + #[test] + fn matches_serial_reads_and_charges_the_same() { + for method in [Method::Stored, Method::Zlib, Method::Zstd] { + for count in [1, 3, 4, 5, 40] { + let file = archive(count, method); + let names: Vec = (0..count).map(|i| format!("d/{i}")).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let mut one = Archive::open(&file, Limits::default()).unwrap(); + let serial: Vec> = names.iter().map(|n| one.read(n).unwrap()).collect(); + let mut many = Archive::open(&file, Limits::default()).unwrap(); + assert_eq!(many.read_many(&names).unwrap(), serial); + assert_eq!(many.extracted(), one.extracted()); + assert_eq!(serial[count - 1], entry(count - 1)); + } + } + } + + #[test] + fn the_limit_stops_at_the_same_entry_as_serial_reads() { + let file = archive(12, Method::Zstd); + let names: Vec = (0..12).map(|i| format!("d/{i}")).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let limits = Limits { max_total: (0..7).map(|i| entry(i).len()).sum(), ..Limits::default() }; + let mut one = Archive::open(&file, limits).unwrap(); + let failed = names.iter().position(|n| one.read(n).is_err()).unwrap(); + assert_eq!(failed, 7); + let mut many = Archive::open(&file, limits).unwrap(); + assert!(matches!(many.read_many(&names), Err(Error::Limit(_)))); + assert_eq!(many.extracted(), one.extracted()); + } + + #[test] + fn the_first_failing_entry_in_order_is_reported() { + let mut file = archive(12, Method::Stored); + // Flip a data byte of entry 2 (checksum failure); entry 9 is missing from the list. + let at = file.windows(4).position(|w| w == b"#Fil").unwrap(); + let second = at + 4 + entry(0).len(); + let third = second + 4 + entry(1).len(); + file[third + 4 + 10] ^= 0xFF; + let names: Vec = (0..12).map(|i| if i == 9 { "gone".to_string() } else { format!("d/{i}") }).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let mut a = Archive::open(&file, Limits::default()).unwrap(); + assert_eq!(a.read_many(&names).unwrap_err(), Error::Malformed("archive entry checksum mismatch")); + // Without the corrupt entry the missing one is what fails. + let intact = archive(12, Method::Stored); + let mut a = Archive::open(&intact, Limits::default()).unwrap(); + assert_eq!(a.read_many(&names).unwrap_err(), Error::Malformed("missing archive entry")); + } +} + /// Object lookup and record arrays against the structures they replaced. mod stream_storage { use crate::stream::{self, Kind, Object, Tag, Value}; diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index f740687c1a..daf7a2526a 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -976,7 +976,7 @@ impl ColorBvh { fn reserve_nodes(capacity: usize) -> Result, &'static str> { let mut nodes = Vec::new(); - nodes.try_reserve_exact(capacity).map_err(|_| "not enough memory to index selection colours")?; + nodes.try_reserve_exact(capacity).map_err(|_| "not enough memory to index selection colors")?; Ok(nodes) } @@ -1072,10 +1072,10 @@ impl ColorMatcher { let key = [norm(c[0]), norm(c[1]), norm(c[2]), norm(c[3])]; if !seen.contains(&key) { if seen.len() >= limit { - return Err("the selection contains too many distinct colours to match; select a smaller area"); + return Err("the selection contains too many distinct colors to match; select a smaller area"); } - seen.try_reserve(1).map_err(|_| "not enough memory to index selection colours")?; - opaque_or_semi.try_reserve(1).map_err(|_| "not enough memory to index selection colours")?; + seen.try_reserve(1).map_err(|_| "not enough memory to index selection colors")?; + opaque_or_semi.try_reserve(1).map_err(|_| "not enough memory to index selection colors")?; seen.insert(key); opaque_or_semi.push(c); } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 0f7540d139..2f6b7ea818 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -184,6 +184,9 @@ impl Headless { let tiff_bool = |key| photocraft_engine::file_cmds::tiff_bool_param(&p, key, "doc.save").map_err(|e| bad(e.to_string())); opts.tiff_transparency = tiff_bool("tiffTransparency")?; opts.encode.tiff_pyramid = tiff_bool("tiffPyramid")?.unwrap_or(false); + if let Some(maximize) = photocraft_engine::file_cmds::maximize_compatibility_param(&p, "doc.save").map_err(|e| bad(e.to_string()))? { + opts.psd_maximize_compatibility = maximize; + } match p.get("quality") { None | Some(Value::Null) => {} Some(v) => { diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index cecc69f376..2e9348ae38 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -303,6 +303,28 @@ fn doc_save_rejects_a_bad_quality_instead_of_ignoring_or_clamping_it() { std::fs::remove_dir_all(dir).unwrap(); } +/// #8064: `doc.save` takes `maximizeCompatibility` for a layered PSD's merged image (false: the +/// placeholder, flagged in resource 1057); anything but a boolean writes nothing. +#[test] +fn doc_save_takes_maximize_compatibility() { + let dir = std::env::temp_dir().join(format!("pc-rpc-save-maximize-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 64, "height": 32})).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); + let real_merged = |p: &std::path::Path| photocraft_psd::PsdFile::from_bytes(&std::fs::read(p).unwrap()).unwrap().has_real_merged_data(); + for (name, maximize, real) in [("default.psd", json!(null), true), ("off.psd", json!(false), false), ("on.psd", json!(true), true)] { + let path = dir.join(name); + h.handle("doc.save", json!({"path": path.to_string_lossy(), "maximizeCompatibility": maximize})).unwrap(); + assert_eq!(real_merged(&path), Some(real), "{name}"); + } + let bad = dir.join("bad.psd"); + let err = h.handle("doc.save", json!({"path": bad.to_string_lossy(), "maximizeCompatibility": 0})).unwrap_err().to_string(); + assert!(err.contains("maximizeCompatibility"), "{err}"); + assert!(!bad.exists(), "a bad value writes nothing"); + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn automation_preview_rejects_oversized_full_size_and_numeric_wraparound() { let mut h = Headless::new(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 46468e0352..2e34cf6cbe 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -113,6 +113,11 @@ pub struct ExportLayersParams { /// Encoder quality, 0..12, for the formats that take one. #[serde(default)] pub quality: Option, + /// PSD/PSB: write the real merged image (Photoshop's Maximize Compatibility); false writes + /// Photoshop's white placeholder (Bitmap, Indexed Color and Duotone documents still write the + /// real image). Unset: the engine's Preferences › File Handling decides. + #[serde(default, rename = "maximizeCompatibility")] + pub maximize_compatibility: Option, } #[derive(Debug, Default, Deserialize, JsonSchema)] @@ -214,6 +219,13 @@ pub struct SaveParams { /// The save may omit it; check the manifest's `full_composite` member. Off by default. #[serde(default, rename = "pcraftFullComposite")] pub pcraft_full_composite: Option, + /// PSD/PSB: write the real merged image (Photoshop's Maximize Compatibility). false writes + /// Photoshop's white placeholder instead: a smaller file and a faster save, but readers that + /// show only the merged image see white. Bitmap, Indexed Color and Duotone documents still + /// write the real image. Unset: the real image (in bridge mode, the app's + /// Preferences › File Handling decides). + #[serde(default, rename = "maximizeCompatibility")] + pub maximize_compatibility: Option, #[serde(default)] pub index: Option, } @@ -798,6 +810,9 @@ impl PhotocraftMcp { if let Some(v) = p.quality { opts.insert("quality".into(), json!(v)); } + if let Some(v) = p.maximize_compatibility { + opts.insert("maximizeCompatibility".into(), json!(v)); + } let opts = Value::Object(opts); // Bridge mode runs the app on this machine, which writes its own paths like any command. let mut bridge_params = opts.clone(); @@ -1186,9 +1201,10 @@ impl PhotocraftMcp { if let Some(b) = self.bridge_client() { // The bridge forwards to the running app's `app.save`, which takes only an optional // path (without one it writes back to the document's own layered file, as headless - // does), the Targa bits, the DDS options and the TIFF compression, transparency and - // pyramid, so the other options are headless-only. Saying so beats saving with - // defaults while the caller believes their quality or format was applied. + // does), the Targa bits, the DDS options, the TIFF compression, transparency and + // pyramid, and Maximize Compatibility, so the other options are headless-only. Saying + // so beats saving with defaults while the caller believes their quality or format was + // applied. let unsupported: Vec<&str> = [ p.format.is_some().then_some("format"), p.quality.is_some().then_some("quality"), @@ -1226,6 +1242,9 @@ impl PhotocraftMcp { if p.tiff_pyramid { params["tiffPyramid"] = json!(true); } + if let Some(maximize) = p.maximize_compatibility { + params["maximizeCompatibility"] = json!(maximize); + } return to_result(b.call("app.save", params).await); } let Some(r) = self @@ -1243,6 +1262,9 @@ impl PhotocraftMcp { } opts.encode.tiff_pyramid = p.tiff_pyramid; opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps }; + if let Some(maximize) = p.maximize_compatibility { + opts.psd_maximize_compatibility = maximize; + } if let Some(q) = p.quality { opts.encode.jpeg_quality = q; opts.encode.webp_quality = q; diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index b2746303b8..7b4ce8aae3 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -513,6 +513,70 @@ async fn headless_doc_save_writes_tiff_options() { cleanup(&dir); } +/// #8064: headless `doc_save`/`doc_export` take `maximizeCompatibility` for a layered PSD/PSB's +/// merged image: false writes Photoshop's placeholder and says so in resource 1057; unset, the +/// real image. A value that isn't a boolean is refused before anything is written. +#[tokio::test(flavor = "multi_thread")] +async fn headless_doc_save_takes_maximize_compatibility() { + let dir = tmp("maximize-compat"); + let client = connect(headless_in(&dir)).await; + call(&client, "doc_new", json!({"width": 64, "height": 32, "background": "white"})).await; + let r = call(&client, "command_run", json!({"id": "layer.new.layer", "params": {}})).await; + assert_ne!(r.is_error, Some(true), "{}", text(&r)); + for (tool, params, real) in [ + ("doc_export", json!({"path": "default.psd"}), true), + ("doc_export", json!({"path": "off.psd", "maximizeCompatibility": false}), false), + ("doc_save", json!({"path": "off.psb", "maximizeCompatibility": false}), false), + ("doc_save", json!({"path": "on.psd", "maximizeCompatibility": true}), true), + ] { + let r = call(&client, tool, params.clone()).await; + assert_ne!(r.is_error, Some(true), "{params}: {}", text(&r)); + let bytes = std::fs::read(dir.join(params["path"].as_str().unwrap())).unwrap(); + assert_eq!(photocraft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); + } + let r = call(&client, "doc_export", json!({"path": "bad.psd", "maximizeCompatibility": "no"})).await; + assert_eq!(r.is_error, Some(true), "{}", text(&r)); + assert!(!dir.join("bad.psd").exists()); + client.cancel().await.unwrap(); + cleanup(&dir); +} + +/// #8064: `doc_export_layers` takes `maximizeCompatibility` too, for PSD/PSB layer files. +#[tokio::test(flavor = "multi_thread")] +async fn headless_doc_export_layers_takes_maximize_compatibility() { + let dir = tmp("export-layers-maximize-compat"); + let client = connect(headless_in(&dir)).await; + call(&client, "doc_new", json!({"width": 16, "height": 16, "background": "white", "name": "card"})).await; + for (sub, params, real) in + [("on", json!({"dir": "on", "format": "psd"}), true), ("off", json!({"dir": "off", "format": "psd", "maximizeCompatibility": false}), false)] + { + let result = json_of(&call(&client, "doc_export_layers", params.clone()).await); + assert_eq!(result["count"], 1, "{params}: {result}"); + let file = result["files"][0].as_str().unwrap(); + assert!(file.starts_with(sub), "{file}"); + let bytes = std::fs::read(dir.join(file)).unwrap(); + assert_eq!(photocraft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); + } + let r = call(&client, "doc_export_layers", json!({"dir": "bad", "format": "psd", "maximizeCompatibility": "no"})).await; + assert_eq!(r.is_error, Some(true), "{}", text(&r)); + client.cancel().await.unwrap(); + cleanup(&dir); +} + +/// #8064: `maximizeCompatibility` reaches the app's `app.save` through the bridge; unset, nothing +/// is sent and the app's preference decides. +#[tokio::test(flavor = "multi_thread")] +async fn bridge_doc_save_forwards_maximize_compatibility() { + let (addr, app) = fake_app().await; + let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await; + let saved = json_of(&call(&client, "doc_save", json!({"path": "out.psd", "maximizeCompatibility": false})).await); + assert_eq!(saved, json!({"saved": {"path": "out.psd", "maximizeCompatibility": false}})); + let saved = json_of(&call(&client, "doc_save", json!({"path": "out.psd"})).await); + assert_eq!(saved, json!({"saved": {"path": "out.psd"}})); + client.cancel().await.unwrap(); + app.abort(); +} + #[tokio::test(flavor = "multi_thread")] async fn bridge_response_budget_drops_connection_without_retrying_the_operation() { use photocraft_automation::{BridgeClient, budgets::MAX_RESPONSE_BYTES}; diff --git a/crates/cms/src/pipeline.rs b/crates/cms/src/pipeline.rs index 1c095756ea..7fad1a107b 100644 --- a/crates/cms/src/pipeline.rs +++ b/crates/cms/src/pipeline.rs @@ -183,6 +183,17 @@ impl Pipeline { out[..self.outputs].copy_from_slice(&v[..self.outputs]); } + /// Evaluates the stages after the first one on values already passed through it. + #[inline] + pub(crate) fn eval_after_first(&self, v: &mut [f32; MAX], out: &mut [f32]) { + let mut n = self.inputs; + for s in self.stages.iter().skip(1) { + n = s.run(v, n); + } + let _ = n; + out[..self.outputs].copy_from_slice(&v[..self.outputs]); + } + /// Removes no-op stages and cancels adjacent inverse pairs (Lab↔XYZ, encode/decode). pub fn optimize(&mut self) { let mut out: Vec = Vec::with_capacity(self.stages.len()); diff --git a/crates/cms/src/transform.rs b/crates/cms/src/transform.rs index 5cd6c65c57..0c8b5fa4a9 100644 --- a/crates/cms/src/transform.rs +++ b/crates/cms/src/transform.rs @@ -42,6 +42,8 @@ pub const GRID_4D: usize = 17; const TABLE_1D: usize = GpuMatrixShaper::INPUT_INTERVALS; /// Resolution of output shaper tables (indexed by `x^(1/4)`). const OUT_TABLE: usize = GpuMatrixShaper::OUTPUT_ENTRIES; +// The blocked matrix/TRC path wraps table indices with a mask instead of a bounds check. +const _: () = assert!(OUT_TABLE.is_power_of_two()); /// ICC v4 perceptual reference medium black (ICC.1:2010 §6.3.4.4), XYZ. const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287]; @@ -91,6 +93,8 @@ pub struct Transform { post: Option, /// Pre-located grid coordinates per 8-bit code: (offset contribution, fraction) per input. grid8: Vec<[(u32, f32); 256]>, + /// For an exact core: the first stage's curves at every 8-bit code. + exact8: Vec<[f32; 256]>, } impl Transform { @@ -178,7 +182,13 @@ impl Transform { .collect(), _ => Vec::new(), }; - Transform { inputs, outputs, opts, pipeline, core, post, grid8 } + let exact8 = match (&core, pipeline.stages.first()) { + (Core::Exact, Some(Stage::Curves(cs))) if cs.len() == inputs && inputs <= 4 => { + cs.iter().map(|c| std::array::from_fn(|i| c.eval(i as f32 / 255.0))).collect() + } + _ => Vec::new(), + }; + Transform { inputs, outputs, opts, pipeline, core, post, grid8, exact8 } } /// White preservation: the device-link node at the source's device white gets exactly the @@ -386,6 +396,10 @@ impl Transform { } } } + Core::Shaper { curves8, matrix: Some((3, 3, m, off)), .. } if self.shaper3_ok(curves8.len(), m.len(), off.len()) => { + let load = |sp: &[u8]| [curves8[0][sp[0] as usize], curves8[1][sp[1] as usize], curves8[2][sp[2] as usize]]; + self.shaper3_blocks(s, ss, d, ds, extra, m, off, load, q); + } Core::Shaper { curves8, matrix, .. } => { let mut v = [0.0f32; 16]; for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) { @@ -402,6 +416,21 @@ impl Transform { } } } + Core::Exact if !self.exact8.is_empty() => { + for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) { + let mut v = [0.0f32; 16]; + for k in 0..self.inputs { + v[k] = self.exact8[k][sp[k] as usize]; + } + self.pipeline.eval_after_first(&mut v, &mut out); + for k in 0..self.outputs { + dp[k] = q(out[k]); + } + for e in 0..extra { + dp[self.outputs + e] = sp[self.inputs + e]; + } + } + } _ => { let mut inp = [0.0f32; 16]; for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) { @@ -420,6 +449,74 @@ impl Transform { } } + fn shaper3_ok(&self, curves: usize, m: usize, off: usize) -> bool { + self.inputs == 3 + && self.outputs == 3 + && curves == 3 + && m == 9 + && off == 3 + && self.post.as_ref().is_some_and(|p| p.tables.len() == 3 && p.tables.iter().all(|t| t.len() == OUT_TABLE)) + } + + /// Matrix/TRC transform of whole pixels in blocks: the matrix and the output-table index + /// maths run over a block of pixels at a time (same operations, same order, per pixel). + #[allow(clippy::too_many_arguments)] + fn shaper3_blocks( + &self, + s: &[S], + ss: usize, + d: &mut [S], + ds: usize, + extra: usize, + m: &[f32], + off: &[f32], + load: impl Fn(&[S]) -> [f32; 3], + store: impl Fn(f32) -> S, + ) { + const B: usize = 64; + let Some(post) = self.post.as_ref() else { return }; + let tabs = [&post.tables[0][..OUT_TABLE], &post.tables[1][..OUT_TABLE], &post.tables[2][..OUT_TABLE]]; + let m: [f32; 9] = std::array::from_fn(|i| m[i]); + let off: [f32; 3] = std::array::from_fn(|i| off[i]); + let n_px = (s.len() / ss).min(d.len() / ds); + let mut x = [[0.0f32; B]; 3]; + let mut start = 0; + while start < n_px { + let n = B.min(n_px - start); + let sb = &s[start * ss..(start + n) * ss]; + let db = &mut d[start * ds..(start + n) * ds]; + for (j, sp) in sb.chunks_exact(ss).enumerate() { + let [a, b, c] = load(sp); + for r in 0..3 { + let mut acc = off[r]; + acc += m[r * 3] * a; + acc += m[r * 3 + 1] * b; + acc += m[r * 3 + 2] * c; + x[r][j] = acc; + } + } + for (ch, t) in tabs.iter().enumerate() { + let mut u = [0.0f32; B]; + let mut ix = [0i32; B]; + for j in 0..B { + let v = x[ch][j].clamp(0.0, 1.0).sqrt().sqrt() * (OUT_TABLE - 1) as f32; + let i = (v as i32).min(OUT_TABLE as i32 - 2); + ix[j] = i; + u[j] = v - i as f32; + } + for (j, dp) in db.chunks_exact_mut(ds).enumerate() { + let i = ix[j] as usize & (OUT_TABLE - 1); + let (v0, v1) = (t[i], t[(i + 1) & (OUT_TABLE - 1)]); + dp[ch] = store(v0 + (v1 - v0) * u[j]); + } + } + for (sp, dp) in sb.chunks_exact(ss).zip(db.chunks_exact_mut(ds)) { + dp[3..3 + extra].copy_from_slice(&sp[3..3 + extra]); + } + start += n; + } + } + /// Converts 16-bit pixels (see [`Transform::convert_f32`] for the layout). pub fn convert_u16(&self, src: &[u16], src_stride: usize, dst: &mut [u16], dst_stride: usize, copy_extra: bool) { self.check(src_stride, dst_stride); @@ -428,6 +525,13 @@ impl Transform { } fn run_u16(&self, s: &[u16], ss: usize, d: &mut [u16], ds: usize, extra: usize) { + if let Core::Shaper { curves, matrix: Some((3, 3, m, off)), .. } = &self.core + && self.shaper3_ok(curves.len(), m.len(), off.len()) + { + let load = + |sp: &[u16]| [table(&curves[0], sp[0] as f32 / 65535.0), table(&curves[1], sp[1] as f32 / 65535.0), table(&curves[2], sp[2] as f32 / 65535.0)]; + return self.shaper3_blocks(s, ss, d, ds, extra, m, off, load, |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16); + } let mut inp = [0.0f32; 16]; let mut out = [0.0f32; 16]; for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) { diff --git a/crates/cms/tests/it/cms.rs b/crates/cms/tests/it/cms.rs index f390a390da..12a451bcad 100644 --- a/crates/cms/tests/it/cms.rs +++ b/crates/cms/tests/it/cms.rs @@ -819,3 +819,93 @@ fn device_links_parse_and_are_reported_unsupported() { // The output space still bounds the tag: a CMYK→CMYK link with a 4→3 table is malformed. assert!(matches!(Profile::parse(&device_link(b"CMYK", b"CMYK", 4, 3)), Err(photocraft_cms::CmsError::Invalid(_)))); } + +/// The blocked matrix/TRC path (64 pixels at a time) must match the per-pixel evaluation for +/// every pixel count around the block size, with and without extra channels. +#[test] +fn matrix_trc_blocks_match_per_pixel_eval() { + let pairs = [(Builtin::Srgb, Builtin::DisplayP3), (Builtin::ProPhotoCompat, Builtin::Srgb), (Builtin::AdobeRgbCompat, Builtin::Rec2020)]; + for (a, b) in pairs { + let t = Transform::new(a.profile(), b.profile(), Intent::RelativeColorimetric, true).unwrap(); + for &(ss, ds, copy) in &[(3usize, 3usize, false), (4, 4, true), (5, 4, true)] { + let max = 20011; + let seed = |i: usize| (i.wrapping_mul(2654435761) >> 7) as u32; + let src16: Vec = (0..max * ss).map(|i| (seed(i) >> 3) as u16).collect(); + let src8: Vec = (0..max * ss).map(|i| (seed(i) >> 11) as u8).collect(); + let mut full8 = vec![0u8; max * ds]; + t.convert_u8(&src8, ss, &mut full8, ds, copy); + for px in [1usize, 2, 63, 64, 65, 127, 128, 129, 1000] { + let mut o16 = vec![0u16; px * ds]; + t.convert_u16(&src16[..px * ss], ss, &mut o16, ds, copy); + let mut o8 = vec![0u8; px * ds]; + t.convert_u8(&src8[..px * ss], ss, &mut o8, ds, copy); + assert_eq!(o8[..], full8[..px * ds], "u8 prefix of a longer buffer, {px} px"); + for p in 0..px { + let inp: Vec = (0..3).map(|k| src16[p * ss + k] as f32 / 65535.0).collect(); + let mut want = [0.0f32; 3]; + t.eval_fast(&inp, &mut want); + for k in 0..3 { + assert_eq!(o16[p * ds + k], (want[k].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16, "u16 px {p} ch {k} of {px}"); + } + if copy && ds > 3 { + assert_eq!(o16[p * ds + 3], src16[p * ss + 3]); + assert_eq!(o8[p * ds + 3], src8[p * ss + 3]); + } + } + } + } + } +} + +/// 8-bit and 16-bit conversion through an analytic pipeline (no lookup table, here RGB to Lab) +/// must equal the exact per-pixel evaluation. The 8-bit path tabulates the first stage's +/// curves per code; `curves_are_tables` selects whether those curves are parametric (their +/// `eval` is analytic) or `curv` tables (their `eval` interpolates inside the same loop). +fn check_exact_core(src_profile: &Profile, curves_are_tables: bool) { + let trc = src_profile.trc.as_ref().expect("matrix/TRC source"); + assert!(trc.iter().all(|c| matches!(c, photocraft_cms::Curve::Table(_)) == curves_are_tables), "TRC kind"); + let t = Transform::new(src_profile, lab(), Intent::RelativeColorimetric, true).unwrap(); + let px = 256usize * 256; + let src: Vec = (0..px as u32).flat_map(|i| [(i & 255) as u8, (i >> 8) as u8, (i.wrapping_mul(2654435761) >> 13) as u8, 200]).collect(); + let mut out = vec![0u8; px * 4]; + t.convert_u8(&src, 4, &mut out, 4, true); + for (sp, dp) in src.as_chunks::<4>().0.iter().zip(out.as_chunks::<4>().0) { + let inp = [sp[0] as f32 / 255.0, sp[1] as f32 / 255.0, sp[2] as f32 / 255.0]; + let mut want = [0.0f32; 3]; + t.eval(&inp, &mut want); + for k in 0..3 { + assert_eq!(dp[k], (want[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8, "u8 {sp:?} ch {k}"); + } + assert_eq!(dp[3], 200); + } + // 16-bit input stays off the 8-bit table and must agree with the untabulated evaluation. + let src16: Vec = (0..px * 4).map(|i| if i % 4 == 3 { 51400 } else { (i.wrapping_mul(2654435761) >> 9) as u16 }).collect(); + let mut out16 = vec![0u16; px * 4]; + t.convert_u16(&src16, 4, &mut out16, 4, true); + for (sp, dp) in src16.as_chunks::<4>().0.iter().zip(out16.as_chunks::<4>().0) { + let inp = [sp[0] as f32 / 65535.0, sp[1] as f32 / 65535.0, sp[2] as f32 / 65535.0]; + let mut want = [0.0f32; 3]; + t.eval(&inp, &mut want); + for k in 0..3 { + assert_eq!(dp[k], (want[k].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16, "u16 {sp:?} ch {k}"); + } + assert_eq!(dp[3], 51400); + } +} + +#[test] +fn exact_core_u8_matches_exact_eval() { + check_exact_core(srgb(), false); +} + +/// Same, with `curv` table TRCs: the first-stage table is built from `Curve::eval`'s table +/// branch and must still be applied to its own channel. +#[test] +fn exact_core_u8_matches_exact_eval_with_table_trc() { + // Distinct tables per channel, so a first stage applied to the wrong channel shows up. + let mut p = srgb_as_v2_tables(); + let table = |g: f64| photocraft_cms::Curve::Table((0..1024).map(|i| ((i as f64 / 1023.0).powf(g) * 65535.0).round() as f32 / 65535.0).collect()); + p.trc = Some([table(1.8), table(2.2), table(2.6)]); + let table_trc = Profile::parse(&p.with_encoded_bytes().to_bytes()).unwrap(); + check_exact_core(&table_trc, true); +} diff --git a/crates/engine/src/actions_record.rs b/crates/engine/src/actions_record.rs index 4bfb54befa..1076950e28 100644 --- a/crates/engine/src/actions_record.rs +++ b/crates/engine/src/actions_record.rs @@ -9,6 +9,8 @@ //! - any other `layer` id becomes the layer's name when the name is unique in the document, and //! `layer.select` always does (selecting is choosing a layer by name, as Photoshop records //! it); an ambiguous name keeps the id, which still replays on the recording document; +//! - a mask drop's destination (`layer.layerMask.moveTo`'s `to`) becomes the layer's name, with +//! `toOccurrence` when several layers share it; //! - the Type tool's keystrokes fold into the `type.create` that made the layer. On an existing //! layer, each replacement stays separate so replay keeps style runs between edited spans. //! @@ -69,6 +71,9 @@ pub(crate) fn portable(s: &Session, id: &str, mut params: Value, before: &Before object.insert("yPercent".into(), serde_json::json!(y_percent)); } } + if id == "layer.layerMask.moveTo" { + portable_mask_destination(doc, &mut params); + } let Some(target) = params.get("layer").and_then(Value::as_u64).map(LayerId) else { return params }; let Some(obj) = params.as_object_mut() else { return params }; let only_selected = before.selected.len() <= 1; @@ -85,6 +90,22 @@ pub(crate) fn portable(s: &Session, id: &str, mut params: Value, before: &Before params } +/// A mask drop's `to` id becomes the layer's name, and `toOccurrence` which of several layers of +/// that name it is, in document order. Moving a mask leaves the stack as it is, so the count means +/// the same layer when the step replays. It is taken from the document before the step: dropping +/// on the Background renames it "Layer 0". +fn portable_mask_destination(doc: &Document, params: &mut Value) { + let Some(to) = params.get("to").and_then(Value::as_u64).map(LayerId) else { return }; + let Some(layer) = doc.layer(to) else { return }; + let matches: Vec<_> = doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).map(|(_, _, l)| l.id).collect(); + let Some(occurrence) = matches.iter().position(|id| *id == to) else { return }; + let Some(fields) = params.as_object_mut() else { return }; + fields.insert("to".into(), Value::String(layer.name.clone())); + if matches.len() > 1 { + fields.insert("toOccurrence".into(), occurrence.into()); + } +} + /// The text layer a journaled `type.create` made or `type.edit` changed, so the keystrokes that /// follow fold into that entry only when they type into the same layer (the Type tool selects /// a clicked layer without a command, so the journal alone cannot tell). diff --git a/crates/engine/src/brush_pressure_size_default_tests.rs b/crates/engine/src/brush_pressure_size_default_tests.rs new file mode 100644 index 0000000000..c09fe26313 --- /dev/null +++ b/crates/engine/src/brush_pressure_size_default_tests.rs @@ -0,0 +1,87 @@ +//! Pressure for Size starts off (#11809). The reference application leaves both pressure toggles +//! in the options bar unhighlighted after Reset Tool, so a fresh brush has neither on — and the +//! brush Reset Tool hands back is `BrushSettings::default()` plus smoothing +//! (`crates/ui-egui/src/canvas/paint_mouse.rs::fresh_brush`), so the default is what the tool +//! reset reports through `brush.get`. The options bar's two `circle-dot` buttons are drawn from +//! these same two fields (`crates/ui-egui/src/panels/options_bar.rs`), so off here means drawn +//! off there. + +use crate::Session; +use photocraft_paint::brush::BrushSettings; +use serde_json::{Value, json}; + +/// The brush a fresh session starts with: neither pressure toggle on. +#[test] +fn the_default_brush_has_neither_pressure_toggle_on() { + let b = BrushSettings::default(); + assert!(!b.pressure_size, "Pressure for Size is off by default, as the reference leaves it after Reset Tool (#11809)"); + assert!(!b.pressure_opacity, "Pressure for Opacity stays off"); +} + +/// What `brush.get` answers on a fresh session, which is what the options bar reads to draw the +/// two toggles. +#[test] +fn brush_get_reports_both_pressure_toggles_off() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let got = s.execute("brush.get", json!({})).unwrap(); + assert_eq!(got["pressureSize"], json!(false), "brush.get reports Pressure for Size off (#11809)"); + assert_eq!(got["pressureOpacity"], json!(false), "brush.get reports Pressure for Opacity off"); + // The session's own starting brush is the default brush at Photoshop's 10 % smoothing — the + // same brush Reset Tool hands back — so only the smoothing differs. + assert_eq!( + s.tools.brush, + BrushSettings { smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, ..BrushSettings::default() } + ); +} + +/// A brush that does not name the field — a preset saved before #11809, an older recorded +/// command — takes the off default rather than the old on one. +#[test] +fn a_brush_that_omits_the_field_takes_the_off_default() { + let b: BrushSettings = serde_json::from_value(json!({"size": 30.0, "hardness": 1.0})).unwrap(); + assert!(!b.pressure_size, "an omitted pressureSize reads as off (#11809)"); + assert!(!b.pressure_opacity, "an omitted pressureOpacity reads as off"); + assert_eq!(b.size, 30.0, "the fields that are there still apply"); +} + +/// Switching it on still works: `tools.setBrush` writes the field `brush.get` reads back, and the +/// same field the options-bar button is drawn from. +#[test] +fn pressure_for_size_still_switches_on_and_off() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); + assert!(s.tools.brush.pressure_size, "the toggle still turns on"); + assert_eq!(s.execute("brush.get", json!({})).unwrap()["pressureSize"], json!(true)); + s.execute("tools.setBrush", json!({"brush": {"pressureSize": false}})).unwrap(); + assert!(!s.tools.brush.pressure_size, "and off again"); + assert!(!s.tools.brush.pressure_opacity, "it never touches Pressure for Opacity"); +} + +/// One stroke of a pressure ramp (0.3 → 0.65 → 1.0) across a new empty layer with `brush`: the +/// layer's pixels and what the stroke covers. +fn ramp(brush: Value) -> (Vec, photocraft_geom::Rect) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 80, "height": 40})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("paint.stroke", json!({"points": [[20.0, 20.0, 0.3], [40.0, 20.0, 0.65], [60.0, 20.0, 1.0]], "size": 24.0, "color": "#ff0000", "brush": brush})) + .unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (surf.read_region(st.doc.bounds()), surf.content_bounds()) +} + +/// Done when 2: a pen stroke with varying pressure and the default brush keeps a constant size, +/// so it paints exactly what the same stroke with Pressure for Size turned off does — and +/// something else with it turned on, which is what makes this say anything. +#[test] +fn a_default_brush_stroke_keeps_its_size_under_a_pressure_ramp() { + let (off, off_box) = ramp(json!({"spacing": 0.25, "pressureSize": false})); + let (on, on_box) = ramp(json!({"spacing": 0.25, "pressureSize": true})); + let (dflt, dflt_box) = ramp(json!({"spacing": 0.25})); + assert_ne!(on, off, "the ramp alone does not change the stroke: Pressure for Size has to"); + assert_eq!(dflt, off, "the default brush paints like Pressure for Size off (#11809)"); + assert_eq!(dflt_box, off_box, "and reaches as far under the whole ramp"); + assert_ne!(dflt_box, on_box, "the turned-on brush still tapers the stroke's ends"); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4c911e6be0..c4addf4c22 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -67,6 +67,8 @@ pub mod color_cmds; pub mod color_to_alpha_cmds; pub mod comps_cmds; pub mod contour_lib_cmds; +#[cfg(test)] +mod count_delete_group_tests; pub mod cutout_cmds; pub mod distort_cmds; pub mod document_preset_cmds; @@ -169,7 +171,7 @@ use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_layer, has_pixel pub use layer_params::blend_from_str; pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; pub(crate) use layer_references::{recorded_drop, recorded_layer}; -use ops::{arrange, merge_group, set_mask, set_mask_and_deselect}; +use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect}; pub(crate) use ops::{layer_copy, translate_layer}; use params::{bad, set_clipped}; pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; @@ -807,6 +809,15 @@ fn build() -> Vec { "Delete Layer Mask", None )), + cmd!( + "layer.layerMask.moveTo", + "Move Layer Mask", + [], + None, + r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, + has_layer, + move_mask + ), cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { let id = layer_param(s, p)?; s.edit("Merge Down", |doc, active| { diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index 08d5a178d7..6a18a871f1 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -600,6 +600,84 @@ fn recorded_layer_selection_replays_by_name_on_another_document() { /// #7845: dragging a layer in the Layers panel while recording keeps the drop target by name, /// so the action plays on another document (whose layer ids differ) instead of failing with /// "no such layer". The reporter's steps, replayed on a new document. +/// #10485: a mask thumbnail dropped on another layer while recording keeps its destination by +/// name, so the action moves the mask to the same layer in another document (whose ids differ) +/// rather than to whichever layer has the recorded id there. +#[test] +fn recorded_mask_drop_replays_on_another_document() { + let masked = |s: &mut Session, name: &str| { + let id = s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 1, "width": 4, "height": 4})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + id + }; + let has_mask = |s: &Session, name: &str| s.active().unwrap().doc.walk().iter().any(|(_, _, l)| l.name == name && l.mask.is_some()); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let photo = masked(&mut s, "Photo"); + let shadow = s.execute("layer.new.layer", json!({"name": "Shadow"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("actions.record", json!({"name": "Mask to shadow"})).unwrap(); + s.execute("layer.layerMask.moveTo", json!({"layer": photo, "to": shadow, "copy": false})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"layer": "Photo", "to": "Shadow", "copy": false})); + // Another document: an extra layer between them, so the recorded id is a different layer. + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + masked(&mut replay, "Photo"); + replay.execute("layer.new.layer", json!({"name": "Extra"})).unwrap(); + replay.execute("layer.new.layer", json!({"name": "Shadow"})).unwrap(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(has_mask(&replay, "Shadow"), "the mask went to Shadow"); + assert!(!has_mask(&replay, "Photo") && !has_mask(&replay, "Extra"), "and nowhere else"); +} + +/// A mask dropped on one of several same-named layers records which of them it is, so replay +/// picks the same one (not the topmost of that name), and an explicit name needs the occurrence. +#[test] +fn recorded_mask_drop_onto_a_duplicate_name_replays_on_the_same_layer() { + let build = |s: &mut Session, extra: bool| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + if extra { + s.execute("layer.new.layer", json!({"name": "Extra"})).unwrap(); + } + let photo = s.execute("layer.new.layer", json!({"name": "Photo"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 1, "width": 4, "height": 4})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + let lower = s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap(); + let upper = s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap(); + (photo, lower, upper) + }; + let mask_on = |s: &Session, id: u64| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().mask.is_some(); + let mut s = Session::new(); + let (photo, lower, upper) = build(&mut s, false); + s.execute("actions.record", json!({"name": "Copy mask"})).unwrap(); + s.execute("layer.layerMask.moveTo", json!({"layer": photo, "to": lower, "copy": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"layer": "Photo", "to": "Twin", "toOccurrence": 0, "copy": true})); + assert!(mask_on(&s, lower) && !mask_on(&s, upper)); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let (photo2, lower2, upper2) = build(&mut replay, true); + assert_ne!((photo, lower, upper), (photo2, lower2, upper2), "the ids differ"); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(mask_on(&replay, photo2), "a copy: the original stays"); + assert!(mask_on(&replay, lower2), "the copy went to the lower Twin"); + assert!(!mask_on(&replay, upper2), "not to the upper one"); + // Explicit calls: a name shared by several layers needs `toOccurrence`; ids still work. + let err = replay.execute("layer.layerMask.moveTo", json!({"layer": photo2, "to": "Twin", "copy": true})).unwrap_err().to_string(); + assert!(err.contains("toOccurrence"), "{err}"); + replay.execute("layer.layerMask.moveTo", json!({"layer": photo2, "to": "Twin", "toOccurrence": 1, "copy": true})).unwrap(); + assert!(mask_on(&replay, upper2), "occurrence 1 is the upper Twin"); + replay.execute("layer.layerMask.delete", json!({"layer": upper2})).unwrap(); + replay.execute("layer.layerMask.moveTo", json!({"layer": photo2, "to": upper2})).unwrap(); + assert!(mask_on(&replay, upper2) && !mask_on(&replay, photo2), "a numeric id still names the layer"); +} + #[test] fn recorded_layer_drag_replays_on_another_document() { for depth in [8, 16, 32] { diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 7f31b8d226..ea3e327832 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -434,6 +434,33 @@ fn replace_color(s: &mut Session, p: &Value) -> Result { // Localized Color Clusters, as in Select › Color Range: the colour only matches within Range // (a percentage of the canvas's longer side) of where it was picked. let points = sample_points(p).map_err(|m| bad(CMD, m))?; + // Several samples (Add to Sample / Subtract from Sample, #6280): the colours match as + // Select › Color Range's do for the same clicks, through its own matcher. + // A malformed `subtractPoints` is refused here, as malformed `points` are, rather than read as + // no subtraction by the single-colour path. + let subtracted = match p.get("subtractPoints") { + None => false, + Some(v) => !v.as_array().ok_or_else(|| bad(CMD, "`subtractPoints` must be [[x, y], …]"))?.is_empty(), + }; + if subtracted || points.len() > 1 { + let mut q = json!({"points": p.get("points").cloned().unwrap_or(Value::Array(Vec::new())), "fuzziness": fuzz}); + // With no Add samples, the subtraction starts from the dialog's From colour, not the + // foreground; with them, the samples alone span the range, as in Color Range. + // Forwarded as resolved (a `null` or missing colour is the foreground), as RGB 0..1. + if points.is_empty() { + q["color"] = json!([c[0], c[1], c[2]]); + } + for key in ["subtractPoints", "order", "localized", "range"] { + if let Some(v) = p.get(key) { + q[key] = v.clone(); + } + } + let samples = crate::selection_cmds::ColorRangeSamples::new(s, &q).map_err(|e| bad(CMD, e.to_string()))?; + return rgba_edit(s, "Replace Color", p, |px, r| { + let mask = samples.coverage(px, r.width() as usize, 1.0, [r.x0 as f32, r.y0 as f32]); + tone::replace_color_masked(px, &mask, h, sat, l); + }); + } let localized = if p.get("localized").and_then(Value::as_bool).unwrap_or(false) { if points.is_empty() { return Err(bad(CMD, "localized clusters need eyedropper `points` (where the colour was picked)")); @@ -587,7 +614,7 @@ pub fn specs() -> Vec { "image.adjustments.replaceColor", "Replace Color…", ["Image", "Adjustments"], - r##"{"localized":bool=false,"color":color,"fuzziness":0..200=40,"range":0..100=100,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"points":[[x,y],…]?,"labMinimum":[L,a,b]?,"labMaximum":[L,a,b]?} (Lab bounds: a finite ordered D50 box, mutually exclusive with color/points/localized/range; composite pixel-layer target only. Otherwise color defaults to the foreground; localized points use range % of the longer side.)"##, + r##"{"localized":bool=false,"color":color,"fuzziness":0..200=40,"range":0..100=100,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"points":[[x,y],…]?,"subtractPoints":[[x,y],…]?,"order":["+"|"-",…]?,"labMinimum":[L,a,b]?,"labMaximum":[L,a,b]?} (Lab bounds: a finite ordered D50 box, mutually exclusive with color/points/subtractPoints/order/localized/range; composite pixel-layer target only. Otherwise color ("#rrggbb") defaults to the foreground; localized points use range % of the longer side; several "points" (Add to Sample) or any "subtractPoints" (Subtract from Sample) match as select.colorRange does for the same samples, "order" the click order.)"##, has_pixels, replace_color ), diff --git a/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs b/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs index 574610523c..9ee5371ac0 100644 --- a/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs +++ b/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs @@ -242,4 +242,20 @@ mod tests { assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.past_len(), history); } + + /// Add to Sample / Subtract from Sample (#6280) are RGB samples: with Lab bounds they are + /// refused, as `points` are, and the document is left as it was. + #[test] + fn lab_bounds_refuse_subtracted_samples_and_click_order() { + for extra in [serde_json::json!({"subtractPoints": [[1, 1]]}), serde_json::json!({"order": ["+", "-"]}), serde_json::json!({"subtractPoints": []})] { + let mut s = Session::new(); + s.execute("file.new", serde_json::json!({"width": 4, "height": 2})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let mut p = serde_json::json!({"labMinimum": [0, -10, -10], "labMaximum": [100, 10, 10], "lightness": 50}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let err = s.execute(CMD, p).unwrap_err().to_string(); + assert!(err.contains("Lab bounds cannot be combined"), "{extra}: {err}"); + assert_eq!(s.active().unwrap().doc, before, "{extra}"); + } + } } diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 51843ae022..162524367d 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -36,6 +36,12 @@ fn changed(a: [f32; 4], b: [f32; 4]) -> f32 { (0..3).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max) } +/// Every pixel of the active layer, row by row. +fn pixels(s: &Session) -> Vec<[f32; 4]> { + let b = doc(s).bounds(); + (b.y0..b.y1).flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))).map(|(x, y)| rgba(s, x, y)).collect() +} + fn doc(s: &Session) -> &Document { &s.active().unwrap().doc } @@ -754,6 +760,239 @@ fn replace_color_localized_clusters_only_change_the_colour_near_the_sample() { assert!(err.to_string().contains("bad point"), "{err}"); } +/// #6280: Add to Sample and Subtract from Sample, as in Photoshop: several picked colours are +/// all replaced, and a subtracted one is left alone, matching as Select › Color Range does for +/// the same samples. +#[test] +fn replace_color_adds_and_subtracts_samples_as_color_range_does() { + // Red on the left (x < 16), blue in the middle, green on the right (32 ≤ x < 44), and a + // lighter red at the edge that the samples only partly cover. + let (red, blue, green, pink) = ([0.85, 0.1, 0.1, 1.0], [0.1, 0.15, 0.85, 1.0], [0.1, 0.8, 0.15, 1.0], [0.95, 0.25, 0.25, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| { + if x < 16 { + red + } else if x < 32 { + blue + } else if x < 44 { + green + } else { + pink + } + }); + let before = (rgba(&s, 4, 16), rgba(&s, 24, 16), rgba(&s, 40, 16), rgba(&s, 46, 16)); + let original = pixels(&s); + let shift = |extra: Value| { + let mut p = json!({"fuzziness": 40, "hue": 120, "saturation": 20}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + // Red and blue sampled (one added): both change, green doesn't. + s.execute("image.adjustments.replaceColor", shift(json!({"color": "#d91a1a", "points": [[4, 16], [24, 16]]}))).unwrap(); + assert!(changed(rgba(&s, 4, 16), before.0) > 0.1, "red is replaced"); + assert!(changed(rgba(&s, 24, 16), before.1) > 0.1, "the added blue is replaced"); + assert_eq!(rgba(&s, 40, 16), before.2, "green wasn't sampled"); + let partial = rgba(&s, 46, 16); + // One undo step brings every pixel back exactly. + s.execute("edit.undo", json!({})).unwrap(); + assert!(pixels(&s) == original, "undo restores the pixels"); + // The same coverage as Select › Color Range for the same clicks. + s.execute("select.colorRange", json!({"points": [[4, 16], [24, 16]], "fuzziness": 40})).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + for x in [4, 24, 40] { + let want = sel.read_region(Rect::from_xywh(x, 16, 1, 1))[0]; + assert!((want > 0.5) == (x < 32), "Color Range at {x}: {want}"); + } + // The lighter red is partly covered, and replaced in proportion: the blend of its colour and + // its fully replaced colour at that coverage, not either one (as a 0.5 threshold would give). + let k = sel.read_region(Rect::from_xywh(46, 16, 1, 1))[0]; + assert!(k > 0.1 && k < 0.9, "partial coverage: {k}"); + let mut full = [before.3]; + tone::replace_color_masked(&mut full, &[1.0], 120.0, 20.0, 0.0); + let blend: [f32; 4] = std::array::from_fn(|c| before.3[c] + (full[0][c] - before.3[c]) * k); + assert!(changed(partial, blend) < 1.5 / 255.0, "{partial:?} vs the blend {blend:?} at coverage {k}"); + assert!(changed(blend, before.3).min(changed(blend, full[0])) > 0.1, "the blend is far from both ends a threshold gives"); + s.execute("select.deselect", json!({})).unwrap(); + // A subtraction undoes exactly too. (Blue is far from the red sample here, so subtracting + // it changes nothing; `replace_color_subtracting_inside_the_added_range_takes_a_colour_out` + // has a subtraction that does.) + let selected = pixels(&s); + s.execute("image.adjustments.replaceColor", shift(json!({"points": [[4, 16]], "subtractPoints": [[24, 16]], "order": ["+", "-"]}))).unwrap(); + assert!(changed(rgba(&s, 4, 16), before.0) > 0.1); + assert_eq!(rgba(&s, 40, 16), before.2); + s.execute("edit.undo", json!({})).unwrap(); + assert!(pixels(&s) == selected, "undo restores the pixels"); + // Bad samples are refused, naming this command. + let err = s.execute("image.adjustments.replaceColor", shift(json!({"points": [[4, 16]], "subtractPoints": [[999, 16]]}))).unwrap_err(); + assert!(err.to_string().contains("replaceColor") && err.to_string().contains("outside"), "{err}"); +} + +/// FredApps review on #10443: a subtracted sample inside the added range. Photoshop's Subtract +/// from Sample reshapes the samples' Lab box (`LabRange::subtract`): a subtracted colour inside +/// it pulls the nearer edge onto itself, so it stays matched and the added colour beyond that +/// edge drops out. Two added greys span dark to light; subtracting a grey near the light end +/// leaves the light one unreplaced. +#[test] +fn replace_color_subtracting_inside_the_added_range_takes_a_colour_out() { + let grey = |v: f32| [v, v, v, 1.0]; + // Dark grey (x < 12), mid grey (subtracted), light grey, black (never sampled). + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| match x { + ..12 => grey(0.25), + 12..24 => grey(0.65), + 24..36 => grey(0.75), + _ => grey(0.0), + }); + let at = [(4, 16), (16, 16), (28, 16), (40, 16)]; + let before: Vec<_> = at.iter().map(|&(x, y)| rgba(&s, x, y)).collect(); + let added = json!({"fuzziness": 20, "lightness": -50, "points": [[4, 16], [28, 16]]}); + // Added only: the box spans dark to light, so all three greys are replaced. + s.execute("image.adjustments.replaceColor", added.clone()).unwrap(); + for (i, &(x, y)) in at[..3].iter().enumerate() { + assert!(changed(rgba(&s, x, y), before[i]) > 0.1, "grey {i} is in the added range"); + } + assert_eq!(rgba(&s, 40, 16), before[3]); + s.execute("edit.undo", json!({})).unwrap(); + // Mid grey subtracted: the light end moves onto it, so the light grey is left alone. + let mut subtracted = added.clone(); + subtracted["subtractPoints"] = json!([[16, 16]]); + subtracted["order"] = json!(["+", "+", "-"]); + s.execute("image.adjustments.replaceColor", subtracted.clone()).unwrap(); + assert!(changed(rgba(&s, 4, 16), before[0]) > 0.1, "the dark grey is still replaced"); + assert!(changed(rgba(&s, 16, 16), before[1]) > 0.1, "the subtracted grey stays matched, at the new edge"); + assert_eq!(rgba(&s, 28, 16), before[2], "the light grey beyond it is taken out"); + assert_eq!(rgba(&s, 40, 16), before[3]); + // Select › Color Range agrees for the same clicks. + s.execute("edit.undo", json!({})).unwrap(); + let mut range = subtracted; + range.as_object_mut().unwrap().remove("lightness"); + s.execute("select.colorRange", range).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + let covered: Vec = at.iter().map(|&(x, y)| sel.read_region(Rect::from_xywh(x, y, 1, 1))[0] > 0.5).collect(); + assert_eq!(covered, [true, true, false, false]); +} + +/// CodeRabbit review on #10443: the click order (`"order"`) reaches the matcher, as in Select › +/// Color Range. Added dark grey, subtracted mid grey, added light grey (`+ - +`): the subtraction +/// comes while the box is the dark grey alone, far from the mid grey, so it changes nothing and the +/// light grey is replaced; all additions first (`+ + -`) would leave it out. +#[test] +fn replace_color_follows_the_click_order_as_color_range_does() { + let grey = |v: f32| [v, v, v, 1.0]; + // Dark grey (x < 12), mid grey (subtracted), light grey, black (never sampled). + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| match x { + ..12 => grey(0.25), + 12..24 => grey(0.65), + 24..36 => grey(0.75), + _ => grey(0.0), + }); + let at = [(4, 16), (16, 16), (28, 16), (40, 16)]; + let before: Vec<_> = at.iter().map(|&(x, y)| rgba(&s, x, y)).collect(); + let clicks = json!({"fuzziness": 20, "points": [[4, 16], [28, 16]], "subtractPoints": [[16, 16]], "order": ["+", "-", "+"]}); + let mut p = clicks.clone(); + p["lightness"] = json!(-50); + s.execute("image.adjustments.replaceColor", p).unwrap(); + let replaced: Vec = at.iter().enumerate().map(|(i, &(x, y))| changed(rgba(&s, x, y), before[i]) > 0.1).collect(); + s.execute("edit.undo", json!({})).unwrap(); + // Darkening leaves black black whether or not it's matched: lighten to see whether it is. + p = clicks.clone(); + p["lightness"] = json!(50); + s.execute("image.adjustments.replaceColor", p).unwrap(); + let lifted = changed(rgba(&s, 40, 16), before[3]) > 0.1; + s.execute("edit.undo", json!({})).unwrap(); + s.execute("select.colorRange", clicks).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + let covered: Vec = at.iter().map(|&(x, y)| sel.read_region(Rect::from_xywh(x, y, 1, 1))[0] > 0.5).collect(); + assert_eq!(covered, [true, true, true, false], "Color Range: the light grey is added back after the subtraction"); + assert_eq!(replaced, covered, "Replace Color matches what Color Range covers for the same clicks"); + assert_eq!(lifted, covered[3], "Replace Color matches black as Color Range does"); +} + +/// FredApps review on #10443: Localized Color Clusters with several samples. A matching colour +/// is replaced only near one of the samples, as in Select › Color Range. +#[test] +fn replace_color_localized_clusters_with_several_samples() { + // Two creams, sampled at x = 2 and x = 24; the first cream again far right (x ≥ 40). + let (cream, cream2, grey) = ([0.9, 0.88, 0.79, 1.0], [0.88, 0.86, 0.76, 1.0], [0.5, 0.5, 0.5, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| match x { + ..8 => cream, + 20..28 => cream2, + 40.. => cream, + _ => grey, + }); + let at = [(3, 16), (24, 16), (44, 16), (14, 16)]; + let before: Vec<_> = at.iter().map(|&(x, y)| rgba(&s, x, y)).collect(); + let mut p = json!({"fuzziness": 20, "hue": 180, "saturation": 60, "points": [[2, 16], [24, 16]]}); + // Without clusters both creams change everywhere, the far one too. + s.execute("image.adjustments.replaceColor", p.clone()).unwrap(); + assert!(changed(rgba(&s, 44, 16), before[2]) > 0.05, "far cream without clusters"); + s.execute("edit.undo", json!({})).unwrap(); + // Range 20 % of 48 px: within about 10 px of either sample. + p["localized"] = json!(true); + p["range"] = json!(20); + s.execute("image.adjustments.replaceColor", p.clone()).unwrap(); + assert!(changed(rgba(&s, 3, 16), before[0]) > 0.05, "near the first sample"); + assert!(changed(rgba(&s, 24, 16), before[1]) > 0.05, "near the second sample"); + assert_eq!(rgba(&s, 44, 16), before[2], "the same cream far from both samples"); + assert_eq!(rgba(&s, 14, 16), before[3], "grey isn't sampled"); + // Select › Color Range agrees for the same clicks. + s.execute("edit.undo", json!({})).unwrap(); + for k in ["hue", "saturation"] { + p.as_object_mut().unwrap().remove(k); + } + s.execute("select.colorRange", p).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + let covered: Vec = at.iter().map(|&(x, y)| sel.read_region(Rect::from_xywh(x, y, 1, 1))[0] > 0.5).collect(); + assert_eq!(covered, [true, true, false, false]); +} + +/// #10443 review: with only Subtract from Sample clicks, the dialog's From colour is what the +/// subtraction starts from, not the foreground (black here), so the red is still replaced. +#[test] +fn replace_color_subtract_only_starts_from_the_from_colour() { + let (red, blue) = ([0.85, 0.1, 0.1, 1.0], [0.1, 0.15, 0.85, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| if x < 16 { red } else { blue }); + let (r0, b0) = (rgba(&s, 4, 16), rgba(&s, 24, 16)); + let p = json!({"color": "#d91a1a", "hue": 120, "fuzziness": 40, "points": [], "subtractPoints": [[24, 16]]}); + s.execute("image.adjustments.replaceColor", p).unwrap(); + assert_ne!(rgba(&s, 4, 16), r0, "the From colour (red) is replaced"); + // Blue is outside the From colour's range anyway: subtracting from a single colour doesn't + // reshape its range, as in Photoshop (see + // `replace_color_subtracting_inside_the_added_range_takes_a_colour_out`). + assert_eq!(rgba(&s, 24, 16), b0, "blue isn't matched"); +} + +/// #10443 review: a `null` From colour means the foreground, for the subtract-only matcher too. +#[test] +fn replace_color_subtract_only_reads_a_null_colour_as_the_foreground() { + let (red, blue) = ([0.85, 0.1, 0.1, 1.0], [0.1, 0.15, 0.85, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| if x < 16 { red } else { blue }); + s.tools.foreground = red; + let r0 = rgba(&s, 4, 16); + let p = json!({"color": null, "hue": 120, "fuzziness": 40, "points": [], "subtractPoints": [[24, 16]]}); + s.execute("image.adjustments.replaceColor", p).unwrap(); + assert_ne!(rgba(&s, 4, 16), r0, "the foreground (red) is replaced"); +} + +/// A malformed `subtractPoints` is refused even with one sample, where the single-colour path +/// would otherwise ignore it (CodeRabbit review on #10443). +#[test] +fn replace_color_refuses_malformed_subtract_points() { + let mut s = session(8, "rgb"); + paint(&mut s, |_, _| [0.85, 0.1, 0.1, 1.0]); + for points in [json!([]), json!([[4, 16]])] { + let p = json!({"color": "#d91a1a", "hue": 120, "points": points, "subtractPoints": "invalid"}); + let err = s.execute("image.adjustments.replaceColor", p).unwrap_err(); + assert!(err.to_string().contains("replaceColor") && err.to_string().contains("subtractPoints"), "{err}"); + } + // An empty list is no subtraction: the single-colour path. + s.execute("image.adjustments.replaceColor", json!({"color": "#d91a1a", "hue": 120, "points": [[4, 16]], "subtractPoints": []})).unwrap(); +} + /// #6095: ⌘I in Quick Mask inverts the whole mask, not only where it was white, so leaving Quick /// Mask selects everything but the original rectangle, whichever way the colour reads. With /// Color Indicates Selected Areas and nothing selected, it selects everything. A black alpha diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 0bf2a335ad..d9d7d1510c 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -896,9 +896,15 @@ fn count_delete_group(s: &mut Session, p: &Value) -> Result { s.edit("Delete Count Group", |d, _| { d.measurement.count_groups.remove(g); let n = d.measurement.count_groups.len(); - // Removing a group before the active one shifts it down a slot. + // Deleting the current group makes the first one current (#11771); removing a group + // before the current one shifts it down a slot (#5654). let a = d.measurement.active_count_group; - d.measurement.active_count_group = (if g < a { a - 1 } else { a }).min(n.saturating_sub(1)); + let next = match g.cmp(&a) { + std::cmp::Ordering::Equal => 0, + std::cmp::Ordering::Less => a - 1, + std::cmp::Ordering::Greater => a, + }; + d.measurement.active_count_group = next.min(n.saturating_sub(1)); Ok(()) })?; Ok(count_json(doc(s)?.as_ref())) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 470971831a..91391edc25 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -19,6 +19,7 @@ use crate::{EngineError, Result, Session}; /// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages. pub const PRESETS: &[(&str, u32, u32)] = &[ + ("iPhone 8/7/6", 750, 1334), ("iPhone 14", 390, 844), ("iPhone 14 Pro Max", 430, 932), ("Android 1080p", 360, 640), @@ -414,6 +415,9 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { /// Changing X/Y moves the board with its contents; changing W/H resizes it from the top left. fn set_props(s: &mut Session, p: &Value) -> Result { let cmd = "layer.artboard.set"; + if p.get("layers").is_some() { + return set_backgrounds(s, p); + } let d = s.active().ok_or(EngineError::NoDocument)?; let id = crate::commands::explicit_layer(s, p)?.or_else(|| active_artboard(s)).ok_or_else(|| bad(cmd, "no artboard selected"))?; let old = d.doc.layer(id).and_then(Layer::artboard).cloned().ok_or_else(|| bad(cmd, "the layer is not an artboard"))?; @@ -469,6 +473,34 @@ fn set_props(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// `layer.artboard.set` with a `layers` array: the background of every listed board in one undo +/// step, "Edit Artboard" for one board and "Edit Artboards" for several (the options bar's +/// background control with boards selected). Only `background`/`color` apply to several boards. +fn set_backgrounds(s: &mut Session, p: &Value) -> Result { + let cmd = "layer.artboard.set"; + let d = s.active().ok_or(EngineError::NoDocument)?; + let mut ids: Vec = Vec::new(); + for v in p.get("layers").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`layers` must be an array of layer ids"))? { + let id = LayerId(v.as_u64().ok_or_else(|| bad(cmd, "`layers` must be an array of layer ids"))?); + d.doc.layer(id).and_then(Layer::artboard).ok_or_else(|| bad(cmd, format!("layer {} is not an artboard", id.0)))?; + if !ids.contains(&id) { + ids.push(id); + } + } + if ids.is_empty() { + return Err(bad(cmd, "`layers` is empty")); + } + let background = background_param(p, cmd)?.ok_or_else(|| bad(cmd, "`layers` needs a `background`"))?; + let label = if ids.len() == 1 { "Edit Artboard" } else { "Edit Artboards" }; + s.edit(label, |doc, _| { + for id in &ids { + doc.layer_mut(*id).and_then(Layer::artboard_mut).ok_or(EngineError::NoLayer(*id))?.background = background; + } + Ok(()) + })?; + Ok(json!({"layers": ids.iter().map(|i| i.0).collect::>()})) +} + /// The Artboard tool's "+" buttons: a board the size of board `layer` on one of its sides, a /// [`GAP`] away (further out past any board in the way), empty or (`duplicate`, the ⌥-click) a /// copy with its contents. A board left of or above the canvas origin shifts the whole document diff --git a/crates/engine/src/cmd/artboard_cmds/tests.rs b/crates/engine/src/cmd/artboard_cmds/tests.rs index 91c860e540..e079c5b54c 100644 --- a/crates/engine/src/cmd/artboard_cmds/tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/tests.rs @@ -1080,3 +1080,28 @@ fn a_layer_centred_just_left_of_a_board_at_negative_coordinates_stays_off_it() { s.execute("layer.translate", json!({"layer": id.0, "dx": 1, "dy": 0, "nest": true})).unwrap(); assert_eq!(doc(&s).artboard_of(id), Some(b)); } + +#[test] +fn a_layers_array_sets_every_listed_boards_background_in_one_step() { + let mut s = session(8); + let a = LayerId(s.execute("layer.new.artboard", json!({"rect": [0, 0, 50, 50]})).unwrap()["layer"].as_u64().unwrap()); + let b = LayerId(s.execute("layer.new.artboard", json!({"rect": [200, 0, 50, 50]})).unwrap()["layer"].as_u64().unwrap()); + let steps = s.active().unwrap().history.entries().len(); + s.execute("layer.artboard.set", json!({"layers": [a.0, b.0], "background": "black"})).unwrap(); + let entries = s.active().unwrap().history.entries(); + assert_eq!(entries.len(), steps + 1); + assert_eq!(entries.last().map(String::as_str), Some("Edit Artboards")); + for id in [a, b] { + assert_eq!(doc(&s).layer(id).and_then(Layer::artboard).unwrap().background, ArtboardBackground::Black); + } + s.execute("layer.artboard.set", json!({"layers": [a.0], "background": "custom", "color": "#ff0000"})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().last().map(String::as_str), Some("Edit Artboard")); + // Undo is one step; errors change nothing. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s).layer(a).and_then(Layer::artboard).unwrap().background, ArtboardBackground::Black); + let n = s.active().unwrap().history.entries().len(); + assert!(s.execute("layer.artboard.set", json!({"layers": [a.0, 9999], "background": "white"})).is_err()); + assert!(s.execute("layer.artboard.set", json!({"layers": [], "background": "white"})).is_err()); + assert!(s.execute("layer.artboard.set", json!({"layers": [a.0]})).is_err()); + assert_eq!(s.active().unwrap().history.entries().len(), n); +} diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index c29d4c3146..f72a0e207b 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -26,8 +26,9 @@ fn stroke_backwards_compatible() { assert_eq!(r["damage"].as_array().unwrap().len(), 4); assert_eq!(rgba(&s, 30, 20), [0.0, 0.0, 1.0, 1.0]); assert_eq!(rgba(&s, 30, 30)[3], 0.0); - // [x, y, pressure] with the default pressure-size brush: light pressure → thinner line. - s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10})).unwrap(); + // [x, y, pressure] with Pressure for Size on: light pressure → a thinner line. The default + // brush has it off since #11809, so this stroke asks for it. + s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10, "brush": {"pressureSize": true}})).unwrap(); assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } diff --git a/crates/engine/src/cmd/count_delete_group_tests.rs b/crates/engine/src/cmd/count_delete_group_tests.rs new file mode 100644 index 0000000000..bdabca1c73 --- /dev/null +++ b/crates/engine/src/cmd/count_delete_group_tests.rs @@ -0,0 +1,61 @@ +//! #11771: deleting the current count group makes the first remaining group current. Deleting +//! another group by index keeps the current one (#5654), and the last group goes without error. + +use serde_json::{Value, json}; + +use crate::Session; + +/// Three groups, each with one marker, and the second one current. +fn three_groups() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + for (i, name) in ["One", "Two", "Three"].iter().enumerate() { + s.execute("count.newGroup", json!({"name": name})).unwrap(); + s.execute("count.add", json!({"x": 10 + 10 * i, "y": 10})).unwrap(); + } + s.execute("count.setGroup", json!({"group": 1})).unwrap(); + assert_eq!(current(&mut s), (1, "Two".to_string())); + s +} + +/// The current group's index and name. +fn current(s: &mut Session) -> (u64, String) { + let c = s.execute("image.analysis.countTool", json!({})).unwrap(); + let i = c["activeGroup"].as_u64().unwrap(); + let name = c["groups"].get(i as usize).and_then(|g| g["name"].as_str()).unwrap_or_default().to_string(); + (i, name) +} + +fn groups(s: &mut Session) -> usize { + s.execute("image.analysis.countTool", json!({})).unwrap()["groups"].as_array().map_or(0, Vec::len) +} + +#[test] +fn deleting_the_current_group_makes_the_first_one_current() { + for params in [json!({}), json!({"group": 1})] { + let mut s = three_groups(); + s.execute("count.deleteGroup", params.clone()).unwrap(); + assert_eq!(groups(&mut s), 2, "{params}"); + assert_eq!(current(&mut s), (0, "One".to_string()), "{params}"); + } +} + +#[test] +fn deleting_another_group_keeps_the_current_one() { + let mut s = three_groups(); + s.execute("count.deleteGroup", json!({"group": 2})).unwrap(); + assert_eq!(current(&mut s), (1, "Two".to_string())); + let mut s = three_groups(); + s.execute("count.deleteGroup", json!({"group": 0})).unwrap(); + assert_eq!(current(&mut s), (0, "Two".to_string())); +} + +#[test] +fn deleting_the_last_group_leaves_none() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("count.newGroup", json!({"name": "Only"})).unwrap(); + s.execute("count.deleteGroup", json!({})).unwrap(); + let c: Value = s.execute("image.analysis.countTool", json!({})).unwrap(); + assert_eq!(c["groups"].as_array().map(Vec::len), Some(0)); +} diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index ccba775115..495f9d1892 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -63,8 +63,8 @@ use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatte use save::save_a_copy; pub(crate) use save::{SaveOpts, encode, save_doc}; pub use save::{ - dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, pcraft_full_composite_param, tga_bits_param, tiff_bool_param, tiff_compression_param, - tiff_would_write_layers, + dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, maximize_compatibility_param, pcraft_full_composite_param, tga_bits_param, tiff_bool_param, + tiff_compression_param, tiff_would_write_layers, }; mod batch_naming; @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tiffTransparency":bool? (TIFF: Save Transparency; off composites over white; unset, kept unless the document has alpha or spot channels),"tiffPyramid":bool=false (TIFF: Save Image Pyramid, half-size copies after the image),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tiffTransparency":bool? (TIFF: Save Transparency; off composites over white; unset, kept unless the document has alpha or spot channels),"tiffPyramid":bool=false (TIFF: Save Image Pyramid, half-size copies after the image),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##, native_doc, save_a_copy ), @@ -349,7 +349,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##, + r##"{"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (for a named action),"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"source":"folder|open"="folder" (open runs on live documents),"input":folder|[paths] (folder source),"errorLog":path? (blank disables it),"suppressOpenOptions":bool=false (use caller RAW defaults and fully supported prior XMP without a dialog; unsupported prior settings or unanswerable profile questions fail the input),"suppressWarnings":bool=false (apply caller opening policy without profile questions; import diagnostics remain in notices),"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; ordinary outputs are flat; namingComponents can retain subfolders when flatOutput is false),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only; put every result directly under output, dropping its subfolder path; duplicate output names make later results error entries),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}/{NAME}/{Name}, {serial}/{serial:1..4}, {letter}/{LETTER}, {date} and date formats, {ext}/{EXT}; template determines the whole filename),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"calledActions":[{"name","steps"}…]? (internal action references; default: the session's; a named source is selected from the caller)} → {files, errors, stopped?, skipped?, errorLog?, documents?} (structured naming, includeNonImages and Save and Close refuse duplicate results; ordinary native templates keep the later result)"##, native, batch ), @@ -358,7 +358,7 @@ pub fn specs() -> Vec { "Image Processor…", &["File", "Scripts"], None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, image_processor ), @@ -386,7 +386,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility)} → {files}"##, native_doc, layers_to_files ), diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index 665a8bbe9a..a262a83a1c 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -72,7 +72,8 @@ impl SaveOpts { /// `jpegFormat` it doesn't name or a `tgaBits` other than 24 or 32 is an error); the image /// previews and the PSD merged image from the session's File Handling preferences (Ask When /// Saving has no dialog here, so it saves them, as Photoshop's Save As checkbox and its - /// Maximize Compatibility checkbox both start on). The `.pcraft` full-size composite comes from + /// Maximize Compatibility checkbox both start on); `maximizeCompatibility` decides the merged + /// image for this save instead. The `.pcraft` full-size composite comes from /// `pcraftFullComposite`, or without it from the File Handling preference. pub(crate) fn from_params(s: &Session, p: &Value, cmd: &str) -> Result { let file_handling = &s.prefs().file_handling; @@ -88,7 +89,7 @@ impl SaveOpts { tiff_pyramid: tiff_bool_param(p, "tiffPyramid", cmd)?.unwrap_or(false), dds: dds_param(p, cmd)?.unwrap_or_default(), image_previews: file_handling.image_previews != crate::prefs::Ask::Never, - psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, + psd_maximize_compatibility: maximize_compatibility_param(p, cmd)?.unwrap_or(file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never), pcraft_full_composite: pcraft_full_composite_param(p, cmd)?.unwrap_or(file_handling.pcraft_full_composite), }) } @@ -131,6 +132,19 @@ pub fn pcraft_full_composite_param(p: &Value, cmd: &str) -> Result> } } +/// One save's Maximize Compatibility in `p` (`"maximizeCompatibility": bool`, Photoshop's checkbox +/// when saving a PSD/PSB; absent or null: the File Handling preference decides). Anything else is +/// a bad parameter of command `cmd` (#8064). +pub fn maximize_compatibility_param(p: &Value, cmd: &str) -> Result> { + match p.get("maximizeCompatibility") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_bool() + .map(Some) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`maximizeCompatibility` must be true or false, got {v}") }), + } +} + /// The TIFF compression in `p` (`"tiffCompression": "none" | "lzw" | "zip"`, Photoshop's TIFF /// Options; absent or null: none). Anything else is a bad parameter of command `cmd` (#5301). pub fn tiff_compression_param(p: &Value, cmd: &str) -> Result> { diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 26e172ffd6..d42d333128 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1875,6 +1875,41 @@ fn full_composite_preference_controls_the_pcraft_full_size_composite() { } } +/// #8064: `maximizeCompatibility` decides one save's PSD/PSB merged image over the preference +/// (Photoshop's Maximize Compatibility checkbox); unset, the preference decides. Anything but a +/// boolean is refused before anything is written. +#[test] +fn maximize_compatibility_param_overrides_the_preference_for_one_save() { + use crate::prefs::Ask; + let dir = tmp("maximize-param"); + let mut s = session(300, 200, 16); + s.execute("layer.new.layer", json!({})).unwrap(); + let real_merged = |path: &str| photocraft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap().has_real_merged_data(); + for (ask, param, expect) in [ + (Ask::Always, json!(false), false), + (Ask::Never, json!(true), true), + (Ask::Ask, json!(false), false), + (Ask::Never, json!(null), false), + (Ask::Always, json!(null), true), + ] { + s.edit_prefs(|p| p.file_handling.maximize_psd_compatibility = ask); + for ext in ["psd", "psb"] { + let out = join(&dir, &format!("{ask:?}-{param}.{ext}")); + s.execute("file.saveACopy", json!({"path": out, "maximizeCompatibility": param})).unwrap(); + assert_eq!(real_merged(&out), Some(expect), "{ask:?} {param} {ext}"); + } + } + let state = |s: &Session| s.active().map(|st| (st.revision, st.path.clone(), st.is_dirty())); + let before = state(&s); + for bad in [json!("no"), json!(0), json!(1), json!([true])] { + let out = join(&dir, "bad.psd"); + let r = s.execute("file.saveACopy", json!({"path": out, "maximizeCompatibility": bad})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert!(!std::path::Path::new(&out).exists(), "{bad}: nothing written"); + assert_eq!(state(&s), before, "{bad}: the document is as it was"); + } +} + #[test] fn open_as_forces_the_decoder() { let dir = tmp("openas"); diff --git a/crates/engine/src/cmd/layer_multi_cmds/selection.rs b/crates/engine/src/cmd/layer_multi_cmds/selection.rs index e5e361fb1c..cb3dad8c75 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/selection.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/selection.rs @@ -49,6 +49,7 @@ pub(crate) fn top_level(doc: &Document, ids: &[LayerId]) -> Vec { /// Replace the layer selection without a history step (like [`Session::select_layer`]). pub fn set_selection(s: &mut Session, ids: Vec, active: Option, anchor: Option) -> Result<()> { + let before = s.active_layer_stamp(); let st = s.active_mut().ok_or(EngineError::NoDocument)?; if let Some(bad) = ids.iter().chain(active.iter()).find(|id| st.doc.layer(**id).is_none()) { return Err(EngineError::NoLayer(*bad)); @@ -70,6 +71,7 @@ pub fn set_selection(s: &mut Session, ids: Vec, active: Option st.saved_revision = st.revision; } st.last_damage = Some(Rect::EMPTY); + s.note_layer_change(before); Ok(()) } diff --git a/crates/engine/src/cmd/magnetic_cmds.rs b/crates/engine/src/cmd/magnetic_cmds.rs index f13d96fa5c..50bd40fdd0 100644 --- a/crates/engine/src/cmd/magnetic_cmds.rs +++ b/crates/engine/src/cmd/magnetic_cmds.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use photocraft_algo::magnetic::{self, Settings, Tracer}; use photocraft_algo::selection as sel; -use photocraft_doc::{DocId, Document, LayerId}; +use photocraft_doc::{ColorMode, DocId, Document, LayerId}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -23,9 +23,12 @@ const MAX_POINTS: usize = 100_000; /// Longest border one command traces (px, measured along the fastening points). const MAX_LENGTH: f64 = 200_000.0; -/// The pixels the Magnetic Lasso follows: the active layer's when it is a pixel layer (Photoshop's -/// tool sees only the current layer), else the composite. A snapshot of one document revision, -/// read lazily and cached while a border is drawn. +/// The pixels the Magnetic Lasso follows: the visible composite of an RGB document, whichever layer +/// is active (hidden layers add no edges). Documents in other modes (CMYK, Grayscale, Indexed, ...) +/// keep the older rule: the active layer's own pixels when it is a pixel layer, else the composite. +/// A snapshot of one document revision, read lazily (only the tiles near the border) and cached by +/// the tracer while a border is drawn; [`EdgeSource::is_current`] drops it when the document changes, +/// so the composite is rendered once per revision and tile, not once per pointer event. pub struct EdgeSource { doc: Arc, layer: Option, @@ -33,8 +36,12 @@ pub struct EdgeSource { tracer: Tracer, } -/// The active layer when it has pixels of its own. +/// The one layer whose pixels the border follows, or `None` for the composite: always the composite +/// in an RGB document; in other modes the active layer when it has pixels of its own. fn pixel_layer(d: &DocState) -> Option { + if d.doc.mode == ColorMode::Rgb { + return None; + } d.active_layer.filter(|id| d.doc.layer(*id).is_some_and(|l| l.surface().is_some())) } @@ -45,7 +52,13 @@ impl EdgeSource { Some(EdgeSource { doc: d.doc.clone(), layer: pixel_layer(d), revision: d.revision, tracer: Tracer::new(d.doc.bounds()) }) } - /// Whether this still shows the session's active document, layer and revision. + /// Whether this still shows the session's active document and revision (and, outside RGB + /// documents, active layer). + /// + /// When this returns `false` the caller must drop the `EdgeSource` and build a new one with + /// [`EdgeSource::new`]: [`EdgeSource::snap`] and [`EdgeSource::trace`] keep reading the old + /// snapshot and its cached pixels otherwise. The Magnetic Lasso tool does so in `source()` + /// (`crates/ui-egui/src/tools/magnetic_lasso_ui.rs`) before every snap and trace. pub fn is_current(&self, s: &Session) -> bool { s.active().is_some_and(|d| d.doc.id == self.doc.id && d.revision == self.revision && pixel_layer(d) == self.layer) } @@ -70,7 +83,7 @@ impl EdgeSource { } } -/// Straight RGBA8 pixels of `r` from the layer, or the composite without one. +/// Straight RGBA8 pixels of `r` from the layer, or the visible composite without one. fn read(doc: &Document, layer: Option, r: Rect) -> Vec<[u8; 4]> { match layer.and_then(|id| doc.layer(id)).and_then(|l| l.surface()) { Some(surface) => sel::rgba8_image(surface, r), diff --git a/crates/engine/src/cmd/magnetic_cmds/tests.rs b/crates/engine/src/cmd/magnetic_cmds/tests.rs index 39f7bef2bb..dd1c163346 100644 --- a/crates/engine/src/cmd/magnetic_cmds/tests.rs +++ b/crates/engine/src/cmd/magnetic_cmds/tests.rs @@ -65,16 +65,16 @@ fn modes_and_a_given_outline() { } #[test] -fn edges_come_from_the_active_pixel_layer() { +fn edges_come_from_the_visible_composite() { let mut s = session(); s.execute("layer.new.layer", json!({})).unwrap(); - // An empty layer has no edges: the point stays where it is. + // An empty layer on top adds no pixels: the edge of the Background's square still counts. let settings = Settings::default(); let mut src = EdgeSource::new(&s).unwrap(); - assert_eq!(src.snap([44.0, 50.0], settings), Some([44.0, 50.0])); + let p = src.snap([44.0, 50.0], settings).unwrap(); + assert!((p[0] - 40.0).abs() < 0.01, "{p:?}"); let bg = s.active().unwrap().doc.layers[0].id; s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - assert!(!src.is_current(&s), "another layer"); let mut src = EdgeSource::new(&s).unwrap(); assert!(src.is_current(&s)); let p = src.snap([44.0, 50.0], settings).unwrap(); diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index b34aab7623..0d1b91aa1f 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -97,6 +97,63 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option Result { + let bad = |m: &str| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m.into() }; + let from = layer_param(s, p)?; + let to = mask_destination(s, p)?; + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false); + if from == to { + return Err(bad("the mask is already on that layer")); + } + let label = if copy { "Copy Layer Mask" } else { "Move Layer Mask" }; + s.edit(label, |doc, _| { + let mask = doc.layer(from).ok_or(EngineError::NoLayer(from))?.mask.clone().ok_or_else(|| bad("the layer has no layer mask"))?; + if doc.layer(to).ok_or(EngineError::NoLayer(to))?.mask.is_some() && !replace { + return Err(bad("the layer already has a layer mask (pass `replace`)")); + } + check_all_unlocked(doc, to)?; + if !copy { + check_all_unlocked(doc, from)?; + } + // The Background can't hold a mask, so it becomes a normal layer first, as for Add Mask. + crate::extra_cmds::background_to_layer_for_mask(doc, to); + doc.layer_mut(to).ok_or(EngineError::NoLayer(to))?.mask = Some(mask); + if !copy { + doc.layer_mut(from).ok_or(EngineError::NoLayer(from))?.mask = None; + } + Ok(()) + })?; + Ok(json!({"layer": from.0, "to": to.0, "copy": copy})) +} + +/// `layer.layerMask.moveTo`'s `to`: an id, or a name (as a recorded step keeps it) with +/// `toOccurrence` choosing among the layers that share it, in document order (required when +/// several do). +fn mask_destination(s: &Session, p: &Value) -> Result { + let bad = |m: String| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m }; + match p.get("to") { + Some(Value::String(name)) => { + let occurrence = p + .get("toOccurrence") + .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("`toOccurrence` must be a non-negative integer".into()))) + .transpose()?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let matches: Vec<_> = doc.walk().into_iter().filter(|(_, _, l)| &l.name == name).map(|(_, _, l)| l.id).collect(); + if matches.len() > 1 && occurrence.is_none() { + return Err(bad(format!("multiple layers named `{name}`; specify `toOccurrence`"))); + } + let index = occurrence.unwrap_or(0); + matches.get(index).copied().ok_or_else(|| bad(format!("no layer named `{name}` at occurrence {index}"))) + } + Some(v) => v.as_u64().map(LayerId).ok_or_else(|| bad("`to` must be a layer id or name".into())), + None => Err(bad("missing `to`".into())), + } +} + /// Move a layer's pixels, linked mask and type by whole pixels (vectors move via /// `vector_cmds::translate_vectors`). pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { @@ -188,3 +245,110 @@ pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result { })?; Ok(json!({ "layer": id.0 })) } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::Session; + + /// #10485: dragging a layer's mask onto a group moves it there, ⌥ copies it (Photoshop). A + /// layer that has a mask already keeps it unless asked to replace it; one undo puts it back. + #[test] + fn a_layer_mask_moves_or_copies_onto_another_layer_or_group() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + let b = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let group = s.execute("layer.groupLayers", json!({"layer": b})).unwrap()["layer"].as_u64().unwrap(); + let mask_of = |s: &Session, id: u64| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().mask.clone(); + let original = mask_of(&s, a).expect("a has a mask"); + // Move onto the group. + s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).unwrap(); + assert!(mask_of(&s, a).is_none(), "moved away"); + assert_eq!(mask_of(&s, group).unwrap().surface, original.surface, "the same mask on the group"); + // One undo puts it back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(mask_of(&s, a).is_some() && mask_of(&s, group).is_none()); + // ⌥: a copy. + s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group, "copy": true})).unwrap(); + assert!(mask_of(&s, a).is_some() && mask_of(&s, group).is_some()); + assert_eq!(mask_of(&s, group).unwrap().surface, original.surface, "the copy on the group"); + // The group gets a mask of its own: refused unless replacing, which leaves a's on it. + s.execute("layer.layerMask.delete", json!({"layer": group})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({"layer": group})).unwrap(); + assert_ne!(mask_of(&s, group).unwrap().surface, original.surface, "the group's own mask differs"); + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).is_err()); + s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group, "replace": true})).unwrap(); + assert!(mask_of(&s, a).is_none()); + assert_eq!(mask_of(&s, group).unwrap().surface, original.surface, "a's mask replaced the group's"); + // Bad input. + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).is_err(), "no mask to move"); + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group, "to": group})).is_err(), "onto itself"); + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group})).is_err(), "no target"); + } + + /// #10485: dropping a mask back on its own layer's row is a no-op: the mask keeps its pixels, + /// enabled state and density, nothing else in the document changes, and no history step is added. + #[test] + fn dropping_a_layer_mask_on_its_own_layer_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("layer.layerMask.edit", json!({"layer": a, "density": 40})).unwrap(); + s.execute("layer.layerMask.enabled", json!({"layer": a, "enabled": false})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let mask = doc.layer(photocraft_doc::LayerId(a)).unwrap().mask.clone().expect("a has a mask"); + assert!(!mask.enabled && (mask.density - 0.4).abs() < 1e-6, "set up: disabled, 40% density"); + let history = s.active().unwrap().history.entries(); + for (copy, replace) in [(false, false), (true, false), (false, true), (true, true)] { + let r = s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": a, "copy": copy, "replace": replace})); + assert!(r.is_err(), "copy: {copy}, replace: {replace}: refused"); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(photocraft_doc::LayerId(a)).unwrap().mask.as_ref(), Some(&mask), "copy: {copy}, replace: {replace}: the mask is untouched"); + assert!(st.doc == doc, "copy: {copy}, replace: {replace}: the document is unchanged"); + assert_eq!(st.history.entries(), history, "copy: {copy}, replace: {replace}: no history step"); + } + } + + /// #10485: one undo after an ⌥-copy, or after a move or copy that replaces the target's own + /// mask, puts both layers' masks back exactly (pixels, enabled, density, feather). + #[test] + fn undo_restores_both_masks_after_a_copy_or_a_replace() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("layer.layerMask.edit", json!({"layer": a, "density": 60, "feather": 3})).unwrap(); + let b = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 18, "y": 2, "width": 6, "height": 20})).unwrap(); + s.execute("layer.layerMask.hideSelection", json!({"layer": b})).unwrap(); + s.execute("layer.layerMask.enabled", json!({"layer": b, "enabled": false})).unwrap(); + let c = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let mask_of = |s: &Session, id: u64| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().mask.clone(); + let (mask_a, mask_b) = (mask_of(&s, a).expect("a has a mask"), mask_of(&s, b).expect("b has a mask")); + assert_ne!(mask_a, mask_b, "set up: two different masks"); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries().len(); + let cases = [ + ("⌥-copy onto a layer without a mask", json!({"layer": a, "to": c, "copy": true}), c), + ("⌥-copy replacing a mask", json!({"layer": a, "to": b, "copy": true, "replace": true}), b), + ("move replacing a mask", json!({"layer": a, "to": b, "replace": true}), b), + ]; + for (case, params, to) in cases { + s.execute("layer.layerMask.moveTo", params).unwrap(); + assert_eq!(mask_of(&s, to).as_ref(), Some(&mask_a), "{case}: the target has a's mask"); + assert_eq!(s.active().unwrap().history.entries().len(), history + 1, "{case}: one history step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(mask_of(&s, a).as_ref(), Some(&mask_a), "{case}: a's mask is back"); + assert_eq!(mask_of(&s, b).as_ref(), Some(&mask_b), "{case}: b's mask is back"); + assert!(mask_of(&s, c).is_none(), "{case}: c has no mask again"); + assert!(s.active().unwrap().doc == doc, "{case}: the document is as before"); + } + } +} diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index e8b0064e2b..ba09fdea23 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -476,8 +476,9 @@ fn system_printers(s: &mut Session, p: &Value) -> Result { // ---------- PDF ---------- -/// Paper sizes in points (portrait). -pub const PAPERS: [(&str, f64, f64); 8] = [ +/// Paper sizes in points (portrait). The original list keeps its order and sizes; the Japanese +/// photo, postcard and JIS sizes follow it (millimetres × 72/25.4). +pub const PAPERS: &[(&str, f64, f64)] = &[ ("letter", 612.0, 792.0), ("legal", 612.0, 1008.0), ("tabloid", 792.0, 1224.0), @@ -486,8 +487,76 @@ pub const PAPERS: [(&str, f64, f64); 8] = [ ("a5", 419.53, 595.28), ("4x6", 288.0, 432.0), ("5x7", 360.0, 504.0), + // Japanese postcards (はがき and 往復はがき), the JIS B series that Japanese printing and + // Excel use (B5 182×257, B4 257×364 mm), A6 and the photo sizes L判, 2L判, KG判, 六切, 四切. + ("postcard", 283.46, 419.53), + ("double-postcard", 419.53, 566.93), + ("b5", 515.91, 728.50), + ("b4", 728.50, 1031.81), + ("a6", 297.64, 419.53), + ("l", 252.28, 360.00), + ("2l", 360.00, 504.57), + ("kg", 289.13, 430.87), + ("6cut", 575.43, 720.00), + ("4cut", 720.00, 864.57), ]; +/// Japanese customary names and other spellings for the papers in [`PAPERS`], matched after +/// [`normalize_paper`]: `はがき` is `postcard`, `L判` is `l`, `JIS B5` is `b5`, and so on. +const PAPER_ALIASES: &[(&str, &str)] = &[ + ("はがき", "postcard"), + ("ハガキ", "postcard"), + ("葉書", "postcard"), + ("ポストカード", "postcard"), + ("往復はがき", "double-postcard"), + ("往復ハガキ", "double-postcard"), + ("JIS B5", "b5"), + ("B5 (JIS)", "b5"), + ("JIS B4", "b4"), + ("B4 (JIS)", "b4"), + ("L判", "l"), + ("Lサイズ", "l"), + ("L-size", "l"), + ("2L判", "2l"), + ("2Lサイズ", "2l"), + ("KG判", "kg"), + ("KGサイズ", "kg"), + ("六切", "6cut"), + ("6切", "6cut"), + ("四切", "4cut"), + ("4切", "4cut"), +]; + +/// The form [`paper_size`] matches names in: lower case, with whitespace and punctuation ignored +/// and `×`/`*` read as `x`, so `L判`, `l-size` and `l` are one name, `4 × 6` is `4x6`, and +/// `B5(JIS)` and `JIS B5.` are `b5`. +fn normalize_paper(name: &str) -> String { + name.chars() + .map(|c| match c { + '×' | '*' => 'x', + c => c, + }) + .filter(|c| !c.is_whitespace() && !c.is_ascii_punctuation() && !matches!(c, '(' | ')' | '、' | '。' | ',' | '.')) + .collect::() + .to_lowercase() +} + +/// The portrait size in points of a named paper, `None` for unknown names. Case, spaces and +/// punctuation don't matter, and the Japanese customary names (`はがき`, `L判`, `六切`, …) and the +/// JIS spelling (`JIS B5`) are aliases of the papers above. +pub fn paper_size(name: &str) -> Option<(f64, f64)> { + let n = normalize_paper(name); + if n.is_empty() { + return None; + } + let canonical = PAPERS + .iter() + .find(|p| normalize_paper(p.0) == n) + .map(|p| p.0) + .or_else(|| PAPER_ALIASES.iter().find(|(alias, _)| normalize_paper(alias) == n).map(|(_, name)| *name))?; + PAPERS.iter().find(|p| p.0 == canonical).map(|p| (p.1, p.2)) +} + /// The image placed on a print page. pub struct PrintImage { pub width: u32, @@ -770,11 +839,9 @@ fn print_image(doc: &Document, p: &Value, cmd: &str) -> Result<(PrintImage, Valu fn paper(p: &Value, cmd: &str) -> Result<(f64, f64)> { let (w, h) = match p.get("paper") { None => (612.0, 792.0), - Some(Value::String(name)) => PAPERS - .iter() - .find(|(n, _, _)| n.eq_ignore_ascii_case(name)) - .map(|(_, w, h)| (*w, *h)) - .ok_or_else(|| bad(cmd, format!("unknown paper `{name}` ({})", PAPERS.map(|p| p.0).join("|"))))?, + Some(Value::String(name)) => { + paper_size(name).ok_or_else(|| bad(cmd, format!("unknown paper `{name}` ({})", PAPERS.iter().map(|p| p.0).collect::>().join("|"))))? + } Some(Value::Array(a)) if a.len() == 2 => (a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0)), _ => return Err(bad(cmd, "paper is a name or [width, height] in points")), }; diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index 177d1305ba..c3d6e536df 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -144,6 +144,80 @@ fn print_dry_run_renders_a_pdf_and_reports_the_platform_backend() { assert!(s.execute("file.print", json!({"colorHandling": "photocraftManages", "dryRun": true})).is_err(), "needs a printer profile"); } +/// The Japanese papers are in the table at their metric sizes, their customary names resolve (case, +/// spaces and punctuation ignored), and the sizes that were there before are unchanged. +#[test] +fn japanese_paper_sizes_and_aliases() { + // mm -> pt, within 0.1 pt. + for (name, w_mm, h_mm) in [ + ("postcard", 100.0, 148.0), + ("double-postcard", 148.0, 200.0), + ("b5", 182.0, 257.0), + ("b4", 257.0, 364.0), + ("a6", 105.0, 148.0), + ("l", 89.0, 127.0), + ("2l", 127.0, 178.0), + ("kg", 102.0, 152.0), + ("6cut", 203.0, 254.0), + ("4cut", 254.0, 305.0), + ] { + let (w, h) = paper_size(name).unwrap_or_else(|| panic!("{name}")); + let want = (w_mm * 72.0 / 25.4, h_mm * 72.0 / 25.4); + assert!((w - want.0).abs() < 0.1 && (h - want.1).abs() < 0.1, "{name}: {w} x {h}, wanted {want:?}"); + } + // The customary and English names resolve to the same paper. + for (a, b) in [ + ("はがき", "postcard"), + ("ハガキ", "postcard"), + ("葉書", "postcard"), + ("往復はがき", "double-postcard"), + ("JIS B5", "b5"), + ("B5 (JIS)", "b5"), + ("JIS B4", "b4"), + ("L判", "l"), + ("Lサイズ", "l"), + ("l-size", "l"), + ("2L判", "2l"), + ("KG判", "kg"), + ("六切", "6cut"), + ("6切", "6cut"), + ("四切", "4cut"), + ("4切", "4cut"), + ("A4", "a 4"), + ("4 × 6", "4x6"), + ("B5(JIS)", "b5"), + ("JIS B5.", "b5"), + ("JIS B5。", "b5"), + ] { + assert_eq!(paper_size(a), paper_size(b), "{a} vs {b}"); + } + assert!(paper_size("napkin").is_none()); + // The papers that were already there keep their sizes. + assert_eq!(paper_size("letter"), Some((612.0, 792.0))); + assert_eq!(paper_size("a4"), Some((595.28, 841.89))); + assert_eq!(paper_size("4x6"), Some((288.0, 432.0))); + assert_eq!(paper_size("5x7"), Some((360.0, 504.0))); +} + +/// A print on はがき or L判 writes a PDF page of that paper's size: 100 × 148 mm is +/// 283.46 × 419.53 pt and 89 × 127 mm is 252.28 × 360.00 pt. The customary names and the JIS +/// spelling work too, and an unknown paper is still refused. +#[test] +fn japanese_paper_sizes_reach_the_pdf_page() { + let dir = tmp("jp-paper"); + for (paper, w, h) in [("postcard", 283.46, 419.53), ("l", 252.28, 360.00), ("はがき", 283.46, 419.53), ("JIS B5", 515.91, 728.50)] { + let mut s = session("rgb", 8); + let out = format!("{dir}/{}.pdf", paper.replace(' ', "_")); + let r = s.execute("file.print", json!({"output": out, "paper": paper, "scaleToFit": true})).unwrap(); + assert_eq!(r["pdf"], out); + let pdf = std::fs::read(&out).unwrap(); + let text = String::from_utf8_lossy(&pdf); + let want = format!("/MediaBox [0 0 {w:.2} {h:.2}]"); + assert!(text.contains(&want), "{paper}: wanted {want}"); + } + assert!(session("rgb", 8).execute("file.print", json!({"paper": "napkin", "dryRun": true})).is_err()); +} + #[test] fn photocraft_manages_colors_converts_to_the_printer_profile() { let mut s = session("rgb", 8); diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index 65b2ab2d09..5832fb5df9 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -193,7 +193,7 @@ pub(crate) use filters::{add_smart_filter, add_smart_filter_in, filter_mask_pain use filters::{blending_options, delete_filter, edit_filters, move_filter, set_filter_params, set_filter_visible, smart, transfer_filters}; pub(crate) use placing::detach_psd; pub(crate) use placing::{affine_homography, set_placement, shift_smart, transform_placement}; -use placing::{convert, shift_layer, via_copy}; +use placing::{convert, reset_transform, shift_layer, via_copy}; pub use placing::{layer_to_smart, layers_to_smart, placement}; #[cfg(test)] pub(crate) use rendering::DISPLAY_NATIVE_HASH_BYTES; @@ -239,6 +239,14 @@ pub fn specs() -> Vec { has_smart, edit_contents ), + spec!( + "layer.smartObjects.resetTransform", + "Reset Transform", + SO, + r##"{"layer":id?} (the placement returns to 100 % of the current contents' own size with rotation, skew, Distort, Perspective and the Warp cleared, centred on the average of the placement's four corners; the smart filters stay; refused with nothing changed when the object can't be re-rendered (a visible filter PhotoCraft doesn't have, or contents that can't be read); one undo step)"##, + has_smart, + reset_transform + ), spec!("layer.smartObjects.saveContents", "Save Contents", &[], "{} (in an Edit Contents document)", is_smart_child, |s, _| { let i = s.active_index().ok_or(EngineError::NoDocument)?; Ok(json!({"updated": commit_child(s, i)?})) diff --git a/crates/engine/src/cmd/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs index 847ad700db..48cede87e4 100644 --- a/crates/engine/src/cmd/smart_cmds/placing.rs +++ b/crates/engine/src/cmd/smart_cmds/placing.rs @@ -1,8 +1,10 @@ +use super::rendering::{refresh_or_fail, unapplied_filters}; use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes}; use super::{ Affine, Arc, BlendMode, Document, EngineError, Homography, Layer, LayerContent, LayerId, PLACED_KEYS, Rect, Result, Session, Size, SmartContentsId, - SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, translate_surface, + SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, source_box, translate_surface, }; +use photocraft_algo::transform::Interp; /// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so /// repeated transforms land back on exact, lossless placements. @@ -57,6 +59,73 @@ pub(crate) fn shift_smart(sm: &mut SmartObject, dx: i32, dy: i32) { } } +/// Layer ▸ Smart Objects ▸ Reset Transform, and the same item of the Layers panel menu (#11662): +/// the placement goes back to 100 % of the current contents' own size with rotation, skew, Distort, +/// Perspective **and Warp** cleared, centred where the object sits. Measured in the reference +/// application 2026-11-06 (see the #11675 discussion): a smart object warped with Arc 50, rotated +/// and scaled came back with no warp at all, at its contents' own size, unrotated, and centred on +/// the average of its four corners. The smart filters stay. +/// +/// The step needs the contents re-rendered from their source: a stack whose filters can't all be +/// applied, or a source that can't be read, refuses it whole rather than recording the old (still +/// warped) pixels under a placement that no longer describes them. +pub(super) fn reset_transform(s: &mut Session, p: &Value) -> Result { + let id = layer_param(s, p)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let LayerContent::Smart(sm) = &st.doc.layer(id).ok_or(EngineError::NoLayer(id))?.content else { + return Err(other("the layer is not a smart object")); + }; + // Checked before anything changes, so a filter PhotoCraft doesn't have (kept verbatim from a + // PSD) leaves the document as it was, as `layer.smartObjects.updateModifiedContent` insists on + // a re-render too. + let stuck = unapplied_filters(sm); + if let Some(name) = stuck.first() { + return Err(other(format!("the {name} smart filter is not supported, so the smart object's transform can't be reset"))); + } + // The contents' own box in source pixels: 100 % maps it one-to-one onto the document. + let [x0, y0, x1, y1] = source_box(&st.doc, sm).ok_or_else(|| other("the smart object's contents are unavailable"))?; + let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + let old = placement(sm); + // The object stays where it is: the average of the placement's four corners, which is its + // centre for an affine placement and the quad's centre once Distort or Perspective bent it. + let (mut sx, mut sy) = (0.0, 0.0); + for (u, v) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] { + let (px, py) = old.apply(u, v); + sx += px; + sy += py; + } + let (dx, dy) = (sx / 4.0 - cx, sy / 4.0 - cy); + let to = Affine { m: [1.0, 0.0, 0.0, 1.0, dx, dy] }; + let new = affine_homography(&to); + // Everything the accumulated transform moved the pixels by, so the linked masks and the Smart + // Filter mask follow the placement back as they do under Free Transform. + let rel = new.mul(&old.inverse().ok_or_else(|| other("the smart object has a degenerate transform"))?); + if ![dx, dy, cx, cy].iter().all(|v| v.is_finite()) || !rel.0.iter().all(|v| v.is_finite()) { + return Err(other("the smart object's placement is not a usable transform")); + } + s.edit("Reset Transform", |doc, _| { + // The Warp is part of what the reference takes back, so the re-render below starts from the + // unwarped contents. How far a painted Smart Filter mask should follow a cleared warp is + // unmeasured: here it follows the placement, as it does under Free Transform. + if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) { + sm.warp = None; + } + crate::transform_cmds::transform_by_map(doc, id, &rel, None, Interp::Bicubic)?; + // Required, not best-effort: `transform_by_map` re-renders too, but falls back to the old + // pixels when that isn't possible. `Session::edit` runs this on a copy, so an `Err` here + // records no step and leaves the document exactly as it was. The state is unchanged since + // that render, so the guarded refresh answers from the stack cache rather than placing the + // contents a second time. + refresh_or_fail(doc, id)?; + // `new ∘ old⁻¹ ∘ old` only lands on the reset map to within float noise, and could leave a + // Distort placement behind as a nearly affine one: store the exact map. + if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) { + set_placement(sm, new); + } + Ok(json!({"layer": id.0, "transform": to.m})) + }) +} + /// Forget PSD placed-layer data that no longer describes the smart object (its source changed): /// PSD export then writes fresh placed-layer blocks and embeds the new source. pub(crate) fn detach_psd(l: &mut Layer) { diff --git a/crates/engine/src/cmd/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs index 6ae2082b3d..2b1af57216 100644 --- a/crates/engine/src/cmd/smart_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_cmds/tests.rs @@ -503,6 +503,193 @@ fn transforms_re_render_from_source_losslessly() { assert!(active_smart(&smart).perspective.is_some()); } +/// The contents' box centre in document pixels under `sm`'s placement: what an affine placement is +/// centred on, and where the box centre of a projective one maps to. +fn placed_centre(s: &Session, sm: &SmartObject) -> (f64, f64) { + let b = crate::smart_cmds::source_box(&s.active().unwrap().doc, sm).unwrap(); + placement(sm).apply((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0) +} + +/// The average of the four corners of `sm`'s placement in document pixels: the point Reset +/// Transform keeps (measured in the reference application 2026-11-06, see the #11675 discussion). +/// It is the box centre under an affine placement, and the quad's centre under a projective one. +fn quad_centre(s: &Session, sm: &SmartObject) -> (f64, f64) { + let b = crate::smart_cmds::source_box(&s.active().unwrap().doc, sm).unwrap(); + let h = placement(sm); + let (mut x, mut y) = (0.0, 0.0); + for (u, v) in [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])] { + let (px, py) = h.apply(u, v); + x += px; + y += py; + } + (x / 4.0, y / 4.0) +} + +/// Layer ▸ Smart Objects ▸ Reset Transform (#11662): 100 % of the contents' own size, no rotation, +/// skew, Distort or Perspective, and the object stays centred where it is. +#[test] +fn reset_transform_restores_100_percent_in_place() { + let mut s = session(8); + paint(&mut s); + let id = convert(&mut s); + let fresh = active_smart(&s).cache.unwrap().content_bounds(); + s.execute("edit.transform", json!({"layer": id, "scaleX": 200, "scaleY": 200, "rotate": 30})).unwrap(); + s.execute("layer.translate", json!({"dx": 7, "dy": 4})).unwrap(); + let sm = active_smart(&s); + assert!(sm.transform.m[0].hypot(sm.transform.m[1]) > 1.5, "the object really is scaled up"); + assert_ne!(sm.transform.m[1], 0.0, "…and rotated"); + let centre = placed_centre(&s, &sm); + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + let after = active_smart(&s); + assert!(after.perspective.is_none(), "no projective placement left"); + assert_eq!(&after.transform.m[..4], &[1.0, 0.0, 0.0, 1.0], "100 %, square, neither rotated nor skewed"); + let now = placed_centre(&s, &after); + assert!((now.0 - centre.0).abs() < 1e-6 && (now.1 - centre.1).abs() < 1e-6, "centred where it was: {now:?} vs {centre:?}"); + let r = after.cache.unwrap().content_bounds(); + assert_eq!((r.width(), r.height()), (fresh.width(), fresh.height()), "the contents at their own size"); + // Re-rendered from the source rather than resampled from the rotated pixels: the reset object + // is exactly the converted layer moved by the same whole-pixel distance. + let mut control = session(8); + paint(&mut control); + convert(&mut control); + control.execute("layer.translate", json!({"dx": 7, "dy": 4})).unwrap(); + let (got, want) = (flat(&s), flat(&control)); + assert!(max_diff(&got, &want) < 1e-6, "lossless reset (mean {})", mean_diff(&got, &want)); + // Already reset: the second run changes nothing. + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + assert_eq!(active_smart(&s).transform, after.transform, "idempotent"); +} + +/// Reset Transform takes the Warp back with the transform and keeps the smart filter stack: +/// measured in the reference application 2026-11-06 (an Arc 50 warp came back as no warp at all), +/// see the #11675 discussion. +#[test] +fn reset_transform_clears_the_warp_and_keeps_the_smart_filters() { + let mut s = session(8); + paint(&mut s); + let id = convert(&mut s); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + let before = active_smart(&s); + assert!(before.warp.is_some(), "the fixture is warped"); + let r = before.cache.unwrap().content_bounds(); + let (x0, y0, x1, y1) = (f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)); + s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": [[x0, y0], [x1, y0], [x1 - 12.0, y1 - 8.0], [x0, y1]]})).unwrap(); + assert!(active_smart(&s).perspective.is_some(), "Distort keeps a projective placement"); + let centre = quad_centre(&s, &active_smart(&s)); + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + let after = active_smart(&s); + assert!(after.warp.is_none(), "the Warp goes with the transform, as the reference does"); + assert_eq!(after.smart_filters.len(), 1, "the smart filter stack stays"); + assert!(after.perspective.is_none(), "Distort is cleared"); + assert_eq!(&after.transform.m[..4], &[1.0, 0.0, 0.0, 1.0]); + let now = placed_centre(&s, &after); + assert!((now.0 - centre.0).abs() < 1e-6 && (now.1 - centre.1).abs() < 1e-6, "centred where it was: {now:?} vs {centre:?}"); + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + let again = active_smart(&s); + assert_eq!(again.transform, after.transform, "idempotent"); + assert!(again.warp.is_none(), "and still unwarpd"); +} + +/// The centre Reset Transform keeps is the average of the placement's four corners, not the point +/// its box centre maps to: they differ once Distort or Perspective bends the quad, and the +/// reference application keeps the corners' average (measured 2026-11-06, #11675 discussion). +#[test] +fn reset_transform_centres_a_distorted_object_on_its_corner_average() { + let mut s = session(8); + paint(&mut s); + let id = convert(&mut s); + let r = active_smart(&s).cache.unwrap().content_bounds(); + let (x0, y0, x1, y1) = (f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)); + let quad = [[x0 - 10.0, y0 - 6.0], [x1 + 26.0, y0 - 2.0], [x1 + 4.0, y1 + 18.0], [x0 - 16.0, y1 + 8.0]]; + s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": quad})).unwrap(); + let sm = active_smart(&s); + assert!(sm.perspective.is_some(), "a projective placement"); + let corners = quad_centre(&s, &sm); + let middle = placed_centre(&s, &sm); + assert!((corners.0 - middle.0).abs() + (corners.1 - middle.1).abs() > 1.0, "the fixture splits the two centres: {corners:?} vs {middle:?}"); + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + let after = active_smart(&s); + assert_eq!(&after.transform.m[..4], &[1.0, 0.0, 0.0, 1.0], "100 %, square"); + assert!(after.perspective.is_none() && after.warp.is_none(), "no projective placement or warp left"); + let now = placed_centre(&s, &after); + assert!((now.0 - corners.0).abs() < 1e-6 && (now.1 - corners.1).abs() < 1e-6, "centred on the corners: {now:?} vs {corners:?}"); + assert!((now.0 - middle.0).abs() + (now.1 - middle.1).abs() > 1.0, "not on the point the box centre mapped to"); +} + +/// A stack holding a filter this build can't apply can't be re-rendered without the warp, so Reset +/// Transform refuses the whole step instead of recording the old warped pixels at the new +/// placement: no history state, and placement, warp and stack left exactly as they were. +#[test] +fn reset_transform_refuses_a_stack_it_cannot_re_render() { + let mut s = session(8); + paint(&mut s); + convert(&mut s); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); + s.execute("edit.transform", json!({"scaleX": 160, "scaleY": 160})).unwrap(); + // A smart filter whose command this build doesn't have, as an imported PSD leaves it. + s.edit("unsupported filter", |doc, active| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(active.unwrap()).unwrap().content else { panic!("a smart object") }; + sm.smart_filters.push(SmartFilter { + command: UNSUPPORTED_FILTER.into(), + params: json!({"name": "Camera Raw Filter"}), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + }); + Ok(()) + }) + .unwrap(); + let before = active_smart(&s); + assert!(!super::rendering::unapplied_filters(&before).is_empty(), "the fixture's filter can't be applied"); + let states = s.active().unwrap().history.entries().len(); + let err = s.execute("layer.smartObjects.resetTransform", json!({})).unwrap_err().to_string(); + assert!(err.contains("Camera Raw Filter"), "the error names the filter that blocks it: {err}"); + let after = active_smart(&s); + assert_eq!(after.transform, before.transform, "the placement is left alone"); + assert_eq!(after.warp, before.warp, "the warp is still there"); + assert_eq!(after.smart_filters, before.smart_filters, "so is the stack"); + assert_eq!(s.active().unwrap().history.entries().len(), states, "a refused step records no history state"); + // Only this step is refused: with the stack gone the same object resets normally. + s.execute("layer.smartFilter.clearSmartFilters", json!({})).unwrap(); + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + let cleared = active_smart(&s); + assert_eq!(&cleared.transform.m[..4], &[1.0, 0.0, 0.0, 1.0], "then the reset goes through"); + assert!(cleared.warp.is_none(), "with the warp"); +} + +/// Enabled for a smart object only, and one undo step back (#11662). +#[test] +fn reset_transform_needs_a_smart_object_and_undoes_in_one_step() { + let mut empty = Session::new(); + assert!(!empty.is_enabled("layer.smartObjects.resetTransform"), "no document"); + assert!(empty.execute("layer.smartObjects.resetTransform", json!({})).is_err()); + let mut s = session(8); + paint(&mut s); + let plain = s.active().unwrap().active_layer.unwrap().0; + assert!(!s.is_enabled("layer.smartObjects.resetTransform"), "a pixel layer has no placement to reset"); + assert!(s.execute("layer.smartObjects.resetTransform", json!({"layer": plain})).is_err()); + let id = convert(&mut s); + assert!(s.is_enabled("layer.smartObjects.resetTransform")); + s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, 0, 0]})).unwrap(); + let scaled = active_smart(&s); + s.execute("layer.smartObjects.resetTransform", json!({})).unwrap(); + assert_eq!(&active_smart(&s).transform.m[..4], &[1.0, 0.0, 0.0, 1.0]); + s.execute("edit.undo", json!({})).unwrap(); + let back = active_smart(&s); + assert_eq!(back.transform, scaled.transform, "one history step back to the scaled placement"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(&active_smart(&s).transform.m[..4], &[1.0, 0.0, 0.0, 1.0], "…and forward again"); + // Hostile targets are refused, never acted on. + assert!(s.execute("layer.smartObjects.resetTransform", json!({"layer": u64::MAX})).is_err()); + assert!(s.execute("layer.smartObjects.resetTransform", json!({"layer": "nope"})).is_err()); + // A locked layer can't be moved. + s.execute("layer.lockLayers", json!({"layer": id, "position": true})).unwrap(); + let locked = active_smart(&s).transform; + assert!(s.execute("layer.smartObjects.resetTransform", json!({})).is_err()); + assert_eq!(active_smart(&s).transform, locked, "the placement is left alone"); +} + #[test] fn filters_follow_transforms() { let mut s = session(16); @@ -712,6 +899,7 @@ fn commands_are_registered_with_catalog_ids() { "layer.smartObjects.newSmartObjectViaCopy", "layer.smartObjects.rasterize", "layer.smartObjects.editContents", + "layer.smartObjects.resetTransform", "layer.smartObjects.replaceContents", "layer.smartObjects.exportContents", "layer.smartObjects.updateModifiedContent", diff --git a/crates/engine/src/cmd/transform_cmds.rs b/crates/engine/src/cmd/transform_cmds.rs index cf9004bbac..4243569f68 100644 --- a/crates/engine/src/cmd/transform_cmds.rs +++ b/crates/engine/src/cmd/transform_cmds.rs @@ -634,18 +634,23 @@ pub fn split_selected(surf: &Surface, sel: &Surface) -> Result<(Surface, Surface /// masks and Smart Filter mask follow, and type, shapes and smart objects re-render. The document /// selection is left alone. pub(crate) fn transform_by(doc: &mut Document, id: LayerId, affine: Affine, interp: Interp) -> Result<()> { - let h = crate::smart_cmds::affine_homography(&affine); + transform_by_map(doc, id, &crate::smart_cmds::affine_homography(&affine), Some(affine), interp) +} + +/// [`transform_by`] with the map already built, and `affine` only when it is affine (Distort and +/// Perspective results aren't: their smart object keeps the full projective placement). +pub(crate) fn transform_by_map(doc: &mut Document, id: LayerId, h: &Homography, affine: Option, interp: Interp) -> Result<()> { let group = group_locks(doc, id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; // Price the smart object caches before they are taken: the fallback warp below isn't budgeted. - check_layer_budget(None, l, &h)?; + check_layer_budget(None, l, h)?; let taken = crate::smart_cmds::take_caches(std::slice::from_mut(l)); - apply_transform(None, group, l, &h, Some(affine), interp, &Interrupt::NONE)?; + apply_transform(None, group, l, h, affine, interp, &Interrupt::NONE)?; let snapshot = doc.clone(); if let Some(l) = doc.layer_mut(id) { refresh_text(&snapshot, l); } - crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), &h, interp))?; + crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), h, interp))?; Ok(()) } diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 47394823d6..5a44943345 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -653,6 +653,9 @@ fn stroke_path_simulate_pressure_tapers_both_ends() { let coverage = |simulate: bool, x: i32| -> usize { let mut s = session(200, 60, 8); s.execute("layer.new.layer", json!({})).unwrap(); + // Simulate Pressure tapers a brush that follows pen pressure; the default brush stopped + // doing that on its own (#11809). + s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap(); s.execute("path.set", json!({"path": {"subpaths": [{"closed": false, "knots": [[20, 30], [180, 30]]}]}})).unwrap(); let p = json!({"tool": "brush", "size": 20, "hardness": 1.0, "color": "#000000", "opacity": 100, "simulatePressure": simulate}); s.execute("path.stroke", p).unwrap(); diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 3b1a631c81..dde11a8f2a 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -14,6 +14,36 @@ use crate::{EngineError, Result, Session}; /// Maximum dense RGBA staging pixels in one animated GIF frame. A GIF also keeps the /// quantised frame and palette while rendering, so the document canvas limit is not enough. const MAX_GIF_FRAME_PIXELS: u64 = 64 << 20; +/// Largest total an animated GIF render keeps staged before encoding: one index byte per pixel plus +/// a 768-byte palette for every frame, the same 2 GiB bound as imported footage ([`MAX_FOOTAGE_BYTES`]). +/// The per-frame cap alone lets `frames × pixels` reach terabytes (a 4000 × 4000 canvas over a +/// 1,000,000-frame timeline). 1920 × 1080 holds about 2,145 frames and 4096 × 2160 about 242. +/// This bounds the staged frames only (indices and palettes). It does not bound the encoder's output +/// buffer (LZW data, roughly 1.3-1.5 times the raw size, growing by doubling) or the per-frame +/// transients (RGBA f32, 16 bytes per pixel), so it is not a bound on peak memory. +const MAX_GIF_STAGED_BYTES: u64 = MAX_FOOTAGE_BYTES; +/// The GIF format stores each side as 16 bits. +const MAX_GIF_SIDE: u64 = 65_535; + +/// Reject a GIF render whose canvas or frames-times-canvas staging would be unreasonable, before any +/// frame is rendered. All sums are checked in `u64`. +fn check_gif_budget(w: u64, h: u64, frames: u64) -> std::result::Result<(), String> { + if w > MAX_GIF_SIDE || h > MAX_GIF_SIDE { + return Err(format!("{w} × {h} is too large to render as an animated GIF (the GIF format allows {MAX_GIF_SIDE} pixels per side)")); + } + let pixels = w.checked_mul(h).filter(|p| *p <= MAX_GIF_FRAME_PIXELS); + let Some(pixels) = pixels else { + return Err(format!("{w} × {h} is too large to render as an animated GIF (limit {MAX_GIF_FRAME_PIXELS} pixels per frame)")); + }; + let per_frame = pixels + 768; + if frames.checked_mul(per_frame).is_none_or(|total| total > MAX_GIF_STAGED_BYTES) { + return Err(format!( + "{frames} frames of {w} × {h} are too large to render as an animated GIF (limit {} MiB staged in total); shorten the timeline or reduce the canvas", + MAX_GIF_STAGED_BYTES >> 20 + )); + } + Ok(()) +} /// Set every video layer's displayed content to its frame at the playhead. pub fn sync(doc: &mut Document) { @@ -638,11 +668,9 @@ pub fn render_video_with( // Animated GIF: one file, every frame quantised to its own palette. if format.eq_ignore_ascii_case("gif") { - // The whole canvas is staged as f32 RGBA for each frame; reject over-budget - // dimensions before an infallible allocation can abort the process. - if (w as u64) * (h as u64) > MAX_GIF_FRAME_PIXELS { - return Err(EngineError::Other(format!("{w} × {h} is too large to render as an animated GIF (limit {MAX_GIF_FRAME_PIXELS} pixels per frame)"))); - } + // Each frame is staged as f32 RGBA and every encoded frame is kept until the file is written; + // reject over-budget sizes before an infallible allocation can abort the process. + check_gif_budget(w as u64, h as u64, frames as u64).map_err(EngineError::Other)?; let delay = (100.0 / fps).round().clamp(1.0, 65535.0) as u16; let mut gframes = Vec::with_capacity(frames); for f in 0..frames { diff --git a/crates/engine/src/cmd/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs index a5e2f5db9c..2038f07ee2 100644 --- a/crates/engine/src/cmd/video_cmds/tests.rs +++ b/crates/engine/src/cmd/video_cmds/tests.rs @@ -916,6 +916,33 @@ fn render_video_rejects_gif_frames_too_large_to_stage() { assert!(err.to_string().contains("too large"), "{err}"); } +#[test] +fn render_video_rejects_a_gif_whose_frames_together_are_too_large() { + // Each 4000 x 4000 frame is under the per-frame cap, but 100,000 of them keep ~1.6 TB staged. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4000, "height": 4000})).unwrap(); + s.execute("timeline.create", json!({"duration": 100_000, "fps": 30})).unwrap(); + let err = s.execute("file.export.renderVideo", json!({"dir": tmpdir("many-gif"), "format": "gif"})).unwrap_err(); + assert!(err.to_string().contains("staged in total"), "{err}"); +} + +#[test] +fn gif_budget_boundaries() { + // Sane work is untouched: a minute of 1080p at 30 fps, and the existing small cases. + assert!(check_gif_budget(1920, 1080, 1000).is_ok()); + assert!(check_gif_budget(16, 12, 1).is_ok()); + // Exactly at the limit passes, one frame more fails. + let per_frame = 1000 * 1000 + 768; + let n = MAX_GIF_STAGED_BYTES / per_frame; + assert!(check_gif_budget(1000, 1000, n).is_ok()); + assert!(check_gif_budget(1000, 1000, n + 1).is_err()); + // The per-frame cap and the 16-bit GIF side still apply, and nothing overflows. + assert!(check_gif_budget(9000, 8000, 1).is_err()); + assert!(check_gif_budget(65_536, 1, 1).is_err()); + assert!(check_gif_budget(65_535, 65_535, u64::MAX).is_err()); + assert!(check_gif_budget(1, 1, u64::MAX).is_err()); +} + #[test] fn fps_from_delays_picks_most_common_and_breaks_ties_by_first_seen() { // Most common delay wins: 100 ms appears twice, 40 ms once -> 10 fps. diff --git a/crates/engine/src/cmd/web_cmds.rs b/crates/engine/src/cmd/web_cmds.rs index 3bd4f5a6c3..624250e509 100644 --- a/crates/engine/src/cmd/web_cmds.rs +++ b/crates/engine/src/cmd/web_cmds.rs @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Save for Web (Legacy)…", &["File", "Export"], Some("Cmd+Alt+Shift+S"), - r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp|webp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60 (JPEG, lossy WebP),"lossless":bool=false (WebP),"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"folder":folder? (whole image, named after the document; ignored with "path" or "dir"),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, + r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp|webp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60 (JPEG, lossy WebP),"lossless":bool=false (WebP),"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"folder":folder? (whole image, named after the document; ignored with "path" or "dir"),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user|selected"="all" (selected requires numbers when the document has slices),"numbers":[n]? (slice numbers, each an existing slice; chooses the slices whatever the mode; with `path` or `folder` alone on a document with slices, refused: use `dir`)} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, has_doc, save_for_web ), diff --git a/crates/engine/src/cmd/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs index cac6a15e5c..af655df8d7 100644 --- a/crates/engine/src/cmd/web_cmds/save_web.rs +++ b/crates/engine/src/cmd/web_cmds/save_web.rs @@ -167,6 +167,57 @@ fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) { }); } +/// Which slices an export writes. +enum SlicePick { + All, + User, + Numbers(Vec), +} + +/// The slices chosen by `slices` (`all|user|selected`) and `numbers`. Photoshop's dialog can +/// only select slices it shows, so a script naming one that doesn't exist, an unknown mode, or +/// Selected Slices with nothing selected is refused rather than exporting too few or too many +/// files. A document without slices is one image whatever the mode, as in the dialog. +fn slice_pick(p: &Value, cmd: &str, doc: &photocraft_doc::Document) -> Result { + let mode = match p.get("slices") { + None | Some(Value::Null) => "all", + Some(Value::String(m)) if matches!(m.as_str(), "all" | "user" | "selected") => m.as_str(), + Some(v) => return Err(bad(cmd, format!("unknown slices `{}` (all|user|selected)", v.as_str().map_or_else(|| v.to_string(), str::to_string)))), + }; + let Some(numbers) = p.get("numbers").filter(|v| !v.is_null()) else { + return match mode { + "selected" if !doc.slices.is_empty() => Err(bad(cmd, "no slices are selected: Selected Slices needs `numbers`")), + "user" => Ok(SlicePick::User), + _ => Ok(SlicePick::All), + }; + }; + let numbers: Vec = numbers + .as_array() + .filter(|a| !a.is_empty()) + .and_then(|a| a.iter().map(Value::as_u64).collect()) + .ok_or_else(|| bad(cmd, "numbers must be a list of slice numbers"))?; + let count = slices::resolve(doc).len(); + let mut missing: Vec = numbers.iter().copied().filter(|n| !(1..=count as u64).contains(n)).collect(); + missing.sort_unstable(); + missing.dedup(); + if !missing.is_empty() { + let list = missing.iter().map(u64::to_string).collect::>().join(", "); + let what = if missing.len() == 1 { "slice" } else { "slices" }; + return Err(bad(cmd, format!("no {what} numbered {list} (the document's slices are 1–{count})"))); + } + // `path` alone is the whole image in one file (with `slices` too, the slices go next to it): + // the chosen slices would be ignored, so a document with slices refuses it. + let given = |k: &str| p.get(k).and_then(Value::as_str).is_some_and(|v| !v.is_empty()); + if given("path") && !given("dir") && matches!(p.get("slices"), None | Some(Value::Null)) && count > 1 { + return Err(bad(cmd, "`path` writes the whole image as one file: to export the slices in `numbers`, use `dir`")); + } + // `folder` alone (#5305) is the whole image too, under the document's name. + if given("folder") && !given("path") && !given("dir") && count > 1 { + return Err(bad(cmd, "`folder` writes the whole image as one file: to export the slices in `numbers`, use `dir`")); + } + Ok(SlicePick::Numbers(numbers)) +} + fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result { let cmd = "file.export.saveForWebLegacy"; if let Some(authorize) = s.authorize { @@ -174,6 +225,8 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u } // Settings are checked first, so a refused export leaves a floating selection where it is. let st = WebSettings::from_params(p, cmd)?; + // So are the slices: committing a floating move doesn't change them. + let pick = slice_pick(p, cmd, &s.active().ok_or(EngineError::NoDocument)?.doc)?; // Direct platform calls must export the moved selection as it appears on the canvas, // just as Session::execute does before dispatching the native command. crate::float_cmds::before_command(s, cmd)?; @@ -191,16 +244,12 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u let dpi = wdoc.resolution_dpi; let warnings = web_warnings(&st, exif, dpi); let all = slices::resolve(&doc); - let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); - let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); - let chosen: Vec<&ResolvedSlice> = all - .iter() - .filter(|r| match (&numbers, pick) { - (Some(n), _) => n.contains(&(r.number as u64)), - (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto, - _ => true, - }) - .collect(); + let picked = |r: &ResolvedSlice| match &pick { + SlicePick::Numbers(n) => n.contains(&(r.number as u64)), + SlicePick::User => r.origin != photocraft_doc::SliceOrigin::Auto, + SlicePick::All => true, + }; + let chosen: Vec<&ResolvedSlice> = all.iter().filter(|r| picked(r)).collect(); let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()); let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()); // `folder` (with no `path` or `dir`): the whole image into that folder under the document's @@ -265,13 +314,20 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u }; // Slices never overlap here: one covered by later slices comes as its visible pieces (see // `slices::resolve`), each its own image and cell, as Photoshop's subslices. A no-image cell's - // text goes into its first piece only. + // text goes into its first piece only. In the HTML, a slice that isn't exported stays as an + // empty cell, so the exported ones keep their place in the table. let mut texted = std::collections::HashSet::new(); - for r in &chosen { + for r in &all { let piece = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds()); if piece.is_empty() { continue; } + if !picked(r) { + if html { + cells.push((piece, String::new(), String::new())); + } + continue; + } let stored = r.id.and_then(|id| doc.slices.get(id)); if r.kind == SliceKind::NoImage { let text = stored diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index e887b92930..82c2a6c5a9 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -1417,3 +1417,169 @@ fn folder_saves_under_the_documents_own_name() { assert_eq!(r["files"], json!([format!("{dir}/named.png")])); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn selected_slices_keep_their_place_in_the_html_table() { + // CodeRabbit review on PR #10557: exporting only the right of two slices put its image in + // the table's first column, on the left. Unexported slices stay as empty cells. + let dir = tmp("selected-html"); + let mut s = session(8); + s.execute("slice.new", json!({"rect": [0, 0, 32, 48], "name": "left"})).unwrap(); + s.execute("slice.new", json!({"rect": [32, 0, 32, 48], "name": "right"})).unwrap(); + let right = photocraft_doc::slices::resolve(&s.active().unwrap().doc).iter().find(|r| r.name == "right").unwrap().number; + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true, "numbers": [right]})).unwrap(); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap()).collect(); + assert_eq!(files, ["right.png"]); + let page = std::fs::read_to_string(r["html"].as_str().unwrap()).unwrap(); + let row = &page[page.find("").unwrap()..page.find("").unwrap()]; + let cells: Vec<&str> = row.split("= 2, "{row}"); + assert!(!cells[0].contains("images/right.png"), "the right slice is in column 0:\n{row}"); + assert!(cells[1].contains("images/right.png"), "column 1:\n{row}"); +} + +/// Two side-by-side user slices, `left` and `right`, and their numbers. +fn two_slices() -> (Session, u64, u64) { + let mut s = session(8); + s.execute("slice.new", json!({"rect": [0, 0, 32, 48], "name": "left"})).unwrap(); + s.execute("slice.new", json!({"rect": [32, 0, 32, 48], "name": "right"})).unwrap(); + let all = photocraft_doc::slices::resolve(&s.active().unwrap().doc); + let number = |name: &str| all.iter().find(|r| r.name == name).unwrap().number as u64; + (s, number("left"), number("right")) +} + +/// A refused slice export writes and remembers nothing, and (called directly, as the platform +/// writer is) leaves a floating move in place. +fn assert_refused(s: &mut Session, dir: &str, p: Value, expect: &str) { + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + s.execute("select.float", json!({"dx": 32})).unwrap(); + let mut written = Vec::new(); + let err = save_for_web_with_writer(s, &p, &mut |path, _| { + written.push(path.to_string()); + Ok(()) + }) + .unwrap_err() + .to_string(); + assert!(err.contains(expect), "{p}: {err}"); + assert_eq!(written, Vec::::new(), "{p}: nothing written"); + assert!(s.file_menu.last_web.is_none(), "{p}: nothing remembered"); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "{p}: the floating move is not committed"); + let err = s.execute("file.export.saveForWebLegacy", p.clone()).unwrap_err().to_string(); + assert!(err.contains(expect), "{p}: {err}"); + assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0, "{p}: nothing written"); +} + +#[test] +fn slice_numbers_that_do_not_exist_are_refused() { + // FredApps review on PR #10557: a number naming no slice was dropped, so an export of only + // missing numbers "succeeded" with no files and a page of empty cells. Photoshop's dialog + // can only select existing slices; a script naming others is refused. + let dir = tmp("missing-numbers"); + let (mut s, left, right) = two_slices(); + let count = photocraft_doc::slices::resolve(&s.active().unwrap().doc).len() as u64; + let (gone, also_gone) = (count + 1, count + 7); + assert_refused(&mut s, &dir, json!({"format": "png24", "dir": dir, "html": true, "numbers": [gone]}), &format!("no slice numbered {gone}")); + // Partly missing: the dialog builds `numbers` from slices it shows, so every number it sends + // exists; one that doesn't is a stale or mistyped script and the export is refused whole. + let err = s + .execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true, "numbers": [left, also_gone, right, gone]})) + .unwrap_err() + .to_string(); + assert!(err.contains(&format!("no slices numbered {gone}, {also_gone}")), "{err}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written"); + // Slice numbers start at 1. + let err = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "numbers": [0]})).unwrap_err().to_string(); + assert!(err.contains("no slice numbered 0"), "{err}"); + // Existing numbers still export exactly those slices. + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "numbers": [right, left]})).unwrap(); + let mut files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap()).collect(); + files.sort_unstable(); + assert_eq!(files, ["left.png", "right.png"]); +} + +#[test] +fn slice_modes_are_validated() { + // FredApps review on PR #10557: any `slices` value but "user" exported every slice, + // including the dialog's "selected" without `numbers`. + let dir = tmp("slice-modes"); + let (mut s, left, right) = two_slices(); + for (p, expect) in [ + (json!({"slices": "selcted"}), "unknown slices `selcted` (all|user|selected)"), + (json!({"slices": 2}), "unknown slices `2` (all|user|selected)"), + (json!({"slices": "selected"}), "no slices are selected"), + (json!({"slices": "selected", "numbers": []}), "numbers must be a list of slice numbers"), + (json!({"numbers": ["1"]}), "numbers must be a list of slice numbers"), + (json!({"numbers": 1}), "numbers must be a list of slice numbers"), + ] { + let mut p = p; + p["format"] = json!("png24"); + p["dir"] = json!(dir); + assert_refused(&mut s, &dir, p, expect); + } + // Every valid call still works. + let count = photocraft_doc::slices::resolve(&s.active().unwrap().doc).len(); + let names = |r: &Value| r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect::>(); + for (mode, expect) in [(json!(null), count), (json!("all"), count), (json!("user"), 2)] { + let out = tmp("slice-modes-ok"); + let mut p = json!({"format": "png24", "dir": out}); + if !mode.is_null() { + p["slices"] = mode.clone(); + } + assert_eq!(names(&s.execute("file.export.saveForWebLegacy", p).unwrap()).len(), expect, "{mode}"); + } + let out = tmp("slice-modes-selected"); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": out, "slices": "selected", "numbers": [right]})).unwrap(); + assert_eq!(names(&r), ["right.png"]); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": out, "slices": "user", "numbers": [left]})).unwrap(); + assert_eq!(names(&r), ["left.png"], "numbers choose the slices whatever the mode"); + // A document without slices exports the whole image as one, whatever the dialog's Slices + // choice: the dialog sends "selected" without numbers then (`web_params`). + let mut s = session(8); + for mode in ["all", "user", "selected"] { + let out = tmp("slice-modes-none"); + if mode != "user" { + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": out, "slices": mode})).unwrap(); + assert_eq!(names(&r), ["web.png"], "{mode}"); + assert_eq!(decode(r["files"][0].as_str().unwrap()).dimensions(), (64, 48), "{mode}"); + } + let path = format!("{out}/whole.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": path, "slices": mode})).unwrap(); + assert_eq!(decode(&path).dimensions(), (64, 48), "{mode}"); + } +} + +#[test] +fn a_whole_image_path_with_slice_numbers_is_refused() { + // CodeRabbit review on PR #10557: `path` alone writes the whole image as one file, so slice + // `numbers` with it were ignored and every slice came out in that file. It is refused; `dir` + // exports the chosen slices. + let dir = tmp("path-numbers"); + let (mut s, left, right) = two_slices(); + let path = format!("{dir}/web.png"); + assert_refused(&mut s, &dir, json!({"format": "png24", "path": path, "numbers": [right]}), "use `dir`"); + assert_refused(&mut s, &dir, json!({"format": "png24", "path": path, "dir": "", "numbers": [left, right]}), "use `dir`"); + // `folder` alone is the whole image under the document's name (#5305): refused the same way. + assert_refused(&mut s, &dir, json!({"format": "png24", "folder": dir, "numbers": [right]}), "use `dir`"); + // An explicit null `slices` is the default mode, as if absent. + assert_refused(&mut s, &dir, json!({"format": "png24", "path": path, "slices": null, "numbers": [right]}), "use `dir`"); + // Valid calls still work: `path` alone is the whole image; with `slices`, the chosen slices + // go next to it; `dir` with `numbers` writes those slices. + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": path})).unwrap(); + assert_eq!(r["files"], json!([path])); + assert_eq!(decode(&path).dimensions(), (64, 48)); + let names = |r: &Value| r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect::>(); + let out = tmp("path-numbers-selected"); + let r = s + .execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": format!("{out}/web.png"), "slices": "selected", "numbers": [right]})) + .unwrap(); + assert_eq!(names(&r), ["right.png"]); + let out = tmp("path-numbers-dir"); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": format!("{out}/web.png"), "dir": out, "numbers": [left]})).unwrap(); + assert_eq!(names(&r), ["left.png"]); + // A document without slices is one image: its only slice number is the whole image. + let mut s = session(8); + let out = tmp("path-numbers-none"); + let whole = format!("{out}/whole.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": whole, "numbers": [1]})).unwrap(); + assert_eq!(decode(&whole).dimensions(), (64, 48)); +} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ba82bd9028..8654a38507 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1042,7 +1042,10 @@ impl Session { /// Run a command, in the background when it supports it (see [`jobs`](crate::jobs)). Errors /// like [`Session::execute`] for unknown, disabled or failing commands. pub fn start(&mut self, id: &str, params: Value) -> Result { - self.dispatch(id, params, true) + let before = self.active_layer_stamp(); + let started = self.dispatch(id, params, true); + self.note_layer_change(before); + started } pub const MAX_PENDING_PREFLIGHTS: usize = 32; @@ -1924,7 +1927,13 @@ impl Session { } /// Apply (or report the failure of) a job whose worker has delivered `r`. - fn finish_job(&mut self, mut job: Running, r: Result) { + fn finish_job(&mut self, job: Running, r: Result) { + let before = self.active_layer_stamp(); + self.finish_job_step(job, r); + self.note_layer_change(before); + } + + fn finish_job_step(&mut self, mut job: Running, r: Result) { let apply = job.apply.take(); // Keep the typed error beside its display text, so `wait_job` and `JobEvent` can still // report a hard budget's required/limit or an approval request's limits. diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 176f08b264..9bb6ab7693 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -676,6 +676,15 @@ fn overlay_gradient(g: &mut Gradient, p: &Value) { if let Some(x) = b_of(p, "reverse") { g.reverse = x; } + // The gradient's centre as a fraction of the layer's bounds, `[x, y]` (0: centred); a drag on + // the image with the Layer Style dialog on the page moves it (#10763). + if let Some(a) = p.get("offset").and_then(Value::as_array) + && let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) + && x.is_finite() + && y.is_finite() + { + g.offset = (x.clamp(-4.0, 4.0) as f32, y.clamp(-4.0, 4.0) as f32); + } } /// Applies the params present in `p` onto an existing effect, in the command's diff --git a/crates/engine/src/layer_style/gradient_overlay.rs b/crates/engine/src/layer_style/gradient_overlay.rs index ee88cb447d..217f6fd70c 100644 --- a/crates/engine/src/layer_style/gradient_overlay.rs +++ b/crates/engine/src/layer_style/gradient_overlay.rs @@ -200,6 +200,16 @@ mod tests { assert_eq!(gradient.angle, 90.0); assert!(gradient.reverse); assert_eq!(gradient.scale, 0.75); + // The offset (#10763) is geometry too: a fraction of the layer's bounds, left alone by + // junk and clamped. + overlay(&mut gradient, &mut source, &json!({"offset": [0.25, -0.1]})); + assert_eq!(gradient.offset, (0.25, -0.1)); + assert_eq!(gradient.stops, expected); + overlay(&mut gradient, &mut source, &json!({"offset": "far"})); + overlay(&mut gradient, &mut source, &json!({"offset": [f64::NAN, 0.0]})); + assert_eq!(gradient.offset, (0.25, -0.1)); + overlay(&mut gradient, &mut source, &json!({"offset": [100.0, -100.0]})); + assert_eq!(gradient.offset, (4.0, -4.0)); } #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 468efec851..8f28147217 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -216,6 +216,13 @@ pub struct Session { active_generation: u64, /// The document id [`Self::active_generation`] was last bumped for. active_doc_for_generation: Option, + /// Change marker: advances at least once whenever the active document or layer changes through + /// the `Session` API (commands via `execute`, `start` and finished jobs, `select_layer`, + /// `restore_layer_selection`, `layer_multi_cmds::set_selection`, `set_active_layer`, undo / redo / + /// rollback, document switches). Compare two readings for equality to know whether anything + /// changed in between; it is not an exact count of operations (one operation may advance it + /// more than once). Writing `DocState::active_layer` directly bypasses it. + active_layer_changes: u64, pub tools: ToolState, /// Log of executed commands (for action recording and debugging). pub journal: Vec<(String, Value)>, @@ -332,6 +339,8 @@ pub struct Session { pub damage_misses: usize, } +#[cfg(test)] +mod brush_pressure_size_default_tests; #[cfg(test)] mod embed_all_linked_tests; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index ee61af791c..ba36f1f850 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -227,6 +227,10 @@ pub struct General { pub export_clipboard: bool, pub resize_image_during_place: bool, pub always_create_smart_objects_when_placing: bool, + /// Place files without opening Free Transform on them (#8492). Only the interactive place + /// (File ▸ Place, canvas drops) opens Free Transform; `file.placeEmbedded`/`file.placeLinked` + /// run with a `path` (actions, scripts, automation) never do, so this doesn't affect them. + pub skip_transform_when_placing: bool, /// Scroll wheel zooms instead of panning. pub zoom_with_scroll_wheel: bool, /// Wheel zoom eases over the frames of a notch; off, a notch is one instant ×1.1 step. @@ -247,6 +251,7 @@ impl Default for General { export_clipboard: true, resize_image_during_place: true, always_create_smart_objects_when_placing: true, + skip_transform_when_placing: false, zoom_with_scroll_wheel: false, animated_zoom: true, zoom_resizes_windows: false, @@ -1296,6 +1301,10 @@ pub struct Preferences { /// Last selected tool, restored at launch. A tool-name string owned and validated by the /// shell; null in older files. Kept separate from tool options so neither overwrites the other. pub selected_tool: Value, + /// The tools used last, most recent first, restored at launch so each toolbar slot shows the + /// tool it was left on and each tool key brings it back, as in Photoshop (#3569). Tool-name + /// strings owned and validated by the shell; null in older files. + pub group_tools: Value, /// View › Extras, the View › Show items (Pixel Grid, Grid, Guides, …) and the View › Snap To /// targets that differ from their defaults, saved as the user toggles them and restored at /// launch, as Photoshop keeps them between sessions (#3762). JSON owned by the shell. diff --git a/crates/engine/src/proof_sim.rs b/crates/engine/src/proof_sim.rs index c7e8bcabf0..f87c77f5fd 100644 --- a/crates/engine/src/proof_sim.rs +++ b/crates/engine/src/proof_sim.rs @@ -307,8 +307,8 @@ pub fn specs() -> Vec { kind_spec!("view.proofSetup.workingBlackPlate", "Working Black Plate"), kind_spec!("view.proofSetup.workingCmyPlate", "Working CMY Plates"), kind_spec!("view.proofSetup.legacyMacintoshRgb", "Legacy Macintosh RGB (Gamma 1.8)"), - kind_spec!("view.proofSetup.colorBlindnessProtanopia", "Color Blindness — Protanopia-type"), - kind_spec!("view.proofSetup.colorBlindnessDeuteranopia", "Color Blindness — Deuteranopia-type"), + kind_spec!("view.proofSetup.colorBlindnessProtanopia", "Color Blindness - Protanopia-type"), + kind_spec!("view.proofSetup.colorBlindnessDeuteranopia", "Color Blindness - Deuteranopia-type"), CommandSpec { id: "view.thirtyTwoBitPreviewOptions", label: "32-bit Preview Options…", diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7cef2be12e..49f8205079 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -1,7 +1,7 @@ use crate::{EngineError, Result}; use super::history::fix_selection; -use super::{DocState, Document, Session, channel_cmds, smart_cmds}; +use super::{DocState, Document, LayerId, Session, channel_cmds, smart_cmds}; /// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when /// `i` is out of range. @@ -43,16 +43,48 @@ impl Session { self.active_generation } + /// Change marker: advances at least once whenever the active document or layer changes through + /// the `Session` API (see the field). Compare two readings for equality to know whether anything + /// changed in between; it is not an exact count of operations. A direct write to + /// `DocState::active_layer` through `active_mut()` bypasses it. + pub fn active_layer_changes(&self) -> u64 { + self.active_layer_changes + } + /// Bump [`Self::active_generation`] when the active document id changed. Call after every /// assignment to `self.active`. pub(crate) fn note_active_change(&mut self) { let id = self.active().map(|st| st.doc.id); if id != self.active_doc_for_generation { + self.active_layer_changes = self.active_layer_changes.wrapping_add(1); self.active_doc_for_generation = id; self.active_generation = self.active_generation.wrapping_add(1); } } + /// The active document and its active layer, for [`Self::note_layer_change`]. + pub(crate) fn active_layer_stamp(&self) -> Option<(photocraft_doc::DocId, Option)> { + self.active().map(|st| (st.doc.id, st.active_layer)) + } + + /// Count a change of the active document or layer since `before` (from + /// [`Self::active_layer_stamp`]). Every path that can change either calls this after it. + pub(crate) fn note_layer_change(&mut self, before: Option<(photocraft_doc::DocId, Option)>) { + if self.active_layer_stamp() != before { + self.active_layer_changes = self.active_layer_changes.wrapping_add(1); + } + } + + /// Make `layer` the active document's active layer and nothing else (the selection list and + /// anchor are left as they are), counted in [`Self::active_layer_changes`]. + pub fn set_active_layer(&mut self, layer: Option) { + let before = self.active_layer_stamp(); + if let Some(st) = self.active_mut() { + st.active_layer = layer; + } + self.note_layer_change(before); + } + pub fn set_active(&mut self, index: usize) -> bool { if index < self.docs.len() { self.active = Some(index); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 3577f5e1df..5522f5fc5c 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -15,7 +15,10 @@ impl Session { /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs /// those in the background). pub fn execute(&mut self, id: &str, params: Value) -> Result { - match self.dispatch(id, params, false)? { + let before = self.active_layer_stamp(); + let result = self.dispatch(id, params, false); + self.note_layer_change(before); + match result? { jobs::Started::Done(v) => Ok(v), // Not reached: inline dispatch never starts a job. Waiting is still correct. jobs::Started::Job(j) => self.wait_job(j), diff --git a/crates/engine/src/session/history.rs b/crates/engine/src/session/history.rs index c5f9cd301c..01a90a169f 100644 --- a/crates/engine/src/session/history.rs +++ b/crates/engine/src/session/history.rs @@ -4,6 +4,13 @@ use super::{Arc, DocState, Document, LayerId, LayerTarget, Session, channel_cmds impl Session { /// Undo a document step or restore Clear History's rows and source without editing pixels. pub fn undo(&mut self) -> bool { + let before = self.active_layer_stamp(); + let taken = self.undo_step(); + self.note_layer_change(before); + taken + } + + fn undo_step(&mut self) -> bool { // A background job is computing from the current state: it must not move under it. if self.active_job().is_some() { return false; @@ -55,6 +62,13 @@ impl Session { /// Restore the next document state and its selection/visibility bookkeeping through the ordinary history path. pub fn redo(&mut self) -> bool { + let before = self.active_layer_stamp(); + let taken = self.redo_step(); + self.note_layer_change(before); + taken + } + + fn redo_step(&mut self) -> bool { if self.active_job().is_some() { return false; } @@ -92,6 +106,13 @@ impl Session { /// last of them). Falls back to Undo plus forgetting the redo states when the history /// changed since that step. Returns whether a step was taken back. pub fn rollback(&mut self) -> bool { + let before = self.active_layer_stamp(); + let taken = self.rollback_step(); + self.note_layer_change(before); + taken + } + + fn rollback_step(&mut self) -> bool { if self.active_job().is_some() { return false; } diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs index 4511b7fbf1..d7f8ed9997 100644 --- a/crates/engine/src/session/layers.rs +++ b/crates/engine/src/session/layers.rs @@ -5,6 +5,7 @@ use crate::TypeLayerRef; impl Session { /// Replace the active document's active layer without creating a history step. pub fn select_layer(&mut self, id: LayerId) -> Result<()> { + let before = self.active_layer_stamp(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; if st.doc.layer(id).is_none() { return Err(EngineError::NoLayer(id)); @@ -20,6 +21,7 @@ impl Session { st.saved_revision = st.revision; } st.last_damage = Some(photocraft_geom::Rect::EMPTY); + self.note_layer_change(before); Ok(()) } @@ -28,6 +30,7 @@ impl Session { /// is no layer selected. Selected layers that are gone are dropped; an active layer that is /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { + let before = self.active_layer_stamp(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; if let Some(id) = active && st.doc.layer(id).is_none() @@ -45,6 +48,7 @@ impl Session { st.saved_revision = st.revision; } st.last_damage = Some(photocraft_geom::Rect::EMPTY); + self.note_layer_change(before); Ok(()) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 599d0ce2d6..8f82376a3a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1986,3 +1986,59 @@ fn the_document_activation_generation_bumps_on_switch_and_back() { assert_eq!(s.active_generation(), g3); assert_eq!(s.active().unwrap().doc.id, first); } + +#[test] +fn the_active_layer_change_count_moves_only_when_a_command_changes_the_active_layer() { + let mut s = session_with_doc(); + s.execute("layer.new.layer", json!({})).unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + let n = s.active_layer_changes(); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + assert_eq!(s.active_layer_changes(), n, "selecting the active layer again changes nothing"); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + assert!(s.active_layer_changes() > n); + let m = s.active_layer_changes(); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + assert!(s.active_layer_changes() >= m + 2, "a round trip back to the same layer still counts"); +} + +#[test] +fn direct_selection_calls_count_active_layer_changes_only_when_the_layer_changes() { + let mut s = session_with_doc(); + s.execute("layer.new.layer", json!({})).unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + let count = |s: &Session| s.active_layer_changes(); + let n = count(&s); + s.select_layer(b).unwrap(); + assert_eq!(count(&s), n, "select_layer of the active layer"); + s.select_layer(a).unwrap(); + assert_eq!(count(&s), n + 1, "select_layer of another layer"); + s.restore_layer_selection(Some(a), &[a], Some(a)).unwrap(); + assert_eq!(count(&s), n + 1, "restore_layer_selection of the same active layer"); + s.restore_layer_selection(Some(b), &[b], Some(b)).unwrap(); + assert_eq!(count(&s), n + 2, "restore_layer_selection of another layer"); + layer_multi_cmds::set_selection(&mut s, vec![b], Some(b), Some(b)).unwrap(); + assert_eq!(count(&s), n + 2, "set_selection of the same active layer"); + layer_multi_cmds::set_selection(&mut s, vec![a], Some(a), Some(a)).unwrap(); + assert_eq!(count(&s), n + 3, "set_selection of another layer"); + s.set_active_layer(Some(a)); + assert_eq!(count(&s), n + 3, "set_active_layer of the same layer"); + s.set_active_layer(Some(b)); + assert_eq!(count(&s), n + 4, "set_active_layer of another layer"); +} + +#[test] +fn the_active_layer_marker_advances_for_a_new_document_and_not_for_a_same_layer_select() { + let mut s = session_with_doc(); + let before = s.active_layer_changes(); + let id = s.active().unwrap().active_layer.unwrap(); + s.select_layer(id).unwrap(); + assert_eq!(s.active_layer_changes(), before, "re-selecting the active layer leaves the marker alone"); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert!(s.active_layer_changes() > before, "a new active document advances the marker"); +} diff --git a/crates/engine/tests/magnetic_lasso_composite.rs b/crates/engine/tests/magnetic_lasso_composite.rs new file mode 100644 index 0000000000..898e62e2e9 --- /dev/null +++ b/crates/engine/tests/magnetic_lasso_composite.rs @@ -0,0 +1,125 @@ +//! The Magnetic Lasso follows the edges of the visible composite, whichever layer is active +//! (#11686), in the live `EdgeSource` and in `select.magneticLasso` with `trace: true`. + +use photocraft_algo::magnetic::Settings; +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use photocraft_engine::magnetic_cmds::EdgeSource; +use photocraft_geom::Rect; +use serde_json::json; + +/// The red rectangle's pixels: x 50..125, y 40..100, 75 x 60 = 4500 px. +const RED: Rect = Rect { x0: 50, y0: 40, x1: 125, y1: 100 }; +const RED_AREA: f32 = 4500.0; +/// Fastening points 4 px outside the rectangle's corners. +const OUTSIDE: [[f64; 2]; 4] = [[46.0, 36.0], [129.0, 36.0], [129.0, 104.0], [46.0, 104.0]]; + +struct Doc { + s: Session, + background: LayerId, + red: LayerId, +} + +/// A 200 x 150 RGB document: a white Background and a layer above it filled red over `RED`. The +/// red layer is active. +fn doc() -> Doc { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150})).unwrap(); + let background = s.active().unwrap().doc.layers[0].id; + s.edit("paint", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 150), &[1.0, 1.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let red = s.active().unwrap().active_layer.unwrap(); + assert_ne!(red, background); + s.edit("paint", |doc, _| { + doc.layer_mut(red).unwrap().surface_mut().unwrap().fill_rect(RED, &[0.86, 0.12, 0.12, 1.0]); + Ok(()) + }) + .unwrap(); + Doc { s, background, red } +} + +fn select(s: &mut Session, id: LayerId) { + s.execute("layer.select", json!({"layer": id.0})).unwrap(); +} + +fn coverage(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +fn selected_area(s: &Session) -> f32 { + (0..150).flat_map(|y| (0..200).map(move |x| (x, y))).map(|(x, y)| coverage(s, x, y)).sum() +} + +/// Traces a border through `OUTSIDE` and asserts it selected the rectangle, not the points' own +/// quadrilateral (83 x 68 = 5644 px). +fn assert_snaps(s: &mut Session, what: &str) { + s.execute("select.magneticLasso", json!({"points": OUTSIDE, "trace": true})).unwrap(); + let area = selected_area(s); + assert!((area - RED_AREA).abs() < 150.0, "{what}: the border should select the rectangle ({RED_AREA} px), selected {area} px"); + assert!(coverage(s, 52, 42) > 0.99 && coverage(s, 122, 97) > 0.99, "{what}: the rectangle's corners are inside"); + assert!(coverage(s, 48, 70) < 0.01 && coverage(s, 127, 70) < 0.01, "{what}: just outside the rectangle is not selected"); + s.execute("select.deselect", json!({})).unwrap(); +} + +/// Whether a fastening point 4 px outside the rectangle's left edge snaps onto it. +fn edge_snaps(s: &Session) -> bool { + let mut src = EdgeSource::new(s).unwrap(); + let p = src.snap([46.0, 70.0], Settings::default()).unwrap(); + (p[0] - 50.0).abs() < 1.5 +} + +#[test] +fn the_border_snaps_whichever_layer_is_active() { + let mut d = doc(); + assert_snaps(&mut d.s, "the red layer active"); + select(&mut d.s, d.background); + assert_snaps(&mut d.s, "the Background active"); + assert!(edge_snaps(&d.s), "Background active: the live source sees the red layer's edge"); + d.s.execute("layer.new.layer", json!({})).unwrap(); + assert!(d.s.active().unwrap().active_layer.is_some_and(|id| id != d.background && id != d.red)); + assert!(edge_snaps(&d.s), "a new empty layer active"); + assert_snaps(&mut d.s, "a new empty layer active"); +} + +#[test] +fn an_adjustment_or_group_layer_active_snaps_too() { + let mut d = doc(); + d.s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let st = d.s.active().unwrap(); + assert!(st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.surface().is_none())); + assert!(edge_snaps(&d.s), "an adjustment layer active"); + assert_snaps(&mut d.s, "an adjustment layer active"); + select(&mut d.s, d.background); + d.s.execute("layer.new.group", json!({})).unwrap(); + assert!(edge_snaps(&d.s), "an empty group active"); + assert_snaps(&mut d.s, "an empty group active"); +} + +#[test] +fn a_hidden_layer_contributes_no_edges() { + let mut d = doc(); + select(&mut d.s, d.background); + d.s.execute("layer.hideLayers", json!({"layer": d.red.0})).unwrap(); + assert!(!edge_snaps(&d.s), "the hidden red layer has no edge to snap to"); + d.s.execute("select.magneticLasso", json!({"points": OUTSIDE, "trace": true})).unwrap(); + let area = selected_area(&d.s); + // The border follows the pointer: the points' own 83 x 68 quadrilateral. + assert!((area - 5644.0).abs() < 150.0, "selected {area} px"); + // Showing it again brings the edge back, for a source made after the change. + d.s.execute("layer.showLayers", json!({"layer": d.red.0})).unwrap(); + assert!(edge_snaps(&d.s)); +} + +#[test] +fn a_live_source_goes_stale_when_the_composite_changes() { + let mut d = doc(); + select(&mut d.s, d.background); + let src = EdgeSource::new(&d.s).unwrap(); + assert!(src.is_current(&d.s)); + d.s.execute("layer.hideLayers", json!({"layer": d.red.0})).unwrap(); + assert!(!src.is_current(&d.s), "hiding a layer changes what the border follows"); +} diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index c4d8359e18..81f893ee68 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -89,6 +89,11 @@ fn no_command_panics_or_hangs_on_adversarial_params() { json!({"x": -9, "y": -9, "radius": 0, "amount": 0, "angle": 0, "opacity": 0, "scale": 0, "levels": 0, "tolerance": 0, "gamma": 0, "layer": 999999, "channel": 999, "index": 999999, "count": 0}), json!({"x": 1e5, "y": -1e5, "radius": 300, "amount": 300, "angle": 1e5, "opacity": -100, "scale": -5, "gamma": -1}), json!({"points": [], "from": [0, 0], "to": [0, 0], "stops": [], "matrix": [0, 0, 0, 0, 0, 0], "colors": [], "name": "", "mode": "", "style": ""}), + // Color Range and Replace Color samples (#6280): far off the canvas, malformed, and a + // click order that doesn't match them. + json!({"points": [[1e9, -1e9], [0.5, 0.5]], "subtractPoints": [[-1e9, 1e9], [2, 2]], "order": ["+", "-", "x", 5], "localized": true, "range": 0}), + json!({"points": [[3, 3]], "subtractPoints": [[3]], "order": {}, "fuzziness": -1}), + json!({"subtractPoints": "none", "order": ["-"], "labMinimum": [0, 0, 0], "labMaximum": [100, 0, 0]}), ]; let mut bad: Vec = Vec::new(); for spec in command_specs() { diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index a454416dff..09800b34b4 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -21,6 +21,9 @@ //! - **Network shares (macOS):** `sync_all` asks for a full flush to the disk's platters //! (`F_FULLFSYNC`), which SMB shares and some virtual file systems refuse while a plain `fsync` //! works. [`sync_file`] falls back to the plain one there (#1336). +//! - **Hidden flags (network shares):** the temporary file's name never starts with a dot. An SMB +//! server that hides dot files marks one hidden when it is created, the mark survives the +//! rename, and the saved document then doesn't show in Finder (#11624). See [`temp_name`]. //! //! On the web there is no file system: writes go through the platform services (downloads), so //! this module is never reached there; on `wasm32` every call returns the `std` "unsupported" @@ -479,13 +482,53 @@ fn resolve_symlink(path: &Path) -> io::Result { Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: too many levels of symbolic links", path.display()))) } -/// A unique hidden temporary file name to write beside `file` before renaming over it. +/// What every [`temp_name`] ends with. +const TEMP_SUFFIX: &str = ".pcsave.tmp"; + +/// How many characters of the file name a [`temp_name`] keeps. +const TEMP_STEM_CHARS: usize = 64; + +/// A unique temporary file name to write beside `file` before renaming over it: +/// `{file}.{pid}-{n}.pcsave.tmp`. +/// +/// It does not start with a dot of its own, so it is not hidden: an SMB server that hides dot +/// files sets the hidden flag on such a file when it is created, the flag survives the rename, +/// and the saved document would be invisible in Finder (#11624). The cost is that the file shows +/// in a folder listing while a save writes it, and one an interrupted save leaves beside the +/// document stays visible until it is removed (#6604). The +/// process id, counter and suffix keep it apart from the files people name, and it is created +/// with `create_new`, so it can never replace one. Older versions wrote +/// `.{file}.{pid}-{n}.pcsave.tmp`; [`temp_owner`] recognizes both. pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); // Keep the name short: a long file name plus the suffix must stay under NAME_MAX. - let stem: String = file.chars().take(64).collect(); - format!(".{stem}.{}-{n}.pcsave.tmp", std::process::id()) + let stem: String = file.chars().take(TEMP_STEM_CHARS).collect(); + format!("{stem}.{}-{n}{TEMP_SUFFIX}", std::process::id()) +} + +/// The id of the process that wrote `name`, if it is a [`temp_name`]: today's +/// `{file}.{pid}-{n}.pcsave.tmp` or the `.{file}.{pid}-{n}.pcsave.tmp` older versions wrote, so +/// their leftovers are still cleaned up. +pub fn temp_owner(name: &str) -> Option { + let rest = name.strip_suffix(TEMP_SUFFIX)?; + let (stem, ids) = rest.rsplit_once('.')?; + let (pid, n) = ids.split_once('-')?; + // Only a file part `temp_name` writes: at most `TEMP_STEM_CHARS` characters, or one more when + // the first is the dot older versions put in front of them. + let chars = stem.chars().count(); + if chars > TEMP_STEM_CHARS && !(chars == TEMP_STEM_CHARS + 1 && stem.starts_with('.')) { + return None; + } + let stem = stem.strip_prefix('.').unwrap_or(stem); + // Only numbers `temp_name` writes: plain decimal digits with no leading zero (a lone "0" is + // fine), a `u32` pid and the `u64` counter it counts with. Any other name is someone else's + // file, and the sweep must not delete it. + let decimal = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0')); + if stem.is_empty() || !decimal(pid) || !decimal(n) || n.parse::().is_err() { + return None; + } + pid.parse().ok() } fn context(e: io::Error, msg: String) -> io::Error { diff --git a/crates/format/src/atomic/meta.rs b/crates/format/src/atomic/meta.rs index a93a1d124b..1a7c5493b5 100644 --- a/crates/format/src/atomic/meta.rs +++ b/crates/format/src/atomic/meta.rs @@ -274,7 +274,7 @@ pub(crate) fn recover_after_1177( /// **A backup name is not optional.** `ReplaceFile` without one deletes the replaced file before /// the final rename, and documents `ERROR_UNABLE_TO_MOVE_REPLACEMENT`: "the replaced file no /// longer exists and the replacement file exists under its original name" — the user's document -/// gone, its replacement left under a hidden temporary name. With a backup name the same failure +/// gone, its replacement left under a temporary name. With a backup name the same failure /// leaves both files where they were. So this always passes one, and deletes it on the way out. /// /// The failures and what each leaves behind (from the `ReplaceFileW` reference): diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rs index ef2a5475f7..84611d1883 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -663,3 +663,105 @@ fn keeps_the_creation_time_under_a_deny_write_acl() { let _ = exacl::setfacl(&[&p], &[], None); assert_no_temp(&d.0); } + +/// A real file system that records the name of every temporary file a save writes. +#[derive(Default)] +struct TempNames(std::cell::RefCell>); + +impl AtomicFs for TempNames { + fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> { + self.0.borrow_mut().push(tmp.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()); + RealFs.write_new(tmp, bytes) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.rename(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.copy_metadata(from, to) + } +} + +/// #11624: the temporary file a save renames over the document has no leading dot. An SMB share +/// that hides dot files marks such a file hidden when it is created, and the mark stayed on the +/// saved document, so it didn't show in Finder. +#[test] +fn the_temporary_file_is_not_a_dot_file() { + let d = TempDir::new("visible"); + let p = d.0.join("report.psd"); + let fs = TempNames::default(); + atomic_write_with(&fs, NO_RETRY, &p, b"first").unwrap(); + atomic_write_with(&fs, NO_RETRY, &p, b"second").unwrap(); + let names = fs.0.take(); + assert_eq!(names.len(), 2, "{names:?}"); + for name in &names { + assert!(!name.starts_with('.'), "a dot file is hidden on some shares: {name}"); + assert!(name.starts_with("report.psd.") && name.ends_with(".pcsave.tmp"), "{name}"); + assert_eq!(temp_owner(name), Some(std::process::id()), "{name}"); + } + assert_ne!(names[0], names[1]); + assert_eq!(std::fs::read(&p).unwrap(), b"second"); + assert_no_temp(&d.0); +} + +/// #11624: both temp name forms are recognized, so the leftovers of versions that wrote +/// `.{file}.{pid}-{n}.pcsave.tmp` are still cleaned up; nothing else is. +#[test] +fn temp_owner_reads_both_name_forms_and_nothing_else() { + assert_eq!(temp_owner(&temp_name("doc.pcraft")), Some(std::process::id())); + assert_eq!(temp_owner("doc.pcraft.42-7.pcsave.tmp"), Some(42)); + assert_eq!(temp_owner(".doc.pcraft.42-7.pcsave.tmp"), Some(42), "the dot-prefixed form older versions wrote"); + assert_eq!(temp_owner(".hidden.psd.42-0.pcsave.tmp"), Some(42), "a dot file's own temp file"); + assert_eq!(temp_owner("doc.42-18446744073709551615.pcsave.tmp"), Some(42), "the largest counter"); + assert_eq!(temp_owner("doc.0-0.pcsave.tmp"), Some(0), "a lone zero is a number temp_name writes"); + for other in [ + "doc.pcraft", + "doc.pcraft.42-7.tmp", + "doc.42-7.pcsave", + ".42-7.pcsave.tmp", + "doc.x-7.pcsave.tmp", + "doc.+42-7.pcsave.tmp", + "doc.42-.pcsave.tmp", + "doc.42-x.pcsave.tmp", + "doc.42-18446744073709551616.pcsave.tmp", + "doc.4294967296-7.pcsave.tmp", + "doc.42-07.pcsave.tmp", + "doc.42-00.pcsave.tmp", + "doc.042-7.pcsave.tmp", + "doc.00-7.pcsave.tmp", + "doc.42.pcsave.tmp", + "42-7.pcsave.tmp", + ] { + assert_eq!(temp_owner(other), None, "{other}"); + } +} + +/// A recovery folder can hold someone else's file that only looks like a temp name. `temp_name` +/// keeps at most 64 characters (not bytes) of the file name, and older versions put one dot in +/// front of them, so a longer file part is not a leftover of a save and the sweep must keep it. +#[test] +fn temp_owner_takes_only_a_file_part_temp_name_writes() { + let pid = Some(std::process::id()); + for file in ["a".repeat(200), "🚀".repeat(70), format!(".{}", "a".repeat(100))] { + assert_eq!(temp_owner(&temp_name(&file)), pid, "{file}"); + } + let today = |stem: &str| format!("{stem}.42-7.pcsave.tmp"); + let older = |stem: &str| format!(".{stem}.42-7.pcsave.tmp"); + for c in ["a", "é", "🚀"] { + let (at, over) = (c.repeat(64), c.repeat(65)); + assert_eq!(temp_owner(&today(&at)), Some(42), "64 characters: {c}"); + assert_eq!(temp_owner(&older(&at)), Some(42), "64 characters after the old dot: {c}"); + assert_eq!(temp_owner(&today(&over)), None, "65 characters: {c}"); + assert_eq!(temp_owner(&older(&over)), None, "65 characters after the old dot: {c}"); + // A dot file's own dot counts in its 64 characters; the old form adds one more dot. + let dotted = |k: usize| format!(".{}", c.repeat(k)); + assert_eq!(temp_owner(&today(&dotted(63))), Some(42), "a dot file today: {c}"); + assert_eq!(temp_owner(&older(&dotted(63))), Some(42), "a dot file in the old form: {c}"); + assert_eq!(temp_owner(&older(&dotted(64))), None, "a dot file one character over: {c}"); + } +} diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs index 2ab8676c66..85798bea7d 100644 --- a/crates/format/src/autosave.rs +++ b/crates/format/src/autosave.rs @@ -473,10 +473,8 @@ fn sweep_orphans(recovery_dir: &Path, min_age: std::time::Duration) { #[cfg(not(target_arch = "wasm32"))] fn sweep_temp_file(path: &Path, min_age: std::time::Duration) { let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return }; - // `.{stem}.{pid}-{n}.pcsave.tmp` - let Some(rest) = name.strip_prefix('.').and_then(|n| n.strip_suffix(".pcsave.tmp")) else { return }; - let Some((_, owner)) = rest.rsplit_once('.') else { return }; - let Some(pid) = owner.split_once('-').and_then(|(pid, _)| pid.parse::().ok()) else { return }; + // `{stem}.{pid}-{n}.pcsave.tmp`, or `.{stem}…` from versions before #11624. + let Some(pid) = crate::atomic::temp_owner(name) else { return }; if pid != std::process::id() && untouched_for(path, min_age, false) { let _ = std::fs::remove_file(path); } @@ -573,6 +571,30 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// #11624: temp files are no longer dot files; the sweep removes another process's in both + /// forms, so what older versions left is still cleaned up. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn sweep_removes_temp_files_of_both_name_forms() { + let dir = std::env::temp_dir().join(format!( + "pcraft-sweep-forms-{}-{}", + std::process::id(), + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0) + )); + std::fs::create_dir_all(&dir).unwrap(); + let foreign = [dir.join("kept.json.4294967294-3.pcsave.tmp"), dir.join(".kept.json.4294967294-4.pcsave.tmp")]; + let own = [dir.join(crate::atomic::temp_name("kept.json")), dir.join(format!(".kept.json.{}-9.pcsave.tmp", std::process::id()))]; + let others = [dir.join("kept.json"), dir.join("kept.json.4294967294-3.tmp"), dir.join("kept.json.pcsave.tmp")]; + for p in foreign.iter().chain(&own).chain(&others) { + std::fs::write(p, b"tmp").unwrap(); + } + sweep_orphans(&dir, std::time::Duration::ZERO); + assert!(foreign.iter().all(|p| !p.exists()), "another process's temp files are swept, either form"); + assert!(own.iter().all(|p| p.is_file()), "this process's temp files are kept"); + assert!(others.iter().all(|p| p.is_file()), "anything else is left alone"); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_committed_bundle_without_a_sidecar_is_listed_and_survives_the_sweep() { diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index e43da363c5..fb062934f8 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -630,7 +630,8 @@ impl Default for BrushSettings { spacing_enabled: true, opacity: 1.0, flow: 1.0, - pressure_size: true, + // Off, as the reference application leaves it after Reset Tool (#11809). + pressure_size: false, pressure_opacity: false, color: [0.0, 0.0, 0.0, 1.0], color_cmyk: None, @@ -702,6 +703,15 @@ impl BrushSettings { brush.dual_brush.size = safe_size(brush.dual_brush.size); brush.scattering.scatter.jitter = safe_scatter(brush.scattering.scatter.jitter); brush.dual_brush.scatter = safe_scatter(brush.dual_brush.scatter); + // A NaN here would paint fully opaque (`f32::min` returns the other operand) or not at all; + // it falls back to the default (the values of `BrushSettings::default` and `DualBrush::default`). Every other value, infinities included, is left to the clamps downstream. + let nan_or = |v: f32, d: f32| if v.is_nan() { d } else { v }; + brush.opacity = nan_or(brush.opacity, 1.0); + brush.flow = nan_or(brush.flow, 1.0); + brush.hardness = nan_or(brush.hardness, 1.0); + brush.spacing = nan_or(brush.spacing, 0.1); + brush.dual_brush.hardness = nan_or(brush.dual_brush.hardness, 1.0); + brush.dual_brush.spacing = nan_or(brush.dual_brush.spacing, 0.25); brush } diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 02d54c18ff..b3411b7a0b 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -114,6 +114,10 @@ impl Smoother { /// Feed one input point; returns the brush positions to paint through. pub fn push(&mut self, p: StrokePoint, out: &mut Vec) { + // A point without a position is dropped: kept, it would make every later smoothed position NaN. + if !(p.x.is_finite() && p.y.is_finite()) { + return; + } let prev_input = self.last_input.replace(p); if !self.active() { out.push(p); @@ -550,6 +554,13 @@ pub fn base_diameter(b: &BrushSettings, s: &StepInput) -> f32 { b.size * f } +/// Distance to the next step at `p`: the diameter there times the spacing. +fn step_len_for(brush: &BrushSettings, p: &StrokePoint) -> f64 { + let s = StepInput { point: *p, direction: 0.0, initial_direction: 0.0, step: 0 }; + let d = base_diameter(brush, &s).max(1.0); + f64::from(d * brush.spacing.max(0.01)).max(0.5) +} + /// Builds the primary dabs of a step (Shape Dynamics, Scattering, Transfer, Color, Texture depth). #[derive(Clone, Debug)] pub struct DabBuilder { @@ -566,9 +577,7 @@ impl DabBuilder { } pub fn step_len(&self, p: &StrokePoint) -> f64 { - let s = StepInput { point: *p, direction: 0.0, initial_direction: 0.0, step: 0 }; - let d = base_diameter(&self.brush, &s).max(1.0); - f64::from(d * self.brush.spacing.max(0.01)).max(0.5) + step_len_for(&self.brush, p) } pub fn build(&mut self, s: &StepInput, out: &mut Vec) { @@ -768,6 +777,9 @@ pub struct DabGenerator { builder: DabBuilder, dual: Option, scratch: Vec, + /// The brush the step length is read from, apart from the builder so the walker can read it + /// while its callback has the builder. + step_brush: std::sync::Arc, } impl DabGenerator { @@ -798,26 +810,21 @@ impl DabGenerator { builder: DabBuilder::new(&brush), dual: dual_on.then(|| DualBuilder::new(&brush)), scratch: Vec::new(), + step_brush: std::sync::Arc::new(brush), } } fn walk(&mut self, pts: &[StrokePoint], dabs: &mut Vec, dual: &mut Vec) { for p in pts { let p = apply_pose(&self.builder.brush, *p); - let b = &self.builder; - let len = |q: &StrokePoint| b.step_len(q); - let mut steps = Vec::new(); - self.walker.push(p, &len, &mut |s| steps.push(s)); - for s in &steps { - self.builder.build(s, dabs); - } + // Each step becomes its dabs as the walker emits it: a long segment never holds its + // step list (the pixel-grid mode can emit 1e7 steps for one). + let brush = &*self.step_brush; + let builder = &mut self.builder; + self.walker.push(p, &|q| step_len_for(brush, q), &mut |s| builder.build(&s, dabs)); if let (Some(w), Some(db)) = (self.dual_walker.as_mut(), self.dual.as_mut()) { - let mut steps = Vec::new(); - let len = |q: &StrokePoint| db.step_len(q); - w.push(p, &len, &mut |s| steps.push(s)); - for s in &steps { - db.build(s, dual); - } + let step = db.step_len(&p); + w.push(p, &|_| step, &mut |s| db.build(&s, dual)); } } } @@ -838,17 +845,9 @@ impl DabGenerator { let mut sm = Vec::new(); self.smoother.finish(&mut sm); self.walk(&sm, dabs, dual); - let mut steps = Vec::new(); - self.walker.finish(&mut |s| steps.push(s)); - for s in &steps { - self.builder.build(s, dabs); - } + self.walker.finish(&mut |s| self.builder.build(&s, dabs)); if let (Some(w), Some(db)) = (self.dual_walker.as_mut(), self.dual.as_mut()) { - let mut steps = Vec::new(); - w.finish(&mut |s| steps.push(s)); - for s in &steps { - db.build(s, dual); - } + w.finish(&mut |s| db.build(&s, dual)); } } } @@ -887,3 +886,163 @@ mod walker_budget_tests { assert_eq!(steps.get(), before + 1); } } + +#[cfg(test)] +mod streaming_tests { + use super::*; + + /// The step-by-step walk before the steps were streamed: every step of a point is collected + /// first, then built. The streamed walk must produce the same dabs. + fn buffered(brush: &BrushSettings, pts: &[StrokePoint]) -> (Vec, Vec) { + let brush = brush.bounded_for_render(); + let mut smoother = Smoother::new(&brush.smoothing, 1.0); + let mut walker = DabGenerator::new(&brush, 1.0).walker; + let mut dual_walker = brush.dual_brush.enabled.then(|| PathWalker::new(None)); + let (mut builder, mut dual_builder) = (DabBuilder::new(&brush), brush.dual_brush.enabled.then(|| DualBuilder::new(&brush))); + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + let mut sm = Vec::new(); + for p in pts { + smoother.push(*p, &mut sm); + } + smoother.finish(&mut sm); + for p in sm { + let p = apply_pose(&builder.brush, p); + let mut steps = Vec::new(); + walker.push(p, &|q| builder.step_len(q), &mut |s| steps.push(s)); + for s in &steps { + builder.build(s, &mut dabs); + } + if let (Some(w), Some(db)) = (dual_walker.as_mut(), dual_builder.as_mut()) { + let mut steps = Vec::new(); + w.push(p, &|q| db.step_len(q), &mut |s| steps.push(s)); + for s in &steps { + db.build(s, &mut dual); + } + } + } + let mut steps = Vec::new(); + walker.finish(&mut |s| steps.push(s)); + for s in &steps { + builder.build(s, &mut dabs); + } + if let (Some(w), Some(db)) = (dual_walker.as_mut(), dual_builder.as_mut()) { + let mut steps = Vec::new(); + w.finish(&mut |s| steps.push(s)); + for s in &steps { + db.build(s, &mut dual); + } + } + (dabs, dual) + } + + fn streamed(brush: &BrushSettings, pts: &[StrokePoint], chunk: usize) -> (Vec, Vec) { + let mut g = DabGenerator::new(brush, 1.0); + let (mut dabs, mut dual) = (Vec::new(), Vec::new()); + for c in pts.chunks(chunk) { + g.push(c, &mut dabs, &mut dual); + } + g.finish(&mut dabs, &mut dual); + (dabs, dual) + } + + fn path() -> Vec { + let mut pts = Vec::new(); + for i in 0..40 { + let t = f64::from(i); + let mut p = StrokePoint::new(10.0 + t * 9.3, 50.0 + (t * 0.7).sin() * 30.0, 0.3 + 0.7 * ((t * 0.31).sin().abs() as f32)); + p.time = t * 7.0; + pts.push(p); + } + pts + } + + #[test] + fn streamed_dabs_equal_the_buffered_walk() { + let mut variants: Vec = vec![BrushSettings::default()]; + variants.push(BrushSettings { size: 14.0, spacing: 0.05, ..BrushSettings::default() }); + variants.push(BrushSettings { size: 1.0, aliased: true, ..BrushSettings::default() }); + variants.push(BrushSettings { size: 9.0, spacing_enabled: false, ..BrushSettings::default() }); + variants.push(BrushSettings { size: 12.0, build_up: true, build_up_rate: 40.0, ..BrushSettings::default() }); + let mut rich = BrushSettings { size: 18.0, spacing: 0.2, ..BrushSettings::default() }; + rich.scattering.enabled = true; + rich.scattering.scatter.jitter = 0.5; + rich.scattering.count = 3; + rich.dual_brush.enabled = true; + rich.dual_brush.size = 8.0; + rich.dual_brush.count = 2; + rich.shape_dynamics.enabled = true; + rich.shape_dynamics.size.jitter = 0.6; + rich.smoothing.amount = 0.5; + variants.push(rich); + for (n, b) in variants.iter().enumerate() { + let (want, want_dual) = buffered(b, &path()); + assert!(want.len() > 10, "variant {n}: {} dabs", want.len()); + for chunk in [1, 7, 1000] { + let (got, got_dual) = streamed(b, &path(), chunk); + assert_eq!(got, want, "variant {n}, chunk {chunk}"); + assert_eq!(got_dual, want_dual, "variant {n}, chunk {chunk} (dual)"); + } + } + } + + #[test] + fn a_nan_opacity_flow_hardness_or_spacing_paints_as_the_default() { + let pts = path(); + let base = BrushSettings { size: 10.0, ..BrushSettings::default() }; + let (want, _) = streamed(&base, &pts, 1000); + for broken in [ + BrushSettings { opacity: f32::NAN, ..base.clone() }, + BrushSettings { flow: f32::NAN, ..base.clone() }, + BrushSettings { hardness: f32::NAN, ..base.clone() }, + BrushSettings { spacing: f32::NAN, ..base.clone() }, + ] { + // The default brush has opacity, flow and hardness 1 and spacing 0.1, as `base` does. + let (got, _) = streamed(&broken, &pts, 1000); + assert_eq!(got, want); + let b = broken.bounded_for_render(); + assert!(b.opacity.is_finite() && b.flow.is_finite() && b.hardness.is_finite() && b.spacing.is_finite()); + } + // Finite values are not touched, even out of range. + let odd = BrushSettings { opacity: 3.0, flow: f32::NEG_INFINITY, spacing: f32::INFINITY, ..base }; + let b = odd.bounded_for_render(); + assert_eq!((b.opacity, b.flow, b.spacing), (3.0, f32::NEG_INFINITY, f32::INFINITY)); + } + + #[test] + fn a_nan_dual_hardness_or_spacing_paints_as_the_default() { + let pts = path(); + let mut explicit = BrushSettings { size: 10.0, ..BrushSettings::default() }; + explicit.dual_brush.enabled = true; + explicit.dual_brush.size = 6.0; + explicit.dual_brush.hardness = 1.0; + explicit.dual_brush.spacing = 0.25; + let (_, want_dual) = streamed(&explicit, &pts, 1000); + assert!(!want_dual.is_empty()); + let mut broken = explicit.clone(); + broken.dual_brush.spacing = f32::NAN; + assert_eq!(streamed(&broken, &pts, 1000).1, want_dual); + broken.dual_brush.hardness = f32::NAN; + let b = broken.bounded_for_render(); + assert_eq!((b.dual_brush.hardness, b.dual_brush.spacing), (1.0, 0.25)); + } + + #[test] + fn a_point_without_a_position_does_not_poison_a_smoothed_stroke() { + let mut brush = BrushSettings { size: 8.0, ..BrushSettings::default() }; + brush.smoothing.amount = 0.6; + let clean = path(); + let mut dirty = clean.clone(); + dirty.insert(10, StrokePoint::new(f64::NAN, 40.0, 1.0)); + dirty.insert(20, StrokePoint::new(30.0, f64::INFINITY, 1.0)); + assert_eq!(streamed(&brush, &dirty, 1000).0, streamed(&brush, &clean, 1000).0); + brush.smoothing.amount = 0.0; + assert_eq!(streamed(&brush, &dirty, 1000).0, streamed(&brush, &clean, 1000).0); + } + + #[test] + fn a_long_pixel_grid_segment_streams() { + let brush = BrushSettings { size: 1.0, aliased: true, spacing: 1.0, ..BrushSettings::default() }; + let (dabs, _) = streamed(&brush, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(2.0e6, 3.0, 1.0)], 1000); + assert_eq!(dabs.len(), 2_000_001); + } +} diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index a9a7485fa5..bb34749065 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -190,12 +190,14 @@ pub fn apply_mixer_dab( state: &mut MixerState, lock_transparency: bool, ) { + // Only the dab's own rectangle is ever read from the sample, not the whole stroke rectangle. let sample = sample.filter(|_| m.samples_canvas(&fp.dab)).map(|surface| { - let source = crate::retouch::Region::read(surface, work.rect); + let rect = fp.rect.intersect(&work.rect); + let source = crate::retouch::Region::read(surface, rect); if surface.format().mode == fmt.mode && surface.format().alpha == fmt.alpha { source } else { - let mut native = crate::retouch::Region::new(work.rect, fmt.channels()); + let mut native = crate::retouch::Region::new(rect, fmt.channels()); for (src, dst) in source.data.chunks_exact(source.ch).zip(native.data.chunks_exact_mut(native.ch)) { from_rgba_into(&fmt, to_rgba(&surface.format(), src), dst); } @@ -205,9 +207,10 @@ pub fn apply_mixer_dab( apply_mixer_dab_region(work, fp, fmt, sample.as_ref(), m, state, lock_transparency); } -/// Contiguous native-channel sample variant. `sample` must have the same rectangle and -/// channel layout as `work`. The live compositor supplies it directly, avoiding a tiled -/// temporary surface and a heap allocation for every sampled/deposited pixel. +/// Contiguous native-channel sample variant. `sample` must have the channel layout of `work` and +/// cover at least `fp.rect` clipped to `work.rect` (the only pixels read). The live compositor +/// supplies it directly, avoiding a tiled temporary surface and a heap allocation for every +/// sampled/deposited pixel. pub fn apply_mixer_dab_region( work: &mut crate::retouch::Region, fp: &crate::retouch::Footprint, diff --git a/crates/paint/src/mixer/reference_tests.rs b/crates/paint/src/mixer/reference_tests.rs index 0f6f0a2a82..2071f60f01 100644 --- a/crates/paint/src/mixer/reference_tests.rs +++ b/crates/paint/src/mixer/reference_tests.rs @@ -205,3 +205,41 @@ fn dry_and_wet_transitions_match_frozen_kernel() { } } } + +/// A sample surface is read only under the dab: dabs that overhang the working rectangle or sit in +/// a corner of a much larger one still match the frozen kernel. +#[test] +fn sampled_dabs_clipped_by_the_working_rectangle_match_frozen_kernel() { + use crate::retouch::Region; + use crate::{BrushContext, BrushSettings, Dab}; + use photocraft_color::{PixelFormat, SampleType}; + use photocraft_geom::Point; + + let work_rect = Rect::new(10, 10, 60, 50); + let fmt = PixelFormat::new(photocraft_color::ColorMode::Cmyk, SampleType::U16, true); + let mut surface = Surface::new(fmt); + surface.fill_rect(Rect::new(0, 0, 80, 80), &from_rgba(&fmt, [0.25, 0.5, 0.75, 0.9])); + let mut source = Surface::new(PixelFormat::RGBA32F); + for y in 0..80 { + for x in 0..80 { + source.fill_rect(Rect::new(x, y, x + 1, y + 1), &[x as f32 / 80.0, y as f32 / 80.0, 0.3, 0.8]); + } + } + let ctx = BrushContext::new(&BrushSettings { size: 30.0, ..Default::default() }); + for sample in [&source, &surface] { + let mut actual = Region::read(&surface, work_rect); + let mut expected = actual.clone(); + let mut state = MixerState::default(); + state.load([0.8, 0.2, 0.1, 1.0]); + let mut expected_state = state.clone(); + // Overhanging the left edge, a corner, and the middle. + for (i, (x, y)) in [(8.0, 30.0), (62.0, 52.0), (30.0, 12.0), (35.0, 30.0)].into_iter().enumerate() { + let fp = ctx.footprint(&Dab::round(Point::new(x, y), 12.0, 1.0), i); + let settings = MixerSettings { wet: 0.8, mix: 0.7, ..Default::default() }; + reference(&mut expected, &fp, fmt, Some(sample), &settings, &mut expected_state, false); + apply_mixer_dab(&mut actual, &fp, fmt, Some(sample), &settings, &mut state, false); + assert_eq!(actual, expected, "dab {i}"); + assert_eq!(state, expected_state, "state after dab {i}"); + } + } +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 15d0e18f88..2a93a713d5 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -263,9 +263,7 @@ impl BrushContext { let (fx, fy) = ((x as f32 + 0.5) / s - 0.5, (y as f32 + 0.5) / s - 0.5); let (x0, y0) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - x0, fy - y0); - let a = p.sample_wrap(x0, y0) + (p.sample_wrap(x0 + 1.0, y0) - p.sample_wrap(x0, y0)) * tx; - let b = p.sample_wrap(x0, y0 + 1.0) + (p.sample_wrap(x0 + 1.0, y0 + 1.0) - p.sample_wrap(x0, y0 + 1.0)) * tx; - a + (b - a) * ty + p.sample_bilinear_wrap(x0, y0, tx, ty) } /// Bounding rectangle of a dab (rotated sampled tips need the corner reach). diff --git a/crates/paint/src/render/coverage_tests.rs b/crates/paint/src/render/coverage_tests.rs index 0b992308ad..db8e8d0cd1 100644 --- a/crates/paint/src/render/coverage_tests.rs +++ b/crates/paint/src/render/coverage_tests.rs @@ -188,3 +188,26 @@ fn sparse_large_footprint_only_allocates_and_dirties_nonzero_tiles() { map.accumulate(Rect::new(0, 0, 0, 0), &[], 0.8, None, None); assert_eq!(map.bounds(), bounds); } + +/// `texture_at` at a scale other than 100 % is the bilinear value of the four wrapped texels around +/// the sample: x and y are not swapped, and a different fraction on each axis is honoured. +#[test] +fn texture_at_scaled_is_the_bilinear_of_the_wrapped_texels() { + let (w, h) = (4usize, 3usize); + let data: Vec = (0..w * h).map(|i| (i * i) as f32 / 100.0).collect(); + let mut brush = BrushSettings::default(); + brush.texture.scale = 4.0; + let mut ctx = BrushContext::new(&brush); + ctx.texture = Some(Arc::new(PatternImage { width: w, height: h, data: data.clone() })); + let texel = |x: i64, y: i64| data[y.rem_euclid(h as i64) as usize * w + x.rem_euclid(w as i64) as usize]; + for (x, y) in [(5, 2), (2, 5), (-3, 7), (0, 0), (-9, -4)] { + let (fx, fy) = ((x as f32 + 0.5) / 4.0 - 0.5, (y as f32 + 0.5) / 4.0 - 0.5); + let (x0, y0) = (fx.floor() as i64, fy.floor() as i64); + let (tx, ty) = (fx - fx.floor(), fy - fy.floor()); + let top = texel(x0, y0) + (texel(x0 + 1, y0) - texel(x0, y0)) * tx; + let bottom = texel(x0, y0 + 1) + (texel(x0 + 1, y0 + 1) - texel(x0, y0 + 1)) * tx; + let want = top + (bottom - top) * ty; + let got = ctx.texture_at(x, y); + assert!((got - want).abs() < 1e-5, "({x}, {y}): {got} vs {want}"); + } +} diff --git a/crates/paint/src/tile.rs b/crates/paint/src/tile.rs index 8ea0e776b6..623a264606 100644 --- a/crates/paint/src/tile.rs +++ b/crates/paint/src/tile.rs @@ -303,12 +303,92 @@ impl PatternImage { let yi = (y.floor() as i64).rem_euclid(self.height as i64) as usize; self.data[yi * self.width + xi] } + + /// Bilinear sample of the four texels at (`x0`, `y0`) and their right/lower neighbours, all + /// wrapped; `x0`, `y0` are already floored. Same values as four [`sample_wrap`](Self::sample_wrap) + /// calls, with the wrap done once per axis instead of once per texel. + #[inline] + pub fn sample_bilinear_wrap(&self, x0: f32, y0: f32, tx: f32, ty: f32) -> f32 { + // Past 2^24 `x0 + 1.0` rounds back to `x0`, so the neighbour is not `x0 + 1` any more. + const EXACT: f32 = 16_777_216.0; + // `rem_euclid` below is on `i32`, so a side past `i32::MAX` takes the `i64` path, like the coordinates past 2^24. + if !(x0.abs() < EXACT && y0.abs() < EXACT) || self.width.max(self.height) > i32::MAX as usize { + let a = self.sample_wrap(x0, y0) + (self.sample_wrap(x0 + 1.0, y0) - self.sample_wrap(x0, y0)) * tx; + let b = self.sample_wrap(x0, y0 + 1.0) + (self.sample_wrap(x0 + 1.0, y0 + 1.0) - self.sample_wrap(x0, y0 + 1.0)) * tx; + return a + (b - a) * ty; + } + let (w, h) = (self.width, self.height); + let xa = (x0 as i32).rem_euclid(w as i32) as usize; + let ya = (y0 as i32).rem_euclid(h as i32) as usize; + let xb = if xa + 1 == w { 0 } else { xa + 1 }; + let yb = if ya + 1 == h { 0 } else { ya + 1 }; + let (ra, rb) = (ya * w, yb * w); + let (p00, p10, p01, p11) = (self.data[ra + xa], self.data[ra + xb], self.data[rb + xa], self.data[rb + xb]); + let a = p00 + (p10 - p00) * tx; + let b = p01 + (p11 - p01) * tx; + a + (b - a) * ty + } } #[cfg(test)] mod tests { use super::*; + fn old_bilinear(p: &PatternImage, x0: f32, y0: f32, tx: f32, ty: f32) -> f32 { + let a = p.sample_wrap(x0, y0) + (p.sample_wrap(x0 + 1.0, y0) - p.sample_wrap(x0, y0)) * tx; + let b = p.sample_wrap(x0, y0 + 1.0) + (p.sample_wrap(x0 + 1.0, y0 + 1.0) - p.sample_wrap(x0, y0 + 1.0)) * tx; + a + (b - a) * ty + } + + /// The wrapped bilinear sampler returns the same bits as four `sample_wrap` calls: odd and + /// non-square sizes, negative and huge coordinates, the wrap seam, NaN. + #[test] + fn bilinear_wrap_is_bit_identical_to_four_sample_wraps() { + for (w, h) in [(1usize, 1usize), (1, 7), (5, 1), (7, 5), (128, 128), (1024, 3)] { + let data = (0..w * h).map(|i| ((i as u32).wrapping_mul(2_654_435_761) >> 8) as f32 / 16_777_216.0).collect(); + let p = PatternImage { width: w, height: h, data }; + let mut coords = + vec![0.0f32, -1.0, -(w as f32), w as f32 - 1.0, w as f32, 16_777_215.0, 16_777_216.0, -16_777_216.0, 3.0e9, -3.0e9, f32::NAN, f32::INFINITY]; + coords.extend((-300..300).map(|i| i as f32 * 1.0)); + for &x0 in &coords { + for &y0 in coords.iter().filter(|y| !y.is_finite() || y.abs() > 20.0 || **y % 7.0 == 0.0) { + for (tx, ty) in [(0.0, 0.0), (0.25, 0.75), (0.999, 0.5)] { + let (new, old) = (p.sample_bilinear_wrap(x0, y0, tx, ty), old_bilinear(&p, x0, y0, tx, ty)); + assert_eq!(new.to_bits(), old.to_bits(), "{w}x{h} at ({x0}, {y0})"); + } + } + } + } + } + + /// Manual timing: `cargo test -p photocraft-paint --release bilinear_wrap_timing -- --ignored --nocapture`. + #[test] + #[ignore] + fn bilinear_wrap_timing() { + let p = PatternImage { width: 128, height: 128, data: (0..128 * 128).map(|i| (i % 251) as f32 / 251.0).collect() }; + let n = 4_000_000; + for round in 0..3 { + let t = std::time::Instant::now(); + let mut s = 0.0f32; + for i in 0..n { + let (fx, fy) = ((i % 2000) as f32 * 1.25 - 40.5, (i / 2000) as f32 * 1.25 - 40.5); + s += old_bilinear(&p, fx.floor(), fy.floor(), fx.fract(), fy.fract()); + } + let old = t.elapsed(); + let t = std::time::Instant::now(); + let mut s2 = 0.0f32; + for i in 0..n { + let (fx, fy) = ((i % 2000) as f32 * 1.25 - 40.5, (i / 2000) as f32 * 1.25 - 40.5); + s2 += p.sample_bilinear_wrap(fx.floor(), fy.floor(), fx.fract(), fy.fract()); + } + println!( + "round {round}: old {:.2} ns/px, new {:.2} ns/px ({s} {s2})", + old.as_secs_f64() * 1e9 / n as f64, + t.elapsed().as_secs_f64() * 1e9 / n as f64 + ); + } + } + /// Cloning a tile (and the brush settings holding it, on every pointer event of a stroke) /// shares its samples instead of copying them (#4534). #[test] diff --git a/crates/psd/README.md b/crates/psd/README.md index 71d12e9f12..1f6c892af5 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -78,7 +78,14 @@ LayerInfo::unpadded_len(version), LayerInfo::pad_to(version, 4) // Photoshop p // Image resources ImageResource { signature, id, name, data }; ImageResource::parsed() -> Option> ResourceData::{ResolutionInfo, LayerState, LayerGroupInfo, Thumbnail, GlobalAngle, IccProfile, - GlobalAltitude, VersionInfo, Exif, Xmp} + GlobalAltitude, VersionInfo, Exif, Xmp, TimelineInfo, Animation} + +// Legacy animation syntax (no playback/document-model dependency) +animation::AnimationResource::from_bytes / to_bytes // maniIRFR; ordered raw records +animation::AnimationRecord::descriptor() // AnDs; version-16 descriptor +animation::{frame_info, frame_sets, layer_frame_states} // borrowed sparse views, opaque ids +animation::parse_descriptor // descriptor + up to 3 zero alignment bytes +metadata::MetadataItem::animation_descriptor() // mlst / tmln; leaves other metadata alone // Compression Compression::{Raw, Rle, Zip, ZipPrediction, Unknown(u16)} @@ -117,6 +124,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla | luni lsct lsdk lyid lnsr clbl infx knko lspf lclr iOpa shmd | ✓ | ✓ | ✓ | `TaggedBlock::parsed()` | | Layer XMP (`shmd` › `cust` › `layerXMP`) | ✓ | ✓ | ✓ | `metadata::layer_xmp` / `take_layer_xmp` / `put_layer_xmp`, laid out as Photoshop 2026 writes it | | ActionDescriptor (all OSTypes) | ✓ | ✓ | ✓ | including references, `ObAr` (best effort), `UnFl`, `Pth `, version-16 wrapper | +| Legacy frame animation syntax | ✓ | ✓ | partial | `mani` / `AnDs`, `mlst`, `tmln`, resource 1075; raw-preserving descriptor views, not playback or keyframe evaluation | | Layer tree (groups) | ✓ | ✓ | ✓ | open/closed folders plus bounding dividers; tolerant of malformed nesting | | RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone | | Builder | – | ✓ | – | RGB / gray / CMYK at 8/16 bit, masks, groups, blend modes, opacity, fill, visibility, clipping | @@ -140,6 +148,25 @@ allocations for padded channels return an error on failure. * Adjustment and fill layers: `curv`, `levl`, `hue2`, `SoCo`, `GdFl`, `PtFl`, …, plus `Patt`, `Txt2`, `FMsk`, 3D and video blocks. * Global layer mask info (raw, with accessors), thumbnails (raw), slices, guides, paths, and every other resource id. +## Legacy animation inspection + +```sh +cargo run -p photocraft-psd --example animation_inspect -- /path/to/input.psd +cargo test -p photocraft-psd --test it animation:: +``` + +The inspection example accepts an explicit local PSD/PSB (up to 128 MiB), reports frame counts, +stored delays and descriptor counts, and checks byte-exact raw round-trips without modifying the +input. It does not print layer names, text or descriptor values. No personal file is bundled; +committed animation tests construct synthetic payloads and PSD/PSB containers. + +`mani` is detected by its payload signature within the plug-in resource range 4000–4999, not by +assuming that resource 4003 always belongs to animation. Unknown records and unsupported descriptor +versions stay raw. `FrIn` definitions and `FSts` playback order are separate; ids are opaque stored +`long` values. Missing frame delays remain absent, and sparse `mlst` properties are not filled with +guessed defaults. Timeline tracks, loops, inheritance and property evaluation are left to higher +layers. This parser alone does **not** make PSD animations play in PhotoCraft. + ## Testing `cargo test -p photocraft-psd --all-features` runs the unit tests, integration tests and proptests: diff --git a/crates/psd/examples/animation_inspect.rs b/crates/psd/examples/animation_inspect.rs new file mode 100644 index 0000000000..2b3f7391dc --- /dev/null +++ b/crates/psd/examples/animation_inspect.rs @@ -0,0 +1,103 @@ +//! Inspect a local PSD/PSB's animation structure without printing layer names, text, or metadata +//! values. No asset is bundled: pass a path explicitly. Does not decode pixels or modify the file. +//! `cargo run -p photocraft-psd --example animation_inspect -- /path/to/input.psd` + +#[cfg(not(target_arch = "wasm32"))] +fn inspect() -> Result<(), Box> { + use std::collections::BTreeMap; + use std::io::Read; + + use photocraft_psd::animation::{frame_info, frame_sets, layer_frame_states}; + use photocraft_psd::metadata::parse_shmd; + use photocraft_psd::{PsdFile, ResourceData}; + + let mut args = std::env::args_os().skip(1); + let path = args.next().ok_or("usage: animation_inspect ")?; + if args.next().is_some() { + return Err("expected exactly one input path".into()); + } + // Diagnostic tool, not the production large-file importer. Bound even a file growing while read. + const MAX_BYTES: u64 = 128 * 1024 * 1024; + let file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() || file.metadata()?.len() > MAX_BYTES { + return Err("expected a regular PSD/PSB no larger than 128 MiB".into()); + } + let mut bytes = Vec::new(); + file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_BYTES { + return Err("input exceeds the diagnostic tool's 128 MiB limit".into()); + } + let psd = PsdFile::from_bytes(&bytes)?; + println!("canvas={}x{} depth={} layers={}", psd.header.width, psd.header.height, psd.header.depth, psd.layers().len()); + let mut animations = 0; + for resource in &psd.resources { + match resource.parsed() { + Some(Ok(ResourceData::Animation(animation))) => { + animations += 1; + let back = animation.to_bytes()?; + if back != resource.data { + return Err("animation resource failed its byte-exact round trip".into()); + } + println!("animation resource: {} records; byte-exact round trip", animation.records.len()); + for record in &animation.records { + if let Some(d) = record.descriptor() { + let d = d?; + let frames = frame_info(&d.descriptor)?; + let sets = frame_sets(&d.descriptor)?; + let mut delays = BTreeMap::new(); + for frame in &frames { + *delays.entry(frame.delay_centiseconds).or_insert(0usize) += 1; + } + println!(" AnDs: {} definitions, {} frame sets", frames.len(), sets.len()); + println!(" stored delays (centiseconds -> frame count): {delays:?}"); + for set in sets { + let unresolved = set.frame_ids.iter().filter(|id| !frames.iter().any(|f| f.id == **id)).count(); + println!(" frame set: {} ordered references, {unresolved} unresolved", set.frame_ids.len()); + } + } + } + } + Some(Ok(ResourceData::TimelineInfo(d))) => println!("document timeline: {} descriptor fields", d.descriptor.items.len()), + Some(Err(e)) if resource.id == 1075 || (4000..=4999).contains(&resource.id) && resource.data.starts_with(b"mani") => return Err(e.into()), + _ => {} + } + } + let (mut states, mut tracks) = (0usize, 0usize); + for layer in psd.layers() { + for block in &layer.blocks { + if block.key != *b"shmd" { + continue; + } + let items = parse_shmd(&block.data)?; + for item in &items { + if let Some(d) = item.animation_descriptor() { + let d = d?; + if item.key == *b"mlst" { + layer_frame_states(&d.descriptor)?; + states += 1; + } else { + tracks += 1; + } + } + } + if photocraft_psd::metadata::write_shmd(&items) != block.data { + return Err("layer metadata failed its byte-exact round trip".into()); + } + } + } + if psd.to_bytes()? != bytes { + return Err("PSD/PSB failed its byte-exact round trip".into()); + } + println!("animation resources={animations}; layer frame-state descriptors={states}; layer timeline descriptors={tracks}"); + println!("whole PSD/PSB: byte-exact round trip; input unchanged"); + Ok(()) +} + +fn main() -> std::process::ExitCode { + #[cfg(not(target_arch = "wasm32"))] + if let Err(e) = inspect() { + eprintln!("animation inspection failed: {e}"); + return std::process::ExitCode::FAILURE; + } + std::process::ExitCode::SUCCESS +} diff --git a/crates/psd/src/animation.rs b/crates/psd/src/animation.rs new file mode 100644 index 0000000000..de29693f6c --- /dev/null +++ b/crates/psd/src/animation.rs @@ -0,0 +1,228 @@ +//! Legacy Photoshop frame-animation syntax, independent of playback or document semantics. +//! +//! Observed in a CS5-authored PSD: a plug-in image resource (id in 4000..=4999) starts with +//! `maniIRFR`, a big-endian u32 byte length, then `8BIM` / key / u32 length / data records. +//! `AnDs` holds a version-16 ActionDescriptor; other records (including `Roll`) stay opaque. +//! Layer `shmd` items `mlst` and `tmln`, and image resource 1075, also hold versioned descriptors. +//! These undocumented layouts were established by inspecting file structure, not proprietary code. +//! +//! Raw records remain the source of truth: typed accessors do not rewrite them, discard unknown +//! fields, interpret sparse layer-state inheritance, or assume a frame id is its sequence index. +//! This module does **not** import an animation into PhotoCraft or evaluate timeline tracks. + +use crate::descriptor::{Descriptor, Value, VersionedDescriptor}; +use crate::error::{PsdError, Result}; +use crate::io::{Reader, WriteExt}; + +/// A record in a `mani` resource. Data includes any padding counted in its stored length. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnimationRecord<'a> { + /// Record key (`AnDs`, `Roll`, or an unknown key). + pub key: [u8; 4], + /// Borrowed, unmodified payload. + pub data: &'a [u8], +} + +impl AnimationRecord<'_> { + /// Typed view of `AnDs`; `None` for other records, including `Roll`. + pub fn descriptor(&self) -> Option> { + (self.key == *b"AnDs").then(|| parse_descriptor(self.data)) + } +} + +/// The records of a legacy frame-animation plug-in resource, in stored order. +/// +/// Unknown keys and duplicate records are preserved, not silently collapsed. The observed +/// envelope has no alignment bytes outside record lengths. Unsupported envelopes return an error; +/// callers should keep their original image resource unchanged in that case. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnimationResource<'a> { + /// Ordered records, borrowing their payloads from the input. + pub records: Vec>, +} + +impl<'a> AnimationResource<'a> { + /// Parses a complete `maniIRFR` payload, checking the outer and every inner length. + /// Descriptor decoding is lazy, so unknown/future `AnDs` versions can still round-trip raw. + pub fn from_bytes(data: &'a [u8]) -> Result { + let mut r = Reader::new(data); + signature(&mut r, *b"mani", "mani")?; + signature(&mut r, *b"IRFR", "IRFR animation envelope")?; + let len = r.u32()?; + let mut body = r.sub(u64::from(len))?; + if !r.is_empty() { + return Err(PsdError::invalid("trailing bytes after animation envelope")); + } + let mut records = Vec::new(); + while !body.is_empty() { + signature(&mut body, *b"8BIM", "8BIM animation record")?; + let key = body.array()?; + let len = body.u32()?; + let data = body.bytes_u64(u64::from(len))?; + records.push(AnimationRecord { key, data }); + } + Ok(Self { records }) + } + + /// Writes the raw records, preserving their payloads exactly, including unknown fields, + /// unknown descriptor versions and noncanonical descriptor encodings. + pub fn to_bytes(&self) -> Result> { + // Check all lengths before constructing the output; no unchecked 32-bit length casts. + let mut len = 0u32; + for record in &self.records { + let n = u32::try_from(record.data.len()).map_err(|_| PsdError::LimitExceeded("animation record exceeds u32 length"))?; + len = len.checked_add(12).and_then(|v| v.checked_add(n)).ok_or(PsdError::LimitExceeded("animation envelope exceeds u32 length"))?; + } + let mut out = Vec::new(); + out.put(b"maniIRFR"); + out.put_u32(len); + for record in &self.records { + out.put(b"8BIM"); + out.put(&record.key); + out.put_len(record.data.len() as u64, false)?; + out.put(record.data); + } + Ok(out) + } +} + +fn signature(r: &mut Reader<'_>, expected: [u8; 4], name: &'static str) -> Result<()> { + let found = r.array()?; + if found != expected { + return Err(PsdError::InvalidSignature { expected: name, found }); + } + Ok(()) +} + +/// Parses a version-16 animation descriptor, allowing up to three zero alignment bytes. +/// +/// Raw payloads should be retained separately for byte-exact writing. This accessor is strict +/// about non-padding trailing bytes and does not guess how to read a future descriptor version. +/// It is shared by `AnDs`, layer `mlst` / `tmln`, and document timeline resource 1075. +pub fn parse_descriptor(data: &[u8]) -> Result { + let (value, consumed) = VersionedDescriptor::parse_prefix(data)?; + let tail = data.get(consumed..).ok_or_else(|| PsdError::invalid("animation descriptor length"))?; + if tail.len() > 3 || tail.iter().any(|&b| b != 0) { + return Err(PsdError::invalid("trailing bytes after animation descriptor")); + } + Ok(value) +} + +/// A frame-definition view. Its id is an opaque signed `long`, not a frame index. +#[derive(Debug, Clone, PartialEq)] +pub struct FrameInfo<'a> { + /// `FrID`, preserved without reinterpreting its bit pattern. + pub id: i32, + /// `FrDl` in centiseconds, or absent. No playback default or browser clamping is applied. + pub delay_centiseconds: Option, + /// All fields, including unknown ones, in their original order. + pub descriptor: &'a Descriptor, +} + +/// Reads the `FrIn` list from an `AnDs` descriptor. A missing list is not an empty animation. +/// Wrong types, missing frame ids and negative delays return errors. Duplicate ids are retained +/// for the document importer to diagnose rather than being silently overwritten here. +pub fn frame_info(descriptor: &Descriptor) -> Result>> { + let Some(Value::List(list)) = descriptor.get("FrIn") else { + return Err(PsdError::invalid("animation FrIn must be a list")); + }; + list.iter() + .map(|v| { + let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation frame must be a descriptor")) }; + let Some(Value::Integer(id)) = d.get("FrID") else { return Err(PsdError::invalid("animation frame FrID must be a long")) }; + let delay_centiseconds = match d.get("FrDl") { + None => None, + Some(Value::Integer(n)) => Some(u32::try_from(*n).map_err(|_| PsdError::invalid("negative animation frame delay"))?), + _ => return Err(PsdError::invalid("animation frame FrDl must be a long")), + }; + Ok(FrameInfo { id: *id, delay_centiseconds, descriptor: d }) + }) + .collect() +} + +/// A stored frame set: explicit playback order is separate from the `FrIn` definitions. +#[derive(Debug, Clone, PartialEq)] +pub struct FrameSet<'a> { + /// `FsID`, an opaque identifier. + pub id: i32, + /// `AFrm`, when present. Kept uninterpreted for the importer to validate. + pub active_frame: Option, + /// `FsFr` frame ids in stored order (including any duplicate or unresolved ids). + pub frame_ids: Vec, + /// Complete original descriptor, including fields not yet understood. + pub descriptor: &'a Descriptor, +} + +/// One sparse layer-state entry from `mlst` / `LaSt`. +#[derive(Debug, Clone, PartialEq)] +pub struct LayerFrameState<'a> { + /// `FrLs`: frame ids to which this entry refers. They are not frame indices. + pub frame_ids: Vec, + /// Complete sparse state, including visibility, blend options, offsets, masks, effects, + /// text settings and unknown fields. Omitted properties are deliberately not defaulted. + pub descriptor: &'a Descriptor, +} + +/// A layer's sparse animation states, without attempting to resolve their inheritance. +#[derive(Debug, Clone, PartialEq)] +pub struct LayerFrameStates<'a> { + /// `LaID`: PSD layer identifier, not the layer's record index. + pub layer_id: i32, + /// `LaSt` entries in stored order. + pub states: Vec>, +} + +/// Reads the identifiers and sparse entries of an `mlst` descriptor. This is a syntax view: +/// missing properties stay missing, and duplicate/unresolved references remain available for +/// the importer to validate. The original descriptor remains available to the caller. +pub fn layer_frame_states(descriptor: &Descriptor) -> Result> { + let Some(Value::Integer(layer_id)) = descriptor.get("LaID") else { + return Err(PsdError::invalid("animation layer LaID must be a long")); + }; + let Some(Value::List(list)) = descriptor.get("LaSt") else { + return Err(PsdError::invalid("animation layer LaSt must be a list")); + }; + let states = list + .iter() + .map(|v| { + let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation layer state must be a descriptor")) }; + let Some(Value::List(ids)) = d.get("FrLs") else { return Err(PsdError::invalid("animation layer FrLs must be a list")) }; + let frame_ids = ids + .iter() + .map(|v| match v { + Value::Integer(n) => Ok(*n), + _ => Err(PsdError::invalid("animation layer frame reference must be a long")), + }) + .collect::>>()?; + Ok(LayerFrameState { frame_ids, descriptor: d }) + }) + .collect::>>()?; + Ok(LayerFrameStates { layer_id: *layer_id, states }) +} + +/// Reads `FSts` without inferring order from frame ids or interpreting loop-related fields. +pub fn frame_sets(descriptor: &Descriptor) -> Result>> { + let Some(Value::List(list)) = descriptor.get("FSts") else { + return Err(PsdError::invalid("animation FSts must be a list")); + }; + list.iter() + .map(|v| { + let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation frame set must be a descriptor")) }; + let Some(Value::Integer(id)) = d.get("FsID") else { return Err(PsdError::invalid("animation frame set FsID must be a long")) }; + let active_frame = match d.get("AFrm") { + None => None, + Some(Value::Integer(n)) => Some(*n), + _ => return Err(PsdError::invalid("animation frame set AFrm must be a long")), + }; + let Some(Value::List(ids)) = d.get("FsFr") else { return Err(PsdError::invalid("animation frame set FsFr must be a list")) }; + let frame_ids = ids + .iter() + .map(|v| match v { + Value::Integer(n) => Ok(*n), + _ => Err(PsdError::invalid("animation frame reference must be a long")), + }) + .collect::>>()?; + Ok(FrameSet { id: *id, active_frame, frame_ids, descriptor: d }) + }) + .collect() +} diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 73c71bab1d..513dda76ba 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -497,22 +497,35 @@ pub fn predict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { } } 16 => { - for i in (1..w).rev() { - let a = u16::from_be_bytes([row[2 * i], row[2 * i + 1]]); - let b = u16::from_be_bytes([row[2 * i - 2], row[2 * i - 1]]); - row[2 * i..2 * i + 2].copy_from_slice(&a.wrapping_sub(b).to_be_bytes()); + // One forward pass: the previous *original* sample stays in a + // register, so nothing is re-read after being overwritten. + let mut prev = 0u16; + for s in row.as_chunks_mut::<2>().0 { + let cur = u16::from_be_bytes(*s); + *s = cur.wrapping_sub(prev).to_be_bytes(); + prev = cur; } } 32 => { scratch.clear(); scratch.resize(rb, 0); - for i in 0..w { - for k in 0..4 { - scratch[k * w + i] = row[4 * i + k]; - } + // Split into four byte planes (MSB first) and delta the whole + // plane-major row. Plane k's first delta uses the last byte of + // plane k - 1, so seed each plane's "previous" with it. + let mut prev = [0u8; 4]; + if let Some(l) = row.as_chunks::<4>().0.last() { + prev = [0, l[0], l[1], l[2]]; } - for i in (1..rb).rev() { - scratch[i] = scratch[i].wrapping_sub(scratch[i - 1]); + let (p0, rest) = scratch.split_at_mut(w); + let (p1, rest) = rest.split_at_mut(w); + let (p2, p3) = rest.split_at_mut(w); + let planes = p0.iter_mut().zip(p1.iter_mut()).zip(p2.iter_mut().zip(p3.iter_mut())); + for (s, ((o0, o1), (o2, o3))) in row.as_chunks::<4>().0.iter().zip(planes) { + *o0 = s[0].wrapping_sub(prev[0]); + *o1 = s[1].wrapping_sub(prev[1]); + *o2 = s[2].wrapping_sub(prev[2]); + *o3 = s[3].wrapping_sub(prev[3]); + prev = [s[0], s[1], s[2], s[3]]; } row.copy_from_slice(&scratch); } @@ -538,22 +551,33 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { } } 16 => { - for i in 1..w { - let a = u16::from_be_bytes([row[2 * i], row[2 * i + 1]]); - let b = u16::from_be_bytes([row[2 * i - 2], row[2 * i - 1]]); - row[2 * i..2 * i + 2].copy_from_slice(&a.wrapping_add(b).to_be_bytes()); + // Running sum carried in a register; one pass over the row. + let mut acc = 0u16; + for s in row.as_chunks_mut::<2>().0 { + acc = acc.wrapping_add(u16::from_be_bytes(*s)); + *s = acc.to_be_bytes(); } } 32 => { - for i in 1..rb { - row[i] = row[i].wrapping_add(row[i - 1]); - } scratch.clear(); scratch.extend_from_slice(row); - for i in 0..w { - for k in 0..4 { - row[4 * i + k] = scratch[k * w + i]; - } + // The byte-wise running sum runs across the four planes, so + // plane k starts at the wrapping total of planes 0..k. + let (p0, rest) = scratch.split_at(w); + let (p1, rest) = rest.split_at(w); + let (p2, p3) = rest.split_at(w); + let sum = |p: &[u8]| p.iter().fold(0u8, |a, &b| a.wrapping_add(b)); + let b1 = sum(p0); + let b2 = b1.wrapping_add(sum(p1)); + let b3 = b2.wrapping_add(sum(p2)); + let mut acc = [0u8, b1, b2, b3]; + let planes = p0.iter().zip(p1).zip(p2.iter().zip(p3)); + for (o, ((&s0, &s1), (&s2, &s3))) in row.as_chunks_mut::<4>().0.iter_mut().zip(planes) { + acc[0] = acc[0].wrapping_add(s0); + acc[1] = acc[1].wrapping_add(s1); + acc[2] = acc[2].wrapping_add(s2); + acc[3] = acc[3].wrapping_add(s3); + *o = acc; } } d => return Err(PsdError::Unsupported(format!("prediction for depth {d}"))), diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs index a9700ded31..47d7986290 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -1,5 +1,117 @@ use super::*; +/// The straightforward index-based versions, kept as the oracle for the +/// register-carried rewrites in [`predict`] and [`unpredict`]. +mod reference { + use super::super::*; + + pub fn predict(buf: &mut [u8], layout: &PlaneLayout) { + let rb = layout.row_bytes(); + let w = layout.width; + let mut scratch = Vec::new(); + for row in buf.chunks_exact_mut(rb) { + match layout.depth { + 8 => { + for i in (1..row.len()).rev() { + row[i] = row[i].wrapping_sub(row[i - 1]); + } + } + 16 => { + for i in (1..w).rev() { + let a = u16::from_be_bytes([row[2 * i], row[2 * i + 1]]); + let b = u16::from_be_bytes([row[2 * i - 2], row[2 * i - 1]]); + row[2 * i..2 * i + 2].copy_from_slice(&a.wrapping_sub(b).to_be_bytes()); + } + } + _ => { + scratch.clear(); + scratch.resize(rb, 0); + for i in 0..w { + for k in 0..4 { + scratch[k * w + i] = row[4 * i + k]; + } + } + for i in (1..rb).rev() { + scratch[i] = scratch[i].wrapping_sub(scratch[i - 1]); + } + row.copy_from_slice(&scratch); + } + } + } + } + + pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) { + let rb = layout.row_bytes(); + let w = layout.width; + let mut scratch = Vec::new(); + for row in buf.chunks_exact_mut(rb) { + match layout.depth { + 8 => { + for i in 1..row.len() { + row[i] = row[i].wrapping_add(row[i - 1]); + } + } + 16 => { + for i in 1..w { + let a = u16::from_be_bytes([row[2 * i], row[2 * i + 1]]); + let b = u16::from_be_bytes([row[2 * i - 2], row[2 * i - 1]]); + row[2 * i..2 * i + 2].copy_from_slice(&a.wrapping_add(b).to_be_bytes()); + } + } + _ => { + for i in 1..rb { + row[i] = row[i].wrapping_add(row[i - 1]); + } + scratch.clear(); + scratch.extend_from_slice(row); + for i in 0..w { + for k in 0..4 { + row[4 * i + k] = scratch[k * w + i]; + } + } + } + } + } + } +} + +#[test] +fn prediction_matches_reference_on_random_planes() { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + for depth in [8u16, 16, 32] { + for width in (1..=70).chain([255, 256, 257, 1000, 1023]) { + for height in [1usize, 2, 3] { + for fill in 0..4 { + let layout = PlaneLayout { planes: 1, width, height, depth, version: Version::Psd }; + let len = layout.row_bytes() * height; + let src: Vec = (0..len) + .map(|_| match fill { + 0 => next() as u8, + 1 => 0xFF, + 2 => [0x00, 0xFF, 0x80, 0x7F][(next() & 3) as usize], + _ => (next() as u8) | 0xF0, + }) + .collect(); + let (mut want, mut got) = (src.clone(), src.clone()); + reference::predict(&mut want, &layout); + predict(&mut got, &layout).unwrap(); + assert_eq!(got, want, "predict depth {depth} width {width} height {height} fill {fill}"); + let (mut want, mut got) = (src.clone(), src); + reference::unpredict(&mut want, &layout); + unpredict(&mut got, &layout).unwrap(); + assert_eq!(got, want, "unpredict depth {depth} width {width} height {height} fill {fill}"); + } + } + } + } +} + #[test] fn checked_zip_validates_trailer_size_and_padding_budget() { let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd }; diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 891a1cde0d..5d0422f13a 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -43,6 +43,7 @@ pub mod abr; pub mod aco; pub mod act; +pub mod animation; pub mod ase; pub mod asl; pub mod atn; diff --git a/crates/psd/src/metadata.rs b/crates/psd/src/metadata.rs index 24d2eebca6..8e4565fe3f 100644 --- a/crates/psd/src/metadata.rs +++ b/crates/psd/src/metadata.rs @@ -27,6 +27,18 @@ pub struct MetadataItem { } impl MetadataItem { + /// Typed animation descriptor for `mlst` (sparse layer frame states) or `tmln` + /// (layer timeline tracks). Other metadata, including `cust` / XMP, is not interpreted. + /// The original item stays unchanged; inheritance and track evaluation belong to the importer. + pub fn animation_descriptor(&self) -> Option> { + matches!(&self.key, b"mlst" | b"tmln").then(|| { + if self.signature != *b"8BIM" { + return Err(PsdError::InvalidSignature { expected: "8BIM animation metadata", found: self.signature }); + } + crate::animation::parse_descriptor(&self.data) + }) + } + /// A new item; `data` is zero-padded to an even length as Photoshop writes it. pub fn new(key: [u8; 4], mut data: Vec) -> Self { if data.len() % 2 == 1 { diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs index 33ce147101..1ac69ed25d 100644 --- a/crates/psd/src/resources.rs +++ b/crates/psd/src/resources.rs @@ -28,6 +28,8 @@ pub mod ids { pub const EXIF: u16 = 1058; /// XMP metadata. pub const XMP: u16 = 1060; + /// Document timeline settings (versioned descriptor). + pub const TIMELINE_INFO: u16 = 1075; } /// One image resource block. @@ -169,6 +171,10 @@ pub enum ResourceData<'a> { Exif(&'a [u8]), /// 1060: XMP packet (UTF-8). Xmp(&'a [u8]), + /// 1075: document timeline settings; tracks and rational times remain descriptor data. + TimelineInfo(crate::VersionedDescriptor), + /// A `mani` legacy animation resource in the plug-in resource id range (4000..=4999). + Animation(crate::animation::AnimationResource<'a>), } impl ImageResource { @@ -199,6 +205,8 @@ impl ImageResource { ids::VERSION_INFO => VersionInfo::from_bytes(d).map(ResourceData::VersionInfo), ids::EXIF => Ok(ResourceData::Exif(d)), ids::XMP => Ok(ResourceData::Xmp(d)), + ids::TIMELINE_INFO => crate::animation::parse_descriptor(d).map(ResourceData::TimelineInfo), + 4000..=4999 if d.starts_with(b"mani") => crate::animation::AnimationResource::from_bytes(d).map(ResourceData::Animation), _ => return None, }) } diff --git a/crates/psd/tests/it/animation.rs b/crates/psd/tests/it/animation.rs new file mode 100644 index 0000000000..ac96b6a0b9 --- /dev/null +++ b/crates/psd/tests/it/animation.rs @@ -0,0 +1,262 @@ +//! Synthetic only: no personal PSDs, paths, or copied descriptor payloads. + +use photocraft_psd::animation::{AnimationRecord, AnimationResource, frame_info, frame_sets, layer_frame_states, parse_descriptor}; +use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; +use photocraft_psd::metadata::{MetadataItem, parse_shmd, write_shmd}; +use photocraft_psd::{ImageResource, PsdBuilder, PsdFile, ResourceData, TaggedBlock, Version}; +use proptest::prelude::*; + +fn descriptor() -> VersionedDescriptor { + VersionedDescriptor::new( + Descriptor::default() + .with("AFSt", Value::Integer(7)) + .with( + "FrIn", + Value::List(vec![ + Value::Descriptor( + Descriptor::default().with("FrID", Value::Integer(-3)).with("FrDl", Value::Integer(3)).with("future", Value::Boolean(true)), + ), + Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(21)).with("FrDl", Value::Integer(53))), + ]), + ) + .with( + "FSts", + Value::List(vec![Value::Descriptor( + Descriptor::default() + .with("FsID", Value::Integer(7)) + .with("AFrm", Value::Integer(0)) + .with("FsFr", Value::List(vec![Value::Integer(21), Value::Integer(-3)])) + .with("future", Value::RawData(vec![1, 2, 3])), + )]), + ), + ) +} + +fn resource(data: &[u8]) -> AnimationResource<'_> { + AnimationResource { + records: vec![ + AnimationRecord { key: *b"AnDs", data }, + AnimationRecord { key: *b"Roll", data: &[0; 8] }, + AnimationRecord { key: *b"next", data: &[9, 8, 7] }, + ], + } +} + +#[test] +fn raw_roundtrip_and_typed_views_preserve_order_and_unknown_data() { + let data = descriptor().to_bytes(); + let bytes = resource(&data).to_bytes().unwrap(); + let parsed = AnimationResource::from_bytes(&bytes).unwrap(); + assert_eq!(parsed, resource(&data)); + let d = parsed.records[0].descriptor().unwrap().unwrap(); + assert_eq!(d, descriptor()); + let frames = frame_info(&d.descriptor).unwrap(); + assert_eq!(frames.iter().map(|f| (f.id, f.delay_centiseconds)).collect::>(), [(-3, Some(3)), (21, Some(53))]); + assert_eq!(frames[0].descriptor.get("future"), Some(&Value::Boolean(true))); + let sets = frame_sets(&d.descriptor).unwrap(); + assert_eq!(sets[0].frame_ids, [21, -3], "playback order is not FrIn order or sorted id order"); + assert_eq!(sets[0].id, 7); + assert_eq!(sets[0].active_frame, Some(0)); + assert_eq!(sets[0].descriptor.get("future"), Some(&Value::RawData(vec![1, 2, 3]))); + assert!(parsed.records[1].descriptor().is_none()); + assert_eq!(parsed.to_bytes().unwrap(), bytes); +} + +#[test] +fn plugin_signature_not_a_single_resource_id_selects_the_parser() { + let data = descriptor().to_bytes(); + let bytes = resource(&data).to_bytes().unwrap(); + for id in [4000, 4003, 4999] { + let r = ImageResource::new(id, bytes.clone()); + assert!(matches!(r.parsed(), Some(Ok(ResourceData::Animation(_))))); + } + for id in [3999, 5000] { + assert!(ImageResource::new(id, bytes.clone()).parsed().is_none()); + } + assert!(ImageResource::new(4003, b"different plugin".to_vec()).parsed().is_none()); + assert!(matches!(ImageResource::new(4003, b"mani".to_vec()).parsed(), Some(Err(_)))); + assert!(matches!( + ImageResource::new(1075, VersionedDescriptor::new(Descriptor::default().with("Vrsn", Value::Integer(1))).to_bytes()).parsed(), + Some(Ok(ResourceData::TimelineInfo(_))) + )); +} + +#[test] +fn metadata_views_do_not_touch_xmp_or_other_items() { + let d = VersionedDescriptor::new(Descriptor::default().with("LaID", Value::Integer(42)).with( + "LaSt", + Value::List(vec![Value::Descriptor( + Descriptor::default() + .with("FrLs", Value::List(vec![Value::Integer(-3)])) + .with("blendOptions", Value::Descriptor(Descriptor::default().with("Opct", Value::Double(12.5)))), + )]), + )); + let items = vec![ + MetadataItem::new(*b"cust", vec![7, 9, 11]), + MetadataItem::new(*b"mlst", d.to_bytes()), + MetadataItem::new(*b"tmln", VersionedDescriptor::new(Descriptor::default().with("trackList", Value::List(vec![]))).to_bytes()), + MetadataItem::new(*b"next", vec![255; 4]), + ]; + let raw = write_shmd(&items); + let parsed = parse_shmd(&raw).unwrap(); + assert!(parsed[0].animation_descriptor().is_none()); + let layer_descriptor = parsed[1].animation_descriptor().unwrap().unwrap(); + assert_eq!(layer_descriptor, d); + let states = layer_frame_states(&layer_descriptor.descriptor).unwrap(); + assert_eq!(states.layer_id, 42); + assert_eq!(states.states[0].frame_ids, [-3]); + assert_eq!(states.states[0].descriptor.get("enab"), None, "missing visibility is not false"); + assert_eq!(states.states[0].descriptor.get("blendOptions"), Some(&Value::Descriptor(Descriptor::default().with("Opct", Value::Double(12.5))))); + assert!(parsed[2].animation_descriptor().unwrap().is_ok()); + assert!(parsed[3].animation_descriptor().is_none()); + assert_eq!(write_shmd(&parsed), raw); + let mut bad = parsed[1].clone(); + bad.signature = *b"nope"; + assert!(bad.animation_descriptor().unwrap().is_err()); +} + +#[test] +fn psd_and_psb_keep_animation_resources_and_metadata_byte_stable() { + let data = descriptor().to_bytes(); + let raw = resource(&data).to_bytes().unwrap(); + for version in [Version::Psd, Version::Psb] { + let mut file = PsdBuilder::new(1, 1).version(version).build().unwrap(); + file.resources.push(ImageResource::new(4003, raw.clone())); + file.global_blocks.push(TaggedBlock::new(*b"shmd", write_shmd(&[MetadataItem::new(*b"mlst", data.clone())]))); + let bytes = file.to_bytes().unwrap(); + let back = PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(back.to_bytes().unwrap(), bytes); + let animation = back.resource(4003).unwrap(); + assert!(matches!(animation.parsed(), Some(Ok(ResourceData::Animation(_))))); + } +} + +#[test] +fn every_truncation_and_hostile_envelope_length_is_rejected() { + let data = descriptor().to_bytes(); + let bytes = resource(&data).to_bytes().unwrap(); + for end in 0..bytes.len() { + assert!(AnimationResource::from_bytes(&bytes[..end]).is_err(), "prefix {end}"); + } + for at in [8, 20] { + for value in [0, 1, u32::MAX] { + let mut bad = bytes.clone(); + bad[at..at + 4].copy_from_slice(&value.to_be_bytes()); + assert!(AnimationResource::from_bytes(&bad).is_err(), "length {at} = {value}"); + } + } + for at in [0, 4, 12] { + let mut bad = bytes.clone(); + bad[at] = b'?'; + assert!(AnimationResource::from_bytes(&bad).is_err()); + } + let mut trailing = bytes.clone(); + trailing.push(0); + assert!(AnimationResource::from_bytes(&trailing).is_err()); +} + +#[test] +fn descriptor_padding_truncation_and_unknown_versions() { + let raw = descriptor().to_bytes(); + for end in 0..raw.len() { + assert!(parse_descriptor(&raw[..end]).is_err(), "descriptor prefix {end}"); + } + for padding in 0..=3 { + let mut padded = raw.clone(); + padded.extend(vec![0; padding]); + assert_eq!(parse_descriptor(&padded).unwrap(), descriptor()); + } + for tail in [vec![0; 4], vec![1], vec![0, 2]] { + let mut bad = raw.clone(); + bad.extend(tail); + assert!(parse_descriptor(&bad).is_err()); + } + let mut future = raw.clone(); + future[..4].copy_from_slice(&17u32.to_be_bytes()); + let bytes = resource(&future).to_bytes().unwrap(); + let r = AnimationResource::from_bytes(&bytes).unwrap(); + assert!(r.records[0].descriptor().unwrap().is_err()); + assert_eq!(r.to_bytes().unwrap(), bytes, "unsupported typed version must survive raw"); +} + +#[test] +fn absent_delays_and_duplicate_ids_are_not_silently_repaired() { + let d = Descriptor::default().with( + "FrIn", + Value::List(vec![ + Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(4))), + Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(4)).with("FrDl", Value::Integer(0))), + ]), + ); + let frames = frame_info(&d).unwrap(); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].delay_centiseconds, None); + assert_eq!(frames[1].delay_centiseconds, Some(0)); + let bytes = + AnimationResource { records: vec![AnimationRecord { key: *b"next", data: &[] }, AnimationRecord { key: *b"next", data: &[1] }] }.to_bytes().unwrap(); + assert_eq!(AnimationResource::from_bytes(&bytes).unwrap().to_bytes().unwrap(), bytes); +} + +#[test] +fn wrong_frame_and_set_types_return_errors() { + for value in [Value::Boolean(false), Value::List(vec![Value::Integer(1)]), Value::List(vec![Value::Descriptor(Descriptor::default())])] { + assert!(frame_info(&Descriptor::default().with("FrIn", value.clone())).is_err()); + assert!(frame_sets(&Descriptor::default().with("FSts", value)).is_err()); + } + for delay in [Value::Integer(-1), Value::Double(3.0)] { + let frame = Descriptor::default().with("FrID", Value::Integer(1)).with("FrDl", delay); + assert!(frame_info(&Descriptor::default().with("FrIn", Value::List(vec![Value::Descriptor(frame)]))).is_err()); + } + for (key, value) in [("FsID", Value::Boolean(false)), ("AFrm", Value::Double(0.0)), ("FsFr", Value::List(vec![Value::Boolean(true)]))] { + let mut set = Descriptor::default().with("FsID", Value::Integer(1)).with("FsFr", Value::List(vec![])); + set.items.retain(|(id, _)| !id.is(key)); + set = set.with(key, value); + assert!(frame_sets(&Descriptor::default().with("FSts", Value::List(vec![Value::Descriptor(set)]))).is_err()); + } +} + +#[test] +fn sparse_layer_states_retain_missing_properties_and_multiple_references() { + let first = Descriptor::default() + .with("FrLs", Value::List(vec![Value::Integer(21), Value::Integer(-3)])) + .with("enab", Value::Boolean(true)) + .with("Ofst", Value::Descriptor(Descriptor::default().with("Hrzn", Value::Integer(-7)).with("Vrtc", Value::Integer(12)))); + let second = Descriptor::default().with("FrLs", Value::List(vec![Value::Integer(99)])); + let d = Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Descriptor(first.clone()), Value::Descriptor(second)])); + let view = layer_frame_states(&d).unwrap(); + assert_eq!(view.states[0].frame_ids, [21, -3]); + assert_eq!(view.states[0].descriptor, &first); + assert_eq!(view.states[1].descriptor.get("Ofst"), None); + assert_eq!(view.states[1].descriptor.get("enab"), None); + for d in [ + Descriptor::default(), + Descriptor::default().with("LaID", Value::Boolean(true)), + Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::Boolean(true)), + Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Integer(0)])), + ] { + assert!(layer_frame_states(&d).is_err()); + } + for state in [ + Descriptor::default(), + Descriptor::default().with("FrLs", Value::Integer(0)), + Descriptor::default().with("FrLs", Value::List(vec![Value::Boolean(true)])), + ] { + let d = Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Descriptor(state)])); + assert!(layer_frame_states(&d).is_err()); + } +} + +proptest! { + #[test] + fn arbitrary_animation_bytes_never_panic(data in proptest::collection::vec(any::(), 0..2048)) { + let _ = AnimationResource::from_bytes(&data); + let _ = parse_descriptor(&data); + } + + #[test] + fn opaque_record_roundtrip(data in proptest::collection::vec(any::(), 0..2048), key in any::<[u8; 4]>()) { + let r = AnimationResource { records: vec![AnimationRecord { key, data: &data }] }; + let bytes = r.to_bytes().unwrap(); + prop_assert_eq!(AnimationResource::from_bytes(&bytes).unwrap(), r); + } +} diff --git a/crates/psd/tests/it/corpus.rs b/crates/psd/tests/it/corpus.rs index 90abb4fefd..a61f911e23 100644 --- a/crates/psd/tests/it/corpus.rs +++ b/crates/psd/tests/it/corpus.rs @@ -19,6 +19,64 @@ fn collect(dir: &Path, out: &mut Vec) { } } +/// The existing pinned ag-psd corpus includes public animation cases. Exercise typed syntax +/// against those without adding personal files or new corpus pins. +#[test] +fn corpus_animation_syntax() { + use photocraft_psd::ResourceData; + use photocraft_psd::animation::{frame_info, frame_sets, layer_frame_states}; + use photocraft_psd::metadata::parse_shmd; + + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd/ag-psd/read-write"); + for (case, delay) in [("animation-frame", Some(30)), ("animation-offset", Some(50)), ("animation-effects", None)] { + for name in ["src.psd", "expected.psd"] { + let path = root.join(case).join(name); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}; run cargo xtask corpus --psd", path.display())); + let psd = PsdFile::from_bytes(&bytes).unwrap(); + let mut found = 0; + let mut decoded_descriptors = 0; + for resource in &psd.resources { + if let Some(Ok(ResourceData::Animation(animation))) = resource.parsed() { + found += 1; + assert_eq!(animation.to_bytes().unwrap(), resource.data); + for record in &animation.records { + if let Some(d) = record.descriptor() { + let d = d.unwrap(); + decoded_descriptors += 1; + let frames = frame_info(&d.descriptor).unwrap(); + assert_eq!(frames.len(), 2, "{case}/{name}"); + assert!(frames.iter().all(|f| f.delay_centiseconds == delay), "{case}/{name}"); + let sets = frame_sets(&d.descriptor).unwrap(); + assert_eq!(sets.len(), 1); + assert_eq!(sets[0].frame_ids.len(), 2); + assert!(sets[0].frame_ids.iter().all(|id| frames.iter().any(|f| f.id == *id))); + } + } + } + } + assert_eq!(found, 1, "{case}/{name}"); + assert_eq!(decoded_descriptors, 1, "expected one decoded AnDs descriptor in {case}/{name}"); + let mut state_layers = 0; + for layer in psd.layers() { + for block in &layer.blocks { + if block.key == *b"shmd" { + for item in parse_shmd(&block.data).unwrap() { + if item.key == *b"mlst" { + let d = item.animation_descriptor().unwrap().unwrap(); + let states = layer_frame_states(&d.descriptor).unwrap(); + assert!(!states.states.is_empty()); + state_layers += 1; + } + } + } + } + } + assert_eq!(state_layers, 2, "{case}/{name}"); + assert_eq!(psd.to_bytes().unwrap(), bytes); + } + } +} + /// Files known to be invalid upstream, with the reason. They are reported but /// do not fail the test. const KNOWN_BAD: &[(&str, &str)] = diff --git a/crates/psd/tests/it/main.rs b/crates/psd/tests/it/main.rs index db445f849c..fef8708849 100644 --- a/crates/psd/tests/it/main.rs +++ b/crates/psd/tests/it/main.rs @@ -1,5 +1,6 @@ //! The crate's integration tests, linked into one test binary. +mod animation; mod atn_contract; mod atn_v12; mod builder; diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs index ac2e4b772b..998720b8b5 100644 --- a/crates/raster/src/memory/system.rs +++ b/crates/raster/src/memory/system.rs @@ -206,6 +206,16 @@ pub(super) mod linux { MembershipParse::Malformed => return CgroupLimits::Unreadable, }; let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); + // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) + // shows the process its membership path but no interface files, so no limit is + // observable. Failing closed there reported 0 bytes free and refused every PSD on a + // machine with tens of GB. A present directory still takes the guarded path below. + // Only a confirmed NotFound counts as absent: a stat that fails for another reason + // (permissions) leaves the directory possibly present, so that case stays fail-closed. + let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound); + if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { + return CgroupLimits::NotConstrained; + } if let Some(path) = membership.v1_memory { let Some(dir) = resolve_dir(sys_root, mountinfo.as_deref(), path, "cgroup", Some("memory")) else { @@ -336,6 +346,21 @@ pub(super) mod linux { best.map(|(_, _, dir)| dir) } + /// A cgroup (v1 or v2) filesystem. + fn is_cgroup_mount(mount: &Mount) -> bool { + mount.fstype == "cgroup" || mount.fstype == "cgroup2" + } + + /// `mountinfo` parsed to at least one mount, none of them a cgroup filesystem. An empty or + /// garbled file parses to no mounts at all, which proves nothing about cgroups; a live kernel + /// always lists the process's own root, so only a real list can show a cgroup mount is absent. + /// Every non-empty line must parse: a skipped truncated line could be the cgroup mount. + fn lists_mounts_without_cgroup(info: &str) -> bool { + let mounts = parse_mountinfo(info); + let lines = info.lines().filter(|l| !l.trim().is_empty()).count(); + !mounts.is_empty() && mounts.len() == lines && !mounts.iter().any(is_cgroup_mount) + } + /// Trims trailing slashes so `Path` equality holds while walking ancestors, keeping `/`. fn normalize_root(point: &str) -> PathBuf { let trimmed = point.trim_end_matches('/'); @@ -933,6 +958,33 @@ mod tests { assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "without metadata the absence of a constraint cannot be established"); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // No cgroup filesystem mounted (Flatpak): the limit is invisible, host memory applies. + let (proc, _) = fixture("no-cgroup-mount"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed. + let (proc, _) = fixture("truncated-mountinfo-line"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A cgroup2 mount at an alternate path must be honoured while /sys/fs/cgroup is absent. + let (proc, _) = fixture("alternate-cgroup-mount"); + let sys = proc.parent().unwrap().join("absent-sys"); + let alt = proc.parent().unwrap().join("alt-cgroup"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw - cgroup2 cgroup2 rw\n", alt.display())); + write(&alt.join("app/memory.max"), "1073741824\n"); + write(&alt.join("app/memory.current"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(1 << 30), swap: None }); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // Available but not delegated anywhere on the path: no cgroup limit applies. let (proc, sys) = fixture("v2-not-enabled"); write(&proc.join("self/cgroup"), "0::/app\n"); @@ -1153,6 +1205,51 @@ mod tests { std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); } + /// A missing `/sys/fs/cgroup` only means "no limit visible" when `mountinfo` was read, parsed + /// to real mounts and lists no cgroup filesystem; every other combination stays fail-closed. + #[cfg(target_os = "linux")] + #[test] + fn linux_absent_cgroup_root_needs_proof_before_it_means_unconstrained() { + let cases: [(&str, Option<&str>); 3] = + [("mountinfo-missing", None), ("mountinfo-empty", Some("")), ("mountinfo-garbage", Some("not a mountinfo line\n\n- - -\n"))]; + for (name, mountinfo) in cases { + let (proc, _) = fixture(name); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app\n"); + if let Some(text) = mountinfo { + write(&proc.join("self/mountinfo"), text); + } + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + // A stat error that is not NotFound (a path component that is a file) may hide a real + // directory, so it is not "absent" either. + let (proc, _) = fixture("sys-root-not-a-directory"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + let sys = proc.join("self/cgroup/fs/cgroup"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + /// A cgroup mount listed at an alternate path means a limit may exist: v1 and v2 alike, and + /// when its files cannot be read the answer is fail-closed, not "unconstrained". + #[cfg(target_os = "linux")] + #[test] + fn linux_alternate_cgroup_mounts_with_unreadable_limits_fail_closed() { + for (name, membership, fstype, options) in [("alt-v1", "4:memory:/app\n", "cgroup", "rw,memory"), ("alt-v2", "0::/app\n", "cgroup2", "rw")] { + let (proc, _) = fixture(name); + let sys = proc.parent().unwrap().join("absent-sys"); + let alt = proc.parent().unwrap().join("alt-cgroup"); + write(&proc.join("self/cgroup"), membership); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw - {fstype} {fstype} {options}\n", alt.display())); + std::fs::create_dir_all(alt.join("app")).unwrap(); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + } + #[cfg(target_os = "linux")] #[test] fn linux_snapshot_combines_host_meminfo_and_cgroup_room() { diff --git a/crates/raw/README.md b/crates/raw/README.md index 03c95390a4..bbda6732da 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -38,6 +38,9 @@ Implemented only from public specifications, papers and observation of files: stored in the files; they were recovered by black-box analysis of CC0 raw.pixls.us samples (the same scenes shot compressed and uncompressed) for LightCraft (storytold/lightcraft#86) and verified there on ~45 files from ~35 bodies. + The "lossy after split" fixed-rate section (word size, prefix-to-category tables, bin-centre + dequantisation, end-of-strip rule) was likewise derived by black-box analysis of 11 CC0 + raw.pixls.us files for LightCraft (storytold/lightcraft#633). * Sony cRAW (ARW 2): H. Dietz, "Sony ARW2 Compression: Artifacts And Credible Repair" (Electronic Imaging 2016) and the RawDigger / diglloyd write-ups of the 11 + 7-bit scheme; the exact bit layout and tone-curve scale were established by observation of sample files. @@ -72,14 +75,14 @@ camera colour tables were copied. | DNG | Uncompressed (8–16 bit, packed or not), Deflate (compression 8, predictors 1 and 2), lossless JPEG, lossy JPEG (DNG 1.4 compression 34892: 8-bit baseline JPEG tiles or strips, gray for CFA, YCbCr-coded RGB for LinearRaw; decoded by `zune-jpeg`, the stored 8-bit values then go through the same LinearizationTable / BlackLevel / WhiteLevel as every other depth) and JPEG XL (DNG 1.7, e.g. Samsung Expert RAW; decoded by `jxl-oxide`; not in wasm32 builds, where it is `Unsupported`); strips and tiles; CFA (Bayer) and LinearRaw (three-sample colour, or one-sample monochrome such as Leica Monochrom and film-scanner DNGs, developed as neutral grey with no white balance or colour matrix); LinearizationTable, BlackLevel (+ repeat, DeltaH/V), WhiteLevel, ActiveArea, DefaultCrop, ColorMatrix1/2, CameraCalibration, ForwardMatrix, AnalogBalance, AsShotNeutral / AsShotWhiteXY, BaselineExposure, Orientation, floating-point JPEG XL raw data (DNG 1.7 lossy LinearRaw, as Adobe DNG Converter writes it; scaled by the highest WhiteLevel), OpcodeList2 GainMap (lens shading) and MapPolynomial | | DNG (floating point other than JPEG XL; opcodes other than OpcodeList2 GainMap and MapPolynomial; ProfileGainTableMap) | Unsupported / not applied (reported) | | CR2 | Lossless JPEG with slices, borders and as-shot white balance from the maker note, black measured on the masked border. CR2 has no CFA tag and the row phase varies by model, so it is measured from the data (the green diagonal), with a Canon model-ID table as the fallback (see `src/cr2.rs`) | -| CR2 sRAW / mRAW | Unsupported | +| CR2 sRAW / mRAW (subsampled YCbCr) | Decoded to camera RGB and developed like LinearRaw: Canon's subsampled lossless JPEG (Y 2×2 or 2×1), BT.601 inverse, bilinear chroma, the per-shot sRAW gains from ColorData (version 15: EOS 6D Mark II, 77D, 200D, 800D; other bodies warn and rely on the fitted camera look). See `src/sraw.rs` | | NEF / NRW, ARW, PEF and other TIFF/EP raws | Uncompressed and lossless-JPEG (incl. Sony lossless ARW) CFA data | -| Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files are unsupported (preview fallback) | +| Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files (a split row in `0x0096`) are decoded: rows from the split on are fixed-rate words of `bits - 4` bits (storytold/lightcraft#633); a strip that does not end as that rule says falls back to the preview | | Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits; applied WB and black from plain tags or encrypted SR2SubIFD with the measured common key. If metadata is unreadable, black falls back to 512 and WB to grey-world. Measured ILCE-7 / ILCE-6000 image area; camera colour calibration remains incomplete | | Panasonic / Leica RW2, RawFormat 5 (12- and 14-bit packed) | Decoded, with PanasonicRaw black / white / WB / sensor borders | | Panasonic / Leica RW2, RawFormat 3 and 4 (vendor-compressed, 12-bit) | Decoded; the black level is read 15 counts above the recorded tag; PanasonicRaw white / WB / sensor borders | | Olympus ORF, uncompressed 16-bit (E-1, E-400…) | Decoded, with ImageProcessing black / WB / ValidBits / crop | -| Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 6 and newer, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead | +| Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 6 and newer, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead | | Fujifilm RAF, uncompressed (X-Trans I–V, GFX and Bayer bodies since about 2010) | Decoded: 16-bit containers (either byte order), 12-bit LSB-first packing, 14-bit packing in 32-bit words; X-Trans 6×6 or Bayer 2×2 layout, black, as-shot WB, crop, RawExposureBias, orientation from the preview's EXIF | | Fujifilm compressed RAF, early FinePix / SuperCCD RAF (no CFA TIFF) | Unsupported (no public description of the compression); preview fallback | | CR3 | Native CRX unsupported; bounded JPEG-track/PRVW preview fallback with CMT1 orientation. I/O labels the result as an 8-bit camera preview | @@ -88,8 +91,8 @@ camera colour tables were copied. Nikon maker-note compression modes 6/10 select checked little-endian packed 12/14-bit rows even when TIFF Compression is 34713. The modern lossy `0x44 0x40` curve uses its smaller encoded domain while preserving sensor ADUs. Valid Nikon CropArea -coordinates take precedence over model fallbacks. HE/HE* and lossy-after-split -remain unsupported. Four pinned CC0 Z6 files cover both bit depths and both paths. +coordinates take precedence over model fallbacks. HE/HE* remain unsupported; +lossy-after-split strips are decoded (see the NEF row above). Four pinned CC0 Z6 files cover both bit depths and both paths. ## Development pipeline diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rs index 8e851c5d59..990745b7e2 100644 --- a/crates/raw/src/cr2.rs +++ b/crates/raw/src/cr2.rs @@ -5,7 +5,8 @@ //! lossless JPEG (T.81 process 14) whose decoded sample sequence fills the //! sensor image in vertical slices: the private tag 0xC640 gives the slice //! count, slice width and last slice width; slice 0 is filled row by row, -//! then slice 1, and so on. sRAW/mRAW (subsampled YCbCr) is not supported. +//! then slice 1, and so on. sRAW / mRAW (subsampled YCbCr) is decoded to +//! camera RGB by `sraw.rs`. //! //! Sensor geometry and the as-shot white balance come from the Canon maker //! note (an IFD at the MakerNote offset, values relative to the TIFF header): @@ -45,7 +46,7 @@ use crate::error::{RawError, Result}; use crate::sensor::{BlackLevels, Cfa, Rect, Sensor}; use crate::tiff::{Ifd, Tiff, tag}; -use crate::{Limits, RawFormat, ljpeg}; +use crate::{Limits, RawFormat, ljpeg, sraw}; const CANON_SENSOR_INFO: u16 = 0x00E0; const CANON_COLOR_DATA: u16 = 0x4001; @@ -115,26 +116,38 @@ pub(crate) fn maker_note(t: &Tiff, ifds: &[Ifd]) -> Option { /// As-shot white-balance multipliers (R, G, B) from ColorData. fn as_shot_wb(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> { - let e = mn.get(CANON_COLOR_DATA)?; - // The entry is UNDEFINED: its bytes are a table of 16-bit words (file byte order), and the - // offsets below count words, not bytes. Reads stay inside the entry's own byte count. - let bytes = e.unit().checked_mul(e.count as usize)?; - let word = |off: usize| { - let at = off.checked_mul(2)?.checked_add(e.at)?; - (at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten().map(f64::from) - }; // Word offsets of WB_RGGBLevelsAsShot used by the ColorData versions. - for off in [0x3F, 0x47, 0x19, 0x22] { - let (Some(r), Some(g1), Some(g2), Some(b)) = (word(off), word(off + 1), word(off + 2), word(off + 3)) else { - continue; - }; - let g = (g1 + g2) / 2.0; - let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g)); - if plausible { - return Some([r / g, 1.0, b / g]); - } - } - None + [0x3F, 0x47, 0x19, 0x22].into_iter().find_map(|off| color_data_rggb(t, mn, off)) +} + +/// Word `off` of ColorData. The entry is UNDEFINED: its bytes are a table of 16-bit words (file +/// byte order), and the offsets count words, not bytes. Reads stay inside the entry's own byte +/// count. +fn color_data_word(t: &Tiff, mn: &Ifd, off: usize) -> Option { + let e = mn.get(CANON_COLOR_DATA)?; + let bytes = e.unit().checked_mul(e.count as usize)?; + let at = off.checked_mul(2)?.checked_add(e.at)?; + (at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten() +} + +/// RGGB levels at ColorData word `off` as multipliers relative to green, when plausible. +fn color_data_rggb(t: &Tiff, mn: &Ifd, off: usize) -> Option<[f64; 3]> { + let word = |k: usize| color_data_word(t, mn, off.checked_add(k)?).map(f64::from); + let (r, g1, g2, b) = (word(0)?, word(1)?, word(2)?, word(3)?); + let g = (g1 + g2) / 2.0; + let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g)); + plausible.then(|| [r / g, 1.0, b / g]) +} + +/// ColorData versions whose sRAW gains (see `sraw.rs`) sit at a word offset we observed: +/// version 15 (EOS 6D Mark II, 77D, 200D, 800D) at 0x80, just before the daylight preset. +const SRAW_GAINS: [(u16, usize); 1] = [(15, 0x80)]; + +/// The per-shot gains an sRAW's stored RGB was divided by, relative to green. +fn sraw_gains(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> { + let version = color_data_word(t, mn, 0)?; + let (_, off) = SRAW_GAINS.iter().find(|(v, _)| *v == version)?; + color_data_rggb(t, mn, *off) } /// The white (clipping) level: the largest value when a meaningful share of @@ -181,6 +194,86 @@ pub(crate) fn masked_black(data: &[u16], width: usize, area: Rect) -> Option<[f3 Some([0, 1, 2, 3].map(|k| sum[k] as f32 / n[k] as f32)) } +/// The slice widths of CR2 tag 0xC640 (count, width, last width), in samples. The tag is SHORT: +/// larger values (a LONG in a damaged file) are refused, which also bounds the sum. +fn slice_widths(tag: &[u32]) -> Option> { + let short = 1..=u32::from(u16::MAX); + match tag { + [n, w, last] if *n < 64 && short.contains(w) && short.contains(last) => { + let mut ws = vec![*w as usize; *n as usize]; + ws.push(*last as usize); + Some(ws) + } + _ => None, + } +} + +/// The image area inside `full` from the maker note's SensorInfo ([1] width, [2] height, [5] +/// left, [6] top, [7] right, [8] bottom border, inclusive); `full` when absent or empty. +fn image_area(t: &Tiff, mn: Option<&Ifd>, full: Rect) -> Rect { + let info = mn.map(|m| t.tag_uints(m, CANON_SENSOR_INFO)).unwrap_or_default(); + let active = match info.get(5..9) { + Some(&[l, tp, r, b]) if r > l && b > tp => Rect::new(l as usize, tp as usize, (r - l + 1) as usize, (b - tp + 1) as usize).intersect(&full), + _ => full, + }; + if active.is_empty() { full } else { active } +} + +/// sRAW / mRAW: subsampled YCbCr, developed as three-sample camera RGB (see `sraw.rs`). +fn decode_sraw(t: &Tiff, ifds: &[Ifd], ifd0: &Ifd, slices: &[u32], src: &[u8], frame: ljpeg::Frame, limits: &Limits) -> Result { + let per_mcu = frame.h * frame.v + 2; + let total = frame.samples().ok_or_else(|| RawError::malformed("CR2 frame too large"))?; + let widths = slice_widths(slices).unwrap_or_else(|| vec![frame.width / frame.h * per_mcu]); + let row: usize = widths.iter().sum(); + if row == 0 || !row.is_multiple_of(per_mcu) || !total.is_multiple_of(row) { + return Err(RawError::malformed("CR2 sRAW slices do not match the JPEG frame")); + } + let (width, height) = (row / per_mcu * frame.h, total / row * frame.v); + // The RGB output: three u16 per pixel. + limits.check(width as u64, height as u64, 6)?; + let (_, samples) = ljpeg::decode_subsampled(src, total)?; + let planes = sraw::planes(&frame, &samples, &widths)?; + drop(samples); + + let mut warnings = Vec::new(); + let mn = maker_note(t, ifds); + let camera_wb = mn.as_ref().and_then(|m| as_shot_wb(t, m)); + let gains = mn.as_ref().and_then(|m| sraw_gains(t, m)); + if gains.is_none() { + warnings.push("the sRAW colour gains of this camera are not known; colours rely on the look fitted to the camera's JPEG".to_string()); + } + let offset = (1u32 << (frame.precision - 1)) as f32; + let data = sraw::camera_rgb(&planes, offset, gains.unwrap_or([1.0; 3])); + drop(planes); + let full = Rect::new(0, 0, width, height); + let active = image_area(t, mn.as_ref(), full); + let white = [0, 1, 2].map(|k| sraw::clip_level(&data, k, sraw::FULL_SCALE)); + Ok(Sensor { + format: RawFormat::Cr2, + make: t.tag_ascii(ifd0, tag::MAKE), + model: t.tag_ascii(ifd0, tag::MODEL), + width, + height, + samples: 3, + data, + cfa: None, + linearization: None, + // Y is stored black-subtracted. + black: BlackLevels::uniform(0.0), + white, + active, + crop: active, + color: Default::default(), + camera_wb, + orientation: crate::tiff::orientation(t.tag_uint(ifd0, tag::ORIENTATION)), + baseline_exposure: 0.0, + gain_maps: Vec::new(), + tone_curve: Vec::new(), + black_point: 0.0, + warnings, + }) +} + pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result { let ifds = t.all_ifds(); let ifd0 = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("CR2 has no IFD0"))?; @@ -191,23 +284,16 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result { let src = t.bytes(off, len).or_else(|| t.data.get(off..)).ok_or_else(|| RawError::malformed("CR2 raw data lies outside the file"))?; let frame = ljpeg::frame(src).map_err(|e| match e { - RawError::Unsupported(m) if m.contains("subsampled") => RawError::unsupported("Canon sRAW / mRAW"), + RawError::Unsupported(m) if m.contains("subsampled") => RawError::unsupported("this Canon sRAW / mRAW layout"), e => e, })?; let total = frame.samples().ok_or_else(|| RawError::malformed("CR2 frame too large"))?; let slices = t.tag_uints(&raw, tag::CR2_SLICE); - let (width, widths) = match slices.as_slice() { - [n, w, last] if *n < 64 && *w > 0 && *last > 0 => { - let (n, w, last) = (*n as usize, *w as usize, *last as usize); - let mut ws = vec![w; n]; - ws.push(last); - (n * w + last, ws) - } - _ => { - let w = frame.width * frame.components; - (w, vec![w]) - } - }; + if frame.is_subsampled() { + return decode_sraw(t, &ifds, &ifd0, &slices, src, frame, limits); + } + let widths = slice_widths(&slices).unwrap_or_else(|| vec![frame.width * frame.components]); + let width: usize = widths.iter().sum(); if width == 0 || total % width != 0 { return Err(RawError::malformed("CR2 slices do not match the JPEG frame")); } @@ -231,13 +317,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result { let mut warnings = Vec::new(); let mn = maker_note(t, &ifds); let full = Rect::new(0, 0, width, height); - // SensorInfo: [1] width, [2] height, [5] left, [6] top, [7] right, [8] bottom border (inclusive). - let info = mn.as_ref().map(|m| t.tag_uints(m, CANON_SENSOR_INFO)).unwrap_or_default(); - let active = match info.get(5..9) { - Some(&[l, tp, r, b]) if r > l && b > tp => Rect::new(l as usize, tp as usize, (r - l + 1) as usize, (b - tp + 1) as usize).intersect(&full), - _ => full, - }; - let active = if active.is_empty() { full } else { active }; + let active = image_area(t, mn.as_ref(), full); // Black: the masked columns left of the image (skipping a few edge columns). let black = if active.x >= 16 { // Only the outer half: the columns next to the image area can be partly exposed. diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 6303931811..ea8493023a 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -147,6 +147,7 @@ impl Padded { } /// Per 2×2 position, per output colour: kernel taps as (offset, weight). +#[cfg(test)] fn kernels(phase: [u8; 4], method: Demosaic, stride: usize) -> [[Vec<(isize, f32)>; 3]; 4] { let color = |x: isize, y: isize| phase[((y & 1) * 2 + (x & 1)) as usize]; let s = stride as isize; @@ -213,9 +214,8 @@ pub(crate) fn demosaic(p: &Padded, phase: [u8; 4], method: Demosaic, to_xyz: &Ma ); return out; } - let ks = kernels(phase, method, s); let rows = par::band_rows(w); - par::chunks_mut(&mut out, rows * w * 3, |band, chunk| linear_band(&p.data, w, s, phase, method, &ks, band * rows, 0, chunk)); + par::chunks_mut(&mut out, rows * w * 3, |band, chunk| linear_band(&p.data, w, s, phase, method, band * rows, 0, chunk)); out } @@ -266,13 +266,12 @@ pub(crate) fn demosaic_fused( }); 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); + linear_band(win, w, s, phase, method, band * FUSED_ROWS, band * FUSED_ROWS, buf); emit(buf, chunk); }); } @@ -283,40 +282,120 @@ 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]) { +fn linear_band(d: &[f32], w: usize, s: usize, phase: [u8; 4], method: Demosaic, 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; + // The two colours of this row's 2-pixel period; the row kinds a Bayer pattern has get + // code of their own with the colours as constants. + let (c0, c1) = (usize::from(phase[(y & 1) * 2]).min(2), usize::from(phase[(y & 1) * 2 + 1]).min(2)); + match (method == Demosaic::Bilinear, c0, c1) { + (true, 0, 1) => linear_row::<0, 1, false>(d, base, s, row), + (true, 1, 0) => linear_row::<1, 0, false>(d, base, s, row), + (true, 2, 1) => linear_row::<2, 1, false>(d, base, s, row), + (true, 1, 2) => linear_row::<1, 2, false>(d, base, s, row), + (false, 0, 1) => linear_row::<0, 1, true>(d, base, s, row), + (false, 1, 0) => linear_row::<1, 0, true>(d, base, s, row), + (false, 2, 1) => linear_row::<2, 1, true>(d, base, s, row), + (false, 1, 2) => linear_row::<1, 2, true>(d, base, s, row), + (bilinear, _, _) => { + for (x, o) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { + let (own, hc) = if x & 1 == 0 { (c0, c1) } else { (c1, c0) }; + *o = if bilinear { bilinear_site(d, base + x, s, own, hc) } else { mhc_site(d, base + x, s, own, hc) }; } - 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); } } } } +/// A row of output whose even pixels are colour `A` and odd pixels colour `B`, MHC or bilinear. +fn linear_row(d: &[f32], base: usize, s: usize, row: &mut [f32]) { + let site = |i: usize, own: usize, hc: usize| if MHC { mhc_site(d, i, s, own, hc) } else { bilinear_site(d, i, s, own, hc) }; + let (pairs, rest) = row.as_chunks_mut::<6>(); + for (j, pair) in pairs.iter_mut().enumerate() { + let i = base + 2 * j; + pair[..3].copy_from_slice(&site(i, A, B)); + pair[3..].copy_from_slice(&site(i + 1, B, A)); + } + if let Some(last) = rest.first_chunk_mut::<3>() { + *last = site(base + 2 * pairs.len(), A, B); + } +} + +/// Direct Bayer bilinear (the kernels' result without the tap loops) for the pixel at plane index +/// `i` of colour `own` (and, when green, its row neighbours' colour `hc`). +#[inline(always)] +fn bilinear_site(d: &[f32], i: usize, s: usize, own: usize, hc: usize) -> [f32; 3] { + let mut o = [0.0f32; 3]; + let (n, so, e, wv) = (d[i - s], d[i + s], d[i + 1], d[i - 1]); + if own == 1 { + 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; + } + o +} + +/// Malvar–He–Cutler for the pixel at plane index `i`, whose colour is `own` (and, when green, its +/// row neighbours' `hc`): the kernels of `kernels` written out, the same taps in the same order +/// with their weights (kernel / 8, exact in f32), so the sums are those of the tap loop. +#[inline(always)] +fn mhc_site(d: &[f32], i: usize, s: usize, own: usize, hc: usize) -> [f32; 3] { + let mut o = [0.0f32; 3]; + o[own] = (0.0 + d[i]).clamp(0.0, 1.0); + if own == 1 { + // R and B at a green site: the row neighbours' colour from the row, the other from the + // column. + o[hc] = mhc_at_green(d, i, 1, s, s).clamp(0.0, 1.0); + o[2 - hc] = mhc_at_green(d, i, s, 1, s).clamp(0.0, 1.0); + } else { + let v = 0.0 + + 0.5 * d[i] + + 0.25 * d[i - 1] + + 0.25 * d[i + 1] + + 0.25 * d[i - s] + + 0.25 * d[i + s] + + -0.125 * d[i - 2] + + -0.125 * d[i + 2] + + -0.125 * d[i - 2 * s] + + -0.125 * d[i + 2 * s]; + o[1] = v.clamp(0.0, 1.0); + let v = 0.0 + + 0.75 * d[i] + + 0.25 * d[i - s - 1] + + 0.25 * d[i - s + 1] + + 0.25 * d[i + s - 1] + + 0.25 * d[i + s + 1] + + -0.1875 * d[i - 2] + + -0.1875 * d[i + 2] + + -0.1875 * d[i - 2 * s] + + -0.1875 * d[i + 2 * s]; + o[2 - own] = v.clamp(0.0, 1.0); + } + o +} + +/// MHC's red or blue at a green site: `a` is the step along the colour's own line (1 along the +/// row, `s` down the column), `b` the step across it. +#[inline(always)] +fn mhc_at_green(d: &[f32], i: usize, a: usize, b: usize, s: usize) -> f32 { + 0.0 + 0.625 * d[i] + + 0.5 * d[i - a] + + 0.5 * d[i + a] + + -0.125 * d[i - s - 1] + + -0.125 * d[i - s + 1] + + -0.125 * d[i + s - 1] + + -0.125 * d[i + s + 1] + + -0.125 * d[i - 2 * a] + + -0.125 * d[i + 2 * a] + + 0.0625 * d[i - 2 * b] + + 0.0625 * d[i + 2 * b] +} + /// 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 @@ -1286,6 +1365,85 @@ mod tests { } } + /// The tap-loop evaluation of bilinear and MHC that `linear_band` replaced. + #[allow(clippy::too_many_arguments)] + fn linear_band_ref( + 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); + } + } + } + } + + #[test] + fn mhc_written_out_gives_the_bits_of_the_tap_loop() { + // Every Bayer phase, odd and tiny sizes, values outside 0..1, signed zeros, NaN and infinities. + for (w, h) in [(1, 1), (2, 3), (5, 4), (17, 13), (64, 9)] { + let mut s = 0x9E37_79B9_7F4A_7C15u64; + let mut plane: Vec = (0..w * h) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32) * 1.6 - 0.3 + }) + .collect(); + for (k, v) in [0.0, -0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1.0, 1e-30].into_iter().enumerate() { + let n = plane.len(); + plane[(k * 7 + 1) % n] = v; + } + let p = Padded::from_plane(&plane, w, h); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + for method in [Demosaic::Bilinear, Demosaic::Mhc] { + let ks = kernels(phase, method, p.stride); + let mut want = vec![0.0f32; w * h * 3]; + linear_band_ref(&p.data, w, p.stride, phase, method, &ks, 0, 0, &mut want); + let mut got = vec![0.0f32; w * h * 3]; + linear_band(&p.data, w, p.stride, phase, method, 0, 0, &mut got); + // Equal bits; a NaN may come out with another sign or payload (the order the + // two evaluations meet two NaNs in), which the encoding maps to the same code. + let bad: Vec<_> = + got.iter().zip(&want).enumerate().filter(|(_, (a, b))| a.to_bits() != b.to_bits() && !(a.is_nan() && b.is_nan())).collect(); + assert!(bad.is_empty(), "{w}x{h} {phase:?} {}: {bad:?}", method.id()); + } + } + } + } + #[test] fn lab_table_is_accurate() { let l = LabF::new(); diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index aaeb390eff..ee7136e2cb 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -118,6 +118,70 @@ impl<'a> Scale<'a> { } } +/// Row `y` of a LinearRaw (3-sample or monochrome) frame from column `x0` on, `row.len() / 3` +/// pixels: [`Scale::value`] times the white balance, clipped. Monochrome data fills all three +/// channels with its one sample. +/// +/// The black level of a row depends on the column only through the repeat pattern, so (when +/// there are no per-column deltas) it is worked out once per row and phase instead of per sample. +fn fill_linear_row(sc: &Scale, mult: &[f32; 3], x0: usize, y: usize, row: &mut [f32]) { + let s = sc.s; + let spp = s.samples; + let w = row.len() / 3; + let bl = &s.black; + let cols = bl.cols.max(1); + if !bl.delta_h.is_empty() || !bl.delta_v.is_empty() || x0 < s.active.x || cols > 16 || !matches!(spp, 1 | 3) { + for (i, px) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { + for k in 0..3 { + px[k] = (sc.value(x0 + i, y, k.min(spp.saturating_sub(1))) * mult[k]).clamp(0.0, 1.0); + } + } + return; + } + // Black level and range per column phase and channel. + let ay = y.saturating_sub(s.active.y); + let table: Vec<[(f32, f32); 3]> = (0..cols) + .map(|p| { + [0, 1, 2].map(|k| { + let sample = k.min(spp - 1); + let black = bl.at(p, ay, sample, spp); + (black, s.white[sample.min(2)] - black) + }) + }) + .collect(); + let src = &s.data[(y * s.width + x0) * spp..(y * s.width + x0 + w) * spp]; + let phase = (x0 - s.active.x) % cols; + let lin = |raw: u16| match sc.lin { + Some(l) => f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)), + None => f32::from(raw), + }; + match spp { + 3 => fill_samples(row, src.as_chunks::<3>().0.iter().copied(), &table, phase, mult, lin), + _ => fill_samples(row, src.iter().map(|r| [*r; 3]), &table, phase, mult, lin), + } +} + +/// The pixels of [`fill_linear_row`]: `raw` gives each pixel's three raw values (the one sample +/// of monochrome data three times), `table` the black level and range per column phase. +#[inline(always)] +fn fill_samples(row: &mut [f32], raw: impl Iterator, table: &[[(f32, f32); 3]], phase: usize, mult: &[f32; 3], lin: impl Fn(u16) -> f32) { + let mut phase = phase; + for (px, raw) in row.as_chunks_mut::<3>().0.iter_mut().zip(raw) { + let t = &table[phase]; + phase = if phase + 1 == table.len() { 0 } else { phase + 1 }; + for k in 0..3 { + let (black, range) = t[k]; + let n = if range.is_nan() || range < 1.0 { + 0.0 + } else { + let n = (lin(raw[k]) - black) / range; + if n.is_finite() { n } else { 0.0 } + }; + px[k] = (n * mult[k]).clamp(0.0, 1.0); + } + } +} + /// Grey-world neutral (camera-space R, G, B) from unclipped mid-range samples. fn grey_world(s: &Sensor, sc: &Scale) -> [f64; 3] { let c = s.crop; @@ -293,13 +357,7 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result (us } } +/// Side of the square tiles orientations 5-8, which swap rows and columns, move at a time: both +/// sides of a tile stay in L1 instead of one of them being walked a column at a time. +const TILE: usize = 32; + /// Applies a TIFF orientation (1–8) to interleaved RGB. pub(crate) fn orient(src: Vec, w: usize, h: usize, o: u16) -> (Vec, usize, usize) { if !(2..=8).contains(&o) { @@ -715,25 +777,44 @@ pub(crate) fn orient(src: Vec, w: usize, h: usize, o: u16) -> (Vec, us let swap = o >= 5; let (ow, oh) = if swap { (h, w) } else { (w, h) }; let mut out = vec![0u16; src.len()]; - let band = par::band_rows(ow); - par::chunks_mut(&mut out, band * ow * 3, |b, chunk| { - for (r, row) in chunk.chunks_exact_mut(ow * 3).enumerate() { - let y2 = b * band + r; - for x2 in 0..ow { - let (x, y) = match o { - 2 => (w - 1 - x2, y2), - 3 => (w - 1 - x2, h - 1 - y2), - 4 => (x2, h - 1 - y2), - 5 => (y2, x2), - 6 => (y2, h - 1 - x2), - 7 => (w - 1 - y2, h - 1 - x2), - _ => (w - 1 - y2, x2), - }; - let i = (y * w + x) * 3; - row[x2 * 3..x2 * 3 + 3].copy_from_slice(&src[i..i + 3]); + if swap { + // Output pixel (x2, y2) is source pixel `base + x2 * sx + y2 * sy` (see `source_xy`). + let (base, sx, sy): (isize, isize, isize) = match o { + 5 => (0, w as isize, 1), + 6 => (((h - 1) * w) as isize, -(w as isize), 1), + 7 => ((h * w - 1) as isize, -(w as isize), -1), + _ => ((w - 1) as isize, w as isize, -1), + }; + let px = src.as_chunks::<3>().0; + par::chunks_mut(&mut out, TILE * ow * 3, |b, chunk| { + let rows = chunk.len() / (ow * 3); + for x0 in (0..ow).step_by(TILE) { + let x1 = (x0 + TILE).min(ow); + for r in 0..rows { + let y2 = (b * TILE + r) as isize; + for (x2, d) in (x0..x1).zip(chunk[(r * ow + x0) * 3..(r * ow + x1) * 3].as_chunks_mut::<3>().0) { + *d = px[(base + x2 as isize * sx + y2 * sy) as usize]; + } + } } - } - }); + }); + } else { + let band = par::band_rows(ow); + par::chunks_mut(&mut out, band * ow * 3, |b, chunk| { + for (r, row) in chunk.chunks_exact_mut(ow * 3).enumerate() { + let y2 = b * band + r; + for x2 in 0..ow { + let (x, y) = match o { + 2 => (w - 1 - x2, y2), + 3 => (w - 1 - x2, h - 1 - y2), + _ => (x2, h - 1 - y2), + }; + let i = (y * w + x) * 3; + row[x2 * 3..x2 * 3 + 3].copy_from_slice(&src[i..i + 3]); + } + } + }); + } (out, ow, oh) } @@ -1000,6 +1081,64 @@ mod tests { assert!(near(GammaLut::with_curve(&[]).encode(0.25), code(0.25))); } + #[test] + fn linear_fill_gives_the_bits_of_the_per_sample_scale() { + // 3-sample and monochrome frames, black patterns, deltas, a table, an offset crop. + for samples in [1usize, 3] { + for (rows, cols, deltas) in [(1, 1, false), (2, 2, false), (1, 3, false), (2, 1, true), (1, 17, false), (4, 4, false)] { + for table in [false, true] { + let (w, h) = (53, 9); + let mut s = test_sensor(w, h, None, samples); + s.active = crate::Rect::new(2, 1, w - 2, h - 1); + s.black.rows = rows; + s.black.cols = cols; + s.black.values = (0..rows * cols * samples).map(|i| 40.0 + (i * 7 % 23) as f32 + 0.25 * (i % 3) as f32).collect(); + if deltas { + s.black.delta_h = (0..w).map(|i| (i % 5) as f32).collect(); + s.black.delta_v = (0..h).map(|i| 0.5 * i as f32).collect(); + } + s.white = [4000.0, 3900.5, 0.5]; + if table { + s.linearization = Some((0..3000u32).map(|i| (i * 3 / 2) as u16).collect()); + } + let sc = Scale::new(&s); + let mult = [1.3f32, 0.9, f32::INFINITY]; + for x0 in [0usize, 2, 5] { + let n = w - x0 - 1; + for y in 0..h { + let mut got = vec![0.0f32; n * 3]; + fill_linear_row(&sc, &mult, x0, y, &mut got); + let want: Vec = + (0..n * 3).map(|j| (sc.value(x0 + j / 3, y, (j % 3).min(samples - 1)) * mult[j % 3]).clamp(0.0, 1.0)).collect(); + assert!( + got.iter().zip(&want).all(|(a, b)| a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())), + "{samples} samples, black {rows}x{cols}, table {table}, x0 {x0}, row {y}" + ); + } + } + } + } + } + } + + #[test] + fn every_orientation_moves_each_pixel_to_its_source_position() { + // Sizes around the tile side (and 1-pixel strips), all eight orientations. + for (w, h) in [(1, 1), (1, 70), (70, 1), (31, 33), (32, 32), (33, 31), (65, 97), (100, 37)] { + let src: Vec = (0..w * h).flat_map(|i| [i as u16, (i >> 4) as u16 ^ 0x5a5a, !(i as u16)]).collect(); + for o in 1..=8 { + let (out, ow, oh) = orient(src.clone(), w, h, o); + assert_eq!((ow, oh), if o >= 5 { (h, w) } else { (w, h) }); + for y2 in 0..oh { + for x2 in 0..ow { + let (x, y) = source_xy(o, w, h, x2, y2); + assert_eq!(out[(y2 * ow + x2) * 3..][..3], src[(y * w + x) * 3..][..3], "{w}x{h} orientation {o} at {x2},{y2}"); + } + } + } + } + } + #[test] fn orientations() { // 3×2 image, pixel value = index. diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 43a3ff47c8..46bd3e4f60 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -29,7 +29,7 @@ //! image area (the D800E, the ILCE-7). //! //! Decoded today: DNG (uncompressed, deflate, lossless-JPEG, lossy-JPEG and JPEG XL, strips and -//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or +//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices, and sRAW / mRAW), uncompressed or //! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed), //! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW), //! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed), @@ -65,6 +65,7 @@ mod saturation; mod sensor; mod sony; mod sony_metadata; +mod sraw; mod tiff; mod tiffep; mod tone; diff --git a/crates/raw/src/ljpeg.rs b/crates/raw/src/ljpeg.rs index 070b3757fd..ffb44f0cb2 100644 --- a/crates/raw/src/ljpeg.rs +++ b/crates/raw/src/ljpeg.rs @@ -8,8 +8,10 @@ //! //! Output is the sample sequence in raster order: `height` rows of `width × //! components` interleaved samples. Only one interleaved scan holding every -//! component with sampling factors 1×1 is supported, which is how DNG, CR2 -//! and the TIFF-based raws use it. +//! component is supported, which is how DNG, CR2 and the TIFF-based raws use +//! it; [`decode`] takes sampling factors 1×1 only. Canon's sRAW / mRAW frames +//! (three components, the first sampled 2×1 or 2×2) go through +//! [`decode_subsampled`], which follows Canon's prediction rather than T.81's. use crate::error::{RawError, Result}; @@ -20,11 +22,21 @@ pub(crate) struct Frame { pub width: usize, pub height: usize, pub components: usize, + /// Horizontal and vertical sampling factors of the first component (1 and 1 unless the + /// frame is subsampled; the other components are then sampled 1×1). + pub h: usize, + pub v: usize, } impl Frame { + /// Samples in the frame: per MCU, `h × v` of the first component and one of each other. pub fn samples(&self) -> Option { - self.width.checked_mul(self.height)?.checked_mul(self.components) + let mcus = (self.width / self.h.max(1)).checked_mul(self.height / self.v.max(1))?; + mcus.checked_mul(self.h.checked_mul(self.v)?.checked_add(self.components)?.checked_sub(1)?) + } + + pub fn is_subsampled(&self) -> bool { + self.h != 1 || self.v != 1 } } @@ -343,14 +355,19 @@ fn parse(data: &[u8]) -> Result> { return Err(RawError::malformed(format!("unsupported SOF3 ({precision}-bit, {width}x{height}, {nf} components)"))); } comp_ids.clear(); + let mut factors = Vec::with_capacity(nf); for c in 0..nf { let s = &seg[6 + 3 * c..9 + 3 * c]; - if s[1] != 0x11 { - return Err(RawError::unsupported("lossless JPEG with subsampled components")); - } + factors.push(s[1]); comp_ids.push(s[0]); } - frame = Some(Frame { precision, width, height, components: nf }); + // Canon sRAW / mRAW: Y sampled 2×1 or 2×2, Cb and Cr 1×1, whole MCUs only. + let (h, v) = match factors.as_slice() { + f if f.iter().all(|&s| s == 0x11) => (1, 1), + [y @ (0x21 | 0x22), 0x11, 0x11] if width % 2 == 0 && height % usize::from(y & 0x0F) == 0 => (2, usize::from(y & 0x0F)), + _ => return Err(RawError::unsupported(format!("lossless JPEG with subsampled components {factors:02x?} ({width}x{height})"))), + }; + frame = Some(Frame { precision, width, height, components: nf, h, v }); } 0xC0..=0xC2 => return Err(RawError::unsupported("lossy (DCT) JPEG compressed raw data")), 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => return Err(RawError::unsupported("hierarchical or arithmetic-coded JPEG")), @@ -422,6 +439,9 @@ fn parse(data: &[u8]) -> Result> { pub(crate) fn decode(data: &[u8], max_samples: usize) -> Result<(Frame, Vec)> { let p = parse(data)?; let f = p.frame; + if f.is_subsampled() { + return Err(RawError::unsupported(format!("lossless JPEG with subsampled components ({}x{} luma)", f.h, f.v))); + } let total = f .samples() .filter(|&n| n <= max_samples) @@ -531,10 +551,100 @@ pub(crate) fn decode(data: &[u8], max_samples: usize) -> Result<(Frame, Vec Ok((f, out)) } +/// Decodes a subsampled frame (Canon sRAW / mRAW: Y sampled 2×1 or 2×2, Cb and Cr 1×1, see +/// [`Frame::h`]) into its sample sequence in decode order: per MCU the `h × v` Y samples +/// row-major, then Cb, then Cr; `width / h` MCUs make a row and `height / v` rows the frame. +/// +/// Only predictor 1 is supported, with Canon's rule instead of T.81's per-component sample +/// grid: each Y sample is predicted from the Y sample decoded just before it (the previous one +/// in the MCU, or the last of the previous MCU), Cb and Cr from those of the previous MCU, and +/// the first MCU of a row from the first MCU of the row above (from `2^(P−Pt−1)` on the first +/// row of a restart interval). +pub(crate) fn decode_subsampled(data: &[u8], max_samples: usize) -> Result<(Frame, Vec)> { + let p = parse(data)?; + let f = p.frame; + let total = f + .samples() + .filter(|&n| n <= max_samples) + .ok_or_else(|| RawError::LimitExceeded(format!("lossless JPEG frame {}x{}x{}", f.width, f.height, f.components)))?; + if !f.is_subsampled() || f.components != 3 { + return Err(RawError::malformed("lossless JPEG frame is not subsampled YCbCr")); + } + if p.predictor != 1 { + return Err(RawError::unsupported(format!("subsampled lossless JPEG with predictor {}", p.predictor))); + } + if p.entropy.len().saturating_mul(8) < total / 2 { + return Err(RawError::malformed("lossless JPEG data is truncated")); + } + // Each component's table (components may share one). + let [ty, tcb, tcr] = match p.comp_table.as_slice() { + &[a, b, c] => [&p.tables[a], &p.tables[b], &p.tables[c]], + _ => return Err(RawError::malformed("lossless JPEG scan tables")), + }; + let luma = f.h * f.v; + let per_mcu = luma + 2; + let mcus = f.width / f.h; + let row_len = mcus * per_mcu; + if row_len == 0 { + return Err(RawError::malformed("empty lossless JPEG frame")); + } + // The restart interval counts MCUs. + if p.restart != 0 && p.restart % mcus != 0 { + return Err(RawError::unsupported("lossless JPEG restart interval that is not whole rows")); + } + let rows_per_interval = if p.restart == 0 { usize::MAX } else { p.restart / mcus }; + let mut out = vec![0u16; total]; + let mut bits = Bits::new(p.entropy); + let initial = 1i32 << (f.precision - p.point_transform - 1); + // First Y, Cb and Cr of the row above: the first MCU's predictors. + let mut top = [initial; 3]; + let mut interval_row = 0usize; + for row in out.chunks_exact_mut(row_len) { + if interval_row == rows_per_interval { + bits.restart()?; + interval_row = 0; + } + if interval_row == 0 { + top = [initial; 3]; + } + let (mut y, mut cb, mut cr) = (top[0], top[1], top[2]); + for (m, mcu) in row.chunks_exact_mut(per_mcu).enumerate() { + let (ys, c) = mcu.split_at_mut(luma); + for (k, s) in ys.iter_mut().enumerate() { + // The first Y of the row comes from the row above, every other from the previous Y. + let pred = if m == 0 && k == 0 { top[0] } else { y }; + *s = (pred + bits.diff(ty)?) as u16; + y = i32::from(*s); + if m == 0 && k == 0 { + top[0] = y; + } + } + if let [scb, scr] = c { + *scb = (cb + bits.diff(tcb)?) as u16; + *scr = (cr + bits.diff(tcr)?) as u16; + (cb, cr) = (i32::from(*scb), i32::from(*scr)); + } + if m == 0 { + (top[1], top[2]) = (cb, cr); + } + } + interval_row += 1; + if bits.fake > 64 { + return Err(RawError::malformed("lossless JPEG data is truncated")); + } + } + if p.point_transform > 0 { + for v in &mut out { + *v <<= p.point_transform; + } + } + Ok((f, out)) +} + #[cfg(test)] mod tests { use super::*; - use crate::testgen::{lj92_encode, lj92_encode_tables}; + use crate::testgen::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables}; /// Deterministic pseudo-random samples with some structure (smooth + noise). fn samples(n: usize, precision: u8, seed: u64) -> Vec { @@ -559,7 +669,7 @@ mod tests { let v = samples(w * h * comps, precision, u64::from(predictor) * 31 + comps as u64); let j = lj92_encode(&v, w, h, comps, precision, predictor, None); let (f, out) = decode(&j, usize::MAX).unwrap(); - assert_eq!(f, Frame { precision, width: w, height: h, components: comps }); + assert_eq!(f, Frame { precision, width: w, height: h, components: comps, h: 1, v: 1 }); assert_eq!(out, v, "P={precision} pred={predictor} comps={comps}"); } } @@ -591,7 +701,7 @@ mod tests { let v = samples(w * h * comps, 14, u64::from(predictor) * 7 + comps as u64); let j = lj92_encode_tables(&v, w, h, table_of, 14, predictor, restart_rows); let (f, out) = decode(&j, usize::MAX).unwrap(); - assert_eq!(f, Frame { precision: 14, width: w, height: h, components: comps }); + assert_eq!(f, Frame { precision: 14, width: w, height: h, components: comps, h: 1, v: 1 }); assert_eq!(out, v, "tables={table_of:?} pred={predictor} restart={restart_rows:?}"); } } @@ -663,4 +773,67 @@ mod tests { flooded.extend_from_slice(&j[2..]); // the rest of the valid stream assert!(matches!(decode(&flooded, usize::MAX), Err(RawError::Malformed(_)))); } + + #[test] + fn subsampled_roundtrip() { + for (h, v) in [(2usize, 2usize), (2, 1)] { + let (w, ht) = (14, 6); + let n = (w / h) * (ht / v) * (h * v + 2); + for precision in [12u8, 15, 16] { + for restart in [None, Some(1), Some(ht / v)] { + let seq = samples(n, precision, h as u64 * 7 + v as u64); + let j = lj92_encode_sraw(&seq, w, ht, h, v, precision, restart); + let f = frame(&j).unwrap(); + assert_eq!((f.h, f.v, f.samples()), (h, v, Some(n))); + let (_, out) = decode_subsampled(&j, usize::MAX).unwrap(); + assert_eq!(out, seq, "{h}x{v} P={precision} restart {restart:?}"); + // The plain decoder refuses subsampled frames instead of mislaying them. + assert!(matches!(decode(&j, usize::MAX), Err(RawError::Unsupported(_)))); + } + } + } + // Extreme values exercise the 16-bit and 32768 difference categories. + let seq: Vec = (0..7 * 3 * 6).map(|i| if (i / 5) % 2 == 0 { 0 } else { 65535 }).collect(); + let j = lj92_encode_sraw(&seq, 14, 6, 2, 2, 16, Some(1)); + assert_eq!(decode_subsampled(&j, usize::MAX).unwrap().1, seq); + // Y and the chroma on separate tables, or each its own: the scan maps every component + // to its table even when components share one. + for table_of in [[0, 1, 1], [0, 1, 2], [1, 0, 0]] { + let seq = samples(7 * 3 * 6, 15, 5); + let j = lj92_encode_sraw_tables(&seq, 14, 6, (2, 2), table_of, 15, Some(1)); + assert_eq!(decode_subsampled(&j, usize::MAX).unwrap().1, seq, "tables {table_of:?}"); + } + } + + #[test] + fn subsampled_hostile_streams_error_without_panicking() { + let seq = samples(7 * 3 * 6, 15, 3); + let j = lj92_encode_sraw(&seq, 14, 6, 2, 2, 15, Some(1)); + for n in 0..j.len() { + let _ = decode_subsampled(&j[..n], usize::MAX); + } + let mut s = 0x0123_4567u64; + for _ in 0..2000 { + let mut b = j.clone(); + for _ in 0..4 { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1); + let at = (s >> 33) as usize % b.len(); + b[at] = (s >> 20) as u8; + } + let _ = decode_subsampled(&b, 1 << 20); + } + assert!(matches!(decode_subsampled(&j, 10), Err(RawError::LimitExceeded(_)))); + // A frame that is not subsampled, or another predictor, is not Canon sRAW. + let plain = lj92_encode(&samples(14 * 6 * 3, 15, 1), 14, 6, 3, 15, 1, None); + assert!(decode_subsampled(&plain, usize::MAX).is_err()); + let mut p6 = j.clone(); + let sos = p6.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap(); + p6[sos + 11] = 6; // Ss (predictor) after Ns and three component selectors + assert!(matches!(decode_subsampled(&p6, usize::MAX), Err(RawError::Unsupported(_)))); + // Sampling layouts other than Canon's are refused at the frame header. + let mut odd = j.clone(); + let sof = odd.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap(); + odd[sof + 14] = 0x21; // Cb subsampled too + assert!(matches!(frame(&odd), Err(RawError::Unsupported(_)))); + } } diff --git a/crates/raw/src/nefc.rs b/crates/raw/src/nefc.rs index e09d934b4b..7582343bf3 100644 --- a/crates/raw/src/nefc.rs +++ b/crates/raw/src/nefc.rs @@ -19,7 +19,8 @@ //! `crates/raw/src/vendor/nefc.rs`): recovered from CC0 raw.pixls.us samples //! shot in both compressed and uncompressed mode, and verified on ~45 files //! from ~35 bodies (D40 … D850, Df, Z 6, Z 50, 1 J1). Only the format facts -//! and the tables were taken over; this module is written against this +//! and the tables were taken over (and, for "lossy after split" below, the +//! dequantisation function); this module is written against this //! crate's own TIFF reader. //! //! Format: @@ -38,9 +39,23 @@ //! samples), not the sensor bit depth; see Bill Claff's NEF Compression tables. //! * Values in the maker note are in the maker note's byte order. //! +//! * "Lossy after split" (type 2 only, a non-zero split row at `0x0096` offset +//! 562): rows above the split row are Huffman coded as above. Row `split` +//! starts at the very next bit; from there every pixel is one fixed-rate +//! word of `bits - 4` bits (8 at 12 bit, 10 at 14 bit), MSB first, with no +//! row padding: a prefix code (every word but all-ones) for the category `n`, +//! followed by the top bits of the T.81 additional bits. The difference is +//! the centre of the magnitude bin that was kept, the predictor is the same +//! as above, and the running value is not clamped. The section fills the +//! strip to its last byte: whole rows (up to 4 more than the image), then +//! 0–7 one-bits of padding. These facts, the prefix +//! tables and the dequantisation (`fixed_words`, ported from LightCraft's +//! `fixed_word_table`) come from LightCraft's black-box analysis of 11 CC0 +//! raw.pixls.us files (storytold/lightcraft#633), like the Huffman tables above. +//! //! Not decoded (reported as unsupported; the embedded preview is used -//! instead): "lossy after split" files (non-zero split row), other `0x0096` -//! versions and bit depths other than 12 / 14. +//! instead): "lossy after split" strips that fail to decode, other +//! `0x0096` versions and bit depths other than 12 / 14. use crate::Limits; use crate::error::{RawError, Result}; @@ -238,6 +253,9 @@ pub(crate) struct DecodeTable { pub encoding: Encoding, /// Predictor seeds `[row parity][column]`. pub seeds: [[i32; 2]; 2], + /// First row of the fixed-rate section ("lossy after split"); 0 when the whole strip is + /// Huffman coded. + pub split: usize, } /// Parses maker note `0x0096` for a `bits`-bit image; `le` is the maker @@ -253,6 +271,7 @@ pub(crate) fn parse_table(t: &[u8], le: bool, bits: u32) -> Result } let (Some(&v0), Some(&v1)) = (t.first(), t.get(1)) else { return Err(short()) }; let mut seeds = [[0i32; 2]; 2]; + let mut split = 0; for (i, s) in seeds.iter_mut().flatten().enumerate() { *s = i32::from(u16_at(2 + 2 * i).ok_or_else(short)?); } @@ -267,9 +286,11 @@ pub(crate) fn parse_table(t: &[u8], le: bool, bits: u32) -> Result if v1 == 0x10 { Encoding::Lossy(points) } else { - let split = u16_at(562).unwrap_or(0); - if split != 0 { - return Err(RawError::unsupported(format!("Nikon \"lossy after split\" compressed NEF (split at row {split})"))); + split = usize::from(u16_at(562).unwrap_or(0)); + // Bytes 12.. hold the curve; with more than 275 points it covers byte 562, so a + // non-zero value there is not a split row: refused as before (preview fallback). + if split != 0 && 12 + 2 * n > 562 { + return Err(RawError::unsupported(format!("Nikon compressed NEF: {n}-point curve overlapping the split row field"))); } // The modern lossy curve has a smaller *encoded* domain while // its output remains in sensor ADUs. Using 2^bits stretches the @@ -292,11 +313,85 @@ pub(crate) fn parse_table(t: &[u8], le: bool, bits: u32) -> Result } _ => return Err(RawError::unsupported(format!("Nikon compressed NEF version {v0:#04x} {v1:#04x}"))), }; - Ok(DecodeTable { encoding, seeds }) + Ok(DecodeTable { encoding, seeds, split }) +} + +/// Difference-category prefix codes of the fixed-rate ("lossy after split") section: +/// `(prefix bits, prefix length, category n)`. A word of `bits - 4` bits is a prefix followed by +/// the top `bits - 4 - length` additional bits of category `n` (storytold/lightcraft#633; the +/// 14-bit `010` prefix never occurred in the analysed files, its category 12 is deduced). +const FIXED_12: &[(u32, u32, u32)] = &[ + (0b00, 2, 9), + (0b010, 3, 10), + (0b011, 3, 8), + (0b100, 3, 7), + (0b101, 3, 6), + (0b110, 3, 5), + (0b1110, 4, 4), + (0b11110, 5, 3), + (0b111110, 6, 2), + (0b1111110, 7, 1), + (0b11111110, 8, 0), +]; +const FIXED_14: &[(u32, u32, u32)] = &[ + (0b00, 2, 8), + (0b010, 3, 12), + (0b011, 3, 11), + (0b100, 3, 10), + (0b101, 3, 9), + (0b110, 3, 7), + (0b1110, 4, 6), + (0b11110, 5, 5), + (0b111110, 6, 4), + (0b1111110, 7, 3), + (0b11111110, 8, 2), + (0b111111110, 9, 1), + (0b1111111110, 10, 0), +]; + +/// Fixed-rate word → dequantised difference, for `bits`-bit samples; `None` for the all-ones +/// word, which no prefix covers. +fn fixed_words(bits: u32) -> Vec> { + let (w, codes) = if bits == 12 { (8, FIXED_12) } else { (10, FIXED_14) }; + let mut lut = vec![None; 1 << w]; + for &(prefix, len, n) in codes { + let kept = w - len; + // `dropped` low bits of the T.81 additional bits are not stored: the word gives the + // bin, the difference is its centre. + let dropped = n.saturating_sub(kept); + let half = (1i32 << dropped) >> 1; + for m in 0..1u32 << kept { + let extra = (m << dropped) as i32; + let d = if n == 0 { + 0 + } else if extra >= 1 << (n - 1) { + extra + half + } else if dropped > 0 { + extra + half - (1 << n) + } else { + extra - ((1 << n) - 1) + }; + if let Some(slot) = lut.get_mut(((prefix << kept) | m) as usize) { + *slot = Some(d); + } + } + } + lut } /// Decodes a `w × h` Nikon Huffman-compressed strip with `bits`-bit samples. +/// +/// A "lossy after split" strip that fails to decode for any reason is reported as unsupported, +/// not malformed: before these files were decoded, every one was refused as unsupported and +/// opened as the camera's embedded preview, and that fallback stays for files the rule does not fit. pub(crate) fn decode(src: &[u8], w: usize, h: usize, bits: u32, table: &DecodeTable) -> Result> { + match decode_strip(src, w, h, bits, table) { + Err(RawError::Malformed(m)) if table.split != 0 => Err(RawError::unsupported(format!("Nikon \"lossy after split\" NEF that does not decode: {m}"))), + r => r, + } +} + +fn decode_strip(src: &[u8], w: usize, h: usize, bits: u32, table: &DecodeTable) -> Result> { if bits != 12 && bits != 14 { return Err(RawError::unsupported(format!("Nikon compressed NEF with {bits}-bit samples"))); } @@ -316,6 +411,14 @@ pub(crate) fn decode(src: &[u8], w: usize, h: usize, bits: u32, table: &DecodeTa Encoding::Lossless => (&[], (1i32 << bits) - 1), Encoding::Lossy(curve) => (curve, i32::try_from(curve.len()).unwrap_or(i32::MAX) - 1), }; + if table.split != 0 && table.split >= h { + return Err(RawError::malformed(format!("NEF: split row {} for a {h}-row image", table.split))); + } + if table.split != 0 && !matches!(table.encoding, Encoding::Lossy(_)) { + return Err(RawError::malformed("NEF: split row with a lossless table")); + } + let fixed = if table.split != 0 { fixed_words(bits) } else { Vec::new() }; + let word = bits - 4; let mut out = vec![0u16; n]; let mut stream = Bits::new(src); let mut vpred = table.seeds; @@ -323,8 +426,14 @@ pub(crate) fn decode(src: &[u8], w: usize, h: usize, bits: u32, table: &DecodeTa for (y, row) in out.chunks_exact_mut(w).enumerate() { let seeds = &mut vpred[y & 1]; let mut hpred = [0i32; 2]; + let fixed_rate = table.split != 0 && y >= table.split; for (x, o) in row.iter_mut().enumerate() { - let d = diff(&mut stream, &huff).ok_or_else(|| RawError::malformed(format!("NEF: invalid Huffman code in row {y}")))?; + let d = if fixed_rate { + let code = stream.take(word) as usize; + fixed.get(code).copied().flatten().ok_or_else(|| RawError::malformed(format!("NEF: unknown fixed-rate word in row {y}")))? + } else { + diff(&mut stream, &huff).ok_or_else(|| RawError::malformed(format!("NEF: invalid Huffman code in row {y}")))? + }; let p = if x < 2 { seeds[x] = seeds[x].saturating_add(d); hpred[x] = seeds[x]; @@ -334,15 +443,29 @@ pub(crate) fn decode(src: &[u8], w: usize, h: usize, bits: u32, table: &DecodeTa hpred[x & 1] }; let v = p.clamp(0, max); - clipped += usize::from(v != p); + // The fixed-rate section's running value is not clamped and may leave the range. + clipped += usize::from(v != p && !fixed_rate); *o = if lut.is_empty() { v as u16 } else { lut.get(v as usize).copied().unwrap_or(0) }; } // The camera pads the strip; reading well past its end means the data // is truncated or corrupt. - if stream.consumed > src.len() * 8 + 64 { + if stream.consumed > src.len().saturating_mul(8).saturating_add(64) { return Err(RawError::malformed(format!("NEF: compressed data ends in row {y} of {h}"))); } } + // The fixed-rate section fills the rest of the strip: whole rows of `w` words, then 0–7 + // one-bits up to the byte boundary (a strip may hold up to 4 rows more than the image). This + // checks the section's length, not its content: a strip that ends any other way does not + // follow the rule and is refused, but a wrong word inside a well-formed one is not detected. + if table.split != 0 { + let left = src.len().saturating_mul(8).checked_sub(stream.consumed); + let row_bits = w.saturating_mul(word as usize).max(1); + let pad = left.map(|l| l % row_bits); + let ones = |k: usize| src.last().is_some_and(|b| u32::from(*b) & ((1 << k) - 1) == (1 << k) - 1); + if !left.is_some_and(|l| l / row_bits <= 4) || !pad.is_some_and(|k| k < 8 && ones(k)) { + return Err(RawError::malformed(format!("NEF: the fixed-rate section from row {} does not end the strip", table.split))); + } + } // A wrong table or a corrupt stream drifts out of range quickly; real // files stay inside (a handful of edge pixels). if clipped > n / 1000 + 16 { @@ -365,6 +488,17 @@ pub(crate) fn read_compressed(t: &Tiff, raw: &Ifd, note: Option<&(Tiff, Ifd)>, l .and_then(|(n, m)| Some((n.raw(m.get(NIKON_LINEARIZATION_TABLE)?)?, n.le))) .ok_or_else(|| RawError::unsupported("Nikon compressed NEF without a linearization table (maker note 0x96)"))?; let table = parse_table(table.0, table.1, bits)?; + match read_strip(t, raw, width, height, bits, &table, limits) { + // Until split files were decoded, each was refused as unsupported before the image was + // read, and opened as the camera's preview: any failure after that point keeps it so. + Err(e @ (RawError::Malformed(_) | RawError::LimitExceeded(_))) if table.split != 0 => { + Err(RawError::unsupported(format!("Nikon \"lossy after split\" NEF that does not decode: {e}"))) + } + r => r, + } +} + +fn read_strip(t: &Tiff, raw: &Ifd, width: usize, height: usize, bits: u32, table: &DecodeTable, limits: &Limits) -> Result { limits.check(width as u64, height as u64, 2)?; // One strip in every sample; several would be consecutive parts of the // same bit stream. @@ -376,7 +510,7 @@ pub(crate) fn read_compressed(t: &Tiff, raw: &Ifd, note: Option<&(Tiff, Ifd)>, l let start = first as usize; let end = (last as usize).saturating_add(last_len as usize).min(t.data.len()); let src = t.data.get(start..end).filter(|s| !s.is_empty()).ok_or_else(|| RawError::malformed("raw data lies outside the file"))?; - let data = decode(src, width, height, bits, &table)?; + let data = decode(src, width, height, bits, table)?; Ok(Plane { width, height, samples: 1, bits, data, float_scale: None }) } diff --git a/crates/raw/src/nefc/tests.rs b/crates/raw/src/nefc/tests.rs index 296f850093..76701208db 100644 --- a/crates/raw/src/nefc/tests.rs +++ b/crates/raw/src/nefc/tests.rs @@ -85,7 +85,7 @@ fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec { fn lossless(bits: u32) -> DecodeTable { let s = 1 << (bits - 3); - DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]] } + DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]], split: 0 } } fn lossy_table(bits: u32, le: bool) -> Vec { @@ -165,7 +165,7 @@ fn unsupported_and_malformed_tables() { let malformed = |r: Result| matches!(r, Err(RawError::Malformed(_))); let mut split = lossy_table(12, false); split[562..564].copy_from_slice(&345u16.to_be_bytes()); - assert!(unsupported(parse_table(&split, false, 12))); + assert_eq!(parse_table(&split, false, 12).unwrap().split, 345); assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], false, 12))); assert!(unsupported(parse_table(&lossy_table(12, false), false, 16))); assert!(malformed(parse_table(&[], false, 12))); @@ -244,7 +244,8 @@ fn decodes_through_the_nef_container() { assert_eq!(s.data, img.iter().map(|&v| curve[v as usize]).collect::>()); assert_eq!(s.black.values, vec![150.0; 4]); assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok()); - // "lossy after split" and a missing table stay unsupported (preview fallback) + // a split row over a stream that does not follow the fixed-rate rule, and a missing + // table, stay unsupported (preview fallback) let mut split = table; split[562..564].copy_from_slice(&3u16.to_le_bytes()); let e = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, vec![(0x0096, Val::Undefined(split))]), &Limits::default()); @@ -304,3 +305,277 @@ fn truncated_and_corrupt_streams_error_never_panic() { assert!(decode(&src, usize::MAX, 2, 14, &table).is_err()); assert!(decode(&src, 0, 2, 14, &table).is_err()); } + +/// Encodes `values` the way a "lossy after split" camera does: Huffman (`t`) for rows above +/// `split` (exact differences), then fixed-rate words of `bits - 4` bits, then one-bits up to the +/// byte boundary. The fixed-rate words keep only the top bits of large differences, so the +/// encoder runs the decoder's own predictor on what it reconstructs (closed loop) and returns the +/// strip together with the values the decoder must produce. +fn encode_split(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2], bits: u32, split: usize) -> (Vec, Vec) { + let codes = codes(t); + let (word, fixed) = if bits == 12 { (8, FIXED_12) } else { (10, FIXED_14) }; + let lut = fixed_words(bits); + let mut wr = Writer::default(); + let mut vpred = seeds; + let mut recon = Vec::with_capacity(values.len()); + for (y, row) in values.chunks(w).enumerate() { + let mut hpred = [0i32; 2]; + for (x, &v) in row.iter().enumerate() { + let pred = if x < 2 { vpred[y & 1][x] } else { hpred[x & 1] }; + let d = v - pred; + let k = 32 - d.unsigned_abs().leading_zeros(); + let extra = if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 }; + let got = if y < split { + let (code, len) = codes[k as usize]; + assert!(len > 0, "no Huffman code for category {k}"); + wr.put(code, len); + wr.put(extra, k); + d + } else { + let &(prefix, len, _) = fixed.iter().find(|c| c.2 == k).unwrap_or_else(|| panic!("no fixed-rate code for category {k}")); + let kept = word - len; + let field = if k <= kept { extra << (kept - k) } else { extra >> (k - kept) }; + wr.put(prefix, len); + wr.put(field, kept); + lut[((prefix << kept) | field) as usize].unwrap() + }; + let r = pred + got; + if x < 2 { + vpred[y & 1][x] = r; + } + hpred[x & 1] = r; + recon.push(r); + } + } + while wr.n > 0 { + wr.put(1, 1); + } + (wr.out, recon) +} + +/// Samples with large jumps (differences up to about ±1000 codes, the largest category both +/// lossy Huffman tables and the 12-bit fixed-rate words code) as well as small steps. +fn rough(w: usize, h: usize, seed: u32) -> Vec { + let mut s = seed; + (0..w * h) + .map(|i| { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let jump = if (s >> 28) < 3 { ((s >> 8) % 900) as i32 - 450 } else { ((s >> 8) % 23) as i32 - 11 }; + 700 + jump + ((i % w) as i32 * 7) % 40 + }) + .collect() +} + +fn split_table(bits: u32, split: usize) -> DecodeTable { + let mut table = lossy_table(bits, false); + table[562..564].copy_from_slice(&(split as u16).to_be_bytes()); + let t = parse_table(&table, false, bits).unwrap(); + assert_eq!(t.split, split); + t +} + +#[test] +fn lossy_after_split_known_answers() { + for bits in [12u32, 14] { + let huff = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; + // Split right after the first row, in the middle and before the last row. + for (h, split) in [(7usize, 1usize), (7, 3), (7, 6)] { + let w = 24usize; + let t = split_table(bits, split); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let max = curve.len() as i32 - 1; + // Large jumps: the fixed-rate words drop low bits and decode to bin centres, which + // the closed-loop encoder reproduces; the running value may leave 0..=max. + let img = rough(w, h, 7 + split as u32); + let (src, recon) = encode_split(&img, w, huff, t.seeds, bits, split); + let want: Vec = recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect(); + assert_eq!(decode(&src, w, h, bits, &t).unwrap(), want, "{bits}-bit split {split}"); + // Some differences really were quantised. + assert!(recon.iter().zip(&img).any(|(r, v)| r != v), "{bits}-bit split {split}: nothing quantised"); + } + } +} + +#[test] +fn lossy_after_split_dequantises_to_symmetric_bin_centres() { + for bits in [12u32, 14] { + let lut = fixed_words(bits); + let values: Vec = lut.iter().flatten().copied().collect(); + // Every word but the all-ones one codes a difference, and the codes are symmetric. + assert_eq!(values.len(), lut.len() - 1, "{bits}-bit"); + assert!(lut.last().unwrap().is_none()); + for v in &values { + assert!(values.contains(&-v), "{bits}-bit: {v} has no negative twin"); + } + // Small differences are exact; the largest category (10 at 12 bit, 12 at 14 bit) reaches + // past half its range. + for d in -31..=31 { + assert!(values.contains(&d), "{bits}-bit: {d}"); + } + let top = *values.iter().max().unwrap(); + assert!(top >= if bits == 12 { 1 << 9 } else { 1 << 11 }, "{bits}-bit: {top}"); + } +} + +#[test] +fn split_files_that_break_the_rule_fall_back_to_the_preview() { + let unsupported = |r: Result>| matches!(r, Err(RawError::Unsupported(_))); + for bits in [12u32, 14] { + let huff = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; + let (w, h, split) = (24usize, 7usize, 3usize); + let t = split_table(bits, split); + let (src, _) = encode_split(&gentle(w, h, 600), w, huff, t.seeds, bits, split); + assert!(decode(&src, w, h, bits, &t).is_ok()); + // Trailing data, a truncated strip, a split row past the image, zero padding and the + // all-ones word: all unsupported (the embedded preview opens), none a panic. + let mut longer = src.clone(); + longer.extend_from_slice(&[0x12; 9]); + assert!(unsupported(decode(&longer, w, h, bits, &t)), "{bits}-bit: trailing data"); + assert!(unsupported(decode(&src[..src.len() - 12], w, h, bits, &t)), "{bits}-bit: truncated"); + assert!(unsupported(decode(&src, w, split, bits, &t)), "{bits}-bit: split past the image"); + let mut zeros = src.clone(); + let last = zeros.len() - 1; + zeros[last] &= 0xf0; + assert_ne!(zeros, src, "{bits}-bit: the fixture must end in padding bits"); + assert!(unsupported(decode(&zeros, w, h, bits, &t)), "{bits}-bit: zero padding"); + let mut all_ones = src.clone(); + let fixed_start = all_ones.len() - (w * (h - split) * (bits as usize - 4)).div_ceil(8); + all_ones[fixed_start + 2..fixed_start + 6].fill(0xff); + assert!(unsupported(decode(&all_ones, w, h, bits, &t)), "{bits}-bit: all-ones word"); + } + // A split row on a lossless table is malformed (no parsed table makes one). + let lossless_split = DecodeTable { split: 3, ..lossless(12) }; + assert!(unsupported(decode(&[0; 64], 24, 7, 12, &lossless_split))); + // A curve long enough to cover byte 562 has no split field: refused as before. + let mut long = vec![0x44, 0x20]; + long.extend(std::iter::repeat_n([0u8, 9], 4).flatten()); + long.extend_from_slice(&513u16.to_be_bytes()); + long.extend((0..513u32).flat_map(|i| ((i * 7) as u16).to_be_bytes())); + assert!(matches!(parse_table(&long, false, 12), Err(RawError::Unsupported(_)))); +} + +#[test] +fn split_nef_decodes_through_the_container() { + use crate::testgen::{Val, nef_compressed}; + use crate::{Limits, decode as decode_raw}; + let (w, h, split) = (40usize, 6usize, 2usize); + let mut table = lossy_table(12, true); + table[562..564].copy_from_slice(&(split as u16).to_le_bytes()); + let t = parse_table(&table, true, 12).unwrap(); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let (src, recon) = encode_split(&rough(w, h, 3), w, &LOSSY_12, t.seeds, 12, split); + let note = vec![(0x0096, Val::Undefined(table))]; + let s = decode_raw(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, note), &Limits::default()).unwrap(); + let max = curve.len() as i32 - 1; + assert_eq!(s.data, recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect::>()); + assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok()); +} + +/// Small steps around a level (every difference below 32), so fixed-rate words keep them whole. +fn gentle(w: usize, h: usize, base: i32) -> Vec { + (0..w * h).map(|i| base + ((i % w) as i32 * 3 + (i / w) as i32 * 5) % 13 + if i % 7 == 0 { 7 } else { 0 }).collect() +} + +#[test] +fn fixed_rate_running_value_is_not_clamped() { + // A jump from 900 down to 0 is category 10: its 12-bit word keeps 5 of 10 additional bits + // and decodes to -912, so the running value sits at -12. The next same-colour pixel codes +12 + // exactly and must land on 0 again; clamping the running value would give 12. + let (w, h, split) = (12usize, 4usize, 1usize); + let t = split_table(12, split); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let img: Vec = (0..w * h).map(|i| if i % w < 2 { 900 } else { 0 }).collect(); + let (src, recon) = encode_split(&img, w, &LOSSY_12, t.seeds, 12, split); + assert!(recon.iter().any(|&r| r < 0), "{recon:?}"); + let max = curve.len() as i32 - 1; + let want: Vec = recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect(); + assert_eq!(decode(&src, w, h, 12, &t).unwrap(), want); +} + +#[test] +fn fixed_rate_words_known_answers() { + // Worked by hand from the rule: prefix -> category n; the word keeps the top `kept` of n + // additional bits; T.81: a leading 0 bit is a negative difference; the difference is the + // centre of the kept bin (low dropped bits = half the bin). + let (w12, w14) = (fixed_words(12), fixed_words(14)); + for (word, want) in [ + (0b1111_1110, Some(0)), // category 0 + (0b1110_0000, Some(-15)), // category 4, all 4 bits kept: 0000 = -15 + (0b1110_1111, Some(15)), // 1111 = +15 + (0b101_00000, Some(-63)), // category 6, 5 of 6 bits kept: bin -63..-62, centre -63 + (0b101_10000, Some(33)), // bin 32..33, centre 33 + (0b010_00011, Some(-912)), // category 10, 5 of 10 bits: 00011xxxxx = 96..127 -> -927..-896 + (0b010_11111, Some(1008)), // 11111xxxxx = 992..1023, centre 1008 + (0b1111_1111, None), // the all-ones word codes nothing + ] { + assert_eq!(w12[word], want, "12-bit word {word:#010b}"); + } + for (word, want) in [ + (0b11_1111_1110, Some(0)), // category 0 + (0b010_0000000, Some(-4080)), // category 12, 7 of 12 bits: -4095..-4064, centre -4080 + (0b010_1111111, Some(4080)), // 4064..4095, centre 4080 + (0b011_1000000, Some(1032)), // category 11, 7 of 11 bits: 1024..1039, centre 1032 + (0b00_00000000, Some(-255)), // category 8, all 8 bits kept: 00000000 = -255 + (0b11_1111_1111, None), // the all-ones word + ] { + assert_eq!(w14[word], want, "14-bit word {word:#012b}"); + } +} + +#[test] +fn out_of_range_fixed_rate_values_are_not_counted_as_clipped() { + // Many jumps down to 0 leave the running value just below 0 (see the test above), far more + // than the 16 + n/1000 out-of-range values tolerated in Huffman rows. They are legitimate in + // the fixed-rate section and must not fail the decode. + let (w, h, split) = (40usize, 5usize, 1usize); + let t = split_table(12, split); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let img: Vec = (0..w * h).map(|i| if (i % w) % 4 < 2 { 900 } else { 0 }).collect(); + let (src, recon) = encode_split(&img, w, &LOSSY_12, t.seeds, 12, split); + assert!(recon.iter().filter(|&&r| r < 0).count() > 16 + w * h / 1000, "{recon:?}"); + let max = curve.len() as i32 - 1; + assert_eq!(decode(&src, w, h, 12, &t).unwrap(), recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect::>()); +} + +#[test] +fn split_files_failing_after_the_table_still_fall_back_to_the_preview() { + use crate::testgen::{Val, nef_compressed}; + use crate::{Limits, decode as decode_raw}; + let (w, h, split) = (40usize, 6usize, 2usize); + let mut table = lossy_table(12, true); + table[562..564].copy_from_slice(&(split as u16).to_le_bytes()); + let t = parse_table(&table, true, 12).unwrap(); + let (src, _) = encode_split(&gentle(w, h, 600), w, &LOSSY_12, t.seeds, 12, split); + let note = || vec![(0x0096, Val::Undefined(table.clone()))]; + // The refusal must come from the split path, not from some other part of the file. + let unsupported = |r: Result| matches!(&r, Err(RawError::Unsupported(m)) if m.contains("lossy after split")); + // Over the size limits, and with the strip cut off by the end of the file. + let small = Limits { max_pixels: 100, ..Limits::default() }; + assert!(unsupported(decode_raw(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note()), &small))); + let file = nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, note()); + let cut = file.len() - 40; + assert!(unsupported(decode_raw(&file[..cut], &Limits::default()))); +} + +#[test] +fn split_strips_with_up_to_four_extra_rows_are_accepted() { + // A strip may hold whole fixed-rate rows past the image (one body stores 4022 rows for + // 4020): up to 4 such rows decode, the image rows unchanged; a fifth is refused. + for bits in [12u32, 14] { + let huff = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; + let (w, h, split) = (24usize, 7usize, 3usize); + let t = split_table(bits, split); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let max = curve.len() as i32 - 1; + for extra in 1..=5 { + let (src, recon) = encode_split(&gentle(w, h + extra, 600), w, huff, t.seeds, bits, split); + let got = decode(&src, w, h, bits, &t); + if extra <= 4 { + let want: Vec = recon[..w * h].iter().map(|&r| curve[r.clamp(0, max) as usize]).collect(); + assert_eq!(got.unwrap(), want, "{bits}-bit, {extra} extra rows"); + } else { + assert!(matches!(got, Err(RawError::Unsupported(_))), "{bits}-bit, {extra} extra rows: {got:?}"); + } + } + } +} diff --git a/crates/raw/src/saturation.rs b/crates/raw/src/saturation.rs index a36692a3f6..e5886d444f 100644 --- a/crates/raw/src/saturation.rs +++ b/crates/raw/src/saturation.rs @@ -12,7 +12,7 @@ //! the stated white level. Unclipped samples keep their values, and a file whose data reaches its white //! level, or has no pile-up, is left alone. Same detector as storytold/lightcraft#586. -use crate::sensor::Sensor; +use crate::sensor::{Cfa, Rect, Sensor}; /// A saturation plateau must hold at least this share of its colour's samples (and 100 of them), as /// many must lie below it (a scene, not a flat field)... @@ -29,6 +29,51 @@ const NEAR_WHITE: f32 = 0.03; /// How far below the plateau the "average value just below it" reaches. const NEIGHBOURHOOD: usize = 64; +/// Largest number of row bands counted in parallel: each holds a 768 KiB histogram. +const MAX_PARTS: usize = 16; + +/// Per-colour histogram of the samples of `active` (and the sample count per colour). Row bands are +/// counted in parallel, each row through one repeat of the CFA colours (one `Cfa::color` per pattern +/// column instead of one per sample), and the integer counts are summed, so the result does not depend +/// on the number of workers. +fn colour_histogram(data: &[u16], stride: usize, a: Rect, cfa: &Cfa) -> (Vec<[u32; 3]>, [u64; 3]) { + let parts = crate::par::workers().clamp(1, MAX_PARTS.min(a.height.max(1))); + let rows_per = a.height.div_ceil(parts).max(1); + let pw = cfa.width.max(1); + let partial = crate::par::map(a.height.div_ceil(rows_per), |p| { + let mut hist = vec![[0u32; 3]; 65536]; + let mut pattern = vec![0usize; pw]; + for y in a.y + p * rows_per..(a.y + (p + 1) * rows_per).min(a.y + a.height) { + for (k, c) in pattern.iter_mut().enumerate() { + *c = usize::from(cfa.color(a.x + k, y)).min(2); + } + let row = &data[y * stride + a.x..][..a.width]; + for run in row.chunks(pw) { + for (&v, &c) in run.iter().zip(&pattern) { + hist[usize::from(v)][c] += 1; + } + } + } + hist + }); + let mut parts = partial.into_iter(); + let mut hist = parts.next().unwrap_or_else(|| vec![[0u32; 3]; 65536]); + for part in parts { + for (h, q) in hist.iter_mut().zip(&part) { + for c in 0..3 { + h[c] += q[c]; + } + } + } + let mut total = [0u64; 3]; + for h in &hist { + for c in 0..3 { + total[c] += u64::from(h[c]); + } + } + (hist, total) +} + impl Sensor { /// The value each colour's samples saturate at, when that is clearly below the stated white level /// (see the module docs). Only CFA data without a linearization table is examined: with a table the @@ -55,16 +100,7 @@ impl Sensor { if lo + NEIGHBOURHOOD >= hi { return none; } - let mut hist = vec![[0u32; 3]; 65536]; - let mut total = [0u64; 3]; - for y in a.y..a.y + a.height { - let row = &self.data[y * self.width + a.x..][..a.width]; - for (x, &v) in (a.x..).zip(row) { - let c = usize::from(cfa.color(x, y)).min(2); - total[c] += 1; - hist[usize::from(v)][c] += 1; - } - } + let (hist, total) = colour_histogram(&self.data, self.width, a, cfa); let mut out = none; for c in 0..3 { // the most populated value of the upper half of the range @@ -119,6 +155,7 @@ impl Sensor { #[cfg(test)] mod tests { + use super::colour_histogram; use crate::*; /// A 64 x 64 RGGB mosaic with a gradient, black 528, white `white`, whose samples above `clip` (when @@ -262,4 +299,34 @@ mod tests { s.data.pop(); assert_eq!(s.lift_clipped_samples(), 0); } + + /// The per-row pattern and the parallel bands count exactly what a per-sample `Cfa::color` pass does, + /// for offset patterns, a 6 x 6 pattern, an inner active area and any number of bands. + #[test] + fn histogram_matches_the_per_sample_count() { + let (w, h) = (53usize, 47usize); + let data: Vec = (0..w * h).map(|i| ((i * 2654435761) >> 7) as u16 % 4096).collect(); + let xtrans = Cfa { width: 6, height: 6, colors: (0..36).map(|i| [1, 0, 2, 1, 2, 0][(i * 7 + i / 6) % 6]).collect(), origin_x: 5, origin_y: 2 }; + let mut offset = Cfa::bayer("GBRG").unwrap(); + offset.origin_x = 3; + offset.origin_y = 1; + for cfa in [Cfa::bayer("RGGB").unwrap(), offset, xtrans] { + for a in [Rect::new(0, 0, w, h), Rect::new(7, 5, 31, 22), Rect::new(1, 3, 1, 1), Rect::new(2, 2, 40, 1), Rect::new(0, 0, 0, 0)] { + let mut hist = vec![[0u32; 3]; 65536]; + let mut total = [0u64; 3]; + for y in a.y..a.y + a.height { + for x in a.x..a.x + a.width { + let c = usize::from(cfa.color(x, y)).min(2); + total[c] += 1; + hist[usize::from(data[y * w + x])][c] += 1; + } + } + for threads in [1, 2, 3, 8] { + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); + let (got, got_total) = pool.install(|| colour_histogram(&data, w, a, &cfa)); + assert!(got == hist && got_total == total, "{threads} threads, active {a:?}"); + } + } + } + } } diff --git a/crates/raw/src/sraw.rs b/crates/raw/src/sraw.rs new file mode 100644 index 0000000000..c027700661 --- /dev/null +++ b/crates/raw/src/sraw.rs @@ -0,0 +1,316 @@ +//! Canon sRAW / mRAW (CR2 with subsampled YCbCr). +//! +//! The camera demosaics the sensor data and stores it as Y, Cb, Cr in one lossless JPEG frame +//! whose Y component is sampled 2×2 (sRAW1, which Canon calls mRAW on the later bodies) or 2×1 +//! (sRAW2), sliced like the Bayer CR2 data (tag 0xC640, widths in samples). The decoder +//! ([`crate::ljpeg::decode_subsampled`]) gives the sample sequence; [`planes`] lays it out, +//! [`camera_rgb`] interpolates the chroma and converts to camera RGB, and the result is +//! developed like a three-sample LinearRaw: no CFA, the as-shot white balance, the look fitted +//! to the embedded JPEG (`photocraft-io`), tone and exposure as for every other raw. +//! +//! Observed on EOS 6D Mark II mRAW files (ColorData version 15, 4680 × 3132 data): +//! * Y is already black-subtracted (the darkest samples are 0) and on the sensor's scale; Cb and +//! Cr are colour differences offset by `2^(P−1)`. +//! * The stored RGB is camera RGB divided by per-shot gains, an RGGB entry of ColorData (word +//! 0x80 in version 15; its green is 1170, not the 1024 of the white-balance presets) that +//! roughly neutralises the scene. Multiplying them back gives camera RGB that matches an +//! independent converter's linear camera-RGB output of the same files to a diagonal of +//! (1, 1, 1) ± 1.5 % and 0.6 % RMS; the as-shot white balance then applies as for Bayer data. +//! * The inverse with the BT.601 luma weights (ITU-R BT.601: Y = 0.299 R + 0.587 G + 0.114 B) +//! and unscaled differences (Cb = B − Y, Cr = R − Y) leaves no cross-channel terms above 3 % +//! in that comparison. +//! * Chroma edges follow the luma edges slightly better half an MCU in than at its first +//! sample, so the chroma is treated as centred on its MCU and interpolated bilinearly. +//! +//! Approximate: the chroma siting and the bilinear interpolation (colour edges are softer than +//! in a Bayer development; luma keeps full resolution). The gains are read only for ColorData +//! versions where their offset was observed; for other bodies they are left at 1, which is a +//! diagonal colour error that the matrix fitted to the camera's JPEG absorbs (a warning says +//! so). Older bodies (sRAW before about 2009) are documented elsewhere to use other offsets +//! and chroma scalings; no such sample was available, so they decode with the same rule. +//! Shadow noise below black is clipped at 0 by the conversion. + +use crate::error::{RawError, Result}; +use crate::ljpeg::Frame; +use crate::par; + +/// The de-sliced YCbCr planes: Y at full resolution, Cb and Cr one sample per MCU, stored +/// values (chroma still carries its offset). +pub(crate) struct Planes { + pub width: usize, + pub height: usize, + pub h: usize, + pub v: usize, + pub y: Vec, + pub cb: Vec, + pub cr: Vec, +} + +/// Lays the decoded sample sequence out as planes. `slices` are the slice widths in samples +/// (CR2 tag 0xC640; one slice of the whole MCU row when absent): slice 0 is filled MCU row by +/// MCU row, then slice 1, and so on, as for the Bayer CR2 data. +pub(crate) fn planes(f: &Frame, samples: &[u16], slices: &[usize]) -> Result { + let (h, v) = (f.h, f.v); + let per_mcu = h * v + 2; + let total: usize = slices.iter().sum(); + if total == 0 || !total.is_multiple_of(per_mcu) || slices.iter().any(|w| !w.is_multiple_of(per_mcu)) || !samples.len().is_multiple_of(total) { + return Err(RawError::malformed("CR2 sRAW slices do not match the JPEG frame")); + } + let mcus = total / per_mcu; + let rows = samples.len() / total; + let (width, height) = (mcus * h, rows * v); + let mut p = Planes { width, height, h, v, y: vec![0; width * height], cb: vec![0; mcus * rows], cr: vec![0; mcus * rows] }; + let mut runs = samples.chunks_exact(per_mcu); + let mut x0 = 0usize; + for &sw in slices { + let n = sw / per_mcu; + for r in 0..rows { + for mx in x0..x0 + n { + let mcu = runs.next().ok_or_else(|| RawError::malformed("CR2 sRAW slice data is short"))?; + let (ys, c) = mcu.split_at(h * v); + for (k, &s) in ys.iter().enumerate() { + let (x, y) = (mx * h + k % h, r * v + k / h); + if let Some(d) = p.y.get_mut(y * width + x) { + *d = s; + } + } + if let ([cb, cr], Some(dcb), Some(dcr)) = (c, p.cb.get_mut(r * mcus + mx), p.cr.get_mut(r * mcus + mx)) { + (*dcb, *dcr) = (*cb, *cr); + } + } + } + x0 += n; + } + Ok(p) +} + +/// White level of unclipped frames: 14-bit full scale less Canon's usual black of about 2048. +pub(crate) const FULL_SCALE: f32 = 14335.0; + +/// BT.601 luma weights of R and B (G's is the rest). +const KR: f32 = 0.299; +const KB: f32 = 0.114; + +/// Interpolates the chroma to every pixel and converts to camera RGB, interleaved: +/// `R = Y + Cr`, `B = Y + Cb`, `G = (Y − KR·R − KB·B) / KG`, then each channel multiplied by the +/// camera's sRAW `gains`. `offset` is the chroma's zero (`2^(P−1)`). +pub(crate) fn camera_rgb(p: &Planes, offset: f32, gains: [f64; 3]) -> Vec { + let (w, h) = (p.width, p.height); + let cw = w / p.h.max(1); + let ch = p.cb.len().checked_div(cw).unwrap_or(0); + let mut out = vec![0u16; w * h * 3]; + if w == 0 || cw == 0 || ch == 0 { + return out; + } + let gains = gains.map(|m| if m.is_finite() && m > 0.0 { m as f32 } else { 1.0 }); + let kg = 1.0 - KR - KB; + // Chroma sample positions: centred on the MCU (see the module docs). Per output column (row): + // the two chroma columns (rows) around it and the weight of the second. + let taps = |n: usize, f: usize, len: usize| -> Vec<(usize, usize, f32)> { + (0..n) + .map(|i| { + let c = ((i as f32 + 0.5) / f as f32 - 0.5).clamp(0.0, (len - 1) as f32); + let a = (c as usize).min(len - 1); + let b = (a + 1).min(len - 1); + (a, b, c - a as f32) + }) + .collect() + }; + let xs = taps(w, p.h.max(1), cw); + let ys = taps(h, p.v.max(1), ch); + let band = par::band_rows(w); + par::chunks_mut(&mut out, band * w * 3, |b, chunk| { + for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() { + let y = b * band + r; + let (Some(luma), Some(&(ya, yb, fy))) = (p.y.get(y * w..(y + 1) * w), ys.get(y)) else { continue }; + let chroma = |plane: &[u16], xa: usize, xb: usize, fx: f32| { + let at = |cy: usize, cx: usize| plane.get(cy * cw + cx).map_or(offset, |&v| f32::from(v)); + let top = at(ya, xa) * (1.0 - fx) + at(ya, xb) * fx; + let bottom = at(yb, xa) * (1.0 - fx) + at(yb, xb) * fx; + top * (1.0 - fy) + bottom * fy - offset + }; + for ((o, &l), &(xa, xb, fx)) in row.as_chunks_mut::<3>().0.iter_mut().zip(luma).zip(&xs) { + let l = f32::from(l); + let (cb, cr) = (chroma(&p.cb, xa, xb, fx), chroma(&p.cr, xa, xb, fx)); + let (red, blue) = (l + cr, l + cb); + let green = (l - KR * red - KB * blue) / kg; + for (k, v) in [red, green, blue].into_iter().enumerate() { + o[k] = (v * gains[k]).round().clamp(0.0, 65535.0) as u16; + } + } + } + }); + out +} + +/// White level of channel `k` of interleaved RGB: the largest value when a meaningful share of +/// samples piles up there (clipped highlights), else `full`. +pub(crate) fn clip_level(rgb: &[u16], k: usize, full: f32) -> f32 { + let step = 3 * (rgb.len() / 3 / 2_000_000).max(1); + let samples = || rgb.iter().skip(k).step_by(step); + let max = samples().copied().max().unwrap_or(0); + if max == 0 { + return full; + } + let near = samples().filter(|&&v| u32::from(v) + u32::from(max / 256) >= u32::from(max)).count(); + if near * 2000 >= samples().count() { f32::from(max) * 0.995 } else { full.max(f32::from(max)) } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testgen::Cr2SrawSpec; + use crate::{DevelopOptions, Limits, decode, develop_sensor}; + + const OFFSET: f32 = 16384.0; + + /// A linear ramp of camera RGB (bilinear chroma interpolation reproduces it exactly away + /// from the borders). + fn camera(x: usize, y: usize) -> [f32; 3] { + let (x, y) = (x as f32, y as f32); + [1500.0 + 40.0 * x + 10.0 * y, 2500.0 + 15.0 * x + 30.0 * y, 1200.0 + 5.0 * x + 45.0 * y] + } + + /// The camera's stored YCbCr for `camera` divided by `gains`: Y per pixel, Cb / Cr at the + /// centre of each MCU (the siting the decoder assumes). + fn spec(h: usize, v: usize, gains: [f32; 3], slices: Vec, restart_rows: Option) -> Cr2SrawSpec { + let (w, ht) = (48, 24); + let stored = |x: f32, y: f32| { + let c = camera(0, 0); + let (dx, dy) = (camera(1, 0), camera(0, 1)); + [0, 1, 2].map(|k| (c[k] + (dx[k] - c[k]) * x + (dy[k] - c[k]) * y) / gains[k]) + }; + let ycc = |p: [f32; 3]| { + let y = KR * p[0] + (1.0 - KR - KB) * p[1] + KB * p[2]; + (y, p[2] - y + OFFSET, p[0] - y + OFFSET) + }; + let y = (0..w * ht).map(|i| ycc(stored((i % w) as f32, (i / w) as f32)).0.round() as u16).collect(); + let (mw, mh) = (w / h, ht / v); + let centre = |m: usize, f: usize| (m * f) as f32 + (f as f32 - 1.0) / 2.0; + let chroma: Vec<(f32, f32, f32)> = (0..mw * mh).map(|i| ycc(stored(centre(i % mw, h), centre(i / mw, v)))).collect(); + Cr2SrawSpec { + width: w, + height: ht, + h, + v, + precision: 15, + y, + cb: chroma.iter().map(|c| c.1.round() as u16).collect(), + cr: chroma.iter().map(|c| c.2.round() as u16).collect(), + slices, + restart_rows, + wb_rggb: Some([2048, 1024, 1024, 1536]), + gains: Some([(1170.0 * gains[0]) as u16, 1170, 1170, (1170.0 * gains[2]) as u16]), + borders: Some([0, 2, 47, 23]), + } + } + + #[test] + fn sraw_decodes_to_camera_rgb() { + let gains = [0.75, 1.0, 0.4]; + // sRAW1 (2×2: 6 samples an MCU) and sRAW2 (2×1: 4 samples an MCU), with and without + // slices and restart intervals. + for (h, v, slices, restart) in + [(2, 2, vec![], None), (2, 2, vec![48, 48, 48], Some(3)), (2, 2, vec![60, 60, 24], None), (2, 1, vec![], Some(1)), (2, 1, vec![32, 32, 32], None)] + { + let s = spec(h, v, gains, slices.clone(), restart); + let sensor = decode(&s.build(), &Limits::default()).expect("decode"); + assert_eq!((sensor.width, sensor.height, sensor.samples), (48, 24, 3), "{h}x{v} {slices:?}"); + assert!(sensor.cfa.is_none()); + assert_eq!(sensor.crop, crate::Rect::new(0, 2, 48, 22)); + assert_eq!(sensor.camera_wb, Some([2.0, 1.0, 1.5])); + assert!(sensor.warnings.is_empty(), "{:?}", sensor.warnings); + for y in 2..22 { + for x in 2..46 { + let at = (y * 48 + x) * 3; + for (k, (&got, want)) in sensor.data[at..at + 3].iter().zip(camera(x, y)).enumerate() { + let got = f32::from(got); + // Rounding of Y, Cb, Cr and the stored gains (whole 1/1170 steps). + assert!((got - want).abs() <= 4.0 + want * 0.002, "{h}x{v} {slices:?} ({x}, {y}) ch {k}: {got} vs {want}"); + } + } + } + } + } + + #[test] + fn unknown_gains_keep_the_stored_colour_and_say_so() { + let mut s = spec(2, 2, [1.0; 3], vec![], None); + s.gains = None; + let sensor = decode(&s.build(), &Limits::default()).expect("decode"); + assert!(sensor.warnings.iter().any(|w| w.contains("sRAW colour gains")), "{:?}", sensor.warnings); + let want = camera(10, 10); + let got = &sensor.data[(10 * 48 + 10) * 3..(10 * 48 + 10) * 3 + 3]; + assert!(got.iter().zip(want).all(|(&g, w)| (f32::from(g) - w).abs() <= 4.0), "{got:?} vs {want:?}"); + } + + #[test] + fn sraw_develops_as_linear_rgb() { + let s = spec(2, 1, [0.75, 1.0, 0.4], vec![], None); + let sensor = decode(&s.build(), &Limits::default()).expect("decode"); + let d = develop_sensor(&sensor, &DevelopOptions::default()).expect("develop"); + assert_eq!((d.width, d.height), (48, 22)); + assert_eq!(d.info.cfa, None); + assert_eq!(d.info.wb_multipliers, [2.0, 1.0, 1.5]); + } + + #[test] + fn corrupt_sraw_errors_without_panicking() { + let b = spec(2, 2, [0.75, 1.0, 0.4], vec![48, 48, 48], Some(2)).build(); + for n in (0..b.len()).step_by(7) { + let _ = decode(&b[..n], &Limits::default()); + } + let mut s = 0x9E37_79B9u64; + for _ in 0..1500 { + let mut c = b.clone(); + for _ in 0..3 { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let at = (s >> 33) as usize % c.len(); + c[at] = (s >> 20) as u8; + } + if let Ok(sensor) = decode(&c, &Limits::default()) { + let _ = develop_sensor(&sensor, &DevelopOptions::default()); + } + } + // Slices that do not split whole MCUs are refused. + let mut bad = spec(2, 2, [1.0; 3], vec![48, 48, 48], None).build(); + let tag = bad.windows(4).position(|w| w == [0x40, 0xC6, 3, 0]).expect("slice tag"); + let at = u32::from_le_bytes([bad[tag + 8], bad[tag + 9], bad[tag + 10], bad[tag + 11]]) as usize; + bad[at + 2..at + 4].copy_from_slice(&47u16.to_le_bytes()); + assert!(matches!(decode(&bad, &Limits::default()), Err(RawError::Malformed(_)))); + // The planes refuse a sample count that is not whole slice rows. + let f = Frame { precision: 15, width: 4, height: 2, components: 3, h: 2, v: 2 }; + assert!(planes(&f, &[0; 11], &[12]).is_err()); + assert!(planes(&f, &[0; 12], &[0]).is_err()); + } + + #[test] + fn white_level_follows_clipping() { + // A lone bright sample is not clipping. + let mut rgb: Vec = (0..3 * 10_000).map(|i| (i % 5000) as u16).collect(); + rgb[0] = 9000; + assert_eq!(clip_level(&rgb, 0, 14335.0), 14335.0); + for p in rgb.as_chunks_mut::<3>().0.iter_mut().take(100) { + p[1] = 12000; + } + assert!((clip_level(&rgb, 1, 14335.0) - 12000.0 * 0.995).abs() < 1e-3); + assert_eq!(clip_level(&[], 2, 14335.0), 14335.0); + } + + /// Real files: `PHOTOCRAFT_SRAW_CR2` lists CR2 paths (separated by `:`), e.g. EOS 6D Mark II + /// mRAW. Checks the size, the gains and that the development runs. + #[test] + #[ignore = "needs real sRAW CR2 files in PHOTOCRAFT_SRAW_CR2"] + fn real_sraw_files() { + let paths = std::env::var("PHOTOCRAFT_SRAW_CR2").expect("PHOTOCRAFT_SRAW_CR2"); + for path in paths.split(':').filter(|p| !p.is_empty()) { + let bytes = std::fs::read(path).expect("read"); + let s = decode(&bytes, &Limits::default()).expect("decode"); + assert_eq!(s.samples, 3, "{path}"); + assert!(s.cfa.is_none() && s.camera_wb.is_some(), "{path}"); + assert!(s.warnings.is_empty(), "{path}: {:?}", s.warnings); + let d = develop_sensor(&s, &DevelopOptions::default()).expect("develop"); + eprintln!("{path}: {}x{} from {}x{}, white {:?}", d.width, d.height, s.width, s.height, s.white); + } + } +} diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs index b5df57e3c0..7d06459365 100644 --- a/crates/raw/src/testgen.rs +++ b/crates/raw/src/testgen.rs @@ -15,9 +15,9 @@ mod raf; mod rw2; mod tiff; -pub use canon::{Cr2Spec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep}; +pub use canon::{Cr2Spec, Cr2SrawSpec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep}; pub use dng::{DngSpec, DngStorage, baseline_jpeg, gain_map_opcode_list, map_polynomial_opcode_list}; -pub use lj92::{lj92_encode, lj92_encode_tables}; +pub use lj92::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables}; pub use orf::orf; pub use raf::{RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, scene}; pub use rw2::{rw2, rw2_format4, rw2_pack, rw2_v4_pack}; diff --git a/crates/raw/src/testgen/canon.rs b/crates/raw/src/testgen/canon.rs index 33a28d057d..2c4ad54f96 100644 --- a/crates/raw/src/testgen/canon.rs +++ b/crates/raw/src/testgen/canon.rs @@ -1,4 +1,4 @@ -use super::lj92::lj92_encode; +use super::lj92::{lj92_encode, lj92_encode_sraw}; use super::tiff::{TiffBuilder, Val}; // ---------------------------------------------------------------- CR2 @@ -94,6 +94,103 @@ impl Cr2Spec { } } +/// A synthetic Canon sRAW / mRAW CR2: Y, Cb and Cr planes in one subsampled lossless JPEG +/// (see `ljpeg::decode_subsampled` and `sraw.rs`). +#[derive(Debug, Clone)] +pub struct Cr2SrawSpec { + /// Image size in pixels (multiples of `h` and `v`). + pub width: usize, + pub height: usize, + /// Y sampling factors: 2×2 (sRAW1 / mRAW) or 2×1 (sRAW2). + pub h: usize, + pub v: usize, + pub precision: u8, + /// `width * height` Y samples, row-major. + pub y: Vec, + /// One Cb and one Cr per MCU (`width / h` by `height / v`), offset by `2^(precision−1)`. + pub cb: Vec, + pub cr: Vec, + /// Slice widths in samples (all but the last equal); empty = no slice tag. + pub slices: Vec, + /// Restart interval in MCU rows. + pub restart_rows: Option, + /// As-shot RGGB levels at ColorData word 0x3F. + pub wb_rggb: Option<[u16; 4]>, + /// sRAW gains (RGGB) at ColorData word 0x80; ColorData version 15 is written either way. + pub gains: Option<[u16; 4]>, + /// Image borders: left, top, right, bottom (inclusive), as in SensorInfo. + pub borders: Option<[u16; 4]>, +} + +impl Cr2SrawSpec { + pub fn build(&self) -> Vec { + let (h, v) = (self.h, self.v); + let per_mcu = h * v + 2; + let (mcus, rows) = (self.width / h, self.height / v); + let widths: Vec = if self.slices.is_empty() { vec![mcus * per_mcu] } else { self.slices.clone() }; + assert_eq!(widths.iter().sum::(), mcus * per_mcu); + // Slice the MCUs into the JPEG sample order. + let mut seq = Vec::with_capacity(mcus * rows * per_mcu); + let mut m0 = 0; + for &sw in &widths { + assert_eq!(sw % per_mcu, 0); + let n = sw / per_mcu; + for r in 0..rows { + for mx in m0..m0 + n { + for k in 0..h * v { + seq.push(self.y[(r * v + k / h) * self.width + mx * h + k % h]); + } + seq.push(self.cb[r * mcus + mx]); + seq.push(self.cr[r * mcus + mx]); + } + } + m0 += n; + } + let jpeg = lj92_encode_sraw(&seq, self.width, self.height, h, v, self.precision, self.restart_rows); + let mut t = TiffBuilder::default(); + let jb = t.blob(jpeg.clone()); + let mut raw = vec![ + (256, Val::Short(vec![self.width as u16])), + (257, Val::Short(vec![self.height as u16])), + (259, Val::Short(vec![6])), + (273, Val::Blobs(vec![jb])), + (279, Val::Long(vec![jpeg.len() as u32])), + ]; + if !self.slices.is_empty() { + let n = widths.len() - 1; + raw.push((50752, Val::Short(vec![n as u16, widths[0] as u16, widths[n] as u16]))); + } + let raw_ifd = t.ifd(raw); + let mut mn: Vec<(u16, Val)> = Vec::new(); + if let Some([l, tp, r, b]) = self.borders { + mn.push((0x00E0, Val::Short(vec![34, self.width as u16, self.height as u16, 0, 0, l, tp, r, b, 0, 0, 0, 0, 0, 0, 0, 0]))); + } + let mut cd = vec![0u8; 2 * 1602]; + cd[0..2].copy_from_slice(&15u16.to_le_bytes()); + for (at, levels) in [(0x3F, self.wb_rggb), (0x80, self.gains)] { + for (i, v) in levels.iter().flatten().enumerate() { + cd[2 * (at + i)..2 * (at + i) + 2].copy_from_slice(&v.to_le_bytes()); + } + } + mn.push((0x4001, Val::Undefined(cd))); + let mi = t.ifd(mn); + let exif_ifd = t.ifd(vec![(33434, Val::Rational(vec![(1, 100)])), (37500, Val::IfdBytes(mi))]); + let ifd0 = t.ifd(vec![ + (256, Val::Long(vec![2])), + (257, Val::Long(vec![2])), + (271, Val::Ascii("Canon".into())), + (272, Val::Ascii("Canon EOS Synthetic".into())), + (274, Val::Short(vec![1])), + (34665, Val::Ifds(vec![exif_ifd])), + ]); + let ifd1 = t.ifd(vec![(256, Val::Long(vec![1]))]); + let ifd2 = t.ifd(vec![(256, Val::Long(vec![1]))]); + t.chain = vec![ifd0, ifd1, ifd2, raw_ifd]; + t.cr2_raw_ifd = Some(raw_ifd); + t.build() + } +} + // ---------------------------------------------------------------- TIFF/EP /// A synthetic uncompressed TIFF/EP raw (NEF / ARW-like): IFD0 with Make, the diff --git a/crates/raw/src/testgen/lj92.rs b/crates/raw/src/testgen/lj92.rs index 379d8dfdd0..fe5034c65c 100644 --- a/crates/raw/src/testgen/lj92.rs +++ b/crates/raw/src/testgen/lj92.rs @@ -56,7 +56,6 @@ pub fn lj92_encode(samples: &[u16], width: usize, height: usize, components: usi pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of: &[u8], precision: u8, predictor: u8, restart_rows: Option) -> Vec { let components = table_of.len(); assert_eq!(samples.len(), width * height * components); - assert!(table_of.iter().all(|&t| t < 4)); let row = width * components; let interval = restart_rows.unwrap_or(usize::MAX); // Differences per sample, following T.81 H.1.2.1 prediction rules. @@ -85,16 +84,118 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of _ => (ra + rb) >> 1, } }; - let mut d = (i32::from(samples[i]) - px) & 0xFFFF; - if d > 32768 { - d -= 65536; - } - diffs.push(d); + diffs.push(wrap_diff(i32::from(samples[i]) - px)); } } } + let frame = Frame { + width, + height, + factors: &vec![0x11; components], + table_of, + pattern: &(0..components as u8).collect::>(), + precision, + predictor, + restart: restart_rows.map(|r| (r * width, interval.saturating_mul(row))), + }; + lj92_stream(&diffs, &frame) +} + +/// A difference modulo 2^16, in −32767..=32768 (T.81 H.1.2.2). +fn wrap_diff(d: i32) -> i32 { + let d = d & 0xFFFF; + if d > 32768 { d - 65536 } else { d } +} + +/// Encodes a Canon sRAW / mRAW frame: `seq` is the sample sequence in decode order (per MCU the +/// `h × v` Y samples, then Cb and Cr; `width / h` MCUs a row), predicted as +/// `ljpeg::decode_subsampled` describes: each Y from the previous Y, Cb and Cr from the previous +/// MCU's, the first MCU of a row from the first of the row above. `restart_rows` counts MCU rows. +pub fn lj92_encode_sraw(seq: &[u16], width: usize, height: usize, h: usize, v: usize, precision: u8, restart_rows: Option) -> Vec { + lj92_encode_sraw_tables(seq, width, height, (h, v), [0, 0, 0], precision, restart_rows) +} + +/// Like [`lj92_encode_sraw`], but Y, Cb and Cr use Huffman tables `table_of` (0–3). +pub fn lj92_encode_sraw_tables( + seq: &[u16], + width: usize, + height: usize, + (h, v): (usize, usize), + table_of: [u8; 3], + precision: u8, + restart_rows: Option, +) -> Vec { + let (luma, mcus) = (h * v, width / h); + let per_mcu = luma + 2; + let row_len = mcus * per_mcu; + assert_eq!(seq.len(), row_len * (height / v)); + let interval = restart_rows.unwrap_or(usize::MAX); + let initial = 1i32 << (precision - 1); + let mut diffs = Vec::with_capacity(seq.len()); + let mut top = [initial; 3]; + for (r, row) in seq.chunks_exact(row_len).enumerate() { + if r % interval == 0 { + top = [initial; 3]; + } + let (mut y, mut cb, mut cr) = (top[0], top[1], top[2]); + for (m, mcu) in row.chunks_exact(per_mcu).enumerate() { + for (k, &s) in mcu[..luma].iter().enumerate() { + let pred = if m == 0 && k == 0 { top[0] } else { y }; + diffs.push(wrap_diff(i32::from(s) - pred)); + y = i32::from(s); + if m == 0 && k == 0 { + top[0] = y; + } + } + diffs.push(wrap_diff(i32::from(mcu[luma]) - cb)); + diffs.push(wrap_diff(i32::from(mcu[luma + 1]) - cr)); + (cb, cr) = (i32::from(mcu[luma]), i32::from(mcu[luma + 1])); + if m == 0 { + (top[1], top[2]) = (cb, cr); + } + } + } + let mut pattern = vec![0u8; luma]; + pattern.extend_from_slice(&[1, 2]); + let frame = Frame { + width, + height, + factors: &[(h as u8) << 4 | v as u8, 0x11, 0x11], + table_of: &table_of, + pattern: &pattern, + precision, + predictor: 1, + restart: restart_rows.map(|r| (r * mcus, interval.saturating_mul(row_len))), + }; + lj92_stream(&diffs, &frame) +} + +/// The frame header [`lj92_stream`] writes around the differences. +struct Frame<'a> { + width: usize, + height: usize, + /// Each component's sampling factors (`h << 4 | v`). + factors: &'a [u8], + /// Each component's Huffman table id (0–3). + table_of: &'a [u8], + /// The component of each difference, repeating: `0, 1, 2` interleaved, or an MCU's Y samples + /// then Cb and Cr. + pattern: &'a [u8], + precision: u8, + predictor: u8, + /// The restart interval `(DRI value, differences per interval)`. + restart: Option<(usize, usize)>, +} + +/// Writes SOI, SOF3, one DHT per table id, the restart interval, SOS and the entropy-coded +/// `diffs`. +fn lj92_stream(diffs: &[i32], f: &Frame<'_>) -> Vec { + let components = f.factors.len(); + assert_eq!(f.table_of.len(), components); + assert!(f.table_of.iter().all(|&t| t < 4)); + let table = |i: usize| f.table_of[usize::from(f.pattern[i % f.pattern.len()])]; // Tables: categories ordered by frequency get increasing code lengths. - let mut ids: Vec = table_of.to_vec(); + let mut ids: Vec = f.table_of.to_vec(); ids.sort_unstable(); ids.dedup(); let mut code_of = [[(0u32, 0u32); 17]; 4]; @@ -102,7 +203,7 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of for &t in &ids { let mut freq = [0usize; 17]; for (i, &d) in diffs.iter().enumerate() { - if table_of[i % components] == t { + if table(i) == t { freq[category(d) as usize] += 1; } } @@ -133,12 +234,12 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of // SOF3 out.extend_from_slice(&[0xFF, 0xC3]); out.extend_from_slice(&((8 + 3 * components) as u16).to_be_bytes()); - out.push(precision); - out.extend_from_slice(&(height as u16).to_be_bytes()); - out.extend_from_slice(&(width as u16).to_be_bytes()); + out.push(f.precision); + out.extend_from_slice(&(f.height as u16).to_be_bytes()); + out.extend_from_slice(&(f.width as u16).to_be_bytes()); out.push(components as u8); - for c in 0..components { - out.extend_from_slice(&[c as u8 + 1, 0x11, 0]); + for (c, &factor) in f.factors.iter().enumerate() { + out.extend_from_slice(&[c as u8 + 1, factor, 0]); } // DHT, one per table id for (t, counts, vals) in &dhts { @@ -148,28 +249,29 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of out.extend_from_slice(counts); out.extend_from_slice(vals); } - if let Some(r) = restart_rows { + if let Some((dri, _)) = f.restart { out.extend_from_slice(&[0xFF, 0xDD, 0, 4]); - out.extend_from_slice(&((r * width) as u16).to_be_bytes()); + out.extend_from_slice(&(dri as u16).to_be_bytes()); } + let every = f.restart.map_or(usize::MAX, |(_, n)| n); // SOS out.extend_from_slice(&[0xFF, 0xDA]); out.extend_from_slice(&((6 + 2 * components) as u16).to_be_bytes()); out.push(components as u8); - for (c, &t) in table_of.iter().enumerate() { + for (c, &t) in f.table_of.iter().enumerate() { out.extend_from_slice(&[c as u8 + 1, t << 4]); } - out.extend_from_slice(&[predictor, 0, 0]); + out.extend_from_slice(&[f.predictor, 0, 0]); let mut w = BitWriter { out, acc: 0, n: 0 }; let mut rst = 0u8; for (i, &d) in diffs.iter().enumerate() { - if i > 0 && i % (interval.saturating_mul(row)) == 0 { + if i > 0 && i % every == 0 { w.flush(); w.out.extend_from_slice(&[0xFF, 0xD0 + rst]); rst = (rst + 1) % 8; } let s = category(d); - let (c, l) = code_of[usize::from(table_of[i % components])][s as usize]; + let (c, l) = code_of[usize::from(table(i))][s as usize]; w.put(c, l); if (1..16).contains(&s) { let extra = if d < 0 { (d - 1) as u32 & ((1 << s) - 1) } else { d as u32 }; diff --git a/crates/raw/tests/it/vendors.rs b/crates/raw/tests/it/vendors.rs index 1946899192..e1b70bc88f 100644 --- a/crates/raw/tests/it/vendors.rs +++ b/crates/raw/tests/it/vendors.rs @@ -56,7 +56,8 @@ fn cr2_develops() { #[test] fn cr2_srgb_raw_is_unsupported() { - // A subsampled (sRAW-style) frame: patch the first component's sampling factors. + // A subsampled frame in a layout Canon sRAW does not use (two components, Y 2×1): patch the + // first component's sampling factors. Real sRAW / mRAW decodes (see `sraw.rs`). let mut b = cr2_spec(32, 8, 2, vec![]).build(); let sof = b.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap(); b[sof + 11] = 0x21; diff --git a/crates/tablet/Cargo.toml b/crates/tablet/Cargo.toml index cc68771f61..2eed4b7cb8 100644 --- a/crates/tablet/Cargo.toml +++ b/crates/tablet/Cargo.toml @@ -3,12 +3,12 @@ name = "photocraft-tablet" version.workspace = true edition.workspace = true license.workspace = true -description = "Pen tablet pressure, tilt, rotation and eraser end on macOS (AppKit), Linux X11 (XInput2) and Windows (WinTab), and barrel button on Windows" +description = "Pen tablet pressure, tilt, rotation and eraser end on macOS (AppKit), Linux X11 (XInput2) and Windows (WinTab), and barrel button and eraser end on Windows (Windows Ink)" # The one isolated `unsafe` helper crate (see AGENTS.md, Never crash): the AppKit event -# monitor on macOS and the WH_GETMESSAGE pointer hook on Windows need platform interop. Only -# `src/macos.rs` and `src/windows.rs` allow `unsafe`; everything else is denied, and every other -# crate keeps the workspace's `unsafe_code = "forbid"`. +# monitor on macOS and the WH_GETMESSAGE and WH_CALLWNDPROC pointer hooks on Windows need +# platform interop. Only `src/macos.rs` and `src/windows.rs` allow `unsafe`; everything else is +# denied, and every other crate keeps the workspace's `unsafe_code = "forbid"`. [lints.rust] unsafe_code = "deny" diff --git a/crates/tablet/src/lib.rs b/crates/tablet/src/lib.rs index ca158a9137..480c888a39 100644 --- a/crates/tablet/src/lib.rs +++ b/crates/tablet/src/lib.rs @@ -5,13 +5,13 @@ //! each `NSEvent` (`pressure`, `tilt`, `rotation`, `subtype`, and `pointingDeviceType` from //! proximity events) before winit sees the event, so every pointer event the UI handles already //! has its pen sample. -//! - **Windows** ([`windows::Monitor`]): a thread-local message hook inspects `WM_POINTER*` -//! messages on the UI thread's message queue to read `PEN_FLAG_BARREL` (`GetPointerPenInfo`), -//! which winit 0.30 drops by mapping pen inputs to touch events. +//! - **Windows** ([`windows::Monitor`]): thread-local message hooks inspect `WM_POINTER*` +//! messages on the UI thread to read `PEN_FLAG_BARREL` and the eraser end (`PEN_FLAG_INVERTED`) +//! from `GetPointerPenInfo`, which winit 0.30 drops by mapping pen inputs to touch events. //! - **Windows WinTab** ([`wintab`]): with Windows Ink disabled for the tablet, a WinTab 1.4 //! system context on PhotoCraft's window supplies pressure, tilt, rotation and the eraser end. //! The vendor driver still moves the cursor; [`wintab::poll`] is called once per frame. -//! AppKit's monitor API and Windows' thread hook need OS interop, so `macos.rs` and `windows.rs` +//! AppKit's monitor API and Windows' thread hooks need OS interop, so `macos.rs` and `windows.rs` //! allow `unsafe` (an isolated, tested helper crate with `SAFETY:` //! comments on every block). //! - **Linux X11** ([`x11::spawn`]): a second, pure-Rust X connection (x11rb) selects XInput2 diff --git a/crates/tablet/src/windows.rs b/crates/tablet/src/windows.rs index c8426fefa5..f509cc5a0f 100644 --- a/crates/tablet/src/windows.rs +++ b/crates/tablet/src/windows.rs @@ -1,17 +1,55 @@ -//! Windows pointer hook for tablet data dropped by winit (such as the pen barrel button). +//! Windows pointer hook for tablet data dropped by winit (the pen barrel button and eraser end). //! -//! winit 0.30 drops `POINTER_PEN_INFO::penFlags` (`PEN_FLAG_BARREL`) on Windows and turns pen -//! inputs into `WindowEvent::Touch`, mapping them to `PointerButton::Primary`. Windows Ink also -//! does not update `GetAsyncKeyState(VK_RBUTTON)` for stylus barrel buttons. This thread-local -//! `WH_GETMESSAGE` hook inspects `WM_POINTER*` messages on the UI thread's message queue to -//! track the physical barrel button state. +//! winit 0.30 drops `POINTER_PEN_INFO::penFlags` (`PEN_FLAG_BARREL`, `PEN_FLAG_INVERTED`, +//! `PEN_FLAG_ERASER`) on Windows and turns pen inputs into `WindowEvent::Touch`, mapping them to +//! `PointerButton::Primary`. Windows Ink also does not update `GetAsyncKeyState(VK_RBUTTON)` for +//! stylus barrel buttons. Thread-local hooks inspect `WM_POINTER*` messages on the UI thread to +//! track the physical barrel button state and which end of the pen is in use: `WH_GETMESSAGE` for +//! the posted ones (`WM_POINTERDOWN`, `WM_POINTERUPDATE`, `WM_POINTERUP`) and `WH_CALLWNDPROC` for +//! `WM_POINTERENTER` and `WM_POINTERLEAVE`, which Windows documents as sent to the window, so the +//! queue hook alone may never see the pen arrive or leave. #![allow(unsafe_code, clippy::upper_case_acronyms)] -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering}; static BARREL_DOWN: AtomicBool = AtomicBool::new(false); +/// The pointer id of the pen last seen, or [`NO_PEN`]. Ids come from a 16-bit field, so +/// `u32::MAX` is never one. +static PEN_ID: AtomicU32 = AtomicU32::new(NO_PEN); +const NO_PEN: u32 = u32::MAX; + +/// The pen end last reported, as [`encode_end`] stores it. +static PEN_END: AtomicU8 = AtomicU8::new(0); + +/// The pen end of the last contact [`take_pen_end`] has not read yet, as [`encode_end`] stores it. +static CONTACT_END: AtomicU8 = AtomicU8::new(0); + +fn encode_end(end: Option) -> u8 { + match end { + None => 0, + Some(false) => 1, + Some(true) => 2, + } +} + +fn decode_end(v: u8) -> Option { + match v { + 1 => Some(false), + 2 => Some(true), + _ => None, + } +} + +#[repr(C)] +struct CWPSTRUCT { + l_param: isize, + w_param: usize, + message: u32, + hwnd: *mut std::ffi::c_void, +} + #[repr(C)] struct POINT { x: i32, @@ -74,17 +112,40 @@ unsafe extern "system" { } const WH_GETMESSAGE: i32 = 3; -const WM_POINTERUPDATE: u32 = 0x0245; -const WM_POINTERDOWN: u32 = 0x0246; -const WM_POINTERUP: u32 = 0x0247; -const WM_POINTERLEAVE: u32 = 0x024A; +const WH_CALLWNDPROC: i32 = 4; +/// `WM_POINTERENTER` (winuser.h). +pub const WM_POINTERENTER: u32 = 0x0249; +/// `WM_POINTERUPDATE` (winuser.h). +pub const WM_POINTERUPDATE: u32 = 0x0245; +/// `WM_POINTERDOWN` (winuser.h). +pub const WM_POINTERDOWN: u32 = 0x0246; +/// `WM_POINTERUP` (winuser.h). +pub const WM_POINTERUP: u32 = 0x0247; +/// `WM_POINTERLEAVE` (winuser.h). +pub const WM_POINTERLEAVE: u32 = 0x024A; /// `PEN_FLAG_BARREL` (winuser.h): the barrel button of the pen is pressed. pub const PEN_FLAG_BARREL: u32 = 0x00000001; +/// `PEN_FLAG_INVERTED` (winuser.h): the pen is inverted (its eraser end is in use). +pub const PEN_FLAG_INVERTED: u32 = 0x00000002; + +/// `PEN_FLAG_ERASER` (winuser.h): the eraser button of the pen is pressed. +pub const PEN_FLAG_ERASER: u32 = 0x00000004; + /// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (winuser.h): the secondary action button is pressed. pub const POINTER_FLAG_SECONDBUTTON: u32 = 0x00000020; +/// Pure decode of which end of the pen is in use: `Some(true)` for the eraser end, `Some(false)` +/// for the tip, `None` when the pointer is not a pen (`GetPointerPenInfo` failed: mouse, touch). +/// +/// Only `PEN_FLAG_INVERTED` means the pen is flipped: it is set the whole time the eraser end is +/// in range, and `PEN_FLAG_ERASER` joins it on contact. `PEN_FLAG_ERASER` alone is an eraser +/// *button*, which some pens put on the barrel; pressing that must not switch tools. +pub fn is_eraser_end(pen_flags: Option) -> Option { + pen_flags.map(|pen| (pen & PEN_FLAG_INVERTED) != 0) +} + /// Pure decode of whether the stylus barrel button is pressed. /// /// Plain tip contact sets `POINTER_FLAG_INCONTACT` (`0x0004`) and optionally `POINTER_FLAG_FIRSTBUTTON` @@ -97,6 +158,73 @@ pub fn is_barrel_pressed(pen_flags: Option, pointer_message_flags: u32) -> } } +/// What the hooks track between pointer messages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PenState { + /// The barrel button is pressed. + pub barrel: bool, + /// Which end of the pen is in use (`Some(true)` = eraser), `None` = no pen in range. + pub end: Option, + /// The pointer id of the pen last seen, so another pointer leaving does not forget it. + pub pen_id: Option, + /// The end of the last pen contact, kept when the pen leaves: the contact and its release + /// can still be queued for the UI after the leave is handled, and must get that end's tool. + pub contact: Option, +} + +/// Pure transition of [`PenState`] for one pointer message. `w_param` is the message's (pointer +/// id in the low word, pointer flags in the high word); `pen_flags` reads `GetPointerPenInfo`'s +/// `penFlags` for a pointer id (`None`: not a pen), and only down and update read it. +pub fn next_state(prev: PenState, message: u32, w_param: usize, pen_flags: impl FnOnce(u32) -> Option) -> PenState { + let pointer_id = (w_param & 0xFFFF) as u32; + match message { + // A pen entering range while hovering may stay still: its first update can come late. + WM_POINTERDOWN | WM_POINTERUPDATE | WM_POINTERENTER => { + let pointer_message_flags = ((w_param >> 16) & 0xFFFF) as u32; + let pen_flags = pen_flags(pointer_id); + let end = is_eraser_end(pen_flags); + // A mouse or a finger in between leaves the pen's end as it was. + PenState { + barrel: is_barrel_pressed(pen_flags, pointer_message_flags), + end: end.or(prev.end), + pen_id: if pen_flags.is_some() { Some(pointer_id) } else { prev.pen_id }, + contact: if message == WM_POINTERDOWN { end.or(prev.contact) } else { prev.contact }, + } + } + WM_POINTERUP => PenState { barrel: false, ..prev }, + // A finger or a palm leaving while the pen stays in range (pen and touch screens). + WM_POINTERLEAVE if prev.pen_id.is_some_and(|id| id != pointer_id) => prev, + WM_POINTERLEAVE => PenState { contact: prev.contact, ..PenState::default() }, + _ => prev, + } +} + +/// Apply one pointer message to the state [`is_barrel_button_down`], [`pen_end`] and +/// [`take_pen_end`] read. The hooks call this; tests call it with a fake `pen_flags` reader. +pub fn handle_pointer_message(message: u32, w_param: usize, pen_flags: impl FnOnce(u32) -> Option) { + let prev = PenState { + barrel: BARREL_DOWN.load(Ordering::Relaxed), + end: decode_end(PEN_END.load(Ordering::Relaxed)), + pen_id: Some(PEN_ID.load(Ordering::Relaxed)).filter(|&id| id != NO_PEN), + contact: decode_end(CONTACT_END.load(Ordering::Relaxed)), + }; + let next = next_state(prev, message, w_param, pen_flags); + BARREL_DOWN.store(next.barrel, Ordering::Relaxed); + PEN_END.store(encode_end(next.end), Ordering::Relaxed); + PEN_ID.store(next.pen_id.unwrap_or(NO_PEN), Ordering::Relaxed); + CONTACT_END.store(encode_end(next.contact), Ordering::Relaxed); +} + +fn read_pen_flags(pointer_id: u32) -> Option { + // SAFETY: `info` is a stack-allocated buffer initialized to zero that outlives the call, and + // `pointer_id` comes from a WM_POINTER message; an unknown id makes the call fail, not crash. + unsafe { + let mut info: POINTER_PEN_INFO = std::mem::zeroed(); + (GetPointerPenInfo(pointer_id, &mut info) != 0).then_some(info.pen_flags) + } +} + +/// `WH_GETMESSAGE`: the posted pointer messages, as the UI thread takes them from its queue. unsafe extern "system" fn get_msg_proc(code: i32, w_param: usize, l_param: isize) -> isize { if code >= 0 && l_param != 0 { // SAFETY: Win32 guarantees that for code >= 0, l_param points to a valid MSG struct @@ -105,61 +233,84 @@ unsafe extern "system" fn get_msg_proc(code: i32, w_param: usize, l_param: isize // The WinTab backend shares this thread hook: it decodes the driver's proximity // messages (and ignores everything else) to clear a pen that left the tablet. crate::wintab::on_message(msg.message, msg.w_param, msg.l_param); - match msg.message { - WM_POINTERDOWN | WM_POINTERUPDATE => { - let pointer_id = (msg.w_param & 0xFFFF) as u32; - let pointer_message_flags = (msg.w_param >> 16) as u32; - // SAFETY: `pen_info` is a stack-allocated buffer initialized to zero, and `pointer_id` - // is the pointer identifier from the valid WM_POINTER message. - let pen_flags = unsafe { - let mut info: POINTER_PEN_INFO = std::mem::zeroed(); - (GetPointerPenInfo(pointer_id, &mut info) != 0).then_some(info.pen_flags) - }; - let is_barrel = is_barrel_pressed(pen_flags, pointer_message_flags); - BARREL_DOWN.store(is_barrel, Ordering::Relaxed); - } - WM_POINTERUP | WM_POINTERLEAVE => { - BARREL_DOWN.store(false, Ordering::Relaxed); - } - _ => {} - } + handle_pointer_message(msg.message, msg.w_param, read_pen_flags); } // SAFETY: CallNextHookEx passes the parameters down the hook chain. MSDN notes the first // parameter is ignored and can be null. unsafe { CallNextHookEx(std::ptr::null_mut(), code, w_param, l_param) } } -/// Keeps the thread-local pointer message hook installed; dropping it removes the hook. +/// `WH_CALLWNDPROC`: messages sent to the thread's windows. Only `WM_POINTERENTER` and +/// `WM_POINTERLEAVE` matter here; down, update and up are posted and reach [`get_msg_proc`]. +unsafe extern "system" fn call_wnd_proc(code: i32, w_param: usize, l_param: isize) -> isize { + if code >= 0 && l_param != 0 { + // SAFETY: Win32 guarantees that for code >= 0 (HC_ACTION), l_param points to a valid + // CWPSTRUCT describing the message being sent. + let msg = unsafe { &*(l_param as *const CWPSTRUCT) }; + match msg.message { + WM_POINTERENTER => handle_pointer_message(msg.message, msg.w_param, read_pen_flags), + WM_POINTERLEAVE => handle_pointer_message(msg.message, msg.w_param, |_| None), + _ => {} + } + } + // SAFETY: as in `get_msg_proc`. + unsafe { CallNextHookEx(std::ptr::null_mut(), code, w_param, l_param) } +} + +type HookProc = unsafe extern "system" fn(i32, usize, isize) -> isize; + +/// Keeps the thread-local pointer message hooks installed; dropping it removes them. /// Main-thread only (not `Send`). pub struct Monitor { - hook: *mut std::ffi::c_void, + /// `WH_GETMESSAGE`, then `WH_CALLWNDPROC` (null when it failed to install). + hooks: [*mut std::ffi::c_void; 2], } impl Monitor { - /// Installs the thread-local pointer message hook on the UI thread. + /// Installs the thread-local pointer message hooks on the UI thread. Only a failed + /// `WH_GETMESSAGE` hook is an error: it carries the barrel button and the pen end. Without + /// `WH_CALLWNDPROC` the pen may not be seen leaving (see [`Monitor::tracks_leave`]). pub fn install() -> Result { - // SAFETY: GetCurrentThreadId has no preconditions. SetWindowsHookExW installs - // a thread-specific WH_GETMESSAGE hook on the calling thread's message queue - // using our extern "system" callback. - let hook = unsafe { - let thread_id = GetCurrentThreadId(); - SetWindowsHookExW(WH_GETMESSAGE, get_msg_proc, std::ptr::null_mut(), thread_id) - }; - if hook.is_null() { - return Err(crate::Error::Platform("SetWindowsHookExW returned null".into())); + // SAFETY: GetCurrentThreadId has no preconditions. + let thread_id = unsafe { GetCurrentThreadId() }; + Self::install_with(|id_hook, proc_| { + // SAFETY: installs a thread-specific hook on the calling thread (no module handle + // needed) with one of our extern "system" callbacks. + unsafe { SetWindowsHookExW(id_hook, proc_, std::ptr::null_mut(), thread_id) } + }) + } + + /// [`Monitor::install`] with the hook installer passed in, so tests can fail one hook. + fn install_with(mut set_hook: impl FnMut(i32, HookProc) -> *mut std::ffi::c_void) -> Result { + let get_msg = set_hook(WH_GETMESSAGE, get_msg_proc); + if get_msg.is_null() { + return Err(crate::Error::Platform("SetWindowsHookExW(WH_GETMESSAGE) returned null".into())); } - Ok(Self { hook }) + Ok(Self { hooks: [get_msg, set_hook(WH_CALLWNDPROC, call_wnd_proc)] }) + } + + /// Whether the `WH_CALLWNDPROC` hook installed. Without it the pen leaving range may be + /// missed: the last pen end and barrel state stay until the next pointer message. + pub fn tracks_leave(&self) -> bool { + !self.hooks[1].is_null() } } impl Drop for Monitor { fn drop(&mut self) { - // SAFETY: `self.hook` is the non-null handle returned by `SetWindowsHookExW`, - // unhooked exactly once here on the thread that created it. - unsafe { - UnhookWindowsHookEx(self.hook); + for hook in self.hooks { + if !hook.is_null() { + // SAFETY: `hook` is a non-null handle returned by `SetWindowsHookExW`, unhooked + // exactly once here on the thread that created it. + unsafe { + UnhookWindowsHookEx(hook); + } + } } BARREL_DOWN.store(false, Ordering::Relaxed); + PEN_END.store(encode_end(None), Ordering::Relaxed); + PEN_ID.store(NO_PEN, Ordering::Relaxed); + CONTACT_END.store(encode_end(None), Ordering::Relaxed); } } @@ -168,6 +319,19 @@ pub fn is_barrel_button_down() -> bool { BARREL_DOWN.load(Ordering::Relaxed) } +/// Which end of the pen is in use: `Some(true)` for the eraser end, `Some(false)` for the tip, +/// `None` when no pen is in range of the window. +pub fn pen_end() -> Option { + decode_end(PEN_END.load(Ordering::Relaxed)) +} + +/// [`pen_end`] for the UI's once-per-frame read: the end of a contact not read yet comes first, +/// once, even when the pen has left since, so a click still queued for the UI gets that end's +/// tool. +pub fn take_pen_end() -> Option { + decode_end(CONTACT_END.swap(encode_end(None), Ordering::Relaxed)).or_else(pen_end) +} + #[cfg(test)] mod tests { use super::*; @@ -195,4 +359,129 @@ mod tests { assert!(is_barrel_pressed(Some(0), POINTER_FLAG_SECONDBUTTON)); assert!(is_barrel_pressed(Some(0), POINTER_FLAG_INCONTACT | POINTER_FLAG_SECONDBUTTON)); } + + #[test] + fn eraser_end_is_the_inverted_pen() { + assert_eq!(is_eraser_end(Some(PEN_FLAG_INVERTED)), Some(true), "hovering eraser end"); + assert_eq!(is_eraser_end(Some(PEN_FLAG_INVERTED | PEN_FLAG_ERASER)), Some(true), "eraser end on the tablet"); + assert_eq!(is_eraser_end(Some(PEN_FLAG_ERASER)), Some(false), "an eraser button on the barrel is not the eraser end"); + assert_eq!(is_eraser_end(Some(0)), Some(false), "the tip"); + assert_eq!(is_eraser_end(Some(PEN_FLAG_BARREL)), Some(false), "the barrel button is not the eraser"); + assert_eq!(is_eraser_end(None), None, "not a pen"); + } + + /// `w_param` of a pointer message: pointer id 7 with these pointer flags. + fn wp(flags: u32) -> usize { + 7 | ((flags as usize) << 16) + } + + #[test] + fn pen_state_follows_pointer_messages() { + let pen = |flags: u32| move |id: u32| (id == 7).then_some(flags); + let s = next_state(PenState::default(), WM_POINTERUPDATE, wp(0), pen(0)); + assert_eq!(s, PenState { barrel: false, end: Some(false), pen_id: Some(7), contact: None }, "the tip hovers"); + let s = next_state(s, WM_POINTERUPDATE, wp(0), pen(PEN_FLAG_INVERTED)); + assert_eq!(s.end, Some(true), "the eraser end hovers"); + let s = next_state(s, WM_POINTERDOWN, wp(POINTER_FLAG_INCONTACT), pen(PEN_FLAG_INVERTED | PEN_FLAG_ERASER)); + assert_eq!(s, PenState { barrel: false, end: Some(true), pen_id: Some(7), contact: Some(true) }); + let s = next_state(s, WM_POINTERUPDATE, wp(0), |_| None); + assert_eq!((s.end, s.pen_id), (Some(true), Some(7)), "a mouse in between keeps the pen"); + let s = next_state(s, WM_POINTERUPDATE, wp(0), pen(PEN_FLAG_BARREL)); + assert_eq!(s, PenState { barrel: true, end: Some(false), pen_id: Some(7), contact: Some(true) }, "only a contact sets it"); + let s = next_state(s, WM_POINTERUP, wp(0), |_| panic!("up does not read the pen")); + assert_eq!(s, PenState { barrel: false, end: Some(false), pen_id: Some(7), contact: Some(true) }, "lifting keeps the end"); + let s = next_state(s, WM_POINTERLEAVE, wp(0), |_| panic!("leave does not read the pen")); + assert_eq!(s, PenState { contact: Some(true), ..PenState::default() }, "leaving range forgets the pen, not its contact"); + let mouse_move = 0x0200; + assert_eq!(next_state(s, mouse_move, wp(0), pen(PEN_FLAG_INVERTED)), s, "other messages change nothing"); + } + + #[test] + fn another_pointer_leaving_keeps_the_pen() { + let held = PenState { barrel: true, end: Some(true), pen_id: Some(7), contact: None }; + let finger_leaves = 2 | ((POINTER_FLAG_INCONTACT as usize) << 16); + assert_eq!(next_state(held, WM_POINTERLEAVE, finger_leaves, |_| panic!("leave does not read the pen")), held); + assert_eq!(next_state(held, WM_POINTERLEAVE, wp(0), |_| None), PenState::default(), "the pen itself leaving"); + let unknown = PenState { barrel: true, end: None, pen_id: None, contact: None }; + assert_eq!(next_state(unknown, WM_POINTERLEAVE, finger_leaves, |_| None), PenState::default(), "no pen seen yet"); + } + + /// A pen entering range with its eraser end is known before it moves (`WM_POINTERENTER` can + /// come well before the first hover update). + #[test] + fn entering_range_reads_the_pen_end() { + let s = next_state(PenState::default(), WM_POINTERENTER, wp(0), |id| (id == 7).then_some(PEN_FLAG_INVERTED)); + assert_eq!(s, PenState { barrel: false, end: Some(true), pen_id: Some(7), contact: None }); + let s = next_state(s, WM_POINTERENTER, 9, |_| None); + assert_eq!((s.end, s.pen_id), (Some(true), Some(7)), "a mouse or finger entering keeps the pen"); + } + + /// Serialises the tests that touch the global state the hooks write (tests run in parallel). + static GLOBALS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn handled_messages_reach_the_readers() { + let _globals = GLOBALS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + handle_pointer_message(WM_POINTERUPDATE, wp(0), |_| Some(PEN_FLAG_INVERTED | PEN_FLAG_BARREL)); + assert_eq!((pen_end(), is_barrel_button_down()), (Some(true), true)); + handle_pointer_message(WM_POINTERUP, wp(0), |_| None); + assert_eq!((pen_end(), is_barrel_button_down()), (Some(true), false)); + handle_pointer_message(WM_POINTERUPDATE, wp(0), |_| Some(0)); + assert_eq!(pen_end(), Some(false)); + handle_pointer_message(WM_POINTERLEAVE, 2, |_| None); + assert_eq!(pen_end(), Some(false), "a finger leaving keeps the pen"); + handle_pointer_message(WM_POINTERLEAVE, wp(0), |_| None); + assert_eq!((pen_end(), is_barrel_button_down()), (None, false)); + assert_eq!(take_pen_end(), None, "no contact to report"); + } + + /// An eraser-end tap and the pen leaving range, all handled before the UI's next frame: the + /// frame still reads the eraser end once, so the queued click erases. + #[test] + fn a_contact_queued_past_the_leave_keeps_its_end() { + let _globals = GLOBALS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + handle_pointer_message(WM_POINTERLEAVE, wp(0), |_| None); + let _ = take_pen_end(); + handle_pointer_message(WM_POINTERDOWN, wp(POINTER_FLAG_INCONTACT), |_| Some(PEN_FLAG_INVERTED | PEN_FLAG_ERASER)); + handle_pointer_message(WM_POINTERUP, wp(0), |_| None); + handle_pointer_message(WM_POINTERLEAVE, wp(0), |_| None); + assert_eq!(pen_end(), None, "the pen is out of range"); + assert_eq!(take_pen_end(), Some(true), "the queued contact was the eraser end"); + assert_eq!(take_pen_end(), None, "reported once"); + handle_pointer_message(WM_POINTERDOWN, wp(POINTER_FLAG_INCONTACT), |_| Some(PEN_FLAG_INVERTED)); + handle_pointer_message(WM_POINTERUP, wp(0), |_| None); + handle_pointer_message(WM_POINTERUPDATE, wp(0), |_| Some(0)); + assert_eq!(take_pen_end(), Some(true), "the unread contact comes before the tip hovering since"); + assert_eq!(take_pen_end(), Some(false), "then the end in range"); + handle_pointer_message(WM_POINTERLEAVE, wp(0), |_| None); + } + + #[test] + fn a_failed_leave_hook_keeps_the_message_hook() { + let _globals = GLOBALS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut installed = Vec::new(); + let monitor = Monitor::install_with(|id_hook, proc_| { + installed.push(id_hook); + if id_hook == WH_CALLWNDPROC { + return std::ptr::null_mut(); + } + // SAFETY: a real thread-specific hook on this test thread; the monitor unhooks it. + unsafe { SetWindowsHookExW(id_hook, proc_, std::ptr::null_mut(), GetCurrentThreadId()) } + }) + .expect("the message hook alone is enough"); + assert_eq!(installed, [WH_GETMESSAGE, WH_CALLWNDPROC]); + assert!(!monitor.hooks[0].is_null()); + assert!(!monitor.tracks_leave()); + } + + #[test] + fn a_failed_message_hook_is_an_error() { + let mut installed = Vec::new(); + let r = Monitor::install_with(|id_hook, _| { + installed.push(id_hook); + std::ptr::null_mut() + }); + assert!(matches!(r, Err(crate::Error::Platform(why)) if why.contains("WH_GETMESSAGE"))); + assert_eq!(installed, [WH_GETMESSAGE], "no leave hook without the message hook"); + } } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0a77bbdf3b..24a6300d04 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -78,6 +78,7 @@ impl PhotocraftApp { last_stroke_end: None, brush_resize: None, quick_pick: false, + move_pick: None, brush_resize_armed: false, alt_sampling: false, mixer_sampling: false, @@ -126,6 +127,7 @@ impl PhotocraftApp { color_range: None, adjust_preview: None, live_adjust_preview: None, + levels_clipping: None, synthetic: Vec::new(), synthetic_batch: None, synthetic_reinject: false, diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 6babd70eb0..ab3654e4ce 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -331,6 +331,7 @@ impl PhotocraftApp { type_transform::cancel_stale(self); crate::cam_transform::cancel_stale(self); crate::lasso_ui::cancel_stale(self); + crate::retouch_ui::cancel_stale(self); // A polygon under construction belongs to the Polygonal Lasso tool, not the next tool. if self.ui.tool != Tool::PolygonLasso { self.ui.polygon.clear(); @@ -378,6 +379,10 @@ impl PhotocraftApp { let docs = self.session.documents(); self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); } + // With no document left, no canvas paints the Levels clipping display to drop its cache. + if self.session.documents().is_empty() { + self.levels_clipping = None; + } // Commands may close and reopen a preserved-ID document before the next repaint. canvas::retain_gpu_documents(self); } diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index 36cf9834f0..1af1f0b9ec 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -203,6 +203,15 @@ impl PhotocraftApp { b } + /// [`Self::cached_bounds`] where only a shared borrow is at hand: the cached box if `surface` + /// hasn't changed since, else a scan (not cached). + pub fn known_bounds(&self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { + match self.bounds_cache.get(&key) { + Some((r, b)) if *r == surface_fingerprint(surface) => *b, + _ => surface.content_bounds(), + } + } + /// The box Properties › Transform shows for `layer` (X, Y, W, H): its pixels' bounds, but a /// soft shape's path and stroke, whose Density and Feather render past them (#5846), as its /// transform frame does. diff --git a/crates/ui-egui/src/artboard_add_mode_tests.rs b/crates/ui-egui/src/artboard_add_mode_tests.rs index 3b98287d41..04344298c0 100644 --- a/crates/ui-egui/src/artboard_add_mode_tests.rs +++ b/crates/ui-egui/src/artboard_add_mode_tests.rs @@ -85,14 +85,15 @@ fn a_click_with_the_mode_off_still_places_nothing() { } #[test] -fn with_no_board_the_click_uses_the_canvas_size() { +fn with_no_board_the_click_uses_the_bars_tool_option_size() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); app.sync_views(); app.ui.tool = Tool::Artboard; app.ui.artboard_tool.adding = true; click(&mut app, 40.0, 50.0); - assert_eq!(boards(&app), vec![Rect::new(40, 50, 840, 650)]); + // The size the bar shows (the iPhone 8/7/6 default), not the canvas's 800 x 600. + assert_eq!(boards(&app), vec![Rect::new(40, 50, 790, 1384)]); } #[test] diff --git a/crates/ui-egui/src/artboard_options_bar_tests.rs b/crates/ui-egui/src/artboard_options_bar_tests.rs new file mode 100644 index 0000000000..dd7375e4e3 --- /dev/null +++ b/crates/ui-egui/src/artboard_options_bar_tests.rs @@ -0,0 +1,538 @@ +//! The Artboard tool's options bar (#11385): the iPhone 8/7/6 default size, the background for the +//! boards it draws, the Align panel and the gear menu, and what Reset Tool puts back. + +use egui::Modifiers; +use photocraft_doc::{ArtboardBackground, LayerId}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::artboard_tool::ArtboardToolUi; +use crate::artboard_tool::bar::{self, ALIGN_PANEL, GEAR, Gear}; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app_with_depth(depth: u32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 600, "depth": depth})).unwrap(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + app.ui.tool = Tool::Artboard; + app +} + +fn app() -> PhotocraftApp { + app_with_depth(8) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let m = Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +fn boards(app: &PhotocraftApp) -> Vec<(LayerId, Rect, ArtboardBackground)> { + app.session.active().unwrap().doc.artboards().iter().map(|b| (b.0, b.2.rect, b.2.background)).collect() +} + +fn reset_tool(app: &mut PhotocraftApp) { + crate::menus::invoke(app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap(); +} + +#[test] +fn the_presets_list_has_iphone_8_7_6() { + assert!(photocraft_engine::artboard_cmds::PRESETS.contains(&("iPhone 8/7/6", 750, 1334))); + assert!(photocraft_engine::artboard_cmds::PRESETS.contains(&("iPhone 14", 390, 844)), "the existing entries stay"); + // The engine takes the new preset by name. + let mut app = app(); + let r = app.run("layer.new.artboard", json!({"preset": "iPhone 8/7/6", "x": 0, "y": 0})).unwrap(); + assert_eq!(r["rect"], json!([0, 0, 750, 1334])); +} + +#[test] +fn a_fresh_bar_has_the_measured_defaults() { + let app = app(); + let o = &app.ui.artboard_tool; + assert_eq!((o.preset.as_str(), o.width, o.height), ("iPhone 8/7/6", 750, 1334)); + assert_eq!((o.background.as_str(), o.background_color.as_str()), ("white", "#ffffff")); + assert!(GEAR.iter().all(|(g, _)| g.checked(o)), "all four gear entries are checked"); + assert_eq!(bar::DEFAULT_SIZE, ("iPhone 8/7/6", 750, 1334)); +} + +#[test] +fn reset_tool_restores_the_options_and_only_for_the_artboard_tool() { + let mut app = app(); + bar::set_size(&mut app, 200.0, 300.0); + bar::set_custom_background(&mut app, "#336699").unwrap(); + app.ui.artboard_tool.auto_nest = false; + app.ui.artboard_tool.shrinkwrap_on_save = false; + // Another tool's Reset Tool leaves them. + app.ui.tool = Tool::Move; + reset_tool(&mut app); + assert_eq!(app.ui.artboard_tool.width, 200); + // The Artboard tool's puts every one back. + app.ui.tool = Tool::Artboard; + reset_tool(&mut app); + assert_eq!(app.ui.artboard_tool, ArtboardToolUi::default()); + assert_eq!(app.ui.artboard_tool.height, 1334); + // Reset All Tools too. + bar::set_preset(&mut app, "A4"); + app.ui.artboard_tool.auto_size_canvas = false; + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET_ALL, json!({"confirmed": true})).unwrap(); + assert_eq!(app.ui.artboard_tool, ArtboardToolUi::default()); +} + +#[test] +fn the_options_are_serde_tool_options() { + let mut app = app(); + bar::set_preset(&mut app, "Letter"); + app.ui.artboard_tool.keep_relative_position = false; + let v = serde_json::to_value(&app.ui.artboard_tool).unwrap(); + assert_eq!(v["preset"], "Letter"); + assert_eq!((v["width"].as_u64(), v["height"].as_u64()), (Some(612), Some(792))); + assert_eq!(v["keep_relative_position"], false); + assert_eq!(v["auto_nest"], true); + assert!(v.get("drag").is_none(), "the drag in progress is not saved"); + let back: ArtboardToolUi = serde_json::from_value(v).unwrap(); + assert_eq!(back, app.ui.artboard_tool); + // Settings saved before these options existed load with the defaults. + let old: ArtboardToolUi = serde_json::from_value(json!({})).unwrap(); + assert_eq!(old, ArtboardToolUi::default()); + // The whole UI state carries them, so `ui.inspect` reaches them. + let ui = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(ui["artboard_tool"]["preset"], "Letter"); +} + +#[test] +fn width_and_height_edit_the_tool_option_when_no_board_is_selected() { + let mut app = app(); + assert!(boards(&app).is_empty()); + assert_eq!(bar::bar_size(&app), [750, 1334]); + bar::set_size(&mut app, 400.0, 500.0); + assert_eq!((app.ui.artboard_tool.width, app.ui.artboard_tool.height), (400, 500)); + assert_eq!(app.ui.artboard_tool.preset, "", "a size that is no preset's reads Custom"); + assert_eq!(bar::bar_size(&app), [400, 500]); + // Back to a preset's size: the preset reads again only when chosen; choosing it sets the size. + bar::set_preset(&mut app, "iPhone 14"); + assert_eq!((app.ui.artboard_tool.width, app.ui.artboard_tool.height), (390, 844)); + assert_eq!(app.ui.artboard_tool.preset, "iPhone 14"); + // Out of range and not a number are held to 1..=300000. + bar::set_size(&mut app, 0.0, 1.0e9); + assert_eq!((app.ui.artboard_tool.width, app.ui.artboard_tool.height), (1, 300_000)); + bar::set_size(&mut app, f32::NAN, 5.0); + assert_eq!(app.ui.artboard_tool.width, 1); + // No document change. + assert_eq!(app.session.active().unwrap().doc.size.width, 800); + assert!(boards(&app).is_empty()); + assert!(!app.session.active().unwrap().history.entries().iter().any(|e| e.contains("Artboard"))); +} + +#[test] +fn with_a_board_selected_the_bar_size_is_the_boards_and_the_options_stay() { + let mut app = app(); + bar::set_size(&mut app, 400.0, 500.0); + drag(&mut app, [100.0, 100.0], [300.0, 300.0]); + assert_eq!(boards(&app).first().map(|b| b.1), Some(Rect::new(100, 100, 300, 300))); + // A 200 x 200 board reads 200 x 200 (Custom), not the options. + assert_eq!(bar::bar_size(&app), [200, 200]); + let id = boards(&app)[0].0; + let preset = app.session.active().unwrap().doc.layer(id).unwrap().artboard().unwrap().preset.clone(); + assert_eq!(preset, "", "Custom"); + assert_eq!((app.ui.artboard_tool.width, app.ui.artboard_tool.height), (400, 500), "the tool option is untouched"); + // Choosing iPhone 8/7/6 resizes the board in one step and keeps its top-left corner. + let steps = app.session.active().unwrap().history.entries().len(); + app.run("layer.artboard.set", json!({"layer": id.0, "preset": "iPhone 8/7/6"})).unwrap(); + assert_eq!(boards(&app)[0].1, Rect::new(100, 100, 850, 1434)); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 1); + assert_eq!(bar::bar_size(&app), [750, 1334]); +} + +#[test] +fn bar_size_helper_prefers_the_selected_board() { + let mut app = app(); + assert_eq!(bar::bar_size(&app), [750, 1334]); + app.run("layer.new.artboard", json!({"rect": [0, 0, 120, 90]})).unwrap(); + assert_eq!(bar::bar_size(&app), [120, 90]); +} + +/// The background reaches `layer.new.artboard` for a board the tool draws, at 8 and 16 bit. +#[test] +fn a_drawn_board_gets_the_bars_background() { + for depth in [8, 16] { + for (name, want) in [("white", ArtboardBackground::White), ("black", ArtboardBackground::Black), ("transparent", ArtboardBackground::Transparent)] { + let mut app = app_with_depth(depth); + app.ui.artboard_tool.background = name.to_string(); + drag(&mut app, [50.0, 50.0], [150.0, 120.0]); + assert!(!app.ui.status_error, "{depth} bit {name}: {}", app.ui.status); + let b = boards(&app); + assert_eq!(b.len(), 1, "{depth} bit {name}"); + assert_eq!((b[0].1, b[0].2), (Rect::new(50, 50, 150, 120), want), "{depth} bit {name}"); + } + // Other…: the picked colour. + let mut app = app_with_depth(depth); + bar::set_custom_background(&mut app, "#ff0000").unwrap(); + drag(&mut app, [50.0, 50.0], [150.0, 120.0]); + let ArtboardBackground::Custom(c) = boards(&app)[0].2 else { panic!("{depth} bit: a custom background") }; + assert_eq!(c.to_rgba8(), [255, 0, 0, 255], "{depth} bit"); + } +} + +/// A board placed by the Add New Artboard click takes the bar's background too. +#[test] +fn a_placed_board_gets_the_bars_background() { + let place = |app: &mut PhotocraftApp| { + app.ui.artboard_tool.adding = true; + let m = Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 20.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + }; + let mut app = self::app(); + place(&mut app); + assert_eq!(boards(&app).len(), 1); + assert_eq!(boards(&app)[0].2, ArtboardBackground::White, "the default setting keeps white"); + let mut app = self::app(); + app.ui.artboard_tool.background = "transparent".to_string(); + place(&mut app); + assert_eq!(boards(&app)[0].2, ArtboardBackground::Transparent); + let mut app = self::app(); + bar::set_custom_background(&mut app, "#00ff00").unwrap(); + place(&mut app); + let ArtboardBackground::Custom(c) = boards(&app)[0].2 else { panic!("a custom background") }; + assert_eq!(c.to_rgba8(), [0, 255, 0, 255]); +} + +/// With no board selected, a placed board takes the size the bar shows (the tool option), not the canvas's. +#[test] +fn a_placed_board_takes_the_bars_size_with_no_board_selected() { + let mut app = app(); + assert!(boards(&app).is_empty()); + bar::set_size(&mut app, 333.0, 222.0); + app.ui.artboard_tool.adding = true; + let m = Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(boards(&app).first().map(|b| b.1), Some(Rect::new(20, 30, 353, 252))); +} + +/// A placed board keeps the bar's preset name, so selected it shows that preset, not Custom. +#[test] +fn a_placed_board_keeps_the_bars_preset_name() { + let mut app = app(); + let place = |app: &mut PhotocraftApp, x: f64| { + app.ui.artboard_tool.adding = true; + let m = Modifiers::NONE; + tool_event(app, ToolEvent::Down { x, y: 30.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x, y: 30.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (id, rect, _) = *boards(app).last().unwrap(); + app.run("layer.select", json!({"layer": id.0})).unwrap(); + (id, rect) + }; + let (id, rect) = place(&mut app, 20.0); + assert_eq!((rect.width(), rect.height()), (750, 1334)); + assert_eq!(bar::board_preset(&app, id), "iPhone 8/7/6"); + let stored = app.session.active().unwrap().doc.layer(id).unwrap().artboard().unwrap().preset.clone(); + assert_eq!(stored, "iPhone 8/7/6"); + // Deselect, edit the size by hand: the preset is Custom and so is the next placed board. + app.session.active_mut().unwrap().active_layer = None; + bar::set_size(&mut app, 333.0, 222.0); + let (id2, rect2) = place(&mut app, 2000.0); + assert_eq!((rect2.width(), rect2.height()), (333, 222)); + assert_eq!(bar::board_preset(&app, id2), ""); +} + +/// OK in the picker with the colour the swatch shows leaves the board's own colour alone. +#[test] +fn ok_in_the_picker_without_a_change_leaves_the_boards_alone() { + let mut app = app(); + let a = app.run("layer.new.artboard", json!({"rect": [0, 0, 100, 100]})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.artboard.set", json!({"layer": a, "background": "custom", "color": [0.2, 0.4, 0.6, 0.5]})).unwrap(); + app.run("layer.select", json!({"layer": a})).unwrap(); + let before = (steps(&app), boards(&app)[0].2); + let hex = bar::shown_background(&app).1; + let id = crate::color_picker_ui::open_for_target(&mut app, "artboardBackground", "Color Picker (Color)", crate::color_picker_ui::parse_hex(&hex).unwrap()); + let fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + crate::color_picker_ui::confirm(&mut app, &fields).unwrap(); + assert_eq!((steps(&app), boards(&app)[0].2), before, "no history step, colour bit-exact"); + // A real change still recolours. + bar::set_custom_background(&mut app, "#00ff00").unwrap(); + assert_eq!(steps(&app), before.0 + 1); + assert_ne!(boards(&app)[0].2, before.1); +} + +/// Two boards, both selected. +fn two_boards(app: &mut PhotocraftApp) -> (u64, u64) { + let a = app.run("layer.new.artboard", json!({"rect": [0, 0, 100, 100]})).unwrap()["layer"].as_u64().unwrap(); + let b = app.run("layer.new.artboard", json!({"rect": [300, 0, 100, 100]})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": a})).unwrap(); + app.run("layer.select", json!({"layer": b, "mode": "add"})).unwrap(); + (a, b) +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn last_label(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.entries().last().cloned() +} + +/// Two selected boards with different custom colours; the first board's colour is the swatch's. +fn two_coloured_boards(app: &mut PhotocraftApp) -> (u64, u64) { + let (a, b) = two_boards(app); + app.run("layer.artboard.set", json!({"layer": a, "background": "custom", "color": "#336699"})).unwrap(); + app.run("layer.artboard.set", json!({"layer": b, "background": "custom", "color": "#cc3300"})).unwrap(); + (a, b) +} + +/// Open the Color Picker from the swatch (as the bar does) and OK it with `color`, or as opened. +fn pick_from_swatch(app: &mut PhotocraftApp, color: Option<&str>) { + let hex = bar::shown_background(app).1; + let id = crate::color_picker_ui::open_for_target(app, "artboardBackground", "Color Picker (Color)", crate::color_picker_ui::parse_hex(&hex).unwrap()); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + if let Some(c) = color { + fields.insert("color".into(), json!(c)); + } + crate::color_picker_ui::confirm(app, &fields).unwrap(); +} + +fn colours(app: &PhotocraftApp) -> Vec { + boards(app).iter().map(|b| b.2).collect() +} + +#[test] +fn an_unchanged_ok_with_boards_of_different_colours_leaves_every_board_alone() { + let mut app = app(); + two_coloured_boards(&mut app); + let before = (steps(&app), colours(&app)); + pick_from_swatch(&mut app, None); + assert_eq!((steps(&app), colours(&app)), before, "no history step, both colours bit-exact"); + assert_eq!((app.ui.artboard_tool.background.as_str(), app.ui.artboard_tool.background_color.as_str()), ("custom", "#336699")); +} + +#[test] +fn a_changed_ok_with_boards_of_different_colours_recolours_both_in_one_step() { + let mut app = app(); + two_coloured_boards(&mut app); + let steps0 = steps(&app); + pick_from_swatch(&mut app, Some("#00ff00")); + assert_eq!(steps(&app), steps0 + 1); + assert_eq!(last_label(&app).as_deref(), Some("Edit Artboards")); + let green = |c: &ArtboardBackground| matches!(c, ArtboardBackground::Custom(c) if c.to_rgba8()[..3] == [0, 255, 0]); + assert!(colours(&app).iter().all(green)); +} + +#[test] +fn an_unchanged_ok_with_only_web_colors_leaves_the_boards_alone() { + let mut app = app(); + app.ui.color_panel.web_only = true; + let (a, _) = two_boards(&mut app); + app.run("layer.artboard.set", json!({"layer": a, "background": "custom", "color": [0.2, 0.4, 0.61, 1.0]})).unwrap(); + let before = (steps(&app), colours(&app)); + pick_from_swatch(&mut app, None); + assert_eq!((steps(&app), colours(&app)), before, "no history step, colours bit-exact"); +} + +#[test] +fn a_colour_some_boards_already_have_recolours_only_the_others() { + let mut app = app(); + let (_, b) = two_coloured_boards(&mut app); + let b_before = colours(&app)[1]; + let steps0 = steps(&app); + pick_from_swatch(&mut app, Some("#cc3300")); + assert_eq!(steps(&app), steps0 + 1); + assert_eq!(last_label(&app).as_deref(), Some("Edit Artboard"), "the label follows the one board that changed"); + assert_eq!(colours(&app)[1], b_before, "board {b} keeps its own value"); + assert!(matches!(colours(&app)[0], ArtboardBackground::Custom(c) if c.to_rgba8()[..3] == [0xcc, 0x33, 0x00])); +} + +#[test] +fn with_a_board_selected_the_bar_shows_its_background() { + let mut app = app(); + let a = app.run("layer.new.artboard", json!({"rect": [0, 0, 100, 100]})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.artboard.set", json!({"layer": a, "background": "black"})).unwrap(); + app.run("layer.select", json!({"layer": a})).unwrap(); + assert_eq!(app.ui.artboard_tool.background, "white", "the tool option is still white"); + assert_eq!(bar::shown_background(&app).0, "black"); + app.run("layer.artboard.set", json!({"layer": a, "background": "custom", "color": "#336699"})).unwrap(); + assert_eq!(bar::shown_background(&app), ("custom".to_string(), "#336699".to_string())); +} + +#[test] +fn a_background_choice_recolours_every_selected_board_in_one_step() { + let mut app = app(); + let (a, b) = two_boards(&mut app); + let before = steps(&app); + bar::set_background(&mut app, "transparent", "#ffffff").unwrap(); + assert_eq!(steps(&app), before + 1); + assert_eq!(last_label(&app).as_deref(), Some("Edit Artboards")); + assert!(boards(&app).iter().all(|x| x.2 == ArtboardBackground::Transparent)); + assert_eq!(boards(&app).iter().map(|x| x.0.0).collect::>(), vec![a, b]); + assert_eq!(app.ui.artboard_tool.background, "transparent", "also the next drawn board's"); + // Other...: OK in the picker recolours them too. + bar::set_custom_background(&mut app, "#00ff00").unwrap(); + assert_eq!(steps(&app), before + 2); + for x in boards(&app) { + let ArtboardBackground::Custom(c) = x.2 else { panic!("a custom background") }; + assert_eq!(c.to_rgba8(), [0, 255, 0, 255]); + } + assert_eq!((app.ui.artboard_tool.background.as_str(), app.ui.artboard_tool.background_color.as_str()), ("custom", "#00ff00")); +} + +#[test] +fn one_selected_board_is_edit_artboard() { + let mut app = app(); + let a = app.run("layer.new.artboard", json!({"rect": [0, 0, 100, 100]})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": a})).unwrap(); + let before = steps(&app); + bar::set_background(&mut app, "black", "#ffffff").unwrap(); + assert_eq!(steps(&app), before + 1); + assert_eq!(last_label(&app).as_deref(), Some("Edit Artboard")); + assert_eq!(boards(&app)[0].2, ArtboardBackground::Black); +} + +#[test] +fn with_no_board_selected_the_background_edits_only_the_tool_option() { + let mut app = app(); + let before = steps(&app); + bar::set_background(&mut app, "black", "#ffffff").unwrap(); + assert_eq!(app.ui.artboard_tool.background, "black"); + assert_eq!(steps(&app), before, "no history step"); + assert!(boards(&app).is_empty()); +} + +#[test] +fn the_background_param_carries_color_only_for_other() { + let mut app = app(); + assert_eq!(bar::with_background(&app, json!({"rect": [0, 0, 5, 5]})), json!({"rect": [0, 0, 5, 5], "background": "white"})); + bar::set_custom_background(&mut app, "#00ff00").unwrap(); + assert_eq!(bar::with_background(&app, json!({})), json!({"background": "custom", "color": "#00ff00"})); + assert!(bar::set_custom_background(&mut app, "green").is_err()); + assert_eq!(app.ui.artboard_tool.background_color, "#00ff00", "a bad colour changes nothing"); +} + +#[test] +fn other_opens_the_color_picker_and_ok_sets_the_option() { + let mut app = app(); + app.ui.artboard_tool.background = "black".to_string(); + // What the dropdown's Other… and the swatch do. + app.ui.artboard_tool.background_color = "#123456".to_string(); + let before = app.ui.dialogs.len(); + let rgb = crate::color_picker_ui::parse_hex("#123456").unwrap(); + let id = crate::color_picker_ui::open_for_target(&mut app, "artboardBackground", "Color Picker (Color)", rgb); + assert_eq!(app.ui.dialogs.len(), before + 1); + // Cancel leaves the option alone; OK sets it. + assert_eq!(app.ui.artboard_tool.background, "black"); + let fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + crate::color_picker_ui::confirm(&mut app, &fields).unwrap(); + assert_eq!((app.ui.artboard_tool.background.as_str(), app.ui.artboard_tool.background_color.as_str()), ("custom", "#123456")); +} + +#[test] +fn the_align_panel_has_the_eight_entries_in_the_measured_order() { + let labels: Vec> = ALIGN_PANEL.iter().map(|g| g.iter().map(|e| e.0).collect()).collect(); + assert_eq!( + labels, + vec![ + vec!["Left Edges", "Horizontal Centers", "Right Edges"], + vec!["Top Edges", "Vertical Centers", "Bottom Edges"], + vec!["Distribute Widths", "Distribute Heights"], + ] + ); + let specs = photocraft_engine::command_specs(); + for (label, cmd) in ALIGN_PANEL.iter().flat_map(|g| g.iter()) { + match cmd { + Some(c) => { + assert!(specs.iter().any(|s| s.id == *c), "{c} is a command"); + assert!(crate::align_bar::ALIGN.iter().any(|a| a.0 == *c && a.2 == *label), "{label} is the Move tool's"); + } + None => assert!(label.starts_with("Distribute"), "{label} has no command yet"), + } + } + // Distribute Widths and Heights run nothing. + assert!(bar::run_align(&mut app(), 2, 0).is_none()); + assert!(bar::run_align(&mut app(), 2, 1).is_none()); +} + +/// A filled square at `r` (`x, y, w, h`); the engine aligns a board by its contents. +fn square(app: &mut PhotocraftApp, r: [i64; 4]) -> u64 { + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": r[0], "y": r[1], "width": r[2], "height": r[3]})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.session.active().unwrap().active_layer.unwrap().0 +} + +fn wrap(app: &mut PhotocraftApp, layer: u64) -> u64 { + app.run("layer.select", json!({"layer": layer})).unwrap(); + app.run("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap() +} + +#[test] +fn an_align_entry_moves_two_selected_boards_in_one_step() { + let mut app = app(); + let (sa, sb) = (square(&mut app, [40, 10, 100, 100]), square(&mut app, [300, 200, 80, 100])); + let (a, b) = (wrap(&mut app, sa), wrap(&mut app, sb)); + app.run("layer.select", json!({"layer": a})).unwrap(); + app.run("layer.select", json!({"layer": b, "mode": "add"})).unwrap(); + assert!(app.session.is_enabled("layer.align.leftEdges")); + let before: Vec = boards(&app).iter().map(|b| b.1).collect(); + assert_eq!(before.len(), 2); + let steps = app.session.active().unwrap().history.entries().len(); + let r = bar::run_align(&mut app, 0, 0); + assert!(matches!(r, Some(Ok(_))), "{r:?}"); + let after: Vec = boards(&app).iter().map(|b| b.1).collect(); + // Left Edges: the second board (with its contents) moves left to the first one's edge. + assert_eq!(after[0], before[0]); + assert_eq!((after[1].x0, after[1].y0), (before[0].x0, before[1].y0)); + assert_eq!((after[1].width(), after[1].height()), (before[1].width(), before[1].height())); + assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 1, "one history step"); + // Top Edges (second group, first entry) moves it up to the first board's top. + assert!(matches!(bar::run_align(&mut app, 1, 0), Some(Ok(_)))); + let after: Vec = boards(&app).iter().map(|b| b.1).collect(); + assert_eq!((after[1].x0, after[1].y0), (before[0].x0, before[0].y0)); +} + +#[test] +fn the_gear_menu_has_four_entries_all_checked_and_only_auto_nest_live() { + let labels: Vec<&str> = GEAR.iter().map(|g| g.1).collect(); + assert_eq!(labels, vec!["Auto-nest Layers", "Auto-size Canvas", "Keep Relative Position During Layer Reordering", "Shrinkwrap Canvas on Save"]); + let live: Vec = GEAR.iter().map(|g| g.0).filter(|g| g.enabled()).collect(); + assert_eq!(live, vec![Gear::AutoNest]); + let mut o = ArtboardToolUi::default(); + for (g, _) in GEAR { + assert!(g.checked(&o)); + } + o.auto_nest = false; + o.shrinkwrap_on_save = false; + let checked: Vec = GEAR.iter().map(|g| g.0.checked(&o)).collect(); + assert_eq!(checked, vec![false, true, true, false]); +} + +/// Auto-nest Layers off: a layer dragged with the Move tool onto another board stays where it was. +#[test] +fn auto_nest_layers_turns_the_move_tools_nesting_on_and_off() { + for (nest, joins) in [(true, true), (false, false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 300, "height": 100, "background": "transparent"})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + let red = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.artboardFromLayers", json!({"name": "A"})).unwrap(); + app.session.execute("layer.artboard.set", json!({"width": 40, "height": 40})).unwrap(); + let b = LayerId(app.session.execute("layer.new.artboard", json!({"rect": [200, 20, 40, 40], "name": "B"})).unwrap()["layer"].as_u64().unwrap()); + app.session.execute("layer.select", json!({"layer": red.0})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.artboard_tool.auto_nest = nest; + crate::canvas::move_ui::finish(&mut app, 190.0, 10.0); + let board = app.session.active().unwrap().doc.artboard_of(red); + assert_eq!(board == Some(b), joins, "auto_nest {nest}"); + } +} diff --git a/crates/ui-egui/src/brush_options_tooltips_tests.rs b/crates/ui-egui/src/brush_options_tooltips_tests.rs new file mode 100644 index 0000000000..b3372d06b0 --- /dev/null +++ b/crates/ui-egui/src/brush_options_tooltips_tests.rs @@ -0,0 +1,114 @@ +//! #11813: the Brush options-bar controls carry the reference application's tooltips (also their +//! accessible descriptions), the Eraser keeps today's texts, and the smoothing options popup has +//! a "Smoothing Options" title. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; +use crate::theme::ThemeKind; + +fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> { + bar_in(tool, ThemeKind::ProMedium) +} + +fn bar_in(tool: Tool, theme: ThemeKind) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, theme); + h.run_steps(4); + h +} + +/// The descriptions of the widgets labelled `label`, or, for the controls a caption names (Mode +/// and the fields), of every control of that kind. +fn descriptions(h: &Harness<'static, PhotocraftApp>, label: &str) -> Vec { + let of = |n: egui_kittest::Node<'_>| n.accesskit_node().description().map(|d| d.to_string()); + if label == "Mode" { + return h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(of).collect(); + } + // The fields too are named by the caption before them. + if ["Opacity", "Flow", "Smoothing"].contains(&label) { + return h.query_all_by_role(egui::accesskit::Role::SpinButton).filter_map(of).collect(); + } + // The non-Pro pressure switches are unnamed nodes: every description in the bar. + if label.starts_with("Pressure for") { + return h.query_all(by().predicate(|n| n.description().is_some())).filter_map(of).collect(); + } + h.query_all_by_label(label).filter_map(of).collect() +} + +const BRUSH: [(&str, &str); 8] = [ + ("Brush Preset picker", "Click to open the Brush Preset picker"), + ("Mode", "Painting Mode"), + ("Opacity", "Set opacity for stroke"), + ("Always use pressure for opacity", "Always use Pressure for Opacity. When off, Brush Preset controls pressure"), + ("Flow", "Set flow rate for stroke"), + ("Smoothing", "Set smoothing for stroke\nUse higher values to reduce the shakiness of brush strokes"), + ("Always use pressure for size", "Always use Pressure for Size. When off, Brush Preset controls pressure"), + ("Set painting symmetry options", "Set symmetry options for Painting"), +]; + +#[test] +fn the_brush_controls_have_the_reference_tooltips() { + let h = bar(Tool::Brush); + for (label, tip) in BRUSH { + let found = descriptions(&h, label); + assert!(found.iter().any(|d| d == tip), "{label}: {found:?}"); + } +} + +#[test] +fn the_eraser_keeps_its_texts() { + let h = bar(Tool::Eraser); + for (label, tip) in BRUSH { + assert!(!descriptions(&h, label).iter().any(|d| d == tip), "{label} changed on the Eraser"); + } +} + +/// The non-Pro themes' Brush bar: the same texts where it has the same controls (its pressure +/// switches are named "Pressure for Size" and "Pressure for Opacity"). +const BRUSH_CLASSIC: [(&str, &str); 6] = [ + ("Mode", "Painting Mode"), + ("Opacity", "Set opacity for stroke"), + ("Flow", "Set flow rate for stroke"), + ("Smoothing", "Set smoothing for stroke\nUse higher values to reduce the shakiness of brush strokes"), + ("Pressure for Size", "Always use Pressure for Size. When off, Brush Preset controls pressure"), + ("Pressure for Opacity", "Always use Pressure for Opacity. When off, Brush Preset controls pressure"), +]; + +#[test] +fn the_brush_has_the_reference_tooltips_in_other_themes_too() { + let h = bar_in(Tool::Brush, ThemeKind::Classic); + for (label, tip) in BRUSH_CLASSIC { + let found = descriptions(&h, label); + assert!(found.iter().any(|d| d == tip), "{label}: {found:?}"); + } + let h = bar_in(Tool::Eraser, ThemeKind::Classic); + for (label, tip) in BRUSH_CLASSIC { + assert!(!descriptions(&h, label).iter().any(|d| d == tip), "{label} changed on the Eraser"); + } +} + +#[test] +fn the_erasers_smoothing_popup_keeps_no_title() { + let mut h = bar(Tool::Eraser); + h.get_by_label("Set additional smoothing options").click(); + h.run_steps(3); + assert!(h.query_by_label("Pulled String Mode").is_some()); + assert!(h.query_by_label("Smoothing Options").is_none()); +} + +#[test] +fn the_smoothing_options_popup_has_a_title() { + let mut h = bar(Tool::Brush); + h.get_by_label("Set additional smoothing options").click(); + h.run_steps(3); + assert!(h.query_by_label("Smoothing Options").is_some()); + assert!(h.query_by_label("Pulled String Mode").is_some()); +} diff --git a/crates/ui-egui/src/brush_picker_escape_tests.rs b/crates/ui-egui/src/brush_picker_escape_tests.rs new file mode 100644 index 0000000000..805a6a1c5d --- /dev/null +++ b/crates/ui-egui/src/brush_picker_escape_tests.rs @@ -0,0 +1,126 @@ +//! #11816: Escape in the Brush Preset picker closes it and reverts a size or hardness typed in +//! it; Enter keeps them, a preset picked before Escape stays picked, a change made outside the +//! picker stays, and each opening reverts to its own start. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} + +fn open(h: &mut Harness<'static, PhotocraftApp>) { + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); +} + +/// Type `text` into the picker's `n`th spin field (0 Size, 1 Hardness), then Tab. +fn type_into(h: &mut Harness<'static, PhotocraftApp>, n: usize, text: &str) { + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).expect("the field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(2); +} + +fn brush(h: &Harness<'static, PhotocraftApp>) -> (f32, f32) { + let b = &h.state().session.tools.brush; + (b.size, b.hardness) +} + +#[test] +fn escape_reverts_typed_size_and_hardness() { + let mut h = harness(); + let steps = h.state().session.active().unwrap().history.past_len(); + open(&mut h); + type_into(&mut h, 0, "60"); + type_into(&mut h, 1, "100"); + assert!(h.state().ui.brush_picker.is_some(), "Tab keeps the picker open"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.brush_picker, None); + assert_eq!(brush(&h), (20.0, 0.0), "back to the brush the picker opened with"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "no history step"); +} + +#[test] +fn enter_keeps_the_typed_values() { + let mut h = harness(); + open(&mut h); + type_into(&mut h, 0, "60"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().ui.brush_picker, None); + assert_eq!(brush(&h).0, 60.0); +} + +#[test] +fn a_preset_picked_before_escape_stays_picked() { + let mut h = harness(); + open(&mut h); + let name = h.state().session.tools.presets.get(1).map(|p| p.name.clone()).expect("a preset"); + h.get_by_label(&name).click(); + h.run_steps(3); + let picked = brush(&h); + assert_ne!(picked, (20.0, 0.0), "the preset changed the brush"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.brush_picker, None); + assert_eq!(brush(&h), picked); +} + +#[test] +fn escape_keeps_a_size_changed_outside_the_picker() { + let mut h = harness(); + open(&mut h); + type_into(&mut h, 1, "100"); + // As `]` or the options bar would, while the picker stays open. + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 45}})).unwrap(); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(brush(&h), (45.0, 0.0), "the typed hardness reverts, the size from elsewhere stays"); +} + +#[test] +fn a_reopened_picker_reverts_to_its_own_opening() { + let mut h = harness(); + open(&mut h); + type_into(&mut h, 0, "60"); + // Closed, changed and opened again (a control request) before the next frame. + let ctx = h.ctx.clone(); + let app = h.state_mut(); + crate::brush_picker::close(&mut app.ui); + app.run("tools.setBrush", json!({"brush": {"size": 33}})).unwrap(); + let at = app.last_canvas_rect.center(); + crate::brush_picker::open(&mut app.ui, &ctx, [at.x, at.y]); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(brush(&h).0, 33.0, "the size this opening started with"); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7a7ece561f..ac471a9269 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -68,7 +68,7 @@ pub(crate) use display::GPU_OUTPUT; use display::texture_key; pub(crate) use display::{cache_key, canvas_display, display_doc, display_image}; use display::{checker, hdr_preview, sync_display_lut}; -pub use drag::{Drag, fixed_size_px, marquee_corners, marquee_px, marquee_readout, readout_in, size_readout, square_px}; +pub use drag::{Drag, DragDocument, fixed_size_px, marquee_corners, marquee_px, marquee_readout, readout_in, size_readout, square_px}; pub(crate) use drag::{angle_readout, doc_box_corners, draw_readout, draw_value_readout}; #[cfg(test)] pub(crate) use drag::{marquee_drag_ants, marquee_preview_px}; @@ -79,7 +79,7 @@ pub(crate) use filter_preview::{ensure_filter_preview, filter_channel_preview, f #[cfg(test)] pub(crate) use gesture::constrained_polygon_point; pub use gesture::{commit_crop, commit_polygon, polygon_cancel_stale, polygon_replaces_selection, polygon_retract}; -pub(crate) use gesture::{finish_gesture, selection_mode}; +pub(crate) use gesture::{finish_gesture, polygon_close_reach, selection_mode}; pub(crate) use navigator::NavigatorCache; #[cfg(test)] use navigator::navigator_waits_for_drag; @@ -111,11 +111,12 @@ use tabs::{dots, paint_dots}; use tabs::{main_canvas_document, move_target_after_filter}; #[cfg(test)] pub(crate) use textures::detail_plan; +pub(crate) use textures::visible_doc_rect; pub(crate) use textures::{DetailPlan, damage_since, effect_reach, ensure_texture_in_view, retain_gpu_documents, shown_as_document}; pub use textures::{MAX_TEXTURE, ensure_texture}; #[cfg(test)] use textures::{clamp_texture_side, preview_bounds, texture_factor}; -use textures::{ensure_gpu, redraw_focus, visible_doc_rect}; +use textures::{ensure_gpu, redraw_focus}; pub use tool_input::{ToolEvent, selection_drag_kind, tool_event}; pub(crate) use tool_input::{command_guide_at, command_moves_layer, event_tool}; pub(crate) use transform_controls::ControlsPress; @@ -247,8 +248,20 @@ fn paint_selection_outline(app: &mut PhotocraftApp, input: SelectionPaintInput<' Some(None) => (None, 1), Some(Some((proxy, k))) => (proxy.selection.as_ref(), (*k).max(1)), }; + // ⌥'s "is anything selected" (`tool_feedback::document_selection_mode`) reads the active + // document's selection bounds every frame: cache them here even while the ants are hidden + // (Selection Edges off, a lasso replacing them), or each frame would scan the selection. + if app.session.active_index() == Some(input.idx) + && let Some(sel) = input.doc.selection.as_ref() + { + app.cached_bounds(u64::MAX - input.doc.id.0, sel); + } // Selection outline: true boundary, animated marching ants (cached per revision). - if let Some(sel) = outlined.filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) { + // A Patch lasso drag replaces the active document's selection, not a floating piece or Select + // and Mask's refined preview; other documents keep their ants. + let patch_replaces = + || refined.is_none() && floated.is_none() && app.session.active_index() == Some(input.idx) && crate::retouch_ui::patch_replaces_selection(app); + if let Some(sel) = outlined.filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app) && !patch_replaces()) { // Trace at display resolution over the visible part only; key by the mask's tile identity // (not the document revision) so unrelated edits don't re-trace it. The step is in // device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px @@ -525,6 +538,11 @@ fn paint_canvas( painter.image(tex, xf.doc_rect(a), uv, Color32::WHITE); } } + // Image › Adjustments › Levels: Alt-drag on the black / white Input slider (levels_clipping.rs). + // The main canvas only: the display keeps one cache, sized to that view. + if primary { + crate::levels_clipping::paint(app, ctx, painter, &xf, idx); + } crate::color_range_ui::paint_selection_preview(app, ctx, painter, doc.id, img_rect, flip); // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). if doc.has_artboards() { @@ -702,6 +720,19 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< // Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701). let shadow_drag = !picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields)); + // Layer Style on a Gradient Overlay page: a drag on the image moves the gradient (#10763), as + // long as the dialog's layer is there to move it on. + let gradient_drag = !picking + && app.ui.dialogs.last().is_some_and(|d| { + d.kind == crate::state::DialogKind::LayerStyle + && crate::layer_style::drags_gradient(&d.fields) + && crate::layer_style::gradient_layer_bounds(&app.session, &d.fields).is_some() + }); + // Off that page (another one chosen under a held press, say) the stored drag is over: the + // page chosen again starts from the offset shown. + if !gradient_drag && let Some(d) = app.ui.dialogs.last_mut().filter(|d| d.kind == crate::state::DialogKind::LayerStyle) { + crate::layer_style::end_gradient_drag(&mut d.fields); + } // ⌘/Ctrl-click with Curves open: a point at the pixel's tone (#7325), whatever the tool. The // press's own modifiers decide, and only the press adds: a drag would add one per frame. let curve_point_press = (input.primary && !input.middle && crate::adjust_dialog::curves_on_top(app)) @@ -716,7 +747,14 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< .flatten() .map(|m| crate::workspace_ui::sticky_mods(app, m)) .filter(|m| m.command); - let dialog_hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag && curve_point_press.is_none(); + let dialog_hand = app.ui.tool == Tool::Hand + && !picking + && !range_picking + && !refine_brushing + && !pinning + && !shadow_drag + && !gradient_drag + && curve_point_press.is_none(); // ⌘Space / ⌥Space zoom under the dialog as they do without one, before Space pans (#6460). // With the Hand tool, ⌘ alone is Zoom In (#6434); under Curves that press is the dialog's // point (#7325), not a zoom. @@ -753,6 +791,17 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< crate::layer_style::drag_shadow(&mut d.fields, start, [f64::from(total.x), f64::from(total.y)]); } } + } else if gradient_drag && !input.middle && crate::dialogs::free_pointer_over(input.ctx, input.rect).is_some() { + input.ctx.set_cursor_icon(egui::CursorIcon::Move); + if let Some(p) = crate::dialogs::free_press(input.ctx, input.rect) { + let (start, origin) = input.ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.press_origin().unwrap_or(p))); + let total = input.xf.unmap_vec(p - origin) / (input.view.zoom / input.ppp); + // The gradient's offset is a fraction of the layer's bounds, as the renderer paints it. + let bounds = app.ui.dialogs.last().and_then(|d| crate::layer_style::gradient_layer_bounds(&app.session, &d.fields)); + if let (Some(bounds), Some(d)) = (bounds, app.ui.dialogs.last_mut()) { + crate::layer_style::drag_gradient(&mut d.fields, start, [f64::from(total.x), f64::from(total.y)], bounds); + } + } } else if picking && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect) { if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { input.ctx.set_cursor_icon(egui::CursorIcon::Crosshair); @@ -764,7 +813,7 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< if curves_picking { crate::adjust_dialog::sample_at(app, d[0], d[1]); } else if replace_picking { - crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1]); + crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1], input.ctx.input(|i| i.modifiers)); } else { crate::color_picker_ui::sample_at(app, d[0], d[1]); } @@ -912,10 +961,14 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> crate::canvas_tool_menu::open_pasteboard(app, ctx, tool, [p.x, p.y]); } } + // A Magnetic Lasso border being drawn: no menu over it, and the border stays live, as in + // Photoshop (#11689). + let magnetic_drawing = crate::canvas_tool_menu::magnetic_drawing(app); if right_click && !lasso_retracted && !transforming && !guide_menu + && !magnetic_drawing && !crate::layer_pick_ui::is_gesture(tool, mods) && let Some(p) = right_at { diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index f633dc91e0..b2e377e0ec 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -464,6 +464,16 @@ pub fn applies(tool: Tool) -> bool { ) || path_menu(tool) } +/// A Magnetic Lasso border is being drawn on the document in front: a right-click opens no menu +/// over it, and the border stays live, as in Photoshop (#11689). A border left on another +/// document doesn't count, even before `magnetic_lasso_ui::frame` drops it: the control +/// channel's events run no frame. Nor does an ⌥-drag's freehand segment: that case wasn't +/// measured, so it keeps the menu it had. +pub fn magnetic_drawing(app: &PhotocraftApp) -> bool { + let m = &app.ui.magnetic; + m.active() && !m.freehand && app.ui.tool == Tool::MagneticLasso && app.session.active().map(|d| d.doc.id.0) == Some(m.doc) +} + /// Tools whose canvas right-click opens the path menu ([`PEN_MENU`]): the Pen, and the Path /// Selection and Direct Selection tools, whose Photoshop menu offers the same whole-path actions /// for the selected path (#1056). diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index dee8017444..e692c4fe07 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -203,16 +203,53 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: true } +/// Sample the image or targeted raster mask at (x, y) using the configured Sample Size. +/// Write a valid sample to the foreground swatch, or to the background swatch with Alt. pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - if let Some(mut rgb) = eyedropper_color(app, x, y) { - if super::paint_target(app) != json!("pixels") { - rgb = [photocraft_color::convert::rgb_to_gray(rgb); 3]; - } + let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) { + sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) + } else { + eyedropper_color(app, x, y).map(|rgb| if super::paint_target(app) == json!("pixels") { rgb } else { [photocraft_color::convert::rgb_to_gray(rgb); 3] }) + }; + if let Some(rgb) = rgb { let key = if mods.alt { "background" } else { "foreground" }; let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })); } } +/// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask. +fn eyedropper_mask_source(app: &PhotocraftApp) -> Option<(&photocraft_raster::Surface, photocraft_geom::Rect)> { + use photocraft_engine::{channel_cmds::ChannelTarget, mask_view_cmds}; + + if app.active_tool() != Tool::Eyedropper + || app.ui.vector_mask_target + || !matches!(app.ui.tool_options.eyedropper_sample.as_str(), "current" | "currentAndBelow") + { + return None; + } + let st = app.session.active()?; + // Painting can implicitly edit an adjustment's mask even with its content thumbnail selected. + let targeted = app.ui.mask_target || st.channel_view.target == ChannelTarget::LayerMask || mask_view_cmds::current(st).is_some_and(|v| !v.filter); + if !targeted || st.doc.quick_mask.is_some() || !app.layer_mask_targeted() { + return None; + } + let mask = st.doc.layer(st.active_layer?)?.mask.as_ref()?; + Some((&mask.surface, st.doc.bounds())) +} + +/// Read the stored mask channel, including its sparse default, rather than its composited coverage. +fn sample_layer_mask(surface: &photocraft_raster::Surface, canvas: photocraft_geom::Rect, x: f64, y: f64, size: u32) -> Option<[f32; 3]> { + let rect = photocraft_engine::cmd::sample_cmds::sample_rect(x, y, size, canvas)?; + let mut sum = 0.0; + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + sum += f64::from(surface.sample_channel(x, y, 0)); + } + } + let gray = (sum / (f64::from(rect.width()) * f64::from(rect.height()))) as f32; + gray.is_finite().then_some([gray; 3]) +} + /// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel, /// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`). /// `None` off the image or over transparency. @@ -248,3 +285,7 @@ pub(crate) fn alt_loads_mixer(tool: Tool, mods: egui::Modifiers) -> bool { pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool { alt_samples(tool, mods) || alt_loads_mixer(tool, mods) } + +#[cfg(test)] +#[path = "../eyedropper_mask_sample_tests.rs"] +mod eyedropper_mask_sample_tests; diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 53eb81c592..8be1a51c5d 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -41,6 +41,8 @@ pub struct Drag { /// at the press picks the selection mode only then; without one it constrains the shape from /// the first move (#11389). `true` until recorded, which keeps that rule for drags that don't. pub selection_at_press: bool, + /// The document a press on the canvas started the drag on (`retouch_ui::cancel_stale`). + pub document: Option, } impl Drag { @@ -63,6 +65,7 @@ impl Drag { vector_owner: None, pen_owner: None, selection_at_press: true, + document: None, } } @@ -382,6 +385,35 @@ pub(crate) fn draw_readout(ctx: &egui::Context, id: &str, cursor ); } +/// The document a drag was pressed on. A reopened document can keep its ID and revision, and be +/// edited past it before the next frame, so the session's active generation, which closing and +/// reopening advance, tells it apart; the snapshot catches one replaced in place. An ordinary edit +/// replaces the snapshot but advances the revision, which keeps the drag on it (the rule +/// `sync_views` applies to the Paths selection). +#[derive(Clone, Debug)] +pub struct DragDocument { + id: photocraft_doc::DocId, + generation: u64, + revision: u64, + snapshot: std::sync::Weak, +} + +impl DragDocument { + pub fn capture(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + Some(Self { id: st.doc.id, generation: app.session.active_generation(), revision: st.revision, snapshot: std::sync::Arc::downgrade(&st.doc) }) + } + + /// The document is still the active one. + pub fn is_active(&self, app: &PhotocraftApp) -> bool { + app.session.active_generation() == self.generation + && app + .session + .active() + .is_some_and(|st| st.doc.id == self.id && (st.revision > self.revision || self.snapshot.ptr_eq(&std::sync::Arc::downgrade(&st.doc)))) + } +} + /// The document, revision and target a vector drag started on. #[derive(Clone, Debug)] pub(super) struct VectorGestureOwner { diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index cc2d3d1ef8..b67aec4beb 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -232,16 +232,49 @@ pub(crate) fn constrained_polygon_point(from: [f64; 2], point: [f64; 2]) -> [f64 [from[0] + length * angle.cos(), from[1] + length * angle.sin()] } +/// How close (in document units) a click must land to a polygon's first vertex to close it: 8 +/// points on screen, but never more than a quarter of the outline's on-screen width (at least 1 +/// point), so the last corner of a small shape doesn't close it early (#6578). The width is the +/// narrower side of the smallest bounding box that fits the outline, turned to line up with one of +/// its edges: a large polygon with one short edge keeps the full 8 points (#7629), while a thin +/// strip stays narrow however it is rotated. Outlines wider than 32 points keep 8. Non-finite +/// points are ignored. Only the first vertex uses this; the last one has its own fixed reach. +pub(crate) fn polygon_close_reach(points: impl IntoIterator, point_zoom: f32) -> f64 { + let zoom = f64::from(point_zoom.max(0.01)); + let pts: Vec<[f64; 2]> = points.into_iter().filter(|p| p.iter().all(|n| n.is_finite())).collect(); + // Edge directions to try; a freehand outline has thousands, so sample them. + let step = pts.len().div_ceil(64).max(1); + let mut width = f64::INFINITY; + for i in (0..pts.len()).step_by(step) { + let (a, b) = (pts[i], pts[(i + 1) % pts.len()]); + let len = (b[0] - a[0]).hypot(b[1] - a[1]); + if len <= 0.0 { + continue; + } + let normal = [-(b[1] - a[1]) / len, (b[0] - a[0]) / len]; + let along = [(b[0] - a[0]) / len, (b[1] - a[1]) / len]; + let extent = |axis: [f64; 2]| { + let (lo, hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| { + let v = p[0] * axis[0] + p[1] * axis[1]; + (lo.min(v), hi.max(v)) + }); + hi - lo + }; + width = width.min(extent(normal).min(extent(along))); + } + let screen = if width.is_finite() { (width * zoom / 4.0).clamp(1.0, 8.0) } else { 8.0 }; + screen / zoom +} + /// A polygonal lasso click adds a vertex; clicking near the first vertex closes the polygon. The /// first click fixes the selection mode; a new-selection polygon hides the old outline while it is /// drawn, and replaces it in one history step when it closes. pub(super) fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { polygon_cancel_stale(app); - let close = app - .ui - .polygon - .first() - .is_some_and(|p0| app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.point_zoom().max(0.01) as f64); + let close = + app.ui.polygon.first().is_some_and(|p0| { + app.ui.polygon.len() >= 3 && (p0[0] - x).hypot(p0[1] - y) < polygon_close_reach(app.ui.polygon.iter().copied(), app.point_zoom()) + }); if close { commit_polygon(app); return; diff --git a/crates/ui-egui/src/canvas/move_ui.rs b/crates/ui-egui/src/canvas/move_ui.rs index 2a70bd6a7a..0743905f7f 100644 --- a/crates/ui-egui/src/canvas/move_ui.rs +++ b/crates/ui-egui/src/canvas/move_ui.rs @@ -383,7 +383,8 @@ pub(crate) fn finish(app: &mut PhotocraftApp, dx: f64, dy: f64) { return; } // `nest`: a layer dropped on another artboard joins it (Photoshop's auto-nesting). - let Ok(result) = app.run("layer.translate", json!({"dx": dx, "dy": dy, "selection": carries_selection(app), "nest": true})) else { + let Ok(result) = app.run("layer.translate", json!({"dx": dx, "dy": dy, "selection": carries_selection(app), "nest": app.ui.artboard_tool.auto_nest})) + else { return; }; // A layer that changed board is clipped by its new board, not the old one the preview showed, diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index e7131b2478..fa644f35ab 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -437,14 +437,22 @@ pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: boo /// edits the session brush like the Brushes panel; a press outside, Escape, Enter or a /// double-click on a preset closes it. pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { - let Some([x, y]) = app.ui.brush_picker else { return }; + let opened_id = crate::brush_picker::opened_id(); + let Some([x, y]) = app.ui.brush_picker else { + ctx.data_mut(|d| d.remove_temp::(opened_id)); + return; + }; if !has_brush_picker(app.ui.tool) { app.ui.brush_picker = None; + ctx.data_mut(|d| d.remove_temp::(opened_id)); return; } + let mut opened = ctx.data_mut(|d| d.get_temp_mut_or_insert_with(opened_id, || crate::brush_picker::Opened::new(&app.session.tools.brush)).clone()); // Escape and Enter close it once this frame's edits are in (a typed size applies), unless they - // end a rename in its rename bar. - let key_close = app.ui.brush_picker_list.renaming.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape) || i.key_pressed(egui::Key::Enter)); + // end a rename in its rename bar. Escape then reverts what was typed (#11816). + let typing_done = app.ui.brush_picker_list.renaming.is_none(); + let escape = typing_done && ctx.input(|i| i.key_pressed(egui::Key::Escape)); + let key_close = escape || (typing_done && ctx.input(|i| i.key_pressed(egui::Key::Enter))); let screen = ctx.content_rect(); // The picker's content size: the one its grip was dragged to, or the one it last closed with // (kept in egui's own memory, which outlives the app's), or the default. The frame's chrome @@ -472,10 +480,25 @@ pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { app.ui.brush_picker_size = Some([new.x, new.y]); } crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &b); + if b != before { + opened.typed(&b); + } let closes = picks.iter().any(crate::brush_picker::Pick::closes); + let picked = + picks.iter().any(|p| matches!(p, crate::brush_picker::Pick::List(crate::brushes_tab::Action::Select(_) | crate::brushes_tab::Action::Choose(_)))); crate::brush_picker::apply(app, ui.ctx(), picks); + // A preset picked stays picked, Escape or not. + if picked { + opened = crate::brush_picker::Opened::new(&app.session.tools.brush); + } closes }); + ctx.data_mut(|d| d.insert_temp(opened_id, opened.clone())); + if escape { + let now = app.session.tools.brush.clone(); + let back = opened.revert(&now); + crate::brush_panel::commit_gesture(app, ctx, &now, &back); + } // Not a press on a menu the picker opened (the gear, a preset's context menu), nor on the // options-bar chip, whose click toggles the picker. A menu floats over the picker in the // foreground order, so the press is told apart by the layer it lands on, not by any popup diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 570549e799..702cf6c3bd 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -637,7 +637,7 @@ fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) { /// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners /// so a rotated camera still covers the visible tiles. -pub(super) fn visible_doc_rect(xf: &ViewXform) -> DRect { +pub(crate) fn visible_doc_rect(xf: &ViewXform) -> DRect { let r = xf.rect; let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))]; let mut x0 = docs[0][0]; diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index ce6cbb9e49..6c9c890571 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -91,8 +91,10 @@ pub fn selection_mode(tool: Tool, bar: u8, m: egui::Modifiers) -> &'static str { /// only draws a marquee from its centre). An options-bar Subtract or Intersect is kept (#1106). pub fn document_selection_mode(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> &'static str { let mode = selection_mode(tool, app.ui.selection_mode, m); - let selected = app.session.active().and_then(|st| st.doc.selection.as_ref()).is_some_and(|s| !s.content_bounds().is_empty()); - if m.alt && !selected && matches!(mode, "subtract" | "intersect") && selection_mode(tool, app.ui.selection_mode, egui::Modifiers::NONE) == "replace" { + // Asked last, and from the bounds the selection outline caches (same key): the canvas asks + // every frame while a Patch lasso is drawn or hovered with ⌥. + let selected = || app.session.active().is_some_and(|st| st.doc.selection.as_ref().is_some_and(|s| !app.known_bounds(u64::MAX - st.doc.id.0, s).is_empty())); + if m.alt && matches!(mode, "subtract" | "intersect") && selection_mode(tool, app.ui.selection_mode, egui::Modifiers::NONE) == "replace" && !selected() { "replace" } else { mode @@ -117,6 +119,15 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option) { + let active_after = app.session.active().and_then(|st| st.active_layer); + if active_after != active_before { + app.move_pick = active_after.map(|id| (id, app.session.active_layer_changes())); + } +} + fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: egui::Modifiers) -> bool { match ev { ToolEvent::Down { x, y, pressure } if tool == Tool::Move => { @@ -244,7 +254,7 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: return true; } if multiple_color_target(app) { - app.ui.status = "Move and transforms on several colour channels are not implemented yet".into(); + app.ui.status = "Move and transforms on several color channels are not implemented yet".into(); return true; } // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first @@ -253,6 +263,7 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: let target = app.ui.tool_options.move_target.clone(); let mode = if mods.shift { "add" } else { "replace" }; let before = app.session.active().map(|st| st.selected_layers()); + let active_before = app.session.active().and_then(|st| st.active_layer); // A locked layer under the pointer (the Background) can't move. Photoshop draws // the layer marquee instead of reporting the lock (#4058). Probe without // selecting so a locked hit doesn't become the selection first. @@ -269,6 +280,7 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: // A click still selects the locked layer, as in Photoshop; a drag's // marquee then replaces that selection on release. let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + note_move_pick(app, active_before); } crate::move_box::begin(app, [x, y], mods.shift); return true; @@ -280,6 +292,7 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: crate::move_box::begin(app, [x, y], mods.shift); return true; } + note_move_pick(app, active_before); // Snapping (and the drag's box) started before the pick: point it at what moves. if app.session.active().map(|st| st.selected_layers()) != before { crate::snap_ui::retarget_move(app, [x, y], mods); @@ -533,6 +546,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) let mut drag = Drag { clear, ..Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase) }; drag.capture_vector_owners(app); drag.capture_selection_at_press(app); + drag.document = super::drag::DragDocument::capture(app); app.drag = Some(drag); app.trail = None; app.stylus.begin_stroke(); diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index c544aad4e3..7cd1e45c3a 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -221,7 +221,7 @@ fn web_sliders_snap_and_take_hex() { // Not a web colour: the cube alert snaps it. type_into(&mut h, egui::accesskit::Role::TextInput, 1, "C8"); assert_eq!(bytes(h.state().session.tools.foreground), [0x66, 0xC8, 0]); - let alert = h.get_by_label("Not a web colour: click for the nearest web colour").rect().center(); + let alert = h.get_by_label("Not a web color: click for the nearest web color").rect().center(); press(&mut h, alert, Modifiers::NONE); assert_eq!(bytes(h.state().session.tools.foreground), [0x66, 0xCC, 0]); } @@ -230,7 +230,7 @@ fn web_sliders_snap_and_take_hex() { 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"; + const GAMUT: &str = "Out of gamut for printing: click for the nearest printable color"; 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"); diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 5469381a29..3441e194ca 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1452,6 +1452,10 @@ fn secondary_transform_or_crop_took(app: &mut PhotocraftApp, ctx: &egui::Context fn secondary_canvas_menu_took(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { let (x, y) = (s.x, s.y); let down = matches!(s.ev, ToolEvent::Down { .. }); + // A Magnetic Lasso border being drawn: no menu over it, as on the canvas (#11689). + if crate::canvas_tool_menu::magnetic_drawing(app) { + return true; + } if crate::canvas_tool_menu::pasteboard_at(app, app.ui.tool, [x, y]) { if down { crate::canvas_tool_menu::open_pasteboard(app, ctx, app.ui.tool, screen_point(app, x, y)); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index e3756a39ea..3a22449782 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1422,6 +1422,50 @@ fn automation_save_passes_targa_bits_without_asking() { assert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing"); } +/// #8064: `app.save` takes `maximizeCompatibility` for a PSD/PSB's merged image over Preferences › +/// File Handling; unset, the preference decides. Anything but a boolean writes nothing. +#[test] +fn app_save_takes_maximize_compatibility() { + use std::cell::RefCell; + use std::rc::Rc; + let asked: Rc>> = Rc::default(); + let written: Rc>> = Rc::default(); + let (a, w) = (asked.clone(), written.clone()); + let services = crate::Services { + export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { + a.borrow_mut().push(s.psd_maximize_compatibility); + Ok((b"out".to_vec(), Vec::new())) + })), + automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let saves = [ + json!({"path": "a.psd"}), + json!({"path": "b.psd", "maximizeCompatibility": false}), + json!({"path": "c.psd", "maximizeCompatibility": true}), + json!({"path": "d.psd", "maximizeCompatibility": null}), + ]; + for params in &saves { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + } + app.session.edit_prefs(|p| p.file_handling.maximize_psd_compatibility = photocraft_engine::prefs::Ask::Never); + for params in [json!({"path": "e.psd"}), json!({"path": "f.psd", "maximizeCompatibility": true})] { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + } + assert_eq!(*asked.borrow(), [true, false, true, true, false, true]); + let r = call(&mut app, &ctx, "app.save", json!({"path": "g.psd", "maximizeCompatibility": "no"})); + assert!(r["error"].as_str().unwrap().contains("maximizeCompatibility"), "{r}"); + assert_eq!(written.borrow().len(), 6, "a bad maximizeCompatibility writes nothing"); +} + /// `app.save` takes JPEG Options (`quality` 0–12, `jpegFormat`) and never stops at the prompt; /// a value it can't read is an error that writes nothing. #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0cfeb7fdc1..621903bd4c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -277,6 +277,19 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { /// it. Returns `Some(true)` / `Some(false)` when the body itself answered OK / Cancel. /// The body of a command dialog: the first handler whose marker the fields carry. The prompts and /// small editors come first; the rest are in `command_body_more`. +/// The delete confirmations: a layer from the Layers panel's trash, or a note (#11788). +fn delete_prompt(fields: &Fields) -> bool { + crate::delete_layer_prompt::owns(fields) || crate::analysis_ui::owns_delete_note(fields) +} + +fn delete_prompt_body(ui: &mut egui::Ui, fields: &mut Fields) { + if crate::analysis_ui::owns_delete_note(fields) { + crate::analysis_ui::delete_note_body(ui, fields); + } else { + crate::delete_layer_prompt::body(ui, fields); + } +} + fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option { let mut outcome: Option = None; match d.kind { @@ -292,7 +305,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: _ if crate::channel_options_ui::owns(fields) => crate::channel_options_ui::body(ui, fields), _ if crate::channel_options_ui::owns_new_spot(fields) => crate::channel_options_ui::new_spot_body(ui, fields), _ if crate::shape_dialog::owns(fields) => crate::shape_dialog::body(app, ui, fields), - _ if crate::delete_layer_prompt::owns(fields) => crate::delete_layer_prompt::body(ui, fields), + _ if delete_prompt(fields) => delete_prompt_body(ui, fields), _ if crate::disk_change_prompt::owns(fields) => crate::disk_change_prompt::body(ui, fields), _ if crate::replace_prompt::owns(fields) => crate::replace_prompt::body(ui, fields), _ if crate::preset_group_prompt::owns(fields) => crate::preset_group_prompt::body(ui, fields), @@ -464,6 +477,8 @@ fn button_row( tl!("Reset") } else if d.kind == DialogKind::NewDocument { tl!("Close") + } else if crate::analysis_ui::owns_delete_note(fields) { + tl!("No") } else { tl!("Cancel") }; @@ -533,6 +548,8 @@ fn ok_label(d: &Dialog) -> &'static str { tl!("Continue") } else if crate::delete_layer_prompt::owns(&d.fields) { tl!("Delete") + } else if crate::analysis_ui::owns_delete_note(&d.fields) { + tl!("Yes") } else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) { tl!("Replace") } else if d.fields.contains_key("__export") { @@ -864,6 +881,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ merge_channels_ui::owns, crate::shape_dialog::owns, crate::delete_layer_prompt::owns, + crate::analysis_ui::owns_delete_note, crate::disk_change_prompt::owns, crate::actions::owns_stop_message, crate::actions::owns_insert_stop, @@ -917,6 +935,24 @@ fn file_command(fields: &Fields) -> Option<&'static str> { } } +/// Batch and the other folder runs (Image Processor, …) go on past a file that fails and list it +/// in their result's `errors`; the status bar and a notice say which files failed and why, so a run +/// that fails on every file isn't silent (#10682). Each file is named by its whole path: files of +/// the same name in different subfolders are told apart. +fn report_file_errors(app: &mut PhotocraftApp, d: &Dialog, r: &Value) { + let Some(errors) = r.get("errors").and_then(Value::as_array).filter(|e| !e.is_empty()) else { return }; + let lines: Vec = errors + .iter() + .map(|e| { + let file = e.get("file").and_then(Value::as_str).unwrap_or_default(); + format!("{file}: {}", e.get("error").and_then(Value::as_str).unwrap_or_default()) + }) + .collect(); + let label = d.fields.get("__label").and_then(Value::as_str).unwrap_or("Command"); + let what = crate::i18n::t(label).trim_end_matches('…').to_string(); + crate::notices::file_failures(app, &what, &lines); +} + /// Confirm a command dialog no specific handler owns: run its `__command` with the dialog's /// parameters, then settle the filter preview and the playing action. fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result { @@ -951,6 +987,9 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result Result fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result { match d.kind { _ if merge_channels_ui::owns(&d.fields) => merge_channels_ui::confirm(app, &d.fields), + _ if crate::analysis_ui::owns_delete_note(&d.fields) => crate::analysis_ui::confirm_delete_note(app, &d.fields), _ if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields), _ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), _ if crate::color_picker_ui::owns(&d.fields) => { diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index ba34906548..f20ea8618e 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -504,6 +504,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map Option { + let egui::Event::Key { key, physical_key, pressed: true, modifiers, .. } = event else { + return None; + }; + if !modifiers.alt || modifiers.command || modifiers.ctrl || modifiers.shift { + return None; + } + let digit = |k: egui::Key| match k { + egui::Key::Num2 => Some(0), + egui::Key::Num3 => Some(1), + egui::Key::Num4 => Some(2), + egui::Key::Num5 => Some(3), + egui::Key::Num6 => Some(4), + _ => None, + }; + digit(physical_key.unwrap_or(*key)) +} + +/// Consumes this frame's Alt/Option+2..6 presses, and the character Option types right after +/// each one on macOS, and selects that entry of the channel popup. +fn select_channel_by_key(ui: &egui::Ui, id: egui::Id, count: usize) { + let picked = ui.input_mut(|i| { + let mut last = None; + let mut typed = false; + i.events.retain(|e| match (channel_for_key(e), e) { + (Some(n), _) => { + last = Some(n); + typed = true; + false + } + (None, egui::Event::Text(_)) if typed => { + typed = false; + false + } + _ => { + typed = false; + true + } + }); + last + }); + if let Some(n) = picked.filter(|&n| n < count) { + ui.data_mut(|d| d.insert_temp(id, n)); + } +} + pub(super) fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let t = Tokens::get(ui.ctx()); let space = space_of(v); @@ -303,6 +351,9 @@ pub(super) fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let state_id = cx.mem.with("curves"); let mut st: CurveUi = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); let isolated = cx.isolated_curve.as_ref(); + if cx.dialog { + select_channel_by_key(ui, cx.mem.with("curves-ch"), channels.len()); + } let ch = editor_channel_picker(ui, cx.mem.with("curves-ch"), &channels); if ch != st.channel { st = CurveUi { channel: ch, ..Default::default() }; @@ -729,3 +780,128 @@ mod polyline_tests { println!("{iterations} polylines: old 4096 samples {old:?}; direct 256 samples {miss:?}; cached screen line {hit:?}"); } } + +#[cfg(test)] +mod channel_key_tests { + use super::*; + use egui::{Event, Key, Modifiers}; + + fn press(key: Key, modifiers: Modifiers) -> Event { + Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers } + } + + fn cx(dialog: bool, gray: bool) -> EditorCx { + EditorCx { + mem: egui::Id::unique("channel-key-test"), + hist: None, + gray, + swatches: [[0.0; 3], [1.0; 3]], + gradients: Vec::new(), + dialog, + dynamic_color_sliders: false, + isolated_curve: None, + } + } + + /// Runs one frame of the Curves editor with `events`; returns the selected channel and how + /// many key events were left unconsumed. + fn frame(ctx: &egui::Context, v: &mut Value, cx: &EditorCx, events: Vec) -> (usize, usize) { + let mut left = 0; + let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + curves(ui, v, cx); + left = ui.input(|i| i.events.iter().filter(|e| matches!(e, Event::Key { .. })).count()); + }); + output.textures_delta.clear(); + (ctx.data(|d| d.get_temp(cx.mem.with("curves-ch"))).unwrap_or(0), left) + } + + #[test] + fn alt_digits_select_rgb_channels_by_position() { + let cx = cx(true, false); + for (key, want) in [(Key::Num3, 1), (Key::Num4, 2), (Key::Num5, 3), (Key::Num2, 0), (Key::Num6, 0)] { + let ctx = egui::Context::default(); + let mut v = json!({}); + let (ch, left) = frame(&ctx, &mut v, &cx, vec![press(key, Modifiers::ALT)]); + assert_eq!(ch, want, "{key:?}"); + assert_eq!(left, 0, "{key:?} is consumed"); + } + } + + #[test] + fn alt_digits_cover_cmyk_and_ignore_keys_past_the_list() { + let cx = cx(true, false); + let cmyk = || json!({"cyan": {}, "black": {}}); + for (key, want) in [(Key::Num2, 0), (Key::Num3, 1), (Key::Num6, 4)] { + let ctx = egui::Context::default(); + let (ch, _) = frame(&ctx, &mut cmyk(), &cx, vec![press(key, Modifiers::ALT)]); + assert_eq!(ch, want, "{key:?}"); + } + // Gray lists one channel: Alt+3 does nothing. + let gray = self::cx(true, true); + let ctx = egui::Context::default(); + let (ch, _) = frame(&ctx, &mut json!({}), &gray, vec![press(Key::Num3, Modifiers::ALT)]); + assert_eq!(ch, 0); + } + + /// Lab lists Lightness, a and b (no composite); Gray lists one channel. Keys past the list + /// select nothing but are still consumed. + #[test] + fn alt_digits_cover_lab_and_gray() { + let rgb = cx(true, false); + let lab = || json!({"a": {}}); + for (key, want) in [(Key::Num2, 0), (Key::Num3, 1), (Key::Num4, 2), (Key::Num5, 0), (Key::Num6, 0)] { + let ctx = egui::Context::default(); + let (ch, left) = frame(&ctx, &mut lab(), &rgb, vec![press(key, Modifiers::ALT)]); + assert_eq!((ch, left), (want, 0), "Lab {key:?}"); + } + let gray = cx(true, true); + for (key, want) in [(Key::Num2, 0), (Key::Num3, 0), (Key::Num6, 0)] { + let ctx = egui::Context::default(); + let (ch, left) = frame(&ctx, &mut json!({}), &gray, vec![press(key, Modifiers::ALT)]); + assert_eq!((ch, left), (want, 0), "Gray {key:?}"); + } + // Past the list after a valid pick: the earlier channel stays. + let ctx = egui::Context::default(); + let mut v = lab(); + frame(&ctx, &mut v, &rgb, vec![press(Key::Num4, Modifiers::ALT)]); + assert_eq!(frame(&ctx, &mut v, &rgb, vec![press(Key::Num5, Modifiers::ALT)]), (2, 0)); + } + + #[test] + fn other_modifiers_and_the_properties_panel_leave_the_keys_alone() { + let ctx = egui::Context::default(); + let dialog = cx(true, false); + for m in [Modifiers::NONE, Modifiers::COMMAND, Modifiers::ALT | Modifiers::SHIFT, Modifiers::ALT | Modifiers::COMMAND] { + let (ch, left) = frame(&ctx, &mut json!({}), &dialog, vec![press(Key::Num3, m)]); + assert_eq!((ch, left), (0, 1), "{m:?}"); + } + let panel = cx(false, false); + let (ch, left) = frame(&ctx, &mut json!({}), &panel, vec![press(Key::Num3, Modifiers::ALT)]); + assert_eq!((ch, left), (0, 1)); + } + + #[test] + fn the_physical_key_decides_when_it_is_known() { + let ctx = egui::Context::default(); + let cx = cx(true, false); + let remapped = Event::Key { key: Key::Num3, physical_key: Some(Key::Q), pressed: true, repeat: false, modifiers: Modifiers::ALT }; + assert_eq!(frame(&ctx, &mut json!({}), &cx, vec![remapped]), (0, 1)); + let logical_only = Event::Key { key: Key::Num3, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::ALT }; + assert_eq!(frame(&ctx, &mut json!({}), &cx, vec![logical_only]), (1, 0)); + } + + #[test] + fn the_character_option_types_is_consumed_with_the_key() { + let ctx = egui::Context::default(); + let cx = cx(true, false); + let mut left = Vec::new(); + let events = vec![press(Key::Num4, Modifiers::ALT), Event::Text("¢".into()), Event::Text("7".into())]; + let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + curves(ui, &mut json!({}), &cx); + left = ui.input(|i| i.events.clone()); + }); + output.textures_delta.clear(); + assert_eq!(left, vec![Event::Text("7".into())]); + assert_eq!(ctx.data(|d| d.get_temp::(cx.mem.with("curves-ch"))), Some(2)); + } +} diff --git a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs index 7079b11972..70413d0440 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs @@ -57,6 +57,8 @@ struct MapStopDrag { index: usize, offset: f32, changed: bool, + /// Dragged off the strip: out of the gradient, kept to come back if the drag returns. + removed: Option, } /// Keep selection on the same stop when it crosses another stop (including coincident stops). @@ -87,28 +89,45 @@ fn gradient_map_strip(ui: &mut egui::Ui, stops: &mut Vec, cx: &EditorCx, s { *selected = index; let offset = stops.get(index).map_or(0.0, |s| pos.x - x_of(s.0)); - ui.data_mut(|d| d.insert_temp(key, MapStopDrag { index, offset, changed: false })); + ui.data_mut(|d| d.insert_temp(key, MapStopDrag { index, offset, changed: false, removed: None })); } if let Some(mut drag) = ui.data(|d| d.get_temp::(key)) { if (resp.dragged() || resp.drag_stopped()) && let Some(pos) = resp.interact_pointer_pos() { let location = round(loc_of(pos.x - drag.offset), 0.001); - let changed = stops.get(drag.index).is_some_and(|s| s.0 != location); - if let Some(index) = move_map_stop(stops, drag.index, location) { - drag.index = index; - drag.changed |= changed; - *selected = index; - edit.changed |= changed; + // As far off the strip as the Gradient tool's; two stops always stay. + let off = crate::gradient_ui::off_strip(pos, bar); + if off && drag.removed.is_none() && stops.len() > 2 && drag.index < stops.len() { + drag.removed = Some(stops.remove(drag.index)); + *selected = drag.index.min(stops.len() - 1); + drag.changed = true; + edit.changed = true; + } else if let Some(stop) = drag.removed.filter(|_| !off) { + drag.removed = None; + stops.push((location, stop.1)); + drag.index = stops.len() - 1; + // Changed, wherever it lands: the preview had it removed. + edit.changed = true; + } + if drag.removed.is_none() { + let changed = stops.get(drag.index).is_some_and(|s| s.0 != location); + if let Some(index) = move_map_stop(stops, drag.index, location) { + drag.index = index; + drag.changed |= changed; + *selected = index; + edit.changed |= changed; + } } } - if resp.drag_stopped() { + // A drag can also end without `drag_stopped` (released outside the window, focus lost): + // either way what the preview shows is committed, so a stop taken off the strip isn't left + // removed with no History step. + if resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down()) { edit.commit = drag.changed; ui.data_mut(|d| d.remove::(key)); - } else if ui.input(|i| i.pointer.primary_down()) { - ui.data_mut(|d| d.insert_temp(key, drag)); } else { - ui.data_mut(|d| d.remove::(key)); + ui.data_mut(|d| d.insert_temp(key, drag)); } } if resp.clicked() diff --git a/crates/ui-egui/src/dialogs/adjust_editors/levels.rs b/crates/ui-egui/src/dialogs/adjust_editors/levels.rs index 5970be1f47..a91e714310 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/levels.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/levels.rs @@ -60,6 +60,16 @@ pub(super) fn nearest(xs: &[f32], x: f32) -> Option { xs.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map(|(i, _)| i as u8) } +fn levels_drag_id(mem: egui::Id) -> egui::Id { + mem.with("levels-drag") +} + +/// The Levels Input slider handle being dragged in the editor rooted at `mem` (0 black, 1 gamma, +/// 2 white), as of its last frame. +pub(crate) fn levels_drag(ctx: &egui::Context, mem: egui::Id) -> Option { + ctx.data(|d| d.get_temp::>(levels_drag_id(mem))).flatten() +} + pub(super) fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let t = Tokens::get(ui.ctx()); let channels = editor_channels(cx, space_of(v)); @@ -98,7 +108,9 @@ pub(super) fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let track = sr.shrink2(vec2(6.0, 0.0)); let xpos = |val: f32| track.left() + val / 255.0 * track.width(); let xval = |x: f32| ((x - track.left()) / track.width() * 255.0).clamp(0.0, 255.0); - let drag_id = cx.mem.with("levels-drag"); + // Where 0 and 255 sit (tests press the handles there). + ui.data_mut(|d| d.insert_temp(cx.mem.with("levels-slider"), track)); + let drag_id = levels_drag_id(cx.mem); let mut which: Option = ui.data(|d| d.get_temp(drag_id)).flatten(); let ctx = ui.ctx().clone(); let pressed = |r: &egui::Response| r.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed()); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index 88dcbaf062..7e21fc91fc 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -532,6 +532,107 @@ fn gradient_map_handle_drag_previews_and_commits_once_after_crossing_stops() { } } +/// #10742: a stop dragged off the strip goes as the Gradient tool's does, with a live preview, and +/// comes back if the drag returns. Two stops always stay. +#[test] +fn gradient_map_stop_dragged_off_the_strip_is_removed_in_one_step() { + for depth in [8, 16, 32] { + let mut h = app_harness("gradientMap", "rgb", depth); + let (id, _) = layer(&h); + let four = json!({"layer": id.0, "stops": [[0, "#000000"], [0.25, "#ff0000"], [0.5, "#00ff00"], [1, "#ffffff"]]}); + h.state_mut().run("layer.setAdjustment", four).unwrap(); + h.run_steps(3); + let before = layer(&h).1; + let steps = h.state().session.active().unwrap().history.past_len(); + let start = map_handle(&h, 0.25); + let away = start + vec2(0.0, 90.0); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(away); + h.run_steps(1); + let preview = h.state().live_adjust.as_ref().map(|(_, v)| v["stops"].as_array().map(Vec::len)); + assert_eq!(preview, Some(Some(3)), "{depth}: the preview drops the stop"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "{depth}: dragging records no history"); + h.drop_at(away); + h.run_steps(3); + assert_eq!(map_stops(&layer(&h).1), vec![(0.0, [0, 0, 0]), (0.5, [0, 255, 0]), (1.0, [255, 255, 255])], "{depth}: the stop is gone"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "{depth}: one history step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(layer(&h).1, before, "{depth}: undo brings it back"); + + // Off the strip and back: the stop stays, with its colour, where the drag ends. + let back = map_handle(&h, 0.4); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(away); + h.run_steps(1); + h.hover_at(back); + h.run_steps(1); + let preview = h.state().live_adjust.as_ref().map(|(_, v)| v["stops"].as_array().map(Vec::len)); + assert_eq!(preview, Some(Some(4)), "{depth}: the preview has the stop back while it's held"); + h.drop_at(back); + h.run_steps(3); + assert_eq!(map_stops(&layer(&h).1), vec![(0.0, [0, 0, 0]), (0.4, [255, 0, 0]), (0.5, [0, 255, 0]), (1.0, [255, 255, 255])], "{depth}: kept"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "{depth}: the move is one step"); + } +} + +/// A drag that ends without its release reaching the strip (the drag taken away: focus lost, the +/// pointer let go elsewhere) still commits what the preview shows: a stop taken off the strip isn't +/// left removed with no History step. +#[test] +fn gradient_map_stop_drag_that_ends_elsewhere_still_commits() { + let mut h = app_harness("gradientMap", "rgb", 8); + let (id, _) = layer(&h); + let four = json!({"layer": id.0, "stops": [[0, "#000000"], [0.25, "#ff0000"], [0.5, "#00ff00"], [1, "#ffffff"]]}); + h.state_mut().run("layer.setAdjustment", four).unwrap(); + h.run_steps(3); + let steps = h.state().session.active().unwrap().history.past_len(); + let start = map_handle(&h, 0.25); + let away = start + vec2(0.0, 90.0); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(away); + h.run_steps(1); + // The drag ends without reaching the strip's response, then the button comes up. + h.ctx.stop_dragging(); + h.run_steps(1); + h.drop_at(away); + h.run_steps(3); + assert_eq!(map_stops(&layer(&h).1).len(), 3, "the stop the preview dropped is gone from the layer"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "in one History step"); +} + +#[test] +fn gradient_map_last_two_stops_cant_be_dragged_off_the_strip() { + let mut h = app_harness("gradientMap", "rgb", 8); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "stops": [[0, "#000000"], [1, "#ffffff"]]})).unwrap(); + h.run_steps(3); + let steps = h.state().session.active().unwrap().history.past_len(); + let start = map_handle(&h, 0.0); + let away = start + vec2(0.0, 90.0); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(away); + h.run_steps(1); + let preview = h.state().live_adjust.as_ref().map(|(_, v)| v["stops"].as_array().map(Vec::len)); + assert!(preview.is_none_or(|n| n == Some(2)), "the preview keeps both: {preview:?}"); + h.drop_at(away); + h.run_steps(3); + assert_eq!(map_stops(&layer(&h).1), vec![(0.0, [0, 0, 0]), (1.0, [255, 255, 255])], "both stay where they were"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "nothing to record"); +} + #[test] fn gradient_map_strip_adds_selects_and_removes_stops_without_deleting_the_last_pair() { let mut h = app_harness("gradientMap", "rgb", 8); diff --git a/crates/ui-egui/src/dialogs/adjust_preview.rs b/crates/ui-egui/src/dialogs/adjust_preview.rs index 60e52bf47a..8238ddeb7b 100644 --- a/crates/ui-egui/src/dialogs/adjust_preview.rs +++ b/crates/ui-egui/src/dialogs/adjust_preview.rs @@ -194,6 +194,19 @@ fn dialog(app: &PhotocraftApp) -> Option<(String, Value, bool)> { Some((kind, crate::filter_dialog::params_of(&d.fields), preview)) } +/// Whether Image › Adjustments `kind` on document `idx` would edit a channel (the Channels panel's +/// target or the Quick Mask) or the active layer's mask instead of the layer's pixels. +pub(crate) fn targets_channel(app: &PhotocraftApp, idx: usize, kind: &str, params: &Value) -> bool { + // The dialog's own target choice, when it has one, decides. + if let Some(target) = params.get("target") { + return target.as_str() != Some("pixels"); + } + let Some(st) = app.session.documents().get(idx) else { return false }; + st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite + || st.doc.quick_mask.is_some() + || !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null() +} + /// FNV-1a over `parts`, never 0. fn hash(parts: &[&[u8]]) -> u64 { parts.iter().flat_map(|p| p.iter()).fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) | 1 @@ -225,13 +238,7 @@ fn update(app: &mut PhotocraftApp, idx: usize) -> Option<&AdjustPreview> { let (doc_id, revision, target) = (st.doc.id, st.revision, st.active_layer?); // Commands that target a channel (Channels panel / Quick Mask) or a layer mask keep the proxy // preview. - let channel_target = if let Some(target) = params.get("target") { - target.as_str() != Some("pixels") - } else { - st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite - || st.doc.quick_mask.is_some() - || !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null() - }; + let channel_target = targets_channel(app, idx, &kind, ¶ms); let session = hash(&[&doc_id.0.to_le_bytes(), &revision.to_le_bytes(), &target.0.to_le_bytes(), &[u8::from(channel_target)]]); let h = hash(&[kind.as_bytes(), params.to_string().as_bytes(), &[u8::from(preview)]]); if let Some(p) = &app.adjust_preview 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 426872e347..dee34b3cc9 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs @@ -83,12 +83,12 @@ fn demosaic_row(ui: &mut egui::Ui, m: &mut photocraft_io::raw::Demosaic) { use photocraft_io::raw::Demosaic; ui.horizontal(|ui| { ui.label(crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", "Demosaic")).on_hover_text(tl!( - "How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with." + "How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with." )); let options = [ - (Demosaic::Ahd, "AHD (adaptive homogeneity)", "Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest."), - (Demosaic::Mhc, "Malvar–He–Cutler", "Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail."), - (Demosaic::Bilinear, "Bilinear", "The fastest and the softest, with colour fringing on fine detail."), + (Demosaic::Ahd, "AHD (adaptive homogeneity)", "Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest."), + (Demosaic::Mhc, "Malvar–He–Cutler", "Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail."), + (Demosaic::Bilinear, "Bilinear", "The fastest and the softest, with color fringing on fine detail."), ]; widgets::dropdown_with_tooltips(ui, "camera-raw-demosaic", tl!("Demosaic"), m, &options, 180.0); }); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs index 41fbe6170e..8e3a9c9de6 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -440,7 +440,7 @@ pub fn on_redevelop_event(app: &mut PhotocraftApp, e: &photocraft_engine::jobs:: crate::notices::error(app, format!("{}: {err}", e.label)); } photocraft_engine::jobs::JobOutcome::Cancelled => { - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &e.label)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled {label}"), &[("label", &e.label)]); app.ui.status_error = false; } } @@ -455,7 +455,7 @@ pub(super) fn cancel(app: &mut PhotocraftApp) { { app.session.close(index); app.sync_views(); - app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &raw.name)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &raw.name)]); app.ui.status_error = false; } } diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index 1c0ce157e8..d59bf082c3 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -572,15 +572,15 @@ fn swatches(ui: &mut egui::Ui, f: &mut Map) { p.rect_filled(cur, 0.0, c32(orig)); p.rect_stroke(sw, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); let click_cur = ui.interact(cur, ui.scope_id().with("cp-current"), Sense::click()); - click_cur.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Click to restore the current colour"))); - if click_cur.on_hover_text(tl!("Click to restore the current colour")).clicked() { + click_cur.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Click to restore the current color"))); + if click_cur.on_hover_text(tl!("Click to restore the current color")).clicked() { set_rgb(f, orig, Keep::Nothing); } // Photoshop's warnings beside the swatch, each over a chip of the nearest colour that passes // (a click takes it): out of gamut for printing on top, not a web colour below. let x = sw.right() + 8.0; - let gamut = tl!("Out of gamut for printing: click for the nearest printable colour"); - let web = tl!("Not a web colour: click for the nearest web colour"); + let gamut = tl!("Out of gamut for printing: click for the nearest printable color"); + let web = tl!("Not a web color: click for the nearest web color"); for (slot, warning, tip) in [(0.0, out_of_gamut(rgb), gamut), (34.0, not_web_safe(rgb), web)] { let Some(near) = warning else { continue }; let icon = Rect::from_min_size(pos2(x, sw.top() + 2.0 + slot), vec2(13.0, 13.0)); @@ -993,6 +993,10 @@ fn confirm_target(app: &mut PhotocraftApp, f: &Map) -> Result egui::Response { } /// Eyedropper button: the pipette icon with a +/− badge; labelled for accessibility. -fn eyedropper(ui: &mut egui::Ui, badge: &str, selected: bool, label: &str) -> egui::Response { +pub(crate) fn eyedropper(ui: &mut egui::Ui, badge: &str, selected: bool, label: &str) -> egui::Response { let t = Tokens::get(ui.ctx()); let r = crate::icons::button(ui, "pipette", 26.0, selected, label); if !badge.is_empty() { @@ -528,7 +528,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map tl!("Sample: foreground colour").to_string(), + (0, 0) => tl!("Sample: foreground color").to_string(), (a, 0) => crate::i18n::trn(crate::i18n::current(), a as u64, "{n} sample", "{n} samples"), (a, s) => crate::i18n::fmt( tl!("{added}, {removed} subtracted"), @@ -571,7 +571,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map &'static str { + match name { + "letter" => "Letter", + "legal" => "Legal", + "tabloid" => "Tabloid", + "a3" => "A3", + "a4" => "A4", + "a5" => "A5", + "a6" => "A6", + "4x6" => "4 × 6 in", + "5x7" => "5 × 7 in", + "postcard" => "はがき (100 × 148 mm)", + "double-postcard" => "往復はがき (148 × 200 mm)", + "b5" => "JIS B5 (182 × 257 mm)", + "b4" => "JIS B4 (257 × 364 mm)", + "l" => "L判 (89 × 127 mm)", + "2l" => "2L判 (127 × 178 mm)", + "kg" => "KG判 (102 × 152 mm)", + "6cut" => "六切 (203 × 254 mm)", + "4cut" => "四切 (254 × 305 mm)", + other => other, + } +} + /// Unrotated paper dimensions in points, for either the current preset or a custom array. fn print_paper_size(value: Option<&Value>) -> (f64, f64) { let default = (612.0, 792.0); match value { Some(Value::Array(a)) => (a.first().and_then(Value::as_f64).unwrap_or(default.0), a.get(1).and_then(Value::as_f64).unwrap_or(default.1)), - Some(Value::String(name)) => photocraft_engine::print_cmds::PAPERS.iter().find(|p| p.0.eq_ignore_ascii_case(name)).map_or(default, |p| (p.1, p.2)), + Some(Value::String(name)) => photocraft_engine::print_cmds::paper_size(name).unwrap_or(default), _ => default, } } @@ -211,9 +237,19 @@ fn print_paper_size(value: Option<&Value>) -> (f64, f64) { /// unrotated print points; the engine applies orientation and validates the final size. fn print_paper_controls(ui: &mut egui::Ui, f: &mut Map) { let previous = f.get("paper").cloned(); - let mut selected = if previous.as_ref().is_some_and(Value::is_array) { "custom".to_string() } else { s(f, "paper", "letter") }; + let mut selected = if previous.as_ref().is_some_and(Value::is_array) { + "custom".to_string() + } else { + let name = s(f, "paper", "letter"); + // `file.print` remembers the name as typed, aliases included; the menu is keyed by the + // canonical `PAPERS` names, so show the key an alias names, and keep unknown names. + match photocraft_engine::print_cmds::paper_size(&name) { + Some(size) => photocraft_engine::print_cmds::PAPERS.iter().find(|p| (p.1, p.2) == size).map_or(name, |p| p.0.to_string()), + None => name, + } + }; ui.horizontal(|ui| { - let mut papers: Vec<_> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0.to_string(), p.0)).collect(); + let mut papers: Vec<_> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0.to_string(), print_paper_label(p.0))).collect(); papers.push(("custom".to_string(), tl!("Custom"))); if crate::widgets::dropdown(ui, "print-paper", tl!("Paper"), &mut selected, &papers, 110.0) { if selected == "custom" { @@ -553,7 +589,7 @@ pub(super) fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map }); if printers.is_some() { ui.label( - egui::RichText::new(tl!("Remember to turn off the printer's own colour management in Print Settings…")).color(t.warning).size(11.0), + egui::RichText::new(tl!("Remember to turn off the printer's own color management in Print Settings…")).color(t.warning).size(11.0), ); } } diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index 050e730bf5..8ddd093f4f 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -1157,3 +1157,75 @@ fn a_turn_takes_the_printable_area_with_the_paper() { assert!(f.get("printable").is_none(), "{area}"); } } + +#[test] +fn the_web_preview_selects_slices_and_saves_only_the_selected_ones() { + // A 120 × 80 document with a user slice on its left half; the right half is auto slice 02. + let (mut app, _) = app(); + app.run("slice.new", json!({"rect": [0, 0, 60, 80], "name": "left"})).unwrap(); + let id = open_web(&mut app); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("__view".into(), json!("optimized")); + fields.insert("format".into(), json!("png24")); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state( + |ui, app| { + crate::color_picker_ui::widget_tick(app, ui.ctx()); + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { + crate::dialogs::show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(5); + let r = &h.state().ui.dialogs[0].fields["__previewRects"][0]; + let pane = egui::Rect::from_min_max( + egui::pos2(r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32), + egui::pos2(r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32), + ); + // The preview fits the document in the pane, centred. + let scale = (pane.width() / 120.0).min(pane.height() / 80.0); + let at = |x: f32, y: f32| pane.center() + egui::vec2(x - 60.0, y - 40.0) * scale; + let click = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, pos: egui::Pos2, modifiers: egui::Modifiers| { + // The window reports held modifiers as their own event as well as on the button events. + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(pos)); + h.step(); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers }); + h.step(); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(2); + }; + let selected = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().ui.dialogs[0].fields.get("__selectedSlices").cloned(); + click(&mut h, at(30.0, 40.0), egui::Modifiers::NONE); + assert_eq!(selected(&h), Some(json!([1])), "a click selects the slice under the pointer"); + click(&mut h, at(90.0, 40.0), egui::Modifiers::SHIFT); + assert_eq!(selected(&h), Some(json!([1, 2])), "Shift-click adds a slice"); + click(&mut h, at(30.0, 40.0), egui::Modifiers::SHIFT); + assert_eq!(selected(&h), Some(json!([2])), "Shift-click on a selected slice removes it"); + // The view's own drag still pans rather than selecting. + assert_eq!(h.state().ui.dialogs[0].fields["__zoom"], json!(null)); + + let mut fields = h.state().ui.dialogs[0].fields.clone(); + fields.insert("slices".into(), json!("selected")); + let p = web_params(&fields, true).unwrap(); + assert_eq!(p["numbers"], json!([2])); + fields.insert("__selectedSlices".into(), json!([])); + assert!(web_params(&fields, true).is_err(), "Selected Slices with nothing selected is an error, not every slice"); + assert!(web_params(&fields, false).unwrap().get("numbers").is_none(), "a document without slices ignores the choice"); + + let mut app = h.into_state(); + let downloads = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let captured = downloads.clone(); + app.services.write = Some(Box::new(move |path, _| { + captured.borrow_mut().push(path.to_string()); + Ok(()) + })); + let mut p = p; + p["dir"] = json!("."); + p["html"] = json!(false); + download_for_web(&mut app, p).unwrap(); + let files = downloads.borrow(); + assert_eq!(files.len(), 1, "only the selected slice is saved: {files:?}"); + assert!(!files[0].contains("left"), "{files:?}"); +} diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index 12fc335b4e..d8db1fee04 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -27,7 +27,7 @@ pub fn open_web(app: &mut PhotocraftApp) -> u64 { .unwrap_or_else(|| json!({"format": "jpeg", "quality": 60})); if let Value::Object(m) = last { for (k, v) in m { - if !matches!(k.as_str(), "path" | "dir" | "folder" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits") { + if !matches!(k.as_str(), "path" | "dir" | "folder" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits" | "numbers") { f.insert(k, v); } } @@ -152,13 +152,14 @@ fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option< }; ui.vertical(|ui| { ui.set_width(size.x); - let (r, response) = ui.allocate_exact_size((size - egui::vec2(0.0, 42.0)).max(egui::vec2(1.0, 1.0)), egui::Sense::drag()); + let (r, response) = ui.allocate_exact_size((size - egui::vec2(0.0, 42.0)).max(egui::vec2(1.0, 1.0)), egui::Sense::click_and_drag()); let response = response.on_hover_cursor(egui::CursorIcon::Grab); if let Some(rects) = f.get_mut("__previewRects").and_then(Value::as_array_mut) { rects.push(json!([r.left(), r.top(), r.right(), r.bottom()])); } crate::widgets::checker(ui.painter(), r, 8.0); - web_preview::paint(ui, r, &response, &tex, source_size, f); + let image = web_preview::paint(ui, r, &response, &tex, source_size, f); + web_preview::slices(ui, r, image, &response, &doc, crate::tools::slice_ui::slice_color(app), f); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside); let (l1, l2) = match (p, info) { (None, _) => ("Original".to_string(), format!("{} · {} × {} px", doc.name, doc.size.width, doc.size.height)), @@ -412,7 +413,15 @@ pub(super) fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) -> Re } Ok(()) }; - let mut p = params(f); + let has_slices = app.session.active().is_some_and(|st| !st.doc.slices.is_empty()); + let mut p = web_params(f, has_slices)?; authorize(&p)?; // Confirmation may follow a field edit without an intervening frame (Enter or automation). let mut fields = f.clone(); web_preview::prepare_table(app, &mut fields)?; - let prepared = params(&fields); + let prepared = web_params(&fields, has_slices)?; if prepared != p { // The policy must also approve the actual palette-bearing export parameters. authorize(&prepared)?; @@ -570,7 +580,6 @@ pub(super) fn web_confirm(app: &mut PhotocraftApp, f: &Map) -> Re return save_for_web(app, p); } let doc = app.session.active().ok_or("no document")?.doc.clone(); - let has_slices = !doc.slices.is_empty(); let html = b(f, "html", true); let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?; let base = photocraft_doc::slices::base_name(&doc); @@ -605,6 +614,20 @@ fn kept_name_folder(path: &str, base: &str, ext: &str) -> Option { kept.then(|| file.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()) } +/// The export parameters: the fields, plus the numbers of the slices selected in the preview +/// when the document's slices are exported as Selected Slices. +pub(super) fn web_params(f: &Map, has_slices: bool) -> Result { + let mut p = params(f); + if has_slices && s(f, "slices", "all") == "selected" { + let numbers = web_preview::selected_slices(f); + if numbers.is_empty() { + return Err(tl!("No slices are selected. Click a slice in the preview to select it.").to_string()); + } + p["numbers"] = json!(numbers); + } + Ok(p) +} + /// Runs Save for Web with `p`, which says where to write. fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result { #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/dialogs/file_ui/web_preview.rs b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs index c2bdd4ad11..41bcd77b0e 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web_preview.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs @@ -230,7 +230,16 @@ pub fn controls(ui: &mut egui::Ui, f: &mut Map) { nav.write(f); } -pub fn paint(ui: &mut egui::Ui, rect: egui::Rect, response: &egui::Response, tex: &egui::TextureHandle, source: egui::Vec2, f: &mut Map) { +/// Paints the preview image in `rect` and returns where the whole image lies (it may extend +/// past `rect` when zoomed in). +pub fn paint( + ui: &mut egui::Ui, + rect: egui::Rect, + response: &egui::Response, + tex: &egui::TextureHandle, + source: egui::Vec2, + f: &mut Map, +) -> egui::Rect { let mut nav = Navigation::read(f); let ppp = ui.ctx().pixels_per_point(); if response.double_clicked() { @@ -267,6 +276,99 @@ pub fn paint(ui: &mut egui::Ui, rect: egui::Rect, response: &egui::Response, tex f.insert("__effectiveZoom".into(), json!(scale * ppp)); } nav.write(f); + image +} + +/// The numbers of the slices selected in the preview, in ascending order. +pub fn selected_slices(f: &Map) -> Vec { + let mut numbers: Vec = f.get("__selectedSlices").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); + numbers.sort_unstable(); + numbers.dedup(); + numbers +} + +/// Draws the document's slices over a preview pane, as Photoshop's Save for Web does: user and +/// layer slices outlined in the slice colour, auto slices dashed, each with its number, and the +/// selected ones highlighted (#10548). A click selects the slice under the pointer and +/// Shift-click adds or removes one, like the dialog's Slice Select tool; the selection is the +/// `__selectedSlices` field, which Selected Slices exports. +pub fn slices( + ui: &egui::Ui, + rect: egui::Rect, + image: egui::Rect, + response: &egui::Response, + doc: &photocraft_doc::Document, + color: egui::Color32, + f: &mut Map, +) { + use photocraft_doc::SliceOrigin; + if doc.slices.is_empty() { + return; + } + let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32); + let to_screen = |r: photocraft_geom::Rect| { + let at = |x: i32, y: i32| image.min + egui::vec2(x as f32 / dw * image.width(), y as f32 / dh * image.height()); + egui::Rect::from_two_pos(at(r.x0, r.y0), at(r.x1, r.y1)) + }; + let all = photocraft_doc::slices::resolve(doc); + if response.clicked() + && let Some(pos) = response.interact_pointer_pos() + { + let hit = all.iter().find(|r| to_screen(r.rect).contains(pos)).map(|r| r.number as u64); + let mut selected = selected_slices(f); + match hit { + Some(n) if ui.input(|i| i.modifiers.shift) => { + if let Some(i) = selected.iter().position(|v| *v == n) { + selected.remove(i); + } else { + selected.push(n); + } + } + Some(n) => selected = vec![n], + None => {} + } + f.insert("__selectedSlices".into(), json!(selected)); + } + let selected = selected_slices(f); + let highlight = egui::Color32::from_rgb(0xff, 0xb0, 0x00); + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + // Auto slices first (dashed, underneath), then user and layer slices, then the selection. + for pass in 0..3 { + for r in &all { + let auto = r.origin == SliceOrigin::Auto; + let chosen = selected.contains(&(r.number as u64)); + if (pass == 0 && !auto) || (pass == 1 && auto) || (pass == 2 && !chosen) { + continue; + } + let sr = to_screen(r.rect); + match pass { + 0 => { + let pts = [sr.left_top(), sr.right_top(), sr.right_bottom(), sr.left_bottom(), sr.left_top()]; + painter.add(egui::Shape::dashed_line(&pts, egui::Stroke::new(1.0, color.gamma_multiply(0.7)), 3.0, 3.0)); + } + 1 => { + painter.rect_stroke(sr, 0.0, egui::Stroke::new(1.0, color), egui::StrokeKind::Inside); + } + _ => { + painter.rect_filled(sr, 0.0, highlight.gamma_multiply(0.12)); + painter.rect_stroke(sr, 0.0, egui::Stroke::new(2.0, highlight), egui::StrokeKind::Inside); + } + } + if pass < 2 && sr.width() > 18.0 && sr.height() > 12.0 { + let galley = painter.layout_no_wrap(format!("{:02}", r.number), egui::FontId::proportional(10.0), egui::Color32::WHITE); + let badge = egui::Rect::from_min_size(sr.left_top() + egui::vec2(2.0, 2.0), galley.size() + egui::vec2(6.0, 2.0)); + let bg = if chosen { + highlight + } else if auto { + egui::Color32::from_gray(110) + } else { + color + }; + painter.rect_filled(badge, 2.0, bg); + painter.galley(badge.min + egui::vec2(3.0, 1.0), galley, egui::Color32::WHITE); + } + } + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index be53034183..540c1bb3b9 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -508,6 +508,8 @@ pub fn reset_fields(app: &PhotocraftApp, fields: &mut Map) { // Drop user params; keep private `__` chrome (and fixed keys outside the schema for `__spec`). let schema_keys: std::collections::HashSet = parse_spec(&spec).into_iter().map(|p| p.key).collect(); fields.retain(|k, _| k.starts_with("__") || !schema_keys.contains(k)); + // The eyedroppers' click order goes with the samples just dropped (Replace Color, #6280). + fields.remove("__order"); for p in parse_spec(&spec) { if let Some(v) = default_value(app, &command, &p) { fields.insert(p.key, v); @@ -783,16 +785,31 @@ pub(crate) fn color_eyedropper_armed(app: &PhotocraftApp) -> bool { /// Sample the merged image at document point (x, y) into the armed dialog's "From" colour. /// Returns true when the click was consumed, even off-image or over transparency, where nothing /// changes and the eyedropper stays armed (like the Curves picker). -pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { +/// With the Add to Sample eyedropper (or Shift) the click adds a sample, with Subtract from +/// Sample (or Alt) it subtracts one, as in Photoshop and Select › Color Range (#6280). +pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { let Some(id) = app.ui.dialogs.last().filter(|d| color_eyedropper_owns(&d.fields)).map(|d| d.id) else { return false; }; - if let Some(rgb) = crate::canvas::composite_color(app, x, y) - && let Some(d) = app.ui.dialog_mut(id) - { - d.fields.insert("color".into(), json!(crate::color_picker_ui::hex(rgb))); - // Where it was picked: Localized Color Clusters match the colour near this point (#4457). - d.fields.insert("points".into(), json!([[x.floor(), y.floor()]])); + let Some(rgb) = crate::canvas::composite_color(app, x, y) else { return true }; + let Some(mut f) = app.ui.dialogs.last().map(|d| d.fields.clone()) else { return true }; + let tool = f.get("__tool").and_then(Value::as_str); + let sample = !mods.shift && !mods.alt && tool.is_none_or(|t| t == "sample"); + // A first Add to Sample, before any sample, starts from the clicked colour too: one point + // matches through `color`, and Color Range's matcher starts its range there as well. + let add = mods.shift || (!mods.alt && tool == Some("add")); + let first_add = add && f.get("points").and_then(Value::as_array).is_none_or(Vec::is_empty); + if sample || first_add { + f.insert("color".into(), json!(crate::color_picker_ui::hex(rgb))); + } + // Where it was picked: Localized Color Clusters match the colour near this point (#4457); + // added and subtracted samples go to `points` / `subtractPoints` in click order. + crate::color_range_ui::pick(app, &mut f, [x, y], mods); + if let Some(order) = f.get("__order").cloned() { + f.insert("order".into(), order); + } + if let Some(d) = app.ui.dialog_mut(id) { + d.fields = f; } true } @@ -1034,9 +1051,21 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { // PhotoCraft's Color Picker, as everywhere else (#2144). clicked = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), &name).clicked(); if eyedropper { + // Photoshop's three eyedroppers (#6280), right to left here: Subtract + // from Sample, Add to Sample, Eyedropper. Clicking the chosen one again + // puts it away. let armed = f.get(COLOR_EYEDROPPER).and_then(Value::as_bool).unwrap_or(false); - if crate::icons::button(ui, "pipette", 24.0, armed, "Pick Color From Image").clicked() { - f.insert(COLOR_EYEDROPPER.into(), json!(!armed)); + let tool = f.get("__tool").and_then(Value::as_str).unwrap_or("sample").to_string(); + for (id, badge, label) in [ + ("subtract", "−", tl!("Subtract from Sample")), + ("add", "+", tl!("Add to Sample")), + ("sample", "", tl!("Pick Color From Image")), + ] { + let on = armed && tool == id; + if crate::color_range_ui::eyedropper(ui, badge, on, label).clicked() { + f.insert(COLOR_EYEDROPPER.into(), json!(!on)); + f.insert("__tool".into(), json!(id)); + } } } ui.label(egui::RichText::new(crate::color_picker_ui::hex(rgb)).color(t.text_dim).monospace()); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 036b085882..de9f389e23 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1535,18 +1535,92 @@ fn replace_color_eyedropper_samples_the_image() { assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour"); // #6279: armed as it opens, so the first click on the image samples. assert!(color_eyedropper_armed(&app)); - assert!(color_eyedropper_sample(&mut app, 4.0, 4.0)); + assert!(color_eyedropper_sample(&mut app, 4.0, 4.0, egui::Modifiers::NONE)); assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); // #4457: where it was picked, for Localized Color Clusters. assert_eq!(app.ui.dialogs.last().unwrap().fields["points"], json!([[4.0, 4.0]])); // Off-image: the click is consumed, nothing changes and the eyedropper stays armed. - assert!(color_eyedropper_sample(&mut app, -1.0, 4.0)); + assert!(color_eyedropper_sample(&mut app, -1.0, 4.0, egui::Modifiers::NONE)); assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); assert!(color_eyedropper_armed(&app)); // Disarmed, the dialog never claims the click. app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(false)); assert!(!color_eyedropper_armed(&app)); - assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0)); + assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0, egui::Modifiers::NONE)); +} + +/// #6280: Shift-click adds a sample and Alt-click subtracts one (as do the + and − eyedroppers), +/// in click order, as in Photoshop; a plain click starts over from the clicked colour. +#[test] +fn replace_color_shift_and_alt_clicks_add_and_subtract_samples() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + open(&mut app, REPLACE_COLOR).unwrap(); + let field = |app: &PhotocraftApp, k: &str| app.ui.dialogs.last().unwrap().fields.get(k).cloned().unwrap_or(Value::Null); + assert!(color_eyedropper_sample(&mut app, 2.0, 2.0, egui::Modifiers::NONE)); + assert!(color_eyedropper_sample(&mut app, 5.0, 5.0, egui::Modifiers::SHIFT)); + assert!(color_eyedropper_sample(&mut app, 9.0, 9.0, egui::Modifiers::ALT)); + assert_eq!(field(&app, "points"), json!([[2.0, 2.0], [5.0, 5.0]])); + assert_eq!(field(&app, "subtractPoints"), json!([[9.0, 9.0]])); + assert_eq!(field(&app, "order"), json!(["+", "+", "-"])); + assert_eq!(field(&app, "color"), json!("#00ff00"), "the From colour is the plain sample's"); + // The − eyedropper subtracts without a modifier; a plain click with the plain one starts over. + let id = app.ui.dialogs.last().unwrap().id; + app.ui.dialog_mut(id).unwrap().fields.insert("__tool".into(), json!("subtract")); + assert!(color_eyedropper_sample(&mut app, 3.0, 3.0, egui::Modifiers::NONE)); + assert_eq!(field(&app, "subtractPoints"), json!([[9.0, 9.0], [3.0, 3.0]])); + app.ui.dialog_mut(id).unwrap().fields.insert("__tool".into(), json!("sample")); + assert!(color_eyedropper_sample(&mut app, 7.0, 7.0, egui::Modifiers::NONE)); + assert_eq!((field(&app, "points"), field(&app, "subtractPoints")), (json!([[7.0, 7.0]]), json!([]))); +} + +/// A first click with Add to Sample, before any plain sample, takes the clicked colour as the +/// From colour, so the single-sample command replaces it, not the foreground colour (CodeRabbit +/// review on #10443). Color Range's matcher, used from the second sample on, also starts its +/// range at the first added colour. +#[test] +fn replace_color_first_add_to_sample_click_sets_the_from_colour() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let id = open(&mut app, REPLACE_COLOR).unwrap(); + let field = |app: &PhotocraftApp, k: &str| app.ui.dialogs.last().unwrap().fields.get(k).cloned().unwrap_or(Value::Null); + assert_ne!(field(&app, "color"), json!("#00ff00"), "the dialog starts from the foreground colour"); + for (tool, mods) in [("sample", egui::Modifiers::SHIFT), ("add", egui::Modifiers::NONE)] { + let mut fields = app.ui.dialogs.last().unwrap().fields.clone(); + reset_fields(&app, &mut fields); + fields.insert("__tool".into(), json!(tool)); + app.ui.dialog_mut(id).unwrap().fields = fields; + assert!(color_eyedropper_sample(&mut app, 4.0, 4.0, mods)); + assert_eq!(field(&app, "points"), json!([[4.0, 4.0]])); + assert_eq!(field(&app, "color"), json!("#00ff00"), "{tool}"); + } + // A later added sample leaves the From colour alone. + app.ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#123456")); + assert!(color_eyedropper_sample(&mut app, 6.0, 6.0, egui::Modifiers::SHIFT)); + assert_eq!(field(&app, "color"), json!("#123456")); +} + +/// Reset (Alt+Cancel) forgets the click order with the samples, so samples added afterwards +/// carry an order that fits them and the command takes it (CodeRabbit review on #10443). +#[test] +fn replace_color_reset_forgets_the_click_order() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let id = open(&mut app, REPLACE_COLOR).unwrap(); + assert!(color_eyedropper_sample(&mut app, 2.0, 2.0, egui::Modifiers::NONE)); + assert!(color_eyedropper_sample(&mut app, 9.0, 9.0, egui::Modifiers::ALT)); + let mut fields = app.ui.dialogs.last().unwrap().fields.clone(); + reset_fields(&app, &mut fields); + app.ui.dialog_mut(id).unwrap().fields = fields; + assert!(color_eyedropper_sample(&mut app, 5.0, 5.0, egui::Modifiers::SHIFT)); + assert!(color_eyedropper_sample(&mut app, 7.0, 7.0, egui::Modifiers::SHIFT)); + let f = app.ui.dialogs.last().unwrap().fields.clone(); + assert_eq!(f["order"], json!(["+", "+"]), "{f:?}"); + let p = json!({"color": f["color"], "points": f["points"], "order": f["order"], "hue": 30}); + app.session.execute(REPLACE_COLOR, p).unwrap(); } /// #4143: the eyedropper button disarms and re-arms the canvas picker (#6279: it opens armed). @@ -1627,7 +1701,7 @@ fn replace_color_localized_color_clusters() { h.run_steps(3); let _ = h.get_by_label("Localized Color Clusters"); h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true)); - assert!(color_eyedropper_sample(h.state_mut(), 2.0, 5.0)); + assert!(color_eyedropper_sample(h.state_mut(), 2.0, 5.0, egui::Modifiers::NONE)); h.get_by_label("Localized Color Clusters").click(); h.run_steps(2); let f = h.state().ui.dialogs.last().unwrap().fields.clone(); diff --git a/crates/ui-egui/src/dialogs/gallery_ui.rs b/crates/ui-egui/src/dialogs/gallery_ui.rs index 43c392c1e9..c8c41d87dd 100644 --- a/crates/ui-egui/src/dialogs/gallery_ui.rs +++ b/crates/ui-egui/src/dialogs/gallery_ui.rs @@ -840,7 +840,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } } if e.filter.uses_colours() { - ui.label(egui::RichText::new(tl!("Uses the foreground and background colours.")).color(t.text_faint).size(11.0)); + ui.label(egui::RichText::new(tl!("Uses the foreground and background colors.")).color(t.text_faint).size(11.0)); } }); // Effect layers (top of the list = applied last). diff --git a/crates/ui-egui/src/dialogs/guide_edit.rs b/crates/ui-egui/src/dialogs/guide_edit.rs index 70a2606999..b058ed208e 100644 --- a/crates/ui-egui/src/dialogs/guide_edit.rs +++ b/crates/ui-egui/src/dialogs/guide_edit.rs @@ -104,7 +104,9 @@ fn prepare(app: &PhotocraftApp, draft: &mut Draft, fields: &Map) let mut params = crate::new_guide_ui::params(app, fields); // Opening a fractional position in cm/percent rounds its display. Leaving the text and // orientation alone must not move the guide or consume Redo through that rounding. - if fields.get("position").and_then(Value::as_str) == Some(&draft.initial_position) + // Once the user edits Position, even a value equal to the original readout is intentional. + if !fields.get("__positionEdited").and_then(Value::as_bool).unwrap_or(false) + && fields.get("position").and_then(Value::as_str) == Some(&draft.initial_position) && (params.get("newOrientation").and_then(Value::as_str) == Some("vertical")) == draft.edit.original().vertical { params["position"] = serde_json::json!(draft.edit.original().position); diff --git a/crates/ui-egui/src/dialogs/jpeg_options_ui.rs b/crates/ui-egui/src/dialogs/jpeg_options_ui.rs index a44a042512..f3dd44df91 100644 --- a/crates/ui-egui/src/dialogs/jpeg_options_ui.rs +++ b/crates/ui-egui/src/dialogs/jpeg_options_ui.rs @@ -4,7 +4,8 @@ //! `photocraft_engine::file_cmds::jpeg_quality`; Format Options are Baseline ("Standard"), Baseline //! Optimized and Progressive, and the dialog shows the size the file will have. Matte and Scans //! aren't offered yet. Re-saving an opened JPEG starts at the file's own quality, as File › Save -//! keeps it (#4032). +//! keeps it (#4032). Otherwise the dialog starts at the quality and format it was last answered +//! with, also after a restart, as Photoshop's does (see [`Start::for_active`]). //! //! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written //! once answered. Cancel drops the save. Scripts skip the prompt by passing `quality` or @@ -138,16 +139,60 @@ impl Start { Start { quality: quality_from_percent(quality), own_quality: None, format: JpegFormat::Baseline } } - /// For the active document: its opened JPEG's own quality (`Document::file_encoding`), or - /// else the Export preferences' JPEG quality (the one Quick Export uses). + /// For the active document: the Format Options the dialog was last answered with, else + /// Baseline; and the quality of its opened JPEG (`Document::file_encoding`, which File › Save + /// keeps, #4032), else the quality last answered, else the Export preferences' JPEG quality + /// (the one Quick Export uses). pub fn for_active(app: &PhotocraftApp) -> Self { - match app.session.active().and_then(|st| st.doc.file_encoding.jpeg_quality) { + let remembered = remembered(app); + let start = match app.session.active().and_then(|st| st.doc.file_encoding.jpeg_quality) { Some(q) => Start::own(q), - None => Start::percent(app.session.prefs().export.jpeg_quality), - } + None => match remembered.quality { + Some(quality) => Start { quality, own_quality: None, format: JpegFormat::Baseline }, + None => Start::percent(app.session.prefs().export.jpeg_quality), + }, + }; + Start { format: remembered.format.unwrap_or(start.format), ..start } } } +/// Preferences ▸ remembered dialog settings: JPEG Options writes its last answer under this key +/// and starts the next dialog from it, as Photoshop does (it keeps it across restarts). There is +/// no command of this id; the key only names the dialog among the others. +const REMEMBER_KEY: &str = "file.jpegOptions"; + +/// What the dialog was last answered with; a value that no longer fits (a hand-edited +/// preferences file) is left out. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Remembered { + quality: Option, + format: Option, +} + +fn remembered(app: &PhotocraftApp) -> Remembered { + let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(REMEMBER_KEY) else { return Remembered::default() }; + Remembered { + quality: saved.get("quality").and_then(Value::as_u64).and_then(|q| u8::try_from(q).ok()).filter(|&q| q <= MAX_QUALITY), + format: saved.get("jpegFormat").and_then(Value::as_str).and_then(JpegFormat::parse), + } +} + +/// Records an answered dialog for the next one. A quality left on the opened file's own is not +/// an answer: the earlier one stays, so saving a series of opened JPEGs doesn't forget what a +/// new document was last saved at. +fn remember(app: &mut PhotocraftApp, choice: JpegChoice) { + let before = remembered(app); + let quality = choice.quality.or(before.quality); + let mut saved = serde_json::Map::new(); + if let Some(q) = quality { + saved.insert("quality".into(), q.into()); + } + saved.insert("jpegFormat".into(), choice.format.name().into()); + app.session.prefs.edit(|p| { + p.dialogs.insert(REMEMBER_KEY.into(), Value::Object(saved)); + }); +} + /// A save waiting on the JPEG Options answer. pub struct Prompt { /// The document that requested the save, even if tabs change while this is open. @@ -243,7 +288,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { confirm(app, ctx); } else if cancel { app.jpeg_options = None; - app.ui.status = tl!("Save cancelled").into(); + app.ui.status = tl!("Save canceled").into(); app.ui.status_error = false; } } @@ -256,6 +301,7 @@ pub fn confirm(app: &mut PhotocraftApp, ctx: &egui::Context) { // quality out, so a replay keeps the file's own quality too, as File › Save does (#4032). let own = p.own_quality.filter(|&q| quality_from_percent(u32::from(q)) == p.quality); let choice = JpegChoice { quality: own.is_none().then_some(p.quality), format: p.format }; + remember(app, choice); let step = if p.record == "file.save" { // A plain Save writes whichever file the action is played on (#3531), with the answer. plain_save_step(Some(choice)) diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 29396f6022..65772e1573 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -324,6 +324,7 @@ fn values_of(e: &Effect, light: f32) -> Value { set(&mut v, gradient_field::KEY, gradient_field::stops_json(stops)); set(&mut v, gradient_field::OPACITY_KEY, gradient_field::opacity_json(&g.opacity_stops)); set(&mut v, "reverse", json!(g.reverse)); + set(&mut v, "offset", json!([g.offset.0, g.offset.1])); set( &mut v, "style", @@ -535,6 +536,82 @@ pub fn drag_shadow(f: &mut Map, start: bool, total: [f64; 2]) { set_param(f, &id, "distance", json!(d.round().clamp(0.0, 30000.0))); } +/// Whether the selected page is a Gradient Overlay, which a drag on the image moves while the +/// dialog is open, as in Photoshop (#10763; [`drag_gradient`]). +pub fn drags_gradient(f: &Map) -> bool { + let selected = f.get("selected").and_then(Value::as_str).unwrap_or_default(); + entry(f, selected).and_then(|e| e.get("kind")).and_then(Value::as_str) == Some("gradientOverlay") +} + +/// Ends a gradient drag's stored origin ([`drag_gradient`]): the canvas calls this whenever its +/// gradient branch is inactive on a Layer Style dialog (another page chosen under a held press, +/// say), so a Gradient Overlay page chosen again starts from the offset shown, not from an origin +/// and a baseline taken before the pointer travelled on another page. +pub fn end_gradient_drag(f: &mut Map) { + f.remove("__gradientDrag"); +} + +/// The width and height of the layer the dialog `f` is open on, what a Gradient Overlay's offset +/// is a fraction of (`photocraft_compose::layer_bounds`, what the renderer paints against): `None` +/// once that layer is gone or while it is empty (a gradient paints nothing there), when a drag on +/// the image has nothing to move and the Hand tool pans. +pub fn gradient_layer_bounds(session: &photocraft_engine::Session, f: &Map) -> Option<[f64; 2]> { + let id = f.get("layer").and_then(Value::as_u64)?; + let st = session.active()?; + let b = photocraft_compose::layer_bounds(st.doc.layer(photocraft_doc::LayerId(id))?, st.doc.bounds()); + let [w, h] = [f64::from(b.width()), f64::from(b.height())]; + (w > 0.0 && h > 0.0).then_some([w, h]) +} + +/// A drag on the image with a Gradient Overlay page selected: `start` is true on the press (it +/// records the gradient's offset then, as does a change of the selected instance under a held +/// press), `total` the pointer's movement since in document pixels +/// and `bounds` the layer's width and height. The gradient's centre moves with the pointer, kept +/// as a fraction of the layer's bounds (`offset`, what the renderer takes), to a thousandth. +pub fn drag_gradient(f: &mut Map, start: bool, total: [f64; 2], bounds: [f64; 2]) { + const KEY: &str = "__gradientDrag"; + let Some(id) = f.get("selected").and_then(Value::as_str).map(str::to_string).filter(|_| drags_gradient(f)) else { return }; + let Some(e) = entry(f, &id) else { return }; + // The offset the gradient shows: `offset` as stored when its first two elements are finite + // numbers (the only form the engine applies, and all it reads of a longer array), else the + // effect's own (its `fx` snapshot), else the centre + // (None: never set); within ±4 of the layer's size, as the renderer keeps it, so the drag + // starts from where the gradient is seen. + let pair = |v: Option<&Value>| { + let a = v?.as_array()?; + let (x, y) = (a.first()?.as_f64()?, a.get(1)?.as_f64()?); + (x.is_finite() && y.is_finite()).then(|| [x.clamp(-4.0, 4.0), y.clamp(-4.0, 4.0)]) + }; + let shown = pair(e.get("params").and_then(|p| p.get("offset"))).or_else(|| pair(e.get("fx").and_then(|fx| fx.pointer("/GradientOverlay/gradient/offset")))); + // The origin: the offset shown, the instance it is for and the pointer's total then. Taken on + // the press, when there is none, and when the page changed under a held press (another + // instance selected, or a Gradient Overlay page chosen during a press that began elsewhere): + // that instance then moves by the pointer's travel from this moment, not from the press. + let read = |v: Option<&Value>| { + let a = v?.as_array()?; + Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?]) + }; + if start || f.get(KEY).and_then(|o| o.get("id")).and_then(Value::as_str) != Some(id.as_str()) { + f.insert(KEY.into(), json!({"id": id, "origin": shown.unwrap_or([0.0, 0.0]), "base": total})); + } + let Some(origin) = f.get(KEY) else { return }; + let (Some([x0, y0]), Some([bx, by])) = (read(origin.get("origin")), read(origin.get("base"))) else { return }; + let [w, h] = [bounds[0].max(1.0), bounds[1].max(1.0)]; + // Kept within what the renderer takes (±4 of the layer's size), so the next drag starts from + // where the gradient shows. + let (x, y) = ((x0 + (total[0] - bx) / w).clamp(-4.0, 4.0), (y0 + (total[1] - by) / h).clamp(-4.0, 4.0)); + if !(x.is_finite() && y.is_finite()) { + return; + } + // A press that has not moved the gradient (or a drag back to where it began, with nothing + // written since) leaves the offset as it is: a stored one to its full precision, none where + // there was none. + if x == x0 && y == y0 && shown.is_none_or(|s| s == [x0, y0]) { + return; + } + set_param(f, &id, "offset", json!([(x * 1000.0).round() / 1000.0, (y * 1000.0).round() / 1000.0])); +} + pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map { initial_fields_with(layer, select, light, Map::new()) } diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index ab221b53b1..dbf0137293 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -33,6 +33,160 @@ fn dragging_on_the_image_moves_the_selected_shadow() { assert_eq!(params(&f, "fx1"), (120.0, 0.0)); } +/// Review: the drag starts from the offset the gradient shows: a stored pair beyond ±4 at the +/// clamp, a malformed pair at the effect's own offset (its `fx` snapshot) or, without one, at the +/// centre, since the engine applies `offset` only when it is two finite numbers. +#[test] +fn a_drag_starts_from_the_offset_the_gradient_shows() { + let mut f = Map::new(); + f.insert("selected".into(), json!("fx1")); + f.insert( + "effects".into(), + json!([ + {"id": "fx1", "kind": "gradientOverlay", "on": true, "params": {"offset": [5.0, 0.0]}}, + {"id": "fx2", "kind": "gradientOverlay", "on": true, "params": {"offset": [0.5, null]}}, + {"id": "fx3", "kind": "gradientOverlay", "on": true, "params": {"offset": [0.5, null]}, "fx": {"GradientOverlay": {"gradient": {"offset": [0.2, 0.3]}}}}, + {"id": "fx4", "kind": "gradientOverlay", "on": true, "params": {"offset": [0.1, 0.2, 9]}}, + ]), + ); + let offset = |f: &Map, id: &str| entry(f, id).unwrap()["params"].get("offset").cloned(); + // Stored at 5, shown at 4: a short drag left moves it from 4, not from 5. + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([5.0, 0.0])), "a plain press leaves it"); + drag_gradient(&mut f, false, [-20.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([3.9, 0.0]))); + // A malformed pair without a snapshot: the renderer shows the centre, so the drag starts there. + f.insert("selected".into(), json!("fx2")); + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.5, null])), "a plain press leaves it"); + drag_gradient(&mut f, false, [50.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.25, 0.0]))); + // With a snapshot: the renderer shows the effect's own offset, so the drag starts there. + f.insert("selected".into(), json!("fx3")); + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + drag_gradient(&mut f, false, [50.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx3"), Some(json!([0.45, 0.3]))); + // Three elements: the first two count, as the engine reads them. + f.insert("selected".into(), json!("fx4")); + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx4"), Some(json!([0.1, 0.2, 9])), "a plain press leaves it"); + drag_gradient(&mut f, false, [50.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx4"), Some(json!([0.35, 0.2]))); +} + +/// Review: with the dialog's layer gone, a drag on the image has nothing to move, so the Hand +/// tool pans as usual: `gradient_layer_bounds` finds the dialog's layer, or nothing. +#[test] +fn the_gradient_drag_needs_its_layer() { + let mut s = session(); + let empty = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + let mut f = Map::new(); + f.insert("layer".into(), json!(id.0)); + assert_eq!(gradient_layer_bounds(&s, &f), Some([64.0, 64.0]), "the dialog's layer"); + // An empty layer paints no gradient (review): nothing to move, the Hand tool pans. + f.insert("layer".into(), json!(empty.0)); + assert_eq!(gradient_layer_bounds(&s, &f), None, "an empty layer"); + f.insert("layer".into(), json!(id.0 + 1000)); + assert_eq!(gradient_layer_bounds(&s, &f), None, "a layer that is gone"); + f.remove("layer"); + assert_eq!(gradient_layer_bounds(&s, &f), None, "a dialog without a layer"); +} + +/// Review: the selected instance changing under a held press, or a Gradient Overlay page chosen +/// during a press that began on another page, moves that instance from its own offset by the +/// pointer's travel from that moment, not from the press. +#[test] +fn the_drag_rebases_when_the_selected_effect_changes() { + let mut f = Map::new(); + f.insert("selected".into(), json!("fx3")); + f.insert( + "effects".into(), + json!([ + {"id": "fx1", "kind": "gradientOverlay", "on": true, "params": {}}, + {"id": "fx2", "kind": "gradientOverlay", "on": true, "params": {"offset": [0.1, 0.1]}}, + {"id": "fx3", "kind": "dropShadow", "on": true, "params": {}}, + ]), + ); + let offset = |f: &Map, id: &str| entry(f, id).unwrap()["params"].get("offset").cloned(); + // The press began on the shadow page: nothing for the gradient, until its page is chosen. + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + drag_gradient(&mut f, false, [40.0, 0.0], [200.0, 100.0]); + f.insert("selected".into(), json!("fx1")); + drag_gradient(&mut f, false, [40.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), None, "nothing moved since the page was chosen"); + drag_gradient(&mut f, false, [60.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([0.1, 0.0])), "20 px on from the switch"); + // Another instance selected mid-press: it moves by the travel from here, from its own offset. + f.insert("selected".into(), json!("fx2")); + drag_gradient(&mut f, false, [60.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.1, 0.1])), "nothing moved yet"); + drag_gradient(&mut f, false, [80.0, 20.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.2, 0.3]))); + assert_eq!(offset(&f, "fx1"), Some(json!([0.1, 0.0])), "the first one stays"); + // The page left and the same instance chosen again under the held press (the canvas ends the + // stored drag while off the page): it starts over from the offset shown, not from the old + // origin and baseline, so the travel made meanwhile doesn't land on it. + f.insert("selected".into(), json!("fx3")); + end_gradient_drag(&mut f); + f.insert("selected".into(), json!("fx2")); + drag_gradient(&mut f, false, [120.0, 20.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.2, 0.3])), "nothing moved since the page came back"); + drag_gradient(&mut f, false, [140.0, 20.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.3, 0.3]))); +} + +/// #10763: with a Gradient Overlay page selected, a drag on the image moves the gradient: its +/// centre follows the pointer as a fraction of the layer's bounds. +#[test] +fn dragging_on_the_image_moves_the_selected_gradient_overlay() { + let mut f = Map::new(); + f.insert("selected".into(), json!("fx1")); + f.insert( + "effects".into(), + json!([ + {"id": "fx1", "kind": "gradientOverlay", "on": true, "params": {"angle": 90.0, "scale": 100.0}}, + {"id": "fx2", "kind": "gradientOverlay", "on": true, "params": {"angle": 90.0, "offset": [0.1, 0.1]}}, + ]), + ); + assert!(drags_gradient(&f)); + let offset = |f: &Map, id: &str| entry(f, id).unwrap()["params"].get("offset").cloned(); + // The press keeps the gradient where it is (centred, no offset yet, and none written); 50 × 25 + // px on a 200 × 100 layer move it a quarter of the way each. + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), None, "a plain press writes nothing"); + drag_gradient(&mut f, false, [50.0, 25.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([0.25, 0.25]))); + assert_eq!(offset(&f, "fx2"), Some(json!([0.1, 0.1])), "another instance is left alone"); + // Back and past the start: the way the pointer went, from where the drag began. + drag_gradient(&mut f, false, [-100.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([-0.5, 0.0]))); + // A new drag starts from the offset the last one left. + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + drag_gradient(&mut f, false, [20.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([-0.4, 0.0]))); + // A press that moves nothing keeps a precise offset as it is; a drag that comes back to where + // it began still writes, since the gradient moved in between. The offset stays within ±4. + f.insert("selected".into(), json!("fx2")); + set_param(&mut f, "fx2", "offset", json!([0.123456, 0.1])); + drag_gradient(&mut f, true, [0.0, 0.0], [200.0, 100.0]); + drag_gradient(&mut f, false, [0.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.123456, 0.1])), "nothing moved: nothing rounded"); + drag_gradient(&mut f, false, [20.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.223, 0.1]))); + drag_gradient(&mut f, false, [0.0, 0.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([0.123, 0.1])), "back at the start: the start is written"); + drag_gradient(&mut f, false, [100_000.0, -100_000.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx2"), Some(json!([4.0, -4.0])), "clamped as the renderer clamps"); + // Not on a gradient page: nothing moves. + f.insert("selected".into(), json!(BLENDING)); + assert!(!drags_gradient(&f)); + drag_gradient(&mut f, true, [50.0, 50.0], [200.0, 100.0]); + assert_eq!(offset(&f, "fx1"), Some(json!([-0.4, 0.0]))); +} + fn session() -> photocraft_engine::Session { let mut s = photocraft_engine::Session::new(); s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index 5d10bd82b9..f5263b1e81 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -268,6 +268,12 @@ pub struct LiquifyDialog { pub preview_ms: f64, /// The smart filter being edited: OK updates it instead of adding a new Liquify filter. smart_filter: Option, + /// Preview (P): off, the image is drawn unwarped while strokes still change the field, as + /// Photoshop's Preview checkbox does (#7905). Every opening starts with it on. + pub preview: bool, + /// The undisplaced field drawn while Preview is off. It is as large as `field`, so it exists + /// only while Preview is off: made when Preview is turned off, freed when it's turned back on. + identity: Option, } fn union(a: Option<[usize; 4]>, b: [usize; 4]) -> Option<[usize; 4]> { @@ -300,6 +306,7 @@ impl LiquifyDialog { "strokes": self.strokes.len() + usize::from(self.cur.is_some()), "redo": self.redo.len(), "meshSize": self.cell, + "preview": self.preview, "maxDisplacement": self.field.max_displacement(), "proxy": [self.proxy.w, self.proxy.h], "dabMs": self.dab_ms, @@ -441,16 +448,29 @@ impl LiquifyDialog { /// Re-renders the dirty proxy pixels into `out` (the texture upload happens in `show`). fn render_dirty(&mut self) { if let Some(r) = self.dirty { + let field = self.identity.as_ref().filter(|_| !self.preview).unwrap_or(&self.field); if let Some(source) = &self.native_proxy { let bounds = Rect::new(0, 0, self.proxy.w as i32, self.proxy.h as i32); let dirty = Rect::new(r[0] as i32, r[1] as i32, r[2] as i32, r[3] as i32); - render_components(source, bounds, &self.field, self.proxy.scale, &self.target, bounds, dirty, &mut self.out); + render_components(source, bounds, field, self.proxy.scale, &self.target, bounds, dirty, &mut self.out); } else { - self.proxy.render(&self.field, r, &mut self.out); + self.proxy.render(field, r, &mut self.out); } } } + /// Turns Preview on or off: the whole preview is redrawn with, or without, the warp. + pub fn set_preview(&mut self, on: bool) { + if on == self.preview { + return; + } + self.identity = (!on).then(|| LiquifyField::new(self.canvas, self.cell)); + self.preview = on; + self.dirty = Some([0, 0, self.proxy.w, self.proxy.h]); + self.render_dirty(); + self.view_dirty = self.view_bounds; + } + /// Builds or updates the visible source-resolution viewport. At ordinary zoom the whole-layer /// proxy remains cheaper; above 100%, a full-resolution crop is enough to fill the preview. fn update_view_preview(&mut self, ctx: &egui::Context, area: ERect) { @@ -497,10 +517,11 @@ impl LiquifyDialog { return; } let started = crate::gpu_canvas::now_ms(); + let field = self.identity.as_ref().filter(|_| !self.preview).unwrap_or(&self.field); let rendered = if self.native_proxy.is_some() { - render_components(&self.source, self.canvas, &self.field, 1.0, &self.target, bounds, dirty, &mut self.view_out) + render_components(&self.source, self.canvas, field, 1.0, &self.target, bounds, dirty, &mut self.view_out) } else { - ProxyImage::render_full_resolution(&self.source, &self.field, bounds, dirty, &mut self.view_out, &mut self.view_source_scratch) + ProxyImage::render_full_resolution(&self.source, field, bounds, dirty, &mut self.view_out, &mut self.view_source_scratch) }; if !rendered { self.view_bounds = None; @@ -654,6 +675,8 @@ fn open_on( dab_ms: 0.0, preview_ms: 0.0, smart_filter, + preview: true, + identity: None, }; // A sensible starting brush (about a tenth of the image), then the settings last used, so // Liquify opens as it was left (#418). Saved values are clamped; a bad one is skipped. @@ -728,6 +751,9 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { applied?; let num = |k: &str| ui.get(k).and_then(Value::as_f64).map(|v| v as f32); let flag = |k: &str| ui.get(k).and_then(Value::as_bool); + if let Some(on) = flag("preview") { + d.set_preview(on); + } if flag("undo") == Some(true) { d.undo(); } @@ -847,6 +873,11 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { _ => 1.0, }; } + // P toggles Preview, as in Photoshop (#7905). + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::P)) { + let on = !d.preview; + d.set_preview(on); + } // Ctrl+H (Hide Extras) toggles the red freeze-mask overlay; the mask itself stays active. if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) { d.opts.show_mask = !d.opts.show_mask; @@ -1086,7 +1117,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let right = ERect::from_min_size(pos2(body.right() - RIGHT_W, body.top()), vec2(RIGHT_W, body.height())); painter.rect_filled(right, 0.0, t.dock); painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); - let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 12.0)))); + // The properties scroll above the Preview row and the buttons. + let props_rect = ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, (right.bottom() - 84.0).max(right.top() + 12.0))); + let mut props = ui.new_child(egui::UiBuilder::new().max_rect(props_rect)); egui::ScrollArea::vertical().id_salt("liquify-props").show(&mut props, |ui| { ui.spacing_mut().item_spacing.y = 6.0; widgets::section_label(ui, tl!("Brush Tool Options")); @@ -1161,6 +1194,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { .size(11.0), ); }); + // Preview, centred above OK and Cancel as in Photoshop (#7905). + let label_w = ui.fonts_mut(|f| f.layout_no_wrap(tl!("Preview").to_owned(), egui::TextStyle::Body.resolve(ui.style()), t.text).size().x); + let row_w = (label_w + 30.0).min(RIGHT_W - 28.0); + let preview_row = ERect::from_center_size(pos2(right.center().x, right.bottom() - 64.0), vec2(row_w, 24.0)); + let mut pr = ui.new_child(egui::UiBuilder::new().max_rect(preview_row).layout(egui::Layout::left_to_right(egui::Align::Center))); + let mut preview = d.preview; + if widgets::checkbox(&mut pr, &mut preview, tl!("Preview")).changed() { + d.set_preview(preview); + } // Footer buttons. let foot = ERect::from_min_size(pos2(right.left() + 14.0, right.bottom() - 48.0), vec2(RIGHT_W - 28.0, 32.0)); let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center))); diff --git a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs index 8ff60e1429..533494a6ea 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -1024,3 +1024,131 @@ fn workspaces_open_on_a_smart_object_with_its_filter_mask_targeted() { let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { panic!("not a smart object") }; assert_eq!(sm.smart_filters.iter().map(|f| f.command.as_str()).collect::>(), ["filter.blur.gaussianBlur", photocraft_engine::distort_cmds::LIQUIFY]); } + +/// Preview off shows the image unwarped while strokes still change the field, and P turns it back +/// on, as Photoshop's Liquify Preview checkbox does (#7905). Each opening starts with it on. +#[test] +fn preview_off_shows_the_original_and_p_toggles_it() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let render = |d: &LiquifyDialog, field: &LiquifyField| { + let mut out = vec![[0u8; 4]; d.proxy.w * d.proxy.h]; + d.proxy.render(field, [0, 0, d.proxy.w, d.proxy.h], &mut out); + out + }; + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.preview && d.describe()["preview"] == json!(true), "Liquify opens with Preview on"); + let original = render(d, &LiquifyField::new(d.canvas, d.cell)); + let stroke = |app: &mut PhotocraftApp, y: f64| { + for ev in [ToolEvent::Down { x: 35.0, y, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y, pressure: 1.0 }, ToolEvent::Up { x: 60.0, y }] { + pointer(app, ev, egui::Modifiers::NONE); + } + }; + control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); + stroke(&mut app, 40.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_ne!(d.out, original, "the warp shows"); + + let r = control(&mut app, &json!({"preview": false})).unwrap(); + assert_eq!(r["preview"], json!(false)); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.out, original, "Preview off: the image as it was"); + // A stroke with Preview off still warps the field, unseen. + stroke(&mut app, 30.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 2); + assert_eq!(d.out, original, "still unwarped while Preview is off"); + { + let d = app.distort.liquify.as_mut().unwrap(); + d.zoom = 2.0; + d.view_bounds = Some(Rect::new(0, 0, 20, 20)); + d.view_dirty = None; + } + + // P turns it back on, with both strokes. + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + ctx.begin_pass(input); + keys(&mut app, &ctx); + ctx.end_pass().textures_delta.clear(); + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.preview); + assert_eq!(d.out, render(d, &d.field), "Preview on: the warp of both strokes"); + assert_eq!(d.view_dirty, d.view_bounds, "the zoomed preview is redrawn too"); +} + +/// A forward-warp stroke across the test layer, at row `y`. +fn warp_stroke(app: &mut PhotocraftApp, y: f64) { + for ev in [ToolEvent::Down { x: 35.0, y, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y, pressure: 1.0 }, ToolEvent::Up { x: 60.0, y }] { + pointer(app, ev, egui::Modifiers::NONE); + } +} + +/// The active layer's pixels over the whole document. +fn layer_pixels(app: &PhotocraftApp) -> Vec { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 120, 80)) +} + +/// With Preview off, a stroke changes the displacement field but the display stays the original +/// image (#7905). +#[test] +fn a_stroke_with_preview_off_changes_the_field_but_not_the_display() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40, "preview": false})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + let (field_before, shown_before) = (d.field.clone(), d.out.clone()); + assert_eq!(d.field.max_displacement(), 0.0); + warp_stroke(&mut app, 40.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_ne!(d.field, field_before, "the stroke changes the field"); + assert!(d.field.max_displacement() > 3.0); + assert_eq!(d.out, shown_before, "the display does not change"); +} + +/// OK with Preview off applies the warp: the layer ends up exactly as it does when the same stroke +/// is committed with Preview on. +#[test] +fn ok_with_preview_off_applies_the_warp() { + let ctx = egui::Context::default(); + let commit_with = |preview: bool| { + let mut app = app_with_layer(); + let before = layer_pixels(&app); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40, "preview": preview})).unwrap(); + warp_stroke(&mut app, 40.0); + let past = app.session.active().unwrap().history.past_len(); + control(&mut app, &json!({"commit": true})).unwrap(); + assert!(app.distort.liquify.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), past + 1, "one Liquify step"); + (before, layer_pixels(&app)) + }; + let (before, unpreviewed) = commit_with(false); + assert_ne!(unpreviewed, before, "OK with Preview off warps the layer"); + assert_eq!(unpreviewed, commit_with(true).1, "the same warp as with Preview on"); +} + +/// The identity field (as large as the image's field) exists only while Preview is off: turning +/// Preview back on frees it, and closing the dialog drops it. +#[test] +fn the_identity_field_exists_only_while_preview_is_off() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let identity = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().identity.is_some(); + assert!(!identity(&app), "not made while Preview is on"); + control(&mut app, &json!({"preview": false})).unwrap(); + assert!(identity(&app)); + control(&mut app, &json!({"preview": true})).unwrap(); + assert!(!identity(&app), "freed when Preview is turned back on"); + control(&mut app, &json!({"preview": false})).unwrap(); + assert!(identity(&app), "made again when Preview is turned off again"); + control(&mut app, &json!({"cancel": true})).unwrap(); + assert!(app.distort.liquify.is_none(), "closing drops the dialog and its identity field"); + open(&mut app, &ctx).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.preview && d.identity.is_none(), "a new opening starts with Preview on and no identity field"); +} diff --git a/crates/ui-egui/src/dialogs/new_guide_ui.rs b/crates/ui-egui/src/dialogs/new_guide_ui.rs index 25b058ea87..794a126da4 100644 --- a/crates/ui-egui/src/dialogs/new_guide_ui.rs +++ b/crates/ui-egui/src/dialogs/new_guide_ui.rs @@ -173,7 +173,17 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { }); ui.end_row(); let position_label = ui.label(tl!("Position")); - ui.add(egui::TextEdit::singleline(&mut position).desired_width(120.0)).labelled_by(position_label.id); + let response = ui.add(egui::TextEdit::singleline(&mut position).desired_width(120.0)).labelled_by(position_label.id); + if ui.is_enabled() { + crate::field_tab::register(ui.ctx(), response.id); + } + if response.gained_focus() { + crate::field_tab::select_all(ui.ctx(), response.id, &position); + } + if response.changed() && f.contains_key(EDIT) { + // A deliberately retyped rounded readout is a new position, not the untouched one. + f.insert("__positionEdited".into(), json!(true)); + } ui.end_row(); ui.label(tl!("Color")); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/dialogs/new_guide_ui/tests.rs b/crates/ui-egui/src/dialogs/new_guide_ui/tests.rs index c08b6d4948..c0c732f0f7 100644 --- a/crates/ui-egui/src/dialogs/new_guide_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/new_guide_ui/tests.rs @@ -154,6 +154,104 @@ fn the_last_position_reopens_in_whatever_the_ruler_unit_is_now() { } } +#[test] +fn position_tab_and_shift_tab_select_all_in_new_and_edit_dialogs() { + use egui_kittest::{Harness, kittest::Queryable}; + + for editing in [false, true] { + for modifiers in [egui::Modifiers::NONE, egui::Modifiers::SHIFT] { + let (mut app, ctx) = app("pixels"); + if editing { + app.run(COMMAND, json!({"orientation": "vertical", "position": 12.5})).unwrap(); + crate::guide_select::select(&mut app, true, 0); + } + let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + let d = if editing { open_edit(h.state_mut()).unwrap() } else { open(h.state_mut(), &ctx) }; + h.run_steps(3); + h.key_press_modifiers(modifiers, egui::Key::Tab); + h.run_steps(3); + assert!(h.get_by_label("Position").is_focused()); + h.event(egui::Event::Text("1 in".into())); + h.run_steps(3); + assert_eq!(h.state_mut().ui.dialog_mut(d).unwrap().fields["position"], "1 in", "typing replaces the full readout"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(guides(h.state()), if editing { (vec![], vec![100.0]) } else { (vec![100.0], vec![]) }); + } + } +} + +#[test] +fn focusing_and_recolouring_preserve_the_exact_guide_position() { + use egui_kittest::{Harness, kittest::Queryable}; + + for (rulers, original) in [("pixels", 12.5), ("cm", 123.45678901234567), ("percent", -1e-100)] { + for recolour in [false, true] { + let (mut app, _) = app(rulers); + app.run(COMMAND, json!({"orientation": "vertical", "position": original})).unwrap(); + app.run("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": original + 1.0})).unwrap(); + assert!(app.session.undo()); + crate::guide_select::select(&mut app, true, 0); + let history = app.session.active().unwrap().history.past_len(); + let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + let d = open_edit(h.state_mut()).unwrap(); + if rulers == "pixels" { + assert_eq!(h.state_mut().ui.dialog_mut(d).unwrap().fields["position"], "13 px"); + } + h.run_steps(3); + h.get_by_label("Position").click(); + h.run_steps(3); + if recolour { + h.state_mut().ui.dialog_mut(d).unwrap().fields.insert("color".into(), json!("magenta")); + } + crate::guide_edit::sync(h.state_mut()); + assert_eq!(edit_preview(h.state(), &h.state().session.active().unwrap().doc).unwrap().vertical, vec![original]); + assert_eq!(guides(h.state()).1, vec![original], "preview must not modify the document"); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + assert_eq!(guides(h.state()).1, vec![original]); + if recolour { + assert_eq!(color_of(h.state(), true, original), Some([255, 0, 255])); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1); + assert!(h.state_mut().session.undo()); + assert_eq!(guides(h.state()).1, vec![original]); + } else { + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); + assert!(h.state().session.active().unwrap().history.can_redo(), "focus alone must preserve Redo"); + } + } + } +} + +#[test] +fn retyping_the_rounded_readout_is_an_intentional_position_edit() { + use egui_kittest::{Harness, kittest::Queryable}; + + let (mut app, _) = app("pixels"); + app.run(COMMAND, json!({"orientation": "vertical", "position": 12.5})).unwrap(); + crate::guide_select::select(&mut app, true, 0); + let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + let d = open_edit(h.state_mut()).unwrap(); + h.run_steps(3); + h.get_by_label("Position").click(); + h.run_steps(3); + h.event(egui::Event::Text("20 px".into())); + h.run_steps(3); + assert_eq!(h.state_mut().ui.dialog_mut(d).unwrap().fields["position"], "20 px", "click focus selects all"); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("13 px".into())); + h.run_steps(3); + crate::guide_edit::sync(h.state_mut()); + assert_eq!(edit_preview(h.state(), &h.state().session.active().unwrap().doc).unwrap().vertical, vec![13.0]); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + assert_eq!(guides(h.state()).1, vec![13.0]); + assert!(h.state_mut().session.undo()); + assert_eq!(guides(h.state()).1, vec![12.5]); +} + // These regressions exercise the ordinary dialog handlers, not a separate model. /// Open a draft on the first of two guides and propose moving it to 30 px. fn edit_fixture() -> (PhotocraftApp, u64) { diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index bcd9f0b7b9..78691112c0 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -207,7 +207,7 @@ pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result Result Result PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); + app.session + .edit("Paint red", |doc, _| { + let surface = doc.layers[0].surface_mut().unwrap(); + surface.fill_rect(Rect::new(0, 0, 8, 8), &photocraft_raster::from_rgba(&surface.format(), RED)); + Ok(()) + }) + .unwrap(); + let add = if adjustment { "layer.newAdjustmentLayer.invert" } else { "layer.layerMask.revealAll" }; + app.run(add, json!({})).unwrap(); + assert!(app.ui.mask_target); + app.ui.tool = Tool::Eyedropper; + app +} + +fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) { + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("Paint mask", |doc, _| { + doc.layer_mut(layer).unwrap().mask.as_mut().unwrap().surface.fill_rect(rect, &[gray]); + Ok(()) + }) + .unwrap(); +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) { + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y }, mods); +} + +fn gray(value: f32) -> [f32; 4] { + [value, value, value, 1.0] +} + +/// Both measured modes pick white and mid-grey from the selected mask on either layer kind. +#[test] +fn targeted_pixel_and_adjustment_masks_supply_point_samples() { + for adjustment in [false, true] { + let mut app = app_with_mask(adjustment); + paint_mask(&mut app, Rect::new(2, 2, 3, 3), 0.5); + for mode in ["current", "currentAndBelow"] { + app.ui.tool_options.eyedropper_sample = mode.into(); + app.run("tools.setColors", json!({"foreground": "#222222"})).unwrap(); + click(&mut app, 1.5, 1.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, gray(1.0), "adjustment={adjustment} {mode}"); + click(&mut app, 2.5, 2.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, gray(128.0 / 255.0), "adjustment={adjustment} {mode}"); + } + } +} + +/// The average at the corner counts only four in-canvas mask pixels and Alt writes background. +#[test] +fn mask_average_clips_at_canvas_edge_and_alt_sets_background() { + let mut app = app_with_mask(false); + paint_mask(&mut app, Rect::new(0, 0, 1, 2), 0.0); + app.ui.tool_options.eyedropper_sample = "currentAndBelow".into(); + app.ui.tool_options.eyedropper_size = 3; + app.run("tools.setColors", json!({"foreground": [0.2, 0.2, 0.2, 1.0], "background": [0.8, 0.8, 0.8, 1.0]})).unwrap(); + let foreground = app.session.tools.foreground; + click(&mut app, 0.5, 0.5, Modifiers::ALT); + assert_eq!(app.session.tools.background, gray(0.5)); + assert_eq!(app.session.tools.foreground, foreground); +} + +/// Composite modes use the image, and selecting contents restores the same sampling as before. +#[test] +fn composite_modes_and_pixel_targets_still_sample_the_image() { + let mut app = app_with_mask(true); + for mode in ["all", "allNoAdjustments", "currentAndBelowNoAdjustments"] { + app.ui.tool_options.eyedropper_sample = mode.into(); + let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": mode})).unwrap(); + let [r, g, b, _]: [f32; 4] = serde_json::from_value(sample).unwrap(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, gray(photocraft_color::convert::rgb_to_gray([r, g, b])), "{mode}"); + } + // An adjustment's content thumbnail can still route painting to its mask. That is not an + // explicit Eyedropper target. + app.run("channel.target.composite", json!({})).unwrap(); + assert!(!app.ui.mask_target); + app.ui.tool_options.eyedropper_sample = "current".into(); + let before = app.session.tools.foreground; + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, before, "the adjustment alone has no image pixels"); + + let mut app = app_with_mask(false); + app.run("channel.target.composite", json!({})).unwrap(); + for mode in ["current", "currentAndBelow"] { + app.ui.tool_options.eyedropper_sample = mode.into(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, RED, "{mode}"); + } +} + +/// A white raster mask beside another selected target cannot take over that target's sample. +#[test] +fn vector_alpha_quick_mask_and_temporary_samples_keep_their_source() { + let red_gray = gray(photocraft_color::convert::rgb_to_gray([1.0, 0.0, 0.0])); + let mut app = app_with_mask(false); + app.ui.tool_options.eyedropper_sample = "current".into(); + app.ui.tool = Tool::Brush; + click(&mut app, 4.5, 4.5, Modifiers::ALT); + assert_eq!(app.session.tools.foreground, red_gray, "the brush's Alt-click still samples the image"); + + app.ui.tool = Tool::Eyedropper; + app.run("layer.vectorMask.revealAll", json!({})).unwrap(); + assert!(app.ui.vector_mask_target); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, RED, "a vector target does not pick the raster mask"); + + app.run("channel.new", json!({"name": "Alpha"})).unwrap(); + app.run("channel.target", json!({"channel": {"alpha": 0}})).unwrap(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, red_gray, "an alpha target does not pick the raster mask"); + + app.run("channel.target.layerMask", json!({})).unwrap(); + app.run("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, red_gray, "Quick Mask does not pick the raster mask"); +} + +/// A smart filter's mask keeps its image-based sample even when the same layer has a raster mask. +#[test] +fn filter_mask_target_keeps_the_image_based_sample() { + let mut app = app_with_mask(false); + app.background_jobs = false; + app.run("channel.target.composite", json!({})).unwrap(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + assert!(app.session.active().unwrap().doc.layer(layer).unwrap().mask.is_some()); + app.select_filter_mask_target(Some(layer.0)); + assert!(app.filter_mask_targeted()); + app.ui.tool_options.eyedropper_sample = "current".into(); + let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": "current"})).unwrap(); + let [r, g, b, a]: [f32; 4] = serde_json::from_value(sample).unwrap(); + let want = gray(photocraft_color::convert::rgb_to_gray([r, g, b])); + assert!(a > 0.0 && want != gray(1.0), "the image and layer mask are distinct"); + click(&mut app, 4.5, 4.5, Modifiers::NONE); + assert_eq!(app.session.tools.foreground, want); +} + +/// Out-of-canvas points and invalid sample options leave both swatches intact. +#[test] +fn invalid_mask_samples_leave_both_swatches_unchanged() { + let mut app = app_with_mask(false); + app.ui.tool_options.eyedropper_sample = "current".into(); + app.run("tools.setColors", json!({"foreground": [0.2, 0.2, 0.2, 1.0], "background": [0.8, 0.8, 0.8, 1.0]})).unwrap(); + let before = (app.session.tools.foreground, app.session.tools.background); + let assert_unchanged = |app: &PhotocraftApp| assert_eq!((app.session.tools.foreground, app.session.tools.background), before); + for (x, y) in [(-0.1, 1.0), (1.0, 8.0), (f64::NAN, 1.0), (1.0, f64::INFINITY)] { + for mods in [Modifiers::NONE, Modifiers::ALT] { + click(&mut app, x, y, mods); + assert_unchanged(&app); + } + } + app.ui.tool_options.eyedropper_size = 2; + click(&mut app, 1.0, 1.0, Modifiers::NONE); + assert_unchanged(&app); + app.ui.tool_options.eyedropper_size = 1; + app.ui.tool_options.eyedropper_sample = "invalid".into(); + click(&mut app, 1.0, 1.0, Modifiers::ALT); + assert_unchanged(&app); +} diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index c1b5ccde35..a617332bd1 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -739,6 +739,72 @@ fn cancelling_a_background_place_continues_the_queue() { assert_eq!(layer_count(&app), layers + 1); } +/// #8492: with Skip Transform when Placing on, dropped files still go through the background place +/// job one at a time, but no Free Transform opens when a layer lands: the next file starts as soon +/// as the previous one has landed, without waiting for ↩. +#[test] +fn skip_transform_when_placing_places_background_drops_without_free_transform() { + let ctx = egui::Context::default(); + let mut app = app_with_canvas(); + app.background_jobs = true; + app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": true})).unwrap(); + let (layers, steps) = (layer_count(&app), history_steps(&app)); + app.open_dropped(&ctx, vec![dropped("first.png", Ok(png_bytes(4, 4))), dropped("second.png", Ok(png_bytes(2, 2)))], Some(egui::pos2(400.0, 300.0))); + app.place_next_dropped(&ctx); + let first = app.jobs.place.clone().expect("the first file is being placed"); + assert_eq!(first.name, "first.png"); + assert!(app.session.job(first.job).is_some(), "as a background job"); + assert_eq!(app.drop_places.len(), 1, "the second file waits for the first job"); + tick_until(&mut app, &ctx, |app| app.jobs.place.as_ref().is_some_and(|p| p.name == "second.png")); + assert!(app.ui.transform.is_none(), "no Free Transform on the first file"); + assert_eq!(layer_count(&app), layers + 1); + tick_until(&mut app, &ctx, |app| app.jobs.place.is_none()); + assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, "second"); + assert_eq!((layer_count(&app), history_steps(&app)), (layers + 2, steps + 2), "one Place Embedded step each"); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Place Embedded")); +} + +/// #8492: inline (background jobs off, as on the web) the preference places every queued drop +/// without Free Transform, a file that can't be placed reported on the way. +#[test] +fn skip_transform_when_placing_places_inline_drops_without_free_transform() { + let ctx = egui::Context::default(); + let mut app = app_with_canvas(); + app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": true})).unwrap(); + let (layers, steps) = (layer_count(&app), history_steps(&app)); + app.open_dropped( + &ctx, + vec![dropped("first.png", Ok(png_bytes(4, 4))), dropped("bad.png", Ok(b"bad".to_vec())), dropped("second.png", Ok(png_bytes(2, 2)))], + Some(egui::pos2(400.0, 300.0)), + ); + app.place_next_dropped(&ctx); + assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); + assert_eq!((layer_count(&app), history_steps(&app)), (layers + 2, steps + 2)); + assert_eq!(app.ui.notices.iter().filter(|n| n.error && n.title.contains("bad.png")).count(), 1); +} + +/// #8492: Skip Transform when Placing only concerns the interactive place. `file.placeEmbedded` +/// with a `path` (actions, scripts, the control channel, MCP) runs the engine command, which never +/// opens Free Transform, whatever the preference. +#[test] +fn a_scripted_place_never_opens_free_transform() { + let dir = std::env::temp_dir().join(format!("pc-scripted-place-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("dot.png"); + std::fs::write(&path, png_bytes(4, 3)).unwrap(); + let mut app = app_with_canvas(); + for skip in [false, true] { + app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": skip})).unwrap(); + let layers = layer_count(&app); + app.run("file.placeEmbedded", json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(layer_count(&app), layers + 1, "skip={skip}"); + assert!(app.ui.transform.is_none(), "skip={skip}"); + } + std::fs::remove_dir_all(dir).unwrap(); +} + /// Frames with nothing to wait for: jobs applied and the drop queue served. fn idle_frames(app: &mut PhotocraftApp, ctx: &egui::Context) { for _ in 0..3 { diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 66ad03cdb2..1cfced87ac 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -546,7 +546,6 @@ Deselect إلغاء التحديد Reselect إعادة التحديد Inverse عكس التحديد - Inverse Selection عكس التحديد Similar مشابه Color Range… نطاق الألوان… Focus Area… منطقة التركيز… @@ -684,8 +683,8 @@ Legacy Macintosh RGB (Gamma 1.8) RGB القديم لنظام Macintosh (Gamma 1.8) Internet Standard RGB (sRGB) RGB القياسي للإنترنت (sRGB) Monitor RGB RGB الشاشة - Color Blindness — Protanopia-type عمى الألوان — نوع بروتانوبيا - Color Blindness — Deuteranopia-type عمى الألوان — نوع ديوتيرانوبيا + Color Blindness - Protanopia-type عمى الألوان — نوع بروتانوبيا + Color Blindness - Deuteranopia-type عمى الألوان — نوع ديوتيرانوبيا Zoom In تكبير Zoom Out تصغير Fit on Screen ملاءمة للشاشة @@ -993,7 +992,7 @@ Click to add a point · drag off or {key}-click or Delete to remove انقر لإضافة نقطة · اسحبها بعيدًا أو {key}+نقر أو Delete للإزالة Click to apply, {key}-click to clear overrides, double-click for Style Options انقر للتطبيق، {key}+نقر لمسح التجاوزات، نقر مزدوج لخيارات النمط Click to edit the gradient انقر لتحرير التدرج - Click to restore the current colour انقر لاستعادة اللون الحالي + Click to restore the current color انقر لاستعادة اللون الحالي Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out انقر للتكبير · {key}+نقر للتصغير · اسحب يمينًا/يسارًا للتكبير/التصغير Click with the Note tool to add a note. انقر بأداة الملاحظة لإضافة ملاحظة. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel نقر: زاوية · سحب: ناعم · نقر على النقطة الأولى: إغلاق · {key} إنهاء · Esc إلغاء @@ -1079,7 +1078,7 @@ Darks الدرجات الداكنة Data Sets مجموعات البيانات Default افتراضي - Default colours (D) الألوان الافتراضية (D) + Default Foreground and Background Colors (D) لونا المقدمة والخلفية الافتراضيان (D) Default printer الطابعة الافتراضية Default restored. تمت استعادة الإعدادات الافتراضية. Define تعريف @@ -1365,7 +1364,7 @@ Opacity Jitter تذبذب العتامة Opacity: العتامة: Open a document to define variables. افتح مستندًا لتعريف المتغيرات. - Open a document to select a colour range. افتح مستندًا لتحديد نطاق ألوان. + Open a document to select a color range. افتح مستندًا لتحديد نطاق ألوان. Open a document to use the timeline. افتح مستندًا لاستخدام المخطط الزمني. Optical بصري Optimized محسّن @@ -1441,7 +1440,6 @@ Purity النقاء Quality الجودة Quick Actions إجراءات سريعة - Quick Export As PNG تصدير سريع بتنسيق PNG Radial Gradient تدرج شعاعي Radius نصف القطر Radius: نصف القطر: @@ -1583,7 +1581,7 @@ Subtract from Sample طرح من العينة Subtract from selection ({key}) طرح من التحديد ({key}) Suggestions: الاقتراحات: - Swap colours (X) تبديل الألوان (X) + Switch Foreground and Background Colors (X) تبديل لوني المقدمة والخلفية (X) Swaps height and width يبدّل الارتفاع والعرض Switch between free transform and warp modes التبديل بين وضعي التحويل الحر والالتواء Switch theme تبديل السمة @@ -1686,7 +1684,7 @@ Choke تضييق Classic كلاسيكي Click to add text انقر لإضافة نص - Click to fill similar colours انقر لتعبئة الألوان المتشابهة + Click to fill similar colors انقر لتعبئة الألوان المتشابهة Clone Stamp Tool أداة ختم النسخ Color Burn تغميق اللون Color Dodge تفتيح اللون @@ -1846,7 +1844,7 @@ Rectangular Marquee Tool أداة إطار التحديد المستطيل Reds درجات الأحمر Reflected منعكس - Sample: foreground colour العينة: لون المقدمة + Sample: foreground color العينة: لون المقدمة Sampled Colors الألوان المأخوذة كعينات Satin ساتان Save Pixel Aspect Ratio حفظ نسبة أبعاد البكسل @@ -1884,7 +1882,7 @@ Transfer نقل Triangle Tool أداة المثلث Unsaved changes تغييرات غير محفوظة - Uses the foreground and background colours. يستخدم لوني المقدمة والخلفية. + Uses the foreground and background colors. يستخدم لوني المقدمة والخلفية. Web الويب Web Large ويب كبير Web Minimum ويب أدنى @@ -2156,7 +2154,7 @@ Graphics الرسومات Reset GPU Backend إعادة تعيين واجهة GPU الخلفية Applies at next launch. يُطبّق عند التشغيل التالي. - Click to sample the foreground colour · {key}-click for background انقر لأخذ عينة من لون المقدمة · {key}+نقر للون الخلفية + Click to sample the foreground color · {key}-click for background انقر لأخذ عينة من لون المقدمة · {key}+نقر للون الخلفية {key}-click to set the source {key}+نقر لضبط المصدر {key} to subtract {key} للطرح Clone source {n} ({key}-click with Clone Stamp to set) مصدر النسخ {n} ({key}+نقر بأداة ختم النسخ للضبط) @@ -2217,7 +2215,7 @@ Gradient Options خيارات التدرج Align with layer محاذاة مع الطبقة Reset Alignment إعادة تعيين المحاذاة - Centre the gradient (offset 0, 0) توسيط التدرج (إزاحة 0، 0) + Center the gradient (offset 0, 0) توسيط التدرج (إزاحة 0، 0) # Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor محرر التدرج Gradient picker منتقي التدرج @@ -2252,7 +2250,7 @@ Alt-click to define a source point to clone from انقر مع Alt لتحديد نقطة مصدر للنسخ منها No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. لا يوجد مسار لإنشاء تحديد منه: ارسم مسارًا بأداة القلم أو حدد مسارًا في لوحة المسارات. Cancel opening إلغاء الفتح - Cancelled opening {name} تم إلغاء فتح {name} + Canceled opening {name} تم إلغاء فتح {name} Damaged Photoshop document مستند Photoshop تالف The document “{name}” may be damaged. قد يكون المستند «{name}» تالفًا. Some layers, pixels or masks could not be read. Do you want to continue opening it? تعذرت قراءة بعض الطبقات أو البكسلات أو الأقنعة. هل تريد متابعة فتحه؟ @@ -2262,7 +2260,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. يحتوي المستند «{name}» على ملف تعريف ألوان مضمّن لا يطابق مساحة عمل {mode} الحالية. Working: {working} مساحة العمل: {working} Developing {name} جارٍ معالجة {name} - Cancelled {label} تم إلغاء {label} + Canceled {label} تم إلغاء {label} Esc to cancel Esc للإلغاء Opened {name} تم فتح {name} Opening {name} جارٍ فتح {name} @@ -2270,7 +2268,7 @@ Saving {name} جارٍ حفظ {name} Saving {percent} جارٍ الحفظ {percent} A save to {name} is still running; try again when it finishes لا تزال عملية حفظ في {name} جارية؛ حاول مرة أخرى عند انتهائها - {label} is writing the file and can no longer be cancelled {label} يكتب الملف ولم يعد بالإمكان إلغاؤه + {label} is writing the file and can no longer be canceled {label} يكتب الملف ولم يعد بالإمكان إلغاؤه Opening {name}… جارٍ فتح {name}… Opening… جارٍ الفتح… Reading… جارٍ القراءة… @@ -2333,7 +2331,7 @@ Pixel بكسل Adjustment تعديل Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract اسحب (حبل) أو انقر على النقاط (مضلع) · {add} إضافة · {sub} طرح - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels اسحب مربع اقتصاص · اسحب من الداخل للتحريك · الحواف لتغيير الحجم ({ratio} للنسبة، {centre} للمركز) · Space للتحريك أثناء الرسم · الأسهم للدفع الدقيق · X لتبديل الاتجاه · {commit} للتأكيد · Esc للإلغاء + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels اسحب مربع اقتصاص · اسحب من الداخل للتحريك · الحواف لتغيير الحجم ({ratio} للنسبة، {centre} للمركز) · Space للتحريك أثناء الرسم · الأسهم للدفع الدقيق · X لتبديل الاتجاه · {commit} للتأكيد · Esc للإلغاء {mode} Color · {bits} bit لون {mode} · {bits} بت Scrubby Zoom تكبير سحبي Auto Erase محو تلقائي @@ -2428,7 +2426,7 @@ Discard Layers and Save a Copy تجاهل الطبقات وحفظ نسخة Don't show again عدم الإظهار مرة أخرى Save failed: {error} فشل الحفظ: {error} - Save cancelled تم إلغاء الحفظ + Save canceled تم إلغاء الحفظ # Layer Style dialog: style presets and per-effect defaults Style {name} saved تم حفظ النمط {name} @@ -2581,7 +2579,7 @@ fontWeight Italic مائل Rotate View تدوير العرض Rotate View Tool أداة تدوير العرض Reset View إعادة تعيين العرض - Drag around the centre to rotate the view · Shift constrains to 15° اسحب حول المركز لتدوير العرض · Shift يقيّد الزاوية بخطوات 15° + Drag around the center to rotate the view · Shift constrains to 15° اسحب حول المركز لتدوير العرض · Shift يقيّد الزاوية بخطوات 15° # Painting symmetry presets. Dual Axis محور مزدوج @@ -2602,8 +2600,8 @@ fontWeight Italic مائل Show Sampling Ring إظهار حلقة أخذ العينات # Color Picker warnings - Out of gamut for printing: click for the nearest printable colour خارج النطاق اللوني للطباعة: انقر لأقرب لون قابل للطباعة - Not a web colour: click for the nearest web colour ليس لون ويب: انقر لأقرب لون ويب + Out of gamut for printing: click for the nearest printable color خارج النطاق اللوني للطباعة: انقر لأقرب لون قابل للطباعة + Not a web color: click for the nearest web color ليس لون ويب: انقر لأقرب لون ويب Color to Alpha… اللون إلى ألفا… Transparency Threshold عتبة الشفافية Opacity Threshold عتبة العتامة @@ -3315,7 +3313,7 @@ curves Smooth تنعيم # Native Windows printing qualification Don't also tick Mirror Image in Print Settings…: the two flips cancel out. لا تُحدد أيضًا صورة معكوسة في إعدادات الطباعة…: فالانعكاسان يلغي كل منهما الآخر. Print Settings… إعدادات الطباعة… - Remember to turn off the printer's own colour management in Print Settings… تذكر إيقاف إدارة الألوان الخاصة بالطابعة في إعدادات الطباعة… + Remember to turn off the printer's own color management in Print Settings… تذكر إيقاف إدارة الألوان الخاصة بالطابعة في إعدادات الطباعة… Sent to {printer} تم الإرسال إلى {printer} set in Print Settings… يتم ضبطه في إعدادات الطباعة… ICO is limited to 256 × 256 pixels ملفات ICO محدودة بـ 256 × 256 بكسل @@ -3456,12 +3454,12 @@ curves Smooth تنعيم {name} was changed by another app after it was opened or saved here. تم تغيير {name} بواسطة تطبيق آخر بعد فتحه أو حفظه هنا. Replace it with this document, or cancel and use File › Save As to keep both. استبدله بهذا المستند، أو ألغِ واستخدم ملف › حفظ باسم للاحتفاظ بكليهما. Demosaic إزالة الفسيفساء - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. طريقة ملء فسيفساء مرشح الألوان في الكاميرا. تُطبَّق عند فتح الملف؛ وتعرض المعاينة الطريقة التي فُتح بها. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. طريقة ملء فسيفساء مرشح الألوان في الكاميرا. تُطبَّق عند فتح الملف؛ وتعرض المعاينة الطريقة التي فُتح بها. AHD (adaptive homogeneity) AHD (التجانس التكيفي) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: أنظف الحواف وأقل هالات لونية، والأبطأ. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. استيفاء مصحح بالتدرج: حاد وسريع، مع بعض الهالات اللونية في التفاصيل الدقيقة. - The fastest and the softest, with colour fringing on fine detail. الأسرع والأنعم، مع هالات لونية في التفاصيل الدقيقة. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: أنظف الحواف وأقل هالات لونية، والأبطأ. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. استيفاء مصحح بالتدرج: حاد وسريع، مع بعض الهالات اللونية في التفاصيل الدقيقة. + The fastest and the softest, with color fringing on fine detail. الأسرع والأنعم، مع هالات لونية في التفاصيل الدقيقة. “{name}” already exists. Replace it? “{name}” موجود بالفعل. هل تريد استبداله؟ The name in the save dialog was “{name}”. كان الاسم في مربع حوار الحفظ “{name}”. Move Up تحريك لأعلى @@ -3603,3 +3601,19 @@ curves Smooth تنعيم Pick a different document for each channel. اختر مستندًا مختلفًا لكل قناة. A picked document is no longer open. أحد المستندات المختارة لم يعد مفتوحًا. A picked document is no longer a grayscale document of the same size. أحد المستندات المختارة لم يعد مستندًا بتدرج الرمادي بالحجم نفسه. +# Move tool options bar (#11381) + Align top edges محاذاة الحواف العلوية + Align vertical centers محاذاة المراكز الرأسية + Align bottom edges محاذاة الحواف السفلية + Distribute vertically توزيع رأسي + Distribute horizontally توزيع أفقي + Show layer bounds on hover إظهار حدود الطبقة عند التمرير + Expand layer group on click توسيع مجموعة الطبقات عند النقر + Show hover bounds from Layers إظهار حدود التمرير من الطبقات +# Artboard tool options bar (#11385) + Distribute Widths توزيع العروض + Distribute Heights توزيع الارتفاعات + Auto-nest Layers تداخل الطبقات تلقائيًا + Auto-size Canvas تحديد حجم مساحة الرسم تلقائيًا + Keep Relative Position During Layer Reordering الإبقاء على الموضع النسبي عند إعادة ترتيب الطبقات + Shrinkwrap Canvas on Save تقليص مساحة الرسم إلى المحتوى عند الحفظ diff --git a/crates/ui-egui/src/i18n/az.tsv b/crates/ui-egui/src/i18n/az.tsv index 958a2bfedc..c228ba73d0 100644 --- a/crates/ui-egui/src/i18n/az.tsv +++ b/crates/ui-egui/src/i18n/az.tsv @@ -4617,3 +4617,19 @@ smartSvg SVG editor opened. Save the SVG to update this Smart Object. SVG redakt # Strings main added after this catalog was written (integration batch 20). Background (default) Fon (defolt) Transparent (default) Şəffaf (defolt) +# Move tool options bar (#11381) + Align top edges Üst kənarları hizalayın + Align vertical centers Şaquli mərkəzləri hizalayın + Align bottom edges Alt kənarları hizalayın + Distribute vertically Şaquli yaymaq + Distribute horizontally Üfüqi yaymaq + Show layer bounds on hover Üzərinə gətirəndə qat sərhədlərini göstərin + Expand layer group on click Klikləyəndə qat qrupunu genişləndirin + Show hover bounds from Layers Üzərinə gətirmə sərhədlərini Qatlardan göstərin +# Artboard tool options bar (#11385) + Distribute Widths Enləri yaymaq + Distribute Heights Hündürlükləri yaymaq + Auto-nest Layers Qatları avtomatik yuvalayın + Auto-size Canvas Kətanın ölçüsünü avtomatik təyin edin + Keep Relative Position During Layer Reordering Qatları yenidən sıralayarkən nisbi mövqeyi saxlayın + Shrinkwrap Canvas on Save Saxlayarkən kətanı məzmuna sıxın diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9c411984bc..3a9cdb8137 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -507,7 +507,6 @@ Deselect Poništi odabir Reselect Ponovo odaberi Inverse Obrnuto - Inverse Selection Obrnuti odabir Similar Slično Color Range… Raspon boja… Focus Area… Područje fokusa… @@ -627,8 +626,8 @@ Legacy Macintosh RGB (Gamma 1.8) Naslijeđeni Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internet standardni RGB (sRGB) Monitor RGB RGB monitora - Color Blindness — Protanopia-type Daltonizam — tip protanopije - Color Blindness — Deuteranopia-type Daltonizam — tip deuteranopije + Color Blindness - Protanopia-type Daltonizam — tip protanopije + Color Blindness - Deuteranopia-type Daltonizam — tip deuteranopije Zoom In Uvećaj Zoom Out Umanji Fit on Screen Uklopi na ekran @@ -937,7 +936,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Kliknite da dodate tačku · prevucite van ili {key}-klik ili Delete za uklanjanje Click to apply, {key}-click to clear overrides, double-click for Style Options Kliknite za primjenu, {key}-klik za brisanje zamjena, dvostruki klik za opcije stila Click to edit the gradient Kliknite da uredite gradijent - Click to restore the current colour Kliknite da vratite trenutnu boju + Click to restore the current color Kliknite da vratite trenutnu boju Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Kliknite za uvećanje · {key}-klik za umanjenje · prevucite desno/lijevo za uvećanje/umanjenje Click with the Note tool to add a note. Kliknite alatom Bilješka da dodate bilješku. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klik: ugao · Prevlačenje: glatko · Klik na prvu tačku: zatvori · {key} završi · Esc otkaži @@ -1017,7 +1016,7 @@ Darks Tamni dijelovi Data Sets Skupovi podataka Default Zadano - Default colours (D) Zadane boje (D) + Default Foreground and Background Colors (D) Zadane boje prednjeg plana i pozadine (D) Default printer Zadani štampač Default restored. Zadano vraćeno. Define Definiši @@ -1291,7 +1290,7 @@ Opacity Jitter Varijacija neprozirnosti Opacity: Neprozirnost: Open a document to define variables. Otvorite dokument da definišete varijable. - Open a document to select a colour range. Otvorite dokument da odaberete raspon boja. + Open a document to select a color range. Otvorite dokument da odaberete raspon boja. Open a document to use the timeline. Otvorite dokument da koristite vremensku liniju. Optical Optičko Optimized Optimizirano @@ -1367,7 +1366,6 @@ Purity Čistoća Quality Kvalitet Quick Actions Brze akcije - Quick Export As PNG Brzi izvoz kao PNG Radial Gradient Radijalni gradijent Radius Poluprečnik Radius: Poluprečnik: @@ -1508,7 +1506,7 @@ Subtract from Sample Oduzmi od uzorka Subtract from selection ({key}) Oduzmi od odabira ({key}) Suggestions: Prijedlozi: - Swap colours (X) Zamijeni boje (X) + Switch Foreground and Background Colors (X) Zamijeni boje prednjeg plana i pozadine (X) Swaps height and width Zamjenjuje visinu i širinu Switch between free transform and warp modes Prebacuj između slobodne transformacije i iskrivljenja Switch theme Promijeni temu @@ -1610,7 +1608,7 @@ Choke Sužavanje Classic Klasično Click to add text Kliknite da dodate tekst - Click to fill similar colours Kliknite da ispunite slične boje + Click to fill similar colors Kliknite da ispunite slične boje Clone Stamp Tool Alat pečat za kloniranje Color Burn Tamnjenje boje Color Dodge Posvjetljivanje boje @@ -1772,7 +1770,7 @@ Rectangular Marquee Tool Alat pravougaoni markiz Reds Crvene Reflected Reflektovano - Sample: foreground colour Uzorak: boja prednjeg plana + Sample: foreground color Uzorak: boja prednjeg plana Sampled Colors Uzorkovane boje Satin Saten Save Pixel Aspect Ratio Sačuvaj omjer stranica piksela @@ -1810,7 +1808,7 @@ Transfer Prijenos Triangle Tool Alat trougao Unsaved changes Nesačuvane promjene - Uses the foreground and background colours. Koristi boje prednjeg plana i pozadine. + Uses the foreground and background colors. Koristi boje prednjeg plana i pozadine. Web Web Web Large Web veliko Web Minimum Web minimum @@ -2078,7 +2076,7 @@ Graphics Grafika Reset GPU Backend Vrati GPU pozadinski sistem na početno Applies at next launch. Primjenjuje se pri sljedećem pokretanju. - Click to sample the foreground colour · {key}-click for background Kliknite da uzmete uzorak boje prednjeg plana · {key}-klik za pozadinu + Click to sample the foreground color · {key}-click for background Kliknite da uzmete uzorak boje prednjeg plana · {key}-klik za pozadinu {key}-click to set the source {key}-klik za postavljanje izvora {key} to subtract {key} za oduzimanje Clone source {n} ({key}-click with Clone Stamp to set) Izvor kloniranja {n} ({key}-klik pečatom za kloniranje za postavljanje) @@ -2136,7 +2134,7 @@ Gradient Options Opcije gradijenta Align with layer Poravnaj sa slojem Reset Alignment Vrati poravnanje na početno - Centre the gradient (offset 0, 0) Centriraj gradijent (pomak 0, 0) + Center the gradient (offset 0, 0) Centriraj gradijent (pomak 0, 0) Gradient Editor Uređivač gradijenta Gradient picker Birač gradijenta Save As Preset Sačuvaj kao predložak @@ -2169,7 +2167,7 @@ Alt-click to define a source point to clone from Alt-klik za definisanje izvorne tačke za kloniranje No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nema putanje iz koje bi se napravio odabir: nacrtajte je alatom Pero ili odaberite jednu u panelu Putanje. Cancel opening Otkaži otvaranje - Cancelled opening {name} Otkazano otvaranje {name} + Canceled opening {name} Otkazano otvaranje {name} Damaged Photoshop document Oštećen Photoshop dokument The document “{name}” may be damaged. Dokument „{name}” je možda oštećen. Some layers, pixels or masks could not be read. Do you want to continue opening it? Neki slojevi, pikseli ili maske nisu mogli biti pročitani. Želite li nastaviti s otvaranjem? @@ -2178,7 +2176,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}” ima ugrađeni profil boja koji ne odgovara trenutnom {mode} radnom prostoru. Working: {working} Radni: {working} Developing {name} Razvijanje {name} - Cancelled {label} Otkazano: {label} + Canceled {label} Otkazano: {label} Esc to cancel Esc za otkazivanje Opened {name} Otvoreno: {name} Opening {name} Otvaranje {name} @@ -2186,7 +2184,7 @@ Saving {name} Čuvanje {name} Saving {percent} Čuvanje {percent} A save to {name} is still running; try again when it finishes Čuvanje u {name} je još u toku; pokušajte ponovo kad završi - {label} is writing the file and can no longer be cancelled {label} zapisuje datoteku i više se ne može otkazati + {label} is writing the file and can no longer be canceled {label} zapisuje datoteku i više se ne može otkazati Opening {name}… Otvaranje {name}… Opening… Otvaranje… Reading… Čitanje… @@ -2560,7 +2558,7 @@ Pixel Piksel Adjustment Podešavanje Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Prevucite (laso) ili kliknite tačke (mnogougaono) · {add} dodaj · {sub} oduzmi - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Prevucite okvir izrezivanja · prevucite unutra za pomjeranje · ivice mijenjaju veličinu ({ratio} omjer, {centre} središte) · Razmak pomjera tokom crtanja · strelice pomiču · X mijenja orijentaciju · {commit} potvrđuje · Esc otkazuje + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Prevucite okvir izrezivanja · prevucite unutra za pomjeranje · ivice mijenjaju veličinu ({ratio} omjer, {centre} središte) · Razmak pomjera tokom crtanja · strelice pomiču · X mijenja orijentaciju · {commit} potvrđuje · Esc otkazuje {mode} Color · {bits} bit {mode} boja · {bits} bita Drag to move the layer Prevucite da pomjerite sloj Scrubby Zoom Zumiranje prevlačenjem @@ -2645,7 +2643,6 @@ Search commands (⌘K) Pretraži naredbe (⌘K) Show Guides (⌘;) Prikaži vodilice (⌘;) Subtract from selection (⌥) Oduzmi od odabira (⌥) - Uses the foreground and background colors. Koristi boje prednjeg plana i pozadine. ↑↓ navigate ↵ run esc close ↑↓ kretanje ↵ pokreni esc zatvori Adds grain to the soft edges of the brush tip. Dodaje zrno mekim ivicama vrha četkice. Keeps the current texture when switching presets. Zadržava trenutnu teksturu pri promjeni predloška. @@ -2754,7 +2751,7 @@ cameraRaw Blending Stapanje Discard Layers and Save a Copy Odbaci slojeve i sačuvaj kopiju Don't show again Ne prikazuj ponovo Save failed: {error} Čuvanje nije uspjelo: {error} - Save cancelled Čuvanje otkazano + Save canceled Čuvanje otkazano Couldn't place {name}: {error} Nije moguće postaviti {name}: {error} Magnetic Lasso Tool Alat magnetni laso Frequency Frekvencija @@ -2879,7 +2876,7 @@ fontWeight Italic Kurziv Impressionist Impresionistički Rotate View Tool Alat za rotaciju prikaza Reset View Vrati prikaz na početno - Drag around the centre to rotate the view · Shift constrains to 15° Prevucite oko središta da rotirate prikaz · Shift ograničava na 15° + Drag around the center to rotate the view · Shift constrains to 15° Prevucite oko središta da rotirate prikaz · Shift ograničava na 15° Dual Axis Dvije ose Diagonal Dijagonalno Transform Symmetry Simetrija transformacije @@ -2894,8 +2891,8 @@ fontWeight Italic Kurziv All Layers No Adjustments Svi slojevi bez podešavanja Current & Below No Adjustments Trenutni i ispod bez podešavanja Show Sampling Ring Prikaži prsten uzorkovanja - Out of gamut for printing: click for the nearest printable colour Izvan gamuta za štampu: kliknite za najbližu boju koja se može štampati - Not a web colour: click for the nearest web colour Nije web boja: kliknite za najbližu web boju + Out of gamut for printing: click for the nearest printable color Izvan gamuta za štampu: kliknite za najbližu boju koja se može štampati + Not a web color: click for the nearest web color Nije web boja: kliknite za najbližu web boju Color to Alpha… Boja u alfu… Transparency Threshold Prag prozirnosti Opacity Threshold Prag neprozirnosti @@ -4194,7 +4191,7 @@ shape Appearance Izgled Auto Add/Delete Automatsko dodavanje/brisanje Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nemojte također označiti Zrcalna slika u Postavke štampanja…: dva preokretanja se poništavaju. Print Settings… Postavke štampanja… - Remember to turn off the printer's own colour management in Print Settings… Ne zaboravite isključiti vlastito upravljanje bojama štampača u Postavke štampanja… + Remember to turn off the printer's own color management in Print Settings… Ne zaboravite isključiti vlastito upravljanje bojama štampača u Postavke štampanja… Sent to {printer} Poslano na {printer} set in Print Settings… postavlja se u Postavke štampanja… Paper Width Širina papira @@ -4364,12 +4361,12 @@ shape Appearance Izgled Decrease Brush Hardness Smanji tvrdoću četkice Increase Brush Hardness Povećaj tvrdoću četkice Demosaic Demozaik - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Kako se popunjava mozaik filtera boja kamere. Primjenjuje se pri otvaranju datoteke; pregled prikazuje metodu kojom je otvorena. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Kako se popunjava mozaik filtera boja kamere. Primjenjuje se pri otvaranju datoteke; pregled prikazuje metodu kojom je otvorena. AHD (adaptive homogeneity) AHD (adaptivna homogenost) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: najčišće ivice i najmanje obojenih rubova, najsporiji. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolacija s korekcijom gradijenta: oštra i brza, uz nešto obojenih rubova na finim detaljima. - The fastest and the softest, with colour fringing on fine detail. Najbrži i najmekši, uz obojene rubove na finim detaljima. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: najčišće ivice i najmanje obojenih rubova, najsporiji. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolacija s korekcijom gradijenta: oštra i brza, uz nešto obojenih rubova na finim detaljima. + The fastest and the softest, with color fringing on fine detail. Najbrži i najmekši, uz obojene rubove na finim detaljima. “{name}” already exists. Replace it? „{name}” već postoji. Zamijeniti? The name in the save dialog was “{name}”. Naziv u dijalogu za čuvanje bio je „{name}”. Move Up Pomakni gore @@ -4568,8 +4565,8 @@ cameraRaw Camera Raw ({name}) Camera Raw ({name}) cameraRaw Camera Raw Filter ({layer}) Camera Raw filter ({layer}) cameraRaw Camera Raw isn't open Camera Raw nije otvoren cameraRaw Cancel Otkaži -cameraRaw Cancelled opening {name} Otkazano otvaranje {name} -cameraRaw Cancelled {label} Otkazano: {label} +cameraRaw Canceled opening {name} Otkazano otvaranje {name} +cameraRaw Canceled {label} Otkazano: {label} cameraRaw Color Priority Prioritet boje cameraRaw Developing {name} Razvijanje {name} cameraRaw Full-resolution preview unavailable Pregled u punoj rezoluciji nije dostupan @@ -4634,3 +4631,19 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Odaberite drugi dokument za svaki kanal. A picked document is no longer open. Jedan odabrani dokument više nije otvoren. A picked document is no longer a grayscale document of the same size. Jedan odabrani dokument više nije dokument u nijansama sive iste veličine. +# Move tool options bar (#11381) + Align top edges Poravnaj gornje ivice + Align vertical centers Poravnaj vertikalne centre + Align bottom edges Poravnaj donje ivice + Distribute vertically Rasporedi vertikalno + Distribute horizontally Rasporedi horizontalno + Show layer bounds on hover Prikaži granice sloja pri prelasku miša + Expand layer group on click Proširi grupu slojeva klikom + Show hover bounds from Layers Prikaži granice pri prelasku iz panela Slojevi +# Artboard tool options bar (#11385) + Distribute Widths Rasporedi širine + Distribute Heights Rasporedi visine + Auto-nest Layers Automatski ugnijezdi slojeve + Auto-size Canvas Automatski promijeni veličinu platna + Keep Relative Position During Layer Reordering Zadrži relativni položaj pri promjeni redoslijeda slojeva + Shrinkwrap Canvas on Save Smanji platno na sadržaj pri sačuvanju diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 96bac5cb3b..ce81791aa2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -666,7 +666,6 @@ Deselect Zrušit výběr Reselect Znovu vybrat Inverse Invertovat výběr - Inverse Selection Invertovat výběr Similar Podobné Color Range… Rozsah barev… Focus Area… Oblast zaostření… @@ -786,8 +785,8 @@ Legacy Macintosh RGB (Gamma 1.8) Starší Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internetový standard RGB (sRGB) Monitor RGB RGB monitoru - Color Blindness — Protanopia-type Barvoslepost — protanopie - Color Blindness — Deuteranopia-type Barvoslepost — deuteranopie + Color Blindness - Protanopia-type Barvoslepost - protanopie + Color Blindness - Deuteranopia-type Barvoslepost - deuteranopie Zoom In Přiblížit Zoom Out Oddálit Fit on Screen Přizpůsobit obrazovce @@ -1111,7 +1110,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Kliknutím přidáte bod · odstraníte tažením ven, {key}+kliknutím nebo klávesou Delete Click to apply, {key}-click to clear overrides, double-click for Style Options Kliknutím použijete, {key}+kliknutím zrušíte přepsání, dvojklikem otevřete možnosti stylu Click to edit the gradient Kliknutím upravíte přechod - Click to restore the current colour Kliknutím obnovíte aktuální barvu + Click to restore the current color Kliknutím obnovíte aktuální barvu Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Kliknutím přiblížíte · {key}+kliknutím oddálíte · tažením doprava/doleva přiblížíte/oddálíte Click with the Note tool to add a note. Poznámku přidáte kliknutím nástrojem poznámka. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Kliknutí: roh · tažení: hladký bod · kliknutí na první bod: uzavřít · {key} dokončit · Esc zrušit @@ -1194,7 +1193,7 @@ Darks Tmavé tóny Data Sets Datové sady Default Výchozí - Default colours (D) Výchozí barvy (D) + Default Foreground and Background Colors (D) Výchozí barvy popředí a pozadí (D) Default printer Výchozí tiskárna Default restored. Výchozí hodnota obnovena. Define Definovat @@ -1476,7 +1475,7 @@ Opacity Jitter Kolísání krytí Opacity: Krytí: Open a document to define variables. Chcete-li definovat proměnné, otevřete dokument. - Open a document to select a colour range. Chcete-li vybrat rozsah barev, otevřete dokument. + Open a document to select a color range. Chcete-li vybrat rozsah barev, otevřete dokument. Open a document to use the timeline. Chcete-li použít časovou osu, otevřete dokument. Optical Optické Optimized Optimalizovaný @@ -1552,7 +1551,6 @@ Purity Čistota Quality Kvalita Quick Actions Rychlé akce - Quick Export As PNG Rychlý export do PNG Radial Gradient Radiální přechod Radius Poloměr Radius: Poloměr: @@ -1695,7 +1693,7 @@ Subtract from Sample Odebrat ze vzorku Subtract from selection ({key}) Odebrat z výběru ({key}) Suggestions: Návrhy: - Swap colours (X) Prohodit barvy (X) + Switch Foreground and Background Colors (X) Prohodit barvy popředí a pozadí (X) Swaps height and width Prohodí výšku a šířku Switch between free transform and warp modes Přepnout mezi volnou transformací a deformací Switch theme Přepnout motiv @@ -1800,7 +1798,7 @@ Choke Stažení Classic Klasický Click to add text Kliknutím přidáte text - Click to fill similar colours Kliknutím vyplníte podobné barvy + Click to fill similar colors Kliknutím vyplníte podobné barvy Clone Stamp Tool Nástroj klonovací razítko Color Burn Ztmavit barvy Color Dodge Zesvětlit barvy @@ -1960,7 +1958,7 @@ Rectangular Marquee Tool Nástroj obdélníkový výběr Reds Červené Reflected Zrcadlený - Sample: foreground colour Vzorek: barva popředí + Sample: foreground color Vzorek: barva popředí Sampled Colors Vzorkované barvy Satin Satén Save Pixel Aspect Ratio Uložit poměr stran pixelu @@ -1999,7 +1997,7 @@ Transfer Přenos Triangle Tool Nástroj trojúhelník Unsaved changes Neuložené změny - Uses the foreground and background colours. Používá barvy popředí a pozadí. + Uses the foreground and background colors. Používá barvy popředí a pozadí. Web Web Web Large Web velký Web Minimum Web minimální @@ -2036,6 +2034,7 @@ Allow scripts to connect Povolit připojení skriptů Always Vždy Always create smart objects when placing Při umísťování vždy vytvořit chytré objekty + Skip transform when placing Při umísťování přeskočit transformaci Animated zoom Animované zvětšování Apply auto tone Použít automatický tón Ask Zeptat se @@ -2271,7 +2270,7 @@ Graphics Grafika Reset GPU Backend Obnovit grafický backend Applies at next launch. Projeví se při příštím spuštění. - Click to sample the foreground colour · {key}-click for background Kliknutím nasnímáte barvu popředí · {key}+kliknutím barvu pozadí + Click to sample the foreground color · {key}-click for background Kliknutím nasnímáte barvu popředí · {key}+kliknutím barvu pozadí {key}-click to set the source {key}+kliknutím nastavíte zdroj {key} to subtract {key} pro odebrání Clone source {n} ({key}-click with Clone Stamp to set) Zdroj klonování {n} (nastavíte {key}+kliknutím klonovacím razítkem) @@ -2333,7 +2332,7 @@ Gradient Options Možnosti přechodu Align with layer Zarovnat s vrstvou Reset Alignment Obnovit zarovnání - Centre the gradient (offset 0, 0) Vystředit přechod (posun 0, 0) + Center the gradient (offset 0, 0) Vystředit přechod (posun 0, 0) Gradient Editor Editor přechodů Gradient picker Výběr přechodu Save As Preset Uložit jako preset @@ -2366,7 +2365,7 @@ Alt-click to define a source point to clone from Kliknutím s klávesou Alt určete zdrojový bod pro klonování No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Není k dispozici žádná cesta, ze které by šlo vytvořit výběr: nakreslete ji nástrojem Pero nebo ji vyberte na panelu Cesty. Cancel opening Zrušit otevírání - Cancelled opening {name} Otevírání {name} zrušeno + Canceled opening {name} Otevírání {name} zrušeno Damaged Photoshop document Poškozený dokument Photoshopu The document “{name}” may be damaged. Dokument „{name}“ může být poškozený. Some layers, pixels or masks could not be read. Do you want to continue opening it? Některé vrstvy, pixely nebo masky nebylo možné načíst. Chcete pokračovat v otevírání? @@ -2375,7 +2374,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}“ má vložený barevný profil, který neodpovídá aktuálnímu pracovnímu prostoru barev {mode}. Working: {working} Pracovní: {working} Developing {name} Vyvolávání {name} - Cancelled {label} Zrušeno: {label} + Canceled {label} Zrušeno: {label} Esc to cancel Esc pro zrušení Opened {name} Otevřeno: {name} Opening {name} Otevírání {name} @@ -2383,7 +2382,7 @@ Saving {name} Ukládání {name} Saving {percent} Ukládání {percent} A save to {name} is still running; try again when it finishes Ukládání do {name} stále probíhá; zkuste to znovu, až skončí - {label} is writing the file and can no longer be cancelled {label} zapisuje soubor a už ho nelze zrušit + {label} is writing the file and can no longer be canceled {label} zapisuje soubor a už ho nelze zrušit Opening {name}… Otevírání {name}… Opening… Otevírání… Reading… Načítání… @@ -2467,7 +2466,7 @@ cameraRaw Color Barvy Discard Layers and Save a Copy Zahodit vrstvy a uložit kopii Don't show again Příště nezobrazovat Save failed: {error} Uložení se nezdařilo: {error} - Save cancelled Ukládání zrušeno + Save canceled Ukládání zrušeno Couldn't place {name}: {error} Nelze umístit {name}: {error} Magnetic Lasso Tool Nástroj magnetické laso Frequency Frekvence @@ -2600,7 +2599,7 @@ fontWeight Italic Kurzíva Rotate View Otočit zobrazení Rotate View Tool Nástroj otočení zobrazení Reset View Obnovit zobrazení - Drag around the centre to rotate the view · Shift constrains to 15° Tažením kolem středu otočíte zobrazení · Shift omezí na 15° + Drag around the center to rotate the view · Shift constrains to 15° Tažením kolem středu otočíte zobrazení · Shift omezí na 15° Dual Axis Dvojitá osa Diagonal Diagonální Transform Symmetry Transformovat symetrii @@ -2615,8 +2614,8 @@ fontWeight Italic Kurzíva All Layers No Adjustments Všechny vrstvy bez korekcí Current & Below No Adjustments Aktuální a pod ní bez korekcí Show Sampling Ring Zobrazit vzorkovací kroužek - Out of gamut for printing: click for the nearest printable colour Mimo gamut tisku: klepnutím zvolíte nejbližší tisknutelnou barvu - Not a web colour: click for the nearest web colour Není webová barva: klepnutím zvolíte nejbližší webovou barvu + Out of gamut for printing: click for the nearest printable color Mimo gamut tisku: klepnutím zvolíte nejbližší tisknutelnou barvu + Not a web color: click for the nearest web color Není webová barva: klepnutím zvolíte nejbližší webovou barvu Color to Alpha… Barva na alfu… Transparency Threshold Práh průhlednosti Opacity Threshold Práh krytí @@ -2710,7 +2709,7 @@ fontWeight Italic Kurzíva How often fastening points are placed by themselves Jak často se kotevní body umisťují samy Scrubby Zoom Plynulá lupa {mode} Color · {bits} bit Barva {mode} · {bits} bitů - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Tažením nakreslete ořez · tažením uvnitř posunete · okraje mění velikost ({ratio} poměr, {centre} střed) · Mezerník posouvá při kreslení · šipky posunují · X prohodí orientaci · {commit} potvrdí · Esc zruší + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Tažením nakreslete ořez · tažením uvnitř posunete · okraje mění velikost ({ratio} poměr, {centre} střed) · Mezerník posouvá při kreslení · šipky posunují · X prohodí orientaci · {commit} potvrdí · Esc zruší Appearance Settings… Nastavení vzhledu… Add to favorites Přidat do oblíbených Remove from favorites Odebrat z oblíbených @@ -3928,7 +3927,7 @@ navigator Zoom Zvětšení Auto Add/Delete Automaticky přidat/odstranit Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nezapínejte současně zrcadlení v nastavení tisku: obě převrácení se navzájem zruší. Print Settings… Nastavení tisku… - Remember to turn off the printer's own colour management in Print Settings… Nezapomeňte v nastavení tisku vypnout vlastní správu barev tiskárny… + Remember to turn off the printer's own color management in Print Settings… Nezapomeňte v nastavení tisku vypnout vlastní správu barev tiskárny… 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ů @@ -4063,12 +4062,12 @@ navigator Zoom Zvětšení Decrease Brush Hardness Snížit tvrdost štětce Increase Brush Hardness Zvýšit tvrdost štětce Demosaic Demozaikování - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Jak se doplňuje mozaika barevného filtru fotoaparátu. Použije se při otevření souboru; náhled ukazuje metodu, se kterou byl otevřen. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Jak se doplňuje mozaika barevného filtru fotoaparátu. Použije se při otevření souboru; náhled ukazuje metodu, se kterou byl otevřen. AHD (adaptive homogeneity) AHD (adaptivní homogenita) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: nejčistší hrany a nejméně barevných lemů, nejpomalejší. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolace s korekcí gradientu: ostrá a rychlá, s mírnými barevnými lemy v jemných detailech. - The fastest and the softest, with colour fringing on fine detail. Nejrychlejší a nejměkčí, s barevnými lemy v jemných detailech. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: nejčistší hrany a nejméně barevných lemů, nejpomalejší. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolace s korekcí gradientu: ostrá a rychlá, s mírnými barevnými lemy v jemných detailech. + The fastest and the softest, with color fringing on fine detail. Nejrychlejší a nejměkčí, s barevnými lemy v jemných detailech. “{name}” already exists. Replace it? „{name}“ již existuje. Nahradit? The name in the save dialog was “{name}”. Název v dialogu ukládání byl „{name}“. Export As: {name} Exportovat jako: {name} @@ -4346,6 +4345,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Pro každý kanál vyberte jiný dokument. A picked document is no longer open. Jeden z vybraných dokumentů už není otevřený. A picked document is no longer a grayscale document of the same size. Jeden z vybraných dokumentů už není dokument ve stupních šedi stejné velikosti. +# Move tool options bar (#11381) + Align top edges Zarovnat horní okraje + Align vertical centers Zarovnat svislé středy + Align bottom edges Zarovnat dolní okraje + Distribute vertically Rozmístit svisle + Distribute horizontally Rozmístit vodorovně + Show layer bounds on hover Zobrazit hranice vrstvy při najetí + Expand layer group on click Rozbalit skupinu vrstev kliknutím + Show hover bounds from Layers Zobrazit hranice při najetí z panelu Vrstvy +# Artboard tool options bar (#11385) + Distribute Widths Rozmístit šířky + Distribute Heights Rozmístit výšky + Auto-nest Layers Automaticky vnořovat vrstvy + Auto-size Canvas Automaticky měnit velikost plátna + Keep Relative Position During Layer Reordering Zachovat relativní polohu při změně pořadí vrstev + Shrinkwrap Canvas on Save Při uložení zmenšit plátno na obsah # JPEG Options: the size the file will have (#7843) Estimated file size Odhadovaná velikost souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index dc7ae940ac..cf9105b865 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -111,7 +111,6 @@ Export As… Eksportér som… Export Eksportér Export… Eksportér… - Quick Export As PNG Hurtig eksport som PNG Quick Export as PNG Hurtig eksport som PNG Place Embedded… Placér indlejret… Place Linked… Placér sammenkædet… @@ -315,7 +314,6 @@ All Alle Deselect Fjern markering Reselect Markér igen - Inverse Selection Invertér markering Inverse Invertér Color Range… Farveområde… Select and Mask… Markér og maskér… @@ -606,8 +604,8 @@ Background Baggrund Set foreground color Angiv forgrundsfarve Set background color Angiv baggrundsfarve - Swap colours (X) Ombyt farver (X) - Default colours (D) Standardfarver (D) + Switch Foreground and Background Colors (X) Byt om på forgrunds- og baggrundsfarver (X) + Default Foreground and Background Colors (D) Standard forgrunds- og baggrundsfarver (D) Brush Tool Options Penselværktøjsindstillinger Opacity Opacitet Flow Gennemstrømning @@ -1614,7 +1612,7 @@ Revert “{name}” to the last saved version? Your changes will be lost. Gendan »{name}« til den sidst gemte version? Dine ændringer går tabt. {key} to subtract {key} for at trække fra ↑↓ navigate {key} run esc close ↑↓ navigér {key} kør esc luk - Click to restore the current colour Klik for at gendanne den aktuelle farve + Click to restore the current color Klik for at gendanne den aktuelle farve Click with the Note tool to add a note. Klik med noteværktøjet for at tilføje en note. Drag a rectangle around the object Træk et rektangel omkring objektet Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Træk på billedet for at tilføje en begrænsning; Shift for vandret/lodret; højreklik på en begrænsning for at ændre eller slette den. @@ -1696,10 +1694,10 @@ Drag to move the active layer Træk for at flytte det aktive lag Drag to pan · hold Space with any tool Træk for at panorere · hold mellemrumstasten nede med et hvilket som helst værktøj Drag to draw a gradient Træk for at tegne en gradient - Click to fill similar colours Klik for at udfylde lignende farver + Click to fill similar colors Klik for at udfylde lignende farver Click to add text Klik for at tilføje tekst Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Træk (lasso) eller klik på punkter (polygonalt) · {add} tilføj · {sub} træk fra - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Træk en beskæringsramme · træk inde i den for at flytte · kanter ændrer størrelse ({ratio}-forhold, {centre} centreret) · Mellemrumstasten flytter, mens du tegner · piletaster skubber · X bytter orientering · {commit} bekræfter · Esc annullerer + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Træk en beskæringsramme · træk inde i den for at flytte · kanter ændrer størrelse ({ratio}-forhold, {centre} centreret) · Mellemrumstasten flytter, mens du tegner · piletaster skubber · X bytter orientering · {commit} bekræfter · Esc annullerer {mode} Color · {bits} bit {mode}-farve · {bits} bit Drag to move the layer Træk for at flytte laget Fit Screen Tilpas til skærm @@ -1731,7 +1729,7 @@ Appearance Udseende Text Position: Tekstplacering: Text color Tekstfarve - Uses the foreground and background colours. Bruger forgrundsfarven og baggrundsfarven. + Uses the foreground and background colors. Bruger forgrundsfarven og baggrundsfarven. Answer the unsaved-changes prompt first Besvar først dialogen om ikke-gemte ændringer Unsaved changes Ugemte ændringer Don't Save Gem ikke @@ -1751,7 +1749,7 @@ name navn new ny Go to Layer Gå til lag - Open a document to select a colour range. Åbn et dokument for at markere et farveområde. + Open a document to select a color range. Åbn et dokument for at markere et farveområde. Saved Gemt Reveal in Finder Vis i Finder Show in Explorer Vis i Stifinder @@ -1929,8 +1927,8 @@ Character Styles Panel Tegnstilpanel Clear Canvas Guides Ryd lærredshjælpelinjer Clear Selected Artboard Guides Ryd hjælpelinjer på markeret tavle - Color Blindness — Deuteranopia-type Farveblindhed — deuteranopi-type - Color Blindness — Protanopia-type Farveblindhed — protanopi-type + Color Blindness - Deuteranopia-type Farveblindhed — deuteranopi-type + Color Blindness - Protanopia-type Farveblindhed — protanopi-type Color Table… Farvetabel… Combine Shapes Kombinér former Contract… Formindsk… @@ -2104,7 +2102,7 @@ Canvas Lærred Capture Optag Center Crop Marks Centrerede beskæringsmærker - Centre the gradient (offset 0, 0) Centrér gradienten (forskydning 0, 0) + Center the gradient (offset 0, 0) Centrér gradienten (forskydning 0, 0) Change Screen Mode (F) Skift skærmtilstand (F) Change To: Ændr til: Clear All Ryd alt @@ -2256,7 +2254,7 @@ Roughness Ruhed Roundness Rundhed Rulers & Grids Linealer og gitter - Sample: foreground colour Prøve: forgrundsfarve + Sample: foreground color Prøve: forgrundsfarve Sampling: Background Swatch Prøvetagning: baggrundsfarveprøve Sampling: Continuous Prøvetagning: fortløbende Sampling: Once Prøvetagning: én gang @@ -2529,7 +2527,7 @@ Alt-click to define a source point to clone from Alt-klik for at definere et kildepunkt at klone fra No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Ingen sti at lave en markering ud fra: tegn én med penværktøjet, eller markér én i panelet Stier. Cancel opening Annullér åbning - Cancelled opening {name} Annullerede åbning af {name} + Canceled opening {name} Annullerede åbning af {name} Damaged Photoshop document Beskadiget Photoshop-dokument The document “{name}” may be damaged. Dokumentet »{name}« er muligvis beskadiget. Some layers, pixels or masks could not be read. Do you want to continue opening it? Nogle lag, pixels eller masker kunne ikke læses. Vil du fortsætte med at åbne det? @@ -2539,7 +2537,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokumentet »{name}« har en indlejret farveprofil, der ikke stemmer overens med det aktuelle {mode}-arbejdsfarverum. Working: {working} Arbejdsfarverum: {working} Developing {name} Fremkalder {name} - Cancelled {label} Annullerede {label} + Canceled {label} Annullerede {label} Esc to cancel Esc for at annullere Opened {name} Åbnede {name} Opening {name} Åbner {name} @@ -2547,7 +2545,7 @@ Saving {name} Gemmer {name} Saving {percent} Gemmer {percent} A save to {name} is still running; try again when it finishes Der gemmes stadig til {name}; prøv igen, når det er afsluttet - {label} is writing the file and can no longer be cancelled {label} skriver filen og kan ikke længere annulleres + {label} is writing the file and can no longer be canceled {label} skriver filen og kan ikke længere annulleres Opening {name}… Åbner {name}… Opening… Åbner… Reading… Læser… @@ -2644,7 +2642,7 @@ cameraRaw Roughness Ruhed Discard Layers and Save a Copy Kassér lag, og gem en kopi Don't show again Vis ikke igen Save failed: {error} Kunne ikke gemme: {error} - Save cancelled Gemning annulleret + Save canceled Gemning annulleret Couldn't place {name}: {error} Kunne ikke placere {name}: {error} Magnetic Lasso Tool Magnetisk lassoværktøj Frequency Frekvens @@ -2788,7 +2786,7 @@ fontWeight Italic Kursiv Impressionist Impressionistisk Rotate View Tool Værktøj til at rotere visningen Reset View Nulstil visning - Drag around the centre to rotate the view · Shift constrains to 15° Træk rundt om midtpunktet for at rotere visningen · Shift låser til 15° + Drag around the center to rotate the view · Shift constrains to 15° Træk rundt om midtpunktet for at rotere visningen · Shift låser til 15° # Painting symmetry presets. Dual Axis Dobbelt akse @@ -2808,11 +2806,11 @@ fontWeight Italic Kursiv All Layers No Adjustments Alle lag uden justeringer Current & Below No Adjustments Aktuelt og nedenunder uden justeringer Show Sampling Ring Vis prøvetagningsring - Click to sample the foreground colour · {key}-click for background Klik for at tage prøve af forgrundsfarven · {key}-klik for baggrundsfarven + Click to sample the foreground color · {key}-click for background Klik for at tage prøve af forgrundsfarven · {key}-klik for baggrundsfarven # Color Picker warnings - Out of gamut for printing: click for the nearest printable colour Uden for gamut ved udskrivning: klik for at få den nærmeste udskrivbare farve - Not a web colour: click for the nearest web colour Ikke en webfarve: klik for at få den nærmeste webfarve + Out of gamut for printing: click for the nearest printable color Uden for gamut ved udskrivning: klik for at få den nærmeste udskrivbare farve + Not a web color: click for the nearest web color Ikke en webfarve: klik for at få den nærmeste webfarve Color to Alpha… Farve til alfa… Transparency Threshold Grænseværdi for gennemsigtighed Opacity Threshold Grænseværdi for opacitet @@ -3230,7 +3228,7 @@ curves Smooth Udjævn # Native Windows printing qualification Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Kryds ikke også Spejlbillede af i Udskriftsindstillinger…: de to spejlvendinger ophæver hinanden. Print Settings… Udskriftsindstillinger… - Remember to turn off the printer's own colour management in Print Settings… Husk at slå printerens egen farvestyring fra i Udskriftsindstillinger… + Remember to turn off the printer's own color management in Print Settings… Husk at slå printerens egen farvestyring fra i Udskriftsindstillinger… Sent to {printer} Sendt til {printer} set in Print Settings… angivet i Udskriftsindstillinger… ICO is limited to 256 × 256 pixels ICO er begrænset til 256 × 256 pixels @@ -3894,12 +3892,12 @@ curves Smooth Udjævn In White Input-hvid Increase Brush Hardness Forøg penselhårdheden Demosaic Demosaicering - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hvordan kameraets farvefiltermosaik udfyldes. Det anvendes, når filen åbnes; forhåndsvisningen viser den metode, den blev åbnet med. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hvordan kameraets farvefiltermosaik udfyldes. Det anvendes, når filen åbnes; forhåndsvisningen viser den metode, den blev åbnet med. AHD (adaptive homogeneity) AHD (adaptiv homogenitet) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: de reneste kanter og de mindste farvefrynser, men den langsomste. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradientkorrigeret interpolation: skarp og hurtig, med nogle farvefrynser i fine detaljer. - The fastest and the softest, with colour fringing on fine detail. Den hurtigste og den blødeste, med farvefrynser i fine detaljer. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: de reneste kanter og de mindste farvefrynser, men den langsomste. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradientkorrigeret interpolation: skarp og hurtig, med nogle farvefrynser i fine detaljer. + The fastest and the softest, with color fringing on fine detail. Den hurtigste og den blødeste, med farvefrynser i fine detaljer. “{name}” already exists. Replace it? »{name}« findes allerede. Vil du erstatte den? The name in the save dialog was “{name}”. Navnet i dialogen Gem var »{name}«. Move Up Flyt op @@ -4550,7 +4548,6 @@ curves Smooth Udjævn Use File › Open to open an image. Brug Filer › Åbn for at åbne et billede. Use Selection In Source Brug markering i kilde Use Selection In Target Brug markering i mål - Uses the foreground and background colors. Bruger forgrunds- og baggrundsfarverne. Vanishing Point Forsvindingspunkt Variable Data Sets Variable datasæt Vector Mask Hides Effects Vektormaske skjuler effekter @@ -4760,8 +4757,8 @@ cameraRaw Camera Raw ({name}) Camera Raw ({name}) cameraRaw Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) cameraRaw Camera Raw isn't open Camera Raw er ikke åben cameraRaw Cancel Annullér -cameraRaw Cancelled opening {name} Annullerede åbning af {name} -cameraRaw Cancelled {label} Annullerede {label} +cameraRaw Canceled opening {name} Annullerede åbning af {name} +cameraRaw Canceled {label} Annullerede {label} cameraRaw Color Priority Farveprioritet cameraRaw Developing {name} Fremkalder {name} cameraRaw Full-resolution preview unavailable Forhåndsvisning i fuld opløsning er ikke tilgængelig @@ -4816,3 +4813,19 @@ cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet Pick a different document for each channel. Vælg et andet dokument til hver kanal. A picked document is no longer open. Et af de valgte dokumenter er ikke længere åbent. A picked document is no longer a grayscale document of the same size. Et af de valgte dokumenter er ikke længere et dokument i gråtoner i samme størrelse. +# Move tool options bar (#11381) + Align top edges Juster øverste kanter + Align vertical centers Juster lodrette midter + Align bottom edges Juster nederste kanter + Distribute vertically Fordel lodret + Distribute horizontally Fordel vandret + Show layer bounds on hover Vis lagets grænser ved svæv + Expand layer group on click Udvid lagergruppe ved klik + Show hover bounds from Layers Vis svævegrænser fra Lag +# Artboard tool options bar (#11385) + Distribute Widths Fordel bredder + Distribute Heights Fordel højder + Auto-nest Layers Indlejr lag automatisk + Auto-size Canvas Tilpas lærredsstørrelse automatisk + Keep Relative Position During Layer Reordering Bevar relativ placering ved omorganisering af lag + Shrinkwrap Canvas on Save Beskær lærredet til indholdet ved lagring diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7e6483b893..f7b6305595 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -639,7 +639,6 @@ Deselect Auswahl aufheben Reselect Erneut auswählen Inverse Umkehren - Inverse Selection Auswahl umkehren Similar Ähnliche Color Range… Farbbereich… Focus Area… Schärfebereich… @@ -759,8 +758,8 @@ Legacy Macintosh RGB (Gamma 1.8) Legacy-Macintosh-RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internet-Standard-RGB (sRGB) Monitor RGB Monitor-RGB - Color Blindness — Protanopia-type Farbenblindheit — Protanopie-Typ - Color Blindness — Deuteranopia-type Farbenblindheit — Deuteranopie-Typ + Color Blindness - Protanopia-type Farbenblindheit - Protanopie-Typ + Color Blindness - Deuteranopia-type Farbenblindheit - Deuteranopie-Typ Zoom In Vergrößern Zoom Out Verkleinern Fit on Screen Auf den Bildschirm einpassen @@ -1071,7 +1070,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Klicken fügt einen Punkt hinzu · Wegziehen, {key}-Klick oder Entfernen löscht ihn Click to apply, {key}-click to clear overrides, double-click for Style Options Klicken wendet an, {key}-Klick löscht Überschreibungen, Doppelklick öffnet die Stiloptionen Click to edit the gradient Klicke, um den Verlauf zu bearbeiten - Click to restore the current colour Klicke, um die aktuelle Farbe wiederherzustellen + Click to restore the current color Klicke, um die aktuelle Farbe wiederherzustellen Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Klicken vergrößert · {key}-Klick verkleinert · nach rechts/links ziehen zoomt rein/raus Click with the Note tool to add a note. Klicke mit dem Notiz-Werkzeug, um eine Notiz hinzuzufügen. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klick: Ecke · Ziehen: weich · Ersten Punkt klicken: schließen · {key} fertig · Esc abbrechen @@ -1157,7 +1156,7 @@ Darks Dunkle Data Sets Datensätze Default Standard - Default colours (D) Standardfarben (D) + Default Foreground and Background Colors (D) Standardfarben für Vorder- und Hintergrund (D) Default printer Standarddrucker Default restored. Standard wiederhergestellt. Define Definieren @@ -1440,7 +1439,7 @@ Opacity Jitter Deckkraftschwankung Opacity: Deckkraft: Open a document to define variables. Öffne ein Dokument, um Variablen zu definieren. - Open a document to select a colour range. Öffne ein Dokument, um einen Farbbereich auszuwählen. + Open a document to select a color range. Öffne ein Dokument, um einen Farbbereich auszuwählen. Open a document to use the timeline. Öffne ein Dokument, um die Zeitleiste zu nutzen. Optical Optisch Optimized Optimiert @@ -1516,7 +1515,6 @@ Purity Reinheit Quality Qualität Quick Actions Schnellaktionen - Quick Export As PNG Schnellexport als PNG Radial Gradient Radialer Verlauf Radius Radius Radius: Radius: @@ -1658,7 +1656,7 @@ Subtract from Sample Von der Probe abziehen Subtract from selection ({key}) Von Auswahl abziehen ({key}) Suggestions: Vorschläge: - Swap colours (X) Farben tauschen (X) + Switch Foreground and Background Colors (X) Vorder- und Hintergrundfarbe vertauschen (X) Swaps height and width Tauscht Höhe und Breite Switch between free transform and warp modes Zwischen freier Transformation und Verkrümmen wechseln Switch theme Design wechseln @@ -1761,7 +1759,7 @@ Choke Drosselung Classic Klassisch Click to add text Klicken, um Text hinzuzufügen - Click to fill similar colours Klicken, um ähnliche Farben zu füllen + Click to fill similar colors Klicken, um ähnliche Farben zu füllen Clone Stamp Tool Kopierstempel-Werkzeug Color Burn Farbig nachbelichten Color Dodge Farbig abwedeln @@ -1921,7 +1919,7 @@ Rectangular Marquee Tool Rechteckauswahl-Werkzeug Reds Rottöne Reflected Reflektiert - Sample: foreground colour Abtasten: Vordergrundfarbe + Sample: foreground color Abtasten: Vordergrundfarbe Sampled Colors Aufgenommene Farben Satin Satin Save Pixel Aspect Ratio Pixel-Seitenverhältnis speichern @@ -1960,7 +1958,7 @@ Transfer Übertragung Triangle Tool Dreieck-Werkzeug Unsaved changes Ungespeicherte Änderungen - Uses the foreground and background colours. Nutzt die Vordergrund- und Hintergrundfarben. + Uses the foreground and background colors. Nutzt die Vordergrund- und Hintergrundfarben. Web Web Web Large Web Groß Web Minimum Web Minimum @@ -1997,6 +1995,7 @@ Allow scripts to connect Skriptverbindungen erlauben Always Immer Always create smart objects when placing Beim Platzieren immer Smart-Objekte erstellen + Skip transform when placing Transformieren beim Platzieren überspringen Animated zoom Animierter Zoom Apply auto tone Automatische Tonwertkorrektur anwenden Ask Nachfragen @@ -2232,7 +2231,7 @@ Graphics Grafik Reset GPU Backend GPU-Backend zurücksetzen Applies at next launch. Wird beim nächsten Start angewendet. - Click to sample the foreground colour · {key}-click for background Klicken nimmt die Vordergrundfarbe auf · {key}-Klick für den Hintergrund + Click to sample the foreground color · {key}-click for background Klicken nimmt die Vordergrundfarbe auf · {key}-Klick für den Hintergrund {key}-click to set the source {key}-Klick setzt die Quelle {key} to subtract {key} zum Abziehen Clone source {n} ({key}-click with Clone Stamp to set) Klonquelle {n} ({key}-Klick mit dem Kopierstempel zum Setzen) @@ -2293,7 +2292,7 @@ Gradient Options Verlaufsoptionen Align with layer An Ebene ausrichten Reset Alignment Ausrichtung zurücksetzen - Centre the gradient (offset 0, 0) Verlauf zentrieren (Versatz 0, 0) + Center the gradient (offset 0, 0) Verlauf zentrieren (Versatz 0, 0) Gradient Editor Gradienten-Editor Gradient picker Verlaufsauswahl Gradient stops Verlaufsstufen @@ -2327,7 +2326,7 @@ Alt-click to define a source point to clone from Alt-Klick legt einen Quellpunkt zum Klonen fest No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Kein Pfad für eine Auswahl vorhanden: zeichne einen mit dem Stift-Werkzeug oder wähle einen im Pfade-Bedienfeld. Cancel opening Öffnen abbrechen - Cancelled opening {name} Öffnen von {name} abgebrochen + Canceled opening {name} Öffnen von {name} abgebrochen Damaged Photoshop document Beschädigtes Photoshop-Dokument The document “{name}” may be damaged. Das Dokument „{name}“ ist möglicherweise beschädigt. Some layers, pixels or masks could not be read. Do you want to continue opening it? Einige Ebenen, Pixel oder Masken konnten nicht gelesen werden. Möchten Sie das Öffnen fortsetzen? @@ -2337,7 +2336,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Das Dokument „{name}“ hat ein eingebettetes Farbprofil, das nicht zum aktuellen {mode}-Arbeitsfarbraum passt. Working: {working} Arbeitsfarbraum: {working} Developing {name} {name} wird entwickelt - Cancelled {label} {label} abgebrochen + Canceled {label} {label} abgebrochen Esc to cancel Esc zum Abbrechen Opened {name} Geöffnet: {name} Opening {name} Öffne {name} @@ -2345,7 +2344,7 @@ Saving {name} Speichere {name} Saving {percent} Speichern {percent} A save to {name} is still running; try again when it finishes {name} wird noch gespeichert; versuchen Sie es erneut, wenn der Vorgang abgeschlossen ist - {label} is writing the file and can no longer be cancelled {label} schreibt die Datei und kann nicht mehr abgebrochen werden + {label} is writing the file and can no longer be canceled {label} schreibt die Datei und kann nicht mehr abgebrochen werden Opening {name}… Öffne {name}… Opening… Öffnen… Reading… Lesen… @@ -2408,7 +2407,7 @@ Pixel Pixel Adjustment Anpassung Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Ziehen (Lasso) oder Punkte klicken (polygonal) · {add} hinzufügen · {sub} abziehen - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Freistellrahmen ziehen · innen ziehen verschiebt · Kanten skalieren ({ratio} Verhältnis, {centre} zentriert) · Leertaste verschiebt beim Zeichnen · Pfeiltasten verschieben · X tauscht Ausrichtung · {commit} übernimmt · Esc bricht ab + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Freistellrahmen ziehen · innen ziehen verschiebt · Kanten skalieren ({ratio} Verhältnis, {centre} zentriert) · Leertaste verschiebt beim Zeichnen · Pfeiltasten verschieben · X tauscht Ausrichtung · {commit} übernimmt · Esc bricht ab {mode} Color · {bits} bit {mode}-Farbe · {bits} Bit Scrubby Zoom Schleppzoom Auto Erase Automatisch löschen @@ -2503,7 +2502,7 @@ Discard Layers and Save a Copy Ebenen verwerfen und Kopie speichern Don't show again Nicht mehr anzeigen Save failed: {error} Speichern fehlgeschlagen: {error} - Save cancelled Speichern abgebrochen + Save canceled Speichern abgebrochen Style {name} saved Stil {name} gespeichert Make Default Als Standard festlegen Reset to Default Auf Standard zurücksetzen @@ -2640,7 +2639,7 @@ fontWeight Italic Kursiv Rotate View Ansicht drehen Rotate View Tool Ansicht-drehen-Werkzeug Reset View Ansicht zurücksetzen - Drag around the centre to rotate the view · Shift constrains to 15° Ansicht drehen: im Bogen ziehen · Umschalt: 15°-Schritte + Drag around the center to rotate the view · Shift constrains to 15° Ansicht drehen: im Bogen ziehen · Umschalt: 15°-Schritte Dual Axis Duale Achse Diagonal Diagonal Transform Symmetry Symmetrie transformieren @@ -2655,8 +2654,8 @@ fontWeight Italic Kursiv All Layers No Adjustments Alle Ebenen ohne Einstellungen Current & Below No Adjustments Aktuelle und darunter ohne Einstellungen Show Sampling Ring Aufnahmering anzeigen - Out of gamut for printing: click for the nearest printable colour Außerhalb des Druckfarbumfangs: Klicken für die nächstliegende druckbare Farbe - Not a web colour: click for the nearest web colour Keine Webfarbe: Klicken für die nächstliegende Webfarbe + Out of gamut for printing: click for the nearest printable color Außerhalb des Druckfarbumfangs: Klicken für die nächstliegende druckbare Farbe + Not a web color: click for the nearest web color Keine Webfarbe: Klicken für die nächstliegende Webfarbe Color to Alpha… Farbe zu Alpha… Transparency Threshold Transparenz-Schwellenwert Opacity Threshold Deckkraft-Schwellenwert @@ -3329,7 +3328,7 @@ curves Smooth Glätten Auto Add/Delete Autom. hinzuf./löschen Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Aktiviere nicht zusätzlich das Spiegelbild in den Druckeinstellungen: Die beiden Spiegelungen heben sich auf. Print Settings… Druckeinstellungen… - Remember to turn off the printer's own colour management in Print Settings… Denke daran, die eigene Farbverwaltung des Druckers in den Druckeinstellungen auszuschalten… + Remember to turn off the printer's own color management in Print Settings… Denke daran, die eigene Farbverwaltung des Druckers in den Druckeinstellungen auszuschalten… 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 @@ -3462,12 +3461,12 @@ curves Smooth Glätten {name} was changed by another app after it was opened or saved here. {name} wurde von einer anderen App geändert, nachdem es hier geöffnet oder gespeichert wurde. Replace it with this document, or cancel and use File › Save As to keep both. Ersetze die Datei durch dieses Dokument oder brich ab und nutze Datei › Speichern unter, um beide zu behalten. Demosaic Demosaicing - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Wie das Farbfiltermosaik der Kamera aufgefüllt wird. Es wird beim Öffnen der Datei angewendet; die Vorschau zeigt die Methode, mit der sie geöffnet wurde. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Wie das Farbfiltermosaik der Kamera aufgefüllt wird. Es wird beim Öffnen der Datei angewendet; die Vorschau zeigt die Methode, mit der sie geöffnet wurde. AHD (adaptive homogeneity) AHD (adaptive Homogenität) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: die saubersten Kanten und die wenigsten Farbsäume, am langsamsten. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradientenkorrigierte Interpolation: scharf und schnell, mit etwas Farbsäumen an feinen Details. - The fastest and the softest, with colour fringing on fine detail. Am schnellsten und weichsten, mit Farbsäumen an feinen Details. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: die saubersten Kanten und die wenigsten Farbsäume, am langsamsten. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradientenkorrigierte Interpolation: scharf und schnell, mit etwas Farbsäumen an feinen Details. + The fastest and the softest, with color fringing on fine detail. Am schnellsten und weichsten, mit Farbsäumen an feinen Details. “{name}” already exists. Replace it? „{name}“ ist bereits vorhanden. Ersetzen? The name in the save dialog was “{name}”. Der Name im Speichern-Dialog war „{name}“. Memory Usage Speichernutzung @@ -3641,6 +3640,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Wählen Sie für jeden Kanal ein anderes Dokument. A picked document is no longer open. Ein ausgewähltes Dokument ist nicht mehr geöffnet. A picked document is no longer a grayscale document of the same size. Ein ausgewähltes Dokument ist kein Graustufen-Dokument derselben Größe mehr. +# Move tool options bar (#11381) + Align top edges Obere Kanten ausrichten + Align vertical centers Vertikale Mitten ausrichten + Align bottom edges Untere Kanten ausrichten + Distribute vertically Vertikal verteilen + Distribute horizontally Horizontal verteilen + Show layer bounds on hover Ebenenbegrenzung beim Darüberfahren anzeigen + Expand layer group on click Ebenengruppe per Klick erweitern + Show hover bounds from Layers Begrenzung beim Darüberfahren aus Ebenen anzeigen +# Artboard tool options bar (#11385) + Distribute Widths Breiten verteilen + Distribute Heights Höhen verteilen + Auto-nest Layers Ebenen automatisch verschachteln + Auto-size Canvas Zeichenflächengröße automatisch anpassen + Keep Relative Position During Layer Reordering Relative Position beim Neuanordnen von Ebenen beibehalten + Shrinkwrap Canvas on Save Zeichenfläche beim Speichern auf den Inhalt verkleinern # JPEG Options: the size the file will have (#7843) Estimated file size Geschätzte Dateigröße diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2bdcf77bc5..dcd48034b2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -867,7 +867,7 @@ Current Layer Τρέχον επίπεδο Current Size Τρέχον μέγεθος Custom Shapes Προσαρμοσμένα σχήματα - Default colours (D) Προεπιλεγμένα χρώματα (D) + Default Foreground and Background Colors (D) Προεπιλεγμένα χρώματα (D) Default printer Προεπιλεγμένος εκτυπωτής Default restored. Έγινε επαναφορά των προεπιλογών. Define at least one variable first. Ορίστε πρώτα τουλάχιστον μία μεταβλητή. @@ -893,7 +893,7 @@ Drop an image or PSD anywhere to open it. Σύρετε μια εικόνα ή ένα PSD εδώ για να το ανοίξετε. Native file drag-and-drop is unavailable Η μεταφορά και απόθεση αρχείων δεν είναι διαθέσιμη Open a document to define variables. Ανοίξτε ένα έγγραφο για να ορίσετε μεταβλητές. - Open a document to select a colour range. Ανοίξτε ένα έγγραφο για να επιλέξετε εύρος χρωμάτων. + Open a document to select a color range. Ανοίξτε ένα έγγραφο για να επιλέξετε εύρος χρωμάτων. Open a document to use the timeline. Ανοίξτε ένα έγγραφο για να χρησιμοποιήσετε τη χρονογραμμή. Option-click to define a source point to clone from Πατήστε Option και κάντε κλικ για να ορίσετε σημείο προέλευσης κλωνοποίησης Output Channel: Κανάλι εξόδου: @@ -928,7 +928,6 @@ Protect Foreground Color Προστασία χρώματος προσκηνίου Protect Tones Προστασία τονικών τιμών Quick Actions Γρήγορες ενέργειες - Quick Export As PNG Γρήγορη εξαγωγή ως PNG Radial Gradient Ακτινική διαβάθμιση Paints from the document's opening state Ζωγραφίζει χρησιμοποιώντας την αρχική κατάσταση του εγγράφου PhotoCraft website Ιστότοπος PhotoCraft @@ -938,7 +937,7 @@ Portrait, 5 x 7 Κατακόρυφο, 5 × 7 Protect Texture Προστασία υφής Recent Πρόσφατα - Sample: foreground colour Δείγμα: χρώμα προσκηνίου + Sample: foreground color Δείγμα: χρώμα προσκηνίου Sampled Colors Χρώματα δείγματος Save Pixel Aspect Ratio Διατήρηση αναλογίας εικονοστοιχείων Scratch Sizes Μεγέθη πρόχειρης μνήμης @@ -1239,7 +1238,7 @@ Discard Layers and Save a Copy Απόρριψη επιπέδων και αποθήκευση αντιγράφου Don't show again Να μην εμφανιστεί ξανά Save failed: {error} Αποτυχία αποθήκευσης: {error} - Save cancelled Η αποθήκευση ακυρώθηκε + Save canceled Η αποθήκευση ακυρώθηκε Use tablet pressure to change pen width Χρησιμοποιήστε την πίεση της γραφίδας για να αλλάξετε το πλάτος της Date and Time Ημερομηνία και ώρα Scale Units Μονάδες κλίμακας @@ -1695,7 +1694,7 @@ Gradient Options Επιλογές διαβάθμισης Align with layer Στοίχιση με το επίπεδο Reset Alignment Επαναφορά στοίχισης - Centre the gradient (offset 0, 0) Κεντράρισμα διαβάθμισης (μετατόπιση 0, 0) + Center the gradient (offset 0, 0) Κεντράρισμα διαβάθμισης (μετατόπιση 0, 0) Refine Strokes Πινελιές βελτίωσης Edits Επεξεργασίες Gradient Editor Επεξεργασία διαβάθμισης @@ -1725,7 +1724,7 @@ Alt-click to define a source point to clone from Alt-κλικ για ορισμό σημείου προέλευσης κλωνοποίησης No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Δεν υπάρχει διαδρομή για δημιουργία επιλογής: σχεδιάστε μία με το εργαλείο Πένα (Pen Tool) ή επιλέξτε μία στο πλαίσιο Διαδρομές. Cancel opening Ακύρωση ανοίγματος - Cancelled opening {name} Ακυρώθηκε το άνοιγμα του {name} + Canceled opening {name} Ακυρώθηκε το άνοιγμα του {name} Damaged Photoshop document Κατεστραμμένο έγγραφο Photoshop The document “{name}” may be damaged. Το έγγραφο «{name}» μπορεί να είναι κατεστραμμένο. Some layers, pixels or masks could not be read. Do you want to continue opening it? Δεν ήταν δυνατή η ανάγνωση ορισμένων επιπέδων, εικονοστοιχείων ή μασκών. Θέλετε να συνεχίσετε το άνοιγμα; @@ -1733,7 +1732,7 @@ The document “{name}” does not have an embedded {mode} profile. Το έγγραφο «{name}» δεν έχει ενσωματωμένο προφίλ {mode}. The document “{name}” has an embedded color profile that does not match the current {mode} working space. Το έγγραφο «{name}» έχει ενσωματωμένο χρωματικό προφίλ που δεν ταιριάζει με τον τρέχοντα χώρο εργασίας {mode}. Working: {working} Χώρος εργασίας: {working} - Cancelled {label} Ακυρώθηκε: {label} + Canceled {label} Ακυρώθηκε: {label} Esc to cancel Esc για ακύρωση Opened {name} Άνοιξε το {name} Opening {name} Άνοιγμα του {name} @@ -1741,7 +1740,7 @@ Saving {name} Αποθήκευση του {name} Saving {percent} Αποθήκευση {percent} A save to {name} is still running; try again when it finishes Η αποθήκευση στο {name} βρίσκεται ακόμη σε εξέλιξη· δοκιμάστε ξανά όταν ολοκληρωθεί - {label} is writing the file and can no longer be cancelled {label}: γίνεται εγγραφή του αρχείου και δεν μπορεί πλέον να ακυρωθεί + {label} is writing the file and can no longer be canceled {label}: γίνεται εγγραφή του αρχείου και δεν μπορεί πλέον να ακυρωθεί Opening {name}… Άνοιγμα του {name}… Opening… Άνοιγμα… Reading… Ανάγνωση… @@ -1756,6 +1755,7 @@ Allow agent control Να επιτρέπεται ο έλεγχος από πράκτορες Allow scripts to connect Να επιτρέπεται η σύνδεση σεναρίων Always create smart objects when placing Να δημιουργούνται πάντα έξυπνα αντικείμενα κατά την τοποθέτηση + Skip transform when placing Παράλειψη μετασχηματισμού κατά την τοποθέτηση Animated zoom Κινούμενη μεγέθυνση Apply auto tone Εφαρμογή αυτόματης τονικής διόρθωσης Ask before saving layered tiff Ερώτηση πριν από την αποθήκευση TIFF με επίπεδα @@ -2316,9 +2316,9 @@ Click to add text Κάντε κλικ για προσθήκη κειμένου Click to apply, {key}-click to clear overrides, double-click for Style Options Κλικ για εφαρμογή, {key}-κλικ για απαλοιφή αλλαγών, διπλό κλικ για επιλογές στυλ Click to edit the gradient Κάντε κλικ για επεξεργασία της διαβάθμισης - Click to fill similar colours Κάντε κλικ για γέμισμα παρόμοιων χρωμάτων - Click to restore the current colour Κάντε κλικ για επαναφορά του τρέχοντος χρώματος - Click to sample the foreground colour · {key}-click for background Κλικ για δειγματοληψία χρώματος προσκηνίου · {key}-κλικ για φόντο + Click to fill similar colors Κάντε κλικ για γέμισμα παρόμοιων χρωμάτων + Click to restore the current color Κάντε κλικ για επαναφορά του τρέχοντος χρώματος + Click to sample the foreground color · {key}-click for background Κλικ για δειγματοληψία χρώματος προσκηνίου · {key}-κλικ για φόντο Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Κλικ για μεγέθυνση · {key}-κλικ για σμίκρυνση · σύρσιμο δεξιά/αριστερά για αλλαγή μεγέθυνσης Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Κλικ: γωνία · Σύρσιμο: εξομάλυνση · Κλικ στο πρώτο σημείο: κλείσιμο · {key}: τέλος · Esc: ακύρωση Click: corner · Drag: smooth · {alt}-drag: break handle · Click or drag first point: close · {key} finish · Esc cancel Κλικ: γωνία · Σύρσιμο: εξομάλυνση · {alt}+σύρσιμο: διάσπαση λαβής · Κλικ ή σύρσιμο στο πρώτο σημείο: κλείσιμο · {key}: τέλος · Esc: ακύρωση @@ -2335,8 +2335,8 @@ Collapse Σύμπτυξη Collapse group ({key}-click: all groups) Σύμπτυξη ομάδας ({key}-κλικ: όλες οι ομάδες) Color & Swatches Χρώμα και δείγματα - Color Blindness — Deuteranopia-type Αχρωματοψία — τύπος δευτερανωπίας - Color Blindness — Protanopia-type Αχρωματοψία — τύπος πρωτανωπίας + Color Blindness - Deuteranopia-type Αχρωματοψία - τύπος δευτερανωπίας + Color Blindness - Protanopia-type Αχρωματοψία - τύπος πρωτανωπίας Color Decontaminate Απομάκρυνση χρωματικής επιμόλυνσης Color Dynamics Δυναμική χρώματος Color Halftone Χρωματικός ημιτονισμός @@ -2469,8 +2469,8 @@ Dots Κουκκίδες Down Κάτω Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Σύρετε για λάσο ή κάντε κλικ για πολυγωνική επιλογή · {add} προσθήκη · {sub} αφαίρεση - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Σύρετε για περιοχή περικοπής · σύρετε στο εσωτερικό για μετακίνηση · από τα άκρα αλλάζει μέγεθος ({ratio} αναλογία, {centre} κέντρο) · Space για μετακίνηση κατά τη σχεδίαση · βέλη για μετακίνηση · X εναλλαγή προσανατολισμού · {commit} εφαρμογή · Esc ακύρωση - Drag around the centre to rotate the view · Shift constrains to 15° Σύρετε γύρω από το κέντρο για να περιστρέψετε την προβολή · Shift περιορίζει στις 15° + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Σύρετε για περιοχή περικοπής · σύρετε στο εσωτερικό για μετακίνηση · από τα άκρα αλλάζει μέγεθος ({ratio} αναλογία, {centre} κέντρο) · Space για μετακίνηση κατά τη σχεδίαση · βέλη για μετακίνηση · X εναλλαγή προσανατολισμού · {commit} εφαρμογή · Esc ακύρωση + Drag around the center to rotate the view · Shift constrains to 15° Σύρετε γύρω από το κέντρο για να περιστρέψετε την προβολή · Shift περιορίζει στις 15° Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Σύρετε πάνω στην εικόνα για προσθήκη περιορισμού· Shift για οριζόντιο/κατακόρυφο· δεξί κλικ σε έναν περιορισμό για αλλαγή ή διαγραφή. Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Σύρετε ή κάντε κλικ για πολυγωνικά σημεία · κρατήστε Alt κατά το λάσο για ευθείες · {add} προσθήκη · {sub} αφαίρεση πριν από τη σχεδίαση Drag to draw a gradient Σύρετε για να σχεδιάσετε διαβάθμιση @@ -2692,7 +2692,6 @@ Intersect with selection ({key}) Τομή με την επιλογή ({key}) Intersect with selection (⇧⌥) Τομή με την επιλογή (⇧⌥) Invalid {mode} profile Μη έγκυρο προφίλ {mode} - Inverse Selection Αντιστροφή επιλογής Invert All Αντιστροφή όλων Invert has no settings. Η αντιστροφή δεν διαθέτει ρυθμίσεις. Invert… Αντιστροφή… @@ -3284,7 +3283,7 @@ Sumi-e Ιαπωνική ζωγραφική με μελάνι Surface Blur Θόλωση επιφάνειας Surface Blur… Θόλωση επιφάνειας… - Swap colours (X) Εναλλαγή χρωμάτων (X) + Switch Foreground and Background Colors (X) Εναλλαγή χρωμάτων (X) Swaps height and width Εναλλαγή ύψους και πλάτους Swash Διακοσμητικά τελειώματα Switch between free transform and warp modes Εναλλαγή ελεύθερου μετασχηματισμού και παραμόρφωσης @@ -3357,7 +3356,6 @@ Use File › Open to open an image. Χρησιμοποιήστε Αρχείο › Άνοιγμα για να ανοίξετε μια εικόνα. Use Legacy Χρήση παλαιάς λειτουργίας Use Measurement Scale Χρήση κλίμακας μέτρησης - Uses the foreground and background colours. Χρησιμοποιεί τα χρώματα προσκηνίου και φόντου. Vanishing Point Σημείο φυγής Vanishing Point… Σημείο φυγής… Variable Data Sets Σύνολα δεδομένων μεταβλητών @@ -3710,8 +3708,8 @@ fontWeight Thin Πολύ λεπτά All Layers No Adjustments Όλα τα επίπεδα χωρίς προσαρμογές Current & Below No Adjustments Τρέχον και υποκείμενα χωρίς προσαρμογές Show Sampling Ring Εμφάνιση δακτυλίου δειγματοληψίας - Out of gamut for printing: click for the nearest printable colour Εκτός γκάμας εκτύπωσης: κάντε κλικ για το πλησιέστερο εκτυπώσιμο χρώμα - Not a web colour: click for the nearest web colour Δεν είναι χρώμα web: κάντε κλικ για το πλησιέστερο χρώμα web + Out of gamut for printing: click for the nearest printable color Εκτός γκάμας εκτύπωσης: κάντε κλικ για το πλησιέστερο εκτυπώσιμο χρώμα + Not a web color: click for the nearest web color Δεν είναι χρώμα web: κάντε κλικ για το πλησιέστερο χρώμα web Color to Alpha… Χρώμα σε άλφα… Transparency Threshold Κατώφλι διαφάνειας Opacity Threshold Κατώφλι αδιαφάνειας @@ -4012,7 +4010,7 @@ curves Smooth Εξομάλυνση Auto Add/Delete Αυτόματη προσθήκη/διαγραφή Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Μην ενεργοποιείτε επίσης τον κατοπτρισμό στις ρυθμίσεις εκτύπωσης: οι δύο αναστροφές αλληλοαναιρούνται. Print Settings… Ρυθμίσεις εκτύπωσης… - Remember to turn off the printer's own colour management in Print Settings… Θυμηθείτε να απενεργοποιήσετε τη διαχείριση χρωμάτων του εκτυπωτή στις ρυθμίσεις εκτύπωσης… + Remember to turn off the printer's own color management in Print Settings… Θυμηθείτε να απενεργοποιήσετε τη διαχείριση χρωμάτων του εκτυπωτή στις ρυθμίσεις εκτύπωσης… Sent to {printer} Στάλθηκε στον {printer} set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης… ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία @@ -4143,12 +4141,12 @@ curves Smooth Εξομάλυνση Decrease Brush Hardness Μείωση σκληρότητας πινέλου Increase Brush Hardness Αύξηση σκληρότητας πινέλου Demosaic Αποψηφιδοποίηση - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Πώς συμπληρώνεται το ψηφιδωτό του χρωματικού φίλτρου της κάμερας. Εφαρμόζεται όταν ανοίγει το αρχείο· η προεπισκόπηση δείχνει τη μέθοδο με την οποία άνοιξε. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Πώς συμπληρώνεται το ψηφιδωτό του χρωματικού φίλτρου της κάμερας. Εφαρμόζεται όταν ανοίγει το αρχείο· η προεπισκόπηση δείχνει τη μέθοδο με την οποία άνοιξε. AHD (adaptive homogeneity) AHD (προσαρμοστική ομοιογένεια) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: οι πιο καθαρές ακμές και τα λιγότερα χρωματικά περιθώρια, η πιο αργή. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Παρεμβολή με διόρθωση κλίσης: ευκρινής και γρήγορη, με λίγα χρωματικά περιθώρια στις λεπτές λεπτομέρειες. - The fastest and the softest, with colour fringing on fine detail. Η πιο γρήγορη και η πιο μαλακή, με χρωματικά περιθώρια στις λεπτές λεπτομέρειες. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: οι πιο καθαρές ακμές και τα λιγότερα χρωματικά περιθώρια, η πιο αργή. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Παρεμβολή με διόρθωση κλίσης: ευκρινής και γρήγορη, με λίγα χρωματικά περιθώρια στις λεπτές λεπτομέρειες. + The fastest and the softest, with color fringing on fine detail. Η πιο γρήγορη και η πιο μαλακή, με χρωματικά περιθώρια στις λεπτές λεπτομέρειες. “{name}” already exists. Replace it? Το «{name}» υπάρχει ήδη. Να αντικατασταθεί; The name in the save dialog was “{name}”. Το όνομα στο παράθυρο αποθήκευσης ήταν «{name}». Previous Brush Προηγούμενο πινέλο @@ -4306,6 +4304,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Επιλέξτε διαφορετικό έγγραφο για κάθε κανάλι. A picked document is no longer open. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον ανοιχτό. A picked document is no longer a grayscale document of the same size. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον έγγραφο σε κλίμακα του γκρι ίδιου μεγέθους. +# Move tool options bar (#11381) + Align top edges Στοίχιση πάνω άκρων + Align vertical centers Στοίχιση κατακόρυφων κέντρων + Align bottom edges Στοίχιση κάτω άκρων + Distribute vertically Κατανομή κατακόρυφα + Distribute horizontally Κατανομή οριζόντια + Show layer bounds on hover Εμφάνιση ορίων στρώσης στο πέρασμα του δείκτη + Expand layer group on click Ανάπτυξη ομάδας στρώσεων με κλικ + Show hover bounds from Layers Εμφάνιση ορίων στο πέρασμα από τις Στρώσεις +# Artboard tool options bar (#11385) + Distribute Widths Κατανομή πλατών + Distribute Heights Κατανομή υψών + Auto-nest Layers Αυτόματη ένθεση επιπέδων + Auto-size Canvas Αυτόματη αλλαγή μεγέθους καμβά + Keep Relative Position During Layer Reordering Διατήρηση σχετικής θέσης κατά την αναδιάταξη επιπέδων + Shrinkwrap Canvas on Save Σμίκρυνση καμβά στο περιεχόμενο κατά την αποθήκευση # JPEG Options: the size the file will have (#7843) Estimated file size Εκτιμώμενο μέγεθος αρχείου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 80527d1baa..cb000de571 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -603,7 +603,6 @@ Deselect Deseleccionar Reselect Volver a seleccionar Inverse Invertir - Inverse Selection Invertir selección Similar Similar Color Range… Gama de colores… Focus Area… Área de enfoque… @@ -724,8 +723,8 @@ Legacy Macintosh RGB (Gamma 1.8) RGB heredado de Macintosh (Gamma 1.8) Internet Standard RGB (sRGB) RGB estándar de Internet (sRGB) Monitor RGB RGB del monitor - Color Blindness — Protanopia-type Daltonismo — tipo protanopia - Color Blindness — Deuteranopia-type Daltonismo — tipo deuteranopia + Color Blindness - Protanopia-type Daltonismo - tipo protanopia + Color Blindness - Deuteranopia-type Daltonismo - tipo deuteranopia Zoom In Acercar Zoom Out Alejar Fit on Screen Encajar en pantalla @@ -1044,7 +1043,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Clic para añadir un punto · arrastre fuera, {key}-clic o Delete para quitar Click to apply, {key}-click to clear overrides, double-click for Style Options Clic para aplicar, {key}-clic para quitar excepciones, doble clic para Opciones de estilo Click to edit the gradient Haga clic para editar el degradado - Click to restore the current colour Haga clic para restaurar el color actual + Click to restore the current color Haga clic para restaurar el color actual Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Clic para acercar · {key}-clic para alejar · arrastre a la derecha/izquierda para acercar/alejar Click with the Note tool to add a note. Haga clic con la herramienta Nota para añadir una nota. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Clic: esquina · Arrastrar: suavizar · Clic en el primer punto: cerrar · {key}: terminar · Esc: cancelar @@ -1127,7 +1126,7 @@ Darks Oscuros Data Sets Conjuntos de datos Default Predeterminado - Default colours (D) Colores predeterminados (D) + Default Foreground and Background Colors (D) Colores frontal y de fondo predeterminados (D) Default printer Impresora predeterminada Default restored. Se restauraron los valores predeterminados. Define Definir @@ -1409,7 +1408,7 @@ Opacity Jitter Variación de opacidad Opacity: Opacidad: Open a document to define variables. Abra un documento para definir variables. - Open a document to select a colour range. Abra un documento para seleccionar una gama de colores. + Open a document to select a color range. Abra un documento para seleccionar una gama de colores. Open a document to use the timeline. Abra un documento para usar la línea de tiempo. Optical Óptico Optimized Optimizado @@ -1485,7 +1484,6 @@ Purity Pureza Quality Calidad Quick Actions Acciones rápidas - Quick Export As PNG Exportación rápida como PNG Radial Gradient Degradado radial Radius Radio Radius: Radio: @@ -1627,7 +1625,7 @@ Subtract from Sample Restar de la muestra Subtract from selection ({key}) Restar de la selección ({key}) Suggestions: Sugerencias: - Swap colours (X) Intercambiar colores (X) + Switch Foreground and Background Colors (X) Intercambiar colores frontal y de fondo (X) Swaps height and width Intercambia la altura y el ancho Switch between free transform and warp modes Cambiar entre los modos de transformación libre y deformación Switch theme Cambiar tema @@ -1730,7 +1728,7 @@ Choke Contraer Classic Clásico Click to add text Haga clic para añadir texto - Click to fill similar colours Haga clic para rellenar colores similares + Click to fill similar colors Haga clic para rellenar colores similares Clone Stamp Tool Herramienta Tampón de clonar Color Burn Subexposición de color Color Dodge Sobreexposición de color @@ -1891,7 +1889,7 @@ Rectangular Marquee Tool Herramienta Marco rectangular Reds Rojos Reflected Reflejado - Sample: foreground colour Muestra: color frontal + Sample: foreground color Muestra: color frontal Sampled Colors Colores muestreados Satin Satinado Save Pixel Aspect Ratio Guardar relación de aspecto de píxel @@ -1930,7 +1928,6 @@ Transfer Transferencia Triangle Tool Herramienta Triángulo Unsaved changes Cambios sin guardar - Uses the foreground and background colours. Usa los colores frontal y de fondo. Web Web Web Large Web (grande) Web Minimum Web (mínimo) @@ -1967,6 +1964,7 @@ Allow scripts to connect Permitir que las secuencias de comandos se conecten Always Siempre Always create smart objects when placing Crear siempre objetos inteligentes al colocar + Skip transform when placing Omitir la transformación al colocar Animated zoom Zoom animado Apply auto tone Aplicar el tono automático Ask Preguntar @@ -2202,7 +2200,7 @@ Graphics Gráficos Reset GPU Backend Restablecer el backend de GPU Applies at next launch. Se aplicará en el próximo inicio. - Click to sample the foreground colour · {key}-click for background Clic para muestrear el color frontal · {key}-clic para el de fondo + Click to sample the foreground color · {key}-click for background Clic para muestrear el color frontal · {key}-clic para el de fondo {key}-click to set the source {key}-clic para establecer el origen {key} to subtract {key} para restar Clone source {n} ({key}-click with Clone Stamp to set) Origen de clonado {n} ({key}-clic con Tampón de clonar para establecerlo) @@ -2263,7 +2261,7 @@ Gradient Options Opciones de degradado Align with layer Alinear con la capa Reset Alignment Restablecer la alineación - Centre the gradient (offset 0, 0) Centrar el degradado (desplazamiento 0, 0) + Center the gradient (offset 0, 0) Centrar el degradado (desplazamiento 0, 0) Gradient Editor Editor de degradados Gradient picker Selector de degradados Save As Preset Guardar como ajuste preestablecido @@ -2296,7 +2294,7 @@ Alt-click to define a source point to clone from Alt+clic para definir un punto de origen de clonación No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. No hay ningún trazado para crear una selección: dibuje uno con la herramienta Pluma o seleccione uno en el panel Trazados. Cancel opening Cancelar apertura - Cancelled opening {name} Se canceló la apertura de {name} + Canceled opening {name} Se canceló la apertura de {name} Damaged Photoshop document Documento de Photoshop dañado The document “{name}” may be damaged. Es posible que el documento «{name}» esté dañado. Some layers, pixels or masks could not be read. Do you want to continue opening it? No se pudieron leer algunas capas, píxeles o máscaras. ¿Desea seguir abriéndolo? @@ -2305,7 +2303,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. El documento «{name}» tiene un perfil de color incrustado que no coincide con el espacio de trabajo {mode} actual. Working: {working} Espacio de trabajo: {working} Developing {name} Revelando {name} - Cancelled {label} Se canceló {label} + Canceled {label} Se canceló {label} Esc to cancel Esc para cancelar Opened {name} Se abrió {name} Opening {name} Abriendo {name} @@ -2313,7 +2311,7 @@ Saving {name} Guardando {name} Saving {percent} Guardando {percent} A save to {name} is still running; try again when it finishes Todavía se está guardando {name}; inténtelo de nuevo cuando termine - {label} is writing the file and can no longer be cancelled {label} está escribiendo el archivo y ya no se puede cancelar + {label} is writing the file and can no longer be canceled {label} está escribiendo el archivo y ya no se puede cancelar Opening {name}… Abriendo {name}… Opening… Abriendo… Reading… Leyendo… @@ -2379,7 +2377,7 @@ Pixel Píxel Adjustment Ajuste Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Arrastre (lazo) o haga clic en los puntos (poligonal) · {add} añadir · {sub} restar - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Arrastre un marco de recorte · arrastre dentro para mover · los bordes cambian el tamaño ({ratio} proporción, {centre} centro) · Espacio mueve mientras dibuja · flechas desplazan · X cambia orientación · {commit} aplica · Esc cancela + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Arrastre un marco de recorte · arrastre dentro para mover · los bordes cambian el tamaño ({ratio} proporción, {centre} centro) · Espacio mueve mientras dibuja · flechas desplazan · X cambia orientación · {commit} aplica · Esc cancela {mode} Color · {bits} bit Color {mode} · {bits} bits Scrubby Zoom Zoom por arrastre Auto Erase Borrado automático @@ -2482,7 +2480,7 @@ cameraRaw Amount Cantidad Discard Layers and Save a Copy Descartar capas y guardar una copia Don't show again No volver a mostrar Save failed: {error} Error al guardar: {error} - Save cancelled Guardado cancelado + Save canceled Guardado cancelado Magnetic Lasso Tool Herramienta Lazo magnético Frequency Frecuencia Use tablet pressure to change pen width Usar la presión de la tableta para cambiar la anchura de la pluma @@ -2612,7 +2610,7 @@ fontWeight Italic Cursiva Rotate View Rotar vista Rotate View Tool Herramienta Rotar vista Reset View Restablecer vista - Drag around the centre to rotate the view · Shift constrains to 15° Arrastre alrededor del centro para rotar la vista · Mayús fija a 15° + Drag around the center to rotate the view · Shift constrains to 15° Arrastre alrededor del centro para rotar la vista · Mayús fija a 15° Dual Axis Doble eje Diagonal Diagonal Transform Symmetry Transformar simetría @@ -2627,8 +2625,8 @@ fontWeight Italic Cursiva All Layers No Adjustments Todas las capas sin ajustes Current & Below No Adjustments Actual e inferiores sin ajustes Show Sampling Ring Mostrar anillo de muestreo - Out of gamut for printing: click for the nearest printable colour Fuera de la gama de impresión: haga clic para el color imprimible más cercano - Not a web colour: click for the nearest web colour No es un color web: haga clic para el color web más cercano + Out of gamut for printing: click for the nearest printable color Fuera de la gama de impresión: haga clic para el color imprimible más cercano + Not a web color: click for the nearest web color No es un color web: haga clic para el color web más cercano Color to Alpha… Color a alfa… Transparency Threshold Umbral de transparencia Opacity Threshold Umbral de opacidad @@ -4223,7 +4221,7 @@ navigator Zoom Zoom Auto Add/Delete Añadir/eliminar automáticamente Don't also tick Mirror Image in Print Settings…: the two flips cancel out. No actives también Imagen especular en Ajustes de impresión: las dos inversiones se anulan. Print Settings… Ajustes de impresión… - Remember to turn off the printer's own colour management in Print Settings… Recuerda desactivar la gestión de color de la impresora en Ajustes de impresión… + Remember to turn off the printer's own color management in Print Settings… Recuerda desactivar la gestión de color de la impresora en Ajustes de impresión… 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 @@ -4353,12 +4351,12 @@ navigator Zoom Zoom Decrease Brush Hardness Reducir dureza del pincel Increase Brush Hardness Aumentar dureza del pincel Demosaic Demosaico - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Cómo se completa el mosaico del filtro de color de la cámara. Se aplica al abrir el archivo; la vista previa muestra el método con el que se abrió. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Cómo se completa el mosaico del filtro de color de la cámara. Se aplica al abrir el archivo; la vista previa muestra el método con el que se abrió. AHD (adaptive homogeneity) AHD (homogeneidad adaptativa) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: los bordes más limpios y el menor halo de color; el más lento. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolación con corrección de gradiente: nítida y rápida, con algo de halo de color en el detalle fino. - The fastest and the softest, with colour fringing on fine detail. El más rápido y el más suave, con halo de color en el detalle fino. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: los bordes más limpios y el menor halo de color; el más lento. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolación con corrección de gradiente: nítida y rápida, con algo de halo de color en el detalle fino. + The fastest and the softest, with color fringing on fine detail. El más rápido y el más suave, con halo de color en el detalle fino. “{name}” already exists. Replace it? «{name}» ya existe. ¿Reemplazarlo? The name in the save dialog was “{name}”. El nombre en el cuadro de diálogo Guardar era «{name}». Previous Brush Pincel anterior @@ -4506,6 +4504,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Elija un documento distinto para cada canal. A picked document is no longer open. Uno de los documentos elegidos ya no está abierto. A picked document is no longer a grayscale document of the same size. Uno de los documentos elegidos ya no es un documento en escala de grises del mismo tamaño. +# Move tool options bar (#11381) + Align top edges Alinear bordes superiores + Align vertical centers Alinear centros verticales + Align bottom edges Alinear bordes inferiores + Distribute vertically Distribuir verticalmente + Distribute horizontally Distribuir horizontalmente + Show layer bounds on hover Mostrar límites de capa al pasar el puntero + Expand layer group on click Expandir grupo de capas al hacer clic + Show hover bounds from Layers Mostrar límites al pasar el puntero desde Capas +# Artboard tool options bar (#11385) + Distribute Widths Distribuir anchos + Distribute Heights Distribuir alturas + Auto-nest Layers Anidar capas automáticamente + Auto-size Canvas Ajustar tamaño de lienzo automáticamente + Keep Relative Position During Layer Reordering Mantener la posición relativa al reordenar capas + Shrinkwrap Canvas on Save Reducir el lienzo al contenido al guardar # JPEG Options: the size the file will have (#7843) Estimated file size Tamaño estimado del archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a62e646ee4..eb99627d4f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -112,7 +112,6 @@ Export As… Vie nimellä… Export Vie Export… Vie… - Quick Export As PNG Pikavienti PNG-muodossa Quick Export as PNG Pikavienti PNG-muotoon Place Embedded… Sijoita upotettuna… Place Linked… Sijoita linkitettynä… @@ -316,7 +315,6 @@ All Kaikki Deselect Poista valinta Reselect Valitse uudelleen - Inverse Selection Käänteinen valinta Inverse Käännä valinta Color Range… Värialue… Select and Mask… Valitse ja maskaa… @@ -607,8 +605,8 @@ Background Tausta Set foreground color Aseta edustaväri Set background color Aseta taustaväri - Swap colours (X) Vaihda värit (X) - Default colours (D) Oletusvärit (D) + Switch Foreground and Background Colors (X) Vaihda edusta- ja taustaväri keskenään (X) + Default Foreground and Background Colors (D) Oletusarvoiset edusta- ja taustavärit (D) Brush Tool Options Sivellintyökalun asetukset Opacity Peittävyys Flow Virtaus @@ -1615,7 +1613,7 @@ Revert “{name}” to the last saved version? Your changes will be lost. Palautetaanko ”{name}” viimeksi tallennettuun versioon? Muutokset menetetään. {key} to subtract {key}: vähennä ↑↓ navigate {key} run esc close ↑↓ siirry {key} suorita esc sulje - Click to restore the current colour Palauta nykyinen väri napsauttamalla + Click to restore the current color Palauta nykyinen väri napsauttamalla Click with the Note tool to add a note. Lisää muistiinpano napsauttamalla Muistiinpano-työkalulla. Drag a rectangle around the object Vedä suorakulmio kohteen ympärille Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Lisää rajoite vetämällä kuvassa; Shift vaaka-/pystysuunnalle; muuta tai poista rajoite napsauttamalla sitä hiiren kakkospainikkeella. @@ -1697,10 +1695,10 @@ Drag to move the active layer Siirrä aktiivista tasoa vetämällä Drag to pan · hold Space with any tool Panoroi vetämällä · tai pidä Välilyöntiä painettuna millä tahansa työkalulla Drag to draw a gradient Piirrä liukuväri vetämällä - Click to fill similar colours Täytä samankaltaiset värit napsauttamalla + Click to fill similar colors Täytä samankaltaiset värit napsauttamalla Click to add text Lisää teksti napsauttamalla Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Vedä (lasso) tai napsauta pisteitä (monikulmio) · {add} lisää · {sub} vähennä - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Vedä rajauslaatikko · siirrä vetämällä sisältä · reunat muuttavat kokoa ({ratio} suhde, {centre} keskeltä) · Välilyönti siirtää piirrettäessä · nuolet siirtävät · X vaihtaa suunnan · {commit} vahvistaa · Esc peruuttaa + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Vedä rajauslaatikko · siirrä vetämällä sisältä · reunat muuttavat kokoa ({ratio} suhde, {centre} keskeltä) · Välilyönti siirtää piirrettäessä · nuolet siirtävät · X vaihtaa suunnan · {commit} vahvistaa · Esc peruuttaa {mode} Color · {bits} bit {mode}-väri · {bits}-bittinen Drag to move the layer Siirrä tasoa vetämällä Fit Screen Sovita näyttöön @@ -1732,7 +1730,7 @@ Appearance Ulkoasu Text Position: Tekstin sijainti: Text color Tekstin väri - Uses the foreground and background colours. Käyttää edusta- ja taustaväriä. + Uses the foreground and background colors. Käyttää edusta- ja taustaväriä. Answer the unsaved-changes prompt first Vastaa ensin tallentamattomien muutosten kyselyyn Unsaved changes Tallentamattomat muutokset Don't Save Älä tallenna @@ -1752,7 +1750,7 @@ name nimi new uusi Go to Layer Siirry tasoon - Open a document to select a colour range. Avaa asiakirja valitaksesi värialueen. + Open a document to select a color range. Avaa asiakirja valitaksesi värialueen. Saved Tallennettu Reveal in Finder Näytä Finderissa Show in Explorer Näytä Resurssienhallinnassa @@ -1930,8 +1928,8 @@ Character Styles Panel Merkkityylipaneeli Clear Canvas Guides Poista kankaan apuviivat Clear Selected Artboard Guides Poista valitun piirtoalustan apuviivat - Color Blindness — Deuteranopia-type Värisokeus — deuteranopia - Color Blindness — Protanopia-type Värisokeus — protanopia + Color Blindness - Deuteranopia-type Värisokeus — deuteranopia + Color Blindness - Protanopia-type Värisokeus — protanopia Color Table… Väritaulukko… Combine Shapes Yhdistä muodot Contract… Supista… @@ -2105,7 +2103,7 @@ Canvas Kangas Capture Kaappaa Center Crop Marks Keskikohdan rajausmerkit - Centre the gradient (offset 0, 0) Keskitä liukuväri (siirtymä 0, 0) + Center the gradient (offset 0, 0) Keskitä liukuväri (siirtymä 0, 0) Change Screen Mode (F) Vaihda näyttötilaa (F) Change To: Muuta muotoon: Clear All Tyhjennä kaikki @@ -2257,7 +2255,7 @@ Roughness Karheus Roundness Pyöreys Rulers & Grids Viivaimet ja ruudukot - Sample: foreground colour Näyte: edustaväri + Sample: foreground color Näyte: edustaväri Sampling: Background Swatch Näytteistys: taustan värimalli Sampling: Continuous Näytteistys: jatkuva Sampling: Once Näytteistys: kerran @@ -2530,7 +2528,7 @@ Alt-click to define a source point to clone from Määritä kloonauksen lähdepiste Alt-napsautuksella No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Ei polkua, josta luoda valinta: piirrä polku kynätyökalulla tai valitse polku Polut-paneelissa. Cancel opening Peruuta avaaminen - Cancelled opening {name} Tiedoston {name} avaaminen peruutettu + Canceled opening {name} Tiedoston {name} avaaminen peruutettu Damaged Photoshop document Vioittunut Photoshop-asiakirja The document “{name}” may be damaged. Asiakirja ”{name}” saattaa olla vioittunut. Some layers, pixels or masks could not be read. Do you want to continue opening it? Joitakin tasoja, pikseleitä tai maskeja ei voitu lukea. Haluatko jatkaa avaamista? @@ -2540,7 +2538,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Asiakirjassa ”{name}” on upotettu väriprofiili, joka ei vastaa nykyistä {mode}-työavaruutta. Working: {working} Työavaruus: {working} Developing {name} Kehitetään tiedostoa {name} - Cancelled {label} Peruutettu: {label} + Canceled {label} Peruutettu: {label} Esc to cancel Peruuta painamalla Esc Opened {name} Avattu {name} Opening {name} Avataan tiedostoa {name} @@ -2548,7 +2546,7 @@ Saving {name} Tallennetaan tiedostoa {name} Saving {percent} Tallennetaan {percent} A save to {name} is still running; try again when it finishes Tallennus tiedostoon {name} on vielä käynnissä; yritä uudelleen sen päätyttyä - {label} is writing the file and can no longer be cancelled {label}: tiedostoa kirjoitetaan, eikä toimintoa voi enää peruuttaa + {label} is writing the file and can no longer be canceled {label}: tiedostoa kirjoitetaan, eikä toimintoa voi enää peruuttaa Opening {name}… Avataan tiedostoa {name}… Opening… Avataan… Reading… Luetaan… @@ -2645,7 +2643,7 @@ cameraRaw Roughness Karheus Discard Layers and Save a Copy Hylkää tasot ja tallenna kopio Don't show again Älä näytä uudelleen Save failed: {error} Tallennus epäonnistui: {error} - Save cancelled Tallennus peruutettu + Save canceled Tallennus peruutettu Couldn't place {name}: {error} Kohteen {name} sijoittaminen epäonnistui: {error} Magnetic Lasso Tool Magneettinen lassotyökalu Frequency Taajuus @@ -2789,7 +2787,7 @@ fontWeight Italic Kursivoitu Impressionist Impressionistinen Rotate View Tool Näkymän kiertotyökalu Reset View Palauta näkymä - Drag around the centre to rotate the view · Shift constrains to 15° Kierrä näkymää vetämällä keskipisteen ympäri · Shift rajoittaa 15°:n välein + Drag around the center to rotate the view · Shift constrains to 15° Kierrä näkymää vetämällä keskipisteen ympäri · Shift rajoittaa 15°:n välein # Painting symmetry presets. Dual Axis Kaksi akselia @@ -2809,11 +2807,11 @@ fontWeight Italic Kursivoitu All Layers No Adjustments Kaikki tasot ilman säätöjä Current & Below No Adjustments Nykyinen ja alemmat ilman säätöjä Show Sampling Ring Näytä näytteenottorengas - Click to sample the foreground colour · {key}-click for background Ota edustavärin näyte napsauttamalla · {key}-napsautus taustavärille + Click to sample the foreground color · {key}-click for background Ota edustavärin näyte napsauttamalla · {key}-napsautus taustavärille # Color Picker warnings - Out of gamut for printing: click for the nearest printable colour Tulostusvärialueen ulkopuolella: napsauta valitaksesi lähimmän tulostettavan värin - Not a web colour: click for the nearest web colour Ei verkkoväri: napsauta valitaksesi lähimmän verkkovärin + Out of gamut for printing: click for the nearest printable color Tulostusvärialueen ulkopuolella: napsauta valitaksesi lähimmän tulostettavan värin + Not a web color: click for the nearest web color Ei verkkoväri: napsauta valitaksesi lähimmän verkkovärin Color to Alpha… Väri alfaksi… Transparency Threshold Läpinäkyvyyskynnys Opacity Threshold Peittävyyskynnys @@ -3231,7 +3229,7 @@ curves Smooth Tasoita # Native Windows printing qualification Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Älä valitse myös Peilikuva-asetusta kohdassa Tulostusasetukset…: kaksi peilausta kumoaa toisensa. Print Settings… Tulostusasetukset… - Remember to turn off the printer's own colour management in Print Settings… Muista poistaa tulostimen oma värinhallinta käytöstä kohdassa Tulostusasetukset… + Remember to turn off the printer's own color management in Print Settings… Muista poistaa tulostimen oma värinhallinta käytöstä kohdassa Tulostusasetukset… Sent to {printer} Lähetetty tulostimelle {printer} set in Print Settings… asetetaan kohdassa Tulostusasetukset… ICO is limited to 256 × 256 pixels ICO-tiedosto on rajoitettu kokoon 256 × 256 pikseliä @@ -3895,12 +3893,12 @@ curves Smooth Tasoita In White Tulon valkoinen Increase Brush Hardness Lisää siveltimen kovuutta Demosaic Mosaiikin purku - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Miten kameran värisuodatinmosaiikki täydennetään. Menetelmä otetaan käyttöön tiedostoa avattaessa; esikatselu näyttää menetelmän, jolla tiedosto avattiin. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Miten kameran värisuodatinmosaiikki täydennetään. Menetelmä otetaan käyttöön tiedostoa avattaessa; esikatselu näyttää menetelmän, jolla tiedosto avattiin. AHD (adaptive homogeneity) AHD (adaptiivinen homogeenisuus) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: siisteimmät reunat ja vähiten värireunuksia, hitain. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradienttikorjattu interpolointi: terävä ja nopea, hienoissa yksityiskohdissa jonkin verran värireunuksia. - The fastest and the softest, with colour fringing on fine detail. Nopein ja pehmein, hienoissa yksityiskohdissa värireunuksia. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: siisteimmät reunat ja vähiten värireunuksia, hitain. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradienttikorjattu interpolointi: terävä ja nopea, hienoissa yksityiskohdissa jonkin verran värireunuksia. + The fastest and the softest, with color fringing on fine detail. Nopein ja pehmein, hienoissa yksityiskohdissa värireunuksia. “{name}” already exists. Replace it? ”{name}” on jo olemassa. Korvataanko se? The name in the save dialog was “{name}”. Tallennusikkunassa nimi oli ”{name}”. Move Up Siirrä ylös @@ -4551,7 +4549,6 @@ curves Smooth Tasoita Use File › Open to open an image. Avaa kuva komennolla Tiedosto › Avaa. Use Selection In Source Käytä valintaa lähteessä Use Selection In Target Käytä valintaa kohteessa - Uses the foreground and background colors. Käyttää edusta- ja taustaväriä. Vanishing Point Pakopiste Variable Data Sets Muuttuvat tietojoukot Vector Mask Hides Effects Vektorimaski piilottaa tehosteet @@ -4761,8 +4758,8 @@ cameraRaw Camera Raw ({name}) Camera Raw ({name}) cameraRaw Camera Raw Filter ({layer}) Camera Raw -suodatin ({layer}) cameraRaw Camera Raw isn't open Camera Raw ei ole auki cameraRaw Cancel Peruuta -cameraRaw Cancelled opening {name} Tiedoston {name} avaaminen peruutettu -cameraRaw Cancelled {label} Peruutettu: {label} +cameraRaw Canceled opening {name} Tiedoston {name} avaaminen peruutettu +cameraRaw Canceled {label} Peruutettu: {label} cameraRaw Color Priority Väriprioriteetti cameraRaw Developing {name} Kehitetään tiedostoa {name} cameraRaw Full-resolution preview unavailable Täyden resoluution esikatselu ei ole käytettävissä @@ -4817,3 +4814,19 @@ cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen Pick a different document for each channel. Valitse jokaiselle kanavalle eri asiakirja. A picked document is no longer open. Yksi valituista asiakirjoista ei ole enää auki. A picked document is no longer a grayscale document of the same size. Yksi valituista asiakirjoista ei ole enää samankokoinen harmaasävyasiakirja. +# Move tool options bar (#11381) + Align top edges Tasaa yläreunat + Align vertical centers Tasaa pystykeskikohdat + Align bottom edges Tasaa alareunat + Distribute vertically Jaa pystysuunnassa + Distribute horizontally Jaa vaakasuunnassa + Show layer bounds on hover Näytä tason rajat osoitettaessa + Expand layer group on click Laajenna tasoryhmä napsautuksella + Show hover bounds from Layers Näytä rajat osoitettaessa Tasot-paneelista +# Artboard tool options bar (#11385) + Distribute Widths Jaa leveydet tasaisesti + Distribute Heights Jaa korkeudet tasaisesti + Auto-nest Layers Sisäkkäistä tasot automaattisesti + Auto-size Canvas Muuta kankaan kokoa automaattisesti + Keep Relative Position During Layer Reordering Säilytä suhteellinen sijainti tasojen järjestystä muutettaessa + Shrinkwrap Canvas on Save Pienennä kangas sisältöön tallennettaessa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 95841739bf..f84cbed8a5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -619,7 +619,6 @@ Deselect Désélectionner Reselect Resélectionner Inverse Inverser - Inverse Selection Inverser la sélection Similar Similaire Color Range… Plage de couleurs… Focus Area… Zone de mise au point… @@ -740,8 +739,8 @@ Legacy Macintosh RGB (Gamma 1.8) RVB Macintosh (ancien) (Gamma 1.8) Internet Standard RGB (sRGB) RVB standard d'Internet (sRGB) Monitor RGB RVB du moniteur - Color Blindness — Protanopia-type Daltonisme — type protanopie - Color Blindness — Deuteranopia-type Daltonisme — type deutéranopie + Color Blindness - Protanopia-type Daltonisme - type protanopie + Color Blindness - Deuteranopia-type Daltonisme - type deutéranopie Zoom In Zoom avant Zoom Out Zoom arrière Fit on Screen Adapter à l'écran @@ -1060,7 +1059,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Cliquez pour ajouter un point · faites-le glisser hors du cadre, {key}-clic ou Suppr pour le retirer Click to apply, {key}-click to clear overrides, double-click for Style Options Cliquez pour appliquer, {key}-clic pour effacer les substitutions, double-clic pour les options de style Click to edit the gradient Cliquez pour modifier le dégradé - Click to restore the current colour Cliquez pour rétablir la couleur actuelle + Click to restore the current color Cliquez pour rétablir la couleur actuelle Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Cliquez pour zoomer · {key}-clic pour dézoomer · faites glisser vers la droite/gauche pour zoomer/dézoomer Click with the Note tool to add a note. Cliquez avec l'outil Note pour ajouter une note. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Clic : angle · Glisser : lisse · Clic sur le premier point : fermer · {key} : terminer · Échap : annuler @@ -1143,7 +1142,7 @@ Darks Tons sombres Data Sets Jeux de données Default Par défaut - Default colours (D) Couleurs par défaut (D) + Default Foreground and Background Colors (D) Couleurs par défaut (D) Default printer Imprimante par défaut Default restored. Valeurs par défaut rétablies. Define Définir @@ -1420,7 +1419,7 @@ Opacity Jitter Variation de l'opacité Opacity: Opacité : Open a document to define variables. Ouvrez un document pour définir des variables. - Open a document to select a colour range. Ouvrez un document pour sélectionner une plage de couleurs. + Open a document to select a color range. Ouvrez un document pour sélectionner une plage de couleurs. Open a document to use the timeline. Ouvrez un document pour utiliser le montage. Optical Optique Optimized Optimisé @@ -1496,7 +1495,6 @@ Purity Pureté Quality Qualité Quick Actions Actions rapides - Quick Export As PNG Exportation rapide au format PNG Radial Gradient Dégradé radial Radius Rayon Radius: Rayon : @@ -1637,7 +1635,7 @@ Subtract from Sample Soustraire de l'échantillon Subtract from selection ({key}) Soustraire de la sélection ({key}) Suggestions: Suggestions : - Swap colours (X) Permuter les couleurs (X) + Switch Foreground and Background Colors (X) Permuter les couleurs (X) Swaps height and width Permute la hauteur et la largeur Switch between free transform and warp modes Basculer entre les modes transformation libre et déformation Switch theme Changer de thème @@ -1739,7 +1737,7 @@ Choke Resserrement Classic Classique Click to add text Cliquez pour ajouter du texte - Click to fill similar colours Cliquez pour remplir les couleurs similaires + Click to fill similar colors Cliquez pour remplir les couleurs similaires Clone Stamp Tool Outil Tampon de clonage Color Burn Densité couleur + Color Dodge Densité couleur − @@ -1899,7 +1897,7 @@ Rectangular Marquee Tool Outil Sélection rectangulaire Reds Rouges Reflected Réfléchi - Sample: foreground colour Échantillon : couleur de premier plan + Sample: foreground color Échantillon : couleur de premier plan Sampled Colors Couleurs échantillonnées Satin Satin Save Pixel Aspect Ratio Enregistrer le format des pixels @@ -1938,7 +1936,6 @@ Transfer Transfert Triangle Tool Outil Triangle Unsaved changes Modifications non enregistrées - Uses the foreground and background colours. Utilise les couleurs de premier plan et d'arrière-plan. Web Web Web Large Web (grand) Web Minimum Web (minimum) @@ -1973,6 +1970,7 @@ Allow scripts to connect Autoriser la connexion des scripts Always Toujours Always create smart objects when placing Toujours créer des objets intelligents lors du placement + Skip transform when placing Ignorer la transformation lors du placement Animated zoom Zoom animé Apply auto tone Appliquer la tonalité automatique Ask Demander @@ -2206,7 +2204,7 @@ Graphics Graphismes Reset GPU Backend Réinitialiser le moteur GPU Applies at next launch. Prend effet au prochain démarrage. - Click to sample the foreground colour · {key}-click for background Cliquez pour prélever la couleur de premier plan · {key}-clic pour l'arrière-plan + Click to sample the foreground color · {key}-click for background Cliquez pour prélever la couleur de premier plan · {key}-clic pour l'arrière-plan {key}-click to set the source {key}-clic pour définir la source {key} to subtract {key} pour soustraire Clone source {n} ({key}-click with Clone Stamp to set) Source de clonage {n} ({key}-clic avec le tampon de clonage pour la définir) @@ -2264,7 +2262,7 @@ Gradient Options Options de dégradé Align with layer Aligner sur le calque Reset Alignment Réinitialiser l'alignement - Centre the gradient (offset 0, 0) Centrer le dégradé (décalage 0, 0) + Center the gradient (offset 0, 0) Centrer le dégradé (décalage 0, 0) Gradient Editor Éditeur de dégradé Gradient picker Sélecteur de dégradé Save As Preset Enregistrer comme préreglage @@ -2297,7 +2295,7 @@ Alt-click to define a source point to clone from Alt-clic pour définir le point source du clonage No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Aucun tracé à partir duquel créer une sélection : dessinez-en un avec l'outil Plume ou sélectionnez-en un dans le panneau Tracés. Cancel opening Annuler l'ouverture - Cancelled opening {name} Ouverture de {name} annulée + Canceled opening {name} Ouverture de {name} annulée Damaged Photoshop document Document Photoshop endommagé The document “{name}” may be damaged. Le document « {name} » est peut-être endommagé. Some layers, pixels or masks could not be read. Do you want to continue opening it? Certains calques, pixels ou masques n’ont pas pu être lus. Voulez-vous poursuivre l’ouverture ? @@ -2307,7 +2305,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Le document « {name} » a un profil colorimétrique incorporé qui ne correspond pas à l'espace de travail {mode} actuel. Working: {working} Espace de travail : {working} Developing {name} Développement de {name} - Cancelled {label} {label} : annulé + Canceled {label} {label} : annulé Esc to cancel Échap pour annuler Opened {name} Ouvert : {name} Opening {name} Ouverture de {name} @@ -2315,7 +2313,7 @@ Saving {name} Enregistrement de {name} Saving {percent} Enregistrement {percent} A save to {name} is still running; try again when it finishes Un enregistrement de {name} est encore en cours ; réessayez lorsqu’il sera terminé - {label} is writing the file and can no longer be cancelled {label} écrit le fichier et ne peut plus être annulé + {label} is writing the file and can no longer be canceled {label} écrit le fichier et ne peut plus être annulé Opening {name}… Ouverture de {name}… Opening… Ouverture… Reading… Lecture… @@ -2681,7 +2679,7 @@ Pixel Pixel Adjustment Ajustement Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Faites glisser (lasso) ou cliquez des points (polygonal) · {add} ajouter · {sub} soustraire - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Tracez un cadre de recadrage · faites glisser à l'intérieur pour le déplacer · les bords le redimensionnent ({ratio} proportions, {centre} centre) · Espace le déplace pendant le tracé · flèches le décalent · X permute l'orientation · {commit} valide · Échap annule + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Tracez un cadre de recadrage · faites glisser à l'intérieur pour le déplacer · les bords le redimensionnent ({ratio} proportions, {centre} centre) · Espace le déplace pendant le tracé · flèches le décalent · X permute l'orientation · {commit} valide · Échap annule {mode} Color · {bits} bit Couleurs {mode} · {bits} bits Drag to move the layer Faites glisser pour déplacer le calque Scrubby Zoom Zoom par glissement @@ -2875,7 +2873,7 @@ cameraRaw Blending Fusion Discard Layers and Save a Copy Supprimer les calques et enregistrer une copie Don't show again Ne plus afficher Save failed: {error} Échec de l'enregistrement : {error} - Save cancelled Enregistrement annulé + Save canceled Enregistrement annulé Couldn't place {name}: {error} Impossible d'importer {name} : {error} Magnetic Lasso Tool Outil Lasso magnétique Frequency Fréquence @@ -3004,7 +3002,7 @@ fontWeight Italic Italique Impressionist Impressionniste Rotate View Tool Outil Rotation de la vue Reset View Réinitialiser la vue - Drag around the centre to rotate the view · Shift constrains to 15° Faites glisser autour du centre pour tourner la vue · Maj contraint à 15° + Drag around the center to rotate the view · Shift constrains to 15° Faites glisser autour du centre pour tourner la vue · Maj contraint à 15° Dual Axis Deux axes Diagonal Diagonale Transform Symmetry Transformer la symétrie @@ -3019,8 +3017,8 @@ fontWeight Italic Italique All Layers No Adjustments Tous les calques sans ajustements Current & Below No Adjustments Actif et inférieurs sans ajustements Show Sampling Ring Afficher l'anneau d'échantillonnage - Out of gamut for printing: click for the nearest printable colour Hors de la gamme d’impression : cliquez pour la couleur imprimable la plus proche - Not a web colour: click for the nearest web colour Pas une couleur web : cliquez pour la couleur web la plus proche + Out of gamut for printing: click for the nearest printable color Hors de la gamme d’impression : cliquez pour la couleur imprimable la plus proche + Not a web color: click for the nearest web color Pas une couleur web : cliquez pour la couleur web la plus proche Color to Alpha… Couleur vers alpha… Transparency Threshold Seuil de transparence Opacity Threshold Seuil d'opacité @@ -3317,7 +3315,7 @@ curves Smooth Lisser Auto Add/Delete Ajout/suppr. auto Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Ne cochez pas aussi Image miroir dans les paramètres d’impression : les deux inversions s’annulent. Print Settings… Paramètres d’impression… - Remember to turn off the printer's own colour management in Print Settings… Pensez à désactiver la gestion des couleurs de l’imprimante dans les paramètres d’impression… + Remember to turn off the printer's own color management in Print Settings… Pensez à désactiver la gestion des couleurs de l’imprimante dans les paramètres d’impression… 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 @@ -3450,12 +3448,12 @@ curves Smooth Lisser Decrease Brush Hardness Réduire la dureté du pinceau Increase Brush Hardness Augmenter la dureté du pinceau Demosaic Dématriçage - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Comment la mosaïque du filtre couleur de l'appareil est complétée. Appliqué à l'ouverture du fichier ; l'aperçu montre la méthode avec laquelle il a été ouvert. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Comment la mosaïque du filtre couleur de l'appareil est complétée. Appliqué à l'ouverture du fichier ; l'aperçu montre la méthode avec laquelle il a été ouvert. AHD (adaptive homogeneity) AHD (homogénéité adaptative) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks : les bords les plus nets et le moins de franges colorées ; le plus lent. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolation corrigée par gradient : nette et rapide, avec quelques franges colorées sur les détails fins. - The fastest and the softest, with colour fringing on fine detail. Le plus rapide et le plus doux, avec des franges colorées sur les détails fins. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks : les bords les plus nets et le moins de franges colorées ; le plus lent. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolation corrigée par gradient : nette et rapide, avec quelques franges colorées sur les détails fins. + The fastest and the softest, with color fringing on fine detail. Le plus rapide et le plus doux, avec des franges colorées sur les détails fins. “{name}” already exists. Replace it? « {name} » existe déjà. Le remplacer ? The name in the save dialog was “{name}”. Le nom dans la boîte de dialogue d'enregistrement était « {name} ». Previous Brush Pinceau précédent @@ -4629,6 +4627,22 @@ shape Appearance Apparence Pick a different document for each channel. Choisissez un document différent pour chaque canal. A picked document is no longer open. Un des documents choisis n'est plus ouvert. A picked document is no longer a grayscale document of the same size. Un des documents choisis n'est plus un document en niveaux de gris de même taille. +# Move tool options bar (#11381) + Align top edges Aligner les bords supérieurs + Align vertical centers Aligner les centres verticaux + Align bottom edges Aligner les bords inférieurs + Distribute vertically Répartir verticalement + Distribute horizontally Répartir horizontalement + Show layer bounds on hover Afficher les limites du calque au survol + Expand layer group on click Développer le groupe de calques au clic + Show hover bounds from Layers Afficher les limites au survol depuis Calques +# Artboard tool options bar (#11385) + Distribute Widths Répartir les largeurs + Distribute Heights Répartir les hauteurs + Auto-nest Layers Imbriquer les calques automatiquement + Auto-size Canvas Redimensionner le canevas automatiquement + Keep Relative Position During Layer Reordering Conserver la position relative lors de la réorganisation des calques + Shrinkwrap Canvas on Save Réduire le canevas au contenu à l'enregistrement # JPEG Options: the size the file will have (#7843) Estimated file size Taille de fichier estimée diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index d1ed86b078..4ffe25aaf7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -379,10 +379,10 @@ cameraRaw Camera Raw Filter ({layer}) Camera Raw फ़िल्टर ({layer}) cameraRaw Camera Raw isn't open Camera Raw खुला नहीं है Camera Raw isn't open Camera Raw खुला नहीं है cameraRaw Cancel रद्द करें -cameraRaw Cancelled opening {name} {name} खोलना रद्द किया गया - Cancelled opening {name} {name} खोलना रद्द किया गया -cameraRaw Cancelled {label} {label} रद्द किया गया - Cancelled {label} {label} रद्द किया गया +cameraRaw Canceled opening {name} {name} खोलना रद्द किया गया + Canceled opening {name} {name} खोलना रद्द किया गया +cameraRaw Canceled {label} {label} रद्द किया गया + Canceled {label} {label} रद्द किया गया cameraRaw Clarity स्पष्टता Clarity स्पष्टता cameraRaw Color रंग @@ -675,6 +675,22 @@ cameraRaw Yellow पीला Pick a different document for each channel. हर चैनल के लिए अलग डॉक्यूमेंट चुनें। A picked document is no longer open. चुना गया एक डॉक्यूमेंट अब खुला नहीं है। A picked document is no longer a grayscale document of the same size. चुना गया एक डॉक्यूमेंट अब उसी आकार का ग्रेस्केल डॉक्यूमेंट नहीं है। +# Move tool options bar (#11381) + Align top edges ऊपरी किनारे संरेखित करें + Align vertical centers ऊर्ध्वाधर केंद्र संरेखित करें + Align bottom edges निचले किनारे संरेखित करें + Distribute vertically ऊर्ध्वाधर रूप से वितरित करें + Distribute horizontally क्षैतिज रूप से वितरित करें + Show layer bounds on hover होवर पर लेयर की सीमाएँ दिखाएँ + Expand layer group on click क्लिक पर लेयर समूह विस्तृत करें + Show hover bounds from Layers लेयर्स से होवर सीमाएँ दिखाएँ +# Artboard tool options bar (#11385) + Distribute Widths चौड़ाइयाँ वितरित करें + Distribute Heights ऊंचाइयाँ वितरित करें + Auto-nest Layers लेयर्स को स्वचालित रूप से नेस्ट करें + Auto-size Canvas कैनवास का आकार स्वचालित रूप से बदलें + Keep Relative Position During Layer Reordering लेयर्स का क्रम बदलते समय सापेक्ष स्थिति बनाए रखें + Shrinkwrap Canvas on Save सहेजते समय कैनवास को सामग्री के अनुसार छोटा करें # JPEG Options: the size the file will have (#7843) Estimated file size अनुमानित फ़ाइल आकार diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c83e9c318f..10a7754178 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -400,7 +400,6 @@ Insert Blank Frame Üres képkocka beszúrása Interpret Footage… Videoanyag értelmezése… Intersect Shape Areas Alakzatterületek metszete - Inverse Selection Kijelölés megfordítása Invert… Invertálás… Isolate Layers Rétegek elkülönítése Kurtosis Csúcsosság @@ -566,8 +565,8 @@ Close Panel Panel bezárása Close Window Ablak bezárása Clouds Felhők - Color Blindness — Deuteranopia-type Színtévesztés — deuteranópia típusú - Color Blindness — Protanopia-type Színtévesztés — protanópia típusú + Color Blindness - Deuteranopia-type Színtévesztés - deuteranópia típusú + Color Blindness - Protanopia-type Színtévesztés - protanópia típusú Color Halftone… Színes féltónus… Color Lookup Tables Színleképezési táblák Color Picker (Custom Canvas Color) Színválasztó (egyéni vászonszín) @@ -811,7 +810,6 @@ Proof Colors Színpróba Proof Setup Színpróba beállítása Properties Tulajdonságok - Quick Export As PNG Gyors exportálás PNG-be Quit Kilépés Quit {app} Kilépés: {app} Radial Blur… Sugárirányú elmosás… @@ -1035,7 +1033,7 @@ Catch-up on Stroke End Utolérés a vonás végén Center Középen Center text Szöveg középre igazítása - Centre the gradient (offset 0, 0) Színátmenet középre helyezése (eltolás: 0, 0) + Center the gradient (offset 0, 0) Színátmenet középre helyezése (eltolás: 0, 0) Change Cserél Change All Mindet cserél Change To: Csere erre: @@ -1048,7 +1046,7 @@ Click to add a point, right-click to remove Kattintással pontot adhatsz hozzá, jobb kattintással eltávolíthatod Click to apply, {key}-click to clear overrides, double-click for Style Options Kattintással alkalmazhatod, {key}+kattintással törölheted a felülbírálásokat, dupla kattintással megnyithatod a stílusbeállításokat Click to edit the gradient Kattints a színátmenet szerkesztéséhez - Click to sample the foreground colour · {key}-click for background Kattintás: mintavétel az előtérszínhez · {key}+kattintás: a háttérszínhez + Click to sample the foreground color · {key}-click for background Kattintás: mintavétel az előtérszínhez · {key}+kattintás: a háttérszínhez Clone source set at {x}, {y} Klónozási forrás beállítva: {x}, {y} Clone Stamp Klónozó bélyegző Close Style Options Stílusbeállítások bezárása @@ -1824,7 +1822,7 @@ layerLabel Magenta Bíbor Change Screen Mode (F) Képernyőmód váltása (F) Click the first point or press {key} to close · Esc cancels Lezárás: kattintás az első pontra vagy {key} · Esc: megszakítás Click the first point or press {key} to close · {del} removes a point · Esc cancels Lezárás: kattintás az első pontra vagy {key} · {del}: pont eltávolítása · Esc: megszakítás - Click to fill similar colours Kattintással kitöltheted a hasonló színeket + Click to fill similar colors Kattintással kitöltheted a hasonló színeket Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Kattintás: nagyítás · {key}+kattintás: kicsinyítés · húzás jobbra/balra: nagyítás/kicsinyítés Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Kattints, majd haladj végig egy élen · kattintás: pont rögzítése · {alt}+kattintás: egyenes szakasz · dupla kattintás: lezárás Clip to layer below Vágás az alatta lévő réteghez @@ -1853,7 +1851,7 @@ layerLabel Magenta Bíbor Dark Sötét Data Set: {name} ({index}/{total}) Adatkészlet: {name} ({index}/{total}) Data Sets Adatkészletek - Default colours (D) Alapértelmezett színek (D) + Default Foreground and Background Colors (D) Alapértelmezett előtér- és háttérszín (D) Define Megadás Define at least one variable first. Előbb adj meg legalább egy változót. Delete Cropped Pixels Levágott pixelek törlése @@ -1866,8 +1864,8 @@ layerLabel Magenta Bíbor Discord Discord Doc: {w} × {h} px Dok.: {w} × {h} px Drag a box or click four corners · drag the corners onto the edges of a skewed shape · {commit} commits · Esc cancels Húzz egy keretet, vagy kattints a négy sarokra · húzd a sarkokat a ferde alakzat éleire · {commit}: véglegesítés · Esc: megszakítás - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Húzz egy körbevágási keretet · belül húzva mozgatod · az élekkel átméretezed ({ratio}: arány, {centre}: középről) · Space: mozgatás rajzolás közben · nyilak: léptetés · X: tájolás cseréje · {commit}: véglegesítés · Esc: megszakítás - Drag around the centre to rotate the view · Shift constrains to 15° A középpont körül húzva forgatod a nézetet · Shift: 15°-os lépések + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Húzz egy körbevágási keretet · belül húzva mozgatod · az élekkel átméretezed ({ratio}: arány, {centre}: középről) · Space: mozgatás rajzolás közben · nyilak: léptetés · X: tájolás cseréje · {commit}: véglegesítés · Esc: megszakítás + Drag around the center to rotate the view · Shift constrains to 15° A középpont körül húzva forgatod a nézetet · Shift: 15°-os lépések Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Húzz, vagy kattints sokszögpontokat · lasszózás közben Alt: egyenes szakaszok · {add}: hozzáadás · {sub} rajzolás előtt: kivonás Drag to draw a gradient Húzással rajzolhatsz színátmenetet Drag to move the active layer Húzással mozgathatod az aktív réteget @@ -1999,7 +1997,7 @@ layerLabel Magenta Bíbor Source: {name} Forrás: {name} Style Stílus Subtract from selection ({key}) Kivonás a kijelölésből ({key}) - Swap colours (X) Színek cseréje (X) + Switch Foreground and Background Colors (X) Előtér- és háttérszín cseréje (X) System title bar Rendszer címsora Text Replacement Szövegcsere Thumbnail size (smallest: list) Bélyegképméret (a legkisebb: lista) @@ -2014,7 +2012,7 @@ layerLabel Magenta Bíbor Working… Feldolgozás… Workspaces Munkaterületek Zoom Nagyító - {label} is writing the file and can no longer be cancelled {label}: a fájl írása folyamatban, már nem szakítható meg + {label} is writing the file and can no longer be canceled {label}: a fájl írása folyamatban, már nem szakítható meg {message} (notes: {n}; {warning}) {message} (megjegyzések: {n}; {warning}) {mode} Color · {bits} bit Színmód: {mode} · {bits} bit {name} Properties Tulajdonságok: {name} @@ -2337,7 +2335,7 @@ navigator Zoom Nagyítás mértéke One Flame Along Path Egy láng az útvonal mentén Opacity Threshold Átlátszatlansági küszöb Open Megnyitás - Open a document to select a colour range. Színtartomány kijelöléséhez nyiss meg egy dokumentumot. + Open a document to select a color range. Színtartomány kijelöléséhez nyiss meg egy dokumentumot. Orange Narancs Out Black Kimeneti fekete Out From Center Középponttól kifelé @@ -2422,7 +2420,7 @@ navigator Zoom Nagyítás mértéke Roses Rózsák Rough Pastels Durva pasztell Ruler Vonalzó - Sample: foreground colour Minta: előtérszín + Sample: foreground color Minta: előtérszín Sampled Colors Mintavételezett színek Sandstone Homokkő Saturation Telítettség @@ -2530,7 +2528,6 @@ navigator Zoom Nagyítás mértéke Use Measurement Scale Mérési méretarány használata Use Selection In Source Kijelölés használata a forrásban Use Selection In Target Kijelölés használata a célban - Uses the foreground and background colours. Az előtér- és a háttérszínt használja. Vertical Only Csak függőleges Vibrance Élénkség View Options Nézetbeállítások @@ -2579,7 +2576,7 @@ navigator Zoom Nagyítás mértéke Camera Raw Filter Camera Raw szűrő Camera Raw Filter ({layer}) Camera Raw szűrő ({layer}) Camera Raw isn't open A Camera Raw nincs megnyitva - Cancelled opening {name} Megnyitás megszakítva: {name} + Canceled opening {name} Megnyitás megszakítva: {name} Damaged Photoshop document Sérült Photoshop-dokumentum The document “{name}” may be damaged. A(z) „{name}” dokumentum sérült lehet. Some layers, pixels or masks could not be read. Do you want to continue opening it? Egyes rétegeket, képpontokat vagy maszkokat nem sikerült beolvasni. Folytatod a megnyitást? @@ -2587,7 +2584,7 @@ navigator Zoom Nagyítás mértéke The document “{name}” does not have an embedded {mode} profile. Nincs beágyazott profil ({mode}) ebben a dokumentumban: „{name}” The document “{name}” has an embedded color profile that does not match the current {mode} working space. A dokumentum beágyazott színprofilja nem egyezik az aktuális munkaszíntérrel ({mode}): „{name}” Working: {working} Munkaszíntér: {working} - Cancelled {label} Megszakítva: {label} + Canceled {label} Megszakítva: {label} Clarity Tisztaság Color Detail Színrészletesség Color Grading Színtónusozás @@ -2731,6 +2728,7 @@ cameraRaw Yellow Sárga All Slices Összes szelet All User Slices Összes felhasználói szelet Always create smart objects when placing Elhelyezéskor mindig intelligens objektum létrehozása + Skip transform when placing Alakítás kihagyása elhelyezéskor Answer the unsaved-changes prompt first Előbb válaszolj a nem mentett módosításokra vonatkozó kérdésre Appearance Settings… Megjelenési beállítások… Apple Watch 45mm Apple Watch 45 mm @@ -2767,7 +2765,7 @@ cameraRaw Yellow Sárga Centimeters Centiméter Clear Kiürít Clear Existing Guides Meglévő segédvonalak törlése - Click to restore the current colour Kattints a jelenlegi szín visszaállításához + Click to restore the current color Kattints a jelenlegi szín visszaállításához Cmd Cmd CMYK Color CMYK-szín Coated CMYK Mázolt papíros CMYK @@ -2948,7 +2946,7 @@ cameraRaw Yellow Sárga No model credits were built into this copy. Ez a példány nem tartalmaz adatokat a modellek készítőiről. No presets of this type. Ilyen típusú előbeállítás nincs. No saved presets yet. Még nincs mentett előbeállítás. - Not a web colour: click for the nearest web colour Nem webes szín: kattints a legközelebbi webes színért + Not a web color: click for the nearest web color Nem webes szín: kattints a legközelebbi webes színért Notification Duration (seconds) Értesítés időtartama (másodperc) Bundle Arrow-Key Nudges Nyílbillentyűs mozgatások összevonása Nudge Bundle Pause (ms) Összevonási szünet (ms) @@ -2959,7 +2957,7 @@ cameraRaw Yellow Sárga OpenGL OpenGL Optimized Optimalizált Original Eredeti - Out of gamut for printing: click for the nearest printable colour Nyomtatási színtartományon kívül: kattints a legközelebbi nyomtatható színért + Out of gamut for printing: click for the nearest printable color Nyomtatási színtartományon kívül: kattints a legközelebbi nyomtatható színért Out of memory Elfogyott a memória Package Csomagolás Percent Százalék @@ -3038,7 +3036,7 @@ cameraRaw Yellow Sárga Rulers & Grids Vonalzók és rácsok Save a Copy Másolat mentése Save as PDF Mentés PDF-ként - Save cancelled Mentés megszakítva + Save canceled Mentés megszakítva Save failed: {error} A mentés nem sikerült: {error} Save for Web (Legacy) Mentés webre (régi) Save HTML and Images HTML és képek mentése @@ -4198,7 +4196,7 @@ cameraRaw Yellow Sárga Auto Add/Delete Automatikus hozzáadás/törlés Don't also tick Mirror Image in Print Settings…: the two flips cancel out. A nyomtatási beállításokban ne jelöld be a tükrözést is: a két tükrözés kioltja egymást. Print Settings… Nyomtatási beállítások… - Remember to turn off the printer's own colour management in Print Settings… Ne felejtsd el kikapcsolni a nyomtató saját színkezelését a nyomtatási beállításokban… + Remember to turn off the printer's own color management in Print Settings… Ne felejtsd el kikapcsolni a nyomtató saját színkezelését a nyomtatási beállításokban… Sent to {printer} Elküldve ide: {printer} set in Print Settings… a nyomtatási beállításokban adható meg… ICO is limited to 256 × 256 pixels Az ICO legfeljebb 256 × 256 képpont lehet @@ -4355,12 +4353,12 @@ cameraRaw Yellow Sárga Decrease Brush Hardness Ecsetkeménység csökkentése Increase Brush Hardness Ecsetkeménység növelése Demosaic Demozaikolás - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hogyan tölti ki a program a kamera színszűrő-mozaikját. A fájl megnyitásakor érvényesül; az előnézet a megnyitáskor használt módszert mutatja. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hogyan tölti ki a program a kamera színszűrő-mozaikját. A fájl megnyitásakor érvényesül; az előnézet a megnyitáskor használt módszert mutatja. AHD (adaptive homogeneity) AHD (adaptív homogenitás) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: a legtisztább élek és a legkevesebb színes szegély, a leglassabb. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradienskorrigált interpoláció: éles és gyors, apró részleteken némi színes szegéllyel. - The fastest and the softest, with colour fringing on fine detail. A leggyorsabb és a leglágyabb, apró részleteken színes szegéllyel. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: a legtisztább élek és a legkevesebb színes szegély, a leglassabb. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradienskorrigált interpoláció: éles és gyors, apró részleteken némi színes szegéllyel. + The fastest and the softest, with color fringing on fine detail. A leggyorsabb és a leglágyabb, apró részleteken színes szegéllyel. “{name}” already exists. Replace it? „{name}” már létezik. Lecseréli? The name in the save dialog was “{name}”. A mentési párbeszédpanelen megadott név: „{name}”. Previous Brush Előző ecset @@ -4513,6 +4511,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Minden csatornához másik dokumentumot válasszon. A picked document is no longer open. Az egyik kiválasztott dokumentum már nincs megnyitva. A picked document is no longer a grayscale document of the same size. Az egyik kiválasztott dokumentum már nem azonos méretű szürkeárnyalatos dokumentum. +# Move tool options bar (#11381) + Align top edges Felső szélek igazítása + Align vertical centers Függőleges középpontok igazítása + Align bottom edges Alsó szélek igazítása + Distribute vertically Egyenletes elosztás függőlegesen + Distribute horizontally Egyenletes elosztás vízszintesen + Show layer bounds on hover Réteghatárok megjelenítése rámutatáskor + Expand layer group on click Rétegcsoport kibontása kattintásra + Show hover bounds from Layers Határok megjelenítése a Rétegek panelről rámutatáskor +# Artboard tool options bar (#11385) + Distribute Widths Szélességek elosztása + Distribute Heights Magasságok elosztása + Auto-nest Layers Rétegek automatikus beágyazása + Auto-size Canvas Vászonméret automatikus módosítása + Keep Relative Position During Layer Reordering Relatív pozíció megtartása a rétegek átrendezésekor + Shrinkwrap Canvas on Save Vászon összehúzása a tartalomra mentéskor # JPEG Options: the size the file will have (#7843) Estimated file size Becsült fájlméret diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 65872de020..0f13b4130b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -614,7 +614,6 @@ Deselect Batalkan Seleksi Reselect Pilih Ulang Inverse Kebalikan - Inverse Selection Balik Seleksi Similar Serupa Color Range… Rentang Warna… Focus Area… Area Fokus… @@ -735,8 +734,8 @@ Legacy Macintosh RGB (Gamma 1.8) RGB Macintosh Lawas (Gamma 1.8) Internet Standard RGB (sRGB) RGB Standar Internet (sRGB) Monitor RGB RGB Monitor - Color Blindness — Protanopia-type Buta Warna — Tipe Protanopia - Color Blindness — Deuteranopia-type Buta Warna — Tipe Deuteranopia + Color Blindness - Protanopia-type Buta Warna - Tipe Protanopia + Color Blindness - Deuteranopia-type Buta Warna - Tipe Deuteranopia Zoom In Perbesar Zoom Out Perkecil Fit on Screen Pas di Layar @@ -1071,7 +1070,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Klik untuk menambah titik · seret keluar atau {key}-klik atau Delete untuk menghapus Click to apply, {key}-click to clear overrides, double-click for Style Options Klik untuk menerapkan, {key}-klik untuk menghapus override, klik dua kali untuk Opsi Gaya Click to edit the gradient Klik untuk mengedit gradien - Click to restore the current colour Klik untuk memulihkan warna saat ini + Click to restore the current color Klik untuk memulihkan warna saat ini Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Klik untuk zoom in · {key}-klik untuk zoom out · seret kanan/kiri untuk zoom in/out Click with the Note tool to add a note. Klik dengan alat Catatan untuk menambah catatan. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klik: sudut · Seret: halus · Klik titik pertama: tutup · {key} selesai · Esc batal @@ -1154,7 +1153,7 @@ Darks Gelap Data Sets Data Set Default Default - Default colours (D) Warna default (D) + Default Foreground and Background Colors (D) Warna default (D) Default printer Printer default Default restored. Default dipulihkan. Define Tentukan @@ -1431,7 +1430,7 @@ Opacity Jitter Jitter Opasitas Opacity: Opasitas: Open a document to define variables. Buka dokumen untuk menentukan variabel. - Open a document to select a colour range. Buka dokumen untuk memilih rentang warna. + Open a document to select a color range. Buka dokumen untuk memilih rentang warna. Open a document to use the timeline. Buka dokumen untuk memakai timeline. Optical Optik Optimized Dioptimalkan @@ -1507,7 +1506,6 @@ Purity Kemurnian Quality Kualitas Quick Actions Aksi Cepat - Quick Export As PNG Ekspor Cepat Sebagai PNG Radial Gradient Gradien Radial Radius Radius Radius: Radius: @@ -1648,7 +1646,7 @@ Subtract from Sample Kurangi dari Sampel Subtract from selection ({key}) Kurangi dari seleksi ({key}) Suggestions: Saran: - Swap colours (X) Tukar warna (X) + Switch Foreground and Background Colors (X) Tukar warna (X) Swaps height and width Tukar tinggi dan lebar Switch between free transform and warp modes Beralih antara mode transformasi bebas dan warp Switch theme Ganti tema @@ -1750,7 +1748,7 @@ Choke Choke Classic Klasik Click to add text Klik untuk menambah teks - Click to fill similar colours Klik untuk mengisi warna serupa + Click to fill similar colors Klik untuk mengisi warna serupa Clone Stamp Tool Alat Clone Stamp Color Burn Color Burn Color Dodge Color Dodge @@ -1910,7 +1908,7 @@ Rectangular Marquee Tool Alat Rectangular Marquee Reds Merah Reflected Pantulan - Sample: foreground colour Sampel: warna foreground + Sample: foreground color Sampel: warna foreground Sampled Colors Warna Sampel Satin Satin Save Pixel Aspect Ratio Simpan Rasio Aspek Piksel @@ -1949,7 +1947,6 @@ Transfer Transfer Triangle Tool Alat Triangle Unsaved changes Perubahan belum disimpan - Uses the foreground and background colours. Memakai warna foreground dan background. Web Web Web Large Web Besar Web Minimum Web Minimum @@ -1984,6 +1981,7 @@ Allow scripts to connect Izinkan skrip terhubung Always Selalu Always create smart objects when placing Selalu buat smart object saat menempatkan + Skip transform when placing Lewati transformasi saat menempatkan Animated zoom Zoom beranimasi Apply auto tone Terapkan auto tone Ask Tanya @@ -2217,7 +2215,7 @@ Graphics Grafis Reset GPU Backend Reset Backend GPU Applies at next launch. Berlaku saat dibuka berikutnya. - Click to sample the foreground colour · {key}-click for background Klik untuk mengambil sampel warna foreground · {key}-klik untuk background + Click to sample the foreground color · {key}-click for background Klik untuk mengambil sampel warna foreground · {key}-klik untuk background {key}-click to set the source {key}-klik untuk mengatur sumber {key} to subtract {key} untuk mengurangi Clone source {n} ({key}-click with Clone Stamp to set) Sumber clone {n} ({key}-klik dengan Clone Stamp untuk mengatur) @@ -2275,7 +2273,7 @@ Gradient Options Opsi Gradien Align with layer Sejajarkan dengan layer Reset Alignment Reset Penyelarasan - Centre the gradient (offset 0, 0) Tengahkan gradien (offset 0, 0) + Center the gradient (offset 0, 0) Tengahkan gradien (offset 0, 0) Gradient Editor Editor Gradien Gradient picker Pemilih gradien Save As Preset Simpan sebagai Preset @@ -2307,7 +2305,7 @@ Vulkan Vulkan No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Tidak ada path untuk dibuat seleksi: gambar dengan alat Pen atau pilih salah satu di panel Path. Cancel opening Batalkan pembukaan - Cancelled opening {name} Pembukaan {name} dibatalkan + Canceled opening {name} Pembukaan {name} dibatalkan Damaged Photoshop document Dokumen Photoshop rusak The document “{name}” may be damaged. Dokumen “{name}” mungkin rusak. Some layers, pixels or masks could not be read. Do you want to continue opening it? Beberapa layer, piksel, atau mask tidak dapat dibaca. Lanjutkan membukanya? @@ -2317,7 +2315,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokumen “{name}” memiliki profil warna tertanam yang tidak cocok dengan working space {mode} saat ini. Working: {working} Working space: {working} Developing {name} Mengembangkan {name} - Cancelled {label} {label} dibatalkan + Canceled {label} {label} dibatalkan Esc to cancel Esc untuk batal Opened {name} Dibuka: {name} Opening {name} Membuka {name} @@ -2325,7 +2323,7 @@ Saving {name} Menyimpan {name} Saving {percent} Menyimpan {percent} A save to {name} is still running; try again when it finishes Penyimpanan ke {name} masih berjalan; coba lagi setelah selesai - {label} is writing the file and can no longer be cancelled {label} sedang menulis berkas dan tidak dapat dibatalkan lagi + {label} is writing the file and can no longer be canceled {label} sedang menulis berkas dan tidak dapat dibatalkan lagi Opening {name}… Membuka {name}… Opening… Membuka… Reading… Membaca… @@ -2689,7 +2687,7 @@ Pixel Piksel Adjustment Penyesuaian Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Seret (lasso) atau klik titik (polygonal) · {add} tambah · {sub} kurangi - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Seret kotak crop · seret di dalam untuk memindah · tepi mengubah ukuran (rasio {ratio}, tengah {centre}) · Space memindah saat menggambar · panah menggeser · X menukar orientasi · {commit} menerapkan · Esc batal + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Seret kotak crop · seret di dalam untuk memindah · tepi mengubah ukuran (rasio {ratio}, tengah {centre}) · Space memindah saat menggambar · panah menggeser · X menukar orientasi · {commit} menerapkan · Esc batal {mode} Color · {bits} bit Warna {mode} · {bits} bit Drag to move the layer Seret untuk memindah layer Scrubby Zoom Zoom Scrubby @@ -2883,7 +2881,7 @@ cameraRaw Blending Pembauran Discard Layers and Save a Copy Buang Layer dan Simpan Salinan Don't show again Jangan tampilkan lagi Save failed: {error} Gagal menyimpan: {error} - Save cancelled Penyimpanan dibatalkan + Save canceled Penyimpanan dibatalkan Couldn't place {name}: {error} Tidak dapat menempatkan {name}: {error} Magnetic Lasso Tool Alat Magnetic Lasso Frequency Frekuensi @@ -3012,7 +3010,7 @@ fontWeight Italic Miring Impressionist Impresionis Rotate View Tool Alat Putar Tampilan Reset View Atur Ulang Tampilan - Drag around the centre to rotate the view · Shift constrains to 15° Seret di sekitar pusat untuk memutar tampilan · Shift membatasi ke 15° + Drag around the center to rotate the view · Shift constrains to 15° Seret di sekitar pusat untuk memutar tampilan · Shift membatasi ke 15° Dual Axis Sumbu Ganda Diagonal Diagonal Transform Symmetry Transformasi Simetri @@ -3027,8 +3025,8 @@ fontWeight Italic Miring All Layers No Adjustments Semua Layer Tanpa Penyesuaian Current & Below No Adjustments Saat Ini & Di Bawahnya Tanpa Penyesuaian Show Sampling Ring Tampilkan Cincin Sampel - Out of gamut for printing: click for the nearest printable colour Di luar gamut cetak: klik untuk warna cetak terdekat - Not a web colour: click for the nearest web colour Bukan warna web: klik untuk warna web terdekat + Out of gamut for printing: click for the nearest printable color Di luar gamut cetak: klik untuk warna cetak terdekat + Not a web color: click for the nearest web color Bukan warna web: klik untuk warna web terdekat Color to Alpha… Warna ke Alpha… Transparency Threshold Ambang transparansi Opacity Threshold Ambang opasitas @@ -3325,7 +3323,7 @@ curves Smooth Haluskan Auto Add/Delete Tambah/Hapus Otomatis Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Jangan aktifkan juga Gambar Cermin di Pengaturan Cetak: kedua pembalikan saling meniadakan. Print Settings… Pengaturan Cetak… - Remember to turn off the printer's own colour management in Print Settings… Ingat untuk menonaktifkan pengelolaan warna milik printer di Pengaturan Cetak… + Remember to turn off the printer's own color management in Print Settings… Ingat untuk menonaktifkan pengelolaan warna milik printer di Pengaturan Cetak… 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 @@ -3458,12 +3456,12 @@ curves Smooth Haluskan Decrease Brush Hardness Kurangi kekerasan kuas Increase Brush Hardness Tambah kekerasan kuas Demosaic Demosaik - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Cara mosaik filter warna kamera diisi. Diterapkan saat berkas dibuka; pratinjau menampilkan metode yang dipakai saat dibuka. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Cara mosaik filter warna kamera diisi. Diterapkan saat berkas dibuka; pratinjau menampilkan metode yang dipakai saat dibuka. AHD (adaptive homogeneity) AHD (homogenitas adaptif) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: tepi paling bersih dan pinggiran warna paling sedikit, paling lambat. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolasi terkoreksi gradien: tajam dan cepat, dengan sedikit pinggiran warna pada detail halus. - The fastest and the softest, with colour fringing on fine detail. Paling cepat dan paling lembut, dengan pinggiran warna pada detail halus. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: tepi paling bersih dan pinggiran warna paling sedikit, paling lambat. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolasi terkoreksi gradien: tajam dan cepat, dengan sedikit pinggiran warna pada detail halus. + The fastest and the softest, with color fringing on fine detail. Paling cepat dan paling lembut, dengan pinggiran warna pada detail halus. “{name}” already exists. Replace it? “{name}” sudah ada. Ganti? The name in the save dialog was “{name}”. Nama di dialog simpan adalah “{name}”. Previous Brush Kuas sebelumnya @@ -3629,6 +3627,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Pilih dokumen yang berbeda untuk setiap channel. A picked document is no longer open. Salah satu dokumen yang dipilih sudah tidak terbuka. A picked document is no longer a grayscale document of the same size. Salah satu dokumen yang dipilih bukan lagi dokumen grayscale dengan ukuran yang sama. +# Move tool options bar (#11381) + Align top edges Ratakan tepi atas + Align vertical centers Ratakan pusat vertikal + Align bottom edges Ratakan tepi bawah + Distribute vertically Distribusikan secara vertikal + Distribute horizontally Distribusikan secara horizontal + Show layer bounds on hover Tampilkan batas layer saat kursor di atasnya + Expand layer group on click Perluas grup layer saat diklik + Show hover bounds from Layers Tampilkan batas saat kursor di atas dari Layer +# Artboard tool options bar (#11385) + Distribute Widths Distribusi lebar + Distribute Heights Distribusi tinggi + Auto-nest Layers Sarangkan layer secara otomatis + Auto-size Canvas Ubah ukuran kanvas otomatis + Keep Relative Position During Layer Reordering Pertahankan posisi relatif saat mengurutkan ulang layer + Shrinkwrap Canvas on Save Kecilkan kanvas sesuai konten saat menyimpan # JPEG Options: the size the file will have (#7843) Estimated file size Perkiraan ukuran file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1a88b5f16a..93ca66b396 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -648,7 +648,6 @@ Deselect Deseleziona Reselect Riseleziona Inverse Inverti - Inverse Selection Inverti selezione Similar Simile Color Range… Intervallo colori… Focus Area… Area di messa a fuoco… @@ -767,8 +766,8 @@ Legacy Macintosh RGB (Gamma 1.8) RGB legacy Macintosh (Gamma 1.8) Internet Standard RGB (sRGB) RGB standard Internet (sRGB) Monitor RGB RGB monitor - Color Blindness — Protanopia-type Daltonismo — tipo protanopia - Color Blindness — Deuteranopia-type Daltonismo — tipo deuteranopia + Color Blindness - Protanopia-type Daltonismo - tipo protanopia + Color Blindness - Deuteranopia-type Daltonismo - tipo deuteranopia Zoom In Ingrandisci Zoom Out Riduci Fit on Screen Adatta a schermo @@ -1088,7 +1087,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Clic per aggiungere un punto · trascina fuori, {key}-clic o Canc per rimuovere Click to apply, {key}-click to clear overrides, double-click for Style Options Clic per applicare, {key}-clic per rimuovere eccezioni, doppio clic per Opzioni stile Click to edit the gradient Clic per modificare la sfumatura - Click to restore the current colour Clic per ripristinare il colore corrente + Click to restore the current color Clic per ripristinare il colore corrente Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Clic per ingrandire · {key}-clic per ridurre · trascina dx/sx per zoom Click with the Note tool to add a note. Fai clic con lo strumento Nota per aggiungere una nota. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Clic: angolo · Trascina: morbido · Clic primo punto: chiudi · {key} termina · Esc annulla @@ -1173,7 +1172,7 @@ Darks Scuri Data Sets Set di dati Default Predefinito - Default colours (D) Colori predefiniti (D) + Default Foreground and Background Colors (D) Colori di primo piano e sfondo predefiniti (D) Default printer Stampante predefinita Default restored. Predefinito ripristinato. Define Definisci @@ -1455,7 +1454,7 @@ Opacity Jitter Variazione opacità Opacity: Opacità: Open a document to define variables. Apri un documento per definire variabili. - Open a document to select a colour range. Apri un documento per selezionare un intervallo colori. + Open a document to select a color range. Apri un documento per selezionare un intervallo colori. Open a document to use the timeline. Apri un documento per usare la timeline. Optical Ottico Optimized Ottimizzato @@ -1531,7 +1530,6 @@ Purity Purezza Quality Qualità Quick Actions Azioni rapide - Quick Export As PNG Esportazione rapida come PNG Radial Gradient Sfumatura radiale Radius Raggio Radius: Raggio: @@ -1673,7 +1671,7 @@ Subtract from Sample Sottrai da campione Subtract from selection ({key}) Sottrai da selezione ({key}) Suggestions: Suggerimenti: - Swap colours (X) Scambia colori (X) + Switch Foreground and Background Colors (X) Scambia colori di primo piano e sfondo (X) Swaps height and width Scambia altezza e larghezza Switch between free transform and warp modes Passa tra trasformazione libera e altera Switch theme Cambia tema @@ -1776,7 +1774,7 @@ Choke Strozza Classic Classico Click to add text Fai clic per aggiungere testo - Click to fill similar colours Fai clic per riempire colori simili + Click to fill similar colors Fai clic per riempire colori simili Clone Stamp Tool Strumento Timbro clone Color Burn Colore brucia Color Dodge Colore scherma @@ -1936,7 +1934,7 @@ Rectangular Marquee Tool Strumento Selezione rettangolare Reds Rossi Reflected Riflesso - Sample: foreground colour Campione: colore primo piano + Sample: foreground color Campione: colore primo piano Sampled Colors Colori campionati Satin Raso Save Pixel Aspect Ratio Salva proporzioni pixel @@ -1975,7 +1973,6 @@ Transfer Trasferimento Triangle Tool Strumento Triangolo Unsaved changes Modifiche non salvate - Uses the foreground and background colours. Usa i colori di primo piano e sfondo. Web Web Web Large Web grande Web Minimum Web minimo @@ -2012,6 +2009,7 @@ Allow scripts to connect Consenti connessione script Always Sempre Always create smart objects when placing Crea sempre oggetti avanzati all'inserimento + Skip transform when placing Salta la trasformazione all'inserimento Animated zoom Zoom animato Apply auto tone Applica tono automatico Ask Chiedi @@ -2248,7 +2246,7 @@ Graphics Grafica Reset GPU Backend Reimposta backend GPU Applies at next launch. Si applica al prossimo avvio. - Click to sample the foreground colour · {key}-click for background Clic per campionare colore primo piano · {key}-clic per sfondo + Click to sample the foreground color · {key}-click for background Clic per campionare colore primo piano · {key}-clic per sfondo {key}-click to set the source {key}-clic per impostare sorgente {key} to subtract {key} per sottrarre Clone source {n} ({key}-click with Clone Stamp to set) Sorgente clone {n} ({key}-clic con Timbro clone per impostare) @@ -2309,7 +2307,7 @@ Gradient Options Opzioni sfumatura Align with layer Allinea con livello Reset Alignment Reimposta allineamento - Centre the gradient (offset 0, 0) Centra sfumatura (offset 0,0) + Center the gradient (offset 0, 0) Centra sfumatura (offset 0,0) Gradient Editor Editor sfumatura Gradient picker Selettore sfumatura Gradient stops Punti della sfumatura @@ -2343,7 +2341,7 @@ Alt-click to define a source point to clone from Alt-clic per definire un punto sorgente da clonare No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nessun tracciato da cui creare selezione: disegnane uno con Penna o selezionane uno nel pannello Tracciati. Cancel opening Annulla apertura - Cancelled opening {name} Apertura {name} annullata + Canceled opening {name} Apertura {name} annullata Damaged Photoshop document Documento Photoshop danneggiato The document “{name}” may be damaged. Il documento “{name}” potrebbe essere danneggiato. Some layers, pixels or masks could not be read. Do you want to continue opening it? Non è stato possibile leggere alcuni livelli, pixel o maschere. Continuare ad aprirlo? @@ -2352,7 +2350,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Il documento “{name}” ha un profilo colore incorporato che non corrisponde allo spazio di lavoro {mode} corrente. Working: {working} Di lavoro: {working} Developing {name} Sviluppo di {name} - Cancelled {label} {label} annullato + Canceled {label} {label} annullato Esc to cancel Esc per annullare Opened {name} Aperto: {name} Opening {name} Apertura {name} @@ -2360,7 +2358,7 @@ Saving {name} Salvataggio {name} Saving {percent} Salvataggio {percent} A save to {name} is still running; try again when it finishes Un salvataggio in {name} è ancora in corso; riprova quando termina - {label} is writing the file and can no longer be cancelled {label} sta scrivendo il file e non può più essere annullato + {label} is writing the file and can no longer be canceled {label} sta scrivendo il file e non può più essere annullato Opening {name}… Apertura {name}… Opening… Apertura… Reading… Lettura… @@ -2426,7 +2424,7 @@ Pixel Pixel Adjustment Regolazione Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Trascina (lazo) o clic su punti (poligonale) · {add} aggiungi · {sub} sottrai - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Trascina un riquadro ritaglio · trascina dentro per spostare · bordi ridimensionano ({ratio} proporzione, {centre} centro) · Spazio sposta durante disegno · frecce spostano · X scambia orientamento · {commit} conferma · Esc annulla + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Trascina un riquadro ritaglio · trascina dentro per spostare · bordi ridimensionano ({ratio} proporzione, {centre} centro) · Spazio sposta durante disegno · frecce spostano · X scambia orientamento · {commit} conferma · Esc annulla {mode} Color · {bits} bit Colore {mode} · {bits} bit Scrubby Zoom Zoom scrubby Auto Erase Cancellazione automatica @@ -2521,7 +2519,7 @@ cameraRaw Amount Quantità Discard Layers and Save a Copy Elimina i livelli e salva una copia Don't show again Non mostrare più Save failed: {error} Salvataggio non riuscito: {error} - Save cancelled Salvataggio annullato + Save canceled Salvataggio annullato Extend Estendi Structure: Struttura: Style {name} saved Stile {name} salvato @@ -2658,7 +2656,7 @@ fontWeight Italic Corsivo Rotate View Ruota vista Rotate View Tool Strumento Ruota vista Reset View Reimposta vista - Drag around the centre to rotate the view · Shift constrains to 15° Trascina intorno al centro per ruotare la vista · Maiusc vincola a 15° + Drag around the center to rotate the view · Shift constrains to 15° Trascina intorno al centro per ruotare la vista · Maiusc vincola a 15° Dual Axis Doppio asse Diagonal Diagonale Transform Symmetry Trasforma simmetria @@ -2673,8 +2671,8 @@ fontWeight Italic Corsivo All Layers No Adjustments Tutti i livelli senza regolazioni Current & Below No Adjustments Corrente e inferiori senza regolazioni Show Sampling Ring Mostra anello di campionamento - Out of gamut for printing: click for the nearest printable colour Fuori gamma di stampa: fai clic per il colore stampabile più vicino - Not a web colour: click for the nearest web colour Non è un colore web: fai clic per il colore web più vicino + Out of gamut for printing: click for the nearest printable color Fuori gamma di stampa: fai clic per il colore stampabile più vicino + Not a web color: click for the nearest web color Non è un colore web: fai clic per il colore web più vicino Color to Alpha… Colore ad alfa… Transparency Threshold Soglia di trasparenza Opacity Threshold Soglia di opacità @@ -4273,7 +4271,7 @@ navigator Zoom Zoom Auto Add/Delete Aggiungi/elimina automaticamente Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Non attivare anche Immagine speculare nelle impostazioni di stampa: le due inversioni si annullano. Print Settings… Impostazioni di stampa… - Remember to turn off the printer's own colour management in Print Settings… Ricorda di disattivare la gestione del colore della stampante nelle impostazioni di stampa… + Remember to turn off the printer's own color management in Print Settings… Ricorda di disattivare la gestione del colore della stampante nelle impostazioni di stampa… 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 @@ -4560,12 +4558,12 @@ shape Appearance Aspetto {name} was changed by another app after it was opened or saved here. {name} è stato modificato da un'altra app dopo essere stato aperto o salvato qui. Replace it with this document, or cancel and use File › Save As to keep both. Sostituiscilo con questo documento, oppure annulla e usa File › Salva con nome per tenerli entrambi. Demosaic Demosaicizzazione - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Come viene completato il mosaico del filtro colore della fotocamera. Si applica all'apertura del file; l'anteprima mostra il metodo con cui è stato aperto. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Come viene completato il mosaico del filtro colore della fotocamera. Si applica all'apertura del file; l'anteprima mostra il metodo con cui è stato aperto. AHD (adaptive homogeneity) AHD (omogeneità adattiva) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: i bordi più puliti e le minori frange di colore, il più lento. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolazione con correzione del gradiente: nitida e veloce, con qualche frangia di colore nei dettagli fini. - The fastest and the softest, with colour fringing on fine detail. Il più veloce e il più morbido, con frange di colore nei dettagli fini. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: i bordi più puliti e le minori frange di colore, il più lento. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolazione con correzione del gradiente: nitida e veloce, con qualche frangia di colore nei dettagli fini. + The fastest and the softest, with color fringing on fine detail. Il più veloce e il più morbido, con frange di colore nei dettagli fini. “{name}” already exists. Replace it? “{name}” esiste già. Sostituirlo? The name in the save dialog was “{name}”. Il nome nella finestra di salvataggio era “{name}”. Memory Usage Utilizzo memoria @@ -4705,6 +4703,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Scegli un documento diverso per ogni canale. A picked document is no longer open. Uno dei documenti scelti non è più aperto. A picked document is no longer a grayscale document of the same size. Uno dei documenti scelti non è più un documento in scala di grigio delle stesse dimensioni. +# Move tool options bar (#11381) + Align top edges Allinea i bordi superiori + Align vertical centers Allinea i centri verticali + Align bottom edges Allinea i bordi inferiori + Distribute vertically Distribuisci verticalmente + Distribute horizontally Distribuisci orizzontalmente + Show layer bounds on hover Mostra i limiti del livello al passaggio del mouse + Expand layer group on click Espandi il gruppo di livelli al clic + Show hover bounds from Layers Mostra i limiti al passaggio dal pannello Livelli +# Artboard tool options bar (#11385) + Distribute Widths Distribuisci larghezze + Distribute Heights Distribuisci altezze + Auto-nest Layers Annida livelli automaticamente + Auto-size Canvas Ridimensiona quadro automaticamente + Keep Relative Position During Layer Reordering Mantieni la posizione relativa durante il riordino dei livelli + Shrinkwrap Canvas on Save Riduci il quadro al contenuto al salvataggio # JPEG Options: the size the file will have (#7843) Estimated file size Dimensioni stimate del file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index fd668c106e..3303a58d6f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -660,7 +660,6 @@ Deselect 選択を解除 Reselect 再選択 Inverse 選択範囲を反転 - Inverse Selection 選択範囲を反転 Similar 近似色を選択 Color Range… 色域指定… Focus Area… 焦点領域… @@ -780,8 +779,8 @@ Legacy Macintosh RGB (Gamma 1.8) 旧 Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) インターネット標準 RGB (sRGB) Monitor RGB モニター RGB - Color Blindness — Protanopia-type 色覚特性 — 1 型(P 型) - Color Blindness — Deuteranopia-type 色覚特性 — 2 型(D 型) + Color Blindness - Protanopia-type 色覚特性 - 1 型(P 型) + Color Blindness - Deuteranopia-type 色覚特性 - 2 型(D 型) Zoom In 拡大 Zoom Out 縮小 Fit on Screen 画面サイズに合わせる @@ -1102,7 +1101,7 @@ Click to add a point · drag off or {key}-click or Delete to remove クリックで点を追加 · 外へドラッグ、{key}+クリック、Delete で削除 Click to apply, {key}-click to clear overrides, double-click for Style Options クリックで適用、{key}+クリックで上書き解除、ダブルクリックでスタイルオプション Click to edit the gradient クリックしてグラデーションを編集 - Click to restore the current colour クリックして現在の色に戻す + Click to restore the current color クリックして現在の色に戻す Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out クリックで拡大 · {key}+クリックで縮小 · 右/左にドラッグで拡大/縮小 Click with the Note tool to add a note. 注釈ツールでクリックすると注釈を追加できます。 Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel クリック: 角 · ドラッグ: 滑らか · 最初の点をクリック: 閉じる · {key} 完了 · Esc キャンセル @@ -1185,7 +1184,7 @@ Darks 暗部 Data Sets データセット Default 既定 - Default colours (D) 初期カラーに戻す(D) + Default Foreground and Background Colors (D) 前景色と背景色を既定に戻す (D) Default printer 既定のプリンター Default restored. 既定に戻しました。 Define 定義 @@ -1467,7 +1466,7 @@ Opacity Jitter 不透明度のジッター Opacity: 不透明度: Open a document to define variables. 変数を定義するには、ドキュメントを開いてください。 - Open a document to select a colour range. 色域を指定するには、ドキュメントを開いてください。 + Open a document to select a color range. 色域を指定するには、ドキュメントを開いてください。 Open a document to use the timeline. タイムラインを使うには、ドキュメントを開いてください。 Optical オプティカル Optimized 最適化 @@ -1543,7 +1542,6 @@ Purity 純度 Quality 画質 Quick Actions クイックアクション - Quick Export As PNG PNG としてクイック書き出し Radial Gradient 円形グラデーション Radius 半径 Radius: 半径: @@ -1683,7 +1681,7 @@ Subtract from Sample サンプルから削除 Subtract from selection ({key}) 選択範囲から削除 ({key}) Suggestions: 候補: - Swap colours (X) 描画色と背景色を入れ替え(X) + Switch Foreground and Background Colors (X) 前景色と背景色を入れ替え (X) Swaps height and width 高さと幅を入れ替えます Switch between free transform and warp modes 自由変形とワープのモードを切り替え Switch theme テーマを切り替え @@ -1786,7 +1784,7 @@ Choke 境界のぼかし幅 Classic クラシック Click to add text クリックしてテキストを追加 - Click to fill similar colours クリックして近い色を塗りつぶし + Click to fill similar colors クリックして近い色を塗りつぶし Clone Stamp Tool コピースタンプツール Color Burn 焼き込みカラー Color Dodge 覆い焼きカラー @@ -1947,7 +1945,7 @@ Rectangular Marquee Tool 長方形選択ツール Reds レッド系 Reflected 反射形 - Sample: foreground colour サンプル: 描画色 + Sample: foreground color サンプル: 描画色 Sampled Colors サンプルしたカラー Satin サテン Save Pixel Aspect Ratio ピクセル縦横比を保存 @@ -1986,7 +1984,6 @@ Transfer 伝達 Triangle Tool 三角形ツール Unsaved changes 未保存の変更 - Uses the foreground and background colours. 描画色と背景色を使用します。 Web Web Web Large Web (大) Web Minimum Web (最小) @@ -2023,6 +2020,7 @@ Allow scripts to connect スクリプトからの接続を許可 Always 常に Always create smart objects when placing 配置時に常にスマートオブジェクトを作成 + Skip transform when placing 配置時に変形をスキップ Animated zoom アニメーションズーム Apply auto tone 自動トーン補正を適用 Ask 確認する @@ -2259,7 +2257,7 @@ Graphics グラフィックス Reset GPU Backend GPU バックエンドをリセット Applies at next launch. 次回の起動時に適用されます。 - Click to sample the foreground colour · {key}-click for background クリックで描画色を取得 · {key}+クリックで背景色を取得 + Click to sample the foreground color · {key}-click for background クリックで描画色を取得 · {key}+クリックで背景色を取得 {key}-click to set the source {key}+クリックでソースを設定 {key} to subtract {key} で削除 Clone source {n} ({key}-click with Clone Stamp to set) コピーソース {n} ({key}+クリックでコピースタンプのソースを設定) @@ -2318,7 +2316,7 @@ Gradient Options グラデーションオプション Align with layer レイヤーに揃える Reset Alignment 位置をリセット - Centre the gradient (offset 0, 0) グラデーションを中央に配置(オフセット 0, 0) + Center the gradient (offset 0, 0) グラデーションを中央に配置(オフセット 0, 0) Gradient Editor グラデーションエディター Gradient picker グラデーションピッカー Save As Preset プリセットとして保存 @@ -2350,7 +2348,7 @@ Vulkan Vulkan No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 選択範囲を作成するパスがありません。ペンツールで描くか、パスパネルでパスを選択してください。 Cancel opening 開くのをキャンセル - Cancelled opening {name} {name} を開くのをキャンセルしました + Canceled opening {name} {name} を開くのをキャンセルしました Damaged Photoshop document 破損した Photoshop ドキュメント The document “{name}” may be damaged. ドキュメント「{name}」は破損している可能性があります。 Some layers, pixels or masks could not be read. Do you want to continue opening it? 一部のレイヤー、ピクセル、またはマスクを読み込めませんでした。開く処理を続行しますか? @@ -2360,7 +2358,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. ドキュメント「{name}」の埋め込みカラープロファイルは、現在の {mode} 作業用スペースと一致しません。 Working: {working} 作業用スペース: {working} Developing {name} {name} を現像中 - Cancelled {label} {label} をキャンセルしました + Canceled {label} {label} をキャンセルしました Esc to cancel Esc キーでキャンセル Opened {name} {name} を開きました Opening {name} {name} を開いています @@ -2368,7 +2366,7 @@ Saving {name} {name} を保存しています Saving {percent} 保存中 {percent} A save to {name} is still running; try again when it finishes {name} への保存がまだ実行中です。完了してからもう一度お試しください - {label} is writing the file and can no longer be cancelled {label} はファイルを書き込み中のため、キャンセルできません + {label} is writing the file and can no longer be canceled {label} はファイルを書き込み中のため、キャンセルできません Opening {name}… {name} を開いています… Opening… 開いています… Reading… 読み込み中… @@ -2446,7 +2444,7 @@ cameraRaw Color カラー Discard Layers and Save a Copy レイヤーを破棄してコピーを保存 Don't show again 次回から表示しない Save failed: {error} 保存に失敗しました: {error} - Save cancelled 保存をキャンセルしました + Save canceled 保存をキャンセルしました Magnetic Lasso Tool マグネット選択ツール Frequency 頻度 Use tablet pressure to change pen width タブレットの筆圧を使用してペンの幅を変更 @@ -2575,7 +2573,7 @@ fontWeight Italic 斜体 Rotate View 表示を回転 Rotate View Tool 表示回転ツール Reset View 表示をリセット - Drag around the centre to rotate the view · Shift constrains to 15° 中心の周りをドラッグして表示を回転 · Shift で 15° 単位 + Drag around the center to rotate the view · Shift constrains to 15° 中心の周りをドラッグして表示を回転 · Shift で 15° 単位 Dual Axis 二軸 Diagonal 斜め Transform Symmetry 対称軸を変形 @@ -2590,8 +2588,8 @@ fontWeight Italic 斜体 All Layers No Adjustments すべてのレイヤー (色調補正なし) Current & Below No Adjustments 現在のレイヤーとその下 (色調補正なし) Show Sampling Ring サンプリングリングを表示 - Out of gamut for printing: click for the nearest printable colour 印刷の色域外: クリックすると最も近い印刷可能な色になります - Not a web colour: click for the nearest web colour Web カラーではありません: クリックすると最も近い Web カラーになります + Out of gamut for printing: click for the nearest printable color 印刷の色域外: クリックすると最も近い印刷可能な色になります + Not a web color: click for the nearest web color Web カラーではありません: クリックすると最も近い Web カラーになります Accented Edges 輪郭の強調 Adjust Interval For Loops ループ用に間隔を調整 Adjustment Properties 色調補正のプロパティ @@ -3434,7 +3432,7 @@ fontWeight Italic 斜体 Document Size ドキュメントサイズ Dodge/Burn 覆い焼き/焼き込み Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract ドラッグ (投げ縄) またはクリックでポイント指定 (多角形) · {add} 追加 · {sub} 除外 - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 切り抜きボックスをドラッグ · 内側をドラッグで移動 · 縁でサイズ変更 ({ratio} で比率、{centre} で中心) · 描画中は Space で移動 · 矢印キーで微調整 · X で縦横を切り替え · {commit} で確定 · Esc で取り消し + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 切り抜きボックスをドラッグ · 内側をドラッグで移動 · 縁でサイズ変更 ({ratio} で比率、{centre} で中心) · 描画中は Space で移動 · 矢印キーで微調整 · X で縦横を切り替え · {commit} で確定 · Esc で取り消し Drag to move the layer ドラッグしてレイヤーを移動 Duplicated selection name 複製した選択範囲の名前 Dynamics ダイナミクス @@ -3984,7 +3982,7 @@ curves Smooth スムーズ Auto Add/Delete 自動追加・削除 Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 印刷設定の「鏡像」も有効にしないでください。2回反転すると元に戻ります。 Print Settings… 印刷設定… - Remember to turn off the printer's own colour management in Print Settings… 印刷設定でプリンター独自のカラーマネジメントを無効にしてください… + Remember to turn off the printer's own color management in Print Settings… 印刷設定でプリンター独自のカラーマネジメントを無効にしてください… Sent to {printer} {printer} に送信しました set in Print Settings… 印刷設定で指定… Drag to pan · Scroll to zoom · Double-click to fit ドラッグで移動 · スクロールでズーム · ダブルクリックで全体表示 @@ -4119,12 +4117,12 @@ curves Smooth スムーズ Decrease Brush Hardness ブラシの硬さを下げる Increase Brush Hardness ブラシの硬さを上げる Demosaic デモザイク - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. カメラのカラーフィルター配列をどのように補間するか。ファイルを開くときに適用されます。プレビューは開いたときの方式で表示されます。 + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. カメラのカラーフィルター配列をどのように補間するか。ファイルを開くときに適用されます。プレビューは開いたときの方式で表示されます。 AHD (adaptive homogeneity) AHD(適応的均質性) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks:エッジが最もきれいで色にじみが最も少ないが、最も遅い。 - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. 勾配補正補間:シャープで高速だが、細部に多少の色にじみが出る。 - The fastest and the softest, with colour fringing on fine detail. 最も高速で最も柔らかく、細部に色にじみが出る。 + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks:エッジが最もきれいで色にじみが最も少ないが、最も遅い。 + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. 勾配補正補間:シャープで高速だが、細部に多少の色にじみが出る。 + The fastest and the softest, with color fringing on fine detail. 最も高速で最も柔らかく、細部に色にじみが出る。 “{name}” already exists. Replace it? 「{name}」は既に存在します。置き換えますか? The name in the save dialog was “{name}”. 保存ダイアログで指定した名前は「{name}」でした。 Previous Brush 前のブラシ @@ -4277,6 +4275,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. チャンネルごとに別のドキュメントを選択してください。 A picked document is no longer open. 選択したドキュメントの一つが開かれていません。 A picked document is no longer a grayscale document of the same size. 選択したドキュメントの一つが、同じサイズのグレースケールのドキュメントではなくなりました。 +# Move tool options bar (#11381) + Align top edges 上端を揃える + Align vertical centers 垂直方向中央を揃える + Align bottom edges 下端を揃える + Distribute vertically 垂直方向に分布 + Distribute horizontally 水平方向に分布 + Show layer bounds on hover ホバー時にレイヤーの境界を表示 + Expand layer group on click クリックでレイヤーグループを展開 + Show hover bounds from Layers レイヤーパネルからのホバー境界を表示 +# Artboard tool options bar (#11385) + Distribute Widths 幅を分布 + Distribute Heights 高さを分布 + Auto-nest Layers レイヤーを自動でネスト + Auto-size Canvas カンバスサイズを自動調整 + Keep Relative Position During Layer Reordering レイヤーの並べ替え中も相対位置を保持 + Shrinkwrap Canvas on Save 保存時にカンバスを内容に合わせて縮小 # JPEG Options: the size the file will have (#7843) Estimated file size 推定ファイルサイズ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index df7ed6699c..ad0661caf5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -625,7 +625,6 @@ Deselect 선택 해제 Reselect 다시 선택 Inverse 반전 - Inverse Selection 선택 영역 반전 Similar 유사한 항목 Color Range… 색상 범위… Focus Area… 초점 영역… @@ -745,8 +744,8 @@ Legacy Macintosh RGB (Gamma 1.8) 기존 Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) 인터넷 표준 RGB (sRGB) Monitor RGB 모니터 RGB - Color Blindness — Protanopia-type 색각 이상 — 적색맹 - Color Blindness — Deuteranopia-type 색각 이상 — 녹색맹 + Color Blindness - Protanopia-type 색각 이상 - 적색맹 + Color Blindness - Deuteranopia-type 색각 이상 - 녹색맹 Zoom In 확대 Zoom Out 축소 Fit on Screen 화면에 맞추기 @@ -1073,7 +1072,7 @@ Click to add a point · drag off or {key}-click or Delete to remove 클릭하여 점 추가 · 바깥으로 드래그하거나 {key} 키를 누른 채 클릭하거나 Delete 키로 제거 Click to apply, {key}-click to clear overrides, double-click for Style Options 클릭하여 적용, {key} 키를 누른 채 클릭하여 재정의 지우기, 두 번 클릭하여 스타일 옵션 열기 Click to edit the gradient 클릭하여 그레이디언트 편집 - Click to restore the current colour 클릭하여 현재 색상 복원 + Click to restore the current color 클릭하여 현재 색상 복원 Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out 클릭하여 확대 · {key} 키를 누른 채 클릭하여 축소 · 오른쪽/왼쪽으로 드래그하여 확대/축소 Click with the Note tool to add a note. 메모 도구로 클릭하여 메모를 추가하세요. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel 클릭: 모서리 · 드래그: 곡선 · 첫 점 클릭: 닫기 · {key}: 완료 · Esc: 취소 @@ -1162,7 +1161,7 @@ Darks 어두운 계열 Data Sets 데이터 세트 Default 기본값 - Default colours (D) 기본 색상 (D) + Default Foreground and Background Colors (D) 기본 색상 (D) Default printer 기본 프린터 Default restored. 기본값을 복원했습니다. Define 정의 @@ -1439,7 +1438,7 @@ Opacity Jitter 불투명도 지터 Opacity: 불투명도: Open a document to define variables. 변수를 정의하려면 문서를 여세요. - Open a document to select a colour range. 색상 범위를 선택하려면 문서를 여세요. + Open a document to select a color range. 색상 범위를 선택하려면 문서를 여세요. Open a document to use the timeline. 타임라인을 사용하려면 문서를 여세요. Optical 광학 Optimized 최적화 @@ -1515,7 +1514,6 @@ Purity 순도 Quality 품질 Quick Actions 빠른 작업 - Quick Export As PNG PNG로 빠르게 내보내기 Radial Gradient 방사형 그레이디언트 Radius 반경 Radius: 반경: @@ -1658,7 +1656,7 @@ Subtract from Sample 샘플에서 빼기 Subtract from selection ({key}) 선택 영역에서 빼기 ({key}) Suggestions: 제안: - Swap colours (X) 색상 교환 (X) + Switch Foreground and Background Colors (X) 색상 교환 (X) Swaps height and width 높이와 너비 바꾸기 Switch between free transform and warp modes 자유 변형과 뒤틀기 모드 간 전환 Switch theme 테마 전환 @@ -1762,7 +1760,7 @@ Choke 조이기 Classic 클래식 Click to add text 클릭하여 텍스트 추가 - Click to fill similar colours 클릭하여 유사한 색상 채우기 + Click to fill similar colors 클릭하여 유사한 색상 채우기 Clone Stamp Tool 복제 도장 도구 Color Burn 색상 번 Color Dodge 색상 닷지 @@ -1922,7 +1920,7 @@ Rectangular Marquee Tool 사각형 선택 윤곽 도구 Reds 빨강 계열 Reflected 반사 - Sample: foreground colour 샘플: 전경색 + Sample: foreground color 샘플: 전경색 Sampled Colors 샘플링한 색상 Satin 새틴 Save Pixel Aspect Ratio 픽셀 종횡비 저장 @@ -1961,7 +1959,7 @@ Transfer 전달 Triangle Tool 삼각형 도구 Unsaved changes 저장하지 않은 변경 사항 - Uses the foreground and background colours. 전경색과 배경색을 사용합니다. + Uses the foreground and background colors. 전경색과 배경색을 사용합니다. Web 웹 Web Large 웹 대형 Web Minimum 웹 최소 @@ -1996,6 +1994,7 @@ Allow scripts to connect 스크립트 연결 허용 Always 항상 Always create smart objects when placing 가져올 때 항상 스마트 오브젝트 만들기 + Skip transform when placing 가져올 때 변형 건너뛰기 Animated zoom 확대/축소 애니메이션 Apply auto tone 자동 톤 적용 Ask 묻기 @@ -2229,7 +2228,7 @@ Graphics 그래픽 Reset GPU Backend GPU 백엔드 초기화 Applies at next launch. 다음 실행 시 적용됩니다. - Click to sample the foreground colour · {key}-click for background 클릭하여 전경색 샘플링 · {key} 키를 누른 채 클릭하여 배경색 샘플링 + Click to sample the foreground color · {key}-click for background 클릭하여 전경색 샘플링 · {key} 키를 누른 채 클릭하여 배경색 샘플링 {key}-click to set the source {key} 키를 누른 채 클릭하여 원본 설정 {key} to subtract {key} 키로 빼기 Clone source {n} ({key}-click with Clone Stamp to set) 복제 원본 {n} (복제 도장으로 {key} 키를 누른 채 클릭하여 설정) @@ -2288,7 +2287,7 @@ Gradient Options 그레이디언트 옵션 Align with layer 레이어에 맞추기 Reset Alignment 정렬 초기화 - Centre the gradient (offset 0, 0) 그레이디언트를 중앙에 배치(오프셋 0, 0) + Center the gradient (offset 0, 0) 그레이디언트를 중앙에 배치(오프셋 0, 0) The current gradient (pick one in Window › Gradients) 현재 그레이디언트(창 › 그레이디언트에서 선택) Select a type layer to edit its character and paragraph settings. 문자 및 단락 설정을 편집하려면 문자 레이어를 선택하세요. Gradient Editor 그레이디언트 편집기 @@ -2321,7 +2320,7 @@ Vulkan Vulkan No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 선택 영역으로 만들 패스가 없습니다: 펜 도구로 그리거나 패스 패널에서 선택하세요. Cancel opening 열기 취소 - Cancelled opening {name} {name} 열기를 취소했습니다 + Canceled opening {name} {name} 열기를 취소했습니다 Damaged Photoshop document 손상된 Photoshop 문서 The document “{name}” may be damaged. 문서 “{name}”이(가) 손상되었을 수 있습니다. Some layers, pixels or masks could not be read. Do you want to continue opening it? 일부 레이어, 픽셀 또는 마스크를 읽을 수 없습니다. 계속 여시겠습니까? @@ -2331,7 +2330,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. 문서 “{name}”에 포함된 색상 프로파일이 현재 {mode} 작업 색상 공간과 일치하지 않습니다. Working: {working} 작업 색상 공간: {working} Developing {name} {name} 현상 중 - Cancelled {label} {label} 작업을 취소했습니다 + Canceled {label} {label} 작업을 취소했습니다 Esc to cancel Esc 키로 취소 Opened {name} {name} 열림 Opening {name} {name} 여는 중 @@ -2339,7 +2338,7 @@ Saving {name} {name} 저장 중 Saving {percent} 저장 중 {percent} A save to {name} is still running; try again when it finishes {name}에 저장하는 작업이 아직 진행 중입니다. 완료된 후 다시 시도하세요 - {label} is writing the file and can no longer be cancelled {label}: 파일을 쓰는 중이므로 더 이상 취소할 수 없습니다 + {label} is writing the file and can no longer be canceled {label}: 파일을 쓰는 중이므로 더 이상 취소할 수 없습니다 Opening {name}… {name} 여는 중… Opening… 여는 중… Reading… 읽는 중… @@ -3066,7 +3065,7 @@ cameraRaw Color 색상 Discard Layers and Save a Copy 레이어를 삭제하고 사본 저장 Don't show again 다시 표시 안 함 Save failed: {error} 저장 실패: {error} - Save cancelled 저장이 취소되었습니다 + Save canceled 저장이 취소되었습니다 Couldn't place {name}: {error} {name}을(를) 가져올 수 없습니다: {error} Magnetic Lasso Tool 자석 올가미 도구 Frequency 빈도 @@ -3192,7 +3191,7 @@ fontWeight Italic 기울임 Rotate View 보기 회전 Rotate View Tool 보기 회전 도구 Reset View 보기 재설정 - Drag around the centre to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기 회전 · Shift로 15° 단위 제한 + Drag around the center to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기 회전 · Shift로 15° 단위 제한 Dual Axis 이중 축 Diagonal 대각선 Transform Symmetry 대칭 변형 @@ -3207,8 +3206,8 @@ fontWeight Italic 기울임 All Layers No Adjustments 모든 레이어(조정 제외) Current & Below No Adjustments 현재 및 이하(조정 제외) Show Sampling Ring 샘플링 링 표시 - Out of gamut for printing: click for the nearest printable colour 인쇄 색역 밖: 클릭하면 가장 가까운 인쇄 가능한 색상으로 바뀝니다 - Not a web colour: click for the nearest web colour 웹 색상이 아님: 클릭하면 가장 가까운 웹 색상으로 바뀝니다 + Out of gamut for printing: click for the nearest printable color 인쇄 색역 밖: 클릭하면 가장 가까운 인쇄 가능한 색상으로 바뀝니다 + Not a web color: click for the nearest web color 웹 색상이 아님: 클릭하면 가장 가까운 웹 색상으로 바뀝니다 Color to Alpha… 색상을 알파로… Transparency Threshold 투명도 한계값 Opacity Threshold 불투명도 한계값 @@ -3300,7 +3299,7 @@ fontWeight Italic 기울임 How often fastening points are placed by themselves 고정점이 자동으로 놓이는 빈도 Scrubby Zoom 스크러비 확대/축소 {mode} Color · {bits} bit {mode} 색상 · {bits}비트 - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 드래그하여 자르기 상자 만들기 · 안쪽을 드래그하여 이동 · 가장자리로 크기 조절({ratio} 비율, {centre} 중심) · 그리는 중 Space로 이동 · 화살표로 미세 이동 · X로 방향 전환 · {commit} 적용 · Esc 취소 + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 드래그하여 자르기 상자 만들기 · 안쪽을 드래그하여 이동 · 가장자리로 크기 조절({ratio} 비율, {centre} 중심) · 그리는 중 Space로 이동 · 화살표로 미세 이동 · X로 방향 전환 · {commit} 적용 · Esc 취소 Appearance Settings… 화면 설정… Add to favorites 즐겨찾기에 추가 Remove from favorites 즐겨찾기에서 제거 @@ -3518,7 +3517,7 @@ curves Smooth 매끄럽게 Auto Add/Delete 자동 추가/삭제 Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 인쇄 설정에서도 이미지 반전을 켜지 마세요. 두 번 반전하면 원래대로 돌아갑니다. Print Settings… 인쇄 설정… - Remember to turn off the printer's own colour management in Print Settings… 인쇄 설정에서 프린터 자체의 색상 관리를 끄세요… + Remember to turn off the printer's own color management in Print Settings… 인쇄 설정에서 프린터 자체의 색상 관리를 끄세요… Sent to {printer} {printer}(으)로 전송됨 set in Print Settings… 인쇄 설정에서 지정… ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 @@ -3658,12 +3657,12 @@ curves Smooth 매끄럽게 Decrease Brush Hardness 브러시 경도 줄이기 Increase Brush Hardness 브러시 경도 늘리기 Demosaic 디모자이크 - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. 카메라 컬러 필터 모자이크를 채우는 방법입니다. 파일을 열 때 적용되며, 미리 보기는 파일을 연 방식으로 표시됩니다. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. 카메라 컬러 필터 모자이크를 채우는 방법입니다. 파일을 열 때 적용되며, 미리 보기는 파일을 연 방식으로 표시됩니다. AHD (adaptive homogeneity) AHD (적응형 균질성) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: 가장 깨끗한 가장자리와 가장 적은 색 번짐, 가장 느림. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. 기울기 보정 보간: 선명하고 빠르지만 미세한 디테일에 약간의 색 번짐이 있음. - The fastest and the softest, with colour fringing on fine detail. 가장 빠르고 가장 부드러우며, 미세한 디테일에 색 번짐이 있음. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: 가장 깨끗한 가장자리와 가장 적은 색 번짐, 가장 느림. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. 기울기 보정 보간: 선명하고 빠르지만 미세한 디테일에 약간의 색 번짐이 있음. + The fastest and the softest, with color fringing on fine detail. 가장 빠르고 가장 부드러우며, 미세한 디테일에 색 번짐이 있음. “{name}” already exists. Replace it? “{name}”이(가) 이미 있습니다. 대치하시겠습니까? The name in the save dialog was “{name}”. 저장 대화상자에 입력한 이름: “{name}” Previous Brush 이전 브러시 @@ -4178,6 +4177,22 @@ document Orientation 방향 layers Fill 칠 layers Fill: 칠: shape Appearance 화면 모양 +# Move tool options bar (#11381) + Align top edges 위쪽 가장자리 정렬 + Align vertical centers 세로 중심 정렬 + Align bottom edges 아래쪽 가장자리 정렬 + Distribute vertically 세로로 분포 + Distribute horizontally 가로로 분포 + Show layer bounds on hover 마우스를 올리면 레이어 경계 표시 + Expand layer group on click 클릭하면 레이어 그룹 펼치기 + Show hover bounds from Layers 레이어 패널에서 마우스를 올릴 때 경계 표시 +# Artboard tool options bar (#11385) + Distribute Widths 너비 분포 + Distribute Heights 높이 분포 + Auto-nest Layers 레이어 자동 중첩 + Auto-size Canvas 캔버스 크기 자동 조정 + Keep Relative Position During Layer Reordering 레이어 순서 변경 시 상대 위치 유지 + Shrinkwrap Canvas on Save 저장 시 캔버스를 내용에 맞게 축소 # JPEG Options: the size the file will have (#7843) Estimated file size 예상 파일 크기 diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv index e91fa3d0d4..83643360f3 100644 --- a/crates/ui-egui/src/i18n/nb.tsv +++ b/crates/ui-egui/src/i18n/nb.tsv @@ -111,7 +111,6 @@ Export As… Eksporter som… Export Eksporter Export… Eksporter… - Quick Export As PNG Hurtigeksport som PNG Quick Export as PNG Hurtigeksport som PNG Place Embedded… Plasser innebygd… Place Linked… Plasser koblet… @@ -315,7 +314,6 @@ All Alle Deselect Opphev utvalg Reselect Velg på nytt - Inverse Selection Inverter utvalget Inverse Inverter Color Range… Fargeområde… Select and Mask… Velg og masker… @@ -606,8 +604,8 @@ Background Bakgrunn Set foreground color Angi forgrunnsfarge Set background color Angi bakgrunnsfarge - Swap colours (X) Bytt farger (X) - Default colours (D) Standardfarger (D) + Switch Foreground and Background Colors (X) Bytt forgrunns- og bakgrunnsfarge (X) + Default Foreground and Background Colors (D) Standard forgrunns- og bakgrunnsfarge (D) Brush Tool Options Alternativer for penselverktøy Opacity Dekkevne Flow Flyt @@ -1614,7 +1612,7 @@ Revert “{name}” to the last saved version? Your changes will be lost. Tilbakestille «{name}» til sist lagrede versjon? Endringene dine går tapt. {key} to subtract {key} for å trekke fra ↑↓ navigate {key} run esc close ↑↓ naviger {key} kjør esc lukk - Click to restore the current colour Klikk for å gjenopprette gjeldende farge + Click to restore the current color Klikk for å gjenopprette gjeldende farge Click with the Note tool to add a note. Klikk med notatverktøyet for å legge til et notat. Drag a rectangle around the object Dra et rektangel rundt objektet Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Dra på bildet for å legge til en begrensning. Shift for vannrett/loddrett. Høyreklikk på en begrensning for å endre eller slette den. @@ -1696,10 +1694,10 @@ Drag to move the active layer Dra for å flytte det aktive laget Drag to pan · hold Space with any tool Dra for å panorere · hold mellomrom med et hvilket som helst verktøy Drag to draw a gradient Dra for å tegne en gradient - Click to fill similar colours Klikk for å fylle lignende farger + Click to fill similar colors Klikk for å fylle lignende farger Click to add text Klikk for å legge til tekst Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Dra (lasso) eller klikk punkter (polygon) · {add} legg til · {sub} trekk fra - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Dra en beskjæringsramme · dra innenfor for å flytte · kantene endrer størrelse ({ratio} forhold, {centre} midtpunkt) · mellomrom flytter under tegning · piltaster forskyver · X bytter retning · {commit} bekrefter · Esc avbryter + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Dra en beskjæringsramme · dra innenfor for å flytte · kantene endrer størrelse ({ratio} forhold, {centre} midtpunkt) · mellomrom flytter under tegning · piltaster forskyver · X bytter retning · {commit} bekrefter · Esc avbryter {mode} Color · {bits} bit {mode}-farge · {bits} biter Drag to move the layer Dra for å flytte laget Fit Screen Tilpass til skjerm @@ -1731,7 +1729,7 @@ Appearance Utseende Text Position: Tekstplassering: Text color Tekstfarge - Uses the foreground and background colours. Bruker forgrunns- og bakgrunnsfargene. + Uses the foreground and background colors. Bruker forgrunns- og bakgrunnsfargene. Answer the unsaved-changes prompt first Svar først på spørsmålet om ulagrede endringer Unsaved changes Ulagrede endringer Don't Save Ikke lagre @@ -1751,7 +1749,7 @@ name navn new ny Go to Layer Gå til lag - Open a document to select a colour range. Åpne et dokument for å velge et fargeområde. + Open a document to select a color range. Åpne et dokument for å velge et fargeområde. Saved Lagret Reveal in Finder Vis i Finder Show in Explorer Vis i Utforsker @@ -1929,8 +1927,8 @@ Character Styles Panel Tegnstilpanel Clear Canvas Guides Fjern lerrethjelpelinjer Clear Selected Artboard Guides Fjern hjelpelinjer på valgt tegneflate - Color Blindness — Deuteranopia-type Fargeblindhet: deuteranopi-type - Color Blindness — Protanopia-type Fargeblindhet: protanopi-type + Color Blindness - Deuteranopia-type Fargeblindhet: deuteranopi-type + Color Blindness - Protanopia-type Fargeblindhet: protanopi-type Color Table… Fargetabell… Combine Shapes Kombiner former Contract… Trekk sammen… @@ -2104,7 +2102,7 @@ Canvas Lerret Capture Opptak Center Crop Marks Sentrerte beskjæringsmerker - Centre the gradient (offset 0, 0) Sentrer gradienten (forskyvning 0, 0) + Center the gradient (offset 0, 0) Sentrer gradienten (forskyvning 0, 0) Change Screen Mode (F) Bytt skjermmodus (F) Change To: Endre til: Clear All Fjern alle @@ -2256,7 +2254,7 @@ Roughness Ruhet Roundness Rundhet Rulers & Grids Linjaler og rutenett - Sample: foreground colour Prøve: forgrunnsfarge + Sample: foreground color Prøve: forgrunnsfarge Sampling: Background Swatch Prøvetaking: bakgrunnsfargeprøve Sampling: Continuous Prøvetaking: kontinuerlig Sampling: Once Prøvetaking: én gang @@ -2529,7 +2527,7 @@ Alt-click to define a source point to clone from Alt-klikk for å angi et kildepunkt å klone fra No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Ingen bane å lage et utvalg fra: tegn en med pennverktøyet eller velg en i banepanelet. Cancel opening Avbryt åpning - Cancelled opening {name} Avbrøt åpning av {name} + Canceled opening {name} Avbrøt åpning av {name} Damaged Photoshop document Skadet Photoshop-dokument The document “{name}” may be damaged. Dokumentet «{name}» kan være skadet. Some layers, pixels or masks could not be read. Do you want to continue opening it? Noen lag, piksler eller masker kunne ikke leses. Vil du fortsette å åpne det? @@ -2539,7 +2537,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokumentet «{name}» har en innebygd fargeprofil som ikke samsvarer med gjeldende {mode}-arbeidsfargerom. Working: {working} Arbeidsfargerom: {working} Developing {name} Fremkaller {name} - Cancelled {label} Avbrøt {label} + Canceled {label} Avbrøt {label} Esc to cancel Esc for å avbryte Opened {name} Åpnet {name} Opening {name} Åpner {name} @@ -2547,7 +2545,7 @@ Saving {name} Lagrer {name} Saving {percent} Lagrer {percent} A save to {name} is still running; try again when it finishes En lagring til {name} pågår fortsatt. Prøv igjen når den er ferdig - {label} is writing the file and can no longer be cancelled {label} skriver filen og kan ikke lenger avbrytes + {label} is writing the file and can no longer be canceled {label} skriver filen og kan ikke lenger avbrytes Opening {name}… Åpner {name}… Opening… Åpner… Reading… Leser… @@ -2644,7 +2642,7 @@ cameraRaw Roughness Ruhet Discard Layers and Save a Copy Forkast lag og lagre en kopi Don't show again Ikke vis igjen Save failed: {error} Lagring mislyktes: {error} - Save cancelled Lagring avbrutt + Save canceled Lagring avbrutt Couldn't place {name}: {error} Kunne ikke plassere {name}: {error} Magnetic Lasso Tool Magnetlasso Frequency Frekvens @@ -2788,7 +2786,7 @@ fontWeight Italic Kursiv Impressionist Impresjonistisk Rotate View Tool Roter visningverktøy Reset View Tilbakestill visning - Drag around the centre to rotate the view · Shift constrains to 15° Dra rundt midtpunktet for å rotere visningen · Shift begrenser til 15° + Drag around the center to rotate the view · Shift constrains to 15° Dra rundt midtpunktet for å rotere visningen · Shift begrenser til 15° # Painting symmetry presets. Dual Axis Dobbel akse @@ -2808,11 +2806,11 @@ fontWeight Italic Kursiv All Layers No Adjustments Alle lag uten justeringer Current & Below No Adjustments Gjeldende og under uten justeringer Show Sampling Ring Vis prøvetakingsring - Click to sample the foreground colour · {key}-click for background Klikk for å hente forgrunnsfargen · {key}-klikk for bakgrunn + Click to sample the foreground color · {key}-click for background Klikk for å hente forgrunnsfargen · {key}-klikk for bakgrunn # Color Picker warnings - Out of gamut for printing: click for the nearest printable colour Utenfor fargeomfanget for utskrift: klikk for nærmeste utskrivbare farge - Not a web colour: click for the nearest web colour Ikke en webfarge: klikk for nærmeste webfarge + Out of gamut for printing: click for the nearest printable color Utenfor fargeomfanget for utskrift: klikk for nærmeste utskrivbare farge + Not a web color: click for the nearest web color Ikke en webfarge: klikk for nærmeste webfarge Color to Alpha… Farge til alfa… Transparency Threshold Gjennomsiktighetsterskel Opacity Threshold Dekkevneterskel @@ -3230,7 +3228,7 @@ curves Smooth Jevn ut # Native Windows printing qualification Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Ikke kryss også av for Speilvend bilde i Utskriftsinnstillinger…: de to vendingene opphever hverandre. Print Settings… Utskriftsinnstillinger… - Remember to turn off the printer's own colour management in Print Settings… Husk å slå av skriverens egen fargestyring i Utskriftsinnstillinger… + Remember to turn off the printer's own color management in Print Settings… Husk å slå av skriverens egen fargestyring i Utskriftsinnstillinger… Sent to {printer} Sendt til {printer} set in Print Settings… angitt i Utskriftsinnstillinger… ICO is limited to 256 × 256 pixels ICO er begrenset til 256 × 256 piksler @@ -3894,12 +3892,12 @@ curves Smooth Jevn ut In White I hvitt Increase Brush Hardness Øk penselhardhet Demosaic Demosaikk - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hvordan kameraets fargefiltermosaikk fylles ut. Det brukes når filen åpnes. Forhåndsvisningen viser metoden den ble åpnet med. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hvordan kameraets fargefiltermosaikk fylles ut. Det brukes når filen åpnes. Forhåndsvisningen viser metoden den ble åpnet med. AHD (adaptive homogeneity) AHD (adaptiv homogenitet) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: de reneste kantene og minst fargefrynsing, den tregeste. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradientkorrigert interpolering: skarp og rask, med noe fargefrynsing på fine detaljer. - The fastest and the softest, with colour fringing on fine detail. Den raskeste og mykeste, med fargefrynsing på fine detaljer. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: de reneste kantene og minst fargefrynsing, den tregeste. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradientkorrigert interpolering: skarp og rask, med noe fargefrynsing på fine detaljer. + The fastest and the softest, with color fringing on fine detail. Den raskeste og mykeste, med fargefrynsing på fine detaljer. “{name}” already exists. Replace it? «{name}» finnes allerede. Erstatte den? The name in the save dialog was “{name}”. Navnet i lagringsdialogen var «{name}». Move Up Flytt opp @@ -4550,7 +4548,6 @@ curves Smooth Jevn ut Use File › Open to open an image. Bruk Fil › Åpne for å åpne et bilde. Use Selection In Source Bruk utvalg i kilde Use Selection In Target Bruk utvalg i mål - Uses the foreground and background colors. Bruker forgrunns- og bakgrunnsfargene. Vanishing Point Fluktpunkt Variable Data Sets Variable datasett Vector Mask Hides Effects Vektormaske skjuler effekter @@ -4760,8 +4757,8 @@ cameraRaw Camera Raw ({name}) Camera Raw ({name}) cameraRaw Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) cameraRaw Camera Raw isn't open Camera Raw er ikke åpen cameraRaw Cancel Avbryt -cameraRaw Cancelled opening {name} Avbrøt åpning av {name} -cameraRaw Cancelled {label} Avbrøt {label} +cameraRaw Canceled opening {name} Avbrøt åpning av {name} +cameraRaw Canceled {label} Avbrøt {label} cameraRaw Color Priority Fargeprioritet cameraRaw Developing {name} Fremkaller {name} cameraRaw Full-resolution preview unavailable Forhåndsvisning i full oppløsning er ikke tilgjengelig @@ -4816,3 +4813,19 @@ cameraRaw White Balance: As Shot Hvitbalanse: som fotografert Pick a different document for each channel. Velg et annet dokument for hver kanal. A picked document is no longer open. Et av de valgte dokumentene er ikke lenger åpent. A picked document is no longer a grayscale document of the same size. Et av de valgte dokumentene er ikke lenger et dokument i gråtoner av samme størrelse. +# Move tool options bar (#11381) + Align top edges Juster øverste kanter + Align vertical centers Juster loddrette midtpunkter + Align bottom edges Juster nederste kanter + Distribute vertically Fordel loddrett + Distribute horizontally Fordel vannrett + Show layer bounds on hover Vis lagets grenser ved hovring + Expand layer group on click Utvid lagergruppe ved klikk + Show hover bounds from Layers Vis hovringsgrenser fra Lag +# Artboard tool options bar (#11385) + Distribute Widths Fordel bredder + Distribute Heights Fordel høyder + Auto-nest Layers Neste lag automatisk + Auto-size Canvas Endre lerretstørrelse automatisk + Keep Relative Position During Layer Reordering Behold relativ posisjon ved omordning av lag + Shrinkwrap Canvas on Save Krymp lerretet til innholdet ved lagring diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4e70853b6c..e2c6332ed5 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -592,7 +592,6 @@ Deselect Deselecteren Reselect Opnieuw selecteren Inverse Omkeren - Inverse Selection Selectie omkeren Similar Vergelijkbaar Color Range… Kleurbereik… Focus Area… Scherptegebied… @@ -711,8 +710,8 @@ Legacy Macintosh RGB (Gamma 1.8) Verouderde Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internetstandaard RGB (sRGB) Monitor RGB Monitor-RGB - Color Blindness — Protanopia-type Kleurenblindheid — type protanopie - Color Blindness — Deuteranopia-type Kleurenblindheid — type deuteranopie + Color Blindness - Protanopia-type Kleurenblindheid - type protanopie + Color Blindness - Deuteranopia-type Kleurenblindheid - type deuteranopie Zoom In Inzoomen Zoom Out Uitzoomen Fit on Screen Passend in scherm @@ -1023,7 +1022,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Klik om een punt toe te voegen · sleep weg, {key}-klik of Delete om te verwijderen Click to apply, {key}-click to clear overrides, double-click for Style Options Klik om toe te passen, {key}-klik om overschrijvingen te wissen, dubbelklik voor stijlopties Click to edit the gradient Klik om het verloop te bewerken - Click to restore the current colour Klik om de huidige kleur te herstellen + Click to restore the current color Klik om de huidige kleur te herstellen Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Klik om in te zoomen · {key}-klik om uit te zoomen · sleep naar rechts/links om in/uit te zoomen Click with the Note tool to add a note. Klik met het notitiegereedschap om een notitie toe te voegen. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klik: hoek · Slepen: vloeiend · Klik op eerste punt: sluiten · {key} voltooien · Esc annuleren @@ -1108,7 +1107,7 @@ Darks Donkere tinten Data Sets Gegevenssets Default Standaard - Default colours (D) Standaardkleuren (D) + Default Foreground and Background Colors (D) Standaard voorgrond- en achtergrondkleur (D) Default printer Standaardprinter Default restored. Standaard hersteld. Define Definiëren @@ -1391,7 +1390,7 @@ Opacity Jitter Dekkingsvariatie Opacity: Dekking: Open a document to define variables. Open een document om variabelen te definiëren. - Open a document to select a colour range. Open een document om een kleurbereik te selecteren. + Open a document to select a color range. Open een document om een kleurbereik te selecteren. Open a document to use the timeline. Open een document om de tijdlijn te gebruiken. Optical Optisch Optimized Geoptimaliseerd @@ -1467,7 +1466,6 @@ Purity Zuiverheid Quality Kwaliteit Quick Actions Snelle acties - Quick Export As PNG Snel exporteren als PNG Radial Gradient Radiaal verloop Radius Straal Radius: Straal: @@ -1606,7 +1604,7 @@ Subtract from Sample Van monster aftrekken Subtract from selection ({key}) Van selectie aftrekken ({key}) Suggestions: Suggesties: - Swap colours (X) Kleuren omwisselen (X) + Switch Foreground and Background Colors (X) Voorgrond- en achtergrondkleur omwisselen (X) Swaps height and width Wisselt hoogte en breedte om Switch between free transform and warp modes Wisselen tussen vrije transformatie en verbuigen Switch theme Thema wisselen @@ -1708,7 +1706,7 @@ Choke Inkrimpen Classic Klassiek Click to add text Klik om tekst toe te voegen - Click to fill similar colours Klik om vergelijkbare kleuren te vullen + Click to fill similar colors Klik om vergelijkbare kleuren te vullen Clone Stamp Tool Kloonstempelgereedschap Color Burn Kleur doordrukken Color Dodge Kleur tegenhouden @@ -1868,7 +1866,7 @@ Rectangular Marquee Tool Rechthoekig selectiekader Reds Roodtinten Reflected Gespiegeld - Sample: foreground colour Monster: voorgrondkleur + Sample: foreground color Monster: voorgrondkleur Sampled Colors Bemonsterde kleuren Satin Satijn Save Pixel Aspect Ratio Pixelverhouding opslaan @@ -1907,7 +1905,6 @@ Transfer Overdracht Triangle Tool Driehoekgereedschap Unsaved changes Niet-opgeslagen wijzigingen - Uses the foreground and background colours. Gebruikt de voorgrond- en achtergrondkleur. Web Web Web Large Web groot Web Minimum Web minimum @@ -1944,6 +1941,7 @@ Allow scripts to connect Scripts toestaan verbinding te maken Always Altijd Always create smart objects when placing Bij plaatsen altijd slimme objecten maken + Skip transform when placing Transformatie overslaan bij plaatsen Animated zoom Geanimeerd zoomen Apply auto tone Automatische tooncorrectie toepassen Ask Vragen @@ -2177,7 +2175,7 @@ Graphics Grafisch Reset GPU Backend GPU-backend herstellen Applies at next launch. Wordt toegepast bij de volgende start. - Click to sample the foreground colour · {key}-click for background Klik om de voorgrondkleur te bemonsteren · {key}-klik voor achtergrond + Click to sample the foreground color · {key}-click for background Klik om de voorgrondkleur te bemonsteren · {key}-klik voor achtergrond {key}-click to set the source {key}-klik om de bron in te stellen {key} to subtract {key} om af te trekken Clone source {n} ({key}-click with Clone Stamp to set) Kloonbron {n} ({key}-klik met kloonstempel om in te stellen) @@ -2236,7 +2234,7 @@ Gradient Options Verloopopties Align with layer Uitlijnen met laag Reset Alignment Uitlijning herstellen - Centre the gradient (offset 0, 0) Het verloop centreren (verschuiving 0, 0) + Center the gradient (offset 0, 0) Het verloop centreren (verschuiving 0, 0) Gradient Editor Verloopeditor Gradient picker Verloopkiezer Gradient stops Verloopstops @@ -2270,7 +2268,7 @@ Alt-click to define a source point to clone from Alt-klik om een bronpunt te definiëren om van te klonen No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Geen pad om een selectie van te maken: teken er een met het pengereedschap of selecteer er een in het paneel Paden. Cancel opening Openen annuleren - Cancelled opening {name} Openen van {name} geannuleerd + Canceled opening {name} Openen van {name} geannuleerd Damaged Photoshop document Beschadigd Photoshop-document The document “{name}” may be damaged. Het document ‘{name}’ is mogelijk beschadigd. Some layers, pixels or masks could not be read. Do you want to continue opening it? Sommige lagen, pixels of maskers konden niet worden gelezen. Wilt u doorgaan met openen? @@ -2279,7 +2277,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Het document “{name}” heeft een ingesloten kleurprofiel dat niet overeenkomt met de huidige {mode}-werkruimte. Working: {working} Werkruimte: {working} Developing {name} {name} wordt ontwikkeld - Cancelled {label} {label} geannuleerd + Canceled {label} {label} geannuleerd Esc to cancel Esc om te annuleren Opened {name} {name} geopend Opening {name} {name} openen @@ -2287,7 +2285,7 @@ Saving {name} {name} opslaan Saving {percent} Opslaan {percent} A save to {name} is still running; try again when it finishes Er wordt nog opgeslagen naar {name}; probeer het opnieuw zodra dat klaar is - {label} is writing the file and can no longer be cancelled {label} schrijft het bestand en kan niet meer worden geannuleerd + {label} is writing the file and can no longer be canceled {label} schrijft het bestand en kan niet meer worden geannuleerd Opening {name}… {name} openen… Opening… Openen… Reading… Lezen… @@ -2349,7 +2347,7 @@ Pixel Pixel Adjustment Aanpassing Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Slepen (lasso) of punten klikken (veelhoek) · {add} toevoegen · {sub} aftrekken - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Sleep een bijsnijkader · sleep binnenin om te verplaatsen · randen wijzigen formaat ({ratio} verhouding, {centre} midden) · Spatie verplaatst tijdens tekenen · pijltjes verschuiven · X wisselt oriëntatie · {commit} past toe · Esc annuleert + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Sleep een bijsnijkader · sleep binnenin om te verplaatsen · randen wijzigen formaat ({ratio} verhouding, {centre} midden) · Spatie verplaatst tijdens tekenen · pijltjes verschuiven · X wisselt oriëntatie · {commit} past toe · Esc annuleert {mode} Color · {bits} bit {mode}-kleur · {bits} bit Scrubby Zoom Sleepzoom Auto Erase Automatisch gummen @@ -2443,7 +2441,7 @@ Discard Layers and Save a Copy Lagen negeren en kopie opslaan Don't show again Niet meer tonen Save failed: {error} Opslaan mislukt: {error} - Save cancelled Opslaan geannuleerd + Save canceled Opslaan geannuleerd Style {name} saved Stijl {name} opgeslagen Make Default Als standaard instellen Reset to Default Terugzetten naar standaard @@ -2579,7 +2577,7 @@ fontWeight Italic Cursief Rotate View Weergave roteren Rotate View Tool Weergave-roteergereedschap Reset View Weergave herstellen - Drag around the centre to rotate the view · Shift constrains to 15° Sleep rond het midden om de weergave te roteren · Shift beperkt tot 15° + Drag around the center to rotate the view · Shift constrains to 15° Sleep rond het midden om de weergave te roteren · Shift beperkt tot 15° @id select.all Alles selecteren @id edit.stroke Omlijnen… @id edit.transform.scale Schalen @@ -3753,8 +3751,8 @@ cameraRaw Whites Witten @id filter.sharpen.sharpen Verscherpen Good Goed Best Beste - Out of gamut for printing: click for the nearest printable colour Buiten afdrukbereik: klik voor de dichtstbijzijnde afdrukbare kleur - Not a web colour: click for the nearest web colour Geen webkleur: klik voor de dichtstbijzijnde webkleur + Out of gamut for printing: click for the nearest printable color Buiten afdrukbereik: klik voor de dichtstbijzijnde afdrukbare kleur + Not a web color: click for the nearest web color Geen webkleur: klik voor de dichtstbijzijnde webkleur Adjustment Properties Eigenschappen aanpassing Brush Stroke Penseelstreek Default Foreground and Background Colors Standaard voorgrond- en achtergrondkleur @@ -4071,7 +4069,7 @@ curves Smooth Vloeiend maken Auto Add/Delete Automatisch toevoegen/verwijderen Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Schakel niet ook Spiegelbeeld in bij de afdrukinstellingen: de twee spiegelingen heffen elkaar op. Print Settings… Afdrukinstellingen… - Remember to turn off the printer's own colour management in Print Settings… Vergeet niet het eigen kleurbeheer van de printer uit te schakelen in de afdrukinstellingen… + Remember to turn off the printer's own color management in Print Settings… Vergeet niet het eigen kleurbeheer van de printer uit te schakelen in de afdrukinstellingen… 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 @@ -4201,12 +4199,12 @@ curves Smooth Vloeiend maken Decrease Brush Hardness Penseelhardheid verlagen Increase Brush Hardness Penseelhardheid verhogen Demosaic Demosaicing - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hoe het kleurfiltermozaïek van de camera wordt ingevuld. Wordt toegepast bij het openen van het bestand; de voorvertoning toont de methode waarmee het is geopend. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hoe het kleurfiltermozaïek van de camera wordt ingevuld. Wordt toegepast bij het openen van het bestand; de voorvertoning toont de methode waarmee het is geopend. AHD (adaptive homogeneity) AHD (adaptieve homogeniteit) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: de schoonste randen en de minste kleurranden, het traagst. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradiëntgecorrigeerde interpolatie: scherp en snel, met wat kleurranden in fijne details. - The fastest and the softest, with colour fringing on fine detail. Het snelst en het zachtst, met kleurranden in fijne details. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: de schoonste randen en de minste kleurranden, het traagst. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradiëntgecorrigeerde interpolatie: scherp en snel, met wat kleurranden in fijne details. + The fastest and the softest, with color fringing on fine detail. Het snelst en het zachtst, met kleurranden in fijne details. “{name}” already exists. Replace it? “{name}” bestaat al. Vervangen? The name in the save dialog was “{name}”. De naam in het venster Opslaan was “{name}”. Previous Brush Vorig penseel @@ -4360,6 +4358,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Kies voor elk kanaal een ander document. A picked document is no longer open. Een gekozen document is niet meer geopend. A picked document is no longer a grayscale document of the same size. Een gekozen document is geen grijswaardendocument van hetzelfde formaat meer. +# Move tool options bar (#11381) + Align top edges Bovenranden uitlijnen + Align vertical centers Verticale middens uitlijnen + Align bottom edges Onderranden uitlijnen + Distribute vertically Verticaal verdelen + Distribute horizontally Horizontaal verdelen + Show layer bounds on hover Laaggrenzen tonen bij aanwijzen + Expand layer group on click Laaggroep uitvouwen bij klikken + Show hover bounds from Layers Aanwijsgrenzen tonen vanuit Lagen +# Artboard tool options bar (#11385) + Distribute Widths Breedtes verdelen + Distribute Heights Hoogtes verdelen + Auto-nest Layers Lagen automatisch nesten + Auto-size Canvas Canvasgrootte automatisch aanpassen + Keep Relative Position During Layer Reordering Relatieve positie behouden bij het wijzigen van de laagvolgorde + Shrinkwrap Canvas on Save Canvas bij opslaan verkleinen tot de inhoud # JPEG Options: the size the file will have (#7843) Estimated file size Geschatte bestandsgrootte diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8e4af95c04..8743dcd8f7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -635,7 +635,6 @@ Deselect Odznacz Reselect Zaznacz ponownie Inverse Odwróć - Inverse Selection Odwróć zaznaczenie Similar Podobne Color Range… Zakres kolorów… Focus Area… Obszar ostrości… @@ -756,8 +755,8 @@ Legacy Macintosh RGB (Gamma 1.8) Starszy Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) Standardowy RGB dla Internetu (sRGB) Monitor RGB RGB monitora - Color Blindness — Protanopia-type Ślepota barw — typ protanopii - Color Blindness — Deuteranopia-type Ślepota barw — typ deuteranopii + Color Blindness - Protanopia-type Ślepota barw - typ protanopii + Color Blindness - Deuteranopia-type Ślepota barw - typ deuteranopii Zoom In Powiększ Zoom Out Pomniejsz Fit on Screen Dopasuj do ekranu @@ -1091,7 +1090,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Kliknij, aby dodać punkt · przeciągnij poza obszar, kliknij z {key} lub naciśnij Delete, aby usunąć Click to apply, {key}-click to clear overrides, double-click for Style Options Kliknij, aby zastosować, kliknij z {key}, aby wyczyścić zastąpienia, kliknij dwukrotnie, aby otworzyć opcje stylu Click to edit the gradient Kliknij, aby edytować gradient - Click to restore the current colour Kliknij, aby przywrócić bieżący kolor + Click to restore the current color Kliknij, aby przywrócić bieżący kolor Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Kliknij, aby powiększyć · kliknij z {key}, aby pomniejszyć · przeciągnij w prawo/lewo, aby powiększyć/pomniejszyć Click with the Note tool to add a note. Kliknij narzędziem Notatka, aby dodać notatkę. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klik: narożnik · Przeciągnięcie: gładki · Klik w pierwszy punkt: zamknij · {key} zakończ · Esc anuluj @@ -1176,7 +1175,7 @@ Darks Ciemne Data Sets Zestawy danych Default Domyślne - Default colours (D) Kolory domyślne (D) + Default Foreground and Background Colors (D) Kolory domyślne (D) Default printer Drukarka domyślna Default restored. Przywrócono wartość domyślną. Define Zdefiniuj @@ -1455,7 +1454,7 @@ Opacity Jitter Rozrzut krycia Opacity: Krycie: Open a document to define variables. Otwórz dokument, aby zdefiniować zmienne. - Open a document to select a colour range. Otwórz dokument, aby wybrać zakres kolorów. + Open a document to select a color range. Otwórz dokument, aby wybrać zakres kolorów. Open a document to use the timeline. Otwórz dokument, aby użyć osi czasu. Optical Optyczne Optimized Zoptymalizowany @@ -1531,7 +1530,6 @@ Purity Czystość Quality Jakość Quick Actions Szybkie akcje - Quick Export As PNG Szybki eksport jako PNG Radial Gradient Gradient promienisty Radius Promień Radius: Promień: @@ -1671,7 +1669,7 @@ Subtract from Sample Odejmij od próbki Subtract from selection ({key}) Odejmij od zaznaczenia ({key}) Suggestions: Sugestie: - Swap colours (X) Zamień kolory (X) + Switch Foreground and Background Colors (X) Zamień kolory (X) Swaps height and width Zamienia wysokość i szerokość Switch between free transform and warp modes Przełącz między trybami dowolnego przekształcania i wypaczenia Switch theme Przełącz motyw @@ -1772,7 +1770,7 @@ Choke Zwężenie Classic Klasyczny Click to add text Kliknij, aby dodać tekst - Click to fill similar colours Kliknij, aby wypełnić podobne kolory + Click to fill similar colors Kliknij, aby wypełnić podobne kolory Clone Stamp Tool Narzędzie Pieczątka Color Burn Wypalanie koloru Color Dodge Rozjaśnianie koloru @@ -1933,7 +1931,7 @@ Rectangular Marquee Tool Narzędzie Zaznaczenie prostokątne Reds Czerwone Reflected Odbity - Sample: foreground colour Próbka: kolor pierwszego planu + Sample: foreground color Próbka: kolor pierwszego planu Sampled Colors Próbkowane kolory Satin Satyna Save Pixel Aspect Ratio Zapisz proporcje pikseli @@ -1972,7 +1970,6 @@ Transfer Transfer Triangle Tool Narzędzie Trójkąt Unsaved changes Niezapisane zmiany - Uses the foreground and background colours. Używa kolorów pierwszego planu i tła. Web Internet Web Large Internet — duży Web Minimum Internet — minimalny @@ -2009,6 +2006,7 @@ Allow scripts to connect Zezwalaj skryptom na połączenie Always Zawsze Always create smart objects when placing Zawsze twórz obiekty inteligentne podczas umieszczania + Skip transform when placing Pomijaj przekształcanie podczas umieszczania Animated zoom Animowane powiększanie Apply auto tone Zastosuj automatyczne tony Ask Pytaj @@ -2241,7 +2239,7 @@ Graphics Grafika Reset GPU Backend Resetuj backend GPU Applies at next launch. Zadziała po następnym uruchomieniu. - Click to sample the foreground colour · {key}-click for background Kliknij, aby pobrać kolor pierwszego planu · kliknij z {key}, aby pobrać kolor tła + Click to sample the foreground color · {key}-click for background Kliknij, aby pobrać kolor pierwszego planu · kliknij z {key}, aby pobrać kolor tła {key}-click to set the source Kliknij z {key}, aby ustawić źródło {key} to subtract {key}, aby odjąć Clone source {n} ({key}-click with Clone Stamp to set) Źródło klonowania {n} (kliknij z {key} Pieczątką, aby ustawić) @@ -2294,7 +2292,7 @@ Gradient Options Opcje gradientu Align with layer Wyrównaj do warstwy Reset Alignment Resetuj wyrównanie - Centre the gradient (offset 0, 0) Wyśrodkuj gradient (przesunięcie 0, 0) + Center the gradient (offset 0, 0) Wyśrodkuj gradient (przesunięcie 0, 0) Gradient Editor Edytor gradientu Gradient picker Wybór gradientu Gradient stops Punkty gradientu @@ -2328,7 +2326,7 @@ Alt-click to define a source point to clone from Kliknij z Alt, aby zdefiniować punkt źródłowy klonowania No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Brak ścieżki, z której można utworzyć zaznaczenie: narysuj ją narzędziem Pióro lub wybierz w panelu Ścieżki. Cancel opening Anuluj otwieranie - Cancelled opening {name} Anulowano otwieranie {name} + Canceled opening {name} Anulowano otwieranie {name} Damaged Photoshop document Uszkodzony dokument programu Photoshop The document “{name}” may be damaged. Dokument „{name}” może być uszkodzony. Some layers, pixels or masks could not be read. Do you want to continue opening it? Nie udało się odczytać niektórych warstw, pikseli lub masek. Czy kontynuować otwieranie? @@ -2337,7 +2335,7 @@ The document “{name}” does not have an embedded {mode} profile. Dokument „{name}” nie ma osadzonego profilu {mode}. The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}” ma osadzony profil kolorów, który nie pasuje do bieżącej przestrzeni roboczej {mode}. Working: {working} Przestrzeń robocza: {working} - Cancelled {label} Anulowano: {label} + Canceled {label} Anulowano: {label} Esc to cancel Esc, aby anulować Opened {name} Otworzono: {name} Opening {name} Otwieranie {name} @@ -2345,7 +2343,7 @@ Saving {name} Zapisywanie {name} Saving {percent} Zapisywanie {percent} A save to {name} is still running; try again when it finishes Zapisywanie do {name} wciąż trwa; spróbuj ponownie, gdy się zakończy - {label} is writing the file and can no longer be cancelled {label} zapisuje plik i nie można już tego anulować + {label} is writing the file and can no longer be canceled {label} zapisuje plik i nie można już tego anulować Opening {name}… Otwieranie {name}… Opening… Otwieranie… Reading… Odczyt… @@ -2713,7 +2711,7 @@ Pixel Piksel Adjustment Korekta Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Przeciągaj (lasso) lub klikaj punkty (wielokątne) · {add} dodaj · {sub} odejmij - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Przeciągnij ramkę przycinania · przeciągnij wewnątrz, aby przesunąć · krawędzie zmieniają rozmiar ({ratio} proporcje, {centre} od środka) · Spacja przesuwa podczas rysowania · strzałki przesuwają · X zamienia orientację · {commit} zatwierdza · Esc anuluje + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Przeciągnij ramkę przycinania · przeciągnij wewnątrz, aby przesunąć · krawędzie zmieniają rozmiar ({ratio} proporcje, {centre} od środka) · Spacja przesuwa podczas rysowania · strzałki przesuwają · X zamienia orientację · {commit} zatwierdza · Esc anuluje {mode} Color · {bits} bit Kolor {mode} · {bits} bitów Drag to move the layer Przeciągnij, aby przesunąć warstwę Scrubby Zoom Powiększanie przeciąganiem @@ -2906,7 +2904,7 @@ cameraRaw Roughness Chropowatość Discard Layers and Save a Copy Odrzuć warstwy i zapisz kopię Don't show again Nie pokazuj ponownie Save failed: {error} Zapis nie powiódł się: {error} - Save cancelled Anulowano zapis + Save canceled Anulowano zapis Magnetic Lasso Tool Narzędzie Lasso magnetyczne Frequency Częstotliwość Use tablet pressure to change pen width Użyj nacisku tabletu do zmiany szerokości pióra @@ -3623,7 +3621,7 @@ cameraRaw Roughness Chropowatość Impressionist Impresjonistyczny Rotate View Tool Narzędzie Obróć widok Reset View Resetuj widok - Drag around the centre to rotate the view · Shift constrains to 15° Przeciągnij wokół środka, aby obrócić widok · Shift ogranicza do 15° + Drag around the center to rotate the view · Shift constrains to 15° Przeciągnij wokół środka, aby obrócić widok · Shift ogranicza do 15° Dual Axis Podwójna oś Diagonal Ukośna Transform Symmetry Przekształć symetrię @@ -3638,8 +3636,8 @@ cameraRaw Roughness Chropowatość All Layers No Adjustments Wszystkie warstwy bez korekt Current & Below No Adjustments Bieżąca i poniżej bez korekt Show Sampling Ring Pokaż pierścień próbkowania - Out of gamut for printing: click for the nearest printable colour Poza gamą druku: kliknij, aby wybrać najbliższy kolor do druku - Not a web colour: click for the nearest web colour To nie jest kolor internetowy: kliknij, aby wybrać najbliższy kolor internetowy + Out of gamut for printing: click for the nearest printable color Poza gamą druku: kliknij, aby wybrać najbliższy kolor do druku + Not a web color: click for the nearest web color To nie jest kolor internetowy: kliknij, aby wybrać najbliższy kolor internetowy Color to Alpha… Kolor na alfę… Transparency Threshold Próg przezroczystości Opacity Threshold Próg krycia @@ -3929,7 +3927,7 @@ curves Smooth Wygładź Auto Add/Delete Automatyczne dodawanie/usuwanie Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nie włączaj też odbicia lustrzanego w ustawieniach druku: oba odbicia wzajemnie się znoszą. Print Settings… Ustawienia druku… - Remember to turn off the printer's own colour management in Print Settings… Pamiętaj o wyłączeniu zarządzania kolorami drukarki w ustawieniach druku… + Remember to turn off the printer's own color management in Print Settings… Pamiętaj o wyłączeniu zarządzania kolorami drukarki w ustawieniach druku… 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 @@ -4060,12 +4058,12 @@ curves Smooth Wygładź Decrease Brush Hardness Zmniejsz twardość pędzla Increase Brush Hardness Zwiększ twardość pędzla Demosaic Demozaikowanie - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Sposób uzupełniania mozaiki filtra barwnego aparatu. Stosowany przy otwieraniu pliku; podgląd pokazuje metodę, z którą plik został otwarty. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Sposób uzupełniania mozaiki filtra barwnego aparatu. Stosowany przy otwieraniu pliku; podgląd pokazuje metodę, z którą plik został otwarty. AHD (adaptive homogeneity) AHD (adaptacyjna jednorodność) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: najczystsze krawędzie i najmniej barwnych obwódek, najwolniejsza. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolacja z korekcją gradientu: ostra i szybka, z niewielkimi barwnymi obwódkami na drobnych szczegółach. - The fastest and the softest, with colour fringing on fine detail. Najszybsza i najmiększa, z barwnymi obwódkami na drobnych szczegółach. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: najczystsze krawędzie i najmniej barwnych obwódek, najwolniejsza. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolacja z korekcją gradientu: ostra i szybka, z niewielkimi barwnymi obwódkami na drobnych szczegółach. + The fastest and the softest, with color fringing on fine detail. Najszybsza i najmiększa, z barwnymi obwódkami na drobnych szczegółach. “{name}” already exists. Replace it? „{name}” już istnieje. Zastąpić? The name in the save dialog was “{name}”. Nazwa w oknie zapisywania: „{name}”. Previous Brush Poprzedni pędzel @@ -4224,6 +4222,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Wybierz inny dokument dla każdego kanału. A picked document is no longer open. Jeden z wybranych dokumentów nie jest już otwarty. A picked document is no longer a grayscale document of the same size. Jeden z wybranych dokumentów nie jest już dokumentem w skali szarości o tym samym rozmiarze. +# Move tool options bar (#11381) + Align top edges Wyrównaj górne krawędzie + Align vertical centers Wyrównaj środki w pionie + Align bottom edges Wyrównaj dolne krawędzie + Distribute vertically Rozmieść w pionie + Distribute horizontally Rozmieść w poziomie + Show layer bounds on hover Pokaż granice warstwy po najechaniu + Expand layer group on click Rozwiń grupę warstw po kliknięciu + Show hover bounds from Layers Pokaż granice po najechaniu z panelu Warstwy +# Artboard tool options bar (#11385) + Distribute Widths Rozmieść szerokości równomiernie + Distribute Heights Rozmieść wysokości równomiernie + Auto-nest Layers Automatycznie zagnieżdżaj warstwy + Auto-size Canvas Automatycznie zmieniaj rozmiar płótna + Keep Relative Position During Layer Reordering Zachowaj położenie względne przy zmianie kolejności warstw + Shrinkwrap Canvas on Save Przytnij płótno do zawartości przy zapisie # JPEG Options: the size the file will have (#7843) Estimated file size Szacowany rozmiar pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9e564e5022..5de8d27aef 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -615,7 +615,6 @@ Deselect Desmarcar Reselect Selecionar novamente Inverse Inverter - Inverse Selection Inverter seleção Similar Semelhante Color Range… Intervalo de cores… Focus Area… Área de foco… @@ -734,8 +733,8 @@ Legacy Macintosh RGB (Gamma 1.8) RGB Macintosh legado (Gamma 1.8) Internet Standard RGB (sRGB) RGB padrão da Internet (sRGB) Monitor RGB RGB do monitor - Color Blindness — Protanopia-type Daltonismo — tipo protanopia - Color Blindness — Deuteranopia-type Daltonismo — tipo deuteranopia + Color Blindness - Protanopia-type Daltonismo - tipo protanopia + Color Blindness - Deuteranopia-type Daltonismo - tipo deuteranopia Zoom In Aumentar zoom Zoom Out Diminuir zoom Fit on Screen Ajustar à tela @@ -1054,7 +1053,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Clique para adicionar um ponto · arraste para fora, {key}-clique ou Delete para remover Click to apply, {key}-click to clear overrides, double-click for Style Options Clique para aplicar, {key}-clique para limpar substituições, clique duplo para Opções de estilo Click to edit the gradient Clique para editar o degradê - Click to restore the current colour Clique para restaurar a cor atual + Click to restore the current color Clique para restaurar a cor atual Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Clique para aumentar o zoom · {key}-clique para diminuir · arraste para a direita/esquerda para aumentar/diminuir Click with the Note tool to add a note. Clique com a ferramenta Anotação para adicionar uma anotação. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Clique: canto · Arrastar: suave · Clique no primeiro ponto: fechar · {key}: concluir · Esc: cancelar @@ -1139,7 +1138,7 @@ Darks Escuros Data Sets Conjuntos de dados Default Padrão - Default colours (D) Cores padrão (D) + Default Foreground and Background Colors (D) Cores padrão de primeiro plano e plano de fundo (D) Default printer Impressora padrão Default restored. Padrão restaurado. Define Definir @@ -1415,7 +1414,7 @@ Opacity Jitter Variação da opacidade Opacity: Opacidade: Open a document to define variables. Abra um documento para definir variáveis. - Open a document to select a colour range. Abra um documento para selecionar um intervalo de cores. + Open a document to select a color range. Abra um documento para selecionar um intervalo de cores. Open a document to use the timeline. Abra um documento para usar a linha do tempo. Optical Óptico Optimized Otimizado @@ -1491,7 +1490,6 @@ Purity Pureza Quality Qualidade Quick Actions Ações rápidas - Quick Export As PNG Exportação rápida como PNG Radial Gradient Degradê radial Radius Raio Radius: Raio: @@ -1632,7 +1630,7 @@ Subtract from Sample Subtrair da amostra Subtract from selection ({key}) Subtrair da seleção ({key}) Suggestions: Sugestões: - Swap colours (X) Trocar cores (X) + Switch Foreground and Background Colors (X) Alternar cores de primeiro plano e plano de fundo (X) Swaps height and width Troca a altura e a largura Switch between free transform and warp modes Alternar entre os modos de transformação livre e deformação Switch theme Alternar tema @@ -1733,7 +1731,7 @@ Choke Contrair Classic Clássico Click to add text Clique para adicionar texto - Click to fill similar colours Clique para preencher cores semelhantes + Click to fill similar colors Clique para preencher cores semelhantes Clone Stamp Tool Ferramenta Carimbo Color Burn Superexposição de cores Color Dodge Subexposição de cores @@ -1893,7 +1891,7 @@ Rectangular Marquee Tool Ferramenta Letreiro retangular Reds Vermelhos Reflected Refletido - Sample: foreground colour Amostra: cor de primeiro plano + Sample: foreground color Amostra: cor de primeiro plano Sampled Colors Cores da amostra Satin Acetinado Save Pixel Aspect Ratio Salvar proporção de pixels @@ -1932,7 +1930,6 @@ Transfer Transferência Triangle Tool Ferramenta Triângulo Unsaved changes Alterações não salvas - Uses the foreground and background colours. Usa as cores de primeiro plano e de fundo. Web Web Web Large Web grande Web Minimum Web mínimo @@ -1967,6 +1964,7 @@ Allow scripts to connect Permitir conexão de scripts Always Sempre Always create smart objects when placing Sempre criar objetos inteligentes ao inserir + Skip transform when placing Ignorar transformação ao inserir Animated zoom Zoom animado Apply auto tone Aplicar tom automático Ask Perguntar @@ -2200,7 +2198,7 @@ Graphics Gráficos Reset GPU Backend Redefinir backend da GPU Applies at next launch. Aplica-se na próxima inicialização. - Click to sample the foreground colour · {key}-click for background Clique para obter a cor de primeiro plano · {key}-clique para a cor de fundo + Click to sample the foreground color · {key}-click for background Clique para obter a cor de primeiro plano · {key}-clique para a cor de fundo {key}-click to set the source {key}-clique para definir a origem {key} to subtract {key} para subtrair Clone source {n} ({key}-click with Clone Stamp to set) Origem da clonagem {n} ({key}-clique com o Carimbo para definir) @@ -2258,7 +2256,7 @@ Gradient Options Opções de degradê Align with layer Alinhar com a camada Reset Alignment Redefinir alinhamento - Centre the gradient (offset 0, 0) Centralizar o degradê (deslocamento 0, 0) + Center the gradient (offset 0, 0) Centralizar o degradê (deslocamento 0, 0) Gradient Editor Editor de degradê Gradient picker Seletor de degradê Gradient stops Paradas do degradê @@ -2292,7 +2290,7 @@ Alt-click to define a source point to clone from Alt-clique para definir um ponto de origem da clonagem No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nenhum demarcador para criar a seleção: desenhe um com a ferramenta Caneta ou selecione um no painel Demarcadores. Cancel opening Cancelar abertura - Cancelled opening {name} Abertura de {name} cancelada + Canceled opening {name} Abertura de {name} cancelada Damaged Photoshop document Documento do Photoshop danificado The document “{name}” may be damaged. O documento “{name}” pode estar danificado. Some layers, pixels or masks could not be read. Do you want to continue opening it? Não foi possível ler algumas camadas, pixels ou máscaras. Deseja continuar abrindo? @@ -2301,7 +2299,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. O documento “{name}” tem um perfil de cores incorporado que não corresponde ao espaço de trabalho {mode} atual. Working: {working} Espaço de trabalho: {working} Developing {name} Revelando {name} - Cancelled {label} {label} cancelado + Canceled {label} {label} cancelado Esc to cancel Esc para cancelar Opened {name} Aberto: {name} Opening {name} Abrindo {name} @@ -2309,7 +2307,7 @@ Saving {name} Salvando {name} Saving {percent} Salvando {percent} A save to {name} is still running; try again when it finishes Um salvamento em {name} ainda está em andamento; tente novamente quando terminar - {label} is writing the file and can no longer be cancelled {label} está gravando o arquivo e não pode mais ser cancelado + {label} is writing the file and can no longer be canceled {label} está gravando o arquivo e não pode mais ser cancelado Opening {name}… Abrindo {name}… Opening… Abrindo… Reading… Lendo… @@ -2675,7 +2673,7 @@ Pixel Pixel Adjustment Ajuste Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Arraste (laço) ou clique nos pontos (poligonal) · {add} adicionar · {sub} subtrair - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Arraste uma caixa de corte · arraste dentro para mover · as bordas redimensionam ({ratio} proporção, {centre} centro) · Espaço move durante o desenho · setas deslocam · X troca a orientação · {commit} confirma · Esc cancela + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Arraste uma caixa de corte · arraste dentro para mover · as bordas redimensionam ({ratio} proporção, {centre} centro) · Espaço move durante o desenho · setas deslocam · X troca a orientação · {commit} confirma · Esc cancela {mode} Color · {bits} bit Cor {mode} · {bits} bits Drag to move the layer Arraste para mover a camada Scrubby Zoom Zoom por arraste @@ -2884,7 +2882,7 @@ cameraRaw Whites Brancos Discard Layers and Save a Copy Descartar camadas e salvar uma cópia Don't show again Não mostrar novamente Save failed: {error} Falha ao salvar: {error} - Save cancelled Salvamento cancelado + Save canceled Salvamento cancelado Style {name} saved Estilo {name} salvo Make Default Definir como padrão Reset to Default Restaurar padrão @@ -3017,7 +3015,7 @@ fontWeight Italic Itálico Impressionist Impressionista Rotate View Tool Ferramenta Girar visualização Reset View Redefinir visualização - Drag around the centre to rotate the view · Shift constrains to 15° Arraste ao redor do centro para girar a visualização · Shift restringe a 15° + Drag around the center to rotate the view · Shift constrains to 15° Arraste ao redor do centro para girar a visualização · Shift restringe a 15° Dual Axis Eixo duplo Diagonal Diagonal Transform Symmetry Transformar simetria @@ -3032,8 +3030,8 @@ fontWeight Italic Itálico All Layers No Adjustments Todas as camadas sem ajustes Current & Below No Adjustments Atual e abaixo sem ajustes Show Sampling Ring Mostrar anel de amostragem - Out of gamut for printing: click for the nearest printable colour Fora da gama de impressão: clique para a cor imprimível mais próxima - Not a web colour: click for the nearest web colour Não é uma cor da Web: clique para a cor da Web mais próxima + Out of gamut for printing: click for the nearest printable color Fora da gama de impressão: clique para a cor imprimível mais próxima + Not a web color: click for the nearest web color Não é uma cor da Web: clique para a cor da Web mais próxima Color to Alpha… Cor para alfa… Transparency Threshold Limiar de transparência Opacity Threshold Limiar de opacidade @@ -4109,7 +4107,7 @@ layerLabel No Color Sem cor Auto Add/Delete Adicionar/excluir automaticamente Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Não ative também a imagem espelhada nas configurações de impressão: as duas inversões se anulam. Print Settings… Configurações de impressão… - Remember to turn off the printer's own colour management in Print Settings… Lembre-se de desativar o gerenciamento de cores da própria impressora nas configurações de impressão… + Remember to turn off the printer's own color management in Print Settings… Lembre-se de desativar o gerenciamento de cores da própria impressora nas configurações de impressão… 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 @@ -4239,12 +4237,12 @@ layerLabel No Color Sem cor Decrease Brush Hardness Diminuir dureza do pincel Increase Brush Hardness Aumentar dureza do pincel Demosaic Demosaico - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Como o mosaico do filtro de cor da câmera é preenchido. É aplicado ao abrir o arquivo; a visualização mostra o método com que ele foi aberto. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Como o mosaico do filtro de cor da câmera é preenchido. É aplicado ao abrir o arquivo; a visualização mostra o método com que ele foi aberto. AHD (adaptive homogeneity) AHD (homogeneidade adaptativa) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: as bordas mais limpas e o menor franjamento de cor; o mais lento. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolação com correção de gradiente: nítida e rápida, com algum franjamento de cor em detalhes finos. - The fastest and the softest, with colour fringing on fine detail. O mais rápido e o mais suave, com franjamento de cor em detalhes finos. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: as bordas mais limpas e o menor franjamento de cor; o mais lento. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolação com correção de gradiente: nítida e rápida, com algum franjamento de cor em detalhes finos. + The fastest and the softest, with color fringing on fine detail. O mais rápido e o mais suave, com franjamento de cor em detalhes finos. “{name}” already exists. Replace it? “{name}” já existe. Substituir? The name in the save dialog was “{name}”. O nome na caixa de diálogo Salvar era “{name}”. Previous Brush Pincel anterior @@ -4520,6 +4518,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Escolha um documento diferente para cada canal. A picked document is no longer open. Um dos documentos escolhidos não está mais aberto. A picked document is no longer a grayscale document of the same size. Um dos documentos escolhidos não é mais um documento em tons de cinza do mesmo tamanho. +# Move tool options bar (#11381) + Align top edges Alinhar bordas superiores + Align vertical centers Alinhar centros verticais + Align bottom edges Alinhar bordas inferiores + Distribute vertically Distribuir verticalmente + Distribute horizontally Distribuir horizontalmente + Show layer bounds on hover Mostrar limites da camada ao passar o cursor + Expand layer group on click Expandir grupo de camadas ao clicar + Show hover bounds from Layers Mostrar limites ao passar o cursor em Camadas +# Artboard tool options bar (#11385) + Distribute Widths Distribuir larguras + Distribute Heights Distribuir alturas + Auto-nest Layers Aninhar camadas automaticamente + Auto-size Canvas Ajustar tamanho da tela automaticamente + Keep Relative Position During Layer Reordering Manter a posição relativa ao reordenar camadas + Shrinkwrap Canvas on Save Reduzir a tela ao conteúdo ao salvar # JPEG Options: the size the file will have (#7843) Estimated file size Tamanho estimado do arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 26db65995b..e653f70772 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -297,7 +297,6 @@ Export As… Экспортировать как… Export Экспорт Export… Экспортировать… - Quick Export As PNG Быстрый экспорт в PNG Quick Export as PNG Быстрый экспорт в PNG Place Embedded… Поместить встроенный… Place Linked… Поместить связанный… @@ -491,7 +490,6 @@ All Всё Deselect Отменить выделение Reselect Повторить выделение - Inverse Selection Инвертировать выделение Inverse Инверсия Color Range… Цветовой диапазон… Select and Mask… Выделение и маска… @@ -770,8 +768,8 @@ Background Фон Set foreground color Основной цвет Set background color Цвет фона - Swap colours (X) Поменять цвета (X) - Default colours (D) Цвета по умолчанию (D) + Switch Foreground and Background Colors (X) Поменять цвета (X) + Default Foreground and Background Colors (D) Цвета по умолчанию (D) Brush Tool Options Параметры кисти Opacity Непрозрачность Flow Нажим @@ -1725,7 +1723,7 @@ Revert “{name}” to the last saved version? Your changes will be lost. Вернуть «{name}» к последней сохранённой версии? Изменения будут потеряны. {key} to subtract {key} — вычесть ↑↓ navigate {key} run esc close ↑↓ переход {key} выполнить esc закрыть - Click to restore the current colour Щёлкните, чтобы восстановить текущий цвет + Click to restore the current color Щёлкните, чтобы восстановить текущий цвет Click with the Note tool to add a note. Щёлкните инструментом «Заметки», чтобы добавить заметку. Drag a rectangle around the object Обведите объект прямоугольником Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Перетащите по изображению, чтобы добавить ограничение; Shift — горизонталь/вертикаль; щелчок правой кнопкой по ограничению — изменить или удалить. @@ -1807,10 +1805,10 @@ Drag to move the active layer Перетащите, чтобы переместить активный слой Drag to pan · hold Space with any tool Перетащите для панорамирования · удерживайте Space с любым инструментом Drag to draw a gradient Перетащите, чтобы нарисовать градиент - Click to fill similar colours Щёлкните, чтобы залить похожие цвета + Click to fill similar colors Щёлкните, чтобы залить похожие цвета Click to add text Щёлкните, чтобы добавить текст Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Перетащите (лассо) или щёлкайте точки (многоугольное) · {add} добавить · {sub} вычесть - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Выделите рамку кадрирования · перетащите внутри для перемещения · края меняют размер ({ratio} пропорции, {centre} центр) · Space двигает при рисовании · стрелки сдвигают · X меняет ориентацию · {commit} применить · Esc отмена + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Выделите рамку кадрирования · перетащите внутри для перемещения · края меняют размер ({ratio} пропорции, {centre} центр) · Space двигает при рисовании · стрелки сдвигают · X меняет ориентацию · {commit} применить · Esc отмена {mode} Color · {bits} bit {mode}, {bits} бит Drag to move the layer Перетащите, чтобы переместить слой Fit Screen По размеру экрана @@ -1842,7 +1840,6 @@ Appearance Внешний вид Text Position: Положение текста: Text color Цвет текста - Uses the foreground and background colours. Использует основной цвет и цвет фона. Answer the unsaved-changes prompt first Сначала ответьте на запрос о несохранённых изменениях Unsaved changes Несохранённые изменения Don't Save Не сохранять @@ -1862,7 +1859,7 @@ name имя new новый Go to Layer Перейти к слою - Open a document to select a colour range. Откройте документ, чтобы выбрать цветовой диапазон. + Open a document to select a color range. Откройте документ, чтобы выбрать цветовой диапазон. Saved Сохранено Reveal in Finder Показать в Finder Show in Explorer Показать в Проводнике @@ -2026,8 +2023,8 @@ Character Styles Panel Панель «Стили символов» Clear Canvas Guides Удалить направляющие холста Clear Selected Artboard Guides Удалить направляющие выбранной области - Color Blindness — Deuteranopia-type Цветовая слепота — дейтеранопия - Color Blindness — Protanopia-type Цветовая слепота — протанопия + Color Blindness - Deuteranopia-type Цветовая слепота - дейтеранопия + Color Blindness - Protanopia-type Цветовая слепота - протанопия Color Table… Цветовая таблица… Combine Shapes Комбинировать фигуры Contract… Сжать… @@ -2200,7 +2197,7 @@ Canvas Холст Capture Снять Center Crop Marks Центральные метки кадрирования - Centre the gradient (offset 0, 0) Центрировать градиент (смещение 0, 0) + Center the gradient (offset 0, 0) Центрировать градиент (смещение 0, 0) Change Screen Mode (F) Сменить режим экрана (F) Change To: Изменить на: Clear All Очистить всё @@ -2352,7 +2349,7 @@ Roughness Шероховатость Roundness Круглость Rulers & Grids Линейки и сетка - Sample: foreground colour Выборка: основной цвет + Sample: foreground color Выборка: основной цвет Sampling: Background Swatch Выборка: фоновый образец Sampling: Continuous Выборка: непрерывная Sampling: Once Выборка: однократная @@ -2427,6 +2424,7 @@ Allow scripts to connect Разрешить подключение сценариев Always Всегда Always create smart objects when placing Всегда создавать смарт-объекты при помещении + Skip transform when placing Пропускать трансформирование при помещении Animated zoom Анимированное масштабирование Apply auto tone Применять автотон Ask Спрашивать @@ -2622,7 +2620,7 @@ Alt-click to define a source point to clone from Alt+щелчок, чтобы задать точку-источник клонирования No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Нет контура для создания выделения: нарисуйте его инструментом «Перо» или выберите на панели «Контуры». Cancel opening Отменить открытие - Cancelled opening {name} Открытие {name} отменено + Canceled opening {name} Открытие {name} отменено Damaged Photoshop document Повреждённый документ Photoshop The document “{name}” may be damaged. Документ «{name}», возможно, повреждён. Some layers, pixels or masks could not be read. Do you want to continue opening it? Не удалось прочитать некоторые слои, пикселы или маски. Продолжить открытие? @@ -2632,7 +2630,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Встроенный цветовой профиль документа «{name}» не совпадает с текущим рабочим пространством {mode}. Working: {working} Рабочее пространство: {working} Developing {name} Обработка {name} - Cancelled {label} {label}: отменено + Canceled {label} {label}: отменено Esc to cancel Esc — отмена Opened {name} Открыто: {name} Opening {name} Открытие {name} @@ -2640,7 +2638,7 @@ Saving {name} Сохранение {name} Saving {percent} Сохранение {percent} A save to {name} is still running; try again when it finishes Сохранение в {name} ещё выполняется; повторите попытку после его завершения - {label} is writing the file and can no longer be cancelled {label}: идёт запись файла, отменить уже нельзя + {label} is writing the file and can no longer be canceled {label}: идёт запись файла, отменить уже нельзя Opening {name}… Открытие {name}… Opening… Открытие… Reading… Чтение… @@ -2732,7 +2730,7 @@ cameraRaw Roughness Неровность Discard Layers and Save a Copy Удалить слои и сохранить копию Don't show again Больше не показывать Save failed: {error} Не удалось сохранить: {error} - Save cancelled Сохранение отменено + Save canceled Сохранение отменено Couldn't place {name}: {error} Не удалось поместить {name}: {error} Magnetic Lasso Tool Магнитное лассо Frequency Частота @@ -2863,7 +2861,7 @@ fontWeight Italic Курсив Impressionist Импрессионист Rotate View Tool Инструмент поворота вида Reset View Сбросить вид - Drag around the centre to rotate the view · Shift constrains to 15° Перетащите вокруг центра, чтобы повернуть вид · Shift фиксирует шаг 15° + Drag around the center to rotate the view · Shift constrains to 15° Перетащите вокруг центра, чтобы повернуть вид · Shift фиксирует шаг 15° Dual Axis Две оси Diagonal Диагональная Transform Symmetry Трансформировать симметрию @@ -2879,9 +2877,9 @@ fontWeight Italic Курсив All Layers No Adjustments Все слои без коррекции Current & Below No Adjustments Текущий и ниже без коррекции Show Sampling Ring Показать кольцо выборки - Click to sample the foreground colour · {key}-click for background Клик — взять основной цвет · {key}-клик — фоновый цвет - Out of gamut for printing: click for the nearest printable colour Вне цветового охвата печати: щёлкните, чтобы выбрать ближайший печатаемый цвет - Not a web colour: click for the nearest web colour Не веб-цвет: щёлкните, чтобы выбрать ближайший веб-цвет + Click to sample the foreground color · {key}-click for background Клик — взять основной цвет · {key}-клик — фоновый цвет + Out of gamut for printing: click for the nearest printable color Вне цветового охвата печати: щёлкните, чтобы выбрать ближайший печатаемый цвет + Not a web color: click for the nearest web color Не веб-цвет: щёлкните, чтобы выбрать ближайший веб-цвет Color to Alpha… Цвет в альфа-канал… Transparency Threshold Порог прозрачности Opacity Threshold Порог непрозрачности @@ -3274,7 +3272,7 @@ curves Smooth Сгладить Auto Add/Delete Автодобавление/удаление Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Не включайте также зеркальное отражение в параметрах печати: два отражения отменяют друг друга. Print Settings… Параметры печати… - Remember to turn off the printer's own colour management in Print Settings… Не забудьте отключить управление цветом самого принтера в параметрах печати… + Remember to turn off the printer's own color management in Print Settings… Не забудьте отключить управление цветом самого принтера в параметрах печати… Sent to {printer} Отправлено на {printer} set in Print Settings… задаётся в параметрах печати… ICO is limited to 256 × 256 pixels ICO ограничен размером 256 × 256 пикселей @@ -3918,12 +3916,12 @@ curves Smooth Сгладить In White Входной белый Increase Brush Hardness Увеличить жёсткость кисти Demosaic Демозаик - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Как восстанавливается мозаика цветного фильтра камеры. Применяется при открытии файла; превью показывает метод, с которым файл был открыт. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Как восстанавливается мозаика цветного фильтра камеры. Применяется при открытии файла; превью показывает метод, с которым файл был открыт. AHD (adaptive homogeneity) AHD (адаптивная однородность) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Хиракава–Паркс: самые чистые края и меньше всего цветной каймы, самый медленный. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Интерполяция с коррекцией градиента: резкая и быстрая, с небольшой цветной каймой на мелких деталях. - The fastest and the softest, with colour fringing on fine detail. Самый быстрый и самый мягкий, с цветной каймой на мелких деталях. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Хиракава–Паркс: самые чистые края и меньше всего цветной каймы, самый медленный. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Интерполяция с коррекцией градиента: резкая и быстрая, с небольшой цветной каймой на мелких деталях. + The fastest and the softest, with color fringing on fine detail. Самый быстрый и самый мягкий, с цветной каймой на мелких деталях. “{name}” already exists. Replace it? «{name}» уже существует. Заменить? The name in the save dialog was “{name}”. В окне сохранения было указано имя «{name}». Previous Brush Предыдущая кисть @@ -4791,6 +4789,22 @@ shape Appearance Оформление Pick a different document for each channel. Выберите отдельный документ для каждого канала. A picked document is no longer open. Один из выбранных документов больше не открыт. A picked document is no longer a grayscale document of the same size. Один из выбранных документов больше не является документом в градациях серого того же размера. +# Move tool options bar (#11381) + Align top edges Выровнять верхние края + Align vertical centers Выровнять центры по вертикали + Align bottom edges Выровнять нижние края + Distribute vertically Распределить по вертикали + Distribute horizontally Распределить по горизонтали + Show layer bounds on hover Показывать границы слоя при наведении + Expand layer group on click Раскрывать группу слоёв по щелчку + Show hover bounds from Layers Показывать границы при наведении из панели «Слои» +# Artboard tool options bar (#11385) + Distribute Widths Распределить ширину + Distribute Heights Распределить высоту + Auto-nest Layers Автоматически вкладывать слои + Auto-size Canvas Автоматически менять размер холста + Keep Relative Position During Layer Reordering Сохранять относительное положение при изменении порядка слоев + Shrinkwrap Canvas on Save Уменьшать холст до содержимого при сохранении # JPEG Options: the size the file will have (#7843) Estimated file size Примерный размер файла diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index d812365019..72f71891a2 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -640,7 +640,6 @@ Deselect Poništi selekciju Reselect Ponovo izaberi Inverse Inverzno - Inverse Selection Obrni selekciju Similar Slično Color Range… Opseg boja… Focus Area… Oblast fokusa… @@ -760,8 +759,8 @@ Legacy Macintosh RGB (Gamma 1.8) Stari Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) Internet standard RGB (sRGB) Monitor RGB RGB monitora - Color Blindness — Protanopia-type Daltonizam — tip protanopije - Color Blindness — Deuteranopia-type Daltonizam — tip deuteranopije + Color Blindness - Protanopia-type Daltonizam - tip protanopije + Color Blindness - Deuteranopia-type Daltonizam - tip deuteranopije Zoom In Uvećaj prikaz Zoom Out Umanji prikaz Fit on Screen Uklopi u ekran @@ -1073,7 +1072,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Kliknite da dodate tačku · prevucite van, {key}-klik ili Delete da uklonite Click to apply, {key}-click to clear overrides, double-click for Style Options Kliknite da primenite, {key}-klik da uklonite nadjačavanja, dvoklik za opcije stila Click to edit the gradient Kliknite da uredite gradijent - Click to restore the current colour Kliknite da vratite tekuću boju + Click to restore the current color Kliknite da vratite tekuću boju Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Kliknite da uvećate · {key}-klik da umanjite · prevucite udesno/ulevo da uvećate/umanjite Click with the Note tool to add a note. Kliknite alatkom za beleške da dodate belešku. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klik: ugao · Prevlačenje: glatko · Klik na prvu tačku: zatvori · {key} završi · Esc otkaži @@ -1153,7 +1152,7 @@ Darks Tamni tonovi Data Sets Skupovi podataka Default Podrazumevano - Default colours (D) Podrazumevane boje (D) + Default Foreground and Background Colors (D) Podrazumevane boje prednjeg plana i pozadine (D) Default printer Podrazumevani štampač Default restored. Podrazumevano stanje je vraćeno. Define Definiši @@ -1427,7 +1426,7 @@ Opacity Jitter Kolebanje neprozirnosti Opacity: Neprozirnost: Open a document to define variables. Otvorite dokument da biste definisali promenljive. - Open a document to select a colour range. Otvorite dokument da biste izabrali opseg boja. + Open a document to select a color range. Otvorite dokument da biste izabrali opseg boja. Open a document to use the timeline. Otvorite dokument da biste koristili vremensku liniju. Optical Optički Optimized Optimizovano @@ -1503,7 +1502,6 @@ Purity Čistoća Quality Kvalitet Quick Actions Brze radnje - Quick Export As PNG Brzi izvoz u PNG Radial Gradient Radijalni gradijent Radius Poluprečnik Radius: Poluprečnik: @@ -1644,7 +1642,7 @@ Subtract from Sample Oduzmi od uzorka Subtract from selection ({key}) Oduzmi od selekcije ({key}) Suggestions: Predlozi: - Swap colours (X) Zameni boje (X) + Switch Foreground and Background Colors (X) Zameni boje prednjeg plana i pozadine (X) Swaps height and width Zamenjuje visinu i širinu Switch between free transform and warp modes Prebaci između režima slobodne transformacije i krivljenja Switch theme Promeni temu @@ -1746,7 +1744,7 @@ Choke Sužavanje Classic Klasično Click to add text Kliknite da dodate tekst - Click to fill similar colours Kliknite da popunite slične boje + Click to fill similar colors Kliknite da popunite slične boje Clone Stamp Tool Alatka pečat za kloniranje Color Burn Zatamnjivanje boje Color Dodge Posvetljivanje boje @@ -1909,7 +1907,7 @@ Rectangular Marquee Tool Alatka za pravougaonu selekciju Reds Crvene Reflected Reflektovano - Sample: foreground colour Uzorak: boja prednjeg plana + Sample: foreground color Uzorak: boja prednjeg plana Sampled Colors Uzorkovane boje Satin Saten Save Pixel Aspect Ratio Sačuvaj odnos stranica piksela @@ -1948,7 +1946,6 @@ Transfer Prenos Triangle Tool Alatka trougao Unsaved changes Nesačuvane izmene - Uses the foreground and background colours. Koristi boje prednjeg plana i pozadine. Web Veb Web Large Veb, veliko Web Minimum Veb, minimum @@ -1983,6 +1980,7 @@ Allow scripts to connect Dozvoli skriptama da se povežu Always Uvek Always create smart objects when placing Uvek pravi pametne objekte pri postavljanju + Skip transform when placing Preskoči transformaciju pri postavljanju Animated zoom Animirano zumiranje Apply auto tone Primeni automatski ton Ask Pitaj @@ -2215,7 +2213,7 @@ Graphics Grafika Reset GPU Backend Resetuj GPU pozadinski sistem Applies at next launch. Primenjuje se pri sledećem pokretanju. - Click to sample the foreground colour · {key}-click for background Kliknite da uzorkujete boju prednjeg plana · {key}-klik za pozadinu + Click to sample the foreground color · {key}-click for background Kliknite da uzorkujete boju prednjeg plana · {key}-klik za pozadinu {key}-click to set the source {key}-klik da postavite izvor {key} to subtract {key} za oduzimanje Clone source {n} ({key}-click with Clone Stamp to set) Izvor kloniranja {n} ({key}-klik pečatom za kloniranje da postavite) @@ -2273,7 +2271,7 @@ Gradient Options Opcije gradijenta Align with layer Poravnaj sa slojem Reset Alignment Resetuj poravnanje - Centre the gradient (offset 0, 0) Centriraj gradijent (pomak 0, 0) + Center the gradient (offset 0, 0) Centriraj gradijent (pomak 0, 0) Gradient Editor Uređivač gradijenta Gradient picker Birač gradijenta Save As Preset Sačuvaj kao šablon @@ -2306,7 +2304,7 @@ Alt-click to define a source point to clone from Alt-klik da odredite izvornu tačku za kloniranje No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nema putanje od koje bi se napravila selekcija: nacrtajte je alatkom pero ili je izaberite u panelu Putanje. Cancel opening Otkaži otvaranje - Cancelled opening {name} Otkazano otvaranje: {name} + Canceled opening {name} Otkazano otvaranje: {name} Damaged Photoshop document Oštećen Photoshop dokument The document “{name}” may be damaged. Dokument „{name}“ je možda oštećen. Some layers, pixels or masks could not be read. Do you want to continue opening it? Neki slojevi, pikseli ili maske nisu mogli da se pročitaju. Želite li da nastavite sa otvaranjem? @@ -2315,7 +2313,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}“ ima ugrađeni profil boja koji se ne slaže sa trenutnim {mode} radnim prostorom. Working: {working} Radni prostor: {working} Developing {name} Razvijanje: {name} - Cancelled {label} Otkazano: {label} + Canceled {label} Otkazano: {label} Esc to cancel Esc za otkazivanje Opened {name} Otvoreno: {name} Opening {name} Otvaranje: {name} @@ -2323,7 +2321,7 @@ Saving {name} Čuvanje: {name} Saving {percent} Čuvanje {percent} A save to {name} is still running; try again when it finishes Čuvanje u {name} je još u toku; pokušajte ponovo kada se završi - {label} is writing the file and can no longer be cancelled {label}: datoteka se upisuje i više ne može da se otkaže + {label} is writing the file and can no longer be canceled {label}: datoteka se upisuje i više ne može da se otkaže Opening {name}… Otvaranje: {name}… Opening… Otvaranje… Reading… Čitanje… @@ -2698,7 +2696,7 @@ Pixel Piksel Adjustment Korekcija Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Prevucite (laso) ili kliknite tačke (mnogougao) · {add} dodaje · {sub} oduzima - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Prevucite okvir za opsecanje · prevlačenje unutra pomera · ivice menjaju veličinu ({ratio} odnos, {centre} centar) · razmaknica pomera tokom crtanja · strelice pomeraju malo · X menja orijentaciju · {commit} potvrđuje · Esc otkazuje + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Prevucite okvir za opsecanje · prevlačenje unutra pomera · ivice menjaju veličinu ({ratio} odnos, {centre} centar) · razmaknica pomera tokom crtanja · strelice pomeraju malo · X menja orijentaciju · {commit} potvrđuje · Esc otkazuje {mode} Color · {bits} bit {mode} boje · {bits} bita Drag to move the layer Prevucite da pomerite sloj Scrubby Zoom Zumiranje prevlačenjem @@ -2892,7 +2890,7 @@ cameraRaw Blending Stapanje Discard Layers and Save a Copy Odbaci slojeve i sačuvaj kopiju Don't show again Ne prikazuj ponovo Save failed: {error} Čuvanje nije uspelo: {error} - Save cancelled Čuvanje je otkazano + Save canceled Čuvanje je otkazano Couldn't place {name}: {error} Postavljanje {name} nije uspelo: {error} Magnetic Lasso Tool Alatka magnetni laso Frequency Frekvencija @@ -3017,7 +3015,7 @@ fontWeight Italic Kurziv Impressionist Impresionistički Rotate View Tool Alatka za rotiranje prikaza Reset View Resetuj prikaz - Drag around the centre to rotate the view · Shift constrains to 15° Prevlačite oko centra da rotirate prikaz · Shift ograničava na korake od 15° + Drag around the center to rotate the view · Shift constrains to 15° Prevlačite oko centra da rotirate prikaz · Shift ograničava na korake od 15° Dual Axis Dvostruka osa Diagonal Dijagonala Transform Symmetry Transformiši simetriju @@ -3032,8 +3030,8 @@ fontWeight Italic Kurziv All Layers No Adjustments Svi slojevi bez korekcija Current & Below No Adjustments Tekući i ispod bez korekcija Show Sampling Ring Prikaži prsten uzorkovanja - Out of gamut for printing: click for the nearest printable colour Van gamuta za štampu: kliknite za najbližu boju koja može da se odštampa - Not a web colour: click for the nearest web colour Nije veb boja: kliknite za najbližu veb boju + Out of gamut for printing: click for the nearest printable color Van gamuta za štampu: kliknite za najbližu boju koja može da se odštampa + Not a web color: click for the nearest web color Nije veb boja: kliknite za najbližu veb boju Color to Alpha… Boja u alfu… Transparency Threshold Prag providnosti Opacity Threshold Prag neprozirnosti @@ -4335,7 +4333,7 @@ shape Appearance Izgled Auto Add/Delete Automatsko dodavanje/brisanje Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nemojte uključiti i ogledalsku sliku u podešavanjima štampanja: dva preslikavanja se poništavaju. Print Settings… Podešavanja štampanja… - Remember to turn off the printer's own colour management in Print Settings… Ne zaboravite da isključite upravljanje bojama samog štampača u podešavanjima štampanja… + Remember to turn off the printer's own color management in Print Settings… Ne zaboravite da isključite upravljanje bojama samog štampača u podešavanjima štampanja… Sent to {printer} Poslato na {printer} set in Print Settings… podešava se u podešavanjima štampanja… Paper Width Širina papira @@ -4508,12 +4506,12 @@ shape Appearance Izgled Decrease Brush Hardness Smanji tvrdoću četkice Increase Brush Hardness Povećaj tvrdoću četkice Demosaic Demozaikovanje - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Kako se popunjava mozaik filtera boja kamere. Primenjuje se pri otvaranju datoteke; pregled prikazuje metod kojim je datoteka otvorena. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Kako se popunjava mozaik filtera boja kamere. Primenjuje se pri otvaranju datoteke; pregled prikazuje metod kojim je datoteka otvorena. AHD (adaptive homogeneity) AHD (adaptivna homogenost) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: najčistije ivice i najmanje obojenih rubova, najsporiji. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Interpolacija sa korekcijom gradijenta: oštra i brza, sa malo obojenih rubova na finim detaljima. - The fastest and the softest, with colour fringing on fine detail. Najbrži i najmekši, sa obojenim rubovima na finim detaljima. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: najčistije ivice i najmanje obojenih rubova, najsporiji. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Interpolacija sa korekcijom gradijenta: oštra i brza, sa malo obojenih rubova na finim detaljima. + The fastest and the softest, with color fringing on fine detail. Najbrži i najmekši, sa obojenim rubovima na finim detaljima. “{name}” already exists. Replace it? „{name}“ već postoji. Zameniti? The name in the save dialog was “{name}”. Ime u dijalogu za čuvanje je bilo „{name}“. Previous Brush Prethodna četkica @@ -4672,6 +4670,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Izaberite drugi dokument za svaki kanal. A picked document is no longer open. Jedan izabrani dokument više nije otvoren. A picked document is no longer a grayscale document of the same size. Jedan izabrani dokument više nije dokument u nijansama sive iste veličine. +# Move tool options bar (#11381) + Align top edges Poravnaj gornje ivice + Align vertical centers Poravnaj vertikalne centre + Align bottom edges Poravnaj donje ivice + Distribute vertically Raspodeli vertikalno + Distribute horizontally Raspodeli horizontalno + Show layer bounds on hover Prikaži granice sloja pri prelasku miša + Expand layer group on click Proširi grupu slojeva klikom + Show hover bounds from Layers Prikaži granice pri prelasku iz panela Slojevi +# Artboard tool options bar (#11385) + Distribute Widths Raspodeli širine + Distribute Heights Raspodeli visine + Auto-nest Layers Automatski ugnezdi slojeve + Auto-size Canvas Automatski promeni veličinu platna + Keep Relative Position During Layer Reordering Zadrži relativni položaj pri promeni redosleda slojeva + Shrinkwrap Canvas on Save Smanji platno na sadržaj pri čuvanju # JPEG Options: the size the file will have (#7843) Estimated file size Procenjena veličina datoteke diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 741c0c09c6..2157f234de 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -109,7 +109,6 @@ Export As… Exportera som… Export Exportera Export… Exportera… - Quick Export As PNG Snabbexportera som PNG Quick Export as PNG Snabbexportera som PNG Place Embedded… Placera inbäddad… Place Linked… Placera länkad… @@ -313,7 +312,6 @@ All Alla Deselect Avmarkera Reselect Markera igen - Inverse Selection Omvänd markering Inverse Omvänd Color Range… Färgintervall… Select and Mask… Markera och maskera… @@ -604,8 +602,8 @@ Background Bakgrund Set foreground color Ange förgrundsfärg Set background color Ange bakgrundsfärg - Swap colours (X) Byt plats på färgerna (X) - Default colours (D) Standardfärger (D) + Switch Foreground and Background Colors (X) Växla förgrunds- och bakgrundsfärg (X) + Default Foreground and Background Colors (D) Standardfärger för förgrund och bakgrund (D) Brush Tool Options Alternativ för penselverktyget Opacity Opacitet Flow Flöde @@ -1612,7 +1610,7 @@ Revert “{name}” to the last saved version? Your changes will be lost. Vill du återgå till den senast sparade versionen av ”{name}”? Dina ändringar går förlorade. {key} to subtract {key} för att subtrahera ↑↓ navigate {key} run esc close ↑↓ navigera {key} kör esc stäng - Click to restore the current colour Klicka för att återställa den aktuella färgen + Click to restore the current color Klicka för att återställa den aktuella färgen Click with the Note tool to add a note. Klicka med anteckningsverktyget för att lägga till en anteckning. Drag a rectangle around the object Dra en rektangel runt objektet Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Dra i bilden för att lägga till en begränsning; Shift för vågrätt/lodrätt; högerklicka på en begränsning för att ändra eller ta bort den. @@ -1694,10 +1692,10 @@ Drag to move the active layer Dra för att flytta det aktiva lagret Drag to pan · hold Space with any tool Dra för att panorera · håll ned blanksteg med valfritt verktyg Drag to draw a gradient Dra för att rita en gradient - Click to fill similar colours Klicka för att fylla liknande färger + Click to fill similar colors Klicka för att fylla liknande färger Click to add text Klicka för att lägga till text Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Dra (lasso) eller klicka på punkter (polygonal) · {add} lägg till · {sub} subtrahera - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Dra en beskärningsram · dra inuti för att flytta · kanterna ändrar storlek ({ratio} proportioner, {centre} centrerat) · Blanksteg flyttar medan du ritar · piltangenterna flyttar stegvis · X byter orientering · {commit} verkställer · Esc avbryter + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Dra en beskärningsram · dra inuti för att flytta · kanterna ändrar storlek ({ratio} proportioner, {centre} centrerat) · Blanksteg flyttar medan du ritar · piltangenterna flyttar stegvis · X byter orientering · {commit} verkställer · Esc avbryter {mode} Color · {bits} bit {mode}-färg · {bits} bitar Drag to move the layer Dra för att flytta lagret Fit Screen Anpassa till skärmen @@ -1729,7 +1727,7 @@ Appearance Utseende Text Position: Textposition: Text color Textfärg - Uses the foreground and background colours. Använder förgrunds- och bakgrundsfärgerna. + Uses the foreground and background colors. Använder förgrunds- och bakgrundsfärgerna. Answer the unsaved-changes prompt first Svara först på frågan om osparade ändringar Unsaved changes Osparade ändringar Don't Save Spara inte @@ -1749,7 +1747,7 @@ name namn new ny Go to Layer Gå till lager - Open a document to select a colour range. Öppna ett dokument för att välja ett färgintervall. + Open a document to select a color range. Öppna ett dokument för att välja ett färgintervall. Saved Sparat Reveal in Finder Visa i Finder Show in Explorer Visa i Utforskaren @@ -1927,8 +1925,8 @@ Character Styles Panel Panelen Teckenformat Clear Canvas Guides Rensa stödlinjer för arbetsytan Clear Selected Artboard Guides Rensa stödlinjer för markerad rityta - Color Blindness — Deuteranopia-type Färgblindhet — deuteranopityp - Color Blindness — Protanopia-type Färgblindhet — protanopityp + Color Blindness - Deuteranopia-type Färgblindhet — deuteranopityp + Color Blindness - Protanopia-type Färgblindhet — protanopityp Color Table… Färgtabell… Combine Shapes Kombinera former Contract… Dra ihop… @@ -2102,7 +2100,7 @@ Canvas Arbetsyta Capture Fånga Center Crop Marks Centrerade beskärningsmärken - Centre the gradient (offset 0, 0) Centrera gradienten (förskjutning 0, 0) + Center the gradient (offset 0, 0) Centrera gradienten (förskjutning 0, 0) Change Screen Mode (F) Ändra skärmläge (F) Change To: Ändra till: Clear All Rensa alla @@ -2254,7 +2252,7 @@ Roughness Grovhet Roundness Rundhet Rulers & Grids Linjaler och rutnät - Sample: foreground colour Prov: förgrundsfärg + Sample: foreground color Prov: förgrundsfärg Sampling: Background Swatch Provtagning: bakgrundsfärgruta Sampling: Continuous Provtagning: kontinuerlig Sampling: Once Provtagning: en gång @@ -2527,7 +2525,7 @@ Alt-click to define a source point to clone from Alt-klicka för att ange en källpunkt att klona från No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Det finns ingen bana att skapa en markering från: rita en med pennverktyget eller markera en i panelen Banor. Cancel opening Avbryt öppning - Cancelled opening {name} Öppningen av {name} avbröts + Canceled opening {name} Öppningen av {name} avbröts Damaged Photoshop document Skadat Photoshop-dokument The document “{name}” may be damaged. Dokumentet ”{name}” kan vara skadat. Some layers, pixels or masks could not be read. Do you want to continue opening it? Vissa lager, pixlar eller masker kunde inte läsas. Vill du fortsätta att öppna det? @@ -2537,7 +2535,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokumentet ”{name}” har en inbäddad färgprofil som inte matchar den aktuella arbetsfärgrymden för {mode}. Working: {working} Arbetsfärgrymd: {working} Developing {name} Framkallar {name} - Cancelled {label} {label} avbröts + Canceled {label} {label} avbröts Esc to cancel Esc för att avbryta Opened {name} Öppnade {name} Opening {name} Öppnar {name} @@ -2545,7 +2543,7 @@ Saving {name} Sparar {name} Saving {percent} Sparar {percent} A save to {name} is still running; try again when it finishes En sparning till {name} pågår fortfarande; försök igen när den är klar - {label} is writing the file and can no longer be cancelled {label} skriver filen och kan inte längre avbrytas + {label} is writing the file and can no longer be canceled {label} skriver filen och kan inte längre avbrytas Opening {name}… Öppnar {name}… Opening… Öppnar… Reading… Läser… @@ -2642,7 +2640,7 @@ cameraRaw Roughness Grovhet Discard Layers and Save a Copy Släng lager och spara en kopia Don't show again Visa inte igen Save failed: {error} Det gick inte att spara: {error} - Save cancelled Sparandet avbröts + Save canceled Sparandet avbröts Couldn't place {name}: {error} Det gick inte att placera {name}: {error} Magnetic Lasso Tool Verktyget Magnetiskt lasso Frequency Frekvens @@ -2786,7 +2784,7 @@ fontWeight Italic Kursiv Impressionist Impressionistisk Rotate View Tool Verktyget Rotera vy Reset View Återställ vy - Drag around the centre to rotate the view · Shift constrains to 15° Dra runt mitten för att rotera vyn · Shift begränsar till 15° + Drag around the center to rotate the view · Shift constrains to 15° Dra runt mitten för att rotera vyn · Shift begränsar till 15° # Painting symmetry presets. Dual Axis Dubbelaxel @@ -2806,11 +2804,11 @@ fontWeight Italic Kursiv All Layers No Adjustments Alla lager utan justeringar Current & Below No Adjustments Aktuellt och under utan justeringar Show Sampling Ring Visa provtagningsring - Click to sample the foreground colour · {key}-click for background Klicka för att ta prov på förgrundsfärgen · {key}-klicka för bakgrundsfärgen + Click to sample the foreground color · {key}-click for background Klicka för att ta prov på förgrundsfärgen · {key}-klicka för bakgrundsfärgen # Color Picker warnings - Out of gamut for printing: click for the nearest printable colour Utanför färgomfånget för utskrift: klicka för närmaste utskrivbara färg - Not a web colour: click for the nearest web colour Inte en webbfärg: klicka för närmaste webbfärg + Out of gamut for printing: click for the nearest printable color Utanför färgomfånget för utskrift: klicka för närmaste utskrivbara färg + Not a web color: click for the nearest web color Inte en webbfärg: klicka för närmaste webbfärg Color to Alpha… Färg till alfa… Transparency Threshold Tröskelvärde för genomskinlighet Opacity Threshold Opacitetströskelvärde @@ -3228,7 +3226,7 @@ curves Smooth Jämna ut # Native Windows printing qualification Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Markera inte också Spegelvänd bild i Utskriftsinställningar…: de två vändningarna tar ut varandra. Print Settings… Utskriftsinställningar… - Remember to turn off the printer's own colour management in Print Settings… Kom ihåg att stänga av skrivarens egen färghantering i Utskriftsinställningar… + Remember to turn off the printer's own color management in Print Settings… Kom ihåg att stänga av skrivarens egen färghantering i Utskriftsinställningar… Sent to {printer} Skickat till {printer} set in Print Settings… anges i Utskriftsinställningar… ICO is limited to 256 × 256 pixels ICO är begränsat till 256 × 256 pixlar @@ -3892,12 +3890,12 @@ curves Smooth Jämna ut In White Vitt in Increase Brush Hardness Öka penselns hårdhet Demosaic Demosaicering - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hur kamerans färgfiltermosaik fylls i. Den tillämpas när filen öppnas; förhandsgranskningen visar metoden som den öppnades med. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Hur kamerans färgfiltermosaik fylls i. Den tillämpas när filen öppnas; förhandsgranskningen visar metoden som den öppnades med. AHD (adaptive homogeneity) AHD (adaptiv homogenitet) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: renast kanter och minst färgfransning, men långsammast. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradientkorrigerad interpolering: skarp och snabb, med viss färgfransning i fina detaljer. - The fastest and the softest, with colour fringing on fine detail. Snabbast och mjukast, med färgfransar vid fina detaljer. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: renast kanter och minst färgfransning, men långsammast. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradientkorrigerad interpolering: skarp och snabb, med viss färgfransning i fina detaljer. + The fastest and the softest, with color fringing on fine detail. Snabbast och mjukast, med färgfransar vid fina detaljer. “{name}” already exists. Replace it? ”{name}” finns redan. Vill du ersätta den? The name in the save dialog was “{name}”. Namnet i dialogrutan Spara var ”{name}”. Move Up Flytta uppåt @@ -4548,7 +4546,6 @@ curves Smooth Jämna ut Use File › Open to open an image. Öppna en bild med Arkiv › Öppna. Use Selection In Source Använd markering i källan Use Selection In Target Använd markering i målet - Uses the foreground and background colors. Använder förgrunds- och bakgrundsfärgerna. Vanishing Point Fluktpunkt Variable Data Sets Variabla datauppsättningar Vector Mask Hides Effects Vektormask döljer effekter @@ -4758,8 +4755,8 @@ cameraRaw Camera Raw ({name}) Camera Raw ({name}) cameraRaw Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) cameraRaw Camera Raw isn't open Camera Raw är inte öppet cameraRaw Cancel Avbryt -cameraRaw Cancelled opening {name} Öppningen av {name} avbröts -cameraRaw Cancelled {label} {label} avbröts +cameraRaw Canceled opening {name} Öppningen av {name} avbröts +cameraRaw Canceled {label} {label} avbröts cameraRaw Color Priority Färgprioritet cameraRaw Developing {name} Framkallar {name} cameraRaw Full-resolution preview unavailable Förhandsgranskning i full upplösning är inte tillgänglig @@ -4814,3 +4811,19 @@ cameraRaw White Balance: As Shot Vitbalans: som tagen Pick a different document for each channel. Välj ett annat dokument för varje kanal. A picked document is no longer open. Ett av de valda dokumenten är inte längre öppet. A picked document is no longer a grayscale document of the same size. Ett av de valda dokumenten är inte längre ett gråskaledokument i samma storlek. +# Move tool options bar (#11381) + Align top edges Justera överkanter + Align vertical centers Justera vertikala mittpunkter + Align bottom edges Justera underkanter + Distribute vertically Fördela vertikalt + Distribute horizontally Fördela horisontellt + Show layer bounds on hover Visa lagrets gränser vid hovring + Expand layer group on click Expandera lagergrupp vid klick + Show hover bounds from Layers Visa hovringsgränser från Lager +# Artboard tool options bar (#11385) + Distribute Widths Fördela bredder + Distribute Heights Fördela höjder + Auto-nest Layers Kapsla in lager automatiskt + Auto-size Canvas Ändra storlek på arbetsytan automatiskt + Keep Relative Position During Layer Reordering Behåll relativ position vid ändring av lagerordning + Shrinkwrap Canvas on Save Krymp arbetsytan till innehållet vid sparning diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e3c55e299c..acbe444801 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -557,7 +557,6 @@ Deselect Seçimi Kaldır Reselect Yeniden Seç Inverse Ters Çevir - Inverse Selection Ters Seçim Similar Benzer Color Range… Renk Aralığı… Focus Area… Odaklanma Alanı… @@ -676,8 +675,8 @@ Legacy Macintosh RGB (Gamma 1.8) Eski Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) İnternet Standardı RGB (sRGB) Monitor RGB Monitör RGB - Color Blindness — Protanopia-type Renk Körlüğü — Protanopi tipi - Color Blindness — Deuteranopia-type Renk Körlüğü — Döteranopi tipi + Color Blindness - Protanopia-type Renk Körlüğü - Protanopi tipi + Color Blindness - Deuteranopia-type Renk Körlüğü - Döteranopi tipi Zoom In Yakınlaştır Zoom Out Uzaklaştır Fit on Screen Ekrana Sığdır @@ -981,7 +980,7 @@ Click to add a point · drag off or {key}-click or Delete to remove Nokta eklemek için tıklayın · kaldırmak için dışarı sürükleyin, {key}-tıklayın veya Delete'e basın Click to apply, {key}-click to clear overrides, double-click for Style Options Uygulamak için tıklayın, geçersiz kılmaları temizlemek için {key}-tıklayın, Stil Seçenekleri için çift tıklayın Click to edit the gradient Degradeyi düzenlemek için tıklayın - Click to restore the current colour Geçerli rengi geri yüklemek için tıklayın + Click to restore the current color Geçerli rengi geri yüklemek için tıklayın Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Yakınlaştırmak için tıklayın · uzaklaştırmak için {key}-tıklayın · yakınlaştırmak/uzaklaştırmak için sağa/sola sürükleyin Click with the Note tool to add a note. Not eklemek için Not aracıyla tıklayın. Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Tıklayın: köşe · Sürükleyin: pürüzsüz · İlk noktaya tıklayın: kapat · {key} bitiş · Esc iptal @@ -1063,7 +1062,7 @@ Darks Koyu Tonlar Data Sets Veri Kümeleri Default Varsayılan - Default colours (D) Varsayılan renkler (D) + Default Foreground and Background Colors (D) Varsayılan Ön Plan ve Arka Plan Renkleri (D) Default printer Varsayılan yazıcı Default restored. Varsayılan geri yüklendi. Define Tanımla @@ -1344,7 +1343,7 @@ Opacity Jitter Opaklık Titreşimi Opacity: Opaklık: Open a document to define variables. Değişkenleri tanımlamak için bir belge açın. - Open a document to select a colour range. Bir renk aralığı seçmek için bir belge açın. + Open a document to select a color range. Bir renk aralığı seçmek için bir belge açın. Open a document to use the timeline. Zaman çizelgesini kullanmak için bir belge açın. Optical Optik Optimized Optimize edilmiş @@ -1420,7 +1419,6 @@ Purity Saflık Quality Kalite Quick Actions Hızlı Eylemler - Quick Export As PNG PNG Olarak Hızlı Dışa Aktarma Radial Gradient Radyal Degrade Radius Yarıçap Radius: Yarıçap: @@ -1559,7 +1557,7 @@ Subtract from Sample Örnekten Çıkar Subtract from selection ({key}) Seçimden çıkar ({key}) Suggestions: Öneriler: - Swap colours (X) Renkleri değiştir (X) + Switch Foreground and Background Colors (X) Ön Plan ve Arka Plan Renklerini Değiştir (X) Swaps height and width Yüksekliği ve genişliği değiştirir Switch between free transform and warp modes Serbest dönüştürme ve bükme modları arasında geçiş yapın Switch theme Temayı değiştir @@ -1661,7 +1659,7 @@ Choke Daraltma Classic Klasik Click to add text Metin eklemek için tıklayın - Click to fill similar colours Benzer renkleri doldurmak için tıklayın + Click to fill similar colors Benzer renkleri doldurmak için tıklayın Clone Stamp Tool Klonlama Damgası Aracı Color Burn Renk Yakma Color Dodge Renk Soldurma @@ -1821,7 +1819,7 @@ Rectangular Marquee Tool Dikdörtgen Seçim Çerçevesi Aracı Reds Kırmızılar Reflected Yansıyan - Sample: foreground colour Örnek: ön plan rengi + Sample: foreground color Örnek: ön plan rengi Sampled Colors Örneklenen Renkler Satin Saten Save Pixel Aspect Ratio Piksel En Boy Oranını Kaydet @@ -1860,7 +1858,6 @@ Transfer Aktarım Triangle Tool Üçgen Aracı Unsaved changes Kaydedilmemiş değişiklikler - Uses the foreground and background colours. Ön plan ve arka plan renklerini kullanır. Web Web Web Large Web Büyük Web Minimum Web Minimumu @@ -1897,6 +1894,7 @@ Allow scripts to connect Komut dosyalarının bağlanmasına izin ver Always Her zaman Always create smart objects when placing Yerleştirirken daima akıllı nesneler yaratın + Skip transform when placing Yerleştirirken dönüştürmeyi atla Animated zoom Animasyonlu yakınlaştırma Apply auto tone Otomatik tonu uygula Ask Sor @@ -2129,7 +2127,7 @@ Graphics Grafik Reset GPU Backend GPU Arka Ucunu Sıfırla Applies at next launch. Bir sonraki açılışta geçerlidir. - Click to sample the foreground colour · {key}-click for background Ön plan rengini örneklemek için tıklayın · arka plan için {key}-tıklayın + Click to sample the foreground color · {key}-click for background Ön plan rengini örneklemek için tıklayın · arka plan için {key}-tıklayın {key}-click to set the source Kaynağı ayarlamak için {key} tuşuna basarak tıklayın {key} to subtract {key} çıkarmak için Clone source {n} ({key}-click with Clone Stamp to set) Klon kaynağı {n} (ayarlamak için Klonlama Damgası ile {key}-tıklayın) @@ -2188,7 +2186,7 @@ Gradient Options Degrade Seçenekleri Align with layer Katmanla hizala Reset Alignment Hizalamayı Sıfırla - Centre the gradient (offset 0, 0) Degradeyi ortalayın (kaydırma 0, 0) + Center the gradient (offset 0, 0) Degradeyi ortalayın (kaydırma 0, 0) Gradient Editor Degrade Düzenleyici Gradient picker Degrade seçici Gradient stops Degrade durakları @@ -2222,7 +2220,7 @@ Alt-click to define a source point to clone from Kopyalanacak kaynak noktayı tanımlamak için Alt tuşuna basarak tıklayın No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Seçim yapılabilecek yol yok: Kalem aracıyla bir yol çizin veya Yollar panelinden birini seçin. Cancel opening Açılışı iptal et - Cancelled opening {name} {name} açılışı iptal edildi + Canceled opening {name} {name} açılışı iptal edildi Damaged Photoshop document Hasarlı Photoshop belgesi The document “{name}” may be damaged. “{name}” belgesi hasarlı olabilir. Some layers, pixels or masks could not be read. Do you want to continue opening it? Bazı katmanlar, pikseller veya maskeler okunamadı. Açmaya devam etmek istiyor musunuz? @@ -2231,14 +2229,14 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. “{name}” belgesinin gömülü renk profili geçerli {mode} çalışma renk uzayıyla eşleşmiyor. Working: {working} Çalışma renk uzayı: {working} Developing {name} {name} geliştiriliyor - Cancelled {label} {label} iptal edildi + Canceled {label} {label} iptal edildi Esc to cancel İptal etmek için Esc Opened {name} {name} açıldı Opening {name} {name} açılıyor Saved {name} {name} kaydedildi Saving {name} {name} kaydediliyor A save to {name} is still running; try again when it finishes {name} konumuna kaydetme işlemi hâlâ devam ediyor; bittiğinde tekrar dene - {label} is writing the file and can no longer be cancelled {label} dosyayı yazıyor ve artık iptal edilemez + {label} is writing the file and can no longer be canceled {label} dosyayı yazıyor ve artık iptal edilemez Opening {name}… {name} açılıyor… Opening… Açılıyor… Reading… Okunuyor… @@ -2304,7 +2302,7 @@ Pixel Piksel Adjustment Ayarlama Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Noktaları sürükleyin (kement) veya tıklayın (çokgen) · {add} ekle · {sub} çıkar - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Kırpma kutusunu sürükleyin · taşımak için içeriye sürükleyin · kenarlar yeniden boyutlandırır ({ratio} oran, {centre} merkez) · çizerken Space taşır · ok tuşları hafifçe kaydırır · X yönü değiştirir · {commit} onaylar · Esc iptal eder + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Kırpma kutusunu sürükleyin · taşımak için içeriye sürükleyin · kenarlar yeniden boyutlandırır ({ratio} oran, {centre} merkez) · çizerken Space taşır · ok tuşları hafifçe kaydırır · X yönü değiştirir · {commit} onaylar · Esc iptal eder {mode} Color · {bits} bit {mode} Renk · {bits} bit Scrubby Zoom Sürüklemeli Yakınlaştırma Auto Erase Otomatik Silme @@ -2396,7 +2394,7 @@ Discard Layers and Save a Copy Katmanları At ve Kopyasını Kaydet Don't show again Bir daha gösterme Save failed: {error} Kaydetme başarısız oldu: {error} - Save cancelled Kaydetme iptal edildi + Save canceled Kaydetme iptal edildi Style {name} saved {name} stili kaydedildi Make Default Varsayılan Yap Reset to Default Varsayılana Sıfırla @@ -2529,7 +2527,7 @@ fontWeight Italic İtalik Rotate View Görünümü Döndür Rotate View Tool Görünümü Döndürme Aracı Reset View Görünümü Sıfırla - Drag around the centre to rotate the view · Shift constrains to 15° Görünümü döndürmek için merkez etrafında sürükleyin · Shift 15° ile sınırlar + Drag around the center to rotate the view · Shift constrains to 15° Görünümü döndürmek için merkez etrafında sürükleyin · Shift 15° ile sınırlar @id select.all Tümünü Seç @id edit.stroke Kontur… @id edit.transform.scale Ölçekle @@ -3713,8 +3711,8 @@ cameraRaw Whites Beyazlar @id filter.sharpen.sharpen Keskinleştir Good iyi Best En iyi - Out of gamut for printing: click for the nearest printable colour Yazdırma için gamın dışında: yazdırılabilir en yakın renk için tıklayın - Not a web colour: click for the nearest web colour Web rengi değil: en yakın web rengi için tıklayın + Out of gamut for printing: click for the nearest printable color Yazdırma için gamın dışında: yazdırılabilir en yakın renk için tıklayın + Not a web color: click for the nearest web color Web rengi değil: en yakın web rengi için tıklayın Adjustment Properties Ayarlama Özellikleri Brush Stroke Fırça Vuruşu Default Foreground and Background Colors Varsayılan Ön Plan ve Arka Plan Renkleri @@ -4007,7 +4005,7 @@ cameraData Lens Lens Auto Add/Delete Otomatik Ekle/Sil Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Yazdırma Ayarlarında ayrıca Ayna Görüntüsünü açmayın: iki yansıtma birbirini iptal eder. Print Settings… Yazdırma Ayarları… - Remember to turn off the printer's own colour management in Print Settings… Yazdırma Ayarlarında yazıcının kendi renk yönetimini kapatmayı unutmayın… + Remember to turn off the printer's own color management in Print Settings… Yazdırma Ayarlarında yazıcının kendi renk yönetimini kapatmayı unutmayın… Sent to {printer} {printer} yazıcısına gönderildi set in Print Settings… Yazdırma Ayarlarında belirlenir… ICO is limited to 256 × 256 pixels ICO 256 × 256 piksel ile sınırlıdır @@ -4164,12 +4162,12 @@ cameraData Lens Lens Decrease Brush Hardness Fırça sertliğini azalt Increase Brush Hardness Fırça sertliğini artır Demosaic Demozaikleme - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Kameranın renk filtresi mozaiğinin nasıl doldurulduğu. Dosya açılırken uygulanır; önizleme dosyanın açıldığı yöntemi gösterir. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Kameranın renk filtresi mozaiğinin nasıl doldurulduğu. Dosya açılırken uygulanır; önizleme dosyanın açıldığı yöntemi gösterir. AHD (adaptive homogeneity) AHD (uyarlamalı homojenlik) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: en temiz kenarlar ve en az renk saçağı, en yavaş. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Gradyan düzeltmeli ara değerleme: keskin ve hızlı, ince ayrıntılarda biraz renk saçağı. - The fastest and the softest, with colour fringing on fine detail. En hızlı ve en yumuşak, ince ayrıntılarda renk saçağı. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: en temiz kenarlar ve en az renk saçağı, en yavaş. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Gradyan düzeltmeli ara değerleme: keskin ve hızlı, ince ayrıntılarda biraz renk saçağı. + The fastest and the softest, with color fringing on fine detail. En hızlı ve en yumuşak, ince ayrıntılarda renk saçağı. “{name}” already exists. Replace it? '{name}' zaten var. Değiştirilsin mi? The name in the save dialog was “{name}”. Kaydetme penceresindeki ad '{name}' idi. Previous Brush Önceki fırça @@ -4337,6 +4335,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Her kanal için farklı bir belge seçin. A picked document is no longer open. Seçilen belgelerden biri artık açık değil. A picked document is no longer a grayscale document of the same size. Seçilen belgelerden biri artık aynı boyutta gri tonlamalı bir belge değil. +# Move tool options bar (#11381) + Align top edges Üst kenarları hizala + Align vertical centers Dikey merkezleri hizala + Align bottom edges Alt kenarları hizala + Distribute vertically Dikey olarak dağıt + Distribute horizontally Yatay olarak dağıt + Show layer bounds on hover Üzerine gelince katman sınırlarını göster + Expand layer group on click Tıklayınca katman grubunu genişlet + Show hover bounds from Layers Katmanlar'dan üzerine gelme sınırlarını göster +# Artboard tool options bar (#11385) + Distribute Widths Genişlikleri Dağıt + Distribute Heights Yükseklikleri Dağıt + Auto-nest Layers Katmanları Otomatik İç İçe Yerleştir + Auto-size Canvas Tuvali Otomatik Boyutlandır + Keep Relative Position During Layer Reordering Katmanları Yeniden Sıralarken Göreli Konumu Koru + Shrinkwrap Canvas on Save Kaydederken Tuvali İçeriğe Göre Küçült # JPEG Options: the size the file will have (#7843) Estimated file size Tahmini dosya boyutu diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 22505f8789..d419831b97 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -280,7 +280,6 @@ Export As… Експортувати як… Export Експорт Export… Експортувати… - Quick Export As PNG Швидкий експорт у PNG Quick Export as PNG Швидкий експорт у PNG Place Embedded… Розмістити вбудований… Place Linked… Розмістити пов'язаний… @@ -462,7 +461,6 @@ All Усе Deselect Зняти виділення Reselect Відновити виділення - Inverse Selection Інвертувати виділення Inverse Інвертувати Color Range… Колірний діапазон… Select and Mask… Виділити та маскувати… @@ -741,8 +739,8 @@ Background Фон Set foreground color Установити колір переднього плану Set background color Установити колір фону - Swap colours (X) Поміняти кольори місцями (X) - Default colours (D) Типові кольори (D) + Switch Foreground and Background Colors (X) Поміняти кольори місцями (X) + Default Foreground and Background Colors (D) Типові кольори (D) Brush Tool Options Параметри пензля Opacity Непрозорість Flow Потік @@ -1695,7 +1693,7 @@ Revert “{name}” to the last saved version? Your changes will be lost. Повернути «{name}» до останньої збереженої версії? Ваші зміни буде втрачено. {key} to subtract {key}, щоб відняти ↑↓ navigate {key} run esc close ↑↓ навігація {key} виконати esc закрити - Click to restore the current colour Клацніть, щоб відновити поточний колір + Click to restore the current color Клацніть, щоб відновити поточний колір Click with the Note tool to add a note. Клацніть інструментом «Нотатка», щоб додати нотатку. Drag a rectangle around the object Намалюйте прямокутник навколо об'єкта Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Перетягніть на зображенні, щоб додати обмеження; Shift для горизонталі/вертикалі; клацніть правою кнопкою на обмеженні, щоб змінити або видалити його. @@ -1777,10 +1775,10 @@ Drag to move the active layer Перетягніть, щоб перемістити активний шар Drag to pan · hold Space with any tool Перетягніть для панорамування · утримуйте пробіл із будь-яким інструментом Drag to draw a gradient Перетягніть, щоб намалювати градієнт - Click to fill similar colours Клацніть, щоб залити подібні кольори + Click to fill similar colors Клацніть, щоб залити подібні кольори Click to add text Клацніть, щоб додати текст Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Перетягування (ласо) або клацання точок (багатокутне) · {add} додати · {sub} відняти - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Намалюйте рамку кадрування · перетягування всередині переміщує · краї змінюють розмір ({ratio} пропорції, {centre} центр) · пробіл переміщує під час малювання · стрілки зсувають · X змінює орієнтацію · {commit} підтверджує · Esc скасовує + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Намалюйте рамку кадрування · перетягування всередині переміщує · краї змінюють розмір ({ratio} пропорції, {centre} центр) · пробіл переміщує під час малювання · стрілки зсувають · X змінює орієнтацію · {commit} підтверджує · Esc скасовує {mode} Color · {bits} bit Колір {mode} · {bits} біт Drag to move the layer Перетягніть, щоб перемістити шар Fit Screen Умістити на екрані @@ -1812,7 +1810,6 @@ Appearance Вигляд Text Position: Положення тексту: Text color Колір тексту - Uses the foreground and background colours. Використовує кольори переднього плану та фону. Answer the unsaved-changes prompt first Спочатку дайте відповідь у діалозі незбережених змін Unsaved changes Незбережені зміни Don't Save Не зберігати @@ -1832,7 +1829,7 @@ name назва new новий Go to Layer Перейти до шару - Open a document to select a colour range. Відкрийте документ, щоб виділити колірний діапазон. + Open a document to select a color range. Відкрийте документ, щоб виділити колірний діапазон. Saved Збережено Reveal in Finder Показати у Finder Show in Explorer Показати у Провіднику @@ -1994,8 +1991,8 @@ Character Styles Panel Панель стилів символів Clear Canvas Guides Очистити напрямні полотна Clear Selected Artboard Guides Очистити напрямні вибраної монтажної області - Color Blindness — Deuteranopia-type Порушення сприйняття кольору — дейтеранопія - Color Blindness — Protanopia-type Порушення сприйняття кольору — протанопія + Color Blindness - Deuteranopia-type Порушення сприйняття кольору - дейтеранопія + Color Blindness - Protanopia-type Порушення сприйняття кольору - протанопія Color Table… Таблиця кольорів… Combine Shapes Об'єднати фігури Contract… Стиснути… @@ -2170,7 +2167,7 @@ Canvas Полотно Capture Зберегти стан Center Crop Marks Центральні мітки обрізання - Centre the gradient (offset 0, 0) Центрувати градієнт (зсув 0, 0) + Center the gradient (offset 0, 0) Центрувати градієнт (зсув 0, 0) Gradient Editor Редактор градієнтів Gradient picker Вибір градієнта Gradient stops Точки градієнта @@ -2327,7 +2324,7 @@ Roughness Шорсткість Roundness Округлість Rulers & Grids Лінійки та сітки - Sample: foreground colour Зразок: колір переднього плану + Sample: foreground color Зразок: колір переднього плану Sampling: Background Swatch Вибірка: зразок фону Sampling: Continuous Вибірка: безперервна Sampling: Once Вибірка: одноразова @@ -2393,6 +2390,7 @@ Allow scripts to connect Дозволити підключення скриптів Always Завжди Always create smart objects when placing Завжди створювати смартоб'єкти під час розміщення + Skip transform when placing Пропускати трансформацію під час розміщення Animated zoom Анімоване масштабування Apply auto tone Застосовувати автоматичну тонову корекцію Ask Запитувати @@ -2586,7 +2584,7 @@ Alt-click to define a source point to clone from Alt+клацання, щоб визначити точку джерела клонування No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Немає контуру для створення виділення: намалюйте його пером або виберіть на панелі контурів. Cancel opening Скасувати відкриття - Cancelled opening {name} Відкриття {name} скасовано + Canceled opening {name} Відкриття {name} скасовано Damaged Photoshop document Пошкоджений документ Photoshop The document “{name}” may be damaged. Документ «{name}», можливо, пошкоджено. Some layers, pixels or masks could not be read. Do you want to continue opening it? Не вдалося прочитати деякі шари, пікселі або маски. Продовжити відкриття? @@ -2596,7 +2594,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. Вбудований колірний профіль документа «{name}» не відповідає поточному робочому простору {mode}. Working: {working} Робочий простір: {working} Developing {name} Обробка {name} - Cancelled {label} Скасовано: {label} + Canceled {label} Скасовано: {label} Esc to cancel Esc для скасування Opened {name} Відкрито: {name} Opening {name} Відкриття {name} @@ -2604,7 +2602,7 @@ Saving {name} Збереження {name} Saving {percent} Збереження {percent} A save to {name} is still running; try again when it finishes Збереження в {name} ще триває; спробуйте ще раз, коли воно завершиться - {label} is writing the file and can no longer be cancelled {label}: триває запис файлу, скасувати вже не можна + {label} is writing the file and can no longer be canceled {label}: триває запис файлу, скасувати вже не можна Opening {name}… Відкриття {name}… Opening… Відкриття… Reading… Читання… @@ -2695,7 +2693,7 @@ cameraRaw Roughness Шорсткість Discard Layers and Save a Copy Відкинути шари та зберегти копію Don't show again Більше не показувати Save failed: {error} Не вдалося зберегти: {error} - Save cancelled Збереження скасовано + Save canceled Збереження скасовано Couldn't place {name}: {error} Не вдалося розмістити {name}: {error} Magnetic Lasso Tool Інструмент «Магнітне ласо» Frequency Частота @@ -2824,7 +2822,7 @@ fontWeight Italic Курсивний Impressionist Імпресіоністичний Rotate View Tool Інструмент «Поворот перегляду» Reset View Скинути перегляд - Drag around the centre to rotate the view · Shift constrains to 15° Перетягніть навколо центру, щоб повернути перегляд · Shift обмежує крок до 15° + Drag around the center to rotate the view · Shift constrains to 15° Перетягніть навколо центру, щоб повернути перегляд · Shift обмежує крок до 15° (coming soon) (незабаром) Add a layer style Додати стиль шару Move effect up Перемістити ефект вгору @@ -3038,7 +3036,7 @@ fontWeight Italic Курсивний Import Brushes… (.abr or image) Імпортувати пензлі… (.abr або зображення) Import Brush from Image… Імпортувати пензель із зображення… System Info Інформація про систему - Click to sample the foreground colour · {key}-click for background Клацання бере зразок переднього плану · {key}+клацання для фону + Click to sample the foreground color · {key}-click for background Клацання бере зразок переднього плану · {key}+клацання для фону Create Warped Text Створити деформований текст Rasterize Smart Object Растеризувати смартоб'єкт Rasterize Fill Content Растеризувати вміст заливки @@ -3705,9 +3703,9 @@ cameraRaw Masking Маскування All Layers No Adjustments Усі шари без коригувань Color to Alpha… Колір у прозорість… Current & Below No Adjustments Поточний і нижчі без коригувань - Not a web colour: click for the nearest web colour Колір поза вебпалітрою: клацніть, щоб вибрати найближчий колір із неї + Not a web color: click for the nearest web color Колір поза вебпалітрою: клацніть, щоб вибрати найближчий колір із неї Now drag the selection onto another area Тепер перетягніть виділення на іншу ділянку - Out of gamut for printing: click for the nearest printable colour Колір поза колірним охопленням друку: клацніть, щоб вибрати найближчий колір, придатний для друку + Out of gamut for printing: click for the nearest printable color Колір поза колірним охопленням друку: клацніть, щоб вибрати найближчий колір, придатний для друку Point Sample Точкова вибірка Sample Size: Розмір вибірки: Show Sampling Ring Показувати кільце вибірки @@ -4015,7 +4013,7 @@ curves Smooth Згладити Auto Add/Delete Автододавання/видалення Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Не вмикайте також дзеркальне відображення в параметрах друку: два відображення скасовують одне одного. Print Settings… Параметри друку… - Remember to turn off the printer's own colour management in Print Settings… Не забудьте вимкнути керування кольором самого принтера в параметрах друку… + Remember to turn off the printer's own color management in Print Settings… Не забудьте вимкнути керування кольором самого принтера в параметрах друку… Sent to {printer} Надіслано на {printer} set in Print Settings… задається в параметрах друку… ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів @@ -4160,12 +4158,12 @@ curves Smooth Згладити This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Щоб продовжити, потрібно растеризувати цей смартоб’єкт. Після цього його вміст більше не можна буде редагувати. Растеризувати смартоб’єкт? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Щоб продовжити, потрібно растеризувати цей шар заливки. Після цього його заливку більше не можна буде редагувати. Растеризувати шар? Demosaic Демозаїк - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Як відновлюється мозаїка кольорового фільтра камери. Застосовується під час відкриття файлу; попередній перегляд показує метод, з яким файл було відкрито. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Як відновлюється мозаїка кольорового фільтра камери. Застосовується під час відкриття файлу; попередній перегляд показує метод, з яким файл було відкрито. AHD (adaptive homogeneity) AHD (адаптивна однорідність) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Хіракава–Паркс: найчистіші краї й найменше кольорової облямівки, найповільніший. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Інтерполяція з корекцією градієнта: різка й швидка, з невеликою кольоровою облямівкою на дрібних деталях. - The fastest and the softest, with colour fringing on fine detail. Найшвидший і найм'якший, з кольоровою облямівкою на дрібних деталях. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Хіракава–Паркс: найчистіші краї й найменше кольорової облямівки, найповільніший. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Інтерполяція з корекцією градієнта: різка й швидка, з невеликою кольоровою облямівкою на дрібних деталях. + The fastest and the softest, with color fringing on fine detail. Найшвидший і найм'якший, з кольоровою облямівкою на дрібних деталях. Memory Usage Використання пам’яті Per-document RAM limit (MB) Ліміт RAM на документ (МБ) Installed RAM: {ram} MB; this limit: {percent}% Встановлено RAM: {ram} МБ; цей ліміт: {percent}% @@ -4317,6 +4315,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Виберіть окремий документ для кожного каналу. A picked document is no longer open. Один із вибраних документів більше не відкрито. A picked document is no longer a grayscale document of the same size. Один із вибраних документів більше не є документом у градаціях сірого того самого розміру. +# Move tool options bar (#11381) + Align top edges Вирівняти верхні краї + Align vertical centers Вирівняти центри по вертикалі + Align bottom edges Вирівняти нижні краї + Distribute vertically Розподілити по вертикалі + Distribute horizontally Розподілити по горизонталі + Show layer bounds on hover Показувати межі шару під час наведення + Expand layer group on click Розгортати групу шарів за клацанням + Show hover bounds from Layers Показувати межі під час наведення з панелі «Шари» +# Artboard tool options bar (#11385) + Distribute Widths Розподілити ширину + Distribute Heights Розподілити висоту + Auto-nest Layers Автоматично вкладати шари + Auto-size Canvas Автоматично змінювати розмір полотна + Keep Relative Position During Layer Reordering Зберігати відносне положення під час зміни порядку шарів + Shrinkwrap Canvas on Save Зменшувати полотно до вмісту під час збереження # JPEG Options: the size the file will have (#7843) Estimated file size Орієнтовний розмір файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4d17280971..7a80ab01a8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -578,7 +578,6 @@ Grow Mở rộng theo màu Horizontal Ngang Huge Cực lớn - Inverse Selection Đảo vùng chọn Isolate Layers Cô lập lớp Language Options Tùy chọn ngôn ngữ Large Lớn @@ -722,8 +721,8 @@ Clear Guides Xóa đường căn Clear Selected Artboard Guides Xóa đường căn artboard đã chọn Clear Slices Xóa lát cắt - Color Blindness — Deuteranopia-type Mù màu — kiểu Deuteranopia - Color Blindness — Protanopia-type Mù màu — kiểu Protanopia + Color Blindness - Deuteranopia-type Mù màu - kiểu Deuteranopia + Color Blindness - Protanopia-type Mù màu - kiểu Protanopia Count Đếm Custom Pixel Aspect Ratio… Tỷ lệ khung pixel tùy chỉnh… D1/DV NTSC (0.91) D1/DV NTSC (0.91) @@ -909,8 +908,8 @@ Custom Shape Tool Công cụ Hình tùy chỉnh Set foreground color Đặt màu nền trước Set background color Đặt màu nền - Swap colours (X) Đổi màu (X) - Default colours (D) Màu mặc định (D) + Switch Foreground and Background Colors (X) Đổi chỗ màu trước và màu sau (X) + Default Foreground and Background Colors (D) Màu trước và màu sau mặc định (D) Edit Toolbar… Sửa thanh công cụ… Edit in Quick Mask Mode (Q) Chỉnh sửa ở chế độ Mặt nạ nhanh (Q) Edit in Standard Mode (Q) Chỉnh sửa ở chế độ chuẩn (Q) @@ -1032,9 +1031,9 @@ Drag to move the active layer Kéo để di chuyển lớp đang chọn Drag to pan · hold Space with any tool Kéo để xem toàn cảnh · giữ Space với mọi công cụ Drag to draw a gradient Kéo để vẽ chuyển sắc - Click to fill similar colours Bấm để tô các màu tương tự + Click to fill similar colors Bấm để tô các màu tương tự Click to add text Bấm để thêm chữ - Click to sample the foreground colour · {key}-click for background Bấm để lấy mẫu màu nền trước · {key}-bấm cho nền + Click to sample the foreground color · {key}-click for background Bấm để lấy mẫu màu nền trước · {key}-bấm cho nền Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Bấm để phóng to · {key}-bấm để thu nhỏ · kéo phải/trái để thu phóng Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Kéo hoặc bấm điểm đa giác · giữ Alt khi Lasso để có đoạn thẳng · {add} thêm · {sub} trước khi vẽ sẽ trừ Hold Alt while drawing for straight segments Giữ Alt khi vẽ để có đoạn thẳng @@ -1111,7 +1110,6 @@ Release Clipping Mask Nhả mặt nạ cắt Merge Down Gộp xuống Merge Group Gộp nhóm - Quick Export As PNG Xuất nhanh dạng PNG Rename Layer… Đổi tên lớp… Frame from Layers… Frame từ các lớp… Create new document from current state Tạo tài liệu mới từ trạng thái hiện tại @@ -1364,7 +1362,7 @@ Diamond Hình thoi Align with layer Căn với lớp Reset Alignment Đặt lại căn chỉnh - Centre the gradient (offset 0, 0) Căn giữa chuyển sắc (dịch lệch 0, 0) + Center the gradient (offset 0, 0) Căn giữa chuyển sắc (dịch lệch 0, 0) The current gradient (pick one in Window › Gradients) Chuyển sắc hiện tại (chọn trong Cửa sổ › Chuyển sắc) Click to edit the gradient Bấm để chỉnh chuyển sắc Create new gradient Tạo chuyển sắc mới @@ -1703,7 +1701,7 @@ cameraRaw Shadows Vùng tối Manage submitted jobs in the system print queue Quản lý các lệnh in đã gửi trong hàng đợi in của hệ thống Esc to cancel Esc để hủy Cancel opening Hủy mở tệp - Cancelled opening {name} Đã hủy mở {name} + Canceled opening {name} Đã hủy mở {name} Damaged Photoshop document Tài liệu Photoshop bị hỏng The document “{name}” may be damaged. Tài liệu “{name}” có thể đã bị hỏng. Some layers, pixels or masks could not be read. Do you want to continue opening it? Không thể đọc một số lớp, pixel hoặc mặt nạ. Bạn có muốn tiếp tục mở không? @@ -1712,10 +1710,10 @@ cameraRaw Shadows Vùng tối The document “{name}” does not have an embedded {mode} profile. Tài liệu “{name}” không có hồ sơ {mode} nhúng. The document “{name}” has an embedded color profile that does not match the current {mode} working space. Tài liệu “{name}” có hồ sơ màu nhúng không khớp với không gian làm việc {mode} hiện tại. Working: {working} Không gian làm việc: {working} - Cancelled {label} Đã hủy {label} + Canceled {label} Đã hủy {label} Cancel transform (Esc) Hủy biến đổi (Esc) Cancel warp (Esc) Hủy biến dạng (Esc) - Save cancelled Đã hủy lưu + Save canceled Đã hủy lưu Spell check complete. Đã kiểm tra chính tả xong. Save failed: {error} Không thể lưu: {error} Couldn't place {name}: {error} Không thể đặt {name}: {error} @@ -2057,11 +2055,11 @@ document Orientation Hướng trang Eyedropper Ống hút màu Add to Sample Thêm vào mẫu Subtract from Sample Bớt khỏi mẫu - Sample: foreground colour Mẫu: màu nền trước + Sample: foreground color Mẫu: màu nền trước {added}, {removed} subtracted {added}, đã bớt {removed} Clear Samples Xóa mẫu Selection Vùng chọn - Open a document to select a colour range. Mở một tài liệu để chọn phạm vi màu. + Open a document to select a color range. Mở một tài liệu để chọn phạm vi màu. Sampled Colors Màu lấy mẫu Reds Đỏ Yellows Vàng @@ -2126,7 +2124,7 @@ layers Fill: Độ tô: Channels: Kênh: Click a red pupil to neutralize it Nhấp vào đồng tử đỏ để trung hòa Click to pick · Esc to cancel Nhấp để chọn · Esc để hủy - Click to restore the current colour Nhấp để khôi phục màu hiện tại + Click to restore the current color Nhấp để khôi phục màu hiện tại Clone source {n} ({key}-click with Clone Stamp to set) Nguồn nhân bản {n} ({key}+nhấp bằng Dấu nhân bản để đặt) Color Picker (Layer Style Color) Ống hút màu (Màu kiểu lớp) Color Picker (Text Color) Ống hút màu (Màu chữ) @@ -2182,13 +2180,13 @@ layers Fill: Độ tô: No subject found — try a rectangle around the object Không tìm thấy chủ thể — thử khung chữ nhật quanh đối tượng No subject found — try Object Selection or the Lasso Không tìm thấy chủ thể — thử Chọn đối tượng hoặc Lasso No tool presets. Không có thiết lập sẵn công cụ. - Not a web colour: click for the nearest web colour Không phải màu web: nhấp để lấy màu web gần nhất + Not a web color: click for the nearest web color Không phải màu web: nhấp để lấy màu web gần nhất Now drag the selection onto another area Bây giờ kéo vùng chọn sang vùng khác Object Selection found nothing there — try a tighter rectangle Chọn đối tượng không tìm thấy gì — thử khung chữ nhật chặt hơn Only Web Colors Chỉ màu web Open paths use centered strokes Đường dẫn mở dùng nét căn giữa Option-click to define a source point to clone from Option+nhấp để chỉ định điểm nguồn nhân bản - Out of gamut for printing: click for the nearest printable colour Ngoài gamut in: nhấp để lấy màu in được gần nhất + Out of gamut for printing: click for the nearest printable color Ngoài gamut in: nhấp để lấy màu in được gần nhất Pick screen color Lấy màu màn hình Pick Color From Image Lấy màu từ hình ảnh Point Sample Mẫu điểm @@ -2231,7 +2229,7 @@ layers Fill: Độ tô: Unavailable in this color mode Không dùng được ở chế độ màu này Update the current brush with these settings Cập nhật cọ hiện tại với các thiết lập này Use finite lengths and a positive pattern total Dùng độ dài hữu hạn và tổng họa tiết dương - Uses the foreground and background colours. Dùng màu nền trước và màu nền sau. + Uses the foreground and background colors. Dùng màu nền trước và màu nền sau. Weight Độ dày Zoom in Phóng to Zoom out Thu nhỏ @@ -2318,7 +2316,7 @@ layers Fill: Độ tô: Untagged {mode} {mode} chưa gắn hồ sơ Use File › Open, or paste a copied image with {paste}. Dùng Tệp › Mở, hoặc dán ảnh đã sao chép bằng {paste}. Vector Mask from Current Path Mặt nạ vector từ đường dẫn hiện tại - {label} is writing the file and can no longer be cancelled {label} đang ghi tệp và không thể hủy nữa + {label} is writing the file and can no longer be canceled {label} đang ghi tệp và không thể hủy nữa {name} options Tùy chọn {name} {n} commands are not in PhotoCraft. {n} lệnh không có trong PhotoCraft. {size} (was {old}) {size} (trước là {old}) @@ -2764,6 +2762,7 @@ shape Appearance Diện mạo Allow agent control Cho phép agent điều khiển Allow scripts to connect Cho phép script kết nối Always create smart objects when placing Luôn tạo đối tượng thông minh khi đặt + Skip transform when placing Bỏ qua biến đổi khi đặt Animated zoom Thu phóng có chuyển động Apply auto tone Áp dụng tự động tông Auto collapse icon panels Tự động thu gọn các bảng biểu tượng @@ -2907,7 +2906,7 @@ fontWeight ExtraBold Rất đậm fontWeight Black Đen fontWeight Italic Nghiêng Rotate View Tool Công cụ xoay khung nhìn - Drag around the centre to rotate the view · Shift constrains to 15° Kéo vòng quanh tâm để xoay khung nhìn · Shift giới hạn ở 15° + Drag around the center to rotate the view · Shift constrains to 15° Kéo vòng quanh tâm để xoay khung nhìn · Shift giới hạn ở 15° Transparency Threshold Ngưỡng trong suốt Opacity Threshold Ngưỡng độ mờ Rasterize svg groups deeper than Raster hoá các nhóm svg sâu hơn @@ -2954,7 +2953,7 @@ fontWeight Italic Nghiêng Dash Nét đứt Gap Khoảng hở {mode} Color · {bits} bit Màu {mode} · {bits} bit - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Kéo hộp cắt · kéo bên trong để di chuyển · cạnh để đổi kích thước ({ratio} tỉ lệ, {centre} giữa) · Space di chuyển khi đang vẽ · phím mũi tên dịch nhẹ · X đổi chiều · {commit} chốt · Esc huỷ + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Kéo hộp cắt · kéo bên trong để di chuyển · cạnh để đổi kích thước ({ratio} tỉ lệ, {centre} giữa) · Space di chuyển khi đang vẽ · phím mũi tên dịch nhẹ · X đổi chiều · {commit} chốt · Esc huỷ Camera Data Dữ liệu máy ảnh cameraData Make Hãng sản xuất cameraData Model Kiểu máy @@ -3781,7 +3780,7 @@ curves Smooth Làm mượt Auto Add/Delete Tự động thêm/xóa Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Đừng bật thêm Ảnh phản chiếu trong thiết lập in: hai lần lật sẽ triệt tiêu nhau. Print Settings… Thiết lập in… - Remember to turn off the printer's own colour management in Print Settings… Nhớ tắt quản lý màu riêng của máy in trong thiết lập in… + Remember to turn off the printer's own color management in Print Settings… Nhớ tắt quản lý màu riêng của máy in trong thiết lập in… 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 @@ -3942,12 +3941,12 @@ curves Smooth Làm mượt Decrease Brush Hardness Giảm độ cứng của cọ Increase Brush Hardness Tăng độ cứng của cọ Demosaic Giải khảm - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Cách lấp đầy khảm lọc màu của máy ảnh. Áp dụng khi mở tệp; bản xem trước hiển thị phương pháp đã dùng khi mở. + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Cách lấp đầy khảm lọc màu của máy ảnh. Áp dụng khi mở tệp; bản xem trước hiển thị phương pháp đã dùng khi mở. AHD (adaptive homogeneity) AHD (đồng nhất thích ứng) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks: cạnh sạch nhất và ít viền màu nhất, chậm nhất. - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. Nội suy hiệu chỉnh gradient: sắc nét và nhanh, có chút viền màu ở chi tiết nhỏ. - The fastest and the softest, with colour fringing on fine detail. Nhanh nhất và mềm nhất, có viền màu ở chi tiết nhỏ. + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks: cạnh sạch nhất và ít viền màu nhất, chậm nhất. + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. Nội suy hiệu chỉnh gradient: sắc nét và nhanh, có chút viền màu ở chi tiết nhỏ. + The fastest and the softest, with color fringing on fine detail. Nhanh nhất và mềm nhất, có viền màu ở chi tiết nhỏ. “{name}” already exists. Replace it? “{name}” đã tồn tại. Thay thế? The name in the save dialog was “{name}”. Tên trong hộp thoại lưu là “{name}”. Previous Brush Cọ trước @@ -4110,6 +4109,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Chọn một tài liệu khác cho mỗi kênh. A picked document is no longer open. Một tài liệu đã chọn không còn mở. A picked document is no longer a grayscale document of the same size. Một tài liệu đã chọn không còn là tài liệu thang xám cùng kích thước. +# Move tool options bar (#11381) + Align top edges Căn các cạnh trên + Align vertical centers Căn các tâm dọc + Align bottom edges Căn các cạnh dưới + Distribute vertically Phân bố theo chiều dọc + Distribute horizontally Phân bố theo chiều ngang + Show layer bounds on hover Hiện ranh giới lớp khi di chuột + Expand layer group on click Mở rộng nhóm lớp khi nhấp + Show hover bounds from Layers Hiện ranh giới khi di chuột từ bảng Lớp +# Artboard tool options bar (#11385) + Distribute Widths Phân bố chiều rộng + Distribute Heights Phân bố chiều cao + Auto-nest Layers Tự động lồng các lớp + Auto-size Canvas Tự động đổi kích thước vùng vẽ + Keep Relative Position During Layer Reordering Giữ vị trí tương đối khi sắp xếp lại lớp + Shrinkwrap Canvas on Save Thu nhỏ vùng vẽ theo nội dung khi lưu # JPEG Options: the size the file will have (#7843) Estimated file size Kích thước tệp ước tính diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7cc21370d3..5eadcf4b62 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -643,7 +643,6 @@ Deselect 取消选择 Reselect 重新选择 Inverse 反向 - Inverse Selection 反选选区 Similar 选择相似 Color Range… 色彩范围… Focus Area… 焦点区域… @@ -764,8 +763,8 @@ Legacy Macintosh RGB (Gamma 1.8) 旧版 Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) 互联网标准 RGB (sRGB) Monitor RGB 显示器 RGB - Color Blindness — Protanopia-type 色盲 — 红色盲型 - Color Blindness — Deuteranopia-type 色盲 — 绿色盲型 + Color Blindness - Protanopia-type 色盲 - 红色盲型 + Color Blindness - Deuteranopia-type 色盲 - 绿色盲型 Zoom In 放大 Zoom Out 缩小 Fit on Screen 适合屏幕 @@ -1102,7 +1101,7 @@ Click to add a point · drag off or ⌘/Ctrl-click or Delete to remove 单击添加点 · 拖离、按 ⌘/Ctrl 单击或按 Delete 移除 Click to apply, ⌥-click to clear overrides, double-click for Style Options 单击应用,按 ⌥ 单击清除覆盖设置,双击打开样式选项 Click to edit the gradient 单击编辑渐变 - Click to restore the current colour 单击恢复当前颜色 + Click to restore the current color 单击恢复当前颜色 Click to zoom in · ⌥-click to zoom out 单击放大 · 按 ⌥ 单击缩小 Click with the Note tool to add a note. 使用注释工具单击以添加注释。 Click: corner · Drag: smooth · Click first point: close · ↩ finish · Esc cancel 单击:角点 · 拖动:平滑点 · 单击起点:闭合 · ↩ 完成 · Esc 取消 @@ -1189,7 +1188,7 @@ Darks 暗部 Data Sets 数据组 Default 默认 - Default colours (D) 默认颜色(D) + Default Foreground and Background Colors (D) 默认颜色(D) Default printer 默认打印机 Default restored. 已恢复默认值。 Define 定义 @@ -1477,7 +1476,7 @@ Opacity Jitter 不透明度抖动 Opacity: 不透明度: Open a document to define variables. 打开文档以定义变量。 - Open a document to select a colour range. 打开文档以选择色彩范围。 + Open a document to select a color range. 打开文档以选择色彩范围。 Open a document to use the timeline. 打开文档以使用时间轴。 Open… ⌘O 打开… ⌘O Optical 视觉 @@ -1554,7 +1553,6 @@ Purity 纯度 Quality 品质 Quick Actions 快速操作 - Quick Export As PNG 快速导出为 PNG Radial Gradient 径向渐变 Radius 半径 Radius: 半径: @@ -1699,7 +1697,7 @@ Subtract from Sample 从采样中减去 Subtract from selection (⌥) 从选区中减去 (⌥) Suggestions: 建议: - Swap colours (X) 交换颜色 (X) + Switch Foreground and Background Colors (X) 交换颜色 (X) Swaps height and width 交换高度和宽度 Switch between free transform and warp modes 在自由变换和变形模式之间切换 Switch theme 切换主题 @@ -1807,7 +1805,7 @@ Choke 收缩 Classic 经典 Click to add text 单击以添加文字 - Click to fill similar colours 单击以填充相近颜色 + Click to fill similar colors 单击以填充相近颜色 Clone Stamp Tool 仿制图章工具 Color Burn 颜色加深 Color Dodge 颜色减淡 @@ -1971,7 +1969,7 @@ Rectangular Marquee Tool 矩形选框工具 Reds 红色 Reflected 对称 - Sample: foreground colour 采样:前景色 + Sample: foreground color 采样:前景色 Sampled Colors 采样颜色 Satin 光泽 Save Pixel Aspect Ratio 保存像素长宽比 @@ -2012,7 +2010,6 @@ Triangle Tool 三角形工具 Up 向上 Unsaved changes 未保存的更改 - Uses the foreground and background colours. 使用前景色和背景色。 Watercolour look: lighter interior, darker rims. 水彩效果:内部较浅,边缘较深。 Web Web Web Large Web 大尺寸 @@ -2049,6 +2046,7 @@ Allow scripts to connect 允许脚本连接 Always 始终 Always create smart objects when placing 置入时始终创建智能对象 + Skip transform when placing 置入时跳过变换 Animated zoom 动画缩放 Apply auto tone 应用自动色调 Ask 询问 @@ -2339,7 +2337,7 @@ cameraRaw Blending 混合 Graphics 图形 Reset GPU Backend 重置 GPU 后端 Applies at next launch. 下次启动时生效。 - Click to sample the foreground colour · {key}-click for background 单击拾取前景色 · 按 {key} 单击拾取背景色 + Click to sample the foreground color · {key}-click for background 单击拾取前景色 · 按 {key} 单击拾取背景色 {key}-click to set the source 按 {key} 单击设置源点 {key} to subtract 按 {key} 从选区中减去 Clone source {n} ({key}-click with Clone Stamp to set) 仿制源 {n}(使用仿制图章时按 {key} 单击设置) @@ -2398,7 +2396,7 @@ cameraRaw Blending 混合 Gradient Options 渐变选项 Align with layer 与图层对齐 Reset Alignment 重置对齐 - Centre the gradient (offset 0, 0) 将渐变居中(偏移量 0, 0) + Center the gradient (offset 0, 0) 将渐变居中(偏移量 0, 0) Gradient Editor 渐变编辑器 Gradient picker 渐变拾色器 Save As Preset 存储为预设 @@ -2430,7 +2428,7 @@ cameraRaw Blending 混合 Vulkan Vulkan No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 没有可用于生成选区的路径:请用钢笔工具绘制路径,或在路径面板中选择路径。 Cancel opening 取消打开 - Cancelled opening {name} 已取消打开 {name} + Canceled opening {name} 已取消打开 {name} Damaged Photoshop document 已损坏的 Photoshop 文档 The document “{name}” may be damaged. 文档“{name}”可能已损坏。 Some layers, pixels or masks could not be read. Do you want to continue opening it? 无法读取某些图层、像素或蒙版。是否继续打开? @@ -2440,7 +2438,7 @@ cameraRaw Blending 混合 The document “{name}” has an embedded color profile that does not match the current {mode} working space. 文档“{name}”嵌入的颜色配置文件与当前的 {mode} 工作空间不匹配。 Working: {working} 工作空间:{working} Developing {name} 正在处理 {name} - Cancelled {label} 已取消 {label} + Canceled {label} 已取消 {label} Esc to cancel 按 Esc 取消 Opened {name} 已打开 {name} Opening {name} 正在打开 {name} @@ -2448,7 +2446,7 @@ cameraRaw Blending 混合 Saving {name} 正在保存 {name} Saving {percent} 正在保存 {percent} A save to {name} is still running; try again when it finishes 仍在保存到 {name};请在完成后重试 - {label} is writing the file and can no longer be cancelled {label} 正在写入文件,已无法取消 + {label} is writing the file and can no longer be canceled {label} 正在写入文件,已无法取消 Opening {name}… 正在打开 {name}… Opening… 正在打开… Reading… 正在读取… @@ -2498,7 +2496,7 @@ cameraRaw Blending 混合 Discard Layers and Save a Copy 扔掉图层并存储副本 Don't show again 不再显示 Save failed: {error} 存储失败:{error} - Save cancelled 已取消存储 + Save canceled 已取消存储 Magnetic Lasso Tool 磁性套索工具 Frequency 频率 Use tablet pressure to change pen width 使用绘图板压力以更改钢笔宽度 @@ -2632,7 +2630,7 @@ fontWeight Italic 斜体 Rotate View 旋转视图 Rotate View Tool 旋转视图工具 Reset View 重置视图 - Drag around the centre to rotate the view · Shift constrains to 15° 绕中心拖动以旋转视图 · Shift 限制为 15° + Drag around the center to rotate the view · Shift constrains to 15° 绕中心拖动以旋转视图 · Shift 限制为 15° Dual Axis 双轴 Diagonal 对角线 Transform Symmetry 变换对称轴 @@ -2647,8 +2645,8 @@ fontWeight Italic 斜体 All Layers No Adjustments 所有图层(不含调整) Current & Below No Adjustments 当前及下方图层(不含调整) Show Sampling Ring 显示采样环 - Out of gamut for printing: click for the nearest printable colour 超出打印色域:单击使用最接近的可打印颜色 - Not a web colour: click for the nearest web colour 不是 Web 颜色:单击使用最接近的 Web 颜色 + Out of gamut for printing: click for the nearest printable color 超出打印色域:单击使用最接近的可打印颜色 + Not a web color: click for the nearest web color 不是 Web 颜色:单击使用最接近的 Web 颜色 Color to Alpha… 颜色转为 Alpha… Transparency Threshold 透明度阈值 Opacity Threshold 不透明度阈值 @@ -2742,7 +2740,7 @@ fontWeight Italic 斜体 How often fastening points are placed by themselves 自动放置紧固点的频率 Scrubby Zoom 细微缩放 {mode} Color · {bits} bit {mode} 颜色 · {bits} 位 - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 拖移绘制裁剪框 · 在框内拖移以移动 · 拖移边缘调整大小({ratio} 比例,{centre} 中心)· 绘制时按 Space 移动 · 方向键微移 · X 切换方向 · {commit} 确认 · Esc 取消 + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 拖移绘制裁剪框 · 在框内拖移以移动 · 拖移边缘调整大小({ratio} 比例,{centre} 中心)· 绘制时按 Space 移动 · 方向键微移 · X 切换方向 · {commit} 确认 · Esc 取消 Appearance Settings… 外观设置… Add to favorites 添加到收藏 Remove from favorites 从收藏中移除 @@ -2969,7 +2967,7 @@ curves Smooth 平滑 Auto Add/Delete 自动添加/删除 Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 不要同时勾选打印设置中的镜像:两次翻转会相互抵消。 Print Settings… 打印设置… - Remember to turn off the printer's own colour management in Print Settings… 请记得在打印设置中关闭打印机自身的色彩管理… + Remember to turn off the printer's own color management in Print Settings… 请记得在打印设置中关闭打印机自身的色彩管理… Sent to {printer} 已发送到 {printer} set in Print Settings… 在打印设置中设置… ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 @@ -3112,12 +3110,12 @@ curves Smooth 平滑 Decrease Brush Hardness 减小画笔硬度 Increase Brush Hardness 增大画笔硬度 Demosaic 去马赛克 - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. 如何填补相机彩色滤镜阵列的马赛克。在打开文件时应用;预览显示打开时所用的方法。 + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. 如何填补相机彩色滤镜阵列的马赛克。在打开文件时应用;预览显示打开时所用的方法。 AHD (adaptive homogeneity) AHD(自适应同质性) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks:边缘最干净、色边最少,速度最慢。 - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. 梯度校正插值:锐利且快速,细节处有些许色边。 - The fastest and the softest, with colour fringing on fine detail. 最快也最柔和,细节处有色边。 + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks:边缘最干净、色边最少,速度最慢。 + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. 梯度校正插值:锐利且快速,细节处有些许色边。 + The fastest and the softest, with color fringing on fine detail. 最快也最柔和,细节处有色边。 “{name}” already exists. Replace it? “{name}”已存在。要替换它吗? The name in the save dialog was “{name}”. 存储对话框中的名称是“{name}”。 Previous Brush 上一个画笔 @@ -3298,6 +3296,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 请为每个通道选择不同的文档。 A picked document is no longer open. 所选的一个文档已不再打开。 A picked document is no longer a grayscale document of the same size. 所选的一个文档已不再是同样大小的灰度文档。 +# Move tool options bar (#11381) + Align top edges 顶端对齐 + Align vertical centers 垂直居中对齐 + Align bottom edges 底端对齐 + Distribute vertically 垂直分布 + Distribute horizontally 水平分布 + Show layer bounds on hover 悬停时显示图层边界 + Expand layer group on click 单击时展开图层组 + Show hover bounds from Layers 显示来自图层面板的悬停边界 +# Artboard tool options bar (#11385) + Distribute Widths 分布宽度 + Distribute Heights 分布高度 + Auto-nest Layers 自动嵌套图层 + Auto-size Canvas 自动调整画布大小 + Keep Relative Position During Layer Reordering 重新排列图层时保持相对位置 + Shrinkwrap Canvas on Save 保存时将画布缩至内容大小 # JPEG Options: the size the file will have (#7843) Estimated file size 预计文件大小 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bc2b8b9557..07bdba95c7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -642,7 +642,6 @@ Deselect 取消選取 Reselect 重新選取 Inverse 反轉 - Inverse Selection 反轉選取範圍 Similar 相近色 Color Range… 顏色範圍… Focus Area… 焦點區域… @@ -763,8 +762,8 @@ Legacy Macintosh RGB (Gamma 1.8) 舊版 Macintosh RGB (Gamma 1.8) Internet Standard RGB (sRGB) 網際網路標準 RGB (sRGB) Monitor RGB 顯示器 RGB - Color Blindness — Protanopia-type 色盲 — 紅色盲型 - Color Blindness — Deuteranopia-type 色盲 — 綠色盲型 + Color Blindness - Protanopia-type 色盲 - 紅色盲型 + Color Blindness - Deuteranopia-type 色盲 - 綠色盲型 Zoom In 放大顯示 Zoom Out 縮小顯示 Fit on Screen 顯示全頁 @@ -1085,7 +1084,7 @@ Click to add a point · drag off or {key}-click or Delete to remove 按一下新增點 · 拖出、{key}+按一下或按 Delete 以移除 Click to apply, {key}-click to clear overrides, double-click for Style Options 按一下套用,{key}+按一下清除覆寫,連按兩下開啟樣式選項 Click to edit the gradient 按一下以編輯漸層 - Click to restore the current colour 按一下以還原目前顏色 + Click to restore the current color 按一下以還原目前顏色 Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out 按一下放大 · {key}+按一下縮小 · 向右/向左拖曳以放大/縮小 Click with the Note tool to add a note. 使用註解工具按一下以新增註解。 Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel 按一下:轉角 · 拖曳:平滑 · 按一下第一點:閉合 · {key} 完成 · Esc 取消 @@ -1172,7 +1171,7 @@ Darks 暗部 Data Sets 資料組 Default 預設 - Default colours (D) 預設顏色 (D) + Default Foreground and Background Colors (D) 預設顏色 (D) Default printer 預設印表機 Default restored. 已還原預設值。 Define 定義 @@ -1455,7 +1454,7 @@ Opacity Jitter 不透明度快速變換 Opacity: 不透明度: Open a document to define variables. 請開啟文件以定義變數。 - Open a document to select a colour range. 請開啟文件以選取顏色範圍。 + Open a document to select a color range. 請開啟文件以選取顏色範圍。 Open a document to use the timeline. 請開啟文件以使用時間軸。 Optical 視覺 Optimized 最佳化 @@ -1531,7 +1530,6 @@ Purity 純度 Quality 品質 Quick Actions 快速動作 - Quick Export As PNG 快速匯出為 PNG Radial Gradient 放射狀漸層 Radius 半徑 Radius: 半徑: @@ -1675,7 +1673,7 @@ Subtract from Sample 從樣本中減去 Subtract from selection ({key}) 從選取範圍減去 ({key}) Suggestions: 建議: - Swap colours (X) 切換顏色 (X) + Switch Foreground and Background Colors (X) 切換顏色 (X) Swaps height and width 交換高度和寬度 Switch between free transform and warp modes 在任意變形和彎曲模式間切換 Switch theme 切換主題 @@ -1780,7 +1778,7 @@ Choke 收縮 Classic 經典 Click to add text 按一下以新增文字 - Click to fill similar colours 按一下以填滿相近顏色 + Click to fill similar colors 按一下以填滿相近顏色 Clone Stamp Tool 仿製印章工具 Color Burn 加深顏色 Color Dodge 加亮顏色 @@ -1941,7 +1939,7 @@ Rectangular Marquee Tool 矩形選取畫面工具 Reds 紅色 Reflected 反射 - Sample: foreground colour 取樣:前景色 + Sample: foreground color 取樣:前景色 Sampled Colors 取樣的顏色 Satin 緞面 Save Pixel Aspect Ratio 儲存像素外觀比例 @@ -1980,7 +1978,7 @@ Transfer 轉換 Triangle Tool 三角形工具 Unsaved changes 未儲存的變更 - Uses the foreground and background colours. 使用前景色和背景色。 + Uses the foreground and background colors. 使用前景色和背景色。 Web 網頁 Web Large 網頁 (大) Web Minimum 網頁 (最小) @@ -2017,6 +2015,7 @@ Allow scripts to connect 允許指令碼連線 Always 一律 Always create smart objects when placing 置入時一律建立智慧型物件 + Skip transform when placing 置入時略過變形 Animated zoom 動畫縮放 Apply auto tone 套用自動色調 Ask 詢問 @@ -2252,7 +2251,7 @@ Graphics 圖形 Reset GPU Backend 重設 GPU 後端 Applies at next launch. 下次啟動時套用。 - Click to sample the foreground colour · {key}-click for background 按一下以取樣前景色 · {key}+按一下取樣背景色 + Click to sample the foreground color · {key}-click for background 按一下以取樣前景色 · {key}+按一下取樣背景色 {key}-click to set the source {key}+按一下以設定來源 {key} to subtract 按 {key} 以減去 Clone source {n} ({key}-click with Clone Stamp to set) 仿製來源 {n} (使用仿製印章時 {key}+按一下以設定) @@ -2314,7 +2313,7 @@ Gradient Options 漸層選項 Align with layer 與圖層對齊 Reset Alignment 重設對齊 - Centre the gradient (offset 0, 0) 置中漸層 (位移 0, 0) + Center the gradient (offset 0, 0) 置中漸層 (位移 0, 0) Gradient Editor 漸層編輯器 Gradient picker 漸層挑選器 Save As Preset 儲存為預設 @@ -2347,7 +2346,7 @@ Alt-click to define a source point to clone from 按 Alt 鍵並按一下以定義仿製來源點 No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 沒有可用來建立選取範圍的路徑:請使用鋼筆工具繪製,或在路徑面板中選取一個路徑。 Cancel opening 取消開啟 - Cancelled opening {name} 已取消開啟 {name} + Canceled opening {name} 已取消開啟 {name} Damaged Photoshop document 已損毀的 Photoshop 文件 The document “{name}” may be damaged. 文件「{name}」可能已損毀。 Some layers, pixels or masks could not be read. Do you want to continue opening it? 無法讀取部分圖層、像素或遮色片。是否繼續開啟? @@ -2357,7 +2356,7 @@ The document “{name}” has an embedded color profile that does not match the current {mode} working space. 文件「{name}」嵌入的色彩描述檔與目前的 {mode} 工作空間不符。 Working: {working} 工作空間:{working} Developing {name} 正在處理 {name} - Cancelled {label} 已取消 {label} + Canceled {label} 已取消 {label} Esc to cancel 按 Esc 取消 Opened {name} 已開啟 {name} Opening {name} 正在開啟 {name} @@ -2365,7 +2364,7 @@ Saving {name} 正在儲存 {name} Saving {percent} 正在儲存 {percent} A save to {name} is still running; try again when it finishes 仍在儲存到 {name};請在完成後再試一次 - {label} is writing the file and can no longer be cancelled {label} 正在寫入檔案,已無法取消 + {label} is writing the file and can no longer be canceled {label} 正在寫入檔案,已無法取消 Opening {name}… 正在開啟 {name}… Opening… 正在開啟… Reading… 正在讀取… @@ -2445,7 +2444,7 @@ cameraRaw Blending 混合 Discard Layers and Save a Copy 放棄圖層並儲存拷貝 Don't show again 不再顯示 Save failed: {error} 儲存失敗:{error} - Save cancelled 已取消儲存 + Save canceled 已取消儲存 Magnetic Lasso Tool 磁性套索工具 Frequency 頻率 Use tablet pressure to change pen width 使用繪圖板壓力以變更鋼筆寬度 @@ -2579,7 +2578,7 @@ fontWeight Italic 斜體 Rotate View 旋轉檢視 Rotate View Tool 旋轉檢視工具 Reset View 重設檢視 - Drag around the centre to rotate the view · Shift constrains to 15° 繞中心拖曳以旋轉檢視 · Shift 限制為 15° + Drag around the center to rotate the view · Shift constrains to 15° 繞中心拖曳以旋轉檢視 · Shift 限制為 15° Dual Axis 雙軸 Diagonal 對角線 Transform Symmetry 變形對稱軸 @@ -2594,8 +2593,8 @@ fontWeight Italic 斜體 All Layers No Adjustments 所有圖層(不含調整) Current & Below No Adjustments 目前及以下(不含調整) Show Sampling Ring 顯示取樣環 - Out of gamut for printing: click for the nearest printable colour 超出列印色域:按一下以使用最接近的可列印顏色 - Not a web colour: click for the nearest web colour 不是網頁顏色:按一下以使用最接近的網頁顏色 + Out of gamut for printing: click for the nearest printable color 超出列印色域:按一下以使用最接近的可列印顏色 + Not a web color: click for the nearest web color 不是網頁顏色:按一下以使用最接近的網頁顏色 Color to Alpha… 顏色轉為 Alpha… Transparency Threshold 透明度臨界值 Opacity Threshold 不透明度臨界值 @@ -2689,7 +2688,7 @@ fontWeight Italic 斜體 How often fastening points are placed by themselves 自動放置固定點的頻率 Scrubby Zoom 細微縮放 {mode} Color · {bits} bit {mode} 色彩 · {bits} 位元 - Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 拖移繪製裁切框 · 在框內拖移以移動 · 拖移邊緣調整大小({ratio} 比例,{centre} 中心)· 繪製時按 Space 移動 · 方向鍵微移 · X 切換方向 · {commit} 確認 · Esc 取消 + Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} center) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 拖移繪製裁切框 · 在框內拖移以移動 · 拖移邊緣調整大小({ratio} 比例,{centre} 中心)· 繪製時按 Space 移動 · 方向鍵微移 · X 切換方向 · {commit} 確認 · Esc 取消 Appearance Settings… 外觀設定… Add to favorites 加入最愛 Remove from favorites 從最愛移除 @@ -2930,7 +2929,7 @@ curves Smooth 平滑 Auto Add/Delete 自動增加/刪除 Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 請勿同時勾選列印設定中的鏡像:兩次翻轉會互相抵消。 Print Settings… 列印設定… - Remember to turn off the printer's own colour management in Print Settings… 請記得在列印設定中關閉印表機本身的色彩管理… + Remember to turn off the printer's own color management in Print Settings… 請記得在列印設定中關閉印表機本身的色彩管理… Sent to {printer} 已傳送至 {printer} set in Print Settings… 在列印設定中設定… ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 @@ -3073,12 +3072,12 @@ curves Smooth 平滑 Decrease Brush Hardness 降低筆刷硬度 Increase Brush Hardness 提高筆刷硬度 Demosaic 去馬賽克 - How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. 如何填補相機彩色濾鏡陣列的馬賽克。在開啟檔案時套用;預覽顯示開啟時所用的方法。 + How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. 如何填補相機彩色濾鏡陣列的馬賽克。在開啟檔案時套用;預覽顯示開啟時所用的方法。 AHD (adaptive homogeneity) AHD(自適應同質性) Malvar–He–Cutler Malvar–He–Cutler - Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest. Hirakawa–Parks:邊緣最乾淨、色邊最少,速度最慢。 - Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail. 梯度校正插值:銳利且快速,細節處有些許色邊。 - The fastest and the softest, with colour fringing on fine detail. 最快也最柔和,細節處有色邊。 + Hirakawa–Parks: the cleanest edges and the least color fringing, the slowest. Hirakawa–Parks:邊緣最乾淨、色邊最少,速度最慢。 + Gradient-corrected interpolation: sharp and fast, with some color fringing on fine detail. 梯度校正插值:銳利且快速,細節處有些許色邊。 + The fastest and the softest, with color fringing on fine detail. 最快也最柔和,細節處有色邊。 “{name}” already exists. Replace it? 「{name}」已存在。要取代它嗎? The name in the save dialog was “{name}”. 儲存對話框中的名稱是「{name}」。 Previous Brush 上一個筆刷 @@ -3254,6 +3253,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 請為每個色版選擇不同的文件。 A picked document is no longer open. 所選的一個文件已不再開啟。 A picked document is no longer a grayscale document of the same size. 所選的一個文件已不再是相同大小的灰階文件。 +# Move tool options bar (#11381) + Align top edges 對齊頂端 + Align vertical centers 垂直置中對齊 + Align bottom edges 對齊底端 + Distribute vertically 垂直分佈 + Distribute horizontally 水平分佈 + Show layer bounds on hover 滑過時顯示圖層邊界 + Expand layer group on click 按一下時展開圖層群組 + Show hover bounds from Layers 顯示來自圖層面板的滑過邊界 +# Artboard tool options bar (#11385) + Distribute Widths 均分寬度 + Distribute Heights 均分高度 + Auto-nest Layers 自動巢狀圖層 + Auto-size Canvas 自動調整版面尺寸 + Keep Relative Position During Layer Reordering 重新排列圖層時保持相對位置 + Shrinkwrap Canvas on Save 儲存時將版面縮至內容大小 # JPEG Options: the size the file will have (#7843) Estimated file size 預估檔案大小 diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 0abd096530..c3ef377874 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -485,9 +485,9 @@ fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if crate::canvas::cancel_mixer_on_context_change(app, ctx) { return false; } - // However the tool was picked (toolbar, flyout, shortcut, automation), its group's key brings - // it back later (#2608). - app.ui.remember_group_tool(); + // However the tool was picked (toolbar, flyout, shortcut, automation), its group's key and its + // toolbar slot bring it back later (#2608). A temporary tool is no choice, so it isn't noted. + app.ui.remember_group_tool(crate::tool_memory::selected(app)); crate::canvas::polygon_cancel_stale(app); // Camera Raw is modal like Photoshop's filter dialog: no application shortcut (Save, Undo, // tools) runs beneath it, and it handles its own keys (Y, U, O, S). Unlike the other dialogs @@ -745,6 +745,10 @@ fn handle_object_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool if crate::slice_ui::keys(app, ctx) { return true; } + // A note selected with the Note tool: ⌫/Delete asks to delete the note, not the layer (#11788). + if crate::analysis_ui::note_keys(app, ctx) { + return true; + } // A selected smart filter row: ⌫/Delete removes the filter, not its smart object (#4751). crate::smart_ui::keys(app, ctx) } @@ -924,7 +928,7 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) { Some(i) if shift_switch && !cycle_shift => group[i], Some(i) => group[(i + 1) % group.len()], - None => app.ui.group_tool(t.key()).filter(|last| group.contains(last)).unwrap_or(group[0]), + None => app.ui.group_tools.iter().copied().find(|last| group.contains(last)).unwrap_or(group[0]), }; crate::tool_memory::ended_by_tool(app); // `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded. diff --git a/crates/ui-egui/src/input/shortcuts/tests.rs b/crates/ui-egui/src/input/shortcuts/tests.rs index cfb3203f10..fd68edff51 100644 --- a/crates/ui-egui/src/input/shortcuts/tests.rs +++ b/crates/ui-egui/src/input/shortcuts/tests.rs @@ -72,6 +72,20 @@ fn shift_key_tool_switch_is_the_default() { assert_ne!(app.ui.tool, Tool::Type); } +/// A tool with a shortcut of its own leaves its letter (#4086) but stays in the history: the letter +/// falls back on the last tool it still picks, not on its group's first. +#[test] +fn a_tool_key_passes_over_a_remapped_tool_to_the_last_one_it_picks() { + use crate::state::Tool; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("prefs.set", json!({"path": "shortcuts.tools.select.polygonLasso", "value": "F6"})).unwrap(); + app.ui.remember_group_tool(Tool::MagneticLasso); + app.ui.remember_group_tool(Tool::PolygonLasso); + press_key(&mut app, &ctx, Key::L, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MagneticLasso); +} + /// #3109: on a German layout Ö / # (physical `;` / `\`) step the brush size and ⇧Ö / ⇧# /// (⇧# types `'`) its hardness, as Photoshop's German shortcuts. #[test] diff --git a/crates/ui-egui/src/input/stylus.rs b/crates/ui-egui/src/input/stylus.rs index b6725af5ea..1899a0db09 100644 --- a/crates/ui-egui/src/input/stylus.rs +++ b/crates/ui-egui/src/input/stylus.rs @@ -8,7 +8,8 @@ //! `egui::Event::Touch { force }` alongside the emulated pointer. [`Stylus::update`] reads it. //! winit drops the pen's tilt and rotation, so those stay 0, and reports pressure 0 (a tap //! lighter than the pen's first pressure level) as no force, which [`Stylus::update`] reads as -//! pressure 0 once it knows a pen is in use. +//! pressure 0 once it knows a pen is in use. The desktop app's pointer message hook +//! (`photocraft-tablet`) reports which end of the pen is in use through `Services::pen_end`. //! - **Web**: eframe forwards touch force but not pen pointer events, so the web runner listens //! to `pointerdown`/`pointermove` itself and writes `pressure`, `tiltX`, `tiltY`, `twist` and //! the eraser button of `pointerType == "pen"` events into the [`StylusFeed`]. @@ -317,9 +318,10 @@ impl Stylus { } /// Did the pen just flip to its eraser end (`Some(true)`) or back to its tip (`Some(false)`)? - /// Each flip is reported once; a mouse in between changes nothing. - pub(crate) fn take_end_flip(&mut self) -> Option { - let eraser = self.feed.get()?.eraser; + /// Each flip is reported once; a mouse in between changes nothing. `platform_end` is the end + /// a platform reports outside the feed (Windows), read when the feed has no pen. + pub(crate) fn take_end_flip(&mut self, platform_end: Option) -> Option { + let eraser = self.feed.get().map(|s| s.eraser).or(platform_end)?; let flipped = self.end.map_or(eraser, |e| e != eraser); self.end = Some(eraser); flipped.then_some(eraser) @@ -332,7 +334,8 @@ impl Stylus { if app.drag.is_some() { return false; } - match app.stylus.take_end_flip() { + let platform_end = app.services.pen_end.as_ref().and_then(|f| f()); + match app.stylus.take_end_flip(platform_end) { Some(true) if app.ui.tool != Tool::Eraser => { app.stylus.tool_before_eraser = Some(app.ui.tool); app.ui.tool = Tool::Eraser; diff --git a/crates/ui-egui/src/input/stylus/tests.rs b/crates/ui-egui/src/input/stylus/tests.rs index 8e1a71dfa4..8ab18692c9 100644 --- a/crates/ui-egui/src/input/stylus/tests.rs +++ b/crates/ui-egui/src/input/stylus/tests.rs @@ -351,6 +351,46 @@ fn eraser_end_switches_tools_once_and_never_mid_drag() { assert_eq!(app.ui.tool, Tool::Eraser); } +/// Windows reports the pen's end through `Services::pen_end`, not the feed (#2285): flipping the +/// pen switches tools the same way, and a feed sample (automation, another backend) wins. +#[test] +fn the_platform_pen_end_switches_to_the_eraser_and_back() { + use crate::state::Tool; + use std::sync::Arc; + use std::sync::atomic::{AtomicU8, Ordering}; + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", serde_json::json!({"width": 60, "height": 60})).unwrap(); + app.ui.tool = Tool::Brush; + // 0 = no pen, 1 = tip, 2 = eraser end. + let end = Arc::new(AtomicU8::new(0)); + let read = end.clone(); + app.services.pen_end = Some(Box::new(move || match read.load(Ordering::Relaxed) { + 1 => Some(false), + 2 => Some(true), + _ => None, + })); + assert!(!Stylus::sync_eraser_tool(&mut app), "no pen in range"); + end.store(1, Ordering::Relaxed); + assert!(!Stylus::sync_eraser_tool(&mut app), "the tip keeps the tool"); + end.store(2, Ordering::Relaxed); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Eraser); + assert!(!Stylus::sync_eraser_tool(&mut app), "reported once"); + // Out of range and back with the eraser end: still the Eraser, nothing to switch. + end.store(0, Ordering::Relaxed); + assert!(!Stylus::sync_eraser_tool(&mut app)); + end.store(2, Ordering::Relaxed); + assert!(!Stylus::sync_eraser_tool(&mut app)); + end.store(1, Ordering::Relaxed); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Brush, "the tip restores the previous tool"); + // A feed sample is read before the platform's end. + end.store(2, Ordering::Relaxed); + app.stylus.feed.set(Some(PenSample { pressure: 0.5, eraser: false, ..Default::default() })); + assert!(!Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Brush); +} + /// The pen's eraser end is a tool switch like any other: Add New Artboard's placing mode ends /// (#11386), and coming back to the Artboard tool on the tip leaves it off. #[test] diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index f8e644fcda..c4ff5397c2 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -440,7 +440,7 @@ fn finish_save(app: &mut PhotocraftApp, ctx: &egui::Context, save: SaveJob, labe } JobOutcome::Cancelled => { app.jobs.close_after_saves = false; - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", label)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled {label}"), &[("label", label)]); app.ui.status_error = false; } } @@ -538,13 +538,13 @@ pub fn try_cancel(app: &mut PhotocraftApp, id: JobId) -> Result<(), CancelRefuse // A save that has started replacing the file runs to the end: cancelling it now would leave // the file written but the document marked unsaved. if r == Err(CancelRefused::Committing) { - app.ui.status = crate::i18n::fmt(tl!("{label} is writing the file and can no longer be cancelled"), &[("label", label.as_deref().unwrap_or_default())]); + app.ui.status = crate::i18n::fmt(tl!("{label} is writing the file and can no longer be canceled"), &[("label", label.as_deref().unwrap_or_default())]); app.ui.status_error = false; } if r.is_ok() { // The event (and its status text) arrives with the next poll; say so now as well. if let Some(l) = label { - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &l)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled {label}"), &[("label", &l)]); app.ui.status_error = false; } } @@ -619,7 +619,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { } JobOutcome::Failed(err) => app.open_failed(&tab.name, &err), JobOutcome::Cancelled => { - app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &tab.name)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &tab.name)]); app.ui.status_error = false; } } @@ -643,7 +643,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { crate::file_ui::print_status(app, result); } JobOutcome::Done(_) if cancelled_batch => { - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &e.label)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled {label}"), &[("label", &e.label)]); app.ui.status_error = false; } JobOutcome::Done(_) => { @@ -659,7 +659,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { notices::error(app, format!("{}: {err}", e.label)); } JobOutcome::Cancelled => { - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &e.label)]); + app.ui.status = crate::i18n::fmt(tl!("Canceled {label}"), &[("label", &e.label)]); app.ui.status_error = false; } } @@ -986,7 +986,7 @@ fn batch_interrupt_dialog(app: &mut PhotocraftApp, ctx: &egui::Context, id: JobI ui.set_width(390.0); ui.label(RichText::new(tl!("Batch")).font(crate::theme::semibold(15.0))); ui.add_space(8.0); - ui.label(RichText::new(tl!("A command was cancelled or stopped during batch processing. Continue with the next file or stop?")).color(t.text_dim)); + ui.label(RichText::new(tl!("A command was canceled or stopped during batch processing. Continue with the next file or stop?")).color(t.text_dim)); ui.add_space(14.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::primary_button(ui, tl!("Continue"), 96.0).clicked() { diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 764936b46f..452d2aeca2 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -124,7 +124,7 @@ fn the_frame_loop_keeps_running_during_a_slow_job_and_esc_cancels_it() { h.run_steps(3); assert!(h.state().session.job(job).is_none()); assert!(Arc::ptr_eq(&h.state().session.active().unwrap().doc, &doc_before)); - assert!(h.state().ui.status.contains("Cancelled"), "{}", h.state().ui.status); + assert!(h.state().ui.status.contains("Canceled"), "{}", h.state().ui.status); assert!(h.query_by_label("Esc to cancel").is_none(), "the dialog closed"); } @@ -549,7 +549,7 @@ fn a_failed_or_cancelled_foreground_save_leaves_the_document_unsaved() { assert!(gates.written().is_empty(), "nothing written"); let st = h.state().session.active().unwrap(); assert!(st.is_dirty() && st.path.is_none()); - assert_eq!(h.state().ui.status, "Cancelled Saving g.psd"); + assert_eq!(h.state().ui.status, "Canceled Saving g.psd"); assert!(crate::jobs_ui::foreground_save(h.state()).is_none()); } @@ -573,7 +573,7 @@ fn a_failed_save_or_one_cancelled_while_encoding_leaves_the_document_unsaved() { assert!(gates.written().is_empty(), "nothing written"); let st = h.state().session.active().unwrap(); assert!(st.is_dirty() && st.path.is_none()); - assert_eq!(h.state().ui.status, "Cancelled Saving b.psd"); + assert_eq!(h.state().ui.status, "Canceled Saving b.psd"); } /// Step until the save in `h` has started writing. @@ -595,7 +595,7 @@ fn a_save_that_has_started_writing_cannot_be_cancelled() { crate::jobs_ui::cancel(h.state_mut(), job); h.key_press(egui::Key::Escape); h.run_steps(2); - assert_eq!(h.state().ui.status, "Saving w.psd is writing the file and can no longer be cancelled"); + assert_eq!(h.state().ui.status, "Saving w.psd is writing the file and can no longer be canceled"); assert!(h.state().session.job(job).is_some(), "still running, the document still locked"); gates.write.store(true, Ordering::Relaxed); @@ -659,7 +659,7 @@ fn jobs_cancel_before_a_save_writes_stops_it_and_leaves_the_target_untouched() { assert_eq!(std::fs::read(&path).unwrap(), b"old", "target untouched"); let st = h.state().session.active().unwrap(); assert!(st.is_dirty() && st.path.is_none(), "the document is not marked saved"); - assert_eq!(h.state().ui.status, "Cancelled Saving w.psd"); + assert_eq!(h.state().ui.status, "Canceled Saving w.psd"); } #[test] @@ -679,7 +679,7 @@ fn jobs_cancel_during_the_write_reports_the_save_as_not_cancelled_and_it_finishe let refused = json!([{"job": save.0, "reason": "committing"}]); let v = control(&mut h, "jobs.cancel", json!({"job": save.0})); assert_eq!(v["result"], json!({"cancelled": 0, "notCancelled": refused}), "{v}"); - assert_eq!(h.state().ui.status, "Saving w.psd is writing the file and can no longer be cancelled"); + assert_eq!(h.state().ui.status, "Saving w.psd is writing the file and can no longer be canceled"); // Cancel everything: the other job stops, the save is reported as left running. let v = control(&mut h, "jobs.cancel", json!({})); assert_eq!(v["result"], json!({"cancelled": 1, "notCancelled": refused}), "{v}"); @@ -879,7 +879,7 @@ fn cancelled_batch_with_partial_results_reports_cancellation_without_beeping() { let (reply_tx, reply_rx) = std::sync::mpsc::channel(); h.state_mut().jobs.waiters.push((id, reply_tx)); crate::jobs_ui::on_event(h.state_mut(), &ctx, event); - assert!(h.state().ui.status.contains("Cancelled"), "{}", h.state().ui.status); + assert!(h.state().ui.status.contains("Canceled"), "{}", h.state().ui.status); assert_eq!(BEEPS.load(Ordering::Relaxed), 0); let reply = reply_rx.recv_timeout(Duration::from_secs(1)).unwrap(); assert_eq!(reply["ok"], false); diff --git a/crates/ui-egui/src/levels_clipping.rs b/crates/ui-egui/src/levels_clipping.rs new file mode 100644 index 0000000000..66a334e4a6 --- /dev/null +++ b/crates/ui-egui/src/levels_clipping.rs @@ -0,0 +1,405 @@ +//! Photoshop's Levels clipping display (#3328). While Alt is held and the black or white Input +//! slider of the Image › Adjustments › Levels dialog is dragged, the canvas shows what the input +//! levels clip instead of the preview: +//! - black slider: the image turns white; a channel the input levels clip to black drops to 0, so +//! pixels clipped in every channel are black and pixels clipped in red alone are cyan; +//! - white slider: the image turns black; a channel clipped to white rises to 255, so red alone is +//! red and all three are white. +//! +//! Releasing Alt or the mouse shows the preview again; the document is never touched. Grayscale +//! documents show black and white only. CMYK and Lab documents, and commands that edit a channel, +//! a layer mask or a non-pixel layer, keep the normal preview. +//! +//! The display is an opaque texture over the visible part of the image, at about the screen's +//! resolution: one texel per block of `factor`×`factor` document pixels. A block shows a channel +//! clipped when any pixel in it is, so a lone clipped highlight stays visible zoomed out. Clipping +//! is a threshold on each channel's sample (the input stretch is monotone), so the target's +//! per-block minimum and maximum are scanned once per view and a slider move only compares them +//! with the new thresholds. +//! +//! State is the dialog field `__clipping` (`"shadows"` / `"highlights"`): [`sync`] sets it when an +//! Alt-drag starts and clears it when the drag ends, and automation can set it with +//! `ui.dialog.set`. OK never sees it (`filter_dialog::params_of` drops `__` keys). + +use egui::{Color32, Mesh, TextureOptions, pos2}; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_compose::adjust::{levels_float, levels_q}; +use photocraft_doc::adjust::{LevelsChannel, ToneSpace}; +use photocraft_doc::{Adjustment, DocId, LayerContent, LayerId}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; + +/// The dialog field that turns the display on. +pub const FIELD: &str = "__clipping"; + +/// A pixel counts where the selection covers at least this much (the command blends the rest). +const SELECTED: f32 = 0.5; + +/// Which input slider's clipping is shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ClipEnd { + /// The black slider: what the input levels clip to black. + Shadows, + /// The white slider: what they clip to white. + Highlights, +} + +impl ClipEnd { + /// The [`FIELD`] value that asks for this end. + fn name(self) -> &'static str { + match self { + ClipEnd::Shadows => "shadows", + ClipEnd::Highlights => "highlights", + } + } + + /// The display a `__clipping` field value asks for (anything else: off). + pub fn parse(v: Option<&Value>) -> Option { + match v.and_then(Value::as_str) { + Some("shadows") => Some(ClipEnd::Shadows), + Some("highlights") => Some(ClipEnd::Highlights), + _ => None, + } + } +} + +/// Mirror an Alt-drag on the Levels dialog's black or white Input slider (editor state under +/// `mem`) into the dialog's [`FIELD`]. Only changes are written, so a display turned on through +/// automation stays until it is cleared or a drag ends. +pub fn sync(ctx: &egui::Context, mem: egui::Id, fields: &mut Map) { + if fields.get("__adjust").and_then(Value::as_str) != Some("levels") { + return; + } + let held = ctx.input(|i| i.modifiers.alt && i.pointer.primary_down()); + let live = match crate::adjust_editors::levels_drag(ctx, mem) { + Some(0) if held => Some(ClipEnd::Shadows), + Some(2) if held => Some(ClipEnd::Highlights), + _ => None, + }; + let last_id = mem.with("levels-clipping"); + let last: Option = ctx.data(|d| d.get_temp(last_id)).flatten(); + if live == last { + return; + } + ctx.data_mut(|d| d.insert_temp(last_id, live)); + match live { + Some(end) => { + fields.insert(FIELD.into(), json!(end.name())); + } + None => { + fields.remove(FIELD); + } + } + // The canvas paints before the dialogs: show the change on the next frame. + ctx.request_repaint(); +} + +/// Which ends the Levels input levels clip a sample `v` (0..1) of one channel to, as +/// (black, white): the channel's own input range or, after it, the composite's. `quantum` is the +/// document's (whole levels, as the compositor rounds them; None: 32-bit float, unclamped). Gamma +/// and the output levels don't matter: what reaches an end of an input range is flattened there, +/// wherever the output levels then put it. +pub fn classify(master: &LevelsChannel, channel: &LevelsChannel, v: f32, quantum: Option) -> (bool, bool) { + let eval = |ch: &LevelsChannel, v: f32| if quantum.is_some() { levels_q(ch, v, quantum) } else { levels_float(ch, v) }; + let full = |ch: &LevelsChannel| LevelsChannel { out_black: 0.0, out_white: 1.0, ..ch.clone() }; + let stretch = |ch: &LevelsChannel| LevelsChannel { gamma: 1.0, ..full(ch) }; + let own = eval(&stretch(channel), v); + let composite = eval(&stretch(master), eval(&full(channel), v)); + (own <= 0.0 || composite <= 0.0, own >= 1.0 || composite >= 1.0) +} + +/// A sample as a 16-bit key: exact for 8- and 16-bit documents (their samples are on this grid), +/// 32-bit samples clamped to 0..1 (beyond is clipped either way). Non-finite: None. +fn key(v: f32) -> Option { + v.is_finite().then(|| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16) +} + +/// Per channel (R, G, B): the highest key clipped to black and the lowest clipped to white (None: +/// no key clips that way). +pub type Thresholds = [(Option, Option); 3]; + +/// The [`Thresholds`] of the Levels `adj` in a document of `depth`. None for anything but Levels +/// in the RGB channel space (which Grayscale documents use too). +pub fn thresholds(adj: &Adjustment, depth: SampleType) -> Option { + let Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } = adj else { return None }; + let quantum = photocraft_compose::adjustment_quantum(depth); + let at = |ch: &LevelsChannel, k: u16| classify(master, ch, f32::from(k) / 65535.0, quantum); + Some(std::array::from_fn(|c| { + let ch = &per_channel[c]; + // Black clipping holds below a key and white clipping above one (the stretch is monotone). + let black = (at(ch, 0).0).then(|| last_true(|k| at(ch, k).0)); + let white = (at(ch, u16::MAX).1).then(|| first_true(|k| at(ch, k).1)); + (black, white) + })) +} + +/// The largest key where `f` holds, given it holds at 0 and stops holding at most once. +fn last_true(f: impl Fn(u16) -> bool) -> u16 { + let (mut lo, mut hi) = (0u32, u32::from(u16::MAX) + 1); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if f(mid as u16) { + lo = mid; + } else { + hi = mid; + } + } + lo as u16 +} + +/// The smallest key where `f` holds, given it holds at `u16::MAX` and starts holding at most once. +fn first_true(f: impl Fn(u16) -> bool) -> u16 { + let (mut lo, mut hi) = (-1i32, i32::from(u16::MAX)); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if f(mid as u16) { + hi = mid; + } else { + lo = mid; + } + } + hi as u16 +} + +/// Per block of the scanned area: each channel's minimum (0..3) and maximum (3..6) key over the +/// pixels that count. A block with none has min > max. +type Extremes = [u16; 6]; +const NONE: Extremes = [u16::MAX, u16::MAX, u16::MAX, 0, 0, 0]; + +/// The target's per-block extremes over `rect` (document pixels, `factor`×`factor` blocks). +pub struct Stats { + rect: Rect, + factor: u32, + size: [usize; 2], + blocks: Vec, +} + +/// Scan `surface` (a layer's pixels) over `rect` in `factor`×`factor` blocks. Pixels count when +/// visible (alpha > 0, finite) and, with a `selection`, at least half selected. +pub fn scan(surface: &Surface, selection: Option<&Surface>, rect: Rect, factor: u32) -> Stats { + let factor = factor.max(1); + let f = factor as usize; + let size = [rect.width().div_ceil(factor) as usize, rect.height().div_ceil(factor) as usize]; + let mut blocks = vec![NONE; size[0] * size[1]]; + let row = |by: usize, out: &mut [Extremes]| { + let y0 = rect.y0.saturating_add((by * f) as i32); + let band = Rect::new(rect.x0, y0, rect.x1, y0.saturating_add(factor as i32).min(rect.y1)); + let width = band.width() as usize; + let mut px = vec![[0.0f32; 4]; width * band.height() as usize]; + surface.read_rgba_into(band, &mut px); + let mut coverage = Vec::new(); + let stride = selection.map_or(1, |s| s.channels().max(1)); + if let Some(s) = selection { + s.read_region_into(band, &mut coverage); + } + for (i, p) in px.iter().enumerate() { + let visible = p[3] > 0.0; + let selected = selection.is_none() || coverage.get(i * stride).is_some_and(|k| *k >= SELECTED); + if !visible || !selected { + continue; + } + let (Some(r), Some(g), Some(b)) = (key(p[0]), key(p[1]), key(p[2])) else { continue }; + let Some(e) = out.get_mut((i % width.max(1)) / f) else { continue }; + for (c, k) in [r, g, b].into_iter().enumerate() { + e[c] = e[c].min(k); + e[c + 3] = e[c + 3].max(k); + } + } + }; + if size[0] > 0 { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + blocks.par_chunks_mut(size[0]).enumerate().for_each(|(by, out)| row(by, out)); + } + #[cfg(target_arch = "wasm32")] + for (by, out) in blocks.chunks_mut(size[0]).enumerate() { + row(by, out); + } + } + Stats { rect, factor, size, blocks } +} + +/// The display colour of a pixel clipped to black in the channels of `black` and to white in +/// those of `white` (bit 0 red, 1 green, 2 blue). +pub fn colour(end: ClipEnd, black: u8, white: u8) -> Color32 { + let on = |mask: u8, c: u8| if mask & (1 << c) != 0 { 255 } else { 0 }; + match end { + ClipEnd::Shadows => { + let m = 7 ^ black; + Color32::from_rgb(on(m, 0), on(m, 1), on(m, 2)) + } + ClipEnd::Highlights => Color32::from_rgb(on(white, 0), on(white, 1), on(white, 2)), + } +} + +/// The display of `stats` for `end` under the per-channel `thresholds`, one colour per block (in +/// parallel off the web: this runs on every slider move). +pub fn image(stats: &Stats, thresholds: &Thresholds, end: ClipEnd) -> Vec { + // Integer bounds (none clipped: below every key / above every key) and the 8 possible colours. + let lo = thresholds.map(|(lo, _)| lo.map_or(-1, i32::from)); + let hi = thresholds.map(|(_, hi)| hi.map_or(i32::from(u16::MAX) + 1, i32::from)); + let palette: [Color32; 8] = std::array::from_fn(|m| match end { + ClipEnd::Shadows => colour(end, m as u8, 0), + ClipEnd::Highlights => colour(end, 0, m as u8), + }); + let block = |e: &Extremes| { + let mut mask = 0usize; + for c in 0..3 { + let (min, max) = (i32::from(e[c]), i32::from(e[c + 3])); + let clipped = match end { + ClipEnd::Shadows => min <= max && min <= lo[c], + ClipEnd::Highlights => min <= max && max >= hi[c], + }; + mask |= usize::from(clipped) << c; + } + palette[mask] + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + stats.blocks.par_iter().map(block).collect() + } + #[cfg(target_arch = "wasm32")] + { + stats.blocks.iter().map(block).collect() + } +} + +/// What the display needs from the app: the end shown and the Levels adjustment, for the active +/// document's target layer. +struct Request { + end: ClipEnd, + adj: Adjustment, + doc: std::sync::Arc, + revision: u64, + target: LayerId, +} + +/// The open Levels dialog's fields, if any. A Smart Filter's Levels (`__smartFilter`) edits the +/// filter, not the layer's pixels, so it has no display (`adjust_preview` keeps it off the layer +/// path too). +fn dialog(app: &PhotocraftApp) -> Option<&Map> { + app.ui.dialogs.iter().map(|d| &d.fields).find(|f| f.get("__adjust").and_then(Value::as_str) == Some("levels") && !f.contains_key("__smartFilter")) +} + +/// The display the open Levels dialog asks for on document `idx`. None when no Levels dialog +/// shows clipping, `idx` isn't the active document, or the document can't show it: CMYK and Lab, +/// a channel, mask or Quick Mask target, or a target that isn't a pixel layer. +fn request(app: &PhotocraftApp, idx: usize) -> Option { + let fields = dialog(app)?; + let end = ClipEnd::parse(fields.get(FIELD))?; + let params = crate::filter_dialog::params_of(fields); + if app.session.active_index() != Some(idx) || crate::adjust_preview::targets_channel(app, idx, "levels", ¶ms) { + return None; + } + let st = app.session.documents().get(idx)?; + if !matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale) { + return None; + } + let target = st.active_layer?; + if !matches!(st.doc.layer(target).map(|l| &l.content), Some(LayerContent::Raster(_))) { + return None; + } + let adj = photocraft_engine::adjust_params::from_params("levels", ¶ms, None, st.doc.mode).ok()?; + Some(Request { end, adj, doc: st.doc.clone(), revision: st.revision, target }) +} + +/// The display's per-view state on the app. +pub struct Cache { + /// What `stats` scanned: document, revision, target, area and block size. + key: (DocId, u64, LayerId, Rect, u32), + stats: Stats, + /// The end and thresholds the texture shows. + drawn: Option<(ClipEnd, Thresholds)>, + tex: Option, +} + +/// Most blocks the display builds (2048 × 2048). A 2560×1440 canvas still gets one block per +/// device pixel, a bigger one bigger blocks: the block stats stay under 50 MB, the texture at +/// 16 MB, and a slider move near the 2 ms `levels_clipping_bench` measures for 3.7M blocks. +const MAX_BLOCKS: u64 = 2048 * 2048; + +/// The visible part of the document in `xf` and the block size giving about one texel per screen +/// pixel (`ppp` physical pixels per point), within `max_side` texels a side and [`MAX_BLOCKS`]. +fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(Rect, u32)> { + let device_zoom = xf.zoom * ppp; + if !(device_zoom.is_finite() && device_zoom > 0.0) { + return None; + } + let visible = crate::canvas::visible_doc_rect(xf).intersect(&bounds); + if visible.is_empty() { + return None; + } + let max_side = max_side.max(1); + let (w, h) = (visible.width(), visible.height()); + let budget = ((u64::from(w) * u64::from(h)) as f64 / MAX_BLOCKS as f64).sqrt().ceil() as u32; + let mut factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(w.div_ceil(max_side)).max(h.div_ceil(max_side)).max(budget); + // Snap to the block grid so panning keeps the blocks where they were. That can widen the area + // by up to a block, so grow the blocks until the snapped area fits. + loop { + let f = i32::try_from(factor).ok()?; + let r = Rect::new(visible.x0.div_euclid(f) * f, visible.y0.div_euclid(f) * f, visible.x1, visible.y1).intersect(&bounds); + let (bw, bh) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); + if bw <= max_side && bh <= max_side && u64::from(bw) * u64::from(bh) <= MAX_BLOCKS { + return Some((r, factor)); + } + factor = factor.checked_add(1)?; + } +} + +/// Draw the Levels clipping display over the image in canvas view `xf` of document `idx`, if one +/// is asked for. Drops the cache once no Levels dialog is open. Only the main canvas calls it: +/// the one cache follows that view. +pub fn paint(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, xf: &ViewXform, idx: usize) { + if dialog(app).is_none() { + app.levels_clipping = None; + return; + } + // A background job holds the workers and may replace the document: no thresholds, scan or + // image until it ends. + if app.session.has_jobs() { + return; + } + let Some(req) = request(app, idx) else { return }; + let Some(thr) = thresholds(&req.adj, req.doc.pixel_format().sample) else { return }; + let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, 8192); + let Some((rect, factor)) = view_area(xf, req.doc.bounds(), ctx.pixels_per_point(), max_side) else { return }; + let key = (req.doc.id, req.revision, req.target, rect, factor); + if app.levels_clipping.as_ref().is_none_or(|c| c.key != key) { + let Some(LayerContent::Raster(surface)) = req.doc.layer(req.target).map(|l| &l.content) else { return }; + let stats = scan(surface, req.doc.selection.as_ref(), rect, factor); + let tex = app.levels_clipping.take().and_then(|c| c.tex); + app.levels_clipping = Some(Cache { key, stats, drawn: None, tex }); + } + let Some(cache) = app.levels_clipping.as_mut() else { return }; + if cache.drawn != Some((req.end, thr)) || cache.tex.is_none() { + let img = egui::ColorImage::new(cache.stats.size, image(&cache.stats, &thr, req.end)); + match &mut cache.tex { + Some(t) => t.set(img, TextureOptions::NEAREST), + None => cache.tex = Some(ctx.load_texture("levels-clipping", img, TextureOptions::NEAREST)), + } + cache.drawn = Some((req.end, thr)); + } + let Some(tex) = cache.tex.as_ref().map(egui::TextureHandle::id) else { return }; + // The texture covers whole blocks; the last row and column may reach past the area. + let s = &cache.stats; + let f = s.factor as f32; + let uv = [s.rect.width() as f32 / (s.size[0] as f32 * f).max(1.0), s.rect.height() as f32 / (s.size[1] as f32 * f).max(1.0)]; + let (x0, y0, x1, y1) = (s.rect.x0 as f32, s.rect.y0 as f32, s.rect.x1 as f32, s.rect.y1 as f32); + let mut mesh = Mesh::with_texture(tex); + for (p, t) in [((x0, y0), (0.0, 0.0)), ((x1, y0), (uv[0], 0.0)), ((x1, y1), (uv[0], uv[1])), ((x0, y1), (0.0, uv[1]))] { + mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(p.0, p.1), uv: pos2(t.0, t.1), color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +#[cfg(test)] +#[path = "levels_clipping_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs new file mode 100644 index 0000000000..bed7134a4e --- /dev/null +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -0,0 +1,625 @@ +use super::*; +use egui_kittest::Harness; +use photocraft_color::{Color, PixelFormat}; +use photocraft_compose::Buffer; +use photocraft_compose::adjust::{Transfer, apply_depth}; +use photocraft_doc::{Document, Size}; + +const DEPTHS: [SampleType; 3] = [SampleType::U8, SampleType::U16, SampleType::F32]; + +fn lv(in_black: f32, gamma: f32, in_white: f32) -> LevelsChannel { + LevelsChannel { in_black: in_black / 255.0, gamma, in_white: in_white / 255.0, ..LevelsChannel::default() } +} + +fn levels(master: LevelsChannel, per_channel: [LevelsChannel; 3]) -> Adjustment { + Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, black: LevelsChannel::default() } +} + +/// Samples to try at `depth`: every 8-bit level, a 16-bit sweep, and float values past both ends. +fn samples(depth: SampleType) -> Vec { + match depth { + SampleType::U8 => (0..=255).map(|n| n as f32 / 255.0).collect(), + SampleType::U16 => (0..=65535).step_by(13).map(|n| n as f32 / 65535.0).collect(), + SampleType::F32 => (-40..=1100).map(|n| n as f32 / 1000.0).collect(), + } +} + +/// With gamma 1 and the output levels at their defaults, a channel is clipped exactly where the +/// compositor's Levels result sits at an end: 0 for black, 1 for white (the 8-bit LUT staircase +/// and the 32-bit formula; 16-bit against the whole-level chain the LUT samples). +#[test] +fn clipping_matches_the_levels_result() { + let master = lv(30.0, 1.0, 200.0); + let channels = [lv(10.0, 1.0, 240.0), LevelsChannel::default(), lv(60.0, 1.0, 120.0)]; + let adj = levels(master.clone(), channels.clone()); + for depth in DEPTHS { + let quantum = photocraft_compose::adjustment_quantum(depth); + for v in samples(depth) { + let result: [f32; 3] = if depth == SampleType::U16 { + std::array::from_fn(|c| levels_q(&master, levels_q(&channels[c], v, quantum), quantum)) + } else { + let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [v, v, v, 1.0]); + apply_depth(&adj, &mut b, Transfer::for_document(ColorMode::Rgb, depth), Some(depth)); + [b.px[0][0], b.px[0][1], b.px[0][2]] + }; + for (c, (ch, r)) in channels.iter().zip(result).enumerate() { + let (black, white) = classify(&master, ch, v, quantum); + assert_eq!(black, r <= 0.0, "{depth:?} v={v} channel {c}: {r}"); + assert_eq!(white, r >= 1.0, "{depth:?} v={v} channel {c}: {r}"); + } + } + } +} + +/// Gamma and the output levels don't change what the input levels clip, so the display tests the +/// input-range clamps rather than the final value. Narrowed output levels never reach black or +/// white, and gamma below 1 rounds the 8-bit levels just above the black point to black although +/// the slider keeps them. (Gamma above 1 reaches white at the top: its toe is at black.) +#[test] +fn gamma_and_output_levels_do_not_hide_clipping() { + let q = Some(255.0); + let master = LevelsChannel { gamma: 1.5, ..lv(20.0, 1.0, 200.0) }; + let plain = lv(20.0, 1.0, 200.0); + let outputs = LevelsChannel { out_black: 25.0 / 255.0, out_white: 230.0 / 255.0, gamma: 0.6, ..lv(20.0, 1.0, 200.0) }; + let crushed = LevelsChannel { gamma: 0.5, ..lv(20.0, 1.0, 200.0) }; + assert!(levels_q(&outputs, 0.0, q) > 0.0 && levels_q(&outputs, 1.0, q) < 1.0, "narrowed outputs never reach black or white"); + assert_eq!(levels_q(&crushed, 21.0 / 255.0, q), 0.0, "gamma 0.5 rounds level 21 to black"); + for n in 0..=255 { + let v = n as f32 / 255.0; + let id = LevelsChannel::default(); + let want = (n <= 20, n >= 200); + assert_eq!(classify(&master, &id, v, q), want, "gamma 1.5 composite, level {n}"); + assert_eq!(classify(&plain, &id, v, q), want, "level {n}"); + assert_eq!(classify(&outputs, &id, v, q), want, "outputs and gamma 0.6, level {n}"); + assert_eq!(classify(&crushed, &id, v, q), want, "gamma 0.5 composite, level {n}"); + assert_eq!(classify(&id, &master, v, q), want, "gamma 1.5 channel, level {n}"); + } +} + +/// The per-channel thresholds give the same answer as [`classify`] for every key tried. +#[test] +fn thresholds_agree_with_classify() { + let cases = [ + levels(lv(30.0, 1.0, 200.0), Default::default()), + levels(LevelsChannel::default(), [lv(10.0, 0.4, 240.0), lv(0.0, 2.5, 90.0), lv(128.0, 1.0, 130.0)]), + levels(lv(5.0, 3.0, 250.0), [LevelsChannel { out_black: 0.2, out_white: 0.9, ..lv(40.0, 0.7, 220.0) }, lv(0.0, 1.0, 255.0), lv(200.0, 9.0, 255.0)]), + ]; + for adj in &cases { + let Adjustment::Levels { master, per_channel, .. } = adj else { panic!("Levels") }; + for depth in DEPTHS { + let quantum = photocraft_compose::adjustment_quantum(depth); + let thr = thresholds(adj, depth).unwrap(); + let keys: Vec = match depth { + SampleType::U8 => (0..=255u16).map(|n| n * 257).collect(), + _ => (0..=65535u16).step_by(7).chain([u16::MAX]).collect(), + }; + for k in keys { + for (c, (ch, (lo, hi))) in per_channel.iter().zip(thr).enumerate() { + let (black, white) = classify(master, ch, f32::from(k) / 65535.0, quantum); + assert_eq!(black, lo.is_some_and(|lo| k <= lo), "{depth:?} key {k} channel {c} black"); + assert_eq!(white, hi.is_some_and(|hi| k >= hi), "{depth:?} key {k} channel {c} white"); + } + } + } + } +} + +/// Photoshop's threshold display: black slider, a clipped channel drops to 0 on white; white +/// slider, a clipped channel rises to 255 on black. +#[test] +fn colours_follow_the_clipped_channels() { + let rgb = Color32::from_rgb; + assert_eq!(colour(ClipEnd::Shadows, 0, 7), Color32::WHITE); + assert_eq!(colour(ClipEnd::Shadows, 0b001, 0), rgb(0, 255, 255), "red alone: cyan"); + assert_eq!(colour(ClipEnd::Shadows, 0b110, 0), rgb(255, 0, 0), "green and blue: red"); + assert_eq!(colour(ClipEnd::Shadows, 7, 0), Color32::BLACK); + assert_eq!(colour(ClipEnd::Highlights, 7, 0), Color32::BLACK); + assert_eq!(colour(ClipEnd::Highlights, 0, 0b001), rgb(255, 0, 0), "red alone: red"); + assert_eq!(colour(ClipEnd::Highlights, 0, 0b011), rgb(255, 255, 0)); + assert_eq!(colour(ClipEnd::Highlights, 0, 7), Color32::WHITE); +} + +fn surface(fmt: PixelFormat, w: u32, h: u32, px: impl Fn(u32, u32) -> Vec) -> Surface { + let mut s = Surface::new(fmt); + let data: Vec = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| px(x, y)).collect(); + s.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + s +} + +/// A block shows what any counted pixel in it clips; transparent, unselected (under half) and +/// non-finite pixels don't count. +#[test] +fn blocks_keep_lone_extremes_of_the_pixels_that_count() { + let s = surface(PixelFormat::RGBA32F, 8, 8, |x, y| match (x, y) { + (5, 5) => vec![0.0, 0.5, 0.5, 1.0], + (1, 1) => vec![1.0, 1.0, 1.0, 0.0], + (2, 2) => vec![f32::NAN, 1.0, 1.0, 1.0], + (7, 1) => vec![1.0, 1.0, 1.0, 1.0], + _ => vec![0.5, 0.5, 0.5, 1.0], + }); + let thr = [(key(0.1), key(0.9)); 3]; + let grey = surface(PixelFormat::GRAY8, 8, 8, |x, _| vec![if x < 6 { 1.0 } else { 0.4 }]); + for (selection, top_right) in [(None, Color32::WHITE), (Some(&grey), Color32::BLACK)] { + let stats = scan(&s, selection, Rect::new(0, 0, 8, 8), 4); + assert_eq!(stats.size, [2, 2]); + let black = image(&stats, &thr, ClipEnd::Shadows); + assert_eq!(black, vec![Color32::WHITE, Color32::WHITE, Color32::WHITE, Color32::from_rgb(0, 255, 255)], "{selection:?}"); + let white = image(&stats, &thr, ClipEnd::Highlights); + assert_eq!(white, vec![Color32::BLACK, top_right, Color32::BLACK, Color32::BLACK], "{selection:?}"); + } +} + +/// Gray documents' Levels act on one channel, so the display is black and white only. +#[test] +fn gray_layers_show_black_and_white_only() { + let s = surface(PixelFormat::GRAYA8, 16, 1, |x, _| vec![x as f32 / 15.0, 1.0]); + let adj = levels(lv(100.0, 1.0, 180.0), Default::default()); + let thr = thresholds(&adj, SampleType::U8).unwrap(); + let stats = scan(&s, None, Rect::new(0, 0, 16, 1), 1); + for end in [ClipEnd::Shadows, ClipEnd::Highlights] { + for (x, c) in image(&stats, &thr, end).into_iter().enumerate() { + let v = x as f32 / 15.0 * 255.0; + let clipped = if end == ClipEnd::Shadows { v <= 100.0 } else { v >= 180.0 }; + assert!(c == Color32::BLACK || c == Color32::WHITE, "x={x}: {c:?}"); + assert_eq!(c == colour(end, 7, 7), clipped, "{end:?} x={x}"); + } + } +} + +/// Out-of-range and non-finite settings never panic. +#[test] +fn hostile_settings_do_not_panic() { + let bad = LevelsChannel { in_black: f32::NAN, in_white: -3.0, gamma: 0.0, out_black: f32::INFINITY, out_white: f32::NEG_INFINITY }; + for adj in [levels(bad.clone(), [bad.clone(), LevelsChannel::default(), lv(255.0, 100.0, 0.0)]), levels(LevelsChannel::default(), Default::default())] { + for depth in DEPTHS { + let _ = thresholds(&adj, depth); + } + } + let cmyk = + Adjustment::Levels { master: LevelsChannel::default(), per_channel: Default::default(), space: ToneSpace::Cmyk, black: LevelsChannel::default() }; + assert!(thresholds(&cmyk, SampleType::U8).is_none()); + assert!(thresholds(&Adjustment::Invert, SampleType::U8).is_none()); + for params in [json!({"inBlack": 1e9, "inWhite": -5, "gamma": 0}), json!({"red": {"gamma": 100, "inWhite": 0}}), json!({"inBlack": "x"})] { + if let Ok(adj) = photocraft_engine::adjust_params::from_params("levels", ¶ms, None, ColorMode::Rgb) { + let _ = thresholds(&adj, SampleType::U16); + } + } +} + +/// A 16×8 document: the background's red channel ramps 0..1 left to right, green is 0.5, blue 1. +fn ramp_app(mode: ColorMode, depth: SampleType) -> PhotocraftApp { + let mut doc = Document::with_background("t", Size::new(16, 8), mode, depth, Color::rgba(1.0, 1.0, 1.0, 1.0)); + let gray = mode == ColorMode::Grayscale; + if let Some(s) = doc.layers[0].surface_mut() { + let data: Vec = + (0..8).flat_map(|_| 0..16).flat_map(|x| if gray { vec![x as f32 / 15.0, 1.0] } else { vec![x as f32 / 15.0, 0.5, 1.0, 1.0] }).collect(); + s.write_region(Rect::new(0, 0, 16, 8), &data); + } + let target = doc.layers[0].id; + let mut session = photocraft_engine::Session::new(); + session.add_document(doc, None); + session.select_layer(target).unwrap(); + PhotocraftApp::new(session, crate::Services::default()) +} + +fn open_levels(app: &mut PhotocraftApp, params: Value, end: Option<&str>) -> u64 { + let id = crate::adjust_dialog::open(app, "image.adjustments.levels").unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + if let Value::Object(p) = params { + fields.extend(p); + } + if let Some(end) = end { + fields.insert(FIELD.into(), json!(end)); + } + id +} + +/// A canvas view of the 16×8 document at `zoom` points per pixel (1 pixel per point). +fn view(zoom: f32) -> ViewXform { + ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(16.0 * zoom, 8.0 * zoom)), + zoom, + center: [8.0, 4.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +/// [`paint`] in a frame of its own (so its mesh doesn't spill into a later frame's shapes), then +/// the colours of the blocks it shows. +fn paint_view(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> Option> { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = egui::Painter::new(ui.ctx().clone(), egui::LayerId::background(), egui::Rect::EVERYTHING); + paint(app, ui.ctx(), &painter, xf, 0); + }); + out.textures_delta.clear(); + let c = app.levels_clipping.as_ref()?; + let (end, thr) = c.drawn?; + Some(image(&c.stats, &thr, end)) +} + +/// A view at one device pixel per document pixel whose visible document rect (with +/// `visible_doc_rect`'s 2 px margin) is exactly `x0..x1` × `y0..y1`. +fn xf_over(x0: i32, x1: i32, y0: i32, y1: i32) -> ViewXform { + let size = egui::vec2((x1 - x0 - 4) as f32, (y1 - y0 - 4) as f32); + ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, size), + zoom: 1.0, + center: [(x0 + x1) as f32 / 2.0, (y0 + y1) as f32 / 2.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +/// Snapping the area to the block grid can widen it by up to a block; the blocks grow until the +/// snapped area still fits the texture limit (here a 2048 px device limit) on both sides. +#[test] +fn the_snapped_area_fits_the_texture_limit() { + let bounds = Rect::new(0, 0, 20000, 20000); + let (r, f) = view_area(&xf_over(1, 4097, 0, 100), bounds, 1.0, 2048).unwrap(); + assert_eq!((r.x0, f), (0, 3), "4096 px from x 1: blocks of 2 would need 2049"); + for (x0, y0) in [(0, 0), (1, 1), (2, 3), (5, 7), (1023, 2047)] { + for span in 4090..4100 { + let (x1, y1) = (x0 + span, y0 + span / 2); + let (r, f) = view_area(&xf_over(x0, x1, y0, y1), bounds, 1.0, 2048).unwrap(); + let fi = f as i32; + assert!(r.width().div_ceil(f) <= 2048 && r.height().div_ceil(f) <= 2048, "{x0},{y0} span {span}: {r:?} / {f}"); + assert!(r.x0 % fi == 0 && r.y0 % fi == 0, "snapped to the grid: {r:?} / {f}"); + assert!(r.x0 <= x0 && r.y0 <= y0 && r.x1 >= x1 && r.y1 >= y1, "covers the view: {r:?}"); + } + } +} + +/// However big the display, the display builds at most `MAX_BLOCKS` blocks: an 8K canvas at +/// 100 % gets bigger blocks instead of a 33M-texel texture, while 2560×1440 keeps one block per +/// device pixel. +#[test] +fn a_huge_display_grows_the_blocks() { + let bounds = Rect::new(0, 0, 20000, 20000); + let (_, f) = view_area(&xf_over(0, 2564, 0, 1444), bounds, 1.0, 8192).unwrap(); + assert_eq!(f, 1, "2560×1440: one block per device pixel"); + for (w, h) in [(7680, 4320), (8192, 8192), (15360, 8640)] { + let (r, f) = view_area(&xf_over(0, w, 0, h), bounds, 1.0, 8192).unwrap(); + let blocks = u64::from(r.width().div_ceil(f)) * u64::from(r.height().div_ceil(f)); + assert!(blocks <= MAX_BLOCKS, "{w}×{h}: {blocks} blocks of {f}"); + assert!(blocks > MAX_BLOCKS / 4, "{w}×{h}: no coarser than needed ({blocks} blocks of {f})"); + } +} + +/// The main canvas's view of the 16×8 document at 10 device pixels per pixel. +fn main_view(app: &mut PhotocraftApp) -> crate::state::View { + app.sync_views(); + crate::state::View { zoom: 10.0, center: [8.0, 4.0], fit_pending: false, fill_pending: false, ..app.ui.views[0].clone() } +} + +/// The shapes of one 160×80 canvas frame of document 0 in `view`. +fn canvas_frame(ctx: &egui::Context, app: &mut PhotocraftApp, view: &crate::state::View, primary: bool) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + crate::canvas::canvas_view(app, ui, 0, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(160.0, 80.0)), view.clone(), primary); + }); + out.textures_delta.clear(); + out.shapes +} + +/// How many meshes among `shapes` (shape lists included) draw texture `tex`. +fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> usize { + fn count(s: &egui::Shape, tex: egui::TextureId) -> usize { + match s { + egui::Shape::Mesh(m) => usize::from(m.texture_id == tex), + egui::Shape::Vec(v) => v.iter().map(|s| count(s, tex)).sum(), + _ => 0, + } + } + shapes.iter().map(|c| count(&c.shape, tex)).sum() +} + +/// The display keeps one cache, sized to the main canvas's view: an extra document window's +/// canvas (not primary) neither draws it nor replaces that cache with its own view. +#[test] +fn only_the_main_canvas_draws_the_display() { + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + let main = main_view(&mut app); + let other = crate::state::View { zoom: 0.25, ..main.clone() }; + let shapes = canvas_frame(&ctx, &mut app, &main, true); + let cache = app.levels_clipping.as_ref().expect("the main canvas builds the display"); + let (key, tex) = (cache.key, cache.tex.as_ref().map(egui::TextureHandle::id).expect("its texture")); + assert_eq!(meshes_with(&shapes, tex), 1, "the main canvas draws the display"); + let shapes = canvas_frame(&ctx, &mut app, &other, false); + assert_eq!(meshes_with(&shapes, tex), 0, "an extra window doesn't draw it"); + assert_eq!(app.levels_clipping.as_ref().map(|c| c.key), Some(key), "nor replaces the main canvas's cache"); +} + +/// The display covers the view at about one texel per screen pixel, in every depth and in Gray, +/// and goes away with the dialog. +#[test] +fn paint_shows_the_target_clipping_for_the_view() { + let ctx = egui::Context::default(); + for (mode, depth) in + [(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Grayscale, SampleType::U8)] + { + let mut app = ramp_app(mode, depth); + let id = open_levels(&mut app, json!({"inBlack": 100, "inWhite": 200}), Some("shadows")); + let px = paint_view(&mut app, &ctx, &view(10.0)).unwrap_or_else(|| panic!("{mode:?} {depth:?}")); + assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [16, 8]); + let gray = mode == ColorMode::Grayscale; + let clipped = if gray { Color32::BLACK } else { Color32::from_rgb(0, 255, 255) }; + for (x, p) in px.iter().take(16).enumerate() { + let want = if x as f32 / 15.0 * 255.0 <= 100.0 { clipped } else { Color32::WHITE }; + assert_eq!(*p, want, "{mode:?} {depth:?} shadows x={x}"); + } + app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), json!("highlights")); + let px = paint_view(&mut app, &ctx, &view(10.0)).unwrap(); + for (x, p) in px.iter().skip(16 * 7).enumerate() { + let red = x as f32 / 15.0 * 255.0 >= 200.0; + let want = match (gray, red) { + (true, true) => Color32::WHITE, + (true, false) => Color32::BLACK, + (false, true) => Color32::from_rgb(255, 0, 255), + (false, false) => Color32::from_rgb(0, 0, 255), + }; + assert_eq!(*p, want, "{mode:?} {depth:?} highlights x={x}"); + } + // Zoomed out, a texel covers a block of pixels. + paint_view(&mut app, &ctx, &view(0.25)).unwrap(); + assert_eq!(app.levels_clipping.as_ref().unwrap().stats.factor, 4); + assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [4, 2]); + // Off with the dialog still open: the cached texture stays but no canvas frame draws it. + let main = main_view(&mut app); + let shapes = canvas_frame(&ctx, &mut app, &main, true); + let tex = app.levels_clipping.as_ref().and_then(|c| c.tex.as_ref()).map(egui::TextureHandle::id).unwrap(); + assert_eq!(meshes_with(&shapes, tex), 1, "{mode:?} {depth:?}: on, it draws"); + app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), Value::Null); + assert!(request(&app, 0).is_none()); + let shapes = canvas_frame(&ctx, &mut app, &main, true); + assert_eq!(meshes_with(&shapes, tex), 0, "{mode:?} {depth:?}: off, it draws nothing"); + assert!(app.levels_clipping.is_some(), "{mode:?} {depth:?}: the cache stays while the dialog is open"); + // Closed: the cache goes. + app.ui.close_dialog(id); + paint_view(&mut app, &ctx, &view(10.0)); + assert!(app.levels_clipping.is_none(), "{mode:?} {depth:?}"); + } +} + +/// CMYK and Lab documents, a Quick Mask, and a target that isn't a pixel layer keep the normal +/// preview. +#[test] +fn ineligible_documents_show_no_display() { + for mode in ["cmyk", "lab"] { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "mode": mode})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + open_levels(&mut app, json!({}), Some("shadows")); + assert!(request(&app, 0).is_none(), "{mode}"); + } + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.quick_mask.is_some()); + open_levels(&mut app, json!({}), Some("shadows")); + assert!(request(&app, 0).is_none(), "Quick Mask"); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + app.run("layer.newFillLayer.solidColor", json!({"color": "#808080"})).unwrap(); + open_levels(&mut app, json!({}), Some("shadows")); + assert!(request(&app, 0).is_none(), "fill layer"); +} + +/// While a background job runs the display draws nothing and neither scans nor builds its +/// texture. It comes back once the job is done. +#[test] +fn a_running_job_holds_the_display() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + let gate = Arc::new(AtomicBool::new(false)); + let open = gate.clone(); + let started = app + .session + .start_job( + "test.slow", + json!({}), + "Slow", + false, + move |job| { + while !open.load(Ordering::Relaxed) { + job.check()?; + std::thread::sleep(std::time::Duration::from_millis(1)); + } + Ok(()) + }, + |_, ()| Ok(json!({})), + ) + .unwrap(); + let photocraft_engine::jobs::Started::Job(job) = started else { panic!("ran inline") }; + assert!(app.session.has_jobs()); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_none()); + assert!(app.levels_clipping.is_none(), "no scan and no texture while the job runs"); + gate.store(true, Ordering::Relaxed); + app.session.wait_job(job).unwrap(); + assert!(!app.session.has_jobs()); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "back once the job is done"); +} + +/// Closing the last document drops the display's cache: no canvas is left to paint it away. +#[test] +fn closing_the_last_document_drops_the_cache() { + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some()); + app.run("file.close", json!({})).unwrap(); + assert!(app.session.documents().is_empty()); + assert!(app.levels_clipping.is_none()); +} + +/// A Smart Filter's Levels dialog edits the filter, not the layer's pixels: no display, and its +/// cache goes as if no Levels dialog were open, even over a pixel layer. +#[test] +fn smart_filter_levels_show_no_display() { + let ctx = egui::Context::default(); + let mut app = ramp_app(ColorMode::Rgb, SampleType::U8); + let id = open_levels(&mut app, json!({"inBlack": 100}), Some("shadows")); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "a plain Levels dialog shows it"); + let layer = app.session.active().and_then(|s| s.active_layer).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("__smartFilter".into(), json!({"layer": layer.0})); + assert!(request(&app, 0).is_none()); + assert!(paint_view(&mut app, &ctx, &view(10.0)).is_none()); + assert!(app.levels_clipping.is_none(), "the cache goes"); +} + +fn dialog_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h +} + +fn clipping(h: &Harness<'static, PhotocraftApp>) -> Option { + h.state().ui.dialogs.first().and_then(|d| d.fields.get(FIELD).cloned()) +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2, pressed: bool, modifiers: egui::Modifiers) { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); +} + +fn modifiers(h: &mut Harness<'static, PhotocraftApp>, m: egui::Modifiers) { + h.event(egui::Event::ModifiersChanged(m)); + h.run_steps(1); +} + +/// Alt-dragging the black slider shows the shadows display while both are held, the white slider +/// the highlights; the gamma slider, a drag without Alt and the Properties panel show nothing. +/// The document stays untouched throughout. +#[test] +fn alt_drag_on_the_black_and_white_sliders_turns_the_display_on() { + let mut h = dialog_harness(ramp_app(ColorMode::Rgb, SampleType::U8)); + let original = h.state().session.active().unwrap().doc.clone(); + let id = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.levels").unwrap(); + h.run_steps(3); + let track = h.ctx.data(|d| d.get_temp::(egui::Id::unique(("adjust-dialog", "levels")).with("levels-slider"))).unwrap(); + let at = |level: f32| egui::pos2(track.left() + level / 255.0 * track.width(), track.center().y + 4.0); + let alt = egui::Modifiers::ALT; + // Black slider: on while Alt and the button are held, off with either. + modifiers(&mut h, alt); + h.event(egui::Event::PointerMoved(at(0.0))); + press(&mut h, at(0.0), true, alt); + assert_eq!(clipping(&h), Some(json!("shadows"))); + h.event(egui::Event::PointerMoved(at(60.0))); + h.run_steps(1); + let in_black = h.state().ui.dialogs[0].fields["inBlack"].as_f64().unwrap(); + assert!((55.0..=65.0).contains(&in_black), "the drag still moves the slider: {in_black}"); + assert_eq!(clipping(&h), Some(json!("shadows"))); + modifiers(&mut h, egui::Modifiers::NONE); + assert_eq!(clipping(&h), None, "releasing Alt shows the preview"); + modifiers(&mut h, alt); + assert_eq!(clipping(&h), Some(json!("shadows")), "Alt again"); + press(&mut h, at(60.0), false, alt); + assert_eq!(clipping(&h), None, "releasing the mouse shows the preview"); + // White slider. + h.event(egui::Event::PointerMoved(at(255.0))); + press(&mut h, at(255.0), true, alt); + assert_eq!(clipping(&h), Some(json!("highlights"))); + press(&mut h, at(255.0), false, alt); + assert_eq!(clipping(&h), None); + // Gamma slider (halfway between 60 and 255 at gamma 1). + let gamma = 60.0 + (255.0 - 60.0) / 2.0; + h.event(egui::Event::PointerMoved(at(gamma))); + press(&mut h, at(gamma), true, alt); + assert_eq!(clipping(&h), None, "the gamma slider has no display"); + press(&mut h, at(gamma), false, alt); + // No Alt. + modifiers(&mut h, egui::Modifiers::NONE); + h.event(egui::Event::PointerMoved(at(60.0))); + press(&mut h, at(60.0), true, egui::Modifiers::NONE); + assert_eq!(clipping(&h), None, "no Alt, no display"); + press(&mut h, at(60.0), false, egui::Modifiers::NONE); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); + assert!(h.state().ui.dialogs.iter().any(|d| d.id == id)); +} + +/// Set through automation, the display stays until cleared; it never re-keys the live preview, +/// touches the document or reaches OK. +#[test] +fn the_display_never_reaches_the_document() { + let commit = |end: Option<&str>| { + let mut h = dialog_harness(ramp_app(ColorMode::Rgb, SampleType::U8)); + let original = h.state().session.active().unwrap().doc.clone(); + let steps = h.state().session.active().unwrap().history.past_len(); + let id = open_levels(h.state_mut(), json!({"inBlack": 60, "gamma": 1.2}), None); + h.run_steps(3); + let _ = crate::adjust_preview::display_doc(h.state_mut(), 0); + let key = crate::adjust_preview::shown_key(h.state()); + if let Some(end) = end { + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), json!(end)); + h.run_steps(3); + assert_eq!(clipping(&h), Some(json!(end)), "an automation-set display stays"); + let _ = crate::adjust_preview::display_doc(h.state_mut(), 0); + assert_eq!(crate::adjust_preview::shown_key(h.state()), key, "the preview is not re-keyed"); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); + } + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let st = h.state().session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1); + let mut px = Vec::new(); + st.doc.layers[0].surface().unwrap().read_region_into(Rect::new(0, 0, 16, 8), &mut px); + px + }; + let plain = commit(None); + for end in ["shadows", "highlights"] { + assert_eq!(commit(Some(end)), plain, "{end}: OK commits only the levels"); + } +} + +/// Scan once per view, then per slider move thresholds + colours (the texture upload comes on +/// top). `CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 cargo test +/// --release -p photocraft-ui-egui --lib levels_clipping_bench -- --ignored --nocapture` +#[test] +#[ignore = "benchmark"] +fn levels_clipping_bench() { + let adj = levels(lv(40.0, 1.3, 215.0), [lv(5.0, 1.0, 250.0), LevelsChannel::default(), lv(0.0, 0.8, 240.0)]); + for (w, h) in [(6000u32, 4000u32), (7360, 4912)] { + let mut s = Surface::new(PixelFormat::RGBA8); + for y0 in (0..h).step_by(256) { + let rows = 256.min(h - y0); + let data: Vec = (0..rows * w) + .flat_map(|i| { + let (x, y) = (i % w, y0 + i / w); + let n = ((x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)) >> 7) % 64; + let v = (x as f32 / w as f32 * 0.8 + n as f32 / 255.0).min(1.0); + [v, 1.0 - v, (y as f32 / h as f32), 1.0] + }) + .collect(); + s.write_region(Rect::new(0, y0 as i32, w as i32, (y0 + rows) as i32), &data); + } + let fit = w.div_ceil(2400); + for (name, rect, factor) in [("fit", Rect::new(0, 0, w as i32, h as i32), fit), ("100%", Rect::new(1000, 1000, 3560, 2440), 1)] { + let best = |f: &mut dyn FnMut()| { + (0..5) + .map(|_| { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .fold(f64::MAX, f64::min) + }; + let scan_ms = best(&mut || { + std::hint::black_box(scan(&s, None, rect, factor)); + }); + let stats = scan(&s, None, rect, factor); + let update_ms = best(&mut || { + let thr = thresholds(&adj, SampleType::U8).unwrap(); + std::hint::black_box(egui::ColorImage::new(stats.size, image(&stats, &thr, ClipEnd::Shadows))); + }); + println!( + "{} MP {name} (1/{factor}, {}×{} texels): scan {scan_ms:.1} ms, update {update_ms:.1} ms", + (w * h) / 1_000_000, + stats.size[0], + stats.size[1] + ); + } + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7fd35442cc..a57ad9f445 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -41,6 +41,7 @@ mod icon_data; pub mod icons; pub mod jobs_ui; pub(crate) mod last_brush; +pub mod levels_clipping; pub mod links; pub mod memory_warning; pub mod menu_catalog; @@ -260,8 +261,8 @@ pub use services::{ AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, - LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, - SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, + LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, + SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, }; pub use text::bidi_text; pub use text::cjk_fonts; @@ -430,6 +431,11 @@ pub struct PhotocraftApp { pub(crate) brush_resize: Option, /// A ⌘⌥⌃-click layer pick is in progress; its drag and release are swallowed (`quick_pick`). pub(crate) quick_pick: bool, + /// The layer a canvas click picked the Move tool way (its Auto-Select, or a ⌘-click from another + /// tool) and the engine's active-layer change count right after that pick + /// (`Session::active_layer_changes`). The Layers panel's reveal reads it when it next draws, and + /// accepts it only if nothing changed the active layer since, however long ago (`layer_reveal`, #11381). + pub(crate) move_pick: Option<(photocraft_doc::LayerId, u64)>, /// The next tool `Down` is an Alt+right-drag that resizes the brush (#297). `tool_event` /// takes it on every event, so a press another handler consumes can't leave it set. pub(crate) brush_resize_armed: bool, @@ -534,6 +540,8 @@ pub struct PhotocraftApp { /// The Properties panel's live adjustment-layer drag: its damage region and coverage /// (`adjust_preview::live_key`). pub(crate) live_adjust_preview: Option, + /// The Levels dialog's Alt-drag clipping display over the canvas. + pub(crate) levels_clipping: Option, /// Synthetic input events queued by automation (`ui.click`, `ui.key`, …), injected next frame. pub(crate) synthetic: Vec, /// The one synthetic batch currently being delivered. @@ -762,6 +770,10 @@ impl SyntheticTarget { #[cfg(test)] mod artboard_add_mode_tests; #[cfg(test)] +mod brush_options_tooltips_tests; +#[cfg(test)] +mod brush_picker_escape_tests; +#[cfg(test)] mod shape_bounds_box_tests; #[cfg(test)] @@ -884,6 +896,9 @@ mod blur_pins_tests; #[cfg(test)] mod move_outline_tests; +#[cfg(test)] +mod move_bar_distribute_gear_tests; + #[cfg(test)] mod layer_thumb_bounds_tests; #[cfg(test)] @@ -978,6 +993,8 @@ mod menu_item_labels_tests; #[cfg(test)] mod pen_path_ownership_tests; +#[cfg(test)] +mod artboard_options_bar_tests; #[cfg(test)] mod doc_tab_menu_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 92fc8a11ca..3838a70bcf 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -148,7 +148,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Edit"], "Menus…", Some("Cmd+Alt+Shift+M"), "edit.menus"), (&["Edit"], "Toolbar…", None, "edit.toolbar"), (&["Edit"], "---", None, "---"), - (&["Edit", "Preferences"], "Settings…", Some("Cmd+K"), "edit.preferences.general"), + (&["Edit", "Preferences"], "General…", Some("Cmd+K"), "edit.preferences.general"), (&["Edit", "Preferences"], "---", None, "---"), (&["Edit", "Preferences"], "AI Integrations…", None, "edit.preferences.integrations"), (&["Edit", "Preferences"], "Interface…", None, "edit.preferences.interface"), @@ -265,7 +265,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Layer"], "Quick Export as PNG", Some("Cmd+Shift+'"), "layer.quickExportAsPng"), (&["Layer"], "Export As…", Some("Cmd+Alt+Shift+'"), "layer.exportAs"), (&["Layer"], "---", None, "---"), - (&["Layer"], "Rename Layer", None, "layer.renameLayer"), + (&["Layer"], "Rename Layer…", None, "layer.renameLayer"), (&["Layer", "Layer Style"], "Blending Options…", None, "layer.layerStyle.blendingOptions"), (&["Layer", "Layer Style"], "Bevel & Emboss…", None, "layer.layerStyle.bevelEmboss"), (&["Layer", "Layer Style"], "Stroke…", None, "layer.layerStyle.stroke"), @@ -348,6 +348,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Layer", "Smart Objects"], "Update All Modified Content", None, "layer.smartObjects.updateAllModifiedContent"), (&["Layer", "Smart Objects"], "---", None, "---"), (&["Layer", "Smart Objects"], "Edit Contents", None, "layer.smartObjects.editContents"), + (&["Layer", "Smart Objects"], "Reset Transform", None, "layer.smartObjects.resetTransform"), (&["Layer", "Smart Objects"], "Relink to File…", None, "layer.smartObjects.relinkToFile"), (&["Layer", "Smart Objects"], "Replace Contents…", None, "layer.smartObjects.replaceContents"), (&["Layer", "Smart Objects"], "Export Contents…", None, "layer.smartObjects.exportContents"), @@ -534,7 +535,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Select"], "All", Some("Cmd+A"), "select.all"), (&["Select"], "Deselect", Some("Cmd+D"), "select.deselect"), (&["Select"], "Reselect", Some("Cmd+Shift+D"), "select.reselect"), - (&["Select"], "Inverse Selection", None, "select.inverse"), + (&["Select"], "Inverse", None, "select.inverse"), (&["Select"], "Convert to Shape", None, "select.convertToShape"), (&["Select"], "---", None, "---"), (&["Select"], "All Layers", Some("Cmd+Alt+A"), "select.allLayers"), @@ -636,12 +637,12 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Filter", "Stylize"], "Wind…", None, "filter.stylize.wind"), (&["Filter", "Video"], "De-Interlace…", None, "filter.video.deInterlace"), (&["Filter", "Video"], "NTSC Colors", None, "filter.video.ntscColors"), - (&["Filter", "Other…"], "Custom…", None, "filter.other.custom"), - (&["Filter", "Other…"], "HSB/HSL", None, "filter.other.hsbHsl"), - (&["Filter", "Other…"], "High Pass…", None, "filter.other.highPass"), - (&["Filter", "Other…"], "Maximum…", None, "filter.other.maximum"), - (&["Filter", "Other…"], "Minimum…", None, "filter.other.minimum"), - (&["Filter", "Other…"], "Offset…", None, "filter.other.offset"), + (&["Filter", "Other"], "Custom…", None, "filter.other.custom"), + (&["Filter", "Other"], "HSB/HSL", None, "filter.other.hsbHsl"), + (&["Filter", "Other"], "High Pass…", None, "filter.other.highPass"), + (&["Filter", "Other"], "Maximum…", None, "filter.other.maximum"), + (&["Filter", "Other"], "Minimum…", None, "filter.other.minimum"), + (&["Filter", "Other"], "Offset…", None, "filter.other.offset"), (&["View", "Proof Setup"], "Custom…", None, "view.proofSetup.custom"), (&["View", "Proof Setup"], "---", None, "---"), (&["View", "Proof Setup"], "Working CMYK", None, "view.proofSetup.workingCmyk"), @@ -655,8 +656,8 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["View", "Proof Setup"], "Internet Standard RGB (sRGB)", None, "view.proofSetup.internetStandardRgb"), (&["View", "Proof Setup"], "Monitor RGB", None, "view.proofSetup.monitorRgb"), (&["View", "Proof Setup"], "---", None, "---"), - (&["View", "Proof Setup"], "Color Blindness — Protanopia-type", None, "view.proofSetup.colorBlindnessProtanopia"), - (&["View", "Proof Setup"], "Color Blindness — Deuteranopia-type", None, "view.proofSetup.colorBlindnessDeuteranopia"), + (&["View", "Proof Setup"], "Color Blindness - Protanopia-type", None, "view.proofSetup.colorBlindnessProtanopia"), + (&["View", "Proof Setup"], "Color Blindness - Deuteranopia-type", None, "view.proofSetup.colorBlindnessDeuteranopia"), (&["View"], "Proof Colors", Some("Cmd+Y"), "view.proofColors"), (&["View"], "Gamut Warning", Some("Cmd+Shift+Y"), "view.gamutWarning"), (&["View"], "---", None, "---"), diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index fabce59420..4c36419c90 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -36,8 +36,8 @@ pub fn is_live(id: &str) -> bool { } /// Commands outside the catalogue that belong right after a catalogue item: `(id, after)`. -/// The command takes that item's submenu path, so it joins Photoshop's submenu even where the -/// catalogue spells it differently (Filter › "Other…"). +/// The command takes that item's submenu path, so it joins the catalogue's submenu rather than +/// opening a second one spelled from its own id (Filter › Other). const PLACE_AFTER: &[(&str, &str)] = &[ ("file.newFromClipboard", "file.new"), ("filter.render.relight", "filter.render.lightingEffects"), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 0eab47280f..69399fc068 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -123,10 +123,12 @@ fn color_to_alpha_sits_in_filter_other_after_offset() { let (offset, c2a) = (at("filter.other.offset"), at("filter.other.colorToAlpha")); assert_eq!(c2a, offset + 1); assert_eq!(items[c2a].path, items[offset].path); + assert_eq!(items[offset].path, ["Filter", "Other"]); assert_eq!(items[c2a].label, "Color to Alpha…"); assert!(items[c2a].enabled, "the Background becomes a layer when the filter runs"); let others: Vec<_> = items.iter().filter(|i| i.path.first().is_some_and(|p| p == "Filter") && i.path.len() == 2).map(|i| &i.path[1]).collect(); - assert!(!others.iter().any(|p| p.as_str() == "Other"), "no duplicate Other submenu: {others:?}"); + assert!(others.iter().any(|p| p.as_str() == "Other"), "the catalogue's Other submenu: {others:?}"); + assert!(!others.iter().any(|p| p.as_str() == "Other…"), "no second submenu spelled Other…: {others:?}"); } #[test] diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 8b80767e6f..c292065045 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -607,6 +607,88 @@ fn batch_dialogs_include_all_subfolders() { let _ = std::fs::remove_dir_all(&dir); } +/// #10682 / #10113: an action recorded with the Type tool (a new type layer, typed in key by key) +/// runs in Batch on every file of the folder and saves each into the destination. +#[test] +fn batch_runs_an_action_recorded_with_the_type_tool() { + let (mut app, ctx) = app_with(1); + let dir = std::env::temp_dir().join(format!("photocraft-ui-batch-type-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("in")).unwrap(); + for name in ["a.png", "b.png"] { + app.run("file.saveACopy", json!({"path": dir.join("in").join(name).to_string_lossy()})).unwrap(); + } + app.run("actions.record", json!({"name": "Caption"})).unwrap(); + let id = app.run("type.create", json!({"x": 10, "y": 40, "text": "", "size": 20})).unwrap()["layer"].as_u64().unwrap(); + for (i, c) in "Hi".chars().enumerate() { + app.run("type.edit", json!({"layer": id, "replace": {"start": i, "end": i, "text": c.to_string()}, "coalesce": "typing"})).unwrap(); + } + app.run("actions.stop", json!({})).unwrap(); + app.run("file.saveACopy", json!({"path": dir.join("ref.png").to_string_lossy()})).unwrap(); + assert_eq!(crate::actions::selected_action(&app).map(|a| a.steps.len()), Some(1), "one step for the typing"); + // CodeRabbit on #10730: and that step makes the layer with the text typed. + assert_eq!(crate::actions::selected_action(&app).and_then(|a| a.steps.first()).map(|(_, p)| p["text"].clone()), Some(json!("Hi"))); + let d = menu(&mut app, &ctx, "file.automate.batch", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let fields = &mut app.ui.dialog_mut(d).unwrap().fields; + fields.insert("input".into(), json!(dir.join("in").to_string_lossy())); + fields.insert("output".into(), json!(dir.join("out").to_string_lossy())); + let r = crate::dialogs::confirm(&mut app, d).unwrap(); + assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}"); + assert!(r.get("failed").is_none_or(|f| f.as_array().is_some_and(Vec::is_empty)), "{r}"); + for name in ["a.png", "b.png"] { + assert!(dir.join("out").join(name).is_file(), "{name} saved: {r}"); + // CodeRabbit on #10730: the action ran on each file: the typed text is in its pixels. + let pixels = |folder: &str| photocraft_codecs::decode(&std::fs::read(dir.join(folder).join(name)).unwrap()).unwrap().data().to_vec(); + assert_ne!(pixels("out"), pixels("in"), "{name}: the text was laid on it"); + } + // CodeRabbit on #10730: all of it, as typed by hand: the document the action was recorded + // on (the same image, with the text typed into it) has the pixels Batch wrote. + let decoded = |path: std::path::PathBuf| photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap().data().to_vec(); + for name in ["a.png", "b.png"] { + assert_eq!(decoded(dir.join("out").join(name)), decoded(dir.join("ref.png")), "{name}: Batch laid the whole text, as it was typed by hand"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// #10682: a Batch whose action fails on every file said nothing; the status bar and a notice now +/// name each file that failed and why. +#[test] +fn a_batch_that_fails_on_its_files_says_which_and_why() { + let (mut app, ctx) = app_with(1); + let dir = std::env::temp_dir().join(format!("photocraft-ui-batch-fails-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("in")).unwrap(); + for name in ["a.png", "b.png"] { + app.run("file.saveACopy", json!({"path": dir.join("in").join(name).to_string_lossy()})).unwrap(); + } + // A step for a layer that only the recording document has. + app.session + .actions + .list + .push(photocraft_engine::actions_cmds::Action::new("Stale", vec![("layer.setProps".into(), json!({"layer": 424_242, "opacity": 50}))])); + let d = menu(&mut app, &ctx, "file.automate.batch", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let fields = &mut app.ui.dialog_mut(d).unwrap().fields; + fields.insert("input".into(), json!(dir.join("in").to_string_lossy())); + fields.insert("output".into(), json!(dir.join("out").to_string_lossy())); + let notices = app.ui.notices.len(); + let r = crate::dialogs::confirm(&mut app, d).unwrap(); + assert_eq!(r["errors"].as_array().map(Vec::len), Some(2), "{r}"); + assert!(app.ui.status_error, "the status bar reports it: {}", app.ui.status); + let notice = app.ui.notices.get(notices).expect("a notice lists the files"); + assert_eq!(notice.lines.len(), 2); + // CodeRabbit on #10730: a failure, not a warning, and each file by its whole path. + assert!(notice.error && notice.title.ends_with("2 files failed"), "{}", notice.title); + let path = |name: &str| format!("{}: ", dir.join("in").join(name).to_string_lossy()); + assert!(notice.lines[0].starts_with(&path("a.png")) && notice.lines[1].starts_with(&path("b.png")), "{:?}", notice.lines); + // CodeRabbit on #10730: each line is its file's error, word for word, path then reason. + let errors = r["errors"].as_array().unwrap(); + for (line, e) in notice.lines.iter().zip(errors) { + assert!(!e["error"].as_str().unwrap_or_default().trim().is_empty(), "{e}"); + assert_eq!(*line, format!("{}: {}", e["file"].as_str().unwrap(), e["error"].as_str().unwrap())); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// Float in Window takes the document and the screen position a dragged-off tab was dropped at /// (#3733); bad params are errors, not panics. #[test] diff --git a/crates/ui-egui/src/move_bar_distribute_gear_tests.rs b/crates/ui-egui/src/move_bar_distribute_gear_tests.rs new file mode 100644 index 0000000000..45ebb91969 --- /dev/null +++ b/crates/ui-egui/src/move_bar_distribute_gear_tests.rs @@ -0,0 +1,438 @@ +//! #11381: the Move tool's options bar. The two Distribute buttons, the "..." icon panel (it +//! closes on a second click, not on Escape) and the gear menu with its three check items. + +use egui::{Rect as ScreenRect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +fn paint(app: &mut PhotocraftApp, r: Rect) -> LayerId { + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.active().unwrap().active_layer.unwrap() +} + +fn bounds(app: &PhotocraftApp, id: LayerId) -> Rect { + let doc = &app.session.active().unwrap().doc; + photocraft_compose::bounds::content_bounds(doc.layer(id).unwrap().surface().unwrap()) +} + +fn select_all(app: &mut PhotocraftApp, ids: &[LayerId]) { + app.session.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + app.session.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); + } +} + +/// A 120x120 document with three layers side by side and on top of each other unevenly, the +/// Move tool current. Returns the app and the layers, bottom to top. +fn app() -> (PhotocraftApp, [LayerId; 3]) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 120, "height": 120})).unwrap(); + let a = paint(&mut app, Rect::new(0, 0, 10, 10)); + let b = paint(&mut app, Rect::new(12, 50, 32, 54)); + let c = paint(&mut app, Rect::new(70, 60, 100, 80)); + app.sync_views(); + app.ui.tool = Tool::Move; + (app, [a, b, c]) +} + +/// The Move tool's align controls and gear, as the options bar lays them out. +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(700.0, 200.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| { + ui.horizontal(|ui| { + crate::align_bar::options(app, ui); + crate::align_bar::gear(app, ui); + }); + }); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} + +fn rect_of(h: &Harness<'static, PhotocraftApp>, label: &str) -> ScreenRect { + h.get_by_label(label).rect() +} + +fn click(h: &mut Harness<'static, PhotocraftApp>, label: &str) { + h.get_by_label(label).click(); + h.run_steps(4); +} + +const BAR: [&str; 10] = [ + "Align left edges", + "Align horizontal centers", + "Align right edges", + "Distribute vertically", + "Align top edges", + "Align vertical centers", + "Align bottom edges", + "Distribute horizontally", + "Align and distribute", + "Options", +]; + +#[test] +fn bar_buttons_and_tooltips_are_in_the_measured_order() { + let (app, _) = app(); + let h = harness(app); + let xs: Vec = BAR.iter().map(|l| rect_of(&h, l).left()).collect(); + assert!(xs.windows(2).all(|w| w[0] < w[1]), "left to right: {BAR:?} at {xs:?}"); + let ys: Vec = BAR.iter().map(|l| rect_of(&h, l).center().y).collect(); + assert!(ys.iter().all(|y| (y - ys[0]).abs() < 1.0), "one row: {ys:?}"); +} + +#[test] +fn distribute_vertically_button_runs_its_command() { + let (mut app, [a, b, c]) = app(); + select_all(&mut app, &[a, b, c]); + let mut h = harness(app); + assert!(!h.get_by_label("Distribute vertically").accesskit_node().is_disabled()); + click(&mut h, "Distribute vertically"); + // The same result as Layer > Distribute > Vertically: spans 0..80, heights 34, gaps 23. + assert_eq!(bounds(h.state(), b), Rect::new(12, 33, 32, 37)); + assert_eq!(bounds(h.state(), a), Rect::new(0, 0, 10, 10)); +} + +#[test] +fn distribute_horizontally_button_runs_its_command() { + let (mut app, [a, b, c]) = app(); + select_all(&mut app, &[a, b, c]); + let mut h = harness(app); + assert!(!h.get_by_label("Distribute horizontally").accesskit_node().is_disabled()); + click(&mut h, "Distribute horizontally"); + // Spans 0..100, widths 60, gaps 20: the middle layer starts at 30. + assert_eq!(bounds(h.state(), b), Rect::new(30, 50, 50, 54)); + assert_eq!(bounds(h.state(), c), Rect::new(70, 60, 100, 80)); +} + +#[test] +fn distribute_buttons_are_greyed_with_too_few_layers_like_the_menu() { + let (mut app, [a, b, c]) = app(); + select_all(&mut app, &[a, b]); + let mut h = harness(app); + for label in ["Distribute vertically", "Distribute horizontally"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} with two layers"); + } + for cmd in ["layer.distribute.vertically", "layer.distribute.horizontally"] { + assert!(!h.state().session.is_enabled(cmd), "{cmd} is off in the menu too"); + } + // Align still works with two layers. + assert!(!h.get_by_label("Align left edges").accesskit_node().is_disabled()); + select_all(h.state_mut(), &[a, b, c]); + h.run_steps(2); + assert!(!h.get_by_label("Distribute vertically").accesskit_node().is_disabled()); +} + +#[test] +fn ellipsis_panel_holds_align_and_distribute_and_closes_on_a_second_click_not_escape() { + let (app, _) = app(); + let mut h = harness(app); + assert!(h.query_by_label("Align: Left Edges").is_none(), "closed at first"); + click(&mut h, "Align and distribute"); + assert!(crate::align_bar::panel_is_open(&h.ctx)); + + let align = ["Left Edges", "Horizontal Centers", "Right Edges", "Top Edges", "Vertical Centers", "Bottom Edges"]; + let distribute = ["Top Edges", "Vertical Centers", "Bottom Edges", "Left Edges", "Horizontal Centers", "Right Edges"]; + let tips: Vec = align.iter().map(|l| format!("Align: {l}")).chain(distribute.iter().map(|l| format!("Distribute: {l}"))).collect(); + let rects: Vec = tips.iter().map(|t| rect_of(&h, t)).collect(); + // Align row above the Distribute row; each row runs left to right. + assert!(rects[..6].windows(2).all(|w| w[0].left() < w[1].left()), "align row: {rects:?}"); + assert!(rects[6..].windows(2).all(|w| w[0].left() < w[1].left()), "distribute row: {rects:?}"); + assert!(rects[5].bottom() <= rects[6].top() + 0.5, "the Distribute group is below the Align group"); + // The panel hangs under the "..." button. + assert!(rects[0].top() > rect_of(&h, "Align and distribute").bottom() - 0.5); + + // Escape leaves it open. + h.key_press(egui::Key::Escape); + h.run_steps(4); + assert!(crate::align_bar::panel_is_open(&h.ctx)); + assert!(h.query_by_label("Align: Left Edges").is_some()); + + // A second click on the button closes it. + click(&mut h, "Align and distribute"); + assert!(!crate::align_bar::panel_is_open(&h.ctx)); + assert!(h.query_by_label("Align: Left Edges").is_none()); +} + +#[test] +fn panel_icons_run_their_commands() { + let (mut app, [a, b, c]) = app(); + select_all(&mut app, &[a, b, c]); + let mut h = harness(app); + click(&mut h, "Align and distribute"); + click(&mut h, "Distribute: Left Edges"); + // Left edges 0, 12, 70 -> the middle one moves to 35. + assert_eq!(bounds(h.state(), b), Rect::new(35, 50, 55, 54)); +} + +#[test] +fn gear_menu_has_three_check_items_on_by_default_that_switch_the_options() { + let (app, _) = app(); + let mut h = harness(app); + click(&mut h, "Options"); + for label in ["Show layer bounds on hover", "Expand layer group on click", "Show hover bounds from Layers"] { + assert!(h.query_by_label(label).is_some(), "{label} is in the gear menu"); + } + click(&mut h, "Show layer bounds on hover"); + assert!(!h.state().ui.tool_options.move_show_hover_bounds); + click(&mut h, "Expand layer group on click"); + assert!(!h.state().ui.tool_options.move_expand_group_on_click); + click(&mut h, "Show hover bounds from Layers"); + assert!(!h.state().ui.tool_options.move_show_layers_hover_bounds); +} + +#[test] +fn gear_toggles_default_on_are_saved_and_reset() { + let o = ToolOptions::default(); + assert!(o.move_show_hover_bounds && o.move_expand_group_on_click && o.move_show_layers_hover_bounds); + + // Saved with the Move tool options: they are in the serde form that ui.inspect and ui.set use, + // and an older save without them reads as on. + let mut v = serde_json::to_value(&o).unwrap(); + for key in ["move_show_hover_bounds", "move_expand_group_on_click", "move_show_layers_hover_bounds"] { + assert_eq!(v[key], json!(true), "{key}"); + v[key] = json!(false); + } + let off: ToolOptions = serde_json::from_value(v.clone()).unwrap(); + assert!(!off.move_show_hover_bounds && !off.move_expand_group_on_click && !off.move_show_layers_hover_bounds); + for key in ["move_show_hover_bounds", "move_expand_group_on_click", "move_show_layers_hover_bounds"] { + v.as_object_mut().unwrap().remove(key); + } + let old: ToolOptions = serde_json::from_value(v).unwrap(); + assert!(old.move_show_hover_bounds && old.move_expand_group_on_click && old.move_show_layers_hover_bounds); + + // Tool > Reset Tool puts them back. + let (mut app, _) = app(); + app.ui.tool_options = off; + app.ui.tool_options.feather = 12.0; + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "tool.reset", json!({})).unwrap(); + let o = &app.ui.tool_options; + assert!(o.move_show_hover_bounds && o.move_expand_group_on_click && o.move_show_layers_hover_bounds); + assert_eq!(o.feather, 12.0, "another tool's option is left alone"); +} + +#[test] +fn show_layer_bounds_on_hover_switches_the_canvas_outline() { + let (mut app, [_, b, _]) = app(); + let b_bounds = bounds(&app, b); + assert_eq!(crate::move_hover::target(&mut app, Some([14.0, 52.0]), false, false), Some(b_bounds)); + app.ui.tool_options.move_show_hover_bounds = false; + assert_eq!(crate::move_hover::target(&mut app, Some([14.0, 52.0]), false, false), None); + assert_eq!(app.canvas_hover_layer, None); + app.ui.tool_options.move_show_hover_bounds = true; + assert_eq!(crate::move_hover::target(&mut app, Some([14.0, 52.0]), false, false), Some(b_bounds)); +} + +#[test] +fn show_hover_bounds_from_layers_switches_the_layers_panel_outline() { + let (mut app, [a, _, _]) = app(); + app.hover_layer = Some(a); + let a_bounds = bounds(&app, a); + assert_eq!(crate::move_hover::active_outline(&mut app, None, false, false), Some(a_bounds)); + app.ui.tool_options.move_show_layers_hover_bounds = false; + assert_eq!(crate::move_hover::active_outline(&mut app, None, false, false), None); + // The canvas outline is a separate switch. + assert!(crate::move_hover::active_outline(&mut app, Some([14.0, 52.0]), false, false).is_some()); + // Preferences > Show Highlight on Rollover stays the master switch. + app.ui.tool_options.move_show_layers_hover_bounds = true; + app.session.edit_prefs(|p| p.tools.show_highlight_on_rollover = false); + assert_eq!(crate::move_hover::active_outline(&mut app, None, false, false), None); +} + +fn expanded(app: &PhotocraftApp, group: LayerId) -> bool { + match &app.session.active().unwrap().doc.layer(group).unwrap().content { + photocraft_doc::LayerContent::Group(g) => g.expanded, + _ => panic!("not a group"), + } +} + +#[test] +fn expand_layer_group_on_click_switches_the_opening_of_closed_parent_groups() { + for on in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let inner = paint(&mut app, Rect::new(8, 8, 24, 24)); + app.session.execute("layer.groupLayers", json!({})).unwrap(); + let group = app.session.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.is_group()).map(|(_, _, l)| l.id).unwrap(); + app.session.execute("layer.setExpanded", json!({"layer": group.0, "expanded": false})).unwrap(); + app.session.execute("layer.select", json!({"layer": group.0})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_expand_group_on_click = on; + let ctx = egui::Context::default(); + // The first frame only records the active layer; then a canvas click picks the inner one. + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), None); + // The Move tool picks the layer under the pointer (Auto-Select targets layers, not groups). + app.ui.tool_options.move_target = "layer".into(); + crate::canvas::tool_event(&mut app, crate::canvas::ToolEvent::Down { x: 12.0, y: 12.0, pressure: 1.0 }, egui::Modifiers::default()); + crate::canvas::tool_event(&mut app, crate::canvas::ToolEvent::Up { x: 12.0, y: 12.0 }, egui::Modifiers::default()); + // The row is still revealed (scrolled to) either way. + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert_eq!(expanded(&app, group), on, "Expand layer group on click = {on}"); + } +} + +/// A 64x64 document: `inner` painted at (8..24)^2 inside a closed group, the Background-less +/// group selected, `tool` current and the gear option set to `on`. The reveal has seen the frame. +fn closed_group_doc(tool: Tool, on: bool) -> (PhotocraftApp, LayerId, LayerId, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let inner = paint(&mut app, Rect::new(8, 8, 24, 24)); + app.session.execute("layer.groupLayers", json!({})).unwrap(); + let group = app.session.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.is_group()).map(|(_, _, l)| l.id).unwrap(); + app.session.execute("layer.setExpanded", json!({"layer": group.0, "expanded": false})).unwrap(); + app.session.execute("layer.select", json!({"layer": group.0})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app.ui.tool_options.move_expand_group_on_click = on; + app.ui.tool_options.move_target = "layer".into(); + let ctx = egui::Context::default(); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), None); + (app, inner, group, ctx) +} + +/// A press and release at (12, 12) with Ctrl/Cmd held (a temporary Move from another tool). +fn ctrl_click(app: &mut PhotocraftApp) { + use crate::canvas::{ToolEvent, tool_event}; + let mods = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; + tool_event(app, ToolEvent::Down { x: 12.0, y: 12.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: 12.0, y: 12.0 }, mods); +} + +#[test] +fn expand_layer_group_on_click_off_keeps_the_group_closed_for_a_ctrl_click_from_another_tool() { + // Auto-Select off, so the Ctrl-click is the Move way of picking from the Brush. + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.ui.tool_options.move_auto_select = false; + ctrl_click(&mut app); + assert_eq!(app.session.active().unwrap().active_layer, Some(inner), "the Ctrl-click picked the layer"); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner), "the row still scrolls into view"); + assert!(!expanded(&app, group), "the group stays closed"); +} + +#[test] +fn expand_layer_group_on_click_on_opens_the_group_for_a_ctrl_click_from_another_tool() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, true); + app.ui.tool_options.move_auto_select = false; + ctrl_click(&mut app); + assert_eq!(app.session.active().unwrap().active_layer, Some(inner)); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(expanded(&app, group), "the group opens"); +} + +#[test] +fn expand_layer_group_on_click_off_keeps_the_group_closed_for_a_move_tool_click() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Move, false); + use crate::canvas::{ToolEvent, tool_event}; + tool_event(&mut app, ToolEvent::Down { x: 12.0, y: 12.0, pressure: 1.0 }, egui::Modifiers::default()); + tool_event(&mut app, ToolEvent::Up { x: 12.0, y: 12.0 }, egui::Modifiers::default()); + assert_eq!(app.session.active().unwrap().active_layer, Some(inner)); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(!expanded(&app, group)); +} + +#[test] +fn expand_layer_group_on_click_off_still_opens_the_group_for_other_active_layer_changes() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.run("layer.select", json!({"layer": inner.0})).unwrap(); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(expanded(&app, group), "a command that changes the active layer reveals it"); +} + +#[test] +fn expand_layer_group_on_click_governs_a_ctrl_click_pick_of_a_position_locked_layer() { + for on in [false, true] { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, on); + app.ui.tool_options.move_auto_select = false; + app.session.execute("layer.setProps", json!({"layer": inner.0, "locks": {"position": true}})).unwrap(); + ctrl_click(&mut app); + assert_eq!(app.session.active().unwrap().active_layer, Some(inner), "the Ctrl-click picked the locked layer (on = {on})"); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert_eq!(expanded(&app, group), on, "Expand layer group on click = {on}"); + } +} + +#[test] +fn a_pick_marker_the_hidden_layers_panel_never_read_does_not_hide_a_later_command_change() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.ui.tool_options.move_auto_select = false; + // A Move-way pick of the inner layer while the Layers panel draws nothing (no `track`). + ctrl_click(&mut app); + assert_eq!(app.session.active().unwrap().active_layer, Some(inner)); + // Frames pass without the panel, then commands change the layer twice and land on it again. + app.frame += 5; + app.run("layer.select", json!({"layer": group.0})).unwrap(); + app.run("layer.select", json!({"layer": inner.0})).unwrap(); + // The panel is shown again: the change was a command's, so the group opens. + app.frame += 1; + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(expanded(&app, group), "a command change after a stale pick expands the group"); +} + +#[test] +fn a_pick_marker_survives_any_number_of_frames_while_the_layers_panel_is_hidden() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.ui.tool_options.move_auto_select = false; + ctrl_click(&mut app); + app.frame += 5; + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(!expanded(&app, group), "the pick is still the latest change of the active layer"); +} + +#[test] +fn commands_after_a_pick_in_the_same_frame_or_the_next_make_it_a_command_change() { + for gap in [0, 1] { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.ui.tool_options.move_auto_select = false; + ctrl_click(&mut app); + app.frame += gap; + app.run("layer.select", json!({"layer": group.0})).unwrap(); + app.run("layer.select", json!({"layer": inner.0})).unwrap(); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(expanded(&app, group), "selects {gap} frame(s) after the pick reveal the layer"); + } +} + +#[test] +fn a_pick_marker_is_read_once_and_governs_the_next_change_only() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.ui.tool_options.move_auto_select = false; + ctrl_click(&mut app); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(!expanded(&app, group)); + app.run("layer.select", json!({"layer": group.0})).unwrap(); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(group)); + app.run("layer.select", json!({"layer": inner.0})).unwrap(); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(expanded(&app, group), "a later command change opens the group"); +} + +#[test] +fn direct_selection_calls_after_a_pick_make_it_a_command_change() { + let (mut app, inner, group, ctx) = closed_group_doc(Tool::Brush, false); + app.ui.tool_options.move_auto_select = false; + ctrl_click(&mut app); + app.session.select_layer(group).unwrap(); + app.session.select_layer(inner).unwrap(); + assert_eq!(crate::layer_reveal::track(&mut app, &ctx), Some(inner)); + assert!(expanded(&app, group), "a direct selection away and back is not a pick"); +} diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index f2025a0d78..32c4d22999 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -184,6 +184,18 @@ pub fn io_warnings(app: &mut PhotocraftApp, what: &str, warnings: &[String]) { post(app, title, warnings.to_vec(), false, None); } +/// Report the files a folder run (Batch, Image Processor, …) could not process, one line each: +/// the status bar shows the first as an error, and a notice titled with how many failed lists +/// them all until dismissed (#10682). +pub fn file_failures(app: &mut PhotocraftApp, what: &str, failures: &[String]) { + let Some(first) = failures.first() else { return }; + let n = failures.len(); + let title = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n as u64, "{what}: {n} file failed", "{what}: {n} files failed"), &[("what", what)]); + app.ui.status = if n == 1 { format!("{what}: {first}") } else { format!("{title}: {first} …") }; + app.ui.status_error = true; + post(app, title, failures.to_vec(), true, None); +} + /// Report a failed file operation: the status bar shows it as an error and a notice keeps it on /// screen until dismissed. pub fn error(app: &mut PhotocraftApp, message: String) { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 9fd21b2f20..0d40e2280b 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -104,6 +104,7 @@ use options_bar::options_bar_height; pub(crate) use options_bar::{FIXED_SIZE_MAX_PX, opt_label}; pub use panel_state::{migrate_panel_state, panel_state_id, remember_panel_state}; pub use properties::properties_window; +pub(crate) use properties::selection_mode_buttons; #[cfg(test)] use properties::{adjustments_grid, properties_body}; pub use status_bar::{status_bar, status_bar_heights}; @@ -112,7 +113,8 @@ use title_bar::title_x; pub use title_bar::{sync_window_title, system_title_bar, title_bar, window_title}; #[cfg(test)] use toolbar::{ - STUDIO_CHIP, TOOL_SECTIONS, chips_height, color_chips, next_slot_tool, tool_flyout_drag_open, tool_flyout_release, toolbar_icon_size, visible_sections, + STUDIO_CHIP, TOOL_SECTIONS, chips_height, color_chips, next_slot_tool, slot_tool, tool_flyout_drag_open, tool_flyout_release, toolbar_icon_size, + visible_sections, }; pub use toolbar::{paint_toolbar_flyout_indicator, toolbar}; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index ee83682dcd..9c07f56255 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -36,21 +36,27 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf } /// Options-bar Smoothing % (the brush's stroke smoothing; the live stroke and the commit use it). -pub(super) fn smoothing_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) { +pub(super) fn smoothing_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) -> egui::Response { let mut sm = (b.smoothing.amount * 100.0).round(); - if widgets::value_field_named(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width).changed() { + let r = widgets::value_field_named(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width); + if r.changed() { b.smoothing.enabled = true; b.smoothing.amount = (sm / 100.0).clamp(0.0, 1.0); } + r } /// Options-bar gear beside Smoothing: Photoshop's smoothing options popup, edited on the brush /// like the Smoothing % (so they stay per tool and reach the live stroke and the commit). -pub(super) fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) { +/// `brush` adds the Brush's "Smoothing Options" title (#11813); the Eraser keeps its popup as it was. +pub(super) fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, brush: bool) { let resp = icons::button(ui, "settings", 24.0, false, tl!("Set additional smoothing options")); let resp = crate::brush_picker::named(resp, "Set additional smoothing options"); egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { let s = &mut b.smoothing; + if brush { + ui.label(egui::RichText::new(tl!("Smoothing Options")).strong()); + } widgets::checkbox(ui, &mut s.pulled_string, tl!("Pulled String Mode")); widgets::checkbox(ui, &mut s.catch_up, tl!("Stroke Catch-up")); widgets::checkbox(ui, &mut s.catch_up_on_end, tl!("Catch-up on Stroke End")); @@ -119,7 +125,9 @@ pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushS ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", b.size.round() as i64), egui::FontId::proportional(9.5), t.text_dim); icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, c.y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Brush Preset picker"))); - if resp.on_hover_text(tl!("Brush Preset picker")).clicked() { + // The Brush's own text (#11813); the other tools keep theirs. + let tip = if state.tool == crate::state::Tool::Brush { tl!("Click to open the Brush Preset picker") } else { tl!("Brush Preset picker") }; + if resp.on_hover_text(tip).clicked() { if state.brush_picker.is_some() { crate::brush_picker::close(state); } else { diff --git a/crates/ui-egui/src/panels/brush_preview.rs b/crates/ui-egui/src/panels/brush_preview.rs index f77975d45c..ba345d51e7 100644 --- a/crates/ui-egui/src/panels/brush_preview.rs +++ b/crates/ui-egui/src/panels/brush_preview.rs @@ -296,7 +296,9 @@ mod tests { #[test] fn preview_draws_a_stroke_that_fits() { - let mut b = BrushSettings { size: 400.0, ..Default::default() }; + // The preview's S-curve carries a pressure ramp, so the coverage window below is a + // tapering stroke's: Pressure for Size is off by default since #11809, so the brush asks. + let mut b = BrushSettings { size: 400.0, pressure_size: true, ..Default::default() }; let px = preview_pixels(&b, 120, 40, [1.0, 0.0, 0.0, 1.0]); assert_eq!(px.len(), 120 * 40 * 4); let covered = px.as_chunks::<4>().0.iter().filter(|p| p[3] > 128).count(); diff --git a/crates/ui-egui/src/panels/color_panel_ui.rs b/crates/ui-egui/src/panels/color_panel_ui.rs index 22665b2150..e05bac9440 100644 --- a/crates/ui-egui/src/panels/color_panel_ui.rs +++ b/crates/ui-egui/src/panels/color_panel_ui.rs @@ -352,8 +352,8 @@ pub(crate) fn alerts(app: &mut PhotocraftApp, ui: &mut egui::Ui, col: Rect, rgb: let background = app.ui.color_panel.background; let mut y = col.top() + CHIPS_W + 2.0; let warnings = [ - (out_of_gamut(rgb), "Out of gamut for printing: click for the nearest printable colour", false), - (if web { not_web_safe(rgb) } else { None }, "Not a web colour: click for the nearest web colour", true), + (out_of_gamut(rgb), "Out of gamut for printing: click for the nearest printable color", false), + (if web { not_web_safe(rgb) } else { None }, "Not a web color: click for the nearest web color", true), ]; for (slot, (near, tip, cube)) in warnings.into_iter().enumerate() { let Some(near) = near else { continue }; diff --git a/crates/ui-egui/src/panels/color_tests.rs b/crates/ui-egui/src/panels/color_tests.rs index 30ecfaf3e7..9900221099 100644 --- a/crates/ui-egui/src/panels/color_tests.rs +++ b/crates/ui-egui/src/panels/color_tests.rs @@ -160,11 +160,11 @@ fn studio_color_chips_keep_default_and_swap_buttons_below() { ); PhotocraftApp::setup_context(&h.ctx, kind); h.run_steps(2); - h.get_by_label("Swap colours (X)").click(); + h.get_by_label("Switch Foreground and Background Colors (X)").click(); h.run_steps(2); assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0], "{kind:?}"); assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0], "{kind:?}"); - h.get_by_label("Default colours (D)").click(); + h.get_by_label("Default Foreground and Background Colors (D)").click(); h.run_steps(2); assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "{kind:?}"); assert_eq!(h.state().session.tools.background, [1.0, 1.0, 1.0, 1.0], "{kind:?}"); @@ -219,7 +219,7 @@ fn swap_and_default_colors_recolour_selected_type() { ); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); h.run_steps(2); - h.get_by_label("Swap colours (X)").click(); + h.get_by_label("Switch Foreground and Background Colors (X)").click(); h.run_steps(2); assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0]); assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0]); @@ -228,7 +228,7 @@ fn swap_and_default_colors_recolour_selected_type() { assert_eq!((rgb(h.state(), id, 6), rgb(h.state(), id, 10)), (blue, blue), "selected: {selected}"); // Default Colors: the selection takes black, the new foreground. h.state_mut().run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); - h.get_by_label("Default colours (D)").click(); + h.get_by_label("Default Foreground and Background Colors (D)").click(); h.run_steps(2); assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0]); assert_eq!(rgb(h.state(), id, 6), [0, 0, 0, 255], "selected: {selected}"); diff --git a/crates/ui-egui/src/panels/compact_visual_regressions.rs b/crates/ui-egui/src/panels/compact_visual_regressions.rs index c4fdf59abc..40845fa460 100644 --- a/crates/ui-egui/src/panels/compact_visual_regressions.rs +++ b/crates/ui-egui/src/panels/compact_visual_regressions.rs @@ -94,7 +94,7 @@ fn tall_toolbar_keeps_the_colour_chips_under_the_tools() { for kind in theme::ThemeKind::ALL { let harness = toolbar_harness_sized(kind, 1.0, 1600.0); let last = harness.get_by_label("Edit Toolbar…").rect(); - let swap = harness.get_by_label("Swap colours (X)").rect(); + let swap = harness.get_by_label("Switch Foreground and Background Colors (X)").rect(); assert!(swap.top() - last.bottom() < 80.0, "{kind:?}: the chips {swap:?} sit far below the last tool {last:?}"); } } diff --git a/crates/ui-egui/src/panels/layer_drag.rs b/crates/ui-egui/src/panels/layer_drag.rs index 35903dcf61..aea09ab6ee 100644 --- a/crates/ui-egui/src/panels/layer_drag.rs +++ b/crates/ui-egui/src/panels/layer_drag.rs @@ -314,6 +314,23 @@ pub(super) fn fx_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, } } +/// A layer mask's thumbnail dropped on another layer or group moves the mask there, ⌥ copies it, +/// as in Photoshop (#10485). A row that has a layer mask already doesn't take the drop (Photoshop +/// asks whether to replace it). Only the part of the row the list shows takes it: a row scrolled +/// out of view still lies under the panel's header or footer. +pub(super) fn mask_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, actions: &mut Vec<(String, Value)>) { + let Some((from, MaskKind::Pixel)) = ctx.data(|d| d.get_temp::(mask_drag_key())) else { return }; + let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; + if from == l.id.0 || l.mask.is_some() || !rect.intersect(ui.clip_rect()).contains(p) { + return; + } + let t = Tokens::get(ctx); + ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); + if ctx.input(|i| i.pointer.any_released()) { + actions.push(("layer.layerMask.moveTo".into(), json!({"layer": from, "to": l.id.0, "copy": ctx.input(|i| i.modifiers.alt)}))); + } +} + /// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect). The eye /// on "Effects" shows or hides them all, the eye on an effect's row just that one (#1622). pub(super) fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) { diff --git a/crates/ui-egui/src/panels/layer_menu_ui.rs b/crates/ui-egui/src/panels/layer_menu_ui.rs index c025f005da..6158ba8997 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui.rs @@ -59,7 +59,7 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec { // 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!("Quick Export as PNG"), "layer.quickExportAsPng"))); v.push(Some((tl!("Export As…"), "layer.exportAs"))); v.push(None); v.push(Some((tl!("Artboard from Layers…"), "layer.new.artboardFromLayers"))); @@ -76,10 +76,15 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec { v.push(Some(("Rasterize Layers", "layer.rasterize.layer"))); } else { match &l.content { - LayerContent::Text(_) => v.push(Some(("Rasterize Type", "layer.rasterize.type"))), + LayerContent::Text(_) => { + v.push(Some(("Rasterize Type", "layer.rasterize.type"))); + v.push(Some((tl!("Create Work Path"), "type.createWorkPath"))); + v.push(Some((tl!("Convert to Shape"), "type.convertToShape"))); + } LayerContent::Shape(_) => v.push(Some(("Rasterize Layer", "layer.rasterize.shape"))), LayerContent::Smart(_) => { v.push(Some((tl!("Edit Contents"), "layer.smartObjects.editContents"))); + v.push(Some((tl!("Reset Transform"), "layer.smartObjects.resetTransform"))); v.push(Some((tl!("Replace Contents…"), "layer.smartObjects.replaceContents"))); v.push(Some((tl!("Relink to File…"), "layer.smartObjects.relinkToFile"))); v.push(Some((tl!("Convert to Layers"), "layer.smartObjects.convertToLayers"))); 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 a7ab70a76e..11c29e58ba 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs @@ -271,11 +271,37 @@ fn edit_contents_is_available_only_for_smart_objects() { let ids: Vec<_> = entries(&layer(&s), false, false).into_iter().flatten().map(|e| e.1).collect(); let edit = ids.iter().position(|id| *id == "layer.smartObjects.editContents").expect("Edit Contents entry"); assert_eq!( - ids[edit + 1..edit + 5], - ["layer.smartObjects.replaceContents", "layer.smartObjects.relinkToFile", "layer.smartObjects.convertToLayers", "layer.rasterize.smartObject"] + ids[edit + 1..edit + 6], + [ + "layer.smartObjects.resetTransform", + "layer.smartObjects.replaceContents", + "layer.smartObjects.relinkToFile", + "layer.smartObjects.convertToLayers", + "layer.rasterize.smartObject" + ], + "Reset Transform follows Edit Contents, as in the reference flyout" ); } +/// A type layer's menu offers Photoshop's outline conversions after Rasterize Type, and Convert +/// to Shape from it turns the text into a shape layer. +#[test] +fn type_layer_menu_converts_to_shape() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 8, "y": 32})).unwrap(); + let layer = |s: &photocraft_engine::Session| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().clone() + }; + let ids: Vec<_> = entries(&layer(&s), false, false).into_iter().flatten().map(|e| e.1).collect(); + let r = ids.iter().position(|id| *id == "layer.rasterize.type").expect("Rasterize Type entry"); + assert_eq!(ids[r + 1..r + 3], ["type.createWorkPath", "type.convertToShape"]); + assert!(!entries(&layer(&s), true, false).iter().flatten().any(|e| e.1 == "type.convertToShape"), "the selection menu keeps one Rasterize item"); + s.execute("type.convertToShape", json!({})).unwrap(); + assert!(matches!(layer(&s).content, LayerContent::Shape(_))); +} + /// Right-clicking inside a multi-layer selection offers one Rasterize item for the whole /// selection, whatever kind the clicked layer is, and no single-layer Smart Object items. #[test] @@ -289,12 +315,14 @@ fn multi_selection_menu_rasterizes_the_selection() { let smart = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); let ids = |multi| entries(&smart, multi, false).into_iter().flatten().map(|e| e.1).collect::>(); assert!(ids(false).contains(&"layer.smartObjects.editContents"), "a single smart object keeps its items"); + assert!(ids(false).contains(&"layer.smartObjects.resetTransform"), "and its Reset Transform"); let multi = ids(true); assert!(multi.contains(&"layer.rasterize.layer")); for single in [ "layer.rasterize.smartObject", "layer.rasterize.shape", "layer.smartObjects.editContents", + "layer.smartObjects.resetTransform", "layer.smartObjects.replaceContents", "layer.smartObjects.relinkToFile", "layer.smartObjects.convertToLayers", @@ -394,7 +422,7 @@ fn multi_selection_menu_greys_what_acts_on_one_layer() { assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} works on one layer only"); } for label in [ - "Quick Export As PNG", + "Quick Export as PNG", "Export As…", "Add Layer Mask", "Duplicate Layers…", diff --git a/crates/ui-egui/src/panels/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs index ea5908abe2..315e762a1b 100644 --- a/crates/ui-egui/src/panels/layer_props_ui.rs +++ b/crates/ui-egui/src/panels/layer_props_ui.rs @@ -51,15 +51,32 @@ fn edit_tolerance(layer: &Layer, u: LenUnit, extent: f64) -> f32 { /// A number field that reports a value once committed (drag released, Enter, focus lost). `label` is its own /// label and the one stacked with it in the same column ("W" over "X"), which share a centre. +/// `id` names the field and the layer it edits. /// `len` is the unit shown, its 100% extent (for percent) and the length a percentage typed into a /// length field is a share of (`50%` in a px W is half the current width, as in Photoshop, /// #10784); `name` is the field's accessible name. // The explicit accessible name accompanies the existing numeric-field parameters. #[expect(clippy::too_many_arguments)] -fn field(ui: &mut egui::Ui, id: &str, label: (&str, &str), name: &str, current: f32, width: f32, len: (LenUnit, f64, f64), tol: f32) -> Option { +fn field(ui: &mut egui::Ui, id: (&str, u64), label: (&str, &str), name: &str, current: f32, width: f32, len: (LenUnit, f64, f64), tol: f32) -> Option { let (u, extent, typed_pct) = len; + let (id, layer) = id; stacked_label(ui, tl!(label.0), &[tl!(label.0), tl!(label.1)], LABEL_W, 2.0); let key = ui.make_persistent_id(("layer-props-field", id)); + // A wheeled value waiting for its gesture to end is its layer's, held while it is drawn. + // It is dropped rather than applied when another layer was made active in the meantime, when + // a pass went by without the field (the section collapsed, a layer without these fields + // shown), however briefly, or when what it edits changed underneath it (an Undo): applied + // later it would be a stale edit. + let wheel_key = key.with("wheel"); + let pass = ui.ctx().cumulative_pass_nr(); + let held = ui.data(|d| d.get_temp::<(u64, u64, u32)>(wheel_key)); + let pending = held.is_some_and(|(l, drawn, from)| l == layer && pass.saturating_sub(drawn) <= 1 && from == current.to_bits()); + if held.is_some() && !pending { + ui.data_mut(|d| { + d.remove::<(u64, u64, u32)>(wheel_key); + d.remove::(key); + }); + } let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or_else(|| u.shown(f64::from(current), extent)); // A field showing percent keeps its own 100%, so a length typed into it converts as shown. // Otherwise the current size, while the field is edited: clicking from W into a linked H @@ -75,12 +92,24 @@ fn field(ui: &mut egui::Ui, id: &str, label: (&str, &str), name: &str, current: } else { ui.data_mut(|d| d.remove::(pct_key)); } + // The wheel over the field is held like a drag: each notch applied as its own edit resampled + // the layer again from the last result, and a fast scroll destroyed it (#9898). + let wheeled = resp.changed() || pending; + if wheeled && !resp.dragged() && !resp.has_focus() && crate::field_wheel::field_gesture_running(ui.ctx()) { + ui.data_mut(|d| { + d.insert_temp(key, v); + d.insert_temp(wheel_key, (layer, pass, current.to_bits())); + }); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(crate::field_wheel::GESTURE_GAP)); + return None; + } if resp.dragged() || resp.has_focus() { ui.data_mut(|d| d.insert_temp(key, v)); return None; } + let wheel_ended = ui.data_mut(|d| d.remove_temp::<(u64, u64, u32)>(wheel_key)).is_some(); ui.data_mut(|d| d.remove::(key)); - if !(resp.drag_stopped() || resp.lost_focus() || resp.changed()) { + if !(resp.drag_stopped() || resp.lost_focus() || resp.changed() || wheel_ended) { return None; } let px = u.px(v, extent) as f32; @@ -182,24 +211,24 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { let w = ((ui.available_width() - 2.0 * (LABEL_W + LABEL_GAP) - LINK_W - 2.0 * LABEL_GAP) / 2.0).max(36.0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = LABEL_GAP; - if let Some(v) = field(ui, "w", ("W", "X"), "Width", (bb[2] - bb[0]) as f32, w, (u, dw, bb[2] - bb[0]), tw) { + if let Some(v) = field(ui, ("w", layer.id.0), ("W", "X"), "Width", (bb[2] - bb[0]) as f32, w, (u, dw, bb[2] - bb[0]), tw) { run.extend(transform_params(layer.id.0, bb, Some(v), None, linked, tw).map(|p| ("edit.transform".to_string(), p))); } if crate::icons::button(ui, if linked { "link" } else { "unlink" }, LINK_W, linked, tl!("Link width and height")).clicked() { ui.data_mut(|d| d.insert_temp(link_key, !linked)); } - if let Some(v) = field(ui, "h", ("H", "Y"), "Height", (bb[3] - bb[1]) as f32, w, (u, dh, bb[3] - bb[1]), th) { + if let Some(v) = field(ui, ("h", layer.id.0), ("H", "Y"), "Height", (bb[3] - bb[1]) as f32, w, (u, dh, bb[3] - bb[1]), th) { run.extend(transform_params(layer.id.0, bb, None, Some(v), linked, th).map(|p| ("edit.transform".to_string(), p))); } }); ui.add_space(ROW_GAP); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = LABEL_GAP; - if let Some(v) = field(ui, "x", ("X", "W"), "X", bb[0] as f32, w, (u, dw, dw), 0.5) { + if let Some(v) = field(ui, ("x", layer.id.0), ("X", "W"), "X", bb[0] as f32, w, (u, dw, dw), 0.5) { run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": (v - bb[0] as f32).round() as i32, "dy": 0}))); } ui.add_space(LINK_W + LABEL_GAP); - if let Some(v) = field(ui, "y", ("Y", "H"), "Y", bb[1] as f32, w, (u, dh, dh), 0.5) { + if let Some(v) = field(ui, ("y", layer.id.0), ("Y", "H"), "Y", bb[1] as f32, w, (u, dh, dh), 0.5) { run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": 0, "dy": (v - bb[1] as f32).round() as i32}))); } }); @@ -363,6 +392,371 @@ mod tests { assert!((at("H") - at("Y")).abs() < 0.01, "H and Y: {centres:?}"); } + /// #9898: wheeling over W applied each notch as its own Free Transform, resampling the layer + /// again from the last result until a fast scroll destroyed it. A wheel gesture is one edit, + /// applied when it stops, from the pixels it started with. + #[test] + fn wheeling_the_width_is_one_transform_when_the_wheel_stops() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(0.05).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + crate::field_wheel::begin_frame(ui.ctx()); + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let history = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let width = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + h.state_mut().layer_frame_bounds(&layer, layer.surface().unwrap()).width() + }; + let before = history(&h); + assert_eq!(width(&mut h), 100); + let at = h.get_by_label("Width").rect().center(); + h.hover_at(at); + h.run_steps(1); + for _ in 0..8 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + assert_eq!(history(&h), before, "nothing applied while the wheel turns"); + assert_eq!(width(&mut h), 100); + h.run_steps(12); + assert_eq!(history(&h), before + 1, "one edit for the whole gesture"); + assert_eq!(width(&mut h), 108); + } + + /// A wheeled width still waiting for its gesture to end is dropped, not applied to another + /// layer made active in the meantime (or to its own when it is made active again). + #[test] + fn a_wheeled_width_is_not_applied_to_another_layer() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + let mut layers = Vec::new(); + for (x, w) in [(10, 100), (120, 40)] { + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": x, "y": 10, "width": w, "height": 40})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + layers.push(app.session.active().unwrap().active_layer.unwrap()); + } + app.run("layer.select", json!({"layer": layers[0].0})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(0.05).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + crate::field_wheel::begin_frame(ui.ctx()); + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let widths = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + let doc = h.state().session.active().unwrap().doc.clone(); + layers + .iter() + .map(|id| doc.layer(*id).unwrap().clone()) + .map(|l| h.state_mut().layer_frame_bounds(&l, l.surface().unwrap()).width()) + .collect::>() + }; + assert_eq!(widths(&mut h), vec![100, 40]); + let at = h.get_by_label("Width").rect().center(); + h.hover_at(at); + h.run_steps(1); + for _ in 0..3 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.state_mut().run("layer.select", json!({"layer": layers[1].0})).unwrap(); + h.run_steps(12); + assert_eq!(widths(&mut h), vec![100, 40], "the other layer took the first one's wheeled width"); + h.state_mut().run("layer.select", json!({"layer": layers[0].0})).unwrap(); + h.run_steps(12); + assert_eq!(widths(&mut h), vec![100, 40], "the dropped width came back on its own layer"); + } + + /// A wheeled width whose field stops being drawn before the gesture ends (Transform + /// collapsed) is dropped, not applied as a stale edit when the field shows again. + #[test] + fn a_wheeled_width_left_undrawn_is_dropped() { + use egui_kittest::kittest::Queryable; + let hide = egui::Id::unique("test-hide-layer-props"); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(0.05).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + crate::field_wheel::begin_frame(ui.ctx()); + if ui.data(|d| d.get_temp::(hide)).unwrap_or(false) { + return; + } + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let history = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let before = history(&h); + let at = h.get_by_label("Width").rect().center(); + h.hover_at(at); + h.run_steps(1); + for _ in 0..3 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.ctx.data_mut(|d| d.insert_temp(hide, true)); + h.run_steps(40); + h.ctx.data_mut(|d| d.insert_temp(hide, false)); + h.run_steps(12); + assert_eq!(history(&h), before, "the stale wheeled width was applied when the field showed again"); + } + + /// An Undo while a wheeled width waits drops it: applied afterwards it would redo the edit + /// the Undo just took back, under a new history step. + #[test] + fn a_wheeled_width_is_dropped_by_an_undo_during_the_gesture() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let width = |app: &mut PhotocraftApp| { + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + app.layer_frame_bounds(&layer, layer.surface().unwrap()).width() + }; + let original = width(&mut app); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let bb = frame(&layer, app.layer_frame_bounds(&layer, layer.surface().unwrap())); + let p = transform_params(layer.id.0, bb, Some((bb[2] - bb[0]) as f32 + 20.0), None, false, 0.5).unwrap(); + app.run("edit.transform", p).unwrap(); + assert!(width(&mut app) > original); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(0.05).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + crate::field_wheel::begin_frame(ui.ctx()); + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let at = h.get_by_label("Width").rect().center(); + h.hover_at(at); + h.run_steps(1); + for _ in 0..3 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.state_mut().run("edit.undo", json!({})).unwrap(); + let history = h.state().session.active().unwrap().history.past_len(); + h.run_steps(40); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history, "the wheeled width was applied after the Undo"); + assert_eq!(width(h.state_mut()), original, "the Undo stands"); + } + + /// A wheeled width is dropped when a layer without these fields (a group) is shown, even for + /// a moment: going back to the layer before the gesture ends must not apply it. + #[test] + fn a_wheeled_width_is_dropped_by_a_moment_on_a_group() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.group", json!({})).unwrap(); + let group = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.select", json!({"layer": layer.0})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(0.05).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + crate::field_wheel::begin_frame(ui.ctx()); + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let history = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let at = h.get_by_label("Width").rect().center(); + h.hover_at(at); + h.run_steps(1); + for _ in 0..3 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.state_mut().run("layer.select", json!({"layer": group.0})).unwrap(); + h.run_steps(2); + h.state_mut().run("layer.select", json!({"layer": layer.0})).unwrap(); + let before = history(&h); + h.run_steps(40); + assert_eq!(history(&h), before, "the wheeled width was applied after a moment on the group"); + } + + /// Moving straight from wheeling W to wheeling H is still W's gesture: W's value lands as + /// soon as the wheel turns off it, and H doesn't step until a gesture of its own, so the + /// two never apply from the same original box together. + #[test] + fn wheeling_width_then_height_applies_each_once() { + use egui_kittest::kittest::Queryable; + let setup = || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app + }; + let app = setup(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(0.05).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + return; + } + crate::field_wheel::begin_frame(ui.ctx()); + let state = app.session.active().unwrap(); + let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); + properties(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let history = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let size = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let r = h.state_mut().layer_frame_bounds(&layer, layer.surface().unwrap()); + (r.width(), r.height()) + }; + let before = history(&h); + let notch = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + }; + let (w_at, h_at) = (h.get_by_label("Width").rect().center(), h.get_by_label("Height").rect().center()); + // What W's four notches alone make, and H's two after them, applied the same way on a copy + // of the document. + let (w_only, then_h) = { + let mut app = setup(); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let bb = frame(&layer, app.layer_frame_bounds(&layer, layer.surface().unwrap())); + let p = transform_params(layer.id.0, bb, Some((bb[2] - bb[0]) as f32 + 4.0), None, true, 0.5).unwrap(); + app.run("edit.transform", p).unwrap(); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let r = app.layer_frame_bounds(&layer, layer.surface().unwrap()); + let w_only = (r.width(), r.height()); + let bb = frame(&layer, r); + let p = transform_params(layer.id.0, bb, None, Some((bb[3] - bb[1]) as f32 + 2.0), true, 0.5).unwrap(); + app.run("edit.transform", p).unwrap(); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let r = app.layer_frame_bounds(&layer, layer.surface().unwrap()); + (w_only, (r.width(), r.height())) + }; + h.hover_at(w_at); + h.run_steps(1); + for _ in 0..4 { + notch(&mut h); + } + h.hover_at(h_at); + h.run_steps(1); + for _ in 0..4 { + notch(&mut h); + } + h.run_steps(20); + assert_eq!(history(&h), before + 1, "W applied once, H not stepped by W's gesture"); + assert_eq!(size(&mut h), w_only, "W's four notches, linked, and nothing from H"); + // A new gesture over H is H's own. + for _ in 0..2 { + notch(&mut h); + } + h.run_steps(20); + assert_eq!(history(&h), before + 2); + assert_eq!(size(&mut h), then_h, "H's two notches, linked"); + } + /// Types each `(name, text)` of `edits` in turn into the Transform field named `name` of an /// 80 × 40 px rectangle shape at (10, 10) in a 200 × 120 document, with the rulers in `unit`, /// and returns its path's [x, y, w, h] (a shape's path scales exactly, where resampled pixels diff --git a/crates/ui-egui/src/panels/layer_reveal.rs b/crates/ui-egui/src/panels/layer_reveal.rs index 2b9976de1b..9ae5eb01cb 100644 --- a/crates/ui-egui/src/panels/layer_reveal.rs +++ b/crates/ui-egui/src/panels/layer_reveal.rs @@ -27,6 +27,11 @@ pub fn track(app: &mut PhotocraftApp, ctx: &egui::Context) -> Option { let index = app.session.active_index()?; let active = app.session.active()?.active_layer; let now = Seen(index, active); + // The marker says the latest active-layer change was a Move-way pick of that layer: it holds only + // while no later change happened (the engine's change count is unchanged), however many frames a + // hidden panel missed, and whether or not the final layer is the same id. + let changes = app.session.active_layer_changes(); + let pick = app.move_pick.take().filter(|&(id, at)| Some(id) == active && at == changes).map(|(id, _)| id); let before = ctx.data(|d| d.get_temp::(seen_id())); ctx.data_mut(|d| d.insert_temp(seen_id(), now)); match before { @@ -34,7 +39,12 @@ pub fn track(app: &mut PhotocraftApp, ctx: &egui::Context) -> Option { _ => return None, } let id = active?; - for group in closed_ancestors(app, id) { + // Expand layer group on click (Move gear menu, #11381) governs a canvas click that picked this + // layer the Move tool way (Auto-Select, or a ⌘-click from another tool); every other change + // opens the groups. The row still scrolls into view. + let move_pick = pick == Some(id); + let expand = !move_pick || app.ui.tool_options.move_expand_group_on_click; + for group in closed_ancestors(app, id).into_iter().filter(|_| expand) { // A view change (no history step); a failure just leaves the group closed. let _ = app.session.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})); } diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index d622a0e9db..e9b984d81f 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -1,4 +1,4 @@ -use super::layer_drag::{MaskDrag, fx_drop, layer_drag_and_drop, mask_drag_key, start_fx_drag, starts_mask_drag}; +use super::layer_drag::{MaskDrag, fx_drop, layer_drag_and_drop, mask_drag_key, mask_drop, start_fx_drag, starts_mask_drag}; use super::layers::simple_lock_toggle; use super::{ Color32, CornerRadius, Layer, LayerContent, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, Value, icons, json, pos2, theme, vec2, widgets, @@ -207,6 +207,7 @@ pub(super) fn layer_row( let mask_drag = mask_drag.is_some(); layer_drag_and_drop(app, ctx, ui, l, rect, &resp, actions); fx_drop(ctx, ui, l, rect, actions); + mask_drop(ctx, ui, l, rect, actions); crate::smart_ui::drop_on_row(ctx, ui, l, rect, actions); if resp.drag_started() && !mask_drag { crate::layer_transfer::begin_from_panel(app, ctx, l.id); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 856f5a09ff..cc71b6884b 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -266,6 +266,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let held = ctx.data(|d| { d.get_temp::(egui::Id::unique("layer-drag")).is_some() || d.get_temp::(fx_drag_key()).is_some() + || d.get_temp::(mask_drag_key()).is_some() || d.get_temp::(crate::smart_ui::drag_key()).is_some() }); let dragging = held && ctx.input(|i| i.pointer.primary_down()); diff --git a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs index 7548beec64..49352643a0 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs @@ -886,3 +886,183 @@ fn selecting_an_adjustment_layer_from_another_layer_targets_its_mask() { } } } + +/// #10485: dragging the layer mask's thumbnail onto a group's row moves the mask to the group, and +/// ⌥ copies it, as in Photoshop. It had no effect. +#[test] +fn dragging_the_mask_thumbnail_onto_a_group_moves_or_copies_it() { + for copy in [false, true] { + let (mut s, masked, shape) = session(); + let group = s.execute("layer.groupLayers", json!({"layer": shape, "name": "Grp"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + let to = h.get_by_label("Grp").rect().center(); + let modifiers = if copy { Modifiers::ALT } else { Modifiers::NONE }; + h.hover_at(from); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(1); + for k in 1..=8 { + h.event(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(3); + assert!(layer(&h, group).mask.is_some(), "copy: {copy}: the group has the mask"); + assert_eq!(layer(&h, masked).mask.is_some(), copy, "copy: {copy}: the original stays only with ⌥"); + } +} + +/// #10485: a layer mask's thumbnail dropped on a row that has a layer mask already (with or +/// without ⌥), or back on its own row, does nothing: no command runs, so no error, no history step, +/// and both masks stay as they were. Photoshop asks before replacing a mask; the panel doesn't offer +/// the drop at all. +#[test] +fn dropping_a_mask_thumbnail_on_a_masked_row_or_its_own_row_does_nothing() { + for (target, copy) in [("Badge", false), ("Badge", true), ("Masked", false), ("Masked", true)] { + let (mut s, masked, shape) = session(); + s.execute("layer.layerMask.hideAll", json!({"layer": shape})).unwrap(); + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + let doc = h.state().session.active().unwrap().doc.clone(); + let history = h.state().session.active().unwrap().history.entries(); + let (mask_masked, mask_shape) = (layer(&h, masked).mask, layer(&h, shape).mask); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + let to = h.get_by_label(target).rect().center(); + let modifiers = if copy { Modifiers::ALT } else { Modifiers::NONE }; + h.hover_at(from); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(1); + // Out of the thumbnail and back onto the target, so the drop on its own row is a drag. + let away = from + vec2(0.0, 40.0); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(from + (away - from) * (k as f32 / 4.0))); + h.run_steps(1); + } + for k in 1..=8 { + h.event(egui::Event::PointerMoved(away + (to - away) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(3); + let case = format!("onto {target}, copy: {copy}"); + assert!(!h.state().ui.status_error, "{case}: no refused command: {}", h.state().ui.status); + assert_eq!(layer(&h, masked).mask, mask_masked, "{case}: the dragged mask stays"); + assert_eq!(layer(&h, shape).mask, mask_shape, "{case}: the target keeps its own mask"); + let st = h.state().session.active().unwrap(); + assert!(st.doc == doc, "{case}: the document is unchanged"); + assert_eq!(st.history.entries(), history, "{case}: no history step"); + } +} + +/// #10485: a layer mask dragged to the Layers list's bottom edge scrolls the list, as a layer +/// drag does, so it can be dropped on a layer scrolled out of view. The list stayed put. +#[test] +fn dragging_a_mask_to_the_list_edge_scrolls_to_rows_out_of_view() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let target = s.execute("layer.new.layer", json!({"name": "Target"})).unwrap()["layer"].as_u64().unwrap(); + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + let window_bottom = h.ctx.content_rect().bottom(); + assert!(h.get_by_label("Target").rect().top() > window_bottom, "the target starts out of view"); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + let start = h.get_by_label("Masked").rect(); + h.hover_at(from); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + vec2(0.0, 12.0))); + h.run_steps(2); + // Held at the bottom of the window, below the list's last visible row. + let bottom = pos2(from.x, window_bottom - 2.0); + for _ in 0..240 { + h.event(egui::Event::PointerMoved(bottom)); + h.run_steps(1); + } + let moved = h.get_by_label("Masked").rect(); + assert!(moved.top() < start.top() - 1.0, "the list scrolled down: {start:?} → {moved:?}"); + let to = h.get_by_label("Target").rect().center(); + assert!(to.y < window_bottom, "the target scrolled into view: {to:?}"); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(bottom + (to - bottom) * (k as f32 / 4.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(layer(&h, target).mask.is_some(), "the target has the mask"); + assert!(layer(&h, masked).mask.is_none(), "moved, not copied"); +} + +/// #10485: a layer mask dropped outside the Layers list, over the panel's header, doesn't land on +/// the row scrolled out of view underneath it. The rows take drops only where the list shows them. +#[test] +fn dropping_a_mask_over_the_panel_header_skips_rows_scrolled_out_of_view() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap(); + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + // Scrolled to the bottom: "Masked" shows, the top rows went up under the header. + h.hover_at(h.get_by_label("Filler 39").rect().center()); + h.run_steps(2); + for _ in 0..80 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + }); + h.run_steps(1); + } + h.run_steps(10); + let window = h.ctx.content_rect(); + let fill = h.get_all_by_label("Fill").next().unwrap().rect(); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + assert!(from.y > fill.bottom() && from.y < window.bottom(), "the masked row shows: {from:?}"); + // The empty header space between Blend Mode and Opacity, over a row scrolled out of view. + let (blend, opacity) = (h.get_by_label("Blend Mode").rect(), h.get_all_by_label("Opacity").next().unwrap().rect()); + let over = pos2((blend.right() + opacity.left()) / 2.0, blend.center().y); + let (target, row) = (0..40) + .map(|i| format!("Filler {i}")) + .map(|name| { + let rect = h.get_by_label(&name).rect(); + (name, rect) + }) + .find(|(_, rect)| rect.contains(over)) + .expect("a row lies under the header"); + assert!(row.bottom() <= fill.bottom(), "{target} is scrolled out of the list: {row:?}"); + let target = h.state().session.active().unwrap().doc.layers.iter().find(|l| l.name == target).unwrap().id.0; + let doc = h.state().session.active().unwrap().doc.clone(); + let history = h.state().session.active().unwrap().history.entries(); + h.hover_at(from); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + // Up through the list, clear of its edges (which scroll it), then out over the header and + // released there at once. + let inside = pos2(from.x, fill.bottom() + 48.0); + for k in 1..=8 { + h.event(egui::Event::PointerMoved(from + (inside - from) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerMoved(over)); + h.event(egui::Event::PointerButton { pos: over, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(layer(&h, target).mask.is_none(), "the row under the header took no mask"); + assert!(layer(&h, masked).mask.is_some(), "the mask stays where it was"); + let st = h.state().session.active().unwrap(); + assert!(st.doc == doc, "the document is unchanged"); + assert_eq!(st.history.entries(), history, "no history step"); +} diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 15c602ae99..34e4042f48 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -158,6 +158,9 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, Tool::Brush | Tool::Eraser if t.pro => { // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). let block = crate::eraser_ui::block_mode(app, app.ui.tool); + // The Brush's own tooltips (#11813); the Eraser keeps its texts. + let brush = app.ui.tool == Tool::Brush; + let tip = |r: egui::Response, text: &str| if brush { r.on_hover_text(text) } else { r }; ui.add_enabled_ui(!block, |ui| { brush_preset_chip(ui, b, &mut app.ui); crate::brush_picker::settings_toggle(app, ui); @@ -170,26 +173,32 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, opt_label(ui, tl!("Mode")); let held = app.held_erase; paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); + // The dropdown's button, by the id its combo box takes from "brush-mode". + if let Some(mode) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("brush-mode"))) { + tip(mode, tl!("Painting Mode")); + } } ui.add_enabled_ui(!block, |ui| { - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0); - if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() { + tip(percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0), tl!("Set opacity for stroke")); + let pressure = pressure_button(ui, b.pressure_opacity, tl!("Always use pressure for opacity"), brush); + if tip(pressure, tl!("Always use Pressure for Opacity. When off, Brush Preset controls pressure")).clicked() { b.pressure_opacity = !b.pressure_opacity; } }); // A Pencil- or Block-mode Eraser is always full flow, without build-up (Photoshop). ui.add_enabled_ui(!block && !crate::eraser_ui::pencil_mode(app, app.ui.tool), |ui| { - percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); + tip(percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0), tl!("Set flow rate for stroke")); let airbrush = icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects")); if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() { b.build_up = !b.build_up; } }); opt_label(ui, tl!("Smoothing")); - smoothing_field(ui, b, 58.0); - smoothing_options(ui, b); + tip(smoothing_field(ui, b, 58.0), tl!("Set smoothing for stroke\nUse higher values to reduce the shakiness of brush strokes")); + smoothing_options(ui, b, brush); widgets::vline(ui, 22.0); - if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() { + let pressure = pressure_button(ui, b.pressure_size, tl!("Always use pressure for size"), brush); + if tip(pressure, tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { b.pressure_size = !b.pressure_size; } } @@ -223,23 +232,37 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); }); widgets::vline(ui, 22.0); + // The Brush's own tooltips here too (#11813); the Eraser keeps its texts. + let brush = app.ui.tool == Tool::Brush; + let tip = |r: egui::Response, text: &str| if brush { r.on_hover_text(text) } else { r }; if app.ui.tool == Tool::Eraser { crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); } else { opt_label(ui, tl!("Mode")); let held = app.held_erase; paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); + if let Some(mode) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("brush-mode"))) { + tip(mode, tl!("Painting Mode")); + } } // A Pencil-mode Eraser is always hard and at full flow (Photoshop). let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool); ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)); + let opacity = ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)).inner; + tip(opacity, tl!("Set opacity for stroke")); + let flow = ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)).inner; + tip(flow, tl!("Set flow rate for stroke")); opt_label(ui, tl!("Smoothing")); - smoothing_field(ui, b, 66.0); + tip(smoothing_field(ui, b, 66.0), tl!("Set smoothing for stroke\nUse higher values to reduce the shakiness of brush strokes")); widgets::vline(ui, 22.0); - widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")); - widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")); + tip( + widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")), + tl!("Always use Pressure for Size. When off, Brush Preset controls pressure"), + ); + tip( + widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")), + tl!("Always use Pressure for Opacity. When off, Brush Preset controls pressure"), + ); } Tool::MixerBrush => { brush_preset_chip(ui, b, &mut app.ui); @@ -331,7 +354,7 @@ fn marquee_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// Lasso family: selection mode, feather, anti-alias, magnetic settings and the drawing hints. fn lasso_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - selection_mode_buttons(app, ui); + selection_mode_buttons(&mut app.ui.selection_mode, ui); widgets::vline(ui, 22.0); opt_label(ui, tl!("Feather")); widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0); @@ -379,7 +402,7 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: lasso_options(app, ui); } Tool::MagicWand => { - selection_mode_buttons(app, ui); + selection_mode_buttons(&mut app.ui.selection_mode, ui); widgets::vline(ui, 22.0); opt_label(ui, tl!("Tolerance")); widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); @@ -618,6 +641,7 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls")); widgets::vline(ui, 22.0); crate::align_bar::options(app, ui); + crate::align_bar::gear(app, ui); } Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), Tool::Zoom => { @@ -653,7 +677,7 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } } Tool::RotateView => { - hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°")); + hint(ui, tl!("Drag around the center to rotate the view · Shift constrains to 15°")); if let Some(i) = app.session.active_index() { ui.label(tl!("Angle")); let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0); @@ -795,12 +819,20 @@ fn fixed_size_field(ui: &mut egui::Ui, px: &mut f32, units: widgets::FieldUnits, picked } -fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) { +fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { opt_label(ui, label); let mut percent = *value * 100.0; - if widgets::value_field_named(ui, label, &mut percent, range, "%", width).changed() { + let r = widgets::value_field_named(ui, label, &mut percent, range, "%", width); + if r.changed() { *value = percent / 100.0; } + r +} + +/// A pressure toggle named `name` (for screen readers and tests); its tooltip is `name`, unless +/// `own_tip` leaves the tooltip to the caller (the Brush's own texts, #11813). +fn pressure_button(ui: &mut egui::Ui, on: bool, name: &str, own_tip: bool) -> egui::Response { + icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), on, name, !own_tip) } fn hint(ui: &mut egui::Ui, s: &str) { diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 9f20214104..9d17b2afac 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -122,15 +122,28 @@ fn layer_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { }); ui.add_space(6.0); } - let mut o = layer.opacity * 100.0; - let r = widgets::slider_row(ui, tl!("Opacity"), &mut o, 0.0..=100.0, "%", None); - if r.drag_stopped() || (r.changed() && !r.dragged()) { - let _ = app.run("layer.setProps", json!({"layer": layer.id.0, "opacity": o / 100.0})); + pct_slider(app, ui, layer, "opacity", tl!("Opacity"), layer.opacity); + pct_slider(app, ui, layer, "fill", crate::i18n::tr_ctx(crate::i18n::current(), "layers", "Fill"), layer.fill_opacity); +} + +/// An Opacity or Fill (`key`) slider, applied as it moves: a drag is one history step, as with the +/// Layers panel's sliders. Applying only when the drag stopped wrote back the old value, since the +/// slider takes the pointer only while it is dragged or clicked, not on the release (#9683, #7601). +fn pct_slider(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer, key: &str, label: &str, current: f32) { + let mut v = current * 100.0; + let r = widgets::slider_row(ui, label, &mut v, 0.0..=100.0, "%", None); + let stamp = r.id.with("drag-stamp"); + if r.drag_started() { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(stamp, n)); } - let mut f = layer.fill_opacity * 100.0; - let r = widgets::slider_row(ui, crate::i18n::tr_ctx(crate::i18n::current(), "layers", "Fill"), &mut f, 0.0..=100.0, "%", None); - if r.drag_stopped() || (r.changed() && !r.dragged()) { - let _ = app.run("layer.setProps", json!({"layer": layer.id.0, "fill": f / 100.0})); + if r.changed() { + let drag = if r.dragged() { ui.data(|d| d.get_temp::(stamp)) } else { None }; + let (id, p) = super::options_bar::pct_action(&json!({"layer": layer.id.0}), key, v, drag); + if let Err(e) = app.run(&id, p) { + app.ui.status = e; + app.ui.status_error = true; + } } } @@ -259,8 +272,9 @@ pub(super) fn select_and_mask_button(app: &mut PhotocraftApp, ui: &mut egui::Ui) } } -/// New / add / subtract / intersect selection buttons (shared by selection tools). -pub(super) fn selection_mode_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { +/// New / add / subtract / intersect selection buttons (shared by selection tools, and the Patch +/// and Content-Aware Move tools, which lasso their area). +pub(crate) fn selection_mode_buttons(mode: &mut u8, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.x = 2.0; for (i, (icon, tip)) in [ ("square", tl!("New selection").to_string()), @@ -271,9 +285,79 @@ pub(super) fn selection_mode_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) .iter() .enumerate() { - if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { - app.ui.selection_mode = i as u8; + if icons::button(ui, icon, 24.0, *mode == i as u8, tip).clicked() { + *mode = i as u8; } } ui.spacing_mut().item_spacing.x = 8.0; } + +#[cfg(test)] +mod tests { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + + use super::*; + + /// #9683, #7601: dragging the Studio Properties panel's Opacity or Fill slider bounced back to + /// the old value on release. A drag keeps where it was let go, as one history step. + #[test] + fn opacity_and_fill_sliders_keep_a_drag() { + for key in ["Opacity", "Fill"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().cumulative_pass_nr() == 0 { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ALL[0]); + return; + } + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + layer_controls(app, ui, &layer); + }, + app, + ); + h.run_steps(3); + let value = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + if key == "Opacity" { l.opacity } else { l.fill_opacity } + }; + let steps = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.entries().len(); + let before = steps(&h); + assert!((value(&h) - 1.0).abs() < 1e-6); + let r = h + .query_all_by_role(Role::Slider) + .find(|n| n.accesskit_node().label().as_deref() == Some(key)) + .map(|n| n.rect()) + .unwrap_or_else(|| panic!("no {key} slider")); + // The press lands away from the current value and the release moves on again, so the + // press and release frames change the value as well as the drag. + let (from, to) = (egui::pos2(r.left() + r.width() * 0.8, r.center().y), egui::pos2(r.left() + r.width() * 0.35, r.center().y)); + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + let mut last = value(&h); + for i in 1..=6 { + h.hover_at(from + (to - from) * (i as f32 / 6.0)); + h.run_steps(1); + let v = value(&h); + assert!(v < last, "{key}: the value follows the drag, not only the release ({last} to {v})"); + last = v; + } + // The pointer moves on and releases in one frame, as a quick flick does. + let release = to - egui::vec2(r.width() * 0.05, 0.0); + h.hover_at(release); + h.drop_at(release); + h.run_steps(3); + let v = value(&h); + assert!(v > 0.15 && v < last, "{key}: the release position wasn't applied ({last} to {v})"); + assert_eq!(steps(&h), before + 1, "{key}: one history step for the drag"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!((value(&h) - 1.0).abs() < 1e-6, "{key}: one undo reverts the whole drag"); + } + } +} diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index a81ca7653a..12f85de2c1 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -35,13 +35,13 @@ pub(crate) const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[&[Tool::Hand, Tool::RotateView], &[Tool::Zoom]], ]; -/// The tool a slot shows: the current tool if it belongs to the slot, else the last one used. -fn slot_tool(ui: &egui::Ui, current: Tool, slot: &[Tool], key: egui::Id) -> Tool { +/// The tool a slot shows: the current tool if it belongs to the slot, else the last one used +/// (`group_tools`, most recent first), else the slot's first tool. +pub(super) fn slot_tool(current: Tool, group_tools: &[Tool], slot: &[Tool]) -> Tool { if slot.contains(¤t) { - ui.data_mut(|d| d.insert_temp(key, current)); return current; } - ui.data(|d| d.get_temp::(key)).filter(|t| slot.contains(t)).unwrap_or(slot[0]) + group_tools.iter().chain(slot).copied().find(|t| slot.contains(t)).unwrap_or(current) } /// Next tool in a toolbar flyout slot after `from`, wrapping (Photoshop Alt/Option-click). An @@ -61,7 +61,7 @@ pub(crate) fn toolbar_position(tool: Tool) -> usize { /// dialog writes `Tool` debug names, `edit.toolbar` takes any name `Tool::from_name` reads). A /// slot keeps only its visible tools, so its flyout lists just those; a slot with none left is /// dropped, and so is a section with no slots. Each slot carries its index in `TOOL_SECTIONS`, -/// so its remembered tool and flyout stay put when other slots are hidden. +/// so its flyout stays put when other slots are hidden. pub(super) fn visible_sections(hidden: &[String]) -> Vec)>> { let hidden: Vec = hidden.iter().map(String::as_str).filter_map(Tool::from_name).collect(); let mut index = 0usize; @@ -226,7 +226,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.horizontal(|ui| { for (slot_index, slot) in row.iter() { let key = egui::Id::unique(("tool-slot", *slot_index)); - let tool = slot_tool(ui, app.ui.tool, slot, key); + let tool = slot_tool(app.ui.tool, &app.ui.group_tools, slot); let sel = slot.contains(&app.ui.tool); let tip = match crate::tool_shortcuts::shortcut(app, tool) { Some(sc) => format!("{} ({})", tl!(tool.label()), crate::shortcuts::pretty(&sc)), @@ -674,13 +674,13 @@ pub(super) fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, two_column p.rect_stroke(b, 1.0, Stroke::new(1.0, ink(d)), StrokeKind::Inside); } if let Some(d) = &d { - d.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Default colours (D)"))); + d.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Default Foreground and Background Colors (D)"))); } - s.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Swap colours (X)"))); - if s.on_hover_text(tl!("Swap colours (X)")).clicked() { + s.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Switch Foreground and Background Colors (X)"))); + if s.on_hover_text(tl!("Switch Foreground and Background Colors (X)")).clicked() { chip_command(app, "tools.swapColors"); } - if d.is_some_and(|d| d.on_hover_text(tl!("Default colours (D)")).clicked()) { + if d.is_some_and(|d| d.on_hover_text(tl!("Default Foreground and Background Colors (D)")).clicked()) { chip_command(app, "tools.defaultColors"); } } diff --git a/crates/ui-egui/src/panels/type_flyout_tests.rs b/crates/ui-egui/src/panels/type_flyout_tests.rs index 9e13f66169..1243992b66 100644 --- a/crates/ui-egui/src/panels/type_flyout_tests.rs +++ b/crates/ui-egui/src/panels/type_flyout_tests.rs @@ -450,6 +450,67 @@ fn next_slot_tool_wraps_around_the_flyout() { assert_eq!(next_slot_tool(&[], Tool::Brush), Tool::Brush); } +#[test] +fn slot_tool_is_the_current_tool_else_the_slots_last_else_its_first() { + let lasso = [Tool::Lasso, Tool::PolygonLasso, Tool::MagneticLasso]; + assert_eq!(slot_tool(Tool::Move, &[], &lasso), Tool::Lasso); + let used = [Tool::Brush, Tool::PolygonLasso, Tool::Lasso]; + assert_eq!(slot_tool(Tool::Move, &used, &lasso), Tool::PolygonLasso); + assert_eq!(slot_tool(Tool::MagneticLasso, &used, &lasso), Tool::MagneticLasso); + // Polygonal Lasso hidden in Edit › Toolbar: the slot falls back on the next one used. + assert_eq!(slot_tool(Tool::Move, &used, &[Tool::Lasso, Tool::MagneticLasso]), Tool::Lasso); + // Slots don't line up with keys: Blur's slot and the two single marquees have no key at all, + // and the Hand slot has two. + let used = [Tool::Sharpen, Tool::SingleRowMarquee, Tool::RotateView]; + assert_eq!(slot_tool(Tool::Move, &used, &[Tool::Blur, Tool::Sharpen, Tool::Smudge]), Tool::Sharpen); + let marquee = [Tool::RectMarquee, Tool::EllipseMarquee, Tool::SingleRowMarquee, Tool::SingleColumnMarquee]; + assert_eq!(slot_tool(Tool::Move, &used, &marquee), Tool::SingleRowMarquee); + assert_eq!(slot_tool(Tool::Move, &used, &[Tool::Hand, Tool::RotateView]), Tool::RotateView); + // Empty slot: no panic, the current tool stays. + assert_eq!(slot_tool(Tool::Brush, &used, &[]), Tool::Brush); +} + +/// #3569: after a restart a slot is still on the tool it was left on, whichever tool is selected: +/// a click picks that tool, not the slot's first. +#[test] +fn slots_come_back_on_their_last_tool_after_a_restart() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.prefs.edit(|p| p.group_tools = json!(["PolygonLasso", "PaintBucket", "Pencil", "Sharpen", "SingleRowMarquee"])); + crate::tool_memory::restore(&mut app); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let slots = [ + (Tool::Brush, Tool::Pencil), + (Tool::Gradient, Tool::PaintBucket), + (Tool::Lasso, Tool::PolygonLasso), + (Tool::Blur, Tool::Sharpen), + (Tool::RectMarquee, Tool::SingleRowMarquee), + ]; + for (i, (first, last)) in slots.into_iter().enumerate() { + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&first)).unwrap(); + let at = buttons[index].center(); + let t = 1.0 + i as f64; + frame(&mut app, &ctx, t, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, t + 0.05, vec![pointer(at, false)]); + frame(&mut app, &ctx, t + 0.1, vec![]); + assert_eq!(app.ui.tool, last); + } +} + /// Edit › Toolbar hidden tools shrink the Alt-click cycle to the remaining flyout members. #[test] fn visible_sections_drop_hidden_tools_from_alt_click_slots() { diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs index 55fb30ca30..326b23c800 100644 --- a/crates/ui-egui/src/polygon_lasso_tests.rs +++ b/crates/ui-egui/src/polygon_lasso_tests.rs @@ -754,3 +754,67 @@ fn a_held_temporary_tool_keeps_the_polygon() { h.run_steps(3); assert_eq!(h.state().ui.polygon.len(), 2, "released"); } + +/// #6578: the last corner of a small polygon lands within 8 points of the first one, but it is a +/// new vertex, not a close; clicking on the first vertex still closes. +#[test] +fn the_last_corner_of_a_small_polygon_does_not_close_it() { + let mut app = polygon_app(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + assert_eq!(app.point_zoom(), 1.0); + let corners = [[100.0, 100.0], [106.0, 100.0], [106.0, 106.0], [100.0, 106.0]]; + for [x, y] in corners { + ev(&mut app, "down", x, y, Modifiers::NONE); + ev(&mut app, "up", x, y, Modifiers::NONE); + } + assert_eq!(app.ui.polygon.len(), 4, "four corners, still open: {:?}", app.ui.polygon); + assert!(app.session.active().unwrap().doc.selection.is_none()); + ev(&mut app, "down", 100.0, 100.0, Modifiers::NONE); + ev(&mut app, "up", 100.0, 100.0, Modifiers::NONE); + assert!(app.ui.polygon.is_empty(), "a click on the first vertex closes"); + let bounds = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert!(near(bounds, 100, 100, 106, 106), "a square, not a triangle: {bounds:?}"); +} + +/// Large outlines keep the full 8-point reach; tiny ones still close on their first vertex. The +/// reach follows the size of the whole outline, not its shortest edge (#7629). +#[test] +fn polygon_close_reach_scales_with_small_outlines_only() { + let reach = crate::canvas::polygon_close_reach; + let square = |s: f64| [[0.0, 0.0], [s, 0.0], [s, s], [0.0, s]]; + assert_eq!(reach(square(100.0), 1.0), 8.0); + assert_eq!(reach(square(100.0), 2.0), 4.0); + assert_eq!(reach(square(32.0), 1.0), 8.0); + assert_eq!(reach(square(6.0), 1.0), 1.5); + assert_eq!(reach(square(1.0), 1.0), 1.0); + assert_eq!(crate::canvas::polygon_close_reach([[f64::NAN, 0.0]], 1.0), 8.0); + assert_eq!(crate::canvas::polygon_close_reach([[f64::NAN, 0.0], [0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]], 1.0), 2.5); +} + +/// A large polygon with one short edge keeps the full reach: only a small outline shrinks it. +#[test] +fn polygon_close_reach_ignores_one_short_edge_of_a_large_outline() { + let reach = crate::canvas::polygon_close_reach; + assert_eq!(reach([[0.0, 0.0], [100.0, 0.0], [100.0, 100.0], [96.0, 101.0]], 1.0), 8.0); + // The outline of #7629's test (about 40 points across): the click 5 points from the first vertex still closes. + assert!(reach([[50.0, 50.0], [90.0, 50.0], [90.0, 90.0], [85.0, 91.0]], 1.0) > 5.0); +} + +#[test] +fn narrow_and_rotated_polygons_keep_the_fourth_corner() { + for corners in [[[100.0, 100.0], [200.0, 100.0], [200.0, 106.0], [100.0, 106.0]], [[100.0, 100.0], [160.0, 180.0], [155.2, 183.6], [95.2, 103.6]]] { + let mut app = polygon_app(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + for [x, y] in corners { + ev(&mut app, "down", x, y, Modifiers::NONE); + ev(&mut app, "up", x, y, Modifiers::NONE); + } + assert_eq!(app.ui.polygon.len(), 4, "{corners:?}"); + assert!(app.session.active().unwrap().doc.selection.is_none()); + ev(&mut app, "down", 100.0, 100.0, Modifiers::NONE); + assert!(app.ui.polygon.is_empty()); + assert!(app.session.active().unwrap().doc.selection.is_some()); + } +} diff --git a/crates/ui-egui/src/prefs/prefs_ui.rs b/crates/ui-egui/src/prefs/prefs_ui.rs index e37efea17f..36cd3e74c5 100644 --- a/crates/ui-egui/src/prefs/prefs_ui.rs +++ b/crates/ui-egui/src/prefs/prefs_ui.rs @@ -53,6 +53,7 @@ pub struct Runtime { /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, pub(crate) selected_tool: Option, + pub(crate) group_tools: Option>, /// The tool owning the session brush and the other tools' brushes, as last remembered. pub(crate) tool_brushes: Option, } diff --git a/crates/ui-egui/src/prefs/prefs_ui/startup.rs b/crates/ui-egui/src/prefs/prefs_ui/startup.rs index 16b945b49e..78b3217dc2 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/startup.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/startup.rs @@ -204,7 +204,7 @@ pub(crate) fn on_recovery_event(app: &mut PhotocraftApp, e: &JobEvent) -> bool { // Native bundle decoding cannot stop midway. Cancel admission and the rest of the // batch so another large decoder isn't started while this worker finishes. app.prefs_rt.recovery_queue.clear(); - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", tl!(&e.label))]); + app.ui.status = crate::i18n::fmt(tl!("Canceled {label}"), &[("label", tl!(&e.label))]); app.ui.status_error = false; } } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index dabde320b8..3d62afaa43 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1139,6 +1139,125 @@ fn selected_tool_excludes_temporary_switches() { assert_eq!(stored(&store)["selectedTool"], json!("PolygonLasso")); } +/// #3569: a restart keeps the last tool of every group, not only the selected tool's. +#[test] +fn group_tools_survive_a_restart() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + for tool in [Tool::Brush, Tool::Pencil, Tool::PaintBucket, Tool::PolygonLasso, Tool::Pencil, Tool::Zoom] { + app.ui.tool = tool; + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + } + assert_eq!(stored(&store)["groupTools"], json!(["Zoom", "Pencil", "PolygonLasso", "PaintBucket", "Brush", "Move"]), "most recent first, each once"); + let (app2, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(app2.ui.tool, Tool::Zoom); + assert_eq!(app2.ui.group_tools, app.ui.group_tools); + assert_eq!(app2.ui.group_tool('B'), Some(Tool::Pencil), "the group's latest tool"); + assert_eq!(app2.ui.group_tool('G'), Some(Tool::PaintBucket)); + assert_eq!(app2.ui.group_tool('L'), Some(Tool::PolygonLasso)); +} + +#[test] +fn group_tools_are_flushed_on_exit_without_another_frame() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + app.ui.tool = Tool::Pencil; + crate::tool_memory::persist(&mut app, &egui::Context::default()); + app.ui.tool = Tool::PaintBucket; + crate::tool_memory::save_on_exit(&mut app).unwrap(); + let (app2, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(app2.ui.group_tool('B'), Some(Tool::Pencil)); + assert_eq!(app2.ui.group_tool('G'), Some(Tool::PaintBucket)); +} + +/// A frame as far as the tools go: the key handling, then what is remembered. +fn tool_frame(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) { + ctx.begin_pass(egui::RawInput { events, ..Default::default() }); + crate::shortcuts::handle(app, ctx); + ctx.end_pass().textures_delta.clear(); + crate::tool_memory::persist(app, ctx); + tick(app, ctx); +} + +/// A tool picked during a drag that ends on the tool it began with: the selected tool never +/// changed, but that tool's group did. +#[test] +fn group_tools_are_saved_when_the_selected_tool_stays_the_same() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + let pointer = |pressed| egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + app.ui.tool = Tool::Brush; + tool_frame(&mut app, &ctx, vec![]); + tool_frame(&mut app, &ctx, vec![pointer(true)]); + app.ui.tool = Tool::PaintBucket; + tool_frame(&mut app, &ctx, vec![]); + app.ui.tool = Tool::Brush; + tool_frame(&mut app, &ctx, vec![]); + tool_frame(&mut app, &ctx, vec![pointer(false)]); + assert_eq!(stored(&store)["selectedTool"], json!("Brush")); + let (app2, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(app2.ui.group_tool('G'), Some(Tool::PaintBucket)); +} + +/// The pen's eraser end and a held tool letter don't change what a group shows or brings back, +/// neither during the session nor when quitting while they are in use. +#[test] +fn group_tools_exclude_temporary_switches() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + for tool in [Tool::MagicEraser, Tool::Brush] { + app.ui.tool = tool; + tool_frame(&mut app, &ctx, vec![]); + } + app.stylus.tool_before_eraser = Some(Tool::Brush); + app.ui.tool = Tool::Eraser; + tool_frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.group_tool('E'), Some(Tool::MagicEraser), "the pen's eraser end"); + app.stylus.tool_before_eraser = None; + app.ui.tool = Tool::Brush; + let press = egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + tool_frame(&mut app, &ctx, vec![press]); + tool_frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.tool, Tool::Zoom, "Z is still down"); + assert_eq!(app.ui.group_tool('Z'), None, "a held letter"); + crate::tool_memory::save_on_exit(&mut app).unwrap(); + assert_eq!(stored(&store)["groupTools"], json!(["Brush", "MagicEraser", "Move"])); +} + +/// A selected tool this version doesn't know starts on the default tool. The saved list stays as +/// it is, names this version doesn't know included, until the next tool is picked. +#[test] +fn a_launch_alone_saves_no_group_tools() { + use crate::state::Tool; + let saved = json!({"selectedTool": "FutureTool", "groupTools": ["Pencil", "FutureTool", "PaintBucket"]}); + let (mut app, store) = app_with_saved(Some(saved.to_string())); + let ctx = egui::Context::default(); + tool_frame(&mut app, &ctx, vec![]); + assert_eq!(stored(&store)["groupTools"], saved["groupTools"]); + app.ui.tool = Tool::Brush; + tool_frame(&mut app, &ctx, vec![]); + assert_eq!(stored(&store)["groupTools"], json!(["Brush", "Move", "Pencil", "PaintBucket"])); +} + +/// A damaged or hand-edited `groupTools` costs no other preference, and what reads back counts. +#[test] +fn damaged_group_tools_keep_what_reads_back() { + use crate::state::Tool; + for bad in [json!(null), json!("Pencil"), json!(42), json!({"B": "Pencil"})] { + let (app, _) = app_with_saved(Some(json!({"groupTools": bad, "toolOptions": {"feather": 12.0}}).to_string())); + assert_eq!(app.ui.group_tools, [Tool::Move], "{bad}"); + assert_eq!(app.ui.tool_options.feather, 12.0); + } + let saved = json!({"groupTools": ["FutureTool", "Pencil", 7, null, {}, "PaintBucket", "Pencil"]}); + let (app, _) = app_with_saved(Some(saved.to_string())); + assert_eq!(app.ui.group_tools, [Tool::Move, Tool::Pencil, Tool::PaintBucket]); +} + #[test] fn tool_options_survive_a_restart() { let (mut app, store) = app_with_store(); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index a9d511fb48..e869f3f7e0 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -8,15 +8,17 @@ pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer the TIFF, Targa, DDS or JPEG /// The format answers a save takes instead of asking: the Targa bits per pixel (`"tgaBits"`), /// the DDS options (`"ddsCompression"`, `"ddsMipmaps"`), JPEG Options (`"quality"` 0–12, -/// `"jpegFormat"`) and TIFF Options (`"tiffCompression"`, `"tiffTransparency"`, `"tiffPyramid"`, -/// `"tiffLayers"`). `None` asks in Save As and takes the default in automation saves, which never -/// prompt. +/// `"jpegFormat"`), TIFF Options (`"tiffCompression"`, `"tiffTransparency"`, `"tiffPyramid"`, +/// `"tiffLayers"`) and a PSD/PSB's Maximize Compatibility (`"maximizeCompatibility"`). `None` +/// asks in Save As and takes the default in automation saves, which never prompt (Maximize +/// Compatibility: Preferences › File Handling decides). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct FormatChoices { pub tga_bits: Option, pub dds: Option, pub jpeg: Option, pub tiff: Option, + pub maximize_compatibility: Option, } impl FormatChoices { @@ -27,6 +29,7 @@ impl FormatChoices { dds: dds_options_ui::options_param(params, cmd)?, jpeg: jpeg_options_ui::choice_param(params, cmd)?, tiff: tiff_options_ui::choice_param(params, cmd)?, + maximize_compatibility: maximize_param(params, cmd)?, }) } @@ -38,12 +41,18 @@ impl FormatChoices { dds: dds_options_ui::options_param(params, cmd)?, jpeg: jpeg_options_ui::recorded_choice(params, cmd)?, tiff: tiff_options_ui::choice_param(params, cmd)?, + maximize_compatibility: maximize_param(params, cmd)?, }) } /// The export settings with these answers applied. pub fn apply(self, settings: ExportSettings) -> ExportSettings { - let settings = ExportSettings { tga_bits: self.tga_bits.or(settings.tga_bits), dds: self.dds.unwrap_or(settings.dds), ..settings }; + let settings = ExportSettings { + tga_bits: self.tga_bits.or(settings.tga_bits), + dds: self.dds.unwrap_or(settings.dds), + psd_maximize_compatibility: self.maximize_compatibility.unwrap_or(settings.psd_maximize_compatibility), + ..settings + }; let settings = match self.tiff { Some(t) => t.apply(settings), None => settings, @@ -68,9 +77,17 @@ impl FormatChoices { if let Some(t) = self.tiff { t.record(step); } + if let Some(maximize) = self.maximize_compatibility { + step["maximizeCompatibility"] = maximize.into(); + } } } +/// `"maximizeCompatibility"` in command or control call `cmd`'s params, read as the engine reads it. +fn maximize_param(params: &Value, cmd: &str) -> Result, String> { + photocraft_engine::file_cmds::maximize_compatibility_param(params, cmd).map_err(|e| e.to_string()) +} + /// Decode a file: (document, warnings about anything approximated or dropped). pub type ImportFn = Box Result<(Document, Vec), String>>; @@ -405,6 +422,9 @@ pub type CaptionStyleFn = Box CaptionStyle>; /// Physical right mouse button or stylus barrel button down (Windows; read for brush resize). pub type RightButtonDownFn = Box bool + Send + Sync>; +/// Which end of the pen is in use, `Some(true)` = eraser, `None` = no pen ([`Services::pen_end`]). +pub type PenEndFn = Box Option + Send + Sync>; + /// Polls the platform's optional WinTab packet queue into the app's stylus feed (Windows), with /// whether the app window is focused (to re-assert WinTab overlap priority on activation). pub type TabletPollFn = Box; @@ -531,6 +551,9 @@ pub struct Services { pub caption_style: Option, /// Physical right mouse button or pen barrel button currently down. pub right_button_down: Option, + /// Which end of the pen is in use, where the platform reports it outside the stylus feed + /// (Windows: the feed carries no pen samples there). Read for the eraser-end tool switch. + pub pen_end: Option, /// WinTab packet poll (Windows with Windows Ink disabled; see `photocraft_tablet::wintab`). pub tablet_poll: Option, /// The persistent brush preset store, loading in the background (desktop; see diff --git a/crates/ui-egui/src/shape_bounds_box_tests.rs b/crates/ui-egui/src/shape_bounds_box_tests.rs index 7e4dbb8902..9c4d4ff322 100644 --- a/crates/ui-egui/src/shape_bounds_box_tests.rs +++ b/crates/ui-egui/src/shape_bounds_box_tests.rs @@ -323,3 +323,165 @@ fn a_tool_switch_during_a_drag_ends_it_and_takes_its_release() { assert_eq!(app.session.active().unwrap().history.past_len(), steps); assert_eq!((bounds(&app, a), bounds(&app, b)), (ba, bb)); } + +/// #11473: a side scales from anywhere along its line, not only from its middle handle, and from +/// just outside it; inside the box the press stays the tool's. On the box 100,98–723,451. +#[test] +fn a_side_is_grabbed_anywhere_along_its_line() { + use egui::CursorIcon::{ResizeHorizontal, ResizeNwSe, ResizeVertical}; + let (app, ..) = app_with_two_shapes(Tool::Rectangle); + let at = |p: [f64; 2]| cursor(&app, p); + // On the left line, far from its middle (274.5) and the corners. + assert_eq!(at([100.0, 150.0]), Some(ResizeHorizontal)); + assert_eq!(at([100.0, 400.0]), Some(ResizeHorizontal)); + assert_eq!(at([723.0, 130.0]), Some(ResizeHorizontal)); + assert_eq!(at([200.0, 98.0]), Some(ResizeVertical)); + assert_eq!(at([650.0, 451.0]), Some(ResizeVertical)); + // Up to 5 screen points outside the line: less than a handle, the rest stays the tool's. + assert_eq!(at([95.0, 150.0]), Some(ResizeHorizontal)); + assert_eq!(at([650.0, 456.0]), Some(ResizeVertical)); + assert_eq!(at([94.0, 150.0]), None); + // Just inside, the Rectangle tool draws and Path Selection selects. + assert_eq!(at([101.0, 150.0]), None); + assert_eq!(at([650.0, 450.0]), None); + // A corner keeps its press where the two sides' bands meet it. + assert_eq!(at([96.0, 95.0]), Some(ResizeNwSe)); + assert_eq!(at([103.0, 101.0]), Some(ResizeNwSe)); + + // A drag from there scales that side about the opposite one. + let (mut app, a, b) = app_with_two_shapes(Tool::Rectangle); + let steps = app.session.active().unwrap().history.past_len(); + drag(&mut app, [100.0, 150.0], [150.0, 160.0]); + assert!(app.ui.shape_box.is_none() && app.ui.corner_radius.is_none()); + let s = 1.0 - 50.0 / 623.0; + near(bounds(&app, a), [150.0, 98.0, 723.0 - 320.0 * s, 301.0]); + near(bounds(&app, b), [723.0 - 303.0 * s, 318.0, 723.0, 451.0]); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + // The bottom side, pressed just outside its line, scales y about the top. + let (mut app, a, b) = app_with_two_shapes(Tool::PathSelection); + drag(&mut app, [300.0, 455.0], [310.0, 405.0]); + let s = 1.0 - 50.0 / 353.0; + near(bounds(&app, a), [100.0, 98.0, 403.0, 98.0 + 203.0 * s]); + near(bounds(&app, b), [420.0, 98.0 + 220.0 * s, 723.0, 98.0 + 353.0 * s]); +} + +/// The side band is screen sized: at 200 % it reaches half as far into the document. +#[test] +fn the_side_band_keeps_its_screen_size_when_zoomed() { + let (mut app, ..) = app_with_two_shapes(Tool::PathSelection); + app.sync_views(); + app.ui.views[0].zoom = 2.0; + assert_eq!(cursor(&app, [97.5, 150.0]), Some(egui::CursorIcon::ResizeHorizontal)); + assert_eq!(cursor(&app, [97.0, 150.0]), None); +} + +#[test] +fn edge_hit_picks_the_nearest_side_within_its_band() { + use crate::shape_bounds_box::edge_hit; + let r = [0.0, 0.0, 100.0, 50.0]; + assert_eq!(edge_hit(r, [0.0, 20.0], 11.0, 1e-3), Some([-1, 0])); + assert_eq!(edge_hit(r, [111.0, 20.0], 11.0, 1e-3), Some([1, 0])); + assert_eq!(edge_hit(r, [40.0, -5.0], 11.0, 1e-3), Some([0, -1])); + assert_eq!(edge_hit(r, [40.0, 50.0], 11.0, 1e-3), Some([0, 1])); + // Inside, only rounding off the line. + assert_eq!(edge_hit(r, [0.0005, 20.0], 11.0, 1e-3), Some([-1, 0])); + assert_eq!(edge_hit(r, [1.0, 20.0], 11.0, 1e-3), None); + // A side is a segment: past its end, the distance runs to its end point. + assert_eq!(edge_hit(r, [-8.0, -8.0], 11.0, 1e-3), None); + assert_eq!(edge_hit(r, [-5.0, 60.0], 11.0, 1e-3), None); + assert_eq!(edge_hit(r, [-5.0, 55.0], 11.0, 1e-3).map(|h| h[0] == -1 || h[1] == 1), Some(true)); + // Non-finite points hit nothing. + assert_eq!(edge_hit(r, [f64::NAN, 20.0], 11.0, 1e-3), None); + assert_eq!(edge_hit(r, [f64::NAN, 0.0], 11.0, 1e-3), None); + assert_eq!(edge_hit(r, [f64::INFINITY, 20.0], 11.0, 1e-3), None); +} + +/// The two measured rectangles selected, and an unselected one starting 3 px right of their box +/// (726,200–876,300). Returns the app, the selected two and the neighbour. +fn app_with_a_neighbour(tool: Tool) -> (PhotocraftApp, u64, u64, u64) { + let (mut app, a, b) = app_with_two_shapes(tool); + app.run("shape.create", json!({"kind": "rect", "rect": [726, 200, 150, 100], "fill": "#20a040"})).unwrap(); + let n = app.session.active().unwrap().active_layer.unwrap().0; + app.run("layer.select", json!({"layer": a})).unwrap(); + app.run("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); + (app, a, b, n) +} + +/// #11473 review: the side band takes no press from the tool next to the box. Outside the band a +/// press is the tool's; inside it, a press on a shape the box doesn't hold is too: Path Selection +/// selects that shape, the Rectangle tool draws, neither scales the selection. +#[test] +fn a_press_on_a_neighbouring_shape_or_past_the_band_stays_the_tools() { + let (app, ..) = app_with_a_neighbour(Tool::PathSelection); + for p in [[726.5, 250.0], [729.0, 250.0], [731.0, 120.0]] { + assert_eq!(cursor(&app, p), None, "{p:?}"); + } + // The band still works where there is no other shape. + assert_eq!(cursor(&app, [726.5, 120.0]), Some(egui::CursorIcon::ResizeHorizontal)); + // A neighbour with no fill is picked by its outline, within Path Selection's tolerance. + let (mut app, a, b) = app_with_two_shapes(Tool::PathSelection); + app.run("shape.create", json!({"kind": "rect", "rect": [726, 200, 150, 100], "fill": null, "stroke": {"width": 2}})).unwrap(); + app.run("layer.select", json!({"layer": a})).unwrap(); + app.run("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); + for p in [[724.0, 250.0], [727.5, 250.0]] { + assert_eq!(cursor(&app, p), None, "{p:?}"); + } + + // Path Selection: a click on the neighbour, inside the band and past it, selects it. + for p in [[726.5, 250.0], [729.0, 250.0]] { + let (mut app, a, b, n) = app_with_a_neighbour(Tool::PathSelection); + let steps = app.session.active().unwrap().history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, NONE); + assert!(app.ui.shape_box.is_none(), "{p:?}: no scale starts"); + tool_event(&mut app, ToolEvent::Up { x: p[0], y: p[1] }, NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.selected_layers(), vec![photocraft_doc::LayerId(n)], "{p:?}: the neighbour is selected"); + assert_eq!(st.history.past_len(), steps, "{p:?}: nothing scaled"); + near(bounds(&app, a), [100.0, 98.0, 403.0, 301.0]); + near(bounds(&app, b), [420.0, 318.0, 723.0, 451.0]); + } + + // The Rectangle tool: a drag from the neighbour, or from past the band, draws a new shape. + for p in [[726.5, 250.0], [731.0, 120.0]] { + let (mut app, a, b, _) = app_with_a_neighbour(Tool::Rectangle); + let layers = app.session.active().unwrap().doc.walk().len(); + tool_event(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, NONE); + assert!(app.ui.shape_box.is_none(), "{p:?}: no scale starts"); + tool_event(&mut app, ToolEvent::Move { x: p[0] + 40.0, y: p[1] + 30.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: p[0] + 60.0, y: p[1] + 40.0 }, NONE); + assert_eq!(app.session.active().unwrap().doc.walk().len(), layers + 1, "{p:?}: a new shape is drawn"); + near(bounds(&app, a), [100.0, 98.0, 403.0, 301.0]); + near(bounds(&app, b), [420.0, 318.0, 723.0, 451.0]); + } +} + +/// #11473 review: the pick under the side band skips a shape's outline test where the point is +/// out of reach of it, and still finds every shape it found before: an outline within the pick +/// tolerance just past the shape's box, and a fill's pixels past the path (an outside stroke). +#[test] +fn the_pick_still_finds_shapes_just_past_their_path_bounds() { + use crate::vector_ui::pick_shape_at; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1000, "height": 700, "background": "white"})).unwrap(); + // A stroke-only ellipse 200,200–400,300: picked by its outline alone. + app.run("shape.create", json!({"kind": "ellipse", "rect": [200, 200, 200, 100], "fill": null, "stroke": {"width": 2}})).unwrap(); + let e = app.session.active().unwrap().active_layer.unwrap(); + // A filled rectangle 500,400–600,500 with a 20 px stroke outside its path. + app.run("shape.create", json!({"kind": "rect", "rect": [500, 400, 100, 100], "fill": "#20a040", "stroke": {"width": 20, "align": "outside"}})).unwrap(); + let r = app.session.active().unwrap().active_layer.unwrap(); + let doc = &app.session.active().unwrap().doc; + let pick = |p: [f64; 2], tol: f64| pick_shape_at(doc, p, tol); + // Within the tolerance of the ellipse's extreme anchors, outside its box. + assert_eq!(pick([405.5, 250.0], 6.0), Some(e)); + assert_eq!(pick([300.0, 194.5], 6.0), Some(e)); + assert_eq!(pick([406.5, 250.0], 6.0), None); + assert_eq!(pick([300.0, 193.5], 6.0), None); + // Within it of a curve, off the anchors: the ellipse's outline at 45°. + let (cx, cy) = (300.0 + 100.0 * std::f64::consts::FRAC_1_SQRT_2, 250.0 + 50.0 * std::f64::consts::FRAC_1_SQRT_2); + assert_eq!(pick([cx + 4.0, cy], 6.0), Some(e)); + // The stroke's pixels up to 20 px past the rectangle's path, far past the tolerance. + assert_eq!(pick([612.0, 450.0], 1.0), Some(r)); + assert_eq!(pick([550.0, 381.5], 1.0), Some(r)); + assert_eq!(pick([625.0, 450.0], 1.0), None); + assert_eq!(pick([550.0, 378.5], 1.0), None); +} diff --git a/crates/ui-egui/src/smart_objects_menu_tests.rs b/crates/ui-egui/src/smart_objects_menu_tests.rs index dd6d7947a6..91addfd6b3 100644 --- a/crates/ui-egui/src/smart_objects_menu_tests.rs +++ b/crates/ui-egui/src/smart_objects_menu_tests.rs @@ -36,6 +36,7 @@ fn the_rows_follow_the_reference_order() { "Update All Modified Content", "---", "Edit Contents", + "Reset Transform", "Relink to File…", "Replace Contents…", "Export Contents…", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a0389e58ad..6a6f1aeca0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -227,8 +227,11 @@ pub struct DocWindow { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub tool: Tool, - /// The last tool used in each shortcut group (the tools sharing a key, [`Tool::key`]), at most - /// one per group: the group's key brings it back, as in Photoshop (#2608). + /// The tools used so far, most recent first and each one once. The first tool of a shortcut + /// group (the tools sharing a key, [`Tool::key`]) is the one its key brings back, and the first + /// tool of a toolbar slot is the one the slot shows, as in Photoshop (#2608, #3569). One list + /// answers both because they don't line up: the Marquee slot holds tools with and without a + /// key, the Hand slot two keys. Kept between launches in `Preferences::group_tools`. #[serde(default)] pub group_tools: Vec, /// A tool letter still held (spring-loaded tool, #2672): the tool to give back on release. @@ -675,16 +678,16 @@ impl Default for UiState { } impl UiState { - /// Records the current tool as the last one used in its shortcut group. - pub fn remember_group_tool(&mut self) { - let tool = self.tool; - if !self.group_tools.contains(&tool) { - self.group_tools.retain(|t| t.key() != tool.key()); - self.group_tools.push(tool); + /// Records `tool` as the last one used in its shortcut group and toolbar slot. + pub fn remember_group_tool(&mut self, tool: Tool) { + if self.group_tools.first() != Some(&tool) { + self.group_tools.retain(|t| *t != tool); + self.group_tools.insert(0, tool); } } /// The last tool used in the shortcut group of `key`, if any. + #[cfg(test)] pub fn group_tool(&self, key: char) -> Option { self.group_tools.iter().copied().find(|t| t.key() == key) } diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 1aea751021..228d8bac38 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -153,6 +153,16 @@ pub struct ToolOptions { pub move_target: String, #[serde(default)] pub move_show_transform: bool, + /// Move tool options bar, gear menu (#11381), all on by default: outline the layer under the + /// pointer, open the closed groups of a layer picked by a canvas click, and outline the layer + /// whose Layers panel row is hovered. Preferences > Show Highlight on Rollover still gates + /// the two outlines. + #[serde(default = "yes")] + pub move_show_hover_bounds: bool, + #[serde(default = "yes")] + pub move_expand_group_on_click: bool, + #[serde(default = "yes")] + pub move_show_layers_hover_bounds: bool, /// Transform options bar: Toggle Reference Point. Off by default, as in Photoshop: the point /// isn't drawn and isn't a handle, so a drag from the middle of the box moves the content; /// transforms still turn and scale about it (#11098). @@ -464,6 +474,9 @@ impl Default for ToolOptions { move_auto_select: true, move_target: default_move_target(), move_show_transform: false, + move_show_hover_bounds: true, + move_expand_group_on_click: true, + move_show_layers_hover_bounds: true, transform_reference_point: false, transform_interpolation: None, crop_ratio: String::new(), diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index 08259200fe..b70974d0b2 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -11,6 +11,10 @@ //! `paint_mouse::sync_tool_brush`) is kept the same way in `Preferences::tool_brushes` (#6212), //! with the tool that owns the session brush (that brush itself is `Preferences::last_brush`). //! Reset Tool and Reset All Tools change both, so the next save forgets what they reset. +//! +//! The tools used last (`UiState::group_tools`) are kept the same way in +//! `Preferences::group_tools` (#3569), so a tool picked from a flyout stays on its toolbar slot +//! and its key after a restart. A name this version doesn't know is skipped, as with the options. use photocraft_engine::BrushSettings; use serde_json::{Map, Value, json}; @@ -43,7 +47,7 @@ pub(crate) fn ended_by_tool(app: &mut PhotocraftApp) { /// Temporary canvas overrides do not change `ui.tool`. Spring-loaded letters and the pen's /// eraser end do, so remember the tool they will return to instead. A different explicit choice /// (or beginning a type edit) owns the tool and stands, just as in `spring_tools::tick`. -fn selected(app: &PhotocraftApp) -> Tool { +pub(crate) fn selected(app: &PhotocraftApp) -> Tool { let tool = if app.ui.tool == Tool::Eraser { app.stylus.tool_before_eraser.unwrap_or(app.ui.tool) } else { app.ui.tool }; if let Some(s) = &app.ui.spring && tool == s.tool @@ -63,8 +67,9 @@ fn changed(o: &ToolOptions) -> Value { if diff.is_empty() { Value::Null } else { Value::Object(diff) } } -/// Remember the selected tool and its options once the user lets go of the pointer. Run every -/// frame, so choices made through the control channel or a tool preset are remembered too. +/// Remember the selected tool, the tools used last and the options once the user lets go of the +/// pointer. Run every frame, so choices made through the control channel or a tool preset are +/// remembered too. pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { if ctx.input(|i| i.pointer.any_down()) { return; @@ -80,6 +85,7 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.request_repaint(); } } + persist_group_tools(app, ctx, tool); persist_brushes(app); if app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) { return; @@ -91,6 +97,24 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { } } +/// Remember the tools used last when the list changes, whether or not the selected tool did: a +/// tool picked during a drag that ends on the tool it began with changes only the list. +fn persist_group_tools(app: &mut PhotocraftApp, ctx: &egui::Context, tool: Tool) { + // Noted here as well: no frame follows a tool picked right before quitting. + app.ui.remember_group_tool(tool); + if app.prefs_rt.group_tools.as_ref() == Some(&app.ui.group_tools) { + return; + } + app.prefs_rt.group_tools = Some(app.ui.group_tools.clone()); + if let Ok(now) = serde_json::to_value(&app.ui.group_tools) + && app.session.prefs().group_tools != now + { + app.session.prefs.edit(|p| p.group_tools = now); + // As for the selected tool: prefs_ui::tick ran before the panels. + ctx.request_repaint(); + } +} + /// Remember the painting tools' own brushes when they change (a compare per frame otherwise: /// tip bitmaps are shared, so equal brushes compare by pointer). A brush that can't be remembered /// yet (a sampled tip too big to embed, before the preset store takes it) keeps what was saved. @@ -174,19 +198,35 @@ pub(crate) fn save_on_exit(app: &mut PhotocraftApp) -> Result<(), String> { crate::prefs_ui::save_preferences(app) } +/// Restore the tools used last, keeping their order. Anything that isn't a tool is skipped with a +/// warning: the rest of the list still holds. +fn restore_group_tools(app: &mut PhotocraftApp) { + let saved = app.session.prefs().group_tools.clone(); + if !saved.is_null() && !saved.is_array() { + log::warn!("Preferences: the remembered group tools are not a list; using the defaults"); + } + for v in saved.as_array().into_iter().flatten().rev() { + match serde_json::from_value::(v.clone()) { + Ok(tool) => app.ui.remember_group_tool(tool), + Err(_) => log::warn!("Preferences: ignoring the remembered group tool {v}"), + } + } +} + /// Restore the selected tool before the first frame and its options field by field. pub fn restore(app: &mut PhotocraftApp) { + restore_group_tools(app); let saved = app.session.prefs().selected_tool.clone(); if !saved.is_null() { match serde_json::from_value::(saved) { - Ok(tool) => { - app.ui.tool = tool; - app.ui.remember_group_tool(); - } + Ok(tool) => app.ui.tool = tool, Err(err) => log::warn!("Preferences: ignoring the remembered selected tool: {err}"), } } + // Here rather than on the first frame, so a launch alone has nothing to save. + app.ui.remember_group_tool(app.ui.tool); app.prefs_rt.selected_tool = Some(app.ui.tool); + app.prefs_rt.group_tools = Some(app.ui.group_tools.clone()); let saved = app.session.prefs().tool_options.clone(); if let Some(saved) = saved.as_object() && let Ok(Value::Object(mut cur)) = serde_json::to_value(&app.ui.tool_options) diff --git a/crates/ui-egui/src/tools/align_bar.rs b/crates/ui-egui/src/tools/align_bar.rs index ebe159471e..927236903b 100644 --- a/crates/ui-egui/src/tools/align_bar.rs +++ b/crates/ui-egui/src/tools/align_bar.rs @@ -1,6 +1,11 @@ //! The Move tool's Align and Distribute controls (Photoshop shows them whenever the Move tool is //! active; they enable once enough layers are selected). Every button dispatches an existing //! `layer.align.*` / `layer.distribute.*` command. +//! +//! The bar reads, after Show Transform Controls: Align left, horizontal centres, right and +//! Distribute vertically; Align top, vertical centres, bottom and Distribute horizontally; the +//! "..." button (a compact icon panel); the gear (the Move tool's three hover and group toggles, +//! #11381). use serde_json::json; @@ -8,7 +13,7 @@ use crate::theme::Tokens; use crate::{PhotocraftApp, icons}; /// (command id, icon, label). The labels are the Layer menu's, already translated. -const ALIGN: [(&str, &str, &str); 6] = [ +pub(crate) const ALIGN: [(&str, &str, &str); 6] = [ ("layer.align.leftEdges", "align-edge-left", "Left Edges"), ("layer.align.horizontalCenters", "align-edge-hcenter", "Horizontal Centers"), ("layer.align.rightEdges", "align-edge-right", "Right Edges"), @@ -17,49 +22,114 @@ const ALIGN: [(&str, &str, &str); 6] = [ ("layer.align.bottomEdges", "align-edge-bottom", "Bottom Edges"), ]; -const DISTRIBUTE: [(&str, &str, &str); 8] = [ +/// The panel's Distribute group: top, vertical centres, bottom, left, horizontal centres, right. +const DISTRIBUTE: [(&str, &str, &str); 6] = [ ("layer.distribute.topEdges", "distribute-top", "Top Edges"), ("layer.distribute.verticalCenters", "distribute-vcenter", "Vertical Centers"), ("layer.distribute.bottomEdges", "distribute-bottom", "Bottom Edges"), ("layer.distribute.leftEdges", "distribute-left", "Left Edges"), ("layer.distribute.horizontalCenters", "distribute-hcenter", "Horizontal Centers"), ("layer.distribute.rightEdges", "distribute-right", "Right Edges"), - ("layer.distribute.horizontally", "distribute-horizontal", "Horizontally"), - ("layer.distribute.vertically", "distribute-vertical", "Vertically"), ]; -/// The six align icons followed by a menu holding both groups with icons and names. -/// Each icon uses 20 pt artwork inside a 28 pt hit target for high-DPI legibility -/// without changing enabled-state or command dispatch (#8849). +/// One bar button: (command id, icon, tooltip). +type BarButton = (&'static str, &'static str, &'static str); + +/// The two button groups of the bar, in order. The tooltips are the reference application's. +fn bar_groups() -> [[BarButton; 4]; 2] { + [ + [ + ("layer.align.leftEdges", "align-edge-left", tl!("Align left edges")), + ("layer.align.horizontalCenters", "align-edge-hcenter", tl!("Align horizontal centers")), + ("layer.align.rightEdges", "align-edge-right", tl!("Align right edges")), + ("layer.distribute.vertically", "distribute-vertical", tl!("Distribute vertically")), + ], + [ + ("layer.align.topEdges", "align-edge-top", tl!("Align top edges")), + ("layer.align.verticalCenters", "align-edge-vcenter", tl!("Align vertical centers")), + ("layer.align.bottomEdges", "align-edge-bottom", tl!("Align bottom edges")), + ("layer.distribute.horizontally", "distribute-horizontal", tl!("Distribute horizontally")), + ], + ] +} + +/// Whether the "..." panel is open: a click on the button toggles it and nothing else closes it +/// (Escape included), as in the reference application. +pub(crate) fn panel_open_id() -> egui::Id { + egui::Id::unique("move-align-panel-open") +} + +pub(crate) fn panel_is_open(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(panel_open_id())).unwrap_or(false) +} + +/// The two groups of four icons, then the "..." button and its panel. Each icon uses 20 pt +/// artwork inside a 28 pt hit target for high-DPI legibility without changing enabled-state or +/// command dispatch (#8849). pub fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing.x = 0.0; - for (cmd, icon, label) in ALIGN { - let tip = format!("{}: {}", tl!("Align"), tl!(label)); - let on = app.session.is_enabled(cmd); - if ui.add_enabled_ui(on, |ui| icons::button_with_icon_size(ui, icon, 28.0, 20.0, false, &tip)).inner.clicked() { - let _ = app.run(cmd, json!({})); + for group in bar_groups() { + for (cmd, icon, tip) in group { + let on = app.session.is_enabled(cmd); + if ui.add_enabled_ui(on, |ui| icons::button_with_icon_size(ui, icon, 28.0, 20.0, false, tip)).inner.clicked() { + let _ = app.run(cmd, json!({})); + } } + ui.add_space(6.0); + } + let more = icons::button_with_icon_size(ui, "ellipsis", 28.0, 20.0, false, tl!("Align and distribute")); + let ctx = ui.ctx().clone(); + let open = panel_is_open(&ctx); + if more.clicked() { + ctx.data_mut(|d| d.insert_temp(panel_open_id(), !open)); + } + if panel_is_open(&ctx) { + panel(app, &ctx, more.rect); } ui.add_space(6.0); - let more = icons::button_with_icon_size(ui, "ellipsis", 28.0, 20.0, false, tl!("Align and distribute")); - egui::Popup::menu(&more).show(|ui| { +} + +/// The compact icon panel under the "..." button: Align (6) and Distribute (6). The Distribute +/// Spacing group (#10715) and the Align To dropdown (#10358) go below these as further `group` +/// rows. +fn panel(app: &mut PhotocraftApp, ctx: &egui::Context, anchor: egui::Rect) { + let t = Tokens::get(ctx); + egui::Area::new(egui::Id::unique("move-align-panel")).order(egui::Order::Foreground).fixed_pos(anchor.left_bottom() + egui::vec2(0.0, 2.0)).show( + ctx, + |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.spacing_mut().item_spacing = egui::vec2(0.0, 2.0); + let mut group = |ui: &mut egui::Ui, title: &str, kind: &str, items: &[(&str, &str, &str)]| { + ui.label(egui::RichText::new(title).small().color(t.text_dim)); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + for (cmd, icon, label) in items { + let tip = format!("{kind}: {}", tl!(label)); + let on = app.session.is_enabled(cmd); + if ui.add_enabled_ui(on, |ui| icons::button_with_icon_size(ui, icon, 28.0, 20.0, false, &tip)).inner.clicked() { + let _ = app.run(cmd, json!({})); + } + } + }); + }; + group(ui, tl!("Align"), tl!("Align"), &ALIGN); + ui.add_space(4.0); + group(ui, tl!("Distribute"), tl!("Distribute"), &DISTRIBUTE); + }); + }, + ); +} + +/// The gear after the "..." button: a menu of the Move tool's three check items, all on by +/// default and saved with the tool options. +pub fn gear(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let gear = icons::button_with_icon_size(ui, "settings", 28.0, 20.0, false, tl!("Options")); + egui::Popup::menu(&gear).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { ui.set_min_width(200.0); - let mut section = |ui: &mut egui::Ui, title: &str, items: &[(&str, &str, &str)]| { - ui.label(egui::RichText::new(title).small().color(t.text_dim)); - for (cmd, icon, label) in items { - let on = app.session.is_enabled(cmd); - let tint = if on { t.icon } else { t.text_dim }; - let button = egui::Button::image_and_text(icons::image(icon, 16.0, tint), tl!(label)); - if ui.add_enabled(on, button).clicked() { - let _ = app.run(cmd, json!({})); - ui.close(); - } - } - }; - section(ui, tl!("Align"), &ALIGN); - ui.separator(); - section(ui, tl!("Distribute"), &DISTRIBUTE); + let o = &mut app.ui.tool_options; + ui.checkbox(&mut o.move_show_hover_bounds, tl!("Show layer bounds on hover")); + ui.checkbox(&mut o.move_expand_group_on_click, tl!("Expand layer group on click")); + ui.checkbox(&mut o.move_show_layers_hover_bounds, tl!("Show hover bounds from Layers")); }); } @@ -70,9 +140,12 @@ mod tests { #[test] fn every_button_is_a_live_command_with_an_icon() { let specs = photocraft_engine::command_specs(); - for (cmd, icon, _) in ALIGN.iter().chain(DISTRIBUTE.iter()) { - assert!(specs.iter().any(|c| c.id == *cmd), "{cmd} is not a command"); + let bar: Vec = bar_groups().into_iter().flatten().collect(); + let panel = ALIGN.iter().chain(DISTRIBUTE.iter()); + for (cmd, icon) in bar.iter().map(|b| (b.0, b.1)).chain(panel.map(|b| (b.0, b.1))) { + assert!(specs.iter().any(|c| c.id == cmd), "{cmd} is not a command"); assert!(icons::exists(icon), "{icon} is not embedded"); } + assert!(icons::exists("settings")); } } diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 6cad2b2158..ed113909a6 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -230,6 +230,23 @@ fn set_ruler(app: &mut PhotocraftApp, r: Ruler) { let _ = app.run("image.analysis.rulerTool", json!({"start": r.start, "end": r.end, "protractor": r.protractor})); } +#[cfg(test)] +#[path = "note_show_on_new_tests.rs"] +mod note_show_on_new_tests; + +/// Create a note at the rounded document position using the Note tool's options. +/// After `notes.add` succeeds, select the note and open the Notes panel. Enable Show Notes +/// while leaving the master Extras switch alone. +pub(crate) fn create_note(app: &mut PhotocraftApp, x: f64, y: f64) -> Result { + let a = &app.ui.analysis; + let params = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": a.note_color}); + let result = app.run("notes.add", params)?; + app.ui.analysis.note_selected = result["index"].as_u64().map(|v| v as usize); + app.ui.analysis.notes = true; + app.ui.view.show.notes = true; + Ok(result) +} + /// Pointer input for the Ruler, Count, Note and Color Sampler tools. Returns true when consumed. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { let tool = app.active_tool(); @@ -318,12 +335,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> app.ui.analysis.drag = Some(Drag::Note(i, [x - doc.notes[i].position[0], y - doc.notes[i].position[1]])); } None => { - let a = &app.ui.analysis; - let p = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": [a.note_color[0], a.note_color[1], a.note_color[2]]}); - if let Ok(r) = app.run("notes.add", p) { - app.ui.analysis.note_selected = r["index"].as_u64().map(|v| v as usize); - app.ui.analysis.notes = true; - } + let _ = create_note(app, x, y); } } } @@ -821,11 +833,8 @@ fn notes_panel(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some(p) = edit { let _ = app.run("notes.set", p); } - if delete - && let Some(i) = sel - && app.run("notes.delete", json!({"index": i})).is_ok() - { - app.ui.analysis.note_selected = (n > 1).then(|| i.min(n - 2)); + if delete && let Some(i) = sel { + ask_delete_note(app, i); } if close { app.ui.analysis.notes = false; @@ -988,3 +997,97 @@ fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] pub(crate) mod tests; + +/// Marks the "Delete this note?" alert (#11788). +const DELETE_NOTE_MARK: &str = "__deleteNote"; +/// Its "Don't show again", kept with the other dialog preferences. +const DELETE_NOTE_PREF: &str = "notes.delete.confirmation"; + +/// Delete note `index` of the active document, as the Note tool's ⌫/Delete and the Notes panel's +/// trash do: after the alert "Delete this note?" ([Yes] [No], "Don't show again"), or at once once +/// that is ticked. Nothing is selected afterwards. +pub fn ask_delete_note(app: &mut PhotocraftApp, index: usize) { + let skip = app.session.prefs().dialogs.get(DELETE_NOTE_PREF).and_then(|v| v.get("skip")).and_then(Value::as_bool) == Some(true); + let Some(doc) = app.session.active().map(|s| s.doc.id.0) else { return }; + if skip { + delete_note(app, index); + return; + } + if app.ui.dialogs.iter().any(|d| owns_delete_note(&d.fields)) { + return; + } + let mut f = Map::new(); + f.insert(DELETE_NOTE_MARK.into(), json!(true)); + f.insert("__command".into(), json!("notes.delete")); + f.insert("__label".into(), json!(tl!("Delete Note"))); + f.insert("document".into(), json!(doc)); + f.insert("index".into(), json!(index)); + f.insert("skip".into(), json!(false)); + app.ui.open_dialog(crate::state::DialogKind::Command, f); +} + +fn delete_note(app: &mut PhotocraftApp, index: usize) { + match app.run("notes.delete", json!({"index": index})) { + Ok(_) => app.ui.analysis.note_selected = None, + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } +} + +pub fn owns_delete_note(fields: &Map) -> bool { + fields.contains_key(DELETE_NOTE_MARK) +} + +pub fn delete_note_body(ui: &mut egui::Ui, fields: &mut Map) { + ui.label(tl!("Delete this note?")); + ui.add_space(8.0); + let mut skip = fields.get("skip").and_then(Value::as_bool).unwrap_or(false); + ui.checkbox(&mut skip, tl!("Don't show again")); + fields.insert("skip".into(), json!(skip)); +} + +/// Yes: the note goes (one "Delete Note" step), and "Don't show again" is remembered. +pub fn confirm_delete_note(app: &mut PhotocraftApp, fields: &Map) -> Result { + let index = fields.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or(tl!("No note to delete"))?; + let doc = app.session.active().map(|s| (s.doc.id.0, s.doc.notes.len())); + if doc.map(|d| d.0) != fields.get("document").and_then(Value::as_u64) || doc.is_none_or(|d| index >= d.1) { + return Err(tl!("The document or its notes changed. Please delete the note again.").into()); + } + let result = app.run("notes.delete", json!({"index": index}))?; + app.ui.analysis.note_selected = None; + if fields.get("skip").and_then(Value::as_bool) == Some(true) { + app.session.edit_prefs(|prefs| { + prefs.dialogs.insert(DELETE_NOTE_PREF.into(), json!({"skip": true})); + }); + if let Err(error) = crate::prefs_ui::save_preferences(app) { + app.ui.status = crate::i18n::fmt(tl!("Note deleted, but the preference could not be saved: {error}"), &[("error", &error)]); + app.ui.status_error = true; + } + } + Ok(result) +} + +/// The Note tool with a note selected: ⌫/Delete asks to delete the note (#11788), never the +/// layer (Delete Layer) or the pixels (Edit › Clear). Text fields keep the keys. +pub fn note_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + use crate::shortcut_dispatch::Focus; + let Some(index) = app.ui.analysis.note_selected else { return false }; + if app.ui.tool != Tool::Note || app.ui.text_edit.is_some() || matches!(Focus::of(ctx), Focus::Text | Focus::DeletingWidget) { + return false; + } + if app.session.active().is_none_or(|s| index >= s.doc.notes.len()) { + return false; + } + let mods = ctx.input(|i| i.modifiers); + if !mods.is_none() || !ctx.input_mut(|i| i.consume_key(mods, egui::Key::Delete) || i.consume_key(mods, egui::Key::Backspace)) { + return false; + } + ask_delete_note(app, index); + true +} + +#[cfg(test)] +#[path = "note_delete_key_tests.rs"] +mod note_delete_key_tests; diff --git a/crates/ui-egui/src/tools/artboard_tool.rs b/crates/ui-egui/src/tools/artboard_tool.rs index 80e8d4779a..36909acb71 100644 --- a/crates/ui-egui/src/tools/artboard_tool.rs +++ b/crates/ui-egui/src/tools/artboard_tool.rs @@ -20,6 +20,7 @@ use crate::state::Tool; use crate::theme::Tokens; mod add_mode; +pub(crate) mod bar; /// How far from an edge (screen points) a press still grabs its handle. const HANDLE_PX: f64 = 6.0; @@ -33,14 +34,47 @@ const PLUS_RADIUS_PX: f64 = 8.0; /// direction from the board's centre. const SIDES: [(&str, [f64; 2]); 4] = [("top", [0.0, -1.0]), ("right", [1.0, 0.0]), ("bottom", [0.0, 1.0]), ("left", [-1.0, 0.0])]; -/// Artboard tool state (serde: readable through the control channel). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +/// Artboard tool state (serde: readable through the control channel). The fields after `drag` are +/// the tool's options (#11385), which Reset Tool puts back to [`ArtboardToolUi::default`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct ArtboardToolUi { /// Add New Artboard's placing mode: a click on empty canvas puts a board there (#11386). pub adding: bool, #[serde(skip)] pub drag: Option, + /// The bar's size preset (empty: Custom) and, with no board selected, the size it shows. + pub preset: String, + pub width: u32, + pub height: u32, + /// The background of a board the tool draws: `white`, `black`, `transparent` or `custom`. + pub background: String, + /// `#rrggbb` of the `custom` background. + pub background_color: String, + /// The gear menu's four entries. + pub auto_nest: bool, + pub auto_size_canvas: bool, + pub keep_relative_position: bool, + pub shrinkwrap_on_save: bool, +} + +impl Default for ArtboardToolUi { + fn default() -> Self { + let (preset, width, height) = bar::DEFAULT_SIZE; + Self { + adding: false, + drag: None, + preset: preset.to_string(), + width, + height, + background: "white".to_string(), + background_color: "#ffffff".to_string(), + auto_nest: true, + auto_size_canvas: true, + keep_relative_position: true, + shrinkwrap_on_save: true, + } + } } /// A gesture in progress. Board rects are `[x0, y0, x1, y1]` in document pixels. @@ -241,7 +275,9 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> if r[2] <= r[0] || r[3] <= r[1] { return true; } - app.run("layer.new.artboard", json!({"rect": xywh(r), "takeBackground": true})) + let mut p = bar::with_background(app, json!({"rect": xywh(r)})); + p["takeBackground"] = json!(true); + app.run("layer.new.artboard", p) } ArtboardDrag::Move { id, rect, .. } if r != rect => app.run("layer.artboard.set", json!({"layer": id.0, "x": r[0], "y": r[1]})), // Resizing leaves the contents where they are, as in Photoshop. @@ -304,45 +340,20 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform } } -/// The Artboard tool's options bar: the selected board's size preset, W/H, Make Portrait / Make -/// Landscape, and Add New Artboard. +/// The Artboard tool's options bar: the size preset, W/H, Make Portrait / Make Landscape, the +/// background, Add New Artboard, the Align panel and the gear menu (the new controls are in `bar`). pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { if tool != Tool::Artboard { add_mode::leave(app); return false; } - let t = Tokens::get(ui.ctx()); let board = active_board(app); - let preset = board.and_then(|(id, _)| app.session.active()?.doc.layer(id)?.artboard().map(|a| a.preset.clone())); - let mut edit: Option = None; - ui.add_enabled_ui(board.is_some(), |ui| { - let (id, r) = board.unwrap_or((LayerId(0), [0, 0, 0, 0])); - ui.label(egui::RichText::new(tl!("Size")).color(t.text_dim)); - let mut preset = preset.unwrap_or_default(); - let mut opts: Vec<(String, &str)> = vec![(String::new(), tl!("Custom"))]; - opts.extend(photocraft_engine::artboard_cmds::PRESETS.iter().map(|(n, _, _)| (n.to_string(), *n))); - if crate::widgets::dropdown(ui, "artboard-tool-preset", tl!("Preset"), &mut preset, &opts, 150.0) && !preset.is_empty() { - edit = Some(json!({"layer": id.0, "preset": preset})); - } - let (mut w, mut h) = ((r[2] - r[0]) as f32, (r[3] - r[1]) as f32); - ui.label(egui::RichText::new(tl!("W")).color(t.text_dim)); - let cw = crate::widgets::value_field(ui, &mut w, 1.0..=300_000.0, "px", 64.0).accessible_name(tl!("Width")).changed(); - ui.label(egui::RichText::new(tl!("H")).color(t.text_dim)); - let ch = crate::widgets::value_field(ui, &mut h, 1.0..=300_000.0, "px", 64.0).accessible_name(tl!("Height")).changed(); - if cw || ch { - edit = Some(json!({"layer": id.0, "width": w.round(), "height": h.round(), "coalesce": format!("artboard-tool-wh-{}", id.0)})); - } - if crate::widgets::secondary_button(ui, tl!("Make Portrait"), 0.0).clicked() && w > h { - edit = Some(json!({"layer": id.0, "width": h.round(), "height": w.round()})); - } - if crate::widgets::secondary_button(ui, tl!("Make Landscape"), 0.0).clicked() && h > w { - edit = Some(json!({"layer": id.0, "width": h.round(), "height": w.round()})); - } - }); + let edit = bar::size_group(app, ui, board); if let Some(p) = edit { let r = app.run("layer.artboard.set", p); report(app, r); } + bar::background(app, ui); crate::widgets::vline(ui, 22.0); let has_doc = app.session.active().is_some(); // Drawn as the primary button while the placing mode is on. @@ -359,6 +370,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo if button.clicked() { add_mode::toggle(app); } + bar::align_and_gear(app, ui); true } diff --git a/crates/ui-egui/src/tools/artboard_tool/add_mode.rs b/crates/ui-egui/src/tools/artboard_tool/add_mode.rs index c46d6d737d..10df5eaaa5 100644 --- a/crates/ui-egui/src/tools/artboard_tool/add_mode.rs +++ b/crates/ui-egui/src/tools/artboard_tool/add_mode.rs @@ -5,7 +5,6 @@ use serde_json::{Value, json}; -use super::active_board; use crate::PhotocraftApp; use crate::state::Tool; @@ -24,23 +23,21 @@ pub(super) fn leave(app: &mut PhotocraftApp) { app.ui.artboard_tool.adding = false; } -/// The size the options bar shows: the selected board's, else the canvas size (the engine's -/// fallback for a board with no size). -fn bar_size(app: &PhotocraftApp) -> Option<[i64; 2]> { - if let Some((_, r)) = active_board(app) { - return Some([r[2].saturating_sub(r[0]), r[3].saturating_sub(r[1])]); - } - let size = app.session.active()?.doc.size; - Some([i64::from(size.width), i64::from(size.height)]) -} - /// A click at document point `p` on empty canvas: one `layer.new.artboard` with the bar's size and /// its top-left corner at the click, rounded to whole pixels. None when the mode is off. pub(super) fn click(app: &mut PhotocraftApp, p: [f64; 2]) -> Option> { if !active(app) { return None; } - let [w, h] = bar_size(app)?; + app.session.active()?; + let [w, h] = super::bar::bar_size(app); let rect = [p[0].round() as i64, p[1].round() as i64, w, h]; - Some(app.run("layer.new.artboard", json!({"rect": rect}))) + let mut params = json!({"rect": rect}); + // With no board selected the size is the tool option's, so the board also keeps its preset + // name (the engine stores it and, with an explicit `rect`, the rect still decides the size). + let preset = &app.ui.artboard_tool.preset; + if !preset.is_empty() && super::active_board(app).is_none() { + params["preset"] = json!(preset); + } + Some(app.run("layer.new.artboard", super::bar::with_background(app, params))) } diff --git a/crates/ui-egui/src/tools/artboard_tool/bar.rs b/crates/ui-egui/src/tools/artboard_tool/bar.rs new file mode 100644 index 0000000000..e42199577e --- /dev/null +++ b/crates/ui-egui/src/tools/artboard_tool/bar.rs @@ -0,0 +1,343 @@ +//! The Artboard tool's options bar controls (#11385): the size group (preset, W, H, Make Portrait, +//! Make Landscape) that edits the selected board, or the tool's own options when no board is +//! selected; the background swatch and dropdown for the boards the tool draws; the Align panel; and +//! the gear menu. The options live in [`ArtboardToolUi`](super::ArtboardToolUi). + +use egui::Color32; +use photocraft_doc::{ArtboardBackground, Layer, LayerId}; +use photocraft_engine::artboard_cmds::PRESETS; +use serde_json::{Value, json}; + +use crate::theme::Tokens; +use crate::{PhotocraftApp, icons}; + +/// The size preset a fresh bar (and Reset Tool) shows, with its width and height. +pub const DEFAULT_SIZE: (&str, u32, u32) = ("iPhone 8/7/6", 750, 1334); + +/// The largest board side the bar accepts (the engine's limit). +const MAX_SIDE: f32 = 300_000.0; + +/// The Align panel: three groups of entries. An entry is a label and the `layer.align.*` command +/// it runs; Distribute Widths / Heights have none yet (their behaviour is not measured), so they +/// show disabled. +pub const ALIGN_PANEL: [&[(&str, Option<&str>)]; 3] = [ + &[ + ("Left Edges", Some("layer.align.leftEdges")), + ("Horizontal Centers", Some("layer.align.horizontalCenters")), + ("Right Edges", Some("layer.align.rightEdges")), + ], + &[ + ("Top Edges", Some("layer.align.topEdges")), + ("Vertical Centers", Some("layer.align.verticalCenters")), + ("Bottom Edges", Some("layer.align.bottomEdges")), + ], + &[("Distribute Widths", None), ("Distribute Heights", None)], +]; + +/// The gear menu's entries, in order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Gear { + AutoNest, + AutoSizeCanvas, + KeepRelativePosition, + ShrinkwrapOnSave, +} + +/// Each gear entry and its label. +pub const GEAR: [(Gear, &str); 4] = [ + (Gear::AutoNest, "Auto-nest Layers"), + (Gear::AutoSizeCanvas, "Auto-size Canvas"), + (Gear::KeepRelativePosition, "Keep Relative Position During Layer Reordering"), + (Gear::ShrinkwrapOnSave, "Shrinkwrap Canvas on Save"), +]; + +impl Gear { + /// Is the entry checked? + pub fn checked(self, o: &super::ArtboardToolUi) -> bool { + match self { + Gear::AutoNest => o.auto_nest, + Gear::AutoSizeCanvas => o.auto_size_canvas, + Gear::KeepRelativePosition => o.keep_relative_position, + Gear::ShrinkwrapOnSave => o.shrinkwrap_on_save, + } + } + + /// Only Auto-nest Layers does something yet (the Move tool's auto-nesting, #10512); the others + /// are drawn checked and disabled until their behaviour is measured. + pub fn enabled(self) -> bool { + self == Gear::AutoNest + } +} + +/// "The bar's size": the selected board's size, else the tool option's. `[width, height]` in pixels. +pub fn bar_size(app: &PhotocraftApp) -> [i64; 2] { + match super::active_board(app) { + Some((_, r)) => [r[2].saturating_sub(r[0]), r[3].saturating_sub(r[1])], + None => [i64::from(app.ui.artboard_tool.width), i64::from(app.ui.artboard_tool.height)], + } +} + +/// `params` for `layer.new.artboard` plus the bar's background: `background`, and `color` for Other…. +pub fn with_background(app: &PhotocraftApp, mut params: Value) -> Value { + let o = &app.ui.artboard_tool; + params["background"] = json!(o.background); + if o.background == "custom" { + params["color"] = json!(o.background_color); + } + params +} + +/// Choose size preset `name` as the tool option: its size, no board involved. Unknown names and +/// Custom (empty) change nothing. +pub fn set_preset(app: &mut PhotocraftApp, name: &str) { + if let Some((n, w, h)) = PRESETS.iter().find(|(n, _, _)| *n == name) { + let o = &mut app.ui.artboard_tool; + (o.preset, o.width, o.height) = (n.to_string(), *w, *h); + } +} + +/// Set the tool option size to `w` x `h` (clamped to 1..=300000); the preset becomes Custom, or +/// stays when the size is still the preset's. +pub fn set_size(app: &mut PhotocraftApp, w: f32, h: f32) { + let clamp = |v: f32| if v.is_finite() { v.round().clamp(1.0, MAX_SIDE) as u32 } else { 1 }; + let (w, h) = (clamp(w), clamp(h)); + let o = &mut app.ui.artboard_tool; + (o.width, o.height) = (w, h); + if !PRESETS.iter().any(|(n, pw, ph)| *n == o.preset && (*pw, *ph) == (w, h)) { + o.preset.clear(); + } +} + +/// The size preset the bar shows for board `id`: the name stored on the board ("" = Custom). +pub fn board_preset(app: &PhotocraftApp, id: LayerId) -> String { + app.session.active().and_then(|st| st.doc.layer(id)).and_then(Layer::artboard).map(|a| a.preset.clone()).unwrap_or_default() +} + +/// The selected boards: each selected layer's artboard, once, in document order. +fn selected_boards(app: &PhotocraftApp) -> Vec { + let Some(st) = app.session.active() else { return Vec::new() }; + let mut ids: Vec = Vec::new(); + for l in st.selected_layers() { + if let Some(b) = st.doc.artboard_of(l) + && !ids.contains(&b) + { + ids.push(b); + } + } + ids +} + +/// The background the bar shows as `(name, #rrggbb)`: the first selected board's, else the tool +/// option's. The colour is the custom one (or the option's remembered one for the named ones). +pub fn shown_background(app: &PhotocraftApp) -> (String, String) { + let o = &app.ui.artboard_tool; + let first = selected_boards(app).first().and_then(|id| app.session.active()?.doc.layer(*id)?.artboard().map(|a| a.background)); + match first { + Some(ArtboardBackground::Custom(c)) => { + let [r, g, b, _] = c.to_rgba8(); + ("custom".to_string(), format!("#{r:02x}{g:02x}{b:02x}")) + } + Some(b) => (b.name().to_string(), o.background_color.clone()), + None => (o.background.clone(), o.background_color.clone()), + } +} + +/// Choose background `name` (`white`, `black`, `transparent` or `custom` with `color`, `#rrggbb`). +/// It is the tool option for the next drawn board, and with boards selected also the background of +/// every selected board in one `layer.artboard.set` step ("Edit Artboard" / "Edit Artboards"). +pub fn set_background(app: &mut PhotocraftApp, name: &str, color: &str) -> Result { + let custom = name == "custom"; + if custom { + crate::color_picker_ui::parse_hex(color).ok_or("not a colour")?; + } + let mut boards = selected_boards(app); + // A board whose custom colour already has this RGB keeps its own value: the swatch shows it + // as 8-bit RGB, so OK in the picker without a change must not flatten its alpha or precision. + if custom && let Some(want) = crate::color_picker_ui::parse_hex(color) { + let hex = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let st = app.session.active(); + boards.retain(|id| match st.and_then(|st| st.doc.layer(*id)?.artboard().map(|a| a.background)) { + Some(ArtboardBackground::Custom(c)) => { + let [r, g, b, _] = c.to_rgba8(); + [r, g, b] != hex(want) + } + _ => true, + }); + } + let mut out = json!({}); + if !boards.is_empty() { + let mut params = json!({"layers": boards.iter().map(|b| b.0).collect::>(), "background": name}); + if custom { + params["color"] = json!(color); + } + out = app.run("layer.artboard.set", params)?; + } + let o = &mut app.ui.artboard_tool; + o.background = name.to_string(); + if custom { + o.background_color = color.to_string(); + } + Ok(out) +} + +/// OK in the Color Picker opened by Other…: the custom background is `color` (`#rrggbb`), for the +/// selected boards (if any) and the next drawn one. +pub fn set_custom_background(app: &mut PhotocraftApp, color: &str) -> Result { + set_background(app, "custom", color)?; + Ok(json!({"color": color})) +} + +/// [`set_custom_background`] for OK in the picker. `unchanged` (the result is the colour the picker +/// opened with, after any Only Web Colors snap) leaves every selected board alone, with no command +/// and no history step: only the tool option for the next board follows. Otherwise boards that +/// already have the picked RGB are skipped one by one ([`set_background`]). +pub fn set_custom_background_from_picker(app: &mut PhotocraftApp, color: &str, unchanged: bool) -> Result { + if !unchanged { + return set_custom_background(app, color); + } + crate::color_picker_ui::parse_hex(color).ok_or("not a colour")?; + let o = &mut app.ui.artboard_tool; + o.background = "custom".to_string(); + o.background_color = color.to_string(); + Ok(json!({"color": color})) +} + +/// Run Align panel entry `index` of group `group` on the selected boards. None for an entry that +/// has no command yet. +pub fn run_align(app: &mut PhotocraftApp, group: usize, index: usize) -> Option> { + let cmd = ALIGN_PANEL.get(group)?.get(index)?.1?; + Some(app.run(cmd, json!({}))) +} + +/// The swatch colour of a background (`name`, with `hex` for custom). +fn background_color(name: &str, hex: &str) -> Color32 { + match name { + "black" => Color32::BLACK, + "transparent" => Color32::TRANSPARENT, + "custom" => crate::color_picker_ui::parse_hex(hex).map_or(Color32::WHITE, rgb32), + _ => Color32::WHITE, + } +} + +fn rgb32(c: [f32; 3]) -> Color32 { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) +} + +/// Opens the Color Picker for the custom background. +fn pick_background(app: &mut PhotocraftApp) { + let rgb = crate::color_picker_ui::parse_hex(&shown_background(app).1).unwrap_or([1.0; 3]); + let title = crate::color_picker_ui::title_for(tl!("Color")); + crate::color_picker_ui::open_for_target(app, "artboardBackground", &title, rgb); +} + +/// Size, W, H, Make Portrait and Make Landscape. With a board selected they show and edit the +/// board (the returned `layer.artboard.set` params); with none, Size, W and H edit the tool's own +/// options and nothing is returned. +pub fn size_group(app: &mut PhotocraftApp, ui: &mut egui::Ui, board: Option<(LayerId, [i64; 4])>) -> Option { + let t = Tokens::get(ui.ctx()); + let mut edit: Option = None; + let (mut preset, mut w, mut h) = match board { + Some((id, r)) => (board_preset(app, id), (r[2] - r[0]) as f32, (r[3] - r[1]) as f32), + None => (app.ui.artboard_tool.preset.clone(), app.ui.artboard_tool.width as f32, app.ui.artboard_tool.height as f32), + }; + let id = board.map_or(LayerId(0), |b| b.0); + ui.label(egui::RichText::new(tl!("Size")).color(t.text_dim)); + let mut opts: Vec<(String, &str)> = vec![(String::new(), tl!("Custom"))]; + opts.extend(PRESETS.iter().map(|(n, _, _)| (n.to_string(), *n))); + if crate::widgets::dropdown(ui, "artboard-tool-preset", tl!("Preset"), &mut preset, &opts, 150.0) && !preset.is_empty() { + if board.is_some() { + edit = Some(json!({"layer": id.0, "preset": preset})); + } else { + set_preset(app, &preset); + } + } + ui.label(egui::RichText::new(tl!("W")).color(t.text_dim)); + let cw = crate::widgets::value_field(ui, &mut w, 1.0..=MAX_SIDE, "px", 64.0).accessible_name(tl!("Width")).changed(); + ui.label(egui::RichText::new(tl!("H")).color(t.text_dim)); + let ch = crate::widgets::value_field(ui, &mut h, 1.0..=MAX_SIDE, "px", 64.0).accessible_name(tl!("Height")).changed(); + if cw || ch { + if board.is_some() { + edit = Some(json!({"layer": id.0, "width": w.round(), "height": h.round(), "coalesce": format!("artboard-tool-wh-{}", id.0)})); + } else { + set_size(app, w, h); + } + } + ui.add_enabled_ui(board.is_some(), |ui| { + if crate::widgets::secondary_button(ui, tl!("Make Portrait"), 0.0).clicked() && w > h { + edit = Some(json!({"layer": id.0, "width": h.round(), "height": w.round()})); + } + if crate::widgets::secondary_button(ui, tl!("Make Landscape"), 0.0).clicked() && h > w { + edit = Some(json!({"layer": id.0, "width": h.round(), "height": w.round()})); + } + }); + edit +} + +/// The background swatch and its dropdown (White, Black, Transparent, Other…). With boards selected +/// they show the first selected board's background and a change recolours every selected board in +/// one history step (`layer.artboard.set`; "Edit Artboard" for one, "Edit Artboards" for several); +/// either way it is also the tool option, the background of the next drawn board. With no board +/// selected it edits the tool option only. +pub fn background(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let (name, hex) = shown_background(app); + if crate::widgets::color_swatch_button(ui, background_color(&name, &hex), tl!("Artboard Background Color")).clicked() { + pick_background(app); + } + let mut bg = name; + let opts = [ + ("white".to_string(), tl!("White")), + ("black".to_string(), tl!("Black")), + ("transparent".to_string(), tl!("Transparent")), + ("custom".to_string(), tl!("Other…")), + ]; + if crate::widgets::dropdown(ui, "artboard-tool-bg", tl!("Background"), &mut bg, &opts, 120.0) { + if bg == "custom" { + pick_background(app); + } else if let Err(e) = set_background(app, &bg, &hex) { + app.ui.status = e; + app.ui.status_error = true; + } + } +} + +/// The Align button with its panel, and the gear button with its menu. +pub fn align_and_gear(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + crate::widgets::vline(ui, 22.0); + let align = icons::button_with_icon_size(ui, "align-edge-left", 28.0, 20.0, false, tl!("Align")); + egui::Popup::menu(&align).show(|ui| { + ui.set_min_width(200.0); + for (g, group) in ALIGN_PANEL.iter().enumerate() { + if g > 0 { + ui.separator(); + } + for (i, (label, cmd)) in group.iter().enumerate() { + let on = cmd.is_some_and(|c| app.session.is_enabled(c)); + let icon = match cmd { + Some(c) => crate::align_bar::ALIGN.iter().find(|a| a.0 == *c).map_or("align-edge-left", |a| a.1), + None if *label == "Distribute Widths" => "distribute-horizontal", + None => "distribute-vertical", + }; + let tint = if on { t.icon } else { t.text_dim }; + let button = egui::Button::image_and_text(icons::image(icon, 16.0, tint), tl!(label)); + if ui.add_enabled(on, button).clicked() { + if let Some(Err(e)) = run_align(app, g, i) { + app.ui.status = e; + app.ui.status_error = true; + } + ui.close(); + } + } + } + }); + let gear = icons::button_with_icon_size(ui, "settings", 28.0, 20.0, false, tl!("Options")); + egui::Popup::menu(&gear).show(|ui| { + for (item, label) in GEAR { + let mut on = item.checked(&app.ui.artboard_tool); + if ui.add_enabled(item.enabled(), egui::Checkbox::new(&mut on, tl!(label))).changed() && item == Gear::AutoNest { + app.ui.artboard_tool.auto_nest = on; + } + } + }); +} diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index e417dc5a77..3e59a90444 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -82,9 +82,45 @@ pub(crate) fn picker_id() -> egui::Id { /// All opening paths protect the same frame, including the control channel and options bar. pub(crate) fn open(ui: &mut crate::state::UiState, ctx: &egui::Context, at: [f32; 2]) { ui.brush_picker = Some(at); + // A new opening takes the brush as it is then, not an earlier opening's. + ctx.data_mut(|d| d.remove_temp::(opened_id())); crate::canvas_popup::mark_open(ctx, picker_id()); } +pub(crate) fn opened_id() -> egui::Id { + picker_id().with("opened-with") +} + +/// What Escape in the picker goes back to (#11816): the Size and Hardness it opened with (or a +/// picked preset brought), and the values its own fields last typed. Escape reverts a value only +/// while it is still the typed one, so a change from elsewhere (`]`, the options bar) stays. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Opened { + opened: [f32; 2], + typed: [f32; 2], +} + +impl Opened { + pub(crate) fn new(b: &photocraft_engine::BrushSettings) -> Self { + Self { opened: [b.size, b.hardness], typed: [b.size, b.hardness] } + } + + pub(crate) fn typed(&mut self, b: &photocraft_engine::BrushSettings) { + self.typed = [b.size, b.hardness]; + } + + pub(crate) fn revert(&self, now: &photocraft_engine::BrushSettings) -> photocraft_engine::BrushSettings { + let mut b = now.clone(); + if b.size == self.typed[0] { + b.size = self.opened[0]; + } + if b.hardness == self.typed[1] { + b.hardness = self.opened[1]; + } + b + } +} + /// The options-bar brush chip that shows and hides the picker. A press on it isn't an outside /// press that closes the picker: the chip's click toggles it. pub fn chip_id() -> egui::Id { diff --git a/crates/ui-egui/src/tools/eyedropper_ui.rs b/crates/ui-egui/src/tools/eyedropper_ui.rs index 10fcaaa603..4e4c3d71c4 100644 --- a/crates/ui-egui/src/tools/eyedropper_ui.rs +++ b/crates/ui-egui/src/tools/eyedropper_ui.rs @@ -50,7 +50,7 @@ pub fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); ui.label( egui::RichText::new(crate::i18n::fmt( - tl!("Click to sample the foreground colour · {key}-click for background"), + tl!("Click to sample the foreground color · {key}-click for background"), &[("key", &crate::shortcuts::pretty("Alt"))], )) .color(t.text_faint), diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index 1978f27086..c3d64441c9 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -995,7 +995,7 @@ fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pendi let dragging: Option = ui.data(|d| d.get_temp(key)); let mut preview = None; if let (Some(m), Some(pos)) = (dragging, resp.interact_pointer_pos()) { - let off = if pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0 { 1.0 } else { 0.0 }; + let off = if off_strip(pos, bar) { 1.0 } else { 0.0 }; let loc = loc_of(pos.x); let edit = match m { Marker::Color(i) if off > 0.0 && stops.len() > 2 => json!({"action": "delete", "index": i}), @@ -1038,3 +1038,9 @@ fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pendi #[cfg(test)] mod tests; + +/// A stop dragged to `pos` is off the gradient strip `bar` and comes off (removed on release): +/// below the stops or above the strip, by the same distance in every gradient editor. +pub(crate) fn off_strip(pos: egui::Pos2, bar: egui::Rect) -> bool { + pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0 +} diff --git a/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs b/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs index b5a16773f1..608f3d12ae 100644 --- a/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs +++ b/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs @@ -70,7 +70,7 @@ fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { if widgets::checkbox(ui, &mut value, "Align with layer").changed() { let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "align": value})); } - if widgets::secondary_button(ui, "Reset Alignment", ui.available_width()).on_hover_text(tl!("Centre the gradient (offset 0, 0)")).clicked() { + if widgets::secondary_button(ui, "Reset Alignment", ui.available_width()).on_hover_text(tl!("Center the gradient (offset 0, 0)")).clicked() { let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "offset": [0, 0]})); } } diff --git a/crates/ui-egui/src/tools/lasso_ui.rs b/crates/ui-egui/src/tools/lasso_ui.rs index 38dfaecdb1..5bca66d06e 100644 --- a/crates/ui-egui/src/tools/lasso_ui.rs +++ b/crates/ui-egui/src/tools/lasso_ui.rs @@ -171,17 +171,21 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool ToolEvent::Down { .. } => { if active(app) { // A click on the first point, or on the last one again, closes the outline. Aiming - // at the first point is a grab; clicking the last one again is the same click - // repeated, so it has only to allow for a pixel of hand jitter. Sharing the grab - // radius made every segment shorter than it impossible to draw, because the click - // meant to place the next vertex closed the outline instead (#7629). - let zoom = app.point_zoom().max(0.01) as f64; - let near = |q: [f64; 2], reach: f64| (q[0] - p[0]).hypot(q[1] - p[1]) < reach / zoom; - let again = |d: &Drag| d.points.last().is_some_and(|l| near([l[0], l[1]], SAME_POINT)); - let close = app.drag.as_ref().is_some_and(|d| d.points.len() >= 3 && (near(d.start, 8.0) || again(d))); + // at the first point is a grab, with a reach scaled to the size of the whole outline + // (`canvas::polygon_close_reach`, #6578); clicking the last one again is the same + // click repeated, so it has only to allow for a pixel of hand jitter. Sharing the + // grab radius made every segment shorter than it impossible to draw, because the + // click meant to place the next vertex closed the outline instead (#7629). + let point_zoom = app.point_zoom(); + let zoom = point_zoom.max(0.01) as f64; + let start_reach = |d: &Drag| crate::canvas::polygon_close_reach(d.points.iter().map(|q| [q[0], q[1]]), point_zoom); + let near = |q: [f64; 2], reach: f64| (q[0] - p[0]).hypot(q[1] - p[1]) < reach; + let at_start = |d: &Drag| near(d.start, start_reach(d)); + let again = |d: &Drag| d.points.last().is_some_and(|l| near([l[0], l[1]], SAME_POINT / zoom)); + let close = app.drag.as_ref().is_some_and(|d| d.points.len() >= 3 && (at_start(d) || again(d))); if close { // A path closes on its start point (a selection outline always closes). - if let Some(d) = app.drag.as_mut().filter(|d| d.tool == Tool::FreeformPen && near(d.start, 8.0)) { + if let Some(d) = app.drag.as_mut().filter(|d| d.tool == Tool::FreeformPen && at_start(d)) { let (start, n) = (d.start, d.points.len()); append(d, start); if let Some(lasso) = d.lasso.as_mut().filter(|_| d.points.len() > n) { diff --git a/crates/ui-egui/src/tools/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs index af1d45a2e0..816d661152 100644 --- a/crates/ui-egui/src/tools/lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/lasso_ui/tests.rs @@ -442,6 +442,28 @@ fn clicking_the_last_point_again_closes_the_outline() { assert!(app.session.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(150, 100, 0) > 0.9); } +/// #6578: Alt-clicking the four corners of a small square leaves the outline open (the last corner +/// lands within 8 points of the first, but is a new vertex); a click on the first point closes it. +#[test] +fn alt_clicking_the_last_corner_of_a_small_shape_does_not_close_it() { + let mut app = app(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + assert_eq!(app.point_zoom(), 1.0); + for [x, y] in [[100.0, 100.0], [106.0, 100.0], [106.0, 106.0], [100.0, 106.0]] { + event(&mut app, "down", x, y, Modifiers::ALT); + event(&mut app, "up", x, y, Modifiers::ALT); + assert!(active(&app), "corner ({x}, {y}): the outline stays open"); + } + assert_eq!(app.drag.as_ref().unwrap().points.len(), 4, "four corners"); + assert!(app.session.active().unwrap().doc.selection.is_none()); + event(&mut app, "down", 100.0, 100.0, Modifiers::ALT); + assert!(!active(&app), "a click on the first point closes"); + let b = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + let close_to = |v: i32, want: i32| v.abs_diff(want) <= 1; + assert!(close_to(b.x0, 100) && close_to(b.y0, 100) && close_to(b.x1, 106) && close_to(b.y1, 106), "a square, not a triangle: {b:?}"); +} + #[test] fn shift_drag_constrains_freeform_pen_to_a_straight_line() { let mut app = app(); @@ -483,3 +505,22 @@ fn real_canvas_cmd_drag_outside_the_selection_moves_the_layer() { assert!(app.session.active().unwrap().doc.selection.is_none(), "no selection was made"); assert_eq!((alpha(105, 120), alpha(165, 120)), (0.0, 1.0), "the layer moved 30 px to the right"); } + +#[test] +fn alt_clicking_narrow_and_rotated_polygons_keeps_the_fourth_corner() { + for corners in [[[100.0, 100.0], [200.0, 100.0], [200.0, 106.0], [100.0, 106.0]], [[100.0, 100.0], [160.0, 180.0], [155.2, 183.6], [95.2, 103.6]]] { + let mut app = app(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + for [x, y] in corners { + event(&mut app, "down", x, y, Modifiers::ALT); + event(&mut app, "up", x, y, Modifiers::ALT); + assert!(active(&app), "{corners:?}"); + } + assert_eq!(app.drag.as_ref().unwrap().points.len(), 4); + assert!(app.session.active().unwrap().doc.selection.is_none()); + event(&mut app, "down", 100.0, 100.0, Modifiers::ALT); + assert!(!active(&app)); + assert!(app.session.active().unwrap().doc.selection.is_some()); + } +} diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index 28ef343212..29d3861d9b 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -6,8 +6,11 @@ //! often at a higher Frequency. A click fastens a point; ⌥-click draws a straight segment and //! ⌥-drag a freehand one. ⌫ or Delete removes the last fastening point. Clicking the first point, //! a double-click or ↩ closes the border along the edges (⌥ with a straight segment); Esc cancels. -//! [ and ] narrow or widen the detection width by 1 px. As in Photoshop, the border follows the -//! active layer's pixels (the composite for a layer without pixels of its own). +//! [ and ] narrow or widen the detection width by 1 px. The border follows the edges of the visible +//! composite, whichever layer is active (hidden layers add none); documents that are not RGB keep +//! following the active layer's own pixels. In a non-RGB document an active group or adjustment +//! layer has no pixel surface of its own, so the tool follows the composite then instead of that +//! layer's pixels (`pixel_layer` and `read` in `photocraft_engine::magnetic_cmds`). //! //! The border closes through `select.magneticLasso` with `"trace": false`: the selection is exactly //! the outline drawn, in one history step, and an action replays that outline. @@ -375,7 +378,7 @@ pub fn frame(app: &mut PhotocraftApp) { /// Keys while the Magnetic Lasso is the tool: ↩ closes the border along the edges (⌥↩ straight), /// Esc cancels it, ⌫ / Delete remove the last fastening point, and [ / ] change the detection width -/// by 1 px. Returns whether a key was taken. +/// by 1 px (Shift+[ / Shift+] jump to 1 / 256 px). Returns whether a key was taken. pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.tool != Tool::MagneticLasso { return false; @@ -399,6 +402,17 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { return true; } } + // Shift+[ / Shift+] jump to the limits; they come first because the plain keys match with Shift held too. + let w = &mut app.ui.tool_options.magnetic_width; + // On a US layout the backend may report Shift+[ as the logical `{` key (egui's `OpenCurlyBracket`) with Shift set; a bare `{` (Programmer Dvorak) is left alone. + if pressed(Modifiers::SHIFT, Key::OpenBracket) || pressed(Modifiers::SHIFT, Key::OpenCurlyBracket) { + *w = 1.0; + return true; + } + if pressed(Modifiers::SHIFT, Key::CloseBracket) || pressed(Modifiers::SHIFT, Key::CloseCurlyBracket) { + *w = 256.0; + return true; + } let step = if pressed(Modifiers::NONE, Key::OpenBracket) { -1.0 } else if pressed(Modifiers::NONE, Key::CloseBracket) { @@ -406,7 +420,6 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } else { return false; }; - let w = &mut app.ui.tool_options.magnetic_width; *w = if w.is_finite() { (w.round() + step).clamp(1.0, 256.0) } else { 10.0 }; true } diff --git a/crates/ui-egui/src/tools/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs index aef1f315ef..f60bc71c6a 100644 --- a/crates/ui-egui/src/tools/move_hover.rs +++ b/crates/ui-egui/src/tools/move_hover.rs @@ -30,6 +30,7 @@ pub(crate) struct Hover { pub(crate) fn target(app: &mut PhotocraftApp, at: Option<[f64; 2]>, command: bool, pressed: bool) -> Option { if !app.session.prefs().tools.show_highlight_on_rollover || app.ui.tool != Tool::Move + || !app.ui.tool_options.move_show_hover_bounds || pressed || app.drag.is_some() || app.guide_drag.is_some() @@ -102,6 +103,7 @@ pub(crate) fn active_outline(app: &mut PhotocraftApp, at: Option<[f64; 2]>, comm } // A layer hovered in the Layers panel takes precedence over canvas rollover. if let Some(id) = app.hover_layer + && (app.ui.tool != Tool::Move || app.ui.tool_options.move_show_layers_hover_bounds) && app.drag.is_none() && app.guide_drag.is_none() && app.ui.transform.is_none() diff --git a/crates/ui-egui/src/tools/note_delete_key_tests.rs b/crates/ui-egui/src/tools/note_delete_key_tests.rs new file mode 100644 index 0000000000..9a1630e4e7 --- /dev/null +++ b/crates/ui-egui/src/tools/note_delete_key_tests.rs @@ -0,0 +1,107 @@ +//! #11788: with the Note tool, ⌫/Delete on a selected note asks "Delete this note?" and deletes +//! the note, never the layer; the Notes panel's trash asks the same. + +use super::*; + +/// A document with a second layer and one note, the Note tool on and the note selected. +fn app() -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap(); + s.execute("notes.add", json!({"x": 10, "y": 12, "text": "fix this"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::Note; + app.ui.analysis.note_selected = Some(0); + app +} + +/// A key through the app's shortcut handling, as the canvas gets it. +fn press(app: &mut PhotocraftApp, key: egui::Key) { + let ctx = egui::Context::default(); + let m = egui::Modifiers::NONE; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +fn notes(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.notes.len() +} + +fn alert(app: &PhotocraftApp) -> Option { + app.ui.dialogs.iter().find(|d| owns_delete_note(&d.fields)).map(|d| d.id) +} + +#[test] +fn delete_with_a_note_selected_asks_and_deletes_the_note_not_the_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let steps = app.session.active().unwrap().history.past_len(); + press(&mut app, key); + let id = alert(&app).unwrap_or_else(|| panic!("{key:?}: the alert")); + assert_eq!((layers(&app), notes(&app)), (2, 1), "{key:?}: nothing changes before the answer"); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!((layers(&app), notes(&app)), (2, 0), "{key:?}: the note goes, the layers stay"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1); + assert_eq!(st.history.undo_label(), Some("Delete Note")); + assert_eq!(app.ui.analysis.note_selected, None, "nothing selected after"); + } +} + +#[test] +fn no_keeps_the_document_and_history() { + let mut app = app(); + let steps = app.session.active().unwrap().history.past_len(); + press(&mut app, egui::Key::Delete); + let id = alert(&app).expect("the alert"); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert_eq!((layers(&app), notes(&app)), (2, 1)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); +} + +#[test] +fn dont_show_again_skips_the_alert_next_time() { + let mut app = app(); + app.run("notes.add", json!({"x": 30, "y": 30})).unwrap(); + press(&mut app, egui::Key::Delete); + let id = alert(&app).expect("the alert"); + app.ui.dialog_mut(id).unwrap().fields.insert("skip".into(), json!(true)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(notes(&app), 1); + // The panel's trash goes the same way: no alert, the note is deleted at once. + ask_delete_note(&mut app, 0); + assert!(alert(&app).is_none()); + assert_eq!((layers(&app), notes(&app)), (2, 0)); +} + +#[test] +fn the_notes_panel_trash_asks_too() { + let mut app = app(); + ask_delete_note(&mut app, 0); + assert!(alert(&app).is_some()); + assert_eq!(notes(&app), 1, "nothing goes before Yes"); +} + +#[test] +fn without_a_selected_note_delete_keeps_its_usual_route() { + let mut app = app(); + app.ui.analysis.note_selected = None; + press(&mut app, egui::Key::Delete); + assert!(alert(&app).is_none()); + assert_eq!(notes(&app), 1, "the note stays"); + // Another tool with a note still selected: the note isn't asked about. + let mut other = self::app(); + other.ui.tool = Tool::Move; + press(&mut other, egui::Key::Delete); + assert!(alert(&other).is_none()); + assert_eq!(notes(&other), 1); +} diff --git a/crates/ui-egui/src/tools/note_show_on_new_tests.rs b/crates/ui-egui/src/tools/note_show_on_new_tests.rs new file mode 100644 index 0000000000..eb9d876fe8 --- /dev/null +++ b/crates/ui-egui/src/tools/note_show_on_new_tests.rs @@ -0,0 +1,114 @@ +use std::cell::Cell; +use std::rc::Rc; + +use super::{PhotocraftApp, Tool, ToolEvent, json}; +use crate::control::{ControlRequest, Outcome, handle}; + +/// Open a document with the Note tool active and no notes yet. +fn note_tool() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.ui.tool = Tool::Note; + (app, egui::Context::default()) +} + +/// Send a click or drag to the canvas in document coordinates. +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + if [x, y] != [end_x, end_y] { + crate::canvas::tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, egui::Modifiers::NONE); + } + crate::canvas::tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, egui::Modifiers::NONE); +} + +/// A new note reveals both icons, and the menu can hide them again. +#[test] +fn creating_a_note_rechecks_show_notes_and_reveals_both_notes() { + let (mut app, ctx) = note_tool(); + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + app.run("notes.add", json!({"x": 20, "y": 20})).unwrap(); + assert!(!app.ui.view.show.notes && !app.ui.analysis.notes); + assert!(!app.ui.view.shows(app.ui.view.show.notes)); + + app.ui.analysis.note_author = "QA".into(); + app.ui.analysis.note_color = [0.25, 0.5, 1.0]; + gesture(&mut app, [130.0, 70.0], [130.0, 70.0]); + + let notes = &app.session.active().unwrap().doc.notes; + assert_eq!(notes.len(), 2); + assert_eq!(notes[0].position, [20.0, 20.0]); + assert_eq!(notes[1].position, [130.0, 70.0]); + assert_eq!(notes[1].author, "QA"); + assert_eq!(notes[1].color.to_rgb(), [0.25, 0.5, 1.0]); + assert_eq!(app.ui.analysis.note_selected, Some(1)); + assert!(app.ui.analysis.notes && app.ui.view.shows(app.ui.view.show.notes)); + + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + assert!(!app.ui.view.shows(app.ui.view.show.notes)); +} + +/// Selecting or moving a stored note keeps Show Notes off. +#[test] +fn selecting_and_dragging_an_existing_note_preserve_hidden_notes() { + let (mut app, ctx) = note_tool(); + app.run("notes.add", json!({"x": 30, "y": 40, "author": "QA"})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + + gesture(&mut app, [32.0, 42.0], [32.0, 42.0]); + assert!(!app.ui.view.show.notes); + assert_eq!(app.ui.analysis.note_selected, Some(0)); + assert_eq!(app.ui.analysis.note_author, "QA"); + + gesture(&mut app, [32.0, 42.0], [62.0, 52.0]); + assert!(!app.ui.view.show.notes); + let notes = &app.session.active().unwrap().doc.notes; + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].position, [60.0, 50.0]); +} + +/// Creating a note rechecks Show Notes while Extras still suppresses the overlay. +#[test] +fn creating_a_note_leaves_extras_off() { + let (mut app, ctx) = note_tool(); + crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(!app.ui.view.show.notes && !app.ui.view.extras); + + gesture(&mut app, [130.0, 70.0], [130.0, 70.0]); + + assert_eq!(app.session.active().unwrap().doc.notes.len(), 1); + assert!(app.ui.view.show.notes); + assert!(!app.ui.view.extras && !app.ui.view.shows(app.ui.view.show.notes)); +} + +/// A denied canvas creation preserves the selected note and visibility settings. +#[test] +fn rejected_note_creation_does_not_change_visibility_or_selection() { + let (mut app, ctx) = note_tool(); + app.run("notes.add", json!({"x": 20, "y": 20})).unwrap(); + app.run("notes.add", json!({"x": 70, "y": 20})).unwrap(); + gesture(&mut app, [72.0, 22.0], [72.0, 22.0]); + assert_eq!(app.ui.analysis.note_selected, Some(1)); + app.ui.view.show.notes = false; + app.ui.analysis.notes = false; + app.ui.view.extras = false; + + let denials = Rc::new(Cell::new(0)); + let observed_denials = Rc::clone(&denials); + app.services.automation_command = Some(Box::new(move |id, _| { + if id == "notes.add" { + observed_denials.set(observed_denials.get() + 1); + return Err("note creation denied".into()); + } + Ok(()) + })); + app.automation_input = true; + let (request, _reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 130, "y": 70}, {"kind": "up", "x": 130, "y": 70}]})); + let Outcome::Done(reply) = handle(&mut app, &ctx, &request) else { panic!("ui.pointer should reply immediately") }; + + assert_eq!(reply["ok"], true); + assert_eq!(denials.get(), 1); + assert!(!app.ui.view.show.notes && !app.ui.analysis.notes && !app.ui.view.extras); + assert_eq!(app.ui.analysis.note_selected, Some(1)); + assert_eq!(app.session.active().unwrap().doc.notes.len(), 2); +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 26550c57a1..540cf5879a 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -313,6 +313,30 @@ pub fn patch_drags_selection(app: &PhotocraftApp, at: [f64; 2], mods: egui::Modi sel.sample_channel(at[0].floor() as i32, at[1].floor() as i32, 0) > 0.0 } +/// A Patch or Content-Aware Move lasso that makes a new selection is being drawn: the selection it +/// replaces is hidden from the press on, as in Photoshop, rather than shown beside the new outline +/// until the release (#11024). Adding, subtracting and intersecting keep it visible. A drag pressed +/// on another document hides nothing, even before `cancel_stale` drops it (the active document can +/// change between `sync_views` and the canvas paint). +pub fn patch_replaces_selection(app: &PhotocraftApp) -> bool { + app.drag.as_ref().is_some_and(|d| { + matches!(d.tool, Tool::Patch | Tool::ContentAwareMove) + && d.document.as_ref().is_none_or(|doc| doc.is_active(app)) + && !patch_drags_selection(app, d.start, d.modifiers) + && crate::canvas::selection_mode(app, d.modifiers) == "replace" + }) +} + +/// A Patch or Content-Aware Move drag belongs to the document it was pressed on: once another one +/// is active it is dropped, so it neither hides that document's selection nor lassos or patches it +/// on release, and its own document shows its selection again (#11024). A document reopened with +/// the same ID is another one too. +pub fn cancel_stale(app: &mut PhotocraftApp) { + if app.drag.as_ref().is_some_and(|d| matches!(d.tool, Tool::Patch | Tool::ContentAwareMove) && d.document.as_ref().is_some_and(|doc| !doc.is_active(app))) { + app.drag = None; + } +} + /// Whole-pixel offset for a drag from `start` to `end`, limited so the dragged outline stays on the /// canvas (the engine rejects a patch or move that leaves it). pub fn patch_offset(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) -> [i32; 2] { @@ -542,8 +566,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } } Tool::Patch => { - // Photoshop's options bar: Patch: Normal (Source / Destination) or Content-Aware - // (Structure, Color, Sample All Layers). + // Photoshop's options bar: the lasso's selection mode, then Patch: Normal (Source / + // Destination) or Content-Aware (Structure, Color, Sample All Layers). + crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui); + crate::widgets::vline(ui, 22.0); opt(ui, tl!("Patch:")); let kinds = [("normal".to_string(), tl!("Normal")), ("contentAware".to_string(), tl!("Content-Aware"))]; let mut kind = if o.patch_content_aware { "contentAware" } else { "normal" }.to_string(); @@ -567,6 +593,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo opt(ui, tl!("Lasso around an area, then drag the selection")); } Tool::ContentAwareMove => { + // The lasso's selection mode leads, as on the Patch tool's bar (#11024). + crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui); + crate::widgets::vline(ui, 22.0); opt(ui, tl!("Mode:")); let modes = [("move".to_string(), tl!("Move")), ("extend".to_string(), tl!("Extend"))]; crate::widgets::dropdown(ui, "cam-mode", tl!("Mode"), &mut o.cam_mode, &modes, 90.0); diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index 4a084bc80a..375f8a410a 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -377,6 +377,221 @@ fn patch_tool_lassoes_then_drags_the_patch() { assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish patched with the white background: {px:?}"); } +/// #11024: a new Patch (or Content-Aware Move) lasso hides the selection it replaces from the +/// press on, and the release leaves only the new area selected. ⇧ keeps the old one and adds. +#[test] +fn a_new_patch_lasso_hides_and_replaces_the_old_selection() { + let lasso = |app: &mut PhotocraftApp, x0: f64, m: egui::Modifiers, release: bool| { + tool_event(app, ToolEvent::Down { x: x0, y: 20.0, pressure: 1.0 }, m); + for [x, y] in [[x0 + 16.0, 20.0], [x0 + 16.0, 40.0], [x0, 40.0]] { + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + if release { + tool_event(app, ToolEvent::Up { x: x0, y: 40.0 }, m); + } + }; + let selected = |app: &PhotocraftApp, x: i32| app.session.active().unwrap().doc.selection.as_ref().is_some_and(|s| s.sample_channel(x, 30, 0) > 0.0); + for tool in [Tool::Patch, Tool::ContentAwareMove] { + let mut app = app(); + app.ui.tool = tool; + lasso(&mut app, 10.0, egui::Modifiers::NONE, true); + assert!(selected(&app, 18), "{tool:?}: the first lasso made a selection"); + assert!(!patch_replaces_selection(&app), "{tool:?}: nothing is being drawn"); + + lasso(&mut app, 60.0, egui::Modifiers::NONE, false); + assert!(patch_replaces_selection(&app), "{tool:?}: the old outline is hidden while the new one is drawn"); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, egui::Modifiers::NONE); + assert!(!patch_replaces_selection(&app), "{tool:?}: the new selection shows after the release"); + assert!(selected(&app, 68) && !selected(&app, 18), "{tool:?}: the new area replaced the old one"); + + lasso(&mut app, 10.0, egui::Modifiers::SHIFT, false); + assert!(!patch_replaces_selection(&app), "{tool:?}: ⇧ adds, so the old outline stays"); + tool_event(&mut app, ToolEvent::Up { x: 10.0, y: 40.0 }, egui::Modifiers::SHIFT); + assert!(selected(&app, 68) && selected(&app, 18), "{tool:?}: ⇧ added to the selection"); + } +} + +/// The screen boxes of the marching ants painted in one canvas frame (meshes of black and white). +fn painted_ants(app: &mut PhotocraftApp) -> Vec { + painted_ants_of(app, 0) +} + +/// [`painted_ants`] for the document at `idx`. +fn painted_ants_of(app: &mut PhotocraftApp, idx: usize) -> Vec { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0)); + let view = crate::state::View { zoom: 2.0, center: [50.0, 30.0], doc_size: [100, 60], fit_pending: false, ..Default::default() }; + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { + crate::canvas::canvas_view(app, ui, idx, rect, view.clone(), true); + }); + output.textures_delta.clear(); + let black_and_white = + |m: &egui::Mesh| m.vertices.iter().any(|v| v.color == egui::Color32::BLACK) && m.vertices.iter().any(|v| v.color == egui::Color32::WHITE); + output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Mesh(m) if black_and_white(m) => Some(egui::Rect::from_points(&m.vertices.iter().map(|v| v.pos).collect::>())), + _ => None, + }) + .collect() +} + +/// #11024 on the canvas: while a new Patch lasso is drawn, no ants are painted where the selection +/// it replaces is, only along the lasso; a ⇧ lasso, which adds, keeps them. +#[test] +fn a_new_patch_lasso_paints_no_ants_on_the_old_selection() { + for tool in [Tool::Patch, Tool::ContentAwareMove] { + for (m, kept) in [(egui::Modifiers::NONE, false), (egui::Modifiers::SHIFT, true)] { + let mut app = app(); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 16, "height": 20})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + let old = painted_ants(&mut app).into_iter().reduce(|a, b| a.union(b)).expect("the selection has its ants"); + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, m); + for [x, y] in [[76.0, 20.0], [76.0, 40.0], [60.0, 40.0]] { + tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + let ants = painted_ants(&mut app); + assert!(ants.iter().any(|a| !a.intersects(old)), "{tool:?} {m:?}: the lasso being drawn has its ants: {ants:?}"); + assert_eq!(ants.iter().any(|a| a.intersects(old)), kept, "{tool:?} {m:?}: ants on the old selection at {old:?}: {ants:?}"); + } + } +} + +/// The ⌥ badge asks every frame whether anything is selected: the canvas caches the selection's +/// bounds even while its ants are hidden (Selection Edges off, a new Patch lasso), so that is +/// never a scan per frame (#11024). +#[test] +fn hidden_ants_still_cache_the_selection_bounds() { + let cached = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + let fingerprint = crate::surface_fingerprint(st.doc.selection.as_ref().unwrap()); + app.bounds_cache.get(&(u64::MAX - st.doc.id.0)).is_some_and(|(f, b)| *f == fingerprint && !b.is_empty()) + }; + let mut app = app(); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 16, "height": 20})).unwrap(); + app.sync_views(); + app.ui.view.show.selection_edges = false; + assert!(painted_ants(&mut app).is_empty(), "Selection Edges off"); + assert!(cached(&app), "cached with Selection Edges off"); + + app.ui.view.show.selection_edges = true; + app.ui.tool = Tool::Patch; + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 76.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + app.bounds_cache.clear(); + painted_ants(&mut app); + assert!(patch_replaces_selection(&app) && cached(&app), "cached while a new Patch lasso hides the ants"); +} + +/// A Patch or Content-Aware Move drag belongs to the document it was pressed on: switching to +/// another drops it, so it doesn't hide that document's ants or land on it (#11024). +#[test] +fn a_patch_drag_is_dropped_when_another_document_is_active() { + for tool in [Tool::Patch, Tool::ContentAwareMove] { + let mut app = app(); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 16, "height": 20})).unwrap(); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 76.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + app.sync_views(); + assert!(patch_replaces_selection(&app), "{tool:?}: the drag is still on its own document"); + + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + app.run("select.rect", json!({"x": 50, "y": 10, "width": 30, "height": 30})).unwrap(); + app.sync_views(); + assert!(app.drag.is_none() && !patch_replaces_selection(&app), "{tool:?}: dropped on the switch"); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, egui::Modifiers::NONE); + let sel = app.session.active().unwrap().doc.selection.clone().unwrap(); + assert_eq!(sel.content_bounds(), photocraft_geom::Rect::new(50, 10, 80, 40), "{tool:?}: the other document's selection is untouched"); + } +} + +/// The active document can change after `sync_views` (a control request, a menu command) and +/// before the canvas paints: a Patch drag pressed on the old one must not hide the new one's ants +/// for that frame (#11024 review). +#[test] +fn a_patch_drag_on_another_document_hides_no_ants_before_it_is_dropped() { + for tool in [Tool::Patch, Tool::ContentAwareMove] { + let mut app = app(); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 16, "height": 20})).unwrap(); + // The other document's selection is clear of the press, so the drag would lasso it. + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap(); + let other = app.session.active_index().unwrap(); + assert!(app.session.set_active(0)); + app.sync_views(); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 76.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + app.sync_views(); + + assert!(app.session.set_active(other)); + assert!(app.drag.is_some(), "{tool:?}: not dropped yet; sync_views has not run"); + assert!(!patch_replaces_selection(&app), "{tool:?}: the drag belongs to the other document"); + assert!(!painted_ants_of(&mut app, other).is_empty(), "{tool:?}: the newly active document shows its ants"); + } +} + +/// A document closed and reopened with the same ID mid-drag is another document, whether it comes +/// back at the same revision or is edited past it: the drag is dropped and its release neither +/// lassos nor patches the reopened one. An ordinary edit keeps the drag (#11024 review). +#[test] +fn a_patch_drag_is_dropped_when_its_document_is_reopened_with_the_same_id() { + for tool in [Tool::Patch, Tool::ContentAwareMove] { + // (reopened, revisions the reopened document is edited past the pressed one) + for (reopen, edits) in [(false, 0), (true, 0), (true, 1)] { + let mut app = app(); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 16, "height": 20})).unwrap(); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 76.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + if reopen { + let closed = app.session.close(0).unwrap(); + app.session.add_document((*closed.doc).clone(), None); + app.session.active_mut().unwrap().revision = closed.revision + edits; + assert_eq!(app.session.active().unwrap().doc.id, closed.doc.id, "a reopened document may keep its ID"); + } else { + app.run("layer.new.layer", json!({})).unwrap(); + } + app.sync_views(); + assert_eq!(app.drag.is_some(), !reopen, "{tool:?}: reopened {reopen}, edited {edits}"); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, egui::Modifiers::NONE); + let sel = app.session.active().unwrap().doc.selection.clone().unwrap(); + let lassoed = sel.content_bounds() != photocraft_geom::Rect::new(10, 20, 26, 40); + assert_eq!(lassoed, !reopen, "{tool:?}: reopened {reopen}, edited {edits}: {:?}", sel.content_bounds()); + } + } +} + +/// #11024: the Patch and Content-Aware Move cursors show + with ⇧ and − with ⌥, like the Lasso's, +/// but nothing over the selection without them, where a press drags the patch. +#[test] +fn patch_cursor_shows_the_selection_mode_badge() { + use crate::tool_feedback::{Badge, badge}; + let (none, shift, alt) = (egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::ALT); + for tool in [Tool::Patch, Tool::ContentAwareMove] { + let mut app = app(); + app.ui.tool = tool; + app.hover_doc = Some([80.0, 30.0]); + assert_eq!(badge(&app, tool, shift), Some(Badge::Add), "{tool:?}"); + assert_eq!(badge(&app, tool, alt), None, "{tool:?}: nothing selected, so ⌥ has nothing to subtract"); + assert_eq!(badge(&app, tool, none), None, "{tool:?}: a new selection has no badge"); + + app.run("select.rect", json!({"x": 10, "y": 20, "width": 20, "height": 20})).unwrap(); + assert_eq!(badge(&app, tool, shift), Some(Badge::Add), "{tool:?}"); + assert_eq!(badge(&app, tool, alt), Some(Badge::Subtract), "{tool:?}"); + assert_eq!(badge(&app, tool, egui::Modifiers::SHIFT | egui::Modifiers::ALT), Some(Badge::Intersect), "{tool:?}"); + app.ui.selection_mode = 1; + assert_eq!(badge(&app, tool, none), Some(Badge::Add), "{tool:?}: the options-bar mode outside the selection"); + app.hover_doc = Some([20.0, 30.0]); + assert_eq!(badge(&app, tool, none), None, "{tool:?}: a press over the selection drags the patch"); + assert_eq!(badge(&app, tool, shift), Some(Badge::Add), "{tool:?}: ⇧ over the selection adds"); + } +} + #[test] fn patch_tool_content_aware_fills_from_where_it_is_dropped() { let mut app = app(); diff --git a/crates/ui-egui/src/tools/shape_bounds_box.rs b/crates/ui-egui/src/tools/shape_bounds_box.rs index 4814e11e2d..ee137bc541 100644 --- a/crates/ui-egui/src/tools/shape_bounds_box.rs +++ b/crates/ui-egui/src/tools/shape_bounds_box.rs @@ -5,8 +5,8 @@ //! handle with one `edit.transform` (which keeps live shapes live), as one History step named //! "Transform Path". No Free Transform session opens, and there is no rotate zone. A corner //! scales both ways, the pointer projected onto the box diagonal as Free Transform's corner does -//! (#11096); an edge middle scales one way. The corner radius widgets (`corner_radius`) keep -//! priority on a press. +//! (#11096); an edge scales one way, grabbed at its middle handle or anywhere along its line +//! (#11473). The corner radius widgets (`corner_radius`) keep priority on a press. use egui::{Color32, CursorIcon, Modifiers, Pos2, Stroke, vec2}; use photocraft_doc::LayerContent; @@ -23,6 +23,18 @@ const MIN_SCALE: f64 = 0.01; const MAX_SCALE: f64 = 100.0; /// A handle is grabbed within this many screen points. const GRAB_PX: f64 = 7.0; +/// Away from the handles, a side is grabbed anywhere along its line and up to this many screen +/// points outside it (#11473). Inside the box only the line itself counts: a press just inside +/// still selects or draws, as the tool does there. The band stays narrower than a handle: unlike +/// Free Transform's box, which rotates everywhere outside, this box leaves the outside to the tool +/// (select or move another shape, draw a new one, start a marquee). +const EDGE_PX: f64 = 5.0; +/// How far inside the box a point still counts as on its line, in screen points: rounding of the +/// pointer through the view, not a grab area. +const LINE_PX: f64 = 1e-3; +/// Path Selection's pick tolerance on a press, in screen points (`tool_input`, `path_ops`): a +/// shape's outline within it is that shape's, so a stroke-only neighbour keeps its press too. +const PICK_PX: f64 = 6.0; /// A handle drag in progress. #[derive(Clone, Debug, PartialEq)] @@ -130,14 +142,48 @@ fn zoom(app: &PhotocraftApp) -> f64 { f64::from(app.point_zoom().max(0.01)) } -/// The handle within grabbing distance of document point `p`, the nearest. +/// The handle within grabbing distance of document point `p`, the nearest; else the side whose +/// line it is on or just outside, as that side's middle handle, unless an unselected shape is +/// there. The handles come first, so a corner keeps its press where the sides' bands meet it. fn hit(app: &PhotocraftApp, p: [f64; 2]) -> Option<[i8; 2]> { if !shows(app) { return None; } - let (_, r) = selection(app)?; - let tol = GRAB_PX / zoom(app); - handles(r).into_iter().map(|(h, at)| (h, (at[0] - p[0]).hypot(at[1] - p[1]))).filter(|(_, d)| *d <= tol).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(h, _)| h) + let (layers, r) = selection(app)?; + let zoom = zoom(app); + let tol = GRAB_PX / zoom; + handles(r) + .into_iter() + .map(|(h, at)| (h, (at[0] - p[0]).hypot(at[1] - p[1]))) + .filter(|(_, d)| *d <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(h, _)| h) + .or_else(|| edge_hit(r, p, EDGE_PX / zoom, LINE_PX / zoom).filter(|_| !on_other_shape(app, &layers, p, PICK_PX / zoom))) +} + +/// Whether the topmost shape at document point `p` is one the box doesn't hold, picked as Path +/// Selection picks: a press on a neighbouring shape in a side's band selects or draws there, as +/// the tool does, instead of scaling the selection. +fn on_other_shape(app: &PhotocraftApp, layers: &[u64], p: [f64; 2], tol: f64) -> bool { + app.session.active().and_then(|st| crate::vector_ui::pick_shape_at(&st.doc, p, tol)).is_some_and(|id| !layers.contains(&id.0)) +} + +/// The side of the box `r` nearest document point `p`, within `band` outside the box or within +/// `line` inside it: `[-1, 0]` left, `[1, 0]` right, `[0, -1]` top, `[0, 1]` bottom. +pub(crate) fn edge_hit(r: [f64; 4], p: [f64; 2], band: f64, line: f64) -> Option<[i8; 2]> { + let [x0, y0, x1, y1] = r; + let [x, y] = p; + // `f64::max` drops a NaN, so `beyond` would put a NaN point on a side's span. + if !(x.is_finite() && y.is_finite()) { + return None; + } + let inside = x > x0 && x < x1 && y > y0 && y < y1; + let reach = if inside { line } else { band }; + // How far `v` lies beyond the span `lo..=hi`: a side is a segment, not a whole line. + let beyond = |v: f64, lo: f64, hi: f64| (lo - v).max(v - hi).max(0.0); + let (past_x, past_y) = (beyond(x, x0, x1), beyond(y, y0, y1)); + let sides = [([-1, 0], (x - x0).hypot(past_y)), ([1, 0], (x - x1).hypot(past_y)), ([0, -1], (y - y0).hypot(past_x)), ([0, 1], (y - y1).hypot(past_x))]; + sides.into_iter().filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(h, _)| h) } /// The scale cursor over a handle at document point `p`, or while one is dragged, turned with the diff --git a/crates/ui-egui/src/tools/shape_gradient_ui.rs b/crates/ui-egui/src/tools/shape_gradient_ui.rs index e2fbfdb679..6b9ed453e2 100644 --- a/crates/ui-egui/src/tools/shape_gradient_ui.rs +++ b/crates/ui-egui/src/tools/shape_gradient_ui.rs @@ -348,7 +348,7 @@ fn stops_strip(ui: &mut egui::Ui, fill: &Fill, id: egui::Id, fg: [f32; 4], bg: [ let pos = resp.interact_pointer_pos(); if let Some(pos) = pos { // Dragged well off the strip, a stop is deleted (while at least two remain), as in Photoshop. - let off = pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0; + let off = crate::gradient_ui::off_strip(pos, bar); let loc = loc_of(pos.x); let edit = match drag.marker { Marker::Color(i) if off && start_cs.len() > 2 => json!({"action": "delete", "index": i}), diff --git a/crates/ui-egui/src/tools/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs index f56e330f0a..3be02a6d81 100644 --- a/crates/ui-egui/src/tools/slice_ui.rs +++ b/crates/ui-egui/src/tools/slice_ui.rs @@ -229,6 +229,11 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) - true } +/// The slice colour from Preferences › Guides, Grid & Slices. +pub fn slice_color(app: &PhotocraftApp) -> Color32 { + hex(&app.session.prefs().guides_grid_and_slices.slice_color, Color32::from_rgb(0x38, 0xb5, 0xff)) +} + fn hex(s: &str, fallback: Color32) -> Color32 { let s = s.trim_start_matches('#'); let b = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); @@ -246,7 +251,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform return; } let prefs = &app.session.prefs().guides_grid_and_slices; - let color = hex(&prefs.slice_color, Color32::from_rgb(0x38, 0xb5, 0xff)); + let color = slice_color(app); let numbers = prefs.show_slice_numbers; let selected_color = Color32::from_rgb(0xff, 0xb0, 0x00); let to_screen = |r: photocraft_geom::Rect| Rect::from_two_pos(xf.to_screen(r.x0 as f32, r.y0 as f32), xf.to_screen(r.x1 as f32, r.y1 as f32)); diff --git a/crates/ui-egui/src/tools/symmetry_ui.rs b/crates/ui-egui/src/tools/symmetry_ui.rs index 95e6b61c61..53413abb72 100644 --- a/crates/ui-egui/src/tools/symmetry_ui.rs +++ b/crates/ui-egui/src/tools/symmetry_ui.rs @@ -167,7 +167,10 @@ fn mode_button(ui: &mut egui::Ui, mode: SymmetryMode, checked: bool) -> egui::Re } pub fn menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let current = app.session.active().and_then(|s| s.symmetry.clone()); - let resp = icons::button_with_icon_size(ui, "painting-symmetry", 24.0, 14.0, current.is_some(), tl!("Set painting symmetry options")); + // The Brush has its own text (#11813); the name stays for screen readers and the other tools. + let brush = app.ui.tool == crate::state::Tool::Brush; + let resp = icons::button_with_icon_size_tip(ui, "painting-symmetry", 24.0, 14.0, current.is_some(), tl!("Set painting symmetry options"), !brush); + let resp = if brush { resp.on_hover_text(tl!("Set symmetry options for Painting")) } else { resp }; let resp = crate::brush_picker::named(resp, "Set painting symmetry options"); egui::Popup::menu(&resp).show(|ui| { ui.set_min_width(220.0); diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index d86af561a5..e1da7b5d2a 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -73,8 +73,12 @@ fn reset_tool(app: &mut PhotocraftApp, tool: Tool) { crate::frame_tool::cancel(app); app.ui.frame_tool = Default::default(); } + if tool == Tool::Artboard { + app.ui.artboard_tool = Default::default(); + } reset_options(&mut app.ui.tool_options, tool); - if is_selection_tool(tool) { + // Patch and Content-Aware Move lasso in the shared selection mode their bars show (#11024). + if is_selection_tool(tool) || matches!(tool, Tool::Patch | Tool::ContentAwareMove) { app.ui.selection_mode = 0; } if crate::paint_mouse::has_brush_picker(tool) { @@ -90,6 +94,7 @@ fn reset_all(app: &mut PhotocraftApp) { crate::frame_tool::cancel(app); app.ui.frame_tool = Default::default(); app.ui.tool_options = ToolOptions::default(); + app.ui.artboard_tool = Default::default(); app.ui.selection_mode = 0; app.ui.tool_brushes.clear(); reset_session_brush(app); @@ -162,7 +167,16 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { }}; } match tool { - Tool::Move => reset!(move_auto_select, move_target, move_show_transform, transform_interpolation, transform_reference_point), + Tool::Move => reset!( + move_auto_select, + move_target, + move_show_transform, + move_show_hover_bounds, + move_expand_group_on_click, + move_show_layers_hover_bounds, + transform_interpolation, + transform_reference_point + ), Tool::RectMarquee | Tool::EllipseMarquee => reset!(feather, anti_alias, marquee_style, marquee_width, marquee_height, marquee_unit), // The single-pixel marquees are never anti-aliased: Feather is their only option. Tool::SingleRowMarquee | Tool::SingleColumnMarquee => reset!(feather), @@ -306,6 +320,20 @@ mod tests { assert!(app.ui.dialogs.is_empty()); } + /// The Patch and Content-Aware Move bars show the shared selection mode, so Reset Tool on + /// either sets it back to New, as on the selection tools (#11024). + #[test] + fn reset_tool_resets_the_patch_selection_mode() { + let ctx = egui::Context::default(); + for tool in [Tool::Patch, Tool::ContentAwareMove] { + let mut app = app(); + app.ui.selection_mode = 2; + app.ui.tool = tool; + crate::menus::invoke(&mut app, &ctx, RESET, json!({})).unwrap(); + assert_eq!(app.ui.selection_mode, 0, "{tool:?}"); + } + } + /// Sample All Layers is per tool (#5524): resetting Blur turns off only Blur's. #[test] fn reset_tool_resets_only_its_own_sample_all_layers() { diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index 16dd8bf8de..bcdd5a0a5f 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -295,7 +295,11 @@ pub fn begin_copy(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), St /// Free Transform on the layer a file dropped on the canvas just placed, like the reference app's /// Place: Esc takes the place back, ↩ makes the place and the transform one Place Embedded step. +/// With Preferences ▸ General ▸ Skip Transform when Placing on, the place stands as it is. pub fn begin_placed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + if app.session.prefs().general.skip_transform_when_placing { + return Ok(()); + } begin(app, ctx)?; if let Some(t) = app.ui.transform.as_mut() { t.made = Some(MadeLayer::Place); diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 5d5507bfd8..3721fdeb2a 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -554,6 +554,23 @@ fn editing_the_contents_of_a_dropped_file_keeps_the_layer() { assert!(app.transform_preview.is_none(), "the transform preview should end"); } +/// #8492: Preferences ▸ General ▸ Skip Transform when Placing (off by default) places a file +/// without opening Free Transform on it, as in the reference app. +#[test] +fn skip_transform_when_placing_leaves_the_place_without_a_box() { + for skip in [false, true] { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": skip})).unwrap(); + app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.session.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + app.sync_views(); + let placed = app.session.active().unwrap().active_layer.unwrap(); + begin_placed(&mut app, &egui::Context::default()).unwrap(); + assert_eq!(app.ui.transform.is_some(), !skip, "skip {skip}: Free Transform opens only with the preference off"); + assert!(app.session.active().unwrap().doc.layer(placed).is_some(), "skip {skip}: the placed layer stays"); + } +} + /// Polls the app's background jobs until they have all landed. fn land_jobs(app: &mut PhotocraftApp) { let ctx = egui::Context::default(); 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 3edef2ad86..2d23f6d3a4 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -289,7 +289,7 @@ pub fn pick_shape_at(doc: &Document, at: [f64; 2], tol: f64) -> Option Option bool { + let Some((x0, y0, x1, y1)) = path.control_bounds() else { return false }; + let pad = tol * 1.001 + 1e-9 * (1.0 + at[0].abs() + at[1].abs()); + // Written so a NaN bound keeps the check (`edit::hit` decides), as an infinite one does. + !(at[0] < x0 - pad || at[0] > x1 + pad || at[1] < y0 - pad || at[1] > y1 + pad) +} + pub fn path_selection_finish(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { let (dx, dy) = (end[0] - start[0], end[1] - start[1]); let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index b162619bba..c9106ea432 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -836,9 +836,7 @@ fn as_owner(app: &mut PhotocraftApp, owner: &PenOwner, f: impl FnOnce(&mut Ph super::PenTarget::Path { name, append } => append.then(|| name.clone()), _ => None, }; - if let Some(st) = app.session.active_mut() { - st.active_layer = owner.layer; - } + app.session.set_active_layer(owner.layer); let foreground = std::mem::replace(&mut app.session.tools.foreground, owner.foreground); let background = std::mem::replace(&mut app.session.tools.background, owner.background); let channel = app.session.active().map(|st| st.channel_view.target); diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index ca0ea37d67..b862d89a74 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -1,7 +1,7 @@ use super::panel::chevron_icon; use super::scrub::take_label_scrub_name; use super::slider::wheel_notches_of; -use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, type_ahead, vec2}; +use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, pos2, type_ahead, vec2}; /// A compact labelled dropdown in the studio style. pub fn dropdown(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { @@ -245,20 +245,100 @@ fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, /// seen (clear of a taskbar a too-tall window runs under, #315), scrolling past that, so long /// context menus (a layer's, the canvas tools') stay reachable on small windows instead of running /// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the -/// screen first shifts up and only scrolls when it is taller than the window. +/// screen first shifts up and only scrolls when it is taller than the window. An overflowing +/// menu's ▲/▼ scroll arrows (#2091) count toward that height, so both stay on screen. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { // The popup frame's margin and stroke, and a small gap to the window's edges. let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT); + // An overflowing menu gets Photoshop's scroll arrows above and below its rows (#2091): the + // thin floating scroll bar alone gave no hint that more items were hidden. Whether it + // overflows is known only after layout, so it is remembered from the last frame. + let id = ui.scope_id().with("menu_scroll"); + let overflow = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + let offset = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + // The arrows are as wide as the rows were last frame, not the popup's whole available width: + // that widened an overflowing menu on every later open (a layer menu went from ~230 to ~600 + // pt). The output's `inner_rect` is the width asked for, before auto-shrink fits the rows. + let width = ui.data(|d| d.get_temp::(id.with("width"))).unwrap_or(0.0); + // The arrows come out of the room, so both stay on screen: the minimum is the whole menu's + // height, arrows included. `room` is at least `MENU_MIN_HEIGHT`, which is taller than the two + // arrows, so the rows always keep a positive height; a window shorter than that minimum still + // gets a menu of that height, as one without arrows does. + let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 }; + let room = (room - arrows).max(MENU_MIN_HEIGHT - arrows); + // The arrows sit flush against the rows, so no item spacing is added around them that `room` + // doesn't count; the rows keep the menu's own spacing. + let spacing = ui.spacing().item_spacing.y; + ui.spacing_mut().item_spacing.y = 0.0; + let mut step = 0.0; + if overflow { + step += menu_scroll_arrow(ui, true, offset > 0.5, width); + } // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for // the whole room: the area still shrinks to its rows when they need less. - egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner + let mut area = egui::ScrollArea::vertical().id_salt(id).max_height(room).min_scrolled_height(room); + // A step is taken on the pass after the arrow was hovered, and only then: a menu closed while + // an arrow was hovered doesn't jump when it next opens. + let now = ui.ctx().cumulative_pass_nr(); + let pending = ui.data(|d| d.get_temp::<(f32, u64)>(id.with("step"))).filter(|&(_, pass)| pass.saturating_add(1) == now).map_or(0.0, |(step, _)| step); + if pending != 0.0 { + area = area.vertical_scroll_offset((offset + pending).max(0.0)); + } + let out = area.show(ui, |ui| { + ui.spacing_mut().item_spacing.y = spacing; + add_contents(ui) + }); + let max = (out.content_size.y - out.inner_rect.height()).max(0.0); + let offset = out.state.clamped_offset().y.clamp(0.0, max); + if overflow { + step += menu_scroll_arrow(ui, false, offset < max - 0.5, width); + } + ui.spacing_mut().item_spacing.y = spacing; + ui.data_mut(|d| { + d.insert_temp(id, max > 0.5); + d.insert_temp(id.with("offset"), offset); + d.insert_temp(id.with("width"), out.content_size.x); + d.insert_temp(id.with("step"), (step, now)); + }); + out.inner } -/// Gap kept between a context menu and the window's edges, and the shortest it gets. -const MENU_EDGE: f32 = 4.0; +/// One scroll arrow of an overflowing menu: hovering scrolls that way, as in Photoshop's and the +/// system menus. It doesn't page on a click: egui closes a context menu on any click inside it, +/// so the page would never be seen. `width` is the rows' width. Returns the scroll step for the +/// next frame. +fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool, width: f32) -> f32 { + let width = if width.is_finite() { width.max(MENU_ARROW_HEIGHT) } else { MENU_ARROW_HEIGHT }; + let (rect, resp) = ui.allocate_exact_size(vec2(width, MENU_ARROW_HEIGHT), Sense::hover()); + let t = Tokens::get(ui.ctx()); + let color = if enabled { t.text } else { t.text_dim.gamma_multiply(0.5) }; + let (c, h) = (rect.center(), 3.5); + let pts = if up { + vec![pos2(c.x - h * 1.4, c.y + h * 0.6), pos2(c.x + h * 1.4, c.y + h * 0.6), pos2(c.x, c.y - h * 0.8)] + } else { + vec![pos2(c.x - h * 1.4, c.y - h * 0.6), pos2(c.x + h * 1.4, c.y - h * 0.6), pos2(c.x, c.y + h * 0.8)] + }; + ui.painter().add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); + if !enabled { + return 0.0; + } + if !resp.hovered() { + return 0.0; + } + ui.ctx().request_repaint(); + let sign = if up { -1.0 } else { 1.0 }; + sign * MENU_ARROW_SPEED * ui.input(|i| i.stable_dt).clamp(0.0, 0.1) +} -const MENU_MIN_HEIGHT: f32 = 120.0; +/// Gap kept between a context menu and the window's edges. +const MENU_EDGE: f32 = 4.0; +/// The shortest a context menu gets, scroll arrows included. +pub(super) const MENU_MIN_HEIGHT: f32 = 120.0; +/// Height of an overflowing menu's scroll arrows, and how fast hovering one scrolls (points per +/// second). +pub(super) const MENU_ARROW_HEIGHT: f32 = 14.0; +const MENU_ARROW_SPEED: f32 = 400.0; /// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside /// closes it. While open, its left edge stays where it first showed (at the swatch, or further diff --git a/crates/ui-egui/src/widgets/field_wheel.rs b/crates/ui-egui/src/widgets/field_wheel.rs index f4d0ac80d2..4d2f7ada59 100644 --- a/crates/ui-egui/src/widgets/field_wheel.rs +++ b/crates/ui-egui/src/widgets/field_wheel.rs @@ -11,7 +11,7 @@ use egui::{Context, Event, Id, MouseWheelUnit, Rect, Ui, Vec2}; /// Wheel events this close together (seconds) are one gesture. -const GESTURE_GAP: f64 = 0.3; +pub(crate) const GESTURE_GAP: f64 = 0.3; /// Who a wheel gesture belongs to. #[derive(Clone, Copy, Debug, PartialEq)] @@ -93,6 +93,14 @@ pub fn begin_frame(ctx: &Context) { ctx.data_mut(|d| d.insert_temp(gesture_id(), Gesture { last: now, owner })); } +/// Whether a wheel gesture stepping a value field is still running: its last notch came less than +/// [`GESTURE_GAP`] ago. A field that applies each value as a new edit holds the wheeled value until +/// this turns false, so a burst of notches is one edit (#9898). +pub fn field_gesture_running(ctx: &Context) -> bool { + let now = ctx.input(|i| i.time); + ctx.data(|d| d.get_temp::(gesture_id())).is_some_and(|g| matches!(g.owner, Owner::Field(_)) && now - g.last <= GESTURE_GAP) +} + /// Record that value field `id` (whose slot is `field`, as given to [`notches`]) has keyboard /// focus this frame, so the wheel is its next frame. pub fn set_focused(ctx: &Context, id: Id, field: Id) { diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index 9dd705f638..e85cb758a6 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -262,6 +262,41 @@ fn text_field_is_a_boxed_input_whose_selection_colour_stays_local() { assert_eq!(h.state().0, "abc", "typing reaches the bound string"); } +/// #2084: a plain text field's text is centred in its box, like a value field's digits, in the +/// monospaced (hex) and proportional faces alike: neither low nor overshooting the middle. +#[test] +fn text_field_text_ink_is_centred_in_its_box() { + let _gpu = photocraft_testkit::gpu_lock(); + let scale = 4.0; + for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::Studio] { + // Digits and capitals: no descenders, so their ink should straddle the box's middle. + for (text, mono) in [("A0F3C2", true), ("100", true), ("HEX", false)] { + let mut h = Harness::builder().with_size(egui::vec2(160.0, 40.0)).with_pixels_per_point(scale).wgpu().build_ui_state( + move |ui, s: &mut (String, egui::Rect)| { + let before = ui.cursor().min; + super::text_field(ui, egui::Id::unique("tf"), &mut s.0, "", 140.0, mono).accessible_name("Value"); + s.1 = egui::Rect::from_min_size(before, egui::vec2(140.0, super::TEXT_FIELD_H)); + }, + (text.to_owned(), egui::Rect::NOTHING), + ); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let image = h.render().expect("render text field"); + let field = h.state().1; + let px = |v: f32| (v * scale) as u32; + let bg = image.get_pixel(px(field.right() - 3.0), px(field.center().y)).0; + let lum = |p: [u8; 4]| u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); + let rows: Vec = (px(field.top() + 2.0)..px(field.bottom() - 2.0)) + .filter(|&y| (px(field.left() + 3.0)..px(field.right() - 6.0)).any(|x| lum(image.get_pixel(x, y).0) > lum(bg) + 150)) + .collect(); + let (top, bottom) = (rows.first().copied().unwrap_or(0) as f32 / scale, (rows.last().copied().unwrap_or(0) + 1) as f32 / scale); + let what = format!("{kind:?} {text:?} mono={mono}: field {field:?}, ink {top}..{bottom}, off {}", (top + bottom) / 2.0 - field.center().y); + assert!(!rows.is_empty(), "{what}"); + assert!(((top + bottom) / 2.0 - field.center().y).abs() <= 0.25, "{what}"); + } + } +} + /// #2150: a huge paste into a plain text field stops at its limit instead of growing the /// string (and its laid-out text) without bound. #[test] @@ -1443,6 +1478,144 @@ fn the_wheel_leaves_a_plain_dropdown_alone() { assert_eq!(*h.state(), 0); } +/// The middle of an overflowing menu's lower scroll arrow, from the menu's laid-out rect. +fn lower_menu_arrow(menu: egui::Rect) -> egui::Pos2 { + let half = super::dropdown::MENU_ARROW_HEIGHT / 2.0; + egui::pos2(menu.left() + half, menu.bottom() - half) +} + +/// #2091: a menu taller than the window shows scroll arrows; hovering the lower one scrolls +/// it, and a short menu gets none. +#[test] +fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() { + // (rows, overflowing, scroll offset, the menu's rect) + type S = (usize, bool, f32, egui::Rect); + let run = |rows: usize| { + let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( + |ui, s: &mut S| { + let id = ui.scope_id().with("menu_scroll"); + super::menu_scroll(ui, |ui| { + for i in 0..s.0 { + ui.label(format!("Item {i}")); + } + }); + s.1 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + s.2 = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + s.3 = ui.min_rect(); + }, + (rows, false, 0.0, egui::Rect::NOTHING), + ); + h.run_steps(3); + h + }; + let short = run(3); + assert!(!short.state().1, "a short menu has no arrows"); + let mut long = run(80); + assert!(long.state().1, "a long menu overflows"); + assert_eq!(long.state().2, 0.0); + let below = lower_menu_arrow(long.state().3); + long.event(egui::Event::PointerMoved(below)); + long.run_steps(10); + assert!(long.state().2 > 0.0, "hovering the lower arrow scrolls down"); +} + +/// #2091: the step a hovered arrow leaves for the next frame isn't taken when a menu closed +/// while hovering it opens again. +#[test] +fn a_reopened_menu_takes_no_stale_scroll_step() { + // (shown, scroll offset, the menu's rect) + type S = (bool, f32, egui::Rect); + let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state( + |ui, s: &mut S| { + let id = ui.scope_id().with("menu_scroll"); + if s.0 { + super::menu_scroll(ui, |ui| { + for i in 0..80 { + ui.label(format!("Item {i}")); + } + }); + s.2 = ui.min_rect(); + } + s.1 = ui.data(|d| d.get_temp::(id.with("offset"))).unwrap_or(0.0); + }, + (true, 0.0, egui::Rect::NOTHING), + ); + h.run_steps(3); + h.event(egui::Event::PointerMoved(lower_menu_arrow(h.state().2))); + h.run_steps(3); + let offset = h.state().1; + assert!(offset > 0.0, "hovering the lower arrow scrolls down"); + h.state_mut().0 = false; + h.run(); + h.state_mut().0 = true; + h.event(egui::Event::PointerGone); + h.run(); + assert_eq!(h.state().1, offset, "the reopened menu stays where it was left"); +} + +/// #2091: an overflowing menu's scroll arrows are as wide as its rows, so they don't widen the +/// menu to the whole width it is offered. +#[test] +fn menu_scroll_arrows_do_not_widen_the_menu() { + // (overflowing, width of the menu) + type S = (bool, f32); + let mut h = Harness::builder().with_size(egui::vec2(600.0, 300.0)).build_ui_state( + |ui, s: &mut S| { + let id = ui.scope_id().with("menu_scroll"); + super::menu_scroll(ui, |ui| { + for i in 0..80 { + ui.label(format!("Item {i}")); + } + }); + s.0 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + s.1 = ui.min_rect().width(); + }, + (false, 0.0), + ); + h.run_steps(4); + assert!(h.state().0, "the menu overflows"); + assert!(h.state().1 < 200.0, "the arrows follow the rows' width, not the 600 pt window: {}", h.state().1); +} + +/// #2091: in a short window, between the shortest menu and that plus its arrows, an overflowing +/// menu's arrows come out of the room rather than being added under it, so the lower arrow stays +/// on screen. A window shorter than a menu's minimum gets a menu of the minimum height, arrows +/// included. +#[test] +fn menu_scroll_arrows_stay_inside_a_short_window() { + // (overflowing, the menu's rect) + type S = (bool, egui::Rect); + let run = |height: f32| { + let mut h = Harness::builder().with_size(egui::vec2(220.0, height)).build_ui_state( + |ui, s: &mut S| { + let id = ui.scope_id().with("menu_scroll"); + super::menu_scroll(ui, |ui| { + for i in 0..80 { + ui.label(format!("Item {i}")); + } + }); + s.0 = ui.data(|d| d.get_temp::(id)).unwrap_or(false); + s.1 = ui.min_rect(); + }, + (false, egui::Rect::NOTHING), + ); + h.run_steps(4); + let screen = h.ctx.content_rect(); + (h.state().0, h.state().1, screen) + }; + // The room is 150 - 22 (the popup frame and edge gaps) = 128 pt: more than the shortest menu, + // less than it plus both 14 pt arrows. + let (overflow, menu, screen) = run(150.0); + assert!(overflow, "the menu overflows and shows its arrows"); + assert!(menu.top() >= screen.top(), "the upper arrow is on screen: {menu:?} in {screen:?}"); + assert!(menu.bottom() <= screen.bottom(), "the lower arrow is on screen: {menu:?} in {screen:?}"); + assert!(menu.height() <= 128.5, "the menu, arrows included, fits the room: {}", menu.height()); + let (overflow, menu, _) = run(60.0); + assert!(overflow, "a tiny window's menu overflows too"); + let min = super::dropdown::MENU_MIN_HEIGHT; + assert!((menu.height() - min).abs() < 0.5, "a tiny window's menu is the minimum height, arrows included: {}", menu.height()); +} + /// [`MODES`] in a wheel dropdown whose list draws a line above each option `starts_group` picks, /// opened: the open list's rect and each option's row in it. fn open_grouped_modes(starts_group: fn(&usize) -> bool) -> (egui::Rect, Vec) { diff --git a/crates/ui-egui/tests/it/custom_print_paper.rs b/crates/ui-egui/tests/it/custom_print_paper.rs index d6c66a21e3..327ccf3283 100644 --- a/crates/ui-egui/tests/it/custom_print_paper.rs +++ b/crates/ui-egui/tests/it/custom_print_paper.rs @@ -56,6 +56,16 @@ fn click(h: &mut Harness<'_, PhotocraftApp>, label: &str) { h.run_steps(3); } +/// Chooses an option from the open paper menu. The Japanese presets made the list longer than +/// the dropdown shows, so it scrolls (and reopens where it was left): bring the row into view +/// before clicking it. +fn choose_paper(h: &mut Harness<'_, PhotocraftApp>, label: &str) { + h.get_by_label(label).scroll_to_me(); + h.run_steps(3); + h.get_by_label(label).click(); + h.run_steps(3); +} + fn shown(h: &Harness<'_, PhotocraftApp>, text: &str) -> bool { // A form caption and its control both expose the same accessible name. h.query_all_by_label(text).next().is_some() || h.query_all_by_value(text).next().is_some() @@ -171,10 +181,12 @@ fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() { dialog.fields.insert("output".into(), json!(output.to_string_lossy())); dialog.fields.insert("dryRun".into(), json!(true)); let mut h = harness(app); - click(&mut h, "letter"); - assert!(shown(&h, "a4"), "the real preset menu must be open"); + // The paper control has no label of its own: it shows the chosen preset's display name + // ("Letter", "A4", …), while the dialog stores the engine key ("letter", "a4", …). + click(&mut h, "Letter"); + assert!(shown(&h, "A4"), "the real preset menu must be open"); assert!(shown(&h, "Custom"), "the paper menu must offer editable custom dimensions"); - click(&mut h, "Custom"); + choose_paper(&mut h, "Custom"); assert_eq!(fields(&h, id)["paper"], json!([612.0, 792.0]), "Custom starts at the current preset dimensions"); click(&mut h, "Centimeters"); click(&mut h, "Inches"); @@ -183,11 +195,11 @@ fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() { let edited = fields(&h, id); assert_eq!(edited["paper"], json!([522.0, 666.0]), "the engine takes points, not the displayed units"); click(&mut h, "Custom"); - click(&mut h, "a4"); + choose_paper(&mut h, "A4"); assert_eq!(fields(&h, id)["paper"], "a4"); assert!(!shown(&h, "Paper Width")); - click(&mut h, "a4"); - click(&mut h, "Custom"); + click(&mut h, "A4"); + choose_paper(&mut h, "Custom"); assert_eq!(fields(&h, id)["paper"], edited["paper"], "returning from a preset restores the custom dimensions"); click(&mut h, "Inches"); click(&mut h, "Millimeters"); @@ -216,6 +228,22 @@ fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() { std::fs::remove_file(output).unwrap(); } +/// #8307: the paper menu lists the Japanese papers by their customary names. Choosing はがき +/// from it stores the preset and lays the page out at its exact metric size. +#[test] +fn japanese_postcard_preset_is_chosen_from_the_paper_menu() { + let (app, id) = app(); + let mut h = harness(app); + click(&mut h, "Letter"); + assert!(shown(&h, "はがき (100 × 148 mm)"), "the paper menu must list the Japanese postcard"); + choose_paper(&mut h, "はがき (100 × 148 mm)"); + assert_eq!(fields(&h, id)["paper"], "postcard", "the preset is stored by its engine name"); + assert!(shown(&h, "はがき (100 × 148 mm)"), "the paper control must show the chosen preset"); + assert!(!shown(&h, "Paper Width"), "a preset is not editable custom paper"); + let layout = photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(fields(&h, id)), "file.print").unwrap(); + assert_eq!(layout.paper, (283.46, 419.53), "100 × 148 mm in points"); +} + #[test] fn remembered_custom_paper_is_shown_without_becoming_a_preset() { let (mut app, id) = app(); @@ -227,6 +255,18 @@ fn remembered_custom_paper_is_shown_without_becoming_a_preset() { assert_eq!(fields(&h, id)["paper"], json!([432.0, 576.0])); } +/// #8307: `file.print` remembers the paper name as typed, aliases included. Reopening the dialog +/// must select the canonical preset an alias names instead of leaving the Paper control unmatched. +#[test] +fn remembered_paper_alias_selects_the_canonical_preset() { + let (mut app, id) = app(); + app.ui.dialog_mut(id).unwrap().fields.insert("paper".into(), json!("はがき")); + let h = harness(app); + assert!(shown(&h, "はがき (100 × 148 mm)"), "a remembered alias must show the paper it names"); + let layout = photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(fields(&h, id)), "file.print").unwrap(); + assert_eq!(layout.paper, (283.46, 419.53), "the remembered alias must still print as はがき"); +} + #[test] fn invalid_custom_paper_is_rejected_without_printing_or_changing_the_document() { let (mut app, id) = app(); @@ -234,8 +274,8 @@ fn invalid_custom_paper_is_rejected_without_printing_or_changing_the_document() app.ui.dialog_mut(id).unwrap().fields.insert("output".into(), json!(output.to_string_lossy())); let before = app.session.active().unwrap().doc.clone(); let mut h = harness(app); - click(&mut h, "letter"); - click(&mut h, "Custom"); + click(&mut h, "Letter"); + choose_paper(&mut h, "Custom"); enter_length(&mut h, "Paper Width", "0"); let edited = fields(&h, id); assert!(photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(edited), "file.print").is_err()); diff --git a/crates/ui-egui/tests/it/magnetic_lasso_right_click.rs b/crates/ui-egui/tests/it/magnetic_lasso_right_click.rs new file mode 100644 index 0000000000..7e2079c8a4 --- /dev/null +++ b/crates/ui-egui/tests/it/magnetic_lasso_right_click.rs @@ -0,0 +1,209 @@ +//! Magnetic Lasso: a right-click while a border is being drawn opens no menu (#11689). +//! +//! Measured in Photoshop: with a Magnetic Lasso border in progress, a right-click on the canvas +//! opens nothing and changes nothing; the border stays live, and ↩ still closes it. With no border +//! in progress the right-click opens the selection tools' menu as before. PhotoCraft opened that +//! menu over the live border, from the canvas and from the control channel alike. +//! +//! The border is drawn with ⌥-clicks (straight segments), so its points don't depend on edges. +//! No GPU needed. + +use egui::{Event, Modifiers, PointerButton}; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::canvas::ViewXform; +use photocraft_ui_egui::control::{ControlRequest, Outcome, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The border's corners: a plain click starts it, ⌥-clicks add the others. +const CORNERS: [[f64; 2]; 3] = [[50.0, 50.0], [250.0, 50.0], [150.0, 200.0]]; + +/// Where the right-click goes: inside the border, on the image. +const INSIDE: [f64; 2] = [150.0, 100.0]; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).expect("new document"); + app.sync_views(); + app +} + +fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = egui::Context::default(); + let (req, _rx) = ControlRequest::new(method, params); + let Outcome::Done(v) = handle(app, &ctx, &req) else { panic!("{method} didn't finish") }; + v +} + +fn pointer(app: &mut PhotocraftApp, params: Value) { + let v = call(app, "ui.pointer", params); + assert_eq!(v["ok"], true, "{v}"); +} + +/// Clicks at `p` through `ui.pointer` with the Magnetic Lasso. +fn agent_click(app: &mut PhotocraftApp, p: [f64; 2], button: &str, alt: bool) { + let events = json!([{"kind": "down", "x": p[0], "y": p[1]}, {"kind": "up", "x": p[0], "y": p[1]}]); + pointer(app, json!({"tool": "MagneticLasso", "button": button, "alt": alt, "events": events})); +} + +/// `ui.inspect`'s Magnetic Lasso border and canvas tool menu. +fn inspect(app: &mut PhotocraftApp) -> (Value, Value) { + let v = call(app, "ui.inspect", json!({})); + let r = &v["result"]; + (r["magnetic"].clone(), r["canvasToolMenu"].clone()) +} + +#[test] +fn agent_right_click_while_drawing_opens_no_menu_and_keeps_the_border() { + let mut app = app(); + agent_click(&mut app, CORNERS[0], "left", false); + agent_click(&mut app, CORNERS[1], "left", true); + agent_click(&mut app, CORNERS[2], "left", true); + let (before, menu) = inspect(&mut app); + assert!(menu.is_null(), "no menu yet: {menu}"); + assert_eq!(before["anchors"].as_array().map(Vec::len), Some(3), "a border is in progress: {before}"); + + agent_click(&mut app, INSIDE, "right", false); + let (after, menu) = inspect(&mut app); + assert!(menu.is_null(), "a right-click over a live border opens no menu: {menu}"); + assert_eq!(after["path"], before["path"], "the border is unchanged"); + assert_eq!(after["anchors"], before["anchors"], "its fastening points are unchanged"); + assert!(app.session.active().expect("a document").doc.selection.is_none(), "nothing is selected yet"); + + // The border is still live: closing it selects it. + photocraft_ui_egui::magnetic_lasso_ui::close(&mut app, true); + let sel = app.session.active().expect("a document").doc.selection.as_ref().expect("the border closed into a selection"); + assert!(sel.sample_channel(150, 100, 0) > 0.9, "the inside is selected"); +} + +#[test] +fn agent_right_click_on_another_document_still_opens_the_selection_menu() { + // A border left on the first document doesn't hold the menu back on the second: the agent's + // events run no frame, so nothing has dropped that border yet. + let mut app = app(); + agent_click(&mut app, CORNERS[0], "left", false); + agent_click(&mut app, CORNERS[1], "left", true); + app.run("file.new", json!({"width": 400, "height": 300})).expect("second document"); + app.sync_views(); + assert!(app.ui.magnetic.active(), "the first document's border is still there"); + + agent_click(&mut app, INSIDE, "right", false); + let (_, menu) = inspect(&mut app); + let entries = menu["entries"].as_array().expect("the selection menu opened"); + assert!(entries.iter().any(|e| e["id"] == "select.all"), "{menu}"); +} + +#[test] +fn agent_right_click_during_an_alt_drag_still_opens_the_selection_menu() { + // Not measured in Photoshop: a right-click while an ⌥-drag draws a freehand segment keeps + // today's behaviour, the selection menu. + let mut app = app(); + agent_click(&mut app, CORNERS[0], "left", false); + let events = json!([{"kind": "down", "x": CORNERS[1][0], "y": CORNERS[1][1]}, {"kind": "move", "x": 200.0, "y": 120.0}]); + pointer(&mut app, json!({"tool": "MagneticLasso", "alt": true, "events": events})); + assert!(app.ui.magnetic.freehand, "an ⌥-drag is drawing a freehand segment"); + + agent_click(&mut app, INSIDE, "right", false); + let (_, menu) = inspect(&mut app); + let entries = menu["entries"].as_array().expect("the selection menu opened"); + assert!(entries.iter().any(|e| e["id"] == "select.all"), "{menu}"); +} + +#[test] +fn agent_right_click_without_a_border_still_opens_the_selection_menu() { + let mut app = app(); + agent_click(&mut app, INSIDE, "right", false); + let (magnetic, menu) = inspect(&mut app); + assert_eq!(magnetic["path"], json!([]), "a right-click starts no border"); + let entries = menu["entries"].as_array().expect("the selection menu opened"); + assert!(entries.iter().any(|e| e["id"] == "select.all"), "{menu}"); +} + +/// The app's document area alone, at 100 %, the Magnetic Lasso selected. +fn harness() -> Harness { + let mut app = app(); + app.ui.tool = photocraft_ui_egui::state::Tool::MagneticLasso; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + photocraft_ui_egui::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| photocraft_ui_egui::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (1.0, [200.0, 150.0], false); + h.run_steps(2); + h +} + +/// The screen point of document point `p`. +fn screen(h: &Harness, p: [f64; 2]) -> egui::Pos2 { + let app = h.state(); + let v = &app.ui.views[0]; + let xf = ViewXform { + rect: photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: false, + rotation: v.rotation, + aspect: 1.0, + }; + xf.to_screen(p[0] as f32, p[1] as f32) +} + +/// Moves the pointer to `p`. +fn hover(h: &mut Harness, p: [f64; 2], modifiers: Modifiers) { + let pos = screen(h, p); + h.event(Event::ModifiersChanged(modifiers)); + h.event(Event::PointerMoved(pos)); + h.run_steps(2); +} + +fn mouse_click(h: &mut Harness, p: [f64; 2], button: PointerButton, modifiers: Modifiers) { + hover(h, p, modifiers); + let pos = screen(h, p); + h.event(Event::PointerButton { pos, button, pressed: true, modifiers }); + h.run_steps(1); + h.event(Event::PointerButton { pos, button, pressed: false, modifiers }); + h.run_steps(2); +} + +#[test] +fn canvas_right_click_while_drawing_opens_no_menu_and_enter_still_closes_the_border() { + let mut h = harness(); + mouse_click(&mut h, CORNERS[0], PointerButton::Primary, Modifiers::NONE); + mouse_click(&mut h, CORNERS[1], PointerButton::Primary, Modifiers::ALT); + mouse_click(&mut h, CORNERS[2], PointerButton::Primary, Modifiers::ALT); + // The pointer goes where the right-click will be first: moves with the button up fasten points + // along the way, as they should. + hover(&mut h, INSIDE, Modifiers::NONE); + let before = h.state().ui.magnetic.clone(); + assert!(before.anchors.len() >= 3, "a border is in progress: {before:?}"); + + mouse_click(&mut h, INSIDE, PointerButton::Secondary, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "a right-click over a live border opens no menu"); + let after = &h.state().ui.magnetic; + assert_eq!((&after.path, &after.anchors), (&before.path, &before.anchors), "the border is unchanged"); + + h.event(Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.event(Event::Key { key: egui::Key::Enter, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(!h.state().ui.magnetic.active(), "↩ closed the border"); + let sel = h.state().session.active().expect("a document").doc.selection.as_ref().expect("the border closed into a selection"); + assert!(sel.sample_channel(150, 100, 0) > 0.9, "the inside is selected"); +} + +#[test] +fn canvas_right_click_without_a_border_still_opens_the_selection_menu() { + let mut h = harness(); + mouse_click(&mut h, INSIDE, PointerButton::Secondary, Modifiers::NONE); + assert!(!h.state().ui.magnetic.active(), "a right-click starts no border"); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the selection menu opened"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 77ae4ec3cf..4816d6c1df 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -31,6 +31,7 @@ mod full_res_preview; mod gpu_device_loss; mod layout_perf; mod live_stroke_canvas; +mod magnetic_lasso_right_click; mod marching_ants_pixels; mod marquee_autoscroll; mod paint_bucket_all_layers; diff --git a/crates/ui-egui/tests/magnetic_lasso_width_keys.rs b/crates/ui-egui/tests/magnetic_lasso_width_keys.rs new file mode 100644 index 0000000000..1f1caaceac --- /dev/null +++ b/crates/ui-egui/tests/magnetic_lasso_width_keys.rs @@ -0,0 +1,107 @@ +//! Magnetic Lasso keys: `[` / `]` change the Width by 1 px within 1-256, Shift+`[` jumps to the +//! minimum (1 px) and Shift+`]` to the maximum (256 px), with and without a border being drawn +//! (#11688). The keys go through the real shortcut handler on a bare egui context. + +use egui::{Event, Key, Modifiers, RawInput}; +use photocraft_ui_egui::canvas::{ToolEvent, tool_event}; +use photocraft_ui_egui::{PhotocraftApp, Tool, magnetic_lasso_ui}; +use serde_json::json; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::MagneticLasso; + app +} + +/// A border is started with a click, so it is being drawn while the keys are pressed. +fn start_border(app: &mut PhotocraftApp) { + tool_event(app, ToolEvent::Down { x: 52.0, y: 37.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 52.0, y: 37.0 }, Modifiers::NONE); + assert!(magnetic_lasso_ui::replaces_selection(app), "a border is being drawn"); +} + +/// Presses `key` with `modifiers` for one frame and returns whether the Magnetic Lasso took it. +fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) -> bool { + let ctx = egui::Context::default(); + let mut taken = false; + let events = vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]; + let mut out = ctx.run_ui(RawInput { events, ..Default::default() }, |ui| taken = magnetic_lasso_ui::keys(app, ui.ctx())); + out.textures_delta.clear(); + taken +} + +fn width(app: &PhotocraftApp) -> f32 { + app.ui.tool_options.magnetic_width +} + +fn with_and_without_border(check: impl Fn(&mut PhotocraftApp)) { + let mut plain = app(); + check(&mut plain); + let mut drawing = app(); + start_border(&mut drawing); + check(&mut drawing); + assert!(magnetic_lasso_ui::replaces_selection(&drawing), "the border being drawn stays as it is"); +} + +#[test] +fn shift_open_bracket_sets_the_width_to_one_from_any_width() { + with_and_without_border(|app| { + for from in [10.0, 2.0, 1.0, 100.0, 256.0] { + app.ui.tool_options.magnetic_width = from; + assert!(press(app, Key::OpenBracket, Modifiers::SHIFT)); + assert_eq!(width(app), 1.0, "Shift+[ from {from}"); + } + }); +} + +#[test] +fn shift_close_bracket_sets_the_width_to_256_from_any_width() { + with_and_without_border(|app| { + for from in [10.0, 255.0, 256.0, 100.0, 1.0] { + app.ui.tool_options.magnetic_width = from; + assert!(press(app, Key::CloseBracket, Modifiers::SHIFT)); + assert_eq!(width(app), 256.0, "Shift+] from {from}"); + } + }); +} + +#[test] +fn plain_brackets_still_step_by_one_and_stop_at_the_limits() { + with_and_without_border(|app| { + app.ui.tool_options.magnetic_width = 10.0; + assert!(press(app, Key::OpenBracket, Modifiers::NONE)); + assert_eq!(width(app), 9.0); + assert!(press(app, Key::CloseBracket, Modifiers::NONE)); + assert!(press(app, Key::CloseBracket, Modifiers::NONE)); + assert_eq!(width(app), 11.0); + app.ui.tool_options.magnetic_width = 1.0; + press(app, Key::OpenBracket, Modifiers::NONE); + assert_eq!(width(app), 1.0, "[ stops at 1"); + app.ui.tool_options.magnetic_width = 256.0; + press(app, Key::CloseBracket, Modifiers::NONE); + assert_eq!(width(app), 256.0, "] stops at 256"); + }); +} + +#[test] +fn shifted_curly_bracket_keys_set_the_limits() { + with_and_without_border(|app| { + app.ui.tool_options.magnetic_width = 10.0; + assert!(press(app, Key::OpenCurlyBracket, Modifiers::SHIFT)); + assert_eq!(width(app), 1.0, "Shift+{{"); + assert!(press(app, Key::CloseCurlyBracket, Modifiers::SHIFT)); + assert_eq!(width(app), 256.0, "Shift+}}"); + }); +} + +#[test] +fn a_bare_curly_bracket_key_is_left_alone() { + with_and_without_border(|app| { + app.ui.tool_options.magnetic_width = 10.0; + assert!(!press(app, Key::OpenCurlyBracket, Modifiers::NONE), "a bare {{ is not taken"); + assert!(!press(app, Key::CloseCurlyBracket, Modifiers::NONE), "a bare }} is not taken"); + assert_eq!(width(app), 10.0); + }); +} diff --git a/docs/brush-parity.md b/docs/brush-parity.md index 3251193ab4..04e0eecc04 100644 --- a/docs/brush-parity.md +++ b/docs/brush-parity.md @@ -1,6 +1,6 @@ # Brush and painting parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 Painting is where Photoshop users notice differences first, so it gets its own checklist: the brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI @@ -48,7 +48,7 @@ tablets against Photoshop side by side. | Quick taps keep their pressure | partial | #1967 fixed one case; tap paints a full blob (#1798), tap sensitivity (#1933) | | Smooth pressure on Windows | partial | "jumpy" (#2046) | | Tilt and rotation drive angle/roundness | partial | macOS, X11, web; not Windows; rotation not applied (#1301) | -| Eraser end of the pen switches to Eraser | partial | macOS; flipped Wacom on Windows not (#2285) | +| Eraser end of the pen switches to Eraser | partial | macOS, Windows (WinTab; Windows Ink not yet confirmed on hardware, #2285); X11 and web partial | ## Stroke quality and feel @@ -120,6 +120,7 @@ tablets against Photoshop side by side. | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Eraser end of the pen switches to the Eraser on Windows with Windows Ink on (#2285); row stays partial (X11, web); no estimate changed | | 2026-10-30 | minor | Art History Brush Opacity on the options bar, #10263; no estimate changed | | 2026-10-25 | minor | Art History Brush row added as partial (8 of 10 styles, TOOL-213-20, #1610). No brush-feel estimate changed. | | 2026-10-23 | minor | Hard-round built-in presets use 5% spacing (#8842); rendered large-tip outline and pressure-opacity continuity tests cover 8/16/32-bit and 0/49% smoothing. Other presets and user settings retain their spacing; percentages and estimates unchanged. | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9f7d5997d6..dc4f36dddb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -76,9 +76,11 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - A save dialog's answer that PhotoCraft changes, by giving a name without an extension the suggested file's or by lowercasing the extension (Preferences › File Handling › Lowercase Extension), opens a replace prompt when a file exists under the changed name: a dialog with `__replaceSaved`, `message`, `detail` and `path` (the file the save would replace). `ui.dialog.confirm` writes the file; `ui.dialog.cancel` ends the save without writing, as Cancel in the save dialog does. The file dialog counts as open until the prompt is answered. A name that differs only in letter case and reaches the same file (Windows and macOS by default) does not open it. - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. + - Gradient Overlay's `params.offset` is the gradient's centre as a fraction of the layer's bounds (`[x, y]`, `[0, 0]` centred, as the renderer takes it). With the dialog on a Gradient Overlay page, a drag on the image moves it by the pointer's movement over the layer's size, as a drag on a shadow page moves the shadow (#10763). - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. - Select › Select and Mask… (`ui.menu.invoke {id: "select.selectAndMask"}`, Ctrl+Alt+R) opens Photoshop's workspace; `ui.inspect` reports it as `distort.selectAndMask`. Drive it with `ui.menu.invoke {id: "select.selectAndMask", params: {ui: {…}}}`: `tool` (`quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom`), `mode` (`add|subtract`), `size`, `hardness`, `sampleAllLayers`, `hideView` (true shows the image without the view, as holding X does), `stroke: {points: [[x,y],…], alt?}` (a drag with the current tool in document px: Object Selection takes a click or the rectangle's corners, the lassos the polygon), `selectSubject`, `clearSelection`, `invert`, the settings (`view`, `opacity`, `showEdge`, `showOriginal`, `realTimeRefinement`, `highQualityPreview`, `overlayColor`, `indicates`, `radius`, `smartRadius`, `smooth`, `feather`, `contrast`, `shiftEdge`, `decontaminate`, `amount`, `output`, `remember`), `undo`, `redo`, `reset`, `waitPreview`, `commit` (OK: `select.refineEdge` with the workspace's `edits` and `refineStrokes`, one history step) and `cancel`. The reply describes the workspace (`edits`, `strokes`, `selectedProxyPixels`, `previewReady`, …). - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). + - Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview. - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized. - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. - Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type. @@ -112,7 +114,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i another document becomes active before the capture, the request fails with an error rather than saving the wrong document - `ui.focus`: bring the main window to the front -- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, quality?, jpegFormat?, tiffCompression?, tiffTransparency?, tiffPyramid?, tiffLayers?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; TIFF: `tiffCompression` `none`, `lzw` or `zip`, `tiffTransparency` and `tiffPyramid` bools; automation never shows JPEG or TIFF Options): relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths beneath the canonical or configured root are accepted, while `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS, JPEG or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands)) +- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, quality?, jpegFormat?, tiffCompression?, tiffTransparency?, tiffPyramid?, tiffLayers?, maximizeCompatibility?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; TIFF: `tiffCompression` `none`, `lzw` or `zip`, `tiffTransparency` and `tiffPyramid` bools; automation never shows JPEG or TIFF Options; PSD/PSB: `maximizeCompatibility` false writes Photoshop's placeholder instead of the merged image (Bitmap, Indexed Color and Duotone documents still write the real image); unset or null follows Preferences › File Handling: Always and Ask When Saving write the real merged image, Never the placeholder, and `app.save` never opens a compatibility dialog): relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths beneath the canonical or configured root are accepted, while `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS, JPEG or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands)) - `app.quit` ## Engine commands @@ -385,7 +387,7 @@ How each MCP tool maps onto control methods in bridge mode: | `doc_export_layers {dir, …}` | `engine.execute {command: "file.export.layersToFiles", params}` | | `doc_export_data_sets {dir, …}` | `engine.execute {command: "file.export.dataSetsAsFiles", params}` | | `doc_import_data_sets {path, …}` | `engine.execute {command: "file.import.variableDataSets", params}` | -| `doc_save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` / `doc_export {path, tgaBits?, ddsCompression?, ddsMipmaps?}` | `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` | +| `doc_save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, maximizeCompatibility?}` / `doc_export {path, tgaBits?, ddsCompression?, ddsMipmaps?, maximizeCompatibility?}` | `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, maximizeCompatibility?}` | | `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content | | `session_list`, `ui_inspect` | `ui.inspect` | | `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content | @@ -451,7 +453,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 07f9ada9de..7182914d80 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (JPEG Options shows the size the file will have, FILE-215-19 partial; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; 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-11-06 · **Change:** minor (JPEG Options shows the size the file will have, FILE-215-19 partial; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; 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. @@ -68,7 +68,7 @@ supports many more, including CR3). | DNG (incl. LJPEG, lossy JPEG and JPEG XL tiles) | yes | 2026-10-13: lossy DNG (DNG 1.4 compression 34892: 8-bit baseline JPEG tiles or strips, CFA and LinearRaw, partial edge tiles) decodes to the stored samples, which go through LinearizationTable / BlackLevel / WhiteLevel (default 255) like every other depth; `crates/raw/tests/it/dng.rs` `lossy_jpeg_*` (FILE-215-11, lossy DNG part; no lossy file in the raw corpus yet) | | Canon CR2 | yes | | | Canon CR3 | detected, unsupported | `crates/raw/src/lib.rs:219` | -| Nikon NEF/NRW (lossless, lossy) | yes; "lossy after split" no | #50; D5100 and D90 image areas measured (14-bit NEFs); D4 profile levels follow the sample depth (12 and 14 bit); [validation](nikon-nef-development.md) | +| Nikon NEF/NRW (lossless, lossy) | yes, including "lossy after split" (2026-10-31: the 11 CC0 raw.pixls.us split files, D3400 / D5 / D5000 / D5200 / D5500 / D5600 / D7000 / 1 J5 / Z 6_2) | #50; D5100 and D90 image areas measured (14-bit NEFs); D4 profile levels follow the sample depth (12 and 14 bit); [validation](nikon-nef-development.md) | | Sony ARW/SR2/SRF (incl. compressed) | yes | | | Panasonic RW2, Pentax PEF | yes | | | Olympus ORF | uncompressed only | | @@ -151,6 +151,7 @@ The original reference entry retains its source date and historical totals; curr | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Scripted PSD/PSB saves take `maximizeCompatibility` (Save, Save As, Save a Copy, `app.save`, serve `doc.save`, MCP `doc_save`/`doc_export`, Batch, Image Processor, Layers to Files) over Preferences › File Handling for one save, and the CLI `--no-maximize-compatibility` (#8064). Layer channels and the merged image were already RLE (ZIP with prediction at 32-bit), as Photoshop writes them (#8645) | | 2026-11-02 | minor | Actions Shear (`Shr `) loads, plays and saves the measured curve points and edge mode; unsafe subranges and unrepresentable forms remain kept steps (#10605). | | 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | | 2026-11-01 | minor | Recorded direct Gradient Map and Lab-range Replace Color load, play and retain their measured settings on save; unsupported forms remain preserved (part of #10607). | diff --git a/docs/gaps.md b/docs/gaps.md index 5dba9ad631..bd132b8052 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-11-05 · **Change:** minor (G10: JPEG Options shows the size the file will have; FILE-215-19 stays partial (Matte, Scans); RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; 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-11-06 · **Change:** minor (G10: JPEG Options shows the size the file will have; FILE-215-19 stays partial (Matte, Scans); G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; 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 @@ -416,10 +416,9 @@ what an agent can't finish alone. ### G12. Pen tablets and display hardware - **Missing:** tilt and rotation on Windows (pressure only, via WM_POINTER; no WinTab); native - Wayland tablet-v2 (#79; the pen does not click on GNOME 50, #2622, KDE #2297); eraser end on - flipped Wacom pens (#2285); HDR/EDR output (Photoshop has "Precise Color Management for HDR - Display"); monitor profile detection off macOS and live profile changes; Touch Bar (macOS - Intel only, low value); 3D mice. + Wayland tablet-v2 (#79; the pen does not click on GNOME 50, #2622, KDE #2297); HDR/EDR output + (Photoshop has "Precise Color Management for HDR Display"); monitor profile detection off + macOS and live profile changes; Touch Bar (macOS Intel only, low value); 3D mice. - **Detail:** [`hardware-parity.md`](hardware-parity.md). - **Estimate:** 80–150 h. **Human:** tablets and HDR displays to test on. @@ -466,6 +465,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | G12: eraser end of flipped pens on Windows (Windows Ink on) selects the Eraser (#2285); no estimate changed | | 2026-10-29 | minor | G17: web build memory handling (#10024): up-front memory checks for Place, Image Size, smart-object re-render and Save; a low-memory warning; a stopped message when the module traps; PSD save reserves its whole output; no estimate changed | | 2026-11-02 | minor | G11: Batch Esc Continue/Stop, one plan and error log across interruptions, and read-only input previews without a progress bar (#4579); live tab parity remains open, AUTO-219-5 partial; readiness and estimate unchanged | | 2026-11-02 | minor | Action recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and places point text by canvas percentage; paragraph boxes remain absolute (AUTO-219-1, #4514); parity percentages unchanged | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 7ed3d1e71e..5d28b21dd8 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 Each hardware feature Photoshop 2026 (27.11.0) uses, per platform, against PhotoCraft. Photoshop side: its bundle (Metal and OpenCL paths, "Precise Color Management for HDR Display" and EDR @@ -35,15 +35,15 @@ HDR display to verify. | Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622), KDE (#2297) | yes | | Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | no | yes | | Barrel rotation | yes | yes (not applied to tip angle, #1301) | no (WinTab: with a twist-reporting pen and driver, opt-in) | partial | no | yes (twist) | -| Eraser end | yes | yes | no (#2285); WinTab: yes (opt-in) | partial | no | partial | +| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | no | partial | | WinTab driver mode | yes | – | yes (opt-in; Windows Ink off) | – | – | – | | Pressure curve | Windows Ink / driver | global curve in Preferences (#2195) | same | same | same | same | Windows: the opt-in WinTab backend (`tools.tabletInput = "winTab"`, with Windows Ink turned off in the tablet utility) supplies pressure and the eraser end, tilt only on devices that report orientation axes, and rotation only when the pen and driver report twist (pressure-only devices -get neutral tilt and rotation). The default Windows Ink path is unchanged and still lacks tilt, -rotation and the eraser. +get neutral tilt and rotation). The default Windows Ink path still lacks tilt and +rotation; its eraser end comes from the pointer hooks (#2285). ## Displays and colour @@ -71,6 +71,7 @@ rotation and the eraser. | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Windows eraser end: the pointer hooks read `PEN_FLAG_INVERTED` and the Eraser switch follows it (Windows Ink on; #2285) | | 2026-11-05 | minor | Optional WinTab driver mode on Windows: pressure and eraser; tilt with orientation axes; rotation with a twist-reporting pen, with Windows Ink off | | 2026-10-28 | minor | Build GPU compositor pipelines in the background; benchmark baseline pending (#9157) | | 2026-10-10 | major | First version | diff --git a/docs/images/guide-position-after-tab.png b/docs/images/guide-position-after-tab.png new file mode 100644 index 0000000000..a0658b74b1 Binary files /dev/null and b/docs/images/guide-position-after-tab.png differ diff --git a/docs/images/guide-position-before-tab.png b/docs/images/guide-position-before-tab.png new file mode 100644 index 0000000000..2eca847845 Binary files /dev/null and b/docs/images/guide-position-before-tab.png differ diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 60bdfcabd1..7c69231573 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -2,14 +2,14 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand. -**661 of 661 menu items live (100.0%).** +**662 of 662 menu items live (100.0%).** | Menu | Live | Total | % | |---|---:|---:|---:| | File | 52 | 52 | 100% | | Edit | 75 | 75 | 100% | | Image | 61 | 61 | 100% | -| Layer | 161 | 161 | 100% | +| Layer | 162 | 162 | 100% | | Type | 74 | 74 | 100% | | Select | 25 | 25 | 100% | | Filter | 75 | 75 | 100% | diff --git a/docs/printing.md b/docs/printing.md index f15773000f..b552647b50 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -5,6 +5,27 @@ position and scale, crop and registration marks, labels, colour handling) and ha to a printer. The rendering is `print_cmds.rs` in `photocraft-engine`, shared by the dialog, the batch commands and automation (`file.print`, `file.printOneCopy`); this page is about the hand-off. +## Paper sizes + +The Print dialog's named Paper entries and `file.print`'s named `paper` values use the paper table +in `print_cmds.rs` (portrait sizes in points). `file.print` also accepts a custom `[width, height]` +in points. Both produce a portrait PDF page: + +| Name | Size | +|---|---| +| `letter`, `legal`, `tabloid` | 8.5 × 11, 8.5 × 14, 11 × 17 in | +| `a3`, `a4`, `a5`, `a6` | ISO A3/A4/A5/A6 | +| `4x6`, `5x7` | 4 × 6, 5 × 7 in | +| `postcard`, `double-postcard` | Japanese postcard はがき 100 × 148 mm (283.46 × 419.53 pt), 往復はがき 148 × 200 mm | +| `b5`, `b4` | JIS B5 182 × 257 mm (515.91 × 728.50 pt), JIS B4 257 × 364 mm (728.50 × 1031.81 pt) | +| `l`, `2l`, `kg` | L判 89 × 127 mm (252.28 × 360.00 pt), 2L判 127 × 178 mm, KG判 102 × 152 mm | +| `6cut`, `4cut` | 六切 203 × 254 mm (575.43 × 720.00 pt), 四切 254 × 305 mm (720.00 × 864.57 pt) | + +Names are matched case-, space- and punctuation-insensitively, and the customary Japanese names +are aliases: `はがき`/`ハガキ`/`葉書`/`ポストカード`, `往復はがき`, `JIS B5`/`B5 (JIS)`, `JIS B4`/`B4 (JIS)`, +`L判`/`Lサイズ`/`L-size`, `2L判`, `KG判`, `六切`/`6切`, `四切`/`4切`. A size not in the table can be +given as points (`[width, height]`), which is what the dialog's Custom row does. + ## Positioning the preview Drag the visible image on the paper to change Top and Left. Starting a drag switches Center @@ -93,7 +114,8 @@ job went) and `pdf` (the page's path, only when `output` named one). printer listing with state and default, the default printer and its absence, `Print-Job` with the document and the job id, chunked and content-length replies, HTTP and IPP error statuses, broken replies. -- `crates/engine/src/print_cmds/tests.rs`: printer resolution (requested, default, only one, +- `crates/engine/src/print_cmds/tests.rs`: the paper sizes and their alternative names (the Japanese + ones included) and the PDF pages they produce; printer resolution (requested, default, only one, several without a default, unknown, none); a complete `file.print` against a fake CUPS (printer URI, copies, job name, document format, the PDF itself) and `file.printers`; `lp` taking the job when it is on the path; the IPP route when it is not (a child process diff --git a/docs/scorecard.md b/docs/scorecard.md index 52c3cbe64b..9e22c14559 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,9 +9,9 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 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: 10 of 192 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 3 | 3 | 661 of 661 menu items live (100.0%) | +| [Automation](#automation) | 5 | 3 | 3 | 662 of 662 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -209,13 +209,13 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 192** (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: 10 of 194** (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.legacy_compositing`, `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`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| -| UI-217-1 | Tool options, last Export As / Save for Web / Fill settings and font recents persist | partial | [#217](https://github.com/storytold/photocraft/issues/217) | Tool options (Preferences.toolOptions, tool_memory.rs, #2814; clamped to the options-bar ranges on restore), each painting tool's own brush (Preferences.toolBrushes + lastBrush, #6212) and the selected tool persist; Reset Tool / Reset All Tools (tool_reset.rs) clear them. Fill, Liquify, Export As (export_dialog.rs COMMAND) and Save for Web (file_ui.rs WEB_COMMAND) remember their last settings in prefs.dialogs. Missing: font recents (type.recentFonts is in the prefs audit's unused list) | +| UI-217-1 | Tool options, last Export As / Save for Web / Fill settings and font recents persist | partial | [#217](https://github.com/storytold/photocraft/issues/217) | Tool options (Preferences.toolOptions, tool_memory.rs, #2814; clamped to the options-bar ranges on restore), each painting tool's own brush (Preferences.toolBrushes + lastBrush, #6212) and the selected tool persist; Reset Tool / Reset All Tools (tool_reset.rs) clear them. The last tool of each toolbar slot and tool key persists too (Preferences.groupTools, #3569). Fill, Liquify, Export As (export_dialog.rs COMMAND) and Save for Web (file_ui.rs WEB_COMMAND) remember their last settings in prefs.dialogs. Missing: font recents (type.recentFonts is in the prefs audit's unused list) | | UI-217-2 | Window size and dock width remembered across restarts | done | [#217](https://github.com/storytold/photocraft/issues/217) | eframe persistence (ui.ron): persist_window for the window, egui memory for the dock panel width; window_and_panel_geometry_survive_a_restart asserts the round trip (apps/photocraft/src/main.rs; b07a2e5b, #587) | | UI-217-3 | File > Open starts in the last-used folder | done | [#217](https://github.com/storytold/photocraft/issues/217) | file_dialog.rs last_used_dir: open dialogs ask with initial_dir (the most recent file's folder) and apps services.rs passes it to rfd set_directory; open_starts_in_the_last_used_folder + last_used_dir_takes_the_most_recent_parent | | UI-217-4 | Preferences all take effect; recent files persist and honour recent_file_count (#204) | missing | [#217](https://github.com/storytold/photocraft/issues/217) | See the prefs audit and BUG-204-* | @@ -256,7 +256,7 @@ Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace. ## Automation -Menu wiring (`docs/parity-checklist.md`): 661 of 661 menu items live (100.0%). This counts dispatch, not behaviour. +Menu wiring (`docs/parity-checklist.md`): 662 of 662 menu items live (100.0%). This counts dispatch, not behaviour. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f696ab9cda..1bf5082544 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (JPEG Options shows the size the file will have, FILE-215-19 partial; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (JPEG Options shows the size the file will have, FILE-215-19 partial; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -179,7 +179,7 @@ parity for the area and are already contained in the dimension rows above. | Camera Raw and computational photo (Photomerge, HDR, lens) | 45% | 120–200 | Raw for DNG/CR2/NEF/ARW/RW2/ORF/RAF(uncompressed)/PEF; no CR3; ACR dialog partial (no masking; no per-camera colour for non-DNG cameras); generic lens profiles only | | Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; recording uses implicit active layers, unique layer names, whole-text Type steps, bundled Move-tool nudges, relative keyboard document switches and canvas-relative point text (AUTO-219-1, #4514; duplicate names and paragraph boxes remain open); Actions panel remains partial (AUTO-219-2); `.atn` load/save since 2026-10-12 (112 events mapped, the rest kept verbatim); compound layer properties export as separate Set events with rename last (#8304, 2026-10-21; independent Photoshop replay pending); no ExtendScript/UXP | | File I/O | 60% | 300–500 | See [file-format-parity.md](file-format-parity.md) | -| Print, export, Save for Web | 50% | 60–100 | JPEG Options without Matte or progressive Scans (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered | +| Print, export, Save for Web | 50% | 60–100 | Paper sizes include the Japanese ones (はがき 100×148 mm, 往復はがき 148×200, JIS B5/B4, A6, L判 89×127, 2L判 127×178, KG判 102×152, 六切 203×254, 四切 254×305) by their customary names; JPEG Options without Matte, or progressive Scans (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered | | Video / timeline, data-driven graphics | 30% | 100–200 | Menu items live; frame model persists in `.pcraft`; no PSD video-layer mapping | | Workspace, panels, preferences | 40% | 150–250 | 11 of 183 prefs do nothing (scorecard, 2026-11-01); no floating/OS-window panel groups; Libraries, Comments, Contextual Task Bar missing | | AI / generative | 10% | 300–600 | See the dimension row | @@ -475,7 +475,7 @@ filled bar. This extends UI reachability and does not claim Photoshop-authored s | Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. | | Performance | 14k+ px on the GPU at ~⅓ the memory; adjustment preview 285 ms → 4–9 ms; font-size edits 297 ms → 4.6 ms; 2026-10-07: 30 MP TIFF open (banded, parallel strip/tile decode) Deflate 345 → 32 ms, LZW 428 → 43 ms, BigTIFF and every IFD readable; 2026-10-09: 4.2 MP Indexed Color, 256 colours, full-resolution CPU preview p50 3018 → 1061 ms (Ryzen AI 7 350, three measured runs; GPU upload excluded); 2026-10-10: Liquify 3500×2200, 800 px brush, visible 1:1 crop 3.20 → 3.63 ms p50 (5 runs) while refreshing ~9× as many pixels | medium-high on rasters | Complex layout documents still laggy (#125/#128); >16384 px GPU tiling in progress (#49). Liquify now displays source-resolution detail above 100% zoom; its ≤1 ms update target is not met (3.73 ms p95 on a Windows run; GPU upload excluded). Native Indexed Color previews run on one background worker with stale-result rejection; large palettes can still take about a second to compute. Web previews remain synchronous. | | Stability | Never-crash lint series, crash guard, `panic_hunt` fuzzing in the gate | medium-high | No field crash data yet. | -| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF; 2026-10-09: uncompressed Fujifilm RAF, Bayer and X-Trans (edge-directed X-Trans demosaic; 26 MP X-Trans develop 306 ms on 12 cores) | medium | CR3, compressed RAF and Nikon "lossy after split" still open (#50). Non-DNG cameras have no calibration: their colour (matrix + tone curve) is fitted per file to the camera's embedded JPEG, with the neutral sRGB-primaries fallback when the fit doesn't clearly help (2026-10-08: 8 D3200 NEFs, mean ΔE vs the camera JPEG 11.6–26.0 → 1.0–7.5); measured per-model calibration still open. | +| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF; 2026-10-09: uncompressed Fujifilm RAF, Bayer and X-Trans (edge-directed X-Trans demosaic; 26 MP X-Trans develop 306 ms on 12 cores) | medium | CR3 and compressed RAF still open (#50); Nikon "lossy after split" decoded since 2026-10-31. Non-DNG cameras have no calibration: their colour (matrix + tone curve) is fitted per file to the camera's embedded JPEG, with the neutral sRGB-primaries fallback when the fit doesn't clearly help (2026-10-08: 8 D3200 NEFs, mean ΔE vs the camera JPEG 11.6–26.0 → 1.0–7.5); measured per-model calibration still open. | | AI / generative | none | ~0% | Deferred by decision (#41). | | Ecosystem | Sandboxed WebAssembly plug-ins instead of .8BF; `.atn` actions load and save (2026-10-12); no ExtendScript/UXP; no Adobe Fonts/Libraries/cloud docs | low | By design for 8BF; scripting compatibility open. | | Platforms | macOS (notarized), Windows, Linux (AppImage/deb/rpm/Flatpak bundle), web | medium-high | Flathub later (#173); Windows signing material pending. | @@ -609,6 +609,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | | 2026-10-22 | minor | Platforms: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; percentages unchanged | +| 2026-10-22 | minor | Print: Japanese paper sizes (はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切) in the Print dialog, `file.print` and the PDF page, by their customary names; no percentage changed | | 2026-10-21 | minor | #8304: compound layer properties export as separate Set events, rename last; independent Photoshop replay pending; percentages and estimates unchanged | | 2026-10-19 | minor | JPEG Options dialog landed (FILE-215-19 partial: no Matte, progressive Scans or size preview); percentages unchanged | | 2026-10-18 | minor | Layers: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial; percentages unchanged | diff --git a/docs/ui-dialogs.md b/docs/ui-dialogs.md index 634c7711a0..a4ce8a30ff 100644 --- a/docs/ui-dialogs.md +++ b/docs/ui-dialogs.md @@ -45,6 +45,7 @@ Dispatch order matches `dialogs::show` in `dialogs.rs` (check earlier rows befor | Match | Module | Role | |---|---|---| | `__guideLayout` | `guide_layout_ui.rs` | View › New Guide Layout… | +| `__newGuide` | `new_guide_ui.rs` | New Guide / Edit Selected Guides; typed positions and guide colours | | `__fill` | `fill_ui.rs` | Edit › Fill… | | `__patternFill` | `pattern_fill_ui.rs` | Pattern Fill layer / New Fill Layer › Pattern… | | `__stroke` | `stroke_ui.rs` | Edit › Stroke… | @@ -74,6 +75,12 @@ actions with their marker already set. ### Shared private keys +New Guide and Edit Selected Guides keep the Position field in the Tab/Shift+Tab order and select +its text on focus. Typed unit suffixes use the existing engine parser; bare numbers use the ruler +unit. An untouched edit preserves the guide's exact pixel position behind its rounded readout, +including when changing only its colour. Once Position is edited, the typed value is intentional, +even if it matches that original readout. Confirming an unchanged guide preserves Redo. + | Key | Meaning | |---|---| | `__command` | Engine command id run on OK (bare confirm, filters, sizing, …) | @@ -216,6 +223,7 @@ Same hub entry as standalone pickers; `color_picker_ui::confirm` branches on ext | Date | Change | |---|---| +| 2026-11-06 | New Guide / Edit Selected Guides: Position Tab focus and exact edit-position handling | | 2026-10-11 | Initial doc from dialog codebase audit | | 2026-10-11 | Document all `DialogKind` values and `Command` routing markers | | 2026-10-11 | Alt+Cancel → Reset hub (`dialog_alt_reset`); opt-in markers | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b84fd81419..fe8b7ee272 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-11-06 · **Change:** minor (Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; 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; 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-11-07 · **Change:** minor (Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; 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; 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, @@ -51,7 +51,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme |---|---|---| | Letter shortcuts, ⇧+letter cycles the group, "Use Shift Key for Tool Switch" (on by default, as in Photoshop) | done | `shortcuts.rs` `select_tool_by_key` | | Alt/Option-click a toolbar button cycles its flyout slot (including tools with no letter key) | done | `toolbar.rs` `next_slot_tool`; `type_flyout_tests.rs` `alt_click_cycles_the_tool_flyout_slot` | -| Group remembers the last tool used | partial | L always resets to Lasso (#2608) | +| Group remembers the last tool used: its toolbar slot shows it and its key brings it back, also after quitting and relaunching; temporary tool switches excluded | done | `state.rs` `group_tools`, `tool_memory.rs`; `shortcuts::tests::tool_key_brings_back_the_groups_last_used_tool`, `prefs_ui::tests::group_tools_survive_a_restart`, `group_tools_exclude_temporary_switches`, `type_flyout_tests::slots_come_back_on_their_last_tool_after_a_restart` | | Press-and-hold or click-drag opens the flyout | done | `toolbar.rs`; right-click, long-press, press-drag | | Edit Toolbar customization | done | `edit.toolbar` | | Last selected tool restored after quitting and relaunching; temporary tool switches excluded | done | `tool_memory.rs`; `prefs_ui::tests::selected_tool_survives_a_restart_without_option_changes`, `selected_tool_excludes_temporary_switches` | @@ -265,11 +265,14 @@ Paragraph; the rest open as in-app floating windows. | Layers panel: Clip Thumbnails to Layer Bounds (panel menu, `interface.clipThumbnailsToLayerBounds`) | done (2026-10-12) | `layer_thumb_bounds_tests.rs`; #4281. Thumbnail size and the Panel Options dialog to come | | Smart filter rows: drag up or down the stack to reorder (a line marks the drop; the bottom filter is applied first) | done | `smart_ui.rs` `reorder_drop`, `layer.smartFilter.move` | | Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…; the single-channel items act on the targeted row (a colour, alpha or spot channel, Quick Mask, the layer mask, a one-channel image's composite) and are greyed without one; New Channel…, New Spot Channel…, Channel Options… and Merge Channels… (only the modes the open grayscale documents fill, a different document per channel; greyed below three documents) open their dialogs, here and in the rows' menu, and Split Channels runs at once | done (2026-11-06) | `channels_panel.rs` `panel_menu`, `channels_panel/tests.rs`, `panel_docking/tests.rs`, `dialogs/merge_channels_ui.rs`; #11451. Panel Options (thumbnail size) to come | +| Layer ▸ Smart Objects ▸ Reset Transform, and the same item in the Layers panel row menu under Edit Contents for a smart object layer: the placement returns to 100 % of the current contents' own size with rotation, skew, Distort, Perspective **and the Warp** cleared, as the reference application clears the warp with the rest of the transform, the object left centred on the average of the placement's four corners, in one undo step; the smart filters stay; a stack whose filters can't all be applied, or contents that can't be read, refuses the step whole rather than recording the old warped pixels under the new placement | done (2026-11-07) | `layer.smartObjects.resetTransform`, `smart_cmds/placing.rs` (`reset_transform`), `panels/layer_menu_ui.rs`, `smart_cmds/tests.rs`; #11662, semantics measured against the reference application 2026-11-06 (#11675 discussion) | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Reset Transform on a smart object also clears the **Warp**, and centres on the average of the placement's four corners rather than the point its box centre maps to: measured in the reference application 2026-11-06 (a smart object warped with Arc 50, rotated 20° and scaled to 80 % came back with no warp at all, at its contents' own size, unrotated), which corrects the row below (#11662, discussion in #11675). The corner average is the box centre for an affine placement, so only Distort and Perspective placements move; the Smart Filter mask and linked masks keep following the placement, as under Free Transform. The step also requires its re-render: a visible filter PhotoCraft doesn't implement, or contents that can't be read, refuses it whole (no history state, placement and warp untouched) rather than recording the old warped pixels at the reset placement. No percentage changed | +| 2026-11-06 | minor | Layer ▸ Smart Objects ▸ Reset Transform, and the same item in the Layers panel row menu for a smart object layer (#11662): 100 % of the current contents' own size again with rotation, skew, Distort and Perspective cleared and the object left centred where it is, in one undo step; the Warp and the smart filters are untouched, as Photoshop resets the transform and not the warp. No percentage changed | | 2026-11-06 | minor | Channels panel menu (☰): the channel items, not only the rows' context menu; New Channel…, New Spot Channel…, Channel Options… and Merge Channels… open their dialogs (New Channel and Merge Channels are new), and Channel Options… in Quick Mask mode opens a targeted alpha channel's options (#11451). No percentage changed | | 2026-11-05 | minor | Image › Adjustments › Selective Color keeps each colour's own Cyan, Magenta, Yellow and Black, and OK and Preview apply all nine colours; the dialog and the Properties panel share one editor (#11463) | | 2026-11-02 | minor | Edit › Transform › Distort: the side handles move their edge freely, both its corners by the drag, stopping before the box folds as a corner does; Perspective's side handles skew along their edge, as in Photoshop (#10085). Not a new command, so no percentage changed | @@ -364,4 +367,7 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-28 | minor | A Color Picker for another dialog's colour field (Fill, Stroke, filters, guides, channels, Preferences…) or the Crop shield's custom colour shows the colour there before OK; Cancel restores it (#9886); no percentage changed | | 2026-10-16 | minor | Hand tool: ⌘ held zooms in and ⌥ zooms out, as in Photoshop (#6434) | | 2026-11-03 | minor | Tools › Overscroll off centres an image smaller than the window on that axis, so zooming out around the pointer keeps it in the middle instead of where the zoom left it (#10488, #4799); this overrides #1718's Photoshop 25.4 measurement on the strength of two Photoshop users' reports, and Overscroll on keeps the free view; no percentage changed | +| 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | + + diff --git a/docs/user/guides/select-and-mask.md b/docs/user/guides/select-and-mask.md index 50f78b7685..eb5caa2464 100644 --- a/docs/user/guides/select-and-mask.md +++ b/docs/user/guides/select-and-mask.md @@ -19,7 +19,7 @@ Smart selection runs on your computer. It needs no account and no cloud. ## Adjust the selection -- **Select › Inverse Selection** swaps the selected and unselected areas. +- **Select › Inverse** swaps the selected and unselected areas. - **Select › Modify** has **Border…**, **Smooth…**, **Expand…**, **Contract…** and **Feather…**. Feather softens the edge. - **Select › Select and Mask…** refines an edge, for example around hair. - **Select › Deselect** removes the selection. **Select › Reselect** brings back the last one. diff --git a/scorecard/ui.toml b/scorecard/ui.toml index 6f2e163eb7..98c4d2d344 100644 --- a/scorecard/ui.toml +++ b/scorecard/ui.toml @@ -10,7 +10,7 @@ id = "UI-217-1" target = "Tool options, last Export As / Save for Web / Fill settings and font recents persist" status = "partial" issue = 217 -note = "Tool options (Preferences.toolOptions, tool_memory.rs, #2814; clamped to the options-bar ranges on restore), each painting tool's own brush (Preferences.toolBrushes + lastBrush, #6212) and the selected tool persist; Reset Tool / Reset All Tools (tool_reset.rs) clear them. Fill, Liquify, Export As (export_dialog.rs COMMAND) and Save for Web (file_ui.rs WEB_COMMAND) remember their last settings in prefs.dialogs. Missing: font recents (type.recentFonts is in the prefs audit's unused list)" +note = "Tool options (Preferences.toolOptions, tool_memory.rs, #2814; clamped to the options-bar ranges on restore), each painting tool's own brush (Preferences.toolBrushes + lastBrush, #6212) and the selected tool persist; Reset Tool / Reset All Tools (tool_reset.rs) clear them. The last tool of each toolbar slot and tool key persists too (Preferences.groupTools, #3569). Fill, Liquify, Export As (export_dialog.rs COMMAND) and Save for Web (file_ui.rs WEB_COMMAND) remember their last settings in prefs.dialogs. Missing: font recents (type.recentFonts is in the prefs audit's unused list)" [[item]] id = "UI-217-2"