diff --git a/.config/nextest.toml b/.config/nextest.toml index 703f9208ee..2ef6d6f215 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -19,11 +19,11 @@ gpu = { max-threads = 4 } filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/)))' test-group = 'gpu' -# CI (`--profile ci`, .github/workflows/ci.yml). Stops at the first failure so a red PR frees its -# runner, fails a test that hangs instead of letting it hold the runner, and repeats every failure -# at the end of the log. The default profile's GPU override still applies. +# CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run +# instead of exposing one regression per rebuild. A hanging test still terminates, and every +# failure is repeated at the end of the log. The default profile's GPU override still applies. [profile.ci] -fail-fast = true +fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 87d0b180fe..66cd9f1307 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -34,7 +34,7 @@ next to them. | `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (114 files; `star-filled.svg` is `star.svg` with a solid fill, `rotate-ccw.svg` is `rotate-cw.svg` mirrored) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -44,6 +44,7 @@ next to them. | `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/type-mask.svg`, `assets/icons/type-mask-vertical.svg` | Horizontal and Vertical Type Mask tool glyphs: a T drawn as marching ants (the vertical one beside a downward arrow), on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/path-op-{new-layer,combine,subtract,intersect,exclude,merge}.svg` | Path Operations glyphs (Pen options bar): a single square for New Layer, and two overlapping squares showing the area each operation keeps (union, back minus front, overlap, everything but the overlap, the merged outline), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/text-warp.svg` | Create Warped Text glyph (Type tool options bar): a T above a bowed arc, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index 52a1b2aac6..8186c52112 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5098,6 +5098,7 @@ dependencies = [ "image", "image-webp", "jpeg-encoder", + "jxl-oxide", "photocraft-heif", "png 0.18.1", "proptest", @@ -5107,6 +5108,7 @@ dependencies = [ "tiff", "zune-core 0.5.3", "zune-jpeg 0.5.15", + "zune-jpegxl", ] [[package]] diff --git a/README.md b/README.md index a22f1aee26..3c4e586f26 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,8 @@ The Flatpak prints through the host's CUPS socket (File › Print talks IPP to i The AppImage needs no install: the first run registers its launcher icon and menu entry in `~/.local/share` so the dock shows PhotoCraft's icon on Wayland. Set `PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1` to skip that, and see [`docs/releasing.md`](docs/releasing.md) › Linux to undo it. +To use the bundled CLI, run `./photocraft--linux-x86_64.AppImage --cli --help`, or `--cli mcp` to start the MCP server on stdio. CLI launches skip desktop integration. A symlink named `photocraft-cli` also selects the CLI; see [`docs/development.md`](docs/development.md#headless-cli). + On a Wayland session, files dropped on the window don't open yet: winit 0.30, the windowing library under egui, has no Wayland drag and drop (#386). Use File › Open, or copy the image in your file manager and paste it with Ctrl+V. To drag and drop, start PhotoCraft under XWayland: `WAYLAND_DISPLAY= photocraft`, `WAYLAND_DISPLAY= ./photocraft--linux-x86_64.AppImage`, or `flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft`. On Wayland, PhotoCraft shows the command for your install in a notice until you dismiss it. Preferences › Performance › Linux display server = X11 does the same on every launch. With a fractional display scale (125%, 150%, 175%) an XWayland window is drawn at a lower resolution and enlarged by the compositor, so the interface is blurred there; native Wayland stays sharp (#1072). On macOS, the command-line tool comes as `photocraft-cli--macos-universal.zip`. The binary is signed with the same Developer ID as the app and notarized by Apple. A bare binary can't carry a stapled notarization ticket the way the DMG does, so the first time you run it macOS checks the notarization online. You can confirm it yourself: diff --git a/apps/photocraft/src/app_icon.rs b/apps/photocraft/src/app_icon.rs index e20e70206a..4fb8765e52 100644 --- a/apps/photocraft/src/app_icon.rs +++ b/apps/photocraft/src/app_icon.rs @@ -15,7 +15,7 @@ //! be stamped on the shortcut, or the taskbar would stop matching the two. /// Window, taskbar and (when running unbundled) Dock icon. macOS gets the padded 1024 px render -/// on Apple's icon grid; elsewhere the tighter 256 px hicolor render reads better at small sizes. +/// on Apple's icon grid; elsewhere the 256 px hicolor render of the full tile. pub fn window_icon() -> egui::IconData { match eframe::icon_data::from_png_bytes(PNG) { Ok(icon) => icon, @@ -108,6 +108,16 @@ mod tests { assert!(icon.rgba.chunks(4).any(|p| p[3] > 0), "the icon isn't blank"); } + #[test] + fn windows_and_linux_icons_keep_the_round_corners() { + // rx=112 of 512 leaves (10, 10) of a 256 px render transparent; the old crop filled it (#4478). + let png = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png"); + let icon = eframe::icon_data::from_png_bytes(png).unwrap(); + assert_eq!(icon.width, 256); + assert_eq!(icon.rgba[(10 * 256 + 10) * 4 + 3], 0, "corner is transparent"); + assert_eq!(icon.rgba[(128 * 256 + 2) * 4 + 3], 255, "the tile is full bleed"); + } + /// The `.ico` build.rs embeds: every size Windows asks for, each a valid PNG or BMP image. #[test] fn exe_icon_has_every_shell_size() { diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index d73984eb8a..4834327b8e 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -16,15 +16,10 @@ use photocraft_ui_egui::ControlRequest; use photocraft_ui_egui::control::REPLY_DEADLINE; use serde_json::{Value, json}; -pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver { +/// Start serving a listener already bound during startup, before a window is opened. +pub fn start(listener: TcpListener, token: String, ctx: egui::Context) -> Receiver { let (tx, rx) = channel::(); - let listener = match TcpListener::bind(("127.0.0.1", port)) { - Ok(l) => l, - Err(e) => { - eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {e}"); - return rx; - } - }; + let port = listener.local_addr().map_or(0, |a| a.port()); eprintln!("photocraft: control server listening on {}", listening_addr(&listener, port)); std::thread::spawn(move || { let limiter = ConnectionLimiter::new(MAX_CONNECTIONS); @@ -152,6 +147,30 @@ mod tests { TcpStream::connect(&logged).unwrap(); } + #[test] + fn a_prebound_listener_authenticates_and_dispatches_requests() { + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let requests = start(listener, TOKEN.into(), egui::Context::default()); + let mut stream = TcpStream::connect(address).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut replies = BufReader::new(stream.try_clone().unwrap()); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap(); + let mut line = String::new(); + replies.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["result"]["authenticated"], true); + writeln!(stream, "{}", json!({"id": 2, "method": "test.bound"})).unwrap(); + let request = requests.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(request.method, "test.bound"); + request.reply.send(json!({"ok": true, "result": "served"})).unwrap(); + line.clear(); + replies.read_line(&mut line).unwrap(); + let reply: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(reply["id"], 2); + assert_eq!(reply["result"], "served"); + } + /// #4965: a connection that keeps sending without authenticating is closed at the deadline /// (releasing its connection permit), and nothing it sent is dispatched. #[test] diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index 6a0cc8f052..f5f014a3c1 100644 --- a/apps/photocraft/src/logging.rs +++ b/apps/photocraft/src/logging.rs @@ -315,22 +315,31 @@ pub struct AppLogger { filter: Filter, stderr: bool, sink: Mutex, + /// The file [`AppLogger::attach_dir`] opened, so a failure can tell the user what to attach. + path: Mutex>, /// The lock that marks the attached log file as in use (see [`rotate`]); held until exit. owner: Mutex>, } impl AppLogger { pub fn new(filter: Filter, stderr: bool) -> AppLogger { - AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)), owner: Mutex::new(None) } + AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)), path: Mutex::new(None), owner: Mutex::new(None) } } /// Rotate the logs in `dir` and send records to the fresh file; returns its path. pub fn attach_dir(&self, dir: &Path) -> Result { let LogFile { path, file, owner } = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?; self.sink.lock().unwrap_or_else(PoisonError::into_inner).attach(file); + *self.path.lock().unwrap_or_else(PoisonError::into_inner) = Some(path.clone()); *self.owner.lock().unwrap_or_else(PoisonError::into_inner) = owner; Ok(path) } + + /// The log file records are written to, once [`AppLogger::attach_dir`] opened one: `None` when + /// the file could not be created (standard error is the only sink, see [`install`]). + pub fn path(&self) -> Option { + self.path.lock().unwrap_or_else(PoisonError::into_inner).clone() + } } impl log::Log for AppLogger { @@ -379,6 +388,21 @@ mod tests { d } + /// The startup-failure dialog names the log file, so the logger has to remember it (#7643). + /// A start that couldn't create one keeps `None` and the dialog leaves the line out. + #[test] + fn path_names_the_attached_log_file() { + let _spawns = crate::no_child_spawns(); + let dir = temp_dir("path"); + let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); + assert_eq!(logger.path(), None, "nothing is written before a file is attached"); + let path = logger.attach_dir(&dir).expect("attach"); + assert_eq!(path, dir.join(LOG_FILE)); + assert_eq!(logger.path(), Some(path)); + drop(logger); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn the_default_filter_shows_photocraft_info_and_other_crates_warnings() { let f = Filter::parse(DEFAULT_FILTER); diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 9f89afc604..2a83b78ce5 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -66,6 +66,7 @@ mod services; // macOS gets one instance from LaunchServices (open-documents Apple events). #[cfg(any(not(target_os = "macos"), test))] mod single_instance; +mod startup_report; // Tablet support (macOS AppKit monitor, Linux X11/Wayland, Windows barrel button). mod tablet; mod ui_state; @@ -285,12 +286,19 @@ fn control_setup( cli_port: Option, auth: photocraft_automation::args::ControlArgs, automation: &photocraft_automation::args::AutomationArgs, -) -> Option<(u16, String, photocraft_automation::workspace::AuthorizedWorkspace)> { +) -> Option<(std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace)> { let (port, warning) = control_port_for(cli_port, &integrations(services::prefs_file().as_deref())); if let Some(warning) = &warning { eprint!("{warning}"); } let port = port?; + let listener = match std::net::TcpListener::bind(("127.0.0.1", port)) { + Ok(listener) => listener, + Err(error) => { + eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {error}"); + std::process::exit(2); + } + }; let (supplied, token_file) = (auth.control_token, auth.control_token_file); let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) { Ok(token) => token, @@ -313,7 +321,7 @@ fn control_setup( std::process::exit(2); } }; - Some((port, token, workspace)) + Some((listener, token, workspace)) } /// Record this start's backend in the GPU startup marker, if the marker is locked. @@ -385,12 +393,14 @@ fn main() -> eframe::Result { #[cfg(target_os = "macos")] let _ = (new_instance, &launch_options); + // Bind and authenticate the authorized control listener before display/GPU initialization. + let control = control_setup(control_port, auth, &automation); + #[cfg(target_os = "linux")] let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok()); #[cfg(target_os = "linux")] let session = linux_display_session(); - let control = control_setup(control_port, auth, &automation); // Finder / Dock / Open With deliver files as Apple events, not arguments; catch the one that // launched us as well as later ones. Lives until the event loop returns. #[cfg(target_os = "macos")] @@ -473,6 +483,10 @@ fn main() -> eframe::Result { log::info!("GPU startup: {:?} ({sentinel_ms:.2} ms)", plan); let retry_cpu = !safe_gpu && plan.backend != photocraft_engine::prefs::GpuBackend::Cpu; let keep_marker = gpu_startup::keep_marker_after_error(&plan, os); + // For the failure dialog below: the plan itself moves into the window closure. With + // `WGPU_BACKEND` set (`plan.env`) wgpu picks the backend, so name that rather than `auto`. + let started_renderer = plan.env.clone().unwrap_or_else(|| plan.backend.name().to_string()); + let started_note = plan.reason.clone(); let app_created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let created_in_callback = app_created.clone(); let started_sentinel = sentinel.clone(); @@ -599,8 +613,8 @@ fn main() -> eframe::Result { log::warn!("couldn't remember GPU backend {}: {e}", b.name()); } }); - if let Some((port, token, _)) = control { - let rx = control_server::start(port, token, cc.egui_ctx.clone()); + if let Some((listener, token, _)) = control { + let rx = control_server::start(listener, token, cc.egui_ctx.clone()); app = app.with_control(rx); } #[cfg(target_os = "macos")] @@ -710,6 +724,16 @@ fn main() -> eframe::Result { } } } + // A launch that fails before a window exists leaves nothing on screen, and a desktop launch + // has no console for the `Err` above: log it, then say why in a native dialog with the log + // file to attach (#7643). A terminal or automation launch can read standard error or the + // exit status instead, so it keeps the silent exit. + if let Err(error) = &result { + log::error!("PhotoCraft could not start: {error}"); + if startup_report::needs_dialog(control_port.is_some()) { + startup_report::show(&error.to_string(), &started_renderer, started_note.as_deref(), logger.and_then(logging::AppLogger::path).as_deref()); + } + } result } diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 7dec44483b..09d40d2cde 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -92,6 +92,7 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("OpenRaster", &["ora"]), ("PNG", &["png"]), ("JPEG", &["jpg", "jpeg"]), + ("JPEG XL", &["jxl"]), ("WebP", &["webp"]), ("TIFF", &["tif", "tiff"]), ("Targa", &["tga"]), diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index 6197d2ba12..8f12fee908 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -312,10 +312,15 @@ fn save_as_offers_only_writable_formats_including_ico() { let subtype = name.rsplit('.').next().unwrap_or_default(); assert!(!filters.iter().any(|(_, exts)| exts.iter().any(|e| e == subtype)), "{name}: .{subtype} is offered"); } - // File › Open lists every file Save As writes, also in that format's own type (PDF is written - // but not read yet). + // File Open lists readable Save As formats in their own type. Export-only formats must + // stay absent from both Open filters rather than advertising an unavailable decoder. for (name, exts) in SAVE_FILTERS { for ext in exts.iter().filter(|e| **e != "pdf") { + if photocraft_codecs::from_extension(ext).is_some_and(|format| !format.caps().read) { + assert!(!OPEN_EXTS.contains(ext), "{name}: export-only .{ext} must not appear in All Formats"); + assert!(!OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: export-only .{ext} must not appear in an Open type"); + continue; + } assert!(OPEN_EXTS.contains(ext), "{name}: Open's All Formats lacks .{ext}"); assert!(OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: no Open type lists .{ext}"); } diff --git a/apps/photocraft/src/startup_report.rs b/apps/photocraft/src/startup_report.rs new file mode 100644 index 0000000000..554b99dea0 --- /dev/null +++ b/apps/photocraft/src/startup_report.rs @@ -0,0 +1,104 @@ +//! Telling the user why a launch failed when there is no window to say it in (#7643). +//! +//! A desktop launch has no console — release builds are GUI-subsystem apps on Windows — so the +//! `Err` that ends `main` used to vanish and PhotoCraft "just closed". This shows one native +//! dialog with the error, the renderer that was tried and the log file to attach. The text is +//! English diagnostics, like Help › System Info, so a bug report reads the same in every language. +//! +//! Terminal and automation launches keep the old behaviour: they can read standard error or the +//! exit status, and a modal dialog would leave a script waiting. + +use std::io::IsTerminal; +use std::path::Path; + +/// Whether a failed launch needs the dialog: no terminal under standard error, no control client +/// (an agent launch reads the exit status instead of clicking OK), and a screen to put it on. +pub fn dialog_wanted(stderr_is_terminal: bool, automation: bool, display: bool) -> bool { + !stderr_is_terminal && !automation && display +} + +/// Whether this launch asks for the dialog (see [`dialog_wanted`]). +pub fn needs_dialog(automation: bool) -> bool { + dialog_wanted(std::io::stderr().is_terminal(), automation, has_display()) +} + +/// Whether there is a screen for a dialog: always on Windows and macOS; on Linux a headless box +/// (a CI runner, an SSH session — `startup_without_display` removes both variables) has none. +fn has_display() -> bool { + #[cfg(target_os = "linux")] + { + ["DISPLAY", "WAYLAND_DISPLAY"].iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())) + } + #[cfg(not(target_os = "linux"))] + { + true + } +} + +/// The dialog's text: the error, the renderer that was tried and why it wasn't the preference, +/// the version and, when one was opened, the log file. +pub fn text(error: &str, renderer: &str, note: Option<&str>, version: &str, log: Option<&Path>) -> String { + let mut text = format!("PhotoCraft could not start.\n\n{error}\n\nRenderer: {renderer}"); + if let Some(note) = note { + text.push_str(&format!("\nStartup: {note}")); + } + text.push_str(&format!("\nVersion: {version}")); + if let Some(path) = log { + text.push_str(&format!("\nLog file: {}", path.display())); + } + text +} + +/// Show [`text`] in a native error dialog. Called after the event loop returned, so nothing is +/// repainting and the launch was about to fail anyway. +pub fn show(error: &str, renderer: &str, note: Option<&str>, log: Option<&Path>) { + let version = photocraft_engine::build_info::long_version(); + let body = text(error, renderer, note, &version, log); + log::info!("showing the startup-failure dialog"); + let _ = rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Error) + .set_title(photocraft_ui_egui::i18n::t("PhotoCraft could not start")) + .set_description(body) + .set_buttons(rfd::MessageButtons::Ok) + .show(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_desktop_launch_asks_the_user_and_a_script_does_not() { + assert!(dialog_wanted(false, false, true), "no console: the error would vanish"); + assert!(!dialog_wanted(true, false, true), "a terminal shows the error itself"); + assert!(!dialog_wanted(false, true, true), "an automation client reads the exit status"); + assert!(!dialog_wanted(false, false, false), "a headless launch has no screen for a dialog"); + } + + #[test] + fn the_text_names_the_error_renderer_version_and_log() { + let log = Path::new("/home/me/.config/photocraft/logs/photocraft.log"); + let body = text("no adapter for Vulkan", "dx12", None, "0.15.1 (abc1234)", Some(log)); + for part in [ + "could not start", + "no adapter for Vulkan", + "Renderer: dx12", + "Version: 0.15.1 (abc1234)", + "Log file: /home/me/.config/photocraft/logs/photocraft.log", + ] { + assert!(body.contains(part), "{part:?} missing from {body:?}"); + } + assert!(!body.contains("Startup:"), "no fallback to explain: {body:?}"); + // A start whose log file could not be created says so by leaving the line out. + assert!(!text("boom", "cpu", None, "0.15.1", None).contains("Log file:")); + } + + /// A crash fallback is the confusing case: the app picks a renderer the user never chose, so + /// the dialog has to say why as well as which. + #[test] + fn a_fallback_that_was_not_the_preference_is_explained() { + let note = "the previous start didn't finish on vulkan; using dx12"; + let body = text("device lost", "dx12", Some(note), "0.15.1", None); + assert!(body.contains(&format!("Renderer: dx12\nStartup: {note}\n")), "{body:?}"); + } +} diff --git a/apps/photocraft/tests/it/control_exit_code.rs b/apps/photocraft/tests/it/control_exit_code.rs index 4be624c5d2..98c3243133 100644 --- a/apps/photocraft/tests/it/control_exit_code.rs +++ b/apps/photocraft/tests/it/control_exit_code.rs @@ -2,8 +2,7 @@ //! status 0 believes the control server is running when it is not. //! //! These tests run the real binary as a subprocess and assert the exit code, -//! covering both failure paths in `main.rs`: control authentication and the -//! automation workspace. +//! covering control authentication, the automation workspace and listener binding. /// A syntactically valid 64-hex-char token, so the workspace test reaches the /// workspace check instead of failing on token validation first. @@ -28,7 +27,7 @@ fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run { let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let output = std::process::Command::new(crate::binary()) + let mut child = std::process::Command::new(crate::binary()) .args(args) .env("PHOTOCRAFT_CONFIG_DIR", &dir) // Isolate from the host environment so the test is reproducible. @@ -41,12 +40,38 @@ fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run { .env_remove("WAYLAND_DISPLAY") .env_remove("WAYLAND_SOCKET") .envs(vars.iter().copied()) - .output() + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() .expect("failed to run photocraft binary"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + let timed_out = loop { + if child.try_wait().unwrap().is_some() { + break false; + } + if std::time::Instant::now() >= deadline { + child.kill().unwrap(); + break true; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + }; + let output = child.wait_with_output().unwrap(); + let gpu_started = dir.join("gpu-starting.json").exists(); std::fs::remove_dir_all(&dir).ok(); + assert!(!timed_out, "PhotoCraft did not exit: {}", String::from_utf8_lossy(&output.stderr)); + assert!(!gpu_started, "control setup errors must exit before GPU startup"); Run { status: output.status, stderr: String::from_utf8_lossy(&output.stderr).into_owned() } } +#[test] +fn an_occupied_control_port_exits_with_status_2() { + let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = held.local_addr().unwrap().port().to_string(); + let Run { status, stderr } = run_photocraft(&["--control", &port, "--control-token", VALID_TOKEN]); + assert_eq!(status.code(), Some(2), "occupied control port must exit 2, stderr: {stderr}"); + assert!(stderr.contains(&format!("failed to bind 127.0.0.1:{port}")), "stderr: {stderr}"); +} + #[test] fn invalid_control_token_exits_with_status_2() { // `validate_token` rejects a token that is not exactly 64 hex characters. diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 8ddb66f093..b1ce53b3d8 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -17,8 +17,8 @@ Exactly three colours: ## Geometry A 512-unit tile (`viewBox="0 0 512 512"`), rounded square with `rx=112`, no border. The macOS -renders pad it onto Apple's 824/1024 icon grid; the Windows and Linux renders crop 22 units off -each side so the figure reads at 16–48 px. +renders pad it onto Apple's 824/1024 icon grid; the Windows and Linux renders use the whole tile, +as the other Crafting Apps do. ## Provenance diff --git a/assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png index a28597fc9b..9f65c1fec1 100644 Binary files a/assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/16x16/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/16x16/apps/ai.storyteller.photocraft.png index ec4cb49675..02e1b9886a 100644 Binary files a/assets/app-icon/hicolor/16x16/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/16x16/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/24x24/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/24x24/apps/ai.storyteller.photocraft.png index 249b94787b..4b321d2bf5 100644 Binary files a/assets/app-icon/hicolor/24x24/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/24x24/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png index db2eb42d8a..b707a2fa91 100644 Binary files a/assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/32x32/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/32x32/apps/ai.storyteller.photocraft.png index ad50ecb450..3694573349 100644 Binary files a/assets/app-icon/hicolor/32x32/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/32x32/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/48x48/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/48x48/apps/ai.storyteller.photocraft.png index 341185fdd8..d2ed2d865e 100644 Binary files a/assets/app-icon/hicolor/48x48/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/48x48/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/512x512/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/512x512/apps/ai.storyteller.photocraft.png index e54f75c920..ba0bee419e 100644 Binary files a/assets/app-icon/hicolor/512x512/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/512x512/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png b/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png index e093144cf2..b5cbfd4fa0 100644 Binary files a/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png and b/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png differ diff --git a/assets/app-icon/photocraft.ico b/assets/app-icon/photocraft.ico index 88c8a0adad..7d4d947f11 100644 Binary files a/assets/app-icon/photocraft.ico and b/assets/app-icon/photocraft.ico differ diff --git a/assets/icons/path-op-combine.svg b/assets/icons/path-op-combine.svg new file mode 100644 index 0000000000..4c60a71e25 --- /dev/null +++ b/assets/icons/path-op-combine.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/path-op-exclude.svg b/assets/icons/path-op-exclude.svg new file mode 100644 index 0000000000..e2bea5b413 --- /dev/null +++ b/assets/icons/path-op-exclude.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/path-op-intersect.svg b/assets/icons/path-op-intersect.svg new file mode 100644 index 0000000000..a6bca9787e --- /dev/null +++ b/assets/icons/path-op-intersect.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/assets/icons/path-op-merge.svg b/assets/icons/path-op-merge.svg new file mode 100644 index 0000000000..32dbe69ffe --- /dev/null +++ b/assets/icons/path-op-merge.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/path-op-new-layer.svg b/assets/icons/path-op-new-layer.svg new file mode 100644 index 0000000000..21b26eac87 --- /dev/null +++ b/assets/icons/path-op-new-layer.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/path-op-subtract.svg b/assets/icons/path-op-subtract.svg new file mode 100644 index 0000000000..c461ac44ad --- /dev/null +++ b/assets/icons/path-op-subtract.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/rotate-ccw.svg b/assets/icons/rotate-ccw.svg new file mode 100644 index 0000000000..988d5fe949 --- /dev/null +++ b/assets/icons/rotate-ccw.svg @@ -0,0 +1,14 @@ + + + + diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md index e1a2cc23fa..13ab740a86 100644 --- a/book/src/formats/raster-formats.md +++ b/book/src/formats/raster-formats.md @@ -1,11 +1,23 @@ # Raster formats -`photocraft-codecs` provides format detection, capability declarations, decode limits, metadata handling, and encoding for flat images. The default build declares read/write support for PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, Netpbm/PFM, QOI, OpenEXR, and Radiance HDR. HEIF/HEIC (iPhone and Mac photos) is read-only, decoded in pure Rust by `heic-rs` through the optional `photocraft-heif` crate. It is a build-time choice behind the `heif` cargo feature (`cargo build -p photocraft --features heif`): official builds include it; without it HEIC files are still recognised and opening one reports that HEIC support isn't included in that build. AVIF encoding is optional; AVIF decoding is not implemented in the current crate. +`photocraft-codecs` provides format detection, capability declarations, decode limits, metadata handling, and encoding for flat images. The default build declares read/write support for PNG, JPEG, TIFF, WebP, GIF, BMP, TGA, ICO, Netpbm/PFM, QOI, OpenEXR, and Radiance HDR. HEIF/HEIC (iPhone and Mac photos) is read-only, decoded in pure Rust by `heic-rs` through the optional `photocraft-heif` crate. It is a build-time choice behind the `heif` cargo feature (`cargo build -p photocraft --features heif`): official builds include it; without it HEIC files are still recognised and opening one reports that HEIC support isn't included in that build. AVIF encoding is optional; AVIF decoding is not implemented in the current crate. Lossless JPEG XL (.jxl) export uses the pure-Rust `zune-jpegxl` encoder for 8/16-bit gray, RGB and RGBA data; gray+alpha is expanded to RGBA at the same bit depth. JPEG XL import is tracked separately in #2868. ## Layered TIFF A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `photocraft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: up to sixteen extra samples (spot colours and alpha channels, plus a Quick Mask) are written in the IFD and round-trip, with Photoshop image resources for the channel name, ink colour and solidity; Lab documents are saved flat, with their extra samples. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling. Scripted and agent saves write a flat TIFF unless they ask for layers: `--tiff-layers` for `photocraft-cli convert`, `run` and `batch`, and `"tiffLayers": true` in the save, batch and export commands and MCP `doc_save`. +## JPEG XL + +Save As, Export As and the CLI can write a lossless, single-image `.jxl` bare +codestream at 8 or 16 bits per sample. Gray, RGB and RGBA are encoded +natively. Grayscale with alpha is expanded to RGBA at the original bit depth +to preserve both grayscale and alpha samples. For 16-bit RGBA the encoder's +incorrect default 8-bit alpha header is corrected to explicitly describe +16-bit alpha, with an independent decoder oracle checking alpha values. +The bare codestream has no ICC, EXIF, XMP or DPI boxes; the export path +converts tagged RGB to sRGB and surfaces metadata losses as fidelity warnings. +JPEG XL opening remains under review in #2868. + ## WebP Lossless WebP (VP8L) is encoded and decoded by `image-webp`. Lossy WebP is written by PhotoCraft's own VP8 key-frame encoder in `crates/codecs/src/codecs/vp8`, a clean-room implementation of RFC 6386: BT.601 4:2:0 conversion, 16×16 and 4×4 intra prediction chosen per macroblock by reconstruction error, the forward DCT and Walsh-Hadamard transforms paired with the bit-exact inverse transforms, quantisation on the RFC's `dc_qlookup`/`ac_qlookup` tables, token coding with per-frame probability updates, and skipped macroblocks for flat areas. `EncodeOptions::webp_lossless` picks the encoder and `webp_quality` (0–100, the libwebp scale) sets the quantiser; alpha travels losslessly in an `ALPH` chunk and ICC/EXIF/XMP in their own chunks of the extended (`VP8X`) container. The decoder applies the frame's loop filter; no C library is involved on either side. diff --git a/crates/affinity/src/access.rs b/crates/affinity/src/access.rs index 732feeef49..a93ec84462 100644 --- a/crates/affinity/src/access.rs +++ b/crates/affinity/src/access.rs @@ -23,10 +23,7 @@ impl Stream { /// The raw slot count of an object's array field (including null slots), for charging /// traversal work before nulls are filtered out. `None` when the field is not an array. pub fn array_len(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Array(a) => Some(a.len()), - _ => None, - } + self.field(id, tag)?.array_len() } /// A child object (shared, linked or inline); `None` for null or missing. diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index fa45cf6213..0c1a871b27 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -153,8 +153,8 @@ pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option { let fields: Vec<&Value> = s.positional(c).collect(); // The corner arrays are scanned for every occurrence of a shared curve, so charge // them like records before they are walked. - if let Some(Value::Array(idx)) = fields.get(1) - && let Err(reason) = r.geometry_budget.records(idx.len()) + if let Some(len) = fields.get(1).and_then(|v| v.array_len()) + && let Err(reason) = r.geometry_budget.records(len) { r.warn(reason); return None; @@ -170,17 +170,23 @@ pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option { Value::Bool(b) => *b, _ => return None, }; - let Value::Array(records) = fields.next()? else { return None }; - seen = seen.checked_add(records.len())?; + let records = fields.next()?; + let len = records.array_len()?; + seen = seen.checked_add(len)?; if seen > MAX_NODES { r.warn("curves with more than four million nodes"); return None; } - if let Err(reason) = r.geometry_budget.records(records.len()) { + if let Err(reason) = r.geometry_budget.records(len) { r.warn(reason); return None; } - let anchors = anchors(records)?; + let anchors = match records { + Value::Array(a) => anchors(a.iter().map(record)), + Value::Records { size: 18, data } => anchors(data.as_chunks::<18>().0.iter().map(record18)), + // Records of another width are no curve nodes. + _ => anchors(std::iter::repeat_n(None, len)), + }?; let radii = if index == 0 { corners.as_ref() } else { None }; if let Some(sp) = subpath(&anchors, closed, radii) { path.subpaths.push(sp); @@ -202,22 +208,24 @@ struct Anchor { fn record(v: &Value) -> Option<(Point, u8)> { let Value::Bytes(b) = v else { return None }; - if b.len() != 18 { - return None; - } - let x = f64::from_le_bytes(b.get(0..8)?.try_into().ok()?); - let y = f64::from_le_bytes(b.get(8..16)?.try_into().ok()?); + record18(b.as_slice().try_into().ok()?) +} + +/// One 18-byte curve node: f64 x, f64 y, u8 kind, u8 role. +fn record18(b: &[u8; 18]) -> Option<(Point, u8)> { + let x = f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]); + let y = f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]); if !x.is_finite() || !y.is_finite() { return None; } - Some((Point { x, y }, *b.get(17)?)) + Some((Point { x, y }, b[17])) } -fn anchors(records: &[Value]) -> Option> { +fn anchors(records: impl ExactSizeIterator>) -> Option> { let mut out: Vec = Vec::with_capacity(records.len() / 3 + 1); let mut pending_in = None; - for (i, v) in records.iter().enumerate() { - let (p, role) = record(v)?; + for (i, v) in records.enumerate() { + let (p, role) = v?; match role { 0 => { out.push(Anchor { p, inh: pending_in.take(), out: None, record: i }); diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs index c59afa1cac..3d74333111 100644 --- a/crates/affinity/src/model.rs +++ b/crates/affinity/src/model.rs @@ -300,6 +300,9 @@ pub fn read(bytes: &[u8], limits: Limits) -> Result { let mut archive = Archive::open(bytes, limits)?; let doc = archive.read("doc.dat")?; let s = stream::parse(&doc)?; + // The parsed stream owns copies of everything it needs: do not hold the inflated bytes + // (hundreds of MB for a large vector document) while the model is built. + drop(doc); Reader::new(&s, &mut archive, limits).document() } diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index 1847fad90f..904f642123 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -129,11 +129,16 @@ const MAX_STOPS: usize = 1024; fn floats(v: &Value) -> Option> { match v { Value::Floats(f) => Some(f.clone()), - Value::Bytes(b) if b.len() % 4 == 0 => Some(b.as_chunks::<4>().0.iter().map(|c| f64::from(f32::from_le_bytes(*c))).collect()), + Value::Bytes(b) if b.len() % 4 == 0 => Some(f32_samples(b)), _ => None, } } +/// Little-endian `f32` samples widened to `f64`. +fn f32_samples(b: &[u8]) -> Vec { + b.as_chunks::<4>().0.iter().map(|c| f64::from(f32::from_le_bytes(*c))).collect() +} + /// Spot colours defined through spot colours. A spot colour (`Pant`) is read through its RGB /// equivalent, else its base colour, which in real files hold plain colours. Colours are shared /// objects, so one can link to itself, and with both links followed at every level a colour read @@ -241,6 +246,9 @@ pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option> = match s.field(grad, b"Posn") { Some(Value::Array(a)) => a.iter().filter_map(floats).take(MAX_STOPS).collect(), + Some(Value::Records { size, data }) if *size % 4 == 0 && *size > 0 => { + data.chunks_exact(usize::from(*size)).map(f32_samples).take(MAX_STOPS).collect() + } _ => Vec::new(), }; let mut stops = Vec::new(); diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs index 7c7d47017b..348fc6540a 100644 --- a/crates/affinity/src/stream.rs +++ b/crates/affinity/src/stream.rs @@ -53,6 +53,23 @@ pub enum Value { /// `None` is a null object. Obj(Option), Array(Vec), + /// An array of fixed-size records (`0x2c`, curve nodes) held in one buffer: `size` bytes each. + /// Counts as one value per record against [`MAX_VALUES`], like the array of `Bytes` it replaces. + Records { + size: u16, + data: Vec, + }, +} + +impl Value { + /// Slot count of an array field (including null slots); `None` for a scalar. + pub fn array_len(&self) -> Option { + match self { + Value::Array(a) => Some(a.len()), + Value::Records { size, data } => Some(data.len() / usize::from(*size).max(1)), + _ => None, + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -73,39 +90,50 @@ pub struct Object { pub chain: Vec, /// Fields in stream order; positional fields have tag 0. pub fields: Vec<(Tag, Value)>, - /// First-occurrence index of each non-positional tag, so `get` is O(1). A shared object - /// can be referenced by many sibling layers, and each reference used to rescan all of its - /// fields; indexing once keeps repeated lookups from multiplying into quadratic work. - index: std::collections::HashMap, + /// Index for objects with more than [`SCAN`] fields: (tag, index of its first occurrence) + /// sorted by tag, so `get` is a binary search. A shared object can be referenced by many + /// sibling layers, and each reference used to rescan all of its fields; indexing once keeps + /// repeated lookups from multiplying into quadratic work. Smaller objects have no index + /// (and no per-object hash map to build): scanning a handful of fields is cheaper. + index: Vec<(Tag, u32)>, +} + +/// Objects with at most this many fields are scanned instead of indexed. +const SCAN: usize = 12; + +fn build_index(fields: &[(Tag, Value)]) -> Vec<(Tag, u32)> { + if fields.len() <= SCAN { + return Vec::new(); + } + // Positional fields share tag 0 and are not looked up by tag. Sorting by (tag, index) and + // keeping the first of each tag preserves first-match semantics. + let mut index: Vec<(Tag, u32)> = fields.iter().zip(0u32..).filter(|((t, _), _)| t.0 != 0).map(|((t, _), i)| (*t, i)).collect(); + index.sort_unstable(); + index.dedup_by_key(|e| e.0); + index } impl Object { pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { - let mut index = std::collections::HashMap::with_capacity(fields.len()); - for (i, (t, _)) in fields.iter().enumerate() { - // Positional fields share tag 0 and are not looked up by tag; keep first-match - // semantics for real tags. - if t.0 != 0 { - index.entry(*t).or_insert(i); - } - } + let index = build_index(&fields); Object { class, kind, chain, fields, index } } pub fn get(&self, tag: Tag) -> Option<&Value> { - self.index.get(&tag).map(|&i| &self.fields[i].1) + if tag.0 == 0 { + return None; + } + if self.fields.len() <= SCAN { + return self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v); + } + let at = self.index.binary_search_by_key(&tag, |e| e.0).ok()?; + self.index.get(at).and_then(|&(_, i)| self.fields.get(i as usize)).map(|(_, v)| v) } /// Replaces the fields (the root object is filled in after it is pushed) and rebuilds the /// tag index so `get` stays correct. fn set_fields(&mut self, fields: Vec<(Tag, Value)>) { - self.index.clear(); - self.index.reserve(fields.len()); - for (i, (t, _)) in fields.iter().enumerate() { - if t.0 != 0 { - self.index.entry(*t).or_insert(i); - } - } + self.index = build_index(&fields); self.fields = fields; } } @@ -336,11 +364,13 @@ impl Parser<'_> { if size == 0 || n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) { return Err(Error::Malformed("array longer than its data")); } - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Bytes(self.c.take(size)?.to_vec())); - } - Ok(Value::Array(v)) + // Still one value per record against the budget, but a single allocation. + self.spend(n)?; + let bytes = self.c.take(n * size)?; + let mut data = Vec::new(); + data.try_reserve_exact(bytes.len()).map_err(|_| Error::Limit("not enough memory for the document stream"))?; + data.extend_from_slice(bytes); + Ok(Value::Records { size: size as u16, data }) } 0x32 => { let n = self.count(1)?; diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index af788d60de..021b532529 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -757,3 +757,42 @@ mod spot_colours { assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); } } + +/// Object lookup and record arrays against the structures they replaced. +mod stream_storage { + use crate::stream::{self, Kind, Object, Tag, Value}; + use crate::synth::{self, F, tag}; + + /// The per-object map `Object::get` used before: first occurrence of each real tag. + fn reference(fields: &[(Tag, Value)], t: Tag) -> Option<&Value> { + let mut index = std::collections::HashMap::new(); + for (i, (ft, _)) in fields.iter().enumerate() { + if ft.0 != 0 { + index.entry(*ft).or_insert(i); + } + } + index.get(&t).map(|&i| &fields[i].1) + } + + #[test] + fn lookup_keeps_first_match_for_every_object_size() { + for n in 0..60u32 { + // Tags repeat (n % 7 distinct tags) and every fifth field is positional (tag 0). + let fields: Vec<(Tag, Value)> = (0..n).map(|i| (if i % 5 == 0 { Tag(0) } else { Tag(100 + i % 7) }, Value::UInt(u64::from(i)))).collect(); + let object = Object::new(Tag(1), Kind::Inline, vec![Tag(1)], fields.clone()); + for t in 0..120 { + assert_eq!(object.get(Tag(t)), reference(&fields, Tag(t)), "{n} fields, tag {t}"); + } + } + } + + #[test] + fn a_fixed_size_array_is_one_buffer_and_one_value_per_record() { + let records: Vec = (0..18 * 5).map(|i| i as u8).collect(); + let bytes = synth::stream(&[(tag(b"Nods"), F::Records(18, records.chunks(18).map(<[u8]>::to_vec).collect()))]); + let s = stream::parse(&bytes).unwrap(); + let root = s.object(s.root).unwrap(); + assert_eq!(root.get(Tag::of(b"Nods")), Some(&Value::Records { size: 18, data: records })); + assert_eq!(root.get(Tag::of(b"Nods")).and_then(Value::array_len), Some(5)); + } +} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index eb52cda436..96c11b4805 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -55,7 +55,7 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { _ => bounds.x0, }; if !artistic { - if s.objs(frame, b"ColW").len() > 1 || matches!(s.field(frame, b"ColW"), Some(Value::Array(a)) if a.len() > 1) { + if s.objs(frame, b"ColW").len() > 1 || s.array_len(frame, b"ColW").is_some_and(|n| n > 1) { r.warn("text frames with several columns (imported as one column)"); } if s.class(id) == Some(crate::stream::Tag::of(b"TxtC")) { diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs index ca346a1f05..4143b30657 100644 --- a/crates/algo/src/artistic_fx.rs +++ b/crates/algo/src/artistic_fx.rs @@ -17,6 +17,7 @@ use photocraft_geom::Rect; use crate::Ctx; use crate::artistic::GalleryEffect; use crate::artistic::GalleryFilter as F; +use crate::cutout; use crate::fxutil::{box_blur_n, cell_point, gauss_blur_n, gauss_box_radii, rgba, set_rgba}; use crate::image::Image; use crate::noise::hash01; @@ -409,7 +410,8 @@ pub(crate) fn effect_reach(e: &GalleryEffect) -> i32 { let g = |k: &str| e.get(k); match e.filter { F::ColoredPencil => 2, - F::Cutout => gs(cutout_sigma(e)), + // Traced over the whole image before tiling (see [`Prepared`]). + F::Cutout => 0, F::DryBrush | F::Fresco => kuwahara_reach(1 + g("brushSize") as usize) + gs(1.0) + 2, F::FilmGrain | F::DiffuseGlow | F::ChalkCharcoal | F::Reticulation | F::Grain | F::MosaicTiles | F::Texturizer => 0, F::RoughPastels => gs(0.6 + 1.2) + ((2.0 + g("strokeLength")) / 2.0) as i32 + 3, @@ -451,8 +453,8 @@ pub(crate) fn effect_reach(e: &GalleryEffect) -> i32 { } } -fn cutout_sigma(e: &GalleryEffect) -> f32 { - 0.5 + e.get("edgeSimplicity") * (1.1 - 0.3 * e.get("edgeFidelity")) +fn cutout_settings(e: &GalleryEffect) -> cutout::Settings { + cutout::Settings { levels: e.get("numberOfLevels").round().clamp(2.0, 8.0) as usize, simplicity: e.get("edgeSimplicity"), fidelity: e.get("edgeFidelity") } } /// Halftone Pattern's screen spacing in pixels (about 3.5 at Size 1, 25.5 at 12). fn halftone_cell(e: &GalleryEffect) -> f32 { @@ -541,6 +543,54 @@ pub(crate) fn run(effects: &[GalleryEffect], src: &Image, out: Rect, ctx: &Ctx) for e in effects { apply(e, &mut win, ctx); } + finish(&win, src, out, ctx) +} + +/// Whether a stack needs the whole image at once (Cutout traces it). +pub(crate) fn is_global(effects: &[GalleryEffect]) -> bool { + effects.iter().any(|e| e.filter == F::Cutout) +} + +/// A stack with a Cutout, prepared once for all tiles: the effects up to the last Cutout run +/// over the whole image and it is traced; each tile then only fills in the traced shapes and +/// runs the effects after it. +pub(crate) struct Prepared { + traced: cutout::Traced, + rest: Vec, +} + +impl Prepared { + /// `None` for a stack that has no Cutout (it runs tile by tile as usual). + pub(crate) fn new(effects: &[GalleryEffect], src: &Image, ctx: &Ctx) -> Option { + let last = effects.iter().rposition(|e| e.filter == F::Cutout)?; + let r = src.rect; + let (w, h) = (r.width() as usize, r.height() as usize); + let mut win = Win { r, w, h, c: src.data.chunks_exact(src.ch).map(|px| rgb(rgba(ctx, px))).collect() }; + for e in effects.get(..last).unwrap_or_default() { + apply(e, &mut win, ctx); + } + let traced = cutout::trace(&win.c, r, &cutout_settings(effects.get(last)?)); + Some(Prepared { traced, rest: effects.get(last + 1..).unwrap_or_default().to_vec() }) + } + + /// The stack's result over `out` (`src` is the image it was prepared from). + pub(crate) fn run(&self, src: &Image, out: Rect, ctx: &Ctx) -> Vec { + let r = out.inflate(reach(&self.rest)).intersect(&src.rect); + let (w, h) = (r.width() as usize, r.height() as usize); + if w == 0 || h == 0 { + return src.crop(out); + } + let mut win = Win { r, w, h, c: self.traced.render(r) }; + for e in &self.rest { + apply(e, &mut win, ctx); + } + finish(&win, src, out, ctx) + } +} + +/// `out` of the source with its colour from `win` (alpha kept). +fn finish(win: &Win, src: &Image, out: Rect, ctx: &Ctx) -> Vec { + let n = src.ch; let mut res = src.crop(out); let ow = out.width() as usize; for (i, px) in res.chunks_exact_mut(n).enumerate() { @@ -585,16 +635,7 @@ fn apply_artistic(e: &GalleryEffect, win: &mut Win) -> bool { win.c[i] = mix(paper, map(win.c[i], |v| v * 0.88), cov); } } - F::Cutout => { - blur3(&mut win.c, w, h, cutout_sigma(e)); - let levels = g("numberOfLevels").round(); - for p in &mut win.c { - // Flat tones per luminance level, keeping each region's hue. - let l = lum(p).max(1e-4); - let k = posterize(l, levels) / l; - *p = map(*p, |v| posterize(clamp01(v * k), levels * 2.0)); - } - } + F::Cutout => win.c = cutout::trace(&win.c, win.r, &cutout_settings(e)).render(win.r), F::DryBrush | F::Fresco => { let fresco = e.filter == F::Fresco; kuwahara(win, 1 + g("brushSize") as usize); @@ -1344,7 +1385,7 @@ mod tests { let fp = FilterParams::FilterGallery { effects: vec![e.clone()] }; apply_tiled(&s, &fp, b, b, None, tile, Some(b)).read_region(b) }; - for f in [G::RoughPastels, G::AngledStrokes] { + for f in [G::RoughPastels, G::AngledStrokes, G::Cutout] { let base = run(&GalleryEffect::new(f), 256); for prm in f.params() { let crate::GalleryParamKind::Range { min, max, .. } = prm.kind else { continue }; @@ -1361,6 +1402,98 @@ mod tests { } } + /// Runs one Cutout over a grey image given as rows of values; returns the red channel. + fn cutout_on(rows: &[Vec], set: &[(&str, f32)]) -> Vec> { + let (w, h) = (rows[0].len() as i32, rows.len() as i32); + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true)); + for (y, row) in rows.iter().enumerate() { + for (x, v) in row.iter().enumerate() { + s.write_pixel(x as i32, y as i32, &[*v, *v, *v, 1.0]); + } + } + let mut e = GalleryEffect::new(crate::GalleryFilter::Cutout); + for (k, v) in set { + e.set(k, *v); + } + let b = Rect::new(0, 0, w, h); + let out = apply_tiled(&s, &FilterParams::FilterGallery { effects: vec![e] }, b, b, None, 256, Some(b)).read_region(b); + out.chunks(4 * w as usize).map(|r| r.chunks(4).map(|p| p[0]).collect()).collect() + } + + #[test] + fn cutout_makes_flat_shapes_with_clean_edges() { + // It used to posterize every pixel after a blur: noise survived as speckle, edges were + // ragged and smooth gradients banded instead of becoming flat paper. + let noisy: Vec> = (0..32).map(|y| (0..64).map(|x| if x < 32 { 0.2 } else { 0.8 } + (hash01(x, y, 0, 7) - 0.5) * 0.16).collect()).collect(); + let out = cutout_on(&noisy, &[]); + for (x0, x1) in [(2, 28), (36, 62)] { + let vals: Vec = (2..30).flat_map(|y| out[y][x0..x1].to_vec()).collect(); + let spread = vals.iter().fold(f32::MIN, |a, &v| a.max(v)) - vals.iter().fold(f32::MAX, |a, &v| a.min(v)); + assert!(spread < 1e-4, "a noisy area should be one flat tone, spread {spread}"); + } + // The cut is an anti-aliased pixel or two, not a blur. + for y in 0..32 { + let (lo, hi) = (out[y][16], out[y][48]); + let soft = out[y].iter().filter(|&&v| (v - lo).abs() > 0.01 && (v - hi).abs() > 0.01).count(); + assert!(soft <= 2, "row {y}: {soft} edge pixels"); + } + // A ramp becomes `numberOfLevels` flat steps (the palette is the image's own colours, so + // one may go to the wide flat margins and merge as noise). + let ramp: Vec> = (0..12).map(|_| (0..144).map(|x| ((x as f32 - 24.0) / 95.0).clamp(0.0, 1.0)).collect()).collect(); + for levels in [2.0, 5.0, 8.0] { + let row = &cutout_on(&ramp, &[("numberOfLevels", levels)])[6]; + let mut tones: Vec = Vec::new(); + for win in row.windows(3) { + if (win[0] - win[2]).abs() < 1e-4 && tones.last().is_none_or(|t| (t - win[1]).abs() > 1e-3) { + tones.push(win[1]); + } + } + assert!(tones.len() <= levels as usize && tones.len() + 1 >= levels as usize, "levels {levels}: tones {tones:?}"); + assert!(tones.windows(2).all(|t| t[0] < t[1]), "levels {levels}: tones {tones:?}"); + } + // Edge Simplicity drops specks. + let speck: Vec> = (0..32).map(|y| (0..32).map(|x| if (15..18).contains(&x) && (15..18).contains(&y) { 0.9 } else { 0.2 }).collect()).collect(); + let detailed = cutout_on(&speck, &[("edgeSimplicity", 0.0)]); + let simple = cutout_on(&speck, &[("edgeSimplicity", 10.0)]); + assert!(detailed[16][16] - detailed[2][2] > 0.5, "the speck should survive at simplicity 0"); + assert!((simple[16][16] - simple[2][2]).abs() < 1e-4, "the speck should go at simplicity 10"); + } + + #[test] + fn cutout_keeps_the_tone_of_surviving_islands_at_low_fidelity() { + for (size, simplicity) in [(2, 0.0), (3, 2.0), (4, 0.0), (4, 2.0), (6, 2.0)] { + let rows: Vec> = + (0..32).map(|y| (0..32).map(|x| if (12..12 + size).contains(&x) && (12..12 + size).contains(&y) { 0.9 } else { 0.2 }).collect()).collect(); + let reference = cutout_on(&rows, &[("edgeSimplicity", simplicity), ("edgeFidelity", 2.0)]); + let centre = 12 + size / 2; + for fidelity in [1.0, 1.5, 2.0] { + let out = cutout_on(&rows, &[("edgeSimplicity", simplicity), ("edgeFidelity", fidelity)]); + assert!( + size == 2 || (out[centre][centre] - reference[centre][centre]).abs() < 0.02, + "{size}x{size}, simplicity {simplicity}, fidelity {fidelity}: {} vs {}", + out[centre][centre], + reference[centre][centre] + ); + assert!(out[centre][centre] - out[2][2] > 0.5, "the island keeps its contrast"); + } + } + } + + #[test] + fn a_stack_around_a_cutout_is_tile_independent() { + // Effects before a Cutout are traced with it over the whole image; effects after it run + // per tile on the filled-in shapes. + use crate::GalleryFilter as G; + let b = Rect::new(0, 0, 56, 40); + let s = pattern(SampleType::F32); + let fp = + FilterParams::FilterGallery { effects: vec![GalleryEffect::new(G::Spatter), GalleryEffect::new(G::Cutout), GalleryEffect::new(G::GlowingEdges)] }; + let a = apply_tiled(&s, &fp, b, b, None, 256, Some(b)).read_region(b); + let t = apply_tiled(&s, &fp, b, b, None, 16, Some(b)).read_region(b); + let worst = a.iter().zip(&t).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "differs across tilings by {worst}"); + } + /// Flat greys keep their tone through every pattern and Contrast, black and white stay /// solid, and Contrast makes the screen crisper. #[test] diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs index 98054c3fea..819bf6fa78 100644 --- a/crates/algo/src/blur.rs +++ b/crates/algo/src/blur.rs @@ -144,13 +144,12 @@ fn conv_row(src: &[f32], dst: &mut [f32], kernel: &[f32]) { pub(crate) fn gaussian(src: &Image, out: Rect, ctx: &Ctx, radius: f32) -> Vec { // Exact kernel for small radii; beyond that three box passes approximate the Gaussian with - // cost independent of the radius (Kovesi, "Fast almost-Gaussian filtering", 2010). - match box_widths(&FilterParams::GaussianBlur { radius }) { - Some(boxes) => box_passes(src, out, ctx.alpha, &boxes), - None => { - let k = gaussian_blur_kernel(radius); - conv_sep(src, out, &k, &k, ctx.alpha) - } + // cost independent of the radius (Kovesi, "Fast almost-Gaussian filtering", 2010). Built + // from the description other devices run (`separable`), so they blur the same (#5772). + match crate::separable::Separable::of(&FilterParams::GaussianBlur { radius }) { + Some(crate::separable::Separable::Boxes(boxes)) => box_passes(src, out, ctx.alpha, &boxes), + Some(crate::separable::Separable::Kernel(k)) => conv_sep(src, out, &k, &k, ctx.alpha), + None => src.crop(out), } } diff --git a/crates/algo/src/cutout/colour.rs b/crates/algo/src/cutout/colour.rs new file mode 100644 index 0000000000..75ddeed2e8 --- /dev/null +++ b/crates/algo/src/cutout/colour.rs @@ -0,0 +1,263 @@ +//! Colour and palette: Oklab, edge-keeping smoothing, and the picture's own palette. + +use super::Px; +use super::util::transpose; +use crate::par; +use crate::quantize::{kmeans, median_cut}; + +/// Oklab (Björn Ottosson, 2020) of an sRGB colour. +pub(super) fn oklab(p: Px) -> Px { + let lin = |v: f32| { + let v = v.clamp(0.0, 1.0); + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + let (r, g, b) = (lin(p[0]), lin(p[1]), lin(p[2])); + let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt(); + let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt(); + let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt(); + [ + 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, + 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, + 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, + ] +} + +/// sRGB of an Oklab colour, or `None` outside the sRGB gamut. +pub(super) fn srgb(lab: Px) -> Option { + let l = (lab[0] + 0.396_337_78 * lab[1] + 0.215_803_76 * lab[2]).powi(3); + let m = (lab[0] - 0.105_561_346 * lab[1] - 0.063_854_17 * lab[2]).powi(3); + let s = (lab[0] - 0.089_484_18 * lab[1] - 1.291_485_5 * lab[2]).powi(3); + let lin = [ + 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s, + -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s, + -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s, + ]; + if lin.iter().any(|v| !(-1e-4..=1.0001).contains(v)) { + return None; + } + let enc = |v: f32| { + let v = v.clamp(0.0, 1.0); + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } + }; + Some(lin.map(enc)) +} + +/// sRGB at Oklab lightness `l`, hue/strength `a`, `b`; out of gamut it loses strength, not hue. +pub(super) fn in_gamut(l: f32, a: f32, b: f32) -> Px { + if let Some(c) = srgb([l, a, b]) { + return c; + } + let (mut ok, mut bad) = (0.0f32, 1.0f32); + for _ in 0..10 { + let t = (ok + bad) / 2.0; + if srgb([l, a * t, b * t]).is_some() { ok = t } else { bad = t } + } + srgb([l, a * ok, b * ok]).unwrap_or([l, l, l]) +} + +/// Squared distance between two colours. +pub(super) fn dist2(a: Px, b: Px) -> f32 { + (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2) +} + +/// Bilateral smoothing in Oklab, `rounds` times along rows then columns. +pub(super) fn smooth(mut lab: Vec, w: usize, h: usize, rounds: usize) -> Vec { + for _ in 0..rounds { + bilateral_rows(&mut lab, w); + let mut t = transpose(&lab, w, h); + bilateral_rows(&mut t, h); + lab = transpose(&t, h, w); + } + lab +} + +/// One bilateral pass along every row of `buf` (rows of `w` pixels), seven pixels wide. +fn bilateral_rows(buf: &mut [Px], w: usize) { + const R: isize = 3; + // Colours this far apart (Oklab) count half as much as equal ones (a Cauchy weight: as + // edge-keeping as a Gaussian one and much cheaper). + const HALF: f32 = 0.06; + let k = 1.0 / (HALF * HALF); + let spatial: [f32; 7] = std::array::from_fn(|i| (-((i as f32 - 3.0).powi(2)) / 8.0).exp()); + par::chunks_mut(buf, w, true, |_, row| { + let src = row.to_vec(); + for (x, out) in row.iter_mut().enumerate() { + let c = src[x]; + let (mut acc, mut wsum) = ([0.0f32; 3], 0.0f32); + for d in -R..=R { + let q = src[(x as isize + d).clamp(0, w as isize - 1) as usize]; + let wt = spatial[(d + R) as usize] / (1.0 + dist2(q, c) * k); + acc = [acc[0] + q[0] * wt, acc[1] + q[1] * wt, acc[2] + q[2] * wt]; + wsum += wt; + } + *out = [acc[0] / wsum, acc[1] / wsum, acc[2] / wsum]; + } + }); +} + +/// At most `levels` colours of the image's own; colours closer than noise are merged. +pub(super) fn palette(lab: &[Px], levels: usize) -> Vec { + const SAMPLES: usize = 1 << 16; + const SAME: f32 = 0.045; + // Hue centres (Oklab a, b) this far apart are different colours, not one colour's spread. + const HUES_APART: f32 = 0.08; + let step = lab.len().div_ceil(SAMPLES).max(1); + let pts: Vec<(Px, u32)> = lab.iter().step_by(step).map(|p| (*p, 1)).collect(); + let mut centres = median_cut(&pts, levels); + kmeans(&pts, &mut centres, 10); + // Number of Levels counts tones: a palette colour whose pixels are two clearly different hues + // of that tone (a blue and a pink) splits in two, or touching areas of both would be one + // shape of their grey average. + let mut split = Vec::with_capacity(centres.len() * 2); + for (k, c) in centres.iter().enumerate() { + let members: Vec<(Px, u32)> = pts.iter().filter(|(p, _)| nearest(¢res, *p) as usize == k).map(|(p, _)| ([0.0, p[1], p[2]], 1)).collect(); + let mut hues = median_cut(&members, 2); + kmeans(&members, &mut hues, 6); + match hues.as_slice() { + [a, b] if dist2(*a, *b).sqrt() > HUES_APART => split.extend([[c[0], a[1], a[2]], [c[0], b[1], b[2]]]), + _ => split.push(*c), + } + } + let mut centres = split; + kmeans(&pts, &mut centres, 4); + let mut weight = vec![0u32; centres.len()]; + for (p, _) in &pts { + if let Some(wt) = weight.get_mut(nearest(¢res, *p) as usize) { + *wt += 1; + } + } + let mut cs: Vec<(Px, f32)> = centres.into_iter().zip(weight).filter(|c| c.1 > 0).map(|(c, wt)| (c, wt as f32)).collect(); + loop { + let mut best: Option<(usize, usize, f32)> = None; + for i in 0..cs.len() { + for j in i + 1..cs.len() { + let d = dist2(cs[i].0, cs[j].0).sqrt(); + if d < SAME && best.is_none_or(|b| d < b.2) { + best = Some((i, j, d)); + } + } + } + let Some((i, j, _)) = best else { break }; + let (a, b) = (cs[i], cs[j]); + let t = a.1 + b.1; + cs[i] = (std::array::from_fn(|k| (a.0[k] * a.1 + b.0[k] * b.1) / t), t); + cs.remove(j); + } + if cs.is_empty() { + return vec![[0.5, 0.0, 0.0]]; + } + cs.into_iter().map(|c| c.0).collect() +} + +/// Index of the palette colour closest to `p`. +pub(super) fn nearest(palette: &[Px], p: Px) -> u8 { + let mut best = (0usize, f32::MAX); + for (i, c) in palette.iter().enumerate() { + let d = dist2(*c, p); + if d < best.1 { + best = (i, d); + } + } + best.0 as u8 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::photo_util::hash01; + + /// Oklab pixels of `w`×`h`: `colour(x)` plus noise of ±`noise` in each channel. + fn noisy(w: usize, h: usize, noise: f32, colour: impl Fn(usize) -> Px) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as i64, (i / w) as i64); + let c = colour(i % w); + std::array::from_fn(|k| c[k] + (hash01(x, y, k as u64 + 1) - 0.5) * 2.0 * noise) + }) + .collect() + } + + #[test] + fn oklab_round_trips_and_marks_the_gamut() { + let white = oklab([1.0, 1.0, 1.0]); + assert!((white[0] - 1.0).abs() < 1e-3 && white[1].abs() < 1e-3 && white[2].abs() < 1e-3, "{white:?}"); + assert!(oklab([0.0, 0.0, 0.0])[0].abs() < 1e-6); + for p in [[0.2, 0.5, 0.9], [0.95, 0.1, 0.3], [0.5, 0.5, 0.5], [0.0, 1.0, 0.0]] { + let back = srgb(oklab(p)).unwrap_or([-1.0; 3]); + assert!(dist2(back, p) < 1e-6, "{p:?} came back as {back:?}"); + } + // Very light and very colourful: no sRGB colour is that. + assert_eq!(srgb([0.95, 0.3, 0.0]), None); + } + + #[test] + fn out_of_gamut_colours_lose_strength_not_hue() { + let (l, a, b) = (0.95, 0.3, 0.1); + let c = in_gamut(l, a, b); + let lab = oklab(c); + assert!((lab[0] - l).abs() < 0.01, "lightness kept: {lab:?}"); + let chroma = (lab[1] * lab[1] + lab[2] * lab[2]).sqrt(); + assert!(chroma > 0.01 && chroma < (a * a + b * b).sqrt(), "weaker but still coloured: {chroma}"); + assert!((lab[2] / lab[1] - b / a).abs() < 0.05, "same hue: {lab:?}"); + // In gamut it is just the conversion. + assert_eq!(in_gamut(0.6, 0.02, -0.03), srgb([0.6, 0.02, -0.03]).unwrap_or_default()); + } + + #[test] + fn smoothing_flattens_noise_and_keeps_edges() { + let (w, h) = (40usize, 20usize); + let lab = noisy(w, h, 0.02, |x| if x < 20 { [0.3, 0.0, 0.0] } else { [0.8, 0.0, 0.0] }); + let out = smooth(lab.clone(), w, h, 2); + let spread = |v: &[Px], xs: std::ops::Range| { + let l: Vec = (0..h).flat_map(|y| xs.clone().map(move |x| y * w + x)).map(|i| v[i][0]).collect(); + let mean = l.iter().sum::() / l.len() as f32; + (l.iter().map(|v| (v - mean).powi(2)).sum::() / l.len() as f32).sqrt() + }; + assert!(spread(&out, 2..16) < spread(&lab, 2..16) / 2.0, "noise kept: {} vs {}", spread(&out, 2..16), spread(&lab, 2..16)); + // The step stays a step: the pixels either side of it keep most of their difference. + let step = (0..h).map(|y| out[y * w + 20][0] - out[y * w + 19][0]).sum::() / h as f32; + assert!(step > 0.4, "edge blurred to {step}"); + } + + #[test] + fn the_palette_finds_the_pictures_own_colours() { + let (w, h) = (60usize, 20usize); + let (dark, light) = ([0.25, 0.02, -0.03], [0.75, -0.04, 0.05]); + let lab = noisy(w, h, 0.01, |x| if x < 30 { dark } else { light }); + // Asked for up to six, it gives two: colours only noise apart are one. + let p = palette(&lab, 6); + assert_eq!(p.len(), 2, "{p:?}"); + for c in [dark, light] { + assert!(p.iter().any(|q| dist2(*q, c).sqrt() < 0.02), "{c:?} not in {p:?}"); + } + assert_eq!(nearest(&p, dark), nearest(&p, [0.27, 0.0, -0.02])); + assert_ne!(nearest(&p, dark), nearest(&p, light)); + } + + #[test] + fn a_tone_of_two_different_hues_splits_in_two() { + // A dark tone and a light one, the light one half blue and half pink: two levels give + // three colours, or the blue and pink areas would be one shape of their grey average. + let (w, h) = (60usize, 20usize); + let (dark, blue, pink) = ([0.2, 0.0, 0.0], [0.7, -0.03, -0.1], [0.7, 0.12, 0.0]); + let lab = noisy(w, h, 0.005, |x| { + if x < 30 { + dark + } else if x < 45 { + blue + } else { + pink + } + }); + let p = palette(&lab, 2); + assert_eq!(p.len(), 3, "{p:?}"); + for c in [dark, blue, pink] { + assert!(p.iter().any(|q| dist2(*q, c).sqrt() < 0.03), "{c:?} not in {p:?}"); + } + } + + #[test] + fn an_empty_image_still_has_a_palette() { + assert_eq!(palette(&[], 4).len(), 1); + } +} diff --git a/crates/algo/src/cutout/curves.rs b/crates/algo/src/cutout/curves.rs new file mode 100644 index 0000000000..9d7e90a44e --- /dev/null +++ b/crates/algo/src/cutout/curves.rs @@ -0,0 +1,380 @@ +//! Curves: each chain fitted once, with its corners kept, its runs simplified (Douglas–Peucker) +//! and drawn as Catmull-Rom curves. + +use super::{Pt, Settings}; + +/// `a - b`. +fn sub(a: Pt, b: Pt) -> Pt { + [a[0] - b[0], a[1] - b[1]] +} + +/// Length of `a`. +fn len(a: Pt) -> f32 { + (a[0] * a[0] + a[1] * a[1]).sqrt() +} + +/// Fits one chain: corners kept, runs simplified and smoothed. Its ends stay where they are, so +/// chains meeting at a junction still meet. +pub(super) fn fit(pts: &[Pt], closed: bool, s: &Settings) -> Vec { + let n = pts.len(); + if n < 3 { + return pts.to_vec(); + } + let original = pts; + let rounded = round_off(pts, closed, s.rounding()); + let pts = &rounded[..]; + let at = |i: isize| pts[i.rem_euclid(n as isize) as usize]; + // Turn at each point, measured over a few cracks either side. + const K: isize = 3; + let turn = |i: isize| { + let (a, b) = (sub(at(i), at(i - K)), sub(at(i + K), at(i))); + let (la, lb) = (len(a), len(b)); + if la < 1e-6 || lb < 1e-6 { 0.0 } else { ((a[0] * b[0] + a[1] * b[1]) / (la * lb)).clamp(-1.0, 1.0).acos() } + }; + let span = if closed { 0..n as isize } else { K..(n as isize - K) }; + let turns: Vec<(isize, f32)> = span.clone().map(|i| (i, turn(i))).collect(); + let limit = s.corner_turn(); + let mut corners: Vec = Vec::new(); + for &(i, t) in &turns { + if t <= limit { + continue; + } + // Only the sharpest point of a bend. + let sharpest = (-K..=K).all(|o| { + let j = i + o; + let in_span = closed || span.contains(&j); + !in_span || o == 0 || { + let tj = turn(j); + tj < t || (tj == t && o > 0) + } + }); + if sharpest { + corners.push(i.rem_euclid(n as isize) as usize); + } + } + // Square a corner back where the pixels cut it: where the straight runs either side meet. + let mut p = pts.to_vec(); + for &i in &corners { + let ii = i as isize; + if let Some(q) = intersect(at(ii - K), at(ii - 1), at(ii + 1), at(ii + K)) + && len(sub(q, at(ii))) <= 1.0 + { + p[i] = q; + } + } + let mut keep: Vec = if closed { corners.clone() } else { std::iter::once(0).chain(corners.iter().copied()).chain(std::iter::once(n - 1)).collect() }; + keep.sort_unstable(); + keep.dedup(); + let mut is_corner = vec![false; n]; + for &k in &keep { + is_corner[k] = true; + } + if closed && keep.len() < 2 { + // A smooth loop: split it at two far-apart points (not corners) to simplify each half. + let a = keep.first().copied().unwrap_or(0); + let far = (0..n).max_by(|&i, &j| len(sub(p[i], p[a])).total_cmp(&len(sub(p[j], p[a])))).unwrap_or(n / 2); + keep = if a == far { vec![a, (a + n / 2) % n] } else { vec![a.min(far), a.max(far)] }; + } + // Douglas–Peucker between consecutive kept points. + let tol = s.tolerance(); + let mut verts: Vec = Vec::new(); + let pieces = if closed { keep.len() } else { keep.len() - 1 }; + for k in 0..pieces { + let a = keep[k]; + let b = if k + 1 < keep.len() { keep[k + 1] } else { keep[0] + n }; + verts.push(a); + let idx: Vec = (a..=b).collect(); + let mut marks = vec![false; idx.len()]; + simplify(&idx.iter().map(|&i| p[i % n]).collect::>(), 0, idx.len() - 1, tol, &mut marks); + verts.extend(idx.iter().zip(&marks).skip(1).take(idx.len().saturating_sub(2)).filter(|m| *m.1).map(|(&i, _)| i % n)); + } + if !closed { + verts.push(n - 1); + } + let v: Vec = verts.iter().map(|&i| p[i]).collect(); + let corner: Vec = verts.iter().map(|&i| is_corner[i]).collect(); + let out = curves(&v, &corner, closed); + if closed { + let before = signed_area(original); + let after = signed_area(&out); + // Region merging decides which islands survive. Rounding and simplification must not + // erase one (or reverse its hole): keep the original shared outline if half its area + // would be lost. Close it explicitly because the fill consumes consecutive segments. + if before * after <= 0.0 || after.abs() < before.abs() * 0.5 { + let mut out = original.to_vec(); + out.extend(original.first().copied()); + return out; + } + } + out +} + +/// Signed loop area, relative to its first point to avoid cancellation far from the origin. +fn signed_area(pts: &[Pt]) -> f64 { + let Some(origin) = pts.first() else { return 0.0 }; + pts.iter() + .zip(pts.iter().cycle().skip(1)) + .map(|(a, b)| { + let (ax, ay) = (f64::from(a[0]) - f64::from(origin[0]), f64::from(a[1]) - f64::from(origin[1])); + let (bx, by) = (f64::from(b[0]) - f64::from(origin[0]), f64::from(b[1]) - f64::from(origin[1])); + ax * by - bx * ay + }) + .sum::() + * 0.5 +} + +/// Two passes of a moving average over `r` points either side; an open chain's ends (junctions) +/// stay put, and the window shrinks towards them so they don't pull the outline. +fn round_off(pts: &[Pt], closed: bool, r: usize) -> Vec { + let n = pts.len(); + let mut p = pts.to_vec(); + if r == 0 || n < 3 { + return p; + } + for _ in 0..2 { + let src = p.clone(); + for (i, q) in p.iter_mut().enumerate() { + let rr = if closed { r.min((n - 1) / 2) } else { r.min(i).min(n - 1 - i) }; + if rr == 0 { + continue; + } + let (mut sx, mut sy) = (0.0f32, 0.0f32); + for o in -(rr as isize)..=rr as isize { + let s = src[(i as isize + o).rem_euclid(n as isize) as usize]; + sx += s[0]; + sy += s[1]; + } + let k = (2 * rr + 1) as f32; + *q = [sx / k, sy / k]; + } + } + p +} + +/// Where the lines through `a0`–`a1` and `b0`–`b1` cross, if they aren't parallel. +fn intersect(a0: Pt, a1: Pt, b0: Pt, b1: Pt) -> Option { + let (da, db) = (sub(a1, a0), sub(b1, b0)); + let den = da[0] * db[1] - da[1] * db[0]; + if den.abs() < 1e-6 { + return None; + } + let t = ((b0[0] - a0[0]) * db[1] - (b0[1] - a0[1]) * db[0]) / den; + Some([a0[0] + da[0] * t, a0[1] + da[1] * t]) +} + +/// Marks the points of `p[a..=b]` that Douglas–Peucker keeps at tolerance `tol`. +fn simplify(p: &[Pt], a: usize, b: usize, tol: f32, marks: &mut [bool]) { + let mut stack = vec![(a, b)]; + while let Some((a, b)) = stack.pop() { + if b <= a + 1 { + continue; + } + let (pa, d) = (p[a], sub(p[b], p[a])); + let l = len(d); + let mut best = (a, 0.0f32); + for (i, q) in p.iter().enumerate().take(b).skip(a + 1) { + let e = sub(*q, pa); + let dist = if l < 1e-6 { len(e) } else { (e[0] * d[1] - e[1] * d[0]).abs() / l }; + if dist > best.1 { + best = (i, dist); + } + } + if best.1 > tol { + marks[best.0] = true; + stack.push((a, best.0)); + stack.push((best.0, b)); + } + } +} + +/// Catmull-Rom curves through `v` (one-sided at corners), flattened to a polyline. +fn curves(v: &[Pt], corner: &[bool], closed: bool) -> Vec { + let m = v.len(); + if m < 2 { + return v.to_vec(); + } + let at = |i: isize| v[i.rem_euclid(m as isize) as usize]; + let sharp = |i: isize| (!closed && (i <= 0 || i >= m as isize - 1)) || corner[i.rem_euclid(m as isize) as usize]; + let mut out = vec![v[0]]; + let segs = if closed { m } else { m - 1 }; + for i in 0..segs as isize { + let (p0, p1) = (at(i), at(i + 1)); + let d = len(sub(p1, p0)); + let (s0, s1) = (sharp(i), sharp(i + 1)); + if s0 && s1 || d < 1e-6 { + out.push(p1); + continue; + } + // Tangents scaled to this segment, so short and long neighbours don't overshoot. + let t0 = if s0 { + sub(p1, p0) + } else { + let dp = len(sub(p0, at(i - 1))); + let k = d / (dp + d).max(1e-6); + let t = sub(p1, at(i - 1)); + [t[0] * k, t[1] * k] + }; + let t1 = if s1 { + sub(p1, p0) + } else { + let dn = len(sub(at(i + 2), p1)); + let k = d / (d + dn).max(1e-6); + let t = sub(at(i + 2), p0); + [t[0] * k, t[1] * k] + }; + let c1 = [p0[0] + t0[0] / 3.0, p0[1] + t0[1] / 3.0]; + let c2 = [p1[0] - t1[0] / 3.0, p1[1] - t1[1] / 3.0]; + let steps = ((d / 1.5).ceil() as usize).clamp(2, 24); + for k in 1..=steps { + let t = k as f32 / steps as f32; + let u = 1.0 - t; + let (b0, b1, b2, b3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + out.push([b0 * p0[0] + b1 * c1[0] + b2 * c2[0] + b3 * p1[0], b0 * p0[1] + b1 * c1[1] + b2 * c2[1] + b3 * p1[1]]); + } + } + out +} + +/// Bounding box `[x0, y0, x1, y1]` of `pts`. +pub(super) fn bounds(pts: &[Pt]) -> [f32; 4] { + pts.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn settings(fidelity: f32) -> Settings { + Settings { levels: 4, simplicity: 2.0, fidelity } + } + + /// The outline of a square from (2, 2) to (12, 12), one point per unit, starting at a corner. + fn square() -> Vec { + let mut p = Vec::new(); + for i in 0..10 { + p.push([2.0 + i as f32, 2.0]); + } + for i in 0..10 { + p.push([12.0, 2.0 + i as f32]); + } + for i in 0..10 { + p.push([12.0 - i as f32, 12.0]); + } + for i in 0..10 { + p.push([2.0, 12.0 - i as f32]); + } + p + } + + fn close(a: Pt, b: Pt) -> bool { + len(sub(a, b)) < 1e-3 + } + + #[test] + fn douglas_peucker_keeps_only_points_off_the_line() { + // An L, slightly ragged: only its corner is further from the end-to-end line than the + // tolerance, and the two arms are straight within it. + let wobble = |i: usize| 0.05 * (i % 2) as f32; + let p: Vec = (0..9).map(|i| if i <= 4 { [i as f32, wobble(i)] } else { [4.0 + wobble(i), (i - 4) as f32] }).collect(); + let mut marks = vec![false; p.len()]; + simplify(&p, 0, 8, 0.5, &mut marks); + assert_eq!(marks.iter().filter(|m| **m).count(), 1, "{marks:?}"); + assert!(marks[4]); + let mut marks = vec![false; p.len()]; + simplify(&p, 0, 8, 3.0, &mut marks); + assert!(marks.iter().all(|m| !m), "under the tolerance nothing is kept"); + } + + #[test] + fn lines_cross_where_they_should() { + let q = intersect([0.0, 0.0], [1.0, 1.0], [0.0, 2.0], [1.0, 1.0]); + assert!(q.is_some_and(|q| close(q, [1.0, 1.0])), "{q:?}"); + assert_eq!(intersect([0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 1.0]), None); + } + + #[test] + fn rounding_off_keeps_an_open_chains_ends() { + let p: Vec = (0..12).map(|i| [i as f32, if i % 2 == 0 { 0.0 } else { 1.0 }]).collect(); + let r = round_off(&p, false, 3); + assert_eq!((r[0], r[11]), (p[0], p[11])); + assert!(r[5][1] > 0.2 && r[5][1] < 0.8, "the zigzag is averaged out: {:?}", r[5]); + assert_eq!(round_off(&p, false, 0), p); + } + + #[test] + fn a_square_keeps_its_four_corners_and_straight_sides() { + let out = fit(&square(), true, &settings(2.0)); + for c in [[2.0, 2.0], [12.0, 2.0], [12.0, 12.0], [2.0, 12.0]] { + assert!(out.iter().any(|p| close(*p, c)), "corner {c:?} lost: {out:?}"); + } + let on_side = |p: &Pt| [p[0] - 2.0, p[0] - 12.0, p[1] - 2.0, p[1] - 12.0].iter().any(|d| d.abs() < 1e-3); + assert!(out.iter().all(on_side), "{out:?}"); + assert!(out.len() < 10, "the sides are simplified to their ends: {out:?}"); + } + + #[test] + fn a_rounded_corner_is_squared_back() { + // The pixels cut the corner at (12, 2): the outline goes (11, 2), (12, 3) instead. + let mut p = square(); + p[10] = [11.5, 2.5]; + let out = fit(&p, true, &settings(2.0)); + assert!(out.iter().any(|q| close(*q, [12.0, 2.0])), "{out:?}"); + } + + #[test] + fn an_open_chain_ends_where_it_started_at_any_fidelity() { + let p: Vec = (0..30).map(|i| [i as f32, (i as f32 / 5.0).sin() * 4.0 + 0.3 * (i % 3) as f32]).collect(); + for f in [1.0, 2.0, 3.0] { + let out = fit(&p, false, &settings(f)); + assert_eq!((out.first(), out.last()), (p.first(), p.last()), "fidelity {f}"); + } + } + + #[test] + fn curves_pass_through_their_vertices() { + let v = [[0.0, 0.0], [4.0, 3.0], [8.0, 0.0], [12.0, 4.0]]; + let out = curves(&v, &[false; 4], false); + for p in v { + assert!(out.iter().any(|q| close(*q, p)), "{p:?} missed: {out:?}"); + } + assert!(out.len() > 8, "flattened into steps: {}", out.len()); + // Between two corners a segment is straight. + assert_eq!(curves(&v, &[true; 4], false), v.to_vec()); + } + + #[test] + fn fitting_keeps_small_islands_and_their_winding() { + use super::super::edges::follow_edges; + let (w, h) = (32, 32); + for size in [2, 3, 4, 6] { + let reg: Vec = (0..w * h).map(|i| u32::from((12..12 + size).contains(&(i % w)) && (12..12 + size).contains(&(i / w)))).collect(); + let colours = [[0.2; 3], [0.9; 3]]; + let c: Vec<_> = reg.iter().map(|&r| colours[r as usize]).collect(); + let (chains, _) = follow_edges(®, &colours, &c, w, h); + let (pts, closed) = chains.iter().find(|(_, closed)| *closed).unwrap(); + assert!(*closed); + let area = |p: &[Pt]| p.iter().zip(p.iter().cycle().skip(1)).map(|(a, b)| a[0] as f64 * b[1] as f64 - b[0] as f64 * a[1] as f64).sum::() / 2.0; + let original = area(pts); + for simplicity in [0.0, 2.0] { + let s = Settings { simplicity, ..settings(2.0) }; + if size * size < s.min_area() as usize { + continue; + } + for fidelity in [1.0, 1.5, 2.0, 3.0] { + let out = fit(pts, true, &Settings { fidelity, ..s }); + let fitted = area(&out); + assert!( + fitted * original > 0.0 && fitted.abs() >= original.abs() * 0.5, + "{size}x{size}, simplicity {simplicity}, fidelity {fidelity}: {original} -> {fitted}" + ); + assert_eq!(out.first(), out.last(), "fallbacks must close the loop for the fill"); + } + } + } + } + + #[test] + fn bounds_cover_every_point() { + assert_eq!(bounds(&[[1.0, 5.0], [-2.0, 3.0], [4.0, 4.0]]), [-2.0, 3.0, 4.0, 5.0]); + } +} diff --git a/crates/algo/src/cutout/edges.rs b/crates/algo/src/cutout/edges.rs new file mode 100644 index 0000000000..8b0a39c41b --- /dev/null +++ b/crates/algo/src/cutout/edges.rs @@ -0,0 +1,210 @@ +//! Edges: the cracks between regions, linked into chains from junction to junction, each crack +//! placed where the anti-aliasing says the edge is. + +use super::{OUT, Pt, Px}; +use crate::par; + +/// A chain's points, and whether it is closed. +pub(super) type Chain = (Vec, bool); +/// A pixel, or a lattice point (the corner at a pixel's top left). +type Cell = (i64, i64); + +/// A step along the lattice, y down. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Dir { + E, + W, + S, + N, +} + +/// Links the cracks between regions into chains. Each chain is its points (the junctions it runs +/// between, if any, and one sub-pixel point per crack) and whether it is closed; its sides are +/// the regions on its left and right (y down). +pub(super) fn follow_edges(reg: &[u32], colours: &[Px], c: &[Px], w: usize, h: usize) -> (Vec, Vec<(u32, u32)>) { + let (wi, hi) = (w as i64, h as i64); + let at = |x: i64, y: i64| -> u32 { if x < 0 || y < 0 || x >= wi || y >= hi { OUT } else { reg[y as usize * w + x as usize] } }; + let hcount = w * (h + 1); + // Horizontal crack (x, y)–(x+1, y) is `y * w + x`; vertical (x, y)–(x, y+1) follows them. + let hc = |x: i64, y: i64| (y as usize) * w + x as usize; + let vc = |x: i64, y: i64| hcount + (y as usize) * (w + 1) + x as usize; + let mut visited = vec![false; hcount + (w + 1) * h]; + // The crack leaving lattice point (x, y) in `d`: its id, the pixels on its left and right, + // and the point it reaches. + let step = |x: i64, y: i64, d: Dir| -> Option<(usize, Cell, Cell, Cell)> { + match d { + Dir::E if x < wi => Some((hc(x, y), (x, y - 1), (x, y), (x + 1, y))), + Dir::W if x > 0 => Some((hc(x - 1, y), (x - 1, y), (x - 1, y - 1), (x - 1, y))), + Dir::S if y < hi => Some((vc(x, y), (x, y), (x - 1, y), (x, y + 1))), + Dir::N if y > 0 => Some((vc(x, y - 1), (x - 1, y - 1), (x, y - 1), (x, y - 1))), + _ => None, + } + }; + // Which cracks separate two regions, and which lattice points are junctions, worked out + // once (in parallel) before the walk. + let mut is_edge = vec![false; visited.len()]; + let (hb, vb) = is_edge.split_at_mut(hcount); + par::chunks_mut(hb, w, true, |y, row| { + for (x, b) in row.iter_mut().enumerate() { + *b = at(x as i64, y as i64 - 1) != at(x as i64, y as i64); + } + }); + par::chunks_mut(vb, w + 1, true, |y, row| { + for (x, b) in row.iter_mut().enumerate() { + *b = at(x as i64 - 1, y as i64) != at(x as i64, y as i64); + } + }); + let boundary = |x: i64, y: i64, d: Dir| step(x, y, d).filter(|s| is_edge[s.0]); + let mut is_junction = vec![false; (w + 1) * (h + 1)]; + par::chunks_mut(&mut is_junction, w + 1, true, |y, row| { + let y = y as i64; + for (x, j) in row.iter_mut().enumerate() { + let x = x as i64; + let deg = [Dir::E, Dir::W, Dir::S, Dir::N].iter().filter(|&&d| boundary(x, y, d).is_some()).count(); + *j = deg >= 3 || (deg > 0 && (x == 0 || x == wi) && (y == 0 || y == hi)); + } + }); + let junction = |x: i64, y: i64| is_junction[y as usize * (w + 1) + x as usize]; + // One point per crack: its middle, moved along the normal from left to right pixel by what + // their colours say about where the edge really is. + let crack_point = |l: (i64, i64), r: (i64, i64)| -> Pt { + let mid = [(l.0 + r.0 + 1) as f32 / 2.0, (l.1 + r.1 + 1) as f32 / 2.0]; + let (n0, n1) = ((r.0 - l.0) as f32, (r.1 - l.1) as f32); + let (ra, rb) = (at(l.0, l.1), at(r.0, r.1)); + let (Some(ca), Some(cb)) = (colours.get(ra as usize), colours.get(rb as usize)) else { return mid }; + let d = [cb[0] - ca[0], cb[1] - ca[1], cb[2] - ca[2]]; + let dd = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if dd < 1e-4 { + return mid; + } + // How far each pixel's colour is from its own region's towards the other's (0–1). + let frac = |p: (i64, i64)| { + let q = c[p.1 as usize * w + p.0 as usize]; + ((q[0] - ca[0]) * d[0] + (q[1] - ca[1]) * d[1] + (q[2] - ca[2]) * d[2]) / dd + }; + let (fl, fr) = (frac(l).clamp(0.0, 1.0), frac(r).clamp(0.0, 1.0)); + let off = ((1.0 - fr) - fl).clamp(-0.5, 0.5); + [mid[0] + n0 * off, mid[1] + n1 * off] + }; + let mut chains = Vec::new(); + let mut sides = Vec::new(); + let mut walk = |x: i64, y: i64, first: Dir, visited: &mut Vec| { + let open = junction(x, y); + let mut pts = if open { vec![[x as f32, y as f32]] } else { Vec::new() }; + let (mut cx, mut cy, mut d) = (x, y, first); + let mut side = (OUT, OUT); + let mut closed = !open; + while let Some((id, l, r, to)) = boundary(cx, cy, d) { + if visited[id] { + break; + } + visited[id] = true; + if pts.len() <= usize::from(open) { + side = (at(l.0, l.1), at(r.0, r.1)); + } + pts.push(crack_point(l, r)); + (cx, cy) = to; + if junction(cx, cy) { + pts.push([cx as f32, cy as f32]); + closed = false; + break; + } + let back = match d { + Dir::E => Dir::W, + Dir::W => Dir::E, + Dir::S => Dir::N, + Dir::N => Dir::S, + }; + let Some(next) = [Dir::E, Dir::S, Dir::W, Dir::N].into_iter().find(|&nd| nd != back && boundary(cx, cy, nd).is_some_and(|b| !visited[b.0])) else { + break; + }; + d = next; + } + if pts.len() >= 2 { + chains.push((pts, closed)); + sides.push(side); + } + }; + for y in 0..=hi { + for x in 0..=wi { + if junction(x, y) { + for d in [Dir::E, Dir::S, Dir::W, Dir::N] { + if boundary(x, y, d).is_some_and(|b| !visited[b.0]) { + walk(x, y, d, &mut visited); + } + } + } + } + } + // What is left are closed loops with no junction (an island inside one other region). + for y in 0..=hi { + for x in 0..=wi { + for d in [Dir::E, Dir::S] { + if boundary(x, y, d).is_some_and(|b| !visited[b.0]) { + walk(x, y, d, &mut visited); + } + } + } + } + (chains, sides) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Regions drawn as digits, one per pixel, with grey `colours` (region `k` is `k / 4`). + fn regions(rows: &[&str]) -> (Vec, Vec, usize, usize) { + let reg: Vec = rows.iter().flat_map(|r| r.bytes()).map(|b| u32::from(b - b'0')).collect(); + let n = reg.iter().max().map_or(0, |m| m + 1); + (reg, (0..n).map(|k| [k as f32 / 4.0; 3]).collect(), rows[0].len(), rows.len()) + } + + /// The chain whose sides are regions `a` and `b`, either way round. + fn between(chains: &[Chain], sides: &[(u32, u32)], a: u32, b: u32) -> Vec { + chains.iter().zip(sides).filter(|(_, s)| **s == (a, b) || **s == (b, a)).map(|(c, _)| c.clone()).collect() + } + + #[test] + fn the_edge_between_two_regions_is_one_chain_between_junctions() { + let (reg, colours, w, h) = regions(&["000111", "000111", "000111", "000111"]); + let c: Vec = reg.iter().map(|&r| colours[r as usize]).collect(); + let (chains, sides) = follow_edges(®, &colours, &c, w, h); + let inner = between(&chains, &sides, 0, 1); + assert_eq!(inner.len(), 1, "{chains:?}"); + let (pts, closed) = &inner[0]; + assert!(!closed); + // From junction to junction (where it meets the canvas edge), one point per crack. + let ends = [pts[0], pts[pts.len() - 1]]; + assert!(ends.contains(&[3.0, 0.0]) && ends.contains(&[3.0, 4.0]), "{pts:?}"); + assert_eq!(pts.len(), 2 + 4); + assert!(pts.iter().all(|p| p[0] == 3.0), "flat colours: the edge is on the crack: {pts:?}"); + // Every crack between two regions, the canvas edge included, is in exactly one chain. + let cracks: usize = chains.iter().map(|(p, closed)| p.len() - if *closed { 0 } else { 2 }).sum(); + assert_eq!(cracks, 4 + 2 * (w + h)); + } + + #[test] + fn an_island_is_one_closed_chain() { + let (reg, colours, w, h) = regions(&["00000", "01100", "01100", "00000"]); + let c: Vec = reg.iter().map(|&r| colours[r as usize]).collect(); + let (chains, sides) = follow_edges(®, &colours, &c, w, h); + let island = between(&chains, &sides, 0, 1); + assert_eq!(island.len(), 1); + assert!(island[0].1, "closed"); + assert_eq!(island[0].0.len(), 8, "one point per crack around the 2x2 island"); + } + + #[test] + fn an_anti_aliased_edge_is_placed_inside_its_pixel() { + // Region 0 is black and region 1 white; the last column of region 0 is half white, so + // the edge runs down the middle of that column. + let (reg, _, w, h) = regions(&["000111", "000111", "000111"]); + let colours = vec![[0.0; 3], [1.0; 3]]; + let c: Vec = reg.iter().enumerate().map(|(i, &r)| if i % w == 2 { [0.5; 3] } else { colours[r as usize] }).collect(); + let (chains, sides) = follow_edges(®, &colours, &c, w, h); + let inner = between(&chains, &sides, 0, 1); + let pts = &inner[0].0; + assert!(pts[1..pts.len() - 1].iter().all(|p| (p[0] - 2.5).abs() < 1e-5), "{pts:?}"); + } +} diff --git a/crates/algo/src/cutout/fill.rs b/crates/algo/src/cutout/fill.rs new file mode 100644 index 0000000000..f2e96973ae --- /dev/null +++ b/crates/algo/src/cutout/fill.rs @@ -0,0 +1,119 @@ +//! Fill: exact-area scan conversion of the traced shapes, so edges are anti-aliased and shapes +//! that share an edge sum to full coverage. + +use super::Pt; + +/// Accumulates the signed area of segment `a`–`b` into `acc` (rows of `stride` cells, `h` rows +/// visible, columns `0..stride - 2` visible): the part left of the tile is drawn down its left +/// edge (it still winds the pixels to its right), the part right of it is dropped. +pub(super) fn line_clipped(acc: &mut [f32], stride: usize, h: usize, a: Pt, b: Pt) { + if !(a[0].is_finite() && a[1].is_finite() && b[0].is_finite() && b[1].is_finite()) || a[1] == b[1] { + return; + } + let wf = (stride - 2) as f32; + // At most the two ends and two crossings; on the stack, as this runs for every segment drawn. + let mut buf = [0.0f32, 1.0, 0.0, 0.0]; + let mut n = 2; + for x in [0.0, wf] { + let t = (x - a[0]) / (b[0] - a[0]); + if t > 0.0 && t < 1.0 { + buf[n] = t; + n += 1; + } + } + let cuts = &mut buf[..n]; + cuts.sort_by(f32::total_cmp); + for t in cuts.windows(2) { + let p = [a[0] + (b[0] - a[0]) * t[0], a[1] + (b[1] - a[1]) * t[0]]; + let q = [a[0] + (b[0] - a[0]) * t[1], a[1] + (b[1] - a[1]) * t[1]]; + let mx = (p[0] + q[0]) / 2.0; + if mx >= wf { + continue; + } + if mx < 0.0 { + line(acc, stride, h, [0.0, p[1]], [0.0, q[1]]); + } else { + line(acc, stride, h, [p[0].clamp(0.0, wf), p[1]], [q[0].clamp(0.0, wf), q[1]]); + } + } +} + +/// Signed-area accumulation of one segment inside the tile (the scanline method of font +/// rasterisers): after a running sum along each row, a cell holds the coverage winding. +fn line(acc: &mut [f32], stride: usize, h: usize, p0: Pt, p1: Pt) { + if p0[1] == p1[1] { + return; + } + let (dir, p0, p1) = if p0[1] < p1[1] { (1.0f32, p0, p1) } else { (-1.0, p1, p0) }; + let dxdy = (p1[0] - p0[0]) / (p1[1] - p0[1]); + let mut x = p0[0]; + let ystart = p0[1].max(0.0); + if p0[1] < 0.0 { + x -= p0[1] * dxdy; + } + let yend = p1[1].min(h as f32); + if ystart >= yend { + return; + } + let max_x = (stride - 1) as f32; + for y in (ystart as usize)..(yend.ceil() as usize).min(h) { + let ls = y * stride; + let dy = ((y + 1) as f32).min(p1[1]) - (y as f32).max(p0[1]); + let xnext = x + dxdy * dy; + let d = dy * dir; + let (x0, x1) = if x < xnext { (x, xnext) } else { (xnext, x) }; + let (x0, x1) = (x0.clamp(0.0, max_x - 1.0), x1.clamp(0.0, max_x - 1.0)); + let x0f = x0.floor(); + let x0i = x0f as usize; + let x1c = x1.ceil(); + let x1i = x1c as usize; + if x1i <= x0i + 1 { + let xmf = 0.5 * (x0 + x1) - x0f; + acc[ls + x0i] += d - d * xmf; + acc[ls + x0i + 1] += d * xmf; + } else { + let sx = (x1 - x0).recip(); + let x0r = x0 - x0f; + let a0 = 0.5 * sx * (1.0 - x0r) * (1.0 - x0r); + let x1r = x1 - x1c + 1.0; + let am = 0.5 * sx * x1r * x1r; + acc[ls + x0i] += d * a0; + if x1i == x0i + 2 { + acc[ls + x0i + 1] += d * (1.0 - a0 - am); + } else { + let a1 = sx * (1.5 - x0r); + acc[ls + x0i + 1] += d * (a1 - a0); + for xi in x0i + 2..x1i - 1 { + acc[ls + xi] += d * sx; + } + let a2 = a1 + (x1i - x0i - 3) as f32 * sx; + acc[ls + x1i - 1] += d * (1.0 - a2 - am); + } + acc[ls + x1i] += d * am; + } + x = xnext; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_square_covers_its_area_exactly() { + let mut acc = vec![0.0f32; 12 * 10]; + let sq = [[2.25, 2.5], [7.75, 2.5], [7.75, 6.5], [2.25, 6.5], [2.25, 2.5]]; + for s in sq.windows(2) { + line_clipped(&mut acc, 12, 10, s[0], s[1]); + } + let mut total = 0.0; + for y in 0..10 { + let mut sum = 0.0; + for x in 0..10 { + sum += acc[y * 12 + x]; + total += sum.abs().min(1.0); + } + } + assert!((total - 5.5 * 4.0).abs() < 1e-4, "{total}"); + } +} diff --git a/crates/algo/src/cutout/mod.rs b/crates/algo/src/cutout/mod.rs new file mode 100644 index 0000000000..b3081f488e --- /dev/null +++ b/crates/algo/src/cutout/mod.rs @@ -0,0 +1,352 @@ +//! Cutout (Filter Gallery › Artistic): the image as flat sheets of cut paper. +//! +//! The image is traced into shapes, and the shapes are filled back in: +//! +//! 1. **Smooth** within tones, edges kept: a bilateral filter (C. Tomasi and R. Manduchi, +//! "Bilateral Filtering for Gray and Color Images", 1998) in Oklab, so a photo's noise doesn't +//! decide pixel by pixel which of two colours a pixel gets. +//! 2. **Palette**: median cut (Heckbert 1982) then k-means over the smoothed colours, Number of +//! Levels tones of the picture's own; a tone made of two clearly different hues splits in two, +//! and colours only noise apart are merged. +//! 3. **Regions**: 4-connected areas of one palette colour. Regions smaller than the Edge +//! Simplicity area, or thin slivers (the blends along an edge between two other colours), are +//! merged smallest first into the neighbour they share most border with. Each region is filled +//! with the mean colour of its own pixels. +//! 4. **Edges**: the cracks between regions are linked into chains from junction to junction +//! (where three regions meet, or the canvas edge). Each crack is moved along its normal to where +//! the pixels on either side say the edge is (an anti-aliased pixel is part one colour, part the +//! other), so outlines are right to a fraction of a pixel. A chain is fitted once, so two +//! neighbouring shapes share one and the same edge. +//! 5. **Curves**: turns sharper than Edge Fidelity allows are kept as corners (squared back where +//! the pixels rounded them); the runs between are simplified to the Edge Simplicity tolerance +//! (Douglas–Peucker) and drawn as Catmull-Rom curves. +//! 6. **Fill**: each region is scan-converted with exact area coverage, so edges are anti-aliased +//! and the coverages of shapes that share an edge sum to one: no seams. +//! +//! Tracing reads the whole image and runs once; filling runs per tile and gives the same pixels +//! whatever the tiling. +//! +//! Each stage is its own module: [`colour`] (steps 1–2), [`regions`] (3), [`edges`] (4), +//! [`curves`] (5) and [`fill`] (6); [`trace`] runs them in turn. + +use photocraft_geom::Rect; + +use crate::par; + +mod colour; +mod curves; +mod edges; +mod fill; +mod regions; +mod util; + +use colour::{nearest, oklab, palette, smooth}; +use curves::{bounds, fit}; +use edges::follow_edges; +use fill::line_clipped; +use regions::{components, local_paper, merge_regions, paper_colours}; + +type Px = [f32; 3]; +type Pt = [f32; 2]; + +/// Region id of the area outside the image. +const OUT: u32 = u32::MAX; + +/// The filter's three sliders. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Settings { + /// Number of Levels (2–8): the most colours the palette has. + pub levels: usize, + /// Edge Simplicity (0–10): smaller shapes merge and outlines simplify more. + pub simplicity: f32, + /// Edge Fidelity (1–3): more corners are kept. + pub fidelity: f32, +} + +impl Settings { + /// Regions with fewer pixels merge into a neighbour. + fn min_area(&self) -> u32 { + (1.0 + self.simplicity.clamp(0.0, 10.0)).powi(2).round() as u32 + } + /// Regions thinner than this (twice the area over the perimeter, in pixels) merge too. + fn sliver(&self) -> f32 { + 0.6 + 0.1 * self.simplicity.clamp(0.0, 10.0) + } + /// Douglas–Peucker tolerance of the outlines, in pixels: looser with less Edge Fidelity + /// (twice as loose at 1, half at 3). + fn tolerance(&self) -> f32 { + (0.5 + 0.12 * self.simplicity.clamp(0.0, 10.0)) * 2f32.powf(2.0 - self.fidelity.clamp(1.0, 3.0)) + } + /// Below Edge Fidelity 2 the outline is rounded off before it is fitted: points averaged with + /// this many neighbours either side (3 at fidelity 1). + fn rounding(&self) -> usize { + ((2.0 - self.fidelity.clamp(1.0, 3.0)) * 3.0).round().max(0.0) as usize + } + /// Turns sharper than this stay corners. + fn corner_turn(&self) -> f32 { + (100.0 - 22.5 * self.fidelity.clamp(1.0, 3.0)).to_radians() + } + /// Rounds of edge-preserving smoothing. + fn smooth_rounds(&self) -> usize { + 2 + (self.simplicity.clamp(0.0, 10.0) / 4.0) as usize + } +} + +/// A traced image: the shapes and their colours, ready to fill any tile. +pub(crate) struct Traced { + /// Document position of the traced window's top-left pixel; outlines are relative to it. + x0: i32, + y0: i32, + /// Fitted edges (polylines), each shared by the one or two regions it separates. + chains: Vec>, + /// Per chain, its bounding box `[x0, y0, x1, y1]`. + chain_boxes: Vec<[f32; 4]>, + regions: Vec, + /// Width of the traced window, each pixel's region, and its paper colour (the region's + /// lightness with the hue of its own pixels nearby). + width: usize, + reg: Vec, + field: Vec, +} + +/// One shape: its flat colour, bounding box and outline. +struct Region { + colour: Px, + bbox: [f32; 4], + /// The chains around the region, reversed where the region is on their right. + edges: Vec<(u32, bool)>, +} + +/// Traces `c` (sRGB colour of every pixel of `r`, row-major). +pub(crate) fn trace(c: &[Px], r: Rect, s: &Settings) -> Traced { + let (w, h) = (r.width() as usize, r.height() as usize); + let empty = Traced { x0: r.x0, y0: r.y0, chains: Vec::new(), chain_boxes: Vec::new(), regions: Vec::new(), width: 0, reg: Vec::new(), field: Vec::new() }; + if w == 0 || h == 0 || c.len() != w * h { + return empty; + } + let mut lab = vec![[0.0f32; 3]; w * h]; + par::chunks_mut(&mut lab, w, true, |y, row| { + for (o, p) in row.iter_mut().zip(&c[y * w..(y + 1) * w]) { + *o = oklab(*p); + } + }); + let original = lab.clone(); + let lab = smooth(lab, w, h, s.smooth_rounds()); + let palette = palette(&lab, s.levels.clamp(2, 8)); + let mut labels = vec![0u8; w * h]; + par::chunks_mut(&mut labels, w, true, |y, row| { + for (o, p) in row.iter_mut().zip(&lab[y * w..(y + 1) * w]) { + *o = nearest(&palette, *p); + } + }); + let (comp, n) = components(&labels, w, h); + let (reg, colours) = merge_regions(&comp, n, c, w, h, s); + let (chains, sides) = follow_edges(®, &colours, c, w, h); + let chains: Vec> = par::map(chains.len(), true, |i| fit(&chains[i].0, chains[i].1, s)); + let chain_boxes: Vec<[f32; 4]> = chains.iter().map(|ch| bounds(ch)).collect(); + let paint = paper_colours(®, colours.len(), &original); + let field = local_paper(®, &paint, &original, w, h, 3.0 + 1.2 * s.simplicity.clamp(0.0, 10.0)); + let mut regions: Vec = + paint.into_iter().map(|colour| Region { colour, bbox: [f32::MAX, f32::MAX, f32::MIN, f32::MIN], edges: Vec::new() }).collect(); + for (k, &(left, right)) in sides.iter().enumerate() { + for (side, rev) in [(left, false), (right, true)] { + if let Some(g) = regions.get_mut(side as usize) { + g.edges.push((k as u32, rev)); + let b = chain_boxes[k]; + g.bbox = [g.bbox[0].min(b[0]), g.bbox[1].min(b[1]), g.bbox[2].max(b[2]), g.bbox[3].max(b[3])]; + } + } + } + Traced { x0: r.x0, y0: r.y0, chains, chain_boxes, regions, width: w, reg, field } +} + +impl Traced { + /// The cut paper over `r` (document coordinates): sRGB colour per pixel, row-major. + pub(crate) fn render(&self, r: Rect) -> Vec { + let (w, h) = (r.width() as usize, r.height() as usize); + let mut col = vec![[0.0f32; 3]; w * h]; + if w == 0 || h == 0 { + return col; + } + let mut weight = vec![0.0f32; w * h]; + let stride = w + 2; + let mut acc = vec![0.0f32; stride * h]; + let (ox, oy) = ((self.x0 - r.x0) as f32, (self.y0 - r.y0) as f32); + let (wf, hf) = (w as f32, h as f32); + let (dx, dy) = ((r.x0 - self.x0) as i64, (r.y0 - self.y0) as i64); + let th = self.reg.len() / self.width.max(1); + for (gi, g) in self.regions.iter().enumerate() { + let b = [g.bbox[0] + ox, g.bbox[1] + oy, g.bbox[2] + ox, g.bbox[3] + oy]; + if b[2] <= 0.0 || b[0] >= wf || b[3] <= 0.0 || b[1] >= hf { + continue; + } + for &(k, rev) in &g.edges { + let (Some(pts), Some(cb)) = (self.chains.get(k as usize), self.chain_boxes.get(k as usize)) else { continue }; + // Chains left of the tile still count (they wind the rows they cross); chains to + // its right or above or below it don't. + if cb[0] + ox >= wf || cb[3] + oy <= 0.0 || cb[1] + oy >= hf { + continue; + } + for seg in pts.windows(2) { + let (a, z) = if rev { (seg[1], seg[0]) } else { (seg[0], seg[1]) }; + line_clipped(&mut acc, stride, h, [a[0] + ox, a[1] + oy], [z[0] + ox, z[1] + oy]); + } + } + let y0 = b[1].floor().max(0.0) as usize; + let y1 = (b[3].ceil().max(0.0) as usize).min(h); + let xe = ((b[2].ceil().max(0.0) as usize) + 1).min(w); + for y in y0..y1 { + let row = &mut acc[y * stride..(y + 1) * stride]; + let mut sum = 0.0f32; + for (x, v) in row.iter().enumerate().take(xe) { + sum += v; + let cov = sum.abs().min(1.0); + if cov > 0.0 { + let i = y * w + x; + // Inside its own pixels a shape takes the local colour; where it reaches + // into a neighbour's edge pixel, its own flat colour. + let (tx, ty) = (x as i64 + dx, y as i64 + dy); + let t = (tx >= 0 && ty >= 0 && (tx as usize) < self.width && (ty as usize) < th).then(|| ty as usize * self.width + tx as usize); + let paint = match t { + Some(t) if self.reg[t] as usize == gi => self.field[t], + _ => g.colour, + }; + col[i] = [col[i][0] + paint[0] * cov, col[i][1] + paint[1] * cov, col[i][2] + paint[2] * cov]; + weight[i] += cov; + } + } + row.fill(0.0); + } + } + for (p, &wt) in col.iter_mut().zip(&weight) { + if wt > 1e-6 { + *p = [p[0] / wt, p[1] / wt, p[2] / wt]; + } + } + col + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use colour::dist2; + + fn settings(levels: usize, simplicity: f32, fidelity: f32) -> Settings { + Settings { levels, simplicity, fidelity } + } + + /// Total coverage of every pixel: each pixel is covered exactly once by the shapes. + fn coverage(t: &Traced, r: Rect) -> Vec { + let (w, h) = (r.width() as usize, r.height() as usize); + let mut weight = vec![0.0f32; w * h]; + let stride = w + 2; + let mut acc = vec![0.0f32; stride * h]; + for g in &t.regions { + for &(k, rev) in &g.edges { + for seg in t.chains[k as usize].windows(2) { + let (a, z) = if rev { (seg[1], seg[0]) } else { (seg[0], seg[1]) }; + line_clipped(&mut acc, stride, h, a, z); + } + } + for y in 0..h { + let mut sum = 0.0; + for x in 0..w { + sum += acc[y * stride + x]; + weight[y * w + x] += sum.abs().min(1.0); + } + acc[y * stride..(y + 1) * stride].fill(0.0); + } + } + weight + } + + #[test] + fn shapes_cover_every_pixel_once_with_no_seams() { + // Blobs of four colours touching each other and the canvas edge, with T-junctions, + // saddles and holes. + let (w, h) = (48usize, 36usize); + let pal = [[0.1, 0.1, 0.1], [0.9, 0.2, 0.2], [0.2, 0.7, 0.3], [0.95, 0.95, 0.9]]; + let c: Vec = (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let k = ((x / 7.0).sin() + (y / 5.0).cos() + (x * y / 90.0).sin()).abs() * 1.6; + pal[(k as usize).min(3)] + }) + .collect(); + let r = Rect::new(0, 0, w as i32, h as i32); + for fidelity in [1.0, 3.0] { + let t = trace(&c, r, &settings(4, 2.0, fidelity)); + assert!(t.regions.len() > 4); + let cov = coverage(&t, r); + let worst = cov.iter().map(|v| (v - 1.0).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "coverage off by {worst}"); + } + } + + #[test] + fn edge_fidelity_changes_the_outlines() { + // It used to set only which bends count as corners: on smooth shapes 0.5% of pixels + // changed from fidelity 1 to 2 and 2.8% from 2 to 3 (now about 9% and 5%). + // Large smooth shapes, as in a photo: few corners, long curved outlines. + let (w, h) = (160usize, 120usize); + let pal = [[0.1, 0.1, 0.1], [0.9, 0.3, 0.2], [0.3, 0.6, 0.9]]; + let c: Vec = (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let k = ((x / 17.0).sin() * 1.3 + (y / 13.0).cos() + (x * y / 900.0).sin()).abs(); + pal[(k as usize).min(2)] + }) + .collect(); + let r = Rect::new(0, 0, w as i32, h as i32); + let out = |f: f32| trace(&c, r, &settings(3, 2.0, f)).render(r); + let changed = |a: &[Px], b: &[Px]| a.iter().zip(b).filter(|(p, q)| dist2(**p, **q) > 0.01).count() as f32 / a.len() as f32; + let (loose, normal, tight) = (out(1.0), out(2.0), out(3.0)); + assert!(changed(&loose, &normal) > 0.04, "fidelity 1 vs 2: {}", changed(&loose, &normal)); + assert!(changed(&normal, &tight) > 0.04, "fidelity 2 vs 3: {}", changed(&normal, &tight)); + } + + #[test] + fn empty_images_stop_before_the_transpose_and_row_passes() { + for r in [Rect::new(0, 0, 0, 4), Rect::new(0, 0, 4, 0), Rect::new(0, 0, 0, 0)] { + let t = trace(&[], r, &settings(4, 2.0, 1.0)); + assert!(t.regions.is_empty()); + assert!(t.chains.is_empty()); + assert!(t.field.is_empty()); + } + } + + #[test] + fn filling_does_not_depend_on_the_tiling() { + let (w, h) = (40usize, 30usize); + let c: Vec = (0..w * h).map(|i| if ((i % w) / 6 + (i / w) / 5) % 3 == 0 { [0.8, 0.3, 0.1] } else { [0.1, 0.3, 0.7] }).collect(); + let r = Rect::new(10, 20, 10 + w as i32, 20 + h as i32); + let t = trace(&c, r, &settings(3, 1.0, 2.0)); + let whole = t.render(r); + for tile in [Rect::new(10, 20, 23, 31), Rect::new(23, 31, 50, 50), Rect::new(37, 20, 50, 33)] { + let part = t.render(tile); + for y in tile.y0..tile.y1 { + for x in tile.x0..tile.x1 { + let a = whole[((y - r.y0) as usize) * w + (x - r.x0) as usize]; + let b = part[((y - tile.y0) as usize) * tile.width() as usize + (x - tile.x0) as usize]; + assert!(dist2(a, b) < 1e-8, "({x}, {y}): {a:?} vs {b:?}"); + } + } + } + } + + #[test] + fn noise_merges_into_neighbours_and_noise_apart_colours_are_one() { + let (w, h) = (32usize, 32usize); + let c: Vec = (0..w * h) + .map(|i| { + let v = 0.3 + crate::photo_util::hash01((i % w) as i64, (i / w) as i64, 5) * 0.06; + if (11..14).contains(&(i % w)) && (11..14).contains(&(i / w)) { [0.9, 0.9, 0.9] } else { [v, v, v] } + }) + .collect(); + let r = Rect::new(0, 0, w as i32, h as i32); + assert_eq!(trace(&c, r, &settings(6, 0.0, 2.0)).regions.len(), 2, "the speck stays at simplicity 0"); + assert_eq!(trace(&c, r, &settings(6, 10.0, 2.0)).regions.len(), 1, "the speck merges at simplicity 10"); + } +} diff --git a/crates/algo/src/cutout/regions.rs b/crates/algo/src/cutout/regions.rs new file mode 100644 index 0000000000..6c467b2ef2 --- /dev/null +++ b/crates/algo/src/cutout/regions.rs @@ -0,0 +1,357 @@ +//! Regions: connected areas of one palette colour, the merge of small ones and slivers, and the +//! paper colour of each region. + +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap}; +use std::hash::BuildHasherDefault; + +use super::colour::{in_gamut, oklab, srgb}; +use super::util::{FxHasher, find, transpose, transpose_u32}; +use super::{Px, Settings}; +use crate::par; + +/// 4-connected components of equal labels, numbered in raster order of their first pixel. +pub(super) fn components(labels: &[u8], w: usize, h: usize) -> (Vec, usize) { + let mut comp = vec![0u32; w * h]; + let mut parent: Vec = Vec::new(); + for y in 0..h { + for x in 0..w { + let i = y * w + x; + let up = (y > 0 && labels[i - w] == labels[i]).then(|| comp[i - w]); + let left = (x > 0 && labels[i - 1] == labels[i]).then(|| comp[i - 1]); + comp[i] = match (up, left) { + (Some(a), Some(b)) => { + let (ra, rb) = (find(&mut parent, a), find(&mut parent, b)); + let (lo, hi) = (ra.min(rb), ra.max(rb)); + parent[hi as usize] = lo; + lo + } + (Some(a), None) | (None, Some(a)) => a, + (None, None) => { + parent.push(parent.len() as u32); + parent.len() as u32 - 1 + } + }; + } + } + let mut index = vec![u32::MAX; parent.len()]; + let mut n = 0u32; + for c in comp.iter_mut() { + let root = find(&mut parent, *c) as usize; + if index[root] == u32::MAX { + index[root] = n; + n += 1; + } + *c = index[root]; + } + (comp, n as usize) +} + +/// Merges small and sliver components into their neighbours. Returns each pixel's region and +/// each region's mean colour. +pub(super) fn merge_regions(comp: &[u32], n: usize, c: &[Px], w: usize, h: usize, s: &Settings) -> (Vec, Vec) { + let mut area = vec![0u32; n]; + let mut sum = vec![[0.0f64; 3]; n]; + for (&k, p) in comp.iter().zip(c) { + let k = k as usize; + area[k] += 1; + sum[k] = [sum[k][0] + f64::from(p[0]), sum[k][1] + f64::from(p[1]), sum[k][2] + f64::from(p[2])]; + } + // Shared border lengths (in cracks) and perimeters, the canvas edge included. + let mut shared: HashMap> = HashMap::default(); + let mut perim = vec![0u32; n]; + for y in 0..h { + for x in 0..w { + let a = comp[y * w + x]; + for (nx, ny) in [(x + 1, y), (x, y + 1)] { + if nx < w && ny < h { + let b = comp[ny * w + nx]; + if a != b { + *shared.entry((u64::from(a.min(b)) << 32) | u64::from(a.max(b))).or_insert(0) += 1; + } + } + } + perim[a as usize] += u32::from(x == 0) + u32::from(x + 1 == w) + u32::from(y == 0) + u32::from(y + 1 == h); + } + } + let mut adj: Vec> = vec![Vec::new(); n]; + let mut pairs: Vec<(u64, u32)> = shared.into_iter().collect(); + pairs.sort_unstable(); + for (key, len) in pairs { + let (a, b) = ((key >> 32) as u32, key as u32); + adj[a as usize].push((b, len)); + adj[b as usize].push((a, len)); + perim[a as usize] += len; + perim[b as usize] += len; + } + let (min_area, sliver) = (s.min_area(), s.sliver()); + let mergeable = |a: u32, p: u32| a < min_area || 2.0 * a as f32 / (p.max(1) as f32) < sliver; + let mut parent: Vec = (0..n as u32).collect(); + let mut heap: BinaryHeap> = (0..n).filter(|&i| mergeable(area[i], perim[i])).map(|i| Reverse((area[i], i as u32))).collect(); + while let Some(Reverse((a, id))) = heap.pop() { + let i = id as usize; + if find(&mut parent, id) != id || area[i] != a || !mergeable(a, perim[i]) { + continue; + } + // The neighbours as they are now, with their total shared border. + let mut nb: Vec<(u32, u32)> = std::mem::take(&mut adj[i]).into_iter().map(|(k, len)| (find(&mut parent, k), len)).filter(|&(k, _)| k != id).collect(); + nb.sort_unstable(); + nb.dedup_by(|b, a| { + if a.0 == b.0 { + a.1 += b.1; + true + } else { + false + } + }); + let Some(&(t, len)) = nb.iter().max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(&a.0))) else { + adj[i] = nb; + continue; + }; + let ti = t as usize; + parent[i] = t; + area[ti] += area[i]; + sum[ti] = [sum[ti][0] + sum[i][0], sum[ti][1] + sum[i][1], sum[ti][2] + sum[i][2]]; + perim[ti] = (perim[ti] + perim[i]).saturating_sub(2 * len); + // Appended as they are; resolved and summed when `t` itself merges. + adj[ti].extend(nb.into_iter().filter(|&(k, _)| k != t)); + if mergeable(area[ti], perim[ti]) { + heap.push(Reverse((area[ti], t))); + } + } + let mut index = vec![u32::MAX; n]; + let mut colours = Vec::new(); + let mut reg = vec![0u32; comp.len()]; + for (r, &k) in reg.iter_mut().zip(comp) { + let root = find(&mut parent, k) as usize; + if index[root] == u32::MAX { + index[root] = colours.len() as u32; + let a = f64::from(area[root].max(1)); + colours.push([(sum[root][0] / a) as f32, (sum[root][1] / a) as f32, (sum[root][2] / a) as f32]); + } + *r = index[root]; + } + (reg, colours) +} + +/// The paper colour of every region. A plain average of a region's pixels greys it (a face of +/// pink and cream patches averages to beige, hues cancel), and a whole image of averages sits in +/// the middle tones. So in Oklab each region keeps its average hue at the average *strength* of +/// its pixels' colour, and lightness is stretched over the image's regions so the darkest paper is +/// near black and the lightest near white. Out-of-gamut colours lose chroma, not hue. +pub(super) fn paper_colours(reg: &[u32], n: usize, lab: &[Px]) -> Vec { + let mut acc = vec![[0.0f64; 5]; n]; + for (&r, p) in reg.iter().zip(lab) { + if let Some(a) = acc.get_mut(r as usize) { + let chroma = (p[1] * p[1] + p[2] * p[2]).sqrt(); + *a = [a[0] + f64::from(p[0]), a[1] + f64::from(p[1]), a[2] + f64::from(p[2]), a[3] + f64::from(chroma), a[4] + 1.0]; + } + } + let mean: Vec<(Px, f32, f64)> = acc + .iter() + .map(|a| { + let k = a[4].max(1.0); + ([(a[0] / k) as f32, (a[1] / k) as f32, (a[2] / k) as f32], (a[3] / k) as f32, a[4]) + }) + .collect(); + // The lightness range of the image's paper, by area (ignoring the extreme 1% at each end). + let mut by_l: Vec<(f32, f64)> = mean.iter().map(|m| (m.0[0], m.2)).collect(); + by_l.sort_by(|a, b| a.0.total_cmp(&b.0)); + let total: f64 = by_l.iter().map(|m| m.1).sum(); + let at = |q: f64| { + let mut run = 0.0; + for &(l, a) in &by_l { + run += a; + if run >= q * total { + return l; + } + } + by_l.last().map_or(0.5, |m| m.0) + }; + let (lo, hi) = (at(0.01), at(0.99)); + const STRETCH: f32 = 0.75; + mean.iter() + .map(|(m, chroma, _)| { + let ab = (m[1] * m[1] + m[2] * m[2]).sqrt(); + let k = if ab > 1e-5 { chroma / ab } else { 1.0 }; + let stretched = if hi - lo > 0.05 { m[0] + (0.04 + (m[0] - lo) / (hi - lo) * 0.88 - m[0]) * STRETCH } else { m[0] }; + let stretched = stretched.clamp(0.0, 1.0); + let colour = |l: f32, t: f32| srgb([l, m[1] * k * t, m[2] * k * t]); + if let Some(c) = colour(stretched, 1.0) { + return c; + } + // Colour comes before contrast: a strong colour the stretch took out of gamut (a + // bright blue pushed towards white) moves back towards its own lightness first. + let own = m[0].clamp(0.0, 1.0); + if colour(own, 1.0).is_some() { + let (mut ok, mut bad) = (own, stretched); + for _ in 0..12 { + let l = (ok + bad) / 2.0; + if colour(l, 1.0).is_some() { ok = l } else { bad = l } + } + return colour(ok, 1.0).unwrap_or([ok, ok, ok]); + } + // Even its own lightness can't hold it: keep the stretch, lose chroma (not hue). + let (mut ok, mut bad) = (0.0f32, 1.0f32); + for _ in 0..12 { + let t = (ok + bad) / 2.0; + if colour(stretched, t).is_some() { ok = t } else { bad = t } + } + colour(stretched, ok).unwrap_or([stretched, stretched, stretched]) + }) + .collect() +} + +/// Each pixel's paper colour: its region's lightness (flat across the shape) with the average +/// hue, at the average strength, of the region's own pixels within about `reach` pixels. Colour +/// can drift gently across a large shape (pink cheeks on a cream face) but never crosses a cut. +/// `paper` is each region's colour (from [`paper_colours`]). +pub(super) fn local_paper(reg: &[u32], paper: &[Px], lab: &[Px], w: usize, h: usize, reach: f32) -> Vec { + let mut v: Vec = lab.iter().map(|p| [p[1], p[2], (p[1] * p[1] + p[2] * p[2]).sqrt()]).collect(); + let regt = transpose_u32(reg, w, h); + let a = (-1.0 / reach.max(0.5)).exp(); + for _ in 0..2 { + same_region_rows(&mut v, reg, w, a); + let mut t = transpose(&v, w, h); + same_region_rows(&mut t, ®t, h, a); + v = transpose(&t, h, w); + } + let light: Vec = paper.iter().map(|c| oklab(*c)[0]).collect(); + let mut out = vec![[0.0f32; 3]; w * h]; + par::chunks_mut(&mut out, w, true, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + let (q, l) = (v[i], light.get(reg[i] as usize).copied().unwrap_or(0.5)); + let ab = (q[0] * q[0] + q[1] * q[1]).sqrt(); + let k = if ab > 1e-5 { q[2] / ab } else { 1.0 }; + *o = in_gamut(l, q[0] * k, q[1] * k); + } + }); + out +} + +/// Exponential smoothing along each row (both ways) that restarts at every change of region. +fn same_region_rows(v: &mut [Px], reg: &[u32], w: usize, a: f32) { + let mut chunks: Vec<(&mut [Px], &[u32])> = v.chunks_mut(w).zip(reg.chunks(w)).collect(); + let f = |(row, rg): &mut (&mut [Px], &[u32])| { + let n = row.len(); + let src = row.to_vec(); + let mut fwd = vec![([0.0f32; 3], 0.0f32); n]; + for x in 0..n { + let (p, d) = if x > 0 && rg[x] == rg[x - 1] { fwd[x - 1] } else { ([0.0; 3], 0.0) }; + fwd[x] = ([src[x][0] + a * p[0], src[x][1] + a * p[1], src[x][2] + a * p[2]], 1.0 + a * d); + } + let mut back = ([0.0f32; 3], 0.0f32); + for x in (0..n).rev() { + if x + 1 < n && rg[x] != rg[x + 1] { + back = ([0.0; 3], 0.0); + } + back = ([src[x][0] + a * back.0[0], src[x][1] + a * back.0[1], src[x][2] + a * back.0[2]], 1.0 + a * back.1); + let den = fwd[x].1 + back.1 - 1.0; + row[x] = std::array::from_fn(|c| (fwd[x].0[c] + back.0[c] - src[x][c]) / den); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + chunks.par_iter_mut().for_each(f); + } + #[cfg(target_arch = "wasm32")] + chunks.iter_mut().for_each(f); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn settings(simplicity: f32) -> Settings { + Settings { levels: 4, simplicity, fidelity: 2.0 } + } + + /// Labels drawn as text, one character per pixel. + fn labels(rows: &[&str]) -> (Vec, usize, usize) { + (rows.iter().flat_map(|r| r.bytes()).collect(), rows[0].len(), rows.len()) + } + + #[test] + fn components_are_four_connected_and_numbered_in_raster_order() { + let (l, w, h) = labels(&["aab", "abb", "bba"]); + let (comp, n) = components(&l, w, h); + // The top-left `a`s, the `b`s (one area), then the lone `a` (touching the first only + // diagonally), in the order their first pixels come. + assert_eq!(n, 3); + assert_eq!(comp, vec![0, 0, 1, 0, 1, 1, 1, 1, 2]); + // A U shape: both arms are found as separate runs first and joined further down. + let (l, w, h) = labels(&["a.a", "a.a", "aaa"]); + let (comp, n) = components(&l, w, h); + assert_eq!(n, 2); + assert_eq!(comp[0], comp[2]); + } + + /// Regions from labels, with one flat colour per label. + fn merged(rows: &[&str], simplicity: f32) -> (Vec, Vec) { + let (l, w, h) = labels(rows); + let c: Vec = l.iter().map(|&b| [f32::from(b - b'a') / 4.0; 3]).collect(); + let (comp, n) = components(&l, w, h); + merge_regions(&comp, n, &c, w, h, &settings(simplicity)) + } + + #[test] + fn small_regions_merge_into_the_neighbour_they_share_most_border_with() { + let rows = ["aaaaaaaa", "aaaaaaaa", "aacaaaaa", "aaccbbbb", "aaaabbbb", "aaaabbbb", "aaaabbbb"]; + // At Edge Simplicity 0 every region is kept. + assert_eq!(merged(&rows, 0.0).1.len(), 3); + // At 1 (regions under four pixels merge) the three `c`s go into the `a`s, which they share seven + // cracks with (one with the `b`s). + let (reg, colours) = merged(&rows, 1.0); + assert_eq!(colours.len(), 2); + assert_eq!(reg[2 * 8 + 2], reg[0]); + assert_ne!(reg[3 * 8 + 4], reg[0]); + // A region's colour is the mean of its pixels: 37 `a`s (0.0) and 3 `c`s (0.5). + let a = colours[reg[0] as usize][0]; + assert!((a - 1.5 / 40.0).abs() < 1e-6, "{a}"); + } + + #[test] + fn slivers_merge_though_they_are_large() { + // A line one pixel wide between two areas: the blend along an edge, not a shape. + let rows: Vec = (0..40).map(|_| format!("{}c{}", "a".repeat(10), "b".repeat(9))).collect(); + let rows: Vec<&str> = rows.iter().map(String::as_str).collect(); + assert_eq!(merged(&rows, 0.0).1.len(), 3, "kept at Edge Simplicity 0"); + let (_, colours) = merged(&rows, 4.0); + assert_eq!(colours.len(), 2, "40 pixels is over the 25 that merge at 4, but it is a sliver"); + } + + #[test] + fn paper_is_stretched_towards_black_and_white_and_keeps_its_hue() { + // Three regions: a dark and a light grey, and a mid-tone orange. + let lab = [[0.35, 0.0, 0.0], [0.65, 0.0, 0.0], [0.5, 0.06, 0.05]]; + let reg: Vec = (0..300).map(|i| (i / 100) as u32).collect(); + let px: Vec = reg.iter().map(|&r| lab[r as usize]).collect(); + let paper: Vec = paper_colours(®, 3, &px).into_iter().map(oklab).collect(); + assert!(paper[0][0] < 0.25 && paper[1][0] > 0.75, "{paper:?}"); + assert!((paper[2][0] - 0.5).abs() < 0.05, "a middle tone stays in the middle: {paper:?}"); + assert!((paper[2][2] / paper[2][1] - 0.05 / 0.06).abs() < 0.05, "hue kept: {paper:?}"); + assert!(paper[0][1].abs() < 1e-3 && paper[0][2].abs() < 1e-3, "grey stays grey: {paper:?}"); + } + + #[test] + fn local_colour_drifts_within_a_shape_but_never_crosses_a_cut() { + // One light region, pink on the left and cream on the right, next to a blue one. + let (w, h) = (30usize, 4usize); + let reg: Vec = (0..w * h).map(|i| u32::from(i % w >= 20)).collect(); + let lab: Vec = (0..w * h) + .map(|i| match i % w { + 0..10 => [0.8, 0.08, 0.02], + 10..20 => [0.8, 0.01, 0.04], + _ => [0.4, -0.02, -0.12], + }) + .collect(); + let paper = [srgb([0.8, 0.04, 0.03]).unwrap_or_default(), srgb([0.4, -0.02, -0.12]).unwrap_or_default()]; + let out: Vec = local_paper(®, &paper, &lab, w, h, 3.0).into_iter().map(oklab).collect(); + let (left, right, edge) = (out[w + 2], out[w + 17], out[w + 19]); + assert!(left[1] > right[1] + 0.03, "the pink side is pinker: {left:?} vs {right:?}"); + assert!((left[0] - right[0]).abs() < 0.01, "one lightness across the shape: {left:?} vs {right:?}"); + assert!(edge[2] > 0.0, "no blue from the next shape at the cut: {edge:?}"); + } +} diff --git a/crates/algo/src/cutout/util.rs b/crates/algo/src/cutout/util.rs new file mode 100644 index 0000000000..233c6aaf08 --- /dev/null +++ b/crates/algo/src/cutout/util.rs @@ -0,0 +1,84 @@ +//! Small helpers shared by the Cutout stages. + +use std::hash::Hasher; + +use super::Px; +use crate::par; + +/// Row-major `w`×`h` colours as `h`×`w` (columns become rows), so a pass along rows can run +/// along columns too. +pub(super) fn transpose(buf: &[Px], w: usize, h: usize) -> Vec { + let mut out = vec![[0.0f32; 3]; w * h]; + par::chunks_mut(&mut out, h, true, |x, col| { + for (y, p) in col.iter_mut().enumerate() { + *p = buf[y * w + x]; + } + }); + out +} + +/// [`transpose`] for region ids. +pub(super) fn transpose_u32(buf: &[u32], w: usize, h: usize) -> Vec { + let mut out = vec![0u32; w * h]; + for (x, col) in out.chunks_mut(h).enumerate() { + for (y, p) in col.iter_mut().enumerate() { + *p = buf[y * w + x]; + } + } + out +} + +/// Union-find root of `i`, halving the path on the way. +pub(super) fn find(parent: &mut [u32], mut i: u32) -> u32 { + while parent[i as usize] != i { + let p = parent[i as usize]; + parent[i as usize] = parent[p as usize]; + i = p; + } + i +} + +/// A fast deterministic hasher for the region adjacency map. +#[derive(Default)] +pub(super) struct FxHasher(u64); + +impl Hasher for FxHasher { + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + fn write_u64(&mut self, v: u64) { + self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x517c_c1b7_2722_0a95); + } + fn finish(&self) -> u64 { + self.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn transposing_twice_gives_the_image_back() { + let (w, h) = (5usize, 3usize); + let c: Vec = (0..w * h).map(|i| [i as f32, 0.0, 0.0]).collect(); + let t = transpose(&c, w, h); + assert_eq!(t[1], c[w], "the second value of the first column is the first of the second row"); + assert_eq!(transpose(&t, h, w), c); + let ids: Vec = (0..(w * h) as u32).collect(); + assert_eq!(transpose_u32(&ids, w, h), t.iter().map(|p| p[0] as u32).collect::>()); + assert_eq!(transpose_u32(&transpose_u32(&ids, w, h), h, w), ids); + } + + #[test] + fn find_returns_the_root_and_shortens_the_path() { + // 4 -> 3 -> 2 -> 1 -> 0. + let mut parent = vec![0, 0, 1, 2, 3]; + assert_eq!(find(&mut parent, 4), 0); + assert_eq!(find(&mut parent, 0), 0); + assert!(parent[4] < 3, "the path was halved: {parent:?}"); + assert!(parent.iter().all(|&p| p <= 2)); + } +} diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 04acf276da..03ffe38144 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -26,6 +26,7 @@ mod blur2; pub mod camera_raw; pub mod color_to_alpha; pub mod content_aware; +mod cutout; mod denoise; pub mod dff; pub mod direct; @@ -72,6 +73,7 @@ pub mod seam; pub mod segment; pub mod selection; mod selection_blur; +pub mod separable; mod shape_blur; mod sharpen; pub mod stack; @@ -564,6 +566,9 @@ impl FilterParams { pub fn halo(&self) -> Halo { let g = |sigma: f32| Halo::Radius(((sigma.max(0.0) * 3.0).ceil() as i32).saturating_add(1)); match self { + // Small Gaussian radii use the calibrated seven-tap kernel as well: its reach is + // three pixels even when ceil(3 * radius) + 1 would be smaller. + FilterParams::GaussianBlur { radius } | FilterParams::HighPass { radius } if (0.05..1.0).contains(radius) => Halo::Radius(3), FilterParams::GaussianBlur { radius } | FilterParams::HighPass { radius } => g(*radius), FilterParams::UnsharpMask { radius, .. } => Halo::Radius(sharpen::exact::halo(*radius)), FilterParams::SmartSharpen { radius, .. } => g(*radius), @@ -730,6 +735,7 @@ fn halo_ext(p: &FilterParams) -> Halo { FilterParams::PathBlur { paths } => r(paths.iter().map(|p| p.speed.abs()).fold(0.0, f32::max) / 2.0 + 1.0), FilterParams::Custom { .. } => r(2.0), FilterParams::DeInterlace { .. } => r(1.0), + FilterParams::FilterGallery { effects } if artistic_fx::is_global(effects) => Halo::Bounds, FilterParams::FilterGallery { effects } => Halo::Radius(artistic_fx::reach(effects)), _ => Halo::Radius(0), } @@ -1120,6 +1126,14 @@ fn apply_tiled_with_impl( } } let shared = (halo == Halo::Bounds).then(|| Image::read(surface, bounds.union(&area))); + // A Filter Gallery stack with a Cutout traces the whole image once; tiles only fill it in. + let gallery = match (params, &shared) { + (FilterParams::FilterGallery { effects }, Some(src)) => artistic_fx::Prepared::new(effects, src, &ctx), + _ => None, + }; + if ctl.cancelled() { + return None; + } // Shape rasterization depends only on params, not on a tile's pixels. let shape = match params { FilterParams::ShapeBlur { radius, shape } => { @@ -1197,6 +1211,7 @@ fn apply_tiled_with_impl( } }; let Some(mut data) = (match (&shape, &radial) { + _ if gallery.is_some() => gallery.as_ref().map(|g| g.run(src, *t, &ctx)), (Some(shape), _) => shape.checked_run(src, *t, &ctx), (None, Some(plan)) => match plan.filter(src, *t, &ctx, ctl) { Some(data) => Some(data), diff --git a/crates/algo/src/matting.rs b/crates/algo/src/matting.rs index f4bfccb0b5..0901dab0c0 100644 --- a/crates/algo/src/matting.rs +++ b/crates/algo/src/matting.rs @@ -35,7 +35,9 @@ pub struct RefineParams { pub feather: f32, /// 0–100. pub contrast: f32, - /// −100–100. 100% moves the edge by `max(radius, 4)` pixels. Values between whole + /// −100–100. 100% moves the edge by its soft width: `max(radius, feather, 2 × smooth σ)`, + /// at least 1 px, so a hard edge moves a pixel (Photoshop's Shift Edge moves soft borders; + /// a band of several pixels around hard line art fills it in solid). Values between whole /// pixels blend the two neighbouring shifts, so the slider does not jump. pub shift_edge: f32, } @@ -60,9 +62,11 @@ impl RefineParams { fn feather_sigma(&self) -> f32 { self.feather.max(0.0) / 2.0 } - /// Signed shift in pixels, fractional. 100% is `max(radius, 4)` px, clamped to ±64. + /// Signed shift in pixels, fractional. 100% is the edge's soft width (at least 1 px), + /// clamped to ±64. fn shift_amount(&self) -> f32 { - let px = self.shift_edge.clamp(-100.0, 100.0) / 100.0 * self.radius.max(4.0); + let soft = self.radius.max(self.feather).max(2.0 * self.smooth_sigma()).max(1.0); + let px = self.shift_edge.clamp(-100.0, 100.0) / 100.0 * soft; if px.is_finite() { px.clamp(-64.0, 64.0) } else { 0.0 } } /// How many pixels the mask can move: the farther of the two integer radii a fractional @@ -765,22 +769,24 @@ mod tests { assert!(f[5 * w + 29] > 0.5 && f[5 * w + 29] < 0.8 && f[5 * w + 31] > 0.1); let c = refine_buffer(None, &f, w, h, &RefineParams { contrast: 100.0, ..Default::default() }); assert!(c[5 * w + 29] == 1.0 && c[5 * w + 31] == 0.0); + // A hard edge (no radius, feather or smooth) moves 1 px at 100%, so 50% is half a + // pixel. The pixel just outside fades in instead of snapping on. let grown = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: 100.0, ..Default::default() }); - assert_eq!(grown[5 * w + 33], 1.0); - assert_eq!(grown[5 * w + 34], 0.0); - let shrunk = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: -50.0, ..Default::default() }); - assert_eq!(shrunk[5 * w + 27], 1.0); - assert_eq!(shrunk[5 * w + 28], 0.0); - // Radius 0 scales 100% to 4 px, so 12.5% is half a pixel and 25% is one pixel. - // The pixel just outside a hard edge fades in instead of snapping on. - let half = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: 12.5, ..Default::default() }); - let one = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: 25.0, ..Default::default() }); assert_eq!(m[5 * w + 30], 0.0); + assert_eq!(grown[5 * w + 30], 1.0); + assert_eq!(grown[5 * w + 31], 0.0); + let shrunk = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: -100.0, ..Default::default() }); + assert_eq!(shrunk[5 * w + 28], 1.0); + assert_eq!(shrunk[5 * w + 29], 0.0); + let half = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: 50.0, ..Default::default() }); assert!((half[5 * w + 30] - 0.5).abs() < 0.02, "half pixel {}", half[5 * w + 30]); - assert_eq!(one[5 * w + 30], 1.0); assert_eq!(half[5 * w + 31], 0.0, "the blend must not jump a second pixel"); - let pulled = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: -12.5, ..Default::default() }); + let pulled = refine_buffer(None, &m, w, h, &RefineParams { shift_edge: -50.0, ..Default::default() }); assert!((pulled[5 * w + 29] - 0.5).abs() < 0.02, "half-pixel contract {}", pulled[5 * w + 29]); + // A softer edge moves farther: 100% is the feather, here 4 px. + let wide = refine_buffer(None, &m, w, h, &RefineParams { feather: 4.0, contrast: 100.0, shift_edge: 100.0, ..Default::default() }); + assert_eq!(wide[5 * w + 33], 1.0); + assert_eq!(wide[5 * w + 34], 0.0); let sm = refine_buffer(None, &m, w, h, &RefineParams { smooth: 50.0, ..Default::default() }); assert!(sm[5 * w + 10] == 1.0 && sm[5 * w + 50] == 0.0); } diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs index 3b22ed05a5..0eef6b98ca 100644 --- a/crates/algo/src/quantize.rs +++ b/crates/algo/src/quantize.rs @@ -286,7 +286,7 @@ fn sort_along(b: &mut Vec<([f32; 3], u32)>, axis: usize) { } /// Median cut over `pts` (feature vectors + weights) into at most `n` boxes; returns box means. -fn median_cut(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { +pub(crate) fn median_cut(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { if pts.is_empty() || n == 0 { return Vec::new(); } @@ -334,7 +334,7 @@ fn median_cut(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { } /// Lloyd refinement of `centers` over weighted points. -fn kmeans(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) { +pub(crate) fn kmeans(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) { if centers.is_empty() { // No room left (the forced colours fill the palette): nothing to refine. return; diff --git a/crates/algo/src/separable.rs b/crates/algo/src/separable.rs new file mode 100644 index 0000000000..9ab6220135 --- /dev/null +++ b/crates/algo/src/separable.rs @@ -0,0 +1,191 @@ +//! Separable blurs described as data, so another device (the GPU compositor's layer operators, +//! #5772) runs exactly the blur the CPU runs: the kernel weights or box widths come from here, +//! and [`crate::blur`] builds its own passes from the same description, so the two can't drift. +//! +//! [`OperatorRegion`] is the region rule that goes with it: which source pixels an output area +//! reads, with the edge pixels repeated at the extent as the CPU filters do. + +use photocraft_geom::Rect; + +use crate::{FilterParams, blur}; + +/// A blur made of passes along each axis, horizontal first, as the CPU runs it. +#[derive(Clone, Debug, PartialEq)] +pub enum Separable { + /// One pass of this normalised kernel (odd length, centred) along each axis. + Kernel(Vec), + /// Running-mean box passes of these odd widths, in turn, along each axis. + Boxes(Vec), +} + +impl Separable { + /// The blur `params` runs on the CPU, or `None` for a filter that isn't one (only Gaussian + /// Blur so far). Small radii use the exact kernel, larger ones three box passes. + pub fn of(params: &FilterParams) -> Option { + match *params { + FilterParams::GaussianBlur { radius } => Some(match blur::box_widths(params) { + Some(boxes) => Separable::Boxes(boxes), + None => Separable::Kernel(blur::gaussian_blur_kernel(radius)), + }), + _ => None, + } + } + + /// How far outside an output pixel the blur reads, along each axis. + pub fn reach(&self) -> i32 { + let reach = match self { + Separable::Kernel(k) => k.len() / 2, + Separable::Boxes(boxes) => boxes.iter().fold(0usize, |sum, w| sum.saturating_add(w / 2)), + }; + i32::try_from(reach).unwrap_or(i32::MAX) + } +} + +/// The area a neighbourhood filter on a layer repeats its edge pixels at: the canvas, or past it +/// where the layer has pixels off the canvas, as Photoshop does. +pub fn edge_extent(canvas: Rect, content: Rect) -> Rect { + canvas.union(&content) +} + +/// Which source pixels an output area of a blur reads. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OperatorRegion { + /// How far the blur reads outside an output pixel ([`Separable::reach`]). + pub reach: i32, + /// Where the source's edge pixels repeat ([`edge_extent`]): nothing outside it is read. + pub extent: Rect, +} + +impl OperatorRegion { + /// The source pixels output `out` reads: `out` grown by the reach, inside the extent. Pixels + /// it needs beyond the extent repeat the edge of this area, so they need no source of their + /// own. Empty when `out` is empty or doesn't come within reach of the extent. + pub fn input(&self, out: Rect) -> Rect { + if out.is_empty() { + return Rect::EMPTY; + } + out.inflate(self.reach.max(0)).intersect(&self.extent) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Halo; + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + use photocraft_raster::{Interrupt, Surface}; + + const RADII: [f32; 11] = [0.01, 0.05, 0.1, 0.3, 0.8, 2.0, 4.0, 4.5, 12.0, 40.0, 250.0]; + + /// The CPU blur's own choice: the exact kernel up to radius 4, boxes beyond; and its halo + /// (how far the CPU grows an output area) covers the reach. + #[test] + fn the_description_is_the_cpus_blur() { + for radius in RADII { + let params = FilterParams::GaussianBlur { radius }; + let blur = Separable::of(¶ms).unwrap(); + match &blur { + Separable::Kernel(k) => { + assert!(radius <= 4.0, "radius {radius}"); + assert_eq!(k, &blur::gaussian_blur_kernel(radius)); + assert_eq!(k.len() % 2, 1); + assert!((k.iter().sum::() - 1.0).abs() < 1e-5); + } + Separable::Boxes(b) => { + assert!(radius > 4.0, "radius {radius}"); + assert_eq!(Some(b.clone()), blur::box_widths(¶ms)); + assert!(b.iter().all(|w| w % 2 == 1)); + } + } + let Halo::Radius(halo) = params.halo() else { panic!("a Gaussian has a radius halo") }; + assert!(blur.reach() <= halo, "radius {radius}: reach {} past the halo {halo}", blur.reach()); + } + assert_eq!(Separable::of(&FilterParams::BoxBlur { radius: 9.0 }), None, "not a Gaussian (yet)"); + assert_eq!(Separable::Boxes(vec![usize::MAX, 3]).reach(), i32::MAX, "saturates"); + } + + /// One opaque pixel in a transparent layer, blurred on the CPU, spreads no further than the + /// reach (beyond it the box passes' running sums leave only float residue, far below a + /// 16-bit level), and the exact kernel spreads exactly that far. + #[test] + fn an_impulse_spreads_no_further_than_the_reach() { + for radius in RADII { + let params = FilterParams::GaussianBlur { radius }; + let reach = Separable::of(¶ms).unwrap().reach(); + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let size = 2 * reach + 41; + let canvas = Rect::new(0, 0, size, size); + let mut s = Surface::new(fmt); + let dot = Rect::new(size / 2, size / 2, size / 2 + 1, size / 2 + 1); + s.fill_rect(dot, &[1.0, 1.0, 1.0, 1.0]); + let out = crate::apply_in_with(&s, ¶ms, canvas, canvas, None, canvas, &Interrupt::NONE).unwrap(); + let mut px = Vec::new(); + out.read_region_into(canvas, &mut px); + let touched = px + .as_chunks::<4>() + .0 + .iter() + .enumerate() + // The box passes' running sums leave float residue (~1e-8) after the impulse. + .filter(|(_, p)| p[3] > 1e-6) + .fold(Rect::EMPTY, |r, (i, _)| { + let (x, y) = ((i as i32) % size, (i as i32) / size); + r.union(&Rect::new(x, y, x + 1, y + 1)) + }); + // Nothing past the reach; the exact kernel reaches all of it. (A single pixel's box + // tails are smaller than the running sums' residue, so they aren't checked for that.) + assert!(dot.inflate(reach).contains_rect(&touched), "radius {radius}: {touched:?} past the reach {reach}"); + if let Some(Separable::Kernel(k)) = Separable::of(¶ms) { + // Calibrated subpixel kernels have tails below the visibility threshold. + let center = k.len() / 2; + let visible = k.iter().enumerate().filter(|(_, w)| **w * k[center] > 1e-6).map(|(i, _)| i.abs_diff(center)).max().unwrap_or(0); + assert_eq!(touched, dot.inflate(visible as i32), "radius {radius}"); + } + } + } + + /// Pixels outside [`OperatorRegion::input`] don't change an output area's result, and the + /// edge repeats at the extent: a layer's area next to the extent's edge blurs the same + /// whatever lies beyond it. + #[test] + fn output_depends_only_on_the_input_region() { + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let extent = Rect::new(0, 0, 300, 200); + let noise = |seed: u32| { + let mut s = Surface::new(fmt); + for y in 0..200 { + for x in 0..300 { + let h = (x as u32).wrapping_mul(73_856_093) ^ (y as u32).wrapping_mul(19_349_663) ^ seed; + let v = (h % 1000) as f32 / 999.0; + s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, 1.0 - v, (h % 7) as f32 / 6.0, (h % 5) as f32 / 4.0]); + } + } + s + }; + let a = noise(1); + for radius in [0.8, 4.0, 12.0] { + let params = FilterParams::GaussianBlur { radius }; + let region = OperatorRegion { reach: Separable::of(¶ms).unwrap().reach(), extent }; + for out in [Rect::new(100, 80, 140, 120), Rect::new(0, 0, 30, 25), Rect::new(270, 170, 300, 200)] { + let input = region.input(out); + assert!(extent.contains_rect(&input) && input.contains_rect(&out)); + // Everything outside the input region replaced by other pixels. + let mut b = noise(2); + let mut inside = Vec::new(); + a.read_region_into(input, &mut inside); + b.write_region(input, &inside); + let blur = |s: &Surface| { + let r = crate::apply_in_with(s, ¶ms, out, extent, None, extent, &Interrupt::NONE).unwrap(); + let mut px = Vec::new(); + r.read_region_into(out, &mut px); + px + }; + assert_eq!(blur(&a), blur(&b), "radius {radius}, {out:?}"); + } + } + assert_eq!(OperatorRegion { reach: 5, extent }.input(Rect::EMPTY), Rect::EMPTY); + assert_eq!(OperatorRegion { reach: 5, extent }.input(Rect::new(400, 400, 410, 410)), Rect::EMPTY, "out of reach of the extent"); + assert_eq!(OperatorRegion { reach: -3, extent }.input(Rect::new(10, 10, 20, 20)), Rect::new(10, 10, 20, 20)); + assert_eq!(edge_extent(extent, Rect::new(-10, 50, 20, 60)), Rect::new(-10, 0, 300, 200)); + } +} diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 98ccc9a24a..92ece2b943 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -86,6 +86,9 @@ impl Headless { match method { "engine.execute" => { let id = str_of(&p, "command").ok_or_else(|| bad("engine.execute needs `command`"))?; + if METHODS.contains(&id) && photocraft_engine::commands::find(id).is_none() { + return Err(bad(photocraft_engine::command_hints::protocol_method_as_command(id))); + } let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true); self.command_start(id, p.get("params").cloned().unwrap_or(Value::Null), wait) } @@ -186,7 +189,7 @@ impl Headless { "doc.close" => self.close(index_of(&p)?), "batch" => self.batch(&p), "methods" => Ok(json!(METHODS)), - other => Err(bad(format!("unknown method `{other}` (try `methods`)"))), + other => Err(bad(format!("{} (try `methods`)", photocraft_engine::command_hints::unknown_method(other, METHODS)))), } } diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 5136b0363b..131df72413 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -268,7 +268,8 @@ fn doc_save_rejects_a_bad_quality_instead_of_ignoring_or_clamping_it() { } h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": 85})).unwrap(); let bytes = std::fs::read(&path).unwrap(); - assert_eq!(bytes.get(12..16), Some(&b"VP8 "[..]), "a WebP saved with a quality is lossy"); + // The lossy chunk; an extended WebP (one carrying a colour profile) puts `VP8X` first. + assert!(bytes.windows(4).any(|c| c == b"VP8 ") && !bytes.windows(4).any(|c| c == b"VP8L"), "a WebP saved with a quality is lossy"); std::fs::remove_dir_all(dir).unwrap(); } @@ -817,6 +818,23 @@ fn methods_lists_the_job_methods_and_every_listed_name_is_served() { assert!(h.handle("jobs.nope", Value::Null).unwrap_err().to_string().contains("unknown method")); } +/// #3674: a guessed name gets a pointer to the right one, in both directions. +#[test] +fn unknown_names_suggest_the_right_method_or_command() { + let mut h = Headless::new(); + let err = |h: &mut Headless, m: &str, p: Value| h.handle(m, p).unwrap_err().to_string(); + let e = err(&mut h, "engine.execute", json!({"command": "engine.commands"})); + assert!(e.contains("did you mean `command.list`") && e.contains("protocol method"), "{e}"); + let e = err(&mut h, "engine.execute", json!({"command": "doc.inspect"})); + assert!(e.contains("`doc.inspect` is a protocol method"), "{e}"); + let e = err(&mut h, "engine.execute", json!({"command": "edit.undoo"})); + assert!(e.contains("did you mean `edit.undo`"), "{e}"); + let e = err(&mut h, "doc.inspct", Value::Null); + assert!(e.contains("did you mean `doc.inspect`") && e.contains("(try `methods`)"), "{e}"); + let e = err(&mut h, "edit.undo", Value::Null); + assert!(e.contains("engine.execute {\"command\": \"edit.undo\"}"), "{e}"); +} + #[test] fn batch_response_budget_stops_later_steps_even_when_stop_on_error_is_false() { let mut h = Headless::new(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 61a6454e79..544dbc90f1 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -342,7 +342,9 @@ pub struct UiSetParams { /// cropOverlayOrientation (0..3), cropShield (an object patching show_cropped_area, enabled, /// color ("matchCanvas" or "custom"), custom_color ([r, g, b]), opacity (0..100), /// auto_adjust, classic_mode and auto_center_preview), cropFill (background or contentAware, - /// the Crop tool's Fill), shapeStroke (an object patching width, align, cap, join, miterLimit, + /// the Crop tool's Fill), penMode (path or shape, the Pen tools' mode), penPathOp (newLayer, + /// combine, subtract, intersect or exclude: how the next Pen path joins the selected shape + /// layer or path), shapeStroke (an object patching width, align, cap, join, miterLimit, /// dashes, dashOffset and opacity; null disables the stroke). Shape stroke fields use /// `shape.edit` names and units; colour comes from `tools.setColors`. camTransformOnDrop (bool, /// the Content-Aware Move tool's Transform On Drop). tileGrid (bool, a developer overlay of the diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 4dd1a5df05..2334a2ff89 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -1,7 +1,7 @@ //! Capability-based filesystem policy for untrusted automation paths. use std::io::{Read, Write}; -use std::path::{Component, Path, PathBuf}; +use std::path::{Component, Components, Path, PathBuf, Prefix}; use std::sync::Arc; use cap_std::ambient_authority; @@ -16,16 +16,18 @@ const DENIED: &str = "automation filesystem access is not granted"; #[derive(Clone)] struct RootCapability { dir: Arc, - /// The root as an absolute path (trusted launch configuration), to recognise absolute request + /// The canonical root path (trusted launch configuration), to recognise absolute request /// paths that name a file beneath it. path: PathBuf, + /// The trusted launch spelling also names the same held capability, even through a link. + configured_path: PathBuf, } /// Separate directory capabilities for automation reads and writes. /// /// Root paths are trusted launch-time configuration. Request paths are always /// untrusted, forward-slash relative paths resolved by `cap-std` beneath the -/// held directory handle, or absolute paths whose text lies beneath the root +/// held directory handle, or absolute paths beneath the canonical or configured root spelling /// (translated to relative ones, see [`request_path`]). Parent traversal, /// alternate separators, Windows prefixes and empty components are rejected /// before I/O. @@ -117,7 +119,10 @@ impl AuthorizedWorkspace { // Best effort, and only when there is a file being replaced: a save still // succeeds for a document whose Finder tag could not come along. if let Ok(old) = root.dir.open(&relative) { + let old = old.into_std(); let _ = photocraft_format::atomic::meta::copy_xattrs(old.as_fd(), file.as_fd()); + // The creation time too (#9388), through the same handles. + let _ = photocraft_format::atomic::meta::copy_created_file(&old, &file); } } // Falls back to a plain fsync on shares that refuse a full flush (#1336). @@ -190,35 +195,60 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result) -> Result { - let Some(root) = root.filter(|_| Path::new(raw).is_absolute()) else { return relative_path(raw) }; - let mut request = Path::new(raw).components(); - for want in root.path.components() { - let same = match (request.next(), want) { - (Some(Component::Prefix(a)), Component::Prefix(b)) => a.as_os_str().eq_ignore_ascii_case(b.as_os_str()), - (Some(got), want) => got == want, - (None, _) => false, + let path = Path::new(raw); + let Some(root) = root.filter(|_| path.is_absolute()) else { return relative_path(raw) }; + // Prefer the trusted launch spelling: it can itself contain `..`. Only that + // exact granted prefix is exempt; traversal in the remaining request still fails below. + let request = path_beneath_root(path, &root.configured_path) + .or_else(|| path_beneath_root(path, &root.path)) + .ok_or_else(|| path_error(raw, "absolute paths must be inside the automation root"))?; + let rest = request.map(|c| c.as_os_str().to_str().ok_or_else(|| path_error(raw, "path is not UTF-8"))).collect::, _>>()?; + relative_path(&rest.join("/")) +} + +/// Strip a granted root prefix without resolving the client path with ambient authority. +/// Windows ASCII case variants name the same grant; the unstripped suffix keeps its case. +fn path_beneath_root<'a>(path: &'a Path, root: &Path) -> Option> { + let mut request = path.components(); + for want in root.components() { + let same = match (request.next()?, want) { + (Component::Prefix(a), Component::Prefix(b)) => match (a.kind(), b.kind()) { + // std::fs::canonicalize uses verbatim paths on Windows. Accept their ordinary + // drive/UNC spelling too, without treating a device prefix as a disk prefix. + (Prefix::Disk(a) | Prefix::VerbatimDisk(a), Prefix::Disk(b) | Prefix::VerbatimDisk(b)) => a.eq_ignore_ascii_case(&b), + (Prefix::UNC(a, b) | Prefix::VerbatimUNC(a, b), Prefix::UNC(c, d) | Prefix::VerbatimUNC(c, d)) => { + a.eq_ignore_ascii_case(c) && b.eq_ignore_ascii_case(d) + } + _ => a.as_os_str().eq_ignore_ascii_case(b.as_os_str()), + }, + #[cfg(windows)] + (Component::Normal(a), Component::Normal(b)) => a.eq_ignore_ascii_case(b), + (got, want) => got == want, }; if !same { - return Err(path_error(raw, "absolute paths must be inside the automation root")); + return None; } } - let rest: Vec<&str> = request.map(|c| c.as_os_str().to_str().unwrap_or("\u{FFFD}")).collect(); - relative_path(&rest.join("/")) + Some(request) } fn relative_path(raw: &str) -> Result { diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index ad5138ef12..4cafd976f9 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -162,6 +162,22 @@ fn write_refuses_a_fifo_target_without_blocking() { assert!(temp_files(&inside).is_empty()); } +/// #9401 review: replacing a file through the automation path keeps its creation time, the +/// same as a save through `atomic_write` does on macOS (#9388). +#[cfg(target_os = "macos")] +#[test] +fn write_keeps_the_replaced_files_creation_time() { + use std::os::macos::fs::FileTimesExt; + let (inside, _, workspace) = roots("created"); + let path = inside.join("doc.psd"); + workspace.write("doc.psd", b"original").unwrap(); + let born = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_times(std::fs::FileTimes::new().set_created(born)).unwrap(); + workspace.write("doc.psd", b"replacement").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"replacement"); + assert_eq!(std::fs::metadata(&path).unwrap().created().unwrap(), born, "the creation time survives the automation write"); +} + /// #7095: replacing a file through the automation path keeps the old file's extended /// attributes, the same as a save through `atomic_write` does. #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] @@ -536,6 +552,8 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool { | "path.convertPoint" | "path.addAnchor" | "path.deleteAnchor" + | "path.mergeShapeComponents" + | "path.setOperation" | "path.clippingPath.set" | "path.rename" | "path.stroke" @@ -638,6 +656,217 @@ fn absolute_paths_beneath_the_root_are_translated_and_others_refused() { assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); } +/// Equivalent drive, UNC and ASCII-case root spellings need no ambient path resolution. +#[cfg(windows)] +#[test] +fn canonical_windows_prefixes_match_without_ambient_resolution() { + for (request, root) in [ + (r"c:\root\new.bin", r"\\?\C:\root"), + (r"\\?\C:\root\new.bin", r"C:\root"), + (r"\\server\share\root\new.bin", r"\\?\UNC\SERVER\SHARE\root"), + (r"c:\ROOT\new.bin", r"\\?\C:\root"), + (r"\\?\C:\ROOT\new.bin", r"c:\root"), + (r"\\server\share\ROOT\new.bin", r"\\?\UNC\SERVER\SHARE\root"), + ] { + let remaining = path_beneath_root(Path::new(request), Path::new(root)).unwrap(); + assert_eq!(remaining.as_path(), Path::new("new.bin")); + } + for request in [r"C:\root-sibling\new.bin", r"D:\root\new.bin", r"\\.\C:\root\new.bin", r"\\other\share\root\new.bin"] { + assert!(path_beneath_root(Path::new(request), Path::new(r"\\?\C:\root")).is_none()); + } +} + +/// Case variants of the granted Windows prefix still use its held directory capability. +#[cfg(windows)] +#[test] +fn windows_root_case_variants_keep_io_inside_the_grant() { + let (inside, outside, workspace) = roots("root-case"); + let configured = PathBuf::from(inside.to_string_lossy().to_ascii_uppercase()); + let canonical = PathBuf::from(std::fs::canonicalize(&inside).unwrap().to_string_lossy().to_ascii_uppercase()); + for spelling in [&configured, &canonical] { + let path = spelling.join("new.png"); + workspace.write(&path.to_string_lossy(), b"inside").unwrap(); + assert_eq!(workspace.read(&path.to_string_lossy()).unwrap(), b"inside"); + assert!(workspace.write(&spelling.join("..").join("outside").join("blocked.bin").to_string_lossy(), b"no").is_err()); + } + assert_eq!(std::fs::read(inside.join("new.png")).unwrap(), b"inside"); + assert!(workspace.write(&configured.with_file_name("INSIDE-SIBLING").join("blocked.bin").to_string_lossy(), b"no").is_err()); + assert!(!outside.join("blocked.bin").exists()); + // Case normalization must not bypass the refusal to replace unrelated existing files. + std::fs::write(inside.join("notes.bin"), b"keep").unwrap(); + assert!(workspace.write(&configured.join("notes.bin").to_string_lossy(), b"no").is_err()); + assert_eq!(std::fs::read(inside.join("notes.bin")).unwrap(), b"keep"); +} + +/// Unix roots with different case must not become aliases of the granted prefix. +#[cfg(unix)] +#[test] +fn unix_root_prefixes_remain_case_sensitive() { + assert!(path_beneath_root(Path::new("/Root/new.bin"), Path::new("/root")).is_none()); +} + +#[test] +fn configured_parent_components_accept_resolved_absolute_paths() { + let (inside, outside, _) = roots("resolved-parent-root"); + let configured = inside.join("..").join("inside"); + let workspace = AuthorizedWorkspace::new(Some(&configured), Some(&configured)).unwrap(); + let resolved = std::fs::canonicalize(&inside).unwrap(); + workspace.write(&resolved.join("new.bin").to_string_lossy(), b"new").unwrap(); + assert_eq!(workspace.read(&resolved.join("new.bin").to_string_lossy()).unwrap(), b"new"); + workspace.write(&configured.join("launch-spelling.bin").to_string_lossy(), b"trusted prefix").unwrap(); + assert_eq!(workspace.read(&configured.join("launch-spelling.bin").to_string_lossy()).unwrap(), b"trusted prefix"); + assert_eq!(workspace.read(&resolved.join("launch-spelling.bin").to_string_lossy()).unwrap(), b"trusted prefix"); + assert!(workspace.write(&configured.join("..").join("outside/escaped.bin").to_string_lossy(), b"no").is_err()); + assert!(!outside.join("escaped.bin").exists()); + assert!(workspace.write(&outside.join("blocked.bin").to_string_lossy(), b"no").is_err()); + assert!(!outside.join("blocked.bin").exists()); +} + +#[test] +fn relative_configured_root_accepts_resolved_absolute_paths() { + let relative = PathBuf::from("target").join(format!("automation-relative-root-{}", std::process::id())); + std::fs::create_dir_all(&relative).unwrap(); + let workspace = AuthorizedWorkspace::new(Some(&relative), Some(&relative)).unwrap(); + let resolved = std::fs::canonicalize(&relative).unwrap(); + workspace.write(&resolved.join("new.bin").to_string_lossy(), b"relative").unwrap(); + assert_eq!(workspace.read(&resolved.join("new.bin").to_string_lossy()).unwrap(), b"relative"); + std::fs::remove_file(resolved.join("new.bin")).unwrap(); + drop(workspace); + std::fs::remove_dir(resolved).unwrap(); +} + +#[cfg(unix)] +#[test] +fn trusted_root_names_are_not_validated_as_relative_request_names() { + let (inside, outside, _) = roots("trusted-root-names"); + let root = inside.join("aux"); + std::fs::create_dir(&root).unwrap(); + let alias = outside.join("CON"); + link_directory(&root, &alias); + let workspace = AuthorizedWorkspace::new(Some(&alias), Some(&alias)).unwrap(); + for (index, spelling) in [&root, &alias].into_iter().enumerate() { + let fresh = spelling.join(format!("new-{index}.bin")); + workspace.write(&fresh.to_string_lossy(), b"trusted").unwrap(); + assert_eq!(workspace.read(&fresh.to_string_lossy()).unwrap(), b"trusted"); + assert!(workspace.write(&fresh.to_string_lossy(), b"replacement").is_err(), "unknown existing files remain protected"); + assert!(workspace.write(&spelling.join("NUL").to_string_lossy(), b"no").is_err()); + } + assert!(!root.join("NUL").exists()); + remove_directory_link(&alias); +} + +// Windows junctions exercise the same root alias without requiring Developer Mode. +#[cfg(any(unix, windows))] +fn link_directory(target: &Path, link: &Path) { + #[cfg(unix)] + std::os::unix::fs::symlink(target, link).unwrap(); + #[cfg(windows)] + assert!(std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(link).arg(target).output().unwrap().status.success()); +} + +#[cfg(any(unix, windows))] +fn remove_directory_link(link: &Path) { + #[cfg(unix)] + std::fs::remove_file(link).unwrap(); + #[cfg(windows)] + std::fs::remove_dir(link).unwrap(); +} + +#[cfg(any(unix, windows))] +#[test] +fn linked_root_accepts_both_spellings_and_new_nested_exports() { + let (inside, outside, _) = roots("linked-root"); + let link = outside.join("root-link"); + link_directory(&inside, &link); + let workspace = AuthorizedWorkspace::new(Some(&link), Some(&link)).unwrap(); + let resolved = std::fs::canonicalize(&inside).unwrap(); + for (i, spelling) in [resolved, link.clone()].iter().enumerate() { + let name = format!("new-{i}.bin"); + workspace.write(&spelling.join(&name).to_string_lossy(), b"new").unwrap(); + assert_eq!(workspace.read(&spelling.join(&name).to_string_lossy()).unwrap(), b"new"); + assert_eq!(workspace.read(&name).unwrap(), b"new"); + let mut export = workspace.export_sequence(&spelling.join(format!("frames-{i}")).join("nested").to_string_lossy()).unwrap(); + export.write("frame.png", b"frame").unwrap(); + export.commit(); + assert_eq!(std::fs::read(inside.join(format!("frames-{i}/nested/frame.png"))).unwrap(), b"frame"); + } + remove_directory_link(&link); +} + +/// TEMP can name the same directory differently from canonicalize (8.3 on Windows). +/// A junction makes that mismatch deterministic even when 8.3 names are disabled. +#[cfg(windows)] +#[test] +fn root_alias_tests_work_with_an_aliased_windows_temp() { + let (inside, outside, _) = roots("aliased-temp"); + let temp_alias = outside.join("temp-alias"); + link_directory(&inside, &temp_alias); + let exe = std::env::current_exe().unwrap(); + for test in [ + "workspace::tests::ungranted_absolute_aliases_and_link_escapes_are_refused", + "workspace::tests::retargeting_root_alias_does_not_regrant_the_held_authority", + ] { + // Set TEMP only in the child; changing the process environment races other tests. + let output = std::process::Command::new(&exe).args(["--exact", test, "--nocapture"]).env("TEMP", &temp_alias).env("TMP", &temp_alias).output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{test}: {stdout}\n{stderr}"); + assert!(stdout.contains("1 passed;"), "child must run the requested test: {stdout}"); + } + remove_directory_link(&temp_alias); +} + +#[cfg(any(unix, windows))] +#[test] +fn ungranted_absolute_aliases_and_link_escapes_are_refused() { + let (inside, outside, workspace) = roots("request-alias"); + // TEMP may use an 8.3 name or a junction. A grant through `alias` below recognises + // that configured alias and the canonical target, not every other name for `inside`. + let resolved_inside = std::fs::canonicalize(&inside).unwrap(); + let alias = outside.join("inside-alias"); + link_directory(&inside, &alias); + workspace.write("new.bin", b"inside").unwrap(); + assert!(workspace.read(&alias.join("new.bin").to_string_lossy()).is_err()); + assert!(workspace.write(&alias.join("ungranted.bin").to_string_lossy(), b"no").is_err()); + assert!(!inside.join("ungranted.bin").exists()); + std::fs::write(outside.join("secret.bin"), b"outside").unwrap(); + let escape = inside.join("escape"); + link_directory(&outside, &escape); + assert!(workspace.read(&escape.join("secret.bin").to_string_lossy()).is_err()); + assert!(workspace.write(&escape.join("blocked.bin").to_string_lossy(), b"no").is_err()); + assert!(workspace.export_sequence(&escape.join("frames").join("nested").to_string_lossy()).is_err()); + assert!(!outside.join("blocked.bin").exists()); + assert!(!outside.join("frames").exists()); + assert_eq!(std::fs::read(outside.join("secret.bin")).unwrap(), b"outside"); + let read_only = AuthorizedWorkspace::new(Some(&alias), Some(&outside)).unwrap(); + assert_eq!(read_only.read(&resolved_inside.join("new.bin").to_string_lossy()).unwrap(), b"inside"); + assert!(read_only.write(&alias.join("denied.bin").to_string_lossy(), b"no").is_err()); + assert!(!inside.join("denied.bin").exists()); + remove_directory_link(&escape); + remove_directory_link(&alias); +} + +#[cfg(any(unix, windows))] +#[test] +fn retargeting_root_alias_does_not_regrant_the_held_authority() { + let (inside, outside, _) = roots("retargeted-root"); + let resolved_inside = std::fs::canonicalize(&inside).unwrap(); + let alias = outside.join("root-alias"); + link_directory(&inside, &alias); + let workspace = AuthorizedWorkspace::new(Some(&alias), Some(&alias)).unwrap(); + remove_directory_link(&alias); + link_directory(&outside, &alias); + std::fs::write(outside.join("secret.bin"), b"secret").unwrap(); + workspace.write("held.bin", b"held").unwrap(); + assert_eq!(workspace.read(&resolved_inside.join("held.bin").to_string_lossy()).unwrap(), b"held"); + assert!(workspace.read(&alias.join("secret.bin").to_string_lossy()).is_err()); + workspace.write(&alias.join("held-alias.bin").to_string_lossy(), b"original grant").unwrap(); + assert_eq!(std::fs::read(inside.join("held-alias.bin")).unwrap(), b"original grant"); + assert!(!outside.join("held-alias.bin").exists()); + assert_eq!(std::fs::read(outside.join("secret.bin")).unwrap(), b"secret"); + remove_directory_link(&alias); +} + /// Each authority is checked against its own root, and none granted refuses absolute paths. #[test] fn absolute_paths_are_checked_against_the_authority_s_own_root() { diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index 0ac5c17a5f..e18df63c4a 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -311,6 +311,10 @@ async fn errors_are_tool_errors_not_crashes() { let r = call(&client, "command_run", json!({"id": "no.such.command"})).await; assert_eq!(r.is_error, Some(true)); assert!(text(&r).contains("unknown command")); + // #3674: the error names the nearest registered id. + let r = call(&client, "command_run", json!({"id": "engine.commands"})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("did you mean `command.list`"), "{}", text(&r)); let r = call(&client, "doc_inspect", json!({"index": 0})).await; assert_eq!(r.is_error, Some(true)); let r = call(&client, "doc_open", json!({"path": "/definitely/missing.png"})).await; diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 3feeb3a97d..d547f064ed 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -225,34 +225,89 @@ pub fn parse_cube(text: &str) -> Result { err("no LUT_3D_SIZE in .cube file") } -/// Lustre `.3dl`: an optional shaper line of input values, then integer RGB rows with **blue** -/// varying fastest; the output bit depth is inferred from the largest value, and is at least 12 -/// bits in a file without a header. +/// Lustre `.3dl`: an optional `3DMESH` magic and `Mesh ` line, an optional +/// shaper line of input values, then integer RGB rows with **blue** varying fastest. The +/// `Mesh` line declares the cube edge (2^inBits + 1) and the output code range (up to +/// 2^outBits − 1), and Photoshop honours both (#9073, #9078); without it the edge is the cube +/// root of the row count and the range is inferred from the largest value (#9121). pub fn parse_3dl(text: &str) -> Result { + let mut mesh: Option<(u32, u32)> = None; let mut rows: Vec<[f64; 3]> = Vec::new(); + // How many numbers the first numeric line carried: a shaper of exactly `n` values (n ≤ 3) + // is otherwise indistinguishable from a node row. + let mut first_len: Option = None; + // Any text line before the rows is a header: a headerless table peaking at 255 or 1023 is + // on the 12-bit scale, as Photoshop 27.11 reads it (#9121). let mut header = false; for line in text.lines() { let line = line.split('#').next().unwrap_or("").trim(); - if line.is_empty() || line.starts_with(|c: char| c.is_ascii_alphabetic()) { - header |= !line.is_empty(); + if line.is_empty() { + continue; + } + if line.starts_with(|c: char| c.is_ascii_alphabetic()) { + header = true; + // The only header keyword that carries data. A malformed or out-of-range `Mesh` + // line is ignored, as every text line always was. + let mut it = line.split_whitespace(); + if it.next().is_some_and(|k| k.eq_ignore_ascii_case("Mesh")) { + // A declaration is exactly two integer fields after the keyword. Anything else + // (a non-numeric field, too few or too many) is not a declaration: `mesh` stays + // unset so headerless inference applies, rather than recovering numbers from + // the wrong positions (#9078). + let fields: Vec<&str> = it.collect(); + if let [a, b] = fields.as_slice() + && let (Ok(n), Ok(bits)) = (a.parse::(), b.parse::()) + && (1..=7).contains(&n) + && (1..=16).contains(&bits) + { + mesh = Some((n, bits)); + } + } continue; } let v: Vec = line.split_whitespace().filter_map(|s| s.parse().ok()).collect(); + if v.is_empty() { + // The `3DMESH` magic carries no numbers, but it is a header all the same: a table + // behind it reads a 1023 peak on the 10-bit scale (#9121). + header = true; + continue; + } + first_len.get_or_insert(v.len()); if v.len() == 3 { rows.push([v[0], v[1], v[2]]); } // Lines with more than three numbers are the input shaper; it is assumed linear. } - let n = (rows.len() as f64).cbrt().round() as usize; - if n < 2 || n * n * n != rows.len() { - return err(format!("{} rows is not a cube", rows.len())); - } - let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); - // Photoshop 27.11 reads a headerless table peaking at 255 or 1023 on the 12-bit scale (#9121). - let depths: &[f64] = if header { &[1023.0, 4095.0, 16383.0, 65535.0] } else { &[4095.0, 16383.0, 65535.0] }; - let scale = if max <= 1.0 { 1.0 } else { depths.iter().copied().find(|&s| max <= s).unwrap_or(max) }; + let (n, nodes, scale) = match mesh { + Some((in_bits, out_bits)) => { + let n = 2usize.pow(in_bits) + 1; + let expected = n.checked_pow(3).ok_or_else(|| LutError(format!("unsupported 3dl cube size {n}")))?; + // One row more than the declared cube, and the first row has exactly `n` values: + // that row is the shaper, not a 28th node of a 3³ cube (#9078). + let nodes = if rows.len() == expected + 1 && first_len == Some(n) { &rows[1..] } else { &rows[..] }; + if nodes.len() != expected { + return err(format!("expected {expected} rows for the declared {n}³ cube, found {}", nodes.len())); + } + // Under a valid declaration the node codes are integers in the declared range, so + // the declaration wins for every in-range value — including a small max, where 1 is + // 1/declared of full output, not full output itself (#9073). Only a node beyond the + // declared range is a wrong declaration, and the old inference keeps such a file + // loading as before. + let max = nodes.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); + let declared = 2f64.powi(i32::try_from(out_bits).unwrap_or(16)) - 1.0; + (n, nodes, if max > declared { inferred_3dl_scale(max, header) } else { declared }) + } + None => { + let n = (rows.len() as f64).cbrt().round() as usize; + if n < 2 || n * n * n != rows.len() { + return err(format!("{} rows is not a cube", rows.len())); + } + let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); + (n, &rows[..], inferred_3dl_scale(max, header)) + } + }; let mut data = vec![0.0f32; n * n * n * 3]; - for (i, row) in rows.iter().enumerate() { + for (i, row) in nodes.iter().enumerate() { let (r, g, b) = (i / (n * n), (i / n) % n, i % n); let at = ((b * n + g) * n + r) * 3; for k in 0..3 { @@ -262,6 +317,18 @@ pub fn parse_3dl(text: &str) -> Result { LutFile { title: String::new(), size: n, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }.check() } +/// The code range a `.3dl` node table without a declared output depth was written with: the +/// smallest common integer depth that covers the largest value; a table of 0..1 floats passes +/// through. A headerless table has no 10-bit reading — 255 and 1023 are on the 12-bit scale, as +/// Photoshop 27.11 reads them (#9121). +fn inferred_3dl_scale(max: f64, header: bool) -> f64 { + if max <= 1.0 { + return 1.0; + } + let depths: &[f64] = if header { &[1023.0, 4095.0, 16383.0, 65535.0] } else { &[4095.0, 16383.0, 65535.0] }; + depths.iter().copied().find(|&s| max <= s).unwrap_or(max) +} + /// SpeedGrade `.look`: `` and a hex `` string of little-endian float32 RGB triplets /// (red fastest). pub fn parse_look(text: &str) -> Result { @@ -515,8 +582,9 @@ DOMAIN_MAX 0.5 1 1 let white = parse_3dl(&table(peak)).unwrap().data[21..24].to_vec(); assert_eq!(white, [peak as f32 / 4095.0; 3], "peak {peak}"); } - // A header keeps the inferred 10-bit depth. - let white = parse_3dl(&format!("3DMESH\nMesh 1 10\n{}", table(1023))).unwrap().data[21..24].to_vec(); + // A header keeps the inferred 10-bit depth. The bare `3DMESH` magic is a header without a + // cube declaration; `Mesh 1 10` would declare a 3³ cube and refuse this 2³ table (#9078). + let white = parse_3dl(&format!("3DMESH\n{}", table(1023))).unwrap().data[21..24].to_vec(); assert_eq!(white, [1.0; 3]); } @@ -535,6 +603,130 @@ DOMAIN_MAX 0.5 1 1 assert_eq!(l.data, LutFile::identity(2).data); } + /// A `size`³ inverse-identity `.3dl` (blue fastest): node (r,g,b) outputs `max - max·v/(size-1)` + /// per channel, with a uniform shaper of `size` codes up to 1023. + fn mesh_3dl(n_bits: u32, out_bits: u32, size: usize, max: f64, shaper: bool) -> String { + let mut text = format!("3DMESH\nMesh {n_bits} {out_bits}\n"); + if shaper { + for i in 0..size { + if i > 0 { + text.push(' '); + } + text.push_str(&format!("{}", (1023.0 * i as f64 / (size - 1) as f64).round())); + } + text.push('\n'); + } + for r in 0..size { + for g in 0..size { + for b in 0..size { + let v = [r, g, b].map(|c| (max - max * c as f64 / (size - 1) as f64).round()); + text.push_str(&format!("{} {} {}\n", v[0], v[1], v[2])); + } + } + } + text + } + + #[test] + fn three_dl_mesh_three_point_shaper_is_not_a_node() { + // #9078: Photoshop loads a 3³ cube whose shaper line has three values; counting it as a + // 28th node rejected the whole file. + let l = parse_3dl(&mesh_3dl(1, 12, 3, 4095.0, true)).unwrap(); + assert_eq!(l.size, 3); + assert_eq!(l.data.len(), 3 * 3 * 3 * 3); + // The inverse identity: node (0,0,0) is full, node (2,2,2) black. + assert!((l.data[0] - 1.0).abs() < 1e-6 && (l.data[1] - 1.0).abs() < 1e-6 && (l.data[2] - 1.0).abs() < 1e-6); + let last = &l.data[l.data.len() - 3..]; + assert_eq!(last, [0.0, 0.0, 0.0]); + // The same 27 nodes without the shaper row still load (the node-only control). + assert_eq!(parse_3dl(&mesh_3dl(1, 12, 3, 4095.0, false)).unwrap().data, l.data); + } + + #[test] + fn three_dl_mesh_declares_the_output_depth() { + // #9073: identical node codes divide by the declared range, not by the largest value. + let mut text_10 = String::new(); + let mut text_12 = String::new(); + for (n_bits, out_bits, dst) in [(2, 10, &mut text_10), (2, 12, &mut text_12)] { + // A 5³ identity scaled to 10-bit codes (max 1023). + *dst = format!("3DMESH\nMesh {n_bits} {out_bits}\n0 256 512 768 1023\n"); + for r in 0..5 { + for g in 0..5 { + for b in 0..5 { + dst.push_str(&format!("{} {} {}\n", r * 255, g * 255, b * 255)); + } + } + } + } + let white_10 = parse_3dl(&text_10).unwrap(); + let white_12 = parse_3dl(&text_12).unwrap(); + assert_eq!(white_10.size, 5); + let last_10 = &white_10.data[white_10.data.len() - 3..]; + let last_12 = &white_12.data[white_12.data.len() - 3..]; + assert!((last_10[0] - 1020.0 / 1023.0).abs() < 1e-6, "{last_10:?}"); + // 1020/4095 ≈ 0.249: white renders grey, as Photoshop measures it. + assert!((last_12[0] - 1020.0 / 4095.0).abs() < 1e-6, "{last_12:?}"); + } + + #[test] + fn three_dl_mesh_header_mismatch_is_rejected() { + // A Mesh header that disagrees with the row count is refused, not silently re-inferred. + assert!(parse_3dl("3DMESH\nMesh 1 12\n0 0 0\n0 0 1\n").is_err()); + // A node beyond the declared range is a wrong declaration: the old inference from the + // largest value keeps the file loading as it did before the header was honoured. + let mut text = String::from("3DMESH\nMesh 1 10\n"); + for r in 0..3 { + for g in 0..3 { + for b in 0..3 { + text.push_str(&format!("{} {} {}\n", r * 2047, g * 2047, b * 2047)); + } + } + } + let l = parse_3dl(&text).unwrap(); + let last = &l.data[l.data.len() - 3..]; + assert!((last[0] - 4094.0 / 4095.0).abs() < 1e-6, "{last:?}"); + } + + #[test] + fn three_dl_malformed_mesh_header_falls_back_to_inference() { + // A `Mesh` line that is not exactly two integer fields is not a declaration: it is + // ignored and the table is inferred as if headerless, rather than recovering numbers + // from the wrong positions (#9078). A 2³ cube would otherwise be read as a 3³ cube. + for header in ["Mesh invalid 1 12", "Mesh 1 12 13", "Mesh 1 x", "Mesh 1"] { + let mut text = format!("3DMESH\n{header}\n"); + for r in 0..2 { + for g in 0..2 { + for b in 0..2 { + text.push_str(&format!("{} {} {}\n", r * 1023, g * 1023, b * 1023)); + } + } + } + let l = parse_3dl(&text).unwrap(); + assert_eq!(l.size, 2, "{header}"); + assert_eq!(l.data, LutFile::identity(2).data, "{header}"); + } + } + + #[test] + fn three_dl_mesh_uses_declared_range_for_small_integer_codes() { + // #9073: under a valid `Mesh` declaration the node codes are integers in the declared + // range, so a max value of 1 is 1/4095 of full output — not full output itself. + let mut text = String::from("3DMESH\nMesh 1 12\n"); + for r in 0..3 { + for g in 0..3 { + for b in 0..3 { + let v = u8::from(r == 0 && g == 0 && b == 0); + text.push_str(&format!("{v} {v} {v}\n")); + } + } + } + let l = parse_3dl(&text).unwrap(); + assert_eq!(l.size, 3); + // blue fastest: node (0,0,0) is the first entry, code 1 → 1/4095. + assert!((l.data[0] - 1.0 / 4095.0).abs() < 1e-6, "{:?}", &l.data[0..3]); + assert!(l.data[3..].iter().all(|&v| v == 0.0), "{:?}", l.data); + } + #[test] fn look_hex_floats() { let id = LutFile::identity(2); diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 062f7c4f98..69e3bd78b5 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -33,6 +33,8 @@ zune-core = "0.5" jpeg-encoder = "0.6" # 12-bit and arithmetic-coded JPEG, which zune-jpeg does not decode. craft-jpeg.workspace = true +# Pure-Rust modular JPEG XL lossless encoder. +zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } photocraft-heif = { path = "../heif", optional = true } # Orientation is applied a band of rows per task on native; wasm stays single-threaded. @@ -46,5 +48,9 @@ proptest.workspace = true # Oracle decoders for cross-checking in tests only. image = { workspace = true, features = ["png", "jpeg", "tiff"] } +# Independent JPEG XL decoder oracle; not linked into the application. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +jxl-oxide = { version = "=0.12.6", default-features = false, features = ["rayon"] } + [lints] workspace = true diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 29d4d1234d..43bf4ea361 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -46,6 +46,7 @@ let out = encode(&img, Format::Tiff, &EncodeOptions::default())?; | OpenEXR | yes | yes | F16, F32 | Y, YA, RGB, RGBA | yes | no | no | no | no | no | no | `exr` | | Radiance HDR | yes | yes | F32 | RGB | no | no | no | no | no | no | yes (RGBE) | `image` | | FITS | yes | yes | U8, U16, F32 | Gray, RGB | no | no | no | no | no | yes (header cards) | no | built in | +| JPEG XL (.jxl) | **no** (see #2868) | yes | U8, U16 | Gray, RGB, RGBA (GrayA expands to RGBA) | yes | no (bare codestream) | no | no | no | no | no | `zune-jpegxl` | | DPX | yes | yes | U8, U16 (10/12-bit code values read and written exactly through U16) | Gray, RGB, RGBA | yes | no | no | no | no | DPX header fields only (creator, project, copyright, creation time, transfer, colorimetric, frame position, frame rate, time code) | no | built in | | Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in | | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | @@ -73,6 +74,17 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them ## Documented asymmetries and limitations +* **JPEG XL export.** Writes lossless 8/16-bit bare codestreams with `zune-jpegxl`. + Native layouts are Gray, RGB and RGBA. GrayA is expanded to RGBA at the + original depth. For 16-bit RGBA (including expanded GrayA), we correct + zune-jpegxl 0.5.2's extra-channel header, which otherwise describes the + 16-bit alpha samples as 8-bit. This preserves alpha precision; the independent + jxl-oxide decoder test checks the actual gray and alpha samples. The expansion + is not a native GrayA layout. No ICC, EXIF, XMP or DPI container boxes are written; the + document pipeline converts tagged images to sRGB and reports metadata loss. + Reading remains in the separate #2868 PR. The `ASYMMETRIC_EXCEPTIONS` + entry stays until import is merged. + * **DDS.** The top mip level of a 2D texture: uncompressed pixels described by channel masks (8, 16, 24 or 32 bits, RGB or luminance, with or without alpha) or BC1/BC2/BC3 (DXT1/DXT3/DXT5), with the legacy header or the DX10 one. Uncompressed row padding follows the header's diff --git a/crates/codecs/src/codecs.rs b/crates/codecs/src/codecs.rs index efdbbf8229..4c4c22388c 100644 --- a/crates/codecs/src/codecs.rs +++ b/crates/codecs/src/codecs.rs @@ -11,6 +11,7 @@ pub(crate) mod gif_palette; pub(crate) mod heif; pub(crate) mod iff; pub(crate) mod jpeg; +pub(crate) mod jxl; pub(crate) mod pcx; pub(crate) mod png; pub(crate) mod pnm; diff --git a/crates/codecs/src/codecs/jxl.rs b/crates/codecs/src/codecs/jxl.rs new file mode 100644 index 0000000000..11591c9300 --- /dev/null +++ b/crates/codecs/src/codecs/jxl.rs @@ -0,0 +1,159 @@ +//! Pure-Rust lossless JPEG XL (Modular) writer. +//! +//! Currently writes a bare JPEG XL codestream. The encoder accepts 8- or 16-bit +//! gray, RGB and RGBA samples, but does not write ICC/EXIF/XMP boxes. +//! Gray+alpha sources are expanded losslessly to RGBA by the export plan. +//! The flat export pipeline converts tagged RGB documents to sRGB first. + +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions as ZuneOptions}; +use zune_jpegxl::JxlSimpleEncoder; + +use crate::error::CodecError; +use crate::fidelity::Plan; +use crate::format::Format; +use crate::image::{ChannelLayout, Image, SampleType}; + +const F: Format = Format::Jxl; + +// zune-jpegxl 0.5.2 emits ExtraChannelInfo(all_default=true) for every alpha +// channel. In JPEG XL that flag means *8-bit* alpha, even when the modular +// payload was encoded from 16-bit samples. Replace only that metadata bundle, +// leaving the entire encoded frame and its TOC untouched. The replacement is +// exactly 16 bits longer, so subsequent byte-aligned data stays aligned. +// +// This deliberately verifies the pinned encoder's header layout rather than +// trying to parse or rewrite arbitrary JPEG XL codestreams. A different header +// must fail closed, not produce a file that silently corrupts transparency. +fn correct_16_bit_alpha_header(bytes: &[u8], width: u32, height: u32) -> Result, CodecError> { + fn read(bytes: &[u8], pos: &mut usize, count: usize) -> Option { + let mut value = 0u32; + for bit in 0..count { + let offset = *pos; + let byte = *bytes.get(offset / 8)?; + value |= u32::from((byte >> (offset % 8)) & 1) << bit; + *pos += 1; + } + Some(value) + } + + fn read_dimension(bytes: &[u8], pos: &mut usize) -> Option { + let bits = match read(bytes, pos, 2)? { + 0 => 9, + 1 => 13, + 2 => 18, + _ => 30, + }; + read(bytes, pos, bits)?.checked_add(1) + } + + fn write_bits(out: &mut Vec, pos: &mut usize, count: usize, value: u32) { + for bit in 0..count { + if (*pos).is_multiple_of(8) { + out.push(0); + } + out[*pos / 8] |= (((value >> bit) & 1) as u8) << (*pos % 8); + *pos += 1; + } + } + + let mut pos = 0; + let header_matches = read(bytes, &mut pos, 16) == Some(0x0aff) + && read(bytes, &mut pos, 1) == Some(0) + && read_dimension(bytes, &mut pos) == Some(height) + && read(bytes, &mut pos, 3) == Some(0) + && read_dimension(bytes, &mut pos) == Some(width) + && read(bytes, &mut pos, 1) == Some(0) // metadata not all-default + && read(bytes, &mut pos, 1) == Some(0) // no extra fields + && read(bytes, &mut pos, 1) == Some(0) // integer samples + && read(bytes, &mut pos, 2) == Some(3) // custom bit depth + && read(bytes, &mut pos, 6) == Some(15) // 16 bits + && read(bytes, &mut pos, 1) == Some(0) // uses >14 bits + && read(bytes, &mut pos, 2) == Some(1); // one extra channel + let alpha_flag_pos = pos; + let header_matches = header_matches + && read(bytes, &mut pos, 1) == Some(1) // incorrect default 8-bit alpha + && read(bytes, &mut pos, 1) == Some(0) // not XYB + && read(bytes, &mut pos, 1) == Some(1) // default sRGB encoding (RGBA) + && read(bytes, &mut pos, 2) == Some(0) // no extensions + && read(bytes, &mut pos, 1) == Some(1); // default transform + + let frame_offset = pos.div_ceil(8); + let header_matches = header_matches && frame_offset <= bytes.len() && (pos..frame_offset * 8).all(|bit| bytes[bit / 8] & (1 << (bit % 8)) == 0); + if !header_matches { + return Err(CodecError::encode(F, "unexpected zune-jpegxl header for 16-bit alpha")); + } + + let mut fixed = Vec::with_capacity(bytes.len() + 2); + let mut cursor = 0; + for bit in 0..alpha_flag_pos { + write_bits(&mut fixed, &mut cursor, 1, u32::from((bytes[bit / 8] >> (bit % 8)) & 1)); + } + + // JPEG XL ExtraChannelInfo, non-default, straight 16-bit alpha: + // type=kAlpha (Enum=0), bit_depth=uint16, dim_shift=0, name_len=0, + // alpha_associated=false. Adds exactly 16 bits versus all_default=true. + write_bits(&mut fixed, &mut cursor, 1, 0); + write_bits(&mut fixed, &mut cursor, 2, 0); + write_bits(&mut fixed, &mut cursor, 1, 0); + write_bits(&mut fixed, &mut cursor, 2, 3); + write_bits(&mut fixed, &mut cursor, 6, 15); + write_bits(&mut fixed, &mut cursor, 2, 0); + write_bits(&mut fixed, &mut cursor, 2, 0); + write_bits(&mut fixed, &mut cursor, 1, 0); + + for bit in alpha_flag_pos + 1..frame_offset * 8 { + write_bits(&mut fixed, &mut cursor, 1, u32::from((bytes[bit / 8] >> (bit % 8)) & 1)); + } + if cursor != (frame_offset + 2) * 8 { + return Err(CodecError::encode(F, "JPEG XL alpha header alignment mismatch")); + } + fixed.extend_from_slice(&bytes[frame_offset..]); + Ok(fixed) +} + +pub(crate) fn encode(image: &Image, plan: Plan) -> Result, CodecError> { + let image = image.converted(plan.layout, plan.sample); + let space = match image.layout() { + ChannelLayout::Gray => ColorSpace::Luma, + ChannelLayout::GrayA => ColorSpace::LumaA, + ChannelLayout::Rgb => ColorSpace::RGB, + ChannelLayout::Rgba => ColorSpace::RGBA, + _ => return Err(CodecError::unsupported(F, "JPEG XL export supports grayscale and RGB, with optional alpha")), + }; + let depth = match image.sample_type() { + SampleType::U8 => BitDepth::Eight, + SampleType::U16 => BitDepth::Sixteen, + _ => return Err(CodecError::unsupported(F, "JPEG XL lossless export supports 8 or 16-bit integer pixels")), + }; + let (width, height) = image.dimensions(); + let samples = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(image.layout().channels())) + .and_then(|n| n.checked_mul(image.sample_type().bytes())) + .ok_or_else(|| CodecError::encode(F, "image dimensions overflow the buffer size"))?; + if image.data().len() != samples { + return Err(CodecError::InvalidImage("incorrect JPEG XL pixel buffer length".into())); + } + // A panic in an external image encoder must not terminate the host application. + catch_unwind(AssertUnwindSafe(|| { + let options = ZuneOptions::new(width as usize, height as usize, space, depth); + let mut output = Vec::new(); + JxlSimpleEncoder::new(image.data(), options).encode(&mut output).map_err(|e| CodecError::encode(F, e.to_string()))?; + if depth == BitDepth::Sixteen && image.layout() == ChannelLayout::Rgba { correct_16_bit_alpha_header(&output, width, height) } else { Ok(output) } + })) + .unwrap_or_else(|_| Err(CodecError::encode(F, "the JPEG XL encoder failed"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn alpha_header_correction_rejects_unexpected_or_truncated_headers() { + for bytes in [&[][..], &[0xff, 0x0a][..], &[0; 32][..]] { + assert!(correct_16_bit_alpha_header(bytes, 2, 2).is_err()); + } + } +} diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs index 54f3ecd64e..55079b07ce 100644 --- a/crates/codecs/src/format.rs +++ b/crates/codecs/src/format.rs @@ -34,6 +34,8 @@ pub enum Format { Fits, /// DPX (SMPTE 268M Digital Picture Exchange): luma, RGB or RGBA film and video frames. Dpx, + /// JPEG XL: lossless export-only until the separate importer lands. + Jxl, /// Kodak Cineon (`.cin`, the 10-bit film-scan format DPX grew from). Cineon, /// DICOM single-frame images (uncompressed): read-only. @@ -85,6 +87,7 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ until a pure-Rust AV1 decoder is viable. Only enabled with the non-default `avif` feature.", ), + (Format::Jxl, "Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder; JPEG XL reading is tracked separately and is not yet available."), ( Format::Heif, "HEIC decode uses heic-rs (pure Rust, in the optional photocraft-heif crate behind the \ @@ -104,9 +107,10 @@ const TIFF_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L:: impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 22] = [ + pub const ALL: [Format; 23] = [ Format::Png, Format::Jpeg, + Format::Jxl, Format::Tiff, Format::WebP, Format::Gif, @@ -160,6 +164,7 @@ impl Format { Format::Heif => "HEIF", Format::Fits => "FITS", Format::Dpx => "DPX", + Format::Jxl => "JPEG XL", Format::Cineon => "Cineon", Format::Dicom => "DICOM", Format::Iff => "Amiga IFF", @@ -189,6 +194,7 @@ impl Format { Format::Heif => &["heic", "heif", "hif"], Format::Fits => &["fits", "fit", "fts"], Format::Dpx => &["dpx"], + Format::Jxl => &["jxl"], Format::Cineon => &["cin"], Format::Dicom => &["dcm", "dicom", "dc3"], Format::Iff => &["iff", "lbm", "ilbm"], @@ -216,6 +222,7 @@ impl Format { Format::Heif => "image/heif", Format::Fits => "image/fits", Format::Dpx => "image/x-dpx", + Format::Jxl => "image/jxl", Format::Cineon => "image/x-cin", Format::Dicom => "application/dicom", Format::Iff => "image/x-iff", @@ -276,6 +283,8 @@ pub fn caps(format: Format) -> FormatCaps { Format::Fits => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: &[L::Gray, L::Rgb], alpha: false, text: true, ..base }, // `text`: the DPX header fields only (see `fidelity_warnings_with`). Format::Dpx => FormatCaps { depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], text: true, ..base }, + // GrayA is widened to RGBA at the same depth; the 16-bit alpha header is corrected. + Format::Jxl => FormatCaps { read: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], ..base }, Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base }, @@ -292,6 +301,10 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(&[0xFF, 0xD8, 0xFF]) { return Some(Format::Jpeg); } + // JPEG XL bare codestream and ISO/IEC 18181-2 container signature box. + if b.starts_with(&[0xFF, 0x0A]) || b.starts_with(b"\0\0\0\x0cJXL \r\n\x87\n") { + return Some(Format::Jxl); + } if b.starts_with(b"II*\0") || b.starts_with(b"MM\0*") || b.starts_with(b"II+\0") || b.starts_with(b"MM\0+") { return Some(Format::Tiff); } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 44ec622ef4..a537e8affd 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -48,7 +48,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_ pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; -use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jpeg, pcx, png, pnm, tiff, via_image, webp, xpm}; +use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jpeg, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -69,7 +69,7 @@ pub fn decode_as(format: Format, bytes: &[u8]) -> Result { /// Decode as a specific format. pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Result { // HEIF without the `heif` feature: its decoder stub says what is missing from this build. - if !caps(format).read && format != Format::Heif { + if !caps(format).read && !matches!(format, Format::Heif | Format::Jxl) { return Err(CodecError::unsupported(format, "decoding is not available for this format")); } let l = &opts.limits; @@ -89,6 +89,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Iff => iff::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), + Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l), }?; // Without a resolution of the format's own (PNG pHYs, TIFF tags, JPEG's metadata), the @@ -307,6 +308,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result iff::encode(image, plan), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), + Format::Jxl => jxl::encode(image, plan), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::encode(format, image, plan, opts), } } diff --git a/crates/codecs/tests/jxl_export.rs b/crates/codecs/tests/jxl_export.rs new file mode 100644 index 0000000000..8875cbce80 --- /dev/null +++ b/crates/codecs/tests/jxl_export.rs @@ -0,0 +1,110 @@ +//! Lossless JPEG XL export and honest export-only capability reporting. + +use photocraft_codecs::{ + ASYMMETRIC_EXCEPTIONS, ChannelLayout, CodecError, EncodeOptions, Format, Image, SampleType, caps, decode, detect, encode, from_extension, +}; + +#[test] +fn jpeg_xl_is_export_only_and_detects_both_signatures() { + let c = caps(Format::Jxl); + assert!(c.write && !c.read); + assert_eq!(c.depths, &[SampleType::U8, SampleType::U16]); + assert_eq!(c.layouts, &[ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba]); + assert!(c.alpha && !c.icc && !c.exif && !c.xmp && !c.dpi && !c.lossy); + assert_eq!(Format::Jxl.mime_type(), "image/jxl"); + assert_eq!(from_extension("image.JXL"), Some(Format::Jxl)); + assert_eq!(detect(&[0xff, 0x0a, 0, 0]), Some(Format::Jxl)); + assert_eq!(detect(b"\0\0\0\x0cJXL \r\n\x87\n"), Some(Format::Jxl)); + assert!(ASYMMETRIC_EXCEPTIONS.iter().any(|(format, reason)| *format == Format::Jxl && !reason.is_empty())); + let err = decode(&[0xff, 0x0a]); + assert!(matches!(err, Err(CodecError::Unsupported { format: Format::Jxl, .. })), "{err:?}"); +} + +#[test] +fn jpeg_xl_encoding_is_deterministic_and_converts_float_to_integer() { + let input = + Image::from_u8(3, 2, ChannelLayout::Rgba, vec![0, 255, 17, 127, 20, 40, 80, 255, 255, 0, 2, 0, 10, 20, 30, 64, 0, 0, 0, 1, 90, 80, 70, 128]).unwrap(); + let opts = EncodeOptions::default(); + let one = encode(&input, Format::Jxl, &opts).unwrap(); + let two = encode(&input, Format::Jxl, &opts).unwrap(); + assert_eq!(one, two); + assert_eq!(detect(&one), Some(Format::Jxl)); + let float = Image::from_f32(2, 2, ChannelLayout::Rgb, &[0.0, 0.5, 1.0, 0.25, 0.5, 0.75, 0.75, 0.5, 0.25, 1.0, 0.0, 0.5]).unwrap(); + let bytes = encode(&float, Format::Jxl, &opts).unwrap(); + assert_eq!(detect(&bytes), Some(Format::Jxl)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn jpeg_xl_decodes_losslessly_with_independent_decoder() { + use jxl_oxide::JxlImage; + + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] { + let channels = layout.channels(); + for sample in [SampleType::U8, SampleType::U16] { + let (w, h) = (7, 5); + let count = w as usize * h as usize * channels; + let expected = match sample { + SampleType::U8 => (0..count).map(|i| (((i * 37 + 19) % 256) as u16) * 257).collect::>(), + SampleType::U16 => (0..count).map(|i| ((i * 9973 + 27) % 65536) as u16).collect::>(), + _ => unreachable!(), + }; + let input = match sample { + SampleType::U8 => { + let data = expected.iter().map(|v| (v / 257) as u8).collect(); + Image::from_u8(w, h, layout, data).unwrap() + } + SampleType::U16 => Image::from_u16(w, h, layout, &expected).unwrap(), + _ => unreachable!(), + }; + // GrayA is losslessly widened to RGBA. Keep the oracle comparison + // against original gray and alpha samples, not only against a converted image. + let (output_channels, expected_output) = if layout == ChannelLayout::GrayA { + let expanded: Vec = expected.as_chunks::<2>().0.iter().flat_map(|[gray, alpha]| [*gray, *gray, *gray, *alpha]).collect(); + (4, expanded) + } else { + (channels, expected.clone()) + }; + let encoded = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap(); + let decoder = JxlImage::builder().read(&encoded[..]).unwrap(); + assert_eq!((decoder.width(), decoder.height()), (w, h)); + let render = decoder.render_frame(0).unwrap(); + let mut stream = render.stream(); + assert_eq!(stream.channels() as usize, output_channels, "{layout:?} {sample:?}"); + let mut output = vec![0u16; expected_output.len()]; + assert_eq!(stream.write_to_buffer(&mut output), expected_output.len()); + assert_eq!(output, expected_output, "{layout:?} {sample:?}"); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn jpeg_xl_preserves_sixteen_bit_alpha_across_dimension_header_sizes() { + use jxl_oxide::JxlImage; + + // Exercise each size-header coding tier, and non-opaque alpha extremes. + for width in [2u32, 513, 8193] { + let height = 2u32; + let mut samples = Vec::with_capacity(width as usize * height as usize * 4); + for i in 0..(width as usize * height as usize) { + samples.extend_from_slice(&[(i as u16).wrapping_mul(127), 65535, (i as u16).wrapping_mul(9973), [0u16, 1, 32768, 65535][i % 4]]); + } + let input = Image::from_u16(width, height, ChannelLayout::Rgba, &samples).unwrap(); + let encoded = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap(); + let decoder = JxlImage::builder().read(&encoded[..]).unwrap(); + let render = decoder.render_frame(0).unwrap(); + let mut stream = render.stream(); + assert_eq!(stream.channels(), 4, "width={width}"); + let mut output = vec![0u16; samples.len()]; + assert_eq!(stream.write_to_buffer(&mut output), samples.len()); + assert_eq!(output, samples, "width={width}"); + } +} + +#[test] +fn jpeg_xl_rejects_one_pixel_images_without_panicking() { + // zune-jpegxl currently requires at least two pixels on each axis. + let image = Image::from_u8(1, 1, ChannelLayout::Rgb, vec![42, 100, 255]).unwrap(); + assert!(matches!(encode(&image, Format::Jxl, &EncodeOptions::default()), Err(CodecError::Encode { format: Format::Jxl, .. }))); +} diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index bc0de2ffc2..8436ff7428 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -72,8 +72,10 @@ pub(crate) fn branchless_floor(x: f32) -> f32 { } /// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each -/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. -fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { +/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode` at layer Fill `fill`: below +/// 100% the special eight ([`psblend::fill_is_special`]) blend a result pulled toward the mode's +/// neutral colour, as a pixel layer does (#9501); for every other mode Fill is in `ks`. +fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode, fill: f32) { for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) { if k <= 0.0 { continue; @@ -81,8 +83,11 @@ fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterato let s = [a[0], a[1], a[2]]; // Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment // layers are Normal: no per-pixel mode dispatch for them. - let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) }; - *b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; + let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb_fill(mode, [b[0], b[1], b[2]], s, fill) }; + // `b·(1−k) + s·k`, not `b + (s − b)·k`: with a huge 32-bit backdrop the difference loses a + // small result to f32 rounding, so full coverage gave 0 instead of a lookup's 0.5 (#9483). + let j = 1.0 - k; + *b = [b[0] * j + blended[0] * k, b[1] * j + blended[1] * k, b[2] * j + blended[2] * k, b[3]]; } } @@ -147,9 +152,9 @@ fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Optio let Some(p) = px else { continue }; let v = |c: usize| blend_if_level(p[c]); match mode { - // Gray is the colour channels' luma (Rec. 601 weights), then R, G, B. + // Gray, then R, G, B. M::Rgb => { - let gray = 0.299 * v(0) + 0.587 * v(1) + 0.114 * v(2); + let gray = blend_if_gray(v(0), v(1), v(2)); k *= bi.get(0)[side].weight(gray); for c in 0..3 { k *= bi.get(c + 1)[side].weight(v(c)); @@ -166,15 +171,28 @@ fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Optio k } -/// A channel value on Blend If's 0..=255 scale. Compositing can leave an 8- or 16-bit level a few -/// millionths off (a level-20 backdrop composited at partial alpha reads 19.999998), which would -/// put it on the wrong side of a hard point at that level: a value that close to a level is that -/// level. Values of those depths that aren't on a level are at least 1/257 away from one. The GPU -/// compositor (`compose.wgsl` `blend_if_weight`) snaps alike. +/// A channel value on Blend If's 0..=255 scale. Photoshop compares Blend If at its 16-bit +/// precision (0..=32768): a cutoff at level `c` falls on the step `round(c · 32768 / 255)`, and a +/// value on that step is exactly level `c`, inside both a black point and a white point there +/// (#9521: RGB16 32895 is step 16448, level 128's, so it passes a hard black point at 128; read as +/// 127.996 it didn't). Every 8-bit level is on its own step, which also absorbs compositing's few +/// millionths of drift (a level-20 backdrop at partial alpha reads 19.999998). The GPU compositor +/// (`compose.wgsl` `blend_if_weight`) snaps alike. fn blend_if_level(x: f32) -> f32 { - let v = x.clamp(0.0, 1.0) * 255.0; - let r = v.round(); - if (v - r).abs() < 1e-4 { r } else { v } + let x = x.clamp(0.0, 1.0); + let v = x * 255.0; + let level = v.round(); + if (x * 32768.0).round() == (level * 32768.0 / 255.0).round() { level } else { v } +} + +/// Blend If's Gray from channel levels: Photoshop's (30 R + 59 G + 11 B) / 100, rounded half down +/// on 8-bit levels (#9522). Measured in Photoshop 2025: pure red passes a black point at 20 from +/// 66 (19.8) but not 65 (19.5), pure blue at 28 from 251 (27.61) but not 250 (27.5); (123, 126, +/// 151) is 128 (127.85) and (120, 129, 149) is 128 (128.5), where Rec. 601 luma gave 127.95 and +/// 128.59. Levels between whole ones (deeper documents) keep the unrounded weighting. +fn blend_if_gray(r: f32, g: f32, b: f32) -> f32 { + let sum = 30.0 * r + 59.0 * g + 11.0 * b; + if [r, g, b].iter().all(|c| c.fract() == 0.0) { ((sum + 49.0) / 100.0).floor() } else { sum / 100.0 } } /// Blend If groups inside one another whose own colour is still rendered separately. Each extra @@ -191,13 +209,18 @@ thread_local! { /// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since /// every blend mode's source-over result is linear in the source alpha. fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { - // "This Layer" is the layer's own colour; adjustment layers (no content of their own) are - // judged by their result. So are groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend - // Ifs: a group's own colour re-composites its children, which doubles the work at every - // level of Blend If groups inside one another. + // "This Layer" is the layer's own colour. An adjustment layer (no content of its own) is + // judged by its result at full strength, before Opacity and its mask mix it in, as Photoshop + // does (#9542). Groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend Ifs are judged by + // the composite: a group's own colour re-composites its children, which doubles the work at + // every level of Blend If groups inside one another. let is_group = matches!(layer.content, LayerContent::Group(_)); let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get); - let own = if matches!(layer.content, LayerContent::Adjustment(_)) || (is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH) { + let own = if let LayerContent::Adjustment(adj) = &layer.content { + let mut result = before.clone(); + cx.apply_adjustment(adj, &mut result); + Some(result) + } else if is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH { None } else { BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group))); @@ -334,6 +357,8 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: // is the base of a clipping group and holds an adjustment layer (psd-tools // passthrough_clipping_mask_adjustment: an Exposure inside leaves the layers beneath alone), // while such a group's blend modes still reach the backdrop (passthrough_clipping_mask_blendmode). + // A group with Blend If renders isolated too: an adjustment inside it no longer changes the + // layers beneath (#9554). let clip_base_adjusts = clipped.iter().any(|c| c.visible) && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); if let LayerContent::Group(g) = &layer.content @@ -341,6 +366,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: && layer.fill_opacity >= 1.0 && !effects::has_effects(layer) && !clip_base_adjusts + && !blend_if_active(layer, cx.mode) { let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some(); let has_clipped = clipped.iter().any(|c| c.visible); @@ -420,9 +446,13 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: } } } else { + // Fill below 100% in one of the special eight changes the blend itself and leaves + // coverage to Opacity, as for a pixel layer (psblend::composite_fill, #9501). + let (k, fill) = + if layer.fill_opacity < 1.0 && psblend::fill_is_special(layer.blend) { (layer.opacity, layer.fill_opacity) } else { (opacity, 1.0) }; match &mv { - Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend), - None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend), + Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| k * v), layer.blend, fill), + None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(k), layer.blend, fill), } } recycle_buffer(adjusted); diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index adf0b7a7b0..d484d384be 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -41,9 +41,9 @@ mod paint; pub use bevel::{BEVEL_H_EPS, BevelGeom, BevelPaint, TextureCtx, bevel_chisel_h, bevel_geom, satin_distance}; #[cfg(test)] use bevel::{bevel_maps, satin_map}; -pub use blur::tent_kernel; #[cfg(test)] use blur::{blur, box_line, dilate, tent, tent_direct}; +pub use blur::{softer_glow_tail_amplitude, softer_glow_tail_width, tent_kernel}; pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, map_count}; pub use composite::{build_maps, composite_with_effects, outline_share, premerges_layer, shadow_see_through, stroke_widths}; pub use distance::{FieldKind, STROKE_CHAMFER_MAX, bevel_distance_fields, distance_field, stroke_outside_exact}; @@ -89,7 +89,14 @@ pub fn margin(layer: &Layer) -> i32 { for e in layer.effects.items.iter().filter(|e| e.enabled()) { let r = match e { Effect::DropShadow(s) | Effect::InnerShadow(s) => s.distance + s.size, - Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.size, + Effect::OuterGlow(g) => { + if g.technique == GlowTechnique::Softer { + g.size + softer_glow_tail_width(g.size) + } else { + g.size + } + } + Effect::InnerGlow(g) => g.size, Effect::Stroke(s) => s.size, Effect::Satin(s) => satin_distance(s) + s.size, Effect::BevelEmboss(b) => b.size + b.soften, diff --git a/crates/compose/src/effects/blur.rs b/crates/compose/src/effects/blur.rs index edea7285d2..4185e5be20 100644 --- a/crates/compose/src/effects/blur.rs +++ b/crates/compose/src/effects/blur.rs @@ -210,3 +210,14 @@ fn tent_fast(m: &mut Map, w: f32) { rows_par(&t, &mut b, mh, twice); m.v = transpose_map(&b, mh, mw); } + +/// Raw coverage at the Size boundary, scaled through the glow's Range to a subtle one-percent tail. +pub fn softer_glow_tail_amplitude(range: f32) -> f32 { + let range = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; + 0.005 * range +} + +/// Width of the added fading tail on a Softer outer glow, capped so large settings stay local. +pub fn softer_glow_tail_width(size: f32) -> f32 { + if size.is_finite() && size > 0.0 { (size * 0.1).clamp(1.0, 6.0) } else { 0.0 } +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index 99b0c6aa0b..a528669685 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -1,4 +1,4 @@ -use super::blur::{blur, dilate}; +use super::blur::{blur, dilate, softer_glow_tail_amplitude, softer_glow_tail_width}; use super::distance::{dist_inside, dist_outside}; use super::{ BlendMode, Buffer, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Map, Placement, PreparedPatterns, Rect, @@ -303,6 +303,9 @@ pub(super) fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) - let (r, bw) = spread_split(g.size, g.spread); let mut m = dilate(&src, r); blur(&mut m, bw); + if !inner { + add_softer_glow_tail(&mut m, &src, g.size, g.range); + } m } }; @@ -402,3 +405,25 @@ pub(super) fn paint_glow(dst: &mut Buffer, m: &Map, g: &Glow, shape_bounds: Rect let strength = Map { w: m.w, h: m.h, v: m.v.iter().map(|v| (v * gain).min(1.0)).collect() }; paint(dst, &strength, |i| prepared.sample(1.0 - m.v.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0)), g.common.blend, g.common.opacity); } + +fn add_softer_glow_tail(map: &mut Map, shape: &Map, size: f32, range: f32) { + let width = softer_glow_tail_width(size); + if width == 0.0 { + return; + } + let amp = softer_glow_tail_amplitude(range); + let distance = dist_outside(shape); + for (coverage, distance) in map.v.iter_mut().zip(distance) { + let t = (distance + 0.5 - (size - width)) / width; + let tail = if (0.0..=1.0).contains(&t) { + amp * t * t * (3.0 - 2.0 * t) + } else if (1.0..=2.0).contains(&t) { + let u = t - 1.0; + let remaining = 1.0 - u; + amp * remaining * remaining * (1.0 + 2.0 * u) + } else { + 0.0 + }; + *coverage = coverage.max(tail); + } +} diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index 4aea00004f..8c2c71ea3a 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -858,6 +858,56 @@ fn glows_match_photoshop() { } } +#[test] +fn softer_outer_glow_keeps_a_fading_tail_past_its_size() { + let mut shape = Map::new(220, 220, 0.0); + for y in 0..shape.h { + for x in 20..100 { + shape.v[y * shape.w + x] = 1.0; + } + } + let glow = Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 60.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }; + let m = glow_map(&shape, &glow, false, (0, 0)); + let row = shape.h / 2; + let at = |distance: usize| m.v[row * m.w + 100 + distance]; + assert!(at(50) > 0.024, "the softer shoulder should stay visible: {}", at(50)); + assert!(at(60) > 1.0 / 255.0, "the glow must retain a visible tail at its Size: {}", at(60)); + assert!(at(62) > 0.5 / 255.0, "the glow must extend beyond its Size: {}", at(62)); + assert!(at(66) < 1e-6, "the added tail should fade to zero: {}", at(66)); +} + +#[test] +fn softer_outer_glow_margin_includes_its_tail_support() { + let glow = Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 60.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }; + let mut layer = Layer::raster("glow", photocraft_color::PixelFormat::RGBA8); + layer.effects.items.push(Effect::OuterGlow(glow)); + assert_eq!(margin(&layer), 68); +} + #[test] fn offsets_follow_light() { let (dx, dy) = offset(120.0, 10.0); diff --git a/crates/compose/src/masks/tests.rs b/crates/compose/src/masks/tests.rs index b6aa42fe1f..9076770913 100644 --- a/crates/compose/src/masks/tests.rs +++ b/crates/compose/src/masks/tests.rs @@ -137,6 +137,36 @@ fn parallel_feathered_pixel_mask_returns_the_same_tiles() { assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); } +/// A feather reaching the canvas edge sees the mask continue past it with its edge values, as +/// in Photoshop (#9475): a rectangle near the edge feathers the same on a taller canvas holding +/// the same mask (clamping each blur pass at the edge brightened it by up to 12 levels at +/// 32 px), and a mask white up to the edge stays white along it. +#[test] +fn feather_at_the_canvas_edge_continues_the_mask_past_it() { + let mut layer = Layer::raster("edge", PixelFormat::RGBA8); + let mut mask = photocraft_doc::LayerMask::hide_all(); + mask.surface.fill_rect(Rect::new(40, 20, 120, 60), &[1.0]); + mask.feather = 32.0; + layer.mask = Some(mask); + let canvas = Rect::new(0, 0, 160, 80); + let tight = combined_mask(&layer, canvas).unwrap().read_region(canvas); + let tall = combined_mask(&layer, Rect::new(0, -200, 160, 280)).unwrap().read_region(canvas); + let worst = tight.iter().zip(&tall).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); + assert!(worst < 1e-4, "the canvas edge changed the feather by {worst}"); + + let mut half = photocraft_doc::LayerMask::hide_all(); + half.surface.fill_rect(Rect::new(0, 0, 80, 80), &[1.0]); + half.feather = 32.0; + layer.mask = Some(half); + let m = combined_mask(&layer, canvas).unwrap().read_region(canvas); + // Photoshop: every row the same, no darkening towards the top or bottom edge. + let middle = &m[40 * 160..41 * 160]; + for (y, row) in m.as_chunks::<160>().0.iter().enumerate() { + assert!(row.iter().zip(middle).all(|(a, b)| (a - b).abs() < 1e-5), "row {y} differs from row 40"); + } + assert!(middle[0] > 0.99, "the left edge stays white: {}", middle[0]); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn vector_mask_build_inside_a_small_rayon_pool_completes() { diff --git a/crates/compose/src/soft_shape_tests.rs b/crates/compose/src/soft_shape_tests.rs index 222b3f3e9a..37575beef5 100644 --- a/crates/compose/src/soft_shape_tests.rs +++ b/crates/compose/src/soft_shape_tests.rs @@ -91,7 +91,8 @@ fn density_shows_the_fill_beyond_the_path() { /// mask break differently: 127 and 128, both what Photoshop's "127/128" allows.) #[test] fn soft_shape_matches_an_equal_vector_mask() { - for (density, feather) in [(1.0, 10.0), (0.45, 0.0), (0.3, 6.5), (0.0, 0.0), (1.0, 0.0), (0.5, 3.0)] { + // 40 px reaches past the canvas edge: both feather it the same way there (#9475). + for (density, feather) in [(1.0, 10.0), (0.45, 0.0), (0.3, 6.5), (0.0, 0.0), (1.0, 0.0), (0.5, 3.0), (1.0, 40.0)] { for depth in [SampleType::U8, SampleType::U16] { let (s, f) = (shape_doc(depth, density, feather, None), fill_doc(depth, density, feather)); for y in [0, 45, 50, 100, 151, 199] { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 9b71af68f2..92b76dd8e3 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -417,6 +417,59 @@ fn every_blend_mode_matches_reference_on_opaque_pixels() { } } +/// #9483: a Color Lookup's bounded output survives full coverage over a huge 32-bit pixel. The +/// blend back to the backdrop computed `b + (r - b) · k`, and in f32 the difference had already +/// lost the small result (1e8 and 0.5 gave 0). +#[test] +fn full_coverage_adjustment_keeps_its_result_over_huge_hdr_values() { + for v in [1.0e6_f32, 1.0e8, -1.0e6] { + let mut d = Document::new("hdr", Size::new(2, 2), ColorMode::Rgb, SampleType::F32); + let mut base = Layer::raster("b", PixelFormat::RGBA32F); + base.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 2), &[v, v, v, 1.0]); + let look = Adjustment::ColorLookup { + name: "half".into(), + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + size: 2, + tetrahedral: false, + dither: false, + source: None, + }; + d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))]; + let got = px(&d, 0, 0); + for c in &got[..3] { + assert!((c - 0.5).abs() < 1e-6, "{v}: {got:?}"); + } + } +} + +/// #9501: an adjustment layer at 40% Fill in Color Dodge or Linear Burn blends a result pulled +/// toward the mode's neutral colour, as a pixel layer does, instead of fading the blend by Fill. +/// Photoshop: a constant 0.5 look over (64, 128, 192) gives (80, 160, 240) and (13, 77, 141). +#[test] +fn adjustment_fill_changes_the_special_blend_modes() { + for (mode, want) in [(BlendMode::ColorDodge, [80, 160, 240]), (BlendMode::LinearBurn, [13, 77, 141])] { + let mut d = Document::with_background("fill", Size::new(1, 1), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut base = Layer::raster("b", PixelFormat::RGBA8); + base.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[64.0 / 255.0, 128.0 / 255.0, 192.0 / 255.0, 1.0]); + let look = Adjustment::ColorLookup { + name: "half".into(), + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + size: 2, + tetrahedral: false, + dither: false, + source: None, + }; + let mut adj = Layer::new("look", LayerContent::Adjustment(look)); + adj.blend = mode; + adj.fill_opacity = 0.4; + d.layers.push(base); + d.layers.push(adj); + let got = px(&d, 0, 0); + let got: Vec = got[..3].iter().map(|v| (v * 255.0).round() as i32).collect(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "{mode:?}: {got:?} vs Photoshop {want:?}"); + } +} + /// One opaque pixel: `top` in `mode` over `bottom`, in a document of `depth`. fn blend_px(depth: SampleType, mode: BlendMode, bottom: [f32; 3], top: [f32; 3]) -> [f32; 4] { let mut d = Document::new("b", Size::new(1, 1), ColorMode::Rgb, depth); @@ -564,6 +617,35 @@ fn clipped_dissolve_matches_whole_render_at_offset_regions_and_depths() { } } +/// #4921: Dissolve coverage must survive clipping and use Opacity × Fill. +#[test] +fn clipped_dissolve_is_binary_and_preserves_the_base_shape() { + let mut d = doc_white(40, 12); + d.layers.push(solid_layer("base", Rect::new(0, 0, 20, 12), [0.0, 0.0, 1.0, 1.0])); + let mut clip = solid_layer("clip", d.bounds(), [1.0, 0.0, 0.0, 1.0]); + clip.clipped = true; + clip.blend = BlendMode::Dissolve; + clip.opacity = 0.6; + clip.fill_opacity = 0.5; + d.layers.push(clip); + let mut red = 0; + let mut blue = 0; + for y in 0..12 { + for x in 0..20 { + let p = px(&d, x, y); + if close4(p, [1.0, 0.0, 0.0, 1.0]) { + red += 1; + } else { + assert!(close4(p, [0.0, 0.0, 1.0, 1.0]), "Dissolve must not interpolate: {p:?} at ({x},{y})"); + blue += 1; + } + } + assert!(close4(px(&d, 30, y), [1.0; 4]), "outside the base the clip is invisible"); + } + assert!(red > 0 && blue > 0, "Dissolve must expose both source and base: {red}/{blue}"); + assert!((red as f32 / (red + blue) as f32 - 0.3).abs() < 0.1, "coverage should follow 60% opacity × 50% fill: {red}/{blue}"); +} + #[test] fn hidden_base_hides_clipping_group() { let mut d = doc_white(4, 4); @@ -959,6 +1041,55 @@ fn dissolve_coverage_matches_opacity() { assert_eq!(flatten(&d), b); } +/// Invert at 50% Dissolve is black or white, not the gray of a Normal mix (#3050). +#[test] +fn dissolve_adjustment_is_a_per_pixel_choice() { + let mut d = doc_white(16, 16); + let mut inv = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)); + inv.blend = photocraft_color::BlendMode::Dissolve; + inv.opacity = 0.5; + d.layers.push(inv); + let b = flatten(&d); + let (black, white, other) = b.px.iter().fold((0, 0, 0), |(k, w, o), p| { + if close4(*p, [0.0, 0.0, 0.0, 1.0]) { + (k + 1, w, o) + } else if close4(*p, [1.0, 1.0, 1.0, 1.0]) { + (k, w + 1, o) + } else { + (k, w, o + 1) + } + }); + assert_eq!(other, 0, "a partial mix would be gray"); + assert!(black > 40 && white > 40, "black {black} white {white}"); +} + +/// A clipped black fill at 50% Dissolve stays black or white on an opaque base (#3052). +#[test] +fn clipped_dissolve_fill_is_a_per_pixel_choice() { + let mut d = doc_white(16, 16); + let mut l = solid_layer("k", Rect::new(0, 0, 16, 16), [0.0, 0.0, 0.0, 1.0]); + l.clipped = true; + l.blend = photocraft_color::BlendMode::Dissolve; + l.opacity = 0.5; + d.layers.push(l); + let b = flatten(&d); + assert!(b.px.iter().all(|p| close4(*p, [0.0, 0.0, 0.0, 1.0]) || close4(*p, [1.0; 4]))); +} + +/// A Color Overlay must not turn Dissolve coverage into a Normal mix (#3051). +#[test] +fn color_overlay_keeps_dissolve_coverage() { + use photocraft_doc::effects::{Effect, FxCommon}; + let mut d = doc_white(16, 16); + let mut l = Layer::new("ink", LayerContent::Fill(Fill::Solid(photocraft_color::Color::BLACK))); + l.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: photocraft_color::Color::BLACK }); + l.blend = photocraft_color::BlendMode::Dissolve; + l.opacity = 0.5; + d.layers.push(l); + let b = flatten(&d); + assert!(b.px.iter().all(|p| close4(*p, [0.0, 0.0, 0.0, 1.0]) || close4(*p, [1.0; 4]))); +} + #[test] fn render_is_tile_independent() { // Rendering a sub-rect must equal the same region of a full render. @@ -2479,6 +2610,71 @@ fn blend_if_hard_point_includes_its_own_level() { } } +/// #9521: Photoshop compares Blend If at its 16-bit precision (0..32768). A hard point at level +/// `c` sits on the step `round(c · 32768 / 255)`, inclusive for both black and white points: +/// measured in Photoshop 2025 at 1, 64, 128 and 200 (black first shown at steps 129, 8224, 16448, +/// 25700; white last shown at the same steps). RGB16 32895 is step 16448, so a white layer with +/// Underlying Blue black at 128 shows over it; 32894 (step 16447) hides it. +#[test] +fn blend_if_16_bit_cutoffs_follow_photoshops_steps() { + let shown = |v16: u16, black: u8, white: u8| { + let v = f32::from(v16) / 65535.0; + let mut d = Document::new("t", Size::new(1, 1), ColorMode::Rgb, SampleType::U16); + let layer16 = |name: &str, c: [f32; 4]| { + let mut l = Layer::raster(name, PixelFormat::RGBA16); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &c); + l + }; + d.layers.push(layer16("under", [v, v, v, 1.0])); + let mut l = layer16("top", [1.0, 1.0, 1.0, 1.0]); + l.blend_if.set(3, [FULL, range([black, black], [white, white])]); + d.layers.push(l); + px(&d, 0, 0)[0] > 0.999 + }; + // 16-bit file values for Photoshop's steps n: round(n · 65535 / 32768). + let at = |n: u32| ((n * 65535 + 16384) / 32768) as u16; + for (c, step) in [(1u8, 129u32), (64, 8224), (128, 16448), (200, 25700)] { + assert!(shown(at(step), c, 255), "black {c}: step {step} shows"); + assert!(!shown(at(step - 1), c, 255), "black {c}: step {} hides", step - 1); + assert!(shown(at(step), 0, c), "white {c}: step {step} shows"); + assert!(!shown(at(step + 1), 0, c), "white {c}: step {} hides", step + 1); + } + assert!(shown(32895, 128, 255) && !shown(32894, 128, 255), "the reporter's RGB16 boundary"); +} + +/// #9522: Blend If's Gray is Photoshop's (30 R + 59 G + 11 B) / 100 rounded half down, measured +/// in Photoshop 2025 with a white layer over one 8-bit backdrop colour and a hard Gray point on +/// Underlying Layer. Rec. 601 luma hid both of the reporter's colours. +#[test] +fn blend_if_gray_follows_photoshops_weights_and_rounding() { + let shown = |rgb: [u8; 3], black: u8, white: u8| { + let mut d = Document::new("t", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + let c = rgb.map(|v| f32::from(v) / 255.0); + d.layers.push(solid_layer("under", Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0])); + let mut l = solid_layer("top", Rect::new(0, 0, 1, 1), [1.0, 1.0, 1.0, 1.0]); + l.blend_if.set(0, [FULL, range([black, black], [white, white])]); + d.layers.push(l); + px(&d, 0, 0)[0] > 0.999 && px(&d, 0, 0)[2] > 0.999 + }; + // (colour hidden by a black point at `cut`, the next colour shown), single channels. + for (cut, below, at) in [ + (20, [65, 0, 0], [66, 0, 0]), + (25, [81, 0, 0], [82, 0, 0]), + (28, [91, 0, 0], [92, 0, 0]), + (20, [0, 33, 0], [0, 34, 0]), + (28, [0, 46, 0], [0, 47, 0]), + (20, [0, 0, 177], [0, 0, 178]), + (28, [0, 0, 250], [0, 0, 251]), + ] { + assert!(!shown(below, cut, 255), "{below:?} hidden by black {cut}"); + assert!(shown(at, cut, 255), "{at:?} shown by black {cut}"); + } + // The reporter's mixed colours, and the white point's half-down rounding. + assert!(shown([123, 126, 151], 128, 255), "127.85 is 128"); + assert!(shown([120, 129, 149], 0, 128), "128.5 is 128"); + assert!(!shown([121, 129, 149], 0, 128), "128.8 is 129"); +} + #[test] fn blend_if_split_point_fades_like_opacity() { // A split black point (Alt-drag) at 50/150 shows a value-100 layer at half strength, which @@ -2537,6 +2733,25 @@ fn blend_if_on_adjustment_and_clipped_layers() { assert!(close4(px(&d, 6, 1), [0.0, 1.0, 0.0, 1.0])); } +/// #9554: a Pass Through group with Blend If renders isolated, as Photoshop does: an Invert inside +/// it leaves the layer beneath alone. Photoshop: (64, 128, 192) under such a group with Red › +/// Underlying Layer white at 110 stays (64, 128, 192); without the Blend If it is inverted. +#[test] +fn pass_through_group_with_blend_if_is_isolated() { + for (gated, want) in [(true, [64, 128, 192]), (false, [191, 127, 63])] { + let mut d = Document::with_background("pt", Size::new(1, 1), ColorMode::Rgb, SampleType::U8, Color::WHITE); + d.layers.push(solid_layer("base", Rect::new(0, 0, 1, 1), [64.0 / 255.0, 128.0 / 255.0, 192.0 / 255.0, 1.0])); + let mut g = Layer::group("group", vec![Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert))]); + g.blend = BlendMode::PassThrough; + if gated { + g.blend_if.set(1, [FULL, range([0, 0], [110, 110])]); + } + d.layers.push(g); + let got: Vec = px(&d, 0, 0)[..3].iter().map(|v| (v * 255.0).round() as i32).collect(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "Blend If {gated}: {got:?} vs Photoshop {want:?}"); + } +} + #[test] fn blend_if_modes() { // Grayscale documents: the single channel's entry (or the gray entry) applies. @@ -4187,12 +4402,8 @@ fn reused_render_matches_previous_allocating_stack() { adjust::apply_in(adj, &mut adjusted, adjust::Transfer::for_document(doc.mode, depth), Some(depth), doc.mode); for (b, a) in previous.px.iter_mut().zip(&adjusted.px) { let blended = blend::blend_rgb(layer.blend, [b[0], b[1], b[2]], [a[0], a[1], a[2]]); - *b = [ - b[0] + (blended[0] - b[0]) * layer.opacity, - b[1] + (blended[1] - b[1]) * layer.opacity, - b[2] + (blended[2] - b[2]) * layer.opacity, - b[3], - ]; + let (k, j) = (layer.opacity, 1.0 - layer.opacity); + *b = [b[0] * j + blended[0] * k, b[1] * j + blended[1] * k, b[2] * j + blended[2] * k, b[3]]; } if let Some(q) = adjustment_quantum(depth) { quantize(&mut previous, q); @@ -4373,3 +4584,21 @@ fn branchless_floor_matches_floor_bitwise() { assert_eq!(branchless_floor(x).to_bits(), x.floor().to_bits(), "{x:e} ({:#010x})", x.to_bits()); } } + +/// #9542: an adjustment layer's "This Layer" range judges its result at full strength, before +/// Opacity mixes it in. Photoshop: Invert at 40% over (64, 128, 192) with Red / This Layer black +/// at 150 keeps the effect, (115, 128, 140), as Invert's red (191) passes 150; with white at 150 +/// it drops it. Judged after Opacity (red 115) the two came out the other way round. +#[test] +fn adjustment_blend_if_judges_the_result_before_opacity() { + for (black, white, want) in [(150u8, 255u8, [115, 128, 140]), (0, 150, [64, 128, 192])] { + let mut d = Document::with_background("bi", Size::new(1, 1), ColorMode::Rgb, SampleType::U8, Color::WHITE); + d.layers.push(solid_layer("base", Rect::new(0, 0, 1, 1), [64.0 / 255.0, 128.0 / 255.0, 192.0 / 255.0, 1.0])); + let mut inv = Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)); + inv.opacity = 0.4; + inv.blend_if.set(1, [range([black, black], [white, white]), FULL]); + d.layers.push(inv); + let got: Vec = px(&d, 0, 0)[..3].iter().map(|v| (v * 255.0).round() as i32).collect(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "black {black} white {white}: {got:?} vs Photoshop {want:?}"); + } +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index a4b9ca2fa3..055444c1e9 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -101,6 +101,11 @@ pub struct CharStyle { pub variations: Vec, /// BCP-47 language tag (affects shaping and line breaking). pub language: Option, + /// Vertical type: roman text (Latin, digits) runs rotated 90° clockwise along the column + /// (PSD `BaselineDirection` 2) instead of standing upright one character per em + /// (`BaselineDirection` 1, what Photoshop's Vertical Type tool sets, #9470). CJK text stands + /// upright either way. + pub rotate_roman: bool, /// Applied character style (id in [`crate::TextStyles`]); `None` = "None". Attributes above /// stay fully resolved; differences from the style are local overrides. #[serde(skip_serializing_if = "Option::is_none")] @@ -135,6 +140,7 @@ impl Default for CharStyle { features: Vec::new(), variations: Vec::new(), language: None, + rotate_roman: false, style_sheet: None, } } diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 5467e0bdbe..8e8d532d5b 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -115,6 +115,47 @@ pub struct ActionState { pub take: u64, } +/// Visibility gestures name a layer for replay, since document-local ids change on another image. +pub(crate) fn recorded_params(s: &Session, id: &str, mut p: Value) -> Value { + if s.actions.recording.is_none() || id != "layer.setProps" || p.get("visible").is_none() { + return p; + } + let Some(st) = s.active() else { return p }; + let Some(layer) = p.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).and_then(|id| st.doc.layer(id)) else { return p }; + let ordinal = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).position(|(_, _, l)| l.id == layer.id).unwrap_or(0); + if let Some(object) = p.as_object_mut() { + object.remove("layer"); + object.remove("coalesce"); + object.insert("_actionLayer".into(), json!({"name": layer.name, "ordinal": ordinal})); + } + p +} + +/// Resolve the recorded visibility target identically in engine and shell playback. +pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { + let mut p = p.clone(); + if id == "layer.setProps" + && let Some(target) = p.get("_actionLayer") + { + let name = target.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing recorded layer name"))?; + let ordinal = + target.get("ordinal").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(id, "invalid recorded layer ordinal"))?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let layer = doc + .walk() + .into_iter() + .filter(|(_, _, l)| l.name == name) + .nth(ordinal) + .map(|(_, _, l)| l.id) + .ok_or_else(|| bad(id, format!("recorded layer `{name}` does not exist")))?; + if let Some(object) = p.as_object_mut() { + object.remove("_actionLayer"); + object.insert("layer".into(), json!(layer.0)); + } + } + Ok(p) +} + impl ActionState { pub(crate) fn touch(&mut self) { self.rev = self.rev.saturating_add(1); @@ -381,6 +422,11 @@ pub fn noop_step(s: &Session, id: &str, params: &Value) -> bool { crate::commands::layer_param(s, params).is_ok_and(|layer| super::ops::arrange_at_end(&d.doc, layer, dir)) } +pub const SAVE_CONTENTS: &str = "layer.smartObjects.saveContents"; +pub fn saves_smart_contents(s: &Session, id: &str) -> bool { + id == "file.save" && s.is_enabled(SAVE_CONTENTS) +} + fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option) { let mut ran = 0u64; let mut failed = None; @@ -399,7 +445,7 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option { if let Some(error) = nested_failure(id, &value) { failed = Some(json!({"step": i, "id": id, "error": error})); diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index cd3910d164..caddcaa892 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -5,6 +5,30 @@ fn pixel(s: &Session, layer: usize, x: i32, y: i32) -> Vec { s.active().unwrap().doc.layers[layer].surface().unwrap().pixel(x, y) } +/// CopyCat's shape: Edit Contents, change the contents, Save. The Save step has no file to +/// write: it updates the smart object, headless too. +#[test] +fn save_in_edit_contents_updates_the_smart_object() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("layer.smartObjects.editContents", json!({})).unwrap(); + let steps = vec![("edit.fill".to_string(), json!({"contents": "color", "color": "#0000ff"})), ("file.save".to_string(), json!({}))]; + s.actions.list.push(Action::new("Edit and save", steps)); + let played = s.execute("actions.play", json!({"action": "Edit and save"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + s.set_active(0); + let doc = &s.active().unwrap().doc; + let flat = crate::file_cmds::flattened(doc, doc.pixel_format()); + let p = flat.pixel(2, 2); + assert!(p[0] < 0.01 && p[2] > 0.99, "the smart object shows the saved contents: {p:?}"); + // With no Edit Contents document, Save stays the shell's (it needs the document's file). + s.actions.list.push(Action::new("Save", vec![("file.save".to_string(), json!({}))])); + assert!(s.execute("actions.play", json!({"action": "Save"})).unwrap().get("failed").is_some()); +} + #[test] fn deselect_with_nothing_selected_is_a_noop_in_playback() { // #6744: imported actions often start with Deselect; with no selection Photoshop plays on. @@ -69,6 +93,27 @@ fn unchecked_steps_are_skipped_and_follow_move_and_delete() { assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); } +#[test] +fn recorded_eye_visibility_replays_on_another_document_and_duplicate_names() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Same"})).unwrap(); + let hidden = s.execute("layer.new.layer", json!({"name": "Same"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("actions.record", json!({"name": "Hide"})).unwrap(); + s.execute("layer.setProps", json!({"layer": hidden, "visible": false, "coalesce": "eye-sweep"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let keep = s.execute("layer.new.layer", json!({"name": "Same"})).unwrap()["layer"].as_u64().unwrap(); + let target = s.execute("layer.new.layer", json!({"name": "Same"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.deselectLayers", json!({})).unwrap(); + let result = s.execute("actions.play", json!({"action": "Hide"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(keep)).unwrap().visible); + assert!(!s.active().unwrap().doc.layer(photocraft_doc::LayerId(target)).unwrap().visible); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(target)).unwrap().visible); +} + #[test] fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { let mut s = Session::new(); @@ -1095,7 +1140,7 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { assert!(played.get("failed").is_none(), "{played}"); assert_eq!(s.active().unwrap().history.past_len(), before + 2, "the no-op adds no history step"); - // The predicate agrees with the command for every layer: top level, above the Background, + // The predicate identifies no movement for every layer: top level, above the Background, // and inside a group. let a = s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].clone(); s.execute("layer.select", json!({"layer": a})).unwrap(); @@ -1107,9 +1152,18 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { for id in ids.into_iter().filter(|id| Some(*id) != bg) { for (cmd, dir) in cmds { let at_end = super::super::ops::arrange_at_end(&s.active().unwrap().doc, id, dir); + let history = s.active().unwrap().history.past_len(); let ran = s.execute(cmd, json!({"layer": id.0})); - assert_eq!(at_end, ran.is_err(), "{cmd} on {id:?}: {ran:?}"); - if ran.is_ok() { + if at_end { + if matches!(cmd, "layer.arrange.bringToFront" | "layer.arrange.sendToBack") { + assert_eq!(ran.unwrap(), json!({"moved": false}), "{cmd} on {id:?}"); + } else { + assert!(ran.is_err(), "{cmd} on {id:?}: {ran:?}"); + } + assert_eq!(s.active().unwrap().history.past_len(), history, "a no-op must not add history"); + } else { + ran.unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); s.execute("edit.undo", json!({})).unwrap(); } } diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index e18e37f1ec..d60fa26d10 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -219,6 +219,31 @@ LUT_3D_SIZE 2 assert_eq!(looks.as_array().unwrap().len(), photocraft_cms::lutfile::BUILTIN.len()); } +#[test] +fn color_lookup_mesh_3dl_honours_the_header() { + // #9078 / #9073: a Lustre .3dl whose `Mesh ` line declares the cube edge + // (2^inBits + 1) and the output range (up to 2^outBits - 1). The three-value shaper row used + // to be counted as a 28th node ("28 rows is not a cube"), and 10-bit codes under a 12-bit + // declaration divided by the inferred 1023 instead of the declared 4095. + let mut lut = String::from("3DMESH\nMesh 1 12\n0 512 1023\n"); + for r in 0..3 { + for g in 0..3 { + for b in 0..3 { + let v = [r, g, b].map(|c| (4095.0 - 4095.0 * c as f64 / 2.0).round() as i32); + lut.push_str(&format!("{} {} {}\n", v[0], v[1], v[2])); + } + } + } + let mut s = session(8, "rgb"); + paint(&mut s, |_, _| [64.0 / 255.0, 128.0 / 255.0, 192.0 / 255.0, 1.0]); + s.execute("image.adjustments.colorLookup", json!({"data": lut, "fileName": "inverse.3dl", "dither": false})).unwrap(); + // Photoshop 27.11 renders (64,128,192) as (191,127,63) through this file. + let after = rgba(&s, 5, 5); + for (c, want) in [(0, 191.0), (1, 127.0), (2, 63.0)] { + assert!((after[c] * 255.0 - want).abs() <= 1.0, "channel {c}: {after:?}"); + } +} + /// The kind's parameters, read back from the model (Color Lookup with its table name and size). #[test] fn color_lookup_file_round_trips_psd_in_its_own_format() { diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 3760e6916e..5723c93c59 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -1,3 +1,4 @@ +const DIFFUSE_MODE: &[(&str, &str)] = &[("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("Anst", "anisotropic")]; use super::adjustments::{adjustment_by_class, adjustment_steps, levels_from, levels_to, shadows_highlights_from, shadows_highlights_to}; use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, ref_class}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; @@ -14,7 +15,7 @@ use super::steps_layer::{ STROKE, apply_comp_from, apply_comp_to, clear_from, clear_to, delete_from, delete_to, duplicate_from, duplicate_to, fill_from, fill_to, flip_from, flip_to, move_from, move_to, play_from, play_to, rotate_from, rotate_to, select_from, select_to, stroke_to, visibility_from, visibility_to, }; -use super::steps_make::{make_from, make_to, set_from, set_to}; +use super::steps_make::{locking_from, locking_to, make_from, make_to, set_from, set_to}; use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM}; use super::{AtnEvent, D, Descriptor, STOP_MESSAGE, Value, json}; @@ -248,6 +249,7 @@ pub(super) const EVENTS: &[Event] = &[ ), ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), + ev!("Dfs ", "diffuse", "Diffuse", "filter.stylize.diffuse", &[F("Md ", "mode", Kind::Enum("DfsM", DIFFUSE_MODE)), F("FlRs", "seed", Kind::Long)]), Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, // Adjustments (Image › Adjustments). Event { @@ -385,6 +387,7 @@ pub(super) const EVENTS: &[Event] = &[ "layer.layerMask.hideSelection", "file.new", "file.newFromClipboard", + "history.newSnapshot", ], from: make_from, to: make_to, @@ -408,6 +411,8 @@ pub(super) const EVENTS: &[Event] = &[ "layer.setAdjustment", "layer.fill.pattern.set", "layer.new.layerFromBackground", + "layer.layerStyle.blendingOptions", + "layer.smartFilter.blendingOptions", ], from: set_from, to: set_to, @@ -436,8 +441,25 @@ pub(super) const EVENTS: &[Event] = &[ from: select_from, to: select_to, }, - Event { code: "Dlt ", name: "delete", label: "Delete", ids: &["layer.delete", "edit.clear", "layer.layerMask.delete"], from: delete_from, to: delete_to }, - Event { code: "", name: "clearEvent", label: "Clear", ids: &["select.editInQuickMaskMode"], from: clear_from, to: clear_to }, + Event { + code: "Dlt ", + name: "delete", + label: "Delete", + ids: &["layer.delete", "edit.clear", "layer.layerMask.delete", "layer.smartFilter.deleteFilterMask"], + from: delete_from, + to: delete_to, + }, + Event { code: "", name: "applyLocking", label: "Apply Locking", ids: &["layer.lockLayers"], from: locking_from, to: locking_to }, + // Timeline › Make Frames from Layers: no frame animation in PhotoCraft, no document change. + Event { + code: "", + name: "animationFramesFromLayers", + label: "Make Frames from Layers", + ids: &[], + from: |_| Mapped::Unsupported { harmless: true }, + to: |_, _| None, + }, + Event { code: "", name: "clearEvent", label: "Clear", ids: &["select.editInQuickMaskMode", "history.clear"], from: clear_from, to: clear_to }, Event { code: "Trnf", name: "transform", diff --git a/crates/engine/src/cmd/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs index a1b808bf34..a52b9fbf5d 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_image.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_image.rs @@ -286,6 +286,8 @@ const REFINE_OUTPUT: &[(&str, &str)] = &[ ("refineEdgeOutputNewLayerWithMask", "newLayerWithMask"), ("refineEdgeOutputNewDocument", "newDocument"), ("refineEdgeOutputNewDocumentWithMask", "newDocumentWithMask"), + // Newer Photoshop's name for Output To: Selection. + ("selectionOutputToSelection", "selection"), ]; /// Filter Gallery effects (`GEfc` with the effect in `GEfk`): Photoshop's effect code, the diff --git a/crates/engine/src/cmd/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs index 9dbdad579b..c69595e566 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_layer.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_layer.rs @@ -117,6 +117,15 @@ pub(super) fn delete_from(d: &Descriptor) -> Mapped { // The targeted channel of a layer is its mask (what Photoshop records after making an // adjustment layer over a selection and discarding the mask). Some(r) if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Trgt") => none("layer.layerMask.delete"), + // The mask Photoshop adds to a new fill or adjustment layer, or to a smart object's filters. + Some(r) if ref_class(r).as_deref() == Some("Chnl") => match target(r) { + Target::Ordinal(o) if o == "Msk" => none("layer.layerMask.delete"), + // Photoshop adds an empty filter mask with the first smart filter; PhotoCraft doesn't. + Target::Ordinal(o) if o == "filterMask" => step("layer.smartFilter.deleteFilterMask", json!({"ifPresent": true})), + _ => Mapped::Unsupported { harmless: false }, + }, + // Timeline frames: PhotoCraft has no frame animation, so there is nothing to delete. + Some(r) if ref_class(r).as_deref() == Some("animationClass") => Mapped::Unsupported { harmless: true }, Some(_) => Mapped::Unsupported { harmless: false }, } } @@ -131,6 +140,8 @@ pub(super) fn quick_mask_ref() -> D { pub(super) fn clear_from(d: &Descriptor) -> Mapped { match get_ref(d, "null").map(target) { Some(Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": false})), + // History panel menu › Clear History. + Some(Target::Property(p)) if p == "HsSt" => none("history.clear"), None => none("edit.clear"), _ => Mapped::Unsupported { harmless: false }, } @@ -139,6 +150,13 @@ pub(super) fn clear_from(d: &Descriptor) -> Mapped { pub(super) fn clear_to(id: &str, p: &Value) -> Option { match id { "select.editInQuickMaskMode" if jbool(p, "on") == Some(false) => Some(desc("null").with("null", quick_mask_ref())), + "history.clear" => Some(desc("null").with( + "null", + D::Reference(vec![ + ReferenceItem::Property { class: class("Prpr"), key: code("HsSt") }, + ReferenceItem::Enumerated { class: class("Dcmn"), type_id: code("Ordn"), value: code("Trgt") }, + ]), + )), _ => None, } } @@ -148,6 +166,8 @@ pub(super) fn delete_to(id: &str, p: &Value) -> Option { "edit.clear" => desc("null"), "layer.delete" => desc("null").with("null", layer_ref(p)?), "layer.layerMask.delete" => desc("null").with("null", target_ref("Chnl")), + "layer.smartFilter.deleteFilterMask" => desc("null") + .with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: Id::new("filterMask") }])), _ => return None, }) } diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 96f9033102..2fce72c36d 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -136,6 +136,9 @@ fn new_document_from_descriptor(d: &Descriptor) -> Option { Some(step("file.new", params)) } +/// New Snapshot's From: the full document, the layers merged, or the current layer. +const SNAPSHOT_FROM: &[(&str, &str)] = &[("FllD", "fullDocument"), ("MrgL", "mergedLayers"), ("CrnL", "currentLayer")]; + pub(super) fn make_from(d: &Descriptor) -> Mapped { if let Some(mapped) = duplicate_layer_from_descriptor(d) { return mapped; @@ -198,6 +201,24 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped { None => step("layer.new.group", Value::Object(p)), } } + // History panel › New Snapshot (of the current state). + Some("SnpS") => { + let mut p = Map::new(); + if let Some(n) = get_text(d, "Nm ") { + p.insert("name".into(), n.into()); + } + match get_enum(d, "Usng").as_deref().map(|u| lookup(SNAPSHOT_FROM, u)) { + None => {} + Some(Some(f)) => { + p.insert("from".into(), f.into()); + } + Some(None) => return Mapped::Unsupported { harmless: false }, + } + if get_bool(d, "replaceExisting") == Some(true) { + p.insert("replaceExisting".into(), true.into()); + } + step("history.newSnapshot", Value::Object(p)) + } _ => Mapped::Unsupported { harmless: false }, } } @@ -286,6 +307,18 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option { desc("null").with("Nw ", D::Class(class("Chnl"))).with("At ", at).with("Usng", enm("UsrM", lookup_back(MASK_USING, id)?)) } "file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))), + "history.newSnapshot" => { + let current = D::Reference(vec![ReferenceItem::Property { class: class("HstS"), key: code("CrnH") }]); + let mut d = desc("null").with("null", class_ref("SnpS")).with("From", current); + if let Some(n) = jstr(p, "name") { + d = d.with("Nm ", text(n)); + } + d = d.with("Usng", enm("HstS", lookup_back(SNAPSHOT_FROM, jstr(p, "from").unwrap_or("fullDocument"))?)); + if jbool(p, "replaceExisting") == Some(true) { + d = d.with("replaceExisting", D::Boolean(true)); + } + d + } "file.new" => { let mut n = desc("Dcmn"); if let Some(name) = jstr(p, "name") { @@ -401,6 +434,121 @@ fn background_from(d: &Descriptor) -> Mapped { steps(v) } +/// The Layers panel lock buttons (`layerLocking`) ↔ `layer.lockLayers` params. +const LOCKS: &[(&str, &str)] = &[ + ("protectTransparency", "transparency"), + ("protectComposite", "pixels"), + ("protectPosition", "position"), + ("protectArtboardAutonest", "artboard"), + ("protectAll", "all"), +]; + +/// Blending Options' Advanced checkboxes ↔ `layer.layerStyle.blendingOptions` params. +const ADVANCED_BLENDING: &[(&str, &str)] = &[("blendClipped", "blendClippedLayersAsGroup"), ("transparencyShapesLayer", "transparencyShapesLayer")]; + +fn lock_params(locks: &Descriptor) -> Option> { + let mut m = Map::new(); + // "Unlock all" clears every lock. + if get_bool(locks, "protectNone") == Some(true) { + for (_, param) in LOCKS { + m.insert((*param).into(), false.into()); + } + } + for (key, param) in LOCKS { + if let Some(b) = get_bool(locks, key) { + m.insert((*param).into(), b.into()); + } + } + (!m.is_empty()).then_some(m) +} + +/// `applyLocking`: a lock button in the Layers panel, on the target layer. +pub(super) fn locking_from(d: &Descriptor) -> Mapped { + let on_target = get_ref(d, "null").is_none_or(|r| ref_class(r).as_deref() == Some("Lyr") && matches!(target(r), Target::Ordinal(o) if o == "Trgt")); + match get_obj(d, "layerLocking").and_then(lock_params) { + Some(l) if on_target => step("layer.lockLayers", Value::Object(l)), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn locking_to(_: &str, p: &Value) -> Option { + let mut locks = desc("layerLocking"); + for (key, param) in LOCKS { + if let Some(b) = jbool(p, param) { + locks = locks.with(key, D::Boolean(b)); + } + } + if locks.items.is_empty() { + return None; + } + Some(desc("null").with("null", target_ref("Lyr ")).with("layerLocking", D::Descriptor(locks))) +} + +fn layer_set_from(d: &Descriptor, r: &[ReferenceItem]) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(mut p) = layer_target(r) else { return unsupported }; + let Some(t) = get_obj(d, "T ") else { return unsupported }; + let mut v = Vec::new(); + if let Some(c) = get_enum(t, "Clr ").and_then(|c| lookup(LABEL_COLORS, &c)) { + let mut lp = p.clone(); + lp.insert("color".into(), c.into()); + v.push(("layer.setLabelColor", Value::Object(lp))); + } + if let Some(n) = get_text(t, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(o) = get_num(t, "Opct") { + p.insert("opacity".into(), (o / 100.0).into()); + } + if let Some(f) = get_num(t, "fillOpacity") { + p.insert("fill".into(), (f / 100.0).into()); + } + if let Some(m) = get_enum(t, "Md ") { + let Some(label) = blend_label(&m) else { return unsupported }; + p.insert("blend".into(), label.into()); + } + if let Some(vis) = get_bool(t, "Vsbl") { + p.insert("visible".into(), vis.into()); + } + // Lock buttons and Blending Options' Advanced checkboxes act on the target layer. + let targeted = !p.contains_key("layer"); + if let Some(locks) = get_obj(t, "layerLocking") { + match lock_params(locks) { + Some(l) if targeted => v.push(("layer.lockLayers", Value::Object(l))), + _ => return unsupported, + } + } + let mut advanced = Map::new(); + for (key, param) in ADVANCED_BLENDING { + if let Some(b) = get_bool(t, key) { + advanced.insert((*param).into(), b.into()); + } + } + if !advanced.is_empty() { + if !targeted { + return unsupported; + } + v.push(("layer.layerStyle.blendingOptions", Value::Object(advanced))); + } + if p.keys().any(|k| k != "layer") { + v.push(("layer.setProps", Value::Object(p))); + } + // The Layer Style dialog's OK on a layer without effects records only the effects' + // scale (`Lefx` = {Scl}); an empty `T` is an OK that changed nothing. Neither changes + // the document. + let no_effect = t.items.iter().all(|(k, val)| match val { + D::Descriptor(fx) if k.is("Lefx") => fx.items.iter().all(|(fk, _)| fk.is("Scl ")), + _ => false, + }); + if !v.is_empty() { + steps(v) + } else if no_effect { + Mapped::Unsupported { harmless: true } + } else { + unsupported + } +} + pub(super) fn set_from(d: &Descriptor) -> Mapped { let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; let unsupported = Mapped::Unsupported { harmless: false }; @@ -416,35 +564,28 @@ pub(super) fn set_from(d: &Descriptor) -> Mapped { Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})), None => unsupported, }, - (Some("Lyr"), _) => { - let Some(mut p) = layer_target(r) else { return unsupported }; - let Some(t) = get_obj(d, "T ") else { return unsupported }; - let mut v = Vec::new(); - if let Some(c) = get_enum(t, "Clr ").and_then(|c| lookup(LABEL_COLORS, &c)) { - let mut lp = p.clone(); - lp.insert("color".into(), c.into()); - v.push(("layer.setLabelColor", Value::Object(lp))); + (Some("Lyr"), _) => layer_set_from(d, r), + // Layer › Smart Filter › Blending Options (`indx` counts the filters from 1, bottom first). + (Some("filterFX"), _) => { + let index = match r.first() { + Some(ReferenceItem::Index { index, .. }) if *index >= 1 => index - 1, + _ => return unsupported, + }; + let on_target = + matches!(r.get(1..), Some(rest) if ref_class(rest).as_deref() == Some("Lyr") && matches!(target(rest), Target::Ordinal(o) if o == "Trgt")); + if !on_target { + return unsupported; } - if let Some(n) = get_text(t, "Nm ") { - p.insert("name".into(), n.into()); + let Some(opts) = get_obj(d, "filterFX").and_then(|f| get_obj(f, "blendOptions")) else { return unsupported }; + let mut p = json!({"index": index}); + if let Some(o) = get_num(opts, "Opct") { + p["opacity"] = json!(o / 100.0); } - if let Some(o) = get_num(t, "Opct") { - p.insert("opacity".into(), (o / 100.0).into()); - } - if let Some(f) = get_num(t, "fillOpacity") { - p.insert("fill".into(), (f / 100.0).into()); - } - if let Some(m) = get_enum(t, "Md ") { + if let Some(m) = get_enum(opts, "Md ") { let Some(label) = blend_label(&m) else { return unsupported }; - p.insert("blend".into(), label.into()); + p["blend"] = json!(label); } - if let Some(vis) = get_bool(t, "Vsbl") { - p.insert("visible".into(), vis.into()); - } - if p.keys().any(|k| k != "layer") { - v.push(("layer.setProps", Value::Object(p))); - } - if v.is_empty() { unsupported } else { steps(v) } + step("layer.smartFilter.blendingOptions", p) } // A Pattern Fill layer's pattern (double-click its thumbnail). (Some("contentLayer"), Target::Ordinal(o)) if o == "Trgt" => match get_obj(d, "T ") { @@ -475,6 +616,38 @@ pub(super) fn set_from(d: &Descriptor) -> Mapped { } } +fn layer_set_to(p: &Value) -> Option { + // Only these keys map onto the `Lyr ` descriptor; locks, clipping, Advanced Blending + // channels or an explicit `layers` list would be dropped (#7196, #7246). + const MAPPED: [&str; 7] = ["layer", "name", "opacity", "fill", "blend", "visible", "color"]; + if p.as_object().is_some_and(|m| m.iter().any(|(k, v)| !v.is_null() && !MAPPED.contains(&k.as_str()))) { + return None; + } + let mut t = desc("Lyr "); + if let Some(n) = jstr(p, "name") { + t = t.with("Nm ", text(n)); + } + if let Some(o) = jnum(p, "opacity") { + t = t.with("Opct", pct(o * 100.0)); + } + if let Some(f) = jnum(p, "fill") { + t = t.with("fillOpacity", pct(f * 100.0)); + } + if let Some(m) = jstr(p, "blend") { + t = t.with("Md ", enm("BlnM", blend_ps(m)?)); + } + if let Some(v) = jbool(p, "visible") { + t = t.with("Vsbl", D::Boolean(v)); + } + if let Some(c) = jstr(p, "color") { + t = t.with("Clr ", enm("Clr ", lookup_back(LABEL_COLORS, c)?)); + } + if t.items.is_empty() { + return None; + } + Some(desc("null").with("null", layer_ref(p)?).with("T ", D::Descriptor(t))) +} + pub(super) fn set_to(id: &str, p: &Value) -> Option { let fsel = D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }]); let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t); @@ -538,35 +711,7 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option { sel(D::Descriptor(desc(cls).with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))) } "layer.setProps" | "layer.renameLayer" | "layer.setLabelColor" => { - // Only these keys map onto the `Lyr ` descriptor; locks, clipping, Advanced Blending - // channels or an explicit `layers` list would be dropped (#7196, #7246). - const MAPPED: [&str; 7] = ["layer", "name", "opacity", "fill", "blend", "visible", "color"]; - if p.as_object().is_some_and(|m| m.iter().any(|(k, v)| !v.is_null() && !MAPPED.contains(&k.as_str()))) { - return None; - } - let mut t = desc("Lyr "); - if let Some(n) = jstr(p, "name") { - t = t.with("Nm ", text(n)); - } - if let Some(o) = jnum(p, "opacity") { - t = t.with("Opct", pct(o * 100.0)); - } - if let Some(f) = jnum(p, "fill") { - t = t.with("fillOpacity", pct(f * 100.0)); - } - if let Some(m) = jstr(p, "blend") { - t = t.with("Md ", enm("BlnM", blend_ps(m)?)); - } - if let Some(v) = jbool(p, "visible") { - t = t.with("Vsbl", D::Boolean(v)); - } - if let Some(c) = jstr(p, "color") { - t = t.with("Clr ", enm("Clr ", lookup_back(LABEL_COLORS, c)?)); - } - if t.items.is_empty() { - return None; - } - desc("null").with("null", layer_ref(p)?).with("T ", D::Descriptor(t)) + return layer_set_to(p); } "layer.new.layerFromBackground" => { let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]); @@ -578,6 +723,39 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option { } desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?)) } + "layer.layerStyle.blendingOptions" => { + let o = p.as_object()?; + let mut t = desc("Lyr "); + for (key, param) in ADVANCED_BLENDING { + if let Some(b) = jbool(p, param) { + t = t.with(key, D::Boolean(b)); + } + } + // Only the Advanced checkboxes export: Photoshop records the dialog's other options + // differently. + if t.items.is_empty() || t.items.len() != o.len() { + return None; + } + desc("null").with("null", target_ref("Lyr ")).with("T ", D::Descriptor(t)) + } + "layer.smartFilter.blendingOptions" => { + if p.get("layer").is_some() { + return None; + } + let index = u32::try_from(p.get("index")?.as_u64()?).ok()?.checked_add(1)?; + let mut opts = desc("blendOptions"); + if let Some(o) = jnum(p, "opacity") { + opts = opts.with("Opct", pct(o * 100.0)); + } + if let Some(m) = jstr(p, "blend") { + opts = opts.with("Md ", enm("BlnM", blend_ps(m)?)); + } + let r = D::Reference(vec![ + ReferenceItem::Index { class: class("filterFX"), index }, + ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Trgt") }, + ]); + desc("null").with("null", r).with("filterFX", D::Descriptor(desc("filterFX").with("blendOptions", D::Descriptor(opts)))) + } "layer.setAdjustment" => { // The adjustment kind isn't in the params: Photoshop needs it, so only steps that // name one (`kind`) export. diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 08286b5329..011e9aa5e5 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -654,6 +654,7 @@ fn every_mapped_command_exports_and_imports_back() { ("edit.undo", json!({})), ("edit.redo", json!({})), ("layer.select", json!({"layer": "YELLOW", "mode": "remove"})), + ("layer.select", json!({"layer": "Or paste photocopy texture here", "mode": "range"})), ("layer.translate", json!({"dx": 0.36, "dy": -1.08, "units": "pt"})), ("select.loadSelection", json!({"channel": "targeted"})), ("layer.newFillLayer.pattern", json!({"pattern": "Debaser-Distressed-Dark", "scale": 50, "angle": 0, "link": true})), @@ -661,6 +662,15 @@ fn every_mapped_command_exports_and_imports_back() { ("image.mode.bitmap", json!({"method": "threshold"})), ("image.imageSize", json!({"resolution": 1200, "resample": "preserveDetails", "keepPrintSize": true})), ("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false})), + // COPYCAT, AJ_Actions2023 and the Line and Color tutorial set. + ("layer.smartFilter.deleteFilterMask", json!({"ifPresent": true})), + ("layer.smartFilter.blendingOptions", json!({"index": 1, "opacity": 0.5, "blend": "Darken"})), + ("layer.layerStyle.blendingOptions", json!({"blendClippedLayersAsGroup": false, "transparencyShapesLayer": false})), + ("layer.createClippingMask", json!({})), + ("layer.lockLayers", json!({"transparency": true})), + ("filter.stylize.diffuse", json!({"mode": "normal", "seed": 321654})), + ("history.clear", json!({})), + ("history.newSnapshot", json!({"name": "CopyCat - action result", "from": "fullDocument", "replaceExisting": true})), ("layerComp.apply", json!({"comp": "Comp 1"})), ]; for (id, params) in &cases { diff --git a/crates/engine/src/cmd/automate_cmds.rs b/crates/engine/src/cmd/automate_cmds.rs index 42fde9e9bf..ee253bea4a 100644 --- a/crates/engine/src/cmd/automate_cmds.rs +++ b/crates/engine/src/cmd/automate_cmds.rs @@ -375,7 +375,19 @@ fn write_shim(droplet: &str) -> Result { // quoted segment, emit a literal quote, then resume it. let quoted_abs = format!("'{}'", abs.replace('\'', "'\\''")); let body = format!( - "#!/bin/sh\n# PhotoCraft droplet: runs the action on the files given (or dropped).\nexec \"${{PHOTOCRAFT_CLI:-photocraft-cli}}\" droplet {quoted_abs} \"$@\"\n" + r#"#!/bin/sh +# PhotoCraft droplet: runs the action on the files given (or dropped). +if [ -n "${{PHOTOCRAFT_CLI:-}}" ]; then + cli="$PHOTOCRAFT_CLI" +elif [ -x /Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli ]; then + cli=/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli +elif [ -x "$HOME/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli" ]; then + cli="$HOME/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli" +else + cli=photocraft-cli +fi +exec "$cli" droplet {quoted_abs} "$@" +"# ); crate::file_cmds::write_file(&shim, body.as_bytes())?; #[cfg(unix)] diff --git a/crates/engine/src/cmd/automate_cmds/tests.rs b/crates/engine/src/cmd/automate_cmds/tests.rs index 3402496331..c6206cc041 100644 --- a/crates/engine/src/cmd/automate_cmds/tests.rs +++ b/crates/engine/src/cmd/automate_cmds/tests.rs @@ -156,6 +156,8 @@ fn droplets_are_written_and_run() { let shim = r["shim"].as_str().unwrap(); let text = std::fs::read_to_string(shim).unwrap(); assert!(text.starts_with("#!/bin/sh") && text.contains("droplet")); + assert!(text.contains("/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli")); + assert!(text.contains("${PHOTOCRAFT_CLI:-}"), "an explicit CLI path must take priority"); use std::os::unix::fs::PermissionsExt; assert_ne!(std::fs::metadata(shim).unwrap().permissions().mode() & 0o111, 0, "executable"); } diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index e0f165afcd..497aec67f2 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -410,14 +410,19 @@ fn clear_mode(p: &Value) -> bool { } /// Applies the options-bar blend `mode` to a brush. `"mode"` accepts any blend-mode name -/// (normal|multiply|screen|…), or `clear` to erase with the brush. The Eraser has no blend mode in +/// (normal|multiply|screen|…), or `behind` to paint beneath existing pixels, or `clear` to erase with the brush. The Eraser has no blend mode in /// Photoshop, so it is forced to Normal. fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings { b.erase |= clear_mode(p); if b.erase { b.mode = photocraft_color::BlendMode::Normal; + b.behind = false; + } else if p.get("mode").and_then(Value::as_str).is_some_and(|m| m.eq_ignore_ascii_case("behind")) { + b.mode = photocraft_color::BlendMode::Normal; + b.behind = true; } else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::blend_from_str) { b.mode = m; + b.behind = false; } b } @@ -789,6 +794,32 @@ fn mixer_clean(s: &mut Session, _: &Value) -> Result { Ok(serde_json::to_value(&s.tools.mixer).unwrap_or_default()) } +/// `paint.mixerLoad`: ⌥-click with the Mixer Brush loads the reservoir from the canvas colour at +/// (`x`, `y`) (Photoshop's Current Brush Load), from the layers Sample All Layers names. The +/// foreground colour is left alone. Over transparency or off the canvas nothing is loaded. +fn mixer_load_pixel(s: &mut Session, p: &Value) -> Result { + let cmd = "paint.mixerLoad"; + let coord = |k: &str| { + let v = p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()); + v.ok_or_else(|| bad(cmd, format!("`{k}` must be a finite number (document pixels)"))) + }; + let (x, y) = (coord("x")?, coord("y")?); + let size = crate::sample_cmds::size_param(cmd, p)?; + let which = if flag(p, "sampleAllLayers", s.tools.brush.mixer.sample_all_layers) { + crate::sample_cmds::SampleLayers::All + } else { + crate::sample_cmds::SampleLayers::Current + }; + let d = s.active().ok_or(EngineError::NoDocument)?; + let [r, g, b, a] = crate::sample_cmds::sample_color(&d.doc, d.active_layer, x, y, size, which); + if a.is_nan() || a <= 0.0 { + return Ok(json!({"loaded": false})); + } + let foreground = s.tools.foreground; + s.tools.mixer.load_sampled([r, g, b, 1.0], foreground); + Ok(json!({"loaded": true, "color": [r, g, b, 1.0]})) +} + /// `paint.colorReplacement`'s stroke and settings. The replacement colour is the brush colour /// (the foreground unless `color` says otherwise). It paints layer pixels only: a mask, alpha /// channel or Quick Mask `target` is refused rather than recolouring the layer instead. @@ -1271,7 +1302,7 @@ pub fn specs() -> Vec { spec!( "paint.pencil", "Pencil", - r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"opacity":0..1?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"block":bool=false (a hard 16×16 screen-px square, 16/zoom doc px; size, opacity, flow, hardness and dynamics ignored: the Eraser's Block mode),"zoom":view zoom=1,"autoErase":bool=false,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"opacity":0..1?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|behind (paints beneath existing pixels)|clear (erases with this brush)"="normal","erase":bool?,"block":bool=false (a hard 16×16 screen-px square, 16/zoom doc px; size, opacity, flow, hardness and dynamics ignored: the Eraser's Block mode),"zoom":view zoom=1,"autoErase":bool=false,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, has_paintable, pencil, true @@ -1286,6 +1317,14 @@ pub fn specs() -> Vec { ), spec!("brush.mixer.load", "Load Mixer Brush", r##"{"color":"#rrggbb"|[r,g,b,a?] 0..1?=foreground}"##, always, mixer_load, true), spec!("brush.mixer.clean", "Clean Mixer Brush", "{}", always, mixer_clean, true), + spec!( + "paint.mixerLoad", + "Load Mixer Brush", + r##"{"x":px,"y":px,"size":"point"|1|3|5|11|31|51|101=1,"sampleAllLayers":bool=brush.mixer.sampleAllLayers} → {"loaded":bool,"color"?:[r,g,b,a]} (loads the Mixer Brush reservoir from the canvas colour there, as ⌥-click does; the foreground colour is unchanged; the next strokes keep that load while the foreground stays as it is)"##, + has_paintable, + mixer_load_pixel, + true + ), spec!( "paint.colorReplacement", "Color Replacement", diff --git a/crates/engine/src/cmd/brush_cmds/mixer_live.rs b/crates/engine/src/cmd/brush_cmds/mixer_live.rs index 586479039d..58185b55f0 100644 --- a/crates/engine/src/cmd/brush_cmds/mixer_live.rs +++ b/crates/engine/src/cmd/brush_cmds/mixer_live.rs @@ -30,6 +30,7 @@ fn valid_state(state: &MixerState) -> bool { && state.reservoir.as_ref().is_none_or(valid_color) && state.pickup.as_ref().is_none_or(valid_color) && state.color.as_ref().is_none_or(valid_color) + && state.sampled_over.as_ref().is_none_or(valid_color) && state.spatial.as_ref().is_none_or(|colors| colors.len() == 4096 && colors.iter().all(valid_color)) } diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 3a3041c4a6..c29d4c3146 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -1407,6 +1407,23 @@ fn clear_mode_erases_with_the_brush_or_pencil() { } } +#[test] +fn behind_brush_and_pencil_preserve_foreground_and_round_trip_history() { + for cmd in ["paint.stroke", "paint.pencil"] { + let mut s = session(40, 20); + s.execute(cmd, json!({"points": [[10, 10]], "size": 6, "color": "#ff0000", "hardness": 1.0})).unwrap(); + let before = surface(&s); + s.execute(cmd, json!({"points": [[2, 10], [38, 10]], "size": 6, "color": "#0000ff", "mode": "behind", "hardness": 1.0})).unwrap(); + assert_eq!(rgba(&s, 10, 10), [1.0, 0.0, 0.0, 1.0], "{cmd}: existing opaque paint"); + assert_eq!(rgba(&s, 25, 10), [0.0, 0.0, 1.0, 1.0], "{cmd}: transparent pixels"); + let painted = surface(&s); + s.execute("edit.undo", json!({})).unwrap(); + assert!(same_pixels(&surface(&s), &before, Rect::new(0, 0, 40, 20))); + s.execute("edit.redo", json!({})).unwrap(); + assert!(same_pixels(&surface(&s), &painted, Rect::new(0, 0, 40, 20))); + } +} + /// #4344: a foreground picked as CMYK 100/0/0/0 is painted into a CMYK document as those inks by /// the Brush and the Pencil, not as whatever its sRGB stand-in converts back to (100/28/0/17). #[test] @@ -1424,3 +1441,36 @@ fn brush_and_pencil_paint_a_cmyk_pick_with_the_picked_inks() { assert!(got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02), "{cmd}: {got:?}"); } } + +#[test] +fn mixer_load_fills_the_reservoir_from_the_canvas_and_keeps_the_foreground() { + let mut s = session(80, 40); + s.execute("paint.stroke", json!({"points": [[4, 20], [60, 20]], "size": 6, "color": "#0000ff"})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + // Over transparency nothing is loaded. + let r = s.execute("paint.mixerLoad", json!({"x": 30, "y": 5})).unwrap(); + assert_eq!(r["loaded"], json!(false)); + assert!(s.tools.mixer.reservoir.is_none()); + // On the blue stroke the reservoir takes its colour; the foreground stays red. + let r = s.execute("paint.mixerLoad", json!({"x": 30, "y": 20})).unwrap(); + assert_eq!(r["loaded"], json!(true)); + assert_eq!(s.tools.mixer.reservoir, Some([0.0, 0.0, 1.0, 1.0])); + assert_eq!(s.tools.foreground, [1.0, 0.0, 0.0, 1.0]); + // The next dry stroke paints the sampled blue, not the foreground. + let brush = json!({"pressureSize": false, "spacing": 0.25}); + let dry = |y: i32, size: u32| json!({"points": [[5, y], [40, y]], "size": size, "wet": 0, "load": 100, "mix": 0, "brush": brush}); + s.execute("paint.mixerBrush", dry(30, 8)).unwrap(); + assert_eq!(rgba(&s, 20, 30), [0.0, 0.0, 1.0, 1.0]); + // A new foreground colour takes the reservoir back. + s.execute("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + s.execute("paint.mixerBrush", dry(36, 4)).unwrap(); + assert_eq!(rgba(&s, 20, 36), [0.0, 1.0, 0.0, 1.0]); + // Bad coordinates are an error, not a panic, and leave the reservoir, the foreground and the + // document untouched. + let (mixer, foreground) = (s.tools.mixer.clone(), s.tools.foreground); + let revision = s.active().unwrap().revision; + assert!(s.execute("paint.mixerLoad", json!({"x": "a", "y": 1})).is_err()); + assert_eq!(s.tools.mixer, mixer); + assert_eq!(s.tools.foreground, foreground); + assert_eq!(s.active().unwrap().revision, revision); +} diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index 9e9c0aafd3..b443441a18 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -1675,7 +1675,10 @@ mod settings_tests { fn exif_srgb_jpeg_round_trip() { let mut s = Session::new(); s.execute("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap(); - let r = photocraft_io::export(&untagged_camera_file(Some(1)), "x.jpg", &photocraft_io::ExportOptions::default()).unwrap(); + // Embed Color Profile off: an untagged document is otherwise tagged sRGB on export (#9325). + let mut opts = photocraft_io::ExportOptions::default(); + opts.encode.embed_icc = false; + let r = photocraft_io::export(&untagged_camera_file(Some(1)), "x.jpg", &opts).unwrap(); let back = photocraft_io::import("x.jpg", &r.bytes).unwrap().document; assert!(back.icc_profile.is_none(), "no ICC profile in the file"); let (_, r) = s.open_document(back, None); diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs index ba875b9a2b..8929301026 100644 --- a/crates/engine/src/cmd/edit_cmds.rs +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -916,7 +916,18 @@ fn edit_guide(s: &mut Session, p: &Value) -> Result { /// View › New Guide / guide moves (undoable, like Photoshop's "New Guide"/"Move Guide" states). fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result { let vertical = p.get("orientation").and_then(Value::as_str).unwrap_or("horizontal") == "vertical"; - let pos = guide_position(s, p, vertical)?; + // Move Guide can turn the guide (⌥ while dragging it, as in Photoshop): `toOrientation`. + let to_vertical = match p.get("toOrientation").map(|v| v.as_str()) { + None => vertical, + Some(Some("vertical")) => true, + Some(Some("horizontal")) => false, + Some(_) => return Err(EngineError::Other("`toOrientation` must be \"horizontal\" or \"vertical\"".into())), + }; + if to_vertical != vertical && op != "move" { + return Err(EngineError::Other("`toOrientation` applies to view.moveGuide only".into())); + } + // A % position is of the axis the guide ends up on. + let pos = guide_position(s, p, to_vertical)?; let color = if op == "new" { guide_color(p)? } else { None }; let index = p.get("index").and_then(Value::as_u64).map(|v| v as usize); let label = match op { @@ -939,10 +950,20 @@ fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result { "move" => { let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?; let to = pos.ok_or(EngineError::Other("missing `position`".into()))?; - let from = std::mem::replace(&mut g[i], to); + let from = if to_vertical == vertical { + std::mem::replace(&mut g[i], to) + } else { + let from = g.remove(i); + if to_vertical { + guides.vertical.push(to) + } else { + guides.horizontal.push(to) + } + from + }; // The guide takes its colour along; another guide left at the old position keeps it. if let Some(rgb) = guides.color(vertical, from) { - guides.set_color(vertical, to, Some(rgb)); + guides.set_color(to_vertical, to, Some(rgb)); } guides.prune_colors(); } @@ -1088,7 +1109,7 @@ pub fn specs() -> Vec { "Move Guide", &[], None, - r##"{"orientation":"horizontal|vertical","index":n,"position":px or ""} (units as for view.newGuide)"##, + r##"{"orientation":"horizontal|vertical","index":n,"position":px or "","toOrientation":"horizontal|vertical"?} (units as for view.newGuide; toOrientation turns the guide, its position then on the new axis)"##, has_doc, |s, p| guide_cmd(s, p, "move") ), diff --git a/crates/engine/src/cmd/edit_cmds/tests.rs b/crates/engine/src/cmd/edit_cmds/tests.rs index ec9a9fa8b7..040ea3721b 100644 --- a/crates/engine/src/cmd/edit_cmds/tests.rs +++ b/crates/engine/src/cmd/edit_cmds/tests.rs @@ -1191,6 +1191,35 @@ fn guides_are_undoable() { assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err()); } +/// #5034: Move Guide turns a guide with `toOrientation` (⌥ while dragging it), in one undo +/// step, taking its colour along; a % position is of the new axis. +#[test] +fn move_guide_turns_a_guide() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 30, "color": "magenta"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 70})).unwrap(); + s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": "50%", "toOrientation": "vertical"})).unwrap(); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.horizontal.clone(), g.vertical.clone()), (vec![70.0], vec![100.0]), "50% of the width"); + assert_eq!(g.color(true, 100.0), Some([255, 0, 255]), "the colour moves with the guide"); + assert_eq!(g.color(false, 30.0), None); + // The same orientation is a plain move. + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 20, "toOrientation": "vertical"})).unwrap(); + assert_eq!(s.active().unwrap().doc.guides.vertical, vec![20.0]); + s.undo(); + s.undo(); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.horizontal.clone(), g.vertical.clone()), (vec![30.0, 70.0], vec![]), "one undo step per move"); + // Bad params are refused and leave the guides alone. + assert!(s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": 5, "toOrientation": "diagonal"})).is_err()); + assert!(s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": 5, "toOrientation": 1})).is_err()); + assert!(s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 5, "toOrientation": "vertical"})).is_err()); + assert!(s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 9, "position": 5, "toOrientation": "vertical"})).is_err()); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.horizontal.clone(), g.vertical.clone()), (vec![30.0, 70.0], vec![])); +} + /// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are /// refused without touching the document. #[test] diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index efdd3ad8bf..3925bf8321 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -341,7 +341,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,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"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"?,"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}"##, native_doc, layers_to_files ), diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 80213dba16..1f7f9677ff 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -44,6 +44,7 @@ pub struct LayerExportReport { pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); + let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. @@ -72,6 +73,24 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& only.visible = true; only.clipped = false; one.layers = vec![only]; + if trim { + let mut bounds = Rect::EMPTY; + let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { + let width = band.rect.width() as usize; + for (i, rgba) in band.px.iter().enumerate() { + if rgba[3] > 0.0 && width > 0 { + let x = band.rect.x0 + (i % width) as i32; + let y = band.rect.y0 + (i / width) as i32; + bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); + } + } + Ok(()) + }); + if !bounds.is_empty() && bounds != one.bounds() { + crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; + } + } + let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 7eb770d844..d93c15fd82 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1159,6 +1159,61 @@ fn layers_to_files_writes_each_visible_layer() { assert_eq!(r["files"].as_array().unwrap().len(), 3); } +#[test] +fn layers_to_files_can_trim_transparent_margins_without_changing_the_document() { + let dir = tmp("layers-trim"); + for depth in [8, 16, 32] { + let mut s = session(12, 11, depth); + s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap(); + s.execute("select.rect", json!({"x": 3, "y": 2, "width": 4, "height": 5})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + + let before = doc(&s).clone(); + let regular = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": format!("full-{depth}"), "format": "png"})).unwrap(); + let full = std::fs::read(regular["files"][0].as_str().unwrap()).unwrap(); + let full = photocraft_io::import("full.png", &full).unwrap().document; + assert_eq!((full.size.width, full.size.height), (12, 11), "default is unchanged"); + + let trimmed = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": format!("trim-{depth}"), "format": "png", "trim": true})).unwrap(); + let image = std::fs::read(trimmed["files"][0].as_str().unwrap()).unwrap(); + let cropped = photocraft_io::import("trim.png", &image).unwrap().document; + assert_eq!((cropped.size.width, cropped.size.height), (4, 5), "depth {depth}"); + let px = photocraft_compose::render(&cropped, Rect::new(0, 0, 1, 1)).px[0]; + assert!(px[0] > 0.95 && px[1] < 0.05 && px[2] < 0.05, "depth {depth}: {px:?}"); + assert_eq!(*doc(&s), before, "export must not crop the original document"); + } +} + +#[test] +fn streamed_layer_export_respects_trim() { + let mut s = session(12, 11, 8); + s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap(); + s.execute("select.rect", json!({"x": 3, "y": 2, "width": 4, "height": 5})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let mut encoded = Vec::new(); + let names = super::export_layers_with(&s, &json!({"trim": true, "format": "png"}), |name, bytes| { + encoded.push((name.to_string(), bytes.to_vec())); + Ok(()) + }) + .unwrap(); + assert_eq!(names.len(), encoded.len()); + let cropped = photocraft_io::import(&encoded[0].0, &encoded[0].1).unwrap().document; + assert_eq!((cropped.size.width, cropped.size.height), (4, 5)); +} + +#[test] +fn trimming_an_empty_layer_keeps_a_valid_nonzero_canvas() { + let dir = tmp("layers-trim-empty"); + let mut s = session(6, 7, 8); + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + let result = s.execute("file.export.layersToFiles", json!({"dir": dir, "format": "png", "trim": true})).unwrap(); + let bytes = std::fs::read(result["files"][0].as_str().unwrap()).unwrap(); + let back = photocraft_io::import("empty.png", &bytes).unwrap().document; + assert_eq!((back.size.width, back.size.height), (6, 7)); +} + #[test] fn load_files_into_stack_and_image_processor_and_batch() { let dir = tmp("batch"); diff --git a/crates/engine/src/cmd/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs index d8bea8607b..ba639876a3 100644 --- a/crates/engine/src/cmd/history_cmds.rs +++ b/crates/engine/src/cmd/history_cmds.rs @@ -163,6 +163,10 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result { let name = name.unwrap_or_else(|| next_snapshot_name(st)); let id = st.next_snapshot; st.next_snapshot = id.saturating_add(1); + // An action's New Snapshot with "replace existing": a snapshot of that name gives way. + if p.get("replaceExisting").and_then(Value::as_bool) == Some(true) { + st.snapshots.retain(|snap| snap.name != name); + } st.snapshots.push(Snapshot { id, name: name.clone(), doc, layers }); Ok(json!({ "snapshot": id, "name": name })) } @@ -284,7 +288,7 @@ pub fn specs() -> Vec { label: "New Snapshot", menu: &[], shortcut: None, - params: r##"{"name":str?="Snapshot N","from":"fullDocument"|"mergedLayers"|"currentLayer"="fullDocument"} → {snapshot,name}: a named copy of the document for the session (not a history state)"##, + params: r##"{"name":str?="Snapshot N","from":"fullDocument"|"mergedLayers"|"currentLayer"="fullDocument","replaceExisting":bool=false (drop snapshots of the same name first)} → {snapshot,name}: a named copy of the document for the session (not a history state)"##, enabled: has_doc, run: new_snapshot, journal: true, @@ -442,6 +446,31 @@ mod tests { assert_eq!(snapshots(&s), json!([first, {"id": 1, "name": "Snapshot 1"}, {"id": 2, "name": "Before green"}])); } + #[test] + fn replace_existing_snapshot_and_clear_history() { + let mut s = session(); + s.execute("history.newSnapshot", json!({"name": "Result"})).unwrap(); + s.execute("history.newSnapshot", json!({"name": "Other"})).unwrap(); + s.execute("history.newSnapshot", json!({"name": "Result", "replaceExisting": true})).unwrap(); + let opening = json!({"id": 0, "name": s.active().unwrap().doc.name}); + assert_eq!(snapshots(&s), json!([opening, {"id": 2, "name": "Other"}, {"id": 3, "name": "Result"}])); + let kept_snapshots = snapshots(&s); + let history_before = entries(&s); + let pixel = top_pixel(&s); + s.execute("history.clear", json!({})).unwrap(); + assert_eq!(entries(&s).len(), 1, "only the current state is left"); + assert!(s.active().unwrap().history.can_undo(), "the current Clear History remains undoable"); + assert_eq!(top_pixel(&s), pixel, "the document is unchanged"); + assert_eq!(snapshots(&s), kept_snapshots, "opening and named snapshots stay unchanged"); + // Current History menu semantics refuse a second clear; snapshots remain independent. + assert!(s.execute("history.clear", json!({})).is_err()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(entries(&s), history_before, "Undo restores the cleared states"); + assert_eq!(snapshots(&s), kept_snapshots, "Undo also preserves every snapshot"); + assert_eq!(top_pixel(&s), pixel); + assert!(Session::new().execute("history.clear", json!({})).is_err(), "no document"); + } + #[test] fn select_snapshot_returns_to_it_as_one_undoable_state() { let mut s = session(); diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 17f87691c8..c8c3e0b7d2 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -334,10 +334,23 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { /// The flattened document, or an error when the canvas is over the compositor's render cap /// ([`photocraft_compose::MAX_RENDER_PIXELS`]; `flatten` returns an empty buffer then). fn flatten_whole(doc: &Document, cmd: &str) -> Result { - let buf = photocraft_compose::flatten(doc); let (w, h) = (doc.size.width, doc.size.height); - if buf.px.len() as u64 != u64::from(w) * u64::from(h) { - return Err(bad(cmd, format!("the document ({w} x {h} px) is too large to flatten (limit {} pixels)", photocraft_compose::MAX_RENDER_PIXELS))); + let count = u64::from(w) * u64::from(h); + let operation = if cmd == "image.trim" { + "trim" + } else if cmd == "image.duplicate" { + "duplicate merged" + } else { + "flatten" + }; + let too_large = + || bad(cmd, format!("the document ({w} x {h} px) is too large to {operation} (flatten limit {} pixels)", photocraft_compose::MAX_RENDER_PIXELS)); + if count > photocraft_compose::MAX_RENDER_PIXELS { + return Err(too_large()); + } + let buf = photocraft_compose::flatten(doc); + if buf.px.len() as u64 != count { + return Err(too_large()); } Ok(buf) } @@ -398,7 +411,7 @@ fn delete_cropped_pixels(layers: &mut [Layer], r: Rect) { /// Crops the document to `r` (in current document coordinates). /// A frame that extends past the canvas fills the Background's new area with `extension` (the /// background colour, as Photoshop's Crop tool does); other layers get transparent pixels there. -fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extension: [f32; 4]) -> Result<()> { +pub(crate) fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extension: [f32; 4]) -> Result<()> { // The origin moves to (0, 0); `-i32::MIN` has no i32 value (#959). let (Some(dx), Some(dy)) = (r.x0.checked_neg(), r.y0.checked_neg()) else { return Err(bad(cmd, format!("the crop origin ({}, {}) can't be moved to (0, 0) within the 32-bit coordinate range", r.x0, r.y0))); diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 3061ce69c0..64c3e5028f 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -961,3 +961,30 @@ fn duplicate_document() { assert_eq!(doc(&s).layers.len(), 1); assert!(doc(&s).name.ends_with("copy")); } + +#[test] +fn trim_and_duplicate_merged_on_too_large_document_fail_gracefully_without_panic() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40000, "height": 30000, "background": "transparent"})).unwrap(); + let initial_layers = doc(&s).layers.len(); + let initial_bounds = doc(&s).bounds(); + let initial_rev = s.active().unwrap().revision; + let initial_docs = s.documents().len(); + + let trim_res = s.execute("image.trim", json!({"basedOn": "topLeft"})); + assert!(trim_res.is_err(), "trim on too-large document must return error"); + let err = trim_res.unwrap_err().to_string(); + assert!(err.contains("too large to trim"), "error should explain document is too large: {err}"); + assert_eq!(doc(&s).layers.len(), initial_layers, "layer count unchanged after failed trim"); + assert_eq!(doc(&s).bounds(), initial_bounds, "canvas size unchanged after failed trim"); + assert_eq!(s.active().unwrap().revision, initial_rev, "revision unchanged after failed trim"); + + let dup_res = s.execute("image.duplicate", json!({"mergedOnly": true})); + assert!(dup_res.is_err(), "duplicate merged on too-large document must return error"); + let dup_err = dup_res.unwrap_err().to_string(); + assert!(dup_err.contains("too large to duplicate merged"), "error should explain document is too large: {dup_err}"); + assert_eq!(s.documents().len(), initial_docs, "document count unchanged after failed duplicate"); + assert_eq!(doc(&s).layers.len(), initial_layers, "layer count unchanged after failed duplicate"); + assert_eq!(doc(&s).bounds(), initial_bounds, "canvas size unchanged after failed duplicate"); + assert_eq!(s.active().unwrap().revision, initial_rev, "revision unchanged after failed duplicate"); +} diff --git a/crates/engine/src/cmd/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs index 631cceac65..d497133380 100644 --- a/crates/engine/src/cmd/layer_copy_cmds.rs +++ b/crates/engine/src/cmd/layer_copy_cmds.rs @@ -118,6 +118,10 @@ pub(crate) fn adapt_copies(s: &Session, copies: &mut Document, dest: &Document) *surf = surf.convert(f); }); } + // Type keeps its size in pixels at the destination's resolution, as an Image Size resolution + // change keeps it (Photoshop adapts the point size: 24 pt at 72 ppi is 5.76 pt at 300 ppi). + // Left at the source's, a copy re-laid out at the destination's on its next edit (#9560). + crate::canvas_geom::set_resolution(copies, dest.resolution_dpi); let new_canvas = copies.bounds() != dest.bounds(); prepare_shapes(&mut copies.layers, dest, new_canvas); Ok(()) diff --git a/crates/engine/src/cmd/layer_copy_cmds/tests.rs b/crates/engine/src/cmd/layer_copy_cmds/tests.rs index b3200b16ef..cdd7d55b7f 100644 --- a/crates/engine/src/cmd/layer_copy_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_copy_cmds/tests.rs @@ -369,3 +369,26 @@ fn a_copied_group_cannot_nest_the_destination_past_the_group_depth_limit() { assert!(e.to_string().contains("deeper than"), "{e}"); assert_eq!(*doc(&s, 1), before, "nothing was copied"); } + +/// #9560: a type layer copied between documents of different resolutions keeps its size in +/// pixels, also after its next text edit (it used to re-lay out at the destination's resolution: +/// a 24 pt line from 72 ppi grew about 4.2 times in a 300 ppi document). Photoshop adapts the +/// point size instead (24 pt at 72 ppi is 5.76 pt at 300 ppi); the pixels are the same. +#[test] +fn copied_type_keeps_its_pixel_size_across_resolutions_after_an_edit() { + for (from, to) in [(72, 300), (300, 72)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": from})).unwrap(); + let t = LayerId(s.execute("type.create", json!({"text": "H", "size": 24, "x": 128, "y": 100})).unwrap()["layer"].as_u64().unwrap()); + let original = bounds(&s, 0, t); + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": to})).unwrap(); + s.set_active(0); + s.execute("layer.select", json!({"layer": t.0})).unwrap(); + let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()); + assert_eq!(bounds(&s, 1, id).size(), original.size(), "{from}→{to}: the copy"); + s.execute("type.edit", json!({"layer": id.0, "text": "M"})).unwrap(); + s.execute("type.edit", json!({"layer": id.0, "text": "H"})).unwrap(); + let after = bounds(&s, 1, id); + assert_eq!(after.size(), original.size(), "{from}→{to}: after an edit, {after:?} vs {original:?}"); + } +} diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index 19a62d0a8b..b34aab7623 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -2,6 +2,10 @@ use super::enabled::check_all_unlocked; use super::layer_params::{layer_param, mask_at_depth}; use super::{Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, json, pixels}; +/// Bring to Front / Send to Back of a layer already there: nothing to do, which isn't an error +/// (a Photoshop action plays it without complaint). +const ALREADY_THERE: &str = "the layer is already at the front or back"; + /// Is layer `id` already as far as Arrange can take it in direction `dir` (up when positive)? True /// at the top or bottom of its stack, or just above the Background, which stays at the bottom. The /// Background itself is not: arranging it is refused outright. @@ -26,7 +30,7 @@ pub(crate) fn arrange_at_end(doc: &Document, id: LayerId, dir: i32) -> bool { pub(super) fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { let id = layer_param(s, p)?; - s.edit("Arrange", |doc, _| { + let edited = s.edit("Arrange", |doc, _| { // The Background stays at the bottom: it doesn't move and nothing goes below it. let bg = crate::background_cmds::background_id(doc); if bg == Some(id) { @@ -51,12 +55,16 @@ pub(super) fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { moved = true; } if !moved { - return Err(EngineError::Other("layer can't move further".into())); + let end = matches!(delta, i32::MAX | i32::MIN); + return Err(EngineError::Other(if end { ALREADY_THERE } else { "layer can't move further" }.into())); } crate::clip_group::settle(doc, &[id], &before, false); Ok(()) - })?; - Ok(Value::Null) + }); + match edited { + Err(EngineError::Other(m)) if m == ALREADY_THERE => Ok(json!({"moved": false})), + r => r.map(|_| Value::Null), + } } /// Add (`Some`) or remove (`None`) a layer mask. Adding acts on every selected layer that can take diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index d06b0fb29c..fce3a28c11 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -10,7 +10,7 @@ //! type layer also has a vector mask). Knots are addressed by `subpath` and `knot` index, as //! listed by `path.info`, and the result is `{name, path}` in the compact JSON form. -use photocraft_doc::{LayerContent, Path}; +use photocraft_doc::{LayerContent, Path, PathOp}; use photocraft_geom::Point; use photocraft_vector::edit::{self, Handle}; use serde_json::{Value, json}; @@ -48,7 +48,15 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> { /// Applies `f` to the targeted path in one undoable step labelled `label`. fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result { - let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); + // A malformed target is an error, never a silent edit of the Work Path or the active layer. + let name = match p.get("name") { + Some(v) => v.as_str().ok_or_else(|| bad(cmd, "`name` must be a path name, \"work\" or \"layer\""))?, + None => "work", + } + .to_owned(); + if name == "layer" && p.get("layer").is_some_and(|v| !v.is_u64()) { + return Err(bad(cmd, "`layer` must be a layer id")); + } let layer = if name == "layer" { Some(layer_id(s, p)?) } else { None }; // Type on a path: its own path, the text laid along it again (#9114). A vector mask on the // layer stays what `"layer"` edits, as with `path.info`, unless `"typePath": true`. @@ -166,6 +174,70 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result { Ok(r) } +/// Merge Shape Components on a path (the Pen's and Path Selection's Path Operations menu): the +/// components' operations are baked into plain combined outlines, as for a shape layer. +fn merge_components(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.mergeShapeComponents"; + let tol = match p.get("tolerance") { + Some(v) => v.as_f64().filter(|t| t.is_finite()).ok_or_else(|| bad(CMD, "`tolerance` must be a number"))?.clamp(0.05, 10.0), + None => 0.1, + }; + let mask = p.get("name").and_then(Value::as_str) == Some("layer") + && layer_id(s, p).ok().and_then(|id| s.active()?.doc.layer(id).map(|l| !matches!(l.content, LayerContent::Shape(_)))).unwrap_or(false); + edit_path(s, CMD, p, "Merge Shape Components", |path| { + let mut merged = crate::vector_cmds::bake_path(path, tol).map_err(|e| e.to_string())?; + // Components that cancel out cover nothing, but an empty vector mask reveals the whole + // layer (hides it when inverted): flip it so the mask still shows what it did. + if mask && merged.is_empty() && !path.is_empty() { + merged.inverted = !path.inverted; + } + *path = merged; + Ok(()) + }) +} + +/// The Path Operations menu (or + / −) with path components selected: the components holding +/// `subpaths` take `op`, the way Photoshop changes the operation of the selected components. A +/// component's operation lives on its first subpath; the subpaths joined to it keep theirs. The +/// first component is what the others combine with and always draws as Combine +/// (`Path::effective_op`), so it keeps its operation; naming only it is refused. +fn set_operation(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.setOperation"; + let op = p + .get("op") + .and_then(Value::as_str) + .and_then(crate::vector_cmds::op_from) + .filter(|op| *op != PathOp::Join) + .ok_or_else(|| bad(CMD, "`op` must be \"combine\", \"subtract\", \"intersect\" or \"exclude\""))?; + let subpaths: Vec = p + .get("subpaths") + .and_then(Value::as_array) + .filter(|a| !a.is_empty()) + .ok_or_else(|| bad(CMD, "`subpaths` must list subpath indices"))? + .iter() + .map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(CMD, "each subpath is an index"))) + .collect::>()?; + edit_path(s, CMD, p, "Path Operation", |path| { + let components = path.components(); + let mut heads = Vec::with_capacity(subpaths.len()); + for i in &subpaths { + let c = components.iter().find(|c| c.contains(i)).ok_or_else(|| format!("no subpath {i} (the path has {})", path.subpaths.len()))?; + if c.start != 0 { + heads.push(c.start); + } + } + if heads.is_empty() { + return Err("the first component always combines: it is the shape the others act on".into()); + } + for h in heads { + if let Some(sp) = path.subpaths.get_mut(h) { + sp.op = op; + } + } + Ok(()) + }) +} + pub fn specs() -> Vec { const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path, a vector mask, or else type on a path's Type Path),"typePath":bool=false (with "layer": the Type Path even when the type layer has a vector mask)"#; let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result| CommandSpec { @@ -210,12 +282,24 @@ pub fn specs() -> Vec { r#""subpath":i,"knot":j (its neighbours are joined, keeping their handles; a subpath's last anchor removes the subpath; the path's only anchor is refused) (the result also has subpathRemoved:bool)"#.into(), delete_anchor, ), + spec( + "path.mergeShapeComponents", + "Merge Shape Components", + r#""tolerance":px=0.1 (bakes the components' path operations into plain combined outlines, traced from the exact coverage)"#.into(), + merge_components, + ), + spec( + "path.setOperation", + "Path Operation", + r#""subpaths":[i,…],"op":"combine|subtract|intersect|exclude" (the shape components holding these subpaths take the operation; the first component always combines and keeps its own; the Path Operations menu with components selected)"#.into(), + set_operation, + ), ] } #[cfg(test)] mod tests { - use photocraft_doc::{LayerId, ShapeLayer}; + use photocraft_doc::{LayerId, PathOp, ShapeLayer}; use serde_json::json; use crate::Session; @@ -413,6 +497,214 @@ mod tests { assert_eq!(s.active().unwrap().history.entries().len(), steps); } + /// Coverage of `path` at the pixel `(x, y)`. + fn covered(path: &photocraft_doc::Path, x: i32, y: i32) -> f32 { + photocraft_vector::fill_rasterizer(path, photocraft_vector::DEFAULT_TOLERANCE).render(photocraft_geom::Rect::from_xywh(x, y, 1, 1))[0] + } + + /// A 10..60 square with a front 25..45 square cut out of it (Subtract Front Shape), then + /// Merge Shape Components: plain combined outlines covering the same area, in one step. + #[test] + fn merge_shape_components_bakes_a_paths_operations() { + let mut s = session(); + s.execute("path.set", json!({"path": square()})).unwrap(); + let hole = json!({"subpaths": [{"closed": true, "knots": [[25, 25], [45, 25], [45, 45], [25, 45]]}]}); + s.execute("path.set", json!({"path": hole, "op": "subtract"})).unwrap(); + let before = work(&s); + let r = s.execute("path.mergeShapeComponents", json!({})).unwrap(); + assert_eq!(r["name"], json!("work")); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Merge Shape Components")); + let merged = work(&s); + assert_eq!(merged.subpaths.len(), 2, "the outline and its hole"); + for (x, y) in [(15, 15), (35, 35), (55, 50), (5, 5)] { + assert!((covered(&merged, x, y) - covered(&before, x, y)).abs() < 0.01, "({x}, {y})"); + } + assert_eq!((covered(&merged, 35, 35), covered(&merged, 15, 15)), (0.0, 1.0), "the hole stays a hole"); + assert!(s.undo()); + assert_eq!(work(&s), before); + // A saved path and a vector mask merge the same way; an inverted mask stays inverted. + s.execute("path.set", json!({"name": "Mug", "path": square()})).unwrap(); + s.execute("path.mergeShapeComponents", json!({"name": "Mug"})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.vectorMask.add", json!({"layer": id, "path": square()})).unwrap(); + s.execute("layer.vectorMask.edit", json!({"layer": id, "path": {"subpaths": square()["subpaths"], "inverted": true}})).unwrap(); + s.execute("path.mergeShapeComponents", json!({"name": "layer", "layer": id})).unwrap(); + let vm = s.active().unwrap().doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap(); + assert!(vm.path.inverted && !vm.path.subpaths.is_empty()); + } + + #[test] + fn merge_shape_components_on_a_shape_layer_rerenders_it() { + let mut s = session(); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 50, 50], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [25, 25, 20, 20], "addTo": id, "op": "subtract"})).unwrap(); + s.execute("path.mergeShapeComponents", json!({"name": "layer", "layer": id})).unwrap(); + let st = s.active().unwrap(); + let photocraft_doc::LayerContent::Shape(ShapeLayer { path, cache, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") }; + assert_eq!(covered(path, 35, 35), 0.0); + assert!(cache.is_some()); + } + + /// Mask components that cancel out (a square minus itself) cover nothing. Merged, the mask + /// must still hide (or, inverted, reveal) what it did, not turn into an empty revealing mask. + #[test] + fn merging_a_vector_mask_to_nothing_keeps_what_it_shows() { + for inverted in [false, true] { + let mut s = session(); + let id = s.active().unwrap().active_layer.unwrap().0; + let mut cancelled = square(); + cancelled["subpaths"].as_array_mut().unwrap().push(json!({"closed": true, "op": "subtract", "knots": [[10, 10], [60, 10], [60, 60], [10, 60]]})); + cancelled["inverted"] = json!(inverted); + s.execute("layer.vectorMask.add", json!({"layer": id, "path": cancelled})).unwrap(); + let mask = |s: &Session| s.active().unwrap().doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap(); + let shown = |s: &Session| photocraft_vector::vector_mask_values(&mask(s), photocraft_geom::Rect::from_xywh(0, 0, 120, 100)); + let before = shown(&s); + assert!(before.iter().all(|v| *v == if inverted { 1.0 } else { 0.0 }), "inverted {inverted}"); + s.execute("path.mergeShapeComponents", json!({"name": "layer", "layer": id})).unwrap(); + assert!(mask(&s).path.is_empty()); + assert_eq!(shown(&s), before, "inverted {inverted}"); + } + } + + /// A hole cut with Combine by mistake becomes a hole: the component takes Subtract Front Shape, + /// in one step, on the Work Path, a shape layer (re-rendered) and a vector mask alike. + #[test] + fn set_operation_changes_existing_components() { + let mut s = session(); + let hole = json!({"subpaths": [{"closed": true, "knots": [[25, 25], [45, 25], [45, 45], [25, 45]]}]}); + s.execute("path.set", json!({"path": square()})).unwrap(); + s.execute("path.set", json!({"path": hole, "op": "combine"})).unwrap(); + assert_eq!(covered(&work(&s), 35, 35), 1.0); + s.execute("path.setOperation", json!({"subpaths": [1], "op": "subtract"})).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Path Operation")); + assert_eq!(covered(&work(&s), 35, 35), 0.0); + assert_eq!(work(&s).subpaths[1].op, PathOp::Subtract); + assert!(s.undo()); + assert_eq!(work(&s).subpaths[1].op, PathOp::Combine); + + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 50, 50], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [25, 25, 20, 20], "addTo": id, "op": "combine"})).unwrap(); + s.execute("path.setOperation", json!({"name": "layer", "layer": id, "subpaths": [1], "op": "subtract"})).unwrap(); + let st = s.active().unwrap(); + let photocraft_doc::LayerContent::Shape(ShapeLayer { path, cache, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") }; + assert_eq!(covered(path, 35, 35), 0.0); + assert!(cache.is_some()); + } + + /// A component's operation is its first subpath's: naming a joined subpath changes the head, + /// and the joined subpaths stay joined. + #[test] + fn set_operation_on_a_joined_subpath_changes_its_component() { + let mut s = session(); + let mut p = square(); + let subs = p["subpaths"].as_array_mut().unwrap(); + subs.push(json!({"closed": true, "op": "combine", "knots": [[70, 10], [110, 10], [110, 50], [70, 50]]})); + subs.push(json!({"closed": true, "op": "join", "knots": [[80, 20], [80, 40], [100, 40], [100, 20]]})); + s.execute("path.set", json!({"path": p})).unwrap(); + s.execute("path.setOperation", json!({"subpaths": [2], "op": "exclude"})).unwrap(); + let ops: Vec<_> = work(&s).subpaths.iter().map(|sp| sp.op).collect(); + assert_eq!(ops, [PathOp::Combine, PathOp::Exclude, PathOp::Join]); + } + + /// The first component always draws as Combine: naming it with others changes only the + /// others, and naming only it is refused without a History step (feedback on #7648). + #[test] + fn set_operation_leaves_the_first_component_combining() { + let mut s = session(); + let hole = json!({"subpaths": [{"closed": true, "knots": [[25, 25], [45, 25], [45, 45], [25, 45]]}]}); + s.execute("path.set", json!({"path": square()})).unwrap(); + s.execute("path.set", json!({"path": hole, "op": "combine"})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + let e = s.execute("path.setOperation", json!({"subpaths": [0], "op": "subtract"})).unwrap_err().to_string(); + assert!(e.contains("first component"), "{e}"); + assert_eq!(s.active().unwrap().history.entries().len(), steps); + s.execute("path.setOperation", json!({"subpaths": [0, 1], "op": "subtract"})).unwrap(); + let ops: Vec<_> = work(&s).subpaths.iter().map(|sp| sp.op).collect(); + assert_eq!(ops, [PathOp::Combine, PathOp::Subtract]); + assert_eq!((covered(&work(&s), 35, 35), covered(&work(&s), 15, 15)), (0.0, 1.0)); + } + + #[test] + fn bad_set_operation_params_change_nothing() { + let mut s = session(); + s.execute("path.set", json!({"path": square()})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + for (p, msg) in [ + (json!({"subpaths": [0]}), "`op`"), + (json!({"subpaths": [0], "op": "join"}), "`op`"), + (json!({"subpaths": [0], "op": 3}), "`op`"), + (json!({"op": "subtract"}), "`subpaths`"), + (json!({"subpaths": [], "op": "subtract"}), "`subpaths`"), + (json!({"subpaths": [-1], "op": "subtract"}), "index"), + (json!({"subpaths": [7], "op": "subtract"}), "no subpath 7"), + (json!({"subpaths": [0], "op": "subtract", "name": "Nope"}), ""), + (json!({"subpaths": [0], "op": "subtract", "name": "layer", "layer": "x"}), "`layer`"), + ] { + let e = s.execute("path.setOperation", p.clone()).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } + assert_eq!(s.active().unwrap().history.entries().len(), steps); + assert_eq!(work(&s).subpaths[0].op, PathOp::Combine); + } + + /// Rejected merges name the problem and leave every path as it was, including the one a + /// malformed target would otherwise have fallen back to (the Work Path, the active layer). + #[test] + fn bad_merge_params_change_nothing() { + let mut s = session(); + s.execute("path.set", json!({"path": square()})).unwrap(); + let hole = json!({"subpaths": [{"closed": true, "knots": [[25, 25], [45, 25], [45, 45], [25, 45]]}]}); + s.execute("path.set", json!({"path": hole, "op": "subtract"})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.vectorMask.add", json!({"layer": id, "path": square()})).unwrap(); + let state = |s: &Session| { + let d = s.active().unwrap(); + (d.doc.work_path.clone(), d.doc.paths.clone(), d.doc.layer(LayerId(id)).unwrap().vector_mask.clone(), d.history.entries().len()) + }; + let before = state(&s); + for (p, msg) in [ + (json!({"tolerance": "fine"}), "tolerance"), + (json!({"name": 5}), "`name`"), + (json!({"name": "nope"}), "no path named"), + (json!({"name": "layer", "layer": "x"}), "`layer`"), + (json!({"name": "layer", "layer": 999}), "999"), + ] { + let e = s.execute("path.mergeShapeComponents", p.clone()).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + assert!(state(&s) == before, "{p}: nothing changed"); + } + } + + /// Tracing an open subpath's fill would close it, or drop a straight one or a lone + /// anchor (a dot under a round or square cap) entirely: the merge + /// is refused and the path, its stroked layer and the history stay as they were. + #[test] + fn merge_refuses_open_subpaths() { + for open in [json!({"closed": false, "knots": [[10, 10], [60, 60]]}), json!({"closed": false, "knots": [[70, 70]]})] { + let mut s = session(); + let mut mixed = square(); + mixed["subpaths"].as_array_mut().unwrap().push(open); + s.execute("path.set", json!({"path": mixed})).unwrap(); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 50, 50]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("shape.edit", json!({"layer": id, "path": mixed})).unwrap(); + let state = |s: &Session| { + let d = s.active().unwrap(); + let photocraft_doc::LayerContent::Shape(sh) = &d.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") }; + (d.doc.work_path.clone(), sh.path.clone(), d.history.entries().len()) + }; + let before = state(&s); + for (cmd, p) in [ + ("path.mergeShapeComponents", json!({})), + ("path.mergeShapeComponents", json!({"name": "layer", "layer": id})), + ("layer.combineShapes.mergeShapeComponents", json!({"layer": id})), + ] { + let e = s.execute(cmd, p.clone()).unwrap_err().to_string(); + assert!(e.contains("open subpaths"), "{cmd} {p}: {e}"); + assert!(state(&s) == before, "{cmd} {p}: nothing changed"); + } + } + } + #[test] fn bad_params_fail_without_an_edit() { let mut s = session(); diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index 447e4c8dc7..51cb0281c0 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -25,17 +25,21 @@ pub struct PatternLibrary { /// Bumped when a pattern's pixels are replaced under the same id (an imported `.pat` whose /// id is already in the library), which its id, name and size don't show. pub pixels_rev: u64, + /// Saved patterns held as a small preview until used, by id: their full size. The preset + /// store reads the pixels ([`full`]); everything that paints goes through [`resolve`]. + pub stored: std::collections::HashMap, } impl Default for PatternLibrary { fn default() -> Self { - PatternLibrary { items: builtin(), pixels_rev: 0 } + PatternLibrary { items: builtin(), pixels_rev: 0, stored: Default::default() } } } impl PatternLibrary { /// Add `pat`, or replace the pattern with its id (marking the pixels changed). pub fn upsert(&mut self, pat: Pattern) { + self.stored.remove(&pat.id); match self.items.iter_mut().find(|q| q.id == pat.id) { Some(q) => { *q = pat; @@ -132,25 +136,59 @@ fn has_pattern(s: &Session) -> std::result::Result<(), String> { if s.patterns.items.is_empty() && s.active().is_none_or(|d| d.doc.patterns.is_empty()) { Err("no patterns".into()) } else { Ok(()) } } -/// Finds a pattern by id or name: the active document's first, then the library. An empty key -/// picks the first library pattern (Photoshop's default). -pub fn resolve(s: &Session, key: &str) -> Option { - if key.is_empty() { - // The Patterns panel's selection, else the first library pattern. - return crate::presets::patterns::current(s).or(s.patterns.items.first()).cloned(); +/// `p` with its full pixels: a saved pattern held as a preview is read from the preset store. +pub fn full(s: &Session, p: &Pattern) -> std::result::Result { + if !s.patterns.stored.contains_key(&p.id) { + return Ok(p.clone()); } - if let Some(d) = s.active() + let st = s.preset_store.as_ref().ok_or_else(|| format!("pattern \"{}\" is not loaded: no preset store", p.display_name()))?; + let mut f = st.load_pattern(&p.id).map_err(|e| format!("pattern \"{}\" could not be loaded: {e}", p.display_name()))?; + f.name = p.name.clone(); + Ok(f) +} + +/// The library pattern `key` names (the panel's selection or the first for an empty key). +fn library_pattern<'a>(s: &'a Session, key: &str) -> Option<&'a Pattern> { + if key.is_empty() { + return crate::presets::patterns::current(s).or(s.patterns.items.first()); + } + photocraft_doc::pattern::find(&s.patterns.items, key, key) +} + +/// The id of the pattern [`resolve`] finds, without reading a saved pattern's pixels: for checks +/// and lookups that don't paint. +pub fn resolve_id(s: &Session, key: &str) -> Option { + if !key.is_empty() + && let Some(d) = s.active() + && let Some(p) = photocraft_doc::pattern::find(&d.doc.patterns, key, key) + { + return Some(p.id.clone()); + } + library_pattern(s, key).map(|p| p.id.clone()) +} + +/// Finds a pattern by id or name: the active document's first, then the library. An empty key +/// picks the first library pattern (Photoshop's default). `None` also when a saved pattern's +/// pixels can't be read (see [`resolve_param`] for the reason). +pub fn resolve(s: &Session, key: &str) -> Option { + if !key.is_empty() + && let Some(d) = s.active() && let Some(p) = photocraft_doc::pattern::find(&d.doc.patterns, key, key) { return Some(p.clone()); } - photocraft_doc::pattern::find(&s.patterns.items, key, key).cloned() + full(s, library_pattern(s, key)?).ok() } pub(crate) fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result { let key = p.get("pattern").and_then(Value::as_str).unwrap_or(""); - let pat = resolve(s, key).ok_or_else(|| bad(cmd, format!("no pattern \"{key}\" (see pattern.list)")))?; - paintable(cmd, pat) + if let Some(pat) = resolve(s, key) { + return paintable(cmd, pat); + } + match library_pattern(s, key).map(|lp| full(s, lp)) { + Some(Err(e)) => Err(bad(cmd, e)), + _ => Err(bad(cmd, format!("no pattern \"{key}\" (see pattern.list)"))), + } } /// `pat`, or the reason it would paint nothing: a pattern too large for the compositor renders as @@ -185,10 +223,10 @@ pub fn resolve_effect(s: &Session, fx: photocraft_doc::Effect) -> Result<(photoc } } -fn info(p: &Pattern, in_doc: bool, in_library: bool) -> Value { +fn info(p: &Pattern, size: (u32, u32), in_doc: bool, in_library: bool) -> Value { let f = p.surface.format(); json!({ - "id": p.id, "name": p.display_name(), "storedName": p.name, "width": p.width, "height": p.height, + "id": p.id, "name": p.display_name(), "storedName": p.name, "width": size.0, "height": size.1, "mode": format!("{:?}", f.mode), "depth": format!("{:?}", f.sample), "alpha": f.alpha, "inDocument": in_doc, "inLibrary": in_library, "paintable": p.is_paintable(), "paintProblem": p.paint_problem(), @@ -197,8 +235,9 @@ fn info(p: &Pattern, in_doc: bool, in_library: bool) -> Value { fn list(s: &mut Session, _: &Value) -> Result { let doc_pats: Vec = s.active().map(|d| d.doc.patterns.clone()).unwrap_or_default(); - let mut out: Vec = s.patterns.items.iter().map(|p| info(p, doc_pats.iter().any(|d| d.id == p.id), true)).collect(); - out.extend(doc_pats.iter().filter(|d| !s.patterns.items.iter().any(|p| p.id == d.id)).map(|p| info(p, true, false))); + let size = |p: &Pattern| s.patterns.stored.get(&p.id).copied().unwrap_or((p.width, p.height)); + let mut out: Vec = s.patterns.items.iter().map(|p| info(p, size(p), doc_pats.iter().any(|d| d.id == p.id), true)).collect(); + out.extend(doc_pats.iter().filter(|d| !s.patterns.items.iter().any(|p| p.id == d.id)).map(|p| info(p, (p.width, p.height), true, false))); Ok(Value::Array(out)) } @@ -299,7 +338,7 @@ fn define(s: &mut Session, p: &Value) -> Result { }; let pat = Pattern::new(name, surf, r.width(), r.height()); let id = pat.id.clone(); - let out = info(&pat, false, true); + let out = info(&pat, (pat.width, pat.height), false, true); if !s.patterns.items.iter().any(|q| q.id == id) { s.patterns.items.push(pat); } @@ -334,6 +373,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { fn delete(s: &mut Session, p: &Value) -> Result { let i = library_index(s, "pattern.delete", p)?; let pat = s.patterns.items.remove(i); + s.patterns.stored.remove(&pat.id); Ok(json!({"deleted": pat.id})) } @@ -349,6 +389,7 @@ fn import(s: &mut Session, p: &Value) -> Result { let mut ids = Vec::new(); for pat in pats { ids.push(pat.id.clone()); + s.patterns.stored.remove(&pat.id); s.patterns.upsert(pat); } Ok(json!({"imported": ids, "count": ids.len()})) @@ -361,7 +402,7 @@ fn export(s: &mut Session, p: &Value) -> Result { Some(keys) => { keys.iter().filter_map(Value::as_str).map(|k| resolve(s, k).ok_or_else(|| bad(cmd, format!("no pattern \"{k}\"")))).collect::>()? } - None => s.patterns.items.clone(), + None => s.patterns.items.iter().map(|p| full(s, p).map_err(|e| bad(cmd, e))).collect::>()?, }; let bytes = photocraft_io::pattern_map::write_pat(&pats).map_err(EngineError::Other)?; crate::file_cmds::write_file(path, &bytes)?; diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index db8af142be..55a637d5cb 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds.rs @@ -69,9 +69,12 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result { doc.layers = stack; let n = fmt.channels(); data = vec![0.0f32; buf.px.len() * n]; - for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) { - from_rgba_into(&fmt, *p, out); - } + // Separate CMYK through the document's profile, the one the render read it with. + photocraft_color::convert::with_cmyk_space(photocraft_compose::cmyk_space(doc).as_ref(), || { + for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) { + from_rgba_into(&fmt, *p, out); + } + }); } let mut px = Surface::new(fmt); if !area.is_empty() { diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index 4499715307..06b5bd17e7 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -21,7 +21,7 @@ const STREAM_PHASE_Y: u64 = 102; pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> { has_pixel_layer(s)?; - if crate::pattern_cmds::resolve(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) } + if crate::pattern_cmds::resolve_id(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) } } /// A parsed `paint.patternStamp`: shared by the command and its live preview, so both paint the diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index 30425d04b4..cd6dd27dab 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -102,6 +102,10 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { fn has_smart_filters(s: &Session) -> std::result::Result<(), String> { if active_smart(s)?.smart_filters.is_empty() { Err("the smart object has no smart filters".into()) } else { Ok(()) } } +/// Delete Filter Mask with `ifPresent` needs only a smart object. +pub(crate) fn smart_layer_active(s: &Session) -> std::result::Result<(), String> { + active_smart(s).map(|_| ()) +} fn has_filter_mask(s: &Session) -> std::result::Result<(), String> { active_smart(s)?.filter_mask.as_ref().map(|_| ()).ok_or_else(|| "the smart object has no filter mask".into()) } @@ -265,12 +269,25 @@ pub fn specs() -> Vec { }) } ), - spec!("layer.smartFilter.deleteFilterMask", "Delete Filter Mask", SF, r##"{"layer":id?}"##, has_filter_mask, |s, p| { - edit_filters(s, p, "Delete Filter Mask", |sm| { - sm.filter_mask = None; - Ok(()) - }) - }), + spec!( + "layer.smartFilter.deleteFilterMask", + "Delete Filter Mask", + SF, + r##"{"layer":id?,"ifPresent":bool=false (true: a smart object without a filter mask is left as it is, as a Photoshop action's step needs where Photoshop added the mask by default)}"##, + has_filter_mask, + |s, p| { + if p.get("ifPresent").and_then(Value::as_bool) == Some(true) { + let id = layer_param(s, p)?; + if smart(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?.filter_mask.is_none() { + return Ok(Value::Null); + } + } + edit_filters(s, p, "Delete Filter Mask", |sm| { + sm.filter_mask = None; + Ok(()) + }) + } + ), spec!( "layer.smartFilter.disableFilterMask", "Disable Filter Mask", diff --git a/crates/engine/src/cmd/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs index f024c72783..d2b426233f 100644 --- a/crates/engine/src/cmd/smart_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_cmds/tests.rs @@ -421,6 +421,13 @@ fn selection_becomes_the_filter_mask() { s.execute("layer.smartFilter.deleteFilterMask", json!({})).unwrap(); assert!(active_smart(&s).filter_mask.is_none()); assert!(!s.is_enabled("layer.smartFilter.deleteFilterMask")); + // A Photoshop action deletes the mask Photoshop adds by default: with `ifPresent`, no mask + // is no step and no error. A layer that isn't a smart object still refuses. + let steps = s.active().unwrap().history.past_len(); + assert_eq!(s.execute("layer.smartFilter.deleteFilterMask", json!({"ifPresent": true})).unwrap(), Value::Null); + assert_eq!(s.active().unwrap().history.past_len(), steps); + s.execute("layer.new.layer", json!({})).unwrap(); + assert!(s.execute("layer.smartFilter.deleteFilterMask", json!({"ifPresent": true})).is_err()); } /// #5619: deleting (or dragging away) the last smart filter removes the filter mask with it, so diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs index b8beea5a80..c04df742a8 100644 --- a/crates/engine/src/cmd/smartselect_cmds.rs +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -303,7 +303,8 @@ impl SubjectCache { } fn select_subject(s: &mut Session, p: &Value) -> Result { - let all_layers = b(p, "sampleAllLayers", true); + // The selected layer's pixels; the composite only when no pixel layer is selected. + let all_layers = b(p, "sampleAllLayers", false); let d = s.active().ok_or(EngineError::NoDocument)?; // What `with_doc_sampler` samples: the active layer's pixels, else the composite. let target = d.active_layer.filter(|id| !all_layers && d.doc.layer(*id).and_then(Layer::surface).is_some()); @@ -543,7 +544,7 @@ pub fn specs() -> Vec { "select.subject", "Subject", ["Select"], - r##"{"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, + r##"{"sampleAllLayers":bool=false,"mode":"replace|add|subtract|intersect"="replace"} (samples the selected layer; the composite when no pixel layer is selected)"##, has_doc, select_subject ), diff --git a/crates/engine/src/cmd/smartselect_cmds/tests.rs b/crates/engine/src/cmd/smartselect_cmds/tests.rs index 8cb19565b5..eca3d3aa7f 100644 --- a/crates/engine/src/cmd/smartselect_cmds/tests.rs +++ b/crates/engine/src/cmd/smartselect_cmds/tests.rs @@ -251,6 +251,23 @@ fn select_subject_centred_object() { assert!(s.active().unwrap().doc.selection.is_none()); } +/// Select Subject looks at the selected layer only; with no layer selected it looks at the +/// whole image. +#[test] +fn select_subject_samples_the_selected_layer_else_the_composite() { + let (mut s, inside) = disc(8); + // A layer above holding only a small square in the corner: the disc is not on it. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("paint.pencil", json!({"points": [[10, 10], [30, 10]], "size": 3, "color": "#000000"})).unwrap(); + s.execute("select.subject", json!({})).unwrap(); + assert!(cov(&s, 100, 80) < 0.5, "the disc on the layer below was selected"); + s.execute("select.deselect", json!({})).unwrap(); + // No layer selected: the whole image, so the disc is found. + s.execute("select.deselectLayers", json!({})).unwrap(); + s.execute("select.subject", json!({})).unwrap(); + assert!(sel_iou(&s, 200, 160, &inside) > 0.9); +} + /// #2865: a repeat on unchanged pixels reuses the last mask (an identical selection, even /// after Deselect); sampling something else or a pixel edit computes it again. #[test] @@ -268,8 +285,8 @@ fn select_subject_repeat_reuses_the_mask_until_pixels_change() { s.execute("select.subject", json!({})).unwrap(); assert!(std::sync::Arc::ptr_eq(&mask, &cached(&s)), "the repeat recomputed the mask"); assert_eq!(sel(&s), first); - // Another sampled target (the layer rather than the composite) is a miss. - s.execute("select.subject", json!({"sampleAllLayers": false})).unwrap(); + // Another sampled target (the composite rather than the layer) is a miss. + s.execute("select.subject", json!({"sampleAllLayers": true})).unwrap(); assert!(!std::sync::Arc::ptr_eq(&mask, &cached(&s))); // A pixel edit drops the entry; the next run recomputes it. s.edit("paint", |doc, _| { @@ -434,8 +451,9 @@ fn refine_edge_outputs_to_a_new_document() { #[test] fn refine_edge_shift_and_contrast() { let mut s = blurred_edge_selected(); + // A hard selection moves 1 px at 100%: no band of several pixels. s.execute("select.refineEdge", json!({"shiftEdge": 100})).unwrap(); - assert!(cov(&s, 42, 20) > 0.99); + assert!(cov(&s, 40, 20) > 0.99 && cov(&s, 41, 20) < 0.01); s.execute("edit.undo", json!({})).unwrap(); s.execute("select.refineEdge", json!({"feather": 8, "contrast": 100})).unwrap(); assert!(cov(&s, 38, 20) == 1.0 && cov(&s, 42, 20) == 0.0); @@ -644,7 +662,7 @@ fn refine_edge_edits_match_the_tools_and_reach_the_outputs() { let mut s = two_regions(8); s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); s.execute("select.refineEdge", json!({"shiftEdge": -100, "edits": [{"tool": "brush", "points": [[30, 80], [100, 80]], "size": 20}]})).unwrap(); - assert!(cov(&s, 60, 80) >= 0.5 && cov(&s, 60, 88) < 0.5 && cov(&s, 60, 72) < 0.5, "the 20 px bar shrank"); + assert!(cov(&s, 60, 80) >= 0.5 && cov(&s, 60, 89) < 0.5 && cov(&s, 60, 70) < 0.5, "the hard 20 px bar shrank by one pixel at -100% Shift Edge"); // Layer mask and new-layer outputs take the edited selection. let mut s = blurred_edge_selected(); let r = s.execute("select.refineEdge", json!({"output": "layerMask", "edits": [{"tool": "invert"}]})).unwrap(); diff --git a/crates/engine/src/cmd/type_styles_cmds.rs b/crates/engine/src/cmd/type_styles_cmds.rs index 4cbb2092dc..7fc58a5ec4 100644 --- a/crates/engine/src/cmd/type_styles_cmds.rs +++ b/crates/engine/src/cmd/type_styles_cmds.rs @@ -111,6 +111,7 @@ fn perturbed_char() -> CharStyle { features: vec![FontFeature { tag: "\u{1}".into(), value: 9 }], variations: vec![FontVariation { axis: "\u{1}".into(), value: -1.0 }], language: Some("\u{1}".into()), + rotate_roman: true, style_sheet: None, } } diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 5a53d5ae07..efbff863fd 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -69,7 +69,7 @@ mod paths; mod shape; mod vector_mask; -pub(crate) use params::{layer_id, nums, pt}; +pub(crate) use params::{layer_id, nums, op_from, pt}; pub use params::{parse_path, parse_stroke, path_json}; pub use paths::STROKE_PATH_TOOLS; use paths::{ @@ -77,11 +77,11 @@ use paths::{ resolve_path, select_to_work_path, }; pub(crate) use paths::{is_work, path_mut}; +pub(crate) use shape::{bake_path, map_path, map_shape, shift_shape, with_shape}; use shape::{ can_paste_shape_fill, can_paste_shape_stroke, combine_shapes, copy_shape_fill, copy_shape_stroke, has_shape_fill, has_shape_stroke, merge_components, paste_shape_fill, paste_shape_stroke, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize, }; -pub(crate) use shape::{map_path, map_shape, shift_shape, with_shape}; pub use shape::{preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors}; use vector_mask::{toggle_vector_mask, vector_mask_add, vector_mask_delete, vector_mask_edit, vector_mask_info, vector_mask_rasterize, with}; diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index 6deb13186a..00f28c5937 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -72,7 +72,7 @@ fn hex(c: &Color) -> String { if c.alpha < 1.0 { format!("#{:02x}{:02x}{:02x}{:02x}", q(r), q(g), q(b), q(c.alpha)) } else { format!("#{:02x}{:02x}{:02x}", q(r), q(g), q(b)) } } -pub(super) fn op_from(s: &str) -> Option { +pub(crate) fn op_from(s: &str) -> Option { Some(match s.to_ascii_lowercase().as_str() { "combine" | "add" | "union" => PathOp::Combine, "subtract" | "minus" => PathOp::Subtract, diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index 167cb9d2a6..3fe1b7461f 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -79,26 +79,32 @@ pub(super) fn path_set(s: &mut Session, p: &Value) -> Result { let name = p.get("name").and_then(Value::as_str).map(str::to_string); let append = p.get("op").and_then(Value::as_str).map(|o| op_from(o).ok_or_else(|| bad(CMD, format!("unknown op `{o}`")))).transpose()?; s.edit(if is_work(name.as_deref()) { "Work Path" } else { "Save Path" }, |doc, _| { - let merge = |old: Option<&Path>, new: Path| match (old, append) { - (Some(o), Some(op)) => { - let mut o = o.clone(); - o.subpaths.extend(new.subpaths.into_iter().map(|mut sp| { - sp.op = op; - sp - })); - o - } - _ => new, + let merge = |old: Option<&Path>, new: Path| -> Result { + let merged = match (old, append) { + (Some(o), Some(op)) => { + let mut o = o.clone(); + o.subpaths.extend(new.subpaths.into_iter().map(|mut sp| { + sp.op = op; + sp + })); + o + } + _ => new, + }; + // Appending small Pen components must not bypass the complete path's bounds and + // tessellation budget. Validate before changing the document or its history. + vector::flatten::validate_path(&merged).map_err(|e| bad(CMD, e))?; + Ok(merged) }; if is_work(name.as_deref()) { - doc.work_path = Some(merge(doc.work_path.as_ref(), path)); + doc.work_path = Some(merge(doc.work_path.as_ref(), path)?); } else { let n = name.clone().unwrap_or_default(); match doc.paths.iter_mut().find(|q| q.name == n) { Some(q) => { - q.path = merge(Some(&q.path), path); + q.path = merge(Some(&q.path), path)?; } - None => doc.paths.push(NamedPath { name: n, path, psd_raw: None }), + None => doc.paths.push(NamedPath { name: n, path: merge(None, path)?, psd_raw: None }), } } Ok(()) diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 789fd8f40b..961e767924 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -443,13 +443,27 @@ pub(super) fn merge_components(s: &mut Session, p: &Value) -> Result { /// Bakes `sh`'s path operations into plain combined outlines, traced from the exact coverage. fn bake_components(sh: &mut ShapeLayer, tol: f64) -> Result<()> { + sh.path = bake_path(&sh.path, tol)?; + sh.live = None; + sh.psd_raw = None; + Ok(()) +} + +/// `path` with its path operations baked into plain combined outlines, traced from the exact +/// coverage within `tol` px (Merge Shape Components). An empty area gives an empty path; an +/// inverted path (a vector mask's) stays inverted around the merged area. An open subpath is +/// refused: tracing its fill would close it, or drop a straight one or a lone anchor (a dot under +/// a round or square cap), losing the stroked geometry. +pub(crate) fn bake_path(path: &Path, tol: f64) -> Result { + if path.subpaths.iter().any(|sp| !sp.closed && !sp.knots.is_empty()) { + return Err(EngineError::Other("Merge Shape Components needs closed paths: close or delete the open subpaths first".into())); + } // Trace at 4× resolution so the fitted outline follows the anti-aliased edge closely. const K: f64 = 4.0; - let up = sh.path.transform(&Affine::scale(K)); + let up = Path { inverted: false, ..path.transform(&Affine::scale(K)) }; let r = vector::fill_rasterizer(&up, vector::DEFAULT_TOLERANCE); let Some(b) = r.pixel_bounds() else { - sh.path.subpaths.clear(); - return Ok(()); + return Ok(Path { subpaths: Vec::new(), ..path.clone() }); }; let b = b.inflate(2); if u64::from(b.width()) * u64::from(b.height()) > 400_000_000 { @@ -457,10 +471,7 @@ fn bake_components(sh: &mut ShapeLayer, tol: f64) -> Result<()> { } let cov = r.render(b); let traced = vector::trace::trace_mask(&cov, b, 0.0, tol * K); - sh.path = traced.transform(&Affine::scale(1.0 / K)); - sh.live = None; - sh.psd_raw = None; - Ok(()) + Ok(Path { inverted: path.inverted, ..traced.transform(&Affine::scale(1.0 / K)) }) } /// The shape layers Layer › Combine Shapes merges into one: with none of the `narrow` params diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 3aec55b837..edc6c7e59d 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -330,6 +330,29 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result 1 { + // A damaged or looping page chain, or one past the 10,000-directory limit, lists + // only its first pages: refuse it rather than silently import part of the file. + if !complete { + return Err(EngineError::Other(format!( + "`{}`: only the first {} pages could be read (its page list is damaged or too long), so not every page would be imported", + f.display(), + pages.len() + ))); + } + for page in pages { + let doc = photocraft_io::import_tiff_page(&name, &bytes, Some(page)) + .map_err(|e| EngineError::Other(format!("`{}` page {}: {e}", f.display(), page + 1)))? + .document; + frames.push(crate::file_cmds::flattened(&doc, fmt)); + } + continue; + } + } let mut doc = crate::file_cmds::import(&name, &bytes)?; // A Targa's alpha opens as a channel (as in Photoshop); a frame's alpha is transparency. if f.extension().is_some_and(|e| e.eq_ignore_ascii_case("tga")) { @@ -431,6 +454,15 @@ fn reload_frame(s: &mut Session, _p: &Value) -> Result { }) } +/// The pages of a TIFF that are pages of the document: full-resolution directories of the main +/// chain (not SubIFDs, thumbnails or masks), by index into [`photocraft_codecs::tiff_info`]'s +/// pages, and whether the walk listed every directory. Empty when the file can't be listed. +fn tiff_pages(bytes: &[u8]) -> (Vec, bool) { + let Ok(info) = photocraft_codecs::tiff_info(bytes) else { return (Vec::new(), true) }; + let pages = info.pages.iter().enumerate().filter(|(_, p)| p.parent.is_none() && p.kind == photocraft_codecs::TiffPageKind::Page).map(|(i, _)| i).collect(); + (pages, info.complete) +} + /// Import › Video Frames to Layers: load frames from a file/sequence and add each as its own layer. fn frames_to_layers(s: &mut Session, p: &Value) -> Result { let path = p diff --git a/crates/engine/src/cmd/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs index 7e8c05a9b4..66566bdb7d 100644 --- a/crates/engine/src/cmd/video_cmds/tests.rs +++ b/crates/engine/src/cmd/video_cmds/tests.rs @@ -69,6 +69,82 @@ fn tmpdir(name: &str) -> String { d.to_string_lossy().into_owned() } +/// A classic little-endian TIFF with one 8-bit gray page per `(w, h, level, NewSubfileType)`, +/// chained in order (NewSubfileType 1 marks a reduced-resolution copy, such as a thumbnail). +fn write_tiff(path: &str, pages: &[(u32, u32, u8, u32)]) { + let mut f = b"II".to_vec(); + f.extend_from_slice(&42u16.to_le_bytes()); + f.extend_from_slice(&0u32.to_le_bytes()); + let mut next_field = 4; + for &(w, h, level, kind) in pages { + let pixels_at = f.len() as u32; + f.extend(std::iter::repeat_n(level, (w * h) as usize)); + if f.len() % 2 == 1 { + f.push(0); + } + let ifd_at = f.len() as u32; + f[next_field..next_field + 4].copy_from_slice(&ifd_at.to_le_bytes()); + let entries: [(u16, u16, u32); 10] = + [(254, 4, kind), (256, 4, w), (257, 4, h), (258, 3, 8), (259, 3, 1), (262, 3, 1), (273, 4, pixels_at), (277, 3, 1), (278, 4, h), (279, 4, w * h)]; + f.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, ty, v) in entries { + f.extend_from_slice(&tag.to_le_bytes()); + f.extend_from_slice(&ty.to_le_bytes()); + f.extend_from_slice(&1u32.to_le_bytes()); + f.extend_from_slice(&v.to_le_bytes()); + } + next_field = f.len(); + f.extend_from_slice(&0u32.to_le_bytes()); + } + std::fs::write(path, f).unwrap(); +} + +/// #6379: Video Frames to Layers takes every page of a multi-page TIFF, one layer each, in +/// order, as it takes a GIF's frames; a thumbnail is not a page. A single-page TIFF is one frame. +#[test] +fn video_frames_to_layers_takes_every_tiff_page() { + let dir = tmpdir("tiff-pages"); + let path = format!("{dir}/pages.tif"); + write_tiff(&path, &[(2, 2, 9, 1), (6, 4, 51, 0), (3, 5, 204, 0)]); + let mut s = session(); + let r = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap(); + assert_eq!(r["layers"], 2, "two pages, the thumbnail left out"); + let doc = &s.active().unwrap().doc; + for (name, (w, h), level) in [("Frame 1", (6, 4), 51.0), ("Frame 2", (3, 5), 204.0)] { + let l = doc.layers.iter().find(|l| l.name == name).unwrap_or_else(|| panic!("{name}")); + let surf = l.surface().unwrap(); + let b = surf.content_bounds(); + assert_eq!((b.width(), b.height()), (w, h), "{name}"); + let px = surf.read_region(photocraft_geom::Rect::new(b.x0, b.y0, b.x0 + 1, b.y0 + 1)); + assert!((px[0] * 255.0 - level).abs() < 0.6 && px[3] == 1.0, "{name}: {px:?}"); + } + let single = format!("{dir}/single.tif"); + write_tiff(&single, &[(4, 4, 120, 0)]); + let mut s = session(); + assert_eq!(s.execute("file.import.videoFramesToLayers", json!({"path": single})).unwrap()["layers"], 1); +} + +/// #6379 review: a TIFF whose page chain loops back (or is cut short, or runs past the directory +/// limit) lists only its first pages. The import is refused, and the document is left as it was, +/// instead of reporting part of the file as all of it. +#[test] +fn video_frames_to_layers_refuses_a_tiff_with_an_incomplete_page_list() { + let dir = tmpdir("tiff-loop"); + let path = format!("{dir}/loop.tif"); + write_tiff(&path, &[(2, 2, 51, 0), (2, 2, 204, 0)]); + // The last directory's next-IFD offset points back to the first directory. + let mut f = std::fs::read(&path).unwrap(); + let first: [u8; 4] = f[4..8].try_into().unwrap(); + let end = f.len(); + f[end - 4..].copy_from_slice(&first); + std::fs::write(&path, f).unwrap(); + let mut s = session(); + let before = s.active().unwrap().doc.layers.len(); + let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err().to_string(); + assert!(err.contains("only the first 2 pages"), "{err}"); + assert_eq!(s.active().unwrap().doc.layers.len(), before, "nothing imported"); +} + #[test] fn new_video_layer_from_image_sequence() { let dir = tmpdir("seq"); diff --git a/crates/engine/src/cmd/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs index aa8f63dd04..46fe609d16 100644 --- a/crates/engine/src/cmd/web_cmds/save_web.rs +++ b/crates/engine/src/cmd/web_cmds/save_web.rs @@ -182,7 +182,10 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u let (wdoc, sx, sy) = web_document(&doc, p, &st)?; let buf = photocraft_compose::flatten(&wdoc); let bw = wdoc.size.width as usize; - let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()); + // An untagged document is treated as sRGB (see [`web_document`]); with Embed Color Profile + // on, the file says so, as Photoshop's does (#9325). + let srgb = (st.embed_icc && wdoc.icc_profile.is_none()).then(|| photocraft_cms::Builtin::Srgb.profile().to_bytes().to_vec()); + let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()).or(srgb.as_deref()); let xmp = web_xmp(&doc, st.metadata); let exif = web_exif(&doc, st.metadata); let dpi = wdoc.resolution_dpi; diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index 04a74da722..590ea0d7ad 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -1299,3 +1299,21 @@ fn quick_export_exr_preserves_linear_hdr_and_alpha() { s.execute("file.export.quickExport", json!({"path": format!("{dir}/explicit.exr")})).unwrap(); assert_eq!(decode(&format!("{dir}/explicit.exr")).dimensions(), (2, 1)); } + +/// #9325: an untagged document is treated as sRGB, and with Embed Color Profile on the file +/// says so, as Photoshop's Save for Web does; off, it still carries none. +#[test] +fn embed_color_profile_tags_an_untagged_document_srgb() { + let mut s = session(8); + assert!(s.active().unwrap().doc.icc_profile.is_none(), "a new document is untagged"); + let dir = tmp("assumed-icc"); + let profile = |path: &str| decode(path).icc.map(|b| photocraft_cms::Profile::parse(&b).unwrap().description); + for (format, ext) in [("jpeg", "jpg"), ("png24", "png")] { + let on = format!("{dir}/on.{ext}"); + s.execute("file.export.saveForWebLegacy", json!({"format": format, "embedIcc": true, "path": on})).unwrap(); + assert_eq!(profile(&on).as_deref(), Some(photocraft_cms::Builtin::Srgb.description()), "{format}"); + let off = format!("{dir}/off.{ext}"); + s.execute("file.export.saveForWebLegacy", json!({"format": format, "embedIcc": false, "path": off})).unwrap(); + assert_eq!(profile(&off), None, "{format}"); + } +} diff --git a/crates/engine/src/command_hints.rs b/crates/engine/src/command_hints.rs new file mode 100644 index 0000000000..2cc210ea25 --- /dev/null +++ b/crates/engine/src/command_hints.rs @@ -0,0 +1,144 @@ +//! "Did you mean …?" hints for unknown command ids and protocol method names (#3674), so an agent +//! that guesses a name gets something to correct from instead of re-listing the whole registry. +//! Only computed on the error path; the registry is small enough to scan. + +use crate::commands; + +/// Names that are documented elsewhere and can't be found by spelling alone: a protocol method +/// mistaken for the engine command that does the same thing. +const ALIASES: &[(&str, &str)] = &[("engine.commands", "command.list"), ("document.undo", "edit.undo"), ("document.redo", "edit.redo")]; + +/// At most this many suggestions per error. +const MAX_SUGGESTIONS: usize = 3; + +/// Up to [`MAX_SUGGESTIONS`] `candidates` close to `name`, best first: a different case or a few +/// typos (edit distance), then names that `name` is the start of (`filter.blur.gaussian`), the +/// same last segment in another namespace (`document.undo` → `edit.undo`), and the same namespace +/// with a longer last segment (`image.size` → `image.imageSize`). Deterministic: within a tier +/// the closest spelling wins, then the name. +pub fn near_matches<'a>(name: &str, candidates: impl IntoIterator) -> Vec<&'a str> { + let lower = name.to_lowercase(); + let max = (lower.chars().count() / 4).clamp(1, 4); + let dotted = lower.split_once('.'); + let tail = |s: &str| s.rsplit('.').next().map(str::to_owned).unwrap_or_default(); + let name_tail = tail(&lower); + let long_tail = name_tail.chars().count() >= 3; + let mut scored: Vec<(usize, usize, &'a str)> = candidates + .into_iter() + .filter(|c| *c != name) + .filter_map(|c| { + let cl = c.to_lowercase(); + if let Some(d) = photocraft_text::spell::edit_distance(&lower, &cl, max) { + return Some((0, d, c)); + } + let (namespace, _) = dotted?; + let cl_tail = tail(&cl); + let tier = if cl.starts_with(&lower) { + 1 + } else if long_tail && cl_tail == name_tail { + 2 + } else if long_tail && cl.split_once('.').is_some_and(|(ns, _)| ns == namespace) && cl_tail.contains(&name_tail) { + 3 + } else { + return None; + }; + Some((tier, photocraft_text::spell::edit_distance(&lower, &cl, 64).unwrap_or(usize::MAX), c)) + }) + .collect(); + scored.sort_unstable(); + scored.dedup(); + scored.into_iter().take(MAX_SUGGESTIONS).map(|(.., c)| c).collect() +} + +/// `"; did you mean `a`?"` / `"; did you mean `a`, `b` or `c`?"`, or `""` for no suggestions. +pub fn did_you_mean(names: &[&str]) -> String { + let quoted: Vec = names.iter().map(|n| format!("`{n}`")).collect(); + match quoted.split_last() { + None => String::new(), + Some((last, [])) => format!("; did you mean {last}?"), + Some((last, rest)) => format!("; did you mean {} or {last}?", rest.join(", ")), + } +} + +/// The hint appended to "unknown command `id`": registered ids close to `id`, or `""`. +pub fn unknown_command_hint(id: &str) -> String { + let mut names: Vec<&str> = ALIASES.iter().filter(|(from, _)| *from == id).map(|(_, to)| *to).collect(); + for n in near_matches(id, commands::command_specs().iter().map(|s| s.id)) { + if names.len() < MAX_SUGGESTIONS && !names.contains(&n) { + names.push(n); + } + } + did_you_mean(&names) +} + +/// The error for `engine.execute` given `id`, a control-protocol method rather than an engine +/// command (shared by the headless server and the desktop control server). +pub fn protocol_method_as_command(id: &str) -> String { + format!("{}; `{id}` is a protocol method: send it as the request's method, not through engine.execute", crate::EngineError::UnknownCommand(id.into())) +} + +/// The error for an unknown protocol request `method`, given the server's `methods`: an engine +/// command id points at `engine.execute`, anything else gets the nearest method names. +pub fn unknown_method(method: &str, methods: &[&str]) -> String { + if commands::find(method).is_some() { + return format!("unknown method `{method}`; `{method}` is an engine command: run it with engine.execute {{\"command\": \"{method}\"}}"); + } + format!("unknown method `{method}`{}", did_you_mean(&near_matches(method, methods.iter().copied()))) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + use crate::{EngineError, Session}; + + fn unknown(id: &str) -> String { + EngineError::UnknownCommand(id.into()).to_string() + } + + #[test] + fn protocol_listing_method_points_at_command_list() { + assert_eq!(unknown("engine.commands"), "unknown command `engine.commands`; did you mean `command.list`?"); + let mut s = Session::new(); + let e = s.execute("engine.commands", json!({})).unwrap_err().to_string(); + assert!(e.contains("did you mean `command.list`"), "{e}"); + assert!(s.disabled_reason("engine.commands").unwrap().contains("`command.list`")); + } + + #[test] + fn near_misses_suggest_registered_ids() { + // Typo, case, and the same verb in another namespace. + assert!(unknown("edit.undoo").contains("did you mean `edit.undo`"), "{}", unknown("edit.undoo")); + assert!(unknown("Edit.Undo").contains("did you mean `edit.undo`"), "{}", unknown("Edit.Undo")); + let e = unknown("document.undo"); + assert!(e.contains("did you mean `edit.undo`"), "{e}"); + assert!(unknown("document.redo").contains("did you mean `edit.redo`")); + // A namespace prefix, a truncated id, a shorter last segment. + assert!(unknown("layer.new").contains("`layer.new.layer`"), "{}", unknown("layer.new")); + assert!(unknown("filter.blur.gaussian").contains("did you mean `filter.blur.gaussianBlur`")); + assert!(unknown("image.size").contains("did you mean `image.imageSize`"), "{}", unknown("image.size")); + assert!(e.len() < 200, "a few suggestions, not a listing: {e}"); + // Nothing close: the plain error. + assert_eq!(unknown("zzzz.qqqq"), "unknown command `zzzz.qqqq`"); + assert_eq!(unknown(""), "unknown command ``"); + } + + #[test] + fn suggestions_are_capped_and_ordered() { + let c = ["a.bc", "a.bd", "a.be", "a.bf", "x.y"]; + assert_eq!(near_matches("a.bb", c), ["a.bc", "a.bd", "a.be"]); + assert_eq!(did_you_mean(&[]), ""); + assert_eq!(did_you_mean(&["a"]), "; did you mean `a`?"); + assert_eq!(did_you_mean(&["a", "b", "c"]), "; did you mean `a`, `b` or `c`?"); + } + + #[test] + fn protocol_method_hints() { + let methods = ["engine.execute", "doc.inspect", "doc.open", "methods"]; + assert_eq!(unknown_method("doc.inspct", &methods), "unknown method `doc.inspct`; did you mean `doc.inspect`?"); + assert!(unknown_method("edit.undo", &methods).contains("engine.execute {\"command\": \"edit.undo\"}")); + assert_eq!(unknown_method("zzzz", &methods), "unknown method `zzzz`"); + assert!(protocol_method_as_command("doc.inspect").contains("`doc.inspect` is a protocol method")); + } +} diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 635089f7a2..323d3f5203 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -1,8 +1,10 @@ use super::LayerId; +use crate::command_hints; #[derive(Debug, thiserror::Error)] pub enum EngineError { - #[error("unknown command `{0}`")] + /// Displays with the nearest registered ids, if any ([`command_hints`], #3674). + #[error("unknown command `{id}`{hint}", id = .0, hint = command_hints::unknown_command_hint(.0))] UnknownCommand(String), #[error("command `{0}` is not available right now: {1}")] Disabled(String, String), diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index 4d8db05213..ed709515ee 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -274,7 +274,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, Some(layer), &p)? { let content = doc_bounds.union(&surf.content_bounds()); let area = algo::output_area(&fp, content, bounds, sel_bounds); - *surf = filter(surf, &fp, area, bounds, selection.as_ref(), doc_bounds.union(&content))?; + *surf = filter(surf, &fp, area, bounds, selection.as_ref(), algo::separable::edge_extent(doc_bounds, content))?; return Ok(fp.clone()); } // Filters that make pixels transparent (Color to Alpha) turn the Background into a @@ -326,7 +326,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result let before = locks.transparency.then(|| surf.clone()); let content = surf.content_bounds(); let area = algo::output_area(&fp, content, bounds, sel_bounds); - *surf = filter(surf, &fp, area, bounds, selection.as_ref(), doc_bounds.union(&content))?; + *surf = filter(surf, &fp, area, bounds, selection.as_ref(), algo::separable::edge_extent(doc_bounds, content))?; if let Some(before) = &before { keep_alpha(before, surf, &|| ctx.cancelled())?; } diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 7a01d6786d..d5c8746062 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -955,6 +955,7 @@ impl Session { "layerComp.apply" => crate::comps_cmds::recorded_apply(self, params), _ => crate::layer_multi_cmds::recorded_step(self, id, params, pre_selected), }; + let params = crate::actions_cmds::recorded_params(self, id, params); self.journal.push((id.to_string(), params)); } } diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index e1a7f3755c..176f08b264 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -47,6 +47,9 @@ fn color_of(p: &Value, k: &str) -> Option { let h = |i: usize| s.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0); (s.len() >= 6).then_some(Color::rgb(h(0), h(2), h(4))) } + Some(v @ Value::Object(_)) => serde_json::from_value::(v.clone()) + .ok() + .filter(|c| c.c.iter().all(|v| v.is_finite()) && c.alpha.is_finite() && (0.0..=1.0).contains(&c.alpha)), _ => None, } } @@ -66,9 +69,16 @@ fn gradient_stops(p: &Value, from: Color, to: Color) -> Vec<(f32, Color)> { None => stops, } } +/// The gradient of a stroke or overlay's params. Bad `stops` are ignored here, as bad values of +/// any other key are; the commands refuse them first ([`check_gradient_params`]). fn gradient(p: &Value) -> Gradient { + let stops = match stops_param(p, "layer.layerStyle").ok().flatten() { + Some(stops) => stops, + None => gradient_stops(p, color(p, "from", [0.0; 3]), color(p, "to", [1.0; 3])), + }; Gradient { - stops: gradient_stops(p, color(p, "from", [0.0; 3]), color(p, "to", [1.0; 3])), + stops, + opacity_stops: opacity_stops_param(p, "layer.layerStyle").ok().flatten().unwrap_or_default(), style: gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")), angle: f(p, "angle", 90.0), scale: (f(p, "scale", 100.0) / 100.0).clamp(0.1, 1.5), @@ -77,6 +87,61 @@ fn gradient(p: &Value) -> Gradient { } } +/// `Err` when `stops` or `opacityStops` are present but malformed, so a command refuses them +/// instead of silently keeping the old gradient. +pub fn check_gradient_params(p: &Value, cmd: &str) -> Result<()> { + stops_param(p, cmd)?; + opacity_stops_param(p, cmd)?; + Ok(()) +} + +/// Most stops a gradient parameter may carry. +const MAX_STOPS: usize = 256; + +/// Explicit colour stops (#5177): `"stops": [[position 0..1, "#rrggbb" | [r, g, b]], …]`, at +/// least 2 and at most [`MAX_STOPS`], returned sorted by position. `None` without the key. +fn stops_param(p: &Value, cmd: &str) -> Result>> { + let Some(v) = p.get("stops") else { return Ok(None) }; + let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; + let a = v.as_array().ok_or_else(|| bad("\"stops\" must be an array of [position, colour]".into()))?; + if a.len() < 2 { + return Err(bad("\"stops\" needs at least 2 stops".into())); + } + if a.len() > MAX_STOPS { + return Err(bad(format!("\"stops\": at most {MAX_STOPS} stops"))); + } + let mut stops = Vec::with_capacity(a.len()); + for (i, s) in a.iter().enumerate() { + let t = s.get(0).and_then(Value::as_f64).filter(|t| t.is_finite()).ok_or_else(|| bad(format!("\"stops\"[{i}] must be [position 0..1, colour]")))?; + let c = s.get(1).and_then(|c| color_of(&json!({"c": c}), "c")).ok_or_else(|| bad(format!("\"stops\"[{i}]: no colour (\"#rrggbb\" or [r, g, b])")))?; + stops.push((t.clamp(0.0, 1.0) as f32, c)); + } + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + Ok(Some(stops)) +} + +/// Explicit transparency stops: `"opacityStops": [[position 0..1, opacity 0..100], …]`; an empty +/// array means fully opaque. `None` without the key. +fn opacity_stops_param(p: &Value, cmd: &str) -> Result>> { + let Some(v) = p.get("opacityStops") else { return Ok(None) }; + let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; + let a = v.as_array().ok_or_else(|| bad("\"opacityStops\" must be an array of [position, opacity]".into()))?; + if a.len() > MAX_STOPS { + return Err(bad(format!("\"opacityStops\": at most {MAX_STOPS} stops"))); + } + if a.len() == 1 { + return Err(bad("\"opacityStops\" needs at least 2 stops (or none)".into())); + } + let mut stops = Vec::with_capacity(a.len()); + for (i, s) in a.iter().enumerate() { + let num = |k: usize| s.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()); + let (t, o) = num(0).zip(num(1)).ok_or_else(|| bad(format!("\"opacityStops\"[{i}] must be [position 0..1, opacity 0..100]")))?; + stops.push((t.clamp(0.0, 1.0) as f32, (o / 100.0).clamp(0.0, 1.0) as f32)); + } + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + Ok(Some(stops)) +} + /// Factory defaults for each effect kind, in the command's parameter units /// (what the Layer Style dialog starts a new effect from). pub fn effect_defaults(kind: &str) -> Value { @@ -572,11 +637,18 @@ fn fresh_effect(kind: &str) -> Option { }) } -/// Edits an existing gradient in place: only the end colours and geometry. -/// Intermediate stops, opacity stops, alignment and offset survive a round trip. +/// Edits an existing gradient in place: explicit `stops` / `opacityStops` replace the lists; +/// otherwise only the end colours and geometry change, and intermediate stops, opacity stops, +/// alignment and offset survive a round trip. fn overlay_gradient(g: &mut Gradient, p: &Value) { + if let Some(stops) = stops_param(p, "layer.layerStyle").ok().flatten() { + g.stops = stops; + } + if let Some(os) = opacity_stops_param(p, "layer.layerStyle").ok().flatten() { + g.opacity_stops = os; + } // A method rebuilds the gradient from its end colours (the stops between are the old curve). - if p.get("method").and_then(Value::as_str).is_some_and(|m| photocraft_io::GradientMethod::from_name(m).is_some()) { + if p.get("stops").is_none() && p.get("method").and_then(Value::as_str).is_some_and(|m| photocraft_io::GradientMethod::from_name(m).is_some()) { let ends = (g.stops.first().map(|s| s.1), g.stops.last().map(|s| s.1)); let from = color_of(p, "from").or(ends.0).unwrap_or(Color::BLACK); let to = color_of(p, "to").or(ends.1).unwrap_or(Color::WHITE); @@ -708,7 +780,7 @@ fn overlay_stroke(s: &mut StrokeFx, p: &Value) { }; } overlay_bool(p, "overprint", &mut s.overprint); - if p.get("from").is_some() { + if p.get("from").is_some() || p.get("stops").is_some() { s.paint = FxPaint::Gradient(gradient(p)); } else if let Some(c) = color_of(p, "color") { s.paint = FxPaint::Color(c); @@ -916,7 +988,7 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result { let mut pats = Vec::new(); for e in entries { let kind = e.get("kind").and_then(Value::as_str).ok_or_else(|| bad(CMD, "each effect needs a `kind` string"))?; - let params = match e.get("params") { + let mut params = match e.get("params") { None | Some(Value::Null) => json!({}), Some(Value::Object(_)) => e.get("params").cloned().unwrap_or_default(), Some(_) => return Err(bad(CMD, "`params` must be an object")), @@ -927,10 +999,27 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result { if kind_of(&fx) != kind { return Err(bad(CMD, format!("effect snapshot is a {}, not `{kind}`", kind_of(&fx)))); } + if let Effect::GradientOverlay { gradient, interpolation, .. } = &fx { + let stops = interpolation.as_ref().map_or(&gradient.stops, |s| &s.stops); + if exact_stops(¶ms).as_ref() == Some(stops) + && let Some(o) = params.as_object_mut() + { + o.remove("stops"); + } + if opacity_stops_param(¶ms, CMD).ok().flatten().as_ref() == Some(&gradient.opacity_stops) + && let Some(o) = params.as_object_mut() + { + o.remove("opacityStops"); + } + } + check_gradient_params(¶ms, CMD)?; overlay_effect(&mut fx, ¶ms); fx } - None => effect_from_params(kind, ¶ms).ok_or_else(|| bad(CMD, format!("unknown effect {kind}")))?, + None => { + check_gradient_params(¶ms, CMD)?; + effect_from_params(kind, ¶ms).ok_or_else(|| bad(CMD, format!("unknown effect {kind}")))? + } }; let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx)?; if let Some(pat) = pat { @@ -960,6 +1049,7 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result { fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result { crate::commands::check_f32_values(&format!("layer.layerStyle.{kind}"), p)?; + check_gradient_params(p, &format!("layer.layerStyle.{kind}"))?; let fx = effect_from_params(kind, p).ok_or_else(|| EngineError::Other(format!("unknown effect {kind}")))?; let (fx, pattern) = crate::pattern_cmds::resolve_effect(s, fx)?; let label = format!("Layer Style: {}", fx.label()); @@ -1068,7 +1158,7 @@ pub fn specs() -> Vec { style_cmd!( "gradientOverlay", "Gradient Overlay…", - r##"{"from":"#rrggbb","to":"#rrggbb","method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted on new effects: straight stops; edits retain the recorded method),"smoothness":0..100=100,"style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"## + r##"{"from":"#rrggbb","to":"#rrggbb","stops":[[0..1,"#rrggbb"],.]? (2..256 source stops),"opacityStops":[[0..1,0..100],.]?,"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted on new effects: straight stops; edits retain the recorded method),"smoothness":0..100=100,"style":"linear|radial|angle|reflected|diamond","angle":deg=90,"scale":10..150=100,"reverse":bool,"opacity":0..100,"blend":str,"add":bool}"## ), style_cmd!( "patternOverlay", @@ -1167,3 +1257,15 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { #[cfg(test)] mod tests; + +fn exact_stops(p: &Value) -> Option> { + p.get("stops")? + .as_array()? + .iter() + .map(|s| { + let t = s.get(0)?.as_f64()? as f32; + let color = color_of(&json!({"c":s.get(1)?}), "c")?; + Some((t, color)) + }) + .collect() +} diff --git a/crates/engine/src/layer_style/gradient_overlay.rs b/crates/engine/src/layer_style/gradient_overlay.rs index 8736597e08..ee88cb447d 100644 --- a/crates/engine/src/layer_style/gradient_overlay.rs +++ b/crates/engine/src/layer_style/gradient_overlay.rs @@ -66,6 +66,9 @@ pub(super) fn overlay(gradient: &mut Gradient, interpolation: &mut Option>(), vec![0.25, 1.0]); + assert!(gradient.opacity_stops.is_empty(), "[] means opaque"); + s.execute("layer.layerStyle.gradientOverlay", json!({"stops": stops})).unwrap(); + // The dialog's path: the snapshot plus a geometry edit keeps the three stops. + let fx = serde_json::to_value(&effects(&s)[0]).unwrap(); + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "gradientOverlay", "fx": fx, "params": {"angle": 45}}]})).unwrap(); + let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; + assert_eq!((gradient.stops.len(), gradient.angle), (3, 45.0)); + let e = s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "gradientOverlay", "params": {"stops": [[0, "#ff0000"]]}}]})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{e}"); + // A gradient stroke takes stops too. + s.execute("layer.layerStyle.stroke", json!({"size": 4, "stops": [[0, "#ff0000"], [0.5, "#00ff00"], [1, "#0000ff"]]})).unwrap(); + assert!(effects(&s).iter().any(|e| matches!(e, Effect::Stroke(st) if matches!(&st.paint, FxPaint::Gradient(g) if g.stops.len() == 3)))); + // Malformed lists are errors and change nothing. + for bad in [ + json!({"stops": "red"}), + json!({"stops": [[0, "#ff0000"]]}), + json!({"stops": [[0, "#ff0000"], ["x", "#0000ff"]]}), + json!({"stops": [[0, "#ff0000"], [1, 7]]}), + json!({"stops": [[0, "#ff0000"], [f64::NAN, "#0000ff"]]}), + json!({"stops": vec![json!([0, "#ff0000"]); 257]}), + json!({"opacityStops": [[0, 100]]}), + json!({"opacityStops": [[0, "x"], [1, 1]]}), + ] { + let e = s.execute("layer.layerStyle.gradientOverlay", bad.clone()).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}"); + } + let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; + assert_eq!(gradient.stops.len(), 3, "a refused edit keeps the gradient"); + // Positions outside 0..1 are clamped. + s.execute("layer.layerStyle.gradientOverlay", json!({"stops": [[-1, "#000000"], [2, "#ffffff"]]})).unwrap(); + let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; + assert_eq!(gradient.stops.iter().map(|s| s.0).collect::>(), vec![0.0, 1.0]); +} + #[test] fn gradient_overlay_method_matches_photoshop() { // Photoshop 27.11, Classic Gradient Overlay #000000 → #ffffff (Smoothness 100 %): 0.037 at @@ -574,3 +624,18 @@ fn double_stroke_bands_render_and_survive_an_edit() { s.execute("layer.layerStyle.replace", json!({"layer": id.0, "effects": entries})).unwrap(); assert_eq!(px(&mut s, 24, 14), before, "both strokes render identically after the round trip"); } + +#[test] +fn unchanged_dense_imported_stops_roundtrip_without_edit_limit_regression() { + let mut s = session(); + let gradient = Gradient { stops: (0..300).map(|i| (i as f32 / 299.0, Color::rgb(i as f32 / 777.0, 0.123456, 0.9))).collect(), ..Gradient::default() }; + let fx = Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: gradient.clone(), dither: false, interpolation: None }; + let stops: Vec<_> = gradient.stops.iter().map(|(t, c)| json!([t, c])).collect(); + s.execute("layer.layerStyle.replace", json!({"effects":[{"kind":"gradientOverlay","fx":fx,"params":{"stops":stops}}]})).unwrap(); + let doc = s.active().unwrap(); + let saved = &doc.doc.layer(doc.active_layer.unwrap()).unwrap().effects.items[0]; + assert_eq!(saved, &fx); + let mut edited = stops; + edited[1] = json!([0.01, "#ffffff"]); + assert!(s.execute("layer.layerStyle.replace", json!({"effects":[{"kind":"gradientOverlay","fx":fx,"params":{"stops":edited}}]})).is_err()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 17dbed3e43..fdcbe24120 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -297,3 +297,5 @@ mod tests; #[cfg(test)] mod fx_mode_tests; + +pub mod command_hints; diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index 3f6b074153..71d7a2060a 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -277,7 +277,9 @@ pub(crate) fn mix_through_selection( sel.sample_row_strided(r.y0.saturating_add(j as i32), r.x0, 1, 0, &mut coverage); } for ((a, o), k) in edited_row.iter().zip(orig_row).zip(&coverage) { - let mixed: [f32; 4] = std::array::from_fn(|c| o[c] + (a[c] - o[c]) * k); + // `o·(1−k) + a·k` keeps the edit exact at full coverage, even over huge 32-bit + // values whose difference from it would round the edit away (#9483). + let mixed: [f32; 4] = std::array::from_fn(|c| o[c] * (1.0 - k) + a[c] * k); let mut enc = [0.0f32; 8]; let m = photocraft_raster::from_rgba_into(fmt, mixed, &mut enc); out.extend_from_slice(&enc[..m]); diff --git a/crates/engine/src/pixels/tests.rs b/crates/engine/src/pixels/tests.rs index 10596fbca9..3461956566 100644 --- a/crates/engine/src/pixels/tests.rs +++ b/crates/engine/src/pixels/tests.rs @@ -292,7 +292,7 @@ fn mixing_through_a_selection_matches_sampling_it_per_pixel() { let mut expected = Vec::new(); for (i, (a, o)) in edited.iter().zip(&orig).enumerate() { let k = sel.sample_channel(r.x0 + (i % w) as i32, r.y0 + (i / w) as i32, 0); - let mixed: [f32; 4] = std::array::from_fn(|c| o[c] + (a[c] - o[c]) * k); + let mixed: [f32; 4] = std::array::from_fn(|c| o[c] * (1.0 - k) + a[c] * k); let mut enc = [0.0f32; 8]; let m = photocraft_raster::from_rgba_into(&fmt, mixed, &mut enc); expected.extend_from_slice(&enc[..m]); @@ -453,3 +453,14 @@ fn a_selection_with_a_nonzero_default_over_distant_blocks_is_refused() { let sel = distant_blocks(PixelFormat::GRAY8, 1.0); assert!(adjust_mask(&mut m, &Adjustment::Invert, Some(&sel)).is_err()); } + +/// #9483: a destructive edit with full coverage writes its result exactly, even over huge 32-bit +/// values (`o + (a − o)·k` gave 0 for a 0.5 result over 1e8, and 0.125 for 0.1 over 1e6). +#[test] +fn full_coverage_keeps_the_edit_over_huge_hdr_values() { + let fmt = PixelFormat::RGBA32F; + for (o, a) in [(1.0e8_f32, 0.5_f32), (1.0e6, 0.1), (-1.0e6, 0.9)] { + let out = mix_through_selection(&fmt, Rect::new(0, 0, 1, 1), &[[o, o, o, 1.0]], &[[a, a, a, 1.0]], None); + assert_eq!(out[..3], [a, a, a], "{a} over {o}"); + } +} diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 38dc5908f1..f2445a2a54 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1148,6 +1148,9 @@ pub struct Preferences { /// as the user changes it and restored at launch when Workspace › Remember Workspace /// Changes is on. JSON owned by the shell. pub panel_layout: Value, + /// The Color panel's options (what it shows, its ramp, Web colors, which chip it edits), + /// kept across restarts as Photoshop keeps them. JSON owned by the shell. + pub color_panel: Value, /// The last choices of dialogs that remember them across restarts, by command id (Edit › /// Fill…: `"edit.fill"` → its params). JSON owned by the shell. pub dialogs: BTreeMap, diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 92ad78e5dd..cc93556412 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -35,14 +35,17 @@ //! changes asynchronously. Gradient presets, including imported `.grd` groups, are small and persist with //! the preferences document (`presets.gradients`). //! +//! The pattern library (imported `.pat` and defined patterns, not the built-ins) lives there too: +//! `patterns.json` plus one `.pat` file per pattern, see [`patterns`]. +//! //! The Actions list (`actions.json`, see [`crate::actions_cmds`]) lives in the same directory. //! A missing file is an empty list. A corrupt or oversized file is skipped with a warning. //! Headless sessions have no store, so their actions stay in memory. //! -//! So do the patterns the user defined or imported (`patterns.pat`, Photoshop's own pattern file -//! format, #9317): the whole user library in its order, rewritten when its ids, names or order -//! change. The built-in patterns are regenerated on start and never written. Like `actions.json`, -//! a file that fails to load is warned about and never overwritten. +//! Patterns use `patterns.json` and lazily loaded per-pattern assets. On first startup a +//! valid legacy `patterns.pat` is migrated by writing assets before the atomic index commit. +//! Legacy and corrupt data are preserved; an existing index is authoritative even when corrupt. +//! A failed migration leaves the legacy library usable and retries at the next startup. use std::collections::{BTreeMap, HashMap, HashSet}; use std::io::Read; @@ -54,6 +57,9 @@ use serde::{Deserialize, Serialize}; use crate::Session; +mod patterns; +pub use patterns::{Loaded as LoadedPattern, MAX_PATTERN_BYTES, PATTERNS_FILE, PREVIEW_SIDE as PATTERN_PREVIEW_SIDE}; + /// Group file extension. pub const GROUP_EXT: &str = "pcbrushes"; /// Tip file extension (inside [`TIPS_DIR`]). @@ -73,7 +79,7 @@ pub const ACTIONS_FILE: &str = "actions.json"; /// Largest Actions file read or written. pub const MAX_ACTIONS_BYTES: u64 = 16 << 20; /// The user's pattern library (`.pat`). -pub const PATTERNS_FILE: &str = "patterns.pat"; +pub const LEGACY_PATTERNS_FILE: &str = "patterns.pat"; /// Largest pattern library read or written. pub const MAX_PATTERNS_BYTES: u64 = 256 << 20; /// The whole store never grows beyond this; further groups are skipped with a warning. @@ -560,13 +566,14 @@ pub struct PresetStore { actions_rev: u64, /// `actions.json` exists but failed to load: left on disk untouched, so it is never written. actions_skipped: bool, - /// [`patterns_key`] of the user patterns last written (or loaded). - patterns_key: u64, - /// `patterns.pat` exists but failed to load: left on disk untouched, so it is never written. - patterns_skipped: bool, + /// The pattern files and index (`patterns.json`). + patterns: patterns::PatternFiles, warnings: Vec, /// Full tips loaded for brushes in use (behind a lock so `&Session` paths can load). cache: Mutex, + /// The stored pattern last read in full, so painting with it again doesn't re-read its file + /// (a texture can be tens of megabytes). One: the pattern in use. + pattern_cache: Mutex>, } /// A loaded store: the presets on disk plus what the session should hide. @@ -582,8 +589,8 @@ pub struct Opened { pub warnings: Vec, /// Recorded actions (`actions.json`). Empty when the file is missing or unreadable. pub actions: Vec, - /// User patterns (`patterns.pat`), in library order. Empty when the file is missing or unreadable. - pub patterns: Vec, + /// Imported and defined patterns (`patterns.json`), in library order; large ones as previews. + pub patterns: Vec, } /// Load a store (any thread; the desktop app does this in the background at start). @@ -660,9 +667,7 @@ pub fn open(backend: Box) -> Opened { let loaded_actions = load_actions(backend.as_ref(), &mut warnings); let actions_skipped = loaded_actions.is_none(); let actions = loaded_actions.unwrap_or_default(); - let loaded_patterns = load_patterns(backend.as_ref(), &mut warnings); - let patterns_skipped = loaded_patterns.is_none(); - let patterns = loaded_patterns.unwrap_or_default(); + let (patterns, pattern_files) = patterns::load(backend.as_ref(), &mut warnings); let mut store = PresetStore { backend, synced_rev: None, @@ -672,10 +677,10 @@ pub fn open(backend: Box) -> Opened { index: None, actions_rev: 0, actions_skipped, - patterns_key: patterns_key(&patterns, 0), - patterns_skipped, + patterns: pattern_files, warnings: Vec::new(), cache: Mutex::new(TipCache { limit: TIP_CACHE_BYTES, ..Default::default() }), + pattern_cache: Mutex::new(None), }; let mut presets = Vec::new(); for (file, size, g) in parsed { @@ -734,40 +739,6 @@ pub fn open(backend: Box) -> Opened { Opened { store, presets, hidden_builtins, order, warnings, actions, patterns } } -/// `patterns.pat`: a missing file is no patterns. Anything else unreadable is a warning. -/// The saved patterns; `None` when `patterns.pat` exists but could not be loaded. -fn load_patterns(backend: &dyn PresetBackend, warnings: &mut Vec) -> Option> { - let bytes = match backend.read(PATTERNS_FILE, MAX_PATTERNS_BYTES) { - Ok(b) => b, - Err(e) if missing_file(&e) => return Some(Vec::new()), - Err(e) => { - warnings.push(format!("patterns: {PATTERNS_FILE} skipped: {e}")); - return None; - } - }; - match photocraft_io::pattern_map::read_pat(&bytes) { - Ok(p) => Some(p), - Err(e) => { - warnings.push(format!("patterns: {PATTERNS_FILE} skipped: {e}")); - None - } - } -} - -/// What decides whether the user patterns need rewriting: their ids, names, sizes and order, and -/// the library's [`pixels_rev`](crate::pattern_cmds::PatternLibrary::pixels_rev) (pixels replaced -/// under the same id). -fn patterns_key(patterns: &[photocraft_doc::Pattern], pixels_rev: u64) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - for p in patterns { - (&p.id, &p.name, p.width, p.height).hash(&mut h); - } - patterns.len().hash(&mut h); - pixels_rev.hash(&mut h); - h.finish() -} - /// `actions.json`: a missing file is an empty list. Anything else unreadable is a warning. /// The saved actions; `None` when `actions.json` exists but could not be loaded. fn load_actions(backend: &dyn PresetBackend, warnings: &mut Vec) -> Option> { @@ -1097,6 +1068,29 @@ impl PresetStore { Ok(()) } + /// Write the pattern library's changes (see [`patterns`]). + pub fn sync_patterns(&mut self, library: &crate::pattern_cmds::PatternLibrary) { + let changed = self.patterns.pixels_rev != library.pixels_rev; + patterns::sync(self.backend.as_ref(), &mut self.patterns, library, &mut self.warnings); + let cache = self.pattern_cache.get_mut().unwrap_or_else(PoisonError::into_inner); + if changed || cache.as_ref().is_some_and(|p| !self.patterns.index.iter().any(|e| e.id == p.id)) { + *cache = None; + } + } + + /// The full pixels of a stored pattern the library holds as a preview: the last one read is + /// kept, so only switching patterns reads a file. + pub fn load_pattern(&self, id: &str) -> Result { + let mut cache = self.pattern_cache.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(p) = cache.as_ref().filter(|p| p.id == id) { + return Ok(p.clone()); + } + let entry = self.patterns.index.iter().find(|e| e.id == id).ok_or_else(|| format!("pattern {id} is not in the preset store"))?; + let p = patterns::load_full(self.backend.as_ref(), entry)?; + *cache = Some(p.clone()); + Ok(p) + } + /// Write the Actions list when `rev` differs from the last load or write. /// An oversized list is warned once and not retried. An I/O error is warned and retried /// on the next command. @@ -1130,49 +1124,6 @@ impl PresetStore { } } -impl PresetStore { - /// Write the user patterns (the library minus the built-ins) when they changed since the last - /// load or write. An oversized library is warned once per change and not written. An I/O - /// error is warned and retried on the next command. - pub fn sync_patterns(&mut self, library: &[photocraft_doc::Pattern], pixels_rev: u64) { - let builtins = crate::pattern_cmds::builtin(); - let user: Vec = library.iter().filter(|p| !crate::pattern_cmds::is_pristine_builtin(p, &builtins)).cloned().collect(); - let key = patterns_key(&user, pixels_rev); - if self.patterns_key == key { - return; - } - self.patterns_key = key; - if self.patterns_skipped { - self.warnings.push(format!("Couldn't save patterns: {PATTERNS_FILE} could not be read, so it was left unchanged")); - return; - } - if user.is_empty() { - if let Err(e) = self.backend.remove(PATTERNS_FILE) { - self.warnings.push(format!("Couldn't save patterns: {e}")); - // Try again after the next command. - self.patterns_key = key.wrapping_add(1); - } - return; - } - let bytes = match photocraft_io::pattern_map::write_pat(&user) { - Ok(b) => b, - Err(e) => { - self.warnings.push(format!("Couldn't save patterns: {e}")); - return; - } - }; - if bytes.len() as u64 > MAX_PATTERNS_BYTES { - self.warnings.push(format!("patterns: the pattern library is too large to save ({} MB limit)", MAX_PATTERNS_BYTES >> 20)); - return; - } - if let Err(e) = self.backend.write(PATTERNS_FILE, &bytes) { - self.warnings.push(format!("Couldn't save patterns: {e}")); - // Try again after the next command. - self.patterns_key = key.wrapping_add(1); - } - } -} - fn builtin_names() -> &'static [String] { static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); NAMES.get_or_init(|| photocraft_paint::presets::builtin().into_iter().map(|p| p.name).collect()) @@ -1190,21 +1141,27 @@ impl Session { /// deleted built-ins, then sync. Returns the load warnings. pub fn attach_preset_store(&mut self, opened: Opened) -> Vec { let Opened { store, presets, hidden_builtins, order, mut warnings, actions: disk, patterns } = opened; - // Saved patterns join the library after the built-ins, and a saved built-in (replaced by - // an import or renamed) takes the shipped one's place; a pattern defined or imported - // before the store finished loading keeps its place (and the same id isn't added twice). let builtins = crate::pattern_cmds::builtin(); - for p in patterns { - match self.patterns.items.iter_mut().find(|q| q.id == p.id) { - Some(q) if crate::pattern_cmds::is_pristine_builtin(q, &builtins) => *q = p, - // The earlier copy wins; other pixels than the saved ones must still be written, - // which its id, name and size don't show. + for l in patterns { + let id = l.pattern.id.clone(); + match self.patterns.items.iter_mut().find(|q| q.id == id) { + Some(q) if crate::pattern_cmds::is_pristine_builtin(q, &builtins) => { + *q = l.pattern; + if let Some(size) = l.full { + self.patterns.stored.insert(id, size); + } + } Some(q) => { - if q.surface != p.surface { + if q.surface != l.pattern.surface { self.patterns.pixels_rev += 1; } } - None => self.patterns.items.push(p), + None => { + if let Some(size) = l.full { + self.patterns.stored.insert(id, size); + } + self.patterns.items.push(l.pattern); + } } } let lib = &mut self.tools.presets; @@ -1266,7 +1223,7 @@ impl Session { } } st.sync_actions(&self.actions.list, actions_rev); - st.sync_patterns(&self.patterns.items, self.patterns.pixels_rev); + st.sync_patterns(&self.patterns); } } diff --git a/crates/engine/src/preset_store/patterns.rs b/crates/engine/src/preset_store/patterns.rs new file mode 100644 index 0000000000..ff535ebcf6 --- /dev/null +++ b/crates/engine/src/preset_store/patterns.rs @@ -0,0 +1,380 @@ +//! The pattern library in the preset store: imported (`.pat`) and defined patterns survive a +//! restart, as Photoshop keeps its Patterns panel. +//! +//! - `pattern-.pat`: one pattern per file (a one-pattern Photoshop `.pat`), written once +//! when the pattern enters the library and deleted when it leaves it; +//! - `pattern-.preview.pat`: the same pattern shrunk to at most [`PREVIEW_SIDE`] px, for +//! patterns larger than that; +//! - `patterns.json`: the library order, names and full sizes (renaming rewrites only this file). +//! +//! Opening the store reads the index and the previews, never a large pattern's pixels: texture +//! libraries run to gigabytes (Debaser's colour libraries hold twenty 4500 × 4500 px patterns per +//! file). Such a pattern joins the library as its preview, with its full size in +//! [`crate::pattern_cmds::PatternLibrary::stored`], and its pixels are read when it is used +//! ([`super::PresetStore::load_pattern`]). +//! +//! Built-in patterns are never written. A pattern file or index that fails to load is left on +//! disk untouched and never overwritten or deleted; a missing index is an empty library. + +use std::collections::HashSet; + +use photocraft_doc::Pattern; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde::{Deserialize, Serialize}; + +use super::{PresetBackend, missing_file}; +use crate::pattern_cmds::PatternLibrary; + +/// Library order and names. +pub const PATTERNS_FILE: &str = "patterns.json"; +/// Largest `patterns.json` read or written. +pub const MAX_PATTERN_INDEX_BYTES: u64 = 4 << 20; +/// Largest pattern file read or written. +pub const MAX_PATTERN_BYTES: u64 = 256 << 20; +/// Most patterns loaded. +pub const MAX_PATTERNS: usize = 10_000; +/// Patterns larger than this (either side) are loaded as a preview of this size until used. +pub const PREVIEW_SIDE: u32 = 128; + +#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] +pub(super) struct Entry { + pub id: String, + pub name: String, + pub file: String, + #[serde(default)] + pub width: u32, + #[serde(default)] + pub height: u32, +} + +#[derive(Serialize, Deserialize)] +struct IndexFile { + version: u32, + patterns: Vec, +} + +/// The store's view of the pattern files it owns. +#[derive(Default)] +pub(super) struct PatternFiles { + /// The index as last loaded or written. + pub index: Vec, + /// `patterns.json` exists but failed to load: never written. + pub index_skipped: bool, + /// Pattern files that failed to load: never written or deleted. + pub skipped: HashSet, + /// Patterns that couldn't be written (too large, I/O error): not retried this session, so + /// one failure is one warning. + pub failed: HashSet, + pub pixels_rev: u64, + pub pending_removals: HashSet, +} + +/// A stored pattern as loaded: the pattern (a preview when `full` is set) and its full size. +pub struct Loaded { + pub pattern: Pattern, + pub full: Option<(u32, u32)>, +} + +fn hash(id: &str) -> u64 { + id.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)) +} + +/// The file a pattern is stored in (its id hashed: ids are UUIDs or content hashes, but may hold +/// any character). +fn file_name(id: &str) -> String { + format!("pattern-{:016x}.pat", hash(id)) +} + +fn preview_name(id: &str) -> String { + format!("pattern-{:016x}.preview.pat", hash(id)) +} + +#[cfg(test)] +pub(super) fn file_name_for_test(id: &str) -> String { + file_name(id) +} + +fn is_large(width: u32, height: u32) -> bool { + width.max(height) > PREVIEW_SIDE +} + +/// `p` shrunk to at most [`PREVIEW_SIDE`] px (nearest sample: a swatch, not a resample). +fn preview(p: &Pattern) -> Pattern { + let (w, h) = (p.width.max(1), p.height.max(1)); + let step = f64::from(w.max(h)) / f64::from(PREVIEW_SIDE); + let pw = ((f64::from(w) / step).round() as u32).clamp(1, PREVIEW_SIDE); + let ph = ((f64::from(h) / step).round() as u32).clamp(1, PREVIEW_SIDE); + let fmt = p.surface.format(); + let mut data = Vec::with_capacity(pw as usize * ph as usize * fmt.channels()); + for y in 0..ph { + for x in 0..pw { + let sx = ((f64::from(x) * step) as u32).min(w - 1); + let sy = ((f64::from(y) * step) as u32).min(h - 1); + data.extend(p.surface.pixel(sx as i32, sy as i32)); + } + } + let mut surface = Surface::new(fmt); + surface.write_region(Rect::new(0, 0, pw as i32, ph as i32), &data); + Pattern { id: p.id.clone(), name: p.name.clone(), width: pw, height: ph, surface } +} + +fn read_one(backend: &dyn PresetBackend, file: &str) -> Result { + let mut v = photocraft_io::pattern_map::read_pat(&backend.read(file, MAX_PATTERN_BYTES)?)?; + if v.is_empty() { Err("no pattern in the file".to_string()) } else { Ok(v.swap_remove(0)) } +} + +/// A stored pattern's full pixels (named and identified as in `entry`). +pub(super) fn load_full(backend: &dyn PresetBackend, entry: &Entry) -> Result { + let mut p = read_one(backend, &entry.file)?; + p.id = entry.id.clone(); + p.name = entry.name.clone(); + Ok(p) +} + +/// Load the stored patterns, in library order: small ones whole, large ones as previews. +pub(super) fn load(backend: &dyn PresetBackend, warnings: &mut Vec) -> (Vec, PatternFiles) { + let mut files = PatternFiles::default(); + let bytes = match backend.read(PATTERNS_FILE, MAX_PATTERN_INDEX_BYTES) { + Ok(b) => b, + Err(e) if missing_file(&e) => return migrate_legacy(backend, warnings), + Err(e) => { + warnings.push(format!("patterns: {PATTERNS_FILE} skipped: {e}")); + files.index_skipped = true; + return (Vec::new(), files); + } + }; + let index = match serde_json::from_slice::(&bytes) { + Ok(f) if f.version == 1 => f.patterns, + Ok(f) => { + warnings.push(format!("patterns: {PATTERNS_FILE} skipped: unsupported version {}", f.version)); + files.index_skipped = true; + return (Vec::new(), files); + } + Err(e) => { + warnings.push(format!("patterns: {PATTERNS_FILE} skipped: {e}")); + files.index_skipped = true; + return (Vec::new(), files); + } + }; + let mut ids = HashSet::new(); + let valid = index.len() <= MAX_PATTERNS && index.iter().all(|e| e.file == file_name(&e.id) && ids.insert(e.id.clone())); + if !valid { + warnings + .push("patterns: invalid/duplicate index entries; preserve files and recover patterns.json before saving (legacy PAT is not reimported)".into()); + files.index_skipped = true; + return (Vec::new(), files); + } + let mut patterns = Vec::new(); + let mut seen = HashSet::new(); + for e in index.into_iter().take(MAX_PATTERNS) { + // Only generated names: an edited index can't reach other files. + if e.file != file_name(&e.id) || !seen.insert(e.id.clone()) { + warnings.push(format!("patterns: entry \"{}\" skipped: bad file name", e.name)); + continue; + } + let loaded = if is_large(e.width, e.height) { + // The preview; without one (a failed write), the full file once to make it. + match read_one(backend, &preview_name(&e.id)) { + Ok(mut p) => { + p.id = e.id.clone(); + p.name = e.name.clone(); + Ok(Loaded { pattern: p, full: Some((e.width, e.height)) }) + } + Err(_) => load_full(backend, &e).map(|p| Loaded { pattern: preview(&p), full: Some((p.width, p.height)) }), + } + } else { + load_full(backend, &e).map(|p| Loaded { pattern: p, full: None }) + }; + match loaded { + Ok(l) => { + patterns.push(l); + files.index.push(e); + } + Err(err) => { + warnings.push(format!("patterns: {} (\"{}\") skipped: {err}", e.file, e.name)); + files.skipped.insert(e.file.clone()); + // Kept in the index, so a later write doesn't forget the file. + files.index.push(e); + } + } + } + (patterns, files) +} + +/// Write what changed: new patterns' files (and previews), the index when the order or a name +/// changed, and delete the files of patterns that left the library. Failures are warnings. +pub(super) fn sync(backend: &dyn PresetBackend, files: &mut PatternFiles, library: &PatternLibrary, warnings: &mut Vec) { + files.pending_removals.retain(|f| match backend.remove(f) { + Ok(()) => false, + Err(e) => { + warnings.push(format!("Couldn't delete pattern file {f}: {e}")); + true + } + }); + let builtins = crate::pattern_cmds::builtin(); + let pixels_changed = files.pixels_rev != library.pixels_rev; + let mut want: Vec = library + .items + .iter() + .filter(|p| !crate::pattern_cmds::is_pristine_builtin(p, &builtins)) + .map(|p| { + let (width, height) = library.stored.get(&p.id).copied().unwrap_or((p.width, p.height)); + Entry { id: p.id.clone(), name: p.name.clone(), file: file_name(&p.id), width, height } + }) + .collect(); + // Unreadable files stay listed (at the end) until the library takes their pattern back. + for e in &files.index { + if files.skipped.contains(&e.file) && !want.iter().any(|w| w.id == e.id) { + want.push(e.clone()); + } + } + if want == files.index && !pixels_changed { + return; + } + if files.index_skipped { + warnings.push(format!("Couldn't save patterns: {PATTERNS_FILE} could not be read, so it was left unchanged")); + files.index = want; + return; + } + let have: HashSet<&str> = files.index.iter().map(|e| e.id.as_str()).collect(); + let mut written = Vec::with_capacity(want.len()); + for e in want { + // Already on disk (a preview in the library included: its pixels never left the disk). + if (have.contains(e.id.as_str()) && !pixels_changed) || files.skipped.contains(&e.file) || library.stored.contains_key(&e.id) { + written.push(e); + continue; + } + let Some(p) = library.items.iter().find(|p| p.id == e.id) else { continue }; + match write_pattern(backend, p, &e, have.contains(e.id.as_str())) { + Ok(()) => written.push(e), + Err(err) => { + warnings.push(err); + files.failed.insert(e.id); + return; + } + } + } + if written.len() > MAX_PATTERNS { + warnings.push("patterns: index count limit exceeded".into()); + return; + } + let index = IndexFile { version: 1, patterns: written }; + let bytes = match serde_json::to_vec_pretty(&index) { + Ok(b) => b, + Err(e) => { + warnings.push(format!("Couldn't save patterns: {e}")); + return; + } + }; + if bytes.len() as u64 > MAX_PATTERN_INDEX_BYTES { + warnings.push("patterns: index byte limit exceeded".into()); + return; + } + if let Err(e) = backend.write(PATTERNS_FILE, &bytes) { + warnings.push(format!("Couldn't save patterns: {e}")); + return; + } + // Files of patterns that left the library (written by an earlier index) are deleted only + // once the new index no longer names them. + let keep: HashSet<&str> = index.patterns.iter().map(|e| e.file.as_str()).collect(); + for e in &files.index { + if !keep.contains(e.file.as_str()) && !files.skipped.contains(&e.file) { + for f in [e.file.clone(), preview_name(&e.id)] { + if let Err(err) = backend.remove(&f) { + warnings.push(format!("Couldn't delete pattern file {f}: {err}")); + files.pending_removals.insert(f); + } + } + } + } + files.index = index.patterns; + files.pixels_rev = library.pixels_rev; +} + +fn write_pattern(backend: &dyn PresetBackend, p: &Pattern, e: &Entry, owned: bool) -> Result<(), String> { + let bytes = photocraft_io::pattern_map::write_pat(std::slice::from_ref(p)).map_err(|err| format!("Couldn't save pattern \"{}\": {err}", p.name))?; + if bytes.len() as u64 > MAX_PATTERN_BYTES { + return Err(format!("pattern \"{}\" is too large to save ({} MB limit)", p.name, MAX_PATTERN_BYTES >> 20)); + } + if is_large(p.width, p.height) { + // The preview first: a full file without one still loads (by making it). + let small = photocraft_io::pattern_map::write_pat(&[preview(p)]).map_err(|err| format!("Couldn't save pattern \"{}\": {err}", p.name))?; + write_asset(backend, &preview_name(&e.id), &small, owned).map_err(|err| format!("Couldn't save pattern \"{}\": {err}", p.name))?; + } + write_asset(backend, &e.file, &bytes, owned).map_err(|err| format!("Couldn't save pattern \"{}\": {err}", p.name)) +} + +/// The index itself is the atomic migration commit. Never consult stale PAT when it exists, +/// including when corrupt. An interrupted asset write leaves the legacy bytes authoritative. +fn migrate_legacy(backend: &dyn PresetBackend, warnings: &mut Vec) -> (Vec, PatternFiles) { + let mut files = PatternFiles::default(); + let bytes = match backend.read(super::LEGACY_PATTERNS_FILE, super::MAX_PATTERNS_BYTES) { + Ok(b) => b, + Err(e) if missing_file(&e) => return (Vec::new(), files), + Err(e) => { + warnings.push(format!("patterns: legacy file preserved: {e}")); + files.index_skipped = true; + return (Vec::new(), files); + } + }; + let patterns = match photocraft_io::pattern_map::read_pat(&bytes) { + Ok(p) => p, + Err(e) => { + warnings.push(format!("patterns: legacy file preserved: {e}")); + files.index_skipped = true; + return (Vec::new(), files); + } + }; + let mut ids = HashSet::new(); + let mut names = HashSet::new(); + if patterns.len() > MAX_PATTERNS || patterns.iter().any(|p| !ids.insert(p.id.clone()) || !names.insert(file_name(&p.id))) { + warnings.push("patterns: legacy migration refused duplicate IDs, file hash collision or count limit; legacy preserved".into()); + files.index_skipped = true; + return (patterns.into_iter().map(|pattern| Loaded { pattern, full: None }).collect(), files); + } + let migration = (|| -> Result<(), String> { + let entries: Vec = + patterns.iter().map(|p| Entry { id: p.id.clone(), name: p.name.clone(), file: file_name(&p.id), width: p.width, height: p.height }).collect(); + let index = serde_json::to_vec_pretty(&IndexFile { version: 1, patterns: entries.clone() }).map_err(|e| e.to_string())?; + if index.len() as u64 > MAX_PATTERN_INDEX_BYTES { + return Err("index exceeds size limit".into()); + } + for (p, e) in patterns.iter().zip(&entries) { + // Never overwrite unknown files, even if a name collides. Identical orphan assets + // from an interrupted migration can be reused; the legacy file stays untouched. + let full = photocraft_io::pattern_map::write_pat(std::slice::from_ref(p))?; + if full.len() as u64 > MAX_PATTERN_BYTES { + return Err("pattern exceeds size limit".into()); + } + write_migration_asset(backend, &e.file, &full)?; + if is_large(p.width, p.height) { + let small = photocraft_io::pattern_map::write_pat(&[preview(p)])?; + write_migration_asset(backend, &preview_name(&p.id), &small)?; + } + } + // Atomic backend write last: no partial or failed migration can become authoritative. + backend.write(PATTERNS_FILE, &index)?; + Ok(()) + })(); + match migration { + Ok(()) => load(backend, warnings), + Err(e) => { + warnings.push(format!("patterns: migration not committed, legacy remains usable: {e}")); + files.index_skipped = true; + (patterns.into_iter().map(|pattern| Loaded { pattern, full: None }).collect(), files) + } + } +} +fn write_migration_asset(backend: &dyn PresetBackend, name: &str, bytes: &[u8]) -> Result<(), String> { + match backend.read(name, MAX_PATTERN_BYTES) { + Ok(existing) if existing == bytes => Ok(()), + Ok(_) => Err(format!("unrecognized existing asset {name} preserved")), + Err(e) if missing_file(&e) => backend.write(name, bytes), + Err(e) => Err(format!("existing asset {name} preserved: {e}")), + } +} + +fn write_asset(backend: &dyn PresetBackend, name: &str, bytes: &[u8], owned: bool) -> Result<(), String> { + if owned { backend.write(name, bytes) } else { write_migration_asset(backend, name, bytes) } +} diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index e0080aa4cb..89be8bc681 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -704,6 +704,129 @@ fn an_actions_file_that_failed_to_load_is_not_overwritten() { assert!(!s.preset_store.as_mut().unwrap().take_warnings().is_empty()); } +/// A large pattern opens as a small preview (texture libraries run to gigabytes) and is read at +/// full size when it is used; its preview file goes with it on delete. +#[test] +fn large_patterns_load_on_use() { + let dir = TempDir::new("patterns-large"); + let (mut s, _) = session(&dir); + s.execute("file.new", json!({"width": 300, "height": 200})).unwrap(); + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + s.execute("select.rect", json!({"x": 250, "y": 150, "width": 50, "height": 50})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("edit.definePattern", json!({"name": "Big"})).unwrap(); + assert_eq!(dir.files().iter().filter(|f| f.ends_with(".preview.pat")).count(), 1); + + let (mut t, w) = session(&dir); + assert!(w.is_empty(), "{w:?}"); + let held = t.patterns.items.iter().find(|p| p.name == "Big").unwrap(); + assert!(held.width <= PATTERN_PREVIEW_SIDE && held.height <= PATTERN_PREVIEW_SIDE, "held as a preview: {}x{}", held.width, held.height); + let listed = t.execute("pattern.list", json!({})).unwrap(); + let big = listed.as_array().unwrap().iter().find(|p| p["name"] == "Big").unwrap(); + assert_eq!((big["width"].as_u64(), big["height"].as_u64()), (Some(300), Some(200)), "the list reports the full size"); + // Checks that only need the pattern's id (Pattern Stamp's enabled state) don't read its file. + let id = t.patterns.items.iter().find(|p| p.name == "Big").unwrap().id.clone(); + let file = dir.0.join(patterns::file_name_for_test(&id)); + let moved = file.with_extension("moved"); + std::fs::rename(&file, &moved).unwrap(); + assert_eq!(crate::pattern_cmds::resolve_id(&t, "Big"), Some(id.clone())); + assert!(crate::pattern_cmds::resolve(&t, "Big").is_none(), "the full pixels come from the file"); + std::fs::rename(&moved, &file).unwrap(); + let full = crate::pattern_cmds::resolve(&t, "Big").unwrap(); + assert_eq!((full.width, full.height), (300, 200)); + assert!(full.surface.pixel(280, 180)[1] < 0.01 && full.surface.pixel(10, 10)[1] > 0.99, "full pixels"); + // Once read, it is kept: using it again doesn't read the file. + std::fs::rename(&file, &moved).unwrap(); + assert_eq!(crate::pattern_cmds::resolve(&t, "Big").map(|p| p.width), Some(300)); + std::fs::rename(&moved, &file).unwrap(); + // A Pattern Fill layer gets the full pattern into the document. + t.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + t.execute("layer.newFillLayer.pattern", json!({"pattern": "Big"})).unwrap(); + let doc_pat = &t.active().unwrap().doc.patterns[0]; + assert_eq!((doc_pat.width, doc_pat.height), (300, 200)); + // Exporting the library writes full pixels too. + let out = dir.0.join("export.pat"); + t.execute("pattern.export", json!({"path": out.to_string_lossy()})).unwrap(); + let back = photocraft_io::pattern_map::read_pat(&std::fs::read(&out).unwrap()).unwrap(); + assert!(back.iter().any(|p| p.name == "Big" && p.width == 300)); + std::fs::remove_file(&out).unwrap(); + + t.execute("pattern.delete", json!({"pattern": "Big"})).unwrap(); + assert!(!dir.files().iter().any(|f| f.starts_with("pattern-")), "{:?}", dir.files()); +} + +/// A corrupt pattern file is skipped with a warning and left on disk; the others load, and later +/// saves never delete or overwrite it. A corrupt index is never overwritten. +#[test] +fn corrupt_pattern_files_are_skipped_and_kept() { + let dir = TempDir::new("patterns-corrupt"); + let (mut s, _) = session(&dir); + define_pattern(&mut s, "Grit", "#202020", 8); + define_pattern(&mut s, "Paper", "#f0e0c0", 12); + let grit = s.patterns.items.iter().find(|p| p.name == "Grit").unwrap().id.clone(); + let file = dir.0.join(patterns::file_name_for_test(&grit)); + std::fs::write(&file, b"not a pattern").unwrap(); + + let (mut t, w) = session(&dir); + assert!(w.iter().any(|w| w.contains("Grit")), "{w:?}"); + assert_eq!(user_patterns(&t), [("Paper".to_string(), 12)]); + define_pattern(&mut t, "Ink", "#000000", 4); + assert_eq!(std::fs::read(&file).unwrap(), b"not a pattern", "the unreadable file is left alone"); + let index = std::fs::read_to_string(dir.0.join(PATTERNS_FILE)).unwrap(); + assert!(index.contains("Grit") && index.contains("Ink"), "{index}"); + + std::fs::write(dir.0.join(PATTERNS_FILE), b"{").unwrap(); + let (mut u, w) = session(&dir); + assert!(w.iter().any(|w| w.contains(PATTERNS_FILE)), "{w:?}"); + assert!(user_patterns(&u).is_empty()); + define_pattern(&mut u, "Late", "#808080", 4); + assert_eq!(std::fs::read(dir.0.join(PATTERNS_FILE)).unwrap(), b"{", "an unreadable index is never overwritten"); +} + +/// Imported and defined patterns survive a restart: one file each, written once, plus the index; +/// a rename rewrites only the index, a delete removes the file. +#[test] +fn patterns_survive_a_restart() { + let dir = TempDir::new("patterns"); + let (mut s, w) = session(&dir); + assert!(w.is_empty(), "{w:?}"); + define_pattern(&mut s, "Grit", "#202020", 8); + define_pattern(&mut s, "Paper", "#f0e0c0", 12); + let pattern_files = |d: &TempDir| d.files().into_iter().filter(|f| f.starts_with("pattern-")).collect::>(); + assert_eq!(pattern_files(&dir).len(), 2); + assert!(dir.files().contains(&PATTERNS_FILE.to_string())); + assert!(!dir.files().iter().any(|f| f.contains("Checkerboard")), "built-ins are never written"); + + let (mut t, w) = session(&dir); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(user_patterns(&t), [("Grit".to_string(), 8), ("Paper".to_string(), 12)]); + // The pixels come back too. + let paper = t.patterns.items.iter().find(|p| p.name == "Paper").unwrap(); + let px = paper.surface.pixel(3, 3); + assert!((px[0] - 240.0 / 255.0).abs() < 0.01, "{px:?}"); + + let before = std::fs::metadata(dir.0.join(&pattern_files(&dir)[0])).unwrap().modified().unwrap(); + t.execute("pattern.rename", json!({"pattern": "Grit", "name": "Toner"})).unwrap(); + assert_eq!(std::fs::metadata(dir.0.join(&pattern_files(&dir)[0])).unwrap().modified().unwrap(), before, "a rename rewrites only the index"); + t.execute("pattern.delete", json!({"pattern": "Paper"})).unwrap(); + assert_eq!(pattern_files(&dir).len(), 1, "the deleted pattern's file is gone"); + + let (u, _) = session(&dir); + assert_eq!(user_patterns(&u), [("Toner".to_string(), 8)]); +} + +fn define_pattern(s: &mut Session, name: &str, color: &str, width: u32) { + s.execute("file.new", json!({"width": width, "height": 6})).unwrap(); + s.execute("edit.fill", json!({"color": color})).unwrap(); + s.execute("edit.definePattern", json!({"name": name})).unwrap(); +} + +fn user_patterns(s: &Session) -> Vec<(String, u32)> { + let builtins: Vec = crate::pattern_cmds::builtin().into_iter().map(|p| p.id).collect(); + s.patterns.items.iter().filter(|p| !builtins.contains(&p.id)).map(|p| (p.name.clone(), p.width)).collect() +} + /// #9317: a defined or imported pattern survives a restart, as in Photoshop; the built-in /// patterns are never written, and deleting the last user pattern removes the file. #[test] @@ -719,7 +842,13 @@ fn user_patterns_survive_a_restart() { assert!(dir.files().contains(&PATTERNS_FILE.to_string()), "{:?}", dir.files()); // Only the user's pattern is in the file. let bytes = std::fs::read(dir.0.join(PATTERNS_FILE)).unwrap(); - let saved = photocraft_io::pattern_map::read_pat(&bytes).unwrap(); + let index: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let saved: Vec = index["patterns"] + .as_array() + .unwrap() + .iter() + .map(|e| photocraft_io::pattern_map::read_pat(&std::fs::read(dir.0.join(e["file"].as_str().unwrap())).unwrap()).unwrap().remove(0)) + .collect(); assert_eq!(saved.iter().map(|p| p.name.as_str()).collect::>(), ["Green Tile"]); drop(s); @@ -736,7 +865,10 @@ fn user_patterns_survive_a_restart() { assert!(u.patterns.items.iter().any(|p| p.id == id && p.name == "Moss")); t.execute("pattern.delete", json!({"pattern": id})).unwrap(); t.sync_preset_store(); - assert!(!dir.files().contains(&PATTERNS_FILE.to_string()), "{:?}", dir.files()); + assert!( + serde_json::from_slice::(&std::fs::read(dir.0.join(PATTERNS_FILE)).unwrap()).unwrap()["patterns"].as_array().unwrap().is_empty(), + "empty authoritative index prevents resurrection" + ); } #[test] @@ -827,7 +959,13 @@ fn a_failed_patterns_removal_is_retried() { backend.fail.store(false, std::sync::atomic::Ordering::SeqCst); s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); s.sync_preset_store(); - assert!(!backend.mem.files.lock().unwrap().contains_key(PATTERNS_FILE), "the removal is retried"); + assert!(!backend.mem.files.lock().unwrap().keys().any(|f| f.starts_with("pattern-")), "owned asset removal is retried"); + assert!( + serde_json::from_slice::(backend.mem.files.lock().unwrap().get(PATTERNS_FILE).unwrap()).unwrap()["patterns"] + .as_array() + .unwrap() + .is_empty() + ); } /// #9318 review: an imported `.pat` that replaces a built-in pattern's pixels (same id) is saved @@ -840,7 +978,13 @@ fn an_imported_builtin_replacement_survives_a_restart() { let builtin = s.patterns.items[0].id.clone(); s.execute("pattern.import", json!({"data": pat_bytes(&builtin, [0.9, 0.1, 0.4, 1.0])})).unwrap(); s.sync_preset_store(); - let saved = photocraft_io::pattern_map::read_pat(mem.files.lock().unwrap().get(PATTERNS_FILE).expect("written")).unwrap(); + let index: serde_json::Value = serde_json::from_slice(mem.files.lock().unwrap().get(PATTERNS_FILE).expect("written")).unwrap(); + let saved: Vec = index["patterns"] + .as_array() + .unwrap() + .iter() + .map(|e| photocraft_io::pattern_map::read_pat(mem.files.lock().unwrap().get(e["file"].as_str().unwrap()).unwrap()).unwrap().remove(0)) + .collect(); assert_eq!(saved.iter().map(|p| p.id.as_str()).collect::>(), [builtin.as_str()], "only the replaced built-in"); let mut t = Session::new(); t.attach_preset_store(open(Box::new(mem.clone()))); @@ -870,3 +1014,114 @@ fn an_early_same_id_import_wins_and_is_saved() { u.attach_preset_store(open(Box::new(mem.clone()))); assert_eq!(u.patterns.items.iter().find(|p| p.id == id).unwrap().surface, early, "the early import's pixels were saved"); } +#[derive(Clone)] +struct MigrationFail { + mem: MemBackend, + fail_name: String, +} +impl PresetBackend for MigrationFail { + fn list(&self) -> Result, String> { + self.mem.list() + } + fn read(&self, n: &str, m: u64) -> Result, String> { + self.mem.read(n, m) + } + fn write(&self, n: &str, b: &[u8]) -> Result<(), String> { + if n == self.fail_name { Err("injected migration write failure".into()) } else { self.mem.write(n, b) } + } + fn remove(&self, n: &str) -> Result<(), String> { + self.mem.remove(n) + } +} +fn legacy_store() -> (MemBackend, Vec, String) { + let mem = MemBackend::default(); + let id = "6f1c2c1e-0000-4000-8000-000000005176".to_string(); + let bytes = photocraft_paint::tile::b64_decode(&pat_bytes(&id, [0.2, 0.6, 0.8, 1.0])).unwrap(); + mem.write(LEGACY_PATTERNS_FILE, &bytes).unwrap(); + (mem, bytes, id) +} +#[test] +fn legacy_migration_commits_last_and_never_resurrects_renames_or_deletions() { + let (mem, old, id) = legacy_store(); + let mut s = Session::new(); + assert!(s.attach_preset_store(open(Box::new(mem.clone()))).is_empty()); + assert!(mem.read(PATTERNS_FILE, 1 << 20).is_ok()); + assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old); + s.execute("pattern.rename", json!({"pattern":id,"name":"Migrated"})).unwrap(); + s.sync_preset_store(); + let mut t = Session::new(); + t.attach_preset_store(open(Box::new(mem.clone()))); + assert_eq!(t.patterns.items.iter().find(|p| p.id == id).unwrap().name, "Migrated"); + t.execute("pattern.delete", json!({"pattern":id})).unwrap(); + t.sync_preset_store(); + for _ in 0..2 { + let mut u = Session::new(); + u.attach_preset_store(open(Box::new(mem.clone()))); + assert!(!u.patterns.items.iter().any(|p| p.id == id)); + } + assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old); +} +#[test] +fn interrupted_migration_preserves_legacy_and_reuses_only_identical_orphans() { + for fail_index in [false, true] { + let (mem, old, id) = legacy_store(); + let file = patterns::file_name_for_test(&id); + let fail_name = if fail_index { PATTERNS_FILE.to_string() } else { file.clone() }; + let opened = open(Box::new(MigrationFail { mem: mem.clone(), fail_name })); + assert!(!opened.warnings.is_empty()); + assert!(opened.patterns.iter().any(|p| p.pattern.id == id), "legacy remains usable"); + assert!(mem.read(PATTERNS_FILE, 1 << 20).is_err(), "no commit marker on failure"); + assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old); + let retry = open(Box::new(mem.clone())); + assert!(retry.warnings.is_empty(), "{:?}", retry.warnings); + assert!(retry.patterns.iter().any(|p| p.pattern.id == id)); + } + let (mem, old, id) = legacy_store(); + let file = patterns::file_name_for_test(&id); + mem.write(&file, b"unknown content").unwrap(); + let opened = open(Box::new(mem.clone())); + assert!(!opened.warnings.is_empty()); + assert_eq!(mem.read(&file, 100).unwrap(), b"unknown content"); + assert!(mem.read(PATTERNS_FILE, 1 << 20).is_err()); + assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old); +} +#[test] +fn malformed_authoritative_index_never_falls_back_to_stale_legacy() { + let (mem, _, id) = legacy_store(); + drop(open(Box::new(mem.clone()))); + for bytes in [b"{".as_slice(), b"{\"version\":1,\"patterns\":[{\"id\":\"x\",\"name\":\"bad\",\"file\":\"../secret\"}]}".as_slice()] { + mem.write(PATTERNS_FILE, bytes).unwrap(); + let opened = open(Box::new(mem.clone())); + assert!(!opened.warnings.is_empty()); + assert!(opened.patterns.is_empty()); + assert_eq!(mem.read(PATTERNS_FILE, 1 << 20).unwrap(), bytes); + assert!(!opened.patterns.iter().any(|p| p.pattern.id == id)); + } + let mem = MemBackend::default(); + mem.write(LEGACY_PATTERNS_FILE, b"broken PAT").unwrap(); + let opened = open(Box::new(mem.clone())); + assert!(!opened.warnings.is_empty()); + assert!(mem.read(PATTERNS_FILE, 1 << 20).is_err()); + assert_eq!(mem.read(LEGACY_PATTERNS_FILE, 20).unwrap(), b"broken PAT"); +} +#[test] +fn migration_preserves_duplicate_names_but_refuses_duplicate_ids() { + let (mem, _, id) = legacy_store(); + let bytes = mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(); + let mut pats = photocraft_io::pattern_map::read_pat(&bytes).unwrap(); + let mut other = pats[0].clone(); + other.id = "6f1c2c1e-0000-4000-8000-000000005177".into(); + pats.push(other); + mem.write(LEGACY_PATTERNS_FILE, &photocraft_io::pattern_map::write_pat(&pats).unwrap()).unwrap(); + let opened = open(Box::new(mem.clone())); + assert!(opened.warnings.is_empty()); + assert_eq!(opened.patterns.len(), 2); + let mem = MemBackend::default(); + pats[1].id = id; + let old = photocraft_io::pattern_map::write_pat(&pats).unwrap(); + mem.write(LEGACY_PATTERNS_FILE, &old).unwrap(); + let opened = open(Box::new(mem.clone())); + assert!(!opened.warnings.is_empty()); + assert!(mem.read(PATTERNS_FILE, 1 << 20).is_err()); + assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old); +} diff --git a/crates/engine/src/presets/patterns.rs b/crates/engine/src/presets/patterns.rs index 2425dd0900..a1d9ff2bf0 100644 --- a/crates/engine/src/presets/patterns.rs +++ b/crates/engine/src/presets/patterns.rs @@ -162,7 +162,7 @@ fn edit(s: &mut Session, p: &Value) -> Result { } "move" => { let key = req_str(p, "preset", CMD)?; - let id = crate::pattern_cmds::resolve(s, key).map(|q| q.id).ok_or_else(|| bad(CMD, format!("no pattern \"{key}\"")))?; + let id = crate::pattern_cmds::resolve_id(s, key).ok_or_else(|| bad(CMD, format!("no pattern \"{key}\"")))?; let mut q = p.clone(); q["preset"] = json!(id); edit_groups(&mut s.presets.pattern_groups, "move", &q, CMD)? diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index bc70ed2739..8ea18aa4e0 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -127,7 +127,7 @@ impl Session { /// [`Self::disabled_reason`] for a call with `params`. pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { - let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; + let Some(s) = commands::find(id) else { return Some(EngineError::UnknownCommand(id.into()).to_string()) }; self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) } @@ -140,13 +140,18 @@ impl Session { if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); } + if spec.id == "layer.smartFilter.deleteFilterMask" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { + return smart_cmds::smart_layer_active(self); + } channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) } /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. fn names_existing_layer(&self, id: &str, params: &Value) -> bool { - matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") + (matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") + || (id == "layer.setProps" + && params.as_object().is_some_and(|o| o.contains_key("visible") && o.keys().all(|k| matches!(k.as_str(), "layer" | "visible" | "coalesce"))))) && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) } diff --git a/crates/engine/src/shell_commands.rs b/crates/engine/src/shell_commands.rs index 61c33bb8cf..3b52c03a03 100644 --- a/crates/engine/src/shell_commands.rs +++ b/crates/engine/src/shell_commands.rs @@ -7,6 +7,7 @@ /// Shell commands: id, label, menu path, default shortcut. pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ + ("layer.selectUnderCursor", "Select Layer Under Cursor", &[], None), ("ui.symmetryTransform", "Transform Symmetry", &[], None), // Right-click the options bar's tool icon (#2825); `tool.resetAll` asks first. ("tool.reset", "Reset Tool", &[], None), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 64ed09e9e2..b09c184c6d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -681,6 +681,10 @@ fn arrange_and_group() { let names: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect(); assert_eq!(names, ["Background", "B", "A"]); assert!(s.execute("layer.arrange.bringForward", json!({})).is_err()); + // Bring to Front of the front layer does nothing: no error (an action plays it), no step. + let steps = s.active().unwrap().history.past_len(); + assert_eq!(s.execute("layer.arrange.bringToFront", json!({})).unwrap(), json!({"moved": false})); + assert_eq!(s.active().unwrap().history.past_len(), steps); s.execute("layer.groupLayers", json!({})).unwrap(); let doc = s.execute("document.inspect", json!({})).unwrap(); assert_eq!(doc["layers"][0]["kind"], "Group"); diff --git a/crates/engine/tests/cmyk_flatten_profile.rs b/crates/engine/tests/cmyk_flatten_profile.rs new file mode 100644 index 0000000000..28b3bf9afc --- /dev/null +++ b/crates/engine/tests/cmyk_flatten_profile.rs @@ -0,0 +1,176 @@ +//! Flatten Image, Stamp Visible, Background from Layer, Merge Down and Merge Visible keep the +//! inks of a CMYK document tagged with a profile other than the built-in one (#3778). +//! +//! A document whose composite is one plain pixel layer keeps its inks exactly, as in Photoshop +//! (black generation and inks outside the display gamut included). Merges of several layers are +//! composited in RGB and separated back through the profile the layers were read with, so they +//! keep the inks up to that round trip's residual instead of moving every pixel. + +use std::sync::Arc; + +use photocraft_color::convert::{CmykSpace, with_cmyk_space}; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use serde_json::json; + +const W: i32 = 8; +const H: i32 = 2; + +/// RGB colours whose separations make the first row: mid tones, saturated colours, near-black. +const RGB: [[f32; 3]; 8] = + [[0.8, 0.3, 0.2], [0.1, 0.5, 0.9], [0.5, 0.5, 0.5], [0.08, 0.06, 0.05], [0.95, 0.9, 0.85], [0.9, 0.8, 0.1], [0.2, 0.7, 0.3], [0.6, 0.2, 0.6]]; + +/// Inks no separation produces, for the second row: K only, rich black, solid cyan (outside +/// sRGB), paper, 50 % K, a heavy four-colour mix, and two odd mixes. +const INKS: [[f32; 4]; 8] = [ + [0.0, 0.0, 0.0, 1.0], + [0.75, 0.68, 0.67, 0.9], + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.5], + [0.9, 0.9, 0.9, 0.9], + [0.886, 0.329, 0.0, 0.0], + [0.1, 0.0, 0.6, 0.3], +]; + +fn profile() -> Arc> { + photocraft_cms::synth::cmyk_profile(&photocraft_cms::synth::CmykParams { + description: "Test Uncoated".into(), + tvi: [0.26, 0.26, 0.26, 0.3], + ..Default::default() + }) + .to_bytes() +} + +/// A one-layer (Background) CMYK document, tagged with `profile()` when `tag`: the first row is +/// separated from [`RGB`] through that profile (a separation read back and separated again a few +/// times, so the profile reproduces it), the second row holds [`INKS`]. +fn document(depth: u32, tag: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + let icc = profile(); + let space = CmykSpace::for_profile(Some(&icc)); + assert!(space.is_some(), "the fixture is not the built-in profile"); + s.edit("tag", |doc, _| { + if tag { + doc.icc_profile = Some(icc.clone()); + } + let bg = doc.layers[0].surface_mut().unwrap(); + let fmt = bg.format(); + with_cmyk_space(if tag { space.as_ref() } else { None }, || { + for (x, rgb) in RGB.iter().enumerate() { + let mut px = photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]); + for _ in 0..3 { + let back = photocraft_raster::to_rgba(&fmt, &px); + px = photocraft_raster::from_rgba(&fmt, back); + } + bg.write_pixel(x as i32, 0, &px); + } + }); + for (x, ink) in INKS.iter().enumerate() { + bg.write_pixel(x as i32, 1, &[ink[0], ink[1], ink[2], ink[3], 1.0]); + } + Ok(()) + }) + .unwrap(); + s +} + +/// The four ink values of every pixel of the active layer. +fn inks(s: &Session) -> Vec<[f32; 4]> { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let n = surf.channels(); + surf.read_region(Rect::new(0, 0, W, H)).chunks_exact(n).map(|p| [p[0], p[1], p[2], p[3]]).collect() +} + +fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { + a.iter().zip(b).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max) +} + +/// Runs `run` on a document and returns how far the inks of `row` (0 = separations, 1 = any +/// inks) moved. +fn drift(depth: u32, tag: bool, row: usize, run: impl FnOnce(&mut Session)) -> f32 { + let mut s = document(depth, tag); + let before = inks(&s); + run(&mut s); + let after = inks(&s); + let r = row * W as usize..(row + 1) * W as usize; + max_diff(&before[r.clone()], &after[r]) +} + +fn exact(what: &str, run: impl Fn(&mut Session)) { + for depth in [8, 16] { + for tag in [true, false] { + for row in [0, 1] { + let d = drift(depth, tag, row, &run); + assert!(d == 0.0, "{depth}-bit {what} (tagged: {tag}, row {row}): inks moved by {d}"); + } + } + } +} + +#[test] +fn flatten_keeps_the_inks_of_a_single_layer_exactly() { + exact("Flatten Image", |s| { + s.execute("layer.flattenImage", json!({})).unwrap(); + }); +} + +#[test] +fn stamp_visible_keeps_the_inks_of_a_single_layer_exactly() { + exact("Stamp Visible", |s| { + s.execute("layer.stampVisible", json!({})).unwrap(); + }); +} + +#[test] +fn background_from_layer_keeps_the_inks_exactly() { + exact("Background from Layer", |s| { + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("layer.new.backgroundFromLayer", json!({})).unwrap(); + }); +} + +#[test] +fn flatten_of_a_partly_transparent_layer_still_composites_over_white() { + for depth in [8, 16] { + let mut s = document(depth, true); + s.edit("hole", |doc, _| { + doc.layers[0].surface_mut().unwrap().write_pixel(0, 0, &[0.0, 0.0, 0.0, 1.0, 0.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.flattenImage", json!({})).unwrap(); + let px = inks(&s)[0]; + // Transparent over white paper: no ink, not the hidden K. + assert!(px.iter().all(|v| *v < 0.02), "{depth}-bit: {px:?}"); + } +} + +/// Merges of several layers go through the RGB composite: separations the profile reproduces +/// come back within this (the profile's own RGB round trip, a few levels), where reading with +/// the document's profile and separating with the built-in one moved them by tens of levels. +const ROUND_TRIP: f32 = 10.0 / 255.0; + +#[test] +fn merge_down_separates_through_the_document_profile() { + for depth in [8, 16] { + let d = drift(depth, true, 0, |s| { + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.mergeDown", json!({})).unwrap(); + }); + assert!(d <= ROUND_TRIP, "{depth}-bit Merge Down: inks moved by {d}"); + } +} + +#[test] +fn merge_visible_separates_through_the_document_profile() { + for depth in [8, 16] { + let d = drift(depth, true, 0, |s| { + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.mergeVisible", json!({})).unwrap(); + }); + assert!(d <= ROUND_TRIP, "{depth}-bit Merge Visible: inks moved by {d}"); + } +} diff --git a/crates/engine/tests/it/affinity.rs b/crates/engine/tests/it/affinity.rs index 2d56fbf986..06c4bf4e66 100644 --- a/crates/engine/tests/it/affinity.rs +++ b/crates/engine/tests/it/affinity.rs @@ -12,7 +12,10 @@ use serde_json::json; fn fixture() -> Vec { let mut src = Session::new(); src.execute("file.new", json!({"width": 2, "height": 1, "background": "#dc283c"})).unwrap(); - let png = photocraft_io::export(&src.active().unwrap().doc, "preview.png", &Default::default()).unwrap().bytes; + // Affinity's previews carry no colour profile. + let mut opts = photocraft_io::ExportOptions::default(); + opts.encode.embed_icc = false; + let png = photocraft_io::export(&src.active().unwrap().doc, "preview.png", &opts).unwrap().bytes; // Observed v12 preview envelope, without a native object graph. let mut bytes = vec![0; 72]; bytes[..4].copy_from_slice(b"\x00\xffKA"); diff --git a/crates/engine/tests/it/smart_psd.rs b/crates/engine/tests/it/smart_psd.rs index 4aeda1519b..542220f34b 100644 --- a/crates/engine/tests/it/smart_psd.rs +++ b/crates/engine/tests/it/smart_psd.rs @@ -469,6 +469,74 @@ fn displace_psd_filter_renders_with_its_embedded_map() { } } +/// #9162: a Photoshop Displace smart filter that names its map file (`DspF`, a `Pth `) without +/// embedding it was skipped as "not supported" on Replace Contents. Opened from PSD, it now reads +/// that file and the replaced contents come out displaced. +#[test] +fn displace_psd_filter_with_only_a_map_path_renders_after_replace_contents() { + use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; + let dir = std::env::temp_dir().join(format!("pcraft-9162-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = |name: &str, size: (u32, u32), c: [f32; 4]| { + let d = Document::with_background( + "m", + photocraft_geom::Size::new(size.0, size.1), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]), + ); + let path = dir.join(name); + std::fs::write(&path, photocraft_io::export(&d, "png", &Default::default()).unwrap().bytes).unwrap(); + path.to_str().unwrap().to_string() + }; + // Red is the horizontal map (full right), green the vertical one (about neutral), as in the + // issue's map. + let map = png("map.png", (12, 8), [1.0, 0.5, 0.5, 1.0]); + let design = png("design.png", (72, 52), [1.0, 0.0, 0.0, 1.0]); + // `DspF` as Photoshop writes a path: `txtu`, sizes (LE), UTF-16LE with a trailing NUL. + let units: Vec = map.encode_utf16().chain([0]).collect(); + let mut pth = b"txtu".to_vec(); + pth.extend((12 + 2 * units.len() as u32).to_le_bytes()); + pth.extend((units.len() as u32).to_le_bytes()); + pth.extend(units.iter().flat_map(|u| u.to_le_bytes())); + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let fltr = Descriptor::new("Dspl") + .with("HrzS", Value::Integer(10)) + .with("VrtS", Value::Integer(10)) + .with("DspM", e("DspM", "StrF")) + .with("UndA", e("UndA", "RptE")) + .with("DspF", Value::Path(pth)); + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Displace..."))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(1148416108)); + for depth in [8, 16, 32] { + let mut s = session(depth); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let id = photocraft_doc::LayerId(s.active().unwrap().active_layer.unwrap().0); + s.edit("displace", |doc, _| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(id).unwrap().content else { panic!("smart") }; + sm.smart_filters.push(photocraft_io::smart_map::filter_from_item(&item)); + Ok(()) + }) + .unwrap(); + let psd = photocraft_io::export(&s.active().unwrap().doc, "psd", &Default::default()).unwrap().bytes; + // The issue's flow: open the PSD, Replace Contents of the smart object. + let mut s2 = Session::new(); + s2.add_document(photocraft_io::import("pc-displace-repro.psd", &psd).unwrap().document, None); + let (sid, _) = smart(&s2.active().unwrap().doc); + let out = s2.execute("layer.smartObjects.replaceContents", json!({"layer": sid, "path": design})).unwrap(); + assert_eq!(out["warnings"], json!([]), "depth {depth}"); + let cache = smart(&s2.active().unwrap().doc).1.cache.unwrap(); + // 10 % of 128 px at full map contrast: the design (x 8..80) moves 12.8 px left. + let alpha = |x: i32| cache.pixel(x, 30)[3]; + assert!(alpha(2) > 0.99 && alpha(75) < 0.01, "depth {depth}: {} {}", alpha(2), alpha(75)); + } + std::fs::remove_dir_all(&dir).ok(); +} + /// A Perspective Warp smart filter as Photoshop writes it (`perspectiveWarpTransform`: vertices, /// warped vertices and quads of vertex indices, document pixels) opens as /// `layer.smartObjects.perspectiveWarp` and re-renders warped instead of flat (#6268), and keeps diff --git a/crates/engine/tests/pen_path_append.rs b/crates/engine/tests/pen_path_append.rs new file mode 100644 index 0000000000..41306ea6a2 --- /dev/null +++ b/crates/engine/tests/pen_path_append.rs @@ -0,0 +1,80 @@ +use photocraft_engine::Session; +use serde_json::json; + +fn session() -> Session { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + session +} + +#[test] +fn appended_work_and_saved_components_preserve_existing_geometry_and_undo() { + for name in ["work", "Saved drawing"] { + let mut session = session(); + let first = json!({"subpaths": [{"closed": false, "knots": [[20, 20], [80, 20]]}]}); + let second = json!({"subpaths": [{"closed": false, "knots": [[30, 60], [90, 60]]}]}); + session.execute("path.set", json!({"name": name, "path": first})).unwrap(); + let before = session.execute("path.info", json!({"name": name})).unwrap(); + session.execute("path.set", json!({"name": name, "path": second, "op": "combine"})).unwrap(); + let after = session.execute("path.info", json!({"name": name})).unwrap(); + assert_eq!(after["path"]["subpaths"].as_array().unwrap().len(), 2); + assert_eq!(after["path"]["subpaths"][0], before["path"]["subpaths"][0]); + session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(session.execute("path.info", json!({"name": name})).unwrap(), before); + session.execute("edit.redo", json!({})).unwrap(); + assert_eq!(session.execute("path.info", json!({"name": name})).unwrap(), after); + } +} + +#[test] +fn appending_valid_components_cannot_exceed_total_path_budget() { + let mut session = session(); + let subpath = json!({"closed": false, "knots": []}); + session.execute("path.set", json!({"path": {"subpaths": vec![subpath.clone(); 2_049]}})).unwrap(); + let before = session.active().unwrap().doc.work_path.clone(); + let history = session.active().unwrap().history.entries().len(); + let error = session.execute("path.set", json!({"path": {"subpaths": vec![subpath; 2_048]}, "op": "combine"})).unwrap_err(); + assert!(error.to_string().contains("4096")); + assert_eq!(session.active().unwrap().doc.work_path, before); + assert_eq!(session.active().unwrap().history.entries().len(), history); +} + +#[test] +fn invalid_path_coordinates_leave_work_and_saved_paths_unchanged() { + for name in ["work", "Saved drawing"] { + let mut session = session(); + session.execute("path.set", json!({"name": name, "path": {"subpaths": [{"knots": [[10, 10], [20, 20]]}]}})).unwrap(); + let before = session.execute("path.info", json!({"name": name})).unwrap(); + let history = session.active().unwrap().history.entries().len(); + assert!( + session.execute("path.set", json!({"name": name, "op": "combine", "path": {"subpaths": [{"knots": [[-1.0e308, 10], [1.0e308, 20]]}]}})).is_err() + ); + assert_eq!(session.execute("path.info", json!({"name": name})).unwrap(), before); + assert_eq!(session.active().unwrap().history.entries().len(), history); + } +} + +#[test] +fn large_straight_work_and_saved_paths_append_and_undo_without_shape_coordinate_limits() { + for name in ["work", "Saved drawing"] { + let mut session = session(); + let large = json!({"subpaths": [{"closed": true, "knots": [[0.0, 0.0], [3.0e9, 0.0], [3.0e9, 1.0e9]]}]}); + let before = session.active().unwrap().doc.clone(); + let history = session.active().unwrap().history.entries().len(); + session.execute("path.set", json!({"name":name,"path":large})).unwrap(); + let first = session.execute("path.info", json!({"name":name})).unwrap(); + assert_eq!(first["path"]["subpaths"][0]["knots"][1]["anchor"], json!([3.0e9, 0.0])); + assert_eq!(session.active().unwrap().history.entries().len(), history + 1); + session.execute("path.set", json!({"name":name,"op":"combine","path":{"subpaths":[{"knots":[[10,20],[80,20]]}]}})).unwrap(); + let appended = session.execute("path.info", json!({"name":name})).unwrap(); + assert_eq!(appended["path"]["subpaths"].as_array().unwrap().len(), 2); + assert_eq!(appended["path"]["subpaths"][0], first["path"]["subpaths"][0]); + session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(session.execute("path.info", json!({"name":name})).unwrap(), first); + session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(session.active().unwrap().doc.work_path, before.work_path); + assert_eq!(session.active().unwrap().doc.paths, before.paths); + session.execute("edit.redo", json!({})).unwrap(); + assert_eq!(session.execute("path.info", json!({"name":name})).unwrap(), first); + } +} diff --git a/crates/format/src/atomic/meta.rs b/crates/format/src/atomic/meta.rs index 10008faa9f..6e1aaa15fe 100644 --- a/crates/format/src/atomic/meta.rs +++ b/crates/format/src/atomic/meta.rs @@ -12,7 +12,7 @@ //! | extended attributes (Finder tags, `user.*`) | `copy_xattrs` | `copy_xattrs` | — | //! | "downloaded from the internet" | `com.apple.quarantine`, an xattr | — | `Zone.Identifier`, a named stream kept by [`replace_existing`] | //! | access-control list | `copy_acl` (`exacl`) | not carried over (see below) | DACL, kept by [`replace_existing`] | -//! | creation time | not carried over (#6603) | — | kept by [`replace_existing`] | +//! | creation time | `copy_created` (#9388) | — | kept by [`replace_existing`] | //! //! Everything here except [`replace_existing`] is **best effort and never touches the file's //! bytes**: a save that cannot carry a piece of metadata across is still a save, because a @@ -22,7 +22,7 @@ //! //! Not carried over, and why: Linux POSIX ACLs live in `system.posix_acl_access`, which //! `listxattr` does not report, so copying the listed attributes misses them; they would need -//! their own step. macOS creation time needs `setattrlist`, which has no safe wrapper here. +//! their own step. use std::io; use std::path::Path; @@ -59,6 +59,13 @@ pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { #[cfg(not(unix))] let attributes = Ok(()); + // The creation time before the ACL: it needs the destination open for writing, which a + // copied ACL denying its owner write access would refuse. + #[cfg(target_os = "macos")] + let created = copy_created(from, to); + #[cfg(not(target_os = "macos"))] + let created = Ok(()); + #[cfg(target_os = "macos")] let acl = copy_acl(from, to); #[cfg(not(target_os = "macos"))] @@ -67,7 +74,35 @@ pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { // A save over a 0600 file must not widen it to whatever the process default is. let permissions = std::fs::metadata(from).and_then(|m| std::fs::set_permissions(to, m.permissions())); - attributes.and(acl).and(permissions) + attributes.and(acl).and(created).and(permissions) +} + +/// The creation time ("Created" in Finder) of the file being replaced, onto the file replacing +/// it: the rename leaves a new file born at the time of the save, where Photoshop keeps the +/// original's (#9388). The rename keeps the time set here. +#[cfg(target_os = "macos")] +fn copy_created(from: &Path, to: &Path) -> io::Result<()> { + let old = std::fs::File::open(from)?; + let new = std::fs::OpenOptions::new().write(true).open(to)?; + copy_created_file(&old, &new) +} + +/// [`copy_created`] through two open files rather than their paths, for the automation write +/// path's capability-checked handles (see [`copy_xattrs`]). `to` must be open for writing. +/// Nothing to do outside macOS: Windows keeps the time in [`replace_existing`], and Linux has no +/// settable creation time. +pub fn copy_created_file(from: &std::fs::File, to: &std::fs::File) -> io::Result<()> { + #[cfg(target_os = "macos")] + { + use std::os::macos::fs::FileTimesExt; + let created = from.metadata()?.created()?; + to.set_times(std::fs::FileTimes::new().set_created(created)) + } + #[cfg(not(target_os = "macos"))] + { + let _ = (from, to); + Ok(()) + } } /// [`copy_metadata`]'s extended-attribute step, by path: open both files and hand the diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rs index bc26ae6d0a..c768044e06 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -481,3 +481,45 @@ fn a_directory_flush_the_file_system_cannot_do_still_saves() { let fs = Faulty { fail_sync_dir: Some(Ok(5)), ..Default::default() }; assert!(atomic_write_with(&fs, NO_RETRY, &p, b"newer").is_err()); } + +/// #9388: on macOS a save keeps the replaced file's creation time ("Created" in Finder), as +/// Photoshop's does; the rename would otherwise leave a file born at the time of the save. +#[cfg(target_os = "macos")] +#[test] +fn keeps_the_original_creation_time() { + use std::os::macos::fs::FileTimesExt; + let d = TempDir::new("created"); + let p = d.0.join("doc.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + // A creation time well in the past, so a reset to "now" can't pass for it. + let born = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000); + std::fs::OpenOptions::new().write(true).open(&p).unwrap().set_times(std::fs::FileTimes::new().set_created(born)).unwrap(); + assert_eq!(std::fs::metadata(&p).unwrap().created().unwrap(), born); + atomic_write(&p, b"new").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&p).unwrap().created().unwrap(), born, "the creation time survives the save"); + assert_no_temp(&d.0); +} + +/// #9401 review: a replaced file whose ACL denies its owner writing still keeps its creation +/// time. The ACL lands on the temporary file too, so the time has to be set before it is. +#[cfg(target_os = "macos")] +#[test] +fn keeps_the_creation_time_under_a_deny_write_acl() { + use std::os::macos::fs::FileTimesExt; + let d = TempDir::new("created-acl"); + let p = d.0.join("doc.psd"); + std::fs::write(&p, ORIGINAL).unwrap(); + let born = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000); + std::fs::OpenOptions::new().write(true).open(&p).unwrap().set_times(std::fs::FileTimes::new().set_created(born)).unwrap(); + let Ok(user) = std::env::var("USER") else { return }; + let deny = exacl::AclEntry::deny_user(&user, exacl::Perm::WRITE, None); + if exacl::setfacl(&[&p], &[deny], None).is_err() { + return; // a file system without ACLs: nothing to assert + } + atomic_write(&p, b"new").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&p).unwrap().created().unwrap(), born, "the creation time survives a deny-write ACL"); + let _ = exacl::setfacl(&[&p], &[], None); + assert_no_temp(&d.0); +} diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs index 8c72a20406..b71e3c8030 100644 --- a/crates/format/src/read.rs +++ b/crates/format/src/read.rs @@ -6,7 +6,10 @@ //! to 4 GiB in one `ReadFile`, and some file systems (exFAT, network redirectors) reject a read //! that large with `ERROR_INVALID_PARAMETER` ("The parameter is incorrect", #375). //! - **A clear out-of-memory error.** The buffer is reserved up front with `try_reserve_exact`, -//! and a file larger than the memory available says how much it needed. +//! and a file larger than the memory available says how much it needed. A file that grows past +//! its stat length while being read grows the buffer with `try_reserve` too. +//! - **A total limit.** No read returns more than [`MAX_OPEN_BYTES`], so a file that keeps growing +//! while it is read cannot keep an open or a save from finishing. //! //! On `wasm32` there is no file system and every call returns the `std` "unsupported" error. @@ -16,13 +19,24 @@ use std::path::Path; /// Largest single read: big enough that a 5 GB file takes under a hundred reads. pub const READ_CHUNK: usize = 64 << 20; -/// Read all of `path`, in reads of at most [`READ_CHUNK`] bytes. +/// Most bytes [`read_file`] and [`read_all`] return. Far above any document memory can hold (a +/// PSB can run to tens of gigabytes), it only bounds a file that never stops growing; a file over it +/// is a `FileTooLarge` error, never a truncated read. +pub const MAX_OPEN_BYTES: u64 = 1 << 38; + +/// Read all of `path`, in reads of at most [`READ_CHUNK`] bytes and at most [`MAX_OPEN_BYTES`] in +/// all. Anything but a regular file is an `InvalidInput` error. pub fn read_file(path: &Path) -> io::Result> { read_file_with(path, READ_CHUNK) } /// [`read_file`] with a chosen read size (tests use small ones to exercise the loop). pub fn read_file_with(path: &Path, chunk: usize) -> io::Result> { + read_path(path, chunk, MAX_OPEN_BYTES) +} + +/// [`read_file_with`] with a chosen total limit (tests use small ones). +fn read_path(path: &Path, chunk: usize, max: u64) -> io::Result> { #[cfg(unix)] let (mut f, metadata) = { use rustix::fs::{Mode, OFlags, open}; @@ -45,31 +59,73 @@ pub fn read_file_with(path: &Path, chunk: usize) -> io::Result> { (f, metadata) }; let len = metadata.len(); - read_all_with(&mut f, len, chunk) + read_all_with(&mut f, len, chunk, max) } /// Read `reader` to its end in reads of at most [`READ_CHUNK`] bytes, for an already open file /// (a capability-scoped handle, say). `size_hint` (the file's length) sizes the buffer up front. +/// More than [`MAX_OPEN_BYTES`] in all is a `FileTooLarge` error. pub fn read_all(reader: &mut impl Read, size_hint: u64) -> io::Result> { - read_all_with(reader, size_hint, READ_CHUNK) + read_all_with(reader, size_hint, READ_CHUNK, MAX_OPEN_BYTES) } -fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize) -> io::Result> { - // The hint only sizes the buffer: a file that grows or shrinks while being read is still read - // to its end. +/// Read `reader` to its end in reads of at most `chunk` bytes, failing once it has given more +/// than `max` bytes. The hint only sizes the buffer: a file that grows or shrinks while being +/// read is still read to its end, within `max`. Past the hint the buffer grows only after a probe +/// read has found more bytes, and fallibly, so a file read exactly to its stat length is never +/// over-allocated and one that outgrows memory is an `OutOfMemory` error, not an abort. +fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize, max: u64) -> io::Result> { + if size_hint > max { + return Err(too_large(max)); + } let mut buf = buffer_for(size_hint)?; - let chunk = u64::try_from(chunk.max(1)).unwrap_or(u64::MAX); - while reader.take(chunk).read_to_end(&mut buf)? > 0 {} + let chunk = chunk.max(1); + // One byte over `max` is enough to tell a file over the limit from one exactly at it. + let mut reader = reader.take(max.saturating_add(1)); + loop { + if buf.len() == buf.capacity() { + let mut probe = [0; 4096]; + let n = loop { + match reader.read(&mut probe) { + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + r => break r?, + } + }; + if n == 0 { + break; + } + let needed = buf.len() as u64 + n as u64; + buf.try_reserve(n.max(chunk)).map_err(|_| out_of_memory(needed))?; + buf.extend_from_slice(&probe[..n]); + } + let room = u64::try_from((buf.capacity() - buf.len()).min(chunk)).unwrap_or(u64::MAX); + if (&mut reader).take(room).read_to_end(&mut buf)? == 0 && buf.len() < buf.capacity() { + break; + } + } + if buf.len() as u64 > max { + return Err(too_large(max)); + } Ok(buf) } +/// The error for a file over the `max` bytes a read may return. +fn too_large(max: u64) -> io::Error { + io::Error::new(io::ErrorKind::FileTooLarge, format!("the file is larger than {} and was not read", size_text(max))) +} + +/// The `OutOfMemory` error for a read that needed `len` bytes. +fn out_of_memory(len: u64) -> io::Error { + io::Error::new(io::ErrorKind::OutOfMemory, format!("not enough memory to read the whole file ({})", size_text(len))) +} + /// An empty buffer with room for `len` bytes, or an `OutOfMemory` error saying how much was needed. pub fn buffer_for(len: u64) -> io::Result> { let mut buf = Vec::new(); let reserved = usize::try_from(len).ok().and_then(|n| buf.try_reserve_exact(n).ok()); match reserved { Some(()) => Ok(buf), - None => Err(io::Error::new(io::ErrorKind::OutOfMemory, format!("not enough memory to read the whole file ({})", size_text(len)))), + None => Err(out_of_memory(len)), } } @@ -115,6 +171,36 @@ mod tests { } } + /// Nothing over the total limit is returned (#8601): a file larger than it, a reader that + /// gives more than it whatever its hint says, and one that never ends are `FileTooLarge` + /// errors, while a file exactly at the limit is read whole. + #[test] + fn reads_stop_at_the_total_limit() { + let data: Vec = (0..10_000u32).map(|i| (i % 251) as u8).collect(); + let p = temp("limit", &data); + assert_eq!(read_path(&p, 7, data.len() as u64).unwrap(), data, "exactly at the limit"); + assert_eq!(read_path(&p, 7, data.len() as u64 - 1).unwrap_err().kind(), io::ErrorKind::FileTooLarge); + for hint in [0, 100, data.len() as u64] { + let e = read_all_with(&mut std::io::Cursor::new(&data), hint, 64, 5_000).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::FileTooLarge, "hint {hint}"); + } + let e = read_all_with(&mut std::io::Cursor::new(&data), 1 << 40, 64, 5_000).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::FileTooLarge, "a hint over the limit fails before reading"); + let e = read_all_with(&mut std::io::repeat(1), 0, 1 << 20, 3 << 20).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::FileTooLarge, "a reader that never ends"); + assert!(e.to_string().contains("3.15 MB"), "{e}"); + } + + /// A file read exactly to its stat length keeps the buffer it reserved: the end is found by a + /// probe read, without growing the buffer first. + #[test] + fn an_exact_hint_is_not_over_allocated() { + let data = vec![7u8; 100_000]; + let buf = read_all_with(&mut std::io::Cursor::new(&data), data.len() as u64, 4096, MAX_OPEN_BYTES).unwrap(); + assert_eq!(buf, data); + assert_eq!(buf.capacity(), data.len()); + } + #[test] fn empty_and_missing_files() { assert!(read_file(&temp("empty", b"")).unwrap().is_empty()); diff --git a/crates/gpu/examples/bench_stack_reuse.rs b/crates/gpu/examples/bench_stack_reuse.rs index 30745c3794..2014cee902 100644 --- a/crates/gpu/examples/bench_stack_reuse.rs +++ b/crates/gpu/examples/bench_stack_reuse.rs @@ -17,7 +17,8 @@ fn render(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc fn main() -> Result<(), Box> { let quick = std::env::args().any(|a| a == "--quick"); let size = if quick { Size::new(1024, 768) } else { Size::new(6000, 4000) }; - let adapter = pollster::block_on(wgpu::Instance::default().request_adapter(&Default::default()))?; + let adapter = + pollster::block_on(wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&Default::default()))?; let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?; let format = Compositor::preferred_acc_format(&adapter); println!("adapter={:?}, accumulation={format:?}, size={}x{}", adapter.get_info(), size.width, size.height); diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 060d12b5d9..8b7701e3c1 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1000,8 +1000,21 @@ fn fs_adjmix(in: VOut) -> @location(0) vec4 { if (op.mode == M_DISSOLVE) { return select(b, vec4(a.rgb, b.a), dissolve_noise(doc_px(p)) < k); } - let bl = blend_rgb(op.mode, b.rgb, a.rgb); - return vec4(b.rgb + (bl - b.rgb) * k, b.a); + // Fill below 100% in one of the special eight (compose::blend_back, psblend::blend_rgb_fill): + // the result pulled toward the mode's neutral colour; Hard Mix (cb - f(1 - cs)) / (1 - f). + let f = clamp(op.fill, 0.0, 1.0); + let special = f < 1.0 && fill_is_special(op.mode); + var cs = a.rgb; + if (special) { + var neutral = 0.0; + if (op.mode == 5 || op.mode == 6) { neutral = 1.0; } + if (op.mode == 16 || op.mode == 17) { neutral = 0.5; } + cs = vec3(neutral) + (a.rgb - vec3(neutral)) * f; + } + var bl = blend_rgb(op.mode, b.rgb, cs); + if (special && op.mode == 19) { bl = clamp((b.rgb - f * (vec3(1.0) - a.rgb)) / (1.0 - f), vec3(0.0), vec3(1.0)); } + // Keep bounded adjustment results exact at full coverage over HDR backdrops. + return vec4(b.rgb * (1.0 - k) + bl * k, b.a); } // Pass-through group coverage mixes premultiplied colour, then returns straight alpha. @@ -1025,8 +1038,8 @@ fn fs_lerp(in: VOut) -> @location(0) vec4 { return vec4(clamp(pm.rgb / al, vec3(0.0), vec3(1.0)), al); } if ((op.flags & F_BLEND_IF) != 0u) { - // compose::apply_blend_if: "This Layer" is C (the layer's own content with its masks), - // or B itself for an adjustment layer; "Underlying Layer" is A. + // compose::apply_blend_if: "This Layer" is C (the layer's own content with its masks, or an + // adjustment's result before Opacity, #9542), B when p4.y is set; "Underlying Layer" is A. var this_px = b; if (op.p4.y < 0.5) { this_px = textureLoad(tex_c, p, 0); @@ -1080,15 +1093,19 @@ fn blend_if_weight(this_px: vec4, under: vec4) -> f32 { if (px.a <= 0.0) { continue; } - // The CPU gets 8- and 16-bit levels exactly (k / 255 × 255 = k), but GPU arithmetic can - // land a few millionths below, which flips a hard threshold at that level: values that - // close to a level are that level. Real 8/16-bit values off a level are ≥ 1/257 away. - let raw = clamp(px.rgb, vec3(0.0), vec3(1.0)) * 255.0; - let v = select(raw, round(raw), abs(raw - round(raw)) < vec3(1e-4)); + // compose::blend_if_level: a value on a level's 16-bit step (Photoshop's 0..32768, + // round(c × 32768 / 255)) is that level, as Photoshop compares Blend If (#9521); every + // 8-bit level is on its own step, a few millionths of GPU drift included. + let x = clamp(px.rgb, vec3(0.0), vec3(1.0)); + let raw = x * 255.0; + let level = round(raw); + let v = select(raw, level, round(x * 32768.0) == round(level * 32768.0 / 255.0)); if (op.p4.x > 0.5) { k = k * bi_weight(0u, s, v.r) * bi_weight(1u, s, v.r); } else { - let gray = 0.299 * v.r + 0.587 * v.g + 0.114 * v.b; + // compose::blend_if_gray: (30 R + 59 G + 11 B) / 100, rounded half down on whole levels. + let sum = 30.0 * v.r + 59.0 * v.g + 11.0 * v.b; + let gray = select(sum / 100.0, floor((sum + 49.0) / 100.0), all(v == round(v))); k = k * bi_weight(0u, s, gray) * bi_weight(1u, s, v.r) * bi_weight(2u, s, v.g) * bi_weight(3u, s, v.b); } if (k <= 0.0) { @@ -1432,6 +1449,18 @@ fn fs_mblur(in: VOut) -> @location(0) vec4 { @fragment fn fs_mglow(in: VOut) -> @location(0) vec4 { let d = textureLoad(tex_a, local(in.pos), 0).r + 0.5; + if (op.p0.w > 0.5) { + let t = (d - op.p0.x) / op.p0.y; + var tail = 0.0; + if (t >= 0.0 && t <= 1.0) { + tail = op.p0.z * t * t * (3.0 - 2.0 * t); + } else if (t > 1.0 && t <= 2.0) { + let u = t - 1.0; + let remaining = 1.0 - u; + tail = op.p0.z * remaining * remaining * (1.0 + 2.0 * u); + } + return mout(tail); + } var m = 0.5 * clamp(1.0 - (d - op.p0.x) / op.p0.y, 0.0, 1.0); if (d <= op.p0.x) { m = 1.0; } return mout(m); @@ -1443,7 +1472,11 @@ fn fs_mglow(in: VOut) -> @location(0) vec4 { fn fs_mfinish(in: VOut) -> @location(0) vec4 { let p = local(in.pos); var v = textureLoad(tex_a, p, 0).r; - if (op.p0.x > 0.5) { v = abs(v - textureLoad(tex_b, p, 0).r); } + if (op.p0.x > 1.5) { + v = max(v, textureLoad(tex_b, p, 0).r); + } else if (op.p0.x > 0.5) { + v = abs(v - textureLoad(tex_b, p, 0).r); + } if (op.p0.y > 0.5 && op.p0.y < 1.5) { v = 1.0 - v; } if (op.p0.z > 0.5) { v = lut(0, v); } if (op.p0.y > 1.5) { v = 1.0 - v; } diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index ceff607686..4e23b7d332 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -226,6 +226,24 @@ impl B { let Some(k) = blur_kernel(size) else { return src }; self.conv(src, k) } + fn max(&mut self, a: In, b: In) -> In { + self.push(stage(Kernel::MFinish, Some(a), Some(b), [2.0, 0.0, 0.0, 0.0], 0)) + } + fn softer_glow_tail(&mut self, blur: In, size: f32, range: f32) -> In { + let width = photocraft_compose::effects::softer_glow_tail_width(size); + if width == 0.0 { + return blur; + } + let distance = self.field(FieldKind::Outside, size + width); + let tail = self.push(stage( + Kernel::MGlow, + Some(distance), + None, + [size - width, width, photocraft_compose::effects::softer_glow_tail_amplitude(range), 1.0], + 0, + )); + self.max(blur, tail) + } /// Separable convolution with a symmetric kernel `(radius, weights)` (two `MBlur` passes). fn conv(&mut self, src: In, (r, w): (i32, Vec)) -> In { if r <= 0 { diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index 39bc9c4fba..253ebe65ad 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -55,7 +55,8 @@ impl B { GlowTechnique::Softer => { // Inner glows spread 1 - alpha. let src = if inner { self.shift(In::Shape, 0.0, 0.0, 0.0, true) } else { In::Shape }; - self.spread_blur(src, (g.size, g.spread), inner, 0.0, 0.0) + let m = self.spread_blur(src, (g.size, g.spread), inner, 0.0, 0.0); + if inner { m } else { self.softer_glow_tail(m, g.size, g.range) } } }; self.finish_glow(m, fx::glow_lut(g), inner, center); diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index 1622da28e2..32bdbae8cc 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -1,6 +1,6 @@ use super::*; use photocraft_color::BlendMode; -use photocraft_doc::FxCommon; +use photocraft_doc::{FxCommon, GlowSource, GlowTechnique}; /// Filled-shape identity survives integer moves, including fractional anchors and handles. #[test] @@ -51,6 +51,36 @@ fn programs_key_on_geometry_not_colour() { assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key); } +#[test] +fn softer_outer_glow_program_keeps_the_tent_and_adds_a_distance_tail() { + let effect = Effect::OuterGlow(photocraft_doc::Glow { + common: FxCommon::new(BlendMode::Screen, 1.0), + paint: photocraft_doc::FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 60.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }); + let kernel = blur_kernel(60.0).unwrap(); + let p = program(&effect, &GlobalLight::default(), false); + let blur: Vec<_> = p.stages.iter().filter(|s| s.kernel == Kernel::MBlur).collect(); + assert_eq!(blur.len(), 2); + for stage in blur { + assert_eq!(stage.radius, kernel.0); + assert_eq!(stage.lut.as_deref().unwrap(), kernel.1.as_slice()); + } + let tail = p.stages.iter().find(|s| s.kernel == Kernel::MGlow).unwrap(); + assert_eq!(tail.a, Some(In::Field(FieldKind::Outside))); + assert_eq!(tail.p0, [54.0, 6.0, 0.0025, 1.0]); + assert!(p.stages.iter().any(|s| s.kernel == Kernel::MFinish && s.p0[0] == 2.0)); + assert!(p.fields.contains(&(FieldKind::Outside, reach_for(66.0)))); +} + /// A styled group's effect shape follows its own vector mask and its children's Blend If and /// Advanced Blending, so the cached shape must be rebuilt when any of them changes. #[test] diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 88de5a81b4..ef0924640a 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -95,7 +95,8 @@ pub const F_QUANT: u32 = 32768; pub const F_ADD_DIFF: u32 = 16384; /// `Lerp`: B mixed back towards A (the backdrop) by the layer's Blend If weight -/// (`compose::apply_blend_if`), from C ("This Layer", or B itself for an adjustment layer, `p4.y`) +/// (`compose::apply_blend_if`), from C ("This Layer": an adjustment layer's unmixed result; B when +/// `p4.y` is set) /// and A ("Underlying Layer"). The ranges are packed in `p0..p3` (`blend_if_params`); `p4.x` marks /// a one-channel document. pub const F_BLEND_IF: u32 = 524288; @@ -279,13 +280,17 @@ impl<'a> Planner<'a> { /// `compose::apply_blend_if`: `after` (the backdrop with `layer` drawn) mixed back towards /// `before` (the backdrop without it) where the layer's Blend If ranges hide it. "This Layer" - /// is the layer's own content with its masks; an adjustment layer is judged by its result. - /// Consumes both slots. + /// is the layer's own content with its masks; an adjustment layer is judged by its result at + /// full strength, before Opacity and its mask (#9542). Consumes both slots. fn blend_if(&mut self, layer: &'a Layer, before: Slot, after: Slot) -> Result { - let own = match layer.content { - LayerContent::Adjustment(_) => None, - _ => Some(self.content(layer)?), + let own = match &layer.content { + LayerContent::Adjustment(adj) => { + let b = self.retain(before); + self.adjust(adj, b)? + } + _ => self.content(layer)?, }; + let own = Some(own); let mut p = Pass::new(Kernel::Lerp, 0); p.a = Some(before); p.b = Some(after); @@ -398,7 +403,8 @@ impl<'a> Planner<'a> { let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect(); // Below 100% fill a pass-through group renders isolated (as the CPU compositor does), and - // so does one that is the base of a clipping group and holds an adjustment layer. + // so does one that is the base of a clipping group and holds an adjustment layer, or one + // with Blend If (#9554). let clip_base_adjusts = !visible_clipped.is_empty() && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); if let LayerContent::Group(g) = &layer.content @@ -406,6 +412,7 @@ impl<'a> Planner<'a> { && layer.fill_opacity >= 1.0 && !has_effects(layer) && !clip_base_adjusts + && !photocraft_compose::blend_if_active(layer, self.cx.mode) { let before = self.retain(backdrop); let mut after = self.stack(&g.children, backdrop)?; @@ -467,7 +474,7 @@ impl<'a> Planner<'a> { p.a = Some(before); p.b = Some(adjusted); p.mode = layer.blend; - p.opacity = opacity; + (p.opacity, p.fill) = adjustment_fill(layer, opacity); p.mask = self.mask_use(layer); return Ok(self.emit(p)); } @@ -732,7 +739,8 @@ impl<'a> Planner<'a> { p.a = Some(before); p.b = Some(adjusted); p.mode = layer.blend; - p.opacity = opacity; + // A clipped adjustment takes Fill as coverage in every mode. + (p.opacity, p.fill) = (opacity, 1.0); p.mask = self.mask_use(layer); return Ok(self.emit(p)); } @@ -1411,3 +1419,8 @@ impl<'a> Planner<'a> { self.emit(p) } } + +/// Adjustment Fill belongs inside the special blend modes; other modes use it as coverage. +fn adjustment_fill(layer: &Layer, opacity: f32) -> (f32, f32) { + if layer.fill_opacity < 1.0 && photocraft_compose::psblend::fill_is_special(layer.blend) { (layer.opacity, layer.fill_opacity) } else { (opacity, 1.0) } +} diff --git a/crates/gpu/tests/it/device_loss.rs b/crates/gpu/tests/it/device_loss.rs index 3875bd4a89..2e8839de12 100644 --- a/crates/gpu/tests/it/device_loss.rs +++ b/crates/gpu/tests/it/device_loss.rs @@ -12,7 +12,7 @@ use photocraft_raster::Surface; use crate::GPU_LOCK; fn device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { - let instance = wgpu::Instance::default(); + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(a) => a, Err(e) => { diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 843f082407..d22a4515d1 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -145,7 +145,10 @@ fn gpu() -> Option { /// The returned guard holds [`GPU_LOCK`] until the device is dropped. fn any_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue, std::sync::MutexGuard<'static, ()>)> { let lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let adapter = pollster::block_on(wgpu::Instance::default().request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let adapter = pollster::block_on( + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&wgpu::RequestAdapterOptions::default()), + ) + .ok()?; let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?; Some((adapter, device, queue, lock)) } @@ -636,6 +639,47 @@ fn special_eight_fill_matches_cpu() { } } +/// The same for adjustment layers (#9501): the GPU's adjustment mix takes Fill inside the special +/// eight's blend, as compose's adjustment branch does, with a mask and Opacity on top. +#[test] +fn special_eight_fill_on_adjustment_layers_matches_cpu() { + let Some(mut g) = gpu() else { return }; + let special = [ + BlendMode::ColorBurn, + BlendMode::LinearBurn, + BlendMode::ColorDodge, + BlendMode::LinearDodge, + BlendMode::VividLight, + BlendMode::LinearLight, + BlendMode::HardMix, + BlendMode::Difference, + ]; + for mode in special { + for fill in [0.3, 0.6] { + let mut d = base_doc(64, 48); + d.layers[0] = noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, 64, 48), 5, 1.0); + let mut l = Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)); + l.blend = mode; + l.opacity = 0.7; + l.fill_opacity = fill; + d.layers.push(l); + check(&mut g, &d, &format!("adjustment {mode:?} fill {fill}")); + // CodeRabbit on #9512: clipped to a pixel layer, the adjustment takes Fill as + // coverage on both paths (compose's clipped branch, the planner's `atop`). + let mut d = base_doc(64, 48); + d.layers[0] = noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, 64, 48), 5, 1.0); + d.layers.push(noise_layer("base", PixelFormat::RGBA8, Rect::from_xywh(8, 6, 40, 30), 9, 1.0)); + let mut l = Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)); + l.blend = mode; + l.opacity = 0.7; + l.fill_opacity = fill; + l.clipped = true; + d.layers.push(l); + check(&mut g, &d, &format!("clipped adjustment {mode:?} fill {fill}")); + } + } +} + #[test] fn xor_rounding_on_half_float_targets() { let Some((_adapter, device, queue, _lock)) = any_device() else { return }; @@ -855,6 +899,18 @@ fn groups_masks_and_clipping() { d.layers.extend([base, clip]); check(&mut g, &d, "clipped Dissolve opacity/fill CPU/GPU parity"); } + // #4921: a clipped Dissolve layer keeps binary coverage at partial opacity/fill. + for (opacity, fill) in [(0.4, 1.0), (0.8, 0.5)] { + let mut d = base_doc(56, 44); + let base = noise_layer("base", PixelFormat::RGBA8, Rect::new(5, 6, 48, 40), 45, 0.0); + let mut clip = noise_layer("dissolve clip", PixelFormat::RGBA8, d.bounds(), 46, 0.0); + clip.clipped = true; + clip.blend = BlendMode::Dissolve; + clip.opacity = opacity; + clip.fill_opacity = fill; + d.layers.extend([base, clip]); + check(&mut g, &d, "clipped Dissolve CPU/GPU parity"); + } // Clipped group base (isolated) with a clipped layer. let mut d = base_doc(56, 44); let mut gb = Layer::group("gb", vec![child(18, BlendMode::Normal)]); @@ -2199,6 +2255,8 @@ fn blend_if() { // An adjustment judged by its result, and a clipped layer. let mut adj = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)); adj.blend_if.set(e, pair); + // Judged by its result before Opacity (#9542). + adj.opacity = 0.4; d.layers[1] = l.clone(); d.layers[1].blend_if = Default::default(); d.layers.push(adj); @@ -2218,6 +2276,25 @@ fn blend_if() { check(&mut g, &d, "gray blend if"); } +/// A Pass Through group with Blend If renders isolated on the GPU as on the CPU (#9554): an +/// adjustment inside it leaves the layers beneath alone. +#[test] +fn pass_through_group_with_blend_if_is_isolated() { + use photocraft_doc::BlendRange; + let Some(mut g) = gpu() else { return }; + for gated in [true, false] { + let mut d = base_doc(64, 48); + d.layers[0] = noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, 64, 48), 5, 1.0); + let mut grp = Layer::group("group", vec![Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]); + grp.blend = BlendMode::PassThrough; + if gated { + grp.blend_if.set(1, [BlendRange::FULL, BlendRange { black: [0, 0], white: [110, 110] }]); + } + d.layers.push(grp); + check(&mut g, &d, &format!("pass-through group, Blend If {gated}")); + } +} + #[test] fn channel_restrictions() { let Some(mut g) = gpu() else { return }; @@ -3131,6 +3208,33 @@ fn pass_through_clipping_base_with_an_adjustment() { check(&mut g, &d, "pass-through clipping base with an adjustment"); } +/// Dissolve's adjustment/effect decisions use document coordinates, even in offset regions +/// and in the paged compositor. The clipped path comes from #4992. +#[test] +fn dissolve_adjustments_and_effects_match_cpu_in_offset_regions() { + let Some(mut g) = gpu() else { return }; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for effects in [false, true] { + let mut d = Document::new("Dissolve", Size::new(300, 280), ColorMode::Rgb, depth); + d.layers.push(noise_layer("base", d.pixel_format(), Rect::new(0, 0, 300, 280), 19, 0.4)); + let mut layer = if effects { + let mut l = noise_layer("effect", d.pixel_format(), Rect::new(-8, 13, 290, 270), 27, 0.6); + l.effects.items = vec![Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 0.7), color: Color::rgb(0.2, 0.8, 0.4) }]; + l + } else { + Layer::new("adjustment", LayerContent::Adjustment(Adjustment::Invert)) + }; + layer.blend = BlendMode::Dissolve; + layer.opacity = 0.37; + layer.mask = Some(mask(Rect::new(11, 7, 287, 265), 43, 0.0)); + d.layers.push(layer); + let label = format!("Dissolve effects={effects} {depth:?}"); + fx_check(&mut g, &d, &label); + diff_rect(&mut g, &d, Rect::new(17, 23, 281, 269), &label).unwrap(); + } + } +} + /// Transparency Shapes Layer off changes the special eight's blend (the layer's alpha blends as /// Fill, #5692); the GPU has no pass for it and leaves such documents to the CPU. Other modes look /// the same either way and stay on the GPU. @@ -3240,6 +3344,61 @@ fn dissolve_clipped_adjustment_matches_cpu() { } } +/// Integration of #9509 and #9512: coverage endpoints, Fill, masks and clipping share the CPU oracle. +#[test] +fn integration_adjustment_fill_opacity_masks_and_hdr_match_cpu() { + let Some(mut g) = gpu() else { return }; + for clipped in [false, true] { + for mode in [BlendMode::Normal, BlendMode::ColorDodge, BlendMode::LinearBurn] { + for fill in [0.0, 0.5, 1.0] { + for opacity in [0.5, 1.0] { + for coverage in [0.5, 1.0] { + let mut d = Document::new("combined adjustment", Size::new(1, 1), ColorMode::Rgb, SampleType::F32); + let mut base = Layer::raster("base", PixelFormat::RGBA32F); + base.surface_mut().unwrap().write_pixel(0, 0, &[0.25, 0.5, 0.75, 1.0]); + let look = Adjustment::ColorLookup { + name: "half".into(), + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + size: 2, + tetrahedral: false, + dither: false, + source: None, + }; + let mut layer = Layer::new("adjust", LayerContent::Adjustment(look)); + layer.blend = mode; + layer.clipped = clipped; + layer.fill_opacity = fill; + layer.opacity = opacity; + let mut mask = LayerMask::reveal_all(); + mask.surface = photocraft_raster::Surface::with_default( + PixelFormat { mode: ColorMode::Grayscale, sample: SampleType::F32, alpha: false }, + &[coverage], + ); + layer.mask = Some(mask); + d.layers = vec![base, layer]; + check(&mut g, &d, &format!("combined {mode:?} fill={fill} opacity={opacity} mask={coverage} clipped={clipped}")); + } + } + } + } + } + // The existing GPU harness requires float32 accumulation. The CPU regression separately + // covers 1e8 inputs, beyond the range of half-float source textures on some adapters. + let mut d = Document::new("HDR full coverage", Size::new(1, 1), ColorMode::Rgb, SampleType::F32); + let mut base = Layer::raster("HDR", PixelFormat::RGBA32F); + base.surface_mut().unwrap().write_pixel(0, 0, &[1.0e4, 1.0e4, 1.0e4, 1.0]); + let look = Adjustment::ColorLookup { + name: "half".into(), + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + size: 2, + tetrahedral: false, + dither: false, + source: None, + }; + d.layers = vec![base, Layer::new("lookup", LayerContent::Adjustment(look))]; + check(&mut g, &d, "HDR full coverage with bounded result"); +} + /// Siblings share only immutable GPU objects, not resident pages or document caches. #[test] fn sibling_compositors_have_independent_residency_and_configuration() { diff --git a/crates/gpu/tests/it/timing.rs b/crates/gpu/tests/it/timing.rs index 76348695c5..68ebc9d0be 100644 --- a/crates/gpu/tests/it/timing.rs +++ b/crates/gpu/tests/it/timing.rs @@ -38,7 +38,7 @@ fn block_on(f: F) -> F::Output { /// A real GPU with timestamp queries, or `None` with the reason printed. fn gpu() -> Option<(wgpu::Device, wgpu::Queue, Compositor)> { let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; - let Ok(adapter) = block_on(wgpu::Instance::default().request_adapter(&options)) else { + let Ok(adapter) = block_on(wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&options)) else { eprintln!("SKIP gpu timing: no adapter"); return None; }; diff --git a/crates/gpu/tests/it/uniform_limits.rs b/crates/gpu/tests/it/uniform_limits.rs index 90dfa57aed..e562a8ca9d 100644 --- a/crates/gpu/tests/it/uniform_limits.rs +++ b/crates/gpu/tests/it/uniform_limits.rs @@ -20,7 +20,7 @@ fn fills_size(count: usize, size: Size) -> Document { } fn constrained_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { - let instance = wgpu::Instance::default(); + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(adapter) => adapter, Err(error) => { diff --git a/crates/gpu/tests/it/vector_mask.rs b/crates/gpu/tests/it/vector_mask.rs index d0d7e7a012..feb8597b8e 100644 --- a/crates/gpu/tests/it/vector_mask.rs +++ b/crates/gpu/tests/it/vector_mask.rs @@ -6,7 +6,7 @@ use photocraft_doc::{Adjustment, Document, Effect, Layer, LayerContent, LayerMas use photocraft_geom::Rect; fn gpu() -> Option<(wgpu::Device, wgpu::Queue, photocraft_gpu::Compositor)> { - let instance = wgpu::Instance::default(); + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?; // Exact comparison needs 32-bit float targets (see parity.rs); skip on adapters without them. diff --git a/crates/io/src/displace_map.rs b/crates/io/src/displace_map.rs index 48b34c4b01..792c8e72df 100644 --- a/crates/io/src/displace_map.rs +++ b/crates/io/src/displace_map.rs @@ -10,10 +10,14 @@ //! width * height bytes (horizontal map, vertical map), then padding //! ``` //! +//! Photoshop does not always embed the map: a Displace can carry only `DspF`, a `Pth ` to the map +//! file (ag-psd models the filter with no `DspD` at all), and Photoshop reads that file again. Such +//! a filter imports with the path as its `mapPath`, read on re-render like any stored path (#9162). +//! //! The whole `filterFX` item (with the map) is kept verbatim in the params as a template //! ([`TEMPLATE_KEY`]), so the filter re-renders, survives `.pcraft` and is written back to PSD -//! with only the editable settings replaced. Anything else (another mode, a missing or truncated -//! map, unknown enum values) stays an opaque [`super::UNSUPPORTED_FILTER`]. +//! with only the editable settings replaced. Anything else (another mode, a truncated map, no map +//! and no readable path, unknown enum values) stays an opaque [`super::UNSUPPORTED_FILTER`]. use std::sync::Arc; @@ -80,6 +84,35 @@ fn fltr_map(item: &Descriptor) -> Option> { } } +/// The map file `DspF` names, when it is a `Pth `: `txtu`, u32 LE total size (`12 + 2 * units`), +/// u32 LE count of UTF-16 units, then the UTF-16LE path ending in one NUL (ag-psd's layout). A +/// record whose size disagrees with its units, or that lacks the NUL, is not trusted as a path. A +/// Mac alias (`alis`) is not decoded. +fn fltr_path(item: &Descriptor) -> Option { + let Value::Path(b) = get_desc(item, "Fltr")?.get("DspF")? else { return None }; + let u32_at = |i: usize| usize::try_from(u32::from_le_bytes(b.get(i..i.checked_add(4)?)?.try_into().ok()?)).ok(); + if b.get(..4)? != b"txtu" { + return None; + } + let (size, units) = (u32_at(4)?, u32_at(8)?); + if size != 12usize.checked_add(units.checked_mul(2)?)? || b.len() != size { + return None; + } + let text: Vec = b.get(12..)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let (&0, path) = text.split_last()? else { return None }; + let path = String::from_utf16(path).ok()?; + (!path.is_empty() && !path.contains('\0')).then_some(path) +} + +/// The `DspF` path a Displace reads its map from, only when no `DspD` is embedded at all: a +/// damaged embedded map keeps the filter opaque rather than falling back to the path. +fn path_only(item: &Descriptor) -> Option { + if get_desc(item, "Fltr")?.get(MAP_KEY).is_some() { + return None; + } + fltr_path(item) +} + fn lookup<'a>(table: &[(&[u8], &'a str)], v: &[u8]) -> Option<&'a str> { table.iter().find(|(k, _)| *k == v).map(|(_, s)| *s) } @@ -95,14 +128,17 @@ fn settings(f: &Descriptor) -> Option { })) } -/// `filter.distort.displace` params for a Displace item with an embedded map. +/// `filter.distort.displace` params for a Displace item with an embedded map, or else a map file +/// path (then `mapPath`). pub(super) fn import_params(item: &Descriptor) -> Option { let f = get_desc(item, "Fltr")?; if !f.class_id.is(CLASS) { return None; } let mut params = settings(f)?; - fltr_map(item)?; + if fltr_map(item).is_none() { + params.as_object_mut()?.insert("mapPath".into(), json!(path_only(item)?)); + } // Neutral blending in the template: the model's own fields replace it on export. let mut template = item.clone(); let neutral = SmartFilter { command: String::new(), params: J::Null, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; @@ -112,7 +148,7 @@ pub(super) fn import_params(item: &Descriptor) -> Option { Some(params) } -/// The template item of `params`, checked to be a Displace filter with a readable map. +/// The template item of `params`, checked to be a Displace filter with a readable map or map path. fn template(params: &J) -> Result { let raw = params.get(TEMPLATE_KEY).ok_or("a Displace map from a file or document is not written to PSD")?; let raw = raw.as_str().ok_or("the Displace PSD data must be hex text")?; @@ -121,8 +157,8 @@ fn template(params: &J) -> Result { } let bytes = from_hex(raw).ok_or("the Displace PSD data is not valid hex")?; let item = Descriptor::from_bytes(&bytes).map_err(|e| format!("the Displace PSD data is unreadable ({e})"))?; - if !item.class_id.is("filterFX") || int(&item, "filterID") != Some(FILTER_ID) || fltr_map(&item).is_none() { - return Err("the Displace PSD data is not a Displace filter with an embedded map".into()); + if !item.class_id.is("filterFX") || int(&item, "filterID") != Some(FILTER_ID) || (fltr_map(&item).is_none() && path_only(&item).is_none()) { + return Err("the Displace PSD data is not a Displace filter with an embedded map or map file".into()); } Ok(item) } @@ -130,10 +166,18 @@ fn template(params: &J) -> Result { /// The `filterFXList` item: the template with the current scales, fit and undefined areas. pub(super) fn export_item(params: &J) -> Result { let object = params.as_object().ok_or("Displace parameters must be an object")?; - if let Some(k) = object.keys().find(|k| !super::is_meta(k) && !["horizontal", "vertical", "fit", "undefinedAreas"].contains(&k.as_str())) { + let mut item = template(params)?; + // The `mapPath` imported from the template's own `DspF` is already in it; another one isn't. + // A path-only template also needs that `mapPath`: without it the filter renders no map while + // the PSD would still name one. + let template_path = path_only(&item); + if template_path.is_some() && params.get("mapPath").and_then(J::as_str) != template_path.as_deref() { + return Err("a Displace that reads its map from a file needs that file as `mapPath` to be written to PSD".into()); + } + let own_path = |k: &str| k == "mapPath" && template_path.is_some(); + if let Some(k) = object.keys().find(|k| !super::is_meta(k) && !own_path(k) && !["horizontal", "vertical", "fit", "undefinedAreas"].contains(&k.as_str())) { return Err(format!("Displace setting `{k}` has no PSD equivalent next to its embedded map")); } - let mut item = template(params)?; let mut f = get_desc(&item, "Fltr").ok_or("the Displace PSD data has no filter")?.clone(); let scale = |k: &str, d: f64| -> Result { let v = params.get(k).map_or(Some(d), J::as_f64).filter(|v| v.is_finite()).ok_or(format!("Displace `{k}` must be a number"))?; @@ -385,6 +429,69 @@ mod tests { } } + /// A `Pth ` value as ag-psd reads it: `txtu`, sizes (LE), UTF-16LE path with a trailing NUL. + fn pth(path: &str) -> Value { + let units: Vec = path.encode_utf16().chain([0]).collect(); + let mut b = b"txtu".to_vec(); + b.extend((12 + 2 * units.len() as u32).to_le_bytes()); + b.extend((units.len() as u32).to_le_bytes()); + b.extend(units.iter().flat_map(|u| u.to_le_bytes())); + Value::Path(b) + } + + /// #9162: Photoshop can save a Displace with only `DspF`, the map file's path, and no + /// embedded map. It imports as Displace reading that file, and writes back unchanged. + #[test] + fn a_map_named_only_by_its_path_imports_as_map_path() { + let with_file = |file: Value| { + let mut i = item(Vec::new()); + let mut f = get_desc(&i, "Fltr").unwrap().clone(); + f.items.retain(|(k, _)| !k.is(MAP_KEY)); + set(&mut f, "DspF", file); + set(&mut i, "Fltr", Value::Descriptor(f)); + i + }; + let src = with_file(pth("C:\\maps\\repro-map.psd")); + let f = filter_from_item(&src); + assert_eq!(f.command, COMMAND); + assert_eq!(f.params["mapPath"], json!("C:\\maps\\repro-map.psd")); + assert!(embedded_map(&f.params).is_none()); + assert_eq!(item_for_filter(&f).unwrap(), src, "written back as it was"); + let mut moved = f.clone(); + moved.params["mapPath"] = json!("/elsewhere/map.png"); + assert!(item_for_filter(&moved).is_err(), "another map path has no place in the template"); + let mut no_path = f.clone(); + no_path.params.as_object_mut().unwrap().remove("mapPath"); + assert!(item_for_filter(&no_path).is_err(), "a path-only template needs its mapPath, or the PSD names a map the render never read"); + // A record whose size field disagrees with its units, or without the final NUL. + let mut wrong_size = pth("map.psd"); + if let Value::Path(b) = &mut wrong_size { + b[4] = b[4].wrapping_add(2); + } + let mut no_nul = b"txtu".to_vec(); + no_nul.extend(16u32.to_le_bytes()); + no_nul.extend(2u32.to_le_bytes()); + no_nul.extend([b'a', 0, b'b', 0]); + // Not a path we can read: kept opaque, as before. + for bad in [ + Value::Path(b"txtu".to_vec()), + Value::Path(b"abcd\0\0\0\0\x02\0\0\0a\0\0\0".to_vec()), + Value::Path(b"txtu\0\0\0\0\x09\0\0\0a\0".to_vec()), + pth(""), + wrong_size, + Value::Path(no_nul), + ] { + let src = with_file(bad); + assert_eq!(filter_from_item(&src).command, UNSUPPORTED_FILTER); + } + // A damaged embedded map is never replaced by a readable path. + let mut damaged = item(vec![0; 4]); + let mut fltr = get_desc(&damaged, "Fltr").unwrap().clone(); + set(&mut fltr, "DspF", pth("C:\\maps\\repro-map.psd")); + set(&mut damaged, "Fltr", Value::Descriptor(fltr)); + assert_eq!(filter_from_item(&damaged).command, UNSUPPORTED_FILTER); + } + #[test] fn bad_exports_report_errors() { let ok = filter_from_item(&item(tdta(2, 2, |_| 0, |_| 0, 0))).params; diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs index 175ce73c94..0c7f60154f 100644 --- a/crates/io/src/effects_map.rs +++ b/crates/io/src/effects_map.rs @@ -128,14 +128,48 @@ fn contour(d: &Descriptor, key: &str) -> Contour { let linear = points.len() == 2 && points[0].input == 0.0 && points[0].output == 0.0 && points[1].input == 1.0 && points[1].output == 1.0; if points.is_empty() || (linear && (name.is_empty() || name == "Linear")) { Contour::Linear } else { Contour::Custom { name, points, corners } } } + +/// Indices of the contour points a PSD keeps, in order: all of them up to [`PSD_CONTOUR_POINTS`], +/// else both ends and then, one at a time, the point farthest (in output) from the line between +/// the kept points around it, so peaks and valleys (Ring - Double's two rings) survive. +fn psd_contour_points(points: &[CurvePoint]) -> Vec { + if points.len() <= PSD_CONTOUR_POINTS { + return (0..points.len()).collect(); + } + let mut kept = vec![0, points.len() - 1]; + while kept.len() < PSD_CONTOUR_POINTS { + let mut farthest: Option<(f32, usize)> = None; + for pair in kept.windows(2) { + let &[a, b] = pair else { continue }; + let (Some(pa), Some(pb)) = (points.get(a), points.get(b)) else { continue }; + let span = pb.input - pa.input; + for (i, p) in points.iter().enumerate().take(b).skip(a + 1) { + // Only equal inputs (a vertical step) have no span: inputs a few ulps apart still do. + let t = if span != 0.0 && span.is_finite() { (p.input - pa.input) / span } else { 0.0 }; + let off = (p.output - (pa.output + t * (pb.output - pa.output))).abs(); + if off.is_finite() && farthest.is_none_or(|(f, _)| off > f) { + farthest = Some((off, i)); + } + } + } + let Some((_, i)) = farthest else { break }; + kept.insert(kept.partition_point(|&k| k < i), i); + } + kept +} + +/// The most points Photoshop reads in an effect's contour (`ShpC` › `Crv `): a layer whose effects +/// carry a longer one fails to load ("A problem was encountered reading layer … program error"), +/// and Photoshop then drops all of its effects; 16 loads (#9556). +const PSD_CONTOUR_POINTS: usize = 16; fn contour_value(c: &Contour) -> Value { let (name, points) = match c { Contour::Linear => ("Linear".to_string(), vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 1.0 }]), Contour::Custom { name, points, .. } => (name.clone(), points.clone()), }; - let pts = points - .iter() - .enumerate() + let pts = psd_contour_points(&points) + .into_iter() + .filter_map(|i| points.get(i).map(|p| (i, p))) .map(|(i, p)| { let d = Descriptor::new("CrPt").with("Hrzn", Value::Double(f64::from(p.input * 255.0))).with("Vrtc", Value::Double(f64::from(p.output * 255.0))); // Photoshop writes no `Cnty` (continuity) on smooth points; a corner carries `Cnty` false. diff --git a/crates/io/src/effects_map/tests.rs b/crates/io/src/effects_map/tests.rs index d2488ae82e..5a43cd194e 100644 --- a/crates/io/src/effects_map/tests.rs +++ b/crates/io/src/effects_map/tests.rs @@ -112,6 +112,47 @@ fn sample_effects() -> Vec { ] } +/// #9556: Photoshop drops every effect of a layer whose contour has more than 16 points. A +/// 29-point contour with two rings is written as 16 points that keep both ends and both peaks; +/// up to 16 points are written as they are. +#[test] +fn psd_contours_keep_at_most_16_points_and_their_peaks() { + let points: Vec = (0..29) + .map(|i| { + let x = i as f32 / 28.0; + // Rings at x = 0.25 and 0.75, small wiggles between. + let y = (1.0 - ((x - 0.25).abs() * 8.0)).max(0.0).max(1.0 - (x - 0.75).abs() * 8.0) + if i % 2 == 0 { 0.0 } else { 0.01 }; + CurvePoint { input: x, output: y.clamp(0.0, 1.0) } + }) + .collect(); + let c = Contour::Custom { name: "Two rings".into(), points: points.clone(), corners: vec![false; 29] }; + let out = crv(&contour_value(&c)); + assert_eq!(out.len(), 16); + assert_eq!(out.first().copied(), Some((0.0, f64::from(points[0].output) * 255.0))); + assert_eq!(out.last().map(|p| p.0), Some(255.0)); + let peak = |x: f32| out.iter().any(|p| ((p.0 / 255.0) as f32 - x).abs() < 0.03 && p.1 > 240.0); + assert!(peak(0.25) && peak(0.75), "both rings kept: {out:?}"); + assert!(out.windows(2).all(|w| w[0].0 < w[1].0), "in order: {out:?}"); + + let short = Contour::Custom { name: "Short".into(), points: points[..16].to_vec(), corners: vec![false; 16] }; + assert_eq!(crv(&contour_value(&short)).len(), 16); +} + +fn crv(v: &Value) -> Vec<(f64, f64)> { + let Value::Descriptor(d) = v else { panic!("ShpC") }; + let Some(Value::List(pts)) = d.get("Crv ") else { panic!("Crv ") }; + pts.iter() + .map(|p| { + let Value::Descriptor(p) = p else { panic!("CrPt") }; + let n = |k: &str| match p.get(k) { + Some(Value::Double(x)) => *x, + _ => panic!("{k}"), + }; + (n("Hrzn"), n("Vrtc")) + }) + .collect() +} + fn approx(a: &[Effect], b: &[Effect]) { // Colours go through 0..255 doubles; compare via re-serialization. assert_eq!(a.len(), b.len()); @@ -368,3 +409,22 @@ fn lrfx_drop_shadow() { other => panic!("{other:?}"), } } + +/// CodeRabbit on #9590: inputs closer than `f32::EPSILON` but distinct are still a span. A point +/// on the straight line between two such inputs isn't mistaken for a bend and kept in place of a +/// genuine one. +#[test] +fn a_point_on_a_tiny_straight_span_is_not_a_bend() { + let p = |input: f32, output: f32| CurvePoint { input, output }; + // Three distinct inputs a few ulps apart near 0.5, on a straight rise from 0 to 1. + let (a, b) = (0.5_f32, f32::from_bits(0.5_f32.to_bits() + 2)); + let mid = f32::from_bits(0.5_f32.to_bits() + 1); + let mut points = vec![p(0.0, 0.0), p(0.2, 0.0)]; + points.extend([p(a, 0.0), p(mid, 0.5), p(b, 1.0)]); + // Fourteen gentle bends after it, each one a real (if small) peak. + points.extend((0..14).map(|k| p(0.55 + k as f32 * 0.03, if k % 2 == 0 { 1.0 } else { 0.9 }))); + points.push(p(1.0, 1.0)); + let kept = psd_contour_points(&points); + assert_eq!(kept.len(), 16); + assert!(!kept.contains(&3), "the point on the tiny straight span was kept over a real bend: {kept:?}"); +} diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 35190a9880..975a988e95 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -730,6 +730,17 @@ fn prepare_flat(mut img: Image, format: Format, warnings: &mut Vec) -> R img = gray; warnings.push(format!("colours converted to sGray; {format:?} can't embed the document's colour profile")); } + } else if img.icc.is_none() { + // An untagged document is in the default working space for its mode, which is how the + // canvas shows it and what Photoshop embeds for it (#9325): sRGB, and for gray the Dot + // Gain 20 %-compatible working gray (not sGray, which would show the same samples + // darker). A JPEG or PNG with Embed Color Profile then says so instead of leaving + // viewers to guess. The codec still leaves it out when embedding is off. + if img.layout().is_rgb() { + img.icc = Some(Builtin::Srgb.profile().to_bytes().to_vec()); + } else if img.layout().is_gray() { + img.icc = Some(Builtin::DotGain20Compat.profile().to_bytes().to_vec()); + } } Ok(img) } @@ -1235,6 +1246,69 @@ mod cmyk_band_tests { } } +#[cfg(test)] +mod assumed_profile_tests { + use super::*; + use photocraft_cms::{Builtin, Profile}; + use photocraft_color::Color; + + fn doc(mode: ColorMode) -> Document { + Document::with_background("t", Size::new(16, 12), mode, SampleType::U8, Color::rgba(0.78, 0.39, 0.2, 1.0)) + } + + fn embedded(r: &ExportResult) -> Option { + codecs::decode(&r.bytes).unwrap().icc.map(|b| Profile::parse(&b).unwrap().description) + } + + #[test] + fn streamed_png_keeps_the_same_assumed_profile_and_pixels() { + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + for embed in [false, true] { + let d = doc(mode); + let mut opts = ExportOptions::default(); + opts.encode.embed_icc = embed; + let whole = export_flat(&d, Format::Png, &opts).unwrap(); + let streamed = export_png_streamed(&d, &opts, &photocraft_raster::Interrupt::NONE, 3).unwrap(); + assert_eq!(embedded(&streamed), embedded(&whole)); + let expected = if mode == ColorMode::Rgb { Builtin::Srgb } else { Builtin::DotGain20Compat }; + assert_eq!(embedded(&streamed), embed.then(|| expected.description().to_string())); + let a = codecs::decode(&whole.bytes).unwrap(); + let b = codecs::decode(&streamed.bytes).unwrap(); + assert_eq!((a.dimensions(), a.layout(), a.sample_type()), (b.dimensions(), b.layout(), b.sample_type())); + assert_eq!(a.data(), b.data()); + } + } + } + + /// #9325: an untagged document is in the profile assumed for its mode, and Photoshop embeds + /// that (sRGB IEC61966-2.1 for a new or untagged RGB document) when the profile is embedded. + #[test] + fn untagged_documents_embed_the_profile_they_are_assumed_to_be_in() { + let opts = ExportOptions::default(); + assert!(opts.encode.embed_icc); + for ext in ["jpg", "png", "tif", "webp"] { + let r = crate::export(&doc(ColorMode::Rgb), ext, &opts).unwrap(); + assert_eq!(embedded(&r).as_deref(), Some(Builtin::Srgb.description()), "{ext}"); + } + // #9342 review: an untagged gray document shows through the default working gray (Dot + // Gain 20 %-compatible), so that is the profile its samples are tagged with, not sGray + // (which would show them darker than the canvas). + let r = crate::export(&doc(ColorMode::Grayscale), "png", &opts).unwrap(); + assert_eq!(embedded(&r).as_deref(), Some(Builtin::DotGain20Compat.description())); + // Embed Color Profile off: still none. + let mut off = ExportOptions::default(); + off.encode.embed_icc = false; + assert_eq!(embedded(&crate::export(&doc(ColorMode::Rgb), "jpg", &off).unwrap()), None); + // A format without profiles gets no warning about one. + let r = crate::export(&doc(ColorMode::Rgb), "bmp", &opts).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("profile")), "{:?}", r.warnings); + // A tagged document keeps its own profile. + let mut p3 = doc(ColorMode::Rgb); + p3.icc_profile = Some(Arc::new(Builtin::DisplayP3.profile().to_bytes().to_vec())); + assert_eq!(embedded(&crate::export(&p3, "jpg", &opts).unwrap()).as_deref(), Some(Builtin::DisplayP3.description())); + } +} + #[cfg(test)] mod streamed_png_tests { use super::*; diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index c6f8539106..23319de097 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -840,7 +840,9 @@ impl Ex { return Err(format!("the linked file {path} is not read for this export")); } let file = crate::doc_path::resolve(path, self.document.as_deref()).map_err(|e| format!("the linked file {path} is not opened: {e}"))?; - let bytes = std::fs::read(file).map_err(|e| format!("the linked file {path} can't be read: {e}"))?; + // Regular files only, in bounded reads: a link to a FIFO would block the save + // and one to a device such as `/dev/zero` would never end (#8601). + let bytes = photocraft_format::read_file(&file).map_err(|e| format!("the linked file {path} can't be read: {e}"))?; let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string(); let source = self.embed(sm.contents_id, &name, &bytes, true)?; self.warnings.push(format!("the linked smart object {name} was embedded (PSD export keeps no external links)")); diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index c9e68fd028..f6c36c2d42 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -174,7 +174,9 @@ fn export_supported_document( let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); for (sig, key, data) in preserved { - if txt2.is_some() && key == *b"Txt2" { + // With no type layers left the opened file's `Txt2` describes text that is gone (fonts and + // layout caches, often most of the file): Photoshop drops it, and so does the save (#9563). + if key == *b"Txt2" && (txt2.is_some() || text_layers.is_empty()) { continue; } // A kept layer block (one the import could not read, #2700) describes layers the diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index af7c8a2241..effa34a10a 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -196,6 +196,21 @@ fn layer_block_follows_a_kept_merged_transparency_marker() { assert!(matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { index: 0, .. })); } +/// #9563: a `Txt2` kept from the opened file is dropped once no type layer is left (Photoshop +/// drops it too); with a type layer the block is still written. +#[test] +fn a_kept_txt2_goes_with_the_last_type_layer() { + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(Surface::new(doc.pixel_format())))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Txt2", std::sync::Arc::new(b"<< /0 << /1 (stale) >> >>".to_vec()))]; + let file = document_to_psd(&doc); + assert!(!file.global_blocks.iter().any(|b| b.key == *b"Txt2"), "no type layers: no Txt2"); + + doc.layers.push(Layer::new("T", LayerContent::Text(photocraft_doc::TextLayer::default()))); + let file = document_to_psd(&doc); + assert!(file.global_blocks.iter().any(|b| b.key == *b"Txt2"), "a type layer keeps its Txt2"); +} + /// A merged-transparency marker kept from the opened file describes that file's composite. /// Saved with an opaque composite, it would make the first alpha channel read back as the /// merged transparency, and the channel would be gone: the save drops it. @@ -568,3 +583,38 @@ fn alpha_names_count_the_merged_transparency() { assert_eq!(back.channels[0].name, "Alpha 1"); assert!((back.channels[0].opacity - 0.5).abs() < 1e-6); } + +/// A linked smart object whose path names a FIFO is not read (#8601): opening a FIFO for +/// reading blocks until a writer appears, and a device such as `/dev/zero` never ends, so the +/// export would hang or run out of memory. The export finishes and writes the layer as pixels, +/// saying why. The export runs on its own thread so that a regression fails here instead of +/// hanging the test run. +#[cfg(unix)] +#[test] +fn a_linked_fifo_is_not_read() { + let dir = std::env::temp_dir().join(format!("photocraft-linked-fifo-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fifo = dir.join("link.png"); + let _ = std::fs::remove_file(&fifo); + assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success(), "mkfifo failed"); + let mut doc = document(8, 6); + let smart = photocraft_doc::SmartObject { + contents_id: SmartContentsId::fresh(), + source: photocraft_doc::SmartSource::Linked { path: fifo.to_string_lossy().into_owned() }, + transform: photocraft_geom::Affine::IDENTITY, + smart_filters: vec![], + cache: Some(Surface::new(doc.pixel_format())), + psd_raw: None, + filters_enabled: true, + filter_mask: None, + warp: None, + stack_mode: None, + perspective: None, + }; + doc.layers.push(Layer::new("Linked", LayerContent::Smart(smart))); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(document_to_psd_with(&doc, &PsdExportOptions::default()).1)); + let warnings = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the export blocked reading the FIFO"); + let _ = std::fs::remove_dir_all(&dir); + assert!(warnings.iter().any(|w| w.contains("smart object written as pixels") && w.contains("not a regular file")), "{warnings:?}"); +} diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index a88773e05c..19cc08b3f8 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -498,7 +498,7 @@ impl Ctx<'_> { let parsed = (!block.is_foreign_order()) .then(|| { photocraft_text::psd::text_layer_from_tysh(&block.data, self.dpi).or_else(|| { - let (text, transform) = blocks::parse_tysh(&block.data).unwrap_or_default(); + let (text, transform) = blocks::parse_tysh(&block.data)?; photocraft_text::psd::transform_is_safe(&transform).then(|| TextLayer { text, transform, ..Default::default() }) }) }) diff --git a/crates/io/tests/it/color.rs b/crates/io/tests/it/color.rs index 06b5134e17..15453a2518 100644 --- a/crates/io/tests/it/color.rs +++ b/crates/io/tests/it/color.rs @@ -180,6 +180,53 @@ fn rgb_fill_colours_separate_through_the_document_cmyk_profile() { } } +#[test] +fn cmyk_merged_composite_reads_through_the_embedded_profile() { + // The merged image of a CMYK file tagged with a non-default profile is turned into RGB through + // that profile, as the layers are, or every comparison against it is off (#3778). + use photocraft_cms::{Intent, Transform}; + use photocraft_psd::{Compression, ImageResource, Version, testgen}; + let profile = photocraft_cms::synth::cmyk_profile(&photocraft_cms::synth::CmykParams { + tvi: [0.26, 0.26, 0.26, 0.3], + grid_a2b: 5, + grid_b2a: 9, + ..Default::default() + }); + let reference = |p: &Profile, ink: &[f32; 4]| { + let t = Transform::new(p, Builtin::Srgb.profile(), Intent::RelativeColorimetric, true).unwrap(); + let mut o = [0.0f32; 4]; + t.eval(ink, &mut o); + [o[0].clamp(0.0, 1.0), o[1].clamp(0.0, 1.0), o[2].clamp(0.0, 1.0)] + }; + for depth in [8u16, 16] { + let mut f = testgen::merged_only(Version::Psd, photocraft_psd::ColorMode::Cmyk, depth, Compression::Raw, 4, 1); + let inks: [[f32; 4]; 4] = [[0.1, 0.6, 0.7, 0.05], [0.8, 0.2, 0.1, 0.0], [0.3, 0.3, 0.3, 0.5], [0.0, 0.0, 0.0, 0.0]]; + let max = if depth == 8 { 255.0 } else { 65535.0 }; + let mut data = Vec::new(); + for c in 0..4 { + for ink in &inks { + // PSD stores CMYK inverted: full scale is no ink. + let v = ((1.0 - ink[c]) * max).round(); + if depth == 8 { data.push(v as u8) } else { data.extend((v as u16).to_be_bytes()) } + } + } + f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data, stored: None }; + f.resources.push(ImageResource::new(1039, profile.to_bytes().to_vec())); + let merged = merged_composite(&f).unwrap(); + let mut seen_far = false; + for (px, ink) in merged.iter().zip(&inks) { + let ink = ink.map(|v| ((v * max).round()) / max); + let want = reference(&profile, &ink); + let coated = reference(Builtin::CoatedCmyk.profile(), &ink); + seen_far |= (0..3).any(|k| (want[k] - coated[k]).abs() > 4.0 / 255.0); + for k in 0..3 { + assert!((px[k] - want[k]).abs() <= 2.0 / 255.0, "{depth}-bit {ink:?}: {px:?} vs {want:?} (built-in {coated:?})"); + } + } + assert!(seen_far, "the fixture profile differs from the built-in one"); + } +} + /// A two-stop version 1 `grdm` block whose stops are the PSD colour structures `a` and `b`. fn grdm_block(a: (u16, [u16; 4]), b: (u16, [u16; 4])) -> Vec { let mut v = vec![0, 1, 0, 0]; diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index fc61e41152..e43da363c5 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -576,6 +576,8 @@ pub struct BrushSettings { pub background: [f32; 4], /// Erase instead of paint. pub erase: bool, + /// Paint beneath existing pixels; opaque pixels and transparency-locked layers are unchanged. + pub behind: bool, /// Brush blend mode (Normal, Multiply, Dissolve…). pub mode: BlendMode, // --- Brush Tip Shape --- @@ -634,6 +636,7 @@ impl Default for BrushSettings { color_cmyk: None, background: [1.0, 1.0, 1.0, 1.0], erase: false, + behind: false, mode: BlendMode::Normal, tip: TipShape::Round, angle: 0.0, diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index f384d527bb..8b024de5a6 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -246,6 +246,43 @@ fn pencil_1px_line_is_the_same_whichever_way_and_however_smoothed() { assert_eq!(sampled, pixels((1.5, 1.5), (20.5, 9.5), 0.0)); } +#[test] +fn pencil_1px_freehand_line_never_breaks_where_it_turns() { + // #8040: each segment of a freehand stroke samples its own line, so where the stroke turned + // the last pixel of one segment and the first of the next could sit two pixels apart. + let b = BrushSettings { aliased: true, hardness: 1.0, size: 1.0, ..brush() }; + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + for _ in 0..300 { + let mut pts = vec![StrokePoint::new(20.0 + rnd() * 8.0, 20.0 + rnd() * 8.0, 1.0)]; + for _ in 0..6 { + let l = *pts.last().unwrap(); + let (dx, dy) = ((rnd() - 0.5) * 6.0, (rnd() - 0.5) * 6.0); + pts.push(StrokePoint::new((l.x + dx).clamp(1.0, 46.0), (l.y + dy).clamp(1.0, 46.0), 1.0)); + } + let s = paint(&b, &pts, 48, 48); + let painted: Vec<(i32, i32)> = (0..48).flat_map(|y| (0..48).map(move |x| (x, y))).filter(|&(x, y)| s.rgba(x, y)[3] > 0.0).collect(); + // Every painted pixel is reachable from the first through 8-connected neighbours. + let mut reached = vec![painted[0]]; + let mut i = 0; + while i < reached.len() { + let (x, y) = reached[i]; + for &q in &painted { + if (q.0 - x).abs() <= 1 && (q.1 - y).abs() <= 1 && !reached.contains(&q) { + reached.push(q); + } + } + i += 1; + } + let path: Vec<(f64, f64)> = pts.iter().map(|p| (p.x, p.y)).collect(); + assert_eq!(reached.len(), painted.len(), "the line breaks along {path:?}"); + } +} // ---------- spacing ---------- #[test] @@ -1204,6 +1241,41 @@ fn blend_mode_and_dissolve() { assert!(vals.iter().all(|&v| v == 0.0 || v == 1.0) && vals.contains(&0.0) && vals.contains(&1.0)); } +#[test] +fn behind_preserves_native_channels_and_respects_alpha_selection_and_locks() { + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let fmt = PixelFormat::new(mode, sample, true); + let b = BrushSettings { size: 12.0, behind: true, opacity: 0.5, color: [0.1, 0.3, 0.8, 1.0], ..brush() }; + let mut s = Surface::new(fmt); + let native = photocraft_raster::from_rgba(&fmt, [0.8, 0.2, 0.1, 0.5]); + s.fill_rect(Rect::new(0, 0, 12, 12), &native); + let before = s.pixel(6, 6); + let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + selection.fill_rect(Rect::new(0, 0, 8, 12), &[0.5]); + render_stroke(&mut s, &b, &[StrokePoint::new(6.0, 6.0, 1.0)], Some(&selection), false, 1.0); + let source = photocraft_raster::from_rgba(&fmt, b.color); + let a = fmt.channels() - 1; + let under = 0.25 * (1.0 - before[a]); + let alpha = before[a] + under; + let got = s.pixel(6, 6); + assert!((got[a] - alpha).abs() < 0.005, "{fmt:?}: {got:?}"); + for c in 0..a { + let expected = (before[c] * before[a] + source[c] * under) / alpha; + assert!((got[c] - expected).abs() < 0.005, "{fmt:?} channel {c}: {got:?}, expected {expected}"); + } + assert_eq!(s.pixel(9, 6), before, "outside selection"); + let locked = s.clone(); + render_stroke(&mut s, &b, &[StrokePoint::new(6.0, 6.0, 1.0)], None, true, 1.0); + assert_eq!(s.read_region(Rect::new(0, 0, 12, 12)), locked.read_region(Rect::new(0, 0, 12, 12)), "locked transparency"); + s.fill_rect(Rect::new(0, 0, 12, 12), &photocraft_raster::from_rgba(&fmt, [0.8, 0.2, 0.1, 1.0])); + let opaque = s.pixel(6, 6); + render_stroke(&mut s, &b, &[StrokePoint::new(6.0, 6.0, 1.0)], None, false, 1.0); + assert_eq!(s.pixel(6, 6), opaque, "opaque pixels"); + } + } +} + #[test] fn presets_render_and_round_trip() { let presets = crate::presets::builtin(); @@ -1279,6 +1351,7 @@ fn live_union_of_passes_matches_merging_the_finished_passes_after_every_chunk() brushes.push(b); brushes.push(BrushSettings { wet_edges: true, ..base.clone() }); brushes.push(BrushSettings { mode: BlendMode::Dissolve, ..base.clone() }); + brushes.push(BrushSettings { behind: true, ..base.clone() }); brushes.push(BrushSettings { erase: true, ..base.clone() }); let mut b = base.clone(); b.texture.enabled = true; diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index 5c8c88b640..02d54c18ff 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -21,6 +21,8 @@ pub const SPEED_SPACING_MS: f64 = 8.0; /// Longest pixel-grid segment (in pixels) before falling back to distance spacing. const MAX_GRID_STEPS: f64 = 1e7; +/// Widest gap (in pixels) [`PathWalker::bridge`] fills between two pixel-grid segments. +const MAX_BRIDGE: f64 = 4.0; /// Densest speed spacing, in pixels between dabs (a slow, long stroke never floods the buffer). const MIN_SPEED_STEP: f64 = 0.5; @@ -242,6 +244,8 @@ pub struct PathWalker { /// Pixel-grid stepping for small aliased tips: the dab-centre offset inside a pixel (see /// [`PathWalker::pixel_grid`]). grid: Option, + /// The grid cell of the last pixel-grid step, so the next segment joins it (#8040). + cell: Option<(f64, f64)>, } impl PathWalker { @@ -258,6 +262,7 @@ impl PathWalker { speed: None, speed_acc: 0.0, grid: None, + cell: None, } } @@ -296,11 +301,32 @@ impl PathWalker { let mut q = lerp_pt(a, p, t.clamp(0.0, 1.0)); let cn = grid_cell(an + dn * t, offset); (q.x, q.y) = if steep { (cn, c) } else { (c, cn) }; + self.bridge(&q, out); self.emit(q, out); } true } + /// Fills the pixels between the last grid step and `q` when they don't touch. Each segment + /// samples its own line, so where a freehand stroke turns, the last pixel of one segment and + /// the first of the next can sit two pixels apart, and the 1 px Pencil line breaks (#8040). + fn bridge(&mut self, q: &StrokePoint, out: &mut impl FnMut(StepInput)) { + let Some((mut x, mut y)) = self.cell else { return }; + // Only a turn's small gap: a step cut off by the walker's budget is not filled in. + if (q.x - x).abs().max((q.y - y).abs()) > MAX_BRIDGE { + return; + } + while (q.x - x).abs() > 1.5 || (q.y - y).abs() > 1.5 { + if (q.x - x).abs() > 0.5 { + x += (q.x - x).signum(); + } + if (q.y - y).abs() > 0.5 { + y += (q.y - y).signum(); + } + self.emit(StrokePoint { x, y, ..*q }, out); + } + } + /// Space steps by stroke time instead of distance ([`SPEED_SPACING_MS`]): faster movement /// spreads them out. Segments without timestamps are spaced by distance. pub fn speed_spacing(mut self, interval_ms: f64) -> Self { @@ -309,6 +335,9 @@ impl PathWalker { } fn emit(&mut self, point: StrokePoint, out: &mut impl FnMut(StepInput)) { + if let Some(g) = self.grid { + self.cell = Some((grid_cell(point.x, g), grid_cell(point.y, g))); + } let s = StepInput { point, direction: self.dir, initial_direction: self.initial_dir.unwrap_or(self.dir), step: self.step }; self.step += 1; out(s); diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index d11e4fa10c..a9a7485fa5 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -61,6 +61,9 @@ pub struct MixerState { pub amount: f32, /// Colour picked up from the canvas (straight RGBA), None = clean. pub pickup: Option<[f32; 4]>, + /// The foreground colour in effect when the reservoir was loaded from the canvas + /// (`load_sampled`), None when it holds the foreground itself. + pub sampled_over: Option<[f32; 4]>, /// A bounded 64 x 64 spatial load in tip-local coordinates. Empty cells carry no paint. pub spatial: Option>, /// The color recorded by the last stroke (its color) or the last Load Brush or Clean Brush @@ -74,6 +77,15 @@ impl MixerState { self.spatial = None; self.reservoir = Some(color); self.amount = 1.0; + self.sampled_over = None; + } + + /// Load the reservoir with a colour sampled from the canvas (⌥-click) while `foreground` is + /// the foreground colour; `holds_sample` stays true until the foreground changes. + pub fn load_sampled(&mut self, color: [f32; 4], foreground: [f32; 4]) { + self.load(color); + self.sampled_over = Some(foreground); + self.color = Some(foreground); } /// Clean Brush: empty the reservoir and the pickup well. pub fn clean(&mut self) { @@ -81,6 +93,12 @@ impl MixerState { self.reservoir = None; self.amount = 0.0; self.pickup = None; + self.sampled_over = None; + } + + /// Whether the reservoir holds a canvas sample taken while `foreground` was the foreground. + pub fn holds_sample(&self, foreground: [f32; 4]) -> bool { + self.reservoir.is_some() && self.sampled_over == Some(foreground) } /// Before a stroke in `color`: choosing a color other than [`MixerState::color`] loads the /// reservoir with it. @@ -95,14 +113,16 @@ impl MixerState { pub fn end_stroke(&mut self, color: [f32; 4], clean: bool, load: bool) { // Automatic Load replenishes a sampled tip as well as a solid-color load. // Move its bounded buffer through Clean instead of allocating a copy. + let sampled = self.holds_sample(color).then_some(color); let spatial = if load { self.spatial.take() } else { None }; - let paint = if spatial.is_some() { self.reservoir.unwrap_or(color) } else { color }; + let paint = if spatial.is_some() || sampled.is_some() { self.reservoir.unwrap_or(color) } else { color }; if clean { self.clean(); } if load { self.load(paint); self.spatial = spatial; + self.sampled_over = sampled; } self.color = Some(color); } diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 1a721b7146..83243bdafa 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -1224,7 +1224,21 @@ impl StrokeRenderer { src[ch] = p[ch] / c; } } - if matches!(b.mode, BlendMode::Normal | BlendMode::Dissolve) { + if b.behind { + let Some(a) = a_idx else { continue }; + let da = px[a]; + if lock_transparency || da >= 1.0 { + continue; + } + let underneath = src[a] * k * (1.0 - da); + let alpha = da + underneath; + if alpha > 0.0 { + for channel in 0..a { + px[channel] = (px[channel] * da + src[channel] * underneath) / alpha; + } + px[a] = alpha; + } + } else if matches!(b.mode, BlendMode::Normal | BlendMode::Dissolve) { over_native(&fmt, px, &src[..n], k, lock_transparency); } else { let d = to_rgba(&fmt, px); diff --git a/crates/plugins/src/apply.rs b/crates/plugins/src/apply.rs index ba3f29f89d..52e3b85826 100644 --- a/crates/plugins/src/apply.rs +++ b/crates/plugins/src/apply.rs @@ -140,9 +140,10 @@ impl Plugin { } r }; - // A few bands at a time (one per worker), so peak memory stays near one band per thread. + // A few bands at a time: one per worker, and no more instances than the run's memory + // budget holds at their cap, so peak memory stays bounded however many cores run (#8603). #[cfg(not(target_arch = "wasm32"))] - let group = rayon::current_num_threads().max(1); + let group = self.limits().parallel_bands(rayon::current_num_threads()); #[cfg(target_arch = "wasm32")] let group = 1; for chunk in bands.chunks(group) { @@ -210,7 +211,8 @@ impl Plugin { v = v.clamp(0.0, 1.0); } if let Some(d) = out.get_mut(di + ch) { - *d = o + (v - o) * k; + // As a built-in edit mixes through the selection (#9483). + *d = o * (1.0 - k) + v * k; } } } diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 9f66b545ba..c3dd8d9ccc 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -23,6 +23,10 @@ pub struct Limits { pub max_module_bytes: usize, /// Cap on a plug-in's linear memory. pub max_memory_bytes: usize, + /// Cap on the linear memory of all of one run's instances together: bands run in parallel + /// only as far as their [`Limits::max_memory_bytes`] fit in it, so a run's peak memory does + /// not grow with the number of cores (#8603). + pub max_total_memory_bytes: usize, /// Target size of one band of `f32` pixels handed to the plug-in. pub band_bytes: usize, /// Instructions (fuel) any call may use, plus [`Limits::fuel_per_sample`] per sample for @@ -37,10 +41,12 @@ pub struct Limits { } impl Default for Limits { + /// The limits plug-ins run under unless a caller narrows them; see `docs/plugins.md`. fn default() -> Self { Self { max_module_bytes: 32 << 20, max_memory_bytes: 512 << 20, + max_total_memory_bytes: 2 << 30, band_bytes: 4 << 20, fuel_base: 50_000_000, fuel_per_sample: 4_000, @@ -50,6 +56,16 @@ impl Default for Limits { } } +impl Limits { + /// How many bands of one run may hold an instance at once on `threads` workers: no more + /// than [`Limits::max_memory_bytes`] fits into [`Limits::max_total_memory_bytes`], and always + /// at least one, so a tight budget runs bands one at a time instead of refusing the run. + pub fn parallel_bands(&self, threads: usize) -> usize { + let fit = self.max_total_memory_bytes.checked_div(self.max_memory_bytes).unwrap_or(threads); + threads.min(fit).max(1) + } +} + /// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads: /// every run gets its own store and instance. pub struct Plugin { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 17e352982e..bb06069ac8 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -337,6 +337,39 @@ fn folder_loading_skips_bad_files() { std::fs::remove_dir_all(&dir).ok(); } +/// #8603: a run whose memory budget holds a single instance still covers every band on a +/// many-worker pool, one band at a time, with the same pixels as a run of parallel bands. +#[test] +fn one_band_at_a_time_matches_parallel_bands() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap(); + let s = surface(PixelFormat::RGBA8, 600, 300); + let canvas = Rect::new(0, 0, 600, 300); + let run = |limits: Limits| { + let p = Plugin::load(INVERT, limits).unwrap(); + pool.install(|| p.apply(&s, canvas, None, &json!({}))).unwrap() + }; + let parallel = run(Limits { band_bytes: 1, ..Limits::default() }); + let serial = run(Limits { band_bytes: 1, max_total_memory_bytes: 512 << 20, ..Limits::default() }); + assert_eq!(serial, parallel); + assert_ne!(serial, s, "the filter ran"); +} + +/// #8603: one run on 16 workers must not hold 16 instances at the 512 MiB cap (8 GiB). With the +/// default limits it holds at most four (2 GiB); a smaller per-instance cap lets every worker +/// run, and a budget under one cap still runs one band at a time rather than none. +#[test] +fn parallel_bands_fit_the_total_memory_budget() { + let d = Limits::default(); + assert_eq!(d.parallel_bands(16), 4); + assert!(d.parallel_bands(64) * d.max_memory_bytes <= d.max_total_memory_bytes); + assert_eq!(d.parallel_bands(2), 2, "fewer workers than the budget allows"); + let small = Limits { max_memory_bytes: 64 << 20, ..Limits::default() }; + assert_eq!(small.parallel_bands(16), 16, "small instances keep every worker busy"); + let tight = Limits { max_total_memory_bytes: 1 << 20, ..Limits::default() }; + assert_eq!(tight.parallel_bands(16), 1, "at least one band runs"); + assert_eq!(d.parallel_bands(0), 1); +} + #[test] fn a_start_function_that_spins_is_cut_off_at_one_slice() { // `fuel_base` is what a call may use; the start function cannot be interrupted to check the diff --git a/crates/raw/README.md b/crates/raw/README.md index 268e200b7f..03c95390a4 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -27,7 +27,7 @@ Implemented only from public specifications, papers and observation of files: * Publicly documented maker-note / private tags (ExifTool's tag tables): Canon ModelID (0x0010), SensorInfo (0x00E0) and ColorData (0x4001), Nikon WB_RBLevels (0x000C), ColorSpace (0x001E) and BlackLevel (0x003D), Sony BlackLevel (0x7310), WB_RGGBLevels (0x7313), SonyRawFileType (0x7000) and SonyToneCurve - (0x7010), the PanasonicRaw IFD0 tags, Olympus ImageProcessing (0x2040) and CameraSettings + (0x7010), SR2Private Offset / Length / Key (0x7200 / 0x7201 / 0x7221), the PanasonicRaw IFD0 tags, Olympus ImageProcessing (0x2040) and CameraSettings (0x2020) preview tags, the Fujifilm RAF header and metadata records (RawImageCropTopLeft / RawImageCroppedSize, FujiLayout, XTransLayout, WB_GRGBLevels, RawExposureBias) and FujiIFD (RawImageFullWidth / Height, BitsPerSample, StripOffsets / ByteCounts, BlackLevel, @@ -41,6 +41,8 @@ Implemented only from public specifications, papers and observation of files: * 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. + Encrypted SR2SubIFD metadata with key bytes `11 22 33 44` was measured independently against + ExifTool's metadata dumps; see [Sony metadata evidence](../../docs/sony-arw-metadata.md). * Panasonic RW2 RawFormat 5, uncompressed Olympus ORF and uncompressed Fujifilm RAF: established by observation of sample files (bit packing, page layout, sample justification; for RAF the three sample storages and the reversed order of the X-Trans / Bayer layout records, each @@ -73,7 +75,7 @@ camera colour tables were copied. | CR2 sRAW / mRAW | Unsupported | | 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) | -| Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits, the curve's 512 black level when no BlackLevel tag is written (the first-generation bodies, e.g. the ILCE-7) | +| 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 | diff --git a/crates/raw/src/cameras.rs b/crates/raw/src/cameras.rs index d7ae5e84d7..321ecf1223 100644 --- a/crates/raw/src/cameras.rs +++ b/crates/raw/src/cameras.rs @@ -149,6 +149,9 @@ const PROFILES: &[Profile] = &[Profile { /// 4352 x 2868 sensor data, giving the camera JPEG's 4288 x 2848 frame /// (10 pixels of margin on the right and bottom; the right border reads the /// camera's flat 255 from column 4310 on). +/// * **ILCE-6000** (3 files): the same 12 x 12 origin and 6000 x 4000 image; +/// confirmed by the file's EXIF size and SR2SubIFD's area [12, 12, 6012, 4012], +/// and checked against the matching camera JPEGs. No colour profile is inferred. struct ImageArea { make: &'static str, model: &'static str, @@ -163,6 +166,7 @@ const IMAGE_AREAS: &[ImageArea] = &[ ImageArea { make: "NIKON CORPORATION", model: "NIKON D5100", size: (4992, 3280), crop: (8, 8, 4928, 3264) }, ImageArea { make: "NIKON CORPORATION", model: "NIKON D800E", size: (7424, 4924), crop: (8, 6, 7360, 4912) }, ImageArea { make: "SONY", model: "ILCE-7", size: (6048, 4024), crop: (12, 12, 6000, 4000) }, + ImageArea { make: "SONY", model: "ILCE-6000", size: (6048, 4024), crop: (12, 12, 6000, 4000) }, ]; /// Applies the measured profile of the camera that made `s`, when there is one, @@ -307,6 +311,19 @@ mod tests { apply(&mut s, 14); assert_eq!(s.crop, Rect::new(12, 12, 6000, 4000)); + let mut s = sensor("SONY", "ILCE-6000", 6048, 4024); + apply(&mut s, 14); + assert_eq!(s.crop, Rect::new(12, 12, 6000, 4000)); + assert!(s.color.calibrations.is_empty() && s.tone_curve.is_empty()); + // A file's explicit crop wins, including a different in-camera aspect ratio. + s.crop = Rect::new(12, 324, 6000, 3376); + apply(&mut s, 14); + assert_eq!(s.crop, Rect::new(12, 324, 6000, 3376)); + + let mut s = sensor("SONY", "ILCE-6000", 3024, 2012); + apply(&mut s, 14); + assert_eq!(s.crop, Rect::new(0, 0, 3024, 2012)); + // Another size or model of the same maker is left alone. let mut s = nef("NIKON D800E", 2496, 1646); apply(&mut s, 14); diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 24cd852c77..43a3ff47c8 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -64,6 +64,7 @@ mod rw2; mod saturation; mod sensor; mod sony; +mod sony_metadata; mod tiff; mod tiffep; mod tone; diff --git a/crates/raw/src/sony_metadata.rs b/crates/raw/src/sony_metadata.rs new file mode 100644 index 0000000000..7584d398a8 --- /dev/null +++ b/crates/raw/src/sony_metadata.rs @@ -0,0 +1,262 @@ +//! Sony's encrypted SR2SubIFD: black levels and the white balance actually applied by the camera. +//! +//! Directory/tag meanings are from ExifTool's public Sony tag documentation. The keystream was +//! measured independently by XOR-ing file bytes with ExifTool 13.59's black-box `-v5` metadata +//! dumps of three ILCE-6000 ARWs (56958-byte blocks, key bytes 11 22 33 44). All 14239 whole +//! words in each block obey k[n] = k[n-63] XOR k[n-127]; the first 127 words agree across the +//! files. This is metadata cipher data, not camera colour calibration or image data. LightCraft's +//! documented investigation suggested the experiment; no sibling or third-party decoder code +//! is used. Other keys remain unreadable rather than being guessed. + +use crate::Limits; +use crate::tiff::{Ifd, Tiff}; + +const PRIVATE_DATA: u16 = 50740; +const OFFSET: u16 = 0x7200; +const LENGTH: u16 = 0x7201; +const KEY: u16 = 0x7221; +const MAX_METADATA: usize = 1 << 20; + +// Measured from metadata only. The key's first 127 words, in byte-stream order (big endian). +const INITIAL: [u32; 127] = [ + 0x54c2c4d6, 0x49c478bc, 0x34ae2f8e, 0x25d80504, 0xc0d9d6b0, 0xd838fb71, 0xe8eff27d, 0xfbc1fcea, 0x506c499a, 0x47f20f37, 0x710777cf, 0x7867e7ba, 0x42d67caa, + 0x7f2bd11a, 0x67a216ca, 0x0e986d40, 0x4ae8d4c0, 0xe36778b4, 0x5a958415, 0xdbfe2be8, 0x20faa1aa, 0x7132a6b8, 0xf4de4b7f, 0x55991aa1, 0xa849d5aa, 0x49577832, + 0xb92f3daa, 0x399cc526, 0x22cdd000, 0xe1977a29, 0x37c5db55, 0xb0177e1e, 0x2a1016aa, 0xa300086e, 0x3bab9bfe, 0x262eece0, 0x23771aa9, 0x0a5dc91c, 0x31b902ae, + 0x58e64bf8, 0x259c300e, 0xa57705c8, 0x284a6541, 0xfb229c60, 0x1bacaa9e, 0xbcab3350, 0x67cd9fbe, 0x8f135e60, 0xf8c26a40, 0x6770da61, 0x3e1febfd, 0xd0c70803, + 0x8dbb037b, 0x6f6fa4c5, 0x6749d10d, 0x7f51598d, 0xd5e5a4ec, 0x207dfa91, 0x6558ebc2, 0xbe594639, 0x617a9e5d, 0x3c497950, 0x0844eb3f, 0x04207ed2, 0xd27ceac4, + 0x70d20f05, 0xb47003f6, 0xe9e4e3ae, 0xcc19d265, 0x326dd956, 0xf0d3a327, 0xb71275f0, 0x7994e285, 0x0aff594d, 0x128e8345, 0x7bda597a, 0xd634c380, 0xe24a006f, + 0x8974818b, 0x3320b22a, 0xbe808417, 0xa2d5648a, 0x6fe80b39, 0x23ebad41, 0xa2d11e5d, 0x027d9397, 0x9a722ac8, 0x432c7dac, 0x7146692a, 0x82a3dc77, 0xd66887c5, + 0x831f43b7, 0x4e5dddde, 0x03793f81, 0x306ab437, 0x00ccf86c, 0xfc6ed3d2, 0x076b8fdb, 0x9808cfca, 0x0f4eef6e, 0xc8cc3830, 0x104ac16a, 0xa189eff4, 0x3e085c08, + 0xd28baf88, 0x5c853ac4, 0xe60480f8, 0xc51acd98, 0x691e5ee1, 0x333feeb9, 0x1e35bc33, 0xec4a4642, 0xee57c5a5, 0xbeeb51f7, 0xe0c4f32c, 0xa5422f6a, 0x1d266d12, + 0x3752fd3b, 0xfbc53c7d, 0x2421a4a3, 0xcdc6a2de, 0x26e6b330, 0x6c073d46, 0x058e2f27, 0x43833f30, 0x46d1382e, 0x5f0804ec, +]; + +fn decipher(data: &mut [u8]) { + let mut history = INITIAL; + for (n, chunk) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let slot = n % 127; + let word = if n < 127 { + INITIAL.get(n).copied().unwrap_or(0) + } else { + history.get(slot).copied().unwrap_or(0) ^ history.get((n - 63) % 127).copied().unwrap_or(0) + }; + if let Some(previous) = history.get_mut(slot) { + *previous = word; + } + for (byte, key) in chunk.iter_mut().zip(word.to_be_bytes()) { + *byte ^= key; + } + } + // Sony leaves an incomplete final word in the clear. +} + +#[derive(Default)] +pub(crate) struct Levels { + pub black: Option<[f64; 4]>, + pub wb: Option<[f64; 4]>, +} + +/// Reads only four SHORT/SSHORT levels from a complete directory. Overflow value offsets are +/// absolute file offsets, but must point inside this decrypted block, never into other file data. +fn four(t: &Tiff, ifd: &Ifd, start: usize, tag: u16) -> Option<[f64; 4]> { + let mut e = *ifd.get(tag)?; + if !matches!(e.typ, 3 | 8) || e.count != 4 { + return None; + } + e.at = e.at.checked_sub(start)?; + t.raw(&e)?; + let v = [t.float(&e, 0)?, t.float(&e, 1)?, t.float(&e, 2)?, t.float(&e, 3)?]; + v.iter().all(|x| (0.0..=16383.0).contains(x)).then_some(v) +} + +fn parse(plain: &[u8], start: usize, le: bool) -> Option { + let t = Tiff { data: plain, le, first_ifd: 0 }; + let count = usize::from(t.u16_at(0)?); + let end = count.checked_mul(12)?.checked_add(6)?; + plain.get(..end)?; + let ifd = t.ifd_at(0, 0)?; + Some(Levels { black: four(&t, &ifd, start, 0x7310), wb: four(&t, &ifd, start, 0x7313) }) +} + +pub(crate) fn read(t: &Tiff, limits: &Limits) -> Option { + let ifd0 = t.ifd_at(t.first_ifd, 0)?; + let pointer = ifd0.get(PRIVATE_DATA)?; + // BYTE[4]/UNDEFINED[4] containing a file-order offset (not a DNG private payload). + if !matches!(pointer.typ, 1 | 7) || pointer.count != 4 { + return None; + } + let private = t.ifd_at(t.u32_at(pointer.at)? as usize, 0)?; + if t.raw(private.get(KEY)?)? != [0x11, 0x22, 0x33, 0x44] { + return None; + } + let start = t.tag_uint(&private, OFFSET)? as usize; + let len = t.tag_uint(&private, LENGTH)? as usize; + if !(6..=MAX_METADATA).contains(&len) || len as u64 > limits.max_alloc { + return None; + } + let mut plain = t.bytes(start, len)?.to_vec(); + decipher(&mut plain); + parse(&plain, start, t.le) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testgen::{TiffBuilder, Val}; + use crate::{DevelopOptions, RawFormat, WhiteBalance, decode, develop_sensor}; + + /// Procedural CFA TIFF with plain and encrypted levels that deliberately disagree. + /// No camera file, scene pixels, metadata dump or private fixture is included. + fn fixture(be: bool, plain: bool, black: [u16; 4], wb: [u16; 4]) -> Vec { + let u16_bytes = |v: u16| if be { v.to_be_bytes() } else { v.to_le_bytes() }; + let u32_bytes = |v: u32| if be { v.to_be_bytes() } else { v.to_le_bytes() }; + let mut block = Vec::new(); + block.extend_from_slice(&u16_bytes(2)); + for (tag, typ, offset) in [(0x7310, 3, 2048), (0x7313, 8, 2056)] { + block.extend_from_slice(&u16_bytes(tag)); + block.extend_from_slice(&u16_bytes(typ)); + block.extend_from_slice(&u32_bytes(4)); + block.extend_from_slice(&u32_bytes(offset)); // replaced with absolute offsets below + } + block.extend_from_slice(&[0; 4]); + block.resize(2048, 0); // crosses multiple 127-word recurrence periods + for v in black.into_iter().chain(wb) { + block.extend_from_slice(&u16_bytes(v)); + } + block.extend_from_slice(&[0xAA, 0xBB]); // tail stored in the clear + let mut b = TiffBuilder { big_endian: be, ..Default::default() }; + let len = block.len(); + let data = b.blob(block); + let pixels = b.blob( + (0..32 * 16) + .flat_map(|i| { + u16_bytes(match (i % 32 % 2, i / 32 % 2) { + (0, 0) => 1512, + (1, 1) => 2512, + _ => 3512, + }) + }) + .collect(), + ); + let mut entries = vec![ + (256, Val::Long(vec![32])), + (257, Val::Long(vec![16])), + (258, Val::Short(vec![16])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![32803])), + (273, Val::Blobs(vec![pixels])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![16])), + (279, Val::Long(vec![32 * 16 * 2])), + (33421, Val::Short(vec![2, 2])), + (33422, Val::Byte(vec![0, 1, 1, 2])), + (50717, Val::Short(vec![16383])), + ]; + if plain { + entries.extend([(0x7310, Val::Short(vec![600; 4])), (0x7313, Val::Short(vec![2048, 1024, 1024, 1536]))]); + } + let raw = b.ifd(entries); + let private = b.ifd(vec![(OFFSET, Val::Blobs(vec![data])), (LENGTH, Val::Long(vec![len as u32])), (KEY, Val::Byte(vec![0x11, 0x22, 0x33, 0x44]))]); + let root = b.ifd(vec![ + (271, Val::Ascii("SONY".into())), + (272, Val::Ascii("ILCE-Synthetic".into())), + (330, Val::Ifds(vec![raw])), + (PRIVATE_DATA, Val::Ifds(vec![private])), + ]); + b.chain = vec![root]; + let mut bytes = b.build(); + let t = Tiff::new(&bytes).unwrap(); + let root = t.ifd_at(t.first_ifd, 0).unwrap(); + let pointer = *root.get(PRIVATE_DATA).unwrap(); + let private = t.ifd_at(t.u32_at(pointer.at).unwrap() as usize, 0).unwrap(); + let start = t.tag_uint(&private, OFFSET).unwrap() as usize; + // TIFF BYTE[4] offset rather than the generator's LONG[1]. + bytes[pointer.at - 6..pointer.at - 4].copy_from_slice(&u16_bytes(1)); + bytes[pointer.at - 4..pointer.at].copy_from_slice(&u32_bytes(4)); + for (entry, offset) in [(10, 2048), (22, 2056)] { + bytes[start + entry..start + entry + 4].copy_from_slice(&u32_bytes((start + offset) as u32)); + } + decipher(&mut bytes[start..start + len]); + bytes + } + + #[test] + fn encrypted_applied_white_balance_and_black_reach_the_developer() { + for be in [false, true] { + let bytes = fixture(be, false, [512, 513, 514, 515], [3072, 1024, 1024, 2048]); + let s = decode(&bytes, &Limits::default()).unwrap(); + assert_eq!(s.format, RawFormat::Arw); + assert_eq!(s.camera_wb, Some([3.0, 1.0, 2.0])); + assert_eq!(s.black.values, vec![512.0, 513.0, 514.0, 515.0]); + let dev = develop_sensor(&s, &DevelopOptions::default()).unwrap(); + assert_eq!(dev.info.wb_multipliers, [3.0, 1.0, 2.0]); + assert!(!dev.warnings.iter().any(|w| w.contains("grey world") || w.contains("assumed 0"))); + let explicit = develop_sensor(&s, &DevelopOptions { white_balance: WhiteBalance::Multipliers([3.0, 1.0, 2.0]), ..Default::default() }).unwrap(); + assert_eq!(dev.rgb, explicit.rgb); + } + } + + #[test] + fn plain_levels_win_and_invalid_encrypted_levels_are_ignored() { + let s = decode(&fixture(false, true, [800; 4], [3072, 1024, 1024, 2048]), &Limits::default()).unwrap(); + assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); + assert_eq!(s.black.values, vec![600.0; 4]); + let mut broken_plain = fixture(false, true, [800; 4], [3072, 1024, 1024, 2048]); + let t = Tiff::new(&broken_plain).unwrap(); + let raw = t.all_ifds().into_iter().find(|i| i.has(0x7313)).unwrap(); + let at = raw.get(0x7313).unwrap().at; + broken_plain[at..at + 8].fill(0); + let s = decode(&broken_plain, &Limits::default()).unwrap(); + assert_eq!(s.camera_wb, Some([3.0, 1.0, 2.0])); + assert_eq!(s.black.values, vec![600.0; 4]); + for wb in [[0, 0, 0, 0], [65535, 1024, 1024, 2048], [30000, 1024, 1024, 2048], [3072, 0, 0, 2048]] { + let s = decode(&fixture(false, false, [65535; 4], wb), &Limits::default()).unwrap(); + assert_eq!(s.camera_wb, None); + assert_eq!(s.black.values, vec![0.0]); + } + } + + #[test] + fn hostile_private_metadata_is_bounded_and_optional() { + let bytes = fixture(false, false, [512; 4], [3072, 1024, 1024, 2048]); + for n in 0..bytes.len() { + if let Some(t) = Tiff::new(&bytes[..n]) { + let _ = read(&t, &Limits::default()); + } + } + let t = Tiff::new(&bytes).unwrap(); + assert!(read(&t, &Limits { max_alloc: 2000, ..Default::default() }).is_none()); + let root = t.ifd_at(t.first_ifd, 0).unwrap(); + let private = t.ifd_at(t.u32_at(root.get(PRIVATE_DATA).unwrap().at).unwrap() as usize, 0).unwrap(); + for (at, value) in [(private.get(KEY).unwrap().at, 0), (private.get(LENGTH).unwrap().at, u32::MAX), (private.get(OFFSET).unwrap().at, u32::MAX)] { + let mut corrupt = bytes.clone(); + corrupt[at..at + 4].copy_from_slice(&value.to_le_bytes()); + assert!(read(&Tiff::new(&corrupt).unwrap(), &Limits::default()).is_none()); + let s = decode(&corrupt, &Limits::default()).unwrap(); + assert_eq!(s.camera_wb, None); + } + let start = t.tag_uint(&private, OFFSET).unwrap() as usize; + let len = t.tag_uint(&private, LENGTH).unwrap() as usize; + let mut corrupt = bytes.clone(); + decipher(&mut corrupt[start..start + len]); + // Values before the encrypted block cannot be interpreted as metadata. + corrupt[start + 22..start + 26].copy_from_slice(&8u32.to_le_bytes()); + decipher(&mut corrupt[start..start + len]); + assert!(read(&Tiff::new(&corrupt).unwrap(), &Limits::default()).unwrap().wb.is_none()); + } + + #[test] + fn measured_keystream_recurrence_and_unencrypted_tail() { + let mut zero = vec![0; 14239 * 4 + 2]; + decipher(&mut zero); + assert_eq!(&zero[..4], &[0x54, 0xc2, 0xc4, 0xd6]); + // Words recovered independently from all three oracle dumps, including ring wrap + // and the final complete word of a real metadata block. + assert_eq!(&zero[127 * 4..128 * 4], &[0x86, 0xbe, 0x2e, 0x12]); + assert_eq!(&zero[255 * 4..256 * 4], &[0xc9, 0x1a, 0x54, 0xc4]); + assert_eq!(&zero[14238 * 4..14239 * 4], &[0xb9, 0xd3, 0x6e, 0xab]); + assert_eq!(&zero[14239 * 4..], &[0, 0]); + decipher(&mut zero); + assert!(zero.iter().all(|&b| b == 0)); + } +} diff --git a/crates/raw/src/tiffep.rs b/crates/raw/src/tiffep.rs index 003eb3c18c..fe0ea80a94 100644 --- a/crates/raw/src/tiffep.rs +++ b/crates/raw/src/tiffep.rs @@ -166,25 +166,34 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result n.tag_floats(m, NIKON_BLACK_LEVEL).into_iter().map(|v| if plane.bits == 12 { v / 4.0 } else { v }).collect(), - None => t.tag_floats(&raw, SONY_BLACK_LEVEL), + None => { + if rggb_by_position(&cfa, &sony_black).is_some() { + sony_black + } else { + sony_levels.as_ref().and_then(|s| s.black).map(|v| v.to_vec()).unwrap_or_default() + } + } }; let black = if let Some(b) = bl.first() { BlackLevels::uniform(*b as f32) } else if let Some(v) = rggb_by_position(&cfa, &vendor_black) { BlackLevels { rows: 2, cols: 2, values: v.to_vec(), delta_h: Vec::new(), delta_v: Vec::new() } } else if craw { - // cRAW files of the first generation (an ILCE-7 writes none) carry no - // BlackLevel tag; the tone curve maps the black code to 512, so their - // decoded data has a 512 black level (see `sony.rs`). Other tag-less - // bodies sit higher (a DSC-RX0's darkest samples are near 800), so 512 - // is a floor, still far closer than 0. + // When neither plain nor encrypted metadata is readable, the common cRAW + // black code maps to 512. Some bodies sit higher, so this remains a fallback. BlackLevels::uniform(512.0) } else if nikon.is_some() { // Nikon bodies that write no BlackLevel tag subtract the black level in camera: a D3200 @@ -204,10 +213,7 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result Some([*r, 1.0, *b]), _ => None, }, - None => match t.tag_floats(&raw, SONY_WB_RGGB_LEVELS).as_slice() { - [r, g1, g2, b] if *g1 + *g2 > 0.0 => Some([2.0 * r / (g1 + g2), 1.0, 2.0 * b / (g1 + g2)]), - _ => None, - }, + None => sony_plain_wb.or_else(|| sony_levels.as_ref().and_then(|s| s.wb).and_then(|v| sony_wb(&v))), } .filter(|m| m.iter().all(|v| (0.25..8.0).contains(v))); // DNG-style DefaultCropOrigin / DefaultCropSize (some vendors write them in the raw IFD). @@ -258,6 +264,16 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result Option<[f64; 3]> { + let [r, g1, g2, b] = <[f64; 4]>::try_from(levels).ok()?; + if [r, g1, g2, b].iter().any(|v| !v.is_finite() || *v <= 0.0) { + return None; + } + let g = (g1 + g2) / 2.0; + let m = [r / g, 1.0, b / g]; + m.iter().all(|v| (0.25..8.0).contains(v)).then_some(m) +} + #[cfg(test)] mod padding_tests { use super::padded_width; diff --git a/crates/raw/src/tone.rs b/crates/raw/src/tone.rs index 00df46fd37..4878319317 100644 --- a/crates/raw/src/tone.rs +++ b/crates/raw/src/tone.rs @@ -138,32 +138,81 @@ const PRO_TO_P3: [[f32; 3]; 3] = [[1.632638, -0.379816, -0.252821], [-0.153846, /// A change of log₂ luminance computed on a reduced copy, carried to full size along the image's /// own edges (guided upsampling): a local linear model `change = a · log₂ Y + b` per reduced pixel. struct Upsampled { - sw: usize, - sh: usize, - a: Vec, - b: Vec, + grid: Grid, + /// `[a, b]` per reduced pixel (one cache line serves both lookups). + ab: Vec<[f32; 2]>, /// log₂ luminance floor (the reduced copy's 0.1th percentile). floor: f32, } impl Upsampled { - /// The change at full-size pixel (`x`, `y`) of a `w × h` image, of linear luminance `lum`. - fn change(&self, w: usize, h: usize, x: usize, y: usize, lum: f32) -> f32 { - let l = if lum > 0.0 { lum.log2().max(self.floor) } else { self.floor }; - bilinear(&self.a, self.sw, self.sh, w, h, x, y) * l + bilinear(&self.b, self.sw, self.sh, w, h, x, y) + fn new(sw: usize, sh: usize, w: usize, h: usize, a: &[f32], b: &[f32], floor: f32) -> Self { + Upsampled { grid: Grid::new(sw, sh, w, h), ab: a.iter().zip(b).map(|(a, b)| [*a, *b]).collect(), floor } + } + + /// The change at full-size pixel (`x`, `y`) whose linear luminance has the log₂ `log` (`None`: not above 0). + fn change(&self, x: usize, y: usize, log: Option) -> f32 { + let l = log.map_or(self.floor, |l| l.max(self.floor)); + let [a, b] = self.grid.at2(&self.ab, x, y); + a * l + b } } -/// `v` (`sw × sh`) at full-size pixel (`x`, `y`) of a `w × h` image, bilinearly. -fn bilinear(v: &[f32], sw: usize, sh: usize, w: usize, h: usize, x: usize, y: usize) -> f32 { - let sx = ((x as f32 + 0.5) * sw as f32 / w as f32 - 0.5).clamp(0.0, (sw - 1) as f32); - let sy = ((y as f32 + 0.5) * sh as f32 / h as f32 - 0.5).clamp(0.0, (sh - 1) as f32); - let (x0, y0) = (sx as usize, sy as usize); - let (x1, y1) = ((x0 + 1).min(sw - 1), (y0 + 1).min(sh - 1)); - let (fx, fy) = (sx - x0 as f32, sy - y0 as f32); - let top = v[y0 * sw + x0] * (1.0 - fx) + v[y0 * sw + x1] * fx; - let bottom = v[y1 * sw + x0] * (1.0 - fx) + v[y1 * sw + x1] * fx; - top * (1.0 - fy) + bottom * fy +/// Where one full-size coordinate reads a reduced axis: the two neighbours and the weight of the +/// second (and one minus it). +#[derive(Clone, Copy)] +struct Tap { + i0: u32, + i1: u32, + f: f32, + g: f32, +} + +/// The bilinear lookup of a reduced `sw × sh` plane at the pixels of a `w × h` image, with the +/// taps of every column and row worked out once instead of for every pixel. +struct Grid { + sw: usize, + cols: Vec, + rows: Vec, +} + +impl Grid { + fn new(sw: usize, sh: usize, w: usize, h: usize) -> Self { + let axis = |s: usize, n: usize| -> Vec { + (0..n) + .map(|i| { + let p = ((i as f32 + 0.5) * s as f32 / n as f32 - 0.5).clamp(0.0, (s - 1) as f32); + let i0 = p as usize; + let f = p - i0 as f32; + Tap { i0: i0 as u32, i1: (i0 + 1).min(s - 1) as u32, f, g: 1.0 - f } + }) + .collect() + }; + Grid { sw, cols: axis(sw, w), rows: axis(sh, h) } + } + + /// `v` (the reduced plane) at full-size pixel (`x`, `y`), bilinearly. + #[inline] + fn at(&self, v: &[f32], x: usize, y: usize) -> f32 { + let (cx, cy) = (self.cols[x], self.rows[y]); + let (r0, r1) = (cy.i0 as usize * self.sw, cy.i1 as usize * self.sw); + let top = v[r0 + cx.i0 as usize] * cx.g + v[r0 + cx.i1 as usize] * cx.f; + let bottom = v[r1 + cx.i0 as usize] * cx.g + v[r1 + cx.i1 as usize] * cx.f; + top * cy.g + bottom * cy.f + } + + /// [`at`](Self::at) for two planes stored together. + #[inline] + fn at2(&self, v: &[[f32; 2]], x: usize, y: usize) -> [f32; 2] { + let (cx, cy) = (self.cols[x], self.rows[y]); + let (r0, r1) = (cy.i0 as usize * self.sw, cy.i1 as usize * self.sw); + let (p00, p01, p10, p11) = (v[r0 + cx.i0 as usize], v[r0 + cx.i1 as usize], v[r1 + cx.i0 as usize], v[r1 + cx.i1 as usize]); + [0, 1].map(|k| { + let top = p00[k] * cx.g + p01[k] * cx.f; + let bottom = p10[k] * cx.g + p11[k] * cx.f; + top * cy.g + bottom * cy.f + }) + } } /// Box means of `f` over `k × k` cells, `k` the smallest factor that brings the long side to @@ -193,11 +242,55 @@ fn reduce(w: usize, h: usize, side: usize, f: impl Fn(usize) -> (sw, sh, rows.concat()) } +/// [`reduce`] of one plane at two sizes in a single pass over the pixels (each pixel's value +/// worked out once): the means of `f` for `sides[0]` and for `sides[1]`, as `reduce` gives them. +fn reduce_pair(w: usize, h: usize, sides: [usize; 2], f: impl Fn(usize) -> f32 + Sync) -> [(usize, usize, Vec); 2] { + let k = sides.map(|side| w.max(h).div_ceil(side).max(1)); + let sizes = k.map(|k| (w.div_ceil(k), h.div_ceil(k))); + // Bands of whole cell rows of both sizes. + let step = { + let (mut a, mut b) = (k[0], k[1]); + while b != 0 { + (a, b) = (b, a % b); + } + k[0] / a * k[1] + }; + let bands = par::map(h.div_ceil(step), |band| { + let (y0, y1) = (band * step, ((band + 1) * step).min(h)); + let mut row = vec![0.0f32; w]; + let mut sums = [vec![0.0f64; sizes[0].0], vec![0.0f64; sizes[1].0]]; + let mut out = [Vec::new(), Vec::new()]; + for y in y0..y1 { + for (x, v) in row.iter_mut().enumerate() { + *v = f(y * w + x).max(0.0); + } + for g in 0..2 { + for (cell, vs) in sums[g].iter_mut().zip(row.chunks(k[g])) { + let mut s = *cell; + for v in vs { + s += f64::from(*v); + } + *cell = s; + } + // The cell row ends here. + if (y + 1) % k[g] == 0 || y + 1 == h { + let rows = y + 1 - y / k[g] * k[g]; + for (sx, s) in sums[g].iter_mut().enumerate() { + let n = ((((sx + 1) * k[g]).min(w) - sx * k[g]) * rows) as f64; + out[g].push((*s / n) as f32); + *s = 0.0; + } + } + } + } + out + }); + [0, 1].map(|g| (sizes[g].0, sizes[g].1, bands.iter().flat_map(|b| b[g].iter().copied()).collect())) +} + /// The luminance change of one image (Shadows, Highlights, Clarity on the work copy; Texture on /// a half-size copy) and the black point. pub(crate) struct ToneMap { - w: usize, - h: usize, work: Option, texture: Option, /// Linear black point to subtract (0: none). @@ -212,11 +305,20 @@ impl ToneMap { if w == 0 || h == 0 || (tone.gain_neutral() && black_point <= 0.0) { return None; } - let (sw, sh, y) = reduce(w, h, WORK_SIDE, |i| [lum(i)]); - let y: Vec = y.into_iter().map(|[v]| v).collect(); - let p01 = quantile(&y, 0.001).max(2f32.powi(-20)); + // The work copy serves the black point and Shadows, Highlights and Clarity, Texture has + // its own; when both are needed they are reduced in one pass over the pixels. + let plane = |(sw, sh, y): (usize, usize, Vec<[f32; 1]>)| (sw, sh, y.into_iter().map(|[v]| v).collect::>()); + let (work_copy, texture_copy) = match (!tone.work_neutral() || black_point > 0.0, tone.texture != 0.0) { + (true, true) => { + let [work, texture] = reduce_pair(w, h, [WORK_SIDE, TEXTURE_SIDE], &lum); + (Some(work), Some(texture)) + } + (true, false) => (Some(plane(reduce(w, h, WORK_SIDE, |i| [lum(i)]))), None), + _ => (None, Some(plane(reduce(w, h, TEXTURE_SIDE, |i| [lum(i)])))), + }; + let p01 = work_copy.as_ref().map_or(0.0, |(_, _, y)| quantile(y, 0.001).max(2f32.powi(-20))); let black = if black_point > 0.0 { black_point * p01 } else { 0.0 }; - let work = (!tone.work_neutral()).then(|| { + let work = work_copy.filter(|_| !tone.work_neutral()).map(|(sw, sh, y)| { let l: Vec = y.iter().map(|v| v.max(p01).log2()).collect(); let n = l.len() as f64; let geo = (l.iter().map(|v| f64::from(*v)).sum::() / n) as f32; @@ -237,10 +339,10 @@ impl ToneMap { // change follow strong edges only: inside texture it stays smooth, so fine detail keeps // its contrast as in Camera Raw (with ε 0.01 shadow detail lost a fifth of it; with ε 4 the change bled ~16 px over 3-stop edges). let (a, b) = linear_fit(&l, &change, sw, sh, 2, UPSAMPLE_EPS); - Upsampled { sw, sh, a, b, floor: p01.log2() } + Upsampled::new(sw, sh, w, h, &a, &b, p01.log2()) }); - let texture = (tone.texture != 0.0).then(|| texture(w, h, &lum, tone.texture)); - Some(ToneMap { w, h, work, texture, black }) + let texture = texture_copy.map(|copy| texture(w, h, copy, tone.texture)); + Some(ToneMap { work, texture, black }) } /// The gain at full-size pixel (`x`, `y`) of linear luminance `lum`. @@ -248,7 +350,8 @@ impl ToneMap { if self.work.is_none() && self.texture.is_none() { return 1.0; } - let c = [&self.work, &self.texture].iter().filter_map(|u| u.as_ref()).map(|u| u.change(self.w, self.h, x, y, lum)).sum::(); + let log = (lum > 0.0).then(|| lum.log2()); + let c = [&self.work, &self.texture].iter().filter_map(|u| u.as_ref()).map(|u| u.change(x, y, log)).sum::(); c.clamp(-6.0, 6.0).exp2() } @@ -300,11 +403,9 @@ fn clarity(change: &mut [f32], l: &[f32], sw: usize, sh: usize, geo: f32, scale: } } -/// Texture `s` on a half-size copy: each Gaussian band of log₂ luminance through its measured +/// Texture `s` on its reduced copy `(sw, sh, y)` of the luminance: each Gaussian band of log₂ luminance through its measured /// response (zero for flat areas), carried to full size. -fn texture(w: usize, h: usize, lum: &(impl Fn(usize) -> f32 + Sync), s: f32) -> Upsampled { - let (sw, sh, y) = reduce(w, h, TEXTURE_SIDE, |i| [lum(i)]); - let y: Vec = y.into_iter().map(|[v]| v).collect(); +fn texture(w: usize, h: usize, (sw, sh, y): (usize, usize, Vec), s: f32) -> Upsampled { let p01 = quantile(&y, 0.001).max(2f32.powi(-20)); let l: Vec = y.iter().map(|v| v.max(p01).log2()).collect(); let scale = sw.max(sh) as f32 / TEXTURE_SIDE as f32; @@ -320,7 +421,7 @@ fn texture(w: usize, h: usize, lum: &(impl Fn(usize) -> f32 + Sync), s: f32) -> prev = base; } let (a, b) = linear_fit(&l, &change, sw, sh, 2, TEXTURE_UPSAMPLE_EPS); - Upsampled { sw, sh, a, b, floor: p01.log2() } + Upsampled::new(sw, sh, w, h, &a, &b, p01.log2()) } /// Texture's band response on the knots [`tables::TEXTURE_KNOTS`], read linearly, flat beyond. @@ -332,7 +433,13 @@ fn knots(c: &[f32; 11], d: f32) -> f32 { c[i - 1] + (c[i] - c[i - 1]) * f } +/// Columns (or output samples) one pass of [`gauss`] and [`box_mean`] accumulates at a time. +const BLOCK: usize = 64; + /// Gaussian blur of `v` (`w × h`), σ `sigma`, radius ⌈3σ⌉, mirrored edges. +/// +/// Every output sample is the taps' sum in tap order, as a plain loop over the kernel would +/// give; the passes run along the rows so that neighbouring samples are summed side by side. fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { if sigma <= 0.05 { return v.to_vec(); @@ -341,23 +448,49 @@ fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { let mut k: Vec = (-r..=r).map(|x| (-(x * x) as f32 / (2.0 * sigma * sigma)).exp()).collect(); let sum: f32 = k.iter().sum(); k.iter_mut().for_each(|v| *v /= sum); - let rows = par::map(h, |y| { - let src = &v[y * w..(y + 1) * w]; - (0..w as isize).map(|x| k.iter().enumerate().map(|(j, kv)| kv * src[mirror(x + j as isize - r, w)]).sum::()).collect::>() - }); - let tmp = rows.concat(); - let cols = par::map(w, |x| { - (0..h as isize).map(|y| k.iter().enumerate().map(|(j, kv)| kv * tmp[mirror(y + j as isize - r, h) * w + x]).sum::()).collect::>() - }); + let r = r as usize; + let mut tmp = vec![0.0f32; w * h]; + par::chunks_mut(&mut tmp, w, |y, out| blur_row(&v[y * w..(y + 1) * w], out, &k, r)); let mut out = vec![0.0f32; w * h]; - for (x, col) in cols.iter().enumerate() { - for (y, v) in col.iter().enumerate() { - out[y * w + x] = *v; + par::chunks_mut(&mut out, w, |y, row| { + // The rows the taps of output row `y` read. + let src: Vec<&[f32]> = (0..k.len()).map(|j| mirror(y as isize + j as isize - r as isize, h)).map(|m| &tmp[m * w..(m + 1) * w]).collect(); + for (x0, block) in row.chunks_mut(BLOCK).enumerate().map(|(i, b)| (i * BLOCK, b)) { + let mut acc = [-0.0f32; BLOCK]; + let acc = &mut acc[..block.len()]; + for (kv, s) in k.iter().zip(&src) { + for (a, s) in acc.iter_mut().zip(&s[x0..]) { + *a += kv * s; + } + } + block.copy_from_slice(acc); } - } + }); out } +/// One row of [`gauss`]: `out[x]` is the sum over the taps `j` of `k[j] · src[mirror(x + j − r)]`. +fn blur_row(src: &[f32], out: &mut [f32], k: &[f32], r: usize) { + let w = src.len(); + let edge = |x: usize| k.iter().enumerate().map(|(j, kv)| kv * src[mirror(x as isize + j as isize - r as isize, w)]).sum::(); + if w <= 2 * r { + out.iter_mut().enumerate().for_each(|(x, o)| *o = edge(x)); + return; + } + (0..r).chain(w - r..w).for_each(|x| out[x] = edge(x)); + // Inside, the taps read `src[x - r + j]` without mirroring. + for (off, block) in out[r..w - r].chunks_mut(BLOCK).enumerate().map(|(i, b)| (i * BLOCK, b)) { + let mut acc = [-0.0f32; BLOCK]; + let acc = &mut acc[..block.len()]; + for (j, kv) in k.iter().enumerate() { + for (a, s) in acc.iter_mut().zip(&src[off + j..]) { + *a += kv * s; + } + } + block.copy_from_slice(acc); + } +} + /// Minimum over a `(2r + 1)²` window, edges clamped. fn min_filter(v: &[f32], w: usize, h: usize, r: usize) -> Vec { let rows = par::map(h, |y| { @@ -378,10 +511,7 @@ fn min_filter(v: &[f32], w: usize, h: usize, r: usize) -> Vec { /// Camera Raw's Dehaze on linear ProPhoto RGB (see the module docs). pub(crate) struct Haze { - w: usize, - h: usize, - sw: usize, - sh: usize, + grid: Grid, /// Transmission per work-copy pixel (Dehaze > 0); empty for the veil of Dehaze < 0. t: Vec, /// Airlight, linear ProPhoto. @@ -413,7 +543,7 @@ impl Haze { } let air = air.map(|v| v.max(1e-6)); if amount < 0.0 { - return Some(Haze { w, h, sw, sh, t: Vec::new(), air, veil: HAZE_DOWN * -amount }); + return Some(Haze { grid: Grid::new(sw, sh, w, h), t: Vec::new(), air, veil: HAZE_DOWN * -amount }); } let air_p3 = p3(&air).map(|v| v.max(1e-6)); let scale = sw.max(sh) as f32 / WORK_SIDE as f32; @@ -426,15 +556,16 @@ impl Haze { let smooth = guided(&guide, &dark, sw, sh, ((HAZE_SMOOTH * scale).round() as usize).max(1), HAZE_EPS); let wgt = HAZE_UP * amount; let t = smooth.iter().map(|d| (1.0 - wgt * d).max(HAZE_T0)).collect(); - Some(Haze { w, h, sw, sh, t, air, veil: 0.0 }) + Some(Haze { grid: Grid::new(sw, sh, w, h), t, air, veil: 0.0 }) } /// Dehaze at full-size pixel (`x`, `y`) of linear ProPhoto `v`. + #[inline(always)] pub(crate) fn apply(&self, x: usize, y: usize, v: [f32; 3]) -> [f32; 3] { if self.t.is_empty() { return [0, 1, 2].map(|c| v[c] * (1.0 - self.veil) + self.air[c] * self.veil); } - let t = bilinear(&self.t, self.sw, self.sh, self.w, self.h, x, y).max(HAZE_T0); + let t = self.grid.at(&self.t, x, y).max(HAZE_T0); [0, 1, 2].map(|c| ((v[c] - self.air[c]) / t + self.air[c]).max(0.0)) } } @@ -489,33 +620,46 @@ fn mirror(i: isize, n: usize) -> usize { fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { let k = (2 * r + 1) as f64; let ri = r as isize; - let rows = par::map(h, |y| { + let mut tmp = vec![0.0f32; w * h]; + par::chunks_mut(&mut tmp, w, |y, out| { let src = &v[y * w..(y + 1) * w]; let mut acc: f64 = (-ri..=ri).map(|i| f64::from(src[mirror(i, w)])).sum(); - let mut out = vec![0.0f32; w]; for (x, o) in out.iter_mut().enumerate() { *o = (acc / k) as f32; let x = x as isize; acc += f64::from(src[mirror(x + ri + 1, w)]) - f64::from(src[mirror(x - ri, w)]); } - out }); - let tmp = rows.concat(); - let cols = par::map(w, |x| { - let at = |y: isize| f64::from(tmp[mirror(y, h) * w + x]); - let mut acc: f64 = (-ri..=ri).map(at).sum(); - let mut out = vec![0.0f32; h]; - for (y, o) in out.iter_mut().enumerate() { - *o = (acc / k) as f32; + // Down the columns: every column's running sum advances by one row at a time, the columns + // of a block side by side. Blocks in parallel, each into its own buffer. + let blocks = par::map(w.div_ceil(BLOCK), |bi| { + let (x0, x1) = (bi * BLOCK, ((bi + 1) * BLOCK).min(w)); + let n = x1 - x0; + let row = |y: isize| &tmp[mirror(y, h) * w + x0..mirror(y, h) * w + x1]; + let mut acc = [-0.0f64; BLOCK]; + let acc = &mut acc[..n]; + for i in -ri..=ri { + for (a, s) in acc.iter_mut().zip(row(i)) { + *a += f64::from(*s); + } + } + let mut out = vec![0.0f32; h * n]; + for (y, o) in out.chunks_exact_mut(n).enumerate() { let y = y as isize; - acc += at(y + ri + 1) - at(y - ri); + let (add, sub) = (row(y + ri + 1), row(y - ri)); + for (((o, a), p), q) in o.iter_mut().zip(acc.iter_mut()).zip(add).zip(sub) { + *o = (*a / k) as f32; + *a += f64::from(*p) - f64::from(*q); + } } out }); let mut out = vec![0.0f32; w * h]; - for (x, col) in cols.iter().enumerate() { - for (y, v) in col.iter().enumerate() { - out[y * w + x] = *v; + for (bi, block) in blocks.iter().enumerate() { + let x0 = bi * BLOCK; + let n = block.len() / h.max(1); + for (y, src) in block.chunks_exact(n.max(1)).enumerate() { + out[y * w + x0..y * w + x0 + n].copy_from_slice(src); } } out @@ -756,4 +900,147 @@ mod tests { assert!((out[i][0] - enc(y[i] * g[i])).abs() < 0.003, "{i}: {} vs {}", out[i][0], enc(y[i] * g[i])); } } + + // The code the faster versions replaced, kept to prove they give the same bits. + + /// `v` (`sw × sh`) at full-size pixel (`x`, `y`) of a `w × h` image, bilinearly. + fn bilinear_ref(v: &[f32], sw: usize, sh: usize, w: usize, h: usize, x: usize, y: usize) -> f32 { + let sx = ((x as f32 + 0.5) * sw as f32 / w as f32 - 0.5).clamp(0.0, (sw - 1) as f32); + let sy = ((y as f32 + 0.5) * sh as f32 / h as f32 - 0.5).clamp(0.0, (sh - 1) as f32); + let (x0, y0) = (sx as usize, sy as usize); + let (x1, y1) = ((x0 + 1).min(sw - 1), (y0 + 1).min(sh - 1)); + let (fx, fy) = (sx - x0 as f32, sy - y0 as f32); + let top = v[y0 * sw + x0] * (1.0 - fx) + v[y0 * sw + x1] * fx; + let bottom = v[y1 * sw + x0] * (1.0 - fx) + v[y1 * sw + x1] * fx; + top * (1.0 - fy) + bottom * fy + } + + fn gauss_ref(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { + if sigma <= 0.05 { + return v.to_vec(); + } + let r = (3.0 * sigma).ceil() as isize; + let mut k: Vec = (-r..=r).map(|x| (-(x * x) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let sum: f32 = k.iter().sum(); + k.iter_mut().for_each(|v| *v /= sum); + let rows = par::map(h, |y| { + let src = &v[y * w..(y + 1) * w]; + (0..w as isize).map(|x| k.iter().enumerate().map(|(j, kv)| kv * src[mirror(x + j as isize - r, w)]).sum::()).collect::>() + }); + let tmp = rows.concat(); + let cols = par::map(w, |x| { + (0..h as isize).map(|y| k.iter().enumerate().map(|(j, kv)| kv * tmp[mirror(y + j as isize - r, h) * w + x]).sum::()).collect::>() + }); + let mut out = vec![0.0f32; w * h]; + for (x, col) in cols.iter().enumerate() { + for (y, v) in col.iter().enumerate() { + out[y * w + x] = *v; + } + } + out + } + + fn box_mean_ref(v: &[f32], w: usize, h: usize, r: usize) -> Vec { + let k = (2 * r + 1) as f64; + let ri = r as isize; + let rows = par::map(h, |y| { + let src = &v[y * w..(y + 1) * w]; + let mut acc: f64 = (-ri..=ri).map(|i| f64::from(src[mirror(i, w)])).sum(); + let mut out = vec![0.0f32; w]; + for (x, o) in out.iter_mut().enumerate() { + *o = (acc / k) as f32; + let x = x as isize; + acc += f64::from(src[mirror(x + ri + 1, w)]) - f64::from(src[mirror(x - ri, w)]); + } + out + }); + let tmp = rows.concat(); + let cols = par::map(w, |x| { + let at = |y: isize| f64::from(tmp[mirror(y, h) * w + x]); + let mut acc: f64 = (-ri..=ri).map(at).sum(); + let mut out = vec![0.0f32; h]; + for (y, o) in out.iter_mut().enumerate() { + *o = (acc / k) as f32; + let y = y as isize; + acc += at(y + ri + 1) - at(y - ri); + } + out + }); + let mut out = vec![0.0f32; w * h]; + for (x, col) in cols.iter().enumerate() { + for (y, v) in col.iter().enumerate() { + out[y * w + x] = *v; + } + } + out + } + + /// Values around log₂ luminance, from a fixed LCG. + fn noise(n: usize, seed: u64) -> Vec { + let mut s = seed; + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32) * 14.0 - 12.0 + }) + .collect() + } + + fn same(a: &[f32], b: &[f32]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.to_bits() == b.to_bits()) + } + + #[test] + fn gauss_gives_the_bits_of_the_tap_loop() { + // Sizes below, around and above the kernel (edges only, a few interior samples, mostly interior). + for (w, h) in [(1, 1), (5, 3), (13, 40), (64, 7), (65, 70), (131, 97), (300, 41)] { + let v = noise(w * h, (w * 31 + h) as u64); + for sigma in [0.04, 0.42, 1.0, 2.1, 4.2, 8.4, 13.44] { + assert!(same(&gauss(&v, w, h, sigma), &gauss_ref(&v, w, h, sigma)), "{w}x{h} sigma {sigma}"); + } + } + } + + #[test] + fn box_mean_gives_the_bits_of_the_column_loop() { + for (w, h) in [(1, 1), (5, 3), (13, 40), (64, 7), (65, 70), (131, 97), (300, 41)] { + let v = noise(w * h, (w * 17 + h) as u64); + for r in [1, 2, 8, 32, 128] { + assert!(same(&box_mean(&v, w, h, r), &box_mean_ref(&v, w, h, r)), "{w}x{h} r {r}"); + } + } + } + + #[test] + fn the_tap_tables_give_the_bits_of_the_per_pixel_lookup() { + for ((sw, sh), (w, h)) in [((1, 1), (7, 5)), ((3, 2), (3, 2)), ((12, 9), (97, 61)), ((308, 205), (1232, 820)), ((1232, 616), (8256, 4128))] { + let a = noise(sw * sh, 5); + let b = noise(sw * sh, 6); + let grid = Grid::new(sw, sh, w, h); + let ab: Vec<[f32; 2]> = a.iter().zip(&b).map(|(a, b)| [*a, *b]).collect(); + for y in (0..h).step_by(if h > 1000 { 7 } else { 1 }) { + for x in (0..w).step_by(if w > 1000 { 5 } else { 1 }) { + let (ra, rb) = (bilinear_ref(&a, sw, sh, w, h, x, y), bilinear_ref(&b, sw, sh, w, h, x, y)); + assert_eq!(grid.at(&a, x, y).to_bits(), ra.to_bits(), "{sw}x{sh} to {w}x{h} at {x},{y}"); + let [pa, pb] = grid.at2(&ab, x, y); + assert!(pa.to_bits() == ra.to_bits() && pb.to_bits() == rb.to_bits(), "{sw}x{sh} to {w}x{h} at {x},{y}"); + } + } + } + } + + #[test] + fn reduce_pair_gives_the_bits_of_two_reductions() { + for (w, h) in [(1, 1), (7, 5), (100, 61), (1233, 77), (2500, 1700), (333, 2999)] { + let v = noise(w * h, (w + 3 * h) as u64); + for sides in [[1232, 2464], [100, 50], [7, 8], [1232, 1232], [3, 600]] { + let pair = reduce_pair(w, h, sides, |i| v[i]); + for (g, side) in sides.iter().enumerate() { + let (sw, sh, one) = reduce(w, h, *side, |i| [v[i]]); + let one: Vec = one.into_iter().map(|[v]| v).collect(); + assert!((sw, sh) == (pair[g].0, pair[g].1) && same(&one, &pair[g].2), "{w}x{h} side {side}"); + } + } + } + } } diff --git a/crates/raw/tests/it/raw_corpus.rs b/crates/raw/tests/it/raw_corpus.rs index afd168a38a..7d2ca341d2 100644 --- a/crates/raw/tests/it/raw_corpus.rs +++ b/crates/raw/tests/it/raw_corpus.rs @@ -68,9 +68,8 @@ const WANTS: &[Want] = &[ model: "DSC-RX0", size: (4832, 3224), cfa: [0, 1, 1, 2], - // No readable BlackLevel tag: the cRAW fallback of 512 (#1902). The file's darkest - // samples sit near 800, so this body's real level is still to be read. - black: &[512.0], + // SR2SubIFD black levels, verified with the metadata oracle (not the 512 fallback). + black: &[800.0; 4], white: [16301.0; 3], }, // The G9's high-resolution mode: a 10480 × 7794 sensor cropped to 10368 × 7776. @@ -109,6 +108,9 @@ fn decode_matches_the_measured_oracles() { let cfa = s.cfa.as_ref().unwrap_or_else(|| panic!("{}: no CFA", w.file)); assert_eq!(cfa.colors, w.cfa, "{}", w.file); assert_eq!(s.black.values, w.black, "{}", w.file); + if w.file == "DSC00009.ARW" { + assert_eq!(s.camera_wb, Some([2056.0 / 1024.0, 1.0, 1908.0 / 1024.0])); + } for ch in 0..3 { assert!((s.white[ch] - w.white[ch]).abs() < 0.5, "{} white[{ch}] = {}", w.file, s.white[ch]); } @@ -130,11 +132,11 @@ fn developing_produces_the_crop_in_16bit_rgb() { hi = (*v).max(hi); } // A real exposure covers a sane share of the range and never leaves it. The PowerShot - // CR2 and the RX0 ARW are the documented exceptions: neither carries an as-shot white + // CR2 is the documented exception: it carries no as-shot white // balance we read, so the grey-world estimate brightens these scenes (the PowerShot's // own DNG, with its file WB, develops blacks to ~0 — reading the maker-note WB of - // Canon and Sony is the follow-up). - let estimated_wb = matches!(w.file, "IMG_4059.CR2" | "DSC00009.ARW"); + // Canon is the follow-up). Sony's SR2SubIFD now supplies the applied gains and black. + let estimated_wb = w.file == "IMG_4059.CR2"; let black_cap: u16 = if estimated_wb { 16384 } else { 4096 }; assert!(lo < black_cap, "{}: developed blacks at {lo}", w.file); assert!(hi > u16::MAX / 4, "{}: developed highlights at {hi}", w.file); diff --git a/crates/testkit/src/gpu.rs b/crates/testkit/src/gpu.rs index 700908ecfb..3bb5df1ed8 100644 --- a/crates/testkit/src/gpu.rs +++ b/crates/testkit/src/gpu.rs @@ -11,6 +11,13 @@ //! - **libvulkan** with the NVIDIA and lavapipe drivers both installed: `wgpu::Instance::new` on //! several threads segfaults. //! +//! Separately, the **Intel Vulkan driver** on Windows (`igvk64.dll`) crashes a process that so +//! much as creates a wgpu instance with Vulkan in it (#4), even on one thread. The app leaves +//! Vulkan out on Intel; tests use wgpu's defaults, so on such a machine run them with +//! `WGPU_BACKEND=dx12`. Tests that build their own instance read it through +//! `InstanceDescriptor::new_without_display_handle_from_env`; `wgpu::Instance::default()` +//! ignores it. +//! //! So every test that builds a GPU harness (or its own wgpu device) holds [`gpu_lock`] for its //! whole run, harness included. Under nextest each test is its own process and the lock costs //! nothing; `.config/nextest.toml` caps how many of those run at once instead. diff --git a/crates/text/src/closed_path_tests.rs b/crates/text/src/closed_path_tests.rs new file mode 100644 index 0000000000..64d37d3d9c --- /dev/null +++ b/crates/text/src/closed_path_tests.rs @@ -0,0 +1,149 @@ +//! Closed-path regression fixtures use the same four cubic knots as the shape ellipse. +use super::*; +use photocraft_doc::Knot; +use photocraft_geom::Point; + +fn ellipse() -> Subpath { + let k = 0.552_284_749_830_793_4; + let point = |x, y| Point::new(x, y); + Subpath { + closed: true, + knots: vec![ + Knot::smooth(point(100.0, 0.0), point(100.0 - 100.0 * k, 0.0), point(100.0 + 100.0 * k, 0.0)), + Knot::smooth(point(200.0, 60.0), point(200.0, 60.0 - 60.0 * k), point(200.0, 60.0 + 60.0 * k)), + Knot::smooth(point(100.0, 120.0), point(100.0 + 100.0 * k, 120.0), point(100.0 - 100.0 * k, 120.0)), + Knot::smooth(point(0.0, 60.0), point(0.0, 60.0 + 60.0 * k), point(0.0, 60.0 - 60.0 * k)), + ], + op: Default::default(), + } +} + +fn centre(m: [f64; 6], x: f64) -> (f64, f64) { + (m[0] * x + m[4], m[1] * x + m[5]) +} + +#[test] +fn closed_rectangle_left_edge_continues_past_the_top_left_seam() { + let p = Subpath::polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let start = arc_length_at(&p, false, 0.0, 50.0).unwrap(); + assert!((start - 350.0).abs() < 1e-6); + let f = PathFrame::new(&p, start as f32, false).unwrap(); + let m = f.frame(75.0).expect("glyph after the seam remains on the closed path"); + let q = centre(m, 75.0); + assert!((q.0 - 25.0).abs() < 1e-6 && q.1.abs() < 1e-6, "{q:?}"); + assert_eq!(&m[..4], &[1.0, 0.0, -0.0, 1.0], "text now travels right on the top side"); + assert_eq!(f.apply(75.0, 0.0), q, "caret and glyph use the same wrapped parameter"); +} + +#[test] +fn closed_ellipse_upper_left_and_apex_cross_the_seam_in_both_directions() { + for reverse in [false, true] { + let mut p = ellipse(); + if reverse { + p.knots.reverse(); + for k in &mut p.knots { + std::mem::swap(&mut k.in_ctrl, &mut k.out_ctrl); + } + } + for flip in [false, true] { + let whole = PathFrame::new(&p, 0.0, flip).unwrap(); + let length = whole.length(); + for remaining in [0.001, 0.2, 30.0] { + let start = (length - remaining) as f32; + let f = PathFrame::new(&p, start, flip).unwrap(); + let x = remaining + 15.0; + let m = f.frame(x).expect("ellipse glyph after the seam must remain visible"); + let (point, tangent) = whole.at((f64::from(start) + x).rem_euclid(length)); + let actual = centre(m, x); + assert!((actual.0 - point.0).hypot(actual.1 - point.1) < 1e-6); + assert!((m[0] - tangent.0).abs() < 1e-6 && (m[1] - tangent.1).abs() < 1e-6); + assert!((m[0] * m[3] - m[1] * m[2] - 1.0).abs() < 1e-6, "no reflection or scale jump"); + let before = f.apply(remaining - 0.001, 0.0); + let after = f.apply(remaining + 0.001, 0.0); + assert!((before.0 - after.0).hypot(before.1 - after.1) < 0.01, "seam is continuous"); + } + } + } +} + +#[test] +fn closed_path_shows_one_lap_without_repeating_glyph_centres() { + let p = ellipse(); + let length = PathFrame::new(&p, 0.0, false).unwrap().length(); + let f = PathFrame::new(&p, (length - 5.0) as f32, false).unwrap(); + let mut points = Vec::new(); + for i in 0..100 { + let x = length * i as f64 / 100.0; + let m = f.frame(x).expect("one complete lap is available from the text origin"); + points.push(centre(m, x)); + } + for (i, a) in points.iter().enumerate() { + assert!(points.iter().skip(i + 1).all(|b| (a.0 - b.0).hypot(a.1 - b.1) > 0.01)); + } + assert!(f.frame(length).is_none(), "the first repeated location is overflow, not another lap"); + assert!(f.frame(length + 20.0).is_none()); +} + +#[test] +fn open_path_clipping_offsets_and_end_tangents_stay_unchanged() { + let p = Subpath::polyline(&[(0.0, 0.0), (100.0, 0.0)]); + for flip in [false, true] { + let f = PathFrame::new(&p, 25.0, flip).unwrap(); + assert!(f.frame(-26.0).is_none()); + assert!(f.frame(-25.0).is_some()); + assert!(f.frame(75.0).is_some()); + assert!(f.frame(76.0).is_none()); + let q = f.apply(100.0, 0.0); + assert!((q.0 - if flip { -25.0 } else { 125.0 }).abs() < 1e-9 && q.1.abs() < 1e-9); + } +} + +#[test] +fn closed_path_alignment_uses_one_lap_from_the_text_left_edge() { + let p = ellipse(); + let length = PathFrame::new(&p, 0.0, false).unwrap().length(); + for left in [-length / 2.0, -length, 0.0] { + let shape = TextShape::Path { path: p.clone(), start: (length - 5.0) as f32, flip: false }; + let warp = Warp::on_path_with_text_start(&shape, left).unwrap(); + assert!(matches!(warp.place_glyph(left + 0.5), Placement::Frame(_))); + assert!(matches!(warp.place_glyph(left + length - 0.5), Placement::Frame(_))); + assert_eq!(warp.place_glyph(left - 0.5), Placement::Hidden); + assert_eq!(warp.place_glyph(left + length + 0.5), Placement::Hidden); + // The origin and tangent at each text coordinate are independent of clipping alignment. + let reference = Warp::on_path(&shape).unwrap(); + assert_eq!(warp.apply(left, 0.0), reference.apply(left, 0.0)); + } +} + +#[test] +fn closed_path_start_offsets_wrap_and_invalid_coordinates_are_hidden() { + let p = Subpath::polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + for start in [-10.0, 0.0, 400.0, 790.0] { + let f = PathFrame::new(&p, start, false).unwrap(); + let reference = PathFrame::new(&p, start.rem_euclid(400.0), false).unwrap(); + assert_eq!(f.frame(20.0), reference.frame(20.0)); + assert!(f.frame(f64::NAN).is_none()); + assert!(f.frame(f64::INFINITY).is_none()); + } +} + +#[test] +fn caret_projection_roundtrips_closed_seams_and_open_offsets() { + let p = ellipse(); + let length = PathFrame::new(&p, 0.0, false).unwrap().length(); + for flip in [false, true] { + for left in [0.0, -length / 2.0, -length] { + let shape = TextShape::Path { path: p.clone(), start: (length - 20.0) as f32, flip }; + let w = Warp::on_path_with_text_start(&shape, left).unwrap(); + for x in [left + 0.5, left + 50.0, left + length / 2.0, left + length - 0.5] { + let point = w.apply(x, 0.0); + let actual = w.path_text_x(point.0, point.1).unwrap(); + assert!((actual - x).abs() < 1e-6, "caret must not jump to start after seam: {actual} vs {x}"); + } + } + let shape = TextShape::Path { path: Subpath::polyline(&[(0.0, 0.0), (100.0, 0.0)]), start: 25.0, flip }; + let w = Warp::on_path(&shape).unwrap(); + let x = w.path_text_x(40.0, 0.0).unwrap(); + assert!((x - if flip { 35.0 } else { 15.0 }).abs() < 1e-9); + } +} diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index d31b888fad..ac05d72a65 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -10,8 +10,8 @@ //! into text space: a line becomes a column running top to bottom, and successive columns advance //! right to left. Within a column, CJK characters stay upright (centred on the column, placed with //! the font's vertical metrics: `VORG`, `vhea`/`vmtx`, else the ideographic em box) and use the -//! font's vertical alternates (`vert`) for punctuation, brackets and the long-vowel mark; other -//! text (Latin, digits) runs rotated 90° clockwise, Photoshop's default. Lines, clusters, carets +//! font's vertical alternates (`vert`) for punctuation, brackets and the long-vowel mark. Roman +//! letters stand upright one per em unless the run sets `rotate_roman`. Lines, clusters, carets //! and hit tests stay in line space; [`TextLayout::to_text`] / [`TextLayout::to_line`] convert. use std::borrow::Cow; diff --git a/crates/text/src/layout/shaping.rs b/crates/text/src/layout/shaping.rs index 283c7e2ef3..c7d701c5d7 100644 --- a/crates/text/src/layout/shaping.rs +++ b/crates/text/src/layout/shaping.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use std::cell::Cell; use std::ops::Range; -use parley::{Alignment, AlignmentOptions, FontFeatures, Layout, LayoutContext, StyleProperty}; +use parley::{Alignment, AlignmentOptions, FontFeatures, Layout, LayoutContext, PositionedLayoutItem, StyleProperty}; use photocraft_doc::text::{CharStyle, ParagraphStyle, TextAlign, TextDirection}; use super::area::{LineMetrics, MAX_AREA_PASSES, area_metrics, break_area}; @@ -161,7 +161,10 @@ impl VerticalPiece<'_> { fn push_all(&self, b: &mut parley::RangedBuilder<'_, RunBrush>, piece: &str) { let mut seg: Option<(usize, VClass)> = None; for (i, ch) in piece.char_indices() { - let cls = vertical_class(ch); + let cls = match vertical_class(ch) { + VClass::Rotate if !self.style.rotate_roman && upright_roman(ch) => VClass::Upright, + cls => cls, + }; match seg { Some((_, c)) if c == cls => {} Some((from, c)) => { @@ -193,6 +196,7 @@ pub(super) struct Para<'a> { /// Runs intersecting the paragraph: `si0..si_end`. si0: usize, si_end: usize, + roman: Vec<(Range, f32, f32, usize)>, fallback: Vec, pub(super) indent_start: f32, indent_end: f32, @@ -242,6 +246,7 @@ impl<'a> Para<'a> { tabs, si0, si_end, + roman: Vec::new(), fallback, indent_start, indent_end, @@ -253,9 +258,33 @@ impl<'a> Para<'a> { area_budget: Cell::new(MAX_AREA_PASSES), }; para.break_scale = para.horizontal_break_scale(); + para.roman = para.roman_ranges(); para } + fn roman_ranges(&self) -> Vec<(Range, f32, f32, usize)> { + let env = self.env; + let mut roman = Vec::new(); + if env.vertical { + for (ri, st) in env.styles.iter().enumerate().take(self.si_end).skip(self.si0) { + let rs = env.run_starts[ri]; + let (a, z) = (rs.max(self.start), (rs + env.runs[ri].len).min(self.content_end)); + if a >= z || st.rotate_roman { + continue; + } + let base = a - self.start + self.prefix.len(); + let piece = self.ptext.get(base..base + (z - a)).unwrap_or(""); + let px = st.size_pt * env.k; + for (i, ch) in piece.char_indices() { + if upright_roman(ch) && !ch.is_whitespace() { + roman.push(((base + i)..(base + i + ch.len_utf8()), st.tracking / 1000.0 * px, px, ri)); + } + } + } + } + roman + } + pub(super) fn first_style(&self) -> &'a CharStyle { &self.env.styles[self.si0] } @@ -290,7 +319,7 @@ impl<'a> Para<'a> { } /// Shapes the paragraph, each tab widened by its letter spacing in `tab_spacing` (px). - fn shape(&self, lcx: &mut LayoutContext, fcx: &mut parley::FontContext, tab_spacing: &[f32]) -> Layout { + fn shape(&self, lcx: &mut LayoutContext, fcx: &mut parley::FontContext, tab_spacing: &[f32], roman_spacing: &[f32]) -> Layout { let env = self.env; let mut b = lcx.ranged_builder(fcx, &self.ptext, 1.0, false); // Paragraph-start style as the default (covers the direction mark and empty @@ -318,6 +347,12 @@ impl<'a> Para<'a> { for (&at, &spacing) in self.tabs.iter().zip(tab_spacing) { b.push(StyleProperty::LetterSpacing(spacing), at..at + 1); } + for ((range, _, _, ri), &spacing) in self.roman.iter().zip(roman_spacing) { + b.push(StyleProperty::LetterSpacing(spacing), range.clone()); + let mut feats = feature_list(&env.styles[*ri], env.small_caps[*ri]); + feats.extend(["kern", "liga", "clig", "dlig"].map(|f| format!("\"{f}\" 0"))); + b.push(StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), range.clone()); + } b.build(&self.ptext) } @@ -383,11 +418,18 @@ impl<'a> Para<'a> { /// that layout gives until they agree; if they don't settle, keep the safe layout. pub(super) fn break_paragraph(&self, lcx: &mut LayoutContext, fcx: &mut parley::FontContext, flow: &Flow) -> (Layout, Vec, bool) { let wide = if self.env.wraps { self.tab_px } else { 0.0 }; - let mut layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()]); + let mut roman_spacing: Vec = self.roman.iter().map(|r| r.1).collect(); + let mut layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()], &roman_spacing); + if !self.roman.is_empty() { + let _ = self.break_lines(&mut layout, flow); + let advances = cluster_advances(&layout, &self.roman); + roman_spacing = self.roman.iter().zip(&advances).map(|((_, track, em, _), a)| a.map_or(*track, |a| em + track - (a - track))).collect(); + layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()], &roman_spacing); + } let (mut slots, mut full) = self.break_lines(&mut layout, flow); if self.env.wraps && !self.tabs.is_empty() - && let Some((settled, settled_slots, settled_full)) = self.settle_tabs(lcx, fcx, &layout, flow) + && let Some((settled, settled_slots, settled_full)) = self.settle_tabs(lcx, fcx, &layout, flow, &roman_spacing) { layout = settled; slots = settled_slots; @@ -403,12 +445,13 @@ impl<'a> Para<'a> { fcx: &mut parley::FontContext, layout: &Layout, flow: &Flow, + roman_spacing: &[f32], ) -> Option<(Layout, Vec, bool)> { let first = self.tab_widths(layout); let mut want: Vec = first.iter().map(|t| t.width).collect(); for _ in 0..4 { let spacing: Vec = first.iter().zip(&want).map(|(t, w)| w / t.scale - (t.advance - self.tab_px)).collect(); - let mut next = self.shape(lcx, fcx, &spacing); + let mut next = self.shape(lcx, fcx, &spacing, roman_spacing); let (next_slots, next_full) = self.break_lines(&mut next, flow); let got: Vec = self.tab_widths(&next).iter().map(|t| t.width).collect(); if got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 0.01) { @@ -436,3 +479,28 @@ impl<'a> Para<'a> { AlignmentOptions { align_when_overflowing: !self.env.wraps } } } + +/// Whether vertical type sets `c` upright when its style doesn't rotate roman text (#9470): the +/// rotating class except half-width katakana and Hangul, which keep their rotated setting. +fn upright_roman(c: char) -> bool { + vertical_class(c) == VClass::Rotate && !(0xFF61..=0xFFDC).contains(&(c as u32)) +} + +/// The shaped advance (px, letter spacing included) of the cluster starting each of `ranges` +/// (sorted byte ranges of the shaped text), `None` where no cluster starts there. +fn cluster_advances(layout: &Layout, ranges: &[(Range, f32, f32, usize)]) -> Vec> { + let mut out = vec![None; ranges.len()]; + for line in layout.lines() { + for item in line.items() { + let PositionedLayoutItem::GlyphRun(gr) = item else { + continue; + }; + for c in gr.run().visual_clusters() { + if let Ok(i) = ranges.binary_search_by_key(&c.text_range().start, |r| r.0.start) { + out[i] = Some(c.advance()); + } + } + } + } + out +} diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 7c51759482..16d63c68b8 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -218,6 +218,25 @@ mod nonfinite_tests { assert_eq!(char_style(&[], &d, &[], 1.0).size_pt, 24.0); } + /// #9470: `BaselineDirection` sets vertical type's roman text upright (1, what Photoshop's + /// Vertical Type tool writes in the run) or rotated (2); a run without one takes the style + /// sheet's (Photoshop's default sheet says 2). It is written back. + #[test] + fn baseline_direction_round_trips() { + let sheet = parse(b"<< /BaselineDirection 2 >>").unwrap(); + let upright = parse(b"<< /BaselineDirection 1 >>").unwrap(); + assert!(!char_style(&[Some(&sheet)], &upright, &[], 1.0).rotate_roman, "the run's own value wins"); + let plain = parse(b"<< /FontSize 24.0 >>").unwrap(); + assert!(char_style(&[Some(&sheet)], &plain, &[], 1.0).rotate_roman, "else the sheet's"); + assert!(!char_style(&[], &plain, &[], 1.0).rotate_roman, "none at all: upright"); + for rotate in [false, true] { + let s = CharStyle { rotate_roman: rotate, ..Default::default() }; + let data = style_sheet_data(&s, 0, 1.0); + assert_eq!(data.get("BaselineDirection").and_then(E::as_i64), Some(if rotate { 2 } else { 1 })); + assert_eq!(char_style(&[Some(&sheet)], &data, &[], 1.0).rotate_roman, rotate); + } + } + /// #5645: `FontBaseline` (1 superscript, 2 subscript) is read and written back. #[test] fn font_baseline_round_trips() { diff --git a/crates/text/src/psd/build.rs b/crates/text/src/psd/build.rs index c92a3cffea..4be80f27ee 100644 --- a/crates/text/src/psd/build.rs +++ b/crates/text/src/psd/build.rs @@ -54,6 +54,7 @@ pub(crate) fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E { FontBaseline::Subscript => 2, }), ), + ("BaselineDirection".into(), E::Int(if s.rotate_roman { 2 } else { 1 })), ("Underline".into(), E::Bool(s.underline)), ("Strikethrough".into(), E::Bool(s.strikethrough)), ("Ligatures".into(), E::Bool(s.ligatures)), diff --git a/crates/text/src/psd/import.rs b/crates/text/src/psd/import.rs index e29ec75fb6..aea712d62c 100644 --- a/crates/text/src/psd/import.rs +++ b/crates/text/src/psd/import.rs @@ -603,6 +603,9 @@ pub(crate) fn char_style(base: &[Option<&E>], d: &E, fonts: &[String], k: f32) - Some(2) => FontBaseline::Subscript, _ => FontBaseline::Normal, }; + // Vertical type's roman text: 2 rotated along the column, 1 upright (#9470). A run without + // its own value takes the style sheet's, which Photoshop writes as 2. + s.rotate_roman = g("BaselineDirection").and_then(E::as_i64) == Some(2); if let Some(c) = g("FillColor") { // Positions matter (alpha, then the channels): a non-finite entry voids the colour. let v: Vec = c.get("Values").and_then(E::as_array).map(|a| a.iter().filter_map(E::as_f64).collect()).unwrap_or_default(); diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index dacd120dcd..4f36c68a83 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -281,7 +281,8 @@ fn glyph_center(layout: &TextLayout, g: &PlacedGlyph, font: &skrifa::FontRef, si /// The deformation of a type layer: the path it runs along, or its Warp Text settings (None /// when neither applies). pub fn layout_deform(layout: &TextLayout, layer: &photocraft_doc::TextLayer) -> Option { - Warp::on_path(&layer.shape).or_else(|| layout_warp(layout, layer.warp.as_ref())) + let text_start = layout.bounds().map_or(0.0, |bounds| f64::from(bounds[0])); + Warp::on_path_with_text_start(&layer.shape, text_start).or_else(|| layout_warp(layout, layer.warp.as_ref())) } /// The warp to apply to `layout` (None when `warp` is absent, `warpNone` or flat). diff --git a/crates/text/src/spell.rs b/crates/text/src/spell.rs index bc2afa63c8..31ddf7bf03 100644 --- a/crates/text/src/spell.rs +++ b/crates/text/src/spell.rs @@ -216,6 +216,13 @@ struct Rows { cur: Vec, } +/// Damerau–Levenshtein (optimal string alignment) distance between `a` and `b` in chars, or None +/// when above `max`. Exposed for "did you mean" hints elsewhere (engine command ids, #3674). +pub fn edit_distance(a: &str, b: &str, max: usize) -> Option { + let (a, b): (Vec, Vec) = (a.chars().collect(), b.chars().collect()); + distance(&a, &b, max, &mut Rows::default()) +} + /// Damerau–Levenshtein (optimal string alignment) distance, or None when above `max`. fn distance(a: &[char], b: &[char], max: usize, rows: &mut Rows) -> Option { let (n, m) = (a.len(), b.len()); @@ -327,5 +334,7 @@ mod tests { assert_eq!(distance(&c("teh"), &c("the"), 2, &mut r), Some(1)); assert_eq!(distance(&c("teh"), &c("toe"), 2, &mut r), Some(2)); assert_eq!(distance(&c("teh"), &c("banana"), 2, &mut r), None); + assert_eq!(edit_distance("edit.undoo", "edit.undo", 2), Some(1)); + assert_eq!(edit_distance("teh", "banana", 2), None); } } diff --git a/crates/text/src/vertical_tests.rs b/crates/text/src/vertical_tests.rs index 0da13b3497..1f36298b34 100644 --- a/crates/text/src/vertical_tests.rs +++ b/crates/text/src/vertical_tests.rs @@ -19,6 +19,15 @@ fn vertical(text: &str, family: &str, size_pt: f32) -> TextLayer { } } +/// [`vertical`] with its roman text rotated along the column (PSD `BaselineDirection` 2). +fn rotated(text: &str, family: &str, size_pt: f32) -> TextLayer { + let mut t = vertical(text, family, size_pt); + for r in &mut t.runs { + r.style.rotate_roman = true; + } + t +} + /// An engine with an installed Japanese font registered, and that font's family. fn cjk_engine() -> Option<(TextEngine, String)> { #[cfg(not(target_arch = "wasm32"))] @@ -53,7 +62,7 @@ fn classes_follow_vertical_orientation() { #[test] fn latin_is_rotated_and_runs_down_columns_right_to_left() { let mut e = TextEngine::new(); - let l = e.layout(&vertical("abc\nde", "Inter", 20.0), 72.0); + let l = e.layout(&rotated("abc\nde", "Inter", 20.0), 72.0); assert!(l.vertical); assert_eq!(l.lines.len(), 2); assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Rotated)); @@ -67,16 +76,90 @@ fn latin_is_rotated_and_runs_down_columns_right_to_left() { // Rotated text is centred on the column through the anchor (x = 0): its baseline sits left. assert!(a.x < 0.0 && a.x > -10.0, "{a:?}"); // Bounds: one column for "abc" is taller than wide. - let one = e.layout(&vertical("abcdef", "Inter", 20.0), 72.0); + let one = e.layout(&rotated("abcdef", "Inter", 20.0), 72.0); let [x0, y0, x1, y1] = one.bounds().unwrap(); assert!((y1 - y0) > 2.0 * (x1 - x0), "{:?}", one.bounds()); assert!((x0 + 10.0).abs() < 1e-3 && (x1 - 10.0).abs() < 1e-3 && y0.abs() < 1e-3); } +/// #9470: Photoshop's Vertical Type tool sets roman text upright, one character per em down the +/// column (`BaselineDirection` 1): a word is a stack of letters, not the word turned on its side. +#[test] +fn latin_stands_upright_one_per_em_by_default() { + let mut e = TextEngine::new(); + let l = e.layout(&vertical("VERTICAL", "Inter", 36.0), 72.0); + assert!(l.vertical); + assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Upright), "{:?}", l.glyphs); + // One em (36 px) per character down a single column. + let steps: Vec = l.glyphs.windows(2).map(|w| w[1].y - w[0].y).collect(); + assert!(steps.iter().all(|d| (d - 36.0).abs() < 0.5), "{steps:?}"); + assert!(l.glyphs.windows(2).all(|w| (w[1].x - w[0].x).abs() < 6.0), "one column: {:?}", l.glyphs); + // Rendered: a narrow stack about 8 em tall, much taller than the rotated word. + let at = Affine::translate(200.0, 40.0); + let (_, up) = e.render(&TextLayer { transform: at, ..vertical("VERTICAL", "Inter", 36.0) }, 72.0, PixelFormat::RGBA8); + let (_, turned) = e.render(&TextLayer { transform: at, ..rotated("VERTICAL", "Inter", 36.0) }, 72.0, PixelFormat::RGBA8); + assert!(up.rect.width() < 40 && up.rect.height() > 7 * 36, "{:?}", up.rect); + assert!(up.rect.height() > turned.rect.height() + 50, "{:?} vs {:?}", up.rect, turned.rect); +} + +/// An engine with an installed font that joins "fi" into one ligature glyph, and its family. +fn ligature_engine() -> Option<(TextEngine, String)> { + #[cfg(not(target_arch = "wasm32"))] + for path in [ + "/System/Library/Fonts/Supplemental/Hoefler Text.ttc", + "/System/Library/Fonts/Supplemental/Baskerville.ttc", + "/System/Library/Fonts/Supplemental/Didot.ttc", + "/System/Library/Fonts/Times.ttc", + "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf", + "C:\\Windows\\Fonts\\calibri.ttf", + "C:\\Windows\\Fonts\\cambria.ttc", + ] { + let Ok(bytes) = std::fs::read(path) else { continue }; + let mut e = TextEngine::new(); + for fam in e.fonts.register_font_data(bytes) { + let flat = TextLayer { orientation: Orientation::Horizontal, ..vertical("fi", &fam, 30.0) }; + if e.layout(&flat, 72.0).glyphs.len() == 1 { + return Some((e, fam)); + } + } + } + eprintln!("no installed font with an fi ligature found: skipping"); + None +} + +/// CodeRabbit on #9478: upright roman letters never join into a ligature; "fi" and "ffl" are +/// one glyph per letter, one em apart. +#[test] +fn upright_roman_letters_stay_apart_without_ligatures() { + let Some((mut e, fam)) = ligature_engine() else { return }; + for text in ["fi", "ffl", "office"] { + let l = e.layout(&vertical(text, &fam, 30.0), 72.0); + assert_eq!(l.glyphs.len(), text.chars().count(), "{fam} {text}: one glyph per letter: {:?}", l.glyphs); + let steps: Vec = l.glyphs.windows(2).map(|w| w[1].y - w[0].y).collect(); + assert!(steps.iter().all(|d| (d - 30.0).abs() < 0.5), "{fam} {text}: one em apart: {steps:?}"); + } +} + +/// CodeRabbit on #9478: half-width katakana and Hangul keep their rotated setting; only roman +/// text stands upright by default (#9470 leaves CJK as it was). +#[test] +fn half_width_cjk_stays_rotated_beside_upright_roman() { + let mut e = TextEngine::new(); + for text in ["アイウ", "ᄀᄁᆪ"] { + let l = e.layout(&vertical(text, "Inter", 24.0), 72.0); + assert!(!l.glyphs.is_empty()); + assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Rotated), "{text}: {:?}", l.glyphs); + } + let l = e.layout(&vertical("A", "Inter", 24.0), 72.0); + assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Upright), "roman stays upright"); +} + #[test] fn rotated_render_ink_is_taller_than_wide() { let mut e = TextEngine::new(); - let horizontal = TextLayer { orientation: Orientation::Horizontal, ..vertical("Vertical", "Inter", 30.0) }; + let horizontal = TextLayer { orientation: Orientation::Horizontal, ..rotated("Vertical", "Inter", 30.0) }; let (_, h) = e.render(&TextLayer { transform: Affine::translate(100.0, 50.0), ..horizontal.clone() }, 72.0, PixelFormat::RGBA8); let (_, v) = e.render(&TextLayer { transform: Affine::translate(100.0, 50.0), orientation: Orientation::Vertical, ..horizontal }, 72.0, PixelFormat::RGBA8); assert!(h.rect.width() > h.rect.height()); @@ -109,7 +192,7 @@ fn caret_hit_test_and_arrow_geometry_follow_columns() { #[test] fn box_text_wraps_columns_within_the_box_height() { let mut e = TextEngine::new(); - let t = TextLayer { shape: TextShape::Box { x: 10.0, y: 20.0, width: 200.0, height: 60.0 }, ..vertical("ab cd ef gh ij kl mn op", "Inter", 20.0) }; + let t = TextLayer { shape: TextShape::Box { x: 10.0, y: 20.0, width: 200.0, height: 60.0 }, ..rotated("ab cd ef gh ij kl mn op", "Inter", 20.0) }; let l = e.layout(&t, 72.0); assert!(l.lines.len() >= 3, "{}", l.lines.len()); let [x0, y0, x1, y1] = l.bounds().unwrap(); @@ -163,8 +246,11 @@ fn cjk_is_upright_centred_with_vertical_alternates() { } else { assert_eq!(dash.orient, GlyphOrient::Rotated); } - // Latin inside vertical CJK runs rotated. - assert_eq!(g[9].orient, GlyphOrient::Rotated); + // Latin inside vertical CJK stands upright (Photoshop's Vertical Type tool), or rotated when + // its style says so. + assert_eq!(g[9].orient, GlyphOrient::Upright); + let r = e.layout(&rotated(text, &fam, 40.0), 72.0); + assert_eq!(r.glyphs[9].orient, GlyphOrient::Rotated); // Punctuation squeeze: 、「 takes 1.5 em down the column, ト、 keeps full cells. let s = e.layout(&vertical("ト、「東", &fam, 40.0), 72.0); let cx: Vec = s.clusters.iter().map(|c| c.x).collect(); diff --git a/crates/text/src/warp.rs b/crates/text/src/warp.rs index 439fc453bf..c2078966c1 100644 --- a/crates/text/src/warp.rs +++ b/crates/text/src/warp.rs @@ -85,6 +85,45 @@ impl Warp { PathFrame::new(path, *start, *flip).map(|f| Warp(Kind::Path(f))) } + /// Path text with its logical left edge after paragraph alignment. A closed path has + /// one lap of capacity from this edge, including centred and right-aligned text whose + /// coordinates start below zero. Open paths keep their existing endpoint clipping. + pub fn on_path_with_text_start(shape: &TextShape, text_start: f64) -> Option { + if !text_start.is_finite() { + return None; + } + let mut warp = Self::on_path(shape)?; + if let Kind::Path(frame) = &mut warp.0 { + frame.text_start = text_start; + } + Some(warp) + } + + /// Text-space x nearest a point on a type path, using the same seam and one-lap + /// interval as glyph placement. Used when clicking to place the caret after the seam. + pub fn path_text_x(&self, x: f64, y: f64) -> Option { + let Kind::Path(frame) = &self.0 else { return None }; + if !x.is_finite() || !y.is_finite() { + return None; + } + let offset = frame.project(x, y) - frame.start; + Some(if frame.closed { (offset - frame.text_start).rem_euclid(frame.length()) + frame.text_start } else { offset }) + } + + /// Caret hit testing in the occupied text interval. In a closed path's unused gap, + /// choose the nearer endpoint along the path instead of always choosing the last caret. + pub fn path_text_x_near_text(&self, x: f64, y: f64, text_end: f64) -> Option { + let offset = self.path_text_x(x, y)?; + let Kind::Path(frame) = &self.0 else { return None }; + if frame.closed && text_end.is_finite() && offset > text_end { + let previous = offset - frame.length(); + if frame.text_start - previous < offset - text_end { + return Some(previous); + } + } + Some(offset) + } + /// Longest segment (text-space px) worth sending through [`Warp::apply`] unsplit. pub fn max_segment(&self) -> f64 { match &self.0 { @@ -128,6 +167,8 @@ struct PathFrame { /// Arc length at each point. cum: Vec, start: f64, + closed: bool, + text_start: f64, } impl PathFrame { @@ -163,7 +204,14 @@ impl PathFrame { } cum.push(acc); } - (pts.len() >= 2 && acc.is_finite() && acc > 1e-6 && start.is_finite()).then(|| PathFrame { pts, cum, start: f64::from(start) }) + (pts.len() >= 2 && acc.is_finite() && acc > 1e-6 && start.is_finite()).then(|| PathFrame { + pts, + cum, + // A click at the seam may project to either 0 or length (then round as f32). + start: if path.closed { f64::from(start).rem_euclid(acc) } else { f64::from(start) }, + closed: path.closed, + text_start: 0.0, + }) } fn length(&self) -> f64 { @@ -186,8 +234,9 @@ impl PathFrame { best.1 } - /// Point and unit tangent at arc length `s`; past either end the end tangent continues straight. + /// Point and unit tangent: closed paths wrap; open paths extend their end tangents. fn at(&self, s: f64) -> ((f64, f64), (f64, f64)) { + let s = if self.closed { s.rem_euclid(self.length()) } else { s }; let last = self.pts.len() - 1; let i = self.cum.partition_point(|&c| c < s).clamp(1, last); let (a, b) = (self.pts[i - 1], self.pts[i]); @@ -205,7 +254,15 @@ impl PathFrame { /// The rigid map for a glyph centred at text-space `cx`; `None` outside the path. fn frame(&self, cx: f64) -> Option<[f64; 6]> { let s = self.start + cx; - if !(0.0..=self.length()).contains(&s) { + if !cx.is_finite() + || if self.closed { + // Stop after one lap of text, not at the arbitrary first knot. A half-open + // interval excludes the first duplicate location at the next revolution. + !(self.text_start..self.text_start + self.length()).contains(&cx) + } else { + !(0.0..=self.length()).contains(&s) + } + { return None; } let (p, t) = self.at(s); @@ -298,3 +355,7 @@ mod tests { assert!(s.apply(100.0, -40.0).1 < -40.0); } } + +#[cfg(test)] +#[path = "closed_path_tests.rs"] +mod closed_path_tests; diff --git a/crates/ui-egui/examples/bevel_bench.rs b/crates/ui-egui/examples/bevel_bench.rs index 15c76e6d35..4d022b77f7 100644 --- a/crates/ui-egui/examples/bevel_bench.rs +++ b/crates/ui-egui/examples/bevel_bench.rs @@ -101,7 +101,7 @@ struct Gpu { } fn gpu() -> Option { - let instance = wgpu::Instance::default(); + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })) .ok()?; diff --git a/crates/ui-egui/examples/fx_bench.rs b/crates/ui-egui/examples/fx_bench.rs index d51fcf610c..af4036e384 100644 --- a/crates/ui-egui/examples/fx_bench.rs +++ b/crates/ui-egui/examples/fx_bench.rs @@ -136,7 +136,7 @@ struct Gpu { } fn gpu() -> Option { - let instance = wgpu::Instance::default(); + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })) .ok()?; diff --git a/crates/ui-egui/examples/interactive_bench.rs b/crates/ui-egui/examples/interactive_bench.rs index 2ffe3c1ce1..efeff0927d 100644 --- a/crates/ui-egui/examples/interactive_bench.rs +++ b/crates/ui-egui/examples/interactive_bench.rs @@ -44,7 +44,7 @@ struct Gpu { } fn gpu() -> Option { - let instance = wgpu::Instance::default(); + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })) .ok()?; diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index 2bbc1a673e..0c3ceda8e8 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -326,3 +326,19 @@ fn alt_click_with_the_zoom_tool_zooms_out_held_or_latched() { assert_eq!(h.state().ui.views[0].zoom, 1.0, "sticky={sticky} scrubby={scrubby}"); } } + +#[test] +fn alt_click_with_the_mixer_brush_loads_the_reservoir_not_the_foreground() { + let mut h = harness(two_colours()); + h.state_mut().ui.tool = Tool::MixerBrush; + h.state_mut().run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0]})).unwrap(); + let rev = h.state().session.active().unwrap().revision; + assert!(h.state().session.tools.mixer.reservoir.is_none()); + click(&mut h, 50.0, 50.0, Modifiers::ALT); + assert_eq!(h.state().session.tools.mixer.reservoir, Some([1.0, 0.0, 0.0, 1.0]), "⌥-click loaded red into the reservoir"); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0], "the foreground colour is unchanged"); + assert_eq!(h.state().session.active().unwrap().revision, rev, "nothing was painted"); + click(&mut h, 150.0, 50.0, Modifiers::ALT); + assert_eq!(h.state().session.tools.mixer.reservoir, Some([0.0, 1.0, 0.0, 1.0]), "⌥-click loaded green"); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0]); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d12c85d005..5672b91f0b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -47,6 +47,7 @@ impl PhotocraftApp { monitors: Default::default(), checker: None, drag: None, + cancelled_vector_drag: false, move_blocked: false, tool_override: None, live_stroke: None, @@ -98,6 +99,7 @@ impl PhotocraftApp { tab_strip: None, drop_places: Default::default(), view_docs: Vec::new(), + path_document: None, fps: 0.0, last_frame_time: 0.0, thumbs: HashMap::new(), diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 14cce82bb8..5645693e4b 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -253,6 +253,22 @@ impl PhotocraftApp { } pub fn sync_views(&mut self) { + // The Paths panel selection belongs to the active document. Ordinary edits replace the + // snapshot and advance its revision; a replaced snapshot without a newer revision is a + // reopened document, even with the same ID. + let document = self.session.active().map(|st| (st.doc.id, st.revision, std::sync::Arc::downgrade(&st.doc))); + let same_document = match (&self.path_document, &document) { + (Some((old_id, old_revision, old_source)), Some((id, revision, source))) => old_id == id && (revision > old_revision || old_source.ptr_eq(source)), + (None, None) => true, + _ => false, + }; + if !same_document { + self.ui.selected_path = None; + } + self.path_document = document; + vector_ui::cancel_stale_pen(self); + crate::direct_select::cancel_stale(self); + canvas::cancel_stale_vector_drag(self); type_transform::cancel_stale(self); crate::cam_transform::cancel_stale(self); crate::lasso_ui::cancel_stale(self); @@ -286,7 +302,7 @@ impl PhotocraftApp { let new_docs: Vec = ids.iter().enumerate().filter(|(_, id)| !self.view_docs.contains(id)).map(|(i, _)| i).collect(); for &idx in &new_docs { if !self.ui.windows.iter().any(|w| w.document == idx) { - crate::view_cmds::float_window(self, idx, idx); + crate::view_cmds::float_window(self, idx, idx, false); } } } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index df0de6ff0b..49b22678a7 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -54,15 +54,14 @@ impl PhotocraftApp { self.drain_captures(ctx); self.drain_control(ctx); native_menu::run(self, ctx); + view_cmds::leave_full_screen_without_document(self, ctx); // Switching tools commits, also between the Type and Type Mask tools. if self.ui.text_edit.as_ref().is_some_and(|ed| !self.ui.tool.is_type() || ed.mask != self.ui.tool.is_type_mask()) { type_tool::commit(self); } // So does selecting another layer or document by any route (#6483). type_tool::end_if_left(self); - if self.ui.pen.as_ref().is_some_and(|p| !p.drawn_with(self.ui.tool)) { - vector_ui::pen_commit(self, false); - } + vector_ui::finish_pen_if_left(self); transform_tool::end_if_left(self); shape_stroke_ui::sync_editor(self, ctx); prefs_ui::tick(self, ctx); diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs new file mode 100644 index 0000000000..7f7bc4afaa --- /dev/null +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -0,0 +1,165 @@ +//! Brush-only Shift+right-click Mode picker. Shares the options bar's painting modes. + +use egui::{Context, Id}; +use photocraft_doc::BlendMode; +use serde_json::json; + +use crate::{PhotocraftApp, state::Tool, theme::Tokens}; + +/// The options bar and canvas picker use the same order, including painting-only Clear. +pub(crate) fn choices() -> Vec<((Option, bool), &'static str)> { + let mut choices: Vec<_> = BlendMode::LAYER_MODES.iter().map(|m| ((Some(*m), false), m.label())).collect(); + let at = choices.iter().position(|o| o.0 == (Some(BlendMode::Dissolve), false)).map_or(choices.len(), |i| i + 1); + choices.insert(at, ((None, true), "Behind")); + choices.insert(at + 1, ((None, false), "Clear")); + choices +} + +pub(crate) fn is_gesture(tool: Tool, mods: egui::Modifiers) -> bool { + tool == Tool::Brush && mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd +} + +/// The modifiers that decide a right-button gesture: the ones held when the button went down. +/// egui reports `secondary_clicked` on release, so letting go of Shift a moment before the button +/// must not turn Shift+right-click into a plain right-click (an erase dab, with the Erase +/// preference). The control path decides on the press too. +pub(crate) fn gesture_mods(ctx: &Context, mods: egui::Modifiers) -> egui::Modifiers { + let key = menu_id().with("press-mods"); + let (pressed, down, released) = ctx.input(|i| { + (i.pointer.button_pressed(egui::PointerButton::Secondary), i.pointer.secondary_down(), i.pointer.button_released(egui::PointerButton::Secondary)) + }); + if pressed { + ctx.data_mut(|d| d.insert_temp(key, mods)); + return mods; + } + if !down && !released { + ctx.data_mut(|d| d.remove::(key)); + return mods; + } + let held = ctx.data(|d| d.get_temp::(key)); + if released { + ctx.data_mut(|d| d.remove::(key)); + } + held.unwrap_or(mods) +} + +pub(crate) fn menu_id() -> Id { + Id::unique("canvas-brush-mode-menu") +} + +pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) { + if !pos.iter().all(|v| v.is_finite()) { + return; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + app.ui.canvas_tool_menu = None; + app.ui.brush_mode_menu = Some(pos); + crate::canvas_popup::mark_open(ctx, menu_id()); +} + +/// A press outside dismisses the popup, and consumes that entire canvas gesture through Up. +pub(crate) fn blocks_canvas(app: &PhotocraftApp, ctx: &Context) -> bool { + let key = menu_id().with("dismiss-pointer"); + if ctx.data(|d| d.get_temp::(key)).unwrap_or(false) { + if !ctx.input(|i| i.pointer.any_down()) { + ctx.data_mut(|d| d.remove::(key)); + } + return true; + } + if app.ui.brush_mode_menu.is_some() { + if let Some(rect) = ctx.memory(|m| m.area_rect(menu_id())) + && crate::canvas_popup::outside_pressed(ctx, menu_id(), rect) + { + ctx.data_mut(|d| d.insert_temp(key, true)); + } + return true; + } + false +} + +/// Document-coordinate control pointers dismiss; menu rows are chosen with screen-space ui.click. +pub(crate) fn blocks_control(app: &mut PhotocraftApp, ctx: &Context, ev: crate::canvas::ToolEvent) -> bool { + use crate::canvas::ToolEvent; + let key = menu_id().with("control-dismiss"); + let blocked = ctx.data(|d| d.get_temp::(key)).unwrap_or(false); + if blocked { + if matches!(ev, ToolEvent::Up { .. }) { + ctx.data_mut(|d| d.remove::(key)); + } + return true; + } + if app.ui.brush_mode_menu.is_some() { + if app.ui.tool != Tool::Brush { + app.ui.brush_mode_menu = None; + return false; + } + if matches!(ev, ToolEvent::Down { .. }) { + app.ui.brush_mode_menu = None; + ctx.data_mut(|d| d.insert_temp(key, true)); + } + return true; + } + false +} + +fn choose(app: &mut PhotocraftApp, mode: (Option, bool)) { + // Clear is the existing painting-only UI flag; keep the underlying blend mode just as the + // options bar does. Journal the choice through the same brush command. + let selected = if mode.1 { BlendMode::Normal } else { mode.0.unwrap_or(app.session.tools.brush.mode) }; + match app.run("tools.setBrush", json!({"brush": {"mode": selected,"behind":mode.1}})) { + Ok(_) => app.ui.tool_options.brush_clear = mode == (None, false), + Err(e) => app.ui.status = e, + } + app.ui.brush_mode_menu = None; +} + +pub(crate) fn show(app: &mut PhotocraftApp, ctx: &Context) { + let Some([x, y]) = app.ui.brush_mode_menu else { return }; + if app.ui.tool != Tool::Brush || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + app.ui.brush_mode_menu = None; + // Escape also consumes the release of a right-button gesture still in flight. + if app.ui.tool == Tool::Brush && ctx.input(|i| i.pointer.secondary_down()) { + ctx.data_mut(|d| d.insert_temp(menu_id().with("dismiss-pointer"), true)); + } + return; + } + let choices = choices(); + let current = if app.ui.tool_options.brush_clear { + (None, false) + } else if app.session.tools.brush.behind { + (None, true) + } else { + (Some(app.session.tools.brush.mode), false) + }; + let screen = crate::work_area::visible_rect(ctx); + let id = menu_id(); + let margin = ctx.global_style().spacing.menu_margin.sum() + egui::Vec2::splat(2.0); + let height = (choices.len() as f32 * 22.0).min((screen.height() - margin.y).max(0.0)); + let width = (screen.width() - margin.x).clamp(0.0, 190.0); + let size = ctx.memory(|m| m.area_rect(id)).map_or(egui::vec2(width + margin.x, height + margin.y), |r| r.size()); + let pos = egui::pos2(x.min(screen.right() - size.x).max(screen.left()), y.min(screen.bottom() - size.y).max(screen.top())); + let mut picked = None; + let area = egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos).constrain_to(screen).show(ctx, |ui| { + let t = Tokens::get(ctx); + egui::Frame::menu(ui.style()).fill(t.card).stroke(egui::Stroke::new(1.0, t.card_border)).show(ui, |ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing.y = 0.0; + crate::widgets::menu_scroll(ui, |ui| { + for (mode, label) in choices { + let selected = mode == current; + let color = if selected && t.bevel { t.accent_text } else { t.text }; + let row = egui::Button::selectable(selected, egui::RichText::new(tl!(label)).color(color)).min_size(egui::vec2(width, 22.0)); + if ui.add(row).clicked() { + picked = Some(mode); + } + } + }); + }); + }); + if let Some(mode) = picked { + choose(app, mode); + } else if crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) { + app.ui.brush_mode_menu = None; + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f479e67510..da59b5a7ca 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -60,7 +60,7 @@ pub mod zoom_window_fit; #[cfg(test)] pub(crate) use cursors::eyedropper_ring_colors; -pub(crate) use cursors::{alt_samples, composite_color, paint_bucket_cursor, pen_cursor, pencil_cursor_rect, pencil_tip_is_round, pipette_cursor}; +pub(crate) use cursors::{alt_picks, alt_samples, composite_color, paint_bucket_cursor, pen_cursor, pencil_cursor_rect, pencil_tip_is_round, pipette_cursor}; use cursors::{brush_tip_centre, eyedropper_ring, precise_other_cursor, visible_crosshair}; #[cfg(test)] pub(crate) use display::GPU_OUTPUT; @@ -107,6 +107,8 @@ use tabs::{TEAR_OFF, pro_tab_title, tab_context_items, tab_drop_index, tab_move_ pub use tabs::{TabStrip, document_area, extra_windows}; use tabs::{dots, paint_dots}; #[cfg(test)] +use tabs::{main_canvas_document, move_target_after_filter}; +#[cfg(test)] pub(crate) use textures::detail_plan; 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}; @@ -978,6 +980,7 @@ fn handle_canvas_tool_stroke( && app.drag.is_none() && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) + && !crate::brush_mode_menu::blocks_canvas(app, ctx) && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)) { let d = xf.to_doc(p); @@ -1441,7 +1444,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & t if app.alt_sampling || (app.drag.is_none() && !app.services.right_button_down.as_ref().is_some_and(|f| f()) - && alt_samples(t, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)))) => + && alt_picks(t, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)))) => { // While it samples (button held), the comparison ring replaces the cursor (#213). if let Some(icon) = eyedropper_ring(app, painter, xf, p, response.is_pointer_button_down_on()) { @@ -1546,6 +1549,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. + Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => { @@ -1738,6 +1742,21 @@ fn sync_view_to_document(app: &PhotocraftApp, ctx: &egui::Context, view: &mut Vi aspect } +fn update_polygon_camera(app: &mut PhotocraftApp, ctx: &egui::Context, (idx, primary): (usize, bool), rect: Rect, view: &mut View, ppp: f32, aspect: f32) { + let previous_center = view.center; + if primary { + polygon_cancel_stale(app); + polygon_edge_scroll(app, ctx, idx, rect, view, ppp); + } + // Bounds belong to an actual edge-scroll update, not an idle/finished polygon. + if view.center != previous_center && !app.session.prefs().tools.overscroll { + crate::scrollbars::clamp_view_with_aspect(view, rect.size(), ppp, aspect); + } + if view.center != previous_center { + ctx.request_repaint(); + } +} + pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View { let ctx = ui.ctx().clone(); // The camera as the app holds it before this frame's input. The canvas works on its own copy @@ -1795,6 +1814,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let doc = app.session.documents()[idx].doc.clone(); let size = [doc.size.width, doc.size.height]; let aspect = sync_view_to_document(app, &ctx, &mut view, &doc, rect, ppp); + update_polygon_camera(app, &ctx, (idx, primary), rect, &mut view, ppp, aspect); + let flip = app.ui.view.flip_horizontal; // Document rendering follows the target; only shader uniforms and overlay geometry ease. let target_xf = ViewXform { rect, zoom: view.zoom / ppp, center: view.center, flip, rotation: view.rotation, aspect }; @@ -1874,6 +1895,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::crop_ui::cancel_stale(app); crate::crop_ui::ensure_frame(app); let mut drawing = crate::crop_ui::active(app); + if let Some(pen) = app.ui.pen.as_mut().filter(|pen| pen.dragging && !pen.curvature) { + pen.reposition = reposition; + drawing = true; + } if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { d.reposition = reposition; drawing = true; @@ -2605,3 +2630,58 @@ mod lasso_preview_tests { assert_eq!((dashes, solid), (0, 1), "Magnetic Lasso: the traced border is solid"); } } + +pub(crate) use drag::cancel_stale_vector_drag; + +#[cfg(test)] +#[path = "pen_gesture_owner_tests.rs"] +mod pen_gesture_owner_tests; +#[cfg(test)] +#[path = "pen_path_visual_tests.rs"] +mod pen_path_visual_tests; + +/// Between Polygonal Lasso clicks, reveal more of the image near or beyond the viewport edge. +/// Only the view moves: fixed vertices stay in document coordinates, including while button-up. +fn polygon_edge_scroll(app: &PhotocraftApp, ctx: &egui::Context, idx: usize, rect: Rect, view: &mut View, ppp: f32) { + if app.ui.polygon.is_empty() + || app.ui.tool != Tool::PolygonLasso + || app.session.active_index() != Some(idx) + || !app.ui.dialogs.is_empty() + || app.camera_raw.is_some() + || app.discard.is_some() + || app.drag.is_some() + || !crate::menus::modal_allows(app, "select.lasso") + || app.ui.transform.is_some() + || crate::distort_ui::modal_workspace(app).is_some() + || ctx.text_edit_focused() + || egui::Popup::is_any_open(ctx) + || crate::hold_keys::for_frame(app, ctx, false).is_some() + { + return; + } + let Some((pointer, dt)) = ctx.input(|i| (i.focused && !i.pointer.middle_down()).then(|| i.pointer.hover_pos().map(|p| (p, i.stable_dt))).flatten()) else { + return; + }; + let zoom = view.zoom / ppp; + if !pointer.x.is_finite() || !pointer.y.is_finite() || !dt.is_finite() || dt <= 0.0 || !zoom.is_finite() || zoom <= 0.0 { + return; + } + // Moving over a neighbouring document is not a request to pan either tiled view. + if arranged_cells(app, app.last_canvas_rect).is_some_and(|cells| cells.iter().any(|(other, cell)| *other != idx && cell.contains(pointer))) { + return; + } + let edge = 32.0_f32.min(rect.width() * 0.25).min(rect.height() * 0.25); + if edge <= 0.0 { + return; + } + let speed = |p: f32, lo: f32, hi: f32| { + let direction = ((edge - (hi - p)) / edge).clamp(0.0, 1.0) - ((edge - (p - lo)) / edge).clamp(0.0, 1.0); + if direction == 0.0 { 0.0 } else { direction.signum() * (80.0 + 520.0 * direction.abs()) } + }; + let velocity = vec2(speed(pointer.x, rect.left(), rect.right()), speed(pointer.y, rect.top(), rect.bottom())); + let velocity = velocity * (600.0 / velocity.length().max(600.0)); + let xf = ViewXform { rect, zoom, center: view.center, flip: app.ui.view.flip_horizontal, rotation: view.rotation, aspect: app.ui.view.display_aspect() }; + let delta = xf.unmap_vec(velocity) * dt.min(0.05) / zoom; + view.center[0] += delta.x; + view.center[1] += delta.y; +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index d2a49241d5..9d5b84651f 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1066,8 +1066,8 @@ pub(crate) fn make_selection(app: &mut PhotocraftApp) -> Result<(), String> { // else the Paths panel path it adds to (a selected saved path, or the Work Path), which it // selects so it is the active path. let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || crate::vector_ui::targeted_vector_mask(app).is_some()); - if pending { - crate::vector_ui::pen_commit(app, false); + if pending && !crate::vector_ui::pen_commit(app, false) { + return Err(app.ui.status.clone()); } let name = if pending_layer { Some("layer".to_string()) } else { crate::vector_ui::active_path_name(app) } .ok_or_else(|| "No path is available for this action".to_string())?; @@ -1086,8 +1086,8 @@ fn choose_pen(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, com } let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || app.ui.vector_mask_target); - if pending { - crate::vector_ui::pen_commit(app, false); + if pending && !crate::vector_ui::pen_commit(app, false) { + return Err(app.ui.status.clone()); } let name = if pending { Some(if pending_layer { "layer" } else { "work" }.to_string()) } else { menu.path_name.clone() } .ok_or_else(|| "No path is available for this action".to_string())?; diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index 06819c5ea1..f87e74ebae 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -159,7 +159,7 @@ pub(crate) fn paint_bucket_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorI pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { if matches!(ev, ToolEvent::Down { .. }) { let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); - app.alt_sampling = !physical_right && alt_samples(app.active_tool(), mods); + app.alt_sampling = !physical_right && !app.secondary_erase && alt_samples(app.active_tool(), mods); } if !app.alt_sampling { return false; @@ -173,9 +173,12 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: } pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - if let Some([r, g, b]) = eyedropper_color(app, x, y) { + 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 key = if mods.alt { "background" } else { "foreground" }; - let _ = app.run("tools.setColors", json!({ key: [r, g, b, 1.0] })); + let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })); } } @@ -207,3 +210,10 @@ pub(crate) fn eyedropper_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Optio pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { sample_color(app, x, y, "all") } + +pub(crate) fn alt_loads_mixer(tool: Tool, mods: egui::Modifiers) -> bool { + mods.alt && !mods.ctrl && tool == Tool::MixerBrush +} +pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool { + alt_samples(tool, mods) || alt_loads_mixer(tool, mods) +} diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 6083756416..ac3da2eacb 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -31,6 +31,9 @@ pub struct Drag { /// keeps the locked direction stable between events. The Move tool's own drags use `move_mods`. pub sel_axis: Option<[f64; 2]>, pub lasso: Option, + /// Freeform Pen and Path Selection gestures belong to their source document and target. + pub(super) vector_owner: Option, + pub(super) pen_owner: Option, } impl Drag { @@ -49,6 +52,19 @@ impl Drag { sel_move: None, sel_axis: None, lasso: None, + vector_owner: None, + pen_owner: None, + } + } + + /// Vector drags capture their owner at the press, the Freeform Pen also its destination, before + /// later ⌥-clicks or a temporary Direct Selection can finish them. + pub(crate) fn capture_vector_owners(&mut self, app: &PhotocraftApp) { + if matches!(self.tool, Tool::FreeformPen | Tool::PathSelection) { + self.vector_owner = VectorGestureOwner::capture(app); + } + if self.tool == Tool::FreeformPen { + self.pen_owner = crate::vector_ui::capture_pen_owner(app); } } @@ -326,3 +342,58 @@ pub(crate) fn draw_readout(ctx: &egui::Context, id: &str, cursor }, ); } + +/// The document, revision and target a vector drag started on. +#[derive(Clone, Debug)] +pub(super) struct VectorGestureOwner { + doc: photocraft_doc::DocId, + document: std::sync::Weak, + revision: u64, + layer: Option, + selected_path: Option, + vector_mask: bool, + mode: String, + tool: Tool, +} + +/// Cancel a vector drag before it can preview or finish on another document or target; the rest of +/// its pointer events go nowhere. True when one was cancelled. +pub(crate) fn cancel_stale_vector_drag(app: &mut PhotocraftApp) -> bool { + let stale = app.drag.as_ref().and_then(|d| d.vector_owner.as_ref()).is_some_and(|owner| !owner.valid(app)); + if stale { + app.drag = None; + app.cancelled_vector_drag = true; + } + stale +} + +impl VectorGestureOwner { + fn capture(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + Some(Self { + doc: st.doc.id, + document: std::sync::Arc::downgrade(&st.doc), + revision: st.revision, + layer: st.active_layer, + selected_path: app.ui.selected_path.clone(), + vector_mask: app.ui.vector_mask_target, + mode: app.ui.tool_options.vector_mode.clone(), + tool: app.active_tool(), + }) + } + + pub(super) fn valid(&self, app: &PhotocraftApp) -> bool { + Self::capture(app).is_some_and(|now| { + self.doc == now.doc + && self.document.ptr_eq(&now.document) + && self.revision == now.revision + && self.layer == now.layer + && self.selected_path == now.selected_path + && self.vector_mask == now.vector_mask + && self.mode == now.mode + && self.tool == now.tool + }) + } +} + +use photocraft_doc::Document; diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 251b6c9205..6e4e015d9f 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -13,6 +13,9 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { app.live_stroke = None; return; } + if d.vector_owner.as_ref().is_some_and(|owner| !owner.valid(app)) { + return; + } let mut end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]); let (sx, sy) = snap_aliased_tip(app, d.tool, end[0], end[1]); end[0] = sx; @@ -78,7 +81,11 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { } match d.tool { Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers), - Tool::FreeformPen => crate::vector_ui::freeform_finish(app, &d.points, d.lasso.as_ref().map_or(&[], |l| l.straight())), + Tool::FreeformPen => { + if let Some(owner) = d.pen_owner { + crate::vector_ui::freeform_finish_owned(app, &d.points, d.lasso.as_ref().map_or(&[], |l| l.straight()), owner); + } + } // Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead. t if crate::vector_ui::is_shape_tool(t) && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) @@ -172,6 +179,7 @@ pub(crate) fn constrained_polygon_point(from: [f64; 2], point: [f64; 2]) -> [f64 /// 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 @@ -202,6 +210,7 @@ pub fn polygon_retract(app: &mut PhotocraftApp) -> bool { } if app.ui.polygon.is_empty() { app.ui.polygon_mode.clear(); + app.ui.polygon_doc = None; } true } @@ -209,13 +218,13 @@ pub fn polygon_retract(app: &mut PhotocraftApp) -> bool { /// The polygon in progress belongs to the document it was started on (`UiState::polygon_doc`): /// once another document becomes active it is dropped, so its outline doesn't show on (or get /// committed to) the other document, and the selection it would have replaced is shown again. -/// Switching tools is handled in `PhotocraftApp::sync_views`. Like the Lasso's +/// Runs before canvas input and shortcuts as well as in `PhotocraftApp::sync_views`. Like the Lasso's /// ([`crate::lasso_ui::cancel_stale`]) and the Magnetic Lasso's ([`crate::magnetic_lasso_ui::frame`]). pub fn polygon_cancel_stale(app: &mut PhotocraftApp) { let active = app.session.active().map(|st| st.doc.id); if app.ui.polygon.is_empty() { app.ui.polygon_doc = None; - } else if app.ui.polygon_doc.is_some_and(|d| Some(d) != active) { + } else if app.ui.tool != Tool::PolygonLasso || app.ui.polygon_doc.is_some_and(|d| Some(d) != active) { app.ui.polygon.clear(); app.ui.polygon_mode.clear(); app.ui.polygon_doc = None; @@ -230,8 +239,10 @@ pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool { /// Close the polygonal lasso and make the selection in the mode it started in. pub fn commit_polygon(app: &mut PhotocraftApp) { + polygon_cancel_stale(app); let pts = std::mem::take(&mut app.ui.polygon); let mode = std::mem::take(&mut app.ui.polygon_mode); + app.ui.polygon_doc = None; if pts.len() >= 3 { let mode = if mode.is_empty() { selection_mode(app, egui::Modifiers::NONE).to_owned() } else { mode }; let o = &app.ui.tool_options; diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index dc64d34312..c0db27eb87 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -114,6 +114,10 @@ pub fn right_erases(app: &PhotocraftApp, tool: Tool) -> bool { /// brush with Alt held (#297), erases (Erase preference) or opens the Brush Preset picker. Arms /// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) -> Buttons { + if crate::brush_mode_menu::blocks_canvas(app, &response.ctx) { + app.secondary_erase = false; + return Buttons::default(); + } let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); let (mods, mut right_down) = response.ctx.input(|i| (i.modifiers, i.pointer.secondary_down())); right_down |= physical_right; @@ -137,13 +141,41 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) app.brush_resize_armed = resize_start || (physical_right && resizing); // ⌘/Ctrl+right-click lists the layers under the pointer instead (layer_pick_ui.rs, #307). let layer_menu = crate::layer_pick_ui::is_gesture(tool, mods); + // Decided by the modifiers held when the button went down, not by those of the release frame that reports the click. + let mode_menu = crate::brush_mode_menu::is_gesture(tool, crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods))); + if mode_menu && !resizing && app.drag.is_none() { + app.secondary_erase = false; + if response.secondary_clicked() + && let Some(p) = response.interact_pointer_pos() + { + crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y]); + } + return Buttons { + started: response.drag_started_by(PointerButton::Primary), + dragged: response.dragged_by(PointerButton::Primary), + stopped: response.drag_stopped_by(PointerButton::Primary), + clicked: response.clicked(), + }; + } let erase = right_erases(app, tool) && !resize_start && !resizing && !layer_menu; + // Shift+Alt+right-press opens Photoshop's HUD Color Picker (#6098) instead of the picker. + // Tools whose right-click is the canvas tool menu (Quick Selection, #7268) keep that menu. + let sticky = crate::workspace_ui::sticky_mods(app, mods); + let hud_gesture = right_click_picker(tool) && !layer_menu && !erase && sticky.shift && sticky.alt; + let right_press = response.ctx.input(|i| i.pointer.button_pressed(PointerButton::Secondary)) && response.contains_pointer(); + if hud_gesture + && right_press + && let Some(p) = response.ctx.input(|i| i.pointer.hover_pos()) + { + crate::color_hud::open(app, [p.x, p.y], true); + } let right_stroke = erase && app.drag.is_some(); let right_start = erase && right_started; let right_click = response.secondary_clicked(); if right_click && !erase && !layer_menu + && !crate::color_hud::is_open(&app.ui) && right_click_picker(tool) && let Some(p) = response.interact_pointer_pos() { @@ -166,10 +198,33 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) /// the Brush Preset picker at screen point `at`, and nothing paints. pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: bool, mods: egui::Modifiers, at: [f32; 2]) -> bool { let tool = app.ui.tool; + // Shift+Alt+right is Photoshop's HUD Color Picker (#6098): the down opens it, the up closes + // it. As on the canvas, the right-erase preference wins over the HUD, and a tool whose + // right-click is the canvas tool menu keeps that menu (handled by the caller). + let hud_gesture = right_click_picker(tool) && mods.shift && mods.alt && !right_erases(app, tool); + // A control-channel request carries one modifier set, so the Up need not repeat the Down's: + // the caller may release Shift and Alt first. Any Up therefore closes a non-held HUD that is + // still open; `release` leaves a real-mouse (held) one to its button release. + let hud_up = !down && app.ui.color_hud.is_some_and(|h| !h.hold); + if hud_gesture || hud_up { + if down { + crate::color_hud::open(app, at, false); + } else { + crate::color_hud::release(&mut app.ui); + } + return false; + } if crate::brush_resize::applies(tool) && (crate::brush_resize::is_right_gesture(mods) || app.brush_resize.is_some_and(|r| r.secondary)) { app.brush_resize_armed = down && app.drag.is_none(); return true; } + if crate::brush_mode_menu::is_gesture(tool, mods) && app.drag.is_none() && app.brush_resize.is_none() { + app.secondary_erase = false; + if down { + crate::brush_mode_menu::open(app, ctx, at); + } + return false; + } if right_erases(app, tool) { app.secondary_erase = down; return true; diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index 4b54a1ce98..72c74cd62e 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -65,6 +65,179 @@ fn strokes(h: &Harness<'static, PhotocraftApp>) -> Vec { h.state().session.journal.iter().filter(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).collect() } +fn mode_right_click(h: &mut Harness<'static, PhotocraftApp>, mods: Modifiers) { + let p = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(mods)); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: mods }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: mods }); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn shift_right_mode_picker_selects_journals_and_clear_erases() { + use egui_kittest::kittest::Queryable; + let mut h = harness(Some("erase")); + let history = h.state().session.active().unwrap().history.past_len(); + let journal = h.state().session.journal.len(); + mode_right_click(&mut h, Modifiers::SHIFT); + assert!(h.state().ui.brush_mode_menu.is_some()); + assert!(h.state().ui.brush_picker.is_none() && h.state().drag.is_none()); + assert_eq!(h.state().session.journal.len(), journal); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); + h.get_by_label("Multiply").click(); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none()); + assert_eq!(h.state().session.tools.brush.mode, photocraft_doc::BlendMode::Multiply); + assert_eq!(h.state().session.journal.last().unwrap(), &("tools.setBrush".into(), json!({"brush": {"mode": "Multiply", "behind": false}}))); + let (a, b) = drag(&mut h, PointerButton::Primary); + let mid = a + (b - a) * 0.5; + assert!(alpha_at(&h, mid) > 0.9); + mode_right_click(&mut h, Modifiers::SHIFT); + h.get_by_label("Clear").click(); + h.run_steps(2); + assert!(h.state().ui.tool_options.brush_clear); + assert_eq!(h.state().session.tools.brush.mode, photocraft_doc::BlendMode::Multiply, "Clear keeps the underlying mode, as the options bar does"); + drag(&mut h, PointerButton::Primary); + assert_eq!(alpha_at(&h, mid), 0.0); + assert!(strokes(&h).last().unwrap()["erase"].as_bool().unwrap()); +} + +#[test] +fn mode_picker_outside_dismissal_does_not_paint_or_erase() { + for button in [PointerButton::Primary, PointerButton::Secondary] { + let mut h = harness(Some("erase")); + drag(&mut h, PointerButton::Primary); + let journal = h.state().session.journal.len(); + let history = h.state().session.active().unwrap().history.past_len(); + mode_right_click(&mut h, Modifiers::SHIFT); + // A full outside drag must only dismiss, including its release click. + drag(&mut h, button); + assert!(h.state().ui.brush_mode_menu.is_none()); + assert_eq!(h.state().session.journal.len(), journal, "dismissal must not paint/erase with {button:?}"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); + } +} + +#[test] +fn mode_control_can_pick_a_row_with_ui_click() { + use crate::control::{ControlRequest, Outcome, handle}; + use egui_kittest::kittest::Queryable; + let mut h = harness(Some("erase")); + let ctx = h.ctx.clone(); + let before = h.state().session.journal.len(); + let (req, _) = ControlRequest::new( + "ui.pointer", + json!({"button": "right", "shift": true, + "events": [{"kind": "down", "x": 200, "y": 150}, {"kind": "up", "x": 200, "y": 150}]}), + ); + assert!(matches!(handle(h.state_mut(), &ctx, &req), Outcome::Done(_))); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_some()); + assert_eq!(h.state().session.journal.len(), before); + let at = h.get_by_label("Darken").rect().center(); + let (req, _) = ControlRequest::new("ui.click", json!({"x": at.x, "y": at.y})); + assert!(matches!(handle(h.state_mut(), &ctx, &req), Outcome::AfterInput)); + // The app injects these queued control events into its next frame's input. + let events = std::mem::take(&mut h.state_mut().synthetic); + for event in events { + h.event(event); + } + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none()); + assert_eq!(h.state().session.tools.brush.mode, photocraft_doc::BlendMode::Darken); + assert_eq!(h.state().session.journal.last().unwrap(), &("tools.setBrush".into(), json!({"brush": {"mode": "Darken", "behind": false}}))); +} + +#[test] +fn shift_right_mode_picker_cancels_and_other_gestures_keep_their_routes() { + let mut h = harness(None); + let journal = h.state().session.journal.len(); + mode_right_click(&mut h, Modifiers::SHIFT); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none()); + mode_right_click(&mut h, Modifiers::SHIFT); + let outside = h.state().last_canvas_rect.min + vec2(2.0, 2.0); + h.event(egui::Event::PointerMoved(outside)); + press(&mut h, outside, PointerButton::Secondary, true); + press(&mut h, outside, PointerButton::Secondary, false); + assert!(h.state().ui.brush_mode_menu.is_none()); + mode_right_click(&mut h, Modifiers::SHIFT); + h.state_mut().ui.tool = Tool::Pencil; + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none()); + mode_right_click(&mut h, Modifiers::SHIFT); + assert!(h.state().ui.brush_mode_menu.is_none() && h.state().ui.brush_picker.is_some()); + h.state_mut().ui.brush_picker = None; + h.state_mut().ui.tool = Tool::Brush; + mode_right_click(&mut h, Modifiers::NONE); + assert!(h.state().ui.brush_picker.is_some() && h.state().ui.brush_mode_menu.is_none()); + assert_eq!(h.state().session.journal.len(), journal, "opening/cancelling never changes brush or pixels"); +} + +#[test] +fn escape_dismissal_consumes_a_held_secondary_release() { + for release_shift in [false, true] { + let mut h = harness(Some("erase")); + let journal = h.state().session.journal.len(); + let history = h.state().session.active().unwrap().history.past_len(); + let p = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(Modifiers::SHIFT)); + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::SHIFT }); + h.run_steps(1); + // A quick second press can arrive in the frame that opens the menu for the first + // click's release, leaving the secondary button held while the picker is visible. + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::SHIFT }); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::SHIFT }); + h.run_steps(1); + assert!(h.state().ui.brush_mode_menu.is_some()); + assert!(h.ctx.input(|i| i.pointer.secondary_down())); + h.key_press(egui::Key::Escape); + h.run_steps(1); + assert!(h.state().ui.brush_mode_menu.is_none()); + let mods = if release_shift { Modifiers::NONE } else { Modifiers::SHIFT }; + h.event(egui::Event::ModifiersChanged(mods)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: mods }); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none(), "Escape must consume the pending release"); + assert!(h.state().ui.brush_picker.is_none() && h.state().drag.is_none() && !h.state().secondary_erase); + assert_eq!(h.state().session.journal.len(), journal); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); + mode_right_click(&mut h, Modifiers::SHIFT); + assert!(h.state().ui.brush_mode_menu.is_some(), "the next gesture must still work"); + } +} + +#[test] +fn shift_released_before_the_right_button_still_opens_the_mode_picker() { + // egui reports `secondary_clicked` on release. With Erase on, a click that lost Shift a + // frame early must open the menu, not erase a dab. + let mut h = harness(Some("erase")); + let history = h.state().session.active().unwrap().history.past_len(); + let journal = h.state().session.journal.len(); + let p = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(Modifiers::SHIFT)); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::SHIFT }); + h.run_steps(1); + // Shift goes up in a frame of its own while the right button is still down. + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_some(), "the press decided the gesture"); + assert!(h.state().drag.is_none() && !h.state().secondary_erase); + assert_eq!(h.state().session.journal.len(), journal, "no erase dab"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); +} + #[test] fn left_drag_paints() { let mut h = harness(None); @@ -313,6 +486,44 @@ fn right_stroke_erases_with_pen_pressure_through_the_control_channel_path() { assert!(app.ui.brush_picker.is_some() && !app.secondary_erase); } +#[test] +fn shift_alt_right_through_the_control_channel_respects_the_erase_preference() { + // As on the canvas, with the right-erase preference the erase stroke wins over the HUD + // for Brush/Eraser; without it, Shift+Alt+right opens the HUD (#6098). + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.ui.tool = Tool::Brush; + let shift_alt = egui::Modifiers { shift: true, alt: true, ..Default::default() }; + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); + assert!(pointer_secondary(&mut app, &egui::Context::default(), true, shift_alt, [10.0, 10.0]), "the events reach the tool"); + assert!(app.ui.color_hud.is_none(), "no HUD with the erase preference"); + assert!(app.secondary_erase, "the down arms the erasing stroke"); + pointer_secondary(&mut app, &egui::Context::default(), false, shift_alt, [10.0, 10.0]); + // With the default preference the same gesture opens the HUD instead. + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "brushPicker"})).unwrap(); + assert!(!pointer_secondary(&mut app, &egui::Context::default(), true, shift_alt, [10.0, 10.0])); + assert!(app.ui.color_hud.is_some_and(|h| !h.hold), "the control-channel HUD opened"); +} + +#[test] +fn a_control_channel_up_closes_the_hud_without_repeating_its_modifiers() { + // Each control-channel request carries its own modifiers, so an Up sent after the keys + // are released arrives without Shift+Alt: it must still close the HUD it opened, or the + // HUD stays up and keeps picking from the hover (#6098 review). + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.ui.tool = Tool::Brush; + let shift_alt = egui::Modifiers { shift: true, alt: true, ..Default::default() }; + assert!(!pointer_secondary(&mut app, &egui::Context::default(), true, shift_alt, [10.0, 10.0])); + assert!(app.ui.color_hud.is_some_and(|h| !h.hold), "the control-channel HUD opened"); + assert!(!pointer_secondary(&mut app, &egui::Context::default(), false, egui::Modifiers::NONE, [10.0, 10.0])); + assert!(app.ui.color_hud.is_none(), "the Up closes it whatever the modifiers say"); + // A real-mouse HUD belongs to the canvas gesture and waits for its own button release. + crate::color_hud::open(&mut app, [10.0, 10.0], true); + pointer_secondary(&mut app, &egui::Context::default(), false, egui::Modifiers::NONE, [10.0, 10.0]); + assert!(app.ui.color_hud.is_some_and(|h| h.hold), "a held HUD is left to the canvas"); +} + #[test] fn the_brush_is_a_per_tool_option_that_presets_keep() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/canvas/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs index 923e81140a..ce1ae599b5 100644 --- a/crates/ui-egui/src/canvas/rulers.rs +++ b/crates/ui-egui/src/canvas/rulers.rs @@ -97,7 +97,7 @@ pub(crate) fn unit_menu_of(ui: &mut egui::Ui, current: Unit, units: &[Unit]) -> } /// A guide being dragged: from a ruler (new) or an existing one (index). -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct GuideDrag { pub vertical: bool, pub index: Option, @@ -108,13 +108,22 @@ pub struct GuideDrag { /// Whether the pointer was over a ruler when the guide was let go (#6286): a guide released /// there is removed, whatever its own axis reads. pub over_ruler: bool, + pub flipped: bool, } impl GuideDrag { + pub fn shows_vertical(&self) -> bool { + self.vertical != self.flipped + } + pub fn track(&mut self, at: [f64; 2], alt: bool) { + self.flipped = alt; + self.pos = if self.shows_vertical() { at[0] } else { at[1] }; + } + /// An existing guide taken at document point `p`. pub fn existing(vertical: bool, index: usize, p: [f64; 2]) -> Self { let at = if vertical { p[0] } else { p[1] }; - Self { vertical, index: Some(index), pos: at, press: at, over_ruler: false } + Self { vertical, index: Some(index), pos: at, press: at, over_ruler: false, flipped: false } } } @@ -235,7 +244,7 @@ pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, if let Some(d) = drag { // A guide being moved shows its own colour; a new one dragged from a ruler the preference's. let list = if d.vertical { &doc.guides.vertical } else { &doc.guides.horizontal }; - line(d.vertical, d.pos, d.index.and_then(|i| list.get(i)).map_or(guide, |p| own(d.vertical, *p))); + line(d.shows_vertical(), d.pos, d.index.and_then(|i| list.get(i)).map_or(guide, |p| own(d.vertical, *p))); } } @@ -245,14 +254,14 @@ pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, pub fn guide_drag_readout(app: &PhotocraftApp, d: GuideDrag) -> Option<(&'static str, String)> { let doc = &app.session.active()?.doc; let ur = &app.session.prefs().units_and_rulers; - let axis = usize::from(!d.vertical); + let axis = usize::from(!d.shows_vertical()); let px = d.pos - doc.ruler_origin.get(axis).copied().unwrap_or(0.0); - let extent = if d.vertical { doc.size.width } else { doc.size.height } as f64; + let extent = if d.shows_vertical() { doc.size.width } else { doc.size.height } as f64; let value = match ur.rulers { Unit::Pixels => photocraft_engine::prefs::fmt_decimals(px, 1), _ => ur.format(px, f64::from(doc.resolution_dpi), extent), }; - Some((if d.vertical { "X:" } else { "Y:" }, format!("{value} {}", ur.rulers.suffix()))) + Some((if d.shows_vertical() { "X:" } else { "Y:" }, format!("{value} {}", ur.rulers.suffix()))) } /// Draw [`guide_drag_readout`] beside the pointer while a guide is dragged. @@ -294,20 +303,29 @@ pub fn finish_drag(app: &mut PhotocraftApp, d: GuideDrag) { // reads as a click: dragged sideways onto the left ruler, a horizontal guide never moves in y. if let Some(i) = d.index && !d.over_ruler + && !d.flipped && (d.pos - d.press).abs() * f64::from(app.point_zoom().max(0.01)) < 0.5 { crate::guide_select::select(app, d.vertical, i); return; } - let extent = if d.vertical { size.width } else { size.height } as f64; + let shows = d.shows_vertical(); + let extent = if shows { size.width } else { size.height } as f64; let orientation = if d.vertical { "vertical" } else { "horizontal" }; let inside = !d.over_ruler && d.pos >= 0.0 && d.pos <= extent; let pos = (d.pos * 1000.0).round() / 1000.0; let _ = match (d.index, inside) { - (None, true) => app.run("view.newGuide", json!({"orientation": orientation, "position": pos})), + (None, true) => app.run("view.newGuide", json!({"orientation": if shows {"vertical"}else{"horizontal"}, "position": pos})), (Some(i), true) => app - .run("view.moveGuide", json!({"orientation": orientation, "index": i, "position": pos})) - .inspect(|_| crate::guide_select::select(app, d.vertical, i)), + .run("view.moveGuide", json!({"orientation": orientation,"toOrientation":if shows {"vertical"}else{"horizontal"}, "index": i, "position": pos})) + .inspect(|_| { + let index = if d.flipped { + app.session.active().map_or(0, |st| if shows { st.doc.guides.vertical.len() } else { st.doc.guides.horizontal.len() }).saturating_sub(1) + } else { + i + }; + crate::guide_select::select(app, shows, index); + }), (Some(i), false) => app.run("view.deleteGuide", json!({"orientation": orientation, "index": i})), (None, false) => Ok(serde_json::Value::Null), }; @@ -519,7 +537,7 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: & let d = xf.to_doc(pos); let along = if vertical { d[0] } else { d[1] }; let pos = if ui.input(|i| i.modifiers.shift) { snap_to_tick(app, xf, vertical, along) } else { crate::snap_ui::snap_guide(app, vertical, along) }; - app.guide_drag = Some(GuideDrag { vertical, index: None, pos, press: pos, over_ruler: false }); + app.guide_drag = Some(GuideDrag { vertical, index: None, pos, press: pos, over_ruler: false, flipped: false }); } if resp.drag_stopped() && let Some(mut d) = app.guide_drag.take() diff --git a/crates/ui-egui/src/canvas/rulers/tests.rs b/crates/ui-egui/src/canvas/rulers/tests.rs index 33684c9b7f..9b08137eed 100644 --- a/crates/ui-egui/src/canvas/rulers/tests.rs +++ b/crates/ui-egui/src/canvas/rulers/tests.rs @@ -202,13 +202,13 @@ fn info_panel_shows_guide_drag_position_outside_canvas() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); app.hover_doc = None; - app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0, over_ruler: false }); + app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0, over_ruler: false, flipped: false }); let mut h = egui_kittest::Harness::builder() .with_size(vec2(260.0, 240.0)) .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); h.run_steps(2); assert!(h.query_by_label("42").is_some(), "vertical guide: X readout"); - h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0, over_ruler: false }); + h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0, over_ruler: false, flipped: false }); h.run_steps(2); assert!(h.query_by_label("17").is_some(), "horizontal guide: Y readout"); } @@ -220,15 +220,18 @@ fn guide_drag_shows_its_position_beside_the_pointer() { 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": 100})).unwrap(); - let v = GuideDrag { vertical: true, index: Some(0), pos: 103.24, press: 50.0, over_ruler: false }; + let v = GuideDrag { vertical: true, index: Some(0), pos: 103.24, press: 50.0, over_ruler: false, flipped: false }; assert_eq!(guide_drag_readout(&app, v), Some(("X:", "103.2 px".to_owned()))); - let h = GuideDrag { vertical: false, index: None, pos: 40.0, press: 40.0, over_ruler: false }; + let h = GuideDrag { vertical: false, index: None, pos: 40.0, press: 40.0, over_ruler: false, flipped: false }; assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "40 px".to_owned()))); app.run("view.setRulerOrigin", json!({"x": 3.0, "y": 10.0})).unwrap(); assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "30 px".to_owned())), "from the zero point"); app.run("view.resetRulerOrigin", json!({})).unwrap(); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); - assert_eq!(guide_drag_readout(&app, GuideDrag { vertical: true, index: None, pos: 103.0, press: 0.0, over_ruler: false }).map(|r| r.0), Some("X:")); + assert_eq!( + guide_drag_readout(&app, GuideDrag { vertical: true, index: None, pos: 103.0, press: 0.0, over_ruler: false, flipped: false }).map(|r| r.0), + Some("X:") + ); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap(); app.guide_drag = Some(v); @@ -456,14 +459,14 @@ fn guide_drags_create_move_and_delete() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); app.sync_views(); - finish_drag(&mut app, GuideDrag { vertical: true, index: None, pos: 50.0, press: 50.0, over_ruler: false }); - finish_drag(&mut app, GuideDrag { vertical: false, index: None, pos: 500.0, press: 500.0, over_ruler: false }); // off canvas: ignored + finish_drag(&mut app, GuideDrag { vertical: true, index: None, pos: 50.0, press: 50.0, over_ruler: false, flipped: false }); + finish_drag(&mut app, GuideDrag { vertical: false, index: None, pos: 500.0, press: 500.0, over_ruler: false, flipped: false }); // off canvas: ignored assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![50.0]); assert!(app.session.active().unwrap().doc.guides.horizontal.is_empty()); assert_eq!(guide_at(&app, 51.0, 10.0), Some((true, 0))); - finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: 120.0, press: 50.0, over_ruler: false }); + finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: 120.0, press: 50.0, over_ruler: false, flipped: false }); assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![120.0]); - finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: -30.0, press: 120.0, over_ruler: false }); + finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: -30.0, press: 120.0, over_ruler: false, flipped: false }); assert!(app.session.active().unwrap().doc.guides.vertical.is_empty()); app.ui.extras.lock_guides = true; assert_eq!(guide_at(&app, 0.0, 0.0), None); @@ -699,20 +702,20 @@ fn a_guide_let_go_on_a_ruler_is_removed_not_moved() { app.sync_views(); let horizontal = |app: &PhotocraftApp| app.session.active().unwrap().doc.guides.horizontal.clone(); for drag in [ - GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 10.0, over_ruler: true }, + GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 10.0, over_ruler: true, flipped: false }, // Dragged sideways onto the left ruler, a horizontal guide holds its y, which on its own // reads as a click: the ruler still removes it. - GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 50.0, over_ruler: true }, + GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 50.0, over_ruler: true, flipped: false }, ] { app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); finish_drag(&mut app, drag); assert!(horizontal(&app).is_empty(), "let go on a ruler: removed, {drag:?}"); } app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); - finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 10.0, over_ruler: false }); + finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 10.0, over_ruler: false, flipped: false }); assert_eq!(horizontal(&app), vec![80.0], "let go on the canvas: moved"); // Clicked where it was pressed, on the canvas: selected and kept, as before. - finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 80.0, over_ruler: false }); + finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 80.0, over_ruler: false, flipped: false }); assert_eq!(horizontal(&app), vec![80.0], "clicked on the canvas: kept"); assert!(app.ui.selected_guide.is_some(), "clicked on the canvas: selected"); } @@ -866,3 +869,101 @@ fn shift_dragged_guides_land_on_ruler_ticks() { assert_eq!(snap_to_tick(&app, &xf, true, 37.0), 33.0); assert_eq!(snap_to_tick(&app, &xf, false, 37.0), 40.0); } + +/// #5034: ⌥ turns a guide dragged out of a ruler, as in Photoshop: out of the left ruler it +/// comes out horizontal, at the pointer's y. +#[test] +fn alt_turns_a_guide_dragged_out_of_a_ruler() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + // ⌥ held for the whole drag (`event_modifiers` would let go of it after each event). + let alt = egui::Modifiers::ALT; + h.event(egui::Event::ModifiersChanged(alt)); + let (from, to) = (pos2(RULER / 2.0, 100.0), xf.to_screen(37.0, 51.0)); + h.event(egui::Event::PointerMoved(from)); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: alt }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(1); + assert!(h.state().guide_drag.is_some_and(|d| !d.shows_vertical()), "drawn horizontal while ⌥ is held"); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: alt }); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.guides; + assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![], vec![51.0])); +} + +/// #5034: with the Move tool, ⌥ while dragging a guide turns it about the pointer, in one +/// undo step; letting go of ⌥ before the release turns it back. An ⌥-click turns it in place. +#[test] +fn alt_turns_a_guide_moved_with_the_move_tool() { + use crate::canvas::{ToolEvent, tool_event}; + let new_app = || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Move; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); + app + }; + let guides = |app: &PhotocraftApp| { + let g = &app.session.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) + }; + let (none, alt) = (egui::Modifiers::NONE, egui::Modifiers::ALT); + + let mut app = new_app(); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 44.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 63.0, y: 17.0, pressure: 1.0 }, alt); + assert!(app.guide_drag.is_some_and(|d| !d.shows_vertical() && d.pos == 17.0)); + tool_event(&mut app, ToolEvent::Up { x: 63.0, y: 17.0 }, alt); + assert_eq!(guides(&app), (vec![], vec![17.0])); + assert!(app.session.undo()); + assert_eq!(guides(&app), (vec![50.0], vec![]), "one undo step"); + + // ⌥ let go before the release: still vertical, moved along x. + let mut app = new_app(); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 44.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 63.0, y: 17.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Up { x: 63.0, y: 17.0 }, none); + assert_eq!(guides(&app), (vec![63.0], vec![])); + + // An ⌥-click turns the guide where it was clicked. + let mut app = new_app(); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 44.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 44.0 }, alt); + assert_eq!(guides(&app), (vec![], vec![44.0])); +} + +/// #5034: a guide dropped on either ruler is deleted, whichever way it runs; a horizontal +/// guide over the left ruler is still level with the image, so this needs the pointer. +#[test] +fn a_guide_dropped_on_either_ruler_is_deleted() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + for (pointer, over) in [(pos2(RULER / 2.0, 150.0), true), (pos2(200.0, RULER / 2.0), true), (pos2(200.0, 150.0), false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app.ui.extras.rulers = true; + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + app.guide_drag = Some(GuideDrag { vertical: false, index: Some(0), pos: 64.0, ..Default::default() }); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + h.event(egui::Event::PointerMoved(pointer)); + h.run_steps(1); + let mut d = h.state().guide_drag.unwrap(); + // The canvas release owns pointer classification in the current routing. + d.over_ruler = dropped_on_a_ruler(h.state(), full, pointer); + assert_eq!(d.over_ruler, over, "{pointer:?}"); + let app = h.state_mut(); + app.guide_drag = None; + finish_drag(app, d); + let left = app.session.active().unwrap().doc.guides.horizontal.clone(); + assert_eq!(left, if over { vec![] } else { vec![64.0] }, "{pointer:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.guides.horizontal, vec![30.0], "one Undo restores the guide"); + } +} diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index a3d18fe285..d3aa28546a 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -10,20 +10,23 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::layer_transfer::finish(app, ui.ctx()); // Once a frame, not per document view: the right-click or options-bar Brush Preset picker. crate::paint_mouse::show_picker(app, ui.ctx()); + // And the Shift+Alt+right-click HUD Color Picker (#6098), while its gesture is held. + crate::color_hud::show(app, ui.ctx()); + crate::brush_mode_menu::show(app, ui.ctx()); } -/// Window › Arrange tiles: each document shown with its tile in `rect`, or `None` when the -/// active document fills the area. pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option> { - let idx = app.session.active_index()?; - let n = app.session.documents().len(); + let documents = docked_document_indices(app); + let n = documents.len(); + if n == 0 { + return None; + } let cells = crate::view_cmds::cells(&app.ui.view.arrange, rect, n)?; - // Each document keeps its tile: a click into another one activates it where it is (#6017; it - // used to move to the first tile). With more documents than tiles, the shown run stays put - // while the active document is in it, and otherwise slides only as far as it must. - let start = app.arrange_start.min(n.saturating_sub(cells.len())); - let start = if idx < start { idx } else { start.max((idx + 1).saturating_sub(cells.len())) }; - Some((start..n).zip(cells).collect()) + // Keep stable tiles, expressing the remembered document index in the filtered docked list. + let start = documents.partition_point(|&d| d < app.arrange_start).min(n.saturating_sub(cells.len())); + let idx = app.session.active_index().and_then(|d| documents.iter().position(|&p| p == d)); + let start = idx.map_or(start, |idx| if idx < start { idx } else { start.max((idx + 1).saturating_sub(cells.len())) }); + Some(documents[start..].iter().copied().zip(cells).collect()) } fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -47,6 +50,12 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { open_on_double_click(app, ui, area); return; } + if n > 0 && !opening && docked_document_indices(app).is_empty() { + // A torn-off document belongs to its OS window. Leaving its canvas in the main + // viewport would make the same page appear twice, which is what “New Window” does. + paint_dots(ui, ui.available_rect_before_wrap(), app.session.prefs().interface.show_canvas_dots); + return; + } if !app.ui.view.hides_tabs() || opening { // Flat Spectrum tabs sit directly against the canvas. The parent's default vertical // item spacing would otherwise leave a visible gap below the tab strip (#2188). @@ -62,7 +71,12 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::jobs_ui::open_card(app, ui, job); return; } - let Some(idx) = app.session.active_index() else { return }; + let Some(active_doc) = app.session.active_index() else { return }; + let Some(idx) = main_canvas_document(app) else { + paint_dots(ui, ui.available_rect_before_wrap(), app.session.prefs().interface.show_canvas_dots); + return; + }; + let main_focused = ui.ctx().input(|i| i.viewport().focused.unwrap_or(true)); let rect = ui.available_rect_before_wrap(); app.last_canvas_rect = rect; app.drop_canvas_rect = Some(rect); @@ -74,20 +88,23 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { for (d, cell) in shown { let cell = cell.shrink(1.0); let view = app.ui.views[d].clone(); - let v = canvas_view(app, ui, d, cell, view, d == idx); - if d != idx { + let v = canvas_view(app, ui, d, cell, view, d == active_doc); + if d != active_doc { app.ui.views[d] = v; - if ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) { + if main_focused && ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) { app.session.set_active(d); } } - let stroke = if d == idx { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) }; + let stroke = if d == active_doc { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) }; ui.painter().rect_stroke(cell, 0, stroke, egui::StrokeKind::Inside); } return; } + if idx != active_doc && main_focused && ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| rect.contains(p))) { + app.session.set_active(idx); + } let view = app.ui.views[idx].clone(); - canvas_view(app, ui, idx, rect, view, true); + canvas_view(app, ui, idx, rect, view, app.session.active_index() == Some(idx)); } /// The tab strip; returns where its document tabs are. @@ -97,7 +114,9 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { return pro_tabs(app, ui); } let active = app.session.active_index(); - let tab_count = app.session.documents().len(); + let documents = docked_document_indices(app); + let tab_count = documents.len(); + let document_count = app.session.documents().len(); let mut doc_tabs = Vec::with_capacity(tab_count); let mut activate = None; let mut close = None; @@ -117,10 +136,9 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { // after the documents. let opening = crate::jobs_ui::open_tabs(app); // Every tab's natural width, whether or not it stays on the strip. - let natural: Vec = app - .session - .documents() + let natural: Vec = documents .iter() + .filter_map(|&doc| app.session.documents().get(doc)) .map(|st| { let name = studio_tab_name(app, st); ui.painter().layout_no_wrap(name, font.clone(), t.text).size().x @@ -137,7 +155,7 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { .jobs .focus .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) - .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); + .map_or_else(|| app.session.active_index().and_then(|doc| documents.iter().position(|&d| d == doc)).unwrap_or(0), |p| tab_count + p); let frame = egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| { let (row, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); let f = fit_doc_tabs(&natural, selected, row.width()); @@ -150,8 +168,9 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { x = r.right() + STUDIO_TAB_GAP; } for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { - let Some(st) = app.session.documents().get(i) else { continue }; - let sel = Some(i) == active && !focused_open; + let Some(&doc) = documents.get(i) else { continue }; + let Some(st) = app.session.documents().get(doc) else { continue }; + let sel = Some(doc) == active && !focused_open; let name = studio_tab_name(app, st); let meta = format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()); let natural_w = natural.get(i).copied().unwrap_or(0.0); @@ -160,13 +179,13 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let name_g = crate::tab_strip::elided(ui, &name, font.clone(), t.text, name_max); // The title was cut: the tooltip has the rest of it. let cut = name_g.size().x + 0.5 < natural_w - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x; - let resp = ui.interact(r, ui.scope_id().with(("dtab", i)), Sense::click_and_drag()); + let resp = ui.interact(r, ui.scope_id().with(("dtab", doc)), Sense::click_and_drag()); let saving = crate::jobs_ui::save_progress(app, st.doc.id); resp.widget_info(|| { let label = saving.as_ref().map_or_else(|| st.doc.name.clone(), |s| format!("{} - {s}", st.doc.name)); egui::WidgetInfo::selected(egui::Role::Button, true, sel, label) }); - doc_tabs.push((i, r)); + doc_tabs.push((doc, r)); if sel { ui.painter().rect_filled(r, t.radius_sm, t.card); ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); @@ -174,7 +193,7 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); } if dragging.is_some_and(|p| r.contains(p)) { - drag_over = Some(i); + drag_over = Some(doc); ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); } let color = if sel { t.text } else { t.text_dim }; @@ -182,25 +201,25 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), color); ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); - let xresp = ui.interact(xr, ui.scope_id().with(("dtabx", i)), Sense::click()); + let xresp = ui.interact(xr, ui.scope_id().with(("dtabx", doc)), Sense::click()); if xresp.hovered() { ui.painter().rect_filled(xr, 4.0, t.hover); } crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); let resp = if cut { resp.on_hover_text(name) } else { resp }; if tab_close_clicked(&resp, &xresp) { - close = Some(i); + close = Some(doc); } else if resp.clicked() { - activate = Some(i); + activate = Some(doc); } match tab_drag(ui, &resp, i, r, row, &placed, &t) { - Some(TabDrop::Move(to)) => tab_move = Some((i, to)), - Some(TabDrop::Float(at)) => tear_off = Some((i, at)), + Some(TabDrop::Move(to)) => tab_move = Some((doc, move_target_after_filter(&documents, doc, to, document_count))), + Some(TabDrop::Float(at)) => tear_off = Some((doc, at)), None => {} } let has_path = st.path.is_some(); resp.context_menu(|ui| { - tab_action = tab_context_menu(ui, i, tab_count, has_path); + tab_action = tab_context_menu(ui, doc, document_count, has_path); }); } // Files opening in the background: a tab with a progress underline; × cancels. @@ -236,15 +255,18 @@ pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). let left = (row.right() - crate::tab_strip::CHEVRON_W).max(row.left()); let r = Rect::from_min_size(egui::pos2(left, row.top()), egui::vec2(crate::tab_strip::CHEVRON_W, row.height())); - let labels: Vec<&str> = - app.session.documents().iter().map(|st| st.doc.name.as_str()).chain(opening.iter().map(|(_, name, _)| name.as_str())).collect(); + let labels: Vec<&str> = documents + .iter() + .filter_map(|&doc| app.session.documents().get(doc).map(|st| st.doc.name.as_str())) + .chain(opening.iter().map(|(_, name, _)| name.as_str())) + .collect(); let mut picked = None; // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks // the active one (#4487). let every: Vec = (0..labels.len()).collect(); crate::tab_strip::overflow_button(ui, ui.scope_id().with("dtab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); match picked { - Some(i) if i < tab_count => activate = Some(i), + Some(i) if i < tab_count => activate = documents.get(i).copied(), Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), None => {} } @@ -472,12 +494,15 @@ fn studio_tab_name(app: &PhotocraftApp, st: &photocraft_engine::DocState) -> Str /// strip; the active document's tab always stays on the strip (#1276, #4487). fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let t = crate::theme::Tokens::get(ui.ctx()); - let active = app.session.active_index().filter(|_| app.jobs.focus.is_none()); + let documents = docked_document_indices(app); + let active_doc = app.session.active_index().filter(|_| app.jobs.focus.is_none()); + let active = active_doc.and_then(|doc| documents.iter().position(|&d| d == doc)); let (mut activate, mut close) = (None, None); let mut tab_action = None; let mut tab_move = None; let mut tear_off = None; - let tab_count = app.session.documents().len(); + let tab_count = documents.len(); + let document_count = app.session.documents().len(); let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); let mut drag_over = None; let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; @@ -489,15 +514,11 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { // Files opening in the background (#210) are tabs too ("name (Opening… 45%)" with a progress // underline); they share the fit's index space, after the documents. let opening = crate::jobs_ui::open_tabs(app); - let mut titles: Vec = (0..tab_count).map(|i| pro_tab_title(app, i)).collect(); + let mut titles: Vec = documents.iter().map(|&i| pro_tab_title(app, i)).collect(); titles.extend(opening.iter().map(|(_, name, frac)| format!("{name} ({} {:.0}%)", tl!("Opening…"), frac * 100.0))); // Every tab's natural width, whether or not it stays on the strip. let natural: Vec = titles.iter().map(|title| ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text).size().x + DOC_TAB_PAD).collect(); - let selected = app - .jobs - .focus - .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) - .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); + let selected = app.jobs.focus.and_then(|job| opening.iter().position(|(open, _, _)| *open == job)).map_or_else(|| active.unwrap_or(0), |p| tab_count + p); let f = fit_doc_tabs(&natural, selected, strip.width()); let mut x = strip.left(); let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); @@ -509,9 +530,10 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let mut doc_tabs = Vec::with_capacity(tab_count); let (mut focus_open, mut cancel_open) = (None, None); for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { + let Some(&doc) = documents.get(i) else { continue }; let Some(title) = titles.get(i) else { continue }; let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); - let resp = ui.interact(r, ui.scope_id().with(("ptab", i)), Sense::click_and_drag()); + let resp = ui.interact(r, ui.scope_id().with(("ptab", doc)), Sense::click_and_drag()); let sel = Some(i) == active; if sel { ui.painter().rect_filled(r, 0.0, t.chrome); @@ -519,12 +541,12 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); } if dragging.is_some_and(|p| r.contains(p)) { - drag_over = Some(i); + drag_over = Some(doc); ui.painter().rect_stroke(r, 0.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); } ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); let (xr, at) = pro_tab_layout(r, g.size().y, mac); - let xresp = ui.interact(xr, ui.scope_id().with(("ptabx", i)), Sense::click()); + let xresp = ui.interact(xr, ui.scope_id().with(("ptabx", doc)), Sense::click()); // Painted: name the tab and its × for accessibility (and so tests and agents can find them). resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, sel, g.text())); xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); @@ -533,20 +555,20 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let cut = natural.get(i).copied().unwrap_or(0.0) > r.width() + 0.5; let resp = if cut { resp.on_hover_text(title.as_str()) } else { resp }; if tab_close_clicked(&resp, &xresp) { - close = Some(i); + close = Some(doc); } else if resp.clicked() { - activate = Some(i); + activate = Some(doc); } match tab_drag(ui, &resp, i, r, strip, &placed, &t) { - Some(TabDrop::Move(to)) => tab_move = Some((i, to)), - Some(TabDrop::Float(at)) => tear_off = Some((i, at)), + Some(TabDrop::Move(to)) => tab_move = Some((doc, move_target_after_filter(&documents, doc, to, document_count))), + Some(TabDrop::Float(at)) => tear_off = Some((doc, at)), None => {} } - let has_path = app.session.documents().get(i).is_some_and(|d| d.path.is_some()); + let has_path = app.session.documents().get(doc).is_some_and(|d| d.path.is_some()); resp.context_menu(|ui| { - tab_action = tab_context_menu(ui, i, tab_count, has_path); + tab_action = tab_context_menu(ui, doc, document_count, has_path); }); - doc_tabs.push((i, r)); + doc_tabs.push((doc, r)); } for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { let Some((job, _, frac)) = opening.get(i - tab_count) else { continue }; @@ -583,7 +605,7 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { let every: Vec = (0..labels.len()).collect(); crate::tab_strip::overflow_button(ui, ui.scope_id().with("ptab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); match picked { - Some(i) if i < tab_count => activate = Some(i), + Some(i) if i < tab_count => activate = documents.get(i).copied(), Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), None => {} } @@ -714,19 +736,25 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { } let mut view = w.view.clone(); let mut close = false; + let mut focused = false; ctx.show_viewport_immediate(vid, builder, |ui, class| { if ui.ctx().input(|i| i.viewport().close_requested()) { close = true; } + focused = ui.ctx().input(|i| i.viewport().focused == Some(true)); + if focused && !w.focused && app.session.active_index() != Some(w.document) { + app.session.set_active(w.document); + } egui::CentralPanel::default().frame(egui::Frame::NONE.fill(crate::theme::Tokens::get(ui.ctx()).canvas)).show(ui, |ui| { let rect = ui.available_rect_before_wrap(); - view = canvas_view(app, ui, w.document, rect, view.clone(), false); + view = canvas_view(app, ui, w.document, rect, view.clone(), focused); // Preferences › Zoom Resizes Windows: a zoom wraps the window around the image. crate::zoom_window_fit::follow(app, ui.ctx(), class, vid, &w, &mut view, rect); }); }); if let Some(win) = app.ui.windows.iter_mut().find(|x| x.id == w.id) { win.view = view; + win.focused = focused; if close { win.open = false; } @@ -734,3 +762,28 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { } app.ui.windows.retain(|w| w.open); } + +/// Window › Arrange tiles: each document shown with its tile in `rect`, or `None` when the +/// active document fills the area. +pub(super) fn docked_document_indices(app: &PhotocraftApp) -> Vec { + (0..app.session.documents().len()).filter(|&doc| !crate::view_cmds::document_is_floating(app, doc)).collect() +} + +pub(super) fn main_canvas_document(app: &PhotocraftApp) -> Option { + let active = app.session.active_index()?; + if !crate::view_cmds::document_is_floating(app, active) { + return Some(active); + } + docked_document_indices(app).into_iter().next() +} + +/// Convert a final tab index in the visible (docked-only) strip to the document list index, +/// keeping hidden floating documents in their existing relative order. +pub(super) fn move_target_after_filter(visible: &[usize], from: usize, to: usize, document_count: usize) -> usize { + let remaining: Vec = visible.iter().copied().filter(|&doc| doc != from).collect(); + match remaining.get(to) { + Some(&doc) if doc > from => doc - 1, + Some(&doc) => doc, + None => document_count.saturating_sub(1), + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 80b9c502a9..6bce89cc0d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2954,3 +2954,55 @@ fn damage_grows_by_nested_effect_reach() { group.visible = false; assert_eq!(effect_reach(&[group]), 0); } + +#[test] +fn tab_reorder_keeps_floating_documents_in_place() { + let visible = [0, 2]; + assert_eq!(move_target_after_filter(&visible, 0, 1, 3), 2); + assert_eq!(move_target_after_filter(&visible, 2, 0, 3), 0); +} + +#[test] +fn arrange_layout_only_includes_docked_documents() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["first", "floating", "last"] { + app.run("file.new", json!({"width": 80, "height": 60, "name": name})).unwrap(); + } + app.ui.view.arrange = "threeUpStacked".into(); + crate::menus::invoke(&mut app, &egui::Context::default(), "window.arrange.floatInWindow", json!({"document": 1})).unwrap(); + let rect = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let shown: Vec<_> = arranged_cells(&app, rect).unwrap().into_iter().map(|(doc, _)| doc).collect(); + assert_eq!(shown, vec![0, 2]); + + crate::menus::invoke(&mut app, &egui::Context::default(), "window.arrange.floatInWindow", json!({"document": 0})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), "window.arrange.floatInWindow", json!({"document": 2})).unwrap(); + assert!(arranged_cells(&app, rect).is_none(), "the main canvas should be blank when every document is floating"); +} + +#[test] +fn torn_off_document_is_not_drawn_again_in_the_main_window() { + for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::Studio] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60, "name": "floating"})).unwrap(); + app.run("file.new", json!({"width": 80, "height": 60, "name": "docked"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "window.arrange.floatInWindow", json!({"document": 0})).unwrap(); + assert!(app.ui.windows[0].floating); + assert_eq!(app.session.active_index(), Some(0), "{kind:?}: the floated page remains active"); + assert_eq!(main_canvas_document(&app), Some(1), "{kind:?}: the main canvas picks a docked page instead"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(680.0, 480.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(3); + let tabs = h.state().0.tab_strip.as_ref().map(|s| s.tabs.iter().map(|(doc, _)| *doc).collect::>()); + assert_eq!(tabs, Some(vec![1]), "{kind:?}: only the docked document stays on the main tab strip"); + } +} diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index d193bf6e00..f3791f23eb 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -1,3 +1,4 @@ +use super::cancel_stale_vector_drag; use super::cursors::{alt_eyedropper, sample_eyedropper}; use super::drag::Drag; use super::gesture::{finish_gesture, polygon_click, selection_mode}; @@ -191,7 +192,9 @@ fn filter_event_before_tool(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui:: if let ToolEvent::Down { x, y, .. } = raw && let Some((vertical, i)) = command_guide_at(app, app.active_tool(), [x, y], mods) { - app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + let mut guide = crate::rulers::GuideDrag::existing(vertical, i, [x, y]); + guide.track([x, y], mods.alt); + app.guide_drag = Some(guide); crate::snap_ui::begin_guide(app, [x, y]); return None; } @@ -214,7 +217,9 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: crate::guide_select::flip(app, vertical, i, [x, y]); return true; } - app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + let mut guide = crate::rulers::GuideDrag::existing(vertical, i, [x, y]); + guide.track([x, y], mods.alt); + app.guide_drag = Some(guide); return true; } // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first @@ -273,14 +278,14 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: } ToolEvent::Move { x, y, .. } => { if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) { - d.pos = if d.vertical { x } else { y }; + d.track([x, y], mods.alt); return true; } } ToolEvent::Up { x, y } => { if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) { app.guide_drag = None; - d.pos = if d.vertical { x } else { y }; + d.track([x, y], mods.alt); crate::rulers::finish_drag(app, d); return true; } @@ -290,19 +295,42 @@ fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: false } +fn consumes_cancelled_vector_event(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { + cancel_stale_vector_drag(app); + if app.cancelled_vector_drag { + match ev { + ToolEvent::Down { .. } => app.cancelled_vector_drag = false, + ToolEvent::Move { .. } => return true, + ToolEvent::Up { .. } => { + app.cancelled_vector_drag = false; + return true; + } + } + } + false +} + +fn handle_eyedropper_event(app: &mut PhotocraftApp, tool: Tool, ev: ToolEvent, mods: egui::Modifiers) -> bool { + if tool != Tool::Eyedropper { + return false; + } + match ev { + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, mods), + ToolEvent::Up { .. } => {} + } + true +} + /// Tool state machine. Shared by mouse input and automation. pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + if consumes_cancelled_vector_event(app, ev) { + return; + } let Some((armed, mods)) = preflight_tool_event(app, ev, mods) else { return }; let Some((raw, ev, mods)) = filter_event_before_tool(app, ev, mods, armed) else { return }; let tool = event_tool(app, mods); - if tool == Tool::Eyedropper { - match ev { - ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => { - sample_eyedropper(app, x, y, mods); - return; - } - ToolEvent::Up { .. } => return, - } + if handle_eyedropper_event(app, tool, ev, mods) { + return; } // A locked layer (the Background without a selection, say): no drag, and Photoshop's message // once the pointer moves (a click says nothing). ⌘ with a selection tool here (#896); the Move @@ -391,6 +419,8 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { let _ = app.run("layer.select", json!({"layer": id.0})); } + // The component pressed is selected, so the drag moves it (and the others selected). + crate::path_components::press(app, [x, y], mods.shift); } Tool::Pen => { if !(mods.alt && crate::vector_ui::pen_grab_handle(app, x, y)) { @@ -473,7 +503,9 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) } // ⌥ flips Dodge/Burn and Blur/Sharpen for this stroke. let tool = crate::retouch_ui::alt_flipped(tool, mods.alt); - app.drag = Some(Drag { clear, ..Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase) }); + 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); + app.drag = Some(drag); app.trail = None; app.stylus.begin_stroke(); if from.is_some() { diff --git a/crates/ui-egui/src/canvas/zoom_window_fit.rs b/crates/ui-egui/src/canvas/zoom_window_fit.rs index 9667c95949..75e2f7495f 100644 --- a/crates/ui-egui/src/canvas/zoom_window_fit.rs +++ b/crates/ui-egui/src/canvas/zoom_window_fit.rs @@ -273,7 +273,7 @@ mod tests { let viewport = ViewportId::from_hash_of(("docwin", 3_u64)); let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0)); let at = |zoom| view([400, 300], zoom); - let window = DocWindow { id: 3, document: 0, view: at(1.0), open: true, position: None }; + let window = DocWindow { id: 3, document: 0, view: at(1.0), open: true, position: None, floating: false, focused: false }; let frame = |app: &PhotocraftApp, class, after: &View| follow(app, &ctx, class, viewport, &window, &mut after.clone(), rect); // Off by default, as in Photoshop. assert!(!app.session.prefs().general.zoom_resizes_windows); @@ -359,7 +359,7 @@ mod tests { let ctx = Context::default(); let viewport = ViewportId::from_hash_of(("docwin", 4_u64)); let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let window = DocWindow { id: 4, document: 0, view: view([400, 300], 1.0), open: true, position: None }; + let window = DocWindow { id: 4, document: 0, view: view([400, 300], 1.0), open: true, position: None, floating: false, focused: false }; let mut first = view([400, 300], 1.0); assert_eq!(follow(&app, &ctx, ViewportClass::Immediate, viewport, &window, &mut first, rect), None); // A Zoom tool click near the top-left corner doubles the zoom about that spot. @@ -377,7 +377,7 @@ mod tests { app.sync_views(); app.run("prefs.set", json!({"path": "general.zoomResizesWindows", "value": true})).unwrap(); let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let window = DocWindow { id: 5, document: 0, view: view([400, 300], 1.0), open: true, position: None }; + let window = DocWindow { id: 5, document: 0, view: view([400, 300], 1.0), open: true, position: None, floating: false, focused: false }; for (maximized, fullscreen) in [(true, false), (false, true)] { let ctx = Context::default(); let mut raw = egui::RawInput::default(); diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index a3c1f4b9b0..c544aad4e3 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -560,3 +560,46 @@ fn every_slider_mode_recolours_the_selected_shape() { assert_eq!(shape_fill(h.state()), [255, 255, 255], "{mode:?}"); } } + +/// #9592: the Color panel's options survive a restart (they ride in the preferences), as in +/// Photoshop; preferences without them keep the defaults. +#[test] +fn color_panel_options_survive_a_restart() { + let mut first = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + first.ui.color_panel.mode = ColorPanelMode::HsbSliders; + first.ui.color_panel.ramp = ColorRamp::GrayscaleRamp; + crate::color_panel_ui::persist(&mut first); + let saved = first.session.prefs().clone(); + + let mut next = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + next.session.prefs.edit(|p| *p = saved); + crate::color_panel_ui::restore(&mut next); + assert_eq!((next.ui.color_panel.mode, next.ui.color_panel.ramp), (ColorPanelMode::HsbSliders, ColorRamp::GrayscaleRamp)); + + let mut fresh = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + crate::color_panel_ui::restore(&mut fresh); + assert_eq!(fresh.ui.color_panel.mode, ColorPanelMode::HueCube, "no saved options: the default"); +} + +/// CodeRabbit on #9606: a preference change made outside the panel (`prefs.set`, a reset) is kept. +/// The next frame takes it into the live panel instead of writing the panel's old options back. +#[test] +fn an_outside_preference_change_reaches_the_live_panel() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.color_panel.mode = ColorPanelMode::HsbSliders; + crate::color_panel_ui::persist(&mut app); + // As prefs.set or a reset to defaults would: the stored options change under the panel. + let mut other = app.ui.color_panel; + other.mode = ColorPanelMode::GrayscaleSlider; + app.session.prefs.edit(|p| p.color_panel = serde_json::to_value(other).unwrap()); + crate::color_panel_ui::persist(&mut app); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::GrayscaleSlider, "the live panel follows the preference"); + let stored: crate::state::ColorPanelState = serde_json::from_value(app.session.prefs().color_panel.clone()).unwrap(); + assert_eq!(stored.mode, ColorPanelMode::GrayscaleSlider, "and the preference isn't overwritten"); + // A reset to defaults clears the stored options: the panel goes back to its defaults too. + app.session.prefs.edit(|p| p.color_panel = serde_json::Value::Null); + crate::color_panel_ui::persist(&mut app); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HueCube, "reset: the default mode"); + crate::color_panel_ui::persist(&mut app); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HueCube, "and it stays reset"); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index aed074b11e..e979d3d829 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -181,3 +181,34 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest #[cfg(test)] mod tests; + +pub(super) const METHODS: &[&str] = &[ + "app.open", + "app.quit", + "app.save", + "engine.commands", + "engine.execute", + "jobs.cancel", + "jobs.list", + "ui.click", + "ui.context.choose", + "ui.dialog.apply", + "ui.dialog.cancel", + "ui.dialog.confirm", + "ui.dialog.open", + "ui.dialog.set", + "ui.focus", + "ui.gpu.simulateLoss", + "ui.inspect", + "ui.key", + "ui.menu.invoke", + "ui.menu.list", + "ui.move", + "ui.pointer", + "ui.resize", + "ui.screenshot", + "ui.set", + "ui.type", + "ui.window.close", + "ui.window.open", +]; diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index f3e2756071..c2600f064a 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1,3 +1,4 @@ +use super::METHODS; use super::inspect::inspect; use super::params::{ BUTTONS, KEY_MODIFIERS, MAX_CLICKS, POINTER_MODIFIERS, UI_SET_FIELDS, bool_field, err, f32_field, f32_range, input_choice, input_modifiers, input_number, @@ -10,7 +11,7 @@ type Handler = fn(&mut PhotocraftApp, &egui::Context, &ControlRequest) -> Option pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { const HANDLERS: [Handler; 5] = [engine_methods, shell_methods, dialog_methods, input_methods, app_methods]; - HANDLERS.iter().find_map(|handler| handler(app, ctx, req)).unwrap_or_else(|| err(format!("unknown method `{}`", req.method))) + HANDLERS.iter().find_map(|handler| handler(app, ctx, req)).unwrap_or_else(|| err(photocraft_engine::command_hints::unknown_method(&req.method, METHODS))) } fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { @@ -68,20 +69,23 @@ fn context_choose(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Ou fn execute_command(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; let Some(id) = str_param(p, "command").or(str_param(p, "id")) else { return err("missing `command`") }; + if req.method == "engine.execute" && METHODS.contains(&id) && photocraft_engine::commands::find(id).is_none() { + return err(photocraft_engine::command_hints::protocol_method_as_command(id)); + } let params = p.get("params").cloned().unwrap_or(json!({})); let wait = wait_param(p); // A control-channel menu click must respect the same modal gate as the native menu. // The documented `ui` requests of Camera Raw and the full-window workspaces operate // the already-open one rather than click a menu. Only that continuation may pass its - // own modal gate. engine.execute is deliberately not subject to the UI's menu-click semantics. + // own modal gate. Both command entry points respect document ownership. let open_modal = if app.camera_raw.is_some() { Some("filter.cameraRaw") } else { crate::distort_ui::modal_workspace(app) }; let continuation = open_modal == Some(id) && params.as_object().is_some_and(|fields| fields.len() == 1 && fields.get("ui").is_some_and(Value::is_object)) && app.ui.dialogs.is_empty() && app.discard.is_none() && !crate::crop_ui::blocks(app, id); - if req.method == "ui.menu.invoke" && !continuation && !crate::menus::modal_allows(app, id) { - return err("menu command is unavailable while a modal dialog is open"); + if !continuation && !crate::menus::modal_allows(app, id) { + return err("command is unavailable while a modal dialog is open"); } if let Some(authorize) = app.services.automation_command.as_ref() && let Err(error) = authorize(id, ¶ms) @@ -272,6 +276,8 @@ struct ToolSet { cam_transform_on_drop: Option, tile_grid: Option, layer_filter: Option, + pen_mode: Option, + pen_path_op: Option, } impl ToolSet { @@ -291,6 +297,8 @@ impl ToolSet { // Developer overlay of the active layer's storage tiles (tile_overlay.rs). tile_grid: bool_field(p, "tileGrid")?, layer_filter: p.get("layerFilter").map(|v| crate::layer_filter_ui::patched(&app.ui, v)).transpose()?, + pen_mode: pen_mode_param(p)?, + pen_path_op: pen_path_op_param(p)?, }) } @@ -328,6 +336,12 @@ impl ToolSet { if let Some(f) = self.layer_filter { crate::layer_filter_ui::apply(&mut app.ui, f); } + if let Some(m) = self.pen_mode { + app.ui.tool_options.vector_mode = m; + } + if let Some(o) = self.pen_path_op { + app.ui.tool_options.pen_path_op = o; + } } fn apply_gradient_and_trace(&self, app: &mut PhotocraftApp) { @@ -347,6 +361,21 @@ impl ToolSet { } } +/// The Pen tools' options bar (#1397): Path or Shape mode. +fn pen_mode_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("penMode") else { return Ok(None) }; + v.as_str().filter(|m| matches!(*m, "path" | "shape")).map(|m| Some(m.to_string())).ok_or_else(|| "penMode must be \"path\" or \"shape\"".to_string()) +} + +/// The Pen tools' Path Operation. +fn pen_path_op_param(p: &Value) -> std::result::Result, String> { + let Some(v) = p.get("penPathOp") else { return Ok(None) }; + v.as_str() + .filter(|o| crate::vector_ui::PATH_OPS.iter().any(|(id, ..)| id == o)) + .map(|o| Some(o.to_string())) + .ok_or_else(|| "penPathOp must be one of newLayer, combine, subtract, intersect, exclude".to_string()) +} + fn gradient_blend_param(p: &Value) -> std::result::Result, String> { let Some(value) = p.get("gradientBlendMode") else { return Ok(None) }; let Some(name) = value.as_str() else { return Err("gradientBlendMode must be a blend mode name".into()) }; @@ -893,7 +922,14 @@ fn color_picker_dialog(app: &mut PhotocraftApp, p: &Value) -> Outcome { let (Some(parent), Some(effect), Some(field)) = (u64_param(p, "parent"), str_param(p, "effect"), str_param(p, "field")) else { return err("need integer `parent` and string `effect` and `field`"); }; - return match crate::layer_style::color_picker::open(app, parent, effect, field) { + let stop = match p.get("stop") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().and_then(|i| usize::try_from(i).ok()) { + Some(i) => Some(i), + None => return err("`stop` must be a non-negative integer"), + }, + }; + return match crate::layer_style::color_picker::open(app, parent, effect, field, stop) { Ok(id) => ok(json!({"dialog": id})), Err(error) => err(error), }; @@ -1110,6 +1146,9 @@ fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { mods: modifiers_from(&parsed.modifiers), }; for sample in parsed.events { + if crate::brush_mode_menu::blocks_control(app, ctx, sample.ev) { + continue; + } if !pointer_event_intercepted(app, ctx, &gesture, &sample) { forward_pointer_event(app, &gesture, sample); } diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 12b34034b4..171fe49ef9 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -41,6 +41,11 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { "camTransform": app.ui.cam_transform, "layerMenu": app.ui.layer_menu, "layerPicker": app.ui.layer_picker, + "brushModeMenu": app.ui.brush_mode_menu.map(|pos| json!({ + "pos": pos, + "mode": if app.ui.tool_options.brush_clear { "Clear" } else { app.session.tools.brush.mode.label() }, + "choices": crate::brush_mode_menu::choices().iter().map(|(_, label)| *label).collect::>(), + })), "brushPicker": app.ui.brush_picker.map(|pos| json!({ "pos": pos, // The picker's content size once its corner grip was dragged (null: the default). diff --git a/crates/ui-egui/src/control/params.rs b/crates/ui-egui/src/control/params.rs index b2d8668ecb..d294cd06fb 100644 --- a/crates/ui-egui/src/control/params.rs +++ b/crates/ui-egui/src/control/params.rs @@ -4,7 +4,7 @@ use super::{Outcome, PhotocraftApp, Value, json}; /// field's value is validated before the first one is applied, so a typo, an unknown field, a /// bad value or a bad nested key can't reply with success while nothing — or only half of it — /// changed (#412). -pub const UI_SET_FIELDS: [&str; 43] = [ +pub const UI_SET_FIELDS: [&str; 45] = [ "updatesOpen", "tool", "strokeTrace", @@ -41,6 +41,8 @@ pub const UI_SET_FIELDS: [&str; 43] = [ "cropOverlayOrientation", "cropShield", "cropFill", + "penMode", + "penPathOp", "shapeStroke", "camTransformOnDrop", "tileGrid", diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 441dd31433..7c6768d2ba 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -8,6 +8,107 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu } } +/// #3674: a guessed name gets a pointer to the right one, in both directions; and every +/// method listed for those hints is served. +#[test] +fn unknown_names_suggest_the_right_method_or_command() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let mut error = |method: &str, params: Value| { + let reply = call(&mut app, &ctx, method, params); + assert_eq!(reply["ok"], false, "{reply}"); + reply["error"].as_str().unwrap_or_default().to_owned() + }; + let e = error("engine.execute", json!({"command": "engine.commands"})); + assert!(e.contains("did you mean `command.list`") && e.contains("protocol method"), "{e}"); + let e = error("engine.execute", json!({"command": "ui.inspect"})); + assert!(e.contains("`ui.inspect` is a protocol method"), "{e}"); + let e = error("engine.execute", json!({"command": "edit.undoo"})); + assert!(e.contains("did you mean `edit.undo`"), "{e}"); + let e = error("ui.inspct", json!({})); + assert!(e.contains("did you mean `ui.inspect`"), "{e}"); + let e = error("edit.undo", json!({})); + assert!(e.contains("engine.execute {\"command\": \"edit.undo\"}"), "{e}"); + for m in METHODS { + let (req, _rx) = ControlRequest::new(*m, json!({})); + if let Outcome::Done(v) = handle(&mut app, &ctx, &req) { + assert!(!v.to_string().contains("unknown method"), "{m} is listed but not served: {v}"); + } + } +} + +#[test] +fn shift_right_brush_does_not_open_presets_or_paint() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.ui.tool = crate::state::Tool::Brush; + let ctx = egui::Context::default(); + let before = app.session.journal.len(); + call( + &mut app, + &ctx, + "ui.pointer", + json!({"button": "right", "shift": true, + "events": [{"kind": "down", "x": 20, "y": 20}, {"kind": "up", "x": 20, "y": 20}]}), + ); + assert!(app.ui.brush_picker.is_none(), "Shift+right opens Mode, not Brush Presets"); + assert!(app.drag.is_none()); + assert_eq!(app.session.journal.len(), before, "opening a menu does not paint or journal"); +} + +#[test] +fn brush_mode_control_routes_modifiers_and_reports_choices_without_history() { + let ctx = egui::Context::default(); + for (tool, modifiers, expected) in [ + ("brush", json!({"shift": true}), "mode"), + ("brush", json!({}), "erase"), + ("brush", json!({"alt": true}), "resize"), + ("brush", json!({"shift": true, "alt": true}), "erase"), + ("brush", json!({"shift": true, "ctrl": true}), if cfg!(target_os = "macos") { "erase" } else { "layer" }), + ("brush", json!({"shift": true, "command": true}), "layer"), + ("pencil", json!({"shift": true}), "preset"), + ] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); + let history = app.session.active().unwrap().history.past_len(); + call( + &mut app, + &ctx, + "ui.pointer", + json!({"tool": tool, "button": "right", "modifiers": modifiers, + "events": [{"kind": "down", "x": 20, "y": 20}]}), + ); + assert_eq!(app.ui.brush_mode_menu.is_some(), expected == "mode", "{tool}: {modifiers}"); + match expected { + "mode" => { + assert!(app.drag.is_none() && !app.secondary_erase); + assert_eq!(app.session.active().unwrap().history.past_len(), history); + let inspect = inspect(&app, &ctx); + assert_eq!(inspect["brushModeMenu"]["choices"], json!(crate::brush_mode_menu::choices().iter().map(|(_, label)| *label).collect::>())); + let journal = app.session.journal.len(); + call( + &mut app, + &ctx, + "ui.pointer", + json!({"events": [ + {"kind": "down", "x": 10, "y": 10}, {"kind": "move", "x": 30, "y": 30}, {"kind": "up", "x": 30, "y": 30}]}), + ); + assert!(app.ui.brush_mode_menu.is_none() && app.drag.is_none()); + assert_eq!(app.session.journal.len(), journal, "control dismissal cannot paint"); + } + "preset" => assert!(app.ui.brush_picker.is_some()), + "layer" => assert!(app.ui.layer_menu.is_some()), + "resize" => assert!(app.brush_resize.is_some()), + "erase" => { + assert!(app.drag.as_ref().is_some_and(|d| d.erase)); + assert!(app.brush_resize.is_none(), "Shift+Alt is not the resize gesture"); + } + _ => panic!("unknown fixture route: {expected}"), + } + } +} + #[test] fn ui_set_turns_the_stroke_trace_on_and_off_at_runtime() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -204,10 +305,16 @@ fn full_window_workspaces_are_modal_for_menu_invocations() { "{workspace}: listed as enabled again" ); } - // engine.execute stays programmatic: it is not a menu click. + // Programmatic edits cannot bypass the active workspace ownership gate. assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.liquify"}))["ok"], true); + let before = app.session.active().unwrap().doc.clone(); + let history = app.session.active().unwrap().history.past_len(); let executed = call(&mut app, &ctx, "engine.execute", json!({"command":"select.all"})); - assert_eq!(executed["ok"], true, "{executed}"); + assert_eq!(executed["ok"], false, "{executed}"); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), history); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.liquify","params":{"ui":{"cancel":true}}}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "engine.execute", json!({"command":"select.all"}))["ok"], true); } #[test] @@ -218,8 +325,9 @@ fn layer_style_picker_control_binds_previews_confirms_and_cancels() { let parent = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"layerStyle","effect":"gradientOverlay"}))["result"]["dialog"].as_u64(); let parent = parent.unwrap(); let before = app.ui.dialogs[0].fields.clone(); - for field in ["from", "to"] { - let reply = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":field})); + // The Gradient Overlay's colours are its stops (#5177): `stop` picks one. + for stop in [0, 1] { + let reply = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"stops","stop":stop})); assert_eq!(reply["ok"], true, "{reply}"); let picker = app.ui.dialogs.last().unwrap().id; let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); @@ -227,10 +335,14 @@ fn layer_style_picker_control_binds_previews_confirms_and_cancels() { assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":parent}))["ok"], false); assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#123456"}))["ok"], true); assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":picker}))["ok"], true); - assert_eq!(app.ui.dialogs[0].fields["effects"][0]["params"][field], "#123456"); + assert_eq!(app.ui.dialogs[0].fields["effects"][0]["params"]["stops"][stop][1], "#123456"); } assert_ne!(app.ui.dialogs[0].fields, before); - call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"to"})); + let bad = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"stops","stop":"x"})); + assert_eq!(bad["ok"], false, "{bad}"); + let bad = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"stops","stop":9})); + assert_eq!(bad["ok"], false, "{bad}"); + call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"stops","stop":1})); assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog":parent}))["ok"], true); assert!(app.ui.dialogs.is_empty()); } @@ -703,6 +815,31 @@ fn menu_invoke_cannot_edit_document_behind_an_open_dialog() { assert!(app.session.active().unwrap().revision > revision); } +#[test] +fn engine_execute_cannot_change_document_behind_adjustment_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 60, "height": 40, "background": "#3366cc"})).unwrap(); + let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "image.adjustments.hueSaturation"})); + assert_eq!(opened["ok"], true, "{opened}"); + let dialog = opened["result"]["dialog"].as_u64().unwrap(); + let revision = app.session.active().unwrap().revision; + let fields = call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["dialogs"][0]["fields"].clone(); + + for method in ["engine.execute", "ui.menu.invoke"] { + let blocked = call(&mut app, &ctx, method, json!({"command": "image.adjustments.invert"})); + assert_eq!(blocked["ok"], false, "{method}: {blocked}"); + assert_eq!(app.session.active().unwrap().revision, revision, "{method} changed the document"); + let snapshot = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(snapshot["result"]["dialogs"][0]["id"], dialog); + assert_eq!(snapshot["result"]["dialogs"][0]["fields"], fields); + } + + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "engine.execute", json!({"command": "image.adjustments.invert"}))["ok"], true); + assert!(app.session.active().unwrap().revision > revision); +} + #[test] fn ui_set_rejects_unknown_fields_before_changing_anything() { use crate::theme::ThemeKind; @@ -846,6 +983,20 @@ fn ui_set_drives_the_crop_fill() { assert!(!app.ui.tool_options.crop_content_aware); } +/// #1397: the Pen's mode and Path Operation over the control channel, reported by `ui.inspect`. +#[test] +fn ui_set_drives_the_pen_path_operation() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "pen", "penMode": "shape", "penPathOp": "subtract"}))["ok"], true); + let o = &call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]; + assert_eq!((o["vector_mode"].clone(), o["pen_path_op"].clone()), (json!("shape"), json!("subtract"))); + for bad in [json!({"penPathOp": "melt"}), json!({"penPathOp": 1}), json!({"penMode": "pixels"}), json!({"penMode": "path", "penPathOp": "xor"})] { + assert_eq!(call(&mut app, &ctx, "ui.set", bad.clone())["ok"], false, "{bad}"); + assert_eq!((app.ui.tool_options.vector_mode.as_str(), app.ui.tool_options.pen_path_op.as_str()), ("shape", "subtract"), "{bad}: unchanged"); + } +} + /// #1919: the Crop tool's overlay menu over the control channel, reported by `ui.inspect`. #[test] fn ui_set_drives_the_crop_overlay_options() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 89954c52ea..755a8217ab 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -229,6 +229,7 @@ fn show_modal( ctx: &egui::Context, id: egui::Id, resizable: Option<(egui::Vec2, egui::Vec2, egui::Vec2)>, + fixed: Option, interactive: bool, contents: impl FnOnce(&mut egui::Ui) -> T, ) -> egui::ModalResponse { @@ -237,7 +238,12 @@ fn show_modal( if !interactive { ui.disable(); } - if let Some((size, min, max)) = resizable { + if let Some(size) = fixed { + egui::Resize::default().id(id.with("resize")).with_stroke(false).fixed_size(size).show(ui, |ui| { + ui.set_clip_rect(ui.clip_rect().expand(8.0)); + contents(ui) + }) + } else if let Some((size, min, max)) = resizable { // No stroke: Resize outlines its contents 2 points out, an inner box inside the // dialog's frame that left the title and buttons flush against it (#8199). egui::Resize::default().id(id.with("resize")).with_stroke(false).default_size(size.min(max)).min_size(min).max_size(max).show(ui, contents) @@ -324,7 +330,14 @@ fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fie _ if crate::blur_pins::owns(fields) => crate::blur_pins::body(ui, fields), _ if fields.contains_key("__filter") => filter_body(app, ui, d, fields, id), _ if crate::new_guide_ui::owns(fields) => crate::new_guide_ui::body(ui, fields), - _ if fields.contains_key("__form") => crate::view_cmds::form_body(ui, fields), + _ if fields.contains_key("__form") => { + if fields.get("__command").and_then(Value::as_str) == Some("file.fileInfo") { + let room = (ui.ctx().content_rect().height() - DIALOG_CHROME).max(120.0); + egui::ScrollArea::vertical().id_salt(("file-info-body", d.id)).max_height(room).show(ui, |ui| crate::view_cmds::form_body(ui, fields)); + } else { + crate::view_cmds::form_body(ui, fields); + } + } _ => {} } outcome @@ -367,7 +380,7 @@ fn dialog_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: & about_tab_body(app, ui, chosen); } DialogKind::Command => outcome = command_body(app, ui, d, fields, id, interactive), - DialogKind::LayerStyle => crate::layer_style::body(app, ui, fields), + DialogKind::LayerStyle => outcome = crate::layer_style::body_with_response(app, ui, fields, interactive), DialogKind::Error => { ui.label(fields.get("message").and_then(Value::as_str).unwrap_or("Error")); } @@ -584,7 +597,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { (remembered.unwrap_or(size), min, resizable_max(ctx, &fields, min)) }); let mut given = None; - let modal = show_modal(modal, ctx, id, resize, interactive, |ui| { + let fixed = (d.kind == DialogKind::LayerStyle) + .then(|| egui::vec2(800.0, 550.0).min((ctx.content_rect().size() - egui::vec2(40.0, 40.0)).max(egui::vec2(640.0, 360.0)))); + let modal = show_modal(modal, ctx, id, resize, fixed, interactive, |ui| { sizing = ui.is_sizing_pass(); let available = ui.available_size(); given = Some(available); @@ -611,7 +626,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ui.set_min_width(700.0); } ui.set_max_width(wide.unwrap_or_else(|| default_max_width(&d, compact, curves, about_tabs, available.x))); - if web { + if web || fixed.is_some() { ui.set_max_width(available.x); ui.set_min_size(available); } else if let Some(w) = crate::file_ui::dialog_width(&d.fields) { @@ -625,7 +640,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ui.set_max_width(360.0); } if color_picker { - ui.set_width(crate::color_picker_ui::CONTENT_WIDTH); + ui.set_width(crate::color_picker_ui::content_width(ui)); } let label = egui::Label::new(egui::RichText::new(&title).font(crate::theme::semibold(15.0))).selectable(false); let t = if crate::color_picker_ui::owns(&fields) { ui.add_sized(egui::vec2(ui.available_width(), 22.0), label).rect } else { ui.add(label).rect }; @@ -651,7 +666,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some(Value::String(key)) = fields.remove(BROWSE_FIELD) { browse_field(app, d.id, &fields, &key); } - if crate::guide_layout_ui::owns(&fields) || crate::brush_preset_dialog::owns(&fields) { + if d.kind == DialogKind::LayerStyle || crate::guide_layout_ui::owns(&fields) || crate::brush_preset_dialog::owns(&fields) { // These dialogs own their right-side actions and validate Enter themselves. } else if crate::color_picker_ui::owns(&fields) { if interactive && outcome.is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { @@ -689,7 +704,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.data_mut(|m| m.insert_persisted(size_id(place), size)); } // Pin once laid out at its real size (the first frame is an invisible sizing pass). - if !sizing && (web || pinned.is_none() || drag != egui::Vec2::ZERO) { + if !sizing && (web || fixed.is_some() || pinned.is_none() || drag != egui::Vec2::ZERO) { let screen = ctx.content_rect(); // Keep the whole dialog (and so its title bar) on screen. let room = (screen.size() - modal.response.rect.size()).max(egui::Vec2::ZERO); @@ -771,6 +786,11 @@ fn about_tab_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, tab: &str) { /// The dialog title as shown: [`title`] in the UI language. fn display_title(d: &Dialog) -> String { + match d.fields.get("__colorPicker").and_then(Value::as_str) { + Some("foreground") => return crate::color_picker_ui::fixed_title("Color Picker (Foreground Color)", "Foreground Color"), + Some("background") => return crate::color_picker_ui::fixed_title("Color Picker (Background Color)", "Background Color"), + _ => {} + } if crate::smart_filter_dialog::owns(&d.fields) { return crate::smart_filter_dialog::title(&d.fields); } diff --git a/crates/ui-egui/src/dialogs/adjust_preview.rs b/crates/ui-egui/src/dialogs/adjust_preview.rs index 69b8ea3568..62e3200eff 100644 --- a/crates/ui-egui/src/dialogs/adjust_preview.rs +++ b/crates/ui-egui/src/dialogs/adjust_preview.rs @@ -22,7 +22,7 @@ //! - the target is not a plain pixel layer (smart object, type, shape, group: the command edits //! a smart object's filters or refuses), or is itself clipped (a clipped adjustment would act on //! the whole clipping group, not just the target); -//! - the target uses Blend If (its "This Layer" ranges test the layer's adjusted colour); +//! - the target uses Blend If (its "Current Layer" ranges test the layer's adjusted colour); //! - the target's untouched area is visible (a surface without alpha whose content doesn't cover //! the canvas: the command only edits content); //! - the command targets an alpha channel, the Quick Mask or a single colour channel; diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index ac026d9e6a..c448d51414 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -221,6 +221,11 @@ pub fn title_for(name: &str) -> String { crate::i18n::fmt(tl!("Color Picker ({name})"), &[("name", name)]) } +/// Prefer a complete catalogued title; some locales only provide the named-colour template. +pub(crate) fn fixed_title(label: &str, name: &str) -> String { + if crate::i18n::has(crate::i18n::current(), label) { tl!(label).to_string() } else { title_for(tl!(name)) } +} + /// The `"#rrggbb"` at `field` of `f` (a key or a JSON pointer). fn field_value<'a>(f: &'a Map, field: &str) -> Option<&'a str> { match field.strip_prefix('/') { @@ -412,6 +417,13 @@ fn flat_grid_mesh(rect: Rect, n: usize, color: impl Fn(f32, f32) -> [f32; 3]) -> /// Room for both component columns, including units, without overflowing the title's width; with /// the frame and title the window fits Photoshop's (about 534 x 376 points). pub(crate) const CONTENT_WIDTH: f32 = 488.0; +/// Translated action labels can be substantially wider than their English equivalents. +pub(crate) fn content_width(ui: &egui::Ui) -> f32 { + let labels = ["OK", "Cancel", "Add to Swatches"]; + let english = crate::i18n::with_language(crate::i18n::Lang::EN, || widgets::button_width(ui, &labels)); + let translated = widgets::button_width(ui, &labels.map(crate::i18n::t)); + CONTENT_WIDTH + (translated - english).max(0.0) +} /// Side of the colour field (Photoshop's is about 256 points). const FIELD: f32 = 200.0; /// Width of the component fields. @@ -419,7 +431,7 @@ const VALUE_W: f32 = 42.0; /// Draw the picker and its top-right actions. `Some(true)` confirms, `Some(false)` cancels. pub fn body(ui: &mut egui::Ui, f: &mut Map) -> Option { - ui.set_width(CONTENT_WIDTH); + ui.set_width(content_width(ui)); ui.spacing_mut().item_spacing.y = 4.0; let mut outcome = None; ui.horizontal_top(|ui| { @@ -487,7 +499,8 @@ fn color_field(ui: &mut egui::Ui, f: &mut Map) { ui.painter().add(mesh(field, &|x, y| field_color(&mode, fz, x, y))); ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); let marker = pos2(field.left() + fx * field.width(), field.top() + fy * field.height()); - ui.painter().circle_stroke(marker, 5.0, Stroke::new(1.5, if hsv[2] > 0.6 && hsv[1] < 0.4 { Color32::BLACK } else { Color32::WHITE })); + // Clipped to the field: at the extremes the marker sits on the edge (#8968). + ui.painter().with_clip_rect(field).circle_stroke(marker, 5.0, Stroke::new(1.5, if hsv[2] > 0.6 && hsv[1] < 0.4 { Color32::BLACK } else { Color32::WHITE })); // Photoshop updates the colour on the press itself, not only when the button is released // (#6937): `is_pointer_button_down_on` is true from the press frame onwards (it covers // dragging too), while `clicked` fires on release and `dragged` only after a move. diff --git a/crates/ui-egui/src/dialogs/color_picker_ui/tests.rs b/crates/ui-egui/src/dialogs/color_picker_ui/tests.rs index 0ef4eb1ec0..254e3fd436 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui/tests.rs @@ -39,6 +39,33 @@ fn picker(color: &str) -> Harness<'static, Map> { h } +/// #8968: at the extremes the marker sits on the field's edge and must not paint past it. +#[test] +fn field_marker_stays_inside_the_field() { + // Black in the default "h" mode: the marker is at the bottom-left corner. + let h = picker("#000000"); + let mut field = None; + let mut circles = Vec::new(); + for clipped in &h.output().shapes { + match &clipped.shape { + egui::Shape::Mesh(m) if m.vertices.len() == 33 * 33 => { + // The component slider is a 33 x 33 mesh too, drawn after the field. + field.get_or_insert(m.calc_bounds()); + } + egui::Shape::Circle(c) => circles.push((c.center, c.radius, clipped.clip_rect)), + _ => {} + } + } + let field = field.expect("colour field drawn"); + // The radio buttons draw circles too: keep the ones on the field. + circles.retain(|(center, _, _)| field.expand(6.0).contains(*center)); + assert!(!circles.is_empty(), "the marker is drawn"); + for (center, radius, clip) in circles { + let visible = Rect::from_center_size(center, vec2(2.0 * radius, 2.0 * radius)).intersect(clip); + assert!(field.contains_rect(visible), "marker {visible:?} leaves the field {field:?}"); + } +} + /// Type `text` into the focused field one key per frame, like a person typing. fn type_keys(h: &mut Harness<'static, Map>, text: &str) { for ch in text.chars() { diff --git a/crates/ui-egui/src/dialogs/edit_history.rs b/crates/ui-egui/src/dialogs/edit_history.rs index 2012f912c7..d122c4b440 100644 --- a/crates/ui-egui/src/dialogs/edit_history.rs +++ b/crates/ui-egui/src/dialogs/edit_history.rs @@ -101,17 +101,30 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } if let Some(top) = app.ui.dialogs.last() { - if top.kind != DialogKind::Command { + // A shortcut field waiting for keys (Keyboard Shortcuts) records ⌘Z like any other key + // (#9487); stepping back here undid the click that started the capture. + if top.kind != DialogKind::Command || top.fields.get("capture").and_then(Value::as_bool) == Some(true) { return; } let id = top.id; let mut now = settings(&top.fields); + let history = app.dialog_edits.entry(id).or_insert_with(|| EditHistory::new(&now)); if let Some(step) = take_step(ctx) - && app.dialog_edits.entry(id).or_insert_with(|| EditHistory::new(&now)).step(&mut now, step) - && let Some(d) = app.ui.dialog_mut(id) + && history.step(&mut now, step) { - d.fields.retain(|k, _| k.starts_with("__")); - d.fields.extend(now); + // A step back to before a recorded shortcut doesn't wait for keys again (and, like + // the dialog itself, keeps no capture modifiers then). That isn't an edit of its own: + // the step's settled settings say so too, or the next frame would record it and + // lose Redo. + if let Some(c) = now.get_mut("capture") { + *c = Value::Bool(false); + now.remove("captureMods"); + history.settled = now.clone(); + } + if let Some(d) = app.ui.dialog_mut(id) { + d.fields.retain(|k, _| k.starts_with("__")); + d.fields.extend(now); + } } } else if let Some(d) = app.distort.gallery.as_mut() { if let Some(step) = take_step(ctx) { diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index b949b3b293..68f46af65f 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -6,7 +6,8 @@ use std::sync::Arc; #[cfg(not(target_arch = "wasm32"))] use std::sync::Mutex; -use photocraft_doc::Document; +use photocraft_cms::Profile; +use photocraft_doc::{ColorMode, Document}; use serde_json::{Map, Value, json}; use photocraft_engine::export_preset_cmds::{DEFAULT_RESAMPLE, RESAMPLE, export_resample}; @@ -15,7 +16,7 @@ use crate::state::DialogKind; use crate::theme::Tokens; use crate::{ExportSettings, PhotocraftApp}; -const FORMATS: [(&str, &str); 6] = [("png", "PNG"), ("jpg", "JPG"), ("webp", "WebP"), ("tif", "TIFF"), ("tga", "TGA"), ("ico", "ICO")]; +const FORMATS: [(&str, &str); 7] = [("png", "PNG"), ("jpg", "JPG"), ("webp", "WebP"), ("tif", "TIFF"), ("tga", "TGA"), ("ico", "ICO"), ("jxl", "JPEG XL")]; /// Preferences ▸ remembered dialog settings: Export As writes the settings it was used with /// last under its command id and seeds the next dialog from them, as Fill, Liquify and the @@ -278,6 +279,14 @@ fn source_document(app: &PhotocraftApp, f: &Map) -> Result Arc { + doc.icc_profile + .as_ref() + .and_then(|bytes| photocraft_engine::color_cmds::profile_from_bytes(bytes).ok()) + .filter(|profile| profile.color_space == photocraft_engine::color_cmds::mode_space(doc.mode)) + .unwrap_or_else(|| app.session.color.working(doc.mode)) +} + fn s(f: &Map, k: &str) -> String { f.get(k).and_then(Value::as_str).unwrap_or_default().to_string() } @@ -304,11 +313,16 @@ fn nearest(f: &Map) -> bool { /// The document as exported: scaled (engine Image Size, with the dialog's Resample method) and /// flattened over white when transparency is off or the format has no alpha. -fn export_document(doc: &Document, f: &Map, max_side: Option) -> Result { +fn export_document(doc: &Document, f: &Map, max_side: Option, source_profile: &Profile) -> Result { let resample = resample_method(f, max_side)?; + let srgb = s(f, "profile") == "srgb"; + let mut copy = doc.clone(); + if srgb { + copy.icc_profile = Some(source_profile.to_bytes()); + } let mut session = photocraft_engine::Session::new(); - session.add_document(doc.clone(), None); - if s(f, "profile") == "srgb" && doc.icc_profile.is_some() { + session.add_document(copy, None); + if srgb && (doc.mode != ColorMode::Rgb || !source_profile.same_bytes(photocraft_cms::Builtin::Srgb.profile())) { session.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "perceptual"})).map_err(|e| e.to_string())?; } let (w, h) = export_pixels(f64::from(doc.size.width), f64::from(doc.size.height), f, max_side)?; @@ -461,8 +475,8 @@ fn settings(f: &Map) -> ExportSettings { /// The preview and size estimate share a single reduced document. Resizing every layer twice is /// especially expensive for layered PSDs, even when the canvas itself is small. -fn preview_proxy(doc: &Document, f: &Map) -> Result { - export_document(doc, f, Some(if s_fmt(f) == "ico" { 256 } else { 512 })) +fn preview_proxy(doc: &Document, f: &Map, source_profile: &Profile) -> Result { + export_document(doc, f, Some(if s_fmt(f) == "ico" { 256 } else { 512 }), source_profile) } fn scaled_estimate(bytes: usize, doc: &Document, proxy: &Document, f: &Map) -> u64 { @@ -496,8 +510,8 @@ fn preview_pixels(proxy: &Document, estimate: Option) -> PreviewPixels { PreviewPixels { estimate, width: img.width as usize, height: img.height as usize, rgba: img.pixels } } -fn preview_sync(app: &PhotocraftApp, doc: &Document, f: &Map) -> Result { - let proxy = preview_proxy(doc, f)?; +fn preview_sync(app: &PhotocraftApp, doc: &Document, f: &Map, source_profile: &Profile) -> Result { + let proxy = preview_proxy(doc, f, source_profile)?; Ok(preview_pixels(&proxy, estimate(app, doc, &proxy, f))) } @@ -552,6 +566,7 @@ fn poll_or_start_preview( signature: &str, doc: Arc, fields: &Map, + source_profile: Arc, ) -> Option> { let pending_key = egui::Id::unique(("export-preview-pending", doc.id.0)); let pending: Option = ui.data(|d| d.get_temp(pending_key)); @@ -570,7 +585,7 @@ fn poll_or_start_preview( let started = std::thread::Builder::new().name("export-preview".into()).spawn(move || { let prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let source = source_document_from(doc.clone(), &fields).unwrap_or(doc); - let proxy = preview_proxy(&source, &fields)?; + let proxy = preview_proxy(&source, &fields, &source_profile)?; let estimate = estimate_native(&source, &proxy, &fields); Ok::<_, String>(preview_pixels(&proxy, estimate)) })) @@ -603,14 +618,14 @@ const EXACT_ESTIMATE_PX: f64 = 40_000_000.0; /// The exported file's size in bytes, from encoding the full export, or `None` when it is too /// large to encode for an estimate or can't be encoded. #[cfg(not(target_arch = "wasm32"))] -fn exact_estimate(doc: &Document, f: &Map) -> Option { +fn exact_estimate(doc: &Document, f: &Map, source_profile: &Profile) -> Option { // The size `export_document` will make: exact pixels only in pixel mode, else the scale. let (w, h) = export_pixels(f64::from(doc.size.width), f64::from(doc.size.height), f, None).ok()?; let px = w * h; if !px.is_finite() || px > EXACT_ESTIMATE_PX { return None; } - let full = export_document(doc, f, None).ok()?; + let full = export_document(doc, f, None, source_profile).ok()?; let bytes = photocraft_io::export(&full, &format!("estimate.{}", s_fmt(f)), &settings(f).io_options()).ok()?.bytes; u64::try_from(bytes.len()).ok() } @@ -618,7 +633,14 @@ fn exact_estimate(doc: &Document, f: &Map) -> Option { /// The exact size for `signature`, worked out off the UI thread: `None` until it is ready (the /// proxy estimate shows meanwhile), then `Some(None)` when there is no exact size. #[cfg(not(target_arch = "wasm32"))] -fn poll_or_start_exact_estimate(ui: &mut egui::Ui, key: egui::Id, signature: &str, doc: Arc, fields: &Map) -> Option> { +fn poll_or_start_exact_estimate( + ui: &mut egui::Ui, + key: egui::Id, + signature: &str, + doc: Arc, + fields: &Map, + source_profile: Arc, +) -> Option> { type Done = Arc>>>; let done_key = key.with("exact-estimate"); if let Some((sig, size)) = ui.data(|d| d.get_temp::<(String, Option)>(done_key)) @@ -648,7 +670,7 @@ fn poll_or_start_exact_estimate(ui: &mut egui::Ui, key: egui::Id, signature: &st let started = std::thread::Builder::new().name("export-estimate".into()).spawn(move || { let size = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let source = source_document_from(doc.clone(), &fields).unwrap_or(doc); - exact_estimate(&source, &fields) + exact_estimate(&source, &fields, &source_profile) })) .unwrap_or(None); *shared.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(size); @@ -869,6 +891,7 @@ fn preset_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); let Some(doc) = app.session.active().map(|s| s.doc.clone()) else { return }; + let source_profile = effective_source_profile(app, &doc); ui.horizontal_top(|ui| { // Left: settings. ui.vertical(|ui| { @@ -964,21 +987,22 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map = ui.data(|d| d.get_temp(key)); let preview = match cached.filter(|cached| cached.signature == sig) { Some(cached) => Some(cached), None => { #[cfg(not(target_arch = "wasm32"))] let result = if background_preview_needed(&doc) { - poll_or_start_preview(ui, key, &sig, doc.clone(), f) + poll_or_start_preview(ui, key, &sig, doc.clone(), f, source_profile.clone()) } else { let source = source_document(app, f).unwrap_or_else(|_| doc.clone()); - Some(preview_sync(app, &source, f)) + Some(preview_sync(app, &source, f, &source_profile)) }; #[cfg(target_arch = "wasm32")] let result = { let source = source_document(app, f).unwrap_or_else(|_| doc.clone()); - Some(preview_sync(app, &source, f)) + Some(preview_sync(app, &source, f, &source_profile)) }; let filter = preview_filter(f); result.map(|result| cache_preview(ui, key, sig.clone(), result, filter)) @@ -999,7 +1023,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map = None; let est = @@ -1017,12 +1041,13 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result) -> Result, path: &str) -> Result { - let out = export_document(doc, f, None)?; +fn write_export(app: &mut PhotocraftApp, doc: &Document, f: &Map, path: &str, source_profile: &Profile) -> Result { + let out = export_document(doc, f, None, source_profile)?; let export = app.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&out, path, &settings(f))?; let write = app.services.write.as_mut().ok_or("no writer configured")?; @@ -1064,7 +1089,8 @@ pub(crate) fn replay(app: &mut PhotocraftApp, params: &Value) -> Result Result, ids: &[photocraft_doc::LayerId]) -> Result { let st = app.session.active().ok_or("no document")?; + let source_profile = effective_source_profile(app, &st.doc); let docs: Vec = ids.iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id).map_err(|e| e.to_string())).collect::>()?; if docs.is_empty() { @@ -1083,7 +1110,7 @@ fn confirm_layers(app: &mut PhotocraftApp, f: &Map, ids: &[photoc app.pick_save(&suggested, move |app, path| { let mut exported = Vec::new(); for (doc, path) in docs.iter().zip(batch_paths(&path, &docs)) { - let out = export_document(doc, &f, None)?; + let out = export_document(doc, &f, None, &source_profile)?; let export = app.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&out, &path, &settings)?; let write = app.services.write.as_mut().ok_or("no writer configured")?; diff --git a/crates/ui-egui/src/dialogs/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs index cf79a0e38c..c5a7bdfa2f 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -6,14 +6,39 @@ fn ico_export_is_available_and_rejects_oversize_output() { f.insert("format".into(), json!("ico")); f.insert("scale".into(), json!(100)); assert!(FORMATS.iter().any(|(ext, _)| *ext == "ico")); - assert!(export_document(&app.session.active().unwrap().doc, &f, None).err().is_some_and(|e| e.contains("256"))); + assert!(default_export_document(&app.session.active().unwrap().doc, &f, None).err().is_some_and(|e| e.contains("256"))); f.insert("scale".into(), json!(50)); - let resized = export_document(&app.session.active().unwrap().doc, &f, None).unwrap(); + let resized = default_export_document(&app.session.active().unwrap().doc, &f, None).unwrap(); assert_eq!((resized.size.width, resized.size.height), (150, 100)); } use super::*; +fn default_export_document(doc: &Document, f: &Map, max_side: Option) -> Result { + super::export_document(doc, f, max_side, &photocraft_engine::color_cmds::document_profile(doc)) +} + +fn default_preview_proxy(doc: &Document, f: &Map) -> Result { + super::preview_proxy(doc, f, &photocraft_engine::color_cmds::document_profile(doc)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn default_exact_estimate(doc: &Document, f: &Map) -> Option { + super::exact_estimate(doc, f, &photocraft_engine::color_cmds::document_profile(doc)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn default_poll_or_start_preview( + ui: &mut egui::Ui, + key: egui::Id, + signature: &str, + doc: Arc, + fields: &Map, +) -> Option> { + let profile = photocraft_engine::color_cmds::document_profile(&doc); + super::poll_or_start_preview(ui, key, signature, doc, fields, profile) +} + /// Export As reopens with the settings it was used with last (Preferences ▸ remembered /// dialog settings), and a value no control accepts keeps its default. #[test] @@ -248,7 +273,7 @@ fn nearest_neighbor_doubles_each_pixel_into_an_exact_block() { f.insert("format".into(), json!("png")); f.insert("scale".into(), json!(200)); f.insert("resample".into(), json!("nearest")); - let out = export_document(&doc, &f, None).unwrap(); + let out = default_export_document(&doc, &f, None).unwrap(); assert_eq!((out.size.width, out.size.height), (10, 6)); assert_eq!(out.depth, depth); let surf = out.layers[0].surface().unwrap(); @@ -260,12 +285,12 @@ fn nearest_neighbor_doubles_each_pixel_into_an_exact_block() { assert_eq!(doc, before, "{depth:?}: export leaves the source document unchanged"); // The preview proxy keeps Nearest Neighbor's hard edges too. - let proxy = export_document(&doc, &f, Some(512)).unwrap(); + let proxy = default_export_document(&doc, &f, Some(512)).unwrap(); assert_eq!(proxy.layers[0].surface().unwrap().rgba(1, 1), checker(0, 0), "{depth:?}: preview proxy is nearest as well"); assert_eq!(preview_filter(&f), egui::TextureOptions::NEAREST); f.insert("resample".into(), json!(DEFAULT_RESAMPLE)); - let smooth = export_document(&doc, &f, None).unwrap(); + let smooth = default_export_document(&doc, &f, None).unwrap(); let blended = (0..6).flat_map(|y| (0..10).map(move |x| (x, y))).any(|(x, y)| { let p = smooth.layers[0].surface().unwrap().rgba(x, y); p[0] > 0.01 && p[2] > 0.01 @@ -284,14 +309,14 @@ fn resample_choices_are_checked() { f.insert("scale".into(), json!(300)); for (method, _) in RESAMPLE { f.insert("resample".into(), json!(method)); - let out = export_document(&doc, &f, None).unwrap(); + let out = default_export_document(&doc, &f, None).unwrap(); assert_eq!((out.size.width, out.size.height), (15, 9), "{method}"); } for bad in [json!("lanczos"), json!("NEAREST"), json!(""), json!(1), json!({"m": "nearest"})] { f.insert("resample".into(), bad.clone()); - let err = export_document(&doc, &f, None).unwrap_err(); + let err = default_export_document(&doc, &f, None).unwrap_err(); assert!(err.contains("resample must be"), "{bad}: {err}"); - assert!(export_document(&doc, &f, Some(512)).is_err(), "{bad}: the preview reports it too"); + assert!(default_export_document(&doc, &f, Some(512)).is_err(), "{bad}: the preview reports it too"); } f.remove("resample"); assert_eq!(resample_method(&f, None).unwrap(), "bicubicAutomatic"); @@ -340,7 +365,7 @@ fn export_document_scales_height_when_rounded_width_is_unchanged() { let mut f = Map::new(); f.insert("format".into(), json!("png")); f.insert("scale".into(), json!(scale)); - let out = export_document(&doc, &f, None).unwrap(); + let out = default_export_document(&doc, &f, None).unwrap(); assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, {depth:?}"); assert_eq!(out.depth, depth, "export preserves the document's depth"); assert_eq!(doc, before, "export leaves the source document unchanged"); @@ -360,7 +385,7 @@ fn export_document_proxy_limits_both_dimensions_before_rounding() { let mut f = Map::new(); f.insert("format".into(), json!("png")); f.insert("scale".into(), json!(scale)); - let out = export_document(&doc, &f, Some(max_side)).unwrap(); + let out = default_export_document(&doc, &f, Some(max_side)).unwrap(); assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, proxy limit {max_side}"); assert!(out.size.width.max(out.size.height) <= max_side, "proxy respects its longest-side limit"); assert_eq!(doc, before, "preview leaves the source document unchanged"); @@ -390,9 +415,12 @@ fn the_estimate_is_the_exported_files_size() { } } let doc = Arc::new(doc); - let f = Map::from_iter([("format".into(), json!("jpg")), ("scale".into(), json!(100)), ("quality".into(), json!(32))]); - let actual = photocraft_io::export(&export_document(&doc, &f, None).unwrap(), "x.jpg", &settings(&f).io_options()).unwrap().bytes.len() as u64; - let proxy = preview_proxy(&doc, &f).unwrap(); + // Without the embedded profile, whose fixed size the proxy would scale with the pixels + // (the untagged document is tagged sRGB on export, #9325). + let f = + Map::from_iter([("format".into(), json!("jpg")), ("scale".into(), json!(100)), ("quality".into(), json!(32)), ("embedProfile".into(), json!(false))]); + let actual = photocraft_io::export(&default_export_document(&doc, &f, None).unwrap(), "x.jpg", &settings(&f).io_options()).unwrap().bytes.len() as u64; + let proxy = default_preview_proxy(&doc, &f).unwrap(); let old = estimate_native(&doc, &proxy, &f).unwrap(); assert!((old as f64 / actual as f64 - 1.0).abs() > 0.1, "the proxy estimate was off: {old} vs {actual}"); @@ -402,7 +430,8 @@ fn the_estimate_is_the_exported_files_size() { let size = loop { let mut size = None; let mut output = ctx.run_ui(Default::default(), |ctx| { - egui::CentralPanel::default().show(ctx, |ui| size = poll_or_start_exact_estimate(ui, key, "jpg32", doc.clone(), &f)); + egui::CentralPanel::default() + .show(ctx, |ui| size = poll_or_start_exact_estimate(ui, key, "jpg32", doc.clone(), &f, photocraft_engine::color_cmds::document_profile(&doc))); }); output.textures_delta.clear(); if let Some(size) = size { @@ -419,7 +448,7 @@ fn the_estimate_is_the_exported_files_size() { ("width".into(), json!(10_000)), ("height".into(), json!(10_000)), ]); - assert_eq!(exact_estimate(&doc, &huge), None); + assert_eq!(default_exact_estimate(&doc, &huge), None); // In scale mode the size comes from the scale, as the export's does, not from stale pixels. let big = Arc::new(Document::with_background( "big", @@ -435,7 +464,7 @@ fn the_estimate_is_the_exported_files_size() { ("width".into(), json!(100)), ("height".into(), json!(100)), ]); - assert_eq!(exact_estimate(&big, &stale), None, "10000 × 10000 at 1000 %, over the limit"); + assert_eq!(default_exact_estimate(&big, &stale), None, "10000 × 10000 at 1000 %, over the limit"); let small = Map::from_iter([ ("format".into(), json!("png")), ("sizing".into(), json!("scale")), @@ -443,8 +472,9 @@ fn the_estimate_is_the_exported_files_size() { ("width".into(), json!(9000)), ("height".into(), json!(9000)), ]); - let at_10 = photocraft_io::export(&export_document(&big, &small, None).unwrap(), "x.png", &settings(&small).io_options()).unwrap().bytes.len() as u64; - assert_eq!(exact_estimate(&big, &small), Some(at_10), "100 × 100 at 10 %, within it"); + let at_10 = + photocraft_io::export(&default_export_document(&big, &small, None).unwrap(), "x.png", &settings(&small).io_options()).unwrap().bytes.len() as u64; + assert_eq!(default_exact_estimate(&big, &small), Some(at_10), "100 × 100 at 10 %, within it"); } /// #8341: Export As and its reduced preview carry the stroke width with the path. @@ -458,7 +488,7 @@ fn export_as_downscales_stroke_only_shapes_and_preview() { let doc = session.active().unwrap().doc.clone(); let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(25))]); for limit in [None, Some(128)] { - let out = export_document(&doc, &fields, limit).unwrap(); + let out = default_export_document(&doc, &fields, limit).unwrap(); let side = if limit.is_some() { 128 } else { 256 }; assert_eq!((out.size.width, out.size.height), (side, side)); let shape = out.layer(photocraft_doc::LayerId(id)).unwrap(); @@ -488,10 +518,10 @@ fn export_document_scales_and_flattens() { let mut f = Map::new(); f.insert("format".into(), json!("jpg")); f.insert("scale".into(), json!(50)); - let out = export_document(&doc, &f, None).unwrap(); + let out = default_export_document(&doc, &f, None).unwrap(); assert_eq!((out.size.width, out.size.height), (100, 50)); assert_eq!(out.layers.len(), 1); - let proxy = export_document(&doc, &f, Some(40)).unwrap(); + let proxy = default_export_document(&doc, &f, Some(40)).unwrap(); assert_eq!(proxy.size.width, 40); assert_eq!(settings(&f).jpeg_quality, Some(85)); } @@ -512,10 +542,10 @@ fn export_document_scales_when_only_the_height_changes() { photocraft_doc::SampleType::U8, photocraft_doc::Color::WHITE, ); - let out = export_document(&doc, &f, None).unwrap(); + let out = default_export_document(&doc, &f, None).unwrap(); assert_eq!((out.size.width, out.size.height), (1, want_h), "1 × {src_h} at 50%"); // The preview proxy takes the same path. - let proxy = export_document(&doc, &f, Some(40)).unwrap(); + let proxy = default_export_document(&doc, &f, Some(40)).unwrap(); assert_eq!((proxy.size.width, proxy.size.height), (1, 40), "proxy of 1 × {src_h}"); } // The label and the export agree, and neither side drops below 1 px. @@ -539,7 +569,7 @@ fn layered_preview_runs_outside_the_ui_frame() { let mut result = None; let mut output = ctx.run_ui(Default::default(), |ctx| { egui::CentralPanel::default().show(ctx, |ui| { - result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); + result = default_poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); }); }); output.textures_delta.clear(); @@ -549,7 +579,7 @@ fn layered_preview_runs_outside_the_ui_frame() { loop { let mut output = ctx.run_ui(Default::default(), |ctx| { egui::CentralPanel::default().show(ctx, |ui| { - result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); + result = default_poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); }); }); output.textures_delta.clear(); @@ -565,7 +595,7 @@ fn layered_preview_runs_outside_the_ui_frame() { } let tiff_fields = Map::from_iter([("format".into(), json!("tif")), ("scale".into(), json!(100))]); - let proxy = preview_proxy(&doc, &tiff_fields).unwrap(); + let proxy = default_preview_proxy(&doc, &tiff_fields).unwrap(); let options = photocraft_io::ExportOptions { tiff_layers: true, xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; let actual_bytes = photocraft_io::export(&proxy, "estimate.tif", &options).unwrap().bytes.len(); assert_eq!(estimate_native(&doc, &proxy, &tiff_fields), Some(scaled_estimate(actual_bytes, &doc, &proxy, &tiff_fields))); @@ -654,13 +684,199 @@ fn exact_pixels_lock_aspect_and_leave_the_source() { f.insert("sizing".into(), json!("pixels")); f.insert("width".into(), json!(120)); f.insert("height".into(), json!(40)); - let out = export_document(&doc, &f, None).unwrap(); + let out = default_export_document(&doc, &f, None).unwrap(); assert_eq!((out.size.width, out.size.height), (120, 40), "explicit pixels win over the percent scale"); - let proxy = export_document(&doc, &f, Some(20)).unwrap(); + let proxy = default_export_document(&doc, &f, Some(20)).unwrap(); assert_eq!((proxy.size.width, proxy.size.height), (20, 7)); assert_eq!(doc, before, "export leaves the source document unchanged"); } +fn check_profile_only_export(width: u32, height: u32) -> std::time::Duration { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + let mut doc = Document::with_background("untagged", Size::new(width, height), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut pixels = vec![0u8; width as usize * height as usize * 4]; + for (i, p) in pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() { + p.copy_from_slice(&[(i % 251) as u8, ((i / 251) % 251) as u8, ((i / 63001) % 251) as u8, 255]); + } + doc.layers[0].surface_mut().unwrap().write_interleaved(photocraft_geom::Rect::from_xywh(0, 0, width, height), &pixels); + let before = doc.clone(); + let fields = json!({"format": "png", "profile": "srgb", "transparency": true, "width": width, "height": height}).as_object().unwrap().clone(); + let start = std::time::Instant::now(); + let converted = default_export_document(&doc, &fields, None).unwrap(); + let elapsed = start.elapsed(); + let profile = photocraft_cms::Profile::parse(converted.icc_profile.as_deref().unwrap()).unwrap(); + assert!(profile.same_bytes(photocraft_cms::Builtin::Srgb.profile())); + let source = doc.layers[0].surface().unwrap(); + let output = converted.layers[0].surface().unwrap(); + assert!(source.tile_count() > 0); + assert_eq!(source.tile_count(), output.tile_count()); + assert_eq!(source.default_pixel(), output.default_pixel()); + for (coord, tile) in source.tiles() { + assert!(Arc::ptr_eq(tile, output.tile(*coord).unwrap()), "tagging must reuse pixel tiles"); + } + assert_eq!(doc, before); + elapsed +} + +#[test] +fn untagged_srgb_export_tags_without_rewriting_pixels() { + check_profile_only_export(8, 8); +} + +#[test] +#[ignore = "24 MP profile-preparation measurement"] +fn untagged_srgb_export_24mp_keeps_pixel_tiles() { + let elapsed = check_profile_only_export(6000, 4000); + println!("24 MP sRGB profile preparation (optimized test build): {elapsed:?}; all pixel tiles shared"); +} + +#[test] +fn untagged_jpeg_export_embeds_the_requested_srgb_profile() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + for (mode, depth) in [ + (ColorMode::Rgb, SampleType::U8), + (ColorMode::Rgb, SampleType::U16), + (ColorMode::Rgb, SampleType::F32), + (ColorMode::Grayscale, SampleType::U8), + (ColorMode::Cmyk, SampleType::U8), + ] { + let doc = Document::with_background("untagged", Size::new(8, 8), mode, depth, Color::WHITE); + assert!(doc.icc_profile.is_none()); + let before = doc.clone(); + let mut fields = + json!({"format": "jpg", "profile": "srgb", "embedProfile": true, "metadata": "none", "width": 8, "height": 8}).as_object().unwrap().clone(); + let converted = default_export_document(&doc, &fields, None).unwrap(); + let bytes = photocraft_io::export(&converted, "out.jpg", &settings(&fields).io_options()).unwrap().bytes; + let reloaded = photocraft_io::import("out.jpg", &bytes).unwrap().document; + let profile = photocraft_cms::Profile::parse(reloaded.icc_profile.as_deref().expect("explicit sRGB export must embed its profile")).unwrap(); + assert!(profile.same_colors(photocraft_cms::Builtin::Srgb.profile()), "{depth:?}"); + fields.insert("embedProfile".into(), json!(false)); + let bytes = photocraft_io::export(&converted, "out.jpg", &settings(&fields).io_options()).unwrap().bytes; + assert!(photocraft_io::import("out.jpg", &bytes).unwrap().document.icc_profile.is_none(), "embedding remains optional"); + fields.insert("profile".into(), json!("document")); + fields.insert("embedProfile".into(), json!(true)); + let unchanged = default_export_document(&doc, &fields, None).unwrap(); + assert!(unchanged.icc_profile.is_none(), "Document Profile preserves an untagged source"); + assert_eq!(doc, before, "export must not tag or convert the source document"); + } +} + +#[test] +fn preview_cache_tracks_working_profiles_but_prefers_embedded_profiles() { + use photocraft_cms::Builtin; + use photocraft_doc::{Color, SampleType, Size}; + for embedded in [false, true] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "policyRgb": "off"})).unwrap(); + let mut doc = Document::with_background("colour", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgba(0.35, 0.65, 0.45, 1.0)); + if embedded { + doc.icc_profile = Some(Builtin::DisplayP3.profile().to_bytes()); + } + app.session.open_document(doc, None); + let id = open(&mut app).unwrap(); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + fields.insert("profile".into(), json!("srgb")); + let st = app.session.active().unwrap(); + let revision = st.revision; + let key = egui::Id::unique(("export-preview", st.doc.id.0, revision, None::)); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); + let draw = |app: &mut PhotocraftApp, fields: &mut Map| { + let mut output = ctx.run_ui(Default::default(), |ui| body(app, ui, fields)); + output.textures_delta.clear(); + ctx.data(|d| d.get_temp::(key)).unwrap() + }; + let before = draw(&mut app, &mut fields); + let settings = settings_of(&fields); + app.session.execute("edit.colorSettings", json!({"workingRgb": "adobe-rgb-compat"})).unwrap(); + assert_eq!(app.session.active().unwrap().revision, revision); + let after = draw(&mut app, &mut fields); + assert_eq!(settings_of(&fields), settings); + assert_eq!(before.signature != after.signature, !embedded); + assert_eq!(before.texture.unwrap().id() != after.texture.unwrap().id(), !embedded); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn preview_workers_keep_the_captured_source_profile() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "policyRgb": "off"})).unwrap(); + let doc = Document::with_background( + "colour", + photocraft_doc::Size::new(8, 8), + ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::rgba(0.35, 0.65, 0.45, 1.0), + ); + app.session.open_document(doc, None); + let doc = app.session.active().unwrap().doc.clone(); + let profile = effective_source_profile(&app, &doc); + let fields = json!({"format": "png", "profile": "srgb", "transparency": true}).as_object().unwrap().clone(); + let expected = preview_sync(&app, &doc, &fields, &profile).unwrap(); + let expected_size = super::exact_estimate(&doc, &fields, &profile).unwrap(); + let ctx = egui::Context::default(); + let key = egui::Id::unique("captured-profile-worker"); + let mut preview = None; + let mut size = None; + let mut poll = || { + let mut output = ctx.run_ui(Default::default(), |ui| { + if preview.is_none() { + preview = super::poll_or_start_preview(ui, key, "p3", doc.clone(), &fields, profile.clone()); + } + if size.is_none() { + size = poll_or_start_exact_estimate(ui, key, "p3", doc.clone(), &fields, profile.clone()); + } + }); + output.textures_delta.clear(); + preview.is_some() && size.is_some() + }; + poll(); + app.session.execute("edit.colorSettings", json!({"workingRgb": "srgb"})).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !poll() { + assert!(std::time::Instant::now() < deadline, "profile-aware preview workers must finish"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(preview.unwrap().unwrap().rgba, expected.rgba); + assert_eq!(size.unwrap(), Some(expected_size)); +} + +#[test] +fn replay_converts_untagged_pixels_from_the_original_working_profile() { + use photocraft_cms::{Builtin, Intent}; + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + for working in [Builtin::DisplayP3, Builtin::AdobeRgbCompat] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("edit.colorSettings", json!({"workingRgb": working.id(), "policyRgb": "off"})).unwrap(); + let doc = Document::with_background("untagged", Size::new(8, 8), ColorMode::Rgb, depth, Color::rgba(0.35, 0.65, 0.45, 1.0)); + app.session.open_document(doc, None); + let source = app.session.active().unwrap().doc.clone(); + assert!(source.icc_profile.is_none()); + let mut expected = (*source).clone(); + expected.icc_profile = Some(working.profile().to_bytes()); + photocraft_engine::color_cmds::convert_document(&mut expected, Builtin::Srgb.profile(), Intent::Perceptual, true).unwrap(); + let original_pixel = source.layers[0].surface().unwrap().pixel(0, 0); + let expected_pixel = expected.layers[0].surface().unwrap().pixel(0, 0); + assert_ne!(original_pixel, expected_pixel, "the control must require a pixel conversion"); + let captured = Arc::new(std::sync::Mutex::new(None)); + let output = captured.clone(); + app.services.export = Some(Box::new(move |doc, _, _| { + *output.lock().unwrap() = Some(doc.clone()); + Ok((Vec::new(), Vec::new())) + })); + app.services.write = Some(Box::new(|_, _| Ok(()))); + replay(&mut app, &json!({"path": "out.png", "format": "png", "profile": "srgb", "transparency": true})).unwrap(); + let actual = captured.lock().unwrap().take().unwrap(); + assert_eq!(actual.layers[0].surface().unwrap().pixel(0, 0), expected_pixel, "{working:?} {depth:?}"); + let profile = photocraft_cms::Profile::parse(actual.icc_profile.as_deref().unwrap()).unwrap(); + assert!(profile.same_bytes(Builtin::Srgb.profile())); + assert_eq!(app.session.active().unwrap().doc, source); + } + } +} + #[test] fn profile_and_metadata_follow_the_existing_exporter() { use photocraft_cms::Builtin; @@ -696,7 +912,7 @@ fn profile_and_metadata_follow_the_existing_exporter() { f.insert("height".into(), json!(8)); f.insert("metadata".into(), json!("none")); f.insert("embedProfile".into(), json!(false)); - let converted = export_document(&doc, &f, None).unwrap(); + let converted = default_export_document(&doc, &f, None).unwrap(); let parsed = photocraft_cms::Profile::parse(converted.icc_profile.as_deref().unwrap()).unwrap(); assert!(parsed.same_colors(Builtin::Srgb.profile()), "Convert to sRGB replaces the document profile"); let stripped = photocraft_io::export(&converted, "out.jpg", &settings(&f).io_options()).unwrap().bytes; diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 2b63ee3379..29396f6022 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -25,6 +25,7 @@ use crate::{PhotocraftApp, widgets}; mod bevel_modes_tests; pub(crate) mod color_picker; mod contour; +mod gradient_field; #[cfg(test)] mod gradient_method_tests; @@ -35,6 +36,7 @@ enum P { Blend, Choice(&'static [(&'static str, &'static str)]), GradientMethod, + Gradient, Check, Angle, /// A pattern from the dialog's `patternList` field (`[[id, name], …]`). @@ -66,6 +68,9 @@ pub const KINDS: &[(&str, &str)] = &[ /// Effect kinds Photoshop offers several instances of (stored as `…Multi` lists in the PSD). const MULTI: &[&str] = &["stroke", "dropShadow", "innerShadow", "colorOverlay", "gradientOverlay"]; +/// Field holding the user defaults (Make Default) that new instances start from. +const USER_DEFAULTS: &str = "userDefaults"; + fn multi(kind: &str) -> bool { MULTI.contains(&kind) } @@ -75,12 +80,22 @@ fn kind_of(e: &Effect) -> &'static str { } fn defaults(kind: &str) -> Value { - photocraft_engine::layer_style::effect_defaults(kind) + let mut p = photocraft_engine::layer_style::effect_defaults(kind); + if kind == "gradientOverlay" { + gradient_field::from_to_to_stops(&mut p); + } + p } -/// Factory params for a new instance, with the shared light angle filled in. -fn fresh_params(kind: &str, light: f32) -> Value { +/// Params for a new instance: the user default saved by Make Default over the factory +/// defaults (#9477), with the shared light angle filled in. +fn fresh_params(kind: &str, light: f32, user: Option<&Value>) -> Value { let mut p = defaults(kind); + if let (Some(o), Some(u)) = (p.as_object_mut(), user.and_then(Value::as_object)) { + for (k, v) in u { + o.insert(k.clone(), v.clone()); + } + } if p.get("useGlobalLight").and_then(Value::as_bool) == Some(true) { p["angle"] = json!(light); } @@ -158,8 +173,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] { "gradientOverlay" => &[ ("blend", "Blend Mode", P::Blend), ("opacity", "Opacity", P::Slider(0.0, 100.0, "%")), - ("from", "From", P::Color), - ("to", "To", P::Color), + ("stops", "Gradient", P::Gradient), ("reverse", "Reverse", P::Check), ("style", "Style", P::Choice(GSTYLE)), ("angle", "Angle", P::Angle), @@ -307,14 +321,8 @@ fn values_of(e: &Effect, light: f32) -> Value { set(&mut v, "method", json!(source.method)); set(&mut v, "smoothness", json!(source.smoothness)); } - // Endpoint colours and geometry always load into the dialog. Recorded - // interpolation exposes the original source ends; a baked curve without a - // record (PSD import) keeps its interior stops in `fx`, and an edit only - // retints its ends until a method is chosen. - if let (Some(first), Some(last)) = (stops.first(), stops.last()) { - set(&mut v, "from", json!(hex(&first.1))); - set(&mut v, "to", json!(hex(&last.1))); - } + 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, @@ -463,7 +471,8 @@ fn next_id(f: &Map) -> String { fn add_instance(f: &mut Map, kind: &str) { let light = f.get("pendingGlobalLight").or_else(|| f.get("globalLight")).and_then(Value::as_f64).unwrap_or(120.0) as f32; let id = next_id(f); - let new = json!({"id": id, "kind": kind, "on": true, "params": fresh_params(kind, light)}); + let user = f.get(USER_DEFAULTS).and_then(|d| d.get(kind)); + let new = json!({"id": id, "kind": kind, "on": true, "params": fresh_params(kind, light, user)}); if let Some(a) = f.get_mut("effects").and_then(Value::as_array_mut) { let pos = a.iter().rposition(|e| e.get("kind").and_then(Value::as_str) == Some(kind)).map_or(a.len(), |i| i + 1); a.insert(pos, new); @@ -527,7 +536,13 @@ pub fn drag_shadow(f: &mut Map, start: bool, total: [f64; 2]) { } pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map { + initial_fields_with(layer, select, light, Map::new()) +} + +/// The dialog's fields, with the user defaults (`kind` → params) new instances start from. +pub fn initial_fields_with(layer: &Layer, select: Option<&str>, light: f32, user_defaults: Map) -> Map { let mut f = Map::new(); + f.insert(USER_DEFAULTS.into(), Value::Object(user_defaults)); f.insert("layer".into(), json!(layer.id.0)); f.insert("globalLight".into(), json!(light)); f.insert("preview".into(), json!(true)); @@ -583,7 +598,8 @@ pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option { let layer = st.doc.layer(st.active_layer?)?.clone(); let light = st.doc.global_light.angle; let mode = st.doc.mode; - let mut f = initial_fields(&layer, select, light); + let user = app.session.presets.layer_defaults.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); + let mut f = initial_fields_with(&layer, select, light, user); // Channels and Blend If list the document's own colour channels. set_blending_fields(&mut f, &layer, mode); f.insert("__document".into(), json!(st.doc.id)); @@ -811,7 +827,6 @@ fn fx_label_color(enabled: bool, t: &Tokens) -> Color32 { if enabled { t.text } else { t.text_dim } } -/// Dialog body (left list, right parameters). /// The enable checkbox of an effect row. fn fx_checkbox_rect(row: egui::Rect) -> egui::Rect { egui::Rect::from_min_size(row.min + vec2(6.0, 6.0), vec2(14.0, 14.0)) @@ -829,347 +844,37 @@ fn fx_checkbox(p: &egui::Painter, cb: egui::Rect, on: bool, t: &Tokens) { } pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { - let t = Tokens::get(ui.ctx()); + let _ = body_with_response(app, ui, f, true); +} + +/// Layer Style's body, laid out like Photoshop's: the effect list over its fx / move / delete +/// bar, the selected page, and a column with OK, Cancel, New Style…, Preview and the preview +/// swatch. Returns OK (true) or Cancel (false) once chosen; Enter is OK. +pub fn body_with_response(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { let selected = f.get("selected").and_then(Value::as_str).unwrap_or("dropShadow").to_string(); let mut style_click: Option = None; let mut new_style = false; + let mut outcome = None; let invalid = validate_params(f).err(); + // One size on every page (`dialogs::sizing_of`): the list and the page fill its height and + // scroll when they are taller. + let height = ui.available_height().max(160.0); ui.horizontal_top(|ui| { - // Left: effect list. - ui.vertical(|ui| { - ui.set_width(190.0); - // Styles & Blending Options rows (matching the effect row layout & padding). - for (id, label) in [(STYLES_PAGE, "Styles"), (BLENDING, "Blending Options")] { - let is_sel = selected == id; - let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click()); - if is_sel { - ui.painter().rect_filled(rect, t.radius_sm, t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }).max_alpha(t.hover)); - } else if resp.hovered() { - ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5)); - } - ui.painter().text( - rect.left_center() + vec2(28.0, 0.0), - egui::Align2::LEFT_CENTER, - tl!(label), - egui::FontId::proportional(12.5), - if is_sel { t.text } else { t.text_dim }, - ); - if resp.clicked() { - f.insert("selected".into(), json!(id)); - } - } - ui.add_space(4.0); - for &(kind, label) in KINDS { - let ids: Vec = effects_of(f) - .iter() - .filter(|e| e.get("kind").and_then(Value::as_str) == Some(kind)) - .filter_map(|e| e.get("id").and_then(Value::as_str).map(str::to_string)) - .collect(); - if ids.is_empty() { - // The effect isn't on the layer: a greyed row with an empty checkbox, as in - // Photoshop (#1357); a click on either adds it, turned on. - let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5)); - } - fx_checkbox(ui.painter(), fx_checkbox_rect(rect), false, &t); - ui.painter().text( - rect.left_center() + vec2(28.0, 0.0), - egui::Align2::LEFT_CENTER, - tl!(label), - egui::FontId::proportional(12.5), - t.text_faint, - ); - if resp.clicked() { - add_instance(f, kind); - } - continue; - } - let count = ids.len(); - for id in &ids { - let Some(e) = entry(f, id) else { continue }; - let kind_label = KINDS.iter().find(|k| k.0 == kind).map(|k| k.1).unwrap_or(label); - let mut on = e.get("on").and_then(Value::as_bool).unwrap_or(false); - let is_sel = id == &selected; - let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 26.0), Sense::click()); - if is_sel { - ui.painter().rect_filled(rect, t.radius_sm, t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }).max_alpha(t.hover)); - } else if resp.hovered() { - ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5)); - } - let cb = fx_checkbox_rect(rect); - let cresp = ui.interact(cb, ui.scope_id().with(("fxcb", kind, id)), Sense::click()); - fx_checkbox(ui.painter(), cb, on, &t); - ui.painter().text( - rect.left_center() + vec2(28.0, 0.0), - egui::Align2::LEFT_CENTER, - tl!(kind_label), - egui::FontId::proportional(12.5), - fx_label_color(on, &t), - ); - // + adds another instance; − removes one once there are several. - if multi(kind) { - let btn = |ui: &egui::Ui, at: egui::Pos2, glyph: &str, tag: &str| { - let r = egui::Rect::from_center_size(at, vec2(18.0, 18.0)); - let hresp = ui.interact(r, ui.scope_id().with(("fxbtn", tag, id)), Sense::click()); - let col = if hresp.hovered() { t.accent } else { t.text_faint }; - ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(13.0), col); - hresp.clicked() - }; - if count > 1 && btn(ui, rect.right_center() - vec2(22.0, 0.0), "\u{2212}", "minus") { - remove_instance(f, id); - continue; - } - if btn(ui, rect.right_center() - vec2(8.0, 0.0), "+", "plus") { - add_instance(f, kind); - } - } - if cresp.clicked() { - on = !on; - if let Some(e) = entry_mut(f, id) { - e["on"] = json!(on); - } - f.insert("selected".into(), json!(id)); - } else if resp.clicked() { - f.insert("selected".into(), json!(id)); - } - } - } + boxed(ui, LIST_W, height, |ui, h| { + egui::ScrollArea::vertical().id_salt("layer-style-effects").max_height(h - BAR_H).auto_shrink(false).show(ui, |ui| effect_list(ui, f, &selected)); + list_bar(ui, f, &selected); + }); + let page_w = ui.available_width() - SIDE_W - ui.spacing().item_spacing.x; + boxed(ui, page_w, height, |ui, h| { + egui::ScrollArea::vertical() + .id_salt("layer-style-page") + .max_height(h) + .auto_shrink(false) + .show(ui, |ui| page(app, ui, f, &selected, invalid.as_deref(), &mut style_click)); }); - widgets::vline(ui, 330.0); - // Right: parameters of the selected page. ui.vertical(|ui| { - ui.set_width(330.0); - if selected == STYLES_PAGE { - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Styles")).font(crate::theme::semibold(14.0)).color(t.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::secondary_button(ui, tl!("New Style…"), 100.0).clicked() { - new_style = true; - } - }); - }); - ui.add_space(8.0); - let ctx = ui.ctx().clone(); - egui::ScrollArea::vertical().max_height(340.0).id_salt("layer-style-presets-main").show(ui, |ui| { - for group in &app.session.presets.styles { - ui.label(RichText::new(&group.name).size(12.0).color(t.text_dim)); - ui.add_space(3.0); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(4.0, 4.0); - for st in &group.items { - let tex = crate::preset_panels::style_texture(app, &ctx, st); - let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); - ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); - let (stroke, kind) = if resp.hovered() { - (Stroke::new(1.5, t.accent), egui::StrokeKind::Outside) - } else { - (Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside) - }; - ui.painter().rect_stroke(rect, 2.0, stroke, kind); - if resp.on_hover_text(&st.name).clicked() { - style_click = Some(st.name.clone()); - } - } - }); - ui.add_space(10.0); - } - }); - return; - } - let sel_kind: String = if selected == BLENDING { - BLENDING.to_string() - } else { - entry(f, &selected).and_then(|e| e.get("kind").and_then(Value::as_str)).unwrap_or("").to_string() - }; - let label = KINDS.iter().find(|k| k.0 == sel_kind).map(|k| k.1).unwrap_or(if selected == BLENDING { "Blending Options" } else { "" }); - ui.horizontal(|ui| { - ui.label(RichText::new(tl!(&label)).font(crate::theme::semibold(14.0)).color(t.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut preview = f.get("preview").and_then(Value::as_bool).unwrap_or(true); - if widgets::checkbox(ui, &mut preview, tl!("Preview")).changed() { - f.insert("preview".into(), json!(preview)); - } - }); - }); - ui.add_space(6.0); - // Only reachable through `ui.dialog.set`: say what is wrong once, keep the bad value. - if let Some(error) = &invalid { - ui.colored_label(t.danger, error); - return; - } - if selected == BLENDING { - // General Blending, Advanced Blending and Blend If, laid out like Photoshop's page. - let names = channel_names_of(f); - let key = format!("p:{BLENDING}"); - let Some(mut p) = f.get(&key).filter(|v| v.is_object()).cloned() else { return }; - blending_page(ui, &mut p, &names); - f.insert(key, p); - return; - } - // The page shows the factory defaults under the instance's values, - // but only real edits reach the stored params. - let disp = if selected == BLENDING { - f.get("p:blendingOptions").cloned().unwrap_or_else(|| json!({})) - } else { - entry(f, &selected).and_then(|e| e.get("params").cloned()).unwrap_or_else(|| json!({})) - }; - let Some(mut disp) = disp.as_object().map(|o| Value::Object(o.clone())) else { return }; - if selected != BLENDING { - let base = defaults(&sel_kind); - if let (Some(o), Some(b)) = (disp.as_object_mut(), base.as_object()) { - for (k, v) in b { - o.entry(k.clone()).or_insert_with(|| v.clone()); - } - } - } - for &(key, label, kind_p) in spec(&sel_kind) { - match kind_p { - P::Angle => { - let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; - if widgets::angle_dial_row(ui, label, &mut v, -180.0..=180.0).changed() { - let value = json!(v); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - } - P::Slider(min, max, unit) => { - let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(min as f64) as f32; - if widgets::slider_row(ui, label, &mut v, min..=max, unit, None).changed() { - let value = json!(v.round()); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - } - P::Color => { - ui.horizontal(|ui| { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let color = disp.get(key).and_then(Value::as_str).unwrap_or("#000000"); - let response = widgets::color_swatch(ui, parse_hex(color)).on_hover_text(tl!("Color Picker (Layer Style Color)")); - if response.clicked() { - f.insert(color_picker::REQUEST.into(), json!({"effect": selected, "field": key})); - } - }); - } - P::Blend => { - ui.horizontal(|ui| { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or("Normal").to_string(); - let opts: Vec<(String, &str)> = - photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect(); - // One id per mode: Bevel & Emboss has two (Highlight, Shadow), which must not share a list (#9368). - if widgets::dropdown(ui, &format!("fx-blend-{sel_kind}-{key}"), tl!(&label), &mut cur, &opts, 150.0) { - let value = json!(cur); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - }); - } - P::Choice(options) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or(options[0].0).to_string(); - let opts: Vec<(String, &str)> = options.iter().map(|(v, l)| (v.to_string(), *l)).collect(); - if widgets::dropdown(ui, &format!("fx-{sel_kind}-{key}"), tl!(&label), &mut cur, &opts, 150.0) { - let value = json!(cur); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - }); - } - P::GradientMethod => { - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Method")).color(t.text_dim)); - let mut current = disp.get(key).and_then(Value::as_str).unwrap_or("custom").to_string(); - let mut options = vec![ - ("smooth".to_string(), "Smooth"), - ("perceptual".to_string(), "Perceptual"), - ("linear".to_string(), "Linear"), - ("classic".to_string(), "Classic"), - ]; - // Old/imported curves have no method record. Preserve them until - // the user explicitly chooses an interpolation method. - if photocraft_io::GradientMethod::from_name(¤t).is_none() { - current = "custom".into(); - options.insert(0, ("custom".into(), "Custom")); - } - if widgets::dropdown(ui, "fx-gradientOverlay-method", tl!("Method"), &mut current, &options, 150.0) { - // The older dialog deliberately omits From/To for rich imported - // curves. Once a method is chosen, show the real source ends. - let snapshot = entry(f, &selected).and_then(|e| e.get("fx")).cloned(); - if let Some(Effect::GradientOverlay { gradient, interpolation, .. }) = - snapshot.and_then(|v| serde_json::from_value::(v).ok()) - { - let stops = interpolation.as_ref().map_or(&gradient.stops, |source| &source.stops); - for (key, stop) in [("from", stops.first()), ("to", stops.last())] { - if entry(f, &selected).and_then(|e| e.get("params")).and_then(|p| p.get(key)).is_none() - && let Some(stop) = stop - { - set_param(f, &selected, key, json!(hex(&stop.1))); - } - } - } - let value = json!(current); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - }); - } - P::Pattern => { - let list: Vec<(String, String)> = f - .get("patternList") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))).collect()) - .unwrap_or_default(); - ui.horizontal(|ui| { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let mut cur = disp - .get(key) - .and_then(Value::as_str) - .filter(|c| !c.is_empty()) - .map(str::to_string) - .or_else(|| list.first().map(|l| l.0.clone())) - .unwrap_or_default(); - let opts: Vec<(String, &str)> = list.iter().map(|(id, n)| (id.clone(), n.as_str())).collect(); - if widgets::dropdown(ui, &format!("fx-{sel_kind}-{key}"), tl!(&label), &mut cur, &opts, 180.0) - || disp.get(key).and_then(Value::as_str).is_none_or(str::is_empty) - { - let value = json!(cur); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - }); - } - P::Contour(aa) => contour::row(app, ui, f, &selected, key, label, aa, &mut disp), - P::Check => { - let mut b = disp.get(key).and_then(Value::as_bool).unwrap_or(false); - if widgets::checkbox(ui, &mut b, label).changed() { - let value = json!(b); - disp[key] = value.clone(); - set_param(f, &selected, key, value); - } - } - } - ui.add_space(2.0); - } - // Make Default stores this page as the user default; Reset to Default - // restores it (or the factory defaults before the first Make). - let page_kind = sel_kind != BLENDING && entry(f, &selected).is_some(); - ui.add_space(4.0); - // Wrap: translated labels (ru, de) can be wider than the page column. - ui.with_layout(egui::Layout::right_to_left(egui::Align::Min).with_main_wrap(true), |ui| { - ui.add_enabled_ui(page_kind, |ui| { - if crate::widgets::secondary_button(ui, tl!("Reset to Default"), 130.0).clicked() - && let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": sel_kind})) - && let Some(e) = entry_mut(f, &selected) - { - e["params"] = v["params"].clone(); - } - if crate::widgets::secondary_button(ui, tl!("Make Default"), 110.0).clicked() { - let _ = app.run("layer.layerStyle.makeDefault", json!({"kind": sel_kind, "params": disp})); - } - }); - }); + ui.set_width(SIDE_W); + outcome = side_column(app, ui, f, &mut new_style); }); }); // Style swatch clicks apply to the layer (Photoshop does this immediately); @@ -1181,6 +886,10 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map = p.get("channels").and_then(Value::as_array).map(|a| a.iter().map(|v| v.as_bool().unwrap_or(true)).collect()).unwrap_or_default(); ch.resize(names.len(), true); @@ -1290,7 +999,7 @@ fn blending_page(ui: &mut egui::Ui, p: &mut Value, names: &[String]) { } }); ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Knockout")).color(t.text_dim)); + widgets::row_label(ui, "Knockout", LABEL_W); let mut cur = p.get("knockout").and_then(Value::as_str).unwrap_or("none").to_string(); let opts: Vec<(String, &str)> = KNOCKOUT.iter().map(|(v, l)| (v.to_string(), *l)).collect(); if widgets::dropdown(ui, "fx-blendingOptions-knockout", tl!("Knockout"), &mut cur, &opts, 150.0) { @@ -1300,19 +1009,19 @@ fn blending_page(ui: &mut egui::Ui, p: &mut Value, names: &[String]) { for &(key, label) in ADVANCED_CHECKS { let default = matches!(key, "blendClippedLayersAsGroup" | "transparencyShapesLayer"); let mut b = p.get(key).and_then(Value::as_bool).unwrap_or(default); - if widgets::checkbox(ui, &mut b, label).changed() { + if checkbox_line(ui, &mut b, label) { p[key] = json!(b); } } widgets::hairline(ui); - // Blend If: the channel, then This Layer / Underlying Layer split sliders (Alt-drag splits). + // Blend If: the channel, then Current Layer / Underlying Layer split sliders (Alt-drag splits). let entries = p.get("blendIf").and_then(Value::as_array).map_or(0, Vec::len); if entries == 0 { return; } let sel = p.get("blendIfChannel").and_then(Value::as_u64).map_or(0, |v| v as usize).min(entries - 1); ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Blend If:")).color(t.text_dim)); + widgets::row_label(ui, "Blend If:", LABEL_W); // A colour document lists Gray first; a one-channel document only its channel (Gray). let label = |i: usize| -> String { if entries == names.len() { @@ -1330,7 +1039,8 @@ fn blending_page(ui: &mut egui::Ui, p: &mut Value, names: &[String]) { p["blendIfChannel"] = json!(cur); } }); - for (key, label) in [("thisLayer", "This Layer:"), ("underlying", "Underlying Layer:")] { + // Photoshop 2026 calls the first bar Current Layer (it was This Layer). + for (key, label) in [("thisLayer", "Current Layer:"), ("underlying", "Underlying Layer:")] { let mut q = blend_quad(p.get("blendIf").and_then(|a| a.get(sel)).and_then(|e| e.get(key))); ui.horizontal(|ui| { ui.label(RichText::new(tl!(label)).color(t.text_dim)); @@ -1363,6 +1073,107 @@ fn blend_quad(v: Option<&Value>) -> [u8; 4] { q } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BlendDrag { + Pair { pair: usize, origin_v: u8 }, + Split { handle: usize, origin: u8 }, + Single(usize), +} + +pub(crate) fn step_blend_drag(mode: &mut BlendDrag, q: &[u8; 4], target: u8, alt: bool) -> [u8; 4] { + let mut n = *q; + match *mode { + BlendDrag::Pair { pair, origin_v } => { + if alt { + if pair == 0 { + if target >= origin_v { + *mode = BlendDrag::Split { handle: 1, origin: origin_v }; + n[0] = origin_v; + n[1] = target.clamp(origin_v, q[2]); + } else { + *mode = BlendDrag::Split { handle: 0, origin: origin_v }; + n[1] = origin_v; + n[0] = target.clamp(0, origin_v); + } + } else if target <= origin_v { + *mode = BlendDrag::Split { handle: 2, origin: origin_v }; + n[3] = origin_v; + n[2] = target.clamp(q[1], origin_v); + } else { + *mode = BlendDrag::Split { handle: 3, origin: origin_v }; + n[2] = origin_v; + n[3] = target.clamp(origin_v, 255); + } + } else { + let delta = i16::from(target) - i16::from(origin_v); + if pair == 0 { + let v = (i16::from(origin_v) + delta).clamp(0, q[2] as i16) as u8; + n[0] = v; + n[1] = v; + } else { + let v = (i16::from(origin_v) + delta).clamp(q[1] as i16, 255) as u8; + n[2] = v; + n[3] = v; + } + } + } + BlendDrag::Split { handle, origin } => match handle { + 1 => { + if target >= origin { + n[0] = origin; + n[1] = target.clamp(origin, q[2]); + } else { + *mode = BlendDrag::Split { handle: 0, origin }; + n[1] = origin; + n[0] = target.clamp(0, origin); + } + } + 0 => { + if target <= origin { + n[1] = origin; + n[0] = target.clamp(0, origin); + } else { + *mode = BlendDrag::Split { handle: 1, origin }; + n[0] = origin; + n[1] = target.clamp(origin, q[2]); + } + } + 2 => { + if target <= origin { + n[3] = origin; + n[2] = target.clamp(q[1], origin); + } else { + *mode = BlendDrag::Split { handle: 3, origin }; + n[2] = origin; + n[3] = target.clamp(origin, 255); + } + } + 3 => { + if target >= origin { + n[2] = origin; + n[3] = target.clamp(origin, 255); + } else { + *mode = BlendDrag::Split { handle: 2, origin }; + n[3] = origin; + n[2] = target.clamp(q[1], origin); + } + } + _ => {} + }, + BlendDrag::Single(h) => match h { + 0 => n[0] = target.clamp(0, n[1]), + 1 => n[1] = target.clamp(n[0], n[2]), + 2 => n[2] = target.clamp(n[1], n[3]), + 3 => n[3] = target.clamp(n[2], 255), + _ => {} + }, + } + for i in 1..4 { + n[i] = n[i].max(n[i - 1]); + } + n +} + /// A Blend If slider: a black-to-white ramp with a black and a white handle, each split in two /// halves by Alt-dragging (the layer fades between them). Returns whether `q` changed. fn blend_if_bar(ui: &mut egui::Ui, id: egui::Id, q: &mut [u8; 4]) -> bool { @@ -1383,47 +1194,44 @@ fn blend_if_bar(ui: &mut egui::Ui, id: egui::Id, q: &mut [u8; 4]) -> bool { ui.painter().rect_stroke(ramp, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); // Handles: triangles under the ramp; a split handle shows two half triangles. let mut changed = false; - let drag_key = id.with("handle"); + let drag_key = id.with("blend_drag"); + let alt = ui.input(|i| i.modifiers.alt); if resp.drag_started() && let Some(pos) = resp.interact_pointer_pos() { - let near = (0..4).min_by(|a, b| (x_of(q[*a]) - pos.x).abs().total_cmp(&(x_of(q[*b]) - pos.x).abs())).unwrap_or(0); - // Between two coinciding halves, pick by the side of the pointer. - let near = match near { - 0 | 1 if q[0] == q[1] => usize::from(pos.x > x_of(q[0])), - 2 | 3 if q[2] == q[3] => 2 + usize::from(pos.x > x_of(q[2])), - n => n, + let d_black = if q[0] == q[1] { (pos.x - x_of(q[0])).abs() } else { (pos.x - (x_of(q[0]) - 2.5)).abs().min((pos.x - (x_of(q[1]) + 2.5)).abs()) }; + let d_white = if q[2] == q[3] { (pos.x - x_of(q[2])).abs() } else { (pos.x - (x_of(q[2]) - 2.5)).abs().min((pos.x - (x_of(q[3]) + 2.5)).abs()) }; + let mode = if d_black <= d_white { + if q[0] == q[1] { + if alt { + let h = if pos.x >= x_of(q[0]) { 1 } else { 0 }; + BlendDrag::Split { handle: h, origin: q[0] } + } else { + BlendDrag::Pair { pair: 0, origin_v: q[0] } + } + } else { + let h = if (pos.x - x_of(q[0])).abs() <= (pos.x - x_of(q[1])).abs() { 0 } else { 1 }; + BlendDrag::Single(h) + } + } else if q[2] == q[3] { + if alt { + let h = if pos.x <= x_of(q[2]) { 2 } else { 3 }; + BlendDrag::Split { handle: h, origin: q[2] } + } else { + BlendDrag::Pair { pair: 2, origin_v: q[2] } + } + } else { + let h = if (pos.x - x_of(q[2])).abs() <= (pos.x - x_of(q[3])).abs() { 2 } else { 3 }; + BlendDrag::Single(h) }; - ui.data_mut(|d| d.insert_temp(drag_key, near)); + ui.data_mut(|d| d.insert_temp(drag_key, mode)); } if resp.dragged() - && let (Some(h), Some(pos)) = (ui.data(|d| d.get_temp::(drag_key)), resp.interact_pointer_pos()) - && let Some(cur) = q.get(h).copied() + && let (Some(mut mode), Some(pos)) = (ui.data(|d| d.get_temp::(drag_key)), resp.interact_pointer_pos()) { let target = v_of(pos.x); - let split = ui.input(|i| i.modifiers.alt); - let mut n = *q; - let pair = if h < 2 { 0 } else { 2 }; - if split { - n[h] = target; - } else { - // Unsplit: the pair moves together, keeping its spread. - let delta = i16::from(target) - i16::from(cur); - for v in &mut n[pair..pair + 2] { - *v = (i16::from(*v) + delta).clamp(0, 255) as u8; - } - } - // Keep the order black low <= black high <= white low <= white high, pushing the others. - for i in 0..4 { - if i < h { - n[i] = n[i].min(n[h]); - } else if i > h { - n[i] = n[i].max(n[h]); - } - } - for i in 1..4 { - n[i] = n[i].max(n[i - 1]); - } + let n = step_blend_drag(&mut mode, q, target, alt); + ui.data_mut(|d| d.insert_temp(drag_key, mode)); if n != *q { *q = n; changed = true; @@ -1472,3 +1280,508 @@ impl MaxAlpha for Color32 { #[cfg(test)] mod tests; + +/// Photoshop's column widths: the effect list, the right-hand column (OK, Cancel, New Style…, +/// Preview, the preview swatch) and a page row's label column. +const LIST_W: f32 = 200.0; + +const SIDE_W: f32 = 112.0; + +const LABEL_W: f32 = 104.0; + +/// The bar under the effect list (fx, move up, move down, delete). +const BAR_H: f32 = 30.0; + +/// A bordered column `w` × `h`, as Photoshop frames the effect list and the page; `add` gets the +/// height inside the border. +fn boxed(ui: &mut egui::Ui, w: f32, h: f32, add: impl FnOnce(&mut egui::Ui, f32)) { + const PAD: f32 = 4.0; + let t = Tokens::get(ui.ctx()); + egui::Frame::new().stroke(Stroke::new(1.0, t.separator)).corner_radius(t.radius_sm).inner_margin(PAD).show(ui, |ui| { + let inner = (vec2(w, h) - egui::Vec2::splat(2.0 * PAD + 2.0)).max(egui::Vec2::splat(40.0)); + // Top-down inside, whatever the row it sits in lays out. + ui.vertical(|ui| { + ui.set_width(inner.x); + ui.set_height(inner.y); + add(ui, inner.y); + }); + }); +} + +/// The effect list: Styles, Blending Options, then a row per effect instance (a greyed row for a +/// kind the layer doesn't have), each as wide as the list. +fn effect_list(ui: &mut egui::Ui, f: &mut Map, selected: &str) { + let t = Tokens::get(ui.ctx()); + let w = ui.available_width(); + // Styles & Blending Options rows (matching the effect row layout & padding). + for (id, label) in [(STYLES_PAGE, "Styles"), (BLENDING, "Blending Options")] { + let is_sel = selected == id; + let (rect, resp) = ui.allocate_exact_size(vec2(w, 26.0), Sense::click()); + if is_sel { + ui.painter().rect_filled(rect, t.radius_sm, t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }).max_alpha(t.hover)); + } else if resp.hovered() { + ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + ui.painter().text( + rect.left_center() + vec2(28.0, 0.0), + egui::Align2::LEFT_CENTER, + tl!(label), + egui::FontId::proportional(12.5), + if is_sel { t.text } else { t.text_dim }, + ); + if resp.clicked() { + f.insert("selected".into(), json!(id)); + } + } + ui.add_space(4.0); + for &(kind, label) in KINDS { + let ids: Vec = effects_of(f) + .iter() + .filter(|e| e.get("kind").and_then(Value::as_str) == Some(kind)) + .filter_map(|e| e.get("id").and_then(Value::as_str).map(str::to_string)) + .collect(); + if ids.is_empty() { + // The effect isn't on the layer: a greyed row with an empty checkbox, as in + // Photoshop (#1357); a click on either adds it, turned on. + let (rect, resp) = ui.allocate_exact_size(vec2(w, 26.0), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + fx_checkbox(ui.painter(), fx_checkbox_rect(rect), false, &t); + ui.painter().text(rect.left_center() + vec2(28.0, 0.0), egui::Align2::LEFT_CENTER, tl!(label), egui::FontId::proportional(12.5), t.text_faint); + // Photoshop shows + on every kind that takes several instances. + if multi(kind) { + let col = if resp.hovered() { t.accent } else { t.text_faint }; + ui.painter().text(rect.right_center() - vec2(8.0, 0.0), egui::Align2::CENTER_CENTER, "+", egui::FontId::proportional(13.0), col); + } + if resp.clicked() { + add_instance(f, kind); + } + continue; + } + let count = ids.len(); + for id in &ids { + let Some(e) = entry(f, id) else { continue }; + let kind_label = KINDS.iter().find(|k| k.0 == kind).map(|k| k.1).unwrap_or(label); + let mut on = e.get("on").and_then(Value::as_bool).unwrap_or(false); + let is_sel = id.as_str() == selected; + let (rect, resp) = ui.allocate_exact_size(vec2(w, 26.0), Sense::click()); + if is_sel { + ui.painter().rect_filled(rect, t.radius_sm, t.row_selected.gamma_multiply(if t.pro { 1.0 } else { 0.0 }).max_alpha(t.hover)); + } else if resp.hovered() { + ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + let cb = fx_checkbox_rect(rect); + let cresp = ui.interact(cb, ui.scope_id().with(("fxcb", kind, id)), Sense::click()); + fx_checkbox(ui.painter(), cb, on, &t); + ui.painter().text( + rect.left_center() + vec2(28.0, 0.0), + egui::Align2::LEFT_CENTER, + tl!(kind_label), + egui::FontId::proportional(12.5), + fx_label_color(on, &t), + ); + // + adds another instance; − removes one once there are several. + if multi(kind) { + let btn = |ui: &egui::Ui, at: egui::Pos2, glyph: &str, tag: &str| { + let r = egui::Rect::from_center_size(at, vec2(18.0, 18.0)); + let hresp = ui.interact(r, ui.scope_id().with(("fxbtn", tag, id)), Sense::click()); + let col = if hresp.hovered() { t.accent } else { t.text_faint }; + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(13.0), col); + hresp.clicked() + }; + if count > 1 && btn(ui, rect.right_center() - vec2(22.0, 0.0), "\u{2212}", "minus") { + remove_instance(f, id); + continue; + } + if btn(ui, rect.right_center() - vec2(8.0, 0.0), "+", "plus") { + add_instance(f, kind); + } + } + if cresp.clicked() { + on = !on; + if let Some(e) = entry_mut(f, id) { + e["on"] = json!(on); + } + f.insert("selected".into(), json!(id)); + } else if resp.clicked() { + f.insert("selected".into(), json!(id)); + } + } + } +} + +/// The ids of the instances of `kind`, in list order. +fn ids_of(f: &Map, kind: &str) -> Vec { + effects_of(f) + .iter() + .filter(|e| e.get("kind").and_then(Value::as_str) == Some(kind)) + .filter_map(|e| e.get("id").and_then(Value::as_str).map(str::to_string)) + .collect() +} + +/// Moves instance `id` `by` places among the instances of its kind (negative: up the list). +fn move_instance(f: &mut Map, id: &str, by: isize) { + let Some(a) = f.get_mut("effects").and_then(Value::as_array_mut) else { return }; + let kind_of = |e: &Value| e.get("kind").and_then(Value::as_str).map(str::to_string); + let Some(kind) = a.iter().find(|e| e.get("id").and_then(Value::as_str) == Some(id)).and_then(kind_of) else { return }; + let slots: Vec = a.iter().enumerate().filter(|(_, e)| kind_of(e).as_deref() == Some(kind.as_str())).map(|(i, _)| i).collect(); + let Some(at) = slots.iter().position(|&i| a.get(i).and_then(|e| e.get("id")).and_then(Value::as_str) == Some(id)) else { return }; + let Some(&other) = at.checked_add_signed(by).and_then(|j| slots.get(j)) else { return }; + if let Some(&here) = slots.get(at) + && here < a.len() + && other < a.len() + { + a.swap(here, other); + } +} + +/// Photoshop's bar under the effect list: fx adds an effect (or turns on and shows the one the +/// layer has, for a kind that takes one), the arrows move the selected instance up or down among +/// those of its kind, the bin deletes it. +fn list_bar(ui: &mut egui::Ui, f: &mut Map, selected: &str) { + let kind = entry(f, selected).and_then(|e| e.get("kind").and_then(Value::as_str)).map(str::to_string); + let siblings = kind.as_deref().map(|k| ids_of(f, k)).unwrap_or_default(); + let at = siblings.iter().position(|id| id == selected); + ui.horizontal(|ui| { + let fx = crate::panels::fx_button(ui, 24.0, tl!("Add a layer style")); + crate::press_menu::show(&fx, |ui, menu| { + ui.set_min_width(160.0); + for &(kind, label) in KINDS { + if menu.item(ui, tl!(label)) { + pick_from_fx_menu(f, kind); + } + } + }); + let up = at.is_some_and(|i| i > 0); + if ui.add_enabled_ui(up, |ui| crate::icons::button(ui, "chevron-up", 24.0, false, tl!("Move effect up"))).inner.clicked() { + move_instance(f, selected, -1); + } + let down = at.is_some_and(|i| i + 1 < siblings.len()); + if ui.add_enabled_ui(down, |ui| crate::icons::button(ui, "chevron-down", 24.0, false, tl!("Move effect down"))).inner.clicked() { + move_instance(f, selected, 1); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add_enabled_ui(at.is_some(), |ui| crate::icons::button(ui, "trash", 24.0, false, tl!("Delete effect"))).inner.clicked() { + remove_instance(f, selected); + } + }); + }); +} + +/// The fx menu's `kind`: another instance of a kind that takes several (or the first), else the +/// layer's one, turned on and shown. +fn pick_from_fx_menu(f: &mut Map, kind: &str) { + match ids_of(f, kind).first() { + Some(id) if !multi(kind) => { + if let Some(e) = entry_mut(f, id) { + e["on"] = json!(true); + } + f.insert("selected".into(), json!(id)); + } + _ => add_instance(f, kind), + } +} + +/// A check box in a page's control column, under the controls rather than the labels. +fn checkbox_line(ui: &mut egui::Ui, on: &mut bool, label: &str) -> bool { + ui.horizontal(|ui| { + ui.add_space(LABEL_W + ui.spacing().item_spacing.x); + widgets::checkbox(ui, on, label).changed() + }) + .inner +} + +/// The selected page: the Styles gallery, Blending Options, or an effect's parameters. +fn page(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, selected: &str, invalid: Option<&str>, style_click: &mut Option) { + let t = Tokens::get(ui.ctx()); + // Photoshop's rows sit close together: every page fits the dialog without scrolling. + ui.spacing_mut().item_spacing.y = 3.0; + if selected == STYLES_PAGE { + ui.label(RichText::new(tl!("Styles")).font(crate::theme::semibold(14.0)).color(t.text)); + ui.add_space(8.0); + let ctx = ui.ctx().clone(); + // The page scrolls, so the gallery takes the room the dialog has. + ui.vertical(|ui| { + for group in &app.session.presets.styles { + ui.label(RichText::new(&group.name).size(12.0).color(t.text_dim)); + ui.add_space(3.0); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + for st in &group.items { + let tex = crate::preset_panels::style_texture(app, &ctx, st); + let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); + ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + let (stroke, kind) = if resp.hovered() { + (Stroke::new(1.5, t.accent), egui::StrokeKind::Outside) + } else { + (Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside) + }; + ui.painter().rect_stroke(rect, 2.0, stroke, kind); + if resp.on_hover_text(&st.name).clicked() { + *style_click = Some(st.name.clone()); + } + } + }); + ui.add_space(10.0); + } + }); + return; + } + let sel_kind: String = if selected == BLENDING { + BLENDING.to_string() + } else { + entry(f, selected).and_then(|e| e.get("kind").and_then(Value::as_str)).unwrap_or("").to_string() + }; + let label = KINDS.iter().find(|k| k.0 == sel_kind).map(|k| k.1).unwrap_or(if selected == BLENDING { "Blending Options" } else { "" }); + ui.label(RichText::new(tl!(&label)).font(crate::theme::semibold(14.0)).color(t.text)); + ui.add_space(6.0); + // Only reachable through `ui.dialog.set`: say what is wrong once, keep the bad value. + if let Some(error) = invalid { + ui.colored_label(t.danger, error); + return; + } + if selected == BLENDING { + // General Blending, Advanced Blending and Blend If, laid out like Photoshop's page. + let names = channel_names_of(f); + let key = format!("p:{BLENDING}"); + let Some(mut p) = f.get(&key).filter(|v| v.is_object()).cloned() else { return }; + blending_page(ui, &mut p, &names); + f.insert(key, p); + return; + } + // The page shows the factory defaults under the instance's values, + // but only real edits reach the stored params. + let disp = if selected == BLENDING { + f.get("p:blendingOptions").cloned().unwrap_or_else(|| json!({})) + } else { + entry(f, selected).and_then(|e| e.get("params").cloned()).unwrap_or_else(|| json!({})) + }; + let Some(mut disp) = disp.as_object().map(|o| Value::Object(o.clone())) else { return }; + if selected != BLENDING { + let base = defaults(&sel_kind); + if let (Some(o), Some(b)) = (disp.as_object_mut(), base.as_object()) { + for (k, v) in b { + o.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + } + for &(key, label, kind_p) in spec(&sel_kind) { + match kind_p { + P::Angle => { + let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; + if widgets::angle_dial_line(ui, label, Some(LABEL_W), &mut v, -180.0..=180.0).changed() { + let value = json!(v); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + } + P::Slider(min, max, unit) => { + let mut v = disp.get(key).and_then(Value::as_f64).unwrap_or(min as f64) as f32; + if widgets::slider_line(ui, label, LABEL_W, &mut v, min..=max, unit).changed() { + let value = json!(v.round()); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + } + P::Color => { + ui.horizontal(|ui| { + widgets::row_label(ui, label, LABEL_W); + let color = disp.get(key).and_then(Value::as_str).unwrap_or("#000000"); + let response = widgets::color_swatch(ui, parse_hex(color)).on_hover_text(tl!("Color Picker (Layer Style Color)")); + if response.clicked() { + f.insert(color_picker::REQUEST.into(), json!({"effect": selected, "field": key})); + } + }); + } + P::Blend => { + ui.horizontal(|ui| { + widgets::row_label(ui, label, LABEL_W); + let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or("Normal").to_string(); + let opts: Vec<(String, &str)> = photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect(); + if widgets::dropdown(ui, &format!("fx-blend-{selected}-{key}"), tl!(&label), &mut cur, &opts, 150.0) { + let value = json!(cur); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + }); + } + P::GradientMethod => { + ui.horizontal(|ui| { + widgets::row_label(ui, label, LABEL_W); + let mut current = disp.get(key).and_then(Value::as_str).unwrap_or("custom").to_string(); + let mut options = vec![ + ("smooth".to_string(), "Smooth"), + ("perceptual".to_string(), "Perceptual"), + ("linear".to_string(), "Linear"), + ("classic".to_string(), "Classic"), + ]; + // Old/imported curves have no method record. Preserve them until + // the user explicitly chooses an interpolation method. + if photocraft_io::GradientMethod::from_name(¤t).is_none() { + current = "custom".into(); + options.insert(0, ("custom".into(), "Custom")); + } + if widgets::dropdown(ui, "fx-gradientOverlay-method", tl!("Method"), &mut current, &options, 150.0) { + // The older dialog deliberately omits From/To for rich imported + // curves. Once a method is chosen, show the real source ends. + let snapshot = entry(f, selected).and_then(|e| e.get("fx")).cloned(); + if let Some(Effect::GradientOverlay { gradient, interpolation, .. }) = snapshot.and_then(|v| serde_json::from_value::(v).ok()) { + let stops = interpolation.as_ref().map_or(&gradient.stops, |source| &source.stops); + for (key, stop) in [("from", stops.first()), ("to", stops.last())] { + if entry(f, selected).and_then(|e| e.get("params")).and_then(|p| p.get(key)).is_none() + && let Some(stop) = stop + { + set_param(f, selected, key, json!(hex(&stop.1))); + } + } + } + let value = json!(current); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + }); + } + P::Choice(options) => { + ui.horizontal(|ui| { + widgets::row_label(ui, label, LABEL_W); + let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or(options[0].0).to_string(); + let opts: Vec<(String, &str)> = options.iter().map(|(v, l)| (v.to_string(), *l)).collect(); + if widgets::dropdown(ui, &format!("fx-{sel_kind}-{key}"), tl!(&label), &mut cur, &opts, 150.0) { + let value = json!(cur); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + }); + } + P::Pattern => { + let list: Vec<(String, String)> = f + .get("patternList") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))).collect()) + .unwrap_or_default(); + ui.horizontal(|ui| { + widgets::row_label(ui, label, LABEL_W); + let mut cur = disp + .get(key) + .and_then(Value::as_str) + .filter(|c| !c.is_empty()) + .map(str::to_string) + .or_else(|| list.first().map(|l| l.0.clone())) + .unwrap_or_default(); + let opts: Vec<(String, &str)> = list.iter().map(|(id, n)| (id.clone(), n.as_str())).collect(); + if widgets::dropdown(ui, &format!("fx-{sel_kind}-{key}"), tl!(&label), &mut cur, &opts, 180.0) + || disp.get(key).and_then(Value::as_str).is_none_or(str::is_empty) + { + let value = json!(cur); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + }); + } + P::Gradient => gradient_field::row(app, ui, f, selected, label, &mut disp), + P::Contour(aa) => contour::row(app, ui, f, selected, key, label, aa, &mut disp), + P::Check => { + let mut b = disp.get(key).and_then(Value::as_bool).unwrap_or(false); + if checkbox_line(ui, &mut b, label) { + let value = json!(b); + disp[key] = value.clone(); + set_param(f, selected, key, value); + } + } + } + } + // Make Default stores this page as the user default; Reset to Default + // restores it (or the factory defaults before the first Make). + let page_kind = sel_kind != BLENDING && entry(f, selected).is_some(); + ui.add_space(4.0); + // Wrap: translated labels (ru, de) can be wider than the page column. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Min).with_main_wrap(true), |ui| { + ui.add_enabled_ui(page_kind, |ui| { + if crate::widgets::secondary_button(ui, tl!("Reset to Default"), 130.0).clicked() + && let Ok(v) = app.run("layer.layerStyle.defaultFor", json!({"kind": sel_kind})) + && let Some(e) = entry_mut(f, selected) + { + e["params"] = v["params"].clone(); + } + if crate::widgets::secondary_button(ui, tl!("Make Default"), 110.0).clicked() + && app.run("layer.layerStyle.makeDefault", json!({"kind": sel_kind, "params": disp})).is_ok() + && let Some(d) = f.get_mut(USER_DEFAULTS).and_then(Value::as_object_mut) + { + d.insert(sel_kind.to_string(), disp.clone()); + } + }); + }); +} + +/// Photoshop's right-hand column: OK, Cancel, New Style…, Preview and the preview swatch. +fn side_column(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, new_style: &mut bool) -> Option { + let mut outcome = None; + if widgets::primary_button(ui, tl!("OK"), SIDE_W).clicked() { + outcome = Some(true); + } + ui.add_space(2.0); + if widgets::secondary_button(ui, tl!("Cancel"), SIDE_W).clicked() { + outcome = Some(false); + } + ui.add_space(2.0); + if widgets::secondary_button(ui, tl!("New Style…"), SIDE_W).clicked() { + *new_style = true; + } + ui.add_space(6.0); + let mut preview = f.get("preview").and_then(Value::as_bool).unwrap_or(true); + if widgets::checkbox(ui, &mut preview, tl!("Preview")).changed() { + f.insert("preview".into(), json!(preview)); + } + ui.add_space(6.0); + preview_swatch(app, ui, f, SIDE_W); + outcome +} + +/// Photoshop's preview swatch: the dialog's pending style on a sample square, redrawn when the +/// style changes. +fn preview_swatch(app: &PhotocraftApp, ui: &mut egui::Ui, f: &Map, size: f32) { + let t = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::Vec2::splat(size), Sense::hover()); + ui.painter().rect_filled(rect, t.radius_sm, t.field); + // At point size while a drag (a slider) changes it every frame, a quarter of the work on a + // 2x screen; at the screen's resolution once it settles. + let scale = if ui.input(|i| i.pointer.any_down()) { 1.0 } else { ui.ctx().pixels_per_point() }; + let px = (size * scale).round().clamp(8.0, 256.0) as u32; + let key = (preview_hash(f), px); + let id = egui::Id::unique("layer-style-swatch"); + let cached = ui.data(|d| d.get_temp::<(u64, u32, egui::TextureHandle)>(id)).filter(|c| (c.0, c.1) == key).map(|c| c.2); + let tex = cached.or_else(|| { + let rgba = photocraft_engine::presets::styles::thumbnail(&app.session, &pending_style(app, f)?, px); + let side = px as usize; + (rgba.len() == side * side * 4).then(|| { + let tex = ui.ctx().load_texture("layer-style-swatch", egui::ColorImage::from_rgba_unmultiplied([side, side], &rgba), egui::TextureOptions::LINEAR); + ui.data_mut(|d| d.insert_temp(id, (key.0, key.1, tex.clone()))); + tex + }) + }); + if let Some(tex) = tex { + ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + } + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.separator), StrokeKind::Inside); +} + +/// The dialog's pending style as a preset, built on a scratch layer the way the canvas preview +/// builds it on the real one (instance snapshots, blending options and patterns all apply). +fn pending_style(app: &PhotocraftApp, f: &Map) -> Option { + let mut s = photocraft_engine::Session::new(); + s.patterns = app.session.patterns.clone(); + s.execute("file.new", json!({"width": 8, "height": 8})).ok()?; + let layer = s.execute("layer.new.layer", json!({})).ok()?.get("layer")?.as_u64()?; + let mut f = f.clone(); + f.insert("layer".into(), json!(layer)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).ok()?; + let l = s.active()?.doc.layer(photocraft_doc::LayerId(layer))?; + Some(photocraft_engine::presets::styles::StylePreset { + name: String::new(), + effects: l.effects.items.clone(), + blend: Some(l.blend), + opacity: Some(l.opacity), + fill_opacity: Some(l.fill_opacity), + }) +} diff --git a/crates/ui-egui/src/dialogs/layer_style/color_picker.rs b/crates/ui-egui/src/dialogs/layer_style/color_picker.rs index 341e659c9e..31dddfd088 100644 --- a/crates/ui-egui/src/dialogs/layer_style/color_picker.rs +++ b/crates/ui-egui/src/dialogs/layer_style/color_picker.rs @@ -17,6 +17,9 @@ struct Target { layer: photocraft_doc::LayerId, effect: String, field: String, + /// The colour stop edited when `field` is the Gradient Overlay's `stops` (#5177). + #[serde(default)] + stop: Option, color: String, // A reused effect id after loading another style must not redirect the transaction. source: Value, @@ -43,24 +46,50 @@ struct ColorField { color: String, } -fn color_value(fields: &Map, effect: &str, field: &str) -> Result { +fn color_value(fields: &Map, effect: &str, field: &str, stop: Option) -> Result { let mut matches = effects_of(fields).iter().filter(|e| e.get("id").and_then(Value::as_str) == Some(effect)); let e = matches.next().ok_or("Layer Style effect no longer exists")?; if matches.next().is_some() { return Err("ambiguous Layer Style effect id".into()); } let kind = e.get("kind").and_then(Value::as_str).ok_or("invalid effect kind")?; - if !spec(kind).iter().any(|(key, _, p)| *key == field && matches!(p, P::Color)) { - return Err("not a Layer Style color parameter".into()); - } let params = e.get("params").and_then(Value::as_object).ok_or("invalid effect parameters")?; - let original = params.get(field).cloned(); let base = defaults(kind); - let color = original.as_ref().or_else(|| base.get(field)).and_then(Value::as_str).ok_or("invalid effect color")?; - let rgb = color_picker_ui::parse_hex(color).ok_or("invalid effect color")?; + let original = params.get(field).or_else(|| base.get(field)); + let rgb = match stop { + // A gradient stop: the colour at that index of the effect's `stops`. + Some(i) => { + if !spec(kind).iter().any(|(key, _, p)| *key == field && matches!(p, P::Gradient)) { + return Err("not a Layer Style gradient parameter".into()); + } + let stops = super::gradient_field::stops_of(original).ok_or("invalid effect gradient")?; + stops.get(i).map(|s| s.1.to_rgb()).ok_or("no such gradient stop")? + } + None => { + if !spec(kind).iter().any(|(key, _, p)| *key == field && matches!(p, P::Color)) { + return Err("not a Layer Style color parameter".into()); + } + let color = original.and_then(Value::as_str).ok_or("invalid effect color")?; + color_picker_ui::parse_hex(color).ok_or("invalid effect color")? + } + }; Ok(ColorField { source: e.clone(), color: color_picker_ui::hex(rgb) }) } +/// The value the picker's colour becomes for the target: the colour itself, or the effect's +/// `stops` with stop `i` recoloured. +fn picked_value(fields: &Map, t: &Target, color: &str) -> Result { + let Some(i) = t.stop else { return Ok(json!(color)) }; + let e = effects_of(fields).iter().find(|e| e.get("id").and_then(Value::as_str) == Some(t.effect.as_str())).ok_or("Layer Style effect no longer exists")?; + let kind = e.get("kind").and_then(Value::as_str).ok_or("invalid effect kind")?; + let base = defaults(kind); + let current = e.get("params").and_then(|p| p.get(&t.field)).or_else(|| base.get(&t.field)); + let mut stops = super::gradient_field::stops_of(current).ok_or("invalid effect gradient")?; + let [r, g, b] = color_picker_ui::parse_hex(color).ok_or("invalid picker color")?; + stops.get_mut(i).ok_or("no such gradient stop")?.1 = photocraft_color::Color::rgb(r, g, b); + Ok(super::gradient_field::stops_json(&stops)) +} + fn validate<'a>(app: &'a PhotocraftApp, t: &Target) -> Result<&'a Map, String> { let st = app.session.active().ok_or("no active document")?; if st.doc.id != t.document || st.doc.layer(t.layer).is_none() { @@ -73,7 +102,7 @@ fn validate<'a>(app: &'a PhotocraftApp, t: &Target) -> Result<&'a Map(app: &'a PhotocraftApp, t: &Target) -> Result<&'a Map Result { +pub(crate) fn open(app: &mut PhotocraftApp, parent: u64, effect: &str, field: &str, stop: Option) -> Result { if app.ui.dialogs.last().map(|d| d.id) != Some(parent) || has_child(app, parent) { return Err("open the picker from the top Layer Style dialog".into()); } let d = app.ui.dialogs.iter().find(|d| d.id == parent && d.kind == DialogKind::LayerStyle).ok_or("no Layer Style dialog")?; let st = app.session.active().ok_or("no active document")?; let layer = photocraft_doc::LayerId(d.fields.get("layer").and_then(Value::as_u64).ok_or("invalid layer id")?); - let ColorField { source, color } = color_value(&d.fields, effect, field)?; - let t = Target { parent, document: st.doc.id, layer, effect: effect.into(), field: field.into(), color: color.clone(), source }; + let ColorField { source, color } = color_value(&d.fields, effect, field, stop)?; + let t = Target { parent, document: st.doc.id, layer, effect: effect.into(), field: field.into(), stop, color: color.clone(), source }; validate(app, &t)?; let rgb = color_picker_ui::parse_hex(&color).ok_or("invalid effect color")?; let mut fields = color_picker_ui::fields_with_web(app, "dialog", "Color Picker (Layer Style Color)", rgb); @@ -102,7 +131,11 @@ pub(crate) fn take_request(app: &mut PhotocraftApp, parent: u64) -> Result<(), S if let Some(r) = request { let effect = r.get("effect").and_then(Value::as_str).ok_or("invalid effect request")?; let field = r.get("field").and_then(Value::as_str).ok_or("invalid color request")?; - open(app, parent, effect, field)?; + let stop = match r.get("stop") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("invalid gradient stop")?), + }; + open(app, parent, effect, field, stop)?; } Ok(()) } @@ -120,8 +153,9 @@ pub(crate) fn preview_fields<'a>(app: &PhotocraftApp, parent: u64, fields: &'a M if t.color == color { return Cow::Borrowed(fields); } + let Ok(value) = picked_value(fields, &t, &color) else { return Cow::Borrowed(fields) }; let mut shown = fields.clone(); - set_param(&mut shown, &t.effect, &t.field, json!(color)); + set_param(&mut shown, &t.effect, &t.field, value); Cow::Owned(shown) } @@ -131,7 +165,8 @@ pub(crate) fn confirm(app: &mut PhotocraftApp, fields: &Map) -> R let color = fields.get("color").and_then(Value::as_str).and_then(color_picker_ui::parse_hex).map(color_picker_ui::hex).ok_or("invalid picker color")?; if t.color != color { let parent = app.ui.dialog_mut(t.parent).ok_or("Layer Style dialog closed")?; - set_param(&mut parent.fields, &t.effect, &t.field, json!(color)); + let value = picked_value(&parent.fields, &t, &color)?; + set_param(&mut parent.fields, &t.effect, &t.field, value); } Ok(Value::Null) } diff --git a/crates/ui-egui/src/dialogs/layer_style/color_picker/tests.rs b/crates/ui-egui/src/dialogs/layer_style/color_picker/tests.rs index 2d87c81ef8..f98e02577b 100644 --- a/crates/ui-egui/src/dialogs/layer_style/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/color_picker/tests.rs @@ -34,7 +34,7 @@ fn every_exposed_color_field_uses_the_shared_picker_and_only_updates_its_target( let tools = app.session.tools.clone(); let doc = app.session.active().unwrap().doc.clone(); let history = app.session.active().unwrap().history.past_len(); - let picker = open(&mut app, parent, &effect, field).unwrap(); + let picker = open(&mut app, parent, &effect, field, None).unwrap(); assert!(color_picker_ui::owns(&fields(&app, picker))); assert_eq!(fields(&app, picker)["__label"], "Color Picker (Layer Style Color)"); set_color(&mut app, picker, "#23a567"); @@ -63,7 +63,7 @@ fn preview_cancel_ok_parent_cancel_and_apply_are_transactional_at_every_depth() let original = fields(&app, parent); let st = app.session.active().unwrap(); let (doc, history, revision, dirty) = (st.doc.clone(), st.history.past_len(), st.revision, st.is_dirty()); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); set_color(&mut app, picker, "#00ff00"); let (shown, key) = canvas::display_doc(&mut app, 0); assert!(!Arc::ptr_eq(&shown, &doc)); @@ -78,7 +78,7 @@ fn preview_cancel_ok_parent_cancel_and_apply_are_transactional_at_every_depth() dialogs::cancel(&mut app, picker).unwrap(); assert_eq!(fields(&app, parent), original); assert_ne!(canvas::display_doc(&mut app, 0).1, key); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); set_color(&mut app, picker, "#00ff00"); dialogs::confirm(&mut app, picker).unwrap(); assert_eq!(app.session.active().unwrap().history.past_len(), history); @@ -86,7 +86,7 @@ fn preview_cancel_ok_parent_cancel_and_apply_are_transactional_at_every_depth() assert!(Arc::ptr_eq(&canvas::display_doc(&mut app, 0).0, &doc)); let parent = layer_style::open(&mut app, Some("colorOverlay")).unwrap(); let effect = selected(&app, parent); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); set_color(&mut app, picker, "#00ff00"); dialogs::confirm(&mut app, picker).unwrap(); dialogs::confirm(&mut app, parent).unwrap(); @@ -108,11 +108,11 @@ fn unchanged_ok_preserves_missing_parameters_and_imported_effect_snapshot() { let parent = layer_style::open(&mut app, Some("stroke")).unwrap(); let original = fields(&app, parent); for effect in ["fx1", "fx2"] { - let picker = open(&mut app, parent, effect, "color").unwrap(); + let picker = open(&mut app, parent, effect, "color", None).unwrap(); dialogs::confirm(&mut app, picker).unwrap(); assert_eq!(fields(&app, parent), original); } - let picker = open(&mut app, parent, "fx2", "color").unwrap(); + let picker = open(&mut app, parent, "fx2", "color", None).unwrap(); set_color(&mut app, picker, "#223344"); dialogs::confirm(&mut app, picker).unwrap(); let current = fields(&app, parent); @@ -121,9 +121,9 @@ fn unchanged_ok_preserves_missing_parameters_and_imported_effect_snapshot() { dialogs::cancel(&mut app, parent).unwrap(); let parent = layer_style::open(&mut app, Some("gradientOverlay")).unwrap(); let effect = selected(&app, parent); - app.ui.dialog_mut(parent).unwrap().fields.get_mut("effects").unwrap().as_array_mut().unwrap()[0]["params"].as_object_mut().unwrap().remove("from"); + app.ui.dialog_mut(parent).unwrap().fields.get_mut("effects").unwrap().as_array_mut().unwrap()[0]["params"].as_object_mut().unwrap().remove("stops"); let original = fields(&app, parent); - let picker = open(&mut app, parent, &effect, "from").unwrap(); + let picker = open(&mut app, parent, &effect, "stops", Some(0)).unwrap(); dialogs::confirm(&mut app, picker).unwrap(); assert_eq!(fields(&app, parent), original); } @@ -134,7 +134,7 @@ fn stale_targets_and_invalid_colors_never_apply_or_leave_preview() { let mut app = app(8); let parent = layer_style::open(&mut app, Some("colorOverlay")).unwrap(); let effect = selected(&app, parent); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); set_color(&mut app, picker, "#00ff00"); match change { "document" => { @@ -174,11 +174,11 @@ fn stale_targets_and_invalid_colors_never_apply_or_leave_preview() { let parent = layer_style::open(&mut app, Some("colorOverlay")).unwrap(); let effect = selected(&app, parent); let original = fields(&app, parent); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); set_color(&mut app, picker, "bad"); assert!(dialogs::confirm(&mut app, picker).is_err()); assert_eq!(fields(&app, parent), original); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); app.run("file.new", json!({"width":3,"height":3})).unwrap(); prune(&mut app); assert!(!app.ui.dialogs.iter().any(|d| d.id == picker)); @@ -192,7 +192,7 @@ fn preview_off_and_parent_confirmation_and_cancellation_keep_their_contract() { let effect = selected(&app, parent); let original = fields(&app, parent); let doc = app.session.active().unwrap().doc.clone(); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); set_color(&mut app, picker, "#00ff00"); assert!(Arc::ptr_eq(&canvas::display_doc(&mut app, 0).0, &doc)); assert!(dialogs::confirm(&mut app, parent).is_err()); @@ -249,7 +249,7 @@ fn eyedropper_edits_only_the_picker_and_invalid_samples_leave_it_unchanged() { let original = fields(&app, parent); let doc = app.session.active().unwrap().doc.clone(); let tools = app.session.tools.clone(); - let picker = open(&mut app, parent, &effect, "color").unwrap(); + let picker = open(&mut app, parent, &effect, "color", None).unwrap(); color_picker_ui::sample_at(&mut app, 4.0, 4.0); assert_eq!(fields(&app, picker)["color"], "#406080"); color_picker_ui::sample_at(&mut app, -100.0, -100.0); @@ -259,3 +259,25 @@ fn eyedropper_edits_only_the_picker_and_invalid_samples_leave_it_unchanged() { assert_eq!(app.session.tools.foreground, tools.foreground); dialogs::cancel(&mut app, picker).unwrap(); } + +/// A Gradient Overlay's stop (#5177): the picker edits one colour of `stops`, previewing it, +/// and leaves the other stops alone; a stop that doesn't exist is refused. +#[test] +fn gradient_stop_colors_go_through_the_picker() { + let mut app = app(8); + let parent = layer_style::open(&mut app, Some("gradientOverlay")).unwrap(); + let effect = selected(&app, parent); + let three = json!([[0.0, "#ff0000"], [0.5, "#00ff00"], [1.0, "#0000ff"]]); + super::super::set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, "stops", three); + assert!(open(&mut app, parent, &effect, "stops", Some(3)).is_err(), "no fourth stop"); + assert!(open(&mut app, parent, &effect, "stops", None).is_err(), "stops is not a plain colour"); + let picker = open(&mut app, parent, &effect, "stops", Some(1)).unwrap(); + set_color(&mut app, picker, "#123456"); + let current = fields(&app, parent); + let shown = preview_fields(&app, parent, ¤t); + assert_eq!(super::super::entry(&shown, &effect).unwrap()["params"]["stops"][1][1], "#123456", "previewed"); + assert_eq!(super::super::entry(&fields(&app, parent), &effect).unwrap()["params"]["stops"][1][1], "#00ff00", "not stored yet"); + dialogs::confirm(&mut app, picker).unwrap(); + let stops = super::super::entry(&fields(&app, parent), &effect).unwrap()["params"]["stops"].clone(); + assert_eq!(stops, json!([[0.0, "#ff0000"], [0.5, "#123456"], [1.0, "#0000ff"]])); +} diff --git a/crates/ui-egui/src/dialogs/layer_style/contour.rs b/crates/ui-egui/src/dialogs/layer_style/contour.rs index 0c1c18b605..6860faa1bd 100644 --- a/crates/ui-egui/src/dialogs/layer_style/contour.rs +++ b/crates/ui-egui/src/dialogs/layer_style/contour.rs @@ -102,10 +102,11 @@ pub(super) fn row( ) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { + // In the page's label column, empty for Bevel & Emboss's Contour (its check box is above). if label.is_empty() { - ui.add_space(16.0); + ui.allocate_exact_size(vec2(super::LABEL_W, 1.0), Sense::hover()); } else { - ui.label(RichText::new(tl!(label)).color(t.text_dim)); + crate::widgets::row_label(ui, label, super::LABEL_W); } let c = contour_of(disp.get(key)); let (r, thumb) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::click()); diff --git a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs new file mode 100644 index 0000000000..8abbefbbd7 --- /dev/null +++ b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs @@ -0,0 +1,462 @@ +//! The Gradient Overlay page's gradient (#5177): a ramp with colour-stop markers under it, edited +//! in place as in Photoshop's Gradient Editor (click under the ramp to add a stop with the +//! gradient's colour there, drag a marker to move it, drag it away to delete it, double-click it +//! or the Color swatch for the Color Picker), a Location field and Delete for the selected stop, +//! and the Gradients panel's presets to start from. The dialog field `stops` is +//! `[[position, "#rrggbb"], …]` and `opacityStops` `[[position, opacity %], …]` (carried through +//! the dialog, not edited here): the engine command's own grammar, so what the page shows is what +//! `layer.layerStyle.gradientOverlay` receives. + +use egui::{Color32, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}; +use photocraft_color::Color; +use photocraft_compose::gradient_fill as gf; +use photocraft_doc::{Fill, GradientStyle}; +use photocraft_engine::gradient_fill_cmds as cmds; +use serde_json::{Map, Value, json}; + +use super::{color_picker, set_param}; +use crate::theme::Tokens; +use crate::{PhotocraftApp, color_picker_ui, widgets}; + +/// The dialog field holding the colour stops. +pub(super) const KEY: &str = "stops"; +/// The dialog field holding the transparency stops. +pub(super) const OPACITY_KEY: &str = "opacityStops"; + +/// Where the last drawn ramp bar is, for tests that drive it: `(effect id, bar rect)`. +pub(crate) fn bar_id() -> egui::Id { + egui::Id::unique("fx-gradient-bar") +} + +/// `[[t, "#rrggbb"], …]` → stops (at least two, sorted); `None` when the value isn't that. +pub(super) fn stops_of(v: Option<&Value>) -> Option> { + let a = v?.as_array()?; + let mut stops: Vec<(f32, Color)> = a + .iter() + .filter_map(|s| { + let t = s.get(0)?.as_f64()?; + let value = s.get(1)?; + let color = if let Some(hex) = value.as_str() { + let [r, g, b] = color_picker_ui::parse_hex(hex)?; + Color::rgb(r, g, b) + } else { + serde_json::from_value::(value.clone()).ok()? + }; + (t.is_finite() && color.c.iter().all(|v| v.is_finite()) && color.alpha.is_finite()).then(|| (t.clamp(0.0, 1.0) as f32, color)) + }) + .collect(); + if stops.len() < 2 { + return None; + } + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(stops) +} + +/// `[[t, opacity %], …]` → transparency stops (empty = opaque); `None` when the value isn't that. +pub(super) fn opacity_of(v: Option<&Value>) -> Option> { + let a = v?.as_array()?; + let mut os: Vec<(f32, f32)> = a + .iter() + .filter_map(|s| { + let (t, o) = (s.get(0)?.as_f64()?, s.get(1)?.as_f64()?); + (t.is_finite() && o.is_finite()).then(|| (t.clamp(0.0, 1.0) as f32, (o / 100.0).clamp(0.0, 1.0) as f32)) + }) + .collect(); + if os.len() == 1 { + return None; + } + os.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(os) +} + +pub(super) fn stops_json(stops: &[(f32, Color)]) -> Value { + Value::Array( + stops + .iter() + .map(|(t, c)| { + let [r, g, b, _] = c.to_rgba8(); + let exact = Color::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0); + if *c == exact { json!([t, super::hex(c)]) } else { json!([t, c]) } + }) + .collect(), + ) +} + +pub(super) fn opacity_json(os: &[(f32, f32)]) -> Value { + Value::Array(os.iter().map(|(t, o)| json!([t, f64::from(*o) * 100.0])).collect()) +} + +/// The page's gradient as a fill: the ramp, and what the stop edits are applied to. +pub(super) fn fill_of(disp: &Value) -> Fill { + let stops = stops_of(disp.get(KEY)).unwrap_or_else(|| vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); + let mut f = Fill::gradient(stops, 0.0, 1.0, GradientStyle::Linear, false); + if let Fill::Gradient { opacity_stops, .. } = &mut f { + *opacity_stops = opacity_of(disp.get(OPACITY_KEY)).unwrap_or_default(); + } + f +} + +/// The engine's factory defaults name a From and To colour; the page models stops, so a fresh +/// instance starts from those two as stops (and never shows From/To). +pub(super) fn from_to_to_stops(p: &mut Value) { + let Some(o) = p.as_object_mut() else { return }; + if !o.contains_key(KEY) { + let hex = |k: &str, d: &str| o.get(k).and_then(Value::as_str).unwrap_or(d).to_string(); + let (from, to) = (hex("from", "#000000"), hex("to", "#ffffff")); + o.insert(KEY.into(), json!([[0.0, from], [1.0, to]])); + } + o.remove("from"); + o.remove("to"); + o.entry(OPACITY_KEY).or_insert_with(|| json!([])); +} + +/// Store `fill`'s stops as the effect's `stops` / `opacityStops` and show them. +fn commit(f: &mut Map, effect: &str, disp: &mut Value, fill: &Fill) { + let Fill::Gradient { stops, opacity_stops, .. } = fill else { return }; + let v = stops_json(stops); + disp[KEY] = v.clone(); + set_param(f, effect, KEY, v); + let v = opacity_json(opacity_stops); + disp[OPACITY_KEY] = v.clone(); + set_param(f, effect, OPACITY_KEY, v); +} + +/// Apply one stop edit (`cmds::apply_stop`'s grammar) to the page's gradient; the new index of +/// the edited stop, for the selection. +fn edit(app: &PhotocraftApp, f: &mut Map, effect: &str, disp: &mut Value, p: Value) -> Option { + let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); + let fill = fill_of(disp); + let new = cmds::apply_stop(&fill, &p, fg, bg).ok()?; + let Fill::Gradient { stops, .. } = &new else { return None }; + // The engine keeps stops sorted: the edited one is the last with its location. + let at = match p.get("action").and_then(Value::as_str) { + Some("add" | "move") => { + let loc = p.get("location").and_then(Value::as_f64).unwrap_or(0.0) as f32; + stops.iter().rposition(|s| (s.0 - loc).abs() < 1e-6).unwrap_or(0) + } + _ => 0, + }; + commit(f, effect, disp, &new); + Some(at) +} + +/// Use `preset` (the Gradients panel's) as the page's gradient, resolved with the tool colours. +pub(super) fn apply_preset(app: &PhotocraftApp, f: &mut Map, effect: &str, disp: &mut Value, name: &str) -> bool { + let Some(preset) = app.session.presets.gradients.iter().flat_map(|g| g.items.iter()).find(|p| p.name == name) else { return false }; + let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); + let (stops, os) = preset.fill_stops(fg, bg); + if stops.len() < 2 { + return false; + } + let mut fill = Fill::gradient(stops, 0.0, 1.0, GradientStyle::Linear, false); + if let Fill::Gradient { opacity_stops, .. } = &mut fill { + *opacity_stops = os; + } + commit(f, effect, disp, &fill); + true +} + +/// The page's row: the preset dropdown, the ramp with its stop markers, the selected stop's +/// Color, Location and Delete. +pub(super) fn row(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, effect: &str, label: &str, disp: &mut Value) { + let t = Tokens::get(ui.ctx()); + let sel_key = egui::Id::unique(("fx-gradient-selection", effect.to_string())); + let drag_key = egui::Id::unique(("fx-gradient-drag", effect.to_string())); + // Presets to start from. + ui.horizontal(|ui| { + ui.label(RichText::new(tl!(label)).color(t.text_dim)); + let names: Vec<(String, String)> = + app.session.presets.gradients.iter().flat_map(|g| g.items.iter()).map(|p| (p.name.clone(), p.name.clone())).collect(); + let mut cur = String::new(); + let mut opts: Vec<(String, &str)> = vec![(String::new(), "Custom")]; + opts.extend(names.iter().map(|(id, n)| (id.clone(), n.as_str()))); + if widgets::dropdown(ui, &format!("fx-gradient-preset-{effect}"), "Gradient preset", &mut cur, &opts, 180.0) && !cur.is_empty() { + apply_preset(app, f, effect, disp, &cur); + ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); + } + }); + let fill = fill_of(disp); + let Fill::Gradient { stops, .. } = &fill else { return }; + let w = ui.available_width().max(120.0); + let (outer, resp) = ui.allocate_exact_size(vec2(w, 46.0), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Gradient stops"))); + let bar = Rect::from_min_max(pos2(outer.left() + 8.0, outer.top() + 2.0), pos2(outer.right() - 8.0, outer.top() + 24.0)); + ui.data_mut(|d| d.insert_temp(bar_id(), (effect.to_string(), bar))); + let x_of = |loc: f32| bar.left() + loc.clamp(0.0, 1.0) * bar.width(); + let loc_of = |x: f32| ((x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); + if let Some(ramp) = gf::Ramp::new(&fill) { + crate::gradient_ui::paint_ramp(ui.painter(), bar, |u| ramp.sample(u)); + } + ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); + let selected: usize = ui.data(|d| d.get_temp(sel_key)).unwrap_or(0).min(stops.len().saturating_sub(1)); + // Markers: a triangle on the bar's lower edge over a chip of the stop's colour. + let hit = |p: egui::Pos2| -> Option { + if p.y < bar.bottom() - 2.0 || p.y > outer.bottom() + 4.0 { + return None; + } + stops.iter().enumerate().rev().find(|(_, s)| (x_of(s.0) - p.x).abs() <= 7.0).map(|(i, _)| i) + }; + for (i, (loc, c)) in stops.iter().enumerate() { + let x = x_of(*loc); + let tri = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 7.0), pos2(x + 5.0, bar.bottom() + 7.0)]; + let ink = if i == selected { t.accent } else { t.text_dim }; + ui.painter().add(egui::Shape::convex_polygon(tri, ink, Stroke::NONE)); + let chip = Rect::from_min_size(pos2(x - 5.0, bar.bottom() + 7.0), vec2(10.0, 10.0)); + let [r, g, b] = c.to_rgb(); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + ui.painter().rect_filled(chip, 0.0, Color32::from_rgb(q(r), q(g), q(b))); + ui.painter().rect_stroke(chip, 0.0, Stroke::new(if i == selected { 1.5 } else { 1.0 }, ink), StrokeKind::Outside); + } + // Pointer: press on a marker selects it and starts a drag; a drag moves it, and a drag that + // leaves the strip deletes it on release (two stops always stay); a click under the bar with + // no marker adds a stop; a double-click on a marker opens the Color Picker. + if resp.drag_started() + && let Some(p) = ui.input(|i| i.pointer.press_origin()) + { + if let Some(i) = hit(p) { + ui.data_mut(|d| d.insert_temp(drag_key, i)); + ui.data_mut(|d| d.insert_temp(sel_key, i)); + } else { + ui.data_mut(|d| d.remove::(drag_key)); + } + } + let dragging: Option = ui.data(|d| d.get_temp(drag_key)); + if let (Some(i), Some(p)) = (dragging, resp.interact_pointer_pos()) { + let away = p.y > outer.bottom() + 24.0 || p.y < bar.top() - 24.0; + if resp.drag_stopped() { + ui.data_mut(|d| d.remove::(drag_key)); + if away && stops.len() > 2 { + edit(app, f, effect, disp, json!({"action": "delete", "index": i})); + ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); + } + } else if resp.dragged() && !away { + let loc = loc_of(p.x); + if (loc - stops.get(i).map_or(loc, |s| s.0)).abs() > 1e-4 + && let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": i, "location": loc})) + { + ui.data_mut(|d| d.insert_temp(drag_key, at)); + ui.data_mut(|d| d.insert_temp(sel_key, at)); + } + } + } else if resp.drag_stopped() { + ui.data_mut(|d| d.remove::(drag_key)); + } + if resp.double_clicked() + && let Some(p) = resp.interact_pointer_pos() + && let Some(i) = hit(p) + { + ui.data_mut(|d| d.insert_temp(sel_key, i)); + f.insert(color_picker::REQUEST.into(), json!({"effect": effect, "field": KEY, "stop": i})); + } else if resp.clicked() + && let Some(p) = resp.interact_pointer_pos() + { + match hit(p) { + Some(i) => { + ui.data_mut(|d| d.insert_temp(sel_key, i)); + } + None if p.x >= bar.left() && p.x <= bar.right() => { + if let Some(at) = edit(app, f, effect, disp, json!({"action": "add", "location": loc_of(p.x)})) { + ui.data_mut(|d| d.insert_temp(sel_key, at)); + } + } + None => {} + } + } + // The selected stop. + let fill = fill_of(disp); + let Fill::Gradient { stops, .. } = &fill else { return }; + let selected = selected.min(stops.len().saturating_sub(1)); + let Some((loc, color)) = stops.get(selected).copied() else { return }; + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Color")).color(t.text_dim)); + let [r, g, b] = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + let swatch = widgets::color_swatch(ui, Color32::from_rgb(r, g, b)).on_hover_text(tl!("Color Picker (Layer Style Color)")); + if swatch.clicked() { + f.insert(color_picker::REQUEST.into(), json!({"effect": effect, "field": KEY, "stop": selected})); + } + ui.add_space(8.0); + ui.label(RichText::new(tl!("Location")).color(t.text_dim)); + let mut pct = loc * 100.0; + if widgets::value_field(ui, &mut pct, 0.0..=100.0, "%", 58.0).changed() + && let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": selected, "location": pct / 100.0})) + { + ui.data_mut(|d| d.insert_temp(sel_key, at)); + } + ui.add_space(8.0); + if ui.add_enabled(stops.len() > 2, egui::Button::new(tl!("Delete"))).clicked() { + edit(app, f, effect, disp, json!({"action": "delete", "index": selected})); + ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use egui_kittest::kittest::Queryable; + + fn dialog_app() -> (PhotocraftApp, u64) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let parent = crate::layer_style::open(&mut app, Some("gradientOverlay")).unwrap(); + (app, parent) + } + + /// The dialog body drawn from the real dialog's fields, edits written back to it. + fn harness(app: PhotocraftApp, parent: u64) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + let Some(mut f) = app.ui.dialogs.iter().find(|d| d.id == parent).map(|d| d.fields.clone()) else { return }; + crate::layer_style::body(app, ui, &mut f); + if let Some(d) = app.ui.dialog_mut(parent) { + d.fields = f; + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(3); + h + } + + fn stops_in(app: &PhotocraftApp, parent: u64) -> Vec<(f32, Color)> { + let f = &app.ui.dialogs.iter().find(|d| d.id == parent).unwrap().fields; + let e = crate::layer_style::effects_of(f).iter().find(|e| e["kind"] == "gradientOverlay").unwrap(); + stops_of(e["params"].get(KEY)).unwrap() + } + + fn press(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, p: egui::Pos2) { + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + } + fn release(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, p: egui::Pos2) { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + } + + /// Photoshop's Gradient Editor gestures on the page: a click under the ramp adds a stop with + /// the colour there, a drag moves one, a drag away from the strip deletes it, two stay. + #[test] + fn ramp_adds_moves_and_deletes_stops() { + let (mut app, parent) = dialog_app(); + let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string(); + set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [1.0, "#ffffff"]])); + let mut h = harness(app, parent); + assert!(h.query_by_label("Gradient stops").is_some()); + let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn"); + // Add in the middle: a mid grey. + let mid = pos2(bar.center().x, bar.bottom() + 9.0); + press(&mut h, mid); + release(&mut h, mid); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.len(), 3, "{stops:?}"); + assert!((stops[1].0 - 0.5).abs() < 0.02 && (stops[1].1.to_rgb()[0] - 0.5).abs() < 0.06, "{stops:?}"); + // Drag it to a quarter. + let quarter = pos2(bar.left() + bar.width() * 0.25, mid.y); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x - 10.0, mid.y))); + h.run_steps(1); + h.event(egui::Event::PointerMoved(quarter)); + h.run_steps(1); + release(&mut h, quarter); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.len(), 3); + assert!((stops[1].0 - 0.25).abs() < 0.03, "{stops:?}"); + // Drag it away: gone. + let away = pos2(quarter.x, bar.bottom() + 90.0); + press(&mut h, quarter); + h.event(egui::Event::PointerMoved(pos2(quarter.x, quarter.y + 20.0))); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + release(&mut h, away); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.len(), 2, "{stops:?}"); + // The last two can't be dragged away. + let first = pos2(bar.left(), mid.y); + press(&mut h, first); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + release(&mut h, away); + assert_eq!(stops_in(h.state(), parent).len(), 2); + } + + /// A preset from the Gradients panel becomes the page's stops; the Delete button and the + /// Location field work on the selected stop. + #[test] + fn presets_delete_and_location() { + let (mut app, parent) = dialog_app(); + let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string(); + let name = app + .session + .presets + .gradients + .iter() + .flat_map(|g| g.items.iter()) + .map(|p| p.name.clone()) + .find(|n| n.contains("Spectrum") || n.contains("Rainbow")) + .or_else(|| app.session.presets.gradients.first().and_then(|g| g.items.first()).map(|p| p.name.clone())) + .unwrap(); + let mut f = app.ui.dialog_mut(parent).unwrap().fields.clone(); + let mut disp = json!({}); + assert!(apply_preset(&app, &mut f, &effect, &mut disp, &name), "{name}"); + assert!(!apply_preset(&app, &mut f, &effect, &mut disp, "no such preset")); + let stops = stops_of(disp.get(KEY)).unwrap(); + assert!(stops.len() >= 2, "{name}: {stops:?}"); + app.ui.dialog_mut(parent).unwrap().fields = f; + set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#ff0000"], [0.5, "#00ff00"], [1.0, "#0000ff"]])); + let mut h = harness(app, parent); + let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).unwrap(); + // Select the middle stop, then Delete. + let mid = pos2(bar.center().x, bar.bottom() + 9.0); + press(&mut h, mid); + release(&mut h, mid); + h.get_by_label("Delete").click(); + h.run_steps(2); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.iter().map(|s| super::super::hex(&s.1)).collect::>(), ["#ff0000", "#0000ff"], "{stops:?}"); + } + + #[test] + fn stops_round_trip_through_the_field_grammar() { + let stops = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.5, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))]; + let v = stops_json(&stops); + assert_eq!(v, json!([[0.0, "#ff0000"], [0.5, "#00ff00"], [1.0, "#0000ff"]])); + assert_eq!(stops_of(Some(&v)), Some(stops)); + // Unsorted input is sorted, bad entries are skipped, fewer than two is nothing. + let v = json!([[1.0, "#ffffff"], ["x", "#ff0000"], [0.25, "#000000"], [0.5, 7]]); + assert_eq!(stops_of(Some(&v)).map(|s| s.iter().map(|x| x.0).collect::>()), Some(vec![0.25, 1.0])); + assert_eq!(stops_of(Some(&json!([[0.0, "#000000"]]))), None); + assert_eq!(stops_of(Some(&json!("red"))), None); + assert_eq!(stops_of(None), None); + let os = vec![(0.0, 1.0), (1.0, 0.5)]; + assert_eq!(opacity_json(&os), json!([[0.0, 100.0], [1.0, 50.0]])); + assert_eq!(opacity_of(Some(&opacity_json(&os))), Some(os)); + assert_eq!(opacity_of(Some(&json!([]))), Some(vec![]), "[] is opaque"); + assert_eq!(opacity_of(Some(&json!([[0.0, 100.0]]))), None, "one stop is not a list"); + } + + #[test] + fn factory_from_to_become_two_stops() { + let mut p = json!({"from": "#ff0000", "to": "#0000ff", "angle": 90}); + from_to_to_stops(&mut p); + assert_eq!(p, json!({"stops": [[0.0, "#ff0000"], [1.0, "#0000ff"]], "opacityStops": [], "angle": 90})); + let mut p = json!({"stops": [[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]], "from": "#123456"}); + from_to_to_stops(&mut p); + assert_eq!(p["stops"].as_array().map(Vec::len), Some(3), "explicit stops win over From/To"); + assert!(p.get("from").is_none()); + } + + #[test] + fn the_fill_of_a_page_never_fails() { + for v in [json!({}), json!({"stops": "x"}), json!({"stops": [[0.0, "#ff0000"]], "opacityStops": [[0.5, 20.0]]}), json!({"stops": null})] { + let Fill::Gradient { stops, opacity_stops, .. } = fill_of(&v) else { panic!("{v}") }; + assert_eq!(stops.len(), 2, "{v}: the default black-to-white"); + assert!(opacity_stops.is_empty() || opacity_stops.len() >= 2, "{v}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/layer_style/gradient_method_tests.rs b/crates/ui-egui/src/dialogs/layer_style/gradient_method_tests.rs index 2578c1ab51..74b4e6b91b 100644 --- a/crates/ui-egui/src/dialogs/layer_style/gradient_method_tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/gradient_method_tests.rs @@ -36,7 +36,7 @@ fn method_picker_is_pending_until_confirm_and_survives_reopening() { ); PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); harness.run_steps(3); - harness.get_by_value("Custom").click(); + harness.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Method").click(); harness.run_steps(2); harness.get_by_label("Smooth").click(); harness.run_steps(2); @@ -51,7 +51,7 @@ fn method_picker_is_pending_until_confirm_and_survives_reopening() { assert_eq!(effect(app), &saved); let reopened = fields(app); assert_eq!(reopened["effects"][0]["params"]["method"], "smooth"); - assert_eq!(reopened["effects"][0]["params"]["from"], "#ff0000"); + assert_eq!(reopened["effects"][0]["params"]["stops"][0][1], "#ff0000"); confirm(app, &reopened).unwrap(); assert_eq!(effect(app), &saved, "OK without edits leaves the rendered curve exact"); } diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 7fe1b40c49..ab221b53b1 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -70,7 +70,7 @@ fn every_effect_row_shows_a_checkbox() { return; } let mut f = fields.clone(); - body(app, ui, &mut f); + body_with_response(app, ui, &mut f, false); }, app, ); @@ -103,7 +103,7 @@ fn default_buttons_wrap_inside_the_page_column_with_long_labels() { app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); let fields = initial_fields(&l, Some("dropShadow"), 120.0); - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + let mut h = egui_kittest::Harness::builder().with_size(vec2(660.0, 700.0)).build_ui_state( move |ui, app: &mut PhotocraftApp| { if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { return; @@ -148,6 +148,30 @@ fn effect_row_of_another_layer_opens_that_layers_style() { assert!(fx[0]["fx"].is_object(), "the existing drop shadow, not a new instance"); } +/// Make Default (#9477): a stroke added afterwards, by opening the dialog on it or with the +/// list's checkbox or +, starts from the saved values; other kinds keep the factory ones. +#[test] +fn new_effects_start_from_the_made_default() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 7, "position": "outside"}})).unwrap(); + + let id = open(&mut app, Some("stroke")).unwrap(); + let mut f = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); + add_instance(&mut f, "stroke"); + add_instance(&mut f, "dropShadow"); + let fx = effects_of(&f); + let strokes: Vec<_> = fx.iter().filter(|e| e["kind"] == json!("stroke")).collect(); + assert_eq!(strokes.len(), 2); + for e in strokes { + assert_eq!((&e["params"]["size"], &e["params"]["position"]), (&json!(7), &json!("outside"))); + assert_eq!(e["params"]["opacity"], defaults("stroke")["opacity"], "unsaved keys keep the factory value"); + } + let shadow = fx.iter().find(|e| e["kind"] == json!("dropShadow")).unwrap(); + assert_eq!(shadow["params"]["size"], defaults("dropShadow")["size"]); +} + #[test] fn every_kind_has_spec_and_defaults() { for &(kind, _) in KINDS { @@ -252,6 +276,32 @@ fn add_and_remove_instances() { assert_eq!(strokes[0].size, 3.0); } +/// The list bar's arrows move an instance among those of its kind only, and stop at the ends. +#[test] +fn move_instance_reorders_within_its_kind() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 3})).unwrap(); + let st = s.active().unwrap(); + let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), None, 120.0); + add_instance(&mut f, "dropShadow"); + add_instance(&mut f, "stroke"); + assert_eq!(ids(&f), ["fx1", "fx3", "fx2"], "a new stroke goes after the last stroke"); + move_instance(&mut f, "fx3", -1); + assert_eq!(ids(&f), ["fx3", "fx1", "fx2"]); + move_instance(&mut f, "fx3", -1); + assert_eq!(ids(&f), ["fx3", "fx1", "fx2"], "already the first stroke"); + move_instance(&mut f, "fx2", 1); + assert_eq!(ids(&f), ["fx3", "fx1", "fx2"], "the only drop shadow stays put"); + for (id, by) in [("fx1", isize::MAX), ("fx1", isize::MIN), ("nope", 1)] { + move_instance(&mut f, id, by); + } + assert_eq!(ids(&f), ["fx3", "fx1", "fx2"], "out-of-range moves and unknown ids change nothing"); +} + +fn ids(f: &Map) -> Vec<&str> { + effects_of(f).iter().filter_map(|e| e.get("id").and_then(Value::as_str)).collect() +} + #[test] fn disabled_instances_are_kept() { let mut s = session(); @@ -269,6 +319,49 @@ fn disabled_instances_are_kept() { assert!(!items[0].enabled()); } +/// The preview swatch shows the dialog's pending style, built away from the document. +#[test] +fn pending_style_is_the_dialogs_and_leaves_the_document_alone() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some("stroke"), 120.0); + set_param(&mut f, "fx1", "size", json!(9)); + let style = pending_style(&app, &f).expect("the pending style builds"); + let sizes: Vec = style + .effects + .iter() + .filter_map(|e| match e { + Effect::Stroke(s) => Some(s.size), + _ => None, + }) + .collect(); + assert_eq!(sizes, [9.0]); + assert!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.is_empty(), "the document is untouched"); + let rgba = photocraft_engine::presets::styles::thumbnail(&app.session, &style, 32); + assert_eq!(rgba.len(), 32 * 32 * 4); +} + +/// The fx menu adds another instance of a kind that takes several, and turns on and shows the +/// layer's one of a kind that takes one. +#[test] +fn fx_menu_adds_or_shows_an_effect() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 3})).unwrap(); + s.execute("layer.layerStyle.satin", json!({"enabled": false})).unwrap(); + let st = s.active().unwrap(); + let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), None, 120.0); + let before = effects_of(&f).len(); + pick_from_fx_menu(&mut f, "stroke"); + assert_eq!(effects_of(&f).len(), before + 1, "a second stroke"); + let satin = effects_of(&f).iter().find(|e| e["kind"] == "satin").and_then(|e| e["id"].as_str()).unwrap().to_string(); + pick_from_fx_menu(&mut f, "satin"); + assert_eq!(effects_of(&f).len(), before + 1, "no second satin"); + assert_eq!(f["selected"], json!(satin)); + assert_eq!(entry(&f, &satin).unwrap()["on"], json!(true)); +} + #[test] fn baked_gradient_overlay_keeps_endpoint_colours_on_reopen() { let mut s = session(); @@ -280,8 +373,9 @@ fn baked_gradient_overlay_keeps_endpoint_colours_on_reopen() { assert!(gradient.stops.len() > 2, "classic bakes intermediate stops"); let f = initial_fields(layer, Some("gradientOverlay"), st.doc.global_light.angle); let params = &effects_of(&f)[0]["params"]; - assert_eq!(params["from"], json!("#ff0000")); - assert_eq!(params["to"], json!("#0000ff")); + let source_stops = gradient_field::stops_of(params.get("stops")).expect("complete gradient stops"); + assert_eq!(source_stops.first().unwrap().1, photocraft_color::Color::rgb(1.0, 0.0, 0.0)); + assert_eq!(source_stops.last().unwrap().1, photocraft_color::Color::rgb(0.0, 0.0, 1.0)); apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); let Effect::GradientOverlay { gradient, .. } = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!() }; assert!(gradient.stops.len() > 2); @@ -398,7 +492,9 @@ fn body_keeps_invalid_params_and_renders_without_panicking() { fields.insert("selected".into(), json!("fx1")); fields.insert("effects".into(), json!([{"id": "fx1", "kind": "dropShadow", "on": true, "params": bad.clone()}])); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields)); + let mut out = ctx.run_ui(Default::default(), |ui| { + body_with_response(&mut app, ui, &mut fields, false); + }); out.textures_delta.clear(); assert_eq!(entry(&fields, "fx1").unwrap()["params"], bad); @@ -408,7 +504,9 @@ fn body_keeps_invalid_params_and_renders_without_panicking() { fields.insert("selected".into(), json!(BLENDING)); fields.insert("p:blendingOptions".into(), bad.clone()); fields.insert("effects".into(), bad.clone()); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields)); + let mut out = ctx.run_ui(Default::default(), |ui| { + body_with_response(&mut app, ui, &mut fields, false); + }); out.textures_delta.clear(); assert_eq!(fields.get("p:blendingOptions"), Some(&bad)); } @@ -435,7 +533,9 @@ fn blending_page_renders_for_every_mode_and_odd_fields() { { let mut f = initial_fields(&layer, Some(BLENDING), 120.0); set_blending_fields(&mut f, &layer, mode); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut f)); + let mut out = ctx.run_ui(Default::default(), |ui| { + body_with_response(&mut app, ui, &mut f, false); + }); out.textures_delta.clear(); assert_eq!(f["p:blendingOptions"]["knockout"], "deep", "{mode:?}"); // Hostile dialog state (only reachable through `ui.dialog.set`) still renders. @@ -444,7 +544,9 @@ fn blending_page_renders_for_every_mode_and_odd_fields() { bo["channels"] = json!("x"); bo["blendIf"] = json!([{"thisLayer": [300, -5, "a"]}]); f.insert("channelNames".into(), json!([])); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut f)); + let mut out = ctx.run_ui(Default::default(), |ui| { + body_with_response(&mut app, ui, &mut f, false); + }); out.textures_delta.clear(); } } @@ -515,6 +617,39 @@ fn blend_if_values_stay_ordered() { assert_eq!(blend_quad(Some(&json!(["x", null]))), [0, 0, 255, 255]); } +#[test] +fn blend_if_alt_split_and_drag_behavior() { + // Case 1: Alt-drag on unsplit black handle [0, 0, 255, 255] splits the right half + let mut mode = BlendDrag::Pair { pair: 0, origin_v: 0 }; + let q = [0, 0, 255, 255]; + let q1 = step_blend_drag(&mut mode, &q, 45, true); + assert_eq!(q1, [0, 45, 255, 255], "Alt-drag right must split black triangle into [0, 45]"); + + // Case 2: Moving the split right half further to 70 + let q2 = step_blend_drag(&mut mode, &q1, 70, false); + assert_eq!(q2, [0, 70, 255, 255]); + + // Case 3: Dragging the split half back to 0 merges the handle + let q3 = step_blend_drag(&mut mode, &q2, 0, false); + assert_eq!(q3, [0, 0, 255, 255], "Dragging back to origin reunites the triangle"); + + // Case 4: Alt-drag on unsplit white handle [0, 0, 255, 255] splits the left half + let mut mode_w = BlendDrag::Pair { pair: 2, origin_v: 255 }; + let qw1 = step_blend_drag(&mut mode_w, &q, 200, true); + assert_eq!(qw1, [0, 0, 200, 255], "Alt-drag left must split white triangle into [200, 255]"); + + // Case 5: Dragging without Alt moves both halves together + let mut mode_solid = BlendDrag::Pair { pair: 0, origin_v: 0 }; + let qs1 = step_blend_drag(&mut mode_solid, &q, 35, false); + assert_eq!(qs1, [35, 35, 255, 255], "Drag without Alt moves solid handle together"); + + // Case 6: Clamping prevents black handle from crossing white handle + let q_close = [0, 100, 150, 255]; + let mut mode_single = BlendDrag::Single(1); + let q_clamped = step_blend_drag(&mut mode_single, &q_close, 180, false); + assert_eq!(q_clamped, [0, 150, 150, 255], "Black max cannot exceed white min"); +} + #[test] fn contour_picker_and_editor_edit_the_effect_curve() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index 29536064a5..332dcacb9a 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -674,17 +674,17 @@ fn brush_circle_at(resize: Option<(Pos2, f32, f32)>, hover: Option) -> Opt /// Alt+right-drag, and Control+Alt-drag, change the Liquify brush instead of painting (#4702). fn brush_resize_gesture(mods: egui::Modifiers, secondary: bool) -> bool { - mods.alt && (secondary || mods.ctrl) + if secondary { crate::brush_resize::is_right_gesture(mods) } else { crate::brush_resize::is_gesture(mods) } } /// Horizontal motion sets the diameter (the circle's edge follows the pointer). Vertical motion /// sets density, Liquify's edge falloff, over the same 200 px travel the canvas uses for hardness. -fn resized_brush(start_size: f32, start_density: f32, dx: f32, dy: f32) -> (f32, f32) { - let dx = if dx.is_finite() { dx } else { 0.0 }; - let dy = if dy.is_finite() { dy } else { 0.0 }; - let size = (start_size + dx).round().clamp(1.0, 15000.0); - let density = (start_density + dy * 100.0 / crate::brush_resize::HARDNESS_TRAVEL).clamp(0.0, 100.0); - (size, (density * 10.0).round() / 10.0) +fn resized_brush(start_size: f32, start_density: f32, dx: f32, dy: f32, zoom: f32) -> (f32, f32) { + // Liquify stores density as 0–100; the shared brush gesture works on normalized hardness. + // Use the same zoom-corrected screen movement and size limits as the main canvas. + let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; + let (size, density) = crate::brush_resize::resized((start_size, start_density / 100.0), f64::from(dx / zoom), f64::from(dy / zoom), zoom); + (size, (density * 100.0).round()) } /// Pointer in document coordinates (from the preview or the control channel). Alt at @@ -794,7 +794,8 @@ fn tool_icon(t: LiquifyTool) -> &'static str { LiquifyTool::Reconstruct => "brush-cleaning", LiquifyTool::Smooth => "droplet", LiquifyTool::TwirlCw => "rotate-cw", - LiquifyTool::TwirlCcw => "undo-2", + // Twirl Clockwise's arrow mirrored: `undo-2` read as Undo (#9547). + LiquifyTool::TwirlCcw => "rotate-ccw", LiquifyTool::Pucker => "scan", LiquifyTool::Bloat => "maximize-2", LiquifyTool::PushLeft => "chevrons-left", @@ -1152,9 +1153,27 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // started, so only its size changes (#7884). if let Some(hp) = brush_circle_at(d.brush_resize, resp.hover_pos()) { if d.opts.tool != LiquifyTool::LassoMask { + let center = d.brush_resize.map_or(hp, |(anchor, _, _)| anchor); let r = d.opts.size * 0.5 * d.zoom; - clip.circle_stroke(hp, r, Stroke::new(1.5, Color32::BLACK)); - clip.circle_stroke(hp, r, Stroke::new(0.75, Color32::WHITE)); + if d.brush_resize.is_some() { + crate::brush_resize::liquify_tip_preview( + &clip, + center, + r, + d.opts.density / 100.0, + Color32::from_rgba_unmultiplied(t.accent.r(), t.accent.g(), t.accent.b(), 110), + ); + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + crate::canvas::draw_readout( + ui.ctx(), + "liquify-brush-resize-readout", + hp, + [tl!("Diameter:"), tl!("Density:")], + [format!("{} px", d.opts.size.round() as i64), format!("{}%", d.opts.density.round() as i64)], + ); + } + clip.circle_stroke(center, r, Stroke::new(1.5, Color32::BLACK)); + clip.circle_stroke(center, r, Stroke::new(0.75, Color32::WHITE)); } d.hover = Some(to_doc(d, area, hp)); } @@ -1175,13 +1194,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } if let (Some((anchor, size0, dens0)), Some(p)) = (d.brush_resize, resp.interact_pointer_pos()) { let delta = p - anchor; - let (size, density) = resized_brush(size0, dens0, delta.x, delta.y); + let (size, density) = resized_brush(size0, dens0, delta.x, delta.y, d.zoom); d.opts.size = size; d.opts.density = density; } if resp.drag_stopped() || !ui.input(|i| i.pointer.any_down()) { d.brush_resize = None; } + ctx.request_repaint(); } else if pan && resp.dragged() { let dl = resp.drag_delta(); d.center = [d.center[0] - f64::from(dl.x / d.zoom), d.center[1] - f64::from(dl.y / d.zoom)]; diff --git a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs index 9b50c50677..777e090f8a 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -15,10 +15,13 @@ fn alt_right_drag_resizes_the_liquify_brush_and_does_not_paint() { assert!(brush_resize_gesture(egui::Modifiers::CTRL | egui::Modifiers::ALT, false)); assert!(!brush_resize_gesture(egui::Modifiers::ALT, false), "Alt+left stays the tool's opposite"); assert!(!brush_resize_gesture(egui::Modifiers::NONE, true)); - let (size, density) = resized_brush(40.0, 50.0, 25.0, crate::brush_resize::HARDNESS_TRAVEL); - assert_eq!((size, density), (65.0, 100.0)); - let (size, density) = resized_brush(40.0, 50.0, -100.0, 0.0); + let (size, density) = resized_brush(40.0, 50.0, 25.0, crate::brush_resize::HARDNESS_TRAVEL, 1.0); + assert_eq!((size, density), (90.0, 100.0), "native brush movement grows the radius by screen pixels"); + let (size, density) = resized_brush(40.0, 50.0, -100.0, 0.0, 1.0); assert_eq!((size, density), (1.0, 50.0)); + // Screen travel changes density identically at different preview zoom levels. + assert_eq!(resized_brush(40.0, 50.0, 25.0, 100.0, 2.0).1, 100.0); + assert_eq!(resized_brush(40.0, 50.0, 0.0, -100.0, 1.0).1, 0.0); } fn app_with_layer() -> PhotocraftApp { @@ -153,6 +156,19 @@ fn brush_settings_are_remembered_between_uses() { /// Follow-up to #1494 / #1484: Alt is captured at stroke-down and stays recorded /// through undo, redo and deterministic Liquify field reconstruction. +/// #9547: Twirl Counterclockwise draws Twirl Clockwise's arrow mirrored, not the Undo arrow, +/// and every Liquify tool's icon exists. +#[test] +fn twirl_counterclockwise_has_its_own_mirrored_icon() { + assert_eq!(tool_icon(LiquifyTool::TwirlCcw), "rotate-ccw"); + let svg = |name: &str| crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).map(|(_, b)| String::from_utf8_lossy(b).into_owned()); + let (cw, ccw) = (svg("rotate-cw").unwrap(), svg("rotate-ccw").expect("the rotate-ccw icon")); + assert!(ccw.contains("M3 12a9 9 0 1 0 9-9") && cw.contains("M21 12a9 9 0 1 1-9-9"), "mirror images"); + for t in [LiquifyTool::ForwardWarp, LiquifyTool::TwirlCw, LiquifyTool::TwirlCcw, LiquifyTool::Pucker, LiquifyTool::Bloat] { + assert!(svg(tool_icon(t)).is_some(), "{t:?}: {}", tool_icon(t)); + } +} + #[test] fn alt_reversed_twirl_survives_replay_undo_and_redo() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/dialogs/pattern_fill_ui.rs b/crates/ui-egui/src/dialogs/pattern_fill_ui.rs index 9404bf6b54..76e8e47620 100644 --- a/crates/ui-egui/src/dialogs/pattern_fill_ui.rs +++ b/crates/ui-egui/src/dialogs/pattern_fill_ui.rs @@ -65,8 +65,8 @@ pub(crate) fn open_new(app: &mut PhotocraftApp) -> Result { return Err(why); } let st = app.session.active().ok_or("no document open")?; - let pattern = photocraft_engine::pattern_cmds::resolve(&app.session, "").ok_or("no patterns")?; - let values = json!({"pattern": pattern.id, "scale": 100.0, "angle": 0.0, "link": true, "phase": [0.0, 0.0]}); + let pattern = photocraft_engine::pattern_cmds::resolve_id(&app.session, "").ok_or("no patterns")?; + let values = json!({"pattern": pattern, "scale": 100.0, "angle": 0.0, "link": true, "phase": [0.0, 0.0]}); let f = fields(cmds::CREATE, json!({"document": st.doc.id.0}), values); Ok(app.ui.open_dialog(crate::state::DialogKind::Command, f)) } diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index 2210058b54..faa4021ab1 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -692,7 +692,9 @@ fn ok_after_a_document_switch_changes_neither_document() { ui(&mut app, json!({"stroke": {"points": [[120.0, 50.0], [130.0, 50.0]]}})); let before = (fingerprint(&app, 0), fingerprint(&app, 1)); let switched = call(&mut app, "engine.execute", json!({"command": "document.activate", "params": {"document": 1}})); - assert_eq!(app.session.active_index(), Some(1), "{switched}"); + assert_eq!(switched["ok"], false, "external edits respect the modal gate"); + assert_eq!(app.session.active_index(), Some(0)); + assert!(app.session.set_active(1), "simulate a trusted native target change before the next frame"); let r = call(&mut app, "ui.menu.invoke", json!({"command": "select.selectAndMask", "params": {"ui": {"commit": true}}})); assert!(r.get("error").is_some(), "the stale OK is refused: {r}"); assert_eq!((fingerprint(&app, 0), fingerprint(&app, 1)), before, "neither document changed"); @@ -732,7 +734,9 @@ fn ok_after_a_layer_switch_leaves_the_new_layer_alone() { open(&mut app).unwrap(); ui(&mut app, json!({"output": "layerMask"})); let revision = app.session.active().unwrap().revision; - call(&mut app, "engine.execute", json!({"command": "layer.select", "params": {"layer": other.0}})); + let blocked = call(&mut app, "engine.execute", json!({"command": "layer.select", "params": {"layer": other.0}})); + assert_eq!(blocked["ok"], false, "external edits respect the modal gate"); + app.session.execute("layer.select", json!({"layer":other.0})).unwrap(); let revision_after_select = app.session.active().unwrap().revision; let r = call(&mut app, "ui.menu.invoke", json!({"command": "select.selectAndMask", "params": {"ui": {"commit": true}}})); assert!(r.get("error").is_some(), "the stale OK is refused: {r}"); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 5635b56ead..829e59e99e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -219,12 +219,31 @@ fn layer_style_title_gutters_can_start_drags() { } } +/// #9515: Bevel & Emboss is taller than a small window (1435 × 858, the reporter's): its page +/// scrolls, so OK and Cancel stay on screen. +#[test] +fn layer_style_buttons_stay_on_a_short_window() { + use egui_kittest::{Harness, kittest::Queryable}; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", serde_json::json!({})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1435.0, 858.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + crate::layer_style::open(h.state_mut(), Some("bevelEmboss")).unwrap(); + h.run_steps(4); + for label in ["OK", "Cancel"] { + let r = h.get_by_label(label).rect(); + assert!(r.bottom() <= 858.0, "{label} is off the window: {r:?}"); + } +} + #[test] fn dragging_the_title_bar_moves_the_dialog() { use egui_kittest::{Harness, kittest::Queryable}; let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 1100.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); harness.state_mut().ui.open_dialog(DialogKind::LayerStyle, serde_json::Map::new()); harness.run_steps(3); @@ -247,6 +266,21 @@ fn dragging_the_title_bar_moves_the_dialog() { assert_eq!(harness.state().ui.dialogs.len(), 1, "dragging must not close the dialog"); } +/// Layer Style open on Bevel & Emboss (its tallest page) for a pixel layer. +fn layer_style_on_bevel(size: egui::Vec2) -> egui_kittest::Harness<'static, PhotocraftApp> { + use egui_kittest::kittest::Queryable; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + crate::layer_style::open(h.state_mut(), Some("bevelEmboss")).expect("Layer Style opens"); + h.run_steps(4); + assert!(h.query_by_label("Gloss Contour").is_some(), "the Bevel & Emboss page is showing"); + h +} + /// #4872: an alert (Error, About) closes with ↩ as with OK, but not on the ↩ that raised it. #[test] fn enter_closes_an_alert_but_not_the_enter_that_opened_it() { @@ -273,6 +307,97 @@ fn enter_closes_an_alert_but_not_the_enter_that_opened_it() { assert!(h.state().ui.dialogs.is_empty(), "Esc too"); } +/// The bin under the effect list deletes the selected effect from the dialog. +#[test] +fn layer_style_bin_deletes_the_selected_effect() { + use egui_kittest::kittest::Queryable; + + let mut h = layer_style_on_bevel(egui::vec2(1400.0, 900.0)); + let effects = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().ui.dialogs[0].fields["effects"].as_array().map_or(0, Vec::len); + assert_eq!(effects(&h), 1); + h.get_by_label("Delete effect").click(); + h.run_steps(3); + assert_eq!(effects(&h), 0, "Bevel & Emboss is gone from the list"); + assert_eq!(h.state().ui.dialogs.len(), 1, "the dialog stays open"); +} + +/// The right-hand column's OK applies the style and Cancel drops it; Enter is OK. +#[test] +fn layer_style_ok_cancel_and_enter() { + let bevels = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + layer.effects.items.iter().filter(|e| matches!(e, photocraft_doc::Effect::BevelEmboss { .. })).count() + }; + for (how, applied) in [("OK", 1), ("Cancel", 0), ("Enter", 1)] { + use egui_kittest::kittest::Queryable; + + let mut h = layer_style_on_bevel(egui::vec2(1400.0, 900.0)); + if how == "Enter" { + h.key_press(egui::Key::Enter); + } else { + h.get_by_label(how).click(); + } + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "{how} closes the dialog"); + assert_eq!(bevels(&h), applied, "{how}"); + } +} + +/// On a short screen Layer Style fits, its page scrolling, so OK and Cancel stay reachable +/// (the Bevel & Emboss page used to push them off the bottom). +#[test] +fn layer_style_fits_a_short_screen() { + use egui_kittest::kittest::Queryable; + + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1366.0, 640.0)); + let h = layer_style_on_bevel(screen.size()); + assert!(screen.contains_rect(frame(&h)), "{:?} fits on {screen:?}", frame(&h)); + for button in ["OK", "Cancel"] { + assert!(screen.contains_rect(h.get_by_label(button).rect()), "{button} is on screen"); + } +} + +/// Layer Style is laid out like Photoshop's: wide and short, the effect list on the left, the +/// page in the middle and OK, Cancel, New Style…, Preview in a column on the right. +#[test] +fn layer_style_is_laid_out_like_photoshops() { + use egui_kittest::kittest::Queryable; + + let h = layer_style_on_bevel(egui::vec2(1400.0, 900.0)); + let at = |label: &str| h.get_by_label(label).rect(); + let frame = frame(&h); + assert!(frame.width() > frame.height() * 1.3, "wide and short: {:?}", frame.size()); + // The list's rows are painted; its bar's fx button marks the column. + let (list, page) = (at("Add a layer style"), at("Depth")); + let [ok, cancel, new_style, preview] = ["OK", "Cancel", "New Style…", "Preview"].map(at); + assert!(list.right() < page.left(), "the list is left of the page"); + for (name, r) in [("OK", ok), ("Cancel", cancel), ("New Style…", new_style), ("Preview", preview)] { + assert!(r.left() > page.right(), "{name} is right of the page"); + } + assert!(ok.top() < cancel.top() && cancel.top() < new_style.top() && new_style.top() < preview.top(), "top to bottom"); +} + +/// Layer Style keeps one size on every page, as Photoshop's does (it used to grow and shrink +/// with each page), and has no resize grip: Photoshop's isn't resizable either. +#[test] +fn layer_style_keeps_one_size_on_every_page() { + let mut h = layer_style_on_bevel(egui::vec2(1400.0, 900.0)); + let size = frame(&h).size(); + let dialog = h.state().ui.dialogs[0].id; + for page in ["blendingOptions", "styles"] { + h.state_mut().ui.dialog_mut(dialog).expect("still open").fields.insert("selected".into(), json!(page)); + h.run_steps(3); + assert_eq!(frame(&h).size(), size, "{page}"); + } + let grip = egui::Id::unique(("dialog", dialog)).with("resize").with("__resize_corner"); + assert!(h.ctx.read_response(grip).is_none(), "no resize grip"); +} + +fn frame(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> egui::Rect { + rects(&h.ctx).first().copied().expect("the dialog is drawn") +} + fn dialog_harness(size: egui::Vec2, command: &str) -> egui_kittest::Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); @@ -429,3 +554,89 @@ fn fit_image_is_as_narrow_as_its_content() { assert!(window.contains_rect(node.rect()), "{label} inside the window"); } } + +#[test] +fn german_color_picker_fits_its_actions_and_translates_the_title() { + use egui_kittest::{Harness, kittest::Queryable}; + let lang = crate::i18n::Lang::from_pref("de"); + let text = |key| crate::i18n::with_language(lang, || crate::i18n::t(key).to_owned()); + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = + Harness::builder().with_size(egui::vec2(760.0, 480.0)).build_ui_state(move |ui, app| crate::i18n::with_language(lang, || show(app, ui.ctx())), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + crate::color_picker_ui::open(h.state_mut(), "foreground"); + h.run_steps(4); + let title = h.get_by_label("Farbwähler (Vordergrundfarbe)").rect(); + let swatch = h.get_by_label(&text("Click to restore the current colour")).rect(); + let frame = rects(&h.ctx)[0]; + for label in ["OK", "Cancel", "Add to Swatches"] { + let r = h.get_by_label(&text(label)).rect(); + assert!(r.left() > swatch.right(), "{label} must stay beside the swatches: {r:?}, {swatch:?}"); + assert!((r.right() - title.right()).abs() < 1.0, "{label} aligns with the title edge"); + } + assert!(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(760.0, 480.0)).contains_rect(frame), "{frame:?}"); +} + +#[test] +fn file_info_multiline_fields_keep_enter_and_cancel_discards_edits() { + use egui_kittest::kittest::Queryable; + + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.fileInfo", json!({})).unwrap(); + h.run_steps(4); + use egui::accesskit::Role; + let fields = [ + (Role::TextInput, "Document Title"), + (Role::TextInput, "Author"), + (Role::TextInput, "Author title"), + (Role::MultilineTextInput, "Description"), + (Role::MultilineTextInput, "Keywords"), + (Role::ComboBox, "Copyright status"), + (Role::MultilineTextInput, "Copyright Notice"), + (Role::TextInput, "Copyright Info URL"), + ]; + for pair in fields.windows(2) { + assert!( + h.get_by_role_and_label(pair[0].0, pair[0].1).rect().center().y < h.get_by_role_and_label(pair[1].0, pair[1].1).rect().center().y, + "field order: {pair:?}" + ); + } + for (label, key) in [("Description", "description"), ("Keywords", "keywords"), ("Copyright Notice", "copyright")] { + h.get_by_role_and_label(Role::MultilineTextInput, label).click(); + h.run_steps(1); + h.event(egui::Event::Text("First".into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(1); + h.event(egui::Event::Text("Second".into())); + h.run_steps(1); + let dialog = h.state().ui.dialogs.last().expect("Enter edits the field, not OK"); + assert_eq!(dialog.fields[key], "First\nSecond", "{label}"); + } + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(h.state_mut().run("file.fileInfo", json!({})).unwrap()["description"], ""); + }); +} + +#[test] +fn file_info_keeps_multiline_metadata_on_confirm_and_reopen() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let ctx = egui::Context::default(); + let id = crate::menus::invoke(&mut app, &ctx, "file.fileInfo", json!({})).unwrap()["dialog"].as_u64().unwrap(); + for key in ["description", "copyright"] { + app.ui.dialog_mut(id).unwrap().fields.insert(key.into(), json!("First line\nSecond line")); + } + confirm(&mut app, id).unwrap(); + let id = crate::menus::invoke(&mut app, &ctx, "file.fileInfo", json!({})).unwrap()["dialog"].as_u64().unwrap(); + for key in ["description", "copyright"] { + assert_eq!(app.ui.dialog_mut(id).unwrap().fields[key], "First line\nSecond line"); + } +} diff --git a/crates/ui-egui/src/dock/tests.rs b/crates/ui-egui/src/dock/tests.rs index c03c067f6d..d3884e20fa 100644 --- a/crates/ui-egui/src/dock/tests.rs +++ b/crates/ui-egui/src/dock/tests.rs @@ -109,7 +109,9 @@ fn switching_layer_kinds_keeps_the_layers_panel_still() { /// A group height dragged in the dock is part of the UI state and the remembered layout. #[test] fn dragging_the_splitter_resizes_and_survives_a_ui_state_round_trip() { - let (app, _, _) = app_with_layers(); + let (mut app, _, _) = app_with_layers(); + // CodeRabbit on #9606: the Color panel's options ride the same frames and preferences. + app.ui.color_panel.mode = crate::state::ColorPanelMode::HsbSliders; let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium); let props = rect_of(&h, Group::Properties); let color = rect_of(&h, Group::Color); @@ -137,6 +139,8 @@ fn dragging_the_splitter_resizes_and_survives_a_ui_state_round_trip() { restore(&mut app3); assert!(app3.ui.docking.is_some()); assert_eq!(app3.ui.docking.as_ref().map(|w| &w.layout), h.state().ui.docking.as_ref().map(|w| &w.layout)); + crate::color_panel_ui::restore(&mut app3); + assert_eq!(app3.ui.color_panel.mode, crate::state::ColorPanelMode::HsbSliders, "the Color panel's mode too"); // …unless Remember Workspace Changes is off. let mut s3 = photocraft_engine::Session::new(); s3.load_prefs_json(&prefs).unwrap(); diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index ef9613057a..c0323da9a1 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -713,8 +713,17 @@ fn views_and_windows_stay_with_their_documents() { for (i, v) in app.ui.views.iter_mut().enumerate() { v.zoom = i as f32 + 1.0; } - app.ui.windows = - (0..4).map(|document| crate::state::DocWindow { id: document as u64, document, view: Default::default(), open: true, position: None }).collect(); + app.ui.windows = (0..4) + .map(|document| crate::state::DocWindow { + id: document as u64, + document, + view: Default::default(), + open: true, + floating: false, + focused: false, + position: None, + }) + .collect(); let zooms = |app: &PhotocraftApp| app.ui.views.iter().map(|v| v.zoom).collect::>(); let windows = |app: &PhotocraftApp| app.ui.windows.iter().map(|w| (w.id, w.document)).collect::>(); assert_eq!(app.run("document.move", json!({"document": 0, "to": 3})).unwrap(), json!({"document": 3})); diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 2a5ef902fb..ffb73afb88 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -3550,3 +3550,8 @@ curves Smooth تنعيم Update and Restart التحديث وإعادة التشغيل X X Y Y + +# Select and Mask target ownership diagnostics (#8896 integration) + + The path was kept as the Work Path تم الاحتفاظ بالمسار كمسار عمل + The path was discarded تم تجاهل المسار diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 97a77d2dab..b095d15596 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -20,18 +20,142 @@ # dialog commands is kept. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Možnosti masky… - Layer Mask Display Options… Možnosti zobrazení masky vrstvy… # Channel Options and New Spot Channel (#3761) - Channel Color Barva kanálu - Color Indicates: Barva označuje: - Solidity: Plnost: - Ink Characteristics Vlastnosti inkoustu # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Command-id overrides: the same English label reads differently in Czech in these menus. + + +# Dialogs and panels + +# Layers-panel trash confirmation + + +# Tool names, brush and style option tables + +# Templates with placeholders + +# Preferences (labels are generated from the setting names) + +# Added with the rebase onto the dock / brush picker work + +# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). +# Gradient Editor window, opened from the options bar's gradient swatch. +# Rendering mode and recovery +# Camera Raw: contextual controls and window title + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors + +# Dynamic labels the tl! literal scanner cannot see: filter and Filter Gallery parameter names and +# choices (humanized from their keys), Camera Raw controls, render filters (Flame, Picture Frame, Tree), +# measurement columns, file info fields and the macOS application menu. Translated the same way as +# above, from the plain meaning of the English label. +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Canvas context menus, Channels panel menu, Layer Style blending page (labels rendered through a variable). + +# Status messages and notices + +# Menus, tooltips and hardware information + +# Composed labels and Navigator zoom context +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# Labels the UI looks up through a variable (tool, glyph-group, Liquify and warp names, command +# parameters and choices humanized from their keys, history steps and contextual +# Camera Raw / layer labels) that other catalogs already covered. Translated the same way as +# above, from the plain meaning of the English label. + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) +# Smart Filter row actions (#1265) + + Mask Options… Možnosti masky… + Layer Mask Display Options… Možnosti zobrazení masky vrstvy… + Channel Color Barva kanálu + Color Indicates: Barva označuje: + Solidity: Plnost: + Ink Characteristics Vlastnosti inkoustu Paper Width Šířka papíru Paper Height Výška papíru Columns Sloupce @@ -51,7 +175,6 @@ 5 Columns, 3 Rows 5 sloupců, 3 řádky 8 Columns 8 sloupců 12 Columns 12 sloupců - File Soubor Edit Úpravy Image Obraz @@ -459,6 +582,7 @@ Intersect Shape Areas Průnik oblastí tvarů Exclude Overlapping Shapes Vyloučit překrývající se tvary Merge Shape Components Sloučit součásti tvaru + Path operations Operace s cestami Align Zarovnat Top Edges Horní okraje Vertical Centers Svislé středy @@ -538,7 +662,6 @@ Color Range… Rozsah barev… Focus Area… Oblast zaostření… Select and Mask… Vybrat a maskovat… -# Select and Mask dialog labels Smart Radius Chytrý poloměr Shift Edge Posunout okraj Decontaminate Dekontaminovat @@ -565,7 +688,6 @@ Blur Rozostření Blur Gallery Galerie rozostření Field Blur… Rozostření pole… -# Field Blur pins (#3373) No pin selected Není vybrán žádný špendlík Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Kliknutím do obrazu přidáte špendlík; tažením špendlík přesunete, tažením jeho prstence změníte rozostření. Delete odstraní vybraný špendlík. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Tažením úchytů na obrysu ho změníte a otočíte, čtverečkem zaoblíte rohy a body uvnitř nastavíte, kde začíná rozostření. @@ -830,15 +952,10 @@ Edits Úpravy @plural {n} item|{n} items {n} položka|{n} položky|{n} položek Auto Automaticky - -# Command-id overrides: the same English label reads differently in Czech in these menus. @id select.all Vybrat vše @id edit.stroke Obtáhnout… @id edit.transform.scale Změnit velikost @id edit.purge.undo Historie kroků zpět - - -# Dialogs and panels (print to the printer) (tisk na tiskárnu) + Add variable + Přidat proměnnou 30 frames @ 30 fps 30 snímků při 30 fps @@ -852,6 +969,9 @@ Add Layer Mask Přidat masku vrstvy Add Stop Přidat zarážku Add a layer style Přidat styl vrstvy + Move effect up Posunout efekt nahoru + Move effect down Posunout efekt dolů + Delete effect Odstranit efekt Add a mask (from the selection; {key} inverts) Přidat masku (z výběru; {key} invertuje) Add an adjustment Přidat korekci Add disk Přidat disk @@ -1076,8 +1196,6 @@ Delete current channel Odstranit aktuální kanál Delete current state Odstranit aktuální stav Delete effect layer Odstranit vrstvu efektu - -# Layers-panel trash confirmation Delete layer ‘{name}’? Smazat vrstvu „{name}“? Delete {count} layers? {names} Smazat vrstvy ({count})? {names} Delete layer? Smazat vrstvu? @@ -1086,7 +1204,6 @@ Missing delete command Chybí příkaz ke smazání Invalid delete command Neplatný příkaz ke smazání Layer deleted, but confirmation preference could not be saved: {error} Vrstva byla smazána, ale nastavení potvrzení se nepodařilo uložit: {error} - Delete layer Odstranit vrstvu Delete layer comp Odstranit kompozici vrstev Delete note Odstranit poznámku @@ -1119,7 +1236,6 @@ Dots Tečky Drag a rectangle around the object Táhněte obdélník kolem objektu Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Tažením v obraze přidáte omezení; Shift pro vodorovné/svislé; pravým kliknutím na omezení ho změníte nebo odstraníte. - Drag to move the active shape's path or the Work Path Tažením přesunete cestu aktivního tvaru nebo pracovní cestu Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Klik: vybrat bod · Tažení: přesunout bod, úchyt nebo segment · {shift}+klik: přidat · {alt}+klik: celá podcesta Draw with the Pen tool (P) or make a work path from a selection. Kreslete nástrojem pero (P) nebo vytvořte pracovní cestu z výběru. Drop an image or PSD anywhere to open it. Přetáhněte sem obrázek nebo PSD a otevře se. @@ -1643,8 +1759,6 @@ No saved presets yet. Zatím nejsou uloženy žádné předvolby. Error Chyba Command Příkaz - -# Tool names, brush and style option tables Adjustment layers have nothing to transform Korekční vrstvy nemají co transformovat Altitude Elevace Android 1080p Android 1080p @@ -1877,8 +1991,6 @@ Yellows Žluté Zoom Tool Nástroj lupa {name} Properties Vlastnosti – {name} - -# Templates with placeholders Revert “{name}” to the last saved version? Your changes will be lost. Vrátit „{name}“ k poslední uložené verzi? Vaše změny budou ztraceny. Do you want to save the changes you made to “{name}” before quitting? Chcete před ukončením uložit změny v „{name}“? Do you want to save the changes you made to “{name}” before closing? Chcete před zavřením uložit změny v „{name}“? @@ -1899,8 +2011,6 @@ @plural {n} Layer|{n} Layers {n} vrstva|{n} vrstvy|{n} vrstev @plural {n} layer|{n} layers {n} vrstva|{n} vrstvy|{n} vrstev @plural Group · {n} layer|Group · {n} layers Skupina · {n} vrstva|Skupina · {n} vrstvy|Skupina · {n} vrstev - -# Preferences (labels are generated from the setting names) Additional plugins folder Složka dalších zásuvných modulů Adobe Adobe Adobe rgb Adobe RGB @@ -2100,8 +2210,6 @@ Luminosity Světlost @plural {n} sample|{n} samples {n} vzorek|{n} vzorky|{n} vzorků {added}, {removed} subtracted {added}, odebráno: {removed} - -# Added with the rebase onto the dock / brush picker work Adjustment Preview Náhled korekce Airbrush: keeps depositing paint while the pointer rests. Airbrush: nanáší barvu i tehdy, když ukazatel stojí. Angle: Úhel: @@ -2133,8 +2241,6 @@ Brush picker Výběr štětce Erase Gumovat Right click with painting tools Pravé tlačítko s malířskými nástroji - -# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). System Info… Informace o systému… System Info Informace o systému More panels Další panely @@ -2206,7 +2312,6 @@ Align with layer Zarovnat s vrstvou Reset Alignment Obnovit zarovnání Centre the gradient (offset 0, 0) Vystředit přechod (posun 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Editor přechodů Gradient picker Výběr přechodu Save As Preset Uložit jako preset @@ -2265,7 +2370,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Mřížka: -# Rendering mode and recovery Rendering Mode Režim vykreslování Automatic (recommended) Automaticky (doporučeno) CPU / Compatibility CPU / Kompatibilita @@ -2292,7 +2396,6 @@ Tone Histogram Histogram tónů Show Selected Region Zobrazit vybranou oblast cameraRaw Light Světlo -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Filtr Camera Raw ({layer}) Camera Raw ({name}) Camera Raw ({name}) cameraRaw Red Červené @@ -2314,14 +2417,10 @@ cameraRaw Color Barvy Scale or rotate the moved area, then press {key} Změňte velikost nebo otočte přesunutou oblast a pak stiskněte {key} Now drag the selection onto another area Nyní přetáhněte výběr na jiné místo Edit Type Upravit text - - New Style… Nový styl… Style {name} saved Styl {name} uložen - Create new style (from the selected type) Vytvořit nový styl (z vybraného textu) Create new style from the selected layer Vytvořit nový styl z vybrané vrstvy - Make Default Nastavit jako výchozí Reset to Default Obnovit výchozí Full-resolution preview unavailable Náhled v plném rozlišení není dostupný @@ -2351,9 +2450,6 @@ cameraRaw Color Barvy Magnetic Lasso Tool Nástroj magnetické laso Frequency Frekvence Use tablet pressure to change pen width Měnit šířku pera přítlakem tabletu - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About O aplikaci Contributors Přispěvatelé Models Modely @@ -2385,8 +2481,6 @@ cameraRaw Color Barvy % of all commits % všech commitů Lines +/− Řádky +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR: {prs}, commity: {commits}, řádky +{added} / −{deleted} (Δ {delta}), binární soubory +{binAdded} / −{binDeleted}, {first} – {last} - -# Swatches panel Create new swatch Vytvořit nový vzorek New Swatch… Nový vzorek… New Swatch Group… Nová skupina vzorků… @@ -2396,13 +2490,10 @@ cameraRaw Color Barvy Export Swatches for Exchange… Exportovat vzorky pro výměnu… Reset Swatches Obnovit vzorky Add to Swatches Přidat do vzorníku -# Layer Style > Blending Options (Advanced Blending) Blend If: Prolnout, pokud: Channels: Kanály: Knockout Vyřazení Apply At Canvas Bounds Použít efekt na hranicích plátna - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Výběr barvy (barva textu) Color Picker ({name}) Výběr barvy ({name}) Color Picker (Fill Color) Výběr barvy (barva výplně) @@ -2419,8 +2510,6 @@ cameraRaw Color Barvy Show/Hide Panels Zobrazit/skrýt panely Could not open Nelze otevřít {path}: the path is not valid Unicode; rename the file and open it again. {path}: cesta není platný Unicode; přejmenujte soubor a otevřete jej znovu. - -# Fill dialog, layer style contours and Image Size Contents: Obsah: Custom Pattern: Vlastní vzorek: Foreground Color Barva popředí @@ -2448,7 +2537,6 @@ cameraRaw Color Barvy Rolling Slope - Descending Zvlněný svah - sestupný Rounded Steps Zaoblené stupně Sawtooth 1 Pila 1 - Red Eye Tool Nástroj červené oči Red Eye Červené oči Pupil Size Velikost zornice @@ -2456,7 +2544,6 @@ cameraRaw Color Barvy Click a red pupil to neutralize it Klepněte na červenou zornici open source otevřený zdrojový kód …and {n} more …a dalších {n} - Eyedroppers: Kapátka: Set Black Point Nastavit černý bod Set Neutral Gray Point Nastavit neutrální šedý bod @@ -2465,8 +2552,6 @@ cameraRaw Color Barvy Selection Preview: Náhled výběru: Black Matte Černý podklad White Matte Bílý podklad - -# Layer colour labels. Seafoam Mořská pěna Indigo Indigová Fuchsia Fuchsiová @@ -2487,8 +2572,6 @@ fontWeight Bold Tučná fontWeight ExtraBold Extratučná fontWeight Black Černá fontWeight Italic Kurzíva - -# Pattern Stamp tool Pattern Stamp Tool Nástroj razítko vzorku Pattern Stamp Razítko vzorku Impressionist Impresionista @@ -2496,13 +2579,9 @@ fontWeight Italic Kurzíva 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° - -# Painting symmetry presets. Dual Axis Dvojitá osa Diagonal Diagonální Transform Symmetry Transformovat symetrii - -# Eyedropper Sample Size and Sample (#1649). Point Sample Bodový vzorek 3 by 3 Average Průměr 3 × 3 5 by 5 Average Průměr 5 × 5 @@ -2514,15 +2593,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Barva na alfu… Transparency Threshold Práh průhlednosti Opacity Threshold Práh krytí PhotoCraft — Screen Color Picker PhotoCraft — Výběr barvy obrazovky - Rasterize svg groups deeper than Rasterizovat skupiny SVG hlubší než tato úroveň 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 vypne tento práh; skupiny SVG vnořené hlouběji než 100 úrovní se rastrují vždy. Rule of Thirds Pravidlo třetin @@ -2536,8 +2612,6 @@ fontWeight Italic Kurzíva Cycle Orientation Přepnout orientaci Set the overlay options for the Crop tool Nastavit volby překryvu pro nástroj Oříznutí Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+klik převzalo pracovní prostředí, které pomocí Alt+tažení přesouvá okna. Nastavte jeho klávesu pro přesun oken na Super, nebo zamkněte Alt v nabídce Okno › Modifikační klávesy. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Výběr barvy (barva stylu vrstvy) Auto Hide Notifications Automaticky skrývat oznámení Notification Duration (seconds) Trvání oznámení (sekundy) @@ -2618,7 +2692,6 @@ fontWeight Italic Kurzíva Appearance Settings… Nastavení vzhledu… Add to favorites Přidat do oblíbených Remove from favorites Odebrat z oblíbených -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data Údaje fotoaparátu cameraData Make Výrobce cameraData Model Model @@ -2629,7 +2702,6 @@ cameraData ISO Speed Citlivost ISO cameraData Focal Length Ohnisková vzdálenost cameraData Focal Length (35 mm) Ohnisková vzdálenost (35 mm) cameraData Lens Objektiv -# Shared panel docking Activate Panel Aktivovat panel Change Panel Group Změnit skupinu panelů Change Panel Layout Změnit rozložení panelů @@ -2675,7 +2747,6 @@ cameraData Lens Objektiv Snap to Origin Přichytit k počátku Search settings… Hledat nastavení… No matching settings Žádná odpovídající nastavení -# Edit › Content-Aware Fill workspace Sampling Brush Tool Nástroj štětec vzorkování Sampling Area Overlay Překrytí oblasti vzorkování Show Sampling Area Zobrazit oblast vzorkování @@ -2695,7 +2766,6 @@ cameraData Lens Objektiv Output To Výstup do Duplicate Layer Duplikovat vrstvu Contract Zúžit - Animation Options Možnosti animace Entire Document Celý dokument Filter Options Možnosti filtrování @@ -2716,8 +2786,6 @@ cameraData Lens Objektiv Add “copy” to Copied Layers and Groups Přidávat „kopie“ ke kopírovaným vrstvám a skupinám Preview on canvas when reordering layers Zobrazovat náhled na plátně při změně pořadí vrstev Show layer mask badges Zobrazovat odznaky masek vrstev - -# Smart Filter editors Blending Options ({filter}) Volby prolnutí ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Skrýt efekty vrstvy a inteligentní filtry (kliknutí s {key}: všechny vrstvy) Show the layer's effects and Smart Filters ({key}-click: all layers) Zobrazit efekty vrstvy a inteligentní filtry (kliknutí s {key}: všechny vrstvy) @@ -2725,11 +2793,6 @@ cameraData Lens Objektiv The document or Smart Filter changed. Reopen its dialog. Dokument nebo inteligentní filtr se změnil. Znovu otevřete jeho dialog. Opacity must be between 0% and 100%. Krytí musí být mezi 0% a 100%. Dissolve is approximated: it blends without Photoshop's dither. Režim Rozpustit je pouze aproximován: prolíná bez ditheringu Photoshopu. - -# Dynamic labels the tl! literal scanner cannot see: filter and Filter Gallery parameter names and -# choices (humanized from their keys), Camera Raw controls, render filters (Flame, Picture Frame, Tree), -# measurement columns, file info fields and the macOS application menu. Translated the same way as -# above, from the plain meaning of the English label. 32-bit Preview Options Možnosti 32bitového náhledu 3D 3D About {app} O aplikaci {app} @@ -3591,7 +3654,6 @@ curves Smooth Vyhladit Fix the red plane first: its corners must form a convex quad Nejprve opravte červenou rovinu: její rohy musí tvořit konvexní čtyřúhelník Alt-click a plane to set the clone source Klepnutím s Alt na rovinu nastavte zdroj klonování Too many clone strokes: apply Vanishing Point first Příliš mnoho tahů klonování: nejprve použijte Úběžník -# Select and Mask view modes (#1754) Onion Skin Cibulová slupka Marching Ants Pochodující mravenci On Black Na černé @@ -3600,7 +3662,6 @@ curves Smooth Vyhladit Show Edge Zobrazit okraj Show Original Zobrazit originál F cycles the views; hold X to see the image F přepíná zobrazení; podržením X uvidíte obraz -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Štětec pro upřesnění okraje (R) Expand Detection Area Rozšířit oblast detekce Restore Original Edge Obnovit původní okraj @@ -3608,23 +3669,17 @@ curves Smooth Vyhladit Clear Brush Strokes Vymazat tahy štětce Show rulers Zobrazit pravítka Presentation Prezentace - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Kliknutím umístíte · Alt-kliknutím nebo přetažením mimo plátno odeberete No document open Není otevřen žádný dokument {n} of {max} sample points {n} z {max} bodů měření - -# History panel menu (#2966) Step Forward Krok vpřed Clear History Vymazat historii New Snapshot… Nový snímek… History Options… Volby historie… -# History panel › History Options… (#2966) Allow Non-Linear History Povolit nelineární historii Make Layer Visibility Changes Undoable Umožnit vrácení změn viditelnosti vrstev Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Táhněte (laso) nebo klikejte na body (mnohoúhelník) · {add} přidat · {sub} odečíst The current gradient (pick one in Window › Gradients) Aktuální přechod (vyberte v Okno › Přechody) -# Canvas context menus, Channels panel menu, Layer Style blending page (labels rendered through a variable). Make Work Path… Vytvořit pracovní cestu… Create Vector Mask Vytvořit vektorovou masku Make Selection… Vytvořit výběr… @@ -3669,10 +3724,8 @@ curves Smooth Vyhladit Layer Mask Hides Effects Maska vrstvy skrývá efekty Vector Mask Hides Effects Vektorová maska skrývá efekty General Blending Obecné prolnutí - This Layer: Tato vrstva: + Current Layer: Aktuální vrstva: Underlying Layer: Podkladová vrstva: - -# Status messages and notices Nothing to paste: the clipboard holds no image Není co vložit: schránka neobsahuje obraz Preferences saved Předvolby uloženy Invalid panel layout; restored the default dock Neplatné rozložení panelů; obnoveno výchozí ukotvení @@ -3715,8 +3768,6 @@ curves Smooth Vyhladit GPU error; using the CPU renderer. Chyba GPU; používá se vykreslování pomocí CPU. @plural {what} with {n} warning|{what} with {n} warnings {what} ({n} upozornění)|{what} ({n} upozornění)|{what} ({n} upozornění) Couldn't open {name}: {error} Soubor {name} se nepodařilo otevřít: {error} - -# Menus, tooltips and hardware information Toggle the Brush Settings panel Zobrazit/skrýt panel Nastavení štětce New Brush Preset Nové přednastavení štětce Grid view Zobrazení mřížky @@ -3770,8 +3821,6 @@ curves Smooth Vyhladit Monitor profile on {display}: {profile} Profil monitoru {display}: {profile} manual ruční fallback náhradní - -# Composed labels and Navigator zoom context Importing {what} from {file}… Importují se {what} ze souboru {file}… brushes štětce gradients přechody @@ -3794,7 +3843,6 @@ navigator Zoom Zvětšení @plural {n} step|{n} steps {n} krok|{n} kroky|{n} kroků {shortcut} assigned. Zkratka {shortcut} přiřazena. {shortcut} is already in use by {commands} and will be removed from it when you click OK. Zkratka {shortcut} se již používá pro {commands}. Kliknutím na OK původní přiřazení zrušíte. -# Print dialog (#2697) Emulsion Down Emulze dolů Functions Funkce Print Resolution: Rozlišení tisku: @@ -3806,7 +3854,6 @@ navigator Zoom Zvětšení Apply mask to layer before removing? Použít masku na vrstvu před odstraněním? The layer or its mask changed. Drag the mask onto the Trash again. Vrstva nebo její maska se změnila. Přetáhněte masku do koše znovu. Delete the vector mask? Odstranit vektorovou masku? -# View › Guides › New Guide… › Color Light Blue Světle modrá Light Red Světle červená Medium Blue Středně modrá @@ -3826,8 +3873,6 @@ navigator Zoom Zvětšení Clear Brush Controls Obnovit ovládací prvky stopy Reset All Locked Settings Obnovit všechna zamknutá nastavení Copy Texture to Other Tools Kopírovat texturu do jiných nástrojů - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Načíst akce… Save Actions… Uložit akce… New Action… Nová akce… @@ -3839,10 +3884,8 @@ navigator Zoom Zvětšení @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} krok zatím nemá v PhotoCraftu obdobu|{n} kroky zatím nemají v PhotoCraftu obdobu|{n} kroků zatím nemá v PhotoCraftu obdobu @plural Saved {n} action to {file}|Saved {n} actions to {file} Uložena {n} akce do souboru {file}|Uloženy {n} akce do souboru {file}|Uloženo {n} akcí do souboru {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Vynechán {n} krok bez obdoby v Photoshopu|Vynechány {n} kroky bez obdoby v Photoshopu|Vynecháno {n} kroků bez obdoby v Photoshopu - File Naming Pojmenování souborů Starting serial Počáteční pořadové číslo -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Vložit zastavení… Save Set… Uložit sadu… Message: Zpráva: @@ -3853,11 +3896,8 @@ navigator Zoom Zvětšení Step {step} is waiting for its dialog Krok {step} čeká na svůj dialog @plural {n} action|{n} actions {n} akce|{n} akce|{n} akcí Background (Default) Pozadí (výchozí) -# Batch / Image Processor Include All Subfolders Zahrnout všechny podsložky Auto Add/Delete Automaticky přidat/odstranit - -# Native Windows printing qualification 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… @@ -3902,7 +3942,6 @@ navigator Zoom Zvětšení Could not write {name}: {error} Nelze zapsat {name}: {error} Kept {name}: written by another application Soubor {name} ponechán: zapsala ho jiná aplikace Shadow Tint Odstín stínů -# PhotoCraft release checks. Check for Updates… Zkontrolovat aktualizace… PhotoCraft Updates Aktualizace PhotoCraft Checking for updates… Kontrola aktualizací… @@ -3915,35 +3954,27 @@ navigator Zoom Zvětšení Automatically Check for Updates Automaticky kontrolovat aktualizace Installed version: {version} Nainstalovaná verze: {version} PhotoCraft {version} is available. PhotoCraft {version} je k dispozici. -# History panel › History Brush source (#2966) Paints from the History panel's source state Maluje ze zdrojového stavu panelu Historie Sets the source for the history brush Nastaví zdroj pro štětec historie -# Bevel & Emboss shading controls. Highlight Mode Režim světel Highlight Color Barva světel Highlight Opacity Krytí světel Shadow Mode Režim stínů Shadow Color Barva stínů Shadow Opacity Krytí stínů -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Použít vložený profil ({profile}) Convert to the working space ({profile}) Převést do pracovního prostoru barev ({profile}) Remember this choice for future images Zapamatovat si tuto volbu pro další obrázky Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Dotaz znovu zapnete volbou „Ptát se při nesouladu profilů“ v nabídce Úpravy › Nastavení barev. Button Mode Režim tlačítka Button Mode On Režim tlačítka zapnutý - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Ztmavit rozhraní Lighten Interface Zesvětlit rozhraní -# Bevel & Emboss Technique. Technique Technika Chisel Hard Tvrdé tesání Chisel Soft Měkké tesání Open color-less EXR as ACEScg Otevřít EXR bez údaje o barevném prostoru jako ACEScg Do not append "copy" to filename when saving a copy Nepřidávat „copy“ k názvu souboru při ukládání kopie - -# View › Guides › right-click a guide Edit Selected Guides Upravit vybraná vodítka Clear Selected Guides Vymazat vybraná vodítka Bicubic Automatic Bikubická automatická @@ -3968,8 +3999,6 @@ navigator Zoom Zvětšení set name název sady {set} (modified) {set} (změněno) Show file name in title Zobrazit název souboru v titulu - -# Image › Mode › Bitmap (#5559) 50% Threshold 50% práh Pattern Dither Rozptyl se vzorkem Diffusion Dither Difuzní rozptyl @@ -3987,11 +4016,9 @@ navigator Zoom Zvětšení Undo Changes Vrátit změny {shortcut} is reserved by the system and can't be assigned. {shortcut} je vyhrazena systémem a nelze ji přiřadit. Low-Latency Drawing (vsync off, applies at next launch) Kreslení s nízkou latencí (bez vertikální synchronizace, platí po dalším spuštění) -# Free Transform: a new layer while the box is open (#5859) Reference point location Umístění referenčního bodu Free Transform is still being applied; try again when it has finished. Volná transformace se stále použije; zkuste to znovu, až skončí. The transform couldn't be applied. Transformaci nelze použít. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Vrstvy potřebují {needed} paměti GPU; rozpočet jim ponechává {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. V Předvolbách › Výkon nastavte Paměť GPU na tolik, kolik vaše grafická karta pojme, nejvýše 3/8 její paměti. Automaticky se řídí Využitím paměti, v rámci čtvrtiny paměti tohoto počítače a 3/8 paměti karty, a u karty se známou pamětí do ní dokument nezapočítává. Dokud se nevejdou, stavový řádek ukazuje Paměť GPU je plná. GPU Memory Full Paměť GPU je plná @@ -4017,11 +4044,6 @@ navigator Zoom Zvětšení The fastest and the softest, with colour 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}“. - -# Labels the UI looks up through a variable (tool, glyph-group, Liquify and warp names, command -# parameters and choices humanized from their keys, history steps and contextual -# Camera Raw / layer labels) that other catalogs already covered. Translated the same way as -# above, from the plain meaning of the English label. Export As: {name} Exportovat jako: {name} Tool Nástroj Arc Lower Oblouk dole @@ -4149,8 +4171,6 @@ navigator Zoom Zvětšení layers Fill Krytí výplně layers Fill: Krytí výplně: cameraRaw Dehaze Odstranění oparu - Move Up Přesunout nahoru - Move Down Přesunout dolů Previous Brush Předchozí štětec Next Brush Další štětec First Brush První štětec @@ -4165,26 +4185,17 @@ cameraRaw Dehaze Odstranění oparu Use Použít In Front Vpředu Behind Vzadu - -# DDS Options (#1327) DDS Options Možnosti DDS Generate Mipmaps Generovat mipmapy - -# Color Table (.act) dialog There is no color table to save. Neexistuje žádná tabulka barev k uložení. @plural Saved {n} color to {file}|Saved {n} colors to {file} Uložena {n} barva do {file}|Uloženy {n} barvy do {file}|Uloženo {n} barev do {file} - -# Graphics Adapter preference (#1885) GPU adapter Adaptér GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Importovat styly… Export Selected Styles… Exportovat vybrané styly… Export Styles… Exportovat styly… {file} is not a style library (.asl) {file} není knihovna stylů (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Importován {n} styl ze souboru {file}|Importovány {n} styly ze souboru {file}|Importováno {n} stylů ze souboru {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Exportován {n} styl do souboru {file}|Exportovány {n} styly do souboru {file}|Exportováno {n} stylů do souboru {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Nejprve potvrďte nebo zrušte otevřený dialog kroku akce Pro Medium Gray Pro (středně šedý) Solarized Solarized @@ -4193,28 +4204,11 @@ cameraRaw Dehaze Odstranění oparu Pro Light Pro (světlý) Resize Windows to Fit Přizpůsobit velikost oken EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Automatický směr odstavce Left-to-right paragraph direction Směr odstavce zleva doprava Right-to-left paragraph direction Směr odstavce zprava doleva Not rendered: this adjustment ({key}) is kept as imported. Nevykresleno: tato úprava ({key}) je ponechána tak, jak byla importována. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Podle barev - Decontaminate Colors Dekontaminovat barvy - Edge Detection Detekce okraje - Global Refinements Globální upřesnění - High Quality Preview Náhled ve vysoké kvalitě - Object Aware Podle objektů - Real-Time Refinement Upřesnění v reálném čase - Refine Edge Brush Tool Nástroj štětec pro upřesnění okraje - Refine Hair Upřesnit vlasy - Refine Mode Režim upřesnění - Remember Settings Zapamatovat nastavení - View Mode Režim zobrazení - Object Aware needs a segmentation model, which isn't available yet Režim Podle objektů vyžaduje segmentační model, který zatím není k dispozici - Refine Hair needs hair detection, which isn't available yet Upřesnit vlasy vyžaduje detekci vlasů, která zatím není k dispozici -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Krychle odstínu Brightness Cube Krychle jasu Color Wheel Barevné kolo @@ -4231,9 +4225,8 @@ cameraRaw Dehaze Odstranění oparu Grayscale Ramp Přechod stupňů šedi Current Colors Aktuální barvy Make Ramp Web Safe Omezit pruh na webové barvy - Select and Mask was closed: its document is no longer the active one Vybrat a maskovat bylo zavřeno: jeho dokument již není aktivní - Select and Mask was closed: another layer was selected Vybrat a maskovat bylo zavřeno: byla vybrána jiná vrstva -# Art History Brush (#213). + The path was kept as the Work Path Cesta byla zachována jako pracovní cesta + The path was discarded Cesta byla zahozena Art History Brush Štětec umělecké historie Art History Brush Tool Nástroj štětec umělecké historie Tight Short Těsný krátký @@ -4245,9 +4238,24 @@ cameraRaw Dehaze Odstranění oparu Tight Curl Těsná smyčka Loose Curl Volná smyčka Stylized dabs from a history state Stylizované šmouhy ze stavu historie - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Poměr stran Font size presets Předvolby velikosti písma Leading presets Předvolby prokladu Tracking presets Předvolby prostrkání + Color Aware Podle barev + Decontaminate Colors Dekontaminovat barvy + Edge Detection Detekce okraje + Global Refinements Globální upřesnění + High Quality Preview Náhled ve vysoké kvalitě + Object Aware Podle objektů + Real-Time Refinement Upřesnění v reálném čase + Refine Edge Brush Tool Nástroj štětec pro upřesnění okraje + Refine Hair Upřesnit vlasy + Refine Mode Režim upřesnění + Remember Settings Zapamatovat nastavení + View Mode Režim zobrazení + Object Aware needs a segmentation model, which isn't available yet Režim Podle objektů vyžaduje segmentační model, který zatím není k dispozici + Refine Hair needs hair detection, which isn't available yet Upřesnit vlasy vyžaduje detekci vlasů, která zatím není k dispozici + Select and Mask was closed: its document is no longer the active one Vybrat a maskovat bylo zavřeno: jeho dokument již není aktivní + Select and Mask was closed: another layer was selected Vybrat a maskovat bylo zavřeno: byla vybrána jiná vrstva + Drag to move the selected path Tažením přesunete vybranou cestu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0078bd4b0a..0a899756d4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4772,3 +4772,10 @@ cameraRaw Show Vectorscope Vis vektorskop cameraRaw Tone Histogram Tonehistogram cameraRaw Vignetting Vignettering cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet + Current Layer: Aktuelt lag: + Delete effect Slet effekt + Move effect down Flyt effekten ned + Move effect up Flyt effekten op + Path operations Stihandlinger + The path was discarded Stien blev kasseret + The path was kept as the Work Path Stien blev bevaret som arbejdssti diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7c27df11cd..ea900cc655 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -16,20 +16,116 @@ # letters; the trailing "…" of dialog commands is kept. Plural rule: one|other (n != 1 -> other). # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Maskenoptionen… - Layer Mask Display Options… Anzeigeoptionen für Ebenenmasken… # Channel Options and New Spot Channel (#3761) + +# Guide layout dialog + +# Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Layer Style dialog: style presets and per-effect defaults + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color +# Status messages, system info and tool names +# Shortcut editor commands without a menu item +# Document Info and color profiles +# Color Lookup, Shadows/Highlights, channels and Calculations +# Measurement log +# Lens Correction, Blur Gallery and distortion filters +# Render filters: Flame, Picture Frame, Tree +# Lens, Lighting Effects, depth and mosaic filters +# Find and Replace, image size, Warp and Layer Style blending options + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# Export As metadata and profile options + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) + Mask Options… Maskenoptionen… + Layer Mask Display Options… Anzeigeoptionen für Ebenenmasken… Channel Color Kanalfarbe Color Indicates: Farbe kennzeichnet: Solidity: Solidität: Masked Areas Maskierte Bereiche Selected Areas Ausgewählte Bereiche Ink Characteristics Farbeigenschaften - -# Guide layout dialog - -# Custom print paper (#3820) Paper Width Papierbreite Paper Height Papierhöhe Columns Spalten @@ -49,7 +145,6 @@ 5 Columns, 3 Rows 5 Spalten, 3 Zeilen 8 Columns 8 Spalten 12 Columns 12 Spalten - File Datei Edit Bearbeiten Image Bild @@ -458,6 +553,7 @@ Intersect Shape Areas Schnittmenge der Formen Exclude Overlapping Shapes Überlappende Formen ausschließen Merge Shape Components Formkomponenten zusammenfügen + Path operations Pfadvorgänge Align Ausrichten Top Edges Obere Kanten Vertical Centers Vertikale Mitten @@ -537,7 +633,6 @@ Color Range… Farbbereich… Focus Area… Schärfebereich… Select and Mask… Auswählen und maskieren… -# Select and Mask dialog labels Smart Radius Smartradius Shift Edge Kante verschieben Decontaminate Dekontaminieren @@ -564,7 +659,6 @@ Blur Weichzeichnen Blur Gallery Weichzeichnen-Galerie Field Blur… Feldweichzeichner… -# Field Blur pins (#3373) No pin selected Kein Pin ausgewählt Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Klicken Sie ins Bild, um einen Pin hinzuzufügen; ziehen Sie einen Pin, um ihn zu verschieben, oder seinen Ring, um die Unschärfe zu ändern. Entf entfernt den ausgewählten Pin. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Ziehen Sie die Griffe am Umriss, um ihn zu skalieren und zu drehen, das Quadrat, um die Ecken abzurunden, und die Punkte innen, um festzulegen, wo die Unschärfe beginnt. @@ -832,6 +926,9 @@ Add Layer Mask Ebenenmaske hinzufügen Add Stop Farbstopp hinzufügen Add a layer style Ebenenstil hinzufügen + Move effect up Effekt nach oben verschieben + Move effect down Effekt nach unten verschieben + Delete effect Effekt löschen Add a mask (from the selection; {key} inverts) Maske hinzufügen (aus der Auswahl; {key} kehrt um) Add an adjustment Anpassung hinzufügen Add disk Festplatte hinzufügen @@ -1060,8 +1157,6 @@ Delete current channel Aktuellen Kanal löschen Delete current state Aktuellen Status löschen Delete effect layer Effektebene löschen - -# Layers-panel trash confirmation Delete layer ‘{name}’? Ebene „{name}“ löschen? Delete {count} layers? {names} {count} Ebenen löschen? {names} Delete layer? Ebene löschen? @@ -1070,7 +1165,6 @@ Missing delete command Löschbefehl fehlt Invalid delete command Ungültiger Löschbefehl Layer deleted, but confirmation preference could not be saved: {error} Die Ebene wurde gelöscht, aber die Bestätigungseinstellung konnte nicht gespeichert werden: {error} - Delete layer Ebene löschen Delete layer comp Ebenenkomposition löschen Delete note Notiz löschen @@ -2176,7 +2270,6 @@ Align with layer An Ebene ausrichten Reset Alignment Ausrichtung zurücksetzen Centre the gradient (offset 0, 0) Verlauf zentrieren (Versatz 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Gradienten-Editor Gradient picker Verlaufsauswahl Gradient stops Verlaufsstufen @@ -2386,8 +2479,6 @@ Don't show again Nicht mehr anzeigen Save failed: {error} Speichern fehlgeschlagen: {error} Save cancelled Speichern abgebrochen - -# Layer Style dialog: style presets and per-effect defaults Style {name} saved Stil {name} gespeichert Make Default Als Standard festlegen Reset to Default Auf Standard zurücksetzen @@ -2396,8 +2487,6 @@ Magnetic Lasso Tool Magnetisches-Lasso-Werkzeug Frequency Frequenz Use tablet pressure to change pen width Tablettdruck zum Ändern der Stiftbreite verwenden - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About Über Contributors Mitwirkende Models Modelle @@ -2428,8 +2517,6 @@ % of all commits % aller Commits Lines +/− Zeilen +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PRs, {commits} Commits, +{added} / −{deleted} Zeilen (Δ {delta}), +{binAdded} / −{binDeleted} Binärdateien, {first} – {last} - -# Swatches panel Create new swatch Neues Farbfeld erstellen New Swatch… Neues Farbfeld… New Swatch Group… Neue Farbfeldgruppe… @@ -2439,13 +2526,11 @@ Export Swatches for Exchange… Farbfelder für Austausch exportieren… Reset Swatches Farbfelder zurücksetzen Add to Swatches Zu Farbfeldern hinzufügen -# Layer Style > Blending Options (Advanced Blending) Blend If: Farbbereich: + Current Layer: Aktuelle Ebene: Channels: Kanäle: Knockout Aussparung Apply At Canvas Bounds Effekt an Arbeitsflächenbegrenzungen anwenden - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Farbwähler (Textfarbe) Color Picker ({name}) Farbwähler ({name}) Color Picker (Fill Color) Farbwähler (Füllfarbe) @@ -2462,8 +2547,6 @@ Show/Hide Panels Bedienfelder ein-/ausblenden Could not open Öffnen nicht möglich {path}: the path is not valid Unicode; rename the file and open it again. {path}: Der Dateipfad enthält ungültige Zeichen. Benenne die Datei um und öffne sie erneut. - -# Fill dialog, layer style contours and Image Size Contents: Inhalt: Custom Pattern: Eigenes Muster: Foreground Color Vordergrundfarbe @@ -2490,7 +2573,6 @@ Rolling Slope - Descending Wellenhang - absteigend Rounded Steps Abgerundete Stufen Sawtooth 1 Sägezahn 1 - Red Eye Tool Rote-Augen-Werkzeug Red Eye Rote Augen Pupil Size Pupillengröße @@ -2498,7 +2580,6 @@ Click a red pupil to neutralize it Klick auf die Pupille, um die Rotfärbung zu entfernen. open source Open Source …and {n} more …und {n} weitere - Eyedroppers: Pipetten: Set Black Point Schwarzpunkt festlegen Set Neutral Gray Point Neutralen Graupunkt festlegen @@ -2507,8 +2588,6 @@ Selection Preview: Auswahlvorschau: Black Matte Schwarzer Hintergrund White Matte Weißer Hintergrund - -# Layer colour labels. layerLabel No Color Keine Farbe Seafoam Meeresschaum Indigo Indigo @@ -2530,8 +2609,6 @@ fontWeight Bold Fett fontWeight ExtraBold Extrafett fontWeight Black Sehr fett (Black) fontWeight Italic Kursiv - -# Pattern Stamp tool Pattern Stamp Tool Musterstempel-Werkzeug Pattern Stamp Musterstempel Impressionist Impressionistisch @@ -2539,13 +2616,9 @@ fontWeight Italic Kursiv 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 - -# Painting symmetry presets. Dual Axis Duale Achse Diagonal Diagonal Transform Symmetry Symmetrie transformieren - -# Eyedropper Sample Size and Sample (#1649). Point Sample 1 Pixel 3 by 3 Average 3 x 3 Pixel Durchschnitt 5 by 5 Average 5 x 5 Pixel Durchschnitt @@ -2557,15 +2630,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Farbe zu Alpha… Transparency Threshold Transparenz-Schwellenwert Opacity Threshold Deckkraft-Schwellenwert PhotoCraft — Screen Color Picker PhotoCraft — Bildschirmfarbenauswahl - Rasterize svg groups deeper than SVG-Gruppen ab dieser Tiefe rastern 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 schaltet diese Schwelle aus; SVG-Gruppen, die tiefer als 100 Ebenen verschachtelt sind, werden immer gerastert. Rule of Thirds Drittel-Regel @@ -2579,8 +2649,6 @@ fontWeight Italic Kursiv Cycle Orientation Ausrichtung wechseln Set the overlay options for the Crop tool Überlagerungsoptionen für das Freistellungswerkzeug festlegen Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Der Alt-Klick ging an die Arbeitsumgebung, die Fenster mit Alt-Ziehen verschiebt. Stelle dort die Taste zum Verschieben von Fenstern auf Super oder raste Alt unter Fenster › Modifikatortasten ein. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Farbwähler (Ebenenstilfarbe) Auto Hide Notifications Benachrichtigungen automatisch ausblenden Notification Duration (seconds) Dauer der Benachrichtigung (Sekunden) @@ -2657,7 +2725,6 @@ fontWeight Italic Kursiv Appearance Settings… Erscheinungsbild-Einstellungen… Add to favorites Zu Favoriten hinzufügen Remove from favorites Aus Favoriten entfernen -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data Kameradaten cameraData Make Hersteller cameraData Model Modell @@ -2668,7 +2735,6 @@ cameraData ISO Speed ISO-Empfindlichkeit cameraData Focal Length Brennweite cameraData Focal Length (35 mm) Brennweite (35 mm) cameraData Lens Objektiv -# Shared panel docking Activate Panel Bedienfeld aktivieren Change Panel Group Bedienfeldgruppe ändern Change Panel Layout Bedienfeldlayout ändern @@ -2712,7 +2778,6 @@ cameraData Lens Objektiv Snap to Origin An Ursprung ausrichten Search settings… Einstellungen durchsuchen… No matching settings Keine passenden Einstellungen -# Edit › Content-Aware Fill workspace Sampling Brush Tool Aufnahmepinsel-Werkzeug Sampling Area Overlay Überlagerung des Aufnahmebereichs Show Sampling Area Aufnahmebereich einblenden @@ -2730,7 +2795,6 @@ cameraData Lens Objektiv Output To Ausgabe in Duplicate Layer Ebene duplizieren Contract Verkleinern - Animation Options Animationsoptionen Entire Document Gesamtes Dokument Filter Options Filteroptionen @@ -2750,8 +2814,6 @@ cameraData Lens Objektiv Add “copy” to Copied Layers and Groups „Kopie“ zu kopierten Ebenen und Gruppen hinzufügen Preview on canvas when reordering layers Vorschau auf der Arbeitsfläche beim Neuanordnen von Ebenen Show layer mask badges Ebenenmasken-Abzeichen anzeigen - -# Smart Filter editors Blending Options ({filter}) Fülloptionen ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Ebeneneffekte und Smartfilter ausblenden ({key}-Klick: alle Ebenen) Show the layer's effects and Smart Filters ({key}-click: all layers) Ebeneneffekte und Smartfilter einblenden ({key}-Klick: alle Ebenen) @@ -2786,7 +2848,6 @@ curves Smooth Glätten Fix the red plane first: its corners must form a convex quad Korrigieren Sie zuerst die rote Ebene: Ihre Ecken müssen ein konvexes Viereck bilden Alt-click a plane to set the clone source Alt-Klick auf eine Ebene legt die Kopierquelle fest Too many clone strokes: apply Vanishing Point first Zu viele Kopierstriche: Wenden Sie zuerst Fluchtpunkt an -# Select and Mask view modes (#1754) Onion Skin Zwiebelschicht Marching Ants Laufende Ameisen On Black Auf Schwarz @@ -2795,7 +2856,6 @@ curves Smooth Glätten Show Edge Kante anzeigen Show Original Original anzeigen F cycles the views; hold X to see the image F wechselt die Ansicht; X gedrückt halten zeigt das Bild -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Kante-verbessern-Pinsel (R) Expand Detection Area Erkennungsbereich erweitern Restore Original Edge Ursprüngliche Kante wiederherstellen @@ -2803,22 +2863,16 @@ curves Smooth Glätten Clear Brush Strokes Pinselstriche löschen Show rulers Lineale anzeigen Presentation Präsentation - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Klicken zum Platzieren · Alt-Klick oder Ziehen außerhalb der Arbeitsfläche zum Entfernen No document open Kein Dokument geöffnet {n} of {max} sample points {n} von {max} Messpunkten - -# History panel menu (#2966) Step Forward Schritt vorwärts Step Backward Schritt zurück Clear History Protokoll löschen New Snapshot… Neuer Schnappschuss… History Options… Protokolloptionen… -# History panel › History Options… (#2966) Allow Non-Linear History Nicht-lineare Protokolle zulassen Make Layer Visibility Changes Undoable Änderungen der Ebenensichtbarkeit widerrufbar machen -# Print dialog (#2697) Emulsion Down Schichtseite unten Functions Funktionen Print Resolution: Druckauflösung: @@ -2830,7 +2884,6 @@ curves Smooth Glätten Apply mask to layer before removing? Maske vor dem Entfernen auf die Ebene anwenden? The layer or its mask changed. Drag the mask onto the Trash again. Die Ebene oder ihre Maske hat sich geändert. Ziehen Sie die Maske erneut in den Papierkorb. Delete the vector mask? Vektormaske löschen? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} {n} Farbfeld nach {file} exportiert|{n} Farbfelder nach {file} exportiert @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {n} Pinsel aus {group} importiert|{n} Pinsel aus {group} importiert @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {n} Farbfeld aus {file} importiert|{n} Farbfelder aus {file} importiert @@ -2845,13 +2898,11 @@ curves Smooth Glätten @plural {n} step|{n} steps {n} Schritt|{n} Schritte @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} weitere Pinselvorgaben-Warnung)|{warning} (+{n} weitere Pinselvorgaben-Warnungen) @plural {what} with {n} warning|{what} with {n} warnings {what} mit {n} Warnung|{what} mit {n} Warnungen -# View › Guides › New Guide… › Color Light Blue Hellblau Light Red Hellrot Medium Blue Mittelblau Light Gray Hellgrau Stop Stopp -# Status messages, system info and tool names Join the ArtCraft Discord ({url}) Dem ArtCraft-Discord beitreten ({url}) Nothing to paste: the clipboard holds no image Nichts einzufügen: Die Zwischenablage enthält kein Bild Graphics adapter: {adapter} Grafikadapter: {adapter} @@ -2874,7 +2925,6 @@ curves Smooth Glätten List view Listenansicht Proof Setup… Proof einrichten… 32-bit Preview Options 32-Bit-Vorschauoptionen -# Shortcut editor commands without a menu item Toggle Layer Mask Overlay Ebenenmasken-Überlagerung umschalten Increase Type Size Schriftgröße erhöhen Decrease Type Size Schriftgröße verringern @@ -2910,7 +2960,6 @@ curves Smooth Glätten Zoom In (hold, drag to scrub) Vergrößern (gedrückt halten, zum Zoomen ziehen) Zoom Out (hold) Verkleinern (gedrückt halten) Erase with Brush or Pencil (hold) Mit Pinsel oder Buntstift radieren (gedrückt halten) -# Document Info and color profiles Author Title Position des Urhebers Copyright Status Urheberrechtsstatus Copyright Info URL URL für Urheberrechtsinfo @@ -2934,7 +2983,6 @@ curves Smooth Glätten Intent Renderpriorität Bpc Schwarzpunktkompensierung Simulate Paper Papierfarbe simulieren -# Color Lookup, Shadows/Highlights, channels and Calculations Warming Filter (85) Wärmefilter (85) Lut LUT Cool Kühl @@ -2976,7 +3024,6 @@ curves Smooth Glätten Channel2 Kanal 2 Channel3 Kanal 3 Channel4 Kanal 4 -# Measurement log Label Beschriftung Date and Time Datum und Uhrzeit Scale Units Maßstabseinheiten @@ -2992,7 +3039,6 @@ curves Smooth Glätten Length Länge W: B: A: Wi: -# Lens Correction, Blur Gallery and distortion filters Pattern Fill… Musterfüllung… Generic Allgemein Correct Distortion Verzerrung korrigieren @@ -3068,7 +3114,6 @@ curves Smooth Glätten Short Strokes Kurze Striche Medium Strokes Mittlere Striche Long Strokes Lange Striche -# Render filters: Flame, Picture Frame, Tree Flame Type Flammentyp One Flame Along Path Eine Flamme entlang des Pfads Multiple Flames Along Path Mehrere Flammen entlang des Pfads @@ -3123,7 +3168,6 @@ curves Smooth Glätten Custom Branch Color Eigene Astfarbe Branches Color Astfarbe Flat Shading Flächige Schattierung -# Lens, Lighting Effects, depth and mosaic filters Lens Objektiv Prime35 Festbrennweite 35 Prime105 Festbrennweite 105 @@ -3181,7 +3225,6 @@ curves Smooth Glätten Row Order Zeilenreihenfolge Preserve Erhalten Squareness Rechteckigkeit -# Find and Replace, image size, Warp and Layer Style blending options Any Beliebig Cmyk CMYK To Nach @@ -3200,7 +3243,6 @@ curves Smooth Glätten Transparency Shapes Layer Transparenz bestimmt die Ebenenform Layer Mask Hides Effects Ebenenmaske blendet Effekte aus Vector Mask Hides Effects Vektormaske blendet Effekte aus - This Layer: Diese Ebene: Underlying Layer: Darunterliegende Ebene: Up Nach oben Checkerboard Schachbrett @@ -3229,8 +3271,6 @@ curves Smooth Glätten Clear Brush Controls Pinselsteuerungen löschen Reset All Locked Settings Alle gesperrten Einstellungen zurücksetzen Copy Texture to Other Tools Struktur auf andere Werkzeuge kopieren - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Aktionen laden… Save Actions… Aktionen speichern… New Action… Neue Aktion… @@ -3242,10 +3282,8 @@ curves Smooth Glätten @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} Schritt hat noch keine Entsprechung in PhotoCraft|{n} Schritte haben noch keine Entsprechung in PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} Aktion in {file} gespeichert|{n} Aktionen in {file} gespeichert @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Schritt ohne Photoshop-Entsprechung ausgelassen|{n} Schritte ohne Photoshop-Entsprechung ausgelassen - File Naming Dateibenennung Starting serial Startnummer -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Stopp einfügen… Save Set… Set speichern… Message: Meldung: @@ -3257,11 +3295,8 @@ curves Smooth Glätten @plural {n} action|{n} actions {n} Aktion|{n} Aktionen Background (Default) Hintergrund (Standard) Content-Aware Fill Inhaltsbasiert füllen -# Batch / Image Processor Include All Subfolders Alle Unterordner einschließen Auto Add/Delete Autom. hinzuf./löschen - -# Native Windows printing qualification 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… @@ -3306,7 +3341,6 @@ curves Smooth Glätten Could not write {name}: {error} {name} konnte nicht geschrieben werden: {error} Kept {name}: written by another application {name} beibehalten: von einer anderen Anwendung geschrieben Shadow Tint Schattentönung -# PhotoCraft release checks. Check for Updates… Nach Updates suchen… PhotoCraft Updates PhotoCraft-Updates Checking for updates… Suche nach Updates… @@ -3319,38 +3353,29 @@ curves Smooth Glätten Automatically Check for Updates Automatisch nach Updates suchen Installed version: {version} Installierte Version: {version} PhotoCraft {version} is available. PhotoCraft {version} ist verfügbar. -# History panel › History Brush source (#2966) Paints from the History panel's source state Malt aus dem Quellzustand des Protokollbedienfelds Sets the source for the history brush Legt die Quelle für den Protokollpinsel fest -# Bevel & Emboss shading controls. Highlight Mode Lichtermodus Highlight Color Lichterfarbe Highlight Opacity Lichterdeckkraft Shadow Mode Schattenmodus Shadow Color Schattenfarbe Shadow Opacity Schattendeckkraft -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Eingebettetes Profil verwenden ({profile}) Convert to the working space ({profile}) In den Arbeitsfarbraum konvertieren ({profile}) Remember this choice for future images Diese Auswahl für künftige Bilder merken Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Die Abfrage lässt sich mit „Ask On Mismatch“ unter Bearbeiten › Farbeinstellungen wieder einschalten. Button Mode Schaltflächenmodus Button Mode On Schaltflächenmodus an - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Benutzeroberfläche abdunkeln Lighten Interface Benutzeroberfläche aufhellen -# Bevel & Emboss Technique. Technique Technik Chisel Hard Meißeln hart Chisel Soft Meißeln weich Open color-less EXR as ACEScg Farbangabenloses EXR als ACEScg öffnen Do not append "copy" to filename when saving a copy Beim Speichern einer Kopie „copy“ nicht an den Dateinamen anhängen -# Export As metadata and profile options Color Profile Farbprofil EXIF EXIF - -# View › Guides › right-click a guide Edit Selected Guides Ausgewählte Hilfslinien bearbeiten Clear Selected Guides Ausgewählte Hilfslinien löschen Bicubic Automatic Bikubisch automatisch @@ -3375,8 +3400,6 @@ curves Smooth Glätten set name Name des Satzes {set} (modified) {set} (geändert) Show file name in title Dateiname im Titel anzeigen - -# Image › Mode › Bitmap (#5559) 50% Threshold 50 %-Schwellenwert Pattern Dither Musterdither Diffusion Dither Diffusionsdither @@ -3394,11 +3417,9 @@ curves Smooth Glätten Undo Changes Änderungen rückgängig machen {shortcut} is reserved by the system and can't be assigned. {shortcut} ist vom System reserviert und kann nicht zugewiesen werden. Low-Latency Drawing (vsync off, applies at next launch) Zeichnen mit geringer Latenz (ohne VSync, gilt ab dem nächsten Start) -# Free Transform: a new layer while the box is open (#5859) Reference point location Position des Referenzpunkts Free Transform is still being applied; try again when it has finished. Frei transformieren wird noch angewendet; versuchen Sie es erneut, wenn es fertig ist. The transform couldn't be applied. Die Transformation konnte nicht angewendet werden. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Die Ebenen brauchen {needed} GPU-Speicher; das Budget lässt ihnen {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Stellen Sie unter Voreinstellungen › Leistung den GPU-Speicher auf das ein, was Ihre Grafikkarte fassen kann, höchstens 3/8 ihres Speichers. Automatisch folgt der Speichernutzung, innerhalb eines Viertels des Arbeitsspeichers dieses Computers und 3/8 des Kartenspeichers, und rechnet das Dokument bei einer Karte mit bekanntem Speicher nicht an. Solange sie nicht hineinpassen, zeigt die Statusleiste GPU-Speicher voll. GPU Memory Full GPU-Speicher voll @@ -3420,8 +3441,6 @@ curves Smooth Glätten The fastest and the softest, with colour 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}“. - Move Up Nach oben - Move Down Nach unten Memory Usage Speichernutzung Per-document RAM limit (MB) RAM-Limit pro Dokument (MB) Installed RAM: {ram} MB; this limit: {percent}% Installierter RAM: {ram} MB; dieses Limit: {percent}% @@ -3432,27 +3451,18 @@ curves Smooth Glätten In Front Davor Behind Dahinter Blend Mischen - -# DDS Options (#1327) DDS Options DDS-Optionen Compression Komprimierung Generate Mipmaps Mipmaps erzeugen - -# Color Table (.act) dialog There is no color table to save. Es gibt keine Farbtabelle zum Speichern. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} Farbe in {file} gespeichert|{n} Farben in {file} gespeichert - -# Graphics Adapter preference (#1885) GPU adapter GPU-Adapter - -# Styles panel: Import / Export Styles (.asl) Import Styles… Stile importieren… Export Selected Styles… Ausgewählte Stile exportieren… Export Styles… Stile exportieren… {file} is not a style library (.asl) {file} ist keine Stilbibliothek (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {n} Stil aus {file} importiert|{n} Stile aus {file} importiert @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} Stil nach {file} exportiert|{n} Stile nach {file} exportiert -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Bestätige oder brich zuerst den offenen Dialog des Aktionsschritts ab Pro Medium Gray Pro (Mittelgrau) Solarized Solarized @@ -3461,29 +3471,11 @@ curves Smooth Glätten Pro Light Pro (Hell) Resize Windows to Fit Fenstergröße anpassen EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Automatische Absatzrichtung Left-to-right paragraph direction Absatzrichtung von links nach rechts Right-to-left paragraph direction Absatzrichtung von rechts nach links Not rendered: this adjustment ({key}) is kept as imported. Nicht dargestellt: Diese Einstellung ({key}) wird wie importiert beibehalten. -# Print preview image (#8236) Print preview image Print preview image - Clear Selection Auswahl löschen - Color Aware Farbbezogen - Decontaminate Colors Farben dekontaminieren - Edge Detection Kantenerkennung - Global Refinements Globale Verbesserungen - High Quality Preview Hochwertige Vorschau - Object Aware Objektbezogen - Real-Time Refinement Verbesserung in Echtzeit - Refine Edge Brush Tool Kante-verbessern-Pinsel-Werkzeug - Refine Hair Haare verbessern - Refine Mode Verbesserungsmodus - Remember Settings Einstellungen merken - View Mode Ansichtsmodus - Object Aware needs a segmentation model, which isn't available yet Objektbezogen benötigt ein Segmentierungsmodell, das noch nicht verfügbar ist - Refine Hair needs hair detection, which isn't available yet Haare verbessern benötigt eine Haarerkennung, die noch nicht verfügbar ist -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Farbtonwürfel Brightness Cube Helligkeitswürfel Color Wheel Farbkreis @@ -3500,9 +3492,8 @@ curves Smooth Glätten Grayscale Ramp Graustufenbalken Current Colors Aktuelle Farben Make Ramp Web Safe Farbbalken auf Webfarben beschränken - Select and Mask was closed: its document is no longer the active one Auswählen und maskieren wurde geschlossen: Das zugehörige Dokument ist nicht mehr aktiv - Select and Mask was closed: another layer was selected Auswählen und maskieren wurde geschlossen: Es wurde eine andere Ebene ausgewählt -# Art History Brush (#213). + The path was kept as the Work Path Der Pfad wurde als Arbeitspfad beibehalten + The path was discarded Der Pfad wurde verworfen Art History Brush Künstlerischer Protokollpinsel Art History Brush Tool Künstlerischer-Protokollpinsel-Werkzeug Tight Short Eng kurz @@ -3514,8 +3505,6 @@ curves Smooth Glätten Tight Curl Eng gewellt Loose Curl Locker gewellt Stylized dabs from a history state Stilisierte Tupfer aus einem Protokollzustand - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Seitenverhältnis Category Kategorie Color Table Farbtabelle @@ -3526,3 +3515,20 @@ curves Smooth Glätten Font size presets Schriftgrößen-Vorgaben Leading presets Zeilenabstand-Vorgaben Tracking presets Laufweiten-Vorgaben + Clear Selection Auswahl löschen + Color Aware Farbbezogen + Decontaminate Colors Farben dekontaminieren + Edge Detection Kantenerkennung + Global Refinements Globale Verbesserungen + High Quality Preview Hochwertige Vorschau + Object Aware Objektbezogen + Real-Time Refinement Verbesserung in Echtzeit + Refine Edge Brush Tool Kante-verbessern-Pinsel-Werkzeug + Refine Hair Haare verbessern + Refine Mode Verbesserungsmodus + Remember Settings Einstellungen merken + View Mode Ansichtsmodus + Object Aware needs a segmentation model, which isn't available yet Objektbezogen benötigt ein Segmentierungsmodell, das noch nicht verfügbar ist + Refine Hair needs hair detection, which isn't available yet Haare verbessern benötigt eine Haarerkennung, die noch nicht verfügbar ist + Select and Mask was closed: its document is no longer the active one Auswählen und maskieren wurde geschlossen: Das zugehörige Dokument ist nicht mehr aktiv + Select and Mask was closed: another layer was selected Auswählen und maskieren wurde geschlossen: Es wurde eine andere Ebene ausgewählt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c3facf56a0..998989a19c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4,18 +4,106 @@ # Covers every source label the i18n coverage check lists. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Επιλογές μάσκας… - Layer Mask Display Options… Επιλογές εμφάνισης μάσκας επιπέδου… # Channel Options and New Spot Channel (#3761) - Channel Color Χρώμα καναλιού - Color Indicates: Το χρώμα υποδεικνύει: - Solidity: Συμπαγότητα: - Ink Characteristics Χαρακτηριστικά μελανιού # Guide layout dialog # Custom print paper (#3820) + + +# Consolidated Greek localization additions +# Select and Mask dialog labels +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Greek audit completion – menus and layers + +# Final interface terminology refinements + +# Greek full-localization recovery additions + +# Layers-panel trash confirmation + +# Field Blur pins (#3373) + +# Greek tool names, original English in parentheses + +# Labels added on main since the first batch + +# Screen color picker (#1232) + +# Saved New Document presets (#1516) + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker + +# Shared text style Color Picker (#2015) +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# Export As metadata and profile options + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) + Mask Options… Επιλογές μάσκας… + Layer Mask Display Options… Επιλογές εμφάνισης μάσκας επιπέδου… + Channel Color Χρώμα καναλιού + Color Indicates: Το χρώμα υποδεικνύει: + Solidity: Συμπαγότητα: + Ink Characteristics Χαρακτηριστικά μελανιού Paper Width Πλάτος χαρτιού Paper Height Ύψος χαρτιού Rows Γραμμές @@ -33,7 +121,6 @@ 5 Columns, 3 Rows 5 στήλες, 3 γραμμές 8 Columns 8 στήλες 12 Columns 12 στήλες - File Αρχείο Edit Επεξεργασία Image Εικόνα @@ -212,8 +299,6 @@ Pixelate Εικονοστοιχείωση Render Απόδοση About PhotoCraft Πληροφορίες για το PhotoCraft - -# Consolidated Greek localization additions Content-Aware Fill… Γέμισμα βάσει περιεχομένου… Content-Aware Scale Κλιμάκωση βάσει περιεχομένου Puppet Warp Παραμόρφωση με σημεία ελέγχου @@ -258,7 +343,6 @@ Mask All Objects Απόκρυψη όλων των αντικειμένων με μάσκα Update All Text Layers Ενημέρωση όλων των επιπέδων κειμένου Select and Mask… Επιλογή και μάσκα… -# Select and Mask dialog labels Smart Radius Έξυπνη ακτίνα Shift Edge Μετατόπιση άκρης Decontaminate Απομάκρυνση επιμόλυνσης @@ -1602,7 +1686,6 @@ Centre the gradient (offset 0, 0) Κεντράρισμα διαβάθμισης (μετατόπιση 0, 0) Refine Strokes Πινελιές βελτίωσης Edits Επεξεργασίες -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Επεξεργασία διαβάθμισης Gradient picker Επιλογή διαβάθμισης Gradient stops Σημεία διαβάθμισης @@ -1727,8 +1810,6 @@ Rulers (⌘R) Χάρακες (⌘R) Show Guides (⌘;) Εμφάνιση οδηγών (⌘;) Grid (⌘') Πλέγμα (⌘') - -# Greek audit completion – menus and layers Free Transform a Copy Ελεύθερος μετασχηματισμός αντιγράφου Again Επανάληψη Transform Again on a Copy Επανάληψη μετασχηματισμού σε αντίγραφο @@ -1929,6 +2010,7 @@ Intersect Shape Areas Τομή περιοχών σχημάτων Exclude Overlapping Shapes Εξαίρεση επικαλυπτόμενων σχημάτων Merge Shape Components Συγχώνευση συστατικών σχήματος + Path operations Λειτουργίες διαδρομών Top Edges Επάνω ακμές Vertical Centers Κατακόρυφα κέντρα Bottom Edges Κάτω ακμές @@ -1950,8 +2032,6 @@ Glyphs Panel Πλαίσιο γλυφών Anti-Alias Εξομάλυνση ακμών Orientation Προσανατολισμός - -# Final interface terminology refinements PDF Presentation… Παρουσίαση PDF… Picture Package… Πακέτο εικόνων… Web Photo Gallery… Συλλογή φωτογραφιών ιστού… @@ -2018,8 +2098,6 @@ Mix Ανάμειξη 8 bit 8 bit ανά κανάλι 16 bit 16 bit ανά κανάλι - -# Greek full-localization recovery additions (print to the printer) (εκτύπωση στον εκτυπωτή) + Add variable + Προσθήκη μεταβλητής 2-up Horizontal Δύο οριζόντια @@ -2046,6 +2124,9 @@ Add Pins Προσθήκη καρφιτσών Add Stop Προσθήκη σημείου διαβάθμισης Add a layer style Προσθήκη στυλ επιπέδου + Move effect up Μετακίνηση εφέ προς τα πάνω + Move effect down Μετακίνηση εφέ προς τα κάτω + Delete effect Διαγραφή εφέ Add a mask (from the selection; {key} inverts) Προσθήκη μάσκας (από την επιλογή· το {key} αντιστρέφει) Add a mask (from the selection; ⌥ inverts) Προσθήκη μάσκας (από την επιλογή· ⌥ για αντιστροφή) Add an adjustment Προσθήκη προσαρμογής @@ -2327,8 +2408,6 @@ Delete Pins Διαγραφή καρφιτσών Delete Workspace Διαγραφή χώρου εργασίας Delete Workspace… Διαγραφή χώρου εργασίας… - -# Layers-panel trash confirmation Delete layer ‘{name}’? Διαγραφή του επιπέδου «{name}»; Delete {count} layers? {names} Διαγραφή {count} επιπέδων; {names} Delete layer? Διαγραφή επιπέδου; @@ -2337,7 +2416,6 @@ Missing delete command Λείπει η εντολή διαγραφής Invalid delete command Μη έγκυρη εντολή διαγραφής Layer deleted, but confirmation preference could not be saved: {error} Το επίπεδο διαγράφηκε, αλλά δεν ήταν δυνατή η αποθήκευση της προτίμησης επιβεβαίωσης: {error} - Delete layer Διαγραφή επιπέδου Density: Πυκνότητα: Depth Βάθος @@ -2375,7 +2453,7 @@ 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 Σύρετε για να σχεδιάσετε διαβάθμιση Drag to move the active layer Σύρετε για μετακίνηση του ενεργού επιπέδου - Drag to move the active shape's path or the Work Path Σύρετε για μετακίνηση της διαδρομής του ενεργού σχήματος ή της διαδρομής εργασίας + Drag to move the selected path Σύρετε για μετακίνηση της επιλεγμένης διαδρομής Dual Brush Διπλό πινέλο Duplicate Path Διπλασιασμός διαδρομής Rename Path… Μετονομασία διαδρομής… @@ -2430,7 +2508,6 @@ Fibers… Ίνες… Field Blur Θόλωση πεδίου Field Blur… Θόλωση πεδίου… -# Field Blur pins (#3373) No pin selected Δεν έχει επιλεγεί καρφίτσα Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Κάντε κλικ στην εικόνα για να προσθέσετε καρφίτσα· σύρετε μια καρφίτσα για να τη μετακινήσετε ή τον δακτύλιό της για να αλλάξετε τη θόλωση. Το Delete αφαιρεί την επιλεγμένη καρφίτσα. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Σύρετε τις λαβές στο περίγραμμα για αλλαγή μεγέθους και περιστροφή, το τετράγωνο για στρογγύλεμα των γωνιών και τις κουκκίδες μέσα για να ορίσετε πού αρχίζει η θόλωση. @@ -3352,8 +3429,6 @@ cameraRaw Tint Χρωματική απόχρωση cameraRaw Vibrance Ζωντάνια χρωμάτων cameraRaw Whites Λευκά cameraRaw Yellow Κίτρινο - -# Greek tool names, original English in parentheses Ruler Tool Χάρακας (Ruler Tool) Count Tool Καταμέτρηση (Count Tool) Background Eraser Tool Γόμα φόντου (Background Eraser Tool) @@ -3431,8 +3506,6 @@ cameraRaw Yellow Κίτρινο Quit {app} Τερματισμός του {app} Services Υπηρεσίες Hide Others Απόκρυψη άλλων - -# Labels added on main since the first batch 100% 100% 105% 105% 110% 110% @@ -3449,6 +3522,8 @@ cameraRaw Yellow Κίτρινο Anamorphic 2:1 (2) Αναμορφικό 2:1 (2) ArtCraft ArtCraft Blend If: Ανάμειξη υπό όρους: + Current Layer: Τρέχον επίπεδο: + Underlying Layer: Υποκείμενο επίπεδο: Channels: Κανάλια: Click a red pupil to neutralize it Κάντε κλικ σε μια κόκκινη κόρη για να την εξουδετερώσετε Cmd Cmd @@ -3589,25 +3664,17 @@ fontWeight Medium Μεσαία fontWeight Regular Κανονικά fontWeight SemiBold Ημιέντονα fontWeight Thin Πολύ λεπτά - -# Screen color picker (#1232) Pick screen color Επιλογή χρώματος οθόνης Pick a screen pixel or press Esc to cancel Επιλέξτε ένα εικονοστοιχείο της οθόνης ή πατήστε Esc για ακύρωση Sample a pixel anywhere on the screen Δειγματοληψία ενός pixel οπουδήποτε στην οθόνη Click to pick · Esc to cancel Κλικ για επιλογή · Esc για ακύρωση Scroll to zoom Κύλιση για μεγέθυνση Drag to pan · Scroll to zoom · Double-click to fit Σύρετε για μετακίνηση · Κυλήστε για μεγέθυνση · Διπλό κλικ για προσαρμογή - -# Saved New Document presets (#1516) Preset Name Όνομα προεπιλογής No saved presets yet. Δεν υπάρχουν ακόμη αποθηκευμένες προεπιλογές. - -# Painting symmetry presets. Dual Axis Διπλός άξονας Diagonal Διαγώνια Transform Symmetry Μετασχηματισμός συμμετρίας - -# Eyedropper Sample Size and Sample (#1649). Point Sample Σημειακό δείγμα 3 by 3 Average Μέσος όρος 3 × 3 5 by 5 Average Μέσος όρος 5 × 5 @@ -3619,15 +3686,12 @@ fontWeight Thin Πολύ λεπτά All Layers No Adjustments Όλα τα επίπεδα χωρίς προσαρμογές Current & Below No Adjustments Τρέχον και υποκείμενα χωρίς προσαρμογές 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 Δεν είναι χρώμα web: κάντε κλικ για το πλησιέστερο χρώμα web Color to Alpha… Χρώμα σε άλφα… Transparency Threshold Κατώφλι διαφάνειας Opacity Threshold Κατώφλι αδιαφάνειας PhotoCraft — Screen Color Picker PhotoCraft — Επιλογή χρώματος οθόνης - Rasterize svg groups deeper than Ραστεροποίηση ομάδων SVG πέρα από αυτό το βάθος 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. Το 0 απενεργοποιεί αυτό το όριο· ομάδες SVG με ένθεση βαθύτερη από 100 επίπεδα ραστεροποιούνται πάντα. Rule of Thirds Κανόνας των τρίτων @@ -3640,11 +3704,7 @@ fontWeight Thin Πολύ λεπτά Cycle Orientation Εναλλαγή προσανατολισμού Set the overlay options for the Crop tool Ορισμός επιλογών επικάλυψης για το εργαλείο Περικοπή Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Το Alt-κλικ πήγε στο περιβάλλον εργασίας, που μετακινεί παράθυρα με Alt-σύρσιμο. Ορίστε το πλήκτρο μετακίνησης παραθύρων του σε Super ή κλειδώστε το Alt στο Παράθυρο › Πλήκτρα τροποποίησης. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Επιλογέας χρώματος (χρώμα στυλ επιπέδου) - -# Shared text style Color Picker (#2015) Color Picker (Text Color) Επιλογέας χρώματος (χρώμα κειμένου) Color Picker ({name}) Επιλογέας χρώματος ({name}) Auto Hide Notifications Αυτόματη απόκρυψη ειδοποιήσεων @@ -3713,7 +3773,6 @@ fontWeight Thin Πολύ λεπτά Appearance Settings… Ρυθμίσεις εμφάνισης… Add to favorites Προσθήκη στα αγαπημένα Remove from favorites Αφαίρεση από τα αγαπημένα -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Κατασκευαστής cameraData Model Μοντέλο cameraData Date Taken Ημερομηνία λήψης @@ -3723,7 +3782,6 @@ cameraData ISO Speed Ευαισθησία ISO cameraData Focal Length Εστιακή απόσταση cameraData Focal Length (35 mm) Εστιακή απόσταση (35 mm) cameraData Lens Φακός -# Shared panel docking Activate Panel Ενεργοποίηση πάνελ Change Panel Group Αλλαγή ομάδας πάνελ Change Panel Layout Αλλαγή διάταξης πάνελ @@ -3768,7 +3826,6 @@ cameraData Lens Φακός Snap to Origin Προσκόλληση στην αρχή Search settings… Αναζήτηση ρυθμίσεων… No matching settings Δεν βρέθηκαν ρυθμίσεις -# Edit › Content-Aware Fill workspace Sampling Brush Tool Εργαλείο πινέλου δειγματοληψίας Sampling Area Overlay Επικάλυψη περιοχής δειγματοληψίας Show Sampling Area Εμφάνιση περιοχής δειγματοληψίας @@ -3784,7 +3841,6 @@ cameraData Lens Φακός Mirror Κατοπτρισμός Output Settings Ρυθμίσεις εξόδου Output To Έξοδος σε - Animation Options Επιλογές κίνησης Entire Document Ολόκληρο έγγραφο Filter Options Επιλογές φίλτρου @@ -3801,8 +3857,6 @@ cameraData Lens Φακός Add “copy” to Copied Layers and Groups Προσθήκη «αντίγραφο» σε αντιγραμμένα επίπεδα και ομάδες Preview on canvas when reordering layers Προεπισκόπηση στον καμβά κατά την αναδιάταξη επιπέδων Show layer mask badges Εμφάνιση σημάτων μασκών επιπέδου - -# Smart Filter editors Blending Options ({filter}) Επιλογές ανάμειξης ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Απόκρυψη εφέ επιπέδου και έξυπνων φίλτρων ({key}-κλικ: όλα τα επίπεδα) Show the layer's effects and Smart Filters ({key}-click: all layers) Εμφάνιση εφέ επιπέδου και έξυπνων φίλτρων ({key}-κλικ: όλα τα επίπεδα) @@ -3836,7 +3890,6 @@ curves Smooth Εξομάλυνση Fix the red plane first: its corners must form a convex quad Διορθώστε πρώτα το κόκκινο επίπεδο: οι γωνίες του πρέπει να σχηματίζουν κυρτό τετράπλευρο Alt-click a plane to set the clone source Alt-κλικ σε ένα επίπεδο για να ορίσετε την πηγή κλωνοποίησης Too many clone strokes: apply Vanishing Point first Πάρα πολλές πινελιές κλωνοποίησης: εφαρμόστε πρώτα το Σημείο φυγής -# Select and Mask view modes (#1754) Onion Skin Φλούδα κρεμμυδιού Marching Ants Κινούμενο περίγραμμα On Black Σε μαύρο @@ -3845,7 +3898,6 @@ curves Smooth Εξομάλυνση Show Edge Εμφάνιση άκρης Show Original Εμφάνιση αρχικού F cycles the views; hold X to see the image Το F εναλλάσσει τις προβολές· κρατήστε το X για να δείτε την εικόνα -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Πινέλο βελτίωσης ακμής (R) Expand Detection Area Επέκταση περιοχής ανίχνευσης Restore Original Edge Επαναφορά αρχικής ακμής @@ -3853,18 +3905,12 @@ curves Smooth Εξομάλυνση Clear Brush Strokes Απαλοιφή πινελιών Show rulers Εμφάνιση χαράκων Presentation Παρουσίαση - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Κλικ για τοποθέτηση · Alt-κλικ ή σύρσιμο εκτός καμβά για αφαίρεση {n} of {max} sample points {n} από {max} σημεία δειγματοληψίας - -# History panel menu (#2966) New Snapshot… Νέο στιγμιότυπο… History Options… Επιλογές ιστορικού… -# History panel › History Options… (#2966) Allow Non-Linear History Να επιτρέπεται μη γραμμικό ιστορικό Make Layer Visibility Changes Undoable Οι αλλαγές ορατότητας επιπέδων να αναιρούνται -# Print dialog (#2697) Emulsion Down Γαλάκτωμα προς τα κάτω Functions Λειτουργίες Print Resolution: Ανάλυση εκτύπωσης: @@ -3876,7 +3922,6 @@ curves Smooth Εξομάλυνση Apply mask to layer before removing? Εφαρμογή της μάσκας στο επίπεδο πριν από την αφαίρεση; The layer or its mask changed. Drag the mask onto the Trash again. Το επίπεδο ή η μάσκα του άλλαξε. Σύρετε ξανά τη μάσκα στον Κάδο. Delete the vector mask? Διαγραφή της διανυσματικής μάσκας; -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} Εξήχθη {n} δείγμα χρώματος στο {file}|Εξήχθησαν {n} δείγματα χρωμάτων στο {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} Εισήχθη {n} πινέλο από την ομάδα {group}|Εισήχθησαν {n} πινέλα από την ομάδα {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} Εισήχθη {n} δείγμα χρώματος από το {file}|Εισήχθησαν {n} δείγματα χρωμάτων από το {file} @@ -3891,7 +3936,6 @@ curves Smooth Εξομάλυνση @plural {n} step|{n} steps {n} βήμα|{n} βήματα @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} ακόμη προειδοποίηση προεπιλογών πινέλων)|{warning} (+{n} ακόμη προειδοποιήσεις προεπιλογών πινέλων) @plural {what} with {n} warning|{what} with {n} warnings {what} με {n} προειδοποίηση|{what} με {n} προειδοποιήσεις -# View › Guides › New Guide… › Color Light Blue Ανοιχτό μπλε Light Red Ανοιχτό κόκκινο Medium Blue Μεσαίο μπλε @@ -3912,8 +3956,6 @@ curves Smooth Εξομάλυνση Clear Brush Controls Απαλοιφή στοιχείων ελέγχου πινέλου Reset All Locked Settings Επαναφορά όλων των κλειδωμένων ρυθμίσεων Copy Texture to Other Tools Αντιγραφή υφής σε άλλα εργαλεία - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Φόρτωση ενεργειών… Save Actions… Αποθήκευση ενεργειών… New Action… Νέα ενέργεια… @@ -3925,10 +3967,8 @@ curves Smooth Εξομάλυνση @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} βήμα δεν έχει ακόμη αντίστοιχο στο PhotoCraft|{n} βήματα δεν έχουν ακόμη αντίστοιχο στο PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Αποθηκεύτηκε {n} ενέργεια στο {file}|Αποθηκεύτηκαν {n} ενέργειες στο {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Παραλείφθηκε {n} βήμα χωρίς αντίστοιχο στο Photoshop|Παραλείφθηκαν {n} βήματα χωρίς αντίστοιχο στο Photoshop - File Naming Ονομασία αρχείων Starting serial Αρχικός αριθμός σειράς -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Εισαγωγή διακοπής… Save Set… Αποθήκευση συνόλου… Message: Μήνυμα: @@ -3939,11 +3979,8 @@ curves Smooth Εξομάλυνση Step {step} is waiting for its dialog Το βήμα {step} περιμένει το παράθυρο διαλόγου του @plural {n} action|{n} actions {n} ενέργεια|{n} ενέργειες Background (Default) Φόντο (προεπιλογή) -# Batch / Image Processor Include All Subfolders Συμπερίληψη όλων των υποφακέλων Auto Add/Delete Αυτόματη προσθήκη/διαγραφή - -# 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… Θυμηθείτε να απενεργοποιήσετε τη διαχείριση χρωμάτων του εκτυπωτή στις ρυθμίσεις εκτύπωσης… @@ -3988,7 +4025,6 @@ curves Smooth Εξομάλυνση Could not write {name}: {error} Αδυναμία εγγραφής του {name}: {error} Kept {name}: written by another application Το {name} διατηρήθηκε: γράφτηκε από άλλη εφαρμογή Shadow Tint Χροιά σκιών -# PhotoCraft release checks. Check for Updates… Έλεγχος ενημερώσεων… PhotoCraft Updates Ενημερώσεις PhotoCraft Checking for updates… Έλεγχος για ενημερώσεις… @@ -4001,37 +4037,28 @@ curves Smooth Εξομάλυνση Automatically Check for Updates Αυτόματος έλεγχος ενημερώσεων Installed version: {version} Εγκατεστημένη έκδοση: {version} PhotoCraft {version} is available. Το PhotoCraft {version} είναι διαθέσιμο. -# History panel › History Brush source (#2966) Paints from the History panel's source state Βάφει από την κατάσταση πηγής του πίνακα Ιστορικό Sets the source for the history brush Ορίζει την πηγή για το πινέλο ιστορικού -# Bevel & Emboss shading controls. Highlight Mode Λειτουργία φωτεινών τόνων Highlight Color Χρώμα φωτεινών τόνων Highlight Opacity Αδιαφάνεια φωτεινών τόνων Shadow Mode Λειτουργία σκιών Shadow Color Χρώμα σκιών Shadow Opacity Αδιαφάνεια σκιών -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Χρήση ενσωματωμένου προφίλ ({profile}) Convert to the working space ({profile}) Μετατροπή στον χώρο εργασίας ({profile}) Remember this choice for future images Απομνημόνευση αυτής της επιλογής για μελλοντικές εικόνες Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Ενεργοποιήστε ξανά την ερώτηση με το Ask On Mismatch στο Επεξεργασία › Ρυθμίσεις χρωμάτων. Button Mode Λειτουργία κουμπιών Button Mode On Λειτουργία κουμπιών ενεργή - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Σκουρότερο περιβάλλον Lighten Interface Φωτεινότερο περιβάλλον -# Bevel & Emboss Technique. Technique Τεχνική Chisel Hard Σκληρή σμίλευση Chisel Soft Μαλακή σμίλευση Open color-less EXR as ACEScg Άνοιγμα EXR χωρίς χρωματική δήλωση ως ACEScg Do not append "copy" to filename when saving a copy Να μην προστίθεται «copy» στο όνομα αρχείου κατά την αποθήκευση αντιγράφου -# Export As metadata and profile options EXIF EXIF - -# View › Guides › right-click a guide Edit Selected Guides Επεξεργασία επιλεγμένων οδηγών Clear Selected Guides Απαλοιφή επιλεγμένων οδηγών Bicubic Automatic Δικυβική αυτόματη @@ -4056,8 +4083,6 @@ curves Smooth Εξομάλυνση set name όνομα συνόλου {set} (modified) {set} (τροποποιημένο) Show file name in title Εμφάνιση ονόματος αρχείου στον τίτλο - -# Image › Mode › Bitmap (#5559) 50% Threshold Κατώφλι 50% Pattern Dither Πρόσμιξη μοτίβου Diffusion Dither Πρόσμιξη διάχυσης @@ -4075,10 +4100,8 @@ curves Smooth Εξομάλυνση Undo Changes Αναίρεση αλλαγών {shortcut} is reserved by the system and can't be assigned. Η συντόμευση {shortcut} δεσμεύεται από το σύστημα και δεν μπορεί να εκχωρηθεί. Low-Latency Drawing (vsync off, applies at next launch) Σχεδίαση χαμηλής καθυστέρησης (χωρίς vsync, ισχύει στην επόμενη εκκίνηση) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Ο Ελεύθερος μετασχηματισμός εφαρμόζεται ακόμη· δοκιμάστε ξανά όταν ολοκληρωθεί. The transform couldn't be applied. Δεν ήταν δυνατή η εφαρμογή του μετασχηματισμού. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Τα επίπεδά του χρειάζονται {needed} μνήμης GPU· το όριο τους αφήνει {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Ορίστε τη Μνήμη GPU στις Προτιμήσεις › Επιδόσεις σε όσο χωράει η κάρτα γραφικών σας, το πολύ στα 3/8 της μνήμης της. Το Αυτόματο ακολουθεί τη Χρήση μνήμης, εντός του ενός τετάρτου της μνήμης αυτού του υπολογιστή και των 3/8 της κάρτας, και δεν χρεώνει το έγγραφο σε κάρτα με γνωστή μνήμη. Όσο δεν χωρούν, η γραμμή κατάστασης δείχνει Η μνήμη GPU είναι πλήρης. GPU Memory Full Η μνήμη GPU είναι πλήρης @@ -4104,8 +4127,6 @@ curves Smooth Εξομάλυνση The fastest and the softest, with colour fringing on fine detail. Η πιο γρήγορη και η πιο μαλακή, με χρωματικά περιθώρια στις λεπτές λεπτομέρειες. “{name}” already exists. Replace it? Το «{name}» υπάρχει ήδη. Να αντικατασταθεί; The name in the save dialog was “{name}”. Το όνομα στο παράθυρο αποθήκευσης ήταν «{name}». - Move Up Μετακίνηση επάνω - Move Down Μετακίνηση κάτω Previous Brush Προηγούμενο πινέλο Next Brush Επόμενο πινέλο First Brush Πρώτο πινέλο @@ -4120,26 +4141,17 @@ curves Smooth Εξομάλυνση Use Χρήση In Front Μπροστά Behind Πίσω - -# DDS Options (#1327) DDS Options Επιλογές DDS Generate Mipmaps Δημιουργία mipmap - -# Color Table (.act) dialog There is no color table to save. Δεν υπάρχει πίνακας χρωμάτων για αποθήκευση. @plural Saved {n} color to {file}|Saved {n} colors to {file} Αποθηκεύτηκε {n} χρώμα στο {file}|Αποθηκεύτηκαν {n} χρώματα στο {file} - -# Graphics Adapter preference (#1885) GPU adapter Προσαρμογέας GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Εισαγωγή στιλ… Export Selected Styles… Εξαγωγή επιλεγμένων στιλ… Export Styles… Εξαγωγή στιλ… {file} is not a style library (.asl) Το {file} δεν είναι βιβλιοθήκη στιλ (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Εισήχθη {n} στιλ από το {file}|Εισήχθησαν {n} στιλ από το {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Εξήχθη {n} στιλ στο {file}|Εξήχθησαν {n} στιλ στο {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Επιβεβαιώστε ή ακυρώστε πρώτα το ανοιχτό παράθυρο βήματος της ενέργειας Pro Medium Gray Pro μεσαίου γκρι Solarized Solarized @@ -4148,28 +4160,11 @@ curves Smooth Εξομάλυνση Pro Light Φωτεινό Pro Resize Windows to Fit Προσαρμογή μεγέθους παραθύρων EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Αυτόματη κατεύθυνση παραγράφου Left-to-right paragraph direction Κατεύθυνση παραγράφου από αριστερά προς τα δεξιά Right-to-left paragraph direction Κατεύθυνση παραγράφου από δεξιά προς τα αριστερά Not rendered: this adjustment ({key}) is kept as imported. Δεν αποδίδεται: αυτή η προσαρμογή ({key}) διατηρείται όπως εισήχθη. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Με βάση το χρώμα - Decontaminate Colors Απολύμανση χρωμάτων - Edge Detection Ανίχνευση άκρης - Global Refinements Καθολικές βελτιώσεις - High Quality Preview Προεπισκόπηση υψηλής ποιότητας - Object Aware Με βάση το αντικείμενο - Real-Time Refinement Βελτίωση σε πραγματικό χρόνο - Refine Edge Brush Tool Εργαλείο πινέλου βελτίωσης ακμής - Refine Hair Βελτίωση μαλλιών - Refine Mode Λειτουργία βελτίωσης - Remember Settings Απομνημόνευση ρυθμίσεων - View Mode Λειτουργία προβολής - Object Aware needs a segmentation model, which isn't available yet Η λειτουργία Με βάση το αντικείμενο χρειάζεται μοντέλο τμηματοποίησης, που δεν είναι ακόμη διαθέσιμο - Refine Hair needs hair detection, which isn't available yet Η Βελτίωση μαλλιών χρειάζεται ανίχνευση μαλλιών, που δεν είναι ακόμη διαθέσιμη -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Κύβος απόχρωσης Brightness Cube Κύβος φωτεινότητας Color Wheel Χρωματικός τροχός @@ -4185,9 +4180,8 @@ curves Smooth Εξομάλυνση Grayscale Ramp Διαβάθμιση του γκρι Current Colors Τρέχοντα χρώματα Make Ramp Web Safe Μόνο χρώματα ιστού στη διαβάθμιση - Select and Mask was closed: its document is no longer the active one Η Επιλογή και μάσκα έκλεισε: το έγγραφό της δεν είναι πλέον το ενεργό - Select and Mask was closed: another layer was selected Η Επιλογή και μάσκα έκλεισε: επιλέχθηκε άλλο επίπεδο -# Art History Brush (#213). + The path was kept as the Work Path Η διαδρομή διατηρήθηκε ως διαδρομή εργασίας + The path was discarded Η διαδρομή απορρίφθηκε Art History Brush Tool Πινέλο ιστορικού τέχνης (Art History Brush Tool) Tight Short Σφιχτό κοντό Tight Medium Σφιχτό μεσαίο @@ -4198,9 +4192,24 @@ curves Smooth Εξομάλυνση Tight Curl Σφιχτή μπούκλα Loose Curl Χαλαρή μπούκλα Stylized dabs from a history state Στυλιζαρισμένες πινελιές από μια κατάσταση ιστορικού - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Στόχος Font size presets Προεπιλογές μεγέθους γραμματοσειράς Leading presets Προεπιλογές διάστιχου Tracking presets Προεπιλογές διαστήματος χαρακτήρων + Color Aware Με βάση το χρώμα + Decontaminate Colors Απολύμανση χρωμάτων + Edge Detection Ανίχνευση άκρης + Global Refinements Καθολικές βελτιώσεις + High Quality Preview Προεπισκόπηση υψηλής ποιότητας + Object Aware Με βάση το αντικείμενο + Real-Time Refinement Βελτίωση σε πραγματικό χρόνο + Refine Edge Brush Tool Εργαλείο πινέλου βελτίωσης ακμής + Refine Hair Βελτίωση μαλλιών + Refine Mode Λειτουργία βελτίωσης + Remember Settings Απομνημόνευση ρυθμίσεων + View Mode Λειτουργία προβολής + Object Aware needs a segmentation model, which isn't available yet Η λειτουργία Με βάση το αντικείμενο χρειάζεται μοντέλο τμηματοποίησης, που δεν είναι ακόμη διαθέσιμο + Refine Hair needs hair detection, which isn't available yet Η Βελτίωση μαλλιών χρειάζεται ανίχνευση μαλλιών, που δεν είναι ακόμη διαθέσιμη + Select and Mask was closed: its document is no longer the active one Η Επιλογή και μάσκα έκλεισε: το έγγραφό της δεν είναι πλέον το ενεργό + Select and Mask was closed: another layer was selected Η Επιλογή και μάσκα έκλεισε: επιλέχθηκε άλλο επίπεδο + Select Layer Under Cursor Επιλογή επιπέδου κάτω από τον δρομέα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4299cc0496..a2e0b19522 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -11,22 +11,87 @@ # resource, string table or product UI was consulted or copied; add entries the same way. # Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin # letters; the trailing "…" of dialog commands is kept. - # Layer Mask Display Options (the layer mask rubylith's colour and opacity) +# Channel Options and New Spot Channel (#3761) +# Guide layout dialog +# Custom print paper (#3820) +# Select and Mask dialog labels +# Field Blur pins (#3373) +# Dialogs and panels +# Layers-panel trash confirmation +# Tool names, brush and style option tables +# Templates with placeholders +# Preferences (labels are generated from the setting names) +# Added with the rebase onto the dock / brush picker work +# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). +# Gradient Editor window, opened from the options bar's gradient swatch. +# Tool, filter, warp-style, path, layer-comp and metadata names that fell outside the `tl!` test. +# Spanish follows the tool wording used above (Herramienta X). +# Command-id override: under Edit > Purge a bare "Deshacer" reads as an action, not the history. +# Rendering mode and recovery +# Camera Raw: contextual controls and window title +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) +# Shared screen eyedropper and text Color Picker (#1128). +# Fill dialog, layer style contours and Image Size +# Layer colour labels. +# Pattern Stamp tool +# Painting symmetry presets. +# Eyedropper Sample Size and Sample (#1649). +# Color Picker warnings +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Add Noise, Reduce Noise and Smart Sharpen dialog controls (Filter > Noise, Filter > Sharpen). +# Edit › Content-Aware Fill workspace +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) +# Color Sampler (added with the i18n coverage repair) +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color +# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) that the +# other catalogs already translate +# Path, channel, layer style, status and System Info labels the Czech catalog added +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# Export As metadata and profile options +# View › Guides › right-click a guide +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice +# DDS Options (#1327) +# Color Table (.act) dialog +# Graphics Adapter preference (#1885) +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). +# Smart Filter row actions (#1265) + Mask Options… Opciones de máscara… Layer Mask Display Options… Opciones de visualización de máscara de capa… - -# Channel Options and New Spot Channel (#3761) Channel Color Color del canal Color Indicates: El color indica: Solidity: Solidez: Masked Areas Áreas enmascaradas Selected Areas Áreas seleccionadas Ink Characteristics Características de la tinta - -# Guide layout dialog - -# Custom print paper (#3820) Paper Width Ancho del papel Paper Height Altura del papel Columns Columnas @@ -46,7 +111,6 @@ 5 Columns, 3 Rows 5 columnas, 3 filas 8 Columns 8 columnas 12 Columns 12 columnas - File Archivo Edit Edición Image Imagen @@ -402,8 +466,8 @@ Summation Sumatoria Variance Varianza Video Layers Capas de vídeo - Interpret Footage… Interpretar material de archivo… - Replace Footage… Reemplazar material de archivo… + Interpret Footage… Interpretar material de vídeo… + Replace Footage… Reemplazar material de vídeo… Reload Frame Recargar fotograma Show Altered Video Mostrar vídeo alterado Restore Frame Restaurar fotograma @@ -455,6 +519,7 @@ Intersect Shape Areas Intersecar áreas de formas Exclude Overlapping Shapes Excluir formas superpuestas Merge Shape Components Combinar componentes de formas + Path operations Operaciones de trazado Align Alinear Top Edges Bordes superiores Vertical Centers Centros verticales @@ -534,7 +599,6 @@ Color Range… Gama de colores… Focus Area… Área de enfoque… Select and Mask… Selección y máscara… -# Select and Mask dialog labels Smart Radius Radio inteligente Shift Edge Desplazar borde Decontaminate Descontaminar @@ -561,7 +625,6 @@ Blur Desenfocar Blur Gallery Galería de desenfoque Field Blur… Desenfoque de campo… -# Field Blur pins (#3373) No pin selected Ningún pin seleccionado Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Haga clic en la imagen para añadir un pin; arrastre un pin para moverlo o su anillo para cambiar el desenfoque. Suprimir elimina el pin seleccionado. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Arrastre los manejadores del contorno para cambiar su tamaño y girarlo, el cuadrado para redondear las esquinas y los puntos interiores para fijar dónde empieza el desenfoque. @@ -569,7 +632,7 @@ Drag the handles on the outline to resize and turn it; the ring sets the blur angle. Arrastre los manejadores del contorno para cambiar su tamaño y girarlo; el anillo fija el ángulo de desenfoque. Blur Angle Ángulo de desenfoque Iris Blur… Desenfoque de iris… - Tilt-Shift… Cambio de inclinación… + Tilt-Shift… Desenfoque de inclinación y desplazamiento… Path Blur… Desenfoque de trazado… Spin Blur… Desenfoque de rotación… Blur More Desenfocar más @@ -602,7 +665,7 @@ Crystallize… Cristalizar… Facet Faceta Fragment Fragmento - Mezzotint… Grabado… + Mezzotint… Grabado a media tinta… Mosaic… Mosaico… Pointillize… Puntillista… Render Interpretar @@ -618,7 +681,7 @@ Sharpen Enfocar Sharpen Edges Enfocar bordes Sharpen More Enfocar más - Smart Sharpen… Enfoque suavizado… + Smart Sharpen… Enfoque inteligente… Unsharp Mask… Máscara de enfoque… High Pass… Paso alto… Stylize Estilizar @@ -827,8 +890,6 @@ Edits Ediciones @plural {n} item|{n} items {n} elemento|{n} elementos Auto Automático - -# Dialogs and panels (print to the printer) (imprimir en la impresora) + Add variable + Añadir variable 30 frames @ 30 fps 30 fotogramas @ 30 fps @@ -842,6 +903,9 @@ Add Layer Mask Añadir máscara de capa Add Stop Añadir parada Add a layer style Añadir un estilo de capa + Move effect up Subir efecto + Move effect down Bajar efecto + Delete effect Eliminar efecto Add a mask (from the selection; {key} inverts) Añadir una máscara (de la selección; {key} la invierte) Add an adjustment Añadir un ajuste Add disk Añadir disco @@ -1066,8 +1130,6 @@ Delete current channel Eliminar el canal actual Delete current state Eliminar el estado actual Delete effect layer Eliminar capa de efecto - -# Layers-panel trash confirmation Delete layer ‘{name}’? ¿Eliminar la capa «{name}»? Delete {count} layers? {names} ¿Eliminar {count} capas? {names} Delete layer? ¿Eliminar capa? @@ -1076,7 +1138,6 @@ Missing delete command Falta el comando de eliminación Invalid delete command Comando de eliminación no válido Layer deleted, but confirmation preference could not be saved: {error} La capa se eliminó, pero no se pudo guardar la preferencia de confirmación: {error} - Delete layer Eliminar capa Delete layer comp Eliminar composición de capa Delete note Eliminar nota @@ -1109,7 +1170,6 @@ Dots Puntos Drag a rectangle around the object Arrastre un rectángulo alrededor del objeto Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Arrastre sobre la imagen para añadir una restricción; Mayús para horizontal/vertical; clic derecho en una restricción para cambiarla o eliminarla. - Drag to move the active shape's path or the Work Path Arrastre para mover el trazado de la forma activa o el trazado de trabajo Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Clic: seleccionar punto · Arrastrar: mover punto, manejador o segmento · {shift}-clic: añadir · {alt}-clic: subtrazado completo Draw with the Pen tool (P) or make a work path from a selection. Dibuje con la herramienta Pluma (P) o cree un trazado de trabajo a partir de una selección. Drop an image or PSD anywhere to open it. Suelte una imagen o un PSD en cualquier lugar para abrirlo. @@ -1631,8 +1691,6 @@ No saved presets yet. Todavía no hay ajustes preestablecidos guardados. Error Error Command Comando - -# Tool names, brush and style option tables Adjustment layers have nothing to transform Las capas de ajuste no tienen nada que transformar Altitude Altitud Android 1080p Android 1080p @@ -1865,8 +1923,6 @@ Yellows Amarillos Zoom Tool Herramienta Zoom {name} Properties Propiedades de {name} - -# Templates with placeholders Revert “{name}” to the last saved version? Your changes will be lost. ¿Desea volver «{name}» a la última versión guardada? Se perderán los cambios. Do you want to save the changes you made to “{name}” before quitting? ¿Desea guardar los cambios realizados en «{name}» antes de salir? Do you want to save the changes you made to “{name}” before closing? ¿Desea guardar los cambios realizados en «{name}» antes de cerrar? @@ -1887,8 +1943,6 @@ @plural {n} Layer|{n} Layers {n} capa|{n} capas @plural {n} layer|{n} layers {n} capa|{n} capas @plural Group · {n} layer|Group · {n} layers Grupo · {n} capa|Grupo · {n} capas - -# Preferences (labels are generated from the setting names) Additional plugins folder Carpeta adicional de plugins Adobe Adobe Adobe rgb Adobe RGB @@ -2088,8 +2142,6 @@ Luminosity Luminosidad @plural {n} sample|{n} samples {n} muestra|{n} muestras {added}, {removed} subtracted {added}, {removed} restados - -# Added with the rebase onto the dock / brush picker work Adjustment Preview Vista previa de ajuste Airbrush: keeps depositing paint while the pointer rests. Aerógrafo: sigue depositando pintura mientras el puntero permanece quieto. Angle: Ángulo: @@ -2121,8 +2173,6 @@ Brush picker Selector de pinceles Erase Borrar Right click with painting tools Clic derecho con herramientas de pintura - -# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). System Info… Información del sistema… System Info Información del sistema More panels Más paneles @@ -2193,7 +2243,6 @@ 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) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Editor de degradados Gradient picker Selector de degradados Save As Preset Guardar como ajuste preestablecido @@ -2252,8 +2301,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Cuadrícula: -# Tool, filter, warp-style, path, layer-comp and metadata names that fell outside the `tl!` test. -# Spanish follows the tool wording used above (Herramienta X). Color Range Gama de colores Adaptive Wide Angle Gran angular adaptable Chalk & Charcoal Tiza y carboncillo @@ -2336,9 +2383,7 @@ New Channel Nuevo canal Save Selection Guardar selección Load Selection Cargar selección -# Command-id override: under Edit > Purge a bare "Deshacer" reads as an action, not the history. @id edit.purge.undo Historial de deshacer -# Rendering mode and recovery Rendering Mode Modo de renderizado Automatic (recommended) Automático (recomendado) CPU / Compatibility CPU / Compatibilidad @@ -2365,7 +2410,6 @@ Tone Histogram Histograma tonal Show Selected Region Mostrar región seleccionada cameraRaw Light Luz -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Filtro de Camera Raw ({layer}) Camera Raw ({name}) Camera Raw ({name}) cameraRaw Lights Claros @@ -2389,14 +2433,10 @@ cameraRaw Amount Cantidad Scale or rotate the moved area, then press {key} Escale o gire el área movida y pulse {key} Now drag the selection onto another area Ahora arrastre la selección a otra área Edit Type Editar texto - - New Style… Nuevo estilo… Style {name} saved Estilo {name} guardado - Create new style (from the selected type) Crear estilo nuevo (del texto seleccionado) Create new style from the selected layer Crear estilo nuevo de la capa seleccionada - Make Default Establecer como predeterminado Reset to Default Restablecer valores predeterminados Full-resolution preview unavailable Vista previa a resolución completa no disponible @@ -2424,9 +2464,6 @@ cameraRaw Amount Cantidad 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 - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About Acerca de Contributors Colaboradores Models Modelos @@ -2457,8 +2494,6 @@ cameraRaw Amount Cantidad % of all commits % de todos los commits Lines +/− Líneas +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commits, +{added} / −{deleted} líneas (Δ {delta}), +{binAdded} / −{binDeleted} archivos binarios, {first} – {last} - -# Swatches panel Create new swatch Crear una muestra nueva New Swatch… Muestra nueva… New Swatch Group… Grupo de muestras nuevo… @@ -2468,13 +2503,11 @@ cameraRaw Amount Cantidad Export Swatches for Exchange… Exportar muestras para intercambio… Reset Swatches Restablecer muestras Add to Swatches Añadir a muestras -# Layer Style > Blending Options (Advanced Blending) Blend If: Fusionar si: + Current Layer: Capa actual: Channels: Canales: Knockout Extraer Apply At Canvas Bounds Aplicar en los límites del lienzo - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Selector de color (Color del texto) Color Picker ({name}) Selector de color ({name}) Color Picker (Fill Color) Selector de color (Color de relleno) @@ -2491,8 +2524,6 @@ cameraRaw Amount Cantidad Show/Hide Panels Mostrar/ocultar paneles Could not open No se pudo abrir {path}: the path is not valid Unicode; rename the file and open it again. {path}: la ruta no es Unicode válido; cambie el nombre del archivo y vuelva a abrirlo. - -# Fill dialog, layer style contours and Image Size Contents: Contenido: Custom Pattern: Motivo personalizado: Foreground Color Color frontal @@ -2518,7 +2549,6 @@ cameraRaw Amount Cantidad Rolling Slope - Descending Pendiente ondulada - descendente Rounded Steps Pasos redondeados Sawtooth 1 Diente de sierra 1 - Red Eye Tool Herramienta Ojos rojos Red Eye Ojos rojos Pupil Size Tamaño de pupila @@ -2526,7 +2556,6 @@ cameraRaw Amount Cantidad Click a red pupil to neutralize it Haga clic en una pupila roja para corregirla open source código abierto …and {n} more …y {n} más - Eyedroppers: Cuentagotas: Set Black Point Definir punto negro Set Neutral Gray Point Definir punto gris neutro @@ -2535,8 +2564,6 @@ cameraRaw Amount Cantidad Selection Preview: Vista previa de la selección: Black Matte Sobre negro White Matte Sobre blanco - -# Layer colour labels. Seafoam Espuma de mar Indigo Índigo Fuchsia Fucsia @@ -2557,8 +2584,6 @@ fontWeight Bold Negrita fontWeight ExtraBold Extranegra fontWeight Black Ultranegra fontWeight Italic Cursiva - -# Pattern Stamp tool Pattern Stamp Tool Herramienta Tampón de motivo Pattern Stamp Tampón de motivo Impressionist Impresionista @@ -2566,13 +2591,9 @@ fontWeight Italic Cursiva 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° - -# Painting symmetry presets. Dual Axis Doble eje Diagonal Diagonal Transform Symmetry Transformar simetría - -# Eyedropper Sample Size and Sample (#1649). Point Sample Muestra puntual 3 by 3 Average Promedio de 3 × 3 5 by 5 Average Promedio de 5 × 5 @@ -2584,15 +2605,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Color a alfa… Transparency Threshold Umbral de transparencia Opacity Threshold Umbral de opacidad PhotoCraft — Screen Color Picker PhotoCraft — Selector de color de pantalla - Rasterize svg groups deeper than Rasterizar grupos SVG con mayor profundidad 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 desactiva este umbral; los grupos SVG anidados a más de 100 niveles siempre se rasterizan. Rule of Thirds Regla de los tercios @@ -2606,8 +2624,6 @@ fontWeight Italic Cursiva Cycle Orientation Alternar orientación Set the overlay options for the Crop tool Definir las opciones de superposición de la herramienta Recortar Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. El Alt+clic lo recibió el escritorio, que mueve ventanas con Alt+arrastrar. Cambie su tecla para mover ventanas a Super o bloquee Alt en Ventana › Teclas modificadoras. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Selector de color (color del estilo de capa) Auto Hide Notifications Ocultar notificaciones automáticamente Notification Duration (seconds) Duración de la notificación (segundos) @@ -2684,7 +2700,6 @@ fontWeight Italic Cursiva Appearance Settings… Ajustes de apariencia… Add to favorites Añadir a favoritos Remove from favorites Quitar de favoritos -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data Datos de cámara cameraData Make Marca cameraData Model Modelo @@ -2695,7 +2710,6 @@ cameraData ISO Speed Sensibilidad ISO cameraData Focal Length Longitud focal cameraData Focal Length (35 mm) Longitud focal (35 mm) cameraData Lens Objetivo -# Shared panel docking Activate Panel Activar panel Change Panel Group Cambiar grupo de paneles Change Panel Layout Cambiar disposición de paneles @@ -2707,8 +2721,6 @@ cameraData Lens Objetivo Panel menu Menú del panel Resize panel window Cambiar tamaño de la ventana del panel Resize panels Cambiar tamaño de los paneles - -# Add Noise, Reduce Noise and Smart Sharpen dialog controls (Filter > Noise, Filter > Sharpen). Distribution Distribución Uniform Uniforme Gaussian Gaussiana @@ -2751,7 +2763,6 @@ cameraData Lens Objetivo Snap to Origin Ajustar a origen Search settings… Buscar ajustes… No matching settings No hay ajustes que coincidan -# Edit › Content-Aware Fill workspace Sampling Brush Tool Herramienta Pincel de muestreo Sampling Area Overlay Superposición del área de muestreo Show Sampling Area Mostrar área de muestreo @@ -2767,7 +2778,6 @@ cameraData Lens Objetivo Mirror Reflejar Output Settings Ajustes de salida Output To Salida a - Animation Options Opciones de animación Entire Document Documento entero Filter Options Opciones de filtro @@ -2787,8 +2797,6 @@ cameraData Lens Objetivo Add “copy” to Copied Layers and Groups Añadir «copia» a las capas y grupos duplicados Preview on canvas when reordering layers Previsualizar en el lienzo al reordenar capas Show layer mask badges Mostrar insignias de máscaras de capa - -# Smart Filter editors Blending Options ({filter}) Opciones de fusión ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Ocultar efectos de capa y filtros inteligentes ({key}-clic: todas las capas) Show the layer's effects and Smart Filters ({key}-click: all layers) Mostrar efectos de capa y filtros inteligentes ({key}-clic: todas las capas) @@ -2823,7 +2831,6 @@ curves Smooth Suavizar Fix the red plane first: its corners must form a convex quad Corrija primero el plano rojo: sus esquinas deben formar un cuadrilátero convexo Alt-click a plane to set the clone source Haga Alt-clic en un plano para definir el origen de clonación Too many clone strokes: apply Vanishing Point first Demasiados trazos de clonación: aplique primero Punto de fuga -# Select and Mask view modes (#1754) Onion Skin Papel cebolla Marching Ants Hormigas en marcha On Black Sobre negro @@ -2832,7 +2839,6 @@ curves Smooth Suavizar Show Edge Mostrar borde Show Original Mostrar original F cycles the views; hold X to see the image F alterna las vistas; mantén X para ver la imagen -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Pincel para perfeccionar bordes (R) Expand Detection Area Ampliar área de detección Restore Original Edge Restaurar borde original @@ -2840,19 +2846,13 @@ curves Smooth Suavizar Clear Brush Strokes Borrar trazos de pincel Show rulers Mostrar reglas Presentation Presentación - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Clic para colocar · Alt-clic o arrastrar fuera del lienzo para quitar No document open Ningún documento abierto {n} of {max} sample points {n} de {max} puntos de muestreo - -# History panel menu (#2966) New Snapshot… Nueva instantánea… History Options… Opciones de historial… -# History panel › History Options… (#2966) Allow Non-Linear History Permitir historia no lineal Make Layer Visibility Changes Undoable Permitir deshacer los cambios de visibilidad de capas -# Print dialog (#2697) Emulsion Down Emulsión hacia abajo Functions Funciones Print Resolution: Resolución de impresión: @@ -2864,7 +2864,6 @@ curves Smooth Suavizar Apply mask to layer before removing? ¿Aplicar la máscara a la capa antes de eliminarla? The layer or its mask changed. Drag the mask onto the Trash again. La capa o su máscara ha cambiado. Arrastre de nuevo la máscara a la papelera. Delete the vector mask? ¿Eliminar la máscara vectorial? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} Se exportó {n} muestra a {file}|Se exportaron {n} muestras a {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} Se importó {n} pincel de {group}|Se importaron {n} pinceles de {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} Se importó {n} muestra de {file}|Se importaron {n} muestras de {file} @@ -2879,7 +2878,6 @@ curves Smooth Suavizar @plural {n} step|{n} steps {n} paso|{n} pasos @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} advertencia más de ajustes preestablecidos de pincel)|{warning} (+{n} advertencias más de ajustes preestablecidos de pincel) @plural {what} with {n} warning|{what} with {n} warnings {what} con {n} advertencia|{what} con {n} advertencias -# View › Guides › New Guide… › Color Light Blue Azul claro Light Red Rojo claro Medium Blue Azul medio @@ -2896,8 +2894,6 @@ curves Smooth Suavizar Delete Contour Eliminar contorno Loaded contours from {file} Contornos cargados de {file} Saved contours to {file} Contornos guardados en {file} -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) that the -# other catalogs already translate @id select.all Seleccionar todo Delete Smart Filters Eliminar filtros inteligentes Enable Smart Filters Activar filtros inteligentes @@ -2909,29 +2905,29 @@ curves Smooth Suavizar 3D 3D Toolbars Barras de herramientas Wand Varita - Healing Corrección + Healing Corrector Pen Pluma Hand Mano Sampler Muestreador Magnetic Lasso Lazo magnético Art History Brush Pincel histórico artístico - Spot Healing Corrección puntual + Spot Healing Corrector puntual Patch Parche Content-Aware Move Mover con detección de contenido - Perspective Crop Recorte con perspectiva - Dodge/Burn Sobreexponer/Subexponer + Perspective Crop Recortar con perspectiva + Dodge/Burn Sobreexponer/subexponer Dynamics Dinámica Tilt Inclinación Defaults restored. Valores predeterminados restaurados. Stop Detener Create new set Crear nuevo conjunto Technology Previews Previsualizaciones de tecnología - Create new layer Crear nueva capa + Create new layer Crear una capa nueva Group · {n} layer Grupo · {n} capa General Blend Fusión general Advanced Blending Fusión avanzada RGB RGB - Spot Channel Canal de tinta plana + Spot Channel Canal de color plano Working Gray Plate Placa gris de trabajo HSL/Grayscale HSL/Escala de grises Tone Curve Curva de tonos @@ -2955,7 +2951,7 @@ curves Smooth Suavizar ProPhoto ProPhoto ACES ACES Industry Standard Estándar del sector - Uncoated CMYK CMYK sin estucar + Uncoated CMYK CMYK para papel no estucado Newspaper Papel de periódico Working Spaces Espacios de trabajo Color Management Policies Normas de gestión de color @@ -3011,7 +3007,7 @@ curves Smooth Suavizar Hanging Punctuation Puntuación colgante Roman Hanging Punctuation Puntuación latina colgante Avoid Widows/Orphans Evitar líneas viudas y huérfanas - Compose Composición + Compose Componer Adobe Single-line Composer Compositor de línea única de Adobe Adobe Every-line Composer Compositor multilínea de Adobe Word Spacing Espacio entre palabras @@ -3078,7 +3074,7 @@ curves Smooth Suavizar Select All Layers Seleccionar todas las capas Keep proportions Mantener proporciones Interpolation Interpolación - Caption Pie de foto + Caption Leyenda Caption Credits Créditos del pie de foto Keywords Palabras clave Copyright Info URL URL de información de copyright @@ -3147,7 +3143,7 @@ curves Smooth Suavizar RGB: RGB: CMYK: CMYK: Gray: Gris: - Spot: Tinta plana: + Spot: Color plano: Advanced Controls Controles avanzados Desaturate Monitor Colors By Desaturar colores del monitor un Blend RGB Colors Using Gamma 1.0 Fusionar colores RGB con gamma 1,0 @@ -3177,7 +3173,7 @@ curves Smooth Suavizar Recent Items Elementos recientes Delete Preset… Eliminar ajuste preestablecido… Preset Name: Nombre del ajuste preestablecido: - Width and Height Anchura y altura + Width and Height Ancho y alto Color Profile Perfil de color Units Unidades Create new count group Crear nuevo grupo de recuento @@ -3193,20 +3189,20 @@ curves Smooth Suavizar Rotate Fixed Rotación fija Select Plane Seleccionar plano Measure Medir - Heal Corrección + Heal Corregir Heal Off Corrección desactivada Heal On Corrección activada Heal Auto Corrección automática - Blend Fusión + Blend Fusionar Brush Size Tamaño del pincel Heal Color Color de corrección Result Resultado Duplicate Duplicar - Fast Rápida + Fast Rápido Accurate Precisa Add to Añadir a Subtract from Restar de - Intersect with Formar intersección con + Intersect with Intersecar con Capture Comp Capturar composición No Layer Comps No hay composiciones de capas Adobe PDF Presets… Ajustes preestablecidos de Adobe PDF… @@ -3231,7 +3227,7 @@ curves Smooth Suavizar General Brushes Pinceles generales Grid (⌘') Cuadrícula (⌘') Intersect with selection (⇧⌥) Formar intersección con la selección (⇧⌥) - New document… ⌘N Nuevo documento… ⌘N + New document… ⌘N Documento nuevo… ⌘N Open… ⌘O Abrir… ⌘O Rulers (⌘R) Reglas (⌘R) Search commands (⌘K) Buscar comandos (⌘K) @@ -3248,8 +3244,8 @@ curves Smooth Suavizar Show the layer's effects (⌥-click: all layers) Mostrar los efectos de la capa (⌥-clic: todas las capas) cameraRaw Blacks Negros cameraRaw Masking Enmascarado -@id edit.stroke Contornear -@id edit.transform.scale Escala +@id edit.stroke Contornear… +@id edit.transform.scale Escalar cameraRaw Luminance Luminancia cameraRaw Color Color cameraRaw Vibrance Intensidad @@ -3269,14 +3265,14 @@ layerLabel No Color Sin color Linear Dodge Sobreexposición lineal Preview Image Previsualizar imagen Save As Guardar como - Remove All Eliminar todo + Remove All Quitar todo Unlock Desbloquear Enable Activar Disable Desactivar On Activado Clear Selection Borrar selección Invert Selection Invertir selección - Select Inverse Seleccionar inverso + Select Inverse Invertir selección Contract Contraer Sample Size Tamaño de muestra Gamma Gamma @@ -3302,7 +3298,7 @@ layerLabel No Color Sin color Hidden Oculto Duplicate Layer Duplicar capa Ungroup Desagrupar - Guide Layout… Composición de guías… + Guide Layout… Diseño de guías… Page Setup… Configurar página… Reset Preferences Restablecer preferencias Documentation Documentación @@ -3312,8 +3308,8 @@ layerLabel No Color Sin color Saving… Guardando… Exporting… Exportando… Please wait… Espere… - No selection Ninguna selección - No layers Ninguna capa + No selection Sin selección + No layers Sin capas No recent files Ningún archivo reciente Unsupported file format Formato de archivo no compatible Failed to open file No se pudo abrir el archivo @@ -3328,7 +3324,7 @@ layerLabel No Color Sin color Rendering… Procesando… Importing… Importando… Ready Listo - Failed Error + Failed Falló Warning Advertencia Information Información Retry Reintentar @@ -3354,18 +3350,18 @@ layerLabel No Color Sin color Edit… Editar… Change… Cambiar… Transformation Transformación - Scaling Escala + Scaling Escalado Canvas Size Tamaño de lienzo Percentage Porcentaje Degrees Grados - Middle Medio + Middle Centro Diameter Diámetro Intensity Intensidad Sensitivity Sensibilidad Softness Suavidad Feather Radius Radio de calado Library Biblioteca - Layer Properties Propiedades de capa + Layer Properties Propiedades de la capa Groups Grupos Masks Máscaras Add Mask Añadir máscara @@ -3513,7 +3509,7 @@ layerLabel No Color Sin color Center Y Centro Y Cell Size Tamaño de celda Generators Generadores - Wavelength Min Longitud de onda mínima + Wavelength Min Longitud de onda mín. Wavelength Max Longitud de onda máxima Amplitude Min Amplitud mínima Amplitude Max Amplitud máxima @@ -3624,8 +3620,8 @@ layerLabel No Color Sin color Bamboo Bambú Bas Relief Bajorrelieve Berries Bayas - Blast Ráfaga - Bleach Bypass Omisión de blanqueado + Blast Explosión + Bleach Bypass Retención de plata Blocks Bloques Brick Ladrillo Brush Strokes Trazos de pincel @@ -3637,20 +3633,20 @@ layerLabel No Color Sin color Colored Pencil Lápiz de color Contrasty Contrastado Cool Frío - Craquelure Cuarteado + Craquelure Craquelado Cross Cruz Cross Process Proceso cruzado Crosshatch Sombreado cruzado - Cutout Recortado + Cutout Recortes Daisies Margaritas Dark Rough Oscuro rugoso Dark Strokes Trazos oscuros Darken Only Solo oscurecer Day For Night Noche americana - Deep Blue Azul intenso - Deep Emerald Esmeralda intenso - Deep Red Rojo intenso - Deep Yellow Amarillo intenso + Deep Blue Azul profundo + Deep Emerald Esmeralda profundo + Deep Red Rojo profundo + Deep Yellow Amarillo profundo Dot Punto Double Line Línea doble Draft Borrador @@ -3661,7 +3657,7 @@ layerLabel No Color Sin color Enlarged Ampliado Even Fields Campos pares Faded Film Película desvanecida - Film Grain Granulado de película + Film Grain Grano de película Fine Fino Fine Dots Puntos finos Flat Plano @@ -3671,7 +3667,7 @@ layerLabel No Color Sin color Frosted Escarchado Generic Genérico Glass Vidrio - Glowing Edges Bordes resplandecientes + Glowing Edges Bordes brillantes Grainy Dots Puntos granulados Hearts Corazones Heptagon Heptágono @@ -3691,7 +3687,7 @@ layerLabel No Color Sin color Medium Lines Líneas medianas Medium Strokes Trazos medianos Mono Contrast Contraste monocromo - Mosaic Tiles Azulejos de mosaico + Mosaic Tiles Teselas de mosaico Multiple Flames Along Path Varias llamas a lo largo del trazado Multiple Flames One Direction Varias llamas en una dirección Multiple Flames Path Directions Varias llamas en las direcciones del trazado @@ -3704,7 +3700,7 @@ layerLabel No Color Sin color Overlay Edge Borde superpuesto Palette Knife Espátula Parallel Paralelo - Patchwork Retales + Patchwork Retazos Pentagon Pentágono Point Punto Pointed Puntiagudo @@ -3753,7 +3749,7 @@ layerLabel No Color Sin color Correct C A Corregir AC Auto Scale Escala automática Red Cyan Rojo/Cian - Blue Yellow Azul/Amarillo + Blue Yellow Azul/amarillo Vignette Amount Cantidad de viñeta Vignette Midpoint Punto medio de la viñeta Constraints Restricciones @@ -3775,17 +3771,17 @@ layerLabel No Color Sin color Grade Global Gradación global Grade Blending Fusión de gradación Grade Balance Equilibrio de gradación - Sine Seno + Sine Sinusoidal Sketch Boceto Snowflakes Copos de nieve Sparkle Destellos Spatter Salpicadura - Speckle Motas + Speckle Moteado Spin Giro Sprinkles Espolvoreado - Squareness Cuadratura + Squareness Forma cuadrada Stagger Escalonado - Stained Glass Vidriera + Stained Glass Vitral Star Estrella Stars Estrellas Stippled Punteado @@ -3793,9 +3789,9 @@ layerLabel No Color Sin color Teal Orange Verde azulado y naranja Tiny Lens Lente diminuta To Center Hacia el centro - Unaltered Sin alterar - Underpainting Pintura base - Underwater Bajo el agua + Unaltered Inalterado + Underpainting Pintura de base + Underwater Subacuático Upper Superior Vertical Only Solo vertical Vine With Flowers Enredadera con flores @@ -3875,7 +3871,7 @@ layerLabel No Color Sin color Highlight Iluminación Image Processor Procesador de imágenes Install Plug-in Instalar plugin - Interpret Footage Interpretar material de archivo + Interpret Footage Interpretar material de vídeo Iris Blur Desenfoque de iris Jag Dentado Label Etiqueta @@ -3893,18 +3889,18 @@ layerLabel No Color Sin color Lum Lum Match Color Igualar color Merge to HDR Pro Combinar en HDR Pro - Mezzotint Grabado + Mezzotint Grabado a media tinta Mosaic Mosaico Motion Blur Desenfoque de movimiento Native file drag-and-drop is not supported on Wayland yet. Use File › Open, or run PhotoCraft under XWayland with `WAYLAND_DISPLAY= photocraft`. Arrastrar y soltar archivos de forma nativa aún no es compatible con Wayland. Use Archivo › Abrir o ejecute PhotoCraft mediante XWayland con `WAYLAND_DISPLAY= photocraft`. Neon Glow Resplandor de neón New Guide Layout Nuevo diseño de guías New Video Layer from File Nueva capa de vídeo desde archivo - Ocean Ripple Ondas marinas + Ocean Ripple Ondulación oceánica Oil Paint Pintura al óleo Open As Abrir como Package Empaquetar - Paint Daubs Pinceladas + Paint Daubs Manchas de pintura Path Blur Desenfoque de trazado Paths to Illustrator Trazados a Illustrator Photomerge Photomerge @@ -3913,11 +3909,11 @@ layerLabel No Color Sin color Place Embedded Colocar incrustado Place Linked Colocar vinculado Place Scale Marker Colocar marcador de escala - Plastic Wrap Plastificado + Plastic Wrap Envoltura de plástico Pointillize Puntillista Polar Coordinates Coordenadas polares Polar To Rectangular Polar a rectangular - Poster Edges Bordes de cartel + Poster Edges Bordes posterizados Preset Manager Gestor de ajustes preestablecidos Profile Perfil Radial Blur Desenfoque radial @@ -3927,35 +3923,35 @@ layerLabel No Color Sin color Render Video Procesar vídeo Replace Color Reemplazar color Replace Contents Reemplazar contenido - Replace Footage Reemplazar material de archivo + Replace Footage Reemplazar material de vídeo Resolve Missing Fonts Resolver fuentes que faltan Ripple Ondulación - Rough Pastels Pasteles rugosos + Rough Pastels Pasteles ásperos Sat Sat Save a Copy Guardar una copia Save for Web (Legacy) Guardar para web (heredado) Scale Effects Escalar efectos Script Events Manager Administrador de eventos de secuencias de comandos - Search menus Buscar en menús - Select and Mask Seleccionar y aplicar máscara + Search menus Buscar en los menús + Select and Mask Selección y máscara Set Measurement Scale Definir escala de medida Shadows/Highlights Sombras/iluminaciones Shape Blur Desenfoque de forma Shear Inclinación Smart Blur Desenfoque inteligente - Smart Sharpen Enfoque suavizado - Smudge Stick Barra de difuminado + Smart Sharpen Enfoque inteligente + Smudge Stick Difumino Solid Color Color sólido Spherize Esferizar Spin Blur Desenfoque de rotación - Spot Tinta plana - Sprayed Strokes Trazos con spray + Spot Foco + Sprayed Strokes Trazos rociados Strokes Trazos Sumi-e Sumi-e Surface Blur Desenfoque de superficie - Texturizer Texturizar + Texturizer Texturizador Tiles Azulejos - Tilt-Shift Cambio de inclinación + Tilt-Shift Desenfoque de inclinación y desplazamiento Trace Contour Trazar contorno Trap Reventado Tree Árbol @@ -3983,24 +3979,23 @@ layerLabel No Color Sin color Hsb HSB Hsl HSL Movie Prime Película Prime - Prime105 Prime 105 - Prime35 Prime 35 + Prime105 Objetivo fijo de 105 mm + Prime35 Objetivo fijo de 35 mm Warming L B A Calentamiento LBA Warming81 Calentamiento 81 Warming85 Calentamiento 85 @id filter.sharpen.sharpen Enfocar Good Buena - Best Óptima - Adjustment Properties Propiedades de ajuste + Best Mejor + Adjustment Properties Propiedades del ajuste Default Foreground and Background Colors Colores frontal y de fondo predeterminados Move Layer Mover capa Rectangular Selection Selección rectangular Reorder Layer Reordenar capa Select Layer Seleccionar capa Set Colors Definir colores - Switch Foreground and Background Colors Intercambiar colores frontal y de fondo + Switch Foreground and Background Colors Intercambiar los colores frontal y de fondo Target Destino -# Path, channel, layer style, status and System Info labels the Czech catalog added Make Work Path… Crear trazado de trabajo… Create Vector Mask Crear máscara vectorial Make Selection… Crear selección… @@ -4041,7 +4036,6 @@ layerLabel No Color Sin color Layer Mask Hides Effects La máscara de capa oculta los efectos Vector Mask Hides Effects La máscara vectorial oculta los efectos General Blending Fusión general - This Layer: Esta capa: Underlying Layer: Capa subyacente: Nothing to paste: the clipboard holds no image Nada que pegar: el portapapeles no contiene ninguna imagen Preferences saved Preferencias guardadas @@ -4156,7 +4150,7 @@ navigator Zoom Zoom manual manual Medium Gray Gris medio New document Documento nuevo - New Selection Selección nueva + New Selection Nueva selección No Document Sin documento Note tool Herramienta Nota off desactivado @@ -4176,8 +4170,6 @@ navigator Zoom Zoom Clear Brush Controls Borrar controles de pincel Reset All Locked Settings Restaurar todos los ajustes bloqueados Copy Texture to Other Tools Copiar textura en otras herramientas - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Cargar acciones… Save Actions… Guardar acciones… New Action… Nueva acción… @@ -4189,9 +4181,7 @@ navigator Zoom Zoom @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} paso aún no tiene equivalente en PhotoCraft|{n} pasos aún no tienen equivalente en PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Se guardó {n} acción en {file}|Se guardaron {n} acciones en {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} paso sin equivalente en Photoshop omitido|{n} pasos sin equivalente en Photoshop omitidos - Starting serial Número de serie inicial -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Insertar detención… Save Set… Guardar conjunto… Message: Mensaje: @@ -4202,11 +4192,8 @@ navigator Zoom Zoom Step {step} is waiting for its dialog El paso {step} está esperando su cuadro de diálogo @plural {n} action|{n} actions {n} acción|{n} acciones Background (Default) Fondo (predeterminado) -# Batch / Image Processor Include All Subfolders Incluir todas las subcarpetas Auto Add/Delete Añadir/eliminar automáticamente - -# Native Windows printing qualification 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… @@ -4251,7 +4238,6 @@ navigator Zoom Zoom Could not write {name}: {error} No se pudo escribir {name}: {error} Kept {name}: written by another application Se conservó {name}: lo escribió otra aplicación Shadow Tint Tinte de sombras -# PhotoCraft release checks. Check for Updates… Buscar actualizaciones… PhotoCraft Updates Actualizaciones de PhotoCraft Checking for updates… Buscando actualizaciones… @@ -4264,36 +4250,27 @@ navigator Zoom Zoom Automatically Check for Updates Buscar actualizaciones automáticamente Installed version: {version} Versión instalada: {version} PhotoCraft {version} is available. PhotoCraft {version} está disponible. -# History panel › History Brush source (#2966) Paints from the History panel's source state Pinta a partir del estado de origen del panel Historia Sets the source for the history brush Establece el origen del pincel de historia -# Bevel & Emboss shading controls. Highlight Mode Modo de luces Highlight Color Color de luces Highlight Opacity Opacidad de luces Shadow Mode Modo de sombras Shadow Color Color de sombras Shadow Opacity Opacidad de sombras -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Usar el perfil incrustado ({profile}) Convert to the working space ({profile}) Convertir al espacio de trabajo ({profile}) Remember this choice for future images Recordar esta opción para próximas imágenes Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Vuelve a activar el aviso con Ask On Mismatch en Edición › Ajustes de color. Button Mode Modo de botón Button Mode On Modo de botón activado - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Oscurecer interfaz Lighten Interface Aclarar interfaz -# Bevel & Emboss Technique. Technique Técnica Chisel Hard Cincelar duro Chisel Soft Cincelar suave Open color-less EXR as ACEScg Abrir EXR sin espacio de color como ACEScg Do not append "copy" to filename when saving a copy No añadir «copy» al nombre de archivo al guardar una copia -# Export As metadata and profile options - -# View › Guides › right-click a guide Edit Selected Guides Editar guías seleccionadas Clear Selected Guides Borrar guías seleccionadas Bicubic Automatic Bicúbica automática @@ -4318,8 +4295,6 @@ navigator Zoom Zoom set name nombre del conjunto {set} (modified) {set} (modificado) Show file name in title Mostrar nombre de archivo en el título - -# Image › Mode › Bitmap (#5559) 50% Threshold Umbral 50% Pattern Dither Tramado de motivo Diffusion Dither Tramado de difusión @@ -4337,10 +4312,8 @@ navigator Zoom Zoom Undo Changes Deshacer cambios {shortcut} is reserved by the system and can't be assigned. {shortcut} está reservado por el sistema y no se puede asignar. Low-Latency Drawing (vsync off, applies at next launch) Dibujo de baja latencia (sin sincronización vertical, se aplica al volver a iniciar) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Transformación libre aún se está aplicando; inténtelo de nuevo cuando termine. The transform couldn't be applied. No se pudo aplicar la transformación. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Sus capas necesitan {needed} de memoria de GPU; el presupuesto les deja {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Ajuste Memoria de GPU en Preferencias › Rendimiento a lo que pueda alojar su tarjeta gráfica, como máximo 3/8 de su memoria. Automático sigue Uso de memoria, dentro de una cuarta parte de la memoria de este equipo y 3/8 de la de la tarjeta, y no descuenta el documento en una tarjeta cuya memoria se conoce. Mientras no quepan, la barra de estado muestra Memoria de GPU llena. GPU Memory Full Memoria de GPU llena @@ -4366,8 +4339,6 @@ navigator Zoom Zoom 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. “{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}». - Move Up Mover arriba - Move Down Mover abajo Previous Brush Pincel anterior Next Brush Pincel siguiente First Brush Primer pincel @@ -4382,26 +4353,17 @@ navigator Zoom Zoom Use Usar In Front Delante Behind Detrás - -# DDS Options (#1327) DDS Options Opciones de DDS Generate Mipmaps Generar mipmaps - -# Color Table (.act) dialog There is no color table to save. No hay ninguna tabla de colores para guardar. @plural Saved {n} color to {file}|Saved {n} colors to {file} Se guardó {n} color en {file}|Se guardaron {n} colores en {file} - -# Graphics Adapter preference (#1885) GPU adapter Adaptador de GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Importar estilos… Export Selected Styles… Exportar estilos seleccionados… Export Styles… Exportar estilos… {file} is not a style library (.asl) {file} no es una biblioteca de estilos (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Se importó {n} estilo de {file}|Se importaron {n} estilos de {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Se exportó {n} estilo a {file}|Se exportaron {n} estilos a {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Confirme o cancele primero el cuadro de diálogo abierto del paso de la acción Pro Medium Gray Pro (gris medio) Solarized Solarized @@ -4410,28 +4372,11 @@ navigator Zoom Zoom Pro Light Pro (claro) Resize Windows to Fit Redimensionar ventanas para ajustar EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Dirección de párrafo automática Left-to-right paragraph direction Dirección de párrafo de izquierda a derecha Right-to-left paragraph direction Dirección de párrafo de derecha a izquierda Not rendered: this adjustment ({key}) is kept as imported. No se renderiza: este ajuste ({key}) se conserva tal como se importó. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Según color - Decontaminate Colors Descontaminar colores - Edge Detection Detección de bordes - Global Refinements Perfeccionamientos globales - High Quality Preview Previsualización de alta calidad - Object Aware Según objeto - Real-Time Refinement Perfeccionamiento en tiempo real - Refine Edge Brush Tool Herramienta Pincel para perfeccionar bordes - Refine Hair Perfeccionar pelo - Refine Mode Modo de perfeccionamiento - Remember Settings Recordar ajustes - View Mode Modo de visualización - Object Aware needs a segmentation model, which isn't available yet Según objeto necesita un modelo de segmentación que aún no está disponible - Refine Hair needs hair detection, which isn't available yet Perfeccionar pelo necesita detección de pelo, que aún no está disponible -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cubo de tono Brightness Cube Cubo de brillo Color Wheel Rueda de color @@ -4447,9 +4392,8 @@ navigator Zoom Zoom Grayscale Ramp Rampa de escala de grises Current Colors Colores actuales Make Ramp Web Safe Hacer rampa segura para web - Select and Mask was closed: its document is no longer the active one Se cerró Seleccionar y aplicar máscara: su documento ya no es el activo - Select and Mask was closed: another layer was selected Se cerró Seleccionar y aplicar máscara: se seleccionó otra capa -# Art History Brush (#213). + The path was kept as the Work Path El trazado se conservó como trazado de trabajo + The path was discarded El trazado se descartó Art History Brush Tool Herramienta Pincel histórico artístico Tight Short Corto apretado Tight Medium Medio apretado @@ -4463,3 +4407,21 @@ navigator Zoom Zoom Font size presets Valores predefinidos de tamaño de fuente Leading presets Valores predefinidos de interlineado Tracking presets Valores predefinidos de tracking + Color Aware Según color + Decontaminate Colors Descontaminar colores + Edge Detection Detección de bordes + Global Refinements Perfeccionamientos globales + High Quality Preview Previsualización de alta calidad + Object Aware Según objeto + Real-Time Refinement Perfeccionamiento en tiempo real + Refine Edge Brush Tool Herramienta Pincel para perfeccionar bordes + Refine Hair Perfeccionar pelo + Refine Mode Modo de perfeccionamiento + Remember Settings Recordar ajustes + View Mode Modo de visualización + Object Aware needs a segmentation model, which isn't available yet Según objeto necesita un modelo de segmentación que aún no está disponible + Refine Hair needs hair detection, which isn't available yet Perfeccionar pelo necesita detección de pelo, que aún no está disponible + Select and Mask was closed: its document is no longer the active one Se cerró Seleccionar y aplicar máscara: su documento ya no es el activo + Select and Mask was closed: another layer was selected Se cerró Seleccionar y aplicar máscara: se seleccionó otra capa + Select Layer Under Cursor Seleccionar capa bajo el cursor + Drag to move the selected path Arrastre para mover el trazado seleccionado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ab213849f6..c6a5a4c07e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4773,3 +4773,10 @@ cameraRaw Show Vectorscope Näytä vektoriskooppi cameraRaw Tone Histogram Sävyhistogrammi cameraRaw Vignetting Vinjetointi cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen + Current Layer: Nykyinen taso: + Delete effect Poista tehoste + Move effect down Siirrä tehostetta alas + Move effect up Siirrä tehostetta ylös + Path operations Polkutoiminnot + The path was discarded Polku hylättiin + The path was kept as the Work Path Polku säilytettiin työpolkuna diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4fbc29fe39..afec5c6bde 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -20,18 +20,112 @@ # dialog commands is kept. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Options de masque… - Layer Mask Display Options… Options d'affichage du masque de calque… # Channel Options and New Spot Channel (#3761) - Channel Color Couleur de la couche - Color Indicates: La couleur indique : - Solidity: Solidité : - Ink Characteristics Caractéristiques de l’encre # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Copy transforms, layer navigation and cancellable opening (from PR #582 by neko233-com). + +# Labels added on main after this catalog (depth labels, Wayland drop, profiles, rendering mode) + +# Camera Raw scopes and the Patch tool + +# Warp grid presets (#388) + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + Mask Options… Options de masque… + Layer Mask Display Options… Options d'affichage du masque de calque… + Channel Color Couleur de la couche + Color Indicates: La couleur indique : + Solidity: Solidité : + Ink Characteristics Caractéristiques de l’encre Paper Width Largeur du papier Paper Height Hauteur du papier Rows Lignes @@ -50,7 +144,6 @@ 5 Columns, 3 Rows 5 colonnes, 3 lignes 8 Columns 8 colonnes 12 Columns 12 colonnes - File Fichier Edit Édition Image Image @@ -442,6 +535,7 @@ Intersect Shape Areas Intersection des zones de formes Exclude Overlapping Shapes Exclure les formes superposées Merge Shape Components Fusionner les composants de forme + Path operations Opérations sur les tracés Align Aligner Top Edges Bords supérieurs Vertical Centers Centres verticaux @@ -521,7 +615,6 @@ Color Range… Plage de couleurs… Focus Area… Zone de mise au point… Select and Mask… Sélectionner et masquer… -# Select and Mask dialog labels Smart Radius Rayon dynamique Shift Edge Décaler le contour Decontaminate Décontaminer @@ -548,7 +641,6 @@ Blur Flou Blur Gallery Galerie de flous Field Blur… Flou de champ… -# Field Blur pins (#3373) No pin selected Aucune épingle sélectionnée Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Cliquez dans l’image pour ajouter une épingle ; faites glisser une épingle pour la déplacer, ou son anneau pour modifier le flou. Suppr supprime l’épingle sélectionnée. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Faites glisser les poignées du contour pour le redimensionner et le faire pivoter, le carré pour arrondir ses angles et les points intérieurs pour définir où commence le flou. @@ -827,6 +919,9 @@ Add Layer Mask Ajouter un masque de calque Add Stop Ajouter un point Add a layer style Ajouter un style de calque + Move effect up Monter l'effet + Move effect down Descendre l'effet + Delete effect Supprimer l'effet Add a mask (from the selection; {key} inverts) Ajouter un masque (d'après la sélection ; {key} l'inverse) Add an adjustment Ajouter un ajustement Add disk Ajouter un disque @@ -1051,8 +1146,6 @@ Delete current channel Supprimer le canal actif Delete current state Supprimer l'état actuel Delete effect layer Supprimer le calque d'effet - -# Layers-panel trash confirmation Delete layer ‘{name}’? Supprimer le calque « {name} » ? Delete {count} layers? {names} Supprimer {count} calques ? {names} Delete layer? Supprimer le calque ? @@ -1061,7 +1154,6 @@ Missing delete command Commande de suppression manquante Invalid delete command Commande de suppression non valide Layer deleted, but confirmation preference could not be saved: {error} Le calque a été supprimé, mais la préférence de confirmation n’a pas pu être enregistrée : {error} - Delete layer Supprimer le calque Delete layer comp Supprimer la composition de calques Delete note Supprimer la note @@ -2152,7 +2244,6 @@ 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) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Éditeur de dégradé Gradient picker Sélecteur de dégradé Save As Preset Enregistrer comme préreglage @@ -2662,8 +2753,6 @@ Expand group (⌥-click: all groups) Développer le groupe (⌥-clic : tous les groupes) Hide the layer's effects (⌥-click: all layers) Masquer les effets du calque (⌥-clic : tous les calques) Show the layer's effects (⌥-click: all layers) Afficher les effets du calque (⌥-clic : tous les calques) - -# Copy transforms, layer navigation and cancellable opening (from PR #582 by neko233-com). New from Clipboard Créer depuis le presse-papiers Free Transform a Copy Transformer librement une copie Transform Again on a Copy Répéter la transformation sur une copie @@ -2673,8 +2762,6 @@ Select Bottom Layer Sélectionner le dernier calque Add Layer Above to Selection Ajouter le calque au-dessus à la sélection Add Layer Below to Selection Ajouter le calque au-dessous à la sélection - -# Labels added on main after this catalog (depth labels, Wayland drop, profiles, rendering mode) 8 bit 8 bits Integer Entier 16 bit 16 bits @@ -2710,8 +2797,6 @@ GPU Backend Moteur GPU Details Détails Rendering mode Mode de rendu - -# Camera Raw scopes and the Patch tool Shadow Clipping Warning (U) Avertissement d'écrêtage des tons foncés (U) Highlight Clipping Warning (O) Avertissement d'écrêtage des tons clairs (O) Show Lab Color Readouts Afficher les valeurs de couleur Lab @@ -2736,21 +2821,15 @@ cameraRaw Blending Fusion Transform On Drop Transformer au dépôt Scale or rotate the moved area, then press {key} Mettez à l'échelle ou faites pivoter la zone déplacée, puis appuyez sur {key} Now drag the selection onto another area Faites maintenant glisser la sélection vers une autre zone - -# Warp grid presets (#388) 3 x 3 3 × 3 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Grille : Edit Type Modifier le texte - - New Style… Nouveau style… Style {name} saved Style {name} enregistré - Create new style (from the selected type) Créer un nouveau style (à partir du texte sélectionné) Create new style from the selected layer Créer un nouveau style à partir du calque sélectionné - Make Default Définir par défaut Reset to Default Rétablir par défaut Full-resolution preview unavailable Aperçu en pleine résolution indisponible @@ -2779,9 +2858,6 @@ cameraRaw Blending Fusion Magnetic Lasso Tool Outil Lasso magnétique Frequency Fréquence Use tablet pressure to change pen width Utiliser la pression de la tablette pour modifier la largeur de la plume - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About À propos Contributors Contributeurs Models Modèles @@ -2812,8 +2888,6 @@ cameraRaw Blending Fusion % of all commits % de tous les commits Lines +/− Lignes +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login} : {prs} PR, {commits} commits, +{added} / −{deleted} lignes (Δ {delta}), +{binAdded} / −{binDeleted} fichiers binaires, {first} – {last} - -# Swatches panel Create new swatch Créer une nouvelle nuance New Swatch… Nouvelle nuance… New Swatch Group… Nouveau groupe de nuances… @@ -2823,13 +2897,12 @@ cameraRaw Blending Fusion Export Swatches for Exchange… Exporter les nuances pour l'échange… Reset Swatches Réinitialiser les nuances Add to Swatches Ajouter au nuancier -# Layer Style > Blending Options (Advanced Blending) Blend If: Fusion si : + Current Layer: Calque actif : + Underlying Layer: Calque sous-jacent : Channels: Couches : Knockout Masquage Apply At Canvas Bounds Appliquer l’effet aux limites de la zone de travail - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Sélecteur de couleurs (Couleur du texte) Color Picker ({name}) Sélecteur de couleurs ({name}) Color Picker (Fill Color) Sélecteur de couleurs (Couleur de remplissage) @@ -2846,8 +2919,6 @@ cameraRaw Blending Fusion Show/Hide Panels Afficher/masquer les panneaux Could not open Impossible d’ouvrir {path}: the path is not valid Unicode; rename the file and open it again. {path} : le chemin n’est pas un Unicode valide ; renommez le fichier puis rouvrez-le. - -# Fill dialog, layer style contours and Image Size Contents: Contenu : Custom Pattern: Motif personnalisé : Foreground Color Couleur de premier plan @@ -2874,14 +2945,12 @@ cameraRaw Blending Fusion Rolling Slope - Descending Pente ondulée - descendante Rounded Steps Paliers arrondis Sawtooth 1 Dents de scie 1 - Red Eye Tool Outil Yeux rouges Pupil Size Taille de la pupille Darken Amount Quantité d'assombrissement Click a red pupil to neutralize it Cliquez sur une pupille rouge pour la corriger open source code source ouvert …and {n} more …et {n} de plus - Eyedroppers: Pipettes : Set Black Point Définir le point noir Set Neutral Gray Point Définir le point gris neutre @@ -2890,8 +2959,6 @@ cameraRaw Blending Fusion Selection Preview: Aperçu de la sélection : Black Matte Fond noir White Matte Fond blanc - -# Layer colour labels. Seafoam Écume de mer Indigo Indigo Fuchsia Fuchsia @@ -2911,20 +2978,14 @@ fontWeight Bold Gras fontWeight ExtraBold Extra-gras fontWeight Black Noir fontWeight Italic Italique - -# Pattern Stamp tool Pattern Stamp Tool Outil Tampon de motif 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° - -# Painting symmetry presets. Dual Axis Deux axes Diagonal Diagonale Transform Symmetry Transformer la symétrie - -# Eyedropper Sample Size and Sample (#1649). Point Sample Échantillon ponctuel 3 by 3 Average Moyenne 3 × 3 5 by 5 Average Moyenne 5 × 5 @@ -2936,15 +2997,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Couleur vers alpha… Transparency Threshold Seuil de transparence Opacity Threshold Seuil d'opacité PhotoCraft — Screen Color Picker PhotoCraft — Sélecteur de couleur d'écran - Rasterize svg groups deeper than Pixelliser les groupes SVG au-delà de cette profondeur 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 désactive ce seuil ; les groupes SVG imbriqués sur plus de 100 niveaux sont toujours pixellisés. Rule of Thirds Règle des tiers @@ -2958,8 +3016,6 @@ fontWeight Italic Italique Cycle Orientation Changer d’orientation Set the overlay options for the Crop tool Définir les options de superposition de l’outil Recadrage Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-clic a été intercepté par le bureau, qui déplace les fenêtres avec Alt-glisser. Réglez sa touche de déplacement des fenêtres sur Super, ou verrouillez Alt dans Fenêtre › Touches de modification. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Sélecteur de couleurs (couleur du style de calque) Auto Hide Notifications Masquer automatiquement les notifications Notification Duration (seconds) Durée de la notification (secondes) @@ -3035,7 +3091,6 @@ fontWeight Italic Italique Appearance Settings… Réglages d’apparence… Add to favorites Ajouter aux favoris Remove from favorites Retirer des favoris -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Marque cameraData Model Modèle cameraData Date Taken Date de prise de vue @@ -3045,7 +3100,6 @@ cameraData ISO Speed Sensibilité ISO cameraData Focal Length Focale cameraData Focal Length (35 mm) Focale (35 mm) cameraData Lens Objectif -# Shared panel docking Activate Panel Activer le panneau Change Panel Group Modifier le groupe de panneaux Change Panel Layout Modifier la disposition des panneaux @@ -3089,7 +3143,6 @@ cameraData Lens Objectif Snap to Origin Aligner sur l'origine Search settings… Rechercher des réglages… No matching settings Aucun réglage correspondant -# Edit › Content-Aware Fill workspace Sampling Brush Tool Outil Pinceau d’échantillonnage Sampling Area Overlay Incrustation de la zone d’échantillonnage Show Sampling Area Afficher la zone d’échantillonnage @@ -3107,7 +3160,6 @@ cameraData Lens Objectif Output To Sortie vers Duplicate Layer Dupliquer le calque Contract Contracter - Animation Options Options d’animation Entire Document Document entier Filter Options Options de filtrage @@ -3125,8 +3177,6 @@ cameraData Lens Objectif Add “copy” to Copied Layers and Groups Ajouter « copie » aux calques et groupes dupliqués Preview on canvas when reordering layers Prévisualiser sur la zone de travail lors du réagencement des calques Show layer mask badges Afficher les badges des masques de fusion - -# Smart Filter editors Blending Options ({filter}) Options de fusion ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Masquer les effets du calque et les filtres dynamiques ({key}-clic : tous les calques) Show the layer's effects and Smart Filters ({key}-click: all layers) Afficher les effets du calque et les filtres dynamiques ({key}-clic : tous les calques) @@ -3159,7 +3209,6 @@ curves Smooth Lisser Fix the red plane first: its corners must form a convex quad Corrigez d’abord le plan rouge : ses coins doivent former un quadrilatère convexe Alt-click a plane to set the clone source Alt-clic sur un plan pour définir la source de duplication Too many clone strokes: apply Vanishing Point first Trop de traits de duplication : appliquez d’abord Point de fuite -# Select and Mask view modes (#1754) Onion Skin Pelure d'oignon Marching Ants Fourmis en marche On Black Sur fond noir @@ -3168,7 +3217,6 @@ curves Smooth Lisser Show Edge Afficher le bord Show Original Afficher l'original F cycles the views; hold X to see the image F fait défiler les vues ; maintenez X pour voir l'image -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Pinceau d'amélioration du contour (R) Expand Detection Area Étendre la zone de détection Restore Original Edge Restaurer le contour d'origine @@ -3176,19 +3224,13 @@ curves Smooth Lisser Clear Brush Strokes Effacer les traits de pinceau Show rulers Afficher les règles Presentation Présentation - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Cliquez pour placer · Alt-clic ou glisser hors du canevas pour supprimer No document open Aucun document ouvert {n} of {max} sample points {n} sur {max} points d'échantillonnage - -# History panel menu (#2966) New Snapshot… Nouvel instantané… History Options… Options d'historique… -# History panel › History Options… (#2966) Allow Non-Linear History Autoriser l'historique non linéaire Make Layer Visibility Changes Undoable Permettre d'annuler les changements de visibilité des calques -# Print dialog (#2697) Emulsion Down Émulsion verso Functions Fonctions Print Resolution: Résolution d’impression : @@ -3200,7 +3242,6 @@ curves Smooth Lisser Apply mask to layer before removing? Appliquer le masque au calque avant de le supprimer ? The layer or its mask changed. Drag the mask onto the Trash again. Le calque ou son masque a changé. Faites de nouveau glisser le masque sur la corbeille. Delete the vector mask? Supprimer le masque vectoriel ? -# View › Guides › New Guide… › Color Light Blue Bleu clair Light Red Rouge clair Medium Blue Bleu moyen @@ -3221,8 +3262,6 @@ curves Smooth Lisser Clear Brush Controls Effacer les commandes de pinceau Reset All Locked Settings Réinitialiser tous les paramètres verrouillés Copy Texture to Other Tools Copier la texture dans d'autres outils - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Charger des actions… Save Actions… Enregistrer les actions… New Action… Nouvelle action… @@ -3234,10 +3273,8 @@ curves Smooth Lisser @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} étape n’a pas encore d’équivalent dans PhotoCraft|{n} étapes n’ont pas encore d’équivalent dans PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} action enregistrée dans {file}|{n} actions enregistrées dans {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} étape sans équivalent Photoshop omise|{n} étapes sans équivalent Photoshop omises - File Naming Dénomination des fichiers Starting serial Numéro de série initial -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Insérer un arrêt… Save Set… Enregistrer l’ensemble… Message: Message : @@ -3249,11 +3286,8 @@ curves Smooth Lisser @plural {n} action|{n} actions {n} action|{n} actions Background (Default) Arrière-plan (par défaut) Content-Aware Fill Remplissage d'après le contenu -# Batch / Image Processor Include All Subfolders Inclure tous les sous-dossiers Auto Add/Delete Ajout/suppr. auto - -# Native Windows printing qualification 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… @@ -3298,7 +3332,6 @@ curves Smooth Lisser Could not write {name}: {error} Impossible d’écrire {name} : {error} Kept {name}: written by another application {name} conservé : écrit par une autre application Shadow Tint Teinte des ombres -# PhotoCraft release checks. Check for Updates… Rechercher des mises à jour… PhotoCraft Updates Mises à jour de PhotoCraft Checking for updates… Recherche de mises à jour… @@ -3311,35 +3344,27 @@ curves Smooth Lisser Automatically Check for Updates Rechercher automatiquement des mises à jour Installed version: {version} Version installée : {version} PhotoCraft {version} is available. PhotoCraft {version} est disponible. -# History panel › History Brush source (#2966) Paints from the History panel's source state Peint à partir de l'état source du panneau Historique Sets the source for the history brush Définit la source du pinceau d'historique -# Bevel & Emboss shading controls. Highlight Mode Mode des tons clairs Highlight Color Couleur des tons clairs Highlight Opacity Opacité des tons clairs Shadow Mode Mode des ombres Shadow Color Couleur des ombres Shadow Opacity Opacité des ombres -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Utiliser le profil incorporé ({profile}) Convert to the working space ({profile}) Convertir vers l'espace de travail ({profile}) Remember this choice for future images Mémoriser ce choix pour les prochaines images Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Réactivez la question avec Ask On Mismatch dans Édition › Paramètres de couleur. Button Mode Mode bouton Button Mode On Mode bouton activé - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Assombrir l'interface Lighten Interface Éclaircir l'interface -# Bevel & Emboss Technique. Technique Technique Chisel Hard Ciselage dur Chisel Soft Ciselage doux Open color-less EXR as ACEScg Ouvrir les EXR sans espace colorimétrique en ACEScg Do not append "copy" to filename when saving a copy Ne pas ajouter « copy » au nom de fichier lors de l’enregistrement d’une copie - -# View › Guides › right-click a guide Edit Selected Guides Modifier les repères sélectionnés Clear Selected Guides Effacer les repères sélectionnés Bicubic Automatic Bicubique automatique @@ -3365,8 +3390,6 @@ curves Smooth Lisser {set} (modified) {set} (modifié) Random Aléatoire Show file name in title Afficher le nom de fichier dans le titre - -# Image › Mode › Bitmap (#5559) 50% Threshold Seuil 50 % Pattern Dither Simulation par motif Diffusion Dither Simulation par diffusion @@ -3385,10 +3408,8 @@ curves Smooth Lisser Undo Changes Annuler les modifications {shortcut} is reserved by the system and can't be assigned. {shortcut} est réservé par le système et ne peut pas être attribué. Low-Latency Drawing (vsync off, applies at next launch) Dessin à faible latence (sans synchronisation verticale, au prochain lancement) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. La transformation manuelle est encore en cours d'application ; réessayez quand elle sera terminée. The transform couldn't be applied. Impossible d'appliquer la transformation. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Ses calques ont besoin de {needed} de mémoire GPU ; le budget leur laisse {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Réglez Mémoire GPU dans Préférences › Performances sur ce que votre carte graphique peut contenir, au plus 3/8 de sa mémoire. Automatique suit Utilisation de la mémoire, dans la limite du quart de la mémoire de cet ordinateur et des 3/8 de celle de la carte, et ne compte pas le document sur une carte dont la mémoire est connue. Tant qu'ils ne tiennent pas, la barre d'état affiche Mémoire GPU pleine. GPU Memory Full Mémoire GPU pleine @@ -3415,8 +3436,6 @@ curves Smooth Lisser 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. “{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} ». - Move Up Déplacer vers le haut - Move Down Déplacer vers le bas Previous Brush Pinceau précédent Next Brush Pinceau suivant First Brush Premier pinceau @@ -3431,27 +3450,18 @@ curves Smooth Lisser Use Utiliser In Front Devant Behind Derrière - -# DDS Options (#1327) DDS Options Options DDS Compression Compression Generate Mipmaps Générer les mipmaps - -# Color Table (.act) dialog There is no color table to save. Il n’y a aucune table de couleurs à enregistrer. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} couleur enregistrée dans {file}|{n} couleurs enregistrées dans {file} - -# Graphics Adapter preference (#1885) GPU adapter Adaptateur GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Importer des styles… Export Selected Styles… Exporter les styles sélectionnés… Export Styles… Exporter les styles… {file} is not a style library (.asl) {file} n’est pas une bibliothèque de styles (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {n} style importé depuis {file}|{n} styles importés depuis {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} style exporté vers {file}|{n} styles exportés vers {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Validez ou annulez d’abord la boîte de dialogue ouverte de l’étape de l’action Pro Medium Gray Pro gris moyen Solarized Solarized @@ -3836,7 +3846,6 @@ curves Smooth Lisser Hearts Cœurs Heptagon Heptagone Hexagon Hexagone - Hidden Masqué Hide Grid Masquer la grille Hide Others Masquer les autres Hide {app} Masquer {app} @@ -4328,7 +4337,6 @@ curves Smooth Lisser Twirl Counterclockwise Tourbillon antihoraire Unaltered Inchangé Undefined Areas Zones non définies - Underlying Layer: Calque sous-jacent : Underpainting Sous-couche Underwater Sous l'eau Ungroup Dissocier @@ -4490,28 +4498,11 @@ layers Fill Remplissage layers Fill: Remplissage : navigator Zoom Zoom shape Appearance Apparence -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Sens du paragraphe automatique Left-to-right paragraph direction Sens du paragraphe de gauche à droite Right-to-left paragraph direction Sens du paragraphe de droite à gauche Not rendered: this adjustment ({key}) is kept as imported. Non rendu : ce réglage ({key}) est conservé tel qu'importé. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Selon la couleur - Decontaminate Colors Décontaminer les couleurs - Edge Detection Détection des contours - Global Refinements Améliorations globales - High Quality Preview Aperçu haute qualité - Object Aware Selon l'objet - Real-Time Refinement Amélioration en temps réel - Refine Edge Brush Tool Outil Pinceau d'amélioration du contour - Refine Hair Améliorer les cheveux - Refine Mode Mode d'amélioration - Remember Settings Mémoriser les paramètres - View Mode Mode d'affichage - Object Aware needs a segmentation model, which isn't available yet Selon l'objet nécessite un modèle de segmentation, pas encore disponible - Refine Hair needs hair detection, which isn't available yet Améliorer les cheveux nécessite une détection des cheveux, pas encore disponible -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cube de teinte Brightness Cube Cube de luminosité Color Wheel Roue chromatique @@ -4527,9 +4518,8 @@ shape Appearance Apparence Grayscale Ramp Barre de niveaux de gris Current Colors Couleurs actuelles Make Ramp Web Safe Limiter la barre aux couleurs Web - Select and Mask was closed: its document is no longer the active one Sélectionner et masquer a été fermé : son document n’est plus le document actif - Select and Mask was closed: another layer was selected Sélectionner et masquer a été fermé : un autre calque a été sélectionné -# Art History Brush (#213). + The path was kept as the Work Path Le tracé a été conservé comme tracé de travail + The path was discarded Le tracé a été supprimé Art History Brush Tool Outil Pinceau d'historique artistique Tight Short Serré court Tight Medium Serré moyen @@ -4543,3 +4533,19 @@ shape Appearance Apparence Font size presets Tailles de police prédéfinies Leading presets Interlignages prédéfinis Tracking presets Approches prédéfinies + Color Aware Selon la couleur + Decontaminate Colors Décontaminer les couleurs + Edge Detection Détection des contours + Global Refinements Améliorations globales + High Quality Preview Aperçu haute qualité + Object Aware Selon l'objet + Real-Time Refinement Amélioration en temps réel + Refine Edge Brush Tool Outil Pinceau d'amélioration du contour + Refine Hair Améliorer les cheveux + Refine Mode Mode d'amélioration + Remember Settings Mémoriser les paramètres + View Mode Mode d'affichage + Object Aware needs a segmentation model, which isn't available yet Selon l'objet nécessite un modèle de segmentation, pas encore disponible + Refine Hair needs hair detection, which isn't available yet Améliorer les cheveux nécessite une détection des cheveux, pas encore disponible + Select and Mask was closed: its document is no longer the active one Sélectionner et masquer a été fermé : son document n’est plus le document actif + Select and Mask was closed: another layer was selected Sélectionner et masquer a été fermé : un autre calque a été sélectionné diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 8e304dc355..02e2dce446 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -17,6 +17,37 @@ # (`plural_one_other` in i18n/mod.rs). # Top-level Menus + +# File Menu + +# Edit Menu + +# Image Menu + +# Layer Menu + +# Select Menu + +# View Menu + +# Window Menu & Panels + +# Tools (Toolbox) + +# Common Dialogs and Buttons + +# Plurals + +# Tool and Scope strings + +# Camera Raw + +# Coverage-test keys (English until translated) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) File फ़ाइल Edit एडिट Image इमेज @@ -28,8 +59,6 @@ View व्यू Window विंडो Help सहायता - -# File Menu New… नया… Open… खोलें… Open Recent हाल ही में खोले गए @@ -48,8 +77,6 @@ Print… प्रिंट करें… Print One Copy एक प्रति प्रिंट करें Exit बाहर निकलें - -# Edit Menu Undo पूर्ववत करें Redo फिर से करें Cut काटें @@ -79,8 +106,6 @@ Workspace… कार्यस्थान… Tools… टूल्स… Performance… परफॉरमेंस… - -# Image Menu Mode मोड RGB Color RGB रंग CMYK Color CMYK रंग @@ -113,8 +138,6 @@ Trim… ट्रिम करें… Reveal All सभी दिखाएँ Duplicate… डुप्लीकेट… - -# Layer Menu New नया Layer… लेयर… Layer from Background बैकग्राउंड से लेयर @@ -141,8 +164,6 @@ Merge Down नीचे मर्ज करें Merge Visible दृश्यमान मर्ज करें Flatten Image इमेज फ़्लैट करें - -# Select Menu All सभी Deselect अचयनित करें Reselect पुनः चयन करें @@ -163,8 +184,6 @@ Transform Selection चयन रूपांतरित करें Load Selection… चयन लोड करें… Save Selection… चयन सहेजें… - -# View Menu Proof Setup प्रूफ़ सेटअप Proof Colors प्रूफ़ रंग Zoom In ज़ूम इन @@ -187,8 +206,6 @@ New Guide… नई गाइड… Lock Slices स्लाइस लॉक करें Clear Slices स्लाइस हटाएं - -# Window Menu & Panels Arrange व्यवस्थित करें Tile Horizontally क्षैतिज टाइल Tile Vertically लंबवत टाइल @@ -216,8 +233,6 @@ Tools टूल्स Options विकल्प Status Bar स्टेटस बार - -# Tools (Toolbox) Move Tool मूव टूल Artboard Tool आर्टबोर्ड टूल Rectangular Marquee Tool रेक्टेंगुलर मार्की टूल @@ -286,8 +301,6 @@ Hand Tool हैंड टूल Rotate View Tool रोटेट व्यू टूल Zoom Tool ज़ूम टूल - -# Common Dialogs and Buttons OK ठीक है Cancel रद्द करें Reset रीसेट करें @@ -316,14 +329,10 @@ Presets: प्रीसेट्स: Language भाषा Auto स्वचालित - -# Plurals @plural {n} layer|{n} layers {n} लेयर|{n} लेयर्स @plural {n} item|{n} items {n} आइटम|{n} आइटम्स @plural {n} document|{n} documents {n} दस्तावेज़|{n} दस्तावेज़ @plural {n} pixel|{n} pixels {n} पिक्सेल|{n} पिक्सेल्स - -# Tool and Scope strings Scope दायरा Selected चयनित Mixer Brush मिक्सर ब्रश @@ -337,8 +346,6 @@ Aligned संरेखित Fit in View दृश्य में फ़िट करें Camera Raw Camera Raw - -# Camera Raw cameraRaw Amount मात्रा Amount मात्रा cameraRaw Aqua एक्वा @@ -493,8 +500,6 @@ cameraRaw Whites व्हाइट्स Whites व्हाइट्स cameraRaw Yellow पीला Yellow पीला - -# Coverage-test keys (English until translated) Black Point Compensation Black Point Compensation Apply At Canvas Bounds Apply At Canvas Bounds Convert to Shape… Convert to Shape… @@ -539,6 +544,29 @@ cameraRaw Yellow पीला Missing delete command हटाने का कमांड नहीं मिला Invalid delete command हटाने का कमांड अमान्य है Layer deleted, but confirmation preference could not be saved: {error} लेयर हटा दी गई, लेकिन पुष्टि की प्राथमिकता सहेजी नहीं जा सकी: {error} + The path was kept as the Work Path पथ को कार्य पथ के रूप में रखा गया + The path was discarded पथ हटा दिया गया + Art History Brush आर्ट हिस्ट्री ब्रश + Style शैली + Area क्षेत्र + Tight Short सघन छोटा + Tight Medium सघन मध्यम + Tight Long सघन लंबा + Loose Medium ढीला मध्यम + Loose Long ढीला लंबा + Dab थपका + Tight Curl सघन घुमाव + Loose Curl ढीला घुमाव + Stylized dabs from a history state इतिहास स्थिति से शैलीबद्ध थपके + Aspect Ratio पहलू अनुपात + Category श्रेणी + Color Table रंग तालिका + Gamma गामा + Interpolation इंटरपोलेशन + Profile प्रोफ़ाइल + Target लक्ष्य + Units इकाइयाँ + Demosaic डिमोज़ेक Clear Selection चयन साफ़ करें Color Aware रंग-आधारित Decontaminate Colors रंग शुद्ध करें @@ -556,27 +584,3 @@ cameraRaw Yellow पीला Refine Hair needs hair detection, which isn't available yet बाल परिशोधित करने के लिए बालों की पहचान चाहिए, जो अभी उपलब्ध नहीं है Select and Mask was closed: its document is no longer the active one चयन और मास्क बंद कर दिया गया: उसका दस्तावेज़ अब सक्रिय नहीं है Select and Mask was closed: another layer was selected चयन और मास्क बंद कर दिया गया: दूसरी लेयर चुनी गई -# Art History Brush (#213). - Art History Brush आर्ट हिस्ट्री ब्रश - Style शैली - Area क्षेत्र - Tight Short सघन छोटा - Tight Medium सघन मध्यम - Tight Long सघन लंबा - Loose Medium ढीला मध्यम - Loose Long ढीला लंबा - Dab थपका - Tight Curl सघन घुमाव - Loose Curl ढीला घुमाव - Stylized dabs from a history state इतिहास स्थिति से शैलीबद्ध थपके - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) - Aspect Ratio पहलू अनुपात - Category श्रेणी - Color Table रंग तालिका - Gamma गामा - Interpolation इंटरपोलेशन - Profile प्रोफ़ाइल - Target लक्ष्य - Units इकाइयाँ - Demosaic डिमोज़ेक diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 59c727ab13..e2e0496a2b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -18,9 +18,73 @@ # Plural messages and command id overrides # Custom paper dimensions in Print Settings. + + +# Menus: File, Edit, Image + +# Menus: Layer, Select + +# Menus: Type, Filter, View, Window; UI and engine commands + +# Tools, brushes and the options bar + +# Layers, masks, layer styles and blend modes + +# Panels + +# Adjustments and filters + +# Camera Raw and camera data + +# Dialogs, preferences and file formats + +# Status bar, messages and other labels + +# Labels kept for parity with the other catalogs +# Edit › Content-Aware Fill workspace + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop + +# Native Windows printing qualification + +# Layer Mask Display Options (the layer mask rubylith's colour and opacity) + +# Channel Options and New Spot Channel (#3761) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) + +# Layers panel options and Smart Filter editors + +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). +# Smart Filter row actions. + Paper Width Papír szélessége Paper Height Papír magassága - @id edit.purge.undo Visszavonási adatok @id edit.stroke Körvonalazás… @id edit.transform.scale Méretezés @@ -53,8 +117,6 @@ @id file.close Bezárás @id layer.layerMask.apply Alkalmazás @id edit.clear Kiürítés - -# Menus: File, Edit, Image 16 Bits/Channel 16 bit/csatorna 180° 180° 32 Bits/Channel 32 bit/csatorna @@ -259,8 +321,6 @@ Warp Hajlítás WIA Support… WIA-támogatás… Workspace… Munkaterület… - -# Menus: Layer, Select Align Igazítás Apply Alkalmaz Arrange Elrendezés @@ -357,6 +417,7 @@ Median Medián Merge Layers Rétegek egyesítése Merge Shape Components Alakzatösszetevők egyesítése + Path operations Útvonalműveletek Merge Visible Láthatók egyesítése Modify Módosítás New Adjustment Layer Új korrekciós réteg @@ -419,8 +480,6 @@ Vertical Centers Függőleges középvonalak Video Videó Video Layers Videorétegek - -# Menus: Type, Filter, View, Window; UI and engine commands (coming soon) (hamarosan) 100% 100% 105% 105% @@ -869,8 +928,6 @@ ZigZag… Cikcakk… Zoom In Nagyítás Zoom Out Kicsinyítés - -# Tools, brushes and the options bar 101 by 101 Average 101 x 101 átlag 11 by 11 Average 11 x 11 átlag 3 by 3 Average 3 x 3 átlag @@ -1443,8 +1500,6 @@ fontWeight Medium Közepes fontWeight Regular Normál fontWeight SemiBold Középkövér fontWeight Thin Hajszálvékony - -# Layers, masks, layer styles and blend modes 30 fps 30 fps Add Layer Above to Selection Felette lévő réteg hozzáadása a kijelöléshez Add Layer Below to Selection Alatta lévő réteg hozzáadása a kijelöléshez @@ -1691,7 +1746,7 @@ fontWeight Thin Hajszálvékony Subtract Kivonás The document is closed A dokumentum be van zárva The document or selected layers changed. Please request deletion again. A dokumentum vagy a kijelölt rétegek megváltoztak. Kérd újra a törlést. - This Layer: Ez a réteg: + Current Layer: Jelenlegi réteg: To Végszín Toggle visibility Láthatóság váltása Transparency Shapes Layer Az átlátszóság alakítja a réteget @@ -1718,8 +1773,6 @@ layerLabel Magenta Bíbor Fill with {mode}-neutral color (black) Kitöltés {mode} módhoz semleges színnel (fekete) Fill with {mode}-neutral color (50% gray) Kitöltés {mode} módhoz semleges színnel (50%-os szürke) (No neutral color exists for {mode} mode.) ({mode} módhoz nincs semleges szín.) - -# Panels (none) (nincs) + Add variable + Változó hozzáadása 30 frames @ 30 fps 30 képkocka, 30 fps @@ -1728,6 +1781,9 @@ layerLabel Magenta Bíbor 80% 80% A save to {name} is still running; try again when it finishes Még tart egy mentés ide: {name}; próbáld újra, ha befejeződött Add a layer style Rétegstílus hozzáadása + Move effect up Effektus feljebb mozgatása + Move effect down Effektus lejjebb mozgatása + Delete effect Effektus törlése Add a mask (from the selection; {key} inverts) Maszk hozzáadása (a kijelölésből; {key}: invertálás) Add an adjustment Korrekció hozzáadása Add to selection ({key}) Hozzáadás a kijelöléshez ({key}) @@ -1946,8 +2002,6 @@ layerLabel Magenta Bíbor {name} Properties Tulajdonságok: {name} ↑↓ navigate {key} run esc close ↑↓ navigálás {key} futtatás esc bezárás navigator Zoom Nagyítás mértéke - -# Adjustments and filters 3D LUT File 3D LUT-fájl 90% 90% Absolute Abszolút @@ -2497,8 +2551,6 @@ navigator Zoom Nagyítás mértéke {added}, {removed} subtracted {added}, {removed} kivonva {index} of {total} {index} / {total} {n} of {max} sample points {n} / {max} mintavételi pont - -# Camera Raw and camera data After Utána Aqua Türkiz Balance Egyensúly @@ -2625,8 +2677,6 @@ cameraRaw Tint Színezet cameraRaw Vibrance Élénkség cameraRaw Whites Fehérek cameraRaw Yellow Sárga - -# Dialogs, preferences and file formats % of all commits Commitok aránya (%) (print to the printer) (nyomtatás a nyomtatón) 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. A 0 kikapcsolja ezt a küszöböt; a 100 szintnél mélyebben egymásba ágyazott SVG-csoportok mindig raszterizálódnak. @@ -3056,8 +3106,6 @@ cameraRaw Yellow Sárga {n} commands are not in PhotoCraft. {n} parancs nem érhető el a PhotoCraftban. {shortcut} assigned. Billentyűparancs hozzárendelve: {shortcut} {shortcut} is already in use by {commands} and will be removed from it when you click OK. A billentyűparancs már foglalt: {shortcut}. Jelenlegi parancs: {commands}. Az OK gombra kattintva onnan törlődik. - -# Status bar, messages and other labels Action playback failed: {error} A műveletsor lejátszása sikertelen: {error} Adaptive Wide Angle Adaptív nagy látószög Add Anchor Point Tool Horgonypont hozzáadása @@ -3689,8 +3737,6 @@ cameraRaw Yellow Sárga {w} px x {h} px ({ppi} ppi) {w} px x {h} px ({ppi} ppi) {w} {unit} x {h} {unit} ({ppi} ppi) {w} {unit} x {h} {unit} ({ppi} ppi) …and {n} more …és még {n} - -# Labels kept for parity with the other catalogs 10 fps 10 fps 15 fps 15 fps 24 fps 24 fps @@ -4066,7 +4112,6 @@ cameraRaw Yellow Sárga Delete Contour Kontúr törlése Loaded contours from {file} Kontúrok betöltve: {file} Saved contours to {file} Kontúrok mentve: {file} -# Edit › Content-Aware Fill workspace Excluded Area Kizárt terület Fill Settings Kitöltési beállítások Full Teljes @@ -4088,8 +4133,6 @@ cameraRaw Yellow Sárga Clear Brush Controls Ecsetvezérlők törlése Reset All Locked Settings Összes zárolt beállítás visszaállítása Copy Texture to Other Tools Textúra másolása más eszközökre - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Műveletek betöltése… Save Actions… Műveletek mentése… New Action… Új művelet… @@ -4101,9 +4144,7 @@ cameraRaw Yellow Sárga @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} lépésnek még nincs megfelelője a PhotoCraftban @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} művelet mentve. Cél: {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Photoshop-megfelelő nélküli lépés kihagyva - Starting serial Kezdő sorszám -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Leállítás beszúrása… Save Set… Készlet mentése… Message: Üzenet: @@ -4127,20 +4168,14 @@ cameraRaw Yellow Sárga Loaded Camera Raw settings from {file} Camera Raw-beállítások betöltve innen: {file} Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-beállítások betöltve innen: {file} ({n} nem támogatott) Auto Add/Delete Automatikus hozzáadás/törlés - -# Native Windows printing qualification 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… 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 - -# Layer Mask Display Options (the layer mask rubylith's colour and opacity) Mask Options… Maszkbeállítások… Layer Mask Display Options… Rétegmaszk megjelenítési beállításai… - -# Channel Options and New Spot Channel (#3761) Channel Color Csatorna színe Color Indicates: A szín jelzése: Ink Characteristics Festék jellemzői @@ -4184,7 +4219,6 @@ cameraRaw Yellow Sárga Slab Serif Talpas (szögletes) TrueType font TrueType betűtípus Variable font Változó betűtípus -# Bevel & Emboss shading controls. Highlight Mode Csúcsfény módja Highlight Color Csúcsfény színe Highlight Opacity Csúcsfény fedettsége @@ -4203,25 +4237,19 @@ cameraRaw Yellow Sárga Automatically Check for Updates Frissítések automatikus keresése Installed version: {version} Telepített verzió: {version} PhotoCraft {version} is available. Elérhető a PhotoCraft {version}. -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) A beágyazott profil használata ({profile}) Convert to the working space ({profile}) Átalakítás a munkaszíntérbe ({profile}) Remember this choice for future images A választás megjegyzése a későbbi képekhez Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. A kérdést a Szerkesztés › Színbeállítások „Profileltérés: rákérdezés megnyitáskor” beállításával kapcsolhatod vissza. Button Mode Gomb mód Button Mode On Gomb mód be - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Felület sötétítése Lighten Interface Felület világosítása -# Bevel & Emboss Technique. Technique Technika Chisel Hard Kemény vésés Chisel Soft Lágy vésés Open color-less EXR as ACEScg Színinformáció nélküli EXR megnyitása ACEScg-ként Do not append "copy" to filename when saving a copy Ne fűzze a „copy” szót a fájlnévhez másolat mentésekor - -# View › Guides › right-click a guide Edit Selected Guides Kijelölt segédvonalak szerkesztése Clear Selected Guides Kijelölt segédvonalak törlése Bicubic Automatic Automatikus bikubikus @@ -4246,8 +4274,6 @@ cameraRaw Yellow Sárga set name készlet neve {set} (modified) {set} (módosítva) Show file name in title Fájlnév megjelenítése a címben - -# Image › Mode › Bitmap (#5559) 50% Threshold 50%-os küszöb Pattern Dither Mintázatos keverés Diffusion Dither Diffúziós keverés @@ -4257,8 +4283,6 @@ cameraRaw Yellow Sárga Lines/Inch Vonal/hüvelyk Lines/Centimeter Vonal/centiméter Ellipse Ellipszis - -# Layers panel options and Smart Filter editors Add “copy” to Copied Layers and Groups „másolat” hozzáadása a másolt rétegekhez és csoportokhoz Animation Options Animációs beállítások Entire Document Teljes dokumentum @@ -4275,7 +4299,6 @@ cameraRaw Yellow Sárga Thumbnail Contents Bélyegkép tartalma Thumbnail Size Bélyegképméret Use Default Masks on Fill Layers Alapértelmezett maszkok kitöltőrétegeken - Blending Options ({filter}) Keverési beállítások ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek elrejtése ({key}+kattintás: minden réteg) Opacity must be between 0% and 100%. Az átlátszatlanságnak 0% és 100% között kell lennie. @@ -4291,10 +4314,8 @@ cameraRaw Yellow Sárga Undo Changes Változások visszavonása {shortcut} is reserved by the system and can't be assigned. A(z) {shortcut} a rendszer számára fenntartott, nem rendelhető hozzá. Low-Latency Drawing (vsync off, applies at next launch) Kis késleltetésű rajzolás (vsync nélkül, a következő indításkor lép életbe) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. A szabad alakítás alkalmazása még folyamatban van; próbáld újra, ha befejeződött. The transform couldn't be applied. Az átalakítás nem alkalmazható. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. A rétegeknek {needed} GPU-memória kell; a keret {budget} hagy nekik. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. A Beállítások › Teljesítmény alatt állítsd a GPU-memóriát arra, amennyit a videokártyád elbír, legfeljebb a memóriája 3/8-ára. Az Automatikus a memóriahasználatot követi, a számítógép memóriájának negyedén és a kártya 3/8-án belül, és ismert memóriájú kártyánál nem számítja bele a dokumentumot. Amíg nem férnek el, az állapotsor a GPU-memória megtelt üzenetet mutatja. GPU Memory Full GPU-memória megtelt @@ -4320,8 +4341,6 @@ cameraRaw Yellow Sárga The fastest and the softest, with colour 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}”. - Move Up Mozgatás felfelé - Move Down Mozgatás lefelé Previous Brush Előző ecset Next Brush Következő ecset First Brush Első ecset @@ -4336,24 +4355,15 @@ cameraRaw Yellow Sárga Use Használat In Front Elöl Behind Mögött - -# DDS Options (#1327) DDS Options DDS-beállítások Generate Mipmaps Mipmapek létrehozása - -# Color Table (.act) dialog There is no color table to save. Nincs menthető színtábla. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} szín mentve ide: {file} - -# Graphics Adapter preference (#1885) GPU adapter GPU-adapter - -# Styles panel: Import / Export Styles (.asl) Import Styles… Stílusok importálása… Export Selected Styles… Kijelölt stílusok exportálása… Export Styles… Stílusok exportálása… {file} is not a style library (.asl) {file} nem stíluskönyvtár (.asl) -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Előbb hagyd jóvá vagy vond vissza a művelet lépésének nyitott párbeszédablakát Pro Medium Gray Pro középszürke Solarized Solarized @@ -4362,28 +4372,11 @@ cameraRaw Yellow Sárga Pro Light Pro világos Resize Windows to Fit Ablakok átméretezése a képhez EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Automatikus bekezdésirány Left-to-right paragraph direction Balról jobbra irányuló bekezdés Right-to-left paragraph direction Jobbról balra irányuló bekezdés Not rendered: this adjustment ({key}) is kept as imported. Nem jelenik meg: ez a korrekció ({key}) importált állapotában marad. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Színalapú - Decontaminate Colors Színek fertőtlenítése - Edge Detection Élészlelés - Global Refinements Globális finomítások - High Quality Preview Kiváló minőségű előnézet - Object Aware Objektumalapú - Real-Time Refinement Valós idejű finomítás - Refine Edge Brush Tool Élfinomító ecset eszköz - Refine Hair Haj finomítása - Refine Mode Finomítási mód - Remember Settings Beállítások megjegyzése - View Mode Nézetmód - Object Aware needs a segmentation model, which isn't available yet Az Objektumalapú módhoz szegmentálási modell kell, amely még nem érhető el - Refine Hair needs hair detection, which isn't available yet A Haj finomításához hajfelismerés kell, amely még nem érhető el -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Színárnyalat-kocka Brightness Cube Fényerő-kocka Color Wheel Színkör @@ -4399,9 +4392,8 @@ cameraRaw Yellow Sárga Grayscale Ramp Szürkeárnyalatos sáv Current Colors Aktuális színek Make Ramp Web Safe Sáv korlátozása webes színekre - Select and Mask was closed: its document is no longer the active one A Kijelölés és maszk bezárult: a dokumentuma már nem az aktív - Select and Mask was closed: another layer was selected A Kijelölés és maszk bezárult: másik réteg lett kijelölve -# Art History Brush (#213). + The path was kept as the Work Path Az útvonal munkaútvonalként megmaradt + The path was discarded Az útvonal el lett vetve Art History Brush Tool Művészi előzményecset eszköz Tight Short Szoros, rövid Tight Medium Szoros, közepes @@ -4415,3 +4407,20 @@ cameraRaw Yellow Sárga Font size presets Betűméret-előbeállítások Leading presets Sorköz-előbeállítások Tracking presets Betűköz-előbeállítások + Color Aware Színalapú + Decontaminate Colors Színek fertőtlenítése + Edge Detection Élészlelés + Global Refinements Globális finomítások + High Quality Preview Kiváló minőségű előnézet + Object Aware Objektumalapú + Real-Time Refinement Valós idejű finomítás + Refine Edge Brush Tool Élfinomító ecset eszköz + Refine Hair Haj finomítása + Refine Mode Finomítási mód + Remember Settings Beállítások megjegyzése + View Mode Nézetmód + Object Aware needs a segmentation model, which isn't available yet Az Objektumalapú módhoz szegmentálási modell kell, amely még nem érhető el + Refine Hair needs hair detection, which isn't available yet A Haj finomításához hajfelismerés kell, amely még nem érhető el + Select and Mask was closed: its document is no longer the active one A Kijelölés és maszk bezárult: a dokumentuma már nem az aktív + Select and Mask was closed: another layer was selected A Kijelölés és maszk bezárult: másik réteg lett kijelölve + Drag to move the selected path Húzza a kijelölt útvonal mozgatásához diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e68b0a7886..b7c92b1802 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -13,18 +13,112 @@ # letters; the trailing "…" of dialog commands is kept. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Opsi Mask… - Layer Mask Display Options… Opsi Tampilan Mask Layer… # Channel Options and New Spot Channel (#3761) - Channel Color Warna Saluran - Color Indicates: Warna Menunjukkan: - Solidity: Soliditas: - Ink Characteristics Karakteristik Tinta # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) +# Counted status and panel messages + + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Labels added on main after this catalog (depth labels, Wayland drop, profiles, Camera Raw, Patch tool, rendering mode) + +# Warp grid presets (#388) + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) + Mask Options… Opsi Mask… + Layer Mask Display Options… Opsi Tampilan Mask Layer… + Channel Color Warna Saluran + Color Indicates: Warna Menunjukkan: + Solidity: Soliditas: + Ink Characteristics Karakteristik Tinta Paper Width Lebar kertas Paper Height Tinggi kertas Rows Baris @@ -43,7 +137,6 @@ 5 Columns, 3 Rows 5 kolom, 3 baris 8 Columns 8 kolom 12 Columns 12 kolom - File Berkas Edit Edit Image Gambar @@ -435,6 +528,7 @@ Intersect Shape Areas Irisan Area Bentuk Exclude Overlapping Shapes Kecualikan Bentuk yang Tumpang Tindih Merge Shape Components Gabungkan Komponen Bentuk + Path operations Operasi path Align Rata Top Edges Tepi Atas Vertical Centers Tengah Vertikal @@ -514,7 +608,6 @@ Color Range… Rentang Warna… Focus Area… Area Fokus… Select and Mask… Seleksi dan Mask… -# Select and Mask dialog labels Smart Radius Radius Cerdas Shift Edge Geser Tepi Decontaminate Dekontaminasi @@ -541,7 +634,6 @@ Blur Blur Blur Gallery Galeri Blur Field Blur… Field Blur… -# Field Blur pins (#3373) No pin selected Tidak ada pin yang dipilih Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Klik gambar untuk menambah pin; seret pin untuk memindahkannya, atau cincinnya untuk mengubah blur. Delete menghapus pin yang dipilih. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Seret pegangan pada garis luar untuk mengubah ukuran dan memutarnya, kotak untuk membulatkan sudutnya, dan titik di dalam untuk menentukan di mana blur dimulai. @@ -805,7 +897,6 @@ Statistics… Statistik… Refine Strokes Goresan penyempurnaan Edits Suntingan -# Counted status and panel messages @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} {n} swatch diekspor ke {file} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {n} swatch diimpor dari {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {n} kuas diimpor dari {group} @@ -820,7 +911,6 @@ @plural {n} slice|{n} slices {n} slice @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} peringatan preset kuas lainnya) @plural {what} with {n} warning|{what} with {n} warnings {what} dengan {n} peringatan - @plural {n} item|{n} items {n} item Auto Otomatis (print to the printer) (cetak ke printer) @@ -836,6 +926,9 @@ Add Layer Mask Tambah Mask Layer Add Stop Tambah Stop Add a layer style Tambah gaya layer + Move effect up Pindahkan efek ke atas + Move effect down Pindahkan efek ke bawah + Delete effect Hapus efek Add a mask (from the selection; {key} inverts) Tambah mask (dari seleksi; {key} membalik) Add an adjustment Tambah penyesuaian Add disk Tambah disk @@ -1061,8 +1154,6 @@ Delete current channel Hapus channel saat ini Delete current state Hapus kondisi saat ini Delete effect layer Hapus layer efek - -# Layers-panel trash confirmation Delete layer ‘{name}’? Hapus layer ‘{name}’? Delete {count} layers? {names} Hapus {count} layer? {names} Delete layer? Hapus layer? @@ -1071,7 +1162,6 @@ Missing delete command Perintah hapus tidak tersedia Invalid delete command Perintah hapus tidak valid Layer deleted, but confirmation preference could not be saved: {error} Layer dihapus, tetapi preferensi konfirmasi tidak dapat disimpan: {error} - Delete layer Hapus layer Delete layer comp Hapus layer comp Delete note Hapus catatan @@ -2162,7 +2252,6 @@ Align with layer Sejajarkan dengan layer Reset Alignment Reset Penyelarasan Centre the gradient (offset 0, 0) Tengahkan gradien (offset 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Editor Gradien Gradient picker Pemilih gradien Save As Preset Simpan sebagai Preset @@ -2678,8 +2767,6 @@ Select Bottom Layer Pilih Layer Terbawah Add Layer Above to Selection Tambah Layer di Atas ke Seleksi Add Layer Below to Selection Tambah Layer di Bawah ke Seleksi - -# Labels added on main after this catalog (depth labels, Wayland drop, profiles, Camera Raw, Patch tool, rendering mode) 8 bit 8 bit (bilangan bulat) Integer Bilangan bulat 16 bit 16 bit (bilangan bulat) @@ -2739,21 +2826,15 @@ cameraRaw Blending Pembauran GPU Backend Backend GPU Details Detail Rendering mode Mode rendering - -# Warp grid presets (#388) 3 x 3 3 × 3 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Kisi-kisi: Edit Type Edit Teks - - New Style… Gaya Baru… Style {name} saved Gaya {name} disimpan - Create new style (from the selected type) Buat gaya baru (dari teks terpilih) Create new style from the selected layer Buat gaya baru dari lapisan terpilih - Make Default Jadikan Default Reset to Default Atur Ulang ke Default Full-resolution preview unavailable Pratinjau resolusi penuh tidak tersedia @@ -2782,9 +2863,6 @@ cameraRaw Blending Pembauran Magnetic Lasso Tool Alat Magnetic Lasso Frequency Frekuensi Use tablet pressure to change pen width Gunakan tekanan tablet untuk mengubah lebar pena - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About Tentang Contributors Kontributor Models Model @@ -2815,8 +2893,6 @@ cameraRaw Blending Pembauran % of all commits % dari semua commit Lines +/− Baris +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commit, +{added} / −{deleted} baris (Δ {delta}), +{binAdded} / −{binDeleted} berkas biner, {first} – {last} - -# Swatches panel Create new swatch Buat swatch baru New Swatch… Swatch Baru… New Swatch Group… Grup Swatch Baru… @@ -2826,13 +2902,12 @@ cameraRaw Blending Pembauran Export Swatches for Exchange… Ekspor Swatch untuk Pertukaran… Reset Swatches Atur Ulang Swatch Add to Swatches Tambahkan ke Swatch -# Layer Style > Blending Options (Advanced Blending) Blend If: Blend If: + Current Layer: Layer Saat Ini: + Underlying Layer: Layer di Bawah: Channels: Channel: Knockout Knockout Apply At Canvas Bounds Terapkan efek di batas kanvas - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Pemilih Warna (Warna Teks) Color Picker ({name}) Pemilih Warna ({name}) Color Picker (Fill Color) Pemilih Warna (Warna Isian) @@ -2849,8 +2924,6 @@ cameraRaw Blending Pembauran Show/Hide Panels Tampilkan/Sembunyikan Panel Could not open Tidak dapat membuka {path}: the path is not valid Unicode; rename the file and open it again. {path}: jalur bukan Unicode yang valid; ganti nama file lalu buka lagi. - -# Fill dialog, layer style contours and Image Size Contents: Isi: Custom Pattern: Pola Kustom: Foreground Color Warna Foreground @@ -2877,14 +2950,12 @@ cameraRaw Blending Pembauran Rolling Slope - Descending Lereng Bergelombang - Menurun Rounded Steps Tangga Bulat Sawtooth 1 Gigi Gergaji 1 - Red Eye Tool Alat Mata Merah Pupil Size Ukuran pupil Darken Amount Jumlah penggelapan Click a red pupil to neutralize it Klik pupil merah untuk memperbaikinya open source sumber terbuka …and {n} more …dan {n} lagi - Eyedroppers: Eyedropper: Set Black Point Atur Titik Hitam Set Neutral Gray Point Atur Titik Abu-abu Netral @@ -2893,8 +2964,6 @@ cameraRaw Blending Pembauran Selection Preview: Pratinjau Seleksi: Black Matte Latar Hitam White Matte Latar Putih - -# Layer colour labels. Seafoam Busa Laut Indigo Nila Fuchsia Fuksia @@ -2914,20 +2983,14 @@ fontWeight Bold Tebal fontWeight ExtraBold Ekstra Tebal fontWeight Black Sangat Tebal fontWeight Italic Miring - -# Pattern Stamp tool Pattern Stamp Tool Alat Stempel Pola 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° - -# Painting symmetry presets. Dual Axis Sumbu Ganda Diagonal Diagonal Transform Symmetry Transformasi Simetri - -# Eyedropper Sample Size and Sample (#1649). Point Sample Sampel Titik 3 by 3 Average Rata-rata 3 × 3 5 by 5 Average Rata-rata 5 × 5 @@ -2939,15 +3002,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Warna ke Alpha… Transparency Threshold Ambang transparansi Opacity Threshold Ambang opasitas PhotoCraft — Screen Color Picker PhotoCraft — Pemilih Warna Layar - Rasterize svg groups deeper than Rasterisasi grup SVG yang lebih dalam dari ini 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 menonaktifkan ambang ini; grup SVG yang bersarang lebih dari 100 tingkat selalu dirasterisasi. Rule of Thirds Aturan Sepertiga @@ -2961,8 +3021,6 @@ fontWeight Italic Miring Cycle Orientation Ganti Orientasi Set the overlay options for the Crop tool Atur opsi overlay untuk alat Crop Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-klik diambil oleh desktop, yang memindahkan jendela dengan Alt-seret. Atur tombol pemindah jendelanya ke Super, atau kunci Alt di Jendela › Tombol Pengubah. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Pemilih Warna (Warna Gaya Lapisan) Auto Hide Notifications Sembunyikan notifikasi secara otomatis Notification Duration (seconds) Durasi notifikasi (detik) @@ -3038,7 +3096,6 @@ fontWeight Italic Miring Appearance Settings… Pengaturan Tampilan… Add to favorites Tambahkan ke favorit Remove from favorites Hapus dari favorit -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Merek cameraData Model Model cameraData Date Taken Tanggal Diambil @@ -3048,7 +3105,6 @@ cameraData ISO Speed Sensitivitas ISO cameraData Focal Length Panjang Fokal cameraData Focal Length (35 mm) Panjang Fokal (35 mm) cameraData Lens Lensa -# Shared panel docking Activate Panel Aktifkan Panel Change Panel Group Ubah Grup Panel Change Panel Layout Ubah Tata Letak Panel @@ -3092,7 +3148,6 @@ cameraData Lens Lensa Snap to Origin Jepret ke Titik Asal Search settings… Cari pengaturan… No matching settings Tidak ada pengaturan yang cocok -# Edit › Content-Aware Fill workspace Sampling Brush Tool Alat Kuas Pengambilan Sampel Sampling Area Overlay Hamparan Area Pengambilan Sampel Show Sampling Area Tampilkan Area Pengambilan Sampel @@ -3110,7 +3165,6 @@ cameraData Lens Lensa Output To Keluaran Ke Duplicate Layer Duplikat Layer Contract Ciutkan - Animation Options Opsi Animasi Entire Document Seluruh Dokumen Filter Options Opsi Filter @@ -3128,8 +3182,6 @@ cameraData Lens Lensa Add “copy” to Copied Layers and Groups Tambahkan “salinan” ke Lapisan dan Grup yang Disalin Preview on canvas when reordering layers Pratinjau pada kanvas saat mengurutkan ulang lapisan Show layer mask badges Tampilkan Lencana Masker Lapisan - -# Smart Filter editors Blending Options ({filter}) Opsi Pencampuran ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Sembunyikan efek lapisan dan Filter Cerdas (klik-{key}: semua lapisan) Show the layer's effects and Smart Filters ({key}-click: all layers) Tampilkan efek lapisan dan Filter Cerdas (klik-{key}: semua lapisan) @@ -3162,7 +3214,6 @@ curves Smooth Haluskan Fix the red plane first: its corners must form a convex quad Perbaiki bidang merah dulu: sudut-sudutnya harus membentuk segi empat cembung Alt-click a plane to set the clone source Alt-klik sebuah bidang untuk menetapkan sumber kloning Too many clone strokes: apply Vanishing Point first Terlalu banyak goresan kloning: terapkan Vanishing Point terlebih dahulu -# Select and Mask view modes (#1754) Onion Skin Kulit Bawang Marching Ants Semut Berbaris On Black Di Atas Hitam @@ -3171,7 +3222,6 @@ curves Smooth Haluskan Show Edge Tampilkan Tepi Show Original Tampilkan Asli F cycles the views; hold X to see the image F berganti tampilan; tahan X untuk melihat gambar -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Kuas Perhalus Tepi (R) Expand Detection Area Perluas Area Deteksi Restore Original Edge Pulihkan Tepi Asli @@ -3179,19 +3229,13 @@ curves Smooth Haluskan Clear Brush Strokes Hapus Goresan Kuas Show rulers Tampilkan Penggaris Presentation Presentasi - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Klik untuk menempatkan · Alt-klik atau seret ke luar kanvas untuk menghapus No document open Tidak ada dokumen yang terbuka {n} of {max} sample points {n} dari {max} titik sampel - -# History panel menu (#2966) New Snapshot… Snapshot Baru… History Options… Opsi Riwayat… -# History panel › History Options… (#2966) Allow Non-Linear History Izinkan Riwayat Non-Linier Make Layer Visibility Changes Undoable Perubahan Visibilitas Layer Dapat Diurungkan -# Print dialog (#2697) Emulsion Down Emulsi di Bawah Functions Fungsi Print Resolution: Resolusi Cetak: @@ -3203,7 +3247,6 @@ curves Smooth Haluskan Apply mask to layer before removing? Terapkan masker ke layer sebelum dihapus? The layer or its mask changed. Drag the mask onto the Trash again. Layer atau maskernya berubah. Seret masker ke Tempat Sampah lagi. Delete the vector mask? Hapus masker vektor? -# View › Guides › New Guide… › Color Light Blue Biru Muda Light Red Merah Terang Medium Blue Biru Sedang @@ -3224,8 +3267,6 @@ curves Smooth Haluskan Clear Brush Controls Hapus Kontrol Kuas Reset All Locked Settings Atur Ulang Semua Pengaturan Terkunci Copy Texture to Other Tools Salin Tekstur ke Alat Lain - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Muat Tindakan… Save Actions… Simpan Tindakan… New Action… Tindakan Baru… @@ -3237,10 +3278,8 @@ curves Smooth Haluskan @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} langkah belum memiliki padanan di PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} tindakan disimpan ke {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} langkah tanpa padanan Photoshop dilewati - File Naming Penamaan Berkas Starting serial Nomor urut awal -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Sisipkan Berhenti… Save Set… Simpan Set… Message: Pesan: @@ -3252,11 +3291,8 @@ curves Smooth Haluskan @plural {n} action|{n} actions {n} tindakan Background (Default) Background (Default) Content-Aware Fill Isi Content-Aware -# Batch / Image Processor Include All Subfolders Sertakan semua subfolder Auto Add/Delete Tambah/Hapus Otomatis - -# Native Windows printing qualification 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… @@ -3301,7 +3337,6 @@ curves Smooth Haluskan Could not write {name}: {error} Tidak dapat menulis {name}: {error} Kept {name}: written by another application {name} dipertahankan: ditulis oleh aplikasi lain Shadow Tint Rona bayangan -# PhotoCraft release checks. Check for Updates… Periksa Pembaruan… PhotoCraft Updates Pembaruan PhotoCraft Checking for updates… Memeriksa pembaruan… @@ -3314,35 +3349,27 @@ curves Smooth Haluskan Automatically Check for Updates Periksa Pembaruan Secara Otomatis Installed version: {version} Versi terpasang: {version} PhotoCraft {version} is available. PhotoCraft {version} tersedia. -# History panel › History Brush source (#2966) Paints from the History panel's source state Melukis dari status sumber panel Riwayat Sets the source for the history brush Menetapkan sumber untuk kuas riwayat -# Bevel & Emboss shading controls. Highlight Mode Mode Sorotan Highlight Color Warna Sorotan Highlight Opacity Opasitas Sorotan Shadow Mode Mode Bayangan Shadow Color Warna Bayangan Shadow Opacity Opasitas Bayangan -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Pakai profil tertanam ({profile}) Convert to the working space ({profile}) Konversi ke working space ({profile}) Remember this choice for future images Ingat pilihan ini untuk gambar berikutnya Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Aktifkan lagi pertanyaan ini lewat Ask On Mismatch di Edit › Pengaturan Warna. Button Mode Mode tombol Button Mode On Mode tombol aktif - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Gelapkan Antarmuka Lighten Interface Cerahkan Antarmuka -# Bevel & Emboss Technique. Technique Teknik Chisel Hard Pahat Keras Chisel Soft Pahat Lembut Open color-less EXR as ACEScg Buka EXR tanpa informasi warna sebagai ACEScg Do not append "copy" to filename when saving a copy Jangan tambahkan "copy" ke nama file saat menyimpan salinan - -# View › Guides › right-click a guide Edit Selected Guides Edit Panduan Terpilih Clear Selected Guides Hapus Panduan Terpilih Bicubic Automatic Bicubic otomatis @@ -3368,8 +3395,6 @@ curves Smooth Haluskan {set} (modified) {set} (diubah) Random Acak Show file name in title Tampilkan nama file di judul - -# Image › Mode › Bitmap (#5559) 50% Threshold Threshold 50% Pattern Dither Dither Pola Diffusion Dither Dither Difusi @@ -3388,10 +3413,8 @@ curves Smooth Haluskan Undo Changes Batalkan Perubahan {shortcut} is reserved by the system and can't be assigned. {shortcut} dicadangkan oleh sistem dan tidak dapat ditetapkan. Low-Latency Drawing (vsync off, applies at next launch) Menggambar latensi rendah (tanpa vsync, berlaku saat peluncuran berikutnya) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Transformasi Bebas masih diterapkan; coba lagi setelah selesai. The transform couldn't be applied. Transformasi tidak dapat diterapkan. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Layer-nya membutuhkan {needed} memori GPU; anggaran menyisakan {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Atur Memori GPU di Preferensi › Performa sesuai kapasitas kartu grafis Anda, paling banyak 3/8 memorinya. Otomatis mengikuti Pemakaian memori, dalam seperempat memori komputer ini dan 3/8 memori kartu, dan tidak membebankan dokumen pada kartu yang memorinya diketahui. Selama belum muat, bilah status menampilkan Memori GPU Penuh. GPU Memory Full Memori GPU Penuh @@ -3418,8 +3441,6 @@ curves Smooth Haluskan The fastest and the softest, with colour 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}”. - Move Up Pindah ke atas - Move Down Pindah ke bawah Previous Brush Kuas sebelumnya Next Brush Kuas berikutnya First Brush Kuas pertama @@ -3434,27 +3455,18 @@ curves Smooth Haluskan Use Gunakan In Front Di Depan Behind Di Belakang - -# DDS Options (#1327) DDS Options Opsi DDS Compression Kompresi Generate Mipmaps Buat mipmap - -# Color Table (.act) dialog There is no color table to save. Tidak ada tabel warna untuk disimpan. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} warna disimpan ke {file} - -# Graphics Adapter preference (#1885) GPU adapter Adaptor GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Impor Gaya… Export Selected Styles… Ekspor Gaya Terpilih… Export Styles… Ekspor Gaya… {file} is not a style library (.asl) {file} bukan pustaka gaya (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {n} gaya diimpor dari {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} gaya diekspor ke {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Konfirmasi atau batalkan dulu dialog langkah tindakan yang terbuka Pro Medium Gray Pro Abu-abu Sedang Solarized Solarized @@ -3463,29 +3475,11 @@ curves Smooth Haluskan Pro Light Pro Terang Resize Windows to Fit Ubah ukuran jendela agar pas EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Arah paragraf otomatis Left-to-right paragraph direction Arah paragraf kiri ke kanan Right-to-left paragraph direction Arah paragraf kanan ke kiri Not rendered: this adjustment ({key}) is kept as imported. Tidak dirender: penyesuaian ini ({key}) disimpan seperti saat diimpor. -# Print preview image (#8236) Print preview image Print preview image - Clear Selection Hapus Seleksi - Color Aware Berbasis Warna - Decontaminate Colors Dekontaminasi Warna - Edge Detection Deteksi Tepi - Global Refinements Penyempurnaan Global - High Quality Preview Pratinjau Kualitas Tinggi - Object Aware Berbasis Objek - Real-Time Refinement Penyempurnaan Waktu Nyata - Refine Edge Brush Tool Alat Kuas Perhalus Tepi - Refine Hair Perhalus Rambut - Refine Mode Mode Penyempurnaan - Remember Settings Ingat Pengaturan - View Mode Mode Tampilan - Object Aware needs a segmentation model, which isn't available yet Berbasis Objek memerlukan model segmentasi, yang belum tersedia - Refine Hair needs hair detection, which isn't available yet Perhalus Rambut memerlukan deteksi rambut, yang belum tersedia -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Kubus Hue Brightness Cube Kubus Kecerahan Color Wheel Roda Warna @@ -3501,9 +3495,8 @@ curves Smooth Haluskan Grayscale Ramp Gradasi Grayscale Current Colors Warna Saat Ini Make Ramp Web Safe Jadikan Gradasi Aman untuk Web - Select and Mask was closed: its document is no longer the active one Seleksi dan Mask ditutup: dokumennya tidak lagi aktif - Select and Mask was closed: another layer was selected Seleksi dan Mask ditutup: layer lain dipilih -# Art History Brush (#213). + The path was kept as the Work Path Path dipertahankan sebagai Work Path + The path was discarded Path dibuang Art History Brush Tool Alat Kuas riwayat artistik Tight Short Rapet pendek Tight Medium Rapet sedang @@ -3515,8 +3508,6 @@ curves Smooth Haluskan Loose Curl Ikal longgar Area Area Stylized dabs from a history state Cap bergaya dari sebuah keadaan riwayat - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Color Table Tabel Warna Gamma Gamma Profile Profil @@ -3524,3 +3515,21 @@ curves Smooth Haluskan Font size presets Preset ukuran font Leading presets Preset leading Tracking presets Preset tracking + Clear Selection Hapus Seleksi + Color Aware Berbasis Warna + Decontaminate Colors Dekontaminasi Warna + Edge Detection Deteksi Tepi + Global Refinements Penyempurnaan Global + High Quality Preview Pratinjau Kualitas Tinggi + Object Aware Berbasis Objek + Real-Time Refinement Penyempurnaan Waktu Nyata + Refine Edge Brush Tool Alat Kuas Perhalus Tepi + Refine Hair Perhalus Rambut + Refine Mode Mode Penyempurnaan + Remember Settings Ingat Pengaturan + View Mode Mode Tampilan + Object Aware needs a segmentation model, which isn't available yet Berbasis Objek memerlukan model segmentasi, yang belum tersedia + Refine Hair needs hair detection, which isn't available yet Perhalus Rambut memerlukan deteksi rambut, yang belum tersedia + Select and Mask was closed: its document is no longer the active one Seleksi dan Mask ditutup: dokumennya tidak lagi aktif + Select and Mask was closed: another layer was selected Seleksi dan Mask ditutup: layer lain dipilih + Select Layer Under Cursor Pilih Lapisan di Bawah Kursor diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c1cb47ef59..98c1c0390a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -13,18 +13,132 @@ # letters; the trailing … of dialog commands is kept. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Opzioni maschera… - Layer Mask Display Options… Opzioni di visualizzazione maschera di livello… # Channel Options and New Spot Channel (#3761) - Channel Color Colore canale - Color Indicates: Il colore indica: - Solidity: Solidità: - Ink Characteristics Caratteristiche inchiostro # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Dialogs and panels + +# Layers-panel trash confirmation + + +# Tool names, brush and style option tables + +# Templates with placeholders + +# Preferences (labels are generated from the setting names) + +# Added with the rebase onto the dock / brush picker work + +# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Tool, filter, warp-style, path, layer-comp and metadata names that fell outside the `tl!` test. +# Italian follows the tool wording used above (Strumento X). + +# Command-id override: under Edit > Purge a bare Annulla reads as an action, not the history. +# Rendering mode and recovery + + + + + +# Camera Raw: contextual controls and window title + +# Strings added on main after this catalog was written (2026-10). + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) +# Layer Style > Blending Options (Advanced Blending) + +# Swatches panel + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) that the +# other catalogs already translate + +# Path, channel, layer style, status and System Info labels the Czech catalog added + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# Color management, Liquify, glyph group, warp and Camera Raw labels the Serbian, Vietnamese and Japanese catalogs added +# Shortcut commands, find and replace, profile prompts and metadata labels the German, Hungarian and Serbian catalogs added +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + Mask Options… Opzioni maschera… + Layer Mask Display Options… Opzioni di visualizzazione maschera di livello… + Channel Color Colore canale + Color Indicates: Il colore indica: + Solidity: Solidità: + Ink Characteristics Caratteristiche inchiostro Paper Width Larghezza della carta Paper Height Altezza della carta Columns Colonne @@ -44,7 +158,6 @@ 5 Columns, 3 Rows 5 colonne, 3 righe 8 Columns 8 colonne 12 Columns 12 colonne - File File Edit Modifica Image Immagine @@ -451,6 +564,7 @@ Intersect Shape Areas Interseca aree forme Exclude Overlapping Shapes Escludi forme sovrapposte Merge Shape Components Unisci componenti forma + Path operations Operazioni sui tracciati Align Allinea Top Edges Bordi superiori Vertical Centers Centri verticali @@ -530,7 +644,6 @@ Color Range… Intervallo colori… Focus Area… Area di messa a fuoco… Select and Mask… Seleziona e maschera… -# Select and Mask dialog labels Smart Radius Raggio avanzato Shift Edge Sposta bordo Decontaminate Decontamina @@ -557,7 +670,6 @@ Blur Sfocatura Blur Gallery Galleria sfocatura Field Blur… Sfocatura campo… -# Field Blur pins (#3373) No pin selected Nessuna puntina selezionata Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Fai clic sull’immagine per aggiungere una puntina; trascina una puntina per spostarla o il suo anello per cambiare la sfocatura. Canc rimuove la puntina selezionata. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Trascina le maniglie sul contorno per ridimensionarlo e ruotarlo, il quadrato per arrotondarne gli angoli e i punti interni per stabilire dove inizia la sfocatura. @@ -821,8 +933,6 @@ Edits Modifiche @plural {n} item|{n} items {n} elemento|{n} elementi Auto Automatico - -# Dialogs and panels (print to the printer) (stampa sulla stampante) + Add variable + Aggiungi variabile 30 frames @ 30 fps 30 fotogrammi @ 30 fps @@ -836,6 +946,9 @@ Add Layer Mask Aggiungi maschera di livello Add Stop Aggiungi punto Add a layer style Aggiungi uno stile livello + Move effect up Sposta effetto in alto + Move effect down Sposta effetto in basso + Delete effect Elimina effetto Add a mask (from the selection; {key} inverts) Aggiungi una maschera (dalla selezione; {key} inverte) Add an adjustment Aggiungi una regolazione Add disk Aggiungi disco @@ -1063,8 +1176,6 @@ Delete current channel Elimina canale corrente Delete current state Elimina stato corrente Delete effect layer Elimina livello effetto - -# Layers-panel trash confirmation Delete layer ‘{name}’? Eliminare il livello «{name}»? Delete {count} layers? {names} Eliminare {count} livelli? {names} Delete layer? Eliminare il livello? @@ -1073,7 +1184,6 @@ Missing delete command Comando di eliminazione mancante Invalid delete command Comando di eliminazione non valido Layer deleted, but confirmation preference could not be saved: {error} Il livello è stato eliminato, ma non è stato possibile salvare la preferenza di conferma: {error} - Delete layer Elimina livello Delete layer comp Elimina composizione livelli Delete note Elimina nota @@ -1105,6 +1215,7 @@ Drag a rectangle around the object Trascina un rettangolo attorno all'oggetto Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Trascina sull'immagine per aggiungere un vincolo; Maiusc per orizz/vert; clic destro su un vincolo per modificarlo o eliminarlo. Drag to move the active shape's path or the Work Path Trascina per spostare il tracciato forma attiva o il Tracciato di lavoro + Drag to move the selected path Trascina per spostare il tracciato selezionato Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Clic: seleziona punto · Trascina: sposta punto, maniglia o segmento · {shift}-clic: aggiungi · {alt}-clic: intero sottotracciato Draw with the Pen tool (P) or make a work path from a selection. Disegna con Penna (P) o crea un tracciato di lavoro da una selezione. Drop an image or PSD anywhere to open it. Trascina un'immagine o PSD ovunque per aprirlo. @@ -1626,8 +1737,6 @@ No saved presets yet. Nessun predefinito salvato. Error Errore Command Comando - -# Tool names, brush and style option tables Adjustment layers have nothing to transform I livelli di regolazione non hanno nulla da trasformare Altitude Altitudine Android 1080p Android 1080p @@ -1859,8 +1968,6 @@ Yellows Gialli Zoom Tool Strumento Zoom {name} Properties Proprietà {name} - -# Templates with placeholders Revert “{name}” to the last saved version? Your changes will be lost. Ripristinare “{name}” all'ultima versione salvata? Le modifiche andranno perse. Do you want to save the changes you made to “{name}” before quitting? Vuoi salvare le modifiche apportate a “{name}” prima di uscire? Do you want to save the changes you made to “{name}” before closing? Vuoi salvare le modifiche apportate a “{name}” prima di chiudere? @@ -1881,8 +1988,6 @@ @plural {n} Layer|{n} Layers {n} livello|{n} livelli @plural {n} layer|{n} layers {n} livello|{n} livelli @plural Group · {n} layer|Group · {n} layers Gruppo · {n} livello|Gruppo · {n} livelli - -# Preferences (labels are generated from the setting names) Additional plugins folder Cartella plugin aggiuntiva Adobe Adobe Adobe rgb Adobe RGB @@ -2082,8 +2187,6 @@ Luminosity Luminosità @plural {n} sample|{n} samples {n} campione|{n} campioni {added}, {removed} subtracted {added}, {removed} sottratti - -# Added with the rebase onto the dock / brush picker work Adjustment Preview Anteprima regolazione Airbrush: keeps depositing paint while the pointer rests. Aerografo: continua a depositare vernice mentre il puntatore è fermo. Angle: Angolo: @@ -2116,8 +2219,6 @@ Brush picker Selettore pennelli Erase Cancella Right click with painting tools Clic destro con strumenti pittura - -# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). System Info… Info sistema… System Info Info sistema More panels Altri pannelli @@ -2188,7 +2289,6 @@ Align with layer Allinea con livello Reset Alignment Reimposta allineamento Centre the gradient (offset 0, 0) Centra sfumatura (offset 0,0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Editor sfumatura Gradient picker Selettore sfumatura Gradient stops Punti della sfumatura @@ -2248,9 +2348,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Griglia: - -# Tool, filter, warp-style, path, layer-comp and metadata names that fell outside the `tl!` test. -# Italian follows the tool wording used above (Strumento X). Color Range Intervallo colori Adaptive Wide Angle Grandangolo adattivo Chalk & Charcoal Gessetto e carboncino @@ -2334,10 +2431,7 @@ New Channel Nuovo canale Save Selection Salva selezione Load Selection Carica selezione - -# Command-id override: under Edit > Purge a bare Annulla reads as an action, not the history. @id edit.purge.undo Cronologia annullamenti -# Rendering mode and recovery Rendering Mode Modalità rendering Automatic (recommended) Automatico (consigliato) CPU / Compatibility CPU / Compatibilità @@ -2353,11 +2447,8 @@ Advanced Avanzato GPU Backend Backend GPU Details Dettagli - Rendering mode Modalità rendering Freeze Lasso: drag to freeze an area, Alt-drag to thaw it (L) Lazo congela: trascina per congelare un'area, Alt-trascina per scongelare (L) - - Shadow Clipping Warning (U) Avviso clipping ombre (U) Highlight Clipping Warning (O) Avviso clipping luci (O) Show Lab Color Readouts Mostra letture colore Lab @@ -2366,10 +2457,7 @@ Show Skin Tone Indicator Mostra indicatore incarnato Tone Histogram Istogramma tonale Show Selected Region Mostra regione selezionata - cameraRaw Light Luce - -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Filtro Camera Raw ({layer}) Camera Raw ({name}) Camera Raw ({name}) cameraRaw Lights Toni chiari @@ -2393,8 +2481,6 @@ cameraRaw Amount Quantità Scale or rotate the moved area, then press {key} Ridimensiona o ruota l'area spostata, poi premi {key} Now drag the selection onto another area Ora trascina la selezione su un'altra area Edit Type Modifica testo - -# Strings added on main after this catalog was written (2026-10). Relight… Riillumina… No patterns Nessun pattern Enable {name} Attiva {name} @@ -2424,9 +2510,6 @@ cameraRaw Amount Quantità Magnetic Lasso Tool Strumento Lazo magnetico Frequency Frequenza Use tablet pressure to change pen width Usa pressione tavoletta per cambiare la larghezza della penna - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About Informazioni Contributors Collaboratori Models Modelli @@ -2457,12 +2540,9 @@ cameraRaw Amount Quantità % of all commits % di tutti i commit Lines +/− Righe +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commit, +{added} / −{deleted} righe (Δ {delta}), +{binAdded} / −{binDeleted} risorse binarie, {first} – {last} -# Layer Style > Blending Options (Advanced Blending) Blend If: Fondi se: Channels: Canali: Knockout Foratura - -# Swatches panel Create new swatch Crea nuovo campione New Swatch… Nuovo campione… New Swatch Group… Nuovo gruppo di campioni… @@ -2474,8 +2554,6 @@ cameraRaw Amount Quantità Add to Swatches Aggiungi ai campioni Convert to Layers Converti in livelli Apply At Canvas Bounds Applica ai limiti del quadro - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Selettore colore (Colore del testo) Color Picker ({name}) Selettore colore ({name}) Color Picker (Fill Color) Selettore colore (Colore di riempimento) @@ -2492,8 +2570,6 @@ cameraRaw Amount Quantità Show/Hide Panels Mostra/nascondi pannelli Could not open Impossibile aprire {path}: the path is not valid Unicode; rename the file and open it again. {path}: il percorso non è Unicode valido; rinomina il file e riaprilo. - -# Fill dialog, layer style contours and Image Size Contents: Contenuto: Custom Pattern: Pattern personalizzato: Foreground Color Colore primo piano @@ -2527,7 +2603,6 @@ cameraRaw Amount Quantità Click a red pupil to neutralize it Fai clic su una pupilla rossa per correggerla open source open source …and {n} more …e altri {n} - Eyedroppers: Contagocce: Set Black Point Imposta punto nero Set Neutral Gray Point Imposta il punto grigio neutro @@ -2536,8 +2611,6 @@ cameraRaw Amount Quantità Selection Preview: Anteprima selezione: Black Matte Sfondo nero White Matte Sfondo bianco - -# Layer colour labels. Seafoam Schiuma marina Indigo Indaco Fuchsia Fucsia @@ -2557,8 +2630,6 @@ fontWeight Bold Grassetto fontWeight ExtraBold Extragrassetto fontWeight Black Nero fontWeight Italic Corsivo - -# Pattern Stamp tool Pattern Stamp Tool Strumento Timbro pattern Pattern Stamp Timbro pattern Impressionist Impressionista @@ -2566,13 +2637,9 @@ fontWeight Italic Corsivo 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° - -# Painting symmetry presets. Dual Axis Doppio asse Diagonal Diagonale Transform Symmetry Trasforma simmetria - -# Eyedropper Sample Size and Sample (#1649). Point Sample Campione puntiforme 3 by 3 Average Media 3 × 3 5 by 5 Average Media 5 × 5 @@ -2584,15 +2651,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Colore ad alfa… Transparency Threshold Soglia di trasparenza Opacity Threshold Soglia di opacità PhotoCraft — Screen Color Picker PhotoCraft — Selettore colore schermo - Rasterize svg groups deeper than Rasterizza i gruppi SVG oltre questa profondità 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 disattiva questa soglia; i gruppi SVG annidati oltre 100 livelli vengono sempre rasterizzati. Rule of Thirds Regola dei terzi @@ -2606,8 +2670,6 @@ fontWeight Italic Corsivo Cycle Orientation Cambia orientamento Set the overlay options for the Crop tool Imposta le opzioni di sovrapposizione dello strumento Taglierina Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-clic è andato al desktop, che sposta le finestre con Alt-trascina. Imposta il suo tasto per spostare le finestre su Super, oppure blocca Alt in Finestra › Tasti modificatori. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Selettore colore (colore dello stile livello) Auto Hide Notifications Nascondi automaticamente le notifiche Notification Duration (seconds) Durata della notifica (secondi) @@ -2684,7 +2746,6 @@ fontWeight Italic Corsivo Appearance Settings… Impostazioni aspetto… Add to favorites Aggiungi ai preferiti Remove from favorites Rimuovi dai preferiti -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data Dati fotocamera cameraData Make Marca cameraData Model Modello @@ -2695,7 +2756,6 @@ cameraData ISO Speed Sensibilità ISO cameraData Focal Length Lunghezza focale cameraData Focal Length (35 mm) Lunghezza focale (35 mm) cameraData Lens Obiettivo -# Shared panel docking Activate Panel Attiva pannello Change Panel Group Cambia gruppo di pannelli Change Panel Layout Cambia disposizione dei pannelli @@ -2739,7 +2799,6 @@ cameraData Lens Obiettivo Snap to Origin Aggancia all'origine Search settings… Cerca impostazioni… No matching settings Nessuna impostazione corrispondente -# Edit › Content-Aware Fill workspace Sampling Brush Tool Strumento Pennello di campionamento Sampling Area Overlay Sovrapposizione area di campionamento Show Sampling Area Mostra area di campionamento @@ -2755,7 +2814,6 @@ cameraData Lens Obiettivo Mirror Rifletti Output Settings Impostazioni di output Output To Output in - Animation Options Opzioni animazione Entire Document Documento intero Filter Options Opzioni filtro @@ -2772,8 +2830,6 @@ cameraData Lens Obiettivo Add “copy” to Copied Layers and Groups Aggiungi «copia» ai livelli e ai gruppi duplicati Preview on canvas when reordering layers Anteprima sulla tela durante il riordino dei livelli Show layer mask badges Mostra distintivi delle maschere di livello - -# Smart Filter editors Blending Options ({filter}) Opzioni di fusione ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Nascondi effetti del livello e filtri avanzati ({key}-clic: tutti i livelli) Show the layer's effects and Smart Filters ({key}-click: all layers) Mostra effetti del livello e filtri avanzati ({key}-clic: tutti i livelli) @@ -2808,7 +2864,6 @@ curves Smooth Leviga Fix the red plane first: its corners must form a convex quad Correggi prima il piano rosso: i suoi angoli devono formare un quadrilatero convesso Alt-click a plane to set the clone source Alt-clic su un piano per impostare l’origine della clonazione Too many clone strokes: apply Vanishing Point first Troppi tratti di clonazione: applica prima Punto di fuga -# Select and Mask view modes (#1754) Onion Skin Velina Marching Ants Formiche in marcia On Black Su nero @@ -2817,7 +2872,6 @@ curves Smooth Leviga Show Edge Mostra bordo Show Original Mostra originale F cycles the views; hold X to see the image F scorre le viste; tieni premuto X per vedere l'immagine -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Pennello per migliorare il bordo (R) Expand Detection Area Espandi area di rilevamento Restore Original Edge Ripristina bordo originale @@ -2825,19 +2879,13 @@ curves Smooth Leviga Clear Brush Strokes Cancella tracce del pennello Show rulers Mostra righelli Presentation Presentazione - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Fai clic per posizionare · Alt-clic o trascina fuori dal quadro per rimuovere No document open Nessun documento aperto {n} of {max} sample points {n} di {max} punti di campionamento - -# History panel menu (#2966) New Snapshot… Nuova istantanea… History Options… Opzioni cronologia… -# History panel › History Options… (#2966) Allow Non-Linear History Consenti cronologia non lineare Make Layer Visibility Changes Undoable Rendi annullabili le modifiche di visibilità dei livelli -# Print dialog (#2697) Emulsion Down Emulsione sotto Functions Funzioni Print Resolution: Risoluzione di stampa: @@ -2849,7 +2897,6 @@ curves Smooth Leviga Apply mask to layer before removing? Applicare la maschera al livello prima di rimuoverla? The layer or its mask changed. Drag the mask onto the Trash again. Il livello o la sua maschera è cambiato. Trascina di nuovo la maschera nel cestino. Delete the vector mask? Eliminare la maschera vettoriale? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} {n} campione esportato in {file}|{n} campioni esportati in {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {n} pennello importato da {group}|{n} pennelli importati da {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {n} campione importato da {file}|{n} campioni importati da {file} @@ -2864,14 +2911,10 @@ curves Smooth Leviga @plural {n} step|{n} steps {n} passaggio|{n} passaggi @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} altro avviso sui predefiniti pennello)|{warning} (+{n} altri avvisi sui predefiniti pennello) @plural {what} with {n} warning|{what} with {n} warnings {what} con {n} avviso|{what} con {n} avvisi -# View › Guides › New Guide… › Color Light Blue Blu chiaro Light Red Rosso chiaro Medium Blue Blu medio Light Gray Grigio chiaro - -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) that the -# other catalogs already translate No No Yes Sì @id select.all Seleziona tutto @@ -4013,8 +4056,6 @@ layerLabel No Color Nessun colore Set Colors Imposta colori Switch Foreground and Background Colors Scambia colori di primo piano e sfondo Target Destinazione - -# Path, channel, layer style, status and System Info labels the Czech catalog added Make Work Path… Crea tracciato di lavoro… Create Vector Mask Crea maschera vettoriale Make Selection… Crea selezione… @@ -4057,7 +4098,7 @@ layerLabel No Color Nessun colore Layer Mask Hides Effects La maschera di livello nasconde gli effetti Vector Mask Hides Effects La maschera vettoriale nasconde gli effetti General Blending Fusione generale - This Layer: Questo livello: + Current Layer: Livello corrente: Underlying Layer: Livello sottostante: Nothing to paste: the clipboard holds no image Niente da incollare: gli appunti non contengono un'immagine Preferences saved Preferenze salvate @@ -4178,8 +4219,6 @@ navigator Zoom Zoom Clear Brush Controls Cancella controlli pennello Reset All Locked Settings Ripristina tutte le impostazioni bloccate Copy Texture to Other Tools Copia texture su altri strumenti - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Carica azioni… Save Actions… Salva azioni… New Action… Nuova azione… @@ -4191,10 +4230,8 @@ navigator Zoom Zoom @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} passaggio non ha ancora un equivalente in PhotoCraft|{n} passaggi non hanno ancora un equivalente in PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Salvata {n} azione in {file}|Salvate {n} azioni in {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Omesso {n} passaggio senza equivalente in Photoshop|Omessi {n} passaggi senza equivalente in Photoshop - File Naming Denominazione file Starting serial Numero di serie iniziale -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Inserisci interruzione… Save Set… Salva set… Message: Messaggio: @@ -4205,11 +4242,8 @@ navigator Zoom Zoom Step {step} is waiting for its dialog Il passaggio {step} attende la sua finestra di dialogo @plural {n} action|{n} actions {n} azione|{n} azioni Background (Default) Sfondo (predefinito) -# Batch / Image Processor Include All Subfolders Includi tutte le sottocartelle Auto Add/Delete Aggiungi/elimina automaticamente - -# Native Windows printing qualification 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… @@ -4254,7 +4288,6 @@ navigator Zoom Zoom Could not write {name}: {error} Impossibile scrivere {name}: {error} Kept {name}: written by another application {name} mantenuto: scritto da un’altra applicazione Shadow Tint Tinta ombre -# PhotoCraft release checks. Check for Updates… Cerca aggiornamenti… PhotoCraft Updates Aggiornamenti di PhotoCraft Checking for updates… Ricerca aggiornamenti… @@ -4267,34 +4300,27 @@ navigator Zoom Zoom Automatically Check for Updates Cerca automaticamente aggiornamenti Installed version: {version} Versione installata: {version} PhotoCraft {version} is available. PhotoCraft {version} è disponibile. -# History panel › History Brush source (#2966) Paints from the History panel's source state Dipinge dallo stato di origine del pannello Cronologia Sets the source for the history brush Imposta l'origine del pennello storia -# Bevel & Emboss shading controls. Highlight Mode Metodo luci Highlight Color Colore luci Highlight Opacity Opacità luci Shadow Mode Metodo ombre Shadow Color Colore ombre Shadow Opacity Opacità ombre -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Usa profilo incorporato ({profile}) Convert to the working space ({profile}) Converti in spazio di lavoro ({profile}) Remember this choice for future images Ricorda questa scelta per le prossime immagini Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Riattiva la richiesta con Ask On Mismatch in Modifica › Impostazioni colore. Button Mode Modalità pulsante Button Mode On Modalità pulsante attiva -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Scurisci interfaccia Lighten Interface Schiarisci interfaccia -# Bevel & Emboss Technique. Technique Tecnica Chisel Hard Cesello duro Chisel Soft Cesello morbido Open color-less EXR as ACEScg Apri gli EXR senza spazio colore come ACEScg Do not append "copy" to filename when saving a copy Non aggiungere "copy" al nome del file quando si salva una copia - -# Color management, Liquify, glyph group, warp and Camera Raw labels the Serbian, Vietnamese and Japanese catalogs added Adobe-rgb-compat Adobe RGB (compatibile) All shortcuts reset to Photoshop defaults. Tutte le scorciatoie ripristinate ai predefiniti di Photoshop. Arc Lower Arco inferiore @@ -4369,7 +4395,6 @@ navigator Zoom Zoom red rosso violet viola yellow giallo -# Shortcut commands, find and replace, profile prompts and metadata labels the German, Hungarian and Serbian catalogs added Export As: {name} Esporta come: {name} Color Sampler Tool Strumento Campionatore colore Proof Setup… Configurazione prova… @@ -4457,7 +4482,6 @@ layerLabel Red Rosso layers Fill Riempimento layers Fill: Riempimento: shape Appearance Aspetto -# View › Guides › right-click a guide Edit Selected Guides Modifica guide selezionate Clear Selected Guides Cancella guide selezionate Bicubic Automatic Bicubica automatica @@ -4482,8 +4506,6 @@ shape Appearance Aspetto set name nome del set {set} (modified) {set} (modificato) Show file name in title Mostra nome file nel titolo - -# Image › Mode › Bitmap (#5559) 50% Threshold Soglia 50% Pattern Dither Dithering pattern Diffusion Dither Dithering diffusione @@ -4501,10 +4523,8 @@ shape Appearance Aspetto Undo Changes Annulla modifiche {shortcut} is reserved by the system and can't be assigned. {shortcut} è riservata dal sistema e non può essere assegnata. Low-Latency Drawing (vsync off, applies at next launch) Disegno a bassa latenza (senza vsync, si applica al prossimo avvio) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Trasformazione libera è ancora in corso di applicazione; riprova quando è terminata. The transform couldn't be applied. Impossibile applicare la trasformazione. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. I livelli richiedono {needed} di memoria GPU; il budget ne lascia {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Imposta Memoria GPU in Preferenze › Prestazioni su quanto può contenere la tua scheda grafica, al massimo 3/8 della sua memoria. Automatico segue Uso memoria, entro un quarto della memoria di questo computer e 3/8 di quella della scheda, e non conta il documento su una scheda la cui memoria è nota. Finché non ci stanno, la barra di stato mostra Memoria GPU piena. GPU Memory Full Memoria GPU piena @@ -4526,8 +4546,6 @@ shape Appearance Aspetto 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. “{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}”. - Move Up Sposta su - Move Down Sposta giù Memory Usage Utilizzo memoria Per-document RAM limit (MB) Limite RAM per documento (MB) Installed RAM: {ram} MB; this limit: {percent}% RAM installata: {ram} MB; questo limite: {percent}% @@ -4537,26 +4555,17 @@ shape Appearance Aspetto Use Usa In Front Davanti Behind Dietro - -# DDS Options (#1327) DDS Options Opzioni DDS Generate Mipmaps Genera mipmap - -# Color Table (.act) dialog There is no color table to save. Non c'è alcuna tabella colori da salvare. @plural Saved {n} color to {file}|Saved {n} colors to {file} Salvato {n} colore in {file}|Salvati {n} colori in {file} - -# Graphics Adapter preference (#1885) GPU adapter Adattatore GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Importa stili… Export Selected Styles… Esporta stili selezionati… Export Styles… Esporta stili… {file} is not a style library (.asl) {file} non è una libreria di stili (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {n} stile importato da {file}|{n} stili importati da {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} stile esportato in {file}|{n} stili esportati in {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Conferma o annulla prima la finestra di dialogo aperta del passo dell’azione Pro Medium Gray Pro grigio medio Solarized Solarized @@ -4565,28 +4574,11 @@ shape Appearance Aspetto Pro Light Pro chiaro Resize Windows to Fit Ridimensiona finestre per adattare EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Direzione del paragrafo automatica Left-to-right paragraph direction Direzione del paragrafo da sinistra a destra Right-to-left paragraph direction Direzione del paragrafo da destra a sinistra Not rendered: this adjustment ({key}) is kept as imported. Non renderizzato: questa regolazione ({key}) viene conservata come importata. -# Print preview image (#8236) Print preview image Print preview image - Color Aware In base al colore - Decontaminate Colors Decontamina colori - Edge Detection Rilevamento bordi - Global Refinements Perfezionamenti globali - High Quality Preview Anteprima di alta qualità - Object Aware In base all'oggetto - Real-Time Refinement Perfezionamento in tempo reale - Refine Edge Brush Tool Strumento Pennello per migliorare il bordo - Refine Hair Migliora capelli - Refine Mode Metodo di perfezionamento - Remember Settings Ricorda impostazioni - View Mode Modalità di visualizzazione - Object Aware needs a segmentation model, which isn't available yet In base all'oggetto richiede un modello di segmentazione, non ancora disponibile - Refine Hair needs hair detection, which isn't available yet Migliora capelli richiede il rilevamento dei capelli, non ancora disponibile -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cubo tonalità Brightness Cube Cubo luminosità Color Wheel Ruota dei colori @@ -4602,9 +4594,8 @@ shape Appearance Aspetto Grayscale Ramp Barra scala di grigio Current Colors Colori correnti Make Ramp Web Safe Limita la barra ai colori web - Select and Mask was closed: its document is no longer the active one Seleziona e maschera è stato chiuso: il suo documento non è più quello attivo - Select and Mask was closed: another layer was selected Seleziona e maschera è stato chiuso: è stato selezionato un altro livello -# Art History Brush (#213). + The path was kept as the Work Path Il tracciato è stato conservato come tracciato di lavoro + The path was discarded Il tracciato è stato scartato Art History Brush Tool Strumento Pennello storia artistica Tight Short Corto stretto Tight Medium Medio stretto @@ -4618,3 +4609,19 @@ shape Appearance Aspetto Font size presets Predefiniti dimensione font Leading presets Predefiniti interlinea Tracking presets Predefiniti spaziatura + Color Aware In base al colore + Decontaminate Colors Decontamina colori + Edge Detection Rilevamento bordi + Global Refinements Perfezionamenti globali + High Quality Preview Anteprima di alta qualità + Object Aware In base all'oggetto + Real-Time Refinement Perfezionamento in tempo reale + Refine Edge Brush Tool Strumento Pennello per migliorare il bordo + Refine Hair Migliora capelli + Refine Mode Metodo di perfezionamento + Remember Settings Ricorda impostazioni + View Mode Modalità di visualizzazione + Object Aware needs a segmentation model, which isn't available yet In base all'oggetto richiede un modello di segmentazione, non ancora disponibile + Refine Hair needs hair detection, which isn't available yet Migliora capelli richiede il rilevamento dei capelli, non ancora disponibile + Select and Mask was closed: its document is no longer the active one Seleziona e maschera è stato chiuso: il suo documento non è più quello attivo + Select and Mask was closed: another layer was selected Seleziona e maschera è stato chiuso: è stato selezionato un altro livello diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 708f63a6d1..7937a483e7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -16,18 +16,140 @@ # letters; the trailing "…" of dialog commands is kept. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… マスクオプション… - Layer Mask Display Options… レイヤーマスクの表示オプション… # Channel Options and New Spot Channel (#3761) - Channel Color チャンネルカラー - Color Indicates: 着色表示: - Solidity: 濃度: - Ink Characteristics インキの特性 # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Dialogs and panels + +# Layers-panel trash confirmation + + +# Tool names, brush and style option tables + +# Templates with placeholders + +# Preferences (labels are generated from the setting names) + +# Added with the rebase onto the dock / brush picker work + +# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). +# Gradient Editor window, opened from the options bar's gradient swatch. +# Rendering mode and recovery +# Camera Raw: contextual controls and window title + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + +# Generated labels: filter/gallery parameter names, option choices and gallery names (camelCase keys shown as words) (added 2026-10, checked against the code) + +# Command, tool and menu names found in the code but not yet in this catalog (added 2026-10, checked against the code) + +# Remaining UI strings: hints, preferences, metadata fields, colour spaces, snapshots (added 2026-10, checked against the code) + +# Command id overrides + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Liquify tool names (shown via tl!(tool.label()) in the UI, so they are not found by the static scan) + +# Panel menu items and section labels passed to tl!() as variables (channels panel, paths panel, layer style) + +# Character panel tooltip (shown once the tooltip helpers in type_tool.rs pass their text through tl!) + +# Glyphs panel "Show" categories (text/src/glyphs.rs; the dropdown passes them through tl!) + +# Dialog field labels generated from parameter names (Warp Text, Trim, Calculations, Apply Image; not seen by the tl! scanner) + +# Canvas background menu, Blend If labels and Advanced Blending options + +# Native Windows printing qualification +# Restored rows (custom print paper #3820, brush presets, Vanishing Point help, brush panel menu) +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). +# Smart Filter row actions (#1265) + + Mask Options… マスクオプション… + Layer Mask Display Options… レイヤーマスクの表示オプション… + Channel Color チャンネルカラー + Color Indicates: 着色表示: + Solidity: 濃度: + Ink Characteristics インキの特性 Paper Width 用紙の幅 Paper Height 用紙の高さ Rows 行 @@ -45,7 +167,6 @@ 5 Columns, 3 Rows 5列、3行 8 Columns 8列 12 Columns 12列 - File ファイル Edit 編集 Image 画像 @@ -453,6 +574,7 @@ Intersect Shape Areas シェイプの重なりを抽出 Exclude Overlapping Shapes シェイプの重なりを除外 Merge Shape Components シェイプの構成要素を結合 + Path operations パスの操作 Align 整列 Top Edges 上端 Vertical Centers 垂直方向の中央 @@ -532,7 +654,6 @@ Color Range… 色域指定… Focus Area… 焦点領域… Select and Mask… 選択とマスク… -# Select and Mask dialog labels Smart Radius スマート半径 Shift Edge エッジをシフト Decontaminate 混入を除去 @@ -559,7 +680,6 @@ Blur ぼかし Blur Gallery ぼかしギャラリー Field Blur… フィールドぼかし… -# Field Blur pins (#3373) No pin selected ピンが選択されていません Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 画像をクリックしてピンを追加します。ピンをドラッグして移動し、リングをドラッグしてぼかしを変更します。Delete キーで選択したピンを削除します。 Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. 輪郭上のハンドルをドラッグしてサイズ変更と回転、四角形で角の丸み、内側の点でぼかしの開始位置を設定します。 @@ -824,8 +944,6 @@ Edits 編集 @plural {n} item|{n} items {n} 件 Auto 自動 - -# Dialogs and panels (print to the printer) (プリンターへ出力) + Add variable + 変数を追加 30 frames @ 30 fps 30 フレーム @ 30 fps @@ -839,6 +957,9 @@ Add Layer Mask レイヤーマスクを追加 Add Stop 分岐点を追加 Add a layer style レイヤースタイルを追加 + Move effect up 効果を上へ移動 + Move effect down 効果を下へ移動 + Delete effect 効果を削除 Add a mask (from the selection; {key} inverts) マスクを追加(選択範囲から。{key} で反転) Add an adjustment 色調補正を追加 Add disk ディスクを追加 @@ -1064,8 +1185,6 @@ Delete current channel 現在のチャンネルを削除 Delete current state 現在の状態を削除 Delete effect layer 効果レイヤーを削除 - -# Layers-panel trash confirmation Delete layer ‘{name}’? レイヤー「{name}」を削除しますか? Delete {count} layers? {names} {count} 個のレイヤーを削除しますか? {names} Delete layer? レイヤーを削除しますか? @@ -1074,7 +1193,6 @@ Missing delete command 削除コマンドがありません Invalid delete command 無効な削除コマンドです Layer deleted, but confirmation preference could not be saved: {error} レイヤーは削除されましたが、確認設定を保存できませんでした: {error} - Delete layer レイヤーを削除 Delete layer comp レイヤーカンプを削除 Delete note 注釈を削除 @@ -1107,7 +1225,6 @@ Dots ドット 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 で水平/垂直、制約を右クリックで変更・削除。 - Drag to move the active shape's path or the Work Path ドラッグして、アクティブなシェイプのパスまたは作業用パスを移動 Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath クリック: アンカーポイントを選択 · ドラッグ: ポイント、ハンドル、セグメントを移動 · {shift}+クリック: 追加 · {alt}+クリック: サブパス全体 Draw with the Pen tool (P) or make a work path from a selection. ペンツール(P)で描くか、選択範囲から作業用パスを作成します。 Drop an image or PSD anywhere to open it. 画像や PSD をここにドロップすると開きます。 @@ -1627,8 +1744,6 @@ No saved presets yet. 保存済みのプリセットはありません。 Error エラー Command コマンド - -# Tool names, brush and style option tables Adjustment layers have nothing to transform 色調補正レイヤーには変形するものがありません Altitude 高度 Android 1080p Android 1080p @@ -1861,8 +1976,6 @@ Yellows イエロー系 Zoom Tool ズームツール {name} Properties {name} のプロパティ - -# Templates with placeholders Revert “{name}” to the last saved version? Your changes will be lost. 「{name}」を最後に保存した状態に戻しますか? 変更は失われます。 Do you want to save the changes you made to “{name}” before quitting? 終了する前に、「{name}」への変更を保存しますか? Do you want to save the changes you made to “{name}” before closing? 閉じる前に、「{name}」への変更を保存しますか? @@ -1883,8 +1996,6 @@ @plural {n} Layer|{n} Layers {n} レイヤー @plural {n} layer|{n} layers {n} レイヤー @plural Group · {n} layer|Group · {n} layers グループ · {n} レイヤー - -# Preferences (labels are generated from the setting names) Additional plugins folder 追加のプラグインフォルダー Adobe Adobe Adobe rgb Adobe RGB @@ -2084,8 +2195,6 @@ Luminosity 輝度 @plural {n} sample|{n} samples サンプル {n} 個 {added}, {removed} subtracted {added}、除外 {removed} 個 - -# Added with the rebase onto the dock / brush picker work Adjustment Preview 色調補正のプレビュー Airbrush: keeps depositing paint while the pointer rests. エアブラシ: ポインターを止めている間も塗料を乗せ続けます。 Angle: 角度: @@ -2118,8 +2227,6 @@ Brush picker ブラシピッカー Erase 消去 Right click with painting tools 描画ツールで右クリック - -# Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). System Info… システム情報… System Info システム情報 More panels その他のパネル @@ -2188,7 +2295,6 @@ Align with layer レイヤーに揃える Reset Alignment 位置をリセット Centre the gradient (offset 0, 0) グラデーションを中央に配置(オフセット 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor グラデーションエディター Gradient picker グラデーションピッカー Save As Preset プリセットとして保存 @@ -2247,7 +2353,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: グリッド: -# Rendering mode and recovery Rendering Mode レンダリングモード Automatic (recommended) 自動(推奨) CPU / Compatibility CPU / 互換性 @@ -2274,7 +2379,6 @@ Tone Histogram 階調ヒストグラム Show Selected Region 選択範囲を表示 cameraRaw Light ライト -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Camera Raw フィルター ({layer}) Camera Raw ({name}) Camera Raw ({name}) cameraRaw Lights 明部 @@ -2289,14 +2393,10 @@ cameraRaw Color カラー Scale or rotate the moved area, then press {key} 移動した範囲を拡大・縮小または回転し、{key} を押します Now drag the selection onto another area 選択範囲を別の場所へドラッグします Edit Type 文字を編集 - - New Style… 新規スタイル… Style {name} saved スタイル {name} を保存しました - Create new style (from the selected type) 新規スタイルを作成(選択したテキストから) Create new style from the selected layer 選択したレイヤーから新規スタイルを作成 - Make Default 既定に設定 Reset to Default 既定値に戻す Vertical Type Tool 縦書き文字ツール @@ -2326,9 +2426,6 @@ cameraRaw Color カラー Magnetic Lasso Tool マグネット選択ツール Frequency 頻度 Use tablet pressure to change pen width タブレットの筆圧を使用してペンの幅を変更 - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About バージョン情報 Contributors コントリビューター Models モデル @@ -2360,8 +2457,6 @@ cameraRaw Color カラー % of all commits 全コミットに占める割合 (%) Lines +/− 行数 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR {prs} 件、コミット {commits} 件、行 +{added} / −{deleted} (Δ {delta})、バイナリ +{binAdded} / −{binDeleted}、{first} – {last} - -# Swatches panel Create new swatch 新規スウォッチを作成 New Swatch… 新規スウォッチ… New Swatch Group… 新規スウォッチグループ… @@ -2371,13 +2466,10 @@ cameraRaw Color カラー Export Swatches for Exchange… 交換用にスウォッチを書き出し… Reset Swatches スウォッチを初期化 Add to Swatches スウォッチに追加 -# Layer Style > Blending Options (Advanced Blending) Blend If: 条件付き合成: Channels: チャンネル: Knockout ノックアウト Apply At Canvas Bounds カンバスの境界に効果を適用 - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) カラーピッカー (文字色) Color Picker ({name}) カラーピッカー({name}) Color Picker (Fill Color) カラーピッカー (塗りつぶしカラー) @@ -2393,8 +2485,6 @@ cameraRaw Color カラー Show/Hide Panels パネルを表示/非表示 Could not open 開けませんでした {path}: the path is not valid Unicode; rename the file and open it again. {path}: パスが有効な Unicode ではありません。ファイル名を変更してから開き直してください。 - -# Fill dialog, layer style contours and Image Size Contents: 内容: Custom Pattern: カスタムパターン: Foreground Color 描画色 @@ -2420,7 +2510,6 @@ cameraRaw Color カラー Rolling Slope - Descending ローリングスロープ - 下降 Rounded Steps 丸い階段 Sawtooth 1 のこぎり波 1 - Red Eye Tool 赤目ツール Red Eye 赤目 Pupil Size 瞳のサイズ @@ -2428,7 +2517,6 @@ cameraRaw Color カラー Click a red pupil to neutralize it 赤い瞳をクリックして補正します open source オープンソース …and {n} more …ほか {n} 件 - Eyedroppers: スポイト: Set Black Point 黒点を設定 Set Neutral Gray Point 中間調のグレーポイントを設定 @@ -2437,8 +2525,6 @@ cameraRaw Color カラー Selection Preview: 選択範囲のプレビュー: Black Matte 黒の背景 White Matte 白の背景 - -# Layer colour labels. Seafoam シーフォーム Indigo インディゴ Fuchsia フクシア @@ -2459,8 +2545,6 @@ fontWeight Bold 太字 fontWeight ExtraBold 特太 fontWeight Black 極太 fontWeight Italic 斜体 - -# Pattern Stamp tool Pattern Stamp Tool パターンスタンプツール Pattern Stamp パターンスタンプ Impressionist 印象派 @@ -2468,13 +2552,9 @@ fontWeight Italic 斜体 Rotate View Tool 表示回転ツール Reset View 表示をリセット Drag around the centre to rotate the view · Shift constrains to 15° 中心の周りをドラッグして表示を回転 · Shift で 15° 単位 - -# Painting symmetry presets. Dual Axis 二軸 Diagonal 斜め Transform Symmetry 対称軸を変形 - -# Eyedropper Sample Size and Sample (#1649). Point Sample ポイントサンプル 3 by 3 Average 3 × 3 平均 5 by 5 Average 5 × 5 平均 @@ -2486,12 +2566,8 @@ fontWeight Italic 斜体 All Layers No Adjustments すべてのレイヤー (色調補正なし) Current & Below No Adjustments 現在のレイヤーとその下 (色調補正なし) 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 Web カラーではありません: クリックすると最も近い Web カラーになります - -# Generated labels: filter/gallery parameter names, option choices and gallery names (camelCase keys shown as words) (added 2026-10, checked against the code) Accented Edges 輪郭の強調 Adjust Interval For Loops ループ用に間隔を調整 Adjustment Properties 色調補正のプロパティ @@ -2855,8 +2931,6 @@ fontWeight Italic 斜体 Wind 風 Wrap 折り返し Zigzag ジグザグ - -# Command, tool and menu names found in the code but not yet in this catalog (added 2026-10, checked against the code) 32-bit Preview Options 32 ビットプレビューオプション Adaptive Wide Angle 広角補正 Add Noise ノイズを加える @@ -3230,8 +3304,6 @@ fontWeight Italic 斜体 Working 作業用 sRGB sRGB {zoom}% {zoom}% - -# Remaining UI strings: hints, preferences, metadata fields, colour spaces, snapshots (added 2026-10, checked against the code) 10 fps 10 fps 15 fps 15 fps 24 fps 24 fps @@ -3534,14 +3606,11 @@ fontWeight Italic 斜体 Working Spaces 作業用スペース {mode} Color · {bits} bit {mode} カラー · {bits} ビット ↑↓ navigate ↵ run esc close ↑↓ 移動 ↵ 実行 esc 閉じる - -# Command id overrides @id select.all すべてを選択 Color to Alpha… カラーを透明に… Transparency Threshold 透明のしきい値 Opacity Threshold 不透明度のしきい値 PhotoCraft — Screen Color Picker PhotoCraft — スクリーンカラーピッカー - Rasterize svg groups deeper than この深さを超える SVG グループをラスタライズ 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 でこのしきい値は無効になります。100 階層を超えて入れ子になった SVG グループは常にラスタライズされます。 Rule of Thirds 三分割法 @@ -3554,8 +3623,6 @@ fontWeight Italic 斜体 Cycle Orientation 方向を切り替え Set the overlay options for the Crop tool 切り抜きツールのオーバーレイオプションを設定 Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+クリックはデスクトップに取られました(Alt+ドラッグでウィンドウを移動する設定です)。デスクトップのウィンドウ移動キーを Super に変更するか、ウィンドウ › 修飾キーで Alt を固定してください。 - -# Shared Layer Style color picker Color Picker (Layer Style Color) カラーピッカー (レイヤースタイルの色) Auto Hide Notifications 通知を自動的に隠す Notification Duration (seconds) 通知の表示時間 (秒) @@ -3630,7 +3697,6 @@ fontWeight Italic 斜体 Appearance Settings… 外観設定… Add to favorites お気に入りに追加 Remove from favorites お気に入りから削除 -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make メーカー cameraData Model モデル cameraData Date Taken 撮影日時 @@ -3640,7 +3706,6 @@ cameraData ISO Speed ISO 感度 cameraData Focal Length 焦点距離 cameraData Focal Length (35 mm) 焦点距離 (35 mm 換算) cameraData Lens レンズ -# Shared panel docking Activate Panel パネルをアクティブにする Change Panel Group パネルグループを変更 Change Panel Layout パネルレイアウトを変更 @@ -3684,7 +3749,6 @@ cameraData Lens レンズ Snap to Origin 原点にスナップ Search settings… 設定を検索… No matching settings 一致する設定はありません -# Edit › Content-Aware Fill workspace Sampling Brush Tool サンプリングブラシツール Sampling Area Overlay サンプリング領域のオーバーレイ Show Sampling Area サンプリング領域を表示 @@ -3700,7 +3764,6 @@ cameraData Lens レンズ Mirror ミラー Output Settings 出力設定 Output To 出力先 - Animation Options アニメーションオプション Entire Document ドキュメント全体 Filter Options フィルターオプション @@ -3717,8 +3780,6 @@ cameraData Lens レンズ Add “copy” to Copied Layers and Groups コピーしたレイヤーとグループの名前に「コピー」を追加 Preview on canvas when reordering layers レイヤーの並べ替え時にカンバスでプレビュー Show layer mask badges レイヤーマスクのバッジを表示 - -# Smart Filter editors Blending Options ({filter}) 描画オプション ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) レイヤー効果とスマートフィルターを非表示 ({key}+クリック: すべてのレイヤー) Show the layer's effects and Smart Filters ({key}-click: all layers) レイヤー効果とスマートフィルターを表示 ({key}+クリック: すべてのレイヤー) @@ -3749,7 +3810,6 @@ curves Smooth スムーズ Alt-click a plane to set the clone source Alt キーを押しながら平面をクリックしてコピー元を設定 Too many clone strokes: apply Vanishing Point first コピースタンプのストロークが多すぎます:先に消点を適用してください Fix the red plane first: its corners must form a convex quad 先に赤い面を修正してください: 角が凸四角形になる必要があります -# Select and Mask view modes (#1754) Onion Skin オニオンスキン Marching Ants 点線の境界 On Black 黒地 @@ -3758,7 +3818,6 @@ curves Smooth スムーズ Show Edge エッジを表示 Show Original 元の状態を表示 F cycles the views; hold X to see the image F で表示を切り替え、X を押している間は画像を表示 -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) 境界線調整ブラシ (R) Expand Detection Area 検出領域を拡張 Restore Original Edge 元のエッジを復元 @@ -3766,19 +3825,13 @@ curves Smooth スムーズ Clear Brush Strokes ブラシストロークを消去 Show rulers 定規を表示 Presentation プレゼンテーション - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove クリックで配置 · Alt キーを押しながらクリック、またはカンバス外へドラッグで削除 No document open ドキュメントが開かれていません {n} of {max} sample points {max} 個中 {n} 個のサンプルポイント - -# History panel menu (#2966) New Snapshot… 新規スナップショット… History Options… ヒストリーオプション… -# History panel › History Options… (#2966) Allow Non-Linear History 非線形のヒストリーを許可 Make Layer Visibility Changes Undoable レイヤーの表示/非表示の変更を取り消し可能にする -# Print dialog (#2697) Emulsion Down 乳剤面を下 Functions 機能 Print Resolution: プリント解像度: @@ -3790,7 +3843,6 @@ curves Smooth スムーズ Apply mask to layer before removing? 削除する前にマスクをレイヤーに適用しますか? The layer or its mask changed. Drag the mask onto the Trash again. レイヤーまたはそのマスクが変更されました。もう一度マスクをゴミ箱にドラッグしてください。 Delete the vector mask? ベクトルマスクを削除しますか? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} スウォッチ {n} 個を {file} に書き出しました @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {group} からブラシ {n} 個を読み込みました @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {file} からスウォッチ {n} 個を読み込みました @@ -3805,7 +3857,6 @@ curves Smooth スムーズ @plural {n} step|{n} steps {n} ステップ @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (ほかにブラシプリセットの警告 {n} 件) @plural {what} with {n} warning|{what} with {n} warnings {what} (警告 {n} 件) -# View › Guides › New Guide… › Color Light Blue ライトブルー Light Red ライトレッド Medium Blue ミディアムブルー @@ -3823,8 +3874,6 @@ curves Smooth スムーズ Loaded contours from {file} {file} からカーブを読み込みました Saved contours to {file} カーブを {file} に保存しました Show home recent files ホーム画面に最近使ったファイルを表示 - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… アクションを読み込み… Save Actions… アクションを保存… New Action… 新規アクション… @@ -3836,10 +3885,8 @@ curves Smooth スムーズ @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 個のステップにはまだ PhotoCraft の対応機能がありません @plural Saved {n} action to {file}|Saved {n} actions to {file} {file} にアクション {n} 個を保存しました @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop に対応するもののない {n} 個のステップを省きました - File Naming ファイル名の付け方 Starting serial 開始番号 -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… ストップを挿入… Save Set… セットを保存… Message: メッセージ: @@ -3850,10 +3897,7 @@ curves Smooth スムーズ Step {step} is waiting for its dialog ステップ {step} はダイアログを待っています @plural {n} action|{n} actions アクション {n} 個 Background (Default) 背景(既定) -# Batch / Image Processor Include All Subfolders すべてのサブフォルダーを含める - -# Liquify tool names (shown via tl!(tool.label()) in the UI, so they are not found by the static scan) Forward Warp 前方ワープ Twirl Clockwise 時計回りに渦巻き Twirl Counterclockwise 反時計回りに渦巻き @@ -3862,8 +3906,6 @@ curves Smooth スムーズ Push Left ピクセル移動 Freeze Mask ブラシでマスクを描画 Thaw Mask ブラシでマスクを消去 - -# Panel menu items and section labels passed to tl!() as variables (channels panel, paths panel, layer style) Convert to Alpha Channel アルファチャンネルに変換 Delete Channel チャンネルを削除 Duplicate Channel チャンネルを複製 @@ -3876,11 +3918,7 @@ curves Smooth スムーズ Split Channels チャンネルを分割 Save Path パスを保存 General Blending 通常の描画 - -# Character panel tooltip (shown once the tooltip helpers in type_tool.rs pass their text through tl!) Kerning: Metrics, Optical or a value in 1/1000 em (Alt+←/→ at the caret) カーニング: メトリクス、オプティカル、または 1/1000 em 単位の値 (キャレット位置で Alt+←/→) - -# Glyphs panel "Show" categories (text/src/glyphs.rs; the dropdown passes them through tl!) Basic Latin 基本ラテン文字 Latin 1 ラテン 1 Latin Extended-A ラテン拡張 A @@ -3891,8 +3929,6 @@ curves Smooth スムーズ Currency 通貨記号 Math Symbols 数学記号 Arrows 矢印 - -# Dialog field labels generated from parameter names (Warp Text, Trim, Calculations, Apply Image; not seen by the tl! scanner) Bend 曲げ Horizontal Distortion 水平方向のゆがみ Vertical Distortion 垂直方向のゆがみ @@ -3905,12 +3941,10 @@ curves Smooth スムーズ Source2 Channel ソース 2 のチャンネル Source2 Invert ソース 2 を反転 R g b RGB - -# Canvas background menu, Blend If labels and Advanced Blending options Dark Gray ダークグレー Medium Gray ミディアムグレー Select Custom Color… カスタムカラーを選択… - This Layer: 現在のレイヤー: + Current Layer: 現在のレイヤー: Underlying Layer: 下のレイヤー: Blend Interior Effects as Group 内部効果をまとめて描画 Blend Clipped Layers as Group クリップされたレイヤーをまとめて描画 @@ -3918,14 +3952,11 @@ curves Smooth スムーズ Layer Mask Hides Effects レイヤーマスクで効果を隠す Vector Mask Hides Effects ベクトルマスクで効果を隠す Auto Add/Delete 自動追加・削除 - -# Native Windows printing qualification 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… 印刷設定でプリンター独自のカラーマネジメントを無効にしてください… Sent to {printer} {printer} に送信しました set in Print Settings… 印刷設定で指定… -# Restored rows (custom print paper #3820, brush presets, Vanishing Point help, brush panel menu) Drag to pan · Scroll to zoom · Double-click to fit ドラッグで移動 · スクロールでズーム · ダブルクリックで全体表示 Clear Brush Controls ブラシのコントロールを消去 Reset All Locked Settings ロックされた設定をすべて初期化 @@ -3969,7 +4000,6 @@ curves Smooth スムーズ Could not write {name}: {error} {name} を書き込めません: {error} Kept {name}: written by another application {name} はそのままにしました: 別のアプリケーションが書き込んだファイルです Shadow Tint シャドウの色かぶり補正 -# PhotoCraft release checks. Check for Updates… アップデートを確認… PhotoCraft Updates PhotoCraft のアップデート Checking for updates… アップデートを確認中… @@ -3982,33 +4012,27 @@ curves Smooth スムーズ Automatically Check for Updates アップデートを自動的に確認 Installed version: {version} インストール済みのバージョン: {version} PhotoCraft {version} is available. PhotoCraft {version} が利用可能です。 -# History panel › History Brush source (#2966) Paints from the History panel's source state ヒストリーパネルのソース状態からペイントします Sets the source for the history brush ヒストリーブラシのソースを設定します -# Bevel & Emboss shading controls. Highlight Mode ハイライトモード Highlight Color ハイライトカラー Highlight Opacity ハイライト不透明度 Shadow Mode シャドウモード Shadow Color シャドウカラー Shadow Opacity シャドウ不透明度 -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) 埋め込みプロファイルを使用 ({profile}) Convert to the working space ({profile}) 作業用スペースに変換 ({profile}) Remember this choice for future images 今後の画像でもこの選択を使用 Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. 確認を再び表示するには、編集 › カラー設定 の Ask On Mismatch をオンにします。 Button Mode ボタンモード Button Mode On ボタンモード オン -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface インターフェイスを暗くする Lighten Interface インターフェイスを明るくする -# Bevel & Emboss Technique. Technique テクニック Chisel Hard チゼルハード Chisel Soft チゼルソフト Open color-less EXR as ACEScg 色空間のないEXRをACEScgとして開く Do not append "copy" to filename when saving a copy コピーを保存するときにファイル名に「copy」を付けない -# View › Guides › right-click a guide Edit Selected Guides 選択したガイドを編集 Clear Selected Guides 選択したガイドを消去 Bicubic Automatic バイキュービック法 (自動) @@ -4033,8 +4057,6 @@ curves Smooth スムーズ set name セット名 {set} (modified) {set}(変更あり) Show file name in title タイトルにファイル名を表示 - -# Image › Mode › Bitmap (#5559) 50% Threshold 50% しきい値 Pattern Dither パターンディザ Diffusion Dither 拡散ディザ @@ -4052,10 +4074,8 @@ curves Smooth スムーズ Undo Changes 変更を取り消し {shortcut} is reserved by the system and can't be assigned. {shortcut} はシステムで予約されているため割り当てられません。 Low-Latency Drawing (vsync off, applies at next launch) 低遅延描画(垂直同期オフ、次回起動時に適用) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. 自由変形を適用中です。完了してからもう一度お試しください。 The transform couldn't be applied. 変形を適用できませんでした。 -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. レイヤーには {needed} の GPU メモリが必要ですが、予算で使えるのは {budget} です。 Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. 環境設定 › パフォーマンスの GPU メモリを、グラフィックカードが保持できる量(最大でメモリの 3/8)に設定してください。自動はメモリ使用量に従い、このコンピューターのメモリの4分の1とカードの 3/8 の範囲内で、メモリ量がわかるカードではドキュメント分を差し引きません。収まらない間、ステータスバーに「GPU メモリ不足」と表示されます。 GPU Memory Full GPU メモリ不足 @@ -4082,8 +4102,6 @@ curves Smooth スムーズ The fastest and the softest, with colour fringing on fine detail. 最も高速で最も柔らかく、細部に色にじみが出る。 “{name}” already exists. Replace it? 「{name}」は既に存在します。置き換えますか? The name in the save dialog was “{name}”. 保存ダイアログで指定した名前は「{name}」でした。 - Move Up 上へ移動 - Move Down 下へ移動 Previous Brush 前のブラシ Next Brush 次のブラシ First Brush 最初のブラシ @@ -4098,27 +4116,18 @@ curves Smooth スムーズ Use 使用 In Front 前面 Behind 背面 - -# DDS Options (#1327) DDS Options DDS オプション Compression 圧縮 Generate Mipmaps ミップマップを生成 - -# Color Table (.act) dialog There is no color table to save. 保存するカラーテーブルがありません。 @plural Saved {n} color to {file}|Saved {n} colors to {file} {file} に {n} 色を保存しました - -# Graphics Adapter preference (#1885) GPU adapter GPU アダプター - -# Styles panel: Import / Export Styles (.asl) Import Styles… スタイルを読み込み… Export Selected Styles… 選択したスタイルを書き出し… Export Styles… スタイルを書き出し… {file} is not a style library (.asl) {file} はスタイルライブラリ (.asl) ではありません @plural Imported {n} style from {file}|Imported {n} styles from {file} {file} からスタイル {n} 個を読み込みました @plural Exported {n} style to {file}|Exported {n} styles to {file} {file} にスタイル {n} 個を書き出しました -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first 先に開いているアクションのステップのダイアログを確定またはキャンセルしてください Pro Medium Gray プロ(中間グレー) Solarized Solarized @@ -4127,29 +4136,11 @@ curves Smooth スムーズ Pro Light プロ(ライト) Resize Windows to Fit ウィンドウサイズを合わせる EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction 段落の方向を自動判別 Left-to-right paragraph direction 左から右への段落方向 Right-to-left paragraph direction 右から左への段落方向 Not rendered: this adjustment ({key}) is kept as imported. レンダリングされません: この調整({key})はインポートされたまま保持されます。 -# Print preview image (#8236) Print preview image Print preview image - Clear Selection 選択範囲をクリア - Color Aware カラー認識 - Decontaminate Colors 不要なカラーの除去 - Edge Detection エッジの検出 - Global Refinements グローバル調整 - High Quality Preview 高品質プレビュー - Object Aware オブジェクト認識 - Real-Time Refinement リアルタイム調整 - Refine Edge Brush Tool 境界線調整ブラシツール - Refine Hair 髪の毛を調整 - Refine Mode 調整モード - Remember Settings 設定を保存 - View Mode 表示モード - Object Aware needs a segmentation model, which isn't available yet オブジェクト認識にはセグメンテーションモデルが必要ですが、まだ利用できません - Refine Hair needs hair detection, which isn't available yet 髪の毛を調整には髪の毛の検出が必要ですが、まだ利用できません -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 色相キューブ Brightness Cube 明るさキューブ Color Wheel カラーホイール @@ -4165,9 +4156,8 @@ curves Smooth スムーズ Grayscale Ramp グレースケールランプ Current Colors 現在のカラー Make Ramp Web Safe ランプを Web セーフにする - Select and Mask was closed: its document is no longer the active one 「選択とマスク」を閉じました: 対象のドキュメントがアクティブではなくなりました - Select and Mask was closed: another layer was selected 「選択とマスク」を閉じました: 別のレイヤーが選択されました -# Art History Brush (#213). + The path was kept as the Work Path パスは作業用パスとして保持されました + The path was discarded パスは破棄されました Art History Brush Tool アートヒストリーブラシツール Tight Short タイト・ショート Tight Medium タイト・ミディアム @@ -4181,3 +4171,21 @@ curves Smooth スムーズ Font size presets フォントサイズのプリセット Leading presets 行送りのプリセット Tracking presets トラッキングのプリセット + Clear Selection 選択範囲をクリア + Color Aware カラー認識 + Decontaminate Colors 不要なカラーの除去 + Edge Detection エッジの検出 + Global Refinements グローバル調整 + High Quality Preview 高品質プレビュー + Object Aware オブジェクト認識 + Real-Time Refinement リアルタイム調整 + Refine Edge Brush Tool 境界線調整ブラシツール + Refine Hair 髪の毛を調整 + Refine Mode 調整モード + Remember Settings 設定を保存 + View Mode 表示モード + Object Aware needs a segmentation model, which isn't available yet オブジェクト認識にはセグメンテーションモデルが必要ですが、まだ利用できません + Refine Hair needs hair detection, which isn't available yet 髪の毛を調整には髪の毛の検出が必要ですが、まだ利用できません + Select and Mask was closed: its document is no longer the active one 「選択とマスク」を閉じました: 対象のドキュメントがアクティブではなくなりました + Select and Mask was closed: another layer was selected 「選択とマスク」を閉じました: 別のレイヤーが選択されました + Drag to move the selected path ドラッグして選択したパスを移動 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 51804edaa1..b1ba69937f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8,10 +8,115 @@ # Product names and technology names retain their spelling. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… 마스크 옵션… - Layer Mask Display Options… 레이어 마스크 표시 옵션… # Channel Options and New Spot Channel (#3761) + +# Guide layout dialog + +# Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) +# Counted status and panel messages + + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Labels added on main before the Korean/live-switching split. + +# Warp grid presets merged on main in #388. + +# Type layer thumbnails (#598) + +# UI scale steps (#611) + + + + +# Additional generated filter labels and Photoshop-aligned UI terminology. + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# Export As metadata and profile options + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) +# Smart Filter row actions (#1265) + + Mask Options… 마스크 옵션… + Layer Mask Display Options… 레이어 마스크 표시 옵션… Channel Color 채널 색상 Color Indicates: 색상 표시 내용: Solidity: 견고도: @@ -19,10 +124,6 @@ Selected Areas 선택 영역 Spot Color 별색 Ink Characteristics 잉크 특성 - -# Guide layout dialog - -# Custom print paper (#3820) Paper Width 용지 너비 Paper Height 용지 높이 Columns 열 @@ -41,7 +142,6 @@ 5 Columns, 3 Rows 5열, 3행 8 Columns 8열 12 Columns 12열 - File 파일 Edit 편집 Image 이미지 @@ -439,6 +539,7 @@ Intersect Shape Areas 모양 영역 교차 Exclude Overlapping Shapes 겹치는 모양 제외 Merge Shape Components 모양 구성 요소 병합 + Path operations 패스 작업 Align 정렬 Top Edges 위쪽 가장자리 Vertical Centers 세로 중앙 @@ -518,7 +619,6 @@ Color Range… 색상 범위… Focus Area… 초점 영역… Select and Mask… 선택 및 마스크… -# Select and Mask dialog labels Smart Radius 고급 반경 Shift Edge 가장자리 이동 Decontaminate 오염 제거 @@ -545,7 +645,6 @@ Blur 흐림 효과 Blur Gallery 흐림 효과 갤러리 Field Blur… 필드 흐림 효과… -# Field Blur pins (#3373) No pin selected 선택한 핀 없음 Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 이미지를 클릭하여 핀을 추가합니다. 핀을 드래그하여 이동하고, 링을 드래그하여 흐림 정도를 바꿉니다. Delete 키로 선택한 핀을 삭제합니다. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. 윤곽선의 핸들을 드래그하여 크기를 바꾸고 회전하고, 사각형으로 모서리를 둥글게 하며, 안쪽 점으로 흐림이 시작되는 위치를 설정합니다. @@ -799,7 +898,6 @@ Statistics… 통계… Refine Strokes 다듬기 획 Edits 편집 -# Counted status and panel messages @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} 색상 견본 {n}개를 {file}(으)로 내보냈습니다 @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {file}에서 색상 견본 {n}개를 가져왔습니다 @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {group}에서 브러시 {n}개를 가져왔습니다 @@ -814,7 +912,6 @@ @plural {n} slice|{n} slices 분할 영역 {n}개 @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (브러시 사전 설정 경고 {n}개 더 있음) @plural {what} with {n} warning|{what} with {n} warnings {what}: 경고 {n}개 - @plural {n} item|{n} items 항목 {n}개 Auto 자동 (print to the printer) (프린터로 인쇄) @@ -830,6 +927,9 @@ Add Layer Mask 레이어 마스크 추가 Add Stop 색상 정지점 추가 Add a layer style 레이어 스타일 추가 + Move effect up 효과 위로 이동 + Move effect down 효과 아래로 이동 + Delete effect 효과 삭제 Add a mask (from the selection; {key} inverts) 마스크 추가 (선택 영역에서 만들기; {key} 키로 반전) Add an adjustment 조정 추가 Add disk 디스크 추가 @@ -1062,8 +1162,6 @@ Delete current channel 현재 채널 삭제 Delete current state 현재 상태 삭제 Delete effect layer 효과 레이어 삭제 - -# Layers-panel trash confirmation Delete layer ‘{name}’? 레이어 ‘{name}’을(를) 삭제하시겠습니까? Delete {count} layers? {names} 레이어 {count}개를 삭제하시겠습니까? {names} Delete layer? 레이어를 삭제하시겠습니까? @@ -1072,7 +1170,6 @@ Missing delete command 삭제 명령이 없습니다 Invalid delete command 잘못된 삭제 명령입니다 Layer deleted, but confirmation preference could not be saved: {error} 레이어가 삭제되었지만 확인 설정을 저장할 수 없습니다: {error} - Delete layer 레이어 삭제 Delete layer comp 레이어 구성 요소 삭제 Delete note 메모 삭제 @@ -1105,7 +1202,6 @@ Dots 점 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 키로 수평/수직 유지; 제약 조건을 오른쪽 클릭하여 변경 또는 삭제. - Drag to move the active shape's path or the Work Path 드래그하여 활성 모양의 패스 또는 작업 패스 이동 Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath 클릭: 기준점 선택 · 드래그: 기준점, 핸들 또는 세그먼트 이동 · {shift}-클릭: 추가 · {alt}-클릭: 하위 패스 전체 Draw with the Pen tool (P) or make a work path from a selection. 펜 도구(P)로 그리거나 선택 영역에서 작업 패스를 만드세요. Drop an image or PSD anywhere to open it. 이미지나 PSD를 아무 곳에나 놓아 여세요. @@ -2171,7 +2267,6 @@ Centre 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 window, opened from the options bar's gradient swatch. Gradient Editor 그레이디언트 편집기 Gradient picker 그레이디언트 선택기 Save As Preset 사전 설정으로 저장 @@ -2225,8 +2320,6 @@ Opening… 여는 중… Reading… 읽는 중… Working… 작업 중… - -# Labels added on main before the Korean/live-switching split. 8 bit 8비트 Integer 정수 16 bit 16비트 @@ -2286,22 +2379,16 @@ cameraRaw Color 색상 Transform On Drop 놓을 때 변형 Scale or rotate the moved area, then press {key} 이동한 영역의 크기를 조절하거나 회전한 다음 {key} 키를 누르세요 Now drag the selection onto another area 이제 선택 영역을 다른 영역으로 드래그하세요 - -# Warp grid presets merged on main in #388. 3 x 3 3 × 3 4 x 4 4 × 4 5 x 5 5 × 5 Grid: 격자: - -# Type layer thumbnails (#598) Edit Type 문자 편집 Eyedroppers: 스포이드: Set Black Point 검은점 설정 Set Neutral Gray Point 중성 회색점 설정 Set White Point 흰점 설정 Unavailable in this color mode 이 색상 모드에서는 사용할 수 없음 - -# UI scale steps (#611) 75% 75% 80% 80% 85% 85% @@ -2313,15 +2400,10 @@ cameraRaw Color 색상 250% 250% 300% 300% Full-resolution preview unavailable 전체 해상도 미리보기를 사용할 수 없습니다 - - New Style… 새 스타일… Style {name} saved {name} 스타일을 저장했습니다 - Make Default 기본값으로 만들기 Reset to Default 기본값으로 되돌리기 - -# Additional generated filter labels and Photoshop-aligned UI terminology. @id select.all 모두 선택 No patterns 패턴 없음 Enable {name} {name} 사용 @@ -2965,9 +3047,6 @@ cameraRaw Color 색상 Magnetic Lasso Tool 자석 올가미 도구 Frequency 빈도 Use tablet pressure to change pen width 태블릿 압력을 사용하여 펜 폭 변경 - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About 정보 Contributors 기여자 Models 모델 @@ -2998,8 +3077,6 @@ cameraRaw Color 색상 % of all commits 전체 커밋 대비 % Lines +/− 줄 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR {prs}개, 커밋 {commits}개, 줄 +{added} / −{deleted} (Δ {delta}), 바이너리 +{binAdded} / −{binDeleted}, {first} – {last} - -# Swatches panel Create new swatch 새 색상 견본 만들기 New Swatch… 새 색상 견본… New Swatch Group… 새 색상 견본 그룹… @@ -3009,13 +3086,12 @@ cameraRaw Color 색상 Export Swatches for Exchange… 교환용 색상 견본 내보내기… Reset Swatches 색상 견본 재설정 Add to Swatches 색상 견본에 추가 -# Layer Style > Blending Options (Advanced Blending) Blend If: 혼합 조건: + Current Layer: 현재 레이어: + Underlying Layer: 아래 레이어: Channels: 채널: Knockout 녹아웃 Apply At Canvas Bounds 캔버스 경계에 효과 적용 - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) 색상 선택기 (텍스트 색상) Color Picker ({name}) 색상 선택기 ({name}) Color Picker (Fill Color) 색상 선택기 (채우기 색상) @@ -3034,8 +3110,6 @@ cameraRaw Color 색상 {path}: the path is not valid Unicode; rename the file and open it again. {path}: 경로가 올바른 유니코드가 아닙니다. 파일 이름을 바꾼 뒤 다시 여세요. Good 좋음 Best 최적 - -# Fill dialog, layer style contours and Image Size Contents: 내용: Custom Pattern: 사용자 정의 패턴: Foreground Color 전경색 @@ -3060,7 +3134,6 @@ cameraRaw Color 색상 Rolling Slope - Descending 구르는 경사 - 내림차순 Rounded Steps 둥근 계단 Sawtooth 1 톱니 1 - Red Eye Tool 적목 현상 도구 Red Eye 적목 현상 Pupil Size 동공 크기 @@ -3071,8 +3144,6 @@ cameraRaw Color 색상 Selection Preview: 선택 영역 미리 보기: Black Matte 검정 배경 White Matte 흰색 배경 - -# Layer colour labels. Seafoam 바다 거품색 Indigo 남색 Fuchsia 자홍색 @@ -3091,8 +3162,6 @@ fontWeight Bold 굵게 fontWeight ExtraBold 더 굵게 fontWeight Black 아주 굵게 fontWeight Italic 기울임 - -# Pattern Stamp tool Pattern Stamp Tool 패턴 스탬프 도구 Pattern Stamp 패턴 스탬프 Impressionist 인상파 @@ -3100,13 +3169,9 @@ fontWeight Italic 기울임 Rotate View Tool 보기 회전 도구 Reset View 보기 재설정 Drag around the centre to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기 회전 · Shift로 15° 단위 제한 - -# Painting symmetry presets. Dual Axis 이중 축 Diagonal 대각선 Transform Symmetry 대칭 변형 - -# Eyedropper Sample Size and Sample (#1649). Point Sample 포인트 샘플 3 by 3 Average 3 × 3 평균 5 by 5 Average 5 × 5 평균 @@ -3118,15 +3183,12 @@ fontWeight Italic 기울임 All Layers No Adjustments 모든 레이어(조정 제외) Current & Below No Adjustments 현재 및 이하(조정 제외) 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 웹 색상이 아님: 클릭하면 가장 가까운 웹 색상으로 바뀝니다 Color to Alpha… 색상을 알파로… Transparency Threshold 투명도 한계값 Opacity Threshold 불투명도 한계값 PhotoCraft — Screen Color Picker PhotoCraft — 화면 색상 선택기 - Rasterize svg groups deeper than 이 깊이보다 깊은 SVG 그룹 래스터화 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0이면 이 한계값을 끕니다. 100단계보다 깊이 중첩된 SVG 그룹은 항상 래스터화됩니다. Rule of Thirds 삼등분 법칙 @@ -3139,8 +3201,6 @@ fontWeight Italic 기울임 Cycle Orientation 방향 순환 Set the overlay options for the Crop tool 자르기 도구의 오버레이 옵션 설정 Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 클릭이 데스크톱으로 전달되었습니다. 데스크톱이 Alt 드래그로 창을 이동합니다. 창 이동 키를 Super로 바꾸거나 창 › 보조 키에서 Alt를 고정하세요. - -# Shared Layer Style color picker Color Picker (Layer Style Color) 색상 피커 (레이어 스타일 색상) Auto Hide Notifications 알림 자동 숨기기 Notification Duration (seconds) 알림 지속 시간(초) @@ -3220,7 +3280,6 @@ fontWeight Italic 기울임 Appearance Settings… 화면 설정… Add to favorites 즐겨찾기에 추가 Remove from favorites 즐겨찾기에서 제거 -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data 카메라 데이터 cameraData Make 제조사 cameraData Model 모델 @@ -3231,7 +3290,6 @@ cameraData ISO Speed ISO 감도 cameraData Focal Length 초점 거리 cameraData Focal Length (35 mm) 초점 거리(35mm 환산) cameraData Lens 렌즈 -# Shared panel docking Activate Panel 패널 활성화 Change Panel Group 패널 그룹 변경 Change Panel Layout 패널 레이아웃 변경 @@ -3277,7 +3335,6 @@ cameraData Lens 렌즈 Snap to Origin 원점에 스냅 Search settings… 설정 검색… No matching settings 일치하는 설정 없음 -# Edit › Content-Aware Fill workspace Sampling Brush Tool 샘플링 브러시 도구 Sampling Area Overlay 샘플링 영역 오버레이 Show Sampling Area 샘플링 영역 표시 @@ -3293,7 +3350,6 @@ cameraData Lens 렌즈 Mirror 미러 Output Settings 출력 설정 Output To 출력 위치 - Animation Options 애니메이션 옵션 Entire Document 전체 문서 Filter Options 필터 옵션 @@ -3313,8 +3369,6 @@ cameraData Lens 렌즈 Add “copy” to Copied Layers and Groups 복사한 레이어 및 그룹에 “복사” 추가 Preview on canvas when reordering layers 레이어 순서 변경 시 캔버스에서 미리보기 Show layer mask badges 레이어 마스크 배지 표시 - -# Smart Filter editors Blending Options ({filter}) 혼합 옵션 ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) 레이어 효과 및 스마트 필터 숨기기 ({key}+클릭: 모든 레이어) Show the layer's effects and Smart Filters ({key}-click: all layers) 레이어 효과 및 스마트 필터 표시 ({key}+클릭: 모든 레이어) @@ -3351,7 +3405,6 @@ curves Smooth 매끄럽게 Fix the red plane first: its corners must form a convex quad 먼저 빨간색 평면을 수정하십시오: 모서리가 볼록 사각형을 이루어야 합니다 Alt-click a plane to set the clone source Alt 키를 누른 채 평면을 클릭하여 복제 소스를 설정하십시오 Too many clone strokes: apply Vanishing Point first 복제 획이 너무 많습니다. 먼저 소실점을 적용하십시오 -# Select and Mask view modes (#1754) Onion Skin 어니언 스킨 Marching Ants 점선 윤곽 On Black 검정 배경 @@ -3360,7 +3413,6 @@ curves Smooth 매끄럽게 Show Edge 가장자리 표시 Show Original 원본 표시 F cycles the views; hold X to see the image F로 보기 전환, X를 누르고 있으면 이미지 표시 -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) 가장자리 다듬기 브러시 (R) Expand Detection Area 감지 영역 확장 Restore Original Edge 원래 가장자리 복원 @@ -3368,22 +3420,16 @@ curves Smooth 매끄럽게 Clear Brush Strokes 브러시 획 지우기 Show rulers 눈금자 표시 Presentation 프레젠테이션 - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove 클릭하여 배치 · Alt-클릭 또는 캔버스 밖으로 드래그하여 제거 No document open 열린 문서 없음 {n} of {max} sample points {max}개 중 {n}개의 샘플 지점 - -# History panel menu (#2966) Step Forward 한 단계 앞으로 Step Backward 한 단계 뒤로 Clear History 작업 내역 지우기 New Snapshot… 새 스냅샷… History Options… 작업 내역 옵션… -# History panel › History Options… (#2966) Allow Non-Linear History 비선형 작업 내역 허용 Make Layer Visibility Changes Undoable 레이어 표시 여부 변경을 실행 취소할 수 있게 하기 -# Print dialog (#2697) Emulsion Down 감광면 아래로 Functions 기능 Print Resolution: 인쇄 해상도: @@ -3395,7 +3441,6 @@ curves Smooth 매끄럽게 Apply mask to layer before removing? 제거하기 전에 마스크를 레이어에 적용하시겠습니까? The layer or its mask changed. Drag the mask onto the Trash again. 레이어 또는 마스크가 변경되었습니다. 마스크를 휴지통으로 다시 드래그하세요. Delete the vector mask? 벡터 마스크를 삭제하시겠습니까? -# View › Guides › New Guide… › Color Light Blue 연한 파랑 Light Red 연한 빨강 Medium Blue 중간 파랑 @@ -3417,8 +3462,6 @@ curves Smooth 매끄럽게 Clear Brush Controls 브러시 제어 지우기 Reset All Locked Settings 모든 잠긴 설정 재설정 Copy Texture to Other Tools 다른 도구로 텍스처 복사 - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… 액션 불러오기… Save Actions… 액션 저장… New Action… 새 액션… @@ -3430,10 +3473,8 @@ curves Smooth 매끄럽게 @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n}개 단계에는 아직 PhotoCraft에 해당하는 기능이 없습니다 @plural Saved {n} action to {file}|Saved {n} actions to {file} {file}에 액션 {n}개를 저장했습니다 @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop에 해당하는 기능이 없는 {n}개 단계를 제외했습니다 - File Naming 파일 이름 지정 Starting serial 시작 일련번호 -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… 정지 삽입… Save Set… 세트 저장… Message: 메시지: @@ -3444,11 +3485,8 @@ curves Smooth 매끄럽게 Step {step} is waiting for its dialog {step}단계가 대화 상자를 기다리고 있습니다 @plural {n} action|{n} actions 액션 {n}개 Background (Default) 배경(기본값) -# Batch / Image Processor Include All Subfolders 모든 하위 폴더 포함 Auto Add/Delete 자동 추가/삭제 - -# 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… 인쇄 설정에서 프린터 자체의 색상 관리를 끄세요… @@ -3493,7 +3531,6 @@ curves Smooth 매끄럽게 Could not write {name}: {error} {name}을(를) 쓸 수 없음: {error} Kept {name}: written by another application {name}을(를) 유지함: 다른 응용 프로그램이 작성한 파일 Shadow Tint 그림자 색조 -# PhotoCraft release checks. Check for Updates… 업데이트 확인… PhotoCraft Updates PhotoCraft 업데이트 Checking for updates… 업데이트 확인 중… @@ -3506,38 +3543,29 @@ curves Smooth 매끄럽게 Automatically Check for Updates 자동으로 업데이트 확인 Installed version: {version} 설치된 버전: {version} PhotoCraft {version} is available. PhotoCraft {version}을 사용할 수 있습니다. -# History panel › History Brush source (#2966) Paints from the History panel's source state 작업 내역 패널의 소스 상태에서 칠합니다 Sets the source for the history brush 작업 내역 브러시의 소스를 설정합니다 -# Bevel & Emboss shading controls. Highlight Mode 하이라이트 모드 Highlight Color 하이라이트 색상 Highlight Opacity 하이라이트 불투명도 Shadow Mode 그림자 모드 Shadow Color 그림자 색상 Shadow Opacity 그림자 불투명도 -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) 포함된 프로파일 사용({profile}) Convert to the working space ({profile}) 작업 색상 공간으로 변환({profile}) Remember this choice for future images 이후 이미지에도 이 선택 기억 Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. 편집 › 색상 설정의 Ask On Mismatch로 이 확인을 다시 켤 수 있습니다. Button Mode 단추 모드 Button Mode On 단추 모드 켜짐 - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface 인터페이스 어둡게 Lighten Interface 인터페이스 밝게 -# Bevel & Emboss Technique. Technique 기법 Chisel Hard 단단하게 조각 Chisel Soft 부드럽게 조각 Open color-less EXR as ACEScg 색 공간 정보 없는 EXR을 ACEScg로 열기 Do not append "copy" to filename when saving a copy 사본 저장 시 파일 이름에 "copy"를 붙이지 않음 -# Export As metadata and profile options Color Profile 색상 프로필 EXIF EXIF - -# View › Guides › right-click a guide Edit Selected Guides 선택한 안내선 편집 Clear Selected Guides 선택한 안내선 지우기 Make Selection 선택 영역 만들기 @@ -3563,8 +3591,6 @@ curves Smooth 매끄럽게 set name 세트 이름 {set} (modified) {set}(수정됨) Show file name in title 제목에 파일 이름 표시 - -# Image › Mode › Bitmap (#5559) 50% Threshold 50% 한계값 Pattern Dither 패턴 디더 Diffusion Dither 확산 디더 @@ -3582,11 +3608,9 @@ curves Smooth 매끄럽게 Undo Changes 변경 사항 취소 {shortcut} is reserved by the system and can't be assigned. {shortcut}은(는) 시스템에서 예약되어 할당할 수 없습니다. Low-Latency Drawing (vsync off, applies at next launch) 저지연 그리기(수직 동기화 끔, 다음 실행 시 적용) -# Free Transform: a new layer while the box is open (#5859) Reference point location 기준점 위치 Free Transform is still being applied; try again when it has finished. 자유 변형을 아직 적용하는 중입니다. 완료된 후 다시 시도하세요. The transform couldn't be applied. 변형을 적용할 수 없습니다. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. 레이어에 GPU 메모리 {needed}가 필요하지만 예산은 {budget}만 남겨 둡니다. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. 환경 설정 › 성능에서 GPU 메모리를 그래픽 카드가 감당할 수 있는 양으로 설정하세요(최대 카드 메모리의 3/8). 자동은 메모리 사용량을 따르며, 이 컴퓨터 메모리의 4분의 1과 카드 메모리의 3/8 이내이고, 메모리를 알 수 있는 카드에서는 문서를 차감하지 않습니다. 맞지 않는 동안 상태 표시줄에 GPU 메모리 부족이 표시됩니다. GPU Memory Full GPU 메모리 부족 @@ -3613,8 +3637,6 @@ curves Smooth 매끄럽게 The fastest and the softest, with colour fringing on fine detail. 가장 빠르고 가장 부드러우며, 미세한 디테일에 색 번짐이 있음. “{name}” already exists. Replace it? “{name}”이(가) 이미 있습니다. 대치하시겠습니까? The name in the save dialog was “{name}”. 저장 대화상자에 입력한 이름: “{name}” - Move Up 위로 이동 - Move Down 아래로 이동 Previous Brush 이전 브러시 Next Brush 다음 브러시 First Brush 첫 번째 브러시 @@ -3630,27 +3652,18 @@ curves Smooth 매끄럽게 In Front 앞 Behind 뒤 Blend 혼합 - -# DDS Options (#1327) DDS Options DDS 옵션 Compression 압축 Generate Mipmaps 밉맵 생성 - -# Color Table (.act) dialog There is no color table to save. 저장할 색상표가 없습니다. @plural Saved {n} color to {file}|Saved {n} colors to {file} {file}에 색상 {n}개 저장 - -# Graphics Adapter preference (#1885) GPU adapter GPU 어댑터 - -# Styles panel: Import / Export Styles (.asl) Import Styles… 스타일 가져오기… Export Selected Styles… 선택한 스타일 내보내기… Export Styles… 스타일 내보내기… {file} is not a style library (.asl) {file}은(는) 스타일 라이브러리(.asl)가 아닙니다 @plural Imported {n} style from {file}|Imported {n} styles from {file} {file}에서 스타일 {n}개를 가져왔습니다 @plural Exported {n} style to {file}|Exported {n} styles to {file} 스타일 {n}개를 {file}(으)로 내보냈습니다 -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first 먼저 열려 있는 액션 단계 대화 상자를 확인하거나 취소하세요 Pro Medium Gray 프로 중간 회색 Solarized Solarized @@ -3659,29 +3672,11 @@ curves Smooth 매끄럽게 Pro Light 프로 밝게 Resize Windows to Fit 창 크기 맞추기 EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction 자동 단락 방향 Left-to-right paragraph direction 왼쪽에서 오른쪽 단락 방향 Right-to-left paragraph direction 오른쪽에서 왼쪽 단락 방향 Not rendered: this adjustment ({key}) is kept as imported. 렌더링되지 않음: 이 조정({key})은 가져온 상태 그대로 유지됩니다. -# Print preview image (#8236) Print preview image Print preview image - Clear Selection 선택 영역 지우기 - Color Aware 색상 인식 - Decontaminate Colors 색상 정화 - Edge Detection 가장자리 감지 - Global Refinements 전역 다듬기 - High Quality Preview 고품질 미리 보기 - Object Aware 개체 인식 - Real-Time Refinement 실시간 다듬기 - Refine Edge Brush Tool 가장자리 다듬기 브러시 도구 - Refine Hair 머리카락 다듬기 - Refine Mode 다듬기 모드 - Remember Settings 설정 기억 - View Mode 보기 모드 - Object Aware needs a segmentation model, which isn't available yet 개체 인식에는 분할 모델이 필요하지만 아직 사용할 수 없습니다 - Refine Hair needs hair detection, which isn't available yet 머리카락 다듬기에는 머리카락 감지가 필요하지만 아직 사용할 수 없습니다 -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 색조 큐브 Brightness Cube 밝기 큐브 Color Wheel 색상환 @@ -3698,9 +3693,8 @@ curves Smooth 매끄럽게 Grayscale Ramp 회색 음영 램프 Current Colors 현재 색상 Make Ramp Web Safe 램프를 웹 안전 색상으로 만들기 - Select and Mask was closed: its document is no longer the active one 선택 및 마스크가 닫혔습니다: 해당 문서가 더 이상 활성 문서가 아닙니다 - Select and Mask was closed: another layer was selected 선택 및 마스크가 닫혔습니다: 다른 레이어가 선택되었습니다 -# Art History Brush (#213). + The path was kept as the Work Path 패스가 작업 패스로 유지되었습니다 + The path was discarded 패스가 삭제되었습니다 Art History Brush 아트 히스토리 브러시 Art History Brush Tool 아트 히스토리 브러시 도구 Tight Short 타이트 숏 @@ -3712,8 +3706,6 @@ curves Smooth 매끄럽게 Tight Curl 타이트 컬 Loose Curl 루즈 컬 Stylized dabs from a history state 작업 내역 상태에서 양식화된 찍기 - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio 종횡비 Category 카테고리 Target 대상 @@ -3721,3 +3713,22 @@ curves Smooth 매끄럽게 Font size presets 글꼴 크기 사전 설정 Leading presets 행간 사전 설정 Tracking presets 자간 사전 설정 + Clear Selection 선택 영역 지우기 + Color Aware 색상 인식 + Decontaminate Colors 색상 정화 + Edge Detection 가장자리 감지 + Global Refinements 전역 다듬기 + High Quality Preview 고품질 미리 보기 + Object Aware 개체 인식 + Real-Time Refinement 실시간 다듬기 + Refine Edge Brush Tool 가장자리 다듬기 브러시 도구 + Refine Hair 머리카락 다듬기 + Refine Mode 다듬기 모드 + Remember Settings 설정 기억 + View Mode 보기 모드 + Object Aware needs a segmentation model, which isn't available yet 개체 인식에는 분할 모델이 필요하지만 아직 사용할 수 없습니다 + Refine Hair needs hair detection, which isn't available yet 머리카락 다듬기에는 머리카락 감지가 필요하지만 아직 사용할 수 없습니다 + Select and Mask was closed: its document is no longer the active one 선택 및 마스크가 닫혔습니다: 해당 문서가 더 이상 활성 문서가 아닙니다 + Select and Mask was closed: another layer was selected 선택 및 마스크가 닫혔습니다: 다른 레이어가 선택되었습니다 + Select Layer Under Cursor 커서 아래 레이어 선택 + Drag to move the selected path 드래그하여 선택한 패스 이동 diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv index c3ef402e61..924f672fc7 100644 --- a/crates/ui-egui/src/i18n/nb.tsv +++ b/crates/ui-egui/src/i18n/nb.tsv @@ -4772,3 +4772,10 @@ cameraRaw Show Vectorscope Vis vektorskop cameraRaw Tone Histogram Tonehistogram cameraRaw Vignetting Vignettering cameraRaw White Balance: As Shot Hvitbalanse: som fotografert + Current Layer: Gjeldende lag: + Delete effect Slett effekt + Move effect down Flytt effekten ned + Move effect up Flytt effekten opp + Path operations Baneoperasjoner + The path was discarded Banen ble forkastet + The path was kept as the Work Path Banen ble beholdt som arbeidsbane diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5a2164c97e..de9d3dfb39 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9,18 +9,81 @@ # informally ("je") and uses sentence case. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Maskeropties… - Layer Mask Display Options… Weergaveopties voor laagmasker… # Channel Options and New Spot Channel (#3761) - Channel Color Kanaalkleur - Color Indicates: Kleur geeft aan: - Solidity: Soliditeit: - Ink Characteristics Inktkenmerken # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Painting symmetry presets. + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + Mask Options… Maskeropties… + Layer Mask Display Options… Weergaveopties voor laagmasker… + Channel Color Kanaalkleur + Color Indicates: Kleur geeft aan: + Solidity: Soliditeit: + Ink Characteristics Inktkenmerken Paper Width Papierbreedte Paper Height Papierhoogte Rows Rijen @@ -38,7 +101,6 @@ 5 Columns, 3 Rows 5 kolommen, 3 rijen 8 Columns 8 kolommen 12 Columns 12 kolommen - File Bestand Edit Bewerken Image Afbeelding @@ -444,6 +506,7 @@ Intersect Shape Areas Overlappende vormgebieden Exclude Overlapping Shapes Overlappende vormen uitsluiten Merge Shape Components Vormcomponenten samenvoegen + Path operations Padbewerkingen Align Uitlijnen Top Edges Bovenranden Vertical Centers Verticale middens @@ -523,7 +586,6 @@ Color Range… Kleurbereik… Focus Area… Scherptegebied… Select and Mask… Selecteren en maskeren… -# Select and Mask dialog labels Smart Radius Slimme straal Shift Edge Rand verschuiven Decontaminate Verontreiniging verwijderen @@ -549,7 +611,6 @@ Blur Vervagen Blur Gallery Vervagingsgalerie Field Blur… Veldvervaging… -# Field Blur pins (#3373) No pin selected Geen speld geselecteerd Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Klik in de afbeelding om een speld toe te voegen; sleep een speld om hem te verplaatsen, of zijn ring om de vervaging te wijzigen. Delete verwijdert de geselecteerde speld. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Sleep de grepen op de omtrek om hem te schalen en te draaien, het vierkantje om de hoeken af te ronden en de punten binnenin om in te stellen waar de vervaging begint. @@ -819,6 +880,9 @@ Add Layer Mask Laagmasker toevoegen Add Stop Kleurstop toevoegen Add a layer style Een laagstijl toevoegen + Move effect up Effect omhoog verplaatsen + Move effect down Effect omlaag verplaatsen + Delete effect Effect verwijderen Add a mask (from the selection; {key} inverts) Een masker toevoegen (vanuit de selectie; {key} keert om) Add an adjustment Een aanpassing toevoegen Add disk Schijf toevoegen @@ -1045,8 +1109,6 @@ Delete current channel Huidig kanaal verwijderen Delete current state Huidige staat verwijderen Delete effect layer Effectlaag verwijderen - -# Layers-panel trash confirmation Delete layer ‘{name}’? Laag ‘{name}’ verwijderen? Delete {count} layers? {names} {count} lagen verwijderen? {names} Delete layer? Laag verwijderen? @@ -1055,7 +1117,6 @@ Missing delete command Verwijderopdracht ontbreekt Invalid delete command Ongeldige verwijderopdracht Layer deleted, but confirmation preference could not be saved: {error} De laag is verwijderd, maar de bevestigingsvoorkeur kon niet worden opgeslagen: {error} - Delete layer Laag verwijderen Delete layer comp Laagcompositie verwijderen Delete note Notitie verwijderen @@ -2153,7 +2214,6 @@ Align with layer Uitlijnen met laag Reset Alignment Uitlijning herstellen Centre the gradient (offset 0, 0) Het verloop centreren (verschuiving 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Verloopeditor Gradient picker Verloopkiezer Gradient stops Verloopstops @@ -2408,6 +2468,8 @@ Reset Swatches Stalen herstellen Add to Swatches Aan stalen toevoegen Blend If: Overvloeien als: + Current Layer: Huidige laag: + Underlying Layer: Onderliggende laag: Channels: Kanalen: Knockout Uitsparing Apply At Canvas Bounds Toepassen op canvasgrenzen @@ -3692,12 +3754,9 @@ cameraRaw Whites Witten Point Sample Puntmonster Sample Size: Monstergrootte: Show Sampling Ring Monsterring tonen - -# Painting symmetry presets. Dual Axis Dubbele as Diagonal Diagonaal Transform Symmetry Symmetrie transformeren - Rasterize svg groups deeper than SVG-groepen rasteriseren dieper dan deze grens 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 schakelt deze drempel uit; SVG-groepen die dieper dan 100 niveaus zijn genest, worden altijd gerasterd. Rule of Thirds Regel van derden @@ -3710,8 +3769,6 @@ cameraRaw Whites Witten Cycle Orientation Oriëntatie wisselen Set the overlay options for the Crop tool Overlay-opties voor het gereedschap Uitsnijden instellen Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. De Alt-klik ging naar het bureaublad, dat vensters verplaatst met Alt-slepen. Stel daar de toets voor het verplaatsen van vensters in op Super, of vergrendel Alt via Venster › Wijzigingstoetsen. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Kleurkiezer (kleur van laagstijl) Auto Hide Notifications Meldingen automatisch verbergen Notification Duration (seconds) Duur van melding (seconden) @@ -3779,7 +3836,6 @@ cameraRaw Whites Witten Appearance Settings… Weergave-instellingen… Add to favorites Toevoegen aan favorieten Remove from favorites Verwijderen uit favorieten -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Merk cameraData Model Model cameraData Date Taken Opnamedatum @@ -3789,7 +3845,6 @@ cameraData ISO Speed ISO-waarde cameraData Focal Length Brandpuntsafstand cameraData Focal Length (35 mm) Brandpuntsafstand (35 mm) cameraData Lens Lens -# Shared panel docking Activate Panel Paneel activeren Change Panel Group Paneelgroep wijzigen Change Panel Layout Paneelindeling wijzigen @@ -3827,7 +3882,6 @@ cameraData Lens Lens Search settings… Instellingen zoeken… No matching settings Geen overeenkomende instellingen PhotoCraft — Screen Color Picker PhotoCraft — Schermkleurkiezer -# Edit › Content-Aware Fill workspace Sampling Brush Tool Gereedschap Monsterpenseel Sampling Area Overlay Overlay van monstergebied Show Sampling Area Monstergebied tonen @@ -3843,7 +3897,6 @@ cameraData Lens Lens Mirror Spiegelen Output Settings Uitvoerinstellingen Output To Uitvoer naar - Animation Options Animatieopties Entire Document Hele document Filter Options Filteropties @@ -3860,8 +3913,6 @@ cameraData Lens Lens Add “copy” to Copied Layers and Groups „kopie” toevoegen aan gekopieerde lagen en groepen Preview on canvas when reordering layers Voorvertoning op canvas bij herschikken van lagen Show layer mask badges Badges voor laagmaskers tonen - -# Smart Filter editors Blending Options ({filter}) Overvloeiopties ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Laageffecten en slimme filters verbergen ({key}-klik: alle lagen) Show the layer's effects and Smart Filters ({key}-click: all layers) Laageffecten en slimme filters tonen ({key}-klik: alle lagen) @@ -3892,7 +3943,6 @@ curves Smooth Vloeiend maken Fix the red plane first: its corners must form a convex quad Herstel eerst het rode vlak: de hoeken moeten een convexe vierhoek vormen Alt-click a plane to set the clone source Alt-klik op een vlak om de kloonbron in te stellen Too many clone strokes: apply Vanishing Point first Te veel kloonstreken: pas eerst Verdwijnpunt toe -# Select and Mask view modes (#1754) Onion Skin Uienschil Marching Ants Mierenmars On Black Op zwart @@ -3901,7 +3951,6 @@ curves Smooth Vloeiend maken Show Edge Rand tonen Show Original Origineel tonen F cycles the views; hold X to see the image F wisselt de weergaven; houd X ingedrukt om de afbeelding te zien -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Penseel Rand verfijnen (R) Expand Detection Area Detectiegebied uitbreiden Restore Original Edge Oorspronkelijke rand herstellen @@ -3915,18 +3964,12 @@ curves Smooth Vloeiend maken Scale: Schaal: Snap to Origin Uitlijnen op oorsprong Presentation Presentatie - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Klik om te plaatsen · Alt-klik of sleep buiten het canvas om te verwijderen {n} of {max} sample points {n} van {max} steekproefpunten - -# History panel menu (#2966) New Snapshot… Nieuwe momentopname… History Options… Geschiedenisopties… -# History panel › History Options… (#2966) Allow Non-Linear History Niet-lineaire geschiedenis toestaan Make Layer Visibility Changes Undoable Wijzigingen in laagzichtbaarheid ongedaan kunnen maken -# Print dialog (#2697) Emulsion Down Emulsie omlaag Functions Functies Print Resolution: Afdrukresolutie: @@ -3938,7 +3981,6 @@ curves Smooth Vloeiend maken Apply mask to layer before removing? Masker toepassen op laag voordat het wordt verwijderd? The layer or its mask changed. Drag the mask onto the Trash again. De laag of het masker is gewijzigd. Sleep het masker opnieuw naar de prullenbak. Delete the vector mask? Het vectormasker verwijderen? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} {n} staal geëxporteerd naar {file}|{n} stalen geëxporteerd naar {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {n} penseel geïmporteerd uit {group}|{n} penselen geïmporteerd uit {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {n} staal geïmporteerd uit {file}|{n} stalen geïmporteerd uit {file} @@ -3953,7 +3995,6 @@ curves Smooth Vloeiend maken @plural {n} step|{n} steps {n} stap|{n} stappen @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} andere waarschuwing over penseelvoorinstellingen)|{warning} (+{n} andere waarschuwingen over penseelvoorinstellingen) @plural {what} with {n} warning|{what} with {n} warnings {what} met {n} waarschuwing|{what} met {n} waarschuwingen -# View › Guides › New Guide… › Color Light Blue Lichtblauw Light Red Lichtrood Medium Blue Middelblauw @@ -3974,8 +4015,6 @@ curves Smooth Vloeiend maken Clear Brush Controls Penseelbesturing wissen Reset All Locked Settings Alle vergrendelde instellingen opnieuw instellen Copy Texture to Other Tools Structuur kopiëren naar andere gereedschappen - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Handelingen laden… Save Actions… Handelingen opslaan… New Action… Nieuwe handeling… @@ -3987,10 +4026,8 @@ curves Smooth Vloeiend maken @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} stap heeft nog geen equivalent in PhotoCraft|{n} stappen hebben nog geen equivalent in PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} handeling opgeslagen in {file}|{n} handelingen opgeslagen in {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} stap zonder Photoshop-equivalent weggelaten|{n} stappen zonder Photoshop-equivalent weggelaten - File Naming Bestandsnamen Starting serial Beginnummer -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Stop invoegen… Save Set… Set opslaan… Message: Bericht: @@ -4001,11 +4038,8 @@ curves Smooth Vloeiend maken Step {step} is waiting for its dialog Stap {step} wacht op zijn dialoogvenster @plural {n} action|{n} actions {n} handeling|{n} handelingen Background (Default) Achtergrond (standaard) -# Batch / Image Processor Include All Subfolders Alle submappen opnemen Auto Add/Delete Automatisch toevoegen/verwijderen - -# Native Windows printing qualification 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… @@ -4050,7 +4084,6 @@ curves Smooth Vloeiend maken Could not write {name}: {error} Kan {name} niet schrijven: {error} Kept {name}: written by another application {name} behouden: geschreven door een andere toepassing Shadow Tint Schaduwtint -# PhotoCraft release checks. Check for Updates… Controleren op updates… PhotoCraft Updates PhotoCraft-updates Checking for updates… Controleren op updates… @@ -4063,35 +4096,27 @@ curves Smooth Vloeiend maken Automatically Check for Updates Automatisch op updates controleren Installed version: {version} Geïnstalleerde versie: {version} PhotoCraft {version} is available. PhotoCraft {version} is beschikbaar. -# History panel › History Brush source (#2966) Paints from the History panel's source state Schildert vanuit de bronstatus van het deelvenster Geschiedenis Sets the source for the history brush Stelt de bron voor het historiepenseel in -# Bevel & Emboss shading controls. Highlight Mode Hooglichtmodus Highlight Color Hooglichtkleur Highlight Opacity Hooglichtdekking Shadow Mode Schaduwmodus Shadow Color Schaduwkleur Shadow Opacity Schaduwdekking -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Het ingesloten profiel gebruiken ({profile}) Convert to the working space ({profile}) Omzetten naar de werkruimte ({profile}) Remember this choice for future images Deze keuze onthouden voor volgende afbeeldingen Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Zet de vraag weer aan met Ask On Mismatch in Bewerken › Kleurinstellingen. Button Mode Knopmodus Button Mode On Knopmodus aan - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Interface donkerder maken Lighten Interface Interface lichter maken -# Bevel & Emboss Technique. Technique Techniek Chisel Hard Beitel hard Chisel Soft Beitel zacht Open color-less EXR as ACEScg EXR zonder kleurruimte als ACEScg openen Do not append "copy" to filename when saving a copy Geen "copy" aan de bestandsnaam toevoegen bij het opslaan van een kopie - -# View › Guides › right-click a guide Edit Selected Guides Geselecteerde hulplijnen bewerken Clear Selected Guides Geselecteerde hulplijnen wissen Bicubic Automatic Bicubisch automatisch @@ -4116,8 +4141,6 @@ curves Smooth Vloeiend maken set name naam van de set {set} (modified) {set} (gewijzigd) Show file name in title Bestandsnaam in titel weergeven - -# Image › Mode › Bitmap (#5559) 50% Threshold 50% drempel Pattern Dither Patroondithering Diffusion Dither Diffusiedithering @@ -4135,10 +4158,8 @@ curves Smooth Vloeiend maken Undo Changes Wijzigingen ongedaan maken {shortcut} is reserved by the system and can't be assigned. {shortcut} is door het systeem gereserveerd en kan niet worden toegewezen. Low-Latency Drawing (vsync off, applies at next launch) Tekenen met lage latentie (zonder vsync, na de volgende start) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Vrije transformatie wordt nog toegepast; probeer het opnieuw als die klaar is. The transform couldn't be applied. De transformatie kon niet worden toegepast. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. De lagen hebben {needed} GPU-geheugen nodig; het budget laat ze {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Stel GPU-geheugen in bij Voorkeuren › Prestaties op wat uw videokaart aankan, hooguit 3/8 van haar geheugen. Automatisch volgt Geheugengebruik, binnen een kwart van het geheugen van deze computer en 3/8 van dat van de kaart, en rekent het document niet af van een kaart waarvan het geheugen bekend is. Zolang ze niet passen, toont de statusbalk GPU-geheugen vol. GPU Memory Full GPU-geheugen vol @@ -4164,8 +4185,6 @@ curves Smooth Vloeiend maken The fastest and the softest, with colour 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}”. - Move Up Omhoog - Move Down Omlaag Previous Brush Vorig penseel Next Brush Volgend penseel First Brush Eerste penseel @@ -4180,26 +4199,17 @@ curves Smooth Vloeiend maken Use Gebruiken In Front Voor Behind Achter - -# DDS Options (#1327) DDS Options DDS-opties Generate Mipmaps Mipmaps genereren - -# Color Table (.act) dialog There is no color table to save. Er is geen kleurtabel om op te slaan. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} kleur opgeslagen in {file}|{n} kleuren opgeslagen in {file} - -# Graphics Adapter preference (#1885) GPU adapter GPU-adapter - -# Styles panel: Import / Export Styles (.asl) Import Styles… Stijlen importeren… Export Selected Styles… Geselecteerde stijlen exporteren… Export Styles… Stijlen exporteren… {file} is not a style library (.asl) {file} is geen stijlbibliotheek (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {n} stijl geïmporteerd uit {file}|{n} stijlen geïmporteerd uit {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} stijl geëxporteerd naar {file}|{n} stijlen geëxporteerd naar {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Bevestig of annuleer eerst het geopende dialoogvenster van de handelingsstap Pro Medium Gray Pro middelgrijs Solarized Solarized @@ -4208,28 +4218,11 @@ curves Smooth Vloeiend maken Pro Light Pro licht Resize Windows to Fit Venstergrootte aanpassen EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Automatische alinearichting Left-to-right paragraph direction Alinearichting van links naar rechts Right-to-left paragraph direction Alinearichting van rechts naar links Not rendered: this adjustment ({key}) is kept as imported. Niet weergegeven: deze aanpassing ({key}) blijft behouden zoals geïmporteerd. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Kleurbewust - Decontaminate Colors Kleuren zuiveren - Edge Detection Randdetectie - Global Refinements Globale verfijningen - High Quality Preview Voorvertoning in hoge kwaliteit - Object Aware Objectbewust - Real-Time Refinement Verfijning in realtime - Refine Edge Brush Tool Gereedschap Penseel Rand verfijnen - Refine Hair Haar verfijnen - Refine Mode Verfijningsmodus - Remember Settings Instellingen onthouden - View Mode Weergavemodus - Object Aware needs a segmentation model, which isn't available yet Objectbewust vereist een segmentatiemodel dat nog niet beschikbaar is - Refine Hair needs hair detection, which isn't available yet Haar verfijnen vereist haardetectie die nog niet beschikbaar is -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Kleurtoonkubus Brightness Cube Helderheidskubus Color Wheel Kleurenwiel @@ -4245,9 +4238,8 @@ curves Smooth Vloeiend maken Grayscale Ramp Grijswaardenbalk Current Colors Huidige kleuren Make Ramp Web Safe Balk beperken tot webkleuren - Select and Mask was closed: its document is no longer the active one Selecteren en maskeren is gesloten: het document is niet meer het actieve document - Select and Mask was closed: another layer was selected Selecteren en maskeren is gesloten: er is een andere laag geselecteerd -# Art History Brush (#213). + The path was kept as the Work Path Het pad is behouden als werkpad + The path was discarded Het pad is weggegooid Art History Brush Tool Artistiek historiepenseel Tight Short Strak kort Tight Medium Strak middel @@ -4261,3 +4253,20 @@ curves Smooth Vloeiend maken Font size presets Voorinstellingen lettergrootte Leading presets Voorinstellingen interlinie Tracking presets Voorinstellingen spatiëring + Color Aware Kleurbewust + Decontaminate Colors Kleuren zuiveren + Edge Detection Randdetectie + Global Refinements Globale verfijningen + High Quality Preview Voorvertoning in hoge kwaliteit + Object Aware Objectbewust + Real-Time Refinement Verfijning in realtime + Refine Edge Brush Tool Gereedschap Penseel Rand verfijnen + Refine Hair Haar verfijnen + Refine Mode Verfijningsmodus + Remember Settings Instellingen onthouden + View Mode Weergavemodus + Object Aware needs a segmentation model, which isn't available yet Objectbewust vereist een segmentatiemodel dat nog niet beschikbaar is + Refine Hair needs hair detection, which isn't available yet Haar verfijnen vereist haardetectie die nog niet beschikbaar is + Select and Mask was closed: its document is no longer the active one Selecteren en maskeren is gesloten: het document is niet meer het actieve document + Select and Mask was closed: another layer was selected Selecteren en maskeren is gesloten: er is een andere laag geselecteerd + Select Layer Under Cursor Laag onder cursor selecteren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 679d90ed34..ea729314f8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -19,18 +19,117 @@ # Zapisz jako…), sentence case as in the English source. Quotes: „…”. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Opcje maski… - Layer Mask Display Options… Opcje wyświetlania maski warstwy… # Channel Options and New Spot Channel (#3761) - Channel Color Kolor kanału - Color Indicates: Kolor oznacza: - Solidity: Gęstość: - Ink Characteristics Właściwości farby # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) +# Counted status and panel messages (plural forms: 1 | 2–4 except 12–14 | the rest) + + +# Dialogs and panels + +# Layers-panel trash confirmation + + +# Tool names, brush and style option tables + +# Templates with placeholders + +# Preferences (labels are generated from the setting names) + +# Added with the dock / brush picker work + +# Strings added to the UI later +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Tool, filter, warp-style, path, layer-comp and metadata names + +# Command-id overrides + +# Rendering mode and recovery + +# About ▸ Contributors / Models (credits) + +# Text Color Picker and screen sampling + +# Swatches panel + +# Fill dialog, layer style contours and Image Size + +# Layer colour labels. +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) + Mask Options… Opcje maski… + Layer Mask Display Options… Opcje wyświetlania maski warstwy… + Channel Color Kolor kanału + Color Indicates: Kolor oznacza: + Solidity: Gęstość: + Ink Characteristics Właściwości farby Paper Width Szerokość papieru Paper Height Wysokość papieru Rows Wiersze @@ -48,7 +147,6 @@ 5 Columns, 3 Rows 5 kolumn, 3 wiersze 8 Columns 8 kolumn 12 Columns 12 kolumn - File Plik Edit Edycja Image Obraz @@ -451,6 +549,7 @@ Intersect Shape Areas Część wspólna obszarów kształtów Exclude Overlapping Shapes Wyklucz nakładające się kształty Merge Shape Components Scal składniki kształtu + Path operations Operacje na ścieżkach Align Wyrównaj Top Edges Górne krawędzie Vertical Centers Środki w pionie @@ -530,7 +629,6 @@ Color Range… Zakres kolorów… Focus Area… Obszar ostrości… Select and Mask… Zaznacz i maskuj… -# Select and Mask dialog labels Smart Radius Inteligentny promień Shift Edge Przesuń krawędź Decontaminate Dekontaminacja @@ -558,7 +656,6 @@ Blur Rozmycie Blur Gallery Galeria rozmyć Field Blur… Rozmycie pola… -# Field Blur pins (#3373) No pin selected Nie zaznaczono pinezki Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Kliknij obraz, aby dodać pinezkę; przeciągnij pinezkę, aby ją przesunąć, lub jej pierścień, aby zmienić rozmycie. Delete usuwa zaznaczoną pinezkę. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Przeciągnij uchwyty na obrysie, aby zmienić rozmiar i obrócić kształt, kwadrat, aby zaokrąglić narożniki, a punkty wewnątrz, aby ustawić, gdzie zaczyna się rozmycie. @@ -821,7 +918,6 @@ Statistics… Statystyki… Refine Strokes Pociągnięcia udoskonalania Edits Edycje -# Counted status and panel messages (plural forms: 1 | 2–4 except 12–14 | the rest) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} Wyeksportowano {n} próbkę koloru do {file}|Wyeksportowano {n} próbki kolorów do {file}|Wyeksportowano {n} próbek kolorów do {file} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} Zaimportowano {n} próbkę koloru z {file}|Zaimportowano {n} próbki kolorów z {file}|Zaimportowano {n} próbek kolorów z {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} Zaimportowano {n} pędzel z {group}|Zaimportowano {n} pędzle z {group}|Zaimportowano {n} pędzli z {group} @@ -836,11 +932,8 @@ @plural {n} slice|{n} slices {n} plasterek|{n} plasterki|{n} plasterków @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} kolejne ostrzeżenie dotyczące ustawień wstępnych pędzli)|{warning} (+{n} kolejne ostrzeżenia dotyczące ustawień wstępnych pędzli)|{warning} (+{n} kolejnych ostrzeżeń dotyczących ustawień wstępnych pędzli) @plural {what} with {n} warning|{what} with {n} warnings {what}: {n} ostrzeżenie|{what}: {n} ostrzeżenia|{what}: {n} ostrzeżeń - @plural {n} item|{n} items {n} element|{n} elementy|{n} elementów Auto Automatycznie - -# Dialogs and panels (print to the printer) (drukuj na drukarce) + Add variable + Dodaj zmienną 30 frames @ 30 fps 30 klatek @ 30 kl./s @@ -854,6 +947,9 @@ Add Layer Mask Dodaj maskę warstwy Add Stop Dodaj punkt Add a layer style Dodaj styl warstwy + Move effect up Przesuń efekt w górę + Move effect down Przesuń efekt w dół + Delete effect Usuń efekt Add a mask (from the selection; {key} inverts) Dodaj maskę (z zaznaczenia; {key} odwraca) Add an adjustment Dodaj korektę Add disk Dodaj dysk @@ -1080,8 +1176,6 @@ Delete current channel Usuń bieżący kanał Delete current state Usuń bieżący stan Delete effect layer Usuń warstwę efektu - -# Layers-panel trash confirmation Delete layer ‘{name}’? Usunąć warstwę „{name}”? Delete {count} layers? {names} Usunąć warstwy ({count})? {names} Delete layer? Usunąć warstwę? @@ -1090,7 +1184,6 @@ Missing delete command Brak polecenia usuwania Invalid delete command Nieprawidłowe polecenie usuwania Layer deleted, but confirmation preference could not be saved: {error} Warstwa została usunięta, ale nie udało się zapisać ustawienia potwierdzenia: {error} - Delete layer Usuń warstwę Delete layer comp Usuń kompozycję warstw Delete note Usuń notatkę @@ -1637,8 +1730,6 @@ No saved presets yet. Nie ma jeszcze zapisanych ustawień wstępnych. Error Błąd Command Polecenie - -# Tool names, brush and style option tables Adjustment layers have nothing to transform Warstwy korekcyjne nie mają czego przekształcać Altitude Wysokość kątowa Android 1080p Android 1080p @@ -1871,8 +1962,6 @@ Yellows Żółte Zoom Tool Narzędzie Lupa {name} Properties Właściwości: {name} - -# Templates with placeholders Revert “{name}” to the last saved version? Your changes will be lost. Przywrócić „{name}” do ostatnio zapisanej wersji? Zmiany zostaną utracone. Do you want to save the changes you made to “{name}” before quitting? Czy zapisać zmiany wprowadzone w „{name}” przed zakończeniem? Do you want to save the changes you made to “{name}” before closing? Czy zapisać zmiany wprowadzone w „{name}” przed zamknięciem? @@ -1893,8 +1982,6 @@ @plural {n} Layer|{n} Layers {n} warstwa|{n} warstwy|{n} warstw @plural {n} layer|{n} layers {n} warstwa|{n} warstwy|{n} warstw @plural Group · {n} layer|Group · {n} layers Grupa · {n} warstwa|Grupa · {n} warstwy|Grupa · {n} warstw - -# Preferences (labels are generated from the setting names) Additional plugins folder Dodatkowy folder wtyczek Adobe Adobe Adobe rgb Adobe RGB @@ -2092,8 +2179,6 @@ Luminosity Luminancja @plural {n} sample|{n} samples {n} próbka|{n} próbki|{n} próbek {added}, {removed} subtracted {added}, odjęto {removed} - -# Added with the dock / brush picker work Adjustment Preview Podgląd korekty Airbrush: keeps depositing paint while the pointer rests. Aerograf: nakłada farbę nadal, gdy wskaźnik się nie porusza. Angle: Kąt: @@ -2125,8 +2210,6 @@ Brush picker Wybór pędzla Erase Wymaż Right click with painting tools Prawy przycisk z narzędziami malarskimi - -# Strings added to the UI later System Info… Informacje o systemie… System Info Informacje o systemie More panels Więcej paneli @@ -2188,7 +2271,6 @@ 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) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Edytor gradientu Gradient picker Wybór gradientu Gradient stops Punkty gradientu @@ -2248,8 +2330,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Siatka: - -# Tool, filter, warp-style, path, layer-comp and metadata names Delete Smart Filters Usuń filtry inteligentne Enable Smart Filters Włącz filtry inteligentne New Layer… Nowa warstwa… @@ -2703,15 +2783,11 @@ Expand group (⌥-click: all groups) Rozwiń grupę (kliknięcie z ⌥: wszystkie grupy) Hide the layer's effects (⌥-click: all layers) Ukryj efekty warstwy (kliknięcie z ⌥: wszystkie warstwy) Show the layer's effects (⌥-click: all layers) Pokaż efekty warstwy (kliknięcie z ⌥: wszystkie warstwy) - -# Command-id overrides @id select.all Zaznacz wszystko @id edit.purge.undo Historia cofania @id edit.stroke Obrys… @id edit.transform.scale Skaluj @id filter.sharpen.sharpen Wyostrz - -# Rendering mode and recovery Rendering Mode Tryb renderowania Automatic (recommended) Automatyczny (zalecany) CPU / Compatibility CPU / zgodność @@ -3396,8 +3472,6 @@ cameraRaw Roughness Chropowatość Wrap Owinięcie Zigzag Zygzak Wetness Wilgotność - -# About ▸ Contributors / Models (credits) About O programie Contributors Współtwórcy Models Modele @@ -3428,8 +3502,6 @@ cameraRaw Roughness Chropowatość % of all commits % wszystkich commitów Lines +/− Wiersze +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR: {prs}, commity: {commits}, wiersze +{added} / −{deleted} (Δ {delta}), pliki binarne +{binAdded} / −{binDeleted}, {first} – {last} - -# Text Color Picker and screen sampling Color Picker (Text Color) Próbnik kolorów (Kolor tekstu) Color Picker ({name}) Próbnik kolorów ({name}) Color Picker (Fill Color) Próbnik kolorów (Kolor wypełnienia) @@ -3456,8 +3528,6 @@ cameraRaw Roughness Chropowatość Or set Preferences › Performance › Linux display server to X11: PhotoCraft then always starts under XWayland. Albo ustaw Preferencje › Wydajność › Serwer wyświetlania Linuksa na X11: PhotoCraft będzie wtedy zawsze uruchamiany pod XWayland. Edit › Paste Edycja › Wklej Use File › Open, or paste a copied image with {paste}. Użyj Plik › Otwórz albo wklej skopiowany obraz za pomocą {paste}. - -# Swatches panel Create new swatch Utwórz nową próbkę New Swatch… Nowa próbka… New Swatch Group… Nowa grupa próbek… @@ -3468,6 +3538,8 @@ cameraRaw Roughness Chropowatość Reset Swatches Resetuj próbki Add to Swatches Dodaj do próbek Blend If: Mieszaj, jeśli: + Current Layer: Bieżąca warstwa: + Underlying Layer: Warstwa pod spodem: Channels: Kanały: Knockout Wycięcie New Brush Preset… Nowe ustawienie wstępne pędzla… @@ -3477,8 +3549,6 @@ cameraRaw Roughness Chropowatość Enter a name for the brush preset Wpisz nazwę ustawienia wstępnego pędzla A brush preset with this name already exists Ustawienie wstępne pędzla o tej nazwie już istnieje Brush Preset Options Opcje ustawień wstępnych pędzla - -# Fill dialog, layer style contours and Image Size Contents: Zawartość: Custom Pattern: Własny wzór: Foreground Color Kolor pierwszego planu @@ -3516,8 +3586,6 @@ cameraRaw Roughness Chropowatość Selection Preview: Podgląd zaznaczenia: Black Matte Czarne tło White Matte Białe tło - -# Layer colour labels. Seafoam Morski Indigo Indygo Fuchsia Fuksja @@ -3526,19 +3594,14 @@ cameraRaw Roughness Chropowatość This redraw took {seconds} s on the CPU. To odświeżenie na CPU trwało {seconds} s. Edits that change the whole document, such as a layer's blend mode, opacity or visibility, redraw all of it. Zmiany obejmujące cały dokument, takie jak tryb mieszania, krycie lub widoczność warstwy, odświeżają go w całości. The GPU compositor wasn't used: {reason} Kompozytor GPU nie został użyty: {reason} -# Pattern Stamp tool Pattern Stamp Tool Narzędzie Pieczątka wzoru 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° - -# Painting symmetry presets. Dual Axis Podwójna oś Diagonal Ukośna Transform Symmetry Przekształć symetrię - -# Eyedropper Sample Size and Sample (#1649). Point Sample Próbka punktowa 3 by 3 Average Uśrednianie 3 × 3 5 by 5 Average Uśrednianie 5 × 5 @@ -3550,15 +3613,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Kolor na alfę… Transparency Threshold Próg przezroczystości Opacity Threshold Próg krycia PhotoCraft — Screen Color Picker PhotoCraft — Próbnik kolorów ekranu - Rasterize svg groups deeper than Rasteryzuj grupy SVG głębsze niż ten poziom 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 wyłącza ten próg; grupy SVG zagnieżdżone głębiej niż 100 poziomów są zawsze rasteryzowane. Rule of Thirds Zasada trójpodziału @@ -3571,8 +3631,6 @@ cameraRaw Roughness Chropowatość Cycle Orientation Przełącz orientację Set the overlay options for the Crop tool Ustaw opcje nakładki narzędzia Kadrowanie Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+kliknięcie przejęło środowisko pulpitu, które przesuwa okna przez Alt+przeciąganie. Ustaw w nim klawisz przesuwania okien na Super lub zablokuj Alt w Okno › Klawisze modyfikujące. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Próbnik kolorów (kolor stylu warstwy) Auto Hide Notifications Automatycznie ukrywaj powiadomienia Notification Duration (seconds) Czas trwania powiadomienia (sekundy) @@ -3648,7 +3706,6 @@ cameraRaw Roughness Chropowatość Appearance Settings… Ustawienia wyglądu… Add to favorites Dodaj do ulubionych Remove from favorites Usuń z ulubionych -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Producent cameraData Model Model cameraData Date Taken Data wykonania @@ -3658,7 +3715,6 @@ cameraData ISO Speed Czułość ISO cameraData Focal Length Ogniskowa cameraData Focal Length (35 mm) Ogniskowa (35 mm) cameraData Lens Obiektyw -# Shared panel docking Activate Panel Aktywuj panel Change Panel Group Zmień grupę paneli Change Panel Layout Zmień układ paneli @@ -3702,7 +3758,6 @@ cameraData Lens Obiektyw Snap to Origin Przyciągnij do początku Search settings… Szukaj ustawień… No matching settings Brak pasujących ustawień -# Edit › Content-Aware Fill workspace Sampling Brush Tool Narzędzie Pędzel próbkowania Sampling Area Overlay Nakładka obszaru próbkowania Show Sampling Area Pokaż obszar próbkowania @@ -3718,7 +3773,6 @@ cameraData Lens Obiektyw Mirror Odbicie lustrzane Output Settings Ustawienia wyjścia Output To Wyjście do - Animation Options Opcje animacji Entire Document Cały dokument Filter Options Opcje filtrowania @@ -3735,8 +3789,6 @@ cameraData Lens Obiektyw Add “copy” to Copied Layers and Groups Dodawaj „kopia” do skopiowanych warstw i grup Preview on canvas when reordering layers Podgląd na obszarze roboczym podczas zmiany kolejności warstw Show layer mask badges Pokaż odznaki masek warstw - -# Smart Filter editors Blending Options ({filter}) Opcje mieszania ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Ukryj efekty warstwy i inteligentne filtry (kliknięcie z {key}: wszystkie warstwy) Show the layer's effects and Smart Filters ({key}-click: all layers) Pokaż efekty warstwy i inteligentne filtry (kliknięcie z {key}: wszystkie warstwy) @@ -3767,7 +3819,6 @@ curves Smooth Wygładź Fix the red plane first: its corners must form a convex quad Najpierw popraw czerwoną płaszczyznę: jej narożniki muszą tworzyć czworokąt wypukły Alt-click a plane to set the clone source Kliknij płaszczyznę z Alt, aby ustawić źródło klonowania Too many clone strokes: apply Vanishing Point first Zbyt wiele pociągnięć klonowania: najpierw zastosuj Punkt zbieżności -# Select and Mask view modes (#1754) Onion Skin Skórka cebuli Marching Ants Maszerujące mrówki On Black Na czarnym @@ -3776,7 +3827,6 @@ curves Smooth Wygładź Show Edge Pokaż krawędź Show Original Pokaż oryginał F cycles the views; hold X to see the image F przełącza widoki; przytrzymaj X, aby zobaczyć obraz -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Pędzel dopracowania krawędzi (R) Expand Detection Area Rozszerz obszar wykrywania Restore Original Edge Przywróć oryginalną krawędź @@ -3784,19 +3834,13 @@ curves Smooth Wygładź Clear Brush Strokes Wyczyść pociągnięcia pędzla Show rulers Pokaż linijki Presentation Prezentacja - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Kliknij, aby umieścić · Alt-kliknij lub przeciągnij poza obszar roboczy, aby usunąć No document open Brak otwartego dokumentu {n} of {max} sample points {n} z {max} punktów próbkowania - -# History panel menu (#2966) New Snapshot… Nowa migawka… History Options… Opcje historii… -# History panel › History Options… (#2966) Allow Non-Linear History Zezwalaj na nieliniową historię Make Layer Visibility Changes Undoable Pozwalaj cofać zmiany widoczności warstw -# Print dialog (#2697) Emulsion Down Emulsja w dół Functions Funkcje Print Resolution: Rozdzielczość druku: @@ -3808,7 +3852,6 @@ curves Smooth Wygładź Apply mask to layer before removing? Zastosować maskę do warstwy przed usunięciem? The layer or its mask changed. Drag the mask onto the Trash again. Warstwa lub jej maska uległa zmianie. Przeciągnij maskę ponownie do kosza. Delete the vector mask? Usunąć maskę wektorową? -# View › Guides › New Guide… › Color Light Blue Jasnoniebieski Light Red Jasnoczerwony Medium Blue Średnioniebieski @@ -3829,8 +3872,6 @@ curves Smooth Wygładź Clear Brush Controls Wyczyść elementy sterujące pędzlem Reset All Locked Settings Resetuj wszystkie zablokowane ustawienia Copy Texture to Other Tools Kopiuj teksturę do innych narzędzi - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Wczytaj operacje… Save Actions… Zapisz operacje… New Action… Nowa operacja… @@ -3842,10 +3883,8 @@ curves Smooth Wygładź @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} krok nie ma jeszcze odpowiednika w PhotoCraft|{n} kroki nie mają jeszcze odpowiednika w PhotoCraft|{n} kroków nie ma jeszcze odpowiednika w PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Zapisano {n} operację do {file}|Zapisano {n} operacje do {file}|Zapisano {n} operacji do {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Pominięto {n} krok bez odpowiednika w Photoshopie|Pominięto {n} kroki bez odpowiednika w Photoshopie|Pominięto {n} kroków bez odpowiednika w Photoshopie - File Naming Nazewnictwo plików Starting serial Początkowy numer seryjny -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Wstaw zatrzymanie… Save Set… Zapisz zestaw… Message: Komunikat: @@ -3856,11 +3895,8 @@ curves Smooth Wygładź Step {step} is waiting for its dialog Krok {step} czeka na swoje okno dialogowe @plural {n} action|{n} actions {n} operacja|{n} operacje|{n} operacji Background (Default) Tło (domyślne) -# Batch / Image Processor Include All Subfolders Uwzględnij wszystkie podfoldery Auto Add/Delete Automatyczne dodawanie/usuwanie - -# Native Windows printing qualification 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… @@ -3905,7 +3941,6 @@ curves Smooth Wygładź Could not write {name}: {error} Nie można zapisać {name}: {error} Kept {name}: written by another application Zachowano {name}: zapisany przez inną aplikację Shadow Tint Tinta cieni -# PhotoCraft release checks. Check for Updates… Sprawdź aktualizacje… PhotoCraft Updates Aktualizacje PhotoCraft Checking for updates… Sprawdzanie aktualizacji… @@ -3918,35 +3953,27 @@ curves Smooth Wygładź Automatically Check for Updates Automatycznie sprawdzaj aktualizacje Installed version: {version} Zainstalowana wersja: {version} PhotoCraft {version} is available. PhotoCraft {version} jest dostępny. -# History panel › History Brush source (#2966) Paints from the History panel's source state Maluje ze stanu źródłowego panelu Historia Sets the source for the history brush Ustawia źródło dla pędzla historii -# Bevel & Emboss shading controls. Highlight Mode Tryb świateł Highlight Color Kolor świateł Highlight Opacity Krycie świateł Shadow Mode Tryb cieni Shadow Color Kolor cieni Shadow Opacity Krycie cieni -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Użyj osadzonego profilu ({profile}) Convert to the working space ({profile}) Konwertuj na przestrzeń roboczą ({profile}) Remember this choice for future images Zapamiętaj ten wybór dla kolejnych obrazów Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Pytanie można włączyć ponownie opcją Ask On Mismatch w Edycja › Ustawienia kolorów. Button Mode Tryb przycisku Button Mode On Tryb przycisku włączony - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Przyciemnij interfejs Lighten Interface Rozjaśnij interfejs -# Bevel & Emboss Technique. Technique Technika Chisel Hard Dłuto twarde Chisel Soft Dłuto miękkie Open color-less EXR as ACEScg Otwieraj EXR bez profilu koloru jako ACEScg Do not append "copy" to filename when saving a copy Nie dodawaj „copy” do nazwy pliku przy zapisywaniu kopii - -# View › Guides › right-click a guide Edit Selected Guides Edytuj zaznaczone prowadnice Clear Selected Guides Usuń zaznaczone prowadnice Bicubic Automatic Dwusześcienna automatyczna @@ -3971,8 +3998,6 @@ curves Smooth Wygładź set name nazwa zestawu {set} (modified) {set} (zmieniony) Show file name in title Pokaż nazwę pliku w tytule - -# Image › Mode › Bitmap (#5559) 50% Threshold Próg 50% Pattern Dither Rozpraszanie wzorkiem Diffusion Dither Rozpraszanie dyfuzyjne @@ -3990,10 +4015,8 @@ curves Smooth Wygładź Undo Changes Cofnij zmiany {shortcut} is reserved by the system and can't be assigned. {shortcut} jest zarezerwowany przez system i nie można go przypisać. Low-Latency Drawing (vsync off, applies at next launch) Rysowanie z małym opóźnieniem (bez synchronizacji pionowej, od następnego uruchomienia) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Przekształcanie swobodne jest nadal stosowane; spróbuj ponownie, gdy się zakończy. The transform couldn't be applied. Nie można zastosować przekształcenia. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Warstwy potrzebują {needed} pamięci GPU; budżet zostawia im {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Ustaw Pamięć GPU w Preferencje › Wydajność na tyle, ile zmieści Twoja karta graficzna, najwyżej 3/8 jej pamięci. Automatycznie podąża za Użyciem pamięci, w granicach jednej czwartej pamięci tego komputera i 3/8 pamięci karty, i nie wlicza dokumentu przy karcie o znanej pamięci. Dopóki się nie mieszczą, pasek stanu pokazuje Pamięć GPU pełna. GPU Memory Full Pamięć GPU pełna @@ -4020,8 +4043,6 @@ curves Smooth Wygładź The fastest and the softest, with colour 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}”. - Move Up Przesuń w górę - Move Down Przesuń w dół Previous Brush Poprzedni pędzel Next Brush Następny pędzel First Brush Pierwszy pędzel @@ -4036,27 +4057,18 @@ curves Smooth Wygładź Use Użyj In Front Z przodu Behind Z tyłu - -# DDS Options (#1327) DDS Options Opcje DDS Compression Kompresja Generate Mipmaps Generuj mipmapy - -# Color Table (.act) dialog There is no color table to save. Brak tabeli kolorów do zapisania. @plural Saved {n} color to {file}|Saved {n} colors to {file} Zapisano {n} kolor do {file}|Zapisano {n} kolory do {file}|Zapisano {n} kolorów do {file} - -# Graphics Adapter preference (#1885) GPU adapter Karta GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Importuj style… Export Selected Styles… Eksportuj zaznaczone style… Export Styles… Eksportuj style… {file} is not a style library (.asl) {file} nie jest biblioteką stylów (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Zaimportowano {n} styl z {file}|Zaimportowano {n} style z {file}|Zaimportowano {n} stylów z {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Wyeksportowano {n} styl do {file}|Wyeksportowano {n} style do {file}|Wyeksportowano {n} stylów do {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Najpierw zatwierdź lub anuluj otwarte okno kroku operacji Pro Medium Gray Pro (średni szary) Solarized Solarized @@ -4065,29 +4077,11 @@ curves Smooth Wygładź Pro Light Pro (jasny) Resize Windows to Fit Dopasuj rozmiar okien EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Automatyczny kierunek akapitu Left-to-right paragraph direction Kierunek akapitu od lewej do prawej Right-to-left paragraph direction Kierunek akapitu od prawej do lewej Not rendered: this adjustment ({key}) is kept as imported. Nie jest renderowana: ta korekta ({key}) jest zachowana w postaci zaimportowanej. -# Print preview image (#8236) Print preview image Print preview image - Clear Selection Wyczyść zaznaczenie - Color Aware Według kolorów - Decontaminate Colors Odkażanie kolorów - Edge Detection Wykrywanie krawędzi - Global Refinements Dopracowanie globalne - High Quality Preview Podgląd wysokiej jakości - Object Aware Według obiektów - Real-Time Refinement Dopracowanie w czasie rzeczywistym - Refine Edge Brush Tool Narzędzie Pędzel dopracowania krawędzi - Refine Hair Dopracuj włosy - Refine Mode Tryb dopracowania - Remember Settings Zapamiętaj ustawienia - View Mode Tryb widoku - Object Aware needs a segmentation model, which isn't available yet Tryb Według obiektów wymaga modelu segmentacji, który nie jest jeszcze dostępny - Refine Hair needs hair detection, which isn't available yet Dopracowanie włosów wymaga wykrywania włosów, które nie jest jeszcze dostępne -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Sześcian odcienia Brightness Cube Sześcian jasności Color Wheel Koło kolorów @@ -4103,9 +4097,8 @@ curves Smooth Wygładź Grayscale Ramp Pasek skali szarości Current Colors Bieżące kolory Make Ramp Web Safe Ogranicz pasek do kolorów internetowych - Select and Mask was closed: its document is no longer the active one Zamknięto Zaznacz i maskuj: jego dokument nie jest już aktywny - Select and Mask was closed: another layer was selected Zamknięto Zaznacz i maskuj: wybrano inną warstwę -# Art History Brush (#213). + The path was kept as the Work Path Ścieżka została zachowana jako ścieżka robocza + The path was discarded Ścieżka została odrzucona Art History Brush Tool Narzędzie Pędzel historii artystycznej Tight Short Ścisły krótki Tight Medium Ścisły średni @@ -4116,9 +4109,25 @@ curves Smooth Wygładź Tight Curl Ścisły lok Loose Curl Luźny lok Stylized dabs from a history state Stylizowane plamy ze stanu historii - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Cel Font size presets Ustawienia wstępne rozmiaru czcionki Leading presets Ustawienia wstępne interlinii Tracking presets Ustawienia wstępne światła + Clear Selection Wyczyść zaznaczenie + Color Aware Według kolorów + Decontaminate Colors Odkażanie kolorów + Edge Detection Wykrywanie krawędzi + Global Refinements Dopracowanie globalne + High Quality Preview Podgląd wysokiej jakości + Object Aware Według obiektów + Real-Time Refinement Dopracowanie w czasie rzeczywistym + Refine Edge Brush Tool Narzędzie Pędzel dopracowania krawędzi + Refine Hair Dopracuj włosy + Refine Mode Tryb dopracowania + Remember Settings Zapamiętaj ustawienia + View Mode Tryb widoku + Object Aware needs a segmentation model, which isn't available yet Tryb Według obiektów wymaga modelu segmentacji, który nie jest jeszcze dostępny + Refine Hair needs hair detection, which isn't available yet Dopracowanie włosów wymaga wykrywania włosów, które nie jest jeszcze dostępne + Select and Mask was closed: its document is no longer the active one Zamknięto Zaznacz i maskuj: jego dokument nie jest już aktywny + Select and Mask was closed: another layer was selected Zamknięto Zaznacz i maskuj: wybrano inną warstwę + Select Layer Under Cursor Zaznacz warstwę pod kursorem diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 57d0fcc985..d119a607e5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -16,18 +16,113 @@ # stay as they are; the trailing "…" of dialog commands is kept. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Opções de máscara… - Layer Mask Display Options… Opções de exibição de máscara de camada… # Channel Options and New Spot Channel (#3761) - Channel Color Cor do canal - Color Indicates: A cor indica: - Solidity: Solidez: - Ink Characteristics Características da tinta # Guide layout dialog # Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Layer Style dialog: style presets and per-effect defaults + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Channels panel menu: channel commands, spot channels, Quick Mask, Color Indicates +# Layer Style › Blending Options: advanced blending and Blend If +# Canvas right-click menus: pasteboard color, paths and shapes +# Color Picker titles +# Rasterize prompts +# GPU and display status (status bar, System Info) +# Status messages +# Panels and small controls +# Liquify tools (tooltips) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). +# Smart Filter row actions (#1265) + + Mask Options… Opções de máscara… + Layer Mask Display Options… Opções de exibição de máscara de camada… + Channel Color Cor do canal + Color Indicates: A cor indica: + Solidity: Solidez: + Ink Characteristics Características da tinta Paper Width Largura do papel Paper Height Altura do papel Rows Linhas @@ -46,7 +141,6 @@ 5 Columns, 3 Rows 5 colunas, 3 linhas 8 Columns 8 colunas 12 Columns 12 colunas - File Arquivo Edit Editar Image Imagem @@ -437,6 +531,7 @@ Intersect Shape Areas Fazer interseção das áreas de formas Exclude Overlapping Shapes Excluir formas sobrepostas Merge Shape Components Mesclar componentes de formas + Path operations Operações de demarcador Align Alinhar Top Edges Bordas superiores Vertical Centers Centros verticais @@ -516,7 +611,6 @@ Color Range… Intervalo de cores… Focus Area… Área de foco… Select and Mask… Selecionar e mascarar… -# Select and Mask dialog labels Smart Radius Raio inteligente Shift Edge Deslocar borda Decontaminate Descontaminar @@ -542,7 +636,6 @@ Blur Desfoque Blur Gallery Galeria de desfoque Field Blur… Desfoque de campo… -# Field Blur pins (#3373) No pin selected Nenhum alfinete selecionado Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Clique na imagem para adicionar um alfinete; arraste um alfinete para movê-lo ou o anel dele para alterar o desfoque. Delete remove o alfinete selecionado. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Arraste as alças do contorno para redimensionar e girar, o quadrado para arredondar os cantos e os pontos internos para definir onde o desfoque começa. @@ -820,6 +913,9 @@ Add Layer Mask Adicionar máscara de camada Add Stop Adicionar parada Add a layer style Adicionar um estilo de camada + Move effect up Mover efeito para cima + Move effect down Mover efeito para baixo + Delete effect Excluir efeito Add a mask (from the selection; {key} inverts) Adicionar uma máscara (a partir da seleção; {key} inverte) Add an adjustment Adicionar um ajuste Add disk Adicionar disco @@ -1046,8 +1142,6 @@ Delete current channel Excluir o canal atual Delete current state Excluir o estado atual Delete effect layer Excluir camada de efeito - -# Layers-panel trash confirmation Delete layer ‘{name}’? Excluir a camada “{name}”? Delete {count} layers? {names} Excluir {count} camadas? {names} Delete layer? Excluir camada? @@ -1056,7 +1150,6 @@ Missing delete command Comando de exclusão ausente Invalid delete command Comando de exclusão inválido Layer deleted, but confirmation preference could not be saved: {error} A camada foi excluída, mas não foi possível salvar a preferência de confirmação: {error} - Delete layer Excluir camada Delete layer comp Excluir composição de camadas Delete note Excluir anotação @@ -1089,7 +1182,6 @@ Dots Pontos Drag a rectangle around the object Arraste um retângulo ao redor do objeto Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it. Arraste sobre a imagem para adicionar uma restrição; Shift para horizontal/vertical; clique direito em uma restrição para alterá-la ou excluí-la. - Drag to move the active shape's path or the Work Path Arraste para mover o demarcador da forma ativa ou o demarcador de trabalho Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Clique: selecionar ponto · Arrastar: mover ponto, alça ou segmento · {shift}-clique: adicionar · {alt}-clique: subdemarcador inteiro Draw with the Pen tool (P) or make a work path from a selection. Desenhe com a ferramenta Caneta (P) ou crie um demarcador de trabalho a partir de uma seleção. Drop an image or PSD anywhere to open it. Solte uma imagem ou um PSD em qualquer lugar para abri-lo. @@ -2146,7 +2238,6 @@ Align with layer Alinhar com a camada Reset Alignment Redefinir alinhamento Centre the gradient (offset 0, 0) Centralizar o degradê (deslocamento 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Editor de degradê Gradient picker Seletor de degradê Gradient stops Paradas do degradê @@ -2772,8 +2863,6 @@ cameraRaw Whites Brancos Don't show again Não mostrar novamente Save failed: {error} Falha ao salvar: {error} Save cancelled Salvamento cancelado - -# Layer Style dialog: style presets and per-effect defaults Style {name} saved Estilo {name} salvo Make Default Definir como padrão Reset to Default Restaurar padrão @@ -2782,8 +2871,6 @@ cameraRaw Whites Brancos Magnetic Lasso Tool Ferramenta Laço magnético Frequency Frequência Use tablet pressure to change pen width Usar a pressão da mesa digitalizadora para alterar a largura da caneta - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About Sobre Contributors Colaboradores Models Modelos @@ -2814,8 +2901,6 @@ cameraRaw Whites Brancos % of all commits % de todos os commits Lines +/− Linhas +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} linhas (Δ {delta}), +{binAdded} / −{binDeleted} arquivos binários, {first} – {last} - -# Swatches panel Create new swatch Criar nova amostra New Swatch… Nova amostra… New Swatch Group… Novo grupo de amostras… @@ -2825,13 +2910,12 @@ cameraRaw Whites Brancos Export Swatches for Exchange… Exportar amostras para troca… Reset Swatches Redefinir amostras Add to Swatches Adicionar às amostras -# Layer Style > Blending Options (Advanced Blending) Blend If: Mesclar se: + Current Layer: Camada atual: + Underlying Layer: Camada subjacente: Channels: Canais: Knockout Vazado Apply At Canvas Bounds Aplicar efeito nos limites da tela - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Seletor de cores (Cor do texto) Color Picker ({name}) Seletor de cores ({name}) Color Picker (Fill Color) Seletor de cores (Cor de preenchimento) @@ -2848,8 +2932,6 @@ cameraRaw Whites Brancos Show/Hide Panels Mostrar/ocultar painéis Could not open Não foi possível abrir {path}: the path is not valid Unicode; rename the file and open it again. {path}: o caminho não é Unicode válido; renomeie o arquivo e abra-o novamente. - -# Fill dialog, layer style contours and Image Size Contents: Conteúdo: Custom Pattern: Padrão personalizado: Foreground Color Cor de primeiro plano @@ -2876,14 +2958,12 @@ cameraRaw Whites Brancos Rolling Slope - Descending Declive ondulado - descendente Rounded Steps Degraus arredondados Sawtooth 1 Dente de serra 1 - Red Eye Tool Ferramenta Olhos vermelhos Pupil Size Tamanho da pupila Darken Amount Quantidade de escurecimento Click a red pupil to neutralize it Clique em uma pupila vermelha para corrigi-la open source código aberto …and {n} more …e mais {n} - Eyedroppers: Conta-gotas: Set Black Point Definir ponto preto Set Neutral Gray Point Definir ponto cinza neutro @@ -2892,8 +2972,6 @@ cameraRaw Whites Brancos Selection Preview: Visualização da seleção: Black Matte Fundo preto White Matte Fundo branco - -# Layer colour labels. Seafoam Espuma do mar Indigo Índigo Fuchsia Fúcsia @@ -2913,20 +2991,14 @@ fontWeight Bold Negrito fontWeight ExtraBold Extranegrito fontWeight Black Ultranegrito fontWeight Italic Itálico - -# Pattern Stamp tool Pattern Stamp Tool Ferramenta Carimbo de padrão 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° - -# Painting symmetry presets. Dual Axis Eixo duplo Diagonal Diagonal Transform Symmetry Transformar simetria - -# Eyedropper Sample Size and Sample (#1649). Point Sample Amostra pontual 3 by 3 Average Média de 3 × 3 5 by 5 Average Média de 5 × 5 @@ -2938,15 +3010,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Cor para alfa… Transparency Threshold Limiar de transparência Opacity Threshold Limiar de opacidade PhotoCraft — Screen Color Picker PhotoCraft — Seletor de cor da tela - Rasterize svg groups deeper than Rasterizar grupos SVG além desta profundidade 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 desativa este limite; grupos SVG aninhados em mais de 100 níveis são sempre rasterizados. Rule of Thirds Regra dos terços @@ -2960,8 +3029,6 @@ fontWeight Italic Itálico Cycle Orientation Alternar orientação Set the overlay options for the Crop tool Definir as opções de sobreposição da ferramenta Corte demarcado Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. O Alt-clique foi para o desktop, que move janelas com Alt-arrastar. Mude a tecla de mover janelas dele para Super ou trave o Alt em Janela › Teclas modificadoras. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Seletor de cores (cor do estilo de camada) Auto Hide Notifications Ocultar notificações automaticamente Notification Duration (seconds) Duração da notificação (segundos) @@ -3037,7 +3104,6 @@ fontWeight Italic Itálico Appearance Settings… Configurações de aparência… Add to favorites Adicionar aos favoritos Remove from favorites Remover dos favoritos -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Fabricante cameraData Model Modelo cameraData Date Taken Data de captura @@ -3047,7 +3113,6 @@ cameraData ISO Speed Sensibilidade ISO cameraData Focal Length Distância focal cameraData Focal Length (35 mm) Distância focal (35 mm) cameraData Lens Lente -# Shared panel docking Activate Panel Ativar painel Change Panel Group Alterar grupo de painéis Change Panel Layout Alterar disposição dos painéis @@ -3091,7 +3156,6 @@ cameraData Lens Lente Snap to Origin Ajustar à origem Search settings… Pesquisar configurações… No matching settings Nenhuma configuração encontrada -# Edit › Content-Aware Fill workspace Sampling Brush Tool Ferramenta Pincel de amostragem Sampling Area Overlay Sobreposição da área de amostragem Show Sampling Area Mostrar área de amostragem @@ -3110,7 +3174,6 @@ cameraData Lens Lente New Layer Nova camada Duplicate Layer Duplicar camada Contract Contrair - Animation Options Opções de animação Entire Document Documento inteiro Filter Options Opções de filtro @@ -3127,8 +3190,6 @@ cameraData Lens Lente Add “copy” to Copied Layers and Groups Adicionar “cópia” às camadas e grupos copiados Preview on canvas when reordering layers Pré-visualizar na tela ao reordenar camadas Show layer mask badges Mostrar emblemas de máscaras de camada - -# Smart Filter editors Blending Options ({filter}) Opções de mesclagem ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Ocultar efeitos da camada e Filtros Inteligentes ({key}-clique: todas as camadas) Show the layer's effects and Smart Filters ({key}-click: all layers) Mostrar efeitos da camada e Filtros Inteligentes ({key}-clique: todas as camadas) @@ -3161,7 +3222,6 @@ curves Smooth Suavizar Fix the red plane first: its corners must form a convex quad Corrija primeiro o plano vermelho: seus cantos devem formar um quadrilátero convexo Alt-click a plane to set the clone source Clique com Alt em um plano para definir a origem da clonagem Too many clone strokes: apply Vanishing Point first Traços de clonagem demais: aplique Ponto de fuga primeiro -# Select and Mask view modes (#1754) Onion Skin Papel vegetal Marching Ants Formigas marchando On Black Sobre preto @@ -3170,7 +3230,6 @@ curves Smooth Suavizar Show Edge Mostrar borda Show Original Mostrar original F cycles the views; hold X to see the image F alterna as visualizações; segure X para ver a imagem -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Pincel de refinamento de borda (R) Expand Detection Area Expandir área de detecção Restore Original Edge Restaurar borda original @@ -3178,8 +3237,6 @@ curves Smooth Suavizar Clear Brush Strokes Limpar traços do pincel Show rulers Mostrar réguas Presentation Apresentação - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Clique para posicionar · Alt-clique ou arraste para fora da tela para remover No document open Nenhum documento aberto {n} of {max} sample points {n} de {max} pontos de amostragem @@ -3949,14 +4006,10 @@ layerLabel No Color Sem cor Set Colors Definir cores Switch Foreground and Background Colors Alternar cores de primeiro plano e plano de fundo Target Alvo - -# History panel menu (#2966) New Snapshot… Novo instantâneo… History Options… Opções de histórico… -# History panel › History Options… (#2966) Allow Non-Linear History Permitir histórico não linear Make Layer Visibility Changes Undoable Permitir desfazer alterações de visibilidade das camadas -# Print dialog (#2697) Emulsion Down Emulsão para baixo Functions Funções Print Resolution: Resolução de impressão: @@ -3968,7 +4021,6 @@ layerLabel No Color Sem cor Apply mask to layer before removing? Aplicar a máscara à camada antes de removê-la? The layer or its mask changed. Drag the mask onto the Trash again. A camada ou a máscara mudou. Arraste a máscara para a Lixeira novamente. Delete the vector mask? Excluir a máscara vetorial? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} {n} amostra exportada para {file}|{n} amostras exportadas para {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} {n} pincel importado de {group}|{n} pincéis importados de {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {n} amostra importada de {file}|{n} amostras importadas de {file} @@ -3983,7 +4035,6 @@ layerLabel No Color Sem cor @plural {n} step|{n} steps {n} etapa|{n} etapas @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} outro aviso de predefinição de pincel)|{warning} (+{n} outros avisos de predefinição de pincel) @plural {what} with {n} warning|{what} with {n} warnings {what} com {n} aviso|{what} com {n} avisos -# View › Guides › New Guide… › Color Light Blue Azul-claro Light Red Vermelho-claro Medium Blue Azul médio @@ -4004,8 +4055,6 @@ layerLabel No Color Sem cor Clear Brush Controls Limpar controles de pincel Reset All Locked Settings Redefinir todas as configurações bloqueadas Copy Texture to Other Tools Copiar textura para outras ferramentas - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Carregar ações… Save Actions… Salvar ações… New Action… Nova ação… @@ -4017,10 +4066,8 @@ layerLabel No Color Sem cor @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} etapa ainda não tem equivalente no PhotoCraft|{n} etapas ainda não têm equivalente no PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} ação salva em {file}|{n} ações salvas em {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} etapa sem equivalente no Photoshop foi omitida|{n} etapas sem equivalente no Photoshop foram omitidas - File Naming Nomenclatura de arquivos Starting serial Número de série inicial -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Inserir parada… Save Set… Salvar conjunto… Message: Mensagem: @@ -4031,11 +4078,8 @@ layerLabel No Color Sem cor Step {step} is waiting for its dialog A etapa {step} está aguardando sua caixa de diálogo @plural {n} action|{n} actions {n} ação|{n} ações Background (Default) Plano de fundo (padrão) -# Batch / Image Processor Include All Subfolders Incluir todas as subpastas Auto Add/Delete Adicionar/excluir automaticamente - -# Native Windows printing qualification 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… @@ -4080,7 +4124,6 @@ layerLabel No Color Sem cor Could not write {name}: {error} Não foi possível gravar {name}: {error} Kept {name}: written by another application {name} mantido: gravado por outro aplicativo Shadow Tint Matiz das sombras -# PhotoCraft release checks. Check for Updates… Verificar atualizações… PhotoCraft Updates Atualizações do PhotoCraft Checking for updates… Verificando atualizações… @@ -4093,35 +4136,27 @@ layerLabel No Color Sem cor Automatically Check for Updates Verificar atualizações automaticamente Installed version: {version} Versão instalada: {version} PhotoCraft {version} is available. PhotoCraft {version} está disponível. -# History panel › History Brush source (#2966) Paints from the History panel's source state Pinta a partir do estado de origem do painel Histórico Sets the source for the history brush Define a origem do pincel do histórico -# Bevel & Emboss shading controls. Highlight Mode Modo de realces Highlight Color Cor dos realces Highlight Opacity Opacidade dos realces Shadow Mode Modo de sombras Shadow Color Cor das sombras Shadow Opacity Opacidade das sombras -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Usar o perfil incorporado ({profile}) Convert to the working space ({profile}) Converter para o espaço de trabalho ({profile}) Remember this choice for future images Lembrar esta escolha para as próximas imagens Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Reative a pergunta com Ask On Mismatch em Editar › Configurações de cores. Button Mode Modo de botão Button Mode On Modo de botão ativado - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Escurecer interface Lighten Interface Clarear interface -# Bevel & Emboss Technique. Technique Técnica Chisel Hard Cinzel duro Chisel Soft Cinzel suave Open color-less EXR as ACEScg Abrir EXR sem espaço de cor como ACEScg Do not append "copy" to filename when saving a copy Não acrescentar "copy" ao nome do arquivo ao salvar uma cópia - -# View › Guides › right-click a guide Edit Selected Guides Editar guias selecionadas Clear Selected Guides Limpar guias selecionadas Bicubic Automatic Bicúbica automática @@ -4146,8 +4181,6 @@ layerLabel No Color Sem cor set name nome do conjunto {set} (modified) {set} (modificado) Show file name in title Exibir nome do arquivo no título - -# Image › Mode › Bitmap (#5559) 50% Threshold Limiar de 50% Pattern Dither Pontilhamento de padrão Diffusion Dither Pontilhamento de difusão @@ -4165,10 +4198,8 @@ layerLabel No Color Sem cor Undo Changes Desfazer alterações {shortcut} is reserved by the system and can't be assigned. {shortcut} é reservado pelo sistema e não pode ser atribuído. Low-Latency Drawing (vsync off, applies at next launch) Desenho de baixa latência (sem sincronização vertical, aplicado na próxima inicialização) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. A Transformação livre ainda está sendo aplicada; tente novamente quando terminar. The transform couldn't be applied. Não foi possível aplicar a transformação. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. As camadas precisam de {needed} de memória da GPU; o orçamento lhes deixa {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Ajuste Memória da GPU em Preferências › Desempenho para o que sua placa de vídeo comporta, no máximo 3/8 da memória dela. Automático segue Uso de memória, dentro de um quarto da memória deste computador e 3/8 da memória da placa, e não desconta o documento de uma placa cuja memória é conhecida. Enquanto não couberem, a barra de status mostra Memória da GPU cheia. GPU Memory Full Memória da GPU cheia @@ -4194,8 +4225,6 @@ layerLabel No Color Sem cor 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. “{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}”. - Move Up Mover para cima - Move Down Mover para baixo Previous Brush Pincel anterior Next Brush Próximo pincel First Brush Primeiro pincel @@ -4210,28 +4239,18 @@ layerLabel No Color Sem cor Use Usar In Front Na frente Behind Atrás - -# DDS Options (#1327) DDS Options Opções de DDS Generate Mipmaps Gerar mipmaps - -# Color Table (.act) dialog There is no color table to save. Não há tabela de cores para salvar. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} cor salva em {file}|{n} cores salvas em {file} - -# Graphics Adapter preference (#1885) GPU adapter Adaptador de GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Importar estilos… Export Selected Styles… Exportar estilos selecionados… Export Styles… Exportar estilos… {file} is not a style library (.asl) {file} não é uma biblioteca de estilos (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {n} estilo importado de {file}|{n} estilos importados de {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} estilo exportado para {file}|{n} estilos exportados para {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Confirme ou cancele primeiro a caixa de diálogo aberta da etapa da ação -# Channels panel menu: channel commands, spot channels, Quick Mask, Color Indicates New Channel… Novo canal… Duplicate Channel Duplicar canal Delete Channel Excluir canal @@ -4244,7 +4263,6 @@ layerLabel No Color Sem cor Exit Quick Mask Sair da máscara rápida Color Indicates Masked Areas A cor indica áreas mascaradas Color Indicates Selected Areas A cor indica áreas selecionadas -# Layer Style › Blending Options: advanced blending and Blend If General Blending Mesclagem geral Shallow Raso Deep Profundo @@ -4254,8 +4272,6 @@ layerLabel No Color Sem cor Layer Mask Hides Effects A máscara de camada oculta os efeitos Vector Mask Hides Effects A máscara vetorial oculta os efeitos This Layer: Esta camada: - Underlying Layer: Camada subjacente: -# Canvas right-click menus: pasteboard color, paths and shapes Dark Gray Cinza-escuro Medium Gray Cinza médio Select Custom Color… Selecionar cor personalizada… @@ -4274,17 +4290,14 @@ layerLabel No Color Sem cor Paste Complete Stroke Colar traçado completo Make Symmetry Path Criar demarcador de simetria Disable Symmetry Path Desativar demarcador de simetria -# Color Picker titles Color Picker (Foreground Color) Seletor de cores (Cor de primeiro plano) Color Picker (Background Color) Seletor de cores (Cor de fundo) Pick Color From Image Escolher cor da imagem -# Rasterize prompts This layer must be rasterized before proceeding. Esta camada precisa ser rasterizada antes de continuar. This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Esta camada de texto precisa ser rasterizada antes de continuar. O texto não poderá mais ser editado. Rasterizar o texto? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Esta camada de forma precisa ser rasterizada antes de continuar. Ela não poderá mais ser editada como forma. Rasterizar a forma? This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Este objeto inteligente precisa ser rasterizado antes de continuar. O conteúdo não poderá mais ser editado. Rasterizar o objeto inteligente? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Esta camada de preenchimento precisa ser rasterizada antes de continuar. O conteúdo do preenchimento não poderá mais ser editado. Rasterizar a camada? -# GPU and display status (status bar, System Info) Graphics adapter: {adapter} Adaptador gráfico: {adapter} Backend: {backend} ({type}) Backend: {backend} ({type}) Driver: {driver} Driver: {driver} @@ -4312,7 +4325,6 @@ layerLabel No Color Sem cor previous reading kept; the last re-read failed: {reason} leitura anterior mantida; a última releitura falhou: {reason} The canvas is shown as sRGB. Choose a monitor profile in Edit › Color Settings. A tela de pintura é exibida como sRGB. Escolha um perfil de monitor em Editar › Configurações de cores. The canvas on {display} is shown as sRGB. Choose a monitor profile in Edit › Color Settings. A tela de pintura em {display} é exibida como sRGB. Escolha um perfil de monitor em Editar › Configurações de cores. -# Status messages Nothing to paste: the clipboard holds no image Nada para colar: a área de transferência não contém imagem Opened {url} Aberto: {url} Preferences saved Preferências salvas @@ -4349,7 +4361,6 @@ layerLabel No Color Sem cor This adjustment ({key}) is kept as imported and can't be edited yet. Este ajuste ({key}) é mantido como foi importado e ainda não pode ser editado. {shortcut} assigned. {shortcut} atribuído. {shortcut} is already in use by {commands} and will be removed from it when you click OK. {shortcut} já está em uso por {commands} e será removido de lá quando você clicar em OK. -# Panels and small controls Grid view Visualização em grade List view Visualização em lista New Brush Preset Nova predefinição de pincel @@ -4362,7 +4373,6 @@ layerLabel No Color Sem cor Apply {option}: {state} Aplicar {option}: {state} on ativado off desativado -# Liquify tools (tooltips) Forward Warp Deformação para frente Twirl Clockwise Torcer no sentido horário Twirl Counterclockwise Torcer no sentido anti-horário @@ -4378,28 +4388,11 @@ layerLabel No Color Sem cor Pro Light Pro claro Resize Windows to Fit Redimensionar janelas para caber EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Direção automática do parágrafo Left-to-right paragraph direction Direção do parágrafo da esquerda para a direita Right-to-left paragraph direction Direção do parágrafo da direita para a esquerda Not rendered: this adjustment ({key}) is kept as imported. Não renderizado: este ajuste ({key}) é mantido como foi importado. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Com reconhecimento de cor - Decontaminate Colors Descontaminar cores - Edge Detection Detecção de borda - Global Refinements Refinamentos globais - High Quality Preview Visualização de alta qualidade - Object Aware Com reconhecimento de objeto - Real-Time Refinement Refinamento em tempo real - Refine Edge Brush Tool Ferramenta Pincel de refinamento de borda - Refine Hair Refinar cabelo - Refine Mode Modo de refinamento - Remember Settings Lembrar configurações - View Mode Modo de exibição - Object Aware needs a segmentation model, which isn't available yet Com reconhecimento de objeto requer um modelo de segmentação, ainda não disponível - Refine Hair needs hair detection, which isn't available yet Refinar cabelo requer detecção de cabelo, ainda não disponível -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Cubo de matiz Brightness Cube Cubo de brilho Color Wheel Roda de cores @@ -4415,9 +4408,8 @@ layerLabel No Color Sem cor Grayscale Ramp Rampa de tons de cinza Current Colors Cores atuais Make Ramp Web Safe Tornar rampa segura para a Web - Select and Mask was closed: its document is no longer the active one Selecionar e mascarar foi fechado: o documento dele não está mais ativo - Select and Mask was closed: another layer was selected Selecionar e mascarar foi fechado: outra camada foi selecionada -# Art History Brush (#213). + The path was kept as the Work Path O demarcador foi mantido como demarcador de trabalho + The path was discarded O demarcador foi descartado Art History Brush Tool Ferramenta Pincel do histórico da arte Tight Short Curto cerrado Tight Medium Médio cerrado @@ -4431,3 +4423,20 @@ layerLabel No Color Sem cor Font size presets Predefinições de tamanho da fonte Leading presets Predefinições de entrelinha Tracking presets Predefinições de tracking + Color Aware Com reconhecimento de cor + Decontaminate Colors Descontaminar cores + Edge Detection Detecção de borda + Global Refinements Refinamentos globais + High Quality Preview Visualização de alta qualidade + Object Aware Com reconhecimento de objeto + Real-Time Refinement Refinamento em tempo real + Refine Edge Brush Tool Ferramenta Pincel de refinamento de borda + Refine Hair Refinar cabelo + Refine Mode Modo de refinamento + Remember Settings Lembrar configurações + View Mode Modo de exibição + Object Aware needs a segmentation model, which isn't available yet Com reconhecimento de objeto requer um modelo de segmentação, ainda não disponível + Refine Hair needs hair detection, which isn't available yet Refinar cabelo requer detecção de cabelo, ainda não disponível + Select and Mask was closed: its document is no longer the active one Selecionar e mascarar foi fechado: o documento dele não está mais ativo + Select and Mask was closed: another layer was selected Selecionar e mascarar foi fechado: outra camada foi selecionada + Drag to move the selected path Arraste para mover o demarcador selecionado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c1be00b842..3fc72b0833 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -18,20 +18,213 @@ # the Russian typographic equivalent, with the space the source carries. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Параметры маски… - Layer Mask Display Options… Параметры отображения маски слоя… # Channel Options and New Spot Channel (#3761) - Channel Color Цвет канала - Color Indicates: Цветом обозначены: - Solidity: Плотность: - Ink Characteristics Характеристики краски # Menus # Guide layout dialog # Custom print paper (#3820) + + +# File + +# Edit + +# Image + +# Layer + +# Type + +# Select +# Select and Mask dialog labels + +# Filter +# Field Blur pins (#3373) + +# View + +# Window + +# Help + +# Tools and options bar + +# Panels, dialogs and common widgets + +# Preferences dialog + +# Document and canvas status bar + +# Layers panel + +# Channels panel + +# Color picker and swatches + +# Filters and adjustments dialogs + +# Camera Raw and lens dialogs + +# Adjustments panel + +# History panel + +# Navigator panel + +# Brush Settings panel + +# Tool presets + +# Paragraph and character panels + +# Glyphs panel + +# Paths panel + +# Clone Source panel + +# Timeline panel + +# Info panel + +# Layer Comps panel + +# Analysis and variables + +# Automate + +# Color Settings dialog + +# Themes + +# Workspaces + +# New Document dialog + +# Placeholders, tooltips, status and keyboard hints + +# Transform / warp overlays + +# Vanishing Point + +# Misc dialog strings + +# Blend modes + +# Saved views and other bits + +# Plurals + +# Remaining menu strings (second pass) + +# tl! literals (third pass) +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Preference dialog: generated setting labels and dropdown choices +# Rendering mode and recovery +# Camera Raw: contextual controls and window title + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker + +# Layers-panel trash confirmation +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# History panel › History Brush source (#2966) + +# Dynamic selection context menu and appearance favorites + +# Measurement Log column headers (analysis_cmds::COLUMNS) +# Bevel & Emboss shading controls. +# PhotoCraft release checks. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + + +# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and +# dialog text that other catalogs already carry. Written from the meaning of the English labels +# in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Dynamic command-id, plural, and contextual labels (fourth pass). +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + Mask Options… Параметры маски… + Layer Mask Display Options… Параметры отображения маски слоя… + Channel Color Цвет канала + Color Indicates: Цветом обозначены: + Solidity: Плотность: + Ink Characteristics Характеристики краски Paper Width Ширина бумаги Paper Height Высота бумаги Rows Строки @@ -50,7 +243,6 @@ 5 Columns, 3 Rows 5 столбцов, 3 строки 8 Columns 8 столбцов 12 Columns 12 столбцов - File Файл Edit Редактирование Image Изображение @@ -67,8 +259,6 @@ View Просмотр Window Окно Help Справка - -# File New… Создать… New from Clipboard Создать из буфера обмена New Создать @@ -110,8 +300,6 @@ Save for Web (Legacy)… Сохранить для Web (устаревшее)… Generate Генерировать Image Assets Ресурсы изображений - -# Edit Undo Отменить Redo Повторить Fade… Ослабить… @@ -135,8 +323,6 @@ Define Pattern… Определить паттерн… Define Custom Shape… Определить свою фигуру… Purge Очистить - -# Image Image Size… Размер изображения… Image Size Размер изображения Canvas Size… Размер холста… @@ -175,8 +361,6 @@ Duotone… Дуотон… Duotone Дуотон Trap… Приводка… - -# Layer Layer via Copy Скопировать на новый слой Layer via Cut Вырезать на новый слой Duplicate Layer… Дублировать слой… @@ -273,8 +457,6 @@ Scale Effects… Масштабировать эффекты… New Layer… Новый слой… Delete Layer… Удалить слой… - -# Type Font Шрифт Font Preview Size Размер предпросмотра шрифтов Orientation Ориентация @@ -301,8 +483,6 @@ Load Default Type Styles Загрузить стили текста по умолчанию Save Default Type Styles Сохранить стили текста по умолчанию Type… Текст… - -# Select All Всё Deselect Отменить выделение Reselect Повторить выделение @@ -310,7 +490,6 @@ Inverse Инверсия Color Range… Цветовой диапазон… Select and Mask… Выделение и маска… -# Select and Mask dialog labels Smart Radius Умный радиус Shift Edge Сместить край Decontaminate Очистить @@ -338,8 +517,6 @@ Current Layer Текущий слой Refine Strokes Штрихи уточнения Edits Правки - -# Filter Last Filter Последний фильтр Filter Gallery… Галерея фильтров… Liquify… Пластичность… @@ -350,7 +527,6 @@ Oil Paint… Масляная живопись… Blur Gallery Галерея размытия Field Blur… Размытие по полю… -# Field Blur pins (#3373) No pin selected Булавка не выбрана Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Щелкните изображение, чтобы добавить булавку; перетащите булавку, чтобы переместить ее, или ее кольцо, чтобы изменить размытие. Delete удаляет выбранную булавку. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Перетаскивайте маркеры на контуре, чтобы изменить размер и повернуть его, квадрат — чтобы скруглить углы, а точки внутри — чтобы задать, где начинается размытие. @@ -440,8 +616,6 @@ Mezzotint… Меццотинто… Color Halftone… Цветные полутона… Layer… Слой… - -# View Proof Setup Настройка цветопробы Proof Colors Цветопроба Pixel Aspect Ratio Пиксельное соотношение сторон @@ -488,8 +662,6 @@ Canvas rotation Вращение холста Zoom in Увеличить Zoom out Уменьшить - -# Window Cascade Каскадом Tile Мозаикой 2-up Horizontal Два по горизонтали @@ -538,8 +710,6 @@ 3D 3D Toolbars Панели инструментов Hide All Скрыть все - -# Help About PhotoCraft О программе PhotoCraft PhotoCraft Website Сайт PhotoCraft PhotoCraft on GitHub PhotoCraft на GitHub @@ -547,8 +717,6 @@ ArtCraft Website Сайт ArtCraft Join the ArtCraft Discord… Discord сообщества ArtCraft… System Info… Информация о системе… - -# Tools and options bar Move Перемещение Marquee Область Lasso Лассо @@ -609,8 +777,6 @@ Rotation Поворот Align Выравнивание Aligned Выровнено - -# Panels, dialogs and common widgets OK OK Cancel Отмена Cancel (Esc) Отмена (Esc) @@ -670,8 +836,6 @@ Select Data Points… Выбрать точки данных… Set Measurement Scale… Задать масштаб измерений… Use Measurement Scale Использовать масштаб измерений - -# Preferences dialog Preferences Настройки General… Общие… Interface… Интерфейс… @@ -696,8 +860,6 @@ Thumbnail size (smallest: list) Размер миниатюр (минимальный: список) Reset GPU Backend Сбросить GPU-бэкенд Applies at next launch. Применится при следующем запуске. - -# Document and canvas status bar Untitled Без имени Untitled-1 Без имени-1 Doc: {flat}/{layered} Док: {flat}/{layered} @@ -736,8 +898,6 @@ Both Axes По обеим осям Horizontally По горизонтали Vertically По вертикали - -# Layers panel Layers to Files… Слои в файлы… Duplicate Layers… Дублировать слои… Group name Имя группы @@ -767,8 +927,6 @@ Smart Filter Смарт-фильтр Fill Content Содержимое заливки Adjustment Preview Предпросмотр коррекции - -# Channels panel Channel: Канал: Channel Mixer… Микширование каналов… Output Channel: Выходной канал: @@ -783,8 +941,6 @@ Spot Channel Цветовой канал Mask All Маскировать всё Mask All Objects Маскировать все объекты - -# Color picker and swatches Color Цвет Color: Цвет: Colors Цвета @@ -799,8 +955,6 @@ Overlay Opacity Непрозрачность наложения Glow Color Цвет свечения Web Snap Привязка к web-палитре - -# Filters and adjustments dialogs Brightness Яркость Contrast Контраст Brightness/Contrast… Яркость/Контраст… @@ -861,8 +1015,6 @@ Working Yellow Plate Рабочая жёлтая форма Working Black Plate Рабочая чёрная форма Working Gray Plate Рабочая серая форма - -# Camera Raw and lens dialogs Basic Основные Detail Детализация HSL/Grayscale HSL/Градации серого @@ -959,8 +1111,6 @@ Selected Areas Выделенные области Spot Color Цветовой (spot) канал Color indicates Цвет обозначает - -# Adjustments panel Curves Кривые Levels Уровни Color Balance Цветовой баланс @@ -973,8 +1123,6 @@ Channel Mixer Микширование каналов Gradient Map Градиентная карта Selective Color Выборочная коррекция цвета - -# History panel History Log… Журнал истории… Create Snapshot Создать снимок Delete Snapshot Удалить снимок @@ -989,14 +1137,10 @@ Automatically Create New Snapshot When Saving Автоматически создавать снимок при сохранении Show New Snapshot Dialog by Default По умолчанию показывать диалог нового снимка Clear History Очистить историю - -# Navigator panel Panel Options… Параметры панели… View menu Меню «Просмотр» Keep view in sync Держать обзор синхронным {zoom}% {zoom}% - -# Brush Settings panel Brush name Имя кисти Brush Preview Предпросмотр кисти Brush Tip Shape Форма отпечатка @@ -1082,8 +1226,6 @@ Override Tilt Y Переопределить наклон Y Override Rotation Переопределить поворот Apply the pen's tilt and rotation to the tip shape Применять наклон и поворот пера к форме отпечатка - -# Tool presets Preset Type Тип набора Preset Manager… Управление наборами… Rename Tool Preset… Переименовать набор… @@ -1097,8 +1239,6 @@ Preset: Набор: Preset Набор Presets: Наборы: - -# Paragraph and character panels Font Size: Кегль: Font size Кегль Type: Текст: @@ -1176,8 +1316,6 @@ Indent First Отступ первой строки Center По центру Justify По ширине - -# Glyphs panel Glyph Глиф Select a type layer or click into text to insert glyphs Выберите текстовый слой или щёлкните в текст, чтобы вставить глифы Entire Font Весь шрифт @@ -1197,8 +1335,6 @@ Ordinals Порядковые числительные East Asian Features Восточноазиатские возможности Middle Eastern Features Ближневосточные возможности - -# Paths panel Path Контур Path: Контур: Work Path Рабочий контур @@ -1215,11 +1351,9 @@ Current Path Текущий контур Vector Mask from Current Path Векторная маска из текущего контура Create new shape from the current path Создать новую фигуру из текущего контура - Drag to move the active shape's path or the Work Path Перетащите, чтобы переместить контур активной фигуры или рабочий контур + Drag to move the selected path Перетащите, чтобы переместить выбранный контур Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Щелчок: выбрать узел · Перетаскивание: переместить узел, маркер или сегмент · {shift}-щелчок: добавить · {alt}-щелчок: весь подконтур Draw with the Pen tool (P) or make a work path from a selection. Нарисуйте пером (P) или создайте рабочий контур из выделения. - -# Clone Source panel Source: not set ({key}-click with Clone Stamp) Источник: не задан ({key}-клик штампом) Clone source {n} ({key}-click with Clone Stamp to set) Источник клонирования {n} ({key}-клик штампом, чтобы задать) {key}-click to set the source {key}-клик, чтобы задать источник @@ -1242,8 +1376,6 @@ Frame Sync Синхронизация кадров Quick Sync Быстрая синхронизация Enabled Включено - -# Timeline panel Create Video Timeline Создать видео-шкалу Open a document to use the timeline. Откройте документ, чтобы работать со шкалой времени. Video Layers Видеослои @@ -1285,8 +1417,6 @@ Repeat Повтор Play Once Однократно Video Cache Видеокэш - -# Info panel Info Options… Параметры информации… First Color Readout Первая цветовая проба Second Color Readout Вторая цветовая проба @@ -1309,8 +1439,6 @@ Mouse Coordinates Координаты курсора Ruler Units Единицы линеек Hide Скрыть - -# Layer Comps panel Layer Comps to Files… Варианты слоя в файлы… Apply next selected layer comp Применить следующий выбранный вариант Apply previous selected layer comp Применить предыдущий выбранный вариант @@ -1328,8 +1456,6 @@ Visibility Видимость Position Положение Appearance (Layer Style) Внешний вид (стиль слоя) - -# Analysis and variables Analysis Анализ Variables Переменные Variable Data Sets… Наборы данных переменных… @@ -1410,8 +1536,6 @@ Version {version} Версия {version} Advanced Дополнительно Import… Импортировать… - -# Automate Automate Автоматизация Batch… Пакетная обработка… Create Droplet… Создать модуль-дроплет… @@ -1442,8 +1566,6 @@ Stop For Errors Останавливаться при ошибках Log Errors To File Записывать ошибки в файл Errors Ошибки - -# Color Settings dialog Color Settings… Настройки цвета… Settings Наборы Settings: Наборы: @@ -1472,8 +1594,6 @@ SMPTE C SMPTE C HDTV (Rec. 709) HDTV (Rec. 709) CIE RGB CIE RGB - -# Themes Theme Тема Switch theme Сменить тему Next Theme Следующая тема @@ -1496,8 +1616,6 @@ Pro Medium Gray Theme Средне-серая тема Pro Pro Light Gray Theme Светло-серая тема Pro Pro Light Theme Светлая тема Pro - -# Workspaces Workspace… Рабочая среда… Essentials Основные New Workspace… Новая рабочая среда… @@ -1525,8 +1643,6 @@ Collapse Panel Group Свернуть группу панелей Expand Panel Group Развернуть группу панелей Close Tab Group Закрыть группу вкладок - -# New Document dialog PRESET DETAILS ПАРАМЕТРЫ НАБОРА BLANK DOCUMENT PRESETS ({n}) НАБОРЫ ПУСТЫХ ДОКУМЕНТОВ ({n}) Create a new document or open an existing file. Создайте новый документ или откройте существующий файл. @@ -1573,8 +1689,6 @@ Points Пункты Picas Пики Columns Столбцы - -# Placeholders, tooltips, status and keyboard hints {name} options Параметры: {name} Align {what} Выровнять: {what} Untagged {mode} Без профиля ({mode}) @@ -1751,8 +1865,6 @@ Current Текущий {added}, {removed} subtracted {added}, вычтено {removed} Filter: Фильтр: - -# Transform / warp overlays Free Transform Свободное трансформирование Free Transform a Copy Свободное трансформирование копии Transform Трансформирование @@ -1805,8 +1917,6 @@ Rotate Fixed Фиксированный поворот Adaptive Wide Angle isn't open Адаптивный широкий угол не открыт Liquify is not open Пластичность не открыта - -# Vanishing Point Create Plane Создать плоскость Edit Plane Править плоскость Select Plane Выбрать плоскость @@ -1820,8 +1930,6 @@ Blend Смешивание Brush Size Размер кисти Heal Color Цвет восстановления - -# Misc dialog strings Mask Маска Channel Канал Rectangle Прямоугольник @@ -1845,8 +1953,6 @@ Add to Добавить к Subtract from Вычесть из Intersect with Пересечь с - -# Blend modes Pass Through Пропустить Dissolve Растворение Darken Замена тёмным @@ -1868,19 +1974,13 @@ Difference Разница Exclusion Исключение Luminosity Яркость - -# Saved views and other bits Capture Comp Зафиксировать вариант No Layer Comps Нет вариантов слоя - -# Plurals @plural {n} item|{n} items {n} элемент|{n} элемента|{n} элементов @plural {n} Layer|{n} Layers {n} слой|{n} слоя|{n} слоёв @plural {n} layer|{n} layers {n} слой|{n} слоя|{n} слоёв @plural Group · {n} layer|Group · {n} layers Группа · {n} слой|Группа · {n} слоя|Группа · {n} слоёв @plural {n} sample|{n} samples {n} образец|{n} образца|{n} образцов - -# Remaining menu strings (second pass) 180° 180° 32-bit Preview Options… Параметры предпросмотра 32 бит… 90° Clockwise 90° по часовой стрелке @@ -1977,6 +2077,7 @@ Merge Group Объединить группу Merge Layers Объединить слои Merge Shape Components Объединить компоненты фигуры + Path operations Операции с контурами Merge Visible Свести видимые Stamp Visible Штамп видимых Select Layer Above Выбрать слой выше @@ -2049,8 +2150,6 @@ Video Frames to Layers… Видеокадры в слои… WIA Support… Поддержка WIA… Working CMY Plate Рабочая голубая форма - -# tl! literals (third pass) Absolute Абсолютный Action Операция Adaptive Адаптивный @@ -2277,7 +2376,6 @@ Outside Снаружи Tetrahedral Тетраэдрическая Texture Each Tip Текстура на каждый отпечаток -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Редактор градиентов Gradient picker Выбор градиента Save As Preset Сохранить как набор @@ -2305,8 +2403,6 @@ Whites Белые Yellow Жёлтый Yellow · Blue Жёлтый · Синий - -# Preference dialog: generated setting labels and dropdown choices Adobe Adobe Adobe rgb Adobe RGB Allow agent control Разрешить управление агентами @@ -2531,7 +2627,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: Сетка: -# Rendering mode and recovery Rendering Mode Режим отрисовки Automatic (recommended) Автоматически (рекомендуется) CPU / Compatibility CPU / Совместимость @@ -2558,7 +2653,6 @@ Tone Histogram Тональная гистограмма Show Selected Region Показать выделенную область cameraRaw Light Свет -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Фильтр Camera Raw ({layer}) Camera Raw ({name}) Camera Raw ({name}) Aqua Голубой @@ -2589,14 +2683,10 @@ cameraRaw Roughness Неровность Scale or rotate the moved area, then press {key} Масштабируйте или поверните перемещённую область, затем нажмите {key} Now drag the selection onto another area Теперь перетащите выделение на другую область Edit Type Редактировать текст - - New Style… Новый стиль… Style {name} saved Стиль {name} сохранён - Create new style (from the selected type) Создать стиль (из выделенного текста) Create new style from the selected layer Создать стиль из выделенного слоя - Make Default Сделать по умолчанию Reset to Default Сбросить к значению по умолчанию Full-resolution preview unavailable Полноразмерный предпросмотр недоступен @@ -2625,9 +2715,6 @@ cameraRaw Roughness Неровность Magnetic Lasso Tool Магнитное лассо Frequency Частота Use tablet pressure to change pen width Использовать нажим планшета для изменения ширины пера - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About О программе Contributors Участники Models Модели @@ -2658,8 +2745,6 @@ cameraRaw Roughness Неровность % of all commits % от всех коммитов Lines +/− Строки +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR: {prs}, коммиты: {commits}, строки +{added} / −{deleted} (Δ {delta}), двоичные файлы +{binAdded} / −{binDeleted}, {first} – {last} - -# Swatches panel Create new swatch Создать новый образец New Swatch… Новый образец… New Swatch Group… Новая группа образцов… @@ -2669,13 +2754,12 @@ cameraRaw Roughness Неровность Export Swatches for Exchange… Экспортировать образцы для обмена… Reset Swatches Восстановить образцы Add to Swatches Добавить в образцы -# Layer Style > Blending Options (Advanced Blending) Blend If: Изображение если: + Current Layer: Текущий слой: + Underlying Layer: Нижележащий слой: Channels: Каналы: Knockout Просвечивание Apply At Canvas Bounds Применить эффект на границах холста - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Палитра цветов (Цвет текста) Color Picker ({name}) Палитра цветов ({name}) Color Picker (Fill Color) Палитра цветов (Цвет заливки) @@ -2692,8 +2776,6 @@ cameraRaw Roughness Неровность Show/Hide Panels Показать/скрыть панели Could not open Не удалось открыть {path}: the path is not valid Unicode; rename the file and open it again. {path}: путь не является допустимым Unicode; переименуйте файл и откройте его снова. - -# Fill dialog, layer style contours and Image Size Contents: Содержимое: Custom Pattern: Свой узор: Foreground Color Основной цвет @@ -2721,14 +2803,12 @@ cameraRaw Roughness Неровность Rounded Steps Скруглённые ступени Sawtooth 1 Пила 1 Linear Линейный - Red Eye Tool Инструмент «Красные глаза» Pupil Size Размер зрачка Darken Amount Степень затемнения Click a red pupil to neutralize it Щёлкните по красному зрачку, чтобы убрать блик open source открытый исходный код …and {n} more …и ещё {n} - Eyedroppers: Пипетки: Set Black Point Задать точку чёрного Set Neutral Gray Point Задать нейтральную серую точку @@ -2738,8 +2818,6 @@ cameraRaw Roughness Неровность Black Matte На чёрном фоне White Matte На белом фоне Quick Mask Быстрая маска - -# Layer colour labels. Seafoam Морская пена Indigo Индиго Fuchsia Фуксия @@ -2759,21 +2837,15 @@ fontWeight Bold Жирный fontWeight ExtraBold Сверхжирный fontWeight Black Сверхжирный (Black) fontWeight Italic Курсив - -# Pattern Stamp tool Pattern Stamp Tool Инструмент узорный штамп Impressionist Импрессионист Rotate View Tool Инструмент поворота вида Reset View Сбросить вид Drag around the centre to rotate the view · Shift constrains to 15° Перетащите вокруг центра, чтобы повернуть вид · Shift фиксирует шаг 15° - -# Painting symmetry presets. Dual Axis Две оси Diagonal Диагональная Transform Symmetry Трансформировать симметрию Set painting symmetry options Настроить параметры симметричного рисования - -# Eyedropper Sample Size and Sample (#1649). Point Sample Точечная выборка 3 by 3 Average Среднее 3 × 3 5 by 5 Average Среднее 5 × 5 @@ -2786,15 +2858,12 @@ fontWeight Italic Курсив Current & Below No Adjustments Текущий и ниже без коррекции Show Sampling Ring Показать кольцо выборки Click to sample the foreground colour · {key}-click for background Клик — взять основной цвет · {key}-клик — фоновый цвет - -# Color Picker warnings Out of gamut for printing: click for the nearest printable colour Вне цветового охвата печати: щёлкните, чтобы выбрать ближайший печатаемый цвет Not a web colour: click for the nearest web colour Не веб-цвет: щёлкните, чтобы выбрать ближайший веб-цвет Color to Alpha… Цвет в альфа-канал… Transparency Threshold Порог прозрачности Opacity Threshold Порог непрозрачности PhotoCraft — Screen Color Picker PhotoCraft — Пипетка цвета экрана - Rasterize svg groups deeper than Растеризовать группы SVG глубже этого уровня 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 отключает этот порог; группы SVG с вложенностью более 100 уровней всегда растрируются. Rule of Thirds Правило третей @@ -2808,8 +2877,6 @@ fontWeight Italic Курсив Cycle Orientation Сменить ориентацию Set the overlay options for the Crop tool Задать параметры перекрытия для инструмента «Рамка» Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+щелчок перехватило окружение рабочего стола: оно перемещает окна через Alt+перетаскивание. Назначьте для перемещения окон клавишу Super или зафиксируйте Alt в меню Окно › Клавиши-модификаторы. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Палитра цветов (цвет стиля слоя) Auto Hide Notifications Автоскрытие уведомлений Notification Duration (seconds) Длительность уведомления (секунды) @@ -2879,8 +2946,6 @@ fontWeight Italic Курсив Quick Selection found nothing there Быстрое выделение ничего здесь не нашло Object Selection found nothing there — try a tighter rectangle Выделение объектов ничего здесь не нашло — попробуйте более узкий прямоугольник No subject found — try a rectangle around the object Объект не найден — попробуйте прямоугольник вокруг объекта - -# Layers-panel trash confirmation Delete layer ‘{name}’? Удалить слой «{name}»? Delete {count} layers? {names} Удалить слои ({count})? {names} Delete layer? Удалить слой? @@ -2890,6 +2955,9 @@ fontWeight Italic Курсив Invalid delete command Недопустимая команда удаления Layer deleted, but confirmation preference could not be saved: {error} Слой удалён, но не удалось сохранить настройку подтверждения: {error} Add a layer style Добавить стиль слоя + Move effect up Переместить эффект вверх + Move effect down Переместить эффект вниз + Delete effect Удалить эффект Add a mask (from the selection; {key} inverts) Добавить маску (из выделения; {key} инвертирует) Add an adjustment Добавить коррекцию Add to selection ({key}) Добавить к выделению ({key}) @@ -2964,7 +3032,6 @@ fontWeight Italic Курсив Appearance Settings… Настройки оформления… Add to favorites Добавить в избранное Remove from favorites Удалить из избранного -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Производитель cameraData Model Модель cameraData Date Taken Дата съёмки @@ -2974,7 +3041,6 @@ cameraData ISO Speed Светочувствительность ISO cameraData Focal Length Фокусное расстояние cameraData Focal Length (35 mm) Фокусное расстояние (35 мм) cameraData Lens Объектив -# Shared panel docking Activate Panel Активировать панель Change Panel Group Изменить группу панелей Change Panel Layout Изменить расположение панелей @@ -3014,7 +3080,6 @@ cameraData Lens Объектив Rasterize Layer Style Растрировать стиль слоя Search settings… Поиск настроек… No matching settings Нет подходящих настроек -# Edit › Content-Aware Fill workspace Sampling Brush Tool Кисть области выборки Sampling Area Overlay Наложение области выборки Show Sampling Area Показать область выборки @@ -3032,7 +3097,6 @@ cameraData Lens Объектив Output To Вывод в Duplicate Layer Дубликат слоя Contract Сжать - Animation Options Параметры анимации Entire Document Весь документ Filter Options Параметры фильтра @@ -3050,8 +3114,6 @@ cameraData Lens Объектив Add “copy” to Copied Layers and Groups Добавлять «копия» к дублированным слоям и группам Preview on canvas when reordering layers Предпросмотр на холсте при изменении порядка слоёв Show layer mask badges Показывать значки типов масок слоя - -# Smart Filter editors Blending Options ({filter}) Параметры наложения ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Скрыть эффекты слоя и смарт-фильтры ({key}-клик: все слои) Show the layer's effects and Smart Filters ({key}-click: all layers) Показать эффекты слоя и смарт-фильтры ({key}-клик: все слои) @@ -3084,7 +3146,6 @@ curves Smooth Сгладить Fix the red plane first: its corners must form a convex quad Сначала исправьте красную плоскость: ее углы должны образовывать выпуклый четырехугольник Alt-click a plane to set the clone source Щёлкните плоскость с Alt, чтобы задать источник клонирования Too many clone strokes: apply Vanishing Point first Слишком много мазков клонирования: сначала примените «Точку схода» -# Select and Mask view modes (#1754) Onion Skin Калька Marching Ants Бегущие муравьи On Black На черном @@ -3093,7 +3154,6 @@ curves Smooth Сгладить Show Edge Показать край Show Original Показать исходное F cycles the views; hold X to see the image F переключает виды; удерживайте X, чтобы увидеть изображение -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Кисть уточнения края (R) Expand Detection Area Расширить область обнаружения Restore Original Edge Восстановить исходный край @@ -3107,19 +3167,13 @@ curves Smooth Сгладить Enter a name for the crop preset Введите имя набора параметров кадрирования There is no crop size or ratio to save Нет размера или соотношения сторон кадрирования для сохранения Presentation Представление - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Щёлкните, чтобы разместить · Alt-щелчок или перетаскивание за пределы холста для удаления No document open Документ не открыт {n} of {max} sample points {n} из {max} точек замера - -# History panel menu (#2966) New Snapshot… Новый снимок… History Options… Параметры истории… -# History panel › History Options… (#2966) Allow Non-Linear History Разрешить нелинейную историю Make Layer Visibility Changes Undoable Разрешить отмену изменений видимости слоёв -# Print dialog (#2697) Emulsion Down Эмульсией вниз Functions Функции Print Resolution: Разрешение печати: @@ -3131,7 +3185,6 @@ curves Smooth Сгладить Apply mask to layer before removing? Применить маску к слою перед удалением? The layer or its mask changed. Drag the mask onto the Trash again. Слой или его маска изменились. Перетащите маску в корзину ещё раз. Delete the vector mask? Удалить векторную маску? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} Экспортирован {n} образец в {file}|Экспортированы {n} образца в {file}|Экспортировано {n} образцов в {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} Импортирована {n} кисть из {group}|Импортированы {n} кисти из {group}|Импортировано {n} кистей из {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} Импортирован {n} образец из {file}|Импортированы {n} образца из {file}|Импортировано {n} образцов из {file} @@ -3146,7 +3199,6 @@ curves Smooth Сгладить @plural {n} step|{n} steps {n} шаг|{n} шага|{n} шагов @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (и ещё {n} предупреждение о наборах кистей)|{warning} (и ещё {n} предупреждения о наборах кистей)|{warning} (и ещё {n} предупреждений о наборах кистей) @plural {what} with {n} warning|{what} with {n} warnings {what}: {n} предупреждение|{what}: {n} предупреждения|{what}: {n} предупреждений -# View › Guides › New Guide… › Color Light Blue Светло-синий Light Red Светло-красный Medium Blue Средне-синий @@ -3167,8 +3219,6 @@ curves Smooth Сгладить Clear Brush Controls Очистить параметры кисти Reset All Locked Settings Сбросить все заблокированные параметры Copy Texture to Other Tools Скопировать текстуру в другие инструменты - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Загрузить операции… Save Actions… Сохранить операции… New Action… Новая операция… @@ -3180,10 +3230,8 @@ curves Smooth Сгладить @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} шаг пока не имеет эквивалента в PhotoCraft|{n} шага пока не имеют эквивалента в PhotoCraft|{n} шагов пока не имеют эквивалента в PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Сохранена {n} операция в {file}|Сохранены {n} операции в {file}|Сохранено {n} операций в {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Пропущен {n} шаг без эквивалента в Photoshop|Пропущены {n} шага без эквивалента в Photoshop|Пропущено {n} шагов без эквивалента в Photoshop - File Naming Именование файлов Starting serial Начальный порядковый номер -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Вставить остановку… Save Set… Сохранить набор… Message: Сообщение: @@ -3195,11 +3243,8 @@ curves Smooth Сгладить @plural {n} action|{n} actions {n} операция|{n} операции|{n} операций Background (Default) Фон (по умолчанию) Content-Aware Fill Заливка с учётом содержимого -# Batch / Image Processor Include All Subfolders Включить все вложенные папки Auto Add/Delete Автодобавление/удаление - -# 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… Не забудьте отключить управление цветом самого принтера в параметрах печати… @@ -3217,16 +3262,11 @@ curves Smooth Сгладить Could not write {name}: {error} Не удалось записать {name}: {error} Kept {name}: written by another application {name} сохранён без изменений: записан другим приложением Shadow Tint Оттенок теней -# History panel › History Brush source (#2966) Paints from the History panel's source state Рисует из исходного состояния панели «История» Sets the source for the history brush Задаёт источник для кисти истории - -# Dynamic selection context menu and appearance favorites Select Inverse Инвертировать выделение Pro (Light) Pro (светлая) Pro (Light Gray) Pro (светло-серая) - -# Measurement Log column headers (analysis_cmds::COLUMNS) Label Метка Date and Time Дата и время Scale Units Единицы масштаба @@ -3267,14 +3307,12 @@ curves Smooth Сгладить Slab Serif С брусковыми засечками TrueType font Шрифт TrueType Variable font Вариативный шрифт -# Bevel & Emboss shading controls. Highlight Mode Режим светлых тонов Highlight Color Цвет светлых тонов Highlight Opacity Непрозрачность светлых тонов Shadow Mode Режим теней Shadow Color Цвет теней Shadow Opacity Непрозрачность теней -# PhotoCraft release checks. Check for Updates… Проверить обновления… PhotoCraft Updates Обновления PhotoCraft Checking for updates… Проверка обновлений… @@ -3287,25 +3325,19 @@ curves Smooth Сгладить Automatically Check for Updates Автоматически проверять обновления Installed version: {version} Установленная версия: {version} PhotoCraft {version} is available. Доступна версия PhotoCraft {version}. -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Использовать встроенный профиль ({profile}) Convert to the working space ({profile}) Преобразовать в рабочее пространство ({profile}) Remember this choice for future images Запомнить этот выбор для следующих изображений Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Снова включить вопрос можно параметром Ask On Mismatch в Редактирование › Настройки цвета. Button Mode Режим кнопок Button Mode On Режим кнопок включён - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Сделать интерфейс темнее Lighten Interface Сделать интерфейс светлее -# Bevel & Emboss Technique. Technique Метод Chisel Hard Жесткая огранка Chisel Soft Мягкая огранка Open color-less EXR as ACEScg Открывать EXR без цветового профиля как ACEScg Do not append "copy" to filename when saving a copy Не добавлять «copy» к имени файла при сохранении копии - -# View › Guides › right-click a guide Edit Selected Guides Изменить выбранные направляющие Clear Selected Guides Удалить выбранные направляющие Bicubic Automatic Бикубическая, автоматически @@ -3331,8 +3363,6 @@ curves Smooth Сгладить {set} (modified) {set} (изменён) Random Случайно Show file name in title Показывать имя файла в заголовке - -# Image › Mode › Bitmap (#5559) 50% Threshold Порог 50% Pattern Dither Регулярный дизеринг Diffusion Dither Диффузионный дизеринг @@ -3352,10 +3382,8 @@ curves Smooth Сгладить Undo Changes Отменить изменения {shortcut} is reserved by the system and can't be assigned. Комбинация {shortcut} зарезервирована системой и не может быть назначена. Low-Latency Drawing (vsync off, applies at next launch) Рисование с малой задержкой (без вертикальной синхронизации, после перезапуска) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Свободное трансформирование ещё применяется; повторите попытку, когда оно завершится. The transform couldn't be applied. Не удалось применить трансформирование. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Слоям нужно {needed} памяти GPU; бюджет оставляет им {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Задайте «Память GPU» в разделе Настройки › Производительность по объёму, который вмещает ваша видеокарта, не больше 3/8 её памяти. «Автоматически» следует параметру «Память», в пределах четверти памяти этого компьютера и 3/8 памяти видеокарты, и не учитывает документ на видеокарте с известным объёмом памяти. Пока слои не помещаются, в строке состояния показано «Память GPU заполнена». GPU Memory Full Память GPU заполнена @@ -3369,12 +3397,6 @@ curves Smooth Сгладить Replace Заменить {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. Замените его этим документом или отмените и используйте Файл › Сохранить как, чтобы сохранить оба. - - -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, -# lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and -# dialog text that other catalogs already carry. Written from the meaning of the English labels -# in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. (coming soon) (скоро) (none) (нет) 32-bit Preview Options Параметры предпросмотра 32 бит @@ -3837,7 +3859,6 @@ curves Smooth Сгладить Hearts Сердца Heptagon Семиугольник Hexagon Шестиугольник - Hidden Скрыто Hide Grid Скрыть сетку Hide Others Скрыть остальные Hide the layer's effects (⌥-click: all layers) Скрыть эффекты слоя (⌥+щелчок: все слои) @@ -3883,8 +3904,6 @@ curves Smooth Сгладить The fastest and the softest, with colour fringing on fine detail. Самый быстрый и самый мягкий, с цветной каймой на мелких деталях. “{name}” already exists. Replace it? «{name}» уже существует. Заменить? The name in the save dialog was “{name}”. В окне сохранения было указано имя «{name}». - Move Up Переместить вверх - Move Down Переместить вниз Previous Brush Предыдущая кисть Next Brush Следующая кисть First Brush Первая кисть @@ -3900,27 +3919,18 @@ curves Smooth Сгладить Use Использовать In Front Спереди Behind Сзади - -# DDS Options (#1327) DDS Options Параметры DDS Compression Сжатие Generate Mipmaps Создать MIP-карты - -# Color Table (.act) dialog There is no color table to save. Нет таблицы цветов для сохранения. @plural Saved {n} color to {file}|Saved {n} colors to {file} Сохранён {n} цвет в {file}|Сохранены {n} цвета в {file}|Сохранено {n} цветов в {file} - -# Graphics Adapter preference (#1885) GPU adapter Адаптер GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Импортировать стили… Export Selected Styles… Экспортировать выбранные стили… Export Styles… Экспортировать стили… {file} is not a style library (.asl) {file} не является библиотекой стилей (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Импортирован {n} стиль из {file}|Импортировано {n} стиля из {file}|Импортировано {n} стилей из {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Экспортирован {n} стиль в {file}|Экспортировано {n} стиля в {file}|Экспортировано {n} стилей в {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Сначала подтвердите или отмените открытый диалог шага операции Pro Medium Gray Средне-серая Pro Solarized Solarized @@ -4495,7 +4505,6 @@ curves Smooth Сгладить Type Options Параметры текста Unaltered Без изменений Undefined Areas Неопределённые области - Underlying Layer: Нижележащий слой: Underpainting Подмалёвок Underwater Под водой Ungroup Разгруппировать @@ -4605,7 +4614,6 @@ curves Smooth Сгладить ↑↓ navigate ↵ run esc close ↑↓ навигация ↵ выполнить esc закрыть ✓ Color Indicates Masked Areas ✓ Цветом обозначены маскированные области ✓ Color Indicates Selected Areas ✓ Цветом обозначены выделенные области -# Dynamic command-id, plural, and contextual labels (fourth pass). @id edit.clear Очистить @id edit.purge.undo Данные отмены @id edit.stroke Обвести… @@ -4651,28 +4659,11 @@ layers Fill Заливка layers Fill: Заливка: navigator Zoom Масштаб shape Appearance Оформление -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Автоматическое направление абзаца Left-to-right paragraph direction Направление абзаца слева направо Right-to-left paragraph direction Направление абзаца справа налево Not rendered: this adjustment ({key}) is kept as imported. Не отображается: эта коррекция ({key}) сохранена как при импорте. -# Print preview image (#8236) Print preview image Print preview image - Color Aware С учетом цвета - Decontaminate Colors Очистить цвета - Edge Detection Обнаружение краев - Global Refinements Глобальное уточнение - High Quality Preview Высококачественный просмотр - Object Aware С учетом объектов - Real-Time Refinement Уточнение в реальном времени - Refine Edge Brush Tool Инструмент «Кисть уточнения края» - Refine Hair Уточнить волосы - Refine Mode Режим уточнения - Remember Settings Запомнить параметры - View Mode Режим просмотра - Object Aware needs a segmentation model, which isn't available yet Для режима «С учетом объектов» нужна модель сегментации, которая пока недоступна - Refine Hair needs hair detection, which isn't available yet Для уточнения волос нужно распознавание волос, которое пока недоступно -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Куб цветового тона Brightness Cube Куб яркости Color Wheel Цветовой круг @@ -4688,9 +4679,8 @@ shape Appearance Оформление Grayscale Ramp Шкала градаций серого Current Colors Текущие цвета Make Ramp Web Safe Сделать шкалу безопасной для web - Select and Mask was closed: its document is no longer the active one Окно «Выделение и маска» закрыто: его документ больше не активен - Select and Mask was closed: another layer was selected Окно «Выделение и маска» закрыто: выбран другой слой -# Art History Brush (#213). + The path was kept as the Work Path Контур сохранён как рабочий контур + The path was discarded Контур удалён Art History Brush Tool Инструмент «Кисть истории искусств» Tight Short Плотный короткий Tight Medium Плотный средний @@ -4704,3 +4694,19 @@ shape Appearance Оформление Font size presets Наборы размеров шрифта Leading presets Наборы интерлиньяжа Tracking presets Наборы трекинга + Color Aware С учетом цвета + Decontaminate Colors Очистить цвета + Edge Detection Обнаружение краев + Global Refinements Глобальное уточнение + High Quality Preview Высококачественный просмотр + Object Aware С учетом объектов + Real-Time Refinement Уточнение в реальном времени + Refine Edge Brush Tool Инструмент «Кисть уточнения края» + Refine Hair Уточнить волосы + Refine Mode Режим уточнения + Remember Settings Запомнить параметры + View Mode Режим просмотра + Object Aware needs a segmentation model, which isn't available yet Для режима «С учетом объектов» нужна модель сегментации, которая пока недоступна + Refine Hair needs hair detection, which isn't available yet Для уточнения волос нужно распознавание волос, которое пока недоступно + Select and Mask was closed: its document is no longer the active one Окно «Выделение и маска» закрыто: его документ больше не активен + Select and Mask was closed: another layer was selected Окно «Выделение и маска» закрыто: выбран другой слой diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 94ac9b7f2b..e29bb41dca 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -23,6 +23,136 @@ # out of noun agreement ("Broj: {n}", "slojeva: {n}") so every number reads correctly. # Guide layout dialog + +# Select and Mask dialog labels + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Copy transforms, layer navigation and cancellable opening (from PR #582 by neko233-com). + +# Labels added on main after this catalog (depth labels, Wayland drop, profiles, rendering mode) + +# Camera Raw scopes and the Patch tool + +# Warp grid presets (#388) + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Camera Raw: contextual controls and window title + +# Counted status messages and labels (Serbian: one | few | many) + +# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) + +# Path, channel, layer style, status and System Info labels the Czech catalog added + +# Command-id overrides where the plain key is also a dialog button + +# Layer colour labels distinct from channel and ink names + + +# Character, Paragraph and Glyphs panels + + +# Camera Raw labels + +# Keyboard Shortcuts and Menus editor + +# Color Settings dialog + + +# Camera Raw chrome, tone, curve, color mixer, grading, detail and effects + +# New Document, Home and Image Size + +# Warp, Liquify, Perspective and Puppet + +# Contextual labels + +# Added on merge with main (spelling, Camera Raw settings files, printing, Object Finder, brush +# controls, actions, gradient presets, Pen Auto Add/Delete) + +# Native Windows printing qualification +# Custom print paper (#3820) + +# ICO dimensions + +# Layer Mask Display Options (the layer mask rubylith's colour and opacity) + +# Channel Options and New Spot Channel (#3761) + +# Bevel & Emboss shading controls. +# Edit › Content-Aware Fill workspace +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + + +# Image › Mode › Bitmap (#5559) + +# Layers panel options + +# Smart Filter editors +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# PhotoCraft release checks. +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). +# Smart Filter row actions (#1265). + Rows Redovi Number Broj Margin Margina @@ -39,7 +169,6 @@ 5 Columns, 3 Rows 5 kolona, 3 reda 8 Columns 8 kolona 12 Columns 12 kolona - File Datoteka Edit Uređivanje Image Slika @@ -427,6 +556,7 @@ Intersect Shape Areas Presek oblasti oblika Exclude Overlapping Shapes Isključi preklapajuće oblike Merge Shape Components Spoji komponente oblika + Path operations Operacije s putanjama Align Poravnaj Top Edges Gornje ivice Vertical Centers Vertikalni centri @@ -506,7 +636,6 @@ Color Range… Opseg boja… Focus Area… Oblast fokusa… Select and Mask… Izaberi i maskiraj… -# Select and Mask dialog labels Smart Radius Pametni poluprečnik Shift Edge Pomeri ivicu Decontaminate Očisti boje @@ -813,6 +942,9 @@ Intersect Mask with Selection Presek maske i selekcije Add Stop Dodaj tačku Add a layer style Dodaj stil sloja + Move effect up Pomeri efekat nagore + Move effect down Pomeri efekat nadole + Delete effect Obriši efekat Add a mask (from the selection; {key} inverts) Dodaj masku (iz selekcije; {key} invertuje) Add an adjustment Dodaj korekciju Add disk Dodaj disk @@ -1024,8 +1156,6 @@ Delete current channel Obriši tekući kanal Delete current state Obriši tekuće stanje Delete effect layer Obriši sloj efekta - -# Layers-panel trash confirmation Delete layer ‘{name}’? Obrisati sloj „{name}“? Delete {count} layers? {names} Obrisati izabrane slojeve ({count})? {names} Delete layer? Obrisati sloj? @@ -1034,7 +1164,6 @@ Missing delete command Nedostaje komanda za brisanje Invalid delete command Neispravna komanda za brisanje Layer deleted, but confirmation preference could not be saved: {error} Sloj je obrisan, ali podešavanje potvrde nije moglo da se sačuva: {error} - Delete layer Obriši sloj Delete layer comp Obriši kompoziciju slojeva Delete note Obriši belešku @@ -2123,7 +2252,6 @@ Align with layer Poravnaj sa slojem Reset Alignment Resetuj poravnanje Centre the gradient (offset 0, 0) Centriraj gradijent (pomak 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Uređivač gradijenta Gradient picker Birač gradijenta Save As Preset Sačuvaj kao šablon @@ -2641,8 +2769,6 @@ Expand group (⌥-click: all groups) Proširi grupu (⌥-klik: sve grupe) Hide the layer's effects (⌥-click: all layers) Sakrij efekte sloja (⌥-klik: svi slojevi) Show the layer's effects (⌥-click: all layers) Prikaži efekte sloja (⌥-klik: svi slojevi) - -# Copy transforms, layer navigation and cancellable opening (from PR #582 by neko233-com). New from Clipboard Novo iz ostave Free Transform a Copy Slobodna transformacija kopije Transform Again on a Copy Ponovi transformaciju na kopiji @@ -2652,8 +2778,6 @@ Select Bottom Layer Izaberi donji sloj Add Layer Above to Selection Dodaj sloj iznad u izbor Add Layer Below to Selection Dodaj sloj ispod u izbor - -# Labels added on main after this catalog (depth labels, Wayland drop, profiles, rendering mode) 8 bit 8 bita Integer Celobrojno 16 bit 16 bita @@ -2689,8 +2813,6 @@ GPU Backend GPU pozadinski sistem Details Detalji Rendering mode Režim renderovanja - -# Camera Raw scopes and the Patch tool Shadow Clipping Warning (U) Upozorenje o odsecanju senki (U) Highlight Clipping Warning (O) Upozorenje o odsecanju svetla (O) Show Lab Color Readouts Prikaži Lab očitavanja boja @@ -2715,20 +2837,15 @@ cameraRaw Blending Stapanje Transform On Drop Transformiši pri otpuštanju Scale or rotate the moved area, then press {key} Skalirajte ili rotirajte pomerenu oblast, a zatim pritisnite {key} Now drag the selection onto another area Sada prevucite selekciju na drugu oblast - -# Warp grid presets (#388) 3 x 3 3 x 3 4 x 4 4 x 4 5 x 5 5 x 5 Grid: Mreža: Edit Type Uredi tekst - New Style… Novi stil… Style {name} saved Stil {name} je sačuvan - Create new style (from the selected type) Napravi novi stil (od izabranog teksta) Create new style from the selected layer Napravi novi stil od izabranog sloja - Make Default Postavi kao podrazumevano Reset to Default Vrati na podrazumevano Full-resolution preview unavailable Pregled u punoj rezoluciji nije dostupan @@ -2757,8 +2874,6 @@ cameraRaw Blending Stapanje Magnetic Lasso Tool Alatka magnetni laso Frequency Frekvencija Use tablet pressure to change pen width Koristi pritisak na tabletu za promenu širine pera - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About O programu Contributors Saradnici Models Modeli @@ -2789,8 +2904,6 @@ cameraRaw Blending Stapanje % of all commits % svih komitova Lines +/− Linije +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR-ova: {prs}, komitova: {commits}, linija: +{added} / −{deleted} (Δ {delta}), binarnih resursa: +{binAdded} / −{binDeleted}, {first} – {last} - -# Swatches panel Create new swatch Napravi novi uzorak boje New Swatch… Novi uzorak boje… New Swatch Group… Nova grupa uzoraka boja… @@ -2800,13 +2913,10 @@ cameraRaw Blending Stapanje Export Swatches for Exchange… Izvezi uzorke boja za razmenu… Reset Swatches Resetuj uzorke boja Add to Swatches Dodaj u uzorke boja -# Layer Style > Blending Options (Advanced Blending) Blend If: Stapaj ako: Channels: Kanali: Knockout Izbijanje Apply At Canvas Bounds Primeni na granicama platna - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Birač boja (boja teksta) Color Picker ({name}) Birač boja ({name}) Color Picker (Fill Color) Birač boja (boja popune) @@ -2822,8 +2932,6 @@ cameraRaw Blending Stapanje Show/Hide Panels Prikaži/sakrij panele Could not open Otvaranje nije uspelo {path}: the path is not valid Unicode; rename the file and open it again. {path}: putanja nije ispravan Unicode; preimenujte datoteku i ponovo je otvorite. - -# Fill dialog, layer style contours and Image Size Contents: Sadržaj: Custom Pattern: Prilagođena šara: Foreground Color Boja prednjeg plana @@ -2850,14 +2958,12 @@ cameraRaw Blending Stapanje Rolling Slope - Descending Talasasta kosina - opadajuća Rounded Steps Zaobljeni stepenici Sawtooth 1 Testera 1 - Red Eye Tool Alatka za crvene oči Pupil Size Veličina zenice Darken Amount Količina zatamnjenja Click a red pupil to neutralize it Kliknite crvenu zenicu da je neutrališete open source otvoreni kod …and {n} more …i još {n} - Eyedroppers: Pipete: Set Black Point Postavi crnu tačku Set Neutral Gray Point Postavi tačku neutralne sive @@ -2866,8 +2972,6 @@ cameraRaw Blending Stapanje Selection Preview: Pregled selekcije: Black Matte Crna podloga White Matte Bela podloga - -# Layer colour labels. Seafoam Morska pena Indigo Indigo Fuchsia Fuksija @@ -2886,20 +2990,14 @@ fontWeight Bold Podebljano fontWeight ExtraBold Ekstra podebljano fontWeight Black Crno fontWeight Italic Kurziv - -# Pattern Stamp tool Pattern Stamp Tool Alatka pečat za šaru 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° - -# Painting symmetry presets. Dual Axis Dvostruka osa Diagonal Dijagonala Transform Symmetry Transformiši simetriju - -# Eyedropper Sample Size and Sample (#1649). Point Sample Uzorak tačke 3 by 3 Average Prosek 3 x 3 5 by 5 Average Prosek 5 x 5 @@ -2911,15 +3009,12 @@ 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 - -# Color Picker warnings 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 Color to Alpha… Boja u alfu… Transparency Threshold Prag providnosti Opacity Threshold Prag neprozirnosti PhotoCraft — Screen Color Picker PhotoCraft — birač boja sa ekrana - Rasterize svg groups deeper than Rasterizuj SVG grupe dublje od 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 isključuje ovaj prag; SVG grupe ugnežđene dublje od 100 nivoa uvek se rasterizuju. Rule of Thirds Pravilo trećina @@ -2933,8 +3028,6 @@ fontWeight Italic Kurziv Cycle Orientation Smenjuj orijentaciju Set the overlay options for the Crop tool Podesi opcije preklopa za alatku za opsecanje Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-klik je preuzelo radno okruženje, koje pomera prozore Alt-prevlačenjem. Postavite taster za pomeranje prozora u njemu na Super ili zaključajte Alt u Prozor › Modifikatorski tasteri. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Birač boja (boja stila sloja) Auto Hide Notifications Automatski sakrij obaveštenja Notification Duration (seconds) Trajanje obaveštenja (sekunde) @@ -3011,7 +3104,6 @@ fontWeight Italic Kurziv Appearance Settings… Podešavanja izgleda… Add to favorites Dodaj u omiljene Remove from favorites Ukloni iz omiljenih -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Proizvođač cameraData Model Model cameraData Date Taken Datum snimanja @@ -3021,7 +3113,6 @@ cameraData ISO Speed ISO osetljivost cameraData Focal Length Žižna daljina cameraData Focal Length (35 mm) Žižna daljina (35 mm) cameraData Lens Objektiv -# Shared panel docking Activate Panel Aktiviraj panel Change Panel Group Promeni grupu panela Change Panel Layout Promeni raspored panela @@ -3090,7 +3181,6 @@ curves Smooth Izgladi Fix the red plane first: its corners must form a convex quad Prvo ispravite crvenu ravan: njeni uglovi moraju činiti konveksan četvorougao Alt-click a plane to set the clone source Alt-kliknite ravan da postavite izvor kloniranja Too many clone strokes: apply Vanishing Point first Previše poteza kloniranja: prvo primenite tačku nestajanja -# Select and Mask view modes (#1754) Onion Skin Prozirni prikaz Marching Ants Pokretne crtice On Black Na crnoj @@ -3099,19 +3189,15 @@ curves Smooth Izgladi Show Edge Prikaži ivicu Show Original Prikaži original F cycles the views; hold X to see the image F smenjuje prikaze; držite X da vidite sliku -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Četkica za doterivanje ivice (R) Expand Detection Area Proširi oblast detekcije Restore Original Edge Vrati originalnu ivicu Paint over hair or fur on the image; Alt paints the other mode Slikajte preko kose ili krzna na slici; Alt slika u drugom režimu Clear Brush Strokes Obriši poteze četkicom Show rulers Prikaži lenjire - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Kliknite da postavite · Alt-klik ili prevlačenje van platna da uklonite No document open Nijedan dokument nije otvoren {n} of {max} sample points {n} od {max} tačaka uzorkovanja -# Print dialog (#2697) Emulsion Down Emulzija nadole Functions Funkcije Print Resolution: Rezolucija štampe: @@ -3123,7 +3209,6 @@ curves Smooth Izgladi Apply mask to layer before removing? Primeniti masku na sloj pre uklanjanja? The layer or its mask changed. Drag the mask onto the Trash again. Sloj ili njegova maska su se promenili. Ponovo prevucite masku u kantu. Delete the vector mask? Obrisati vektorsku masku? -# View › Guides › New Guide… › Color Light Blue Svetloplava Light Red Svetlocrvena Medium Blue Srednje plava @@ -3137,11 +3222,7 @@ curves Smooth Izgladi Delete Contour Obriši konturu Loaded contours from {file} Konture učitane iz {file} Saved contours to {file} Konture sačuvane u {file} - -# Gradient Editor window, opened from the options bar's gradient swatch. The current gradient (pick one in Window › Gradients) Tekući gradijent (izaberite ga u Prozor › Gradijenti) - -# Camera Raw: contextual controls and window title cameraRaw Red Crvena cameraRaw Orange Narandžasta cameraRaw Yellow Žuta @@ -3151,8 +3232,6 @@ cameraRaw Blue Plava cameraRaw Purple Ljubičasta cameraRaw Magenta Magenta cameraRaw Temperature Temperatura - -# Counted status messages and labels (Serbian: one | few | many) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} Izvezen je {n} uzorak boje u {file}|Izvezena su {n} uzorka boja u {file}|Izvezeno je {n} uzoraka boja u {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} Uvezena je {n} četkica iz {group}|Uvezene su {n} četkice iz {group}|Uvezeno je {n} četkica iz {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} Uvezen je {n} uzorak boje iz {file}|Uvezena su {n} uzorka boja iz {file}|Uvezeno je {n} uzoraka boja iz {file} @@ -3167,8 +3246,6 @@ cameraRaw Temperature Temperatura @plural {n} step|{n} steps {n} korak|{n} koraka|{n} koraka @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+ još {n} upozorenje za šablone četkica)|{warning} (+ još {n} upozorenja za šablone četkica)|{warning} (+ još {n} upozorenja za šablone četkica) @plural {what} with {n} warning|{what} with {n} warnings {what} sa {n} upozorenjem|{what} sa {n} upozorenja|{what} sa {n} upozorenja - -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) @id edit.stroke Ocrtaj… @id edit.transform.scale Skaliranje cameraRaw Luminance Luminansa @@ -3949,8 +4026,6 @@ layerLabel No Color Bez boje Set Colors Postavi boje Switch Foreground and Background Colors Zameni boje prednjeg plana i pozadine Target Cilj - -# Path, channel, layer style, status and System Info labels the Czech catalog added Make Work Path… Napravi radnu putanju… Create Vector Mask Napravi vektorsku masku Make Selection… Napravi selekciju… @@ -3993,7 +4068,7 @@ layerLabel No Color Bez boje Layer Mask Hides Effects Maska sloja skriva efekte Vector Mask Hides Effects Vektorska maska skriva efekte General Blending Opšte stapanje - This Layer: Ovaj sloj: + Current Layer: Tekući sloj: Underlying Layer: Sloj ispod: Nothing to paste: the clipboard holds no image Nema šta da se nalepi: u ostavi nema slike Preferences saved Podešavanja su sačuvana @@ -4099,20 +4174,13 @@ navigator Zoom Uvećanje {index} of {total} {index} od {total} {shortcut} assigned. {shortcut} je dodeljena. {shortcut} is already in use by {commands} and will be removed from it when you click OK. {shortcut} već koristi {commands} i biće uklonjena odatle kada kliknete U redu. - -# Command-id overrides where the plain key is also a dialog button @id file.close Zatvori @id layer.layerMask.apply Primeni @id edit.clear Obriši - -# Layer colour labels distinct from channel and ink names layerLabel Red Crvena layerLabel Magenta Magenta - Drag: draw freehand · Release on the start point: close Prevlačenje: crtanje slobodnom rukom · Otpuštanje na početnoj tački: zatvori Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · {commit} commits · Esc cancels Prevucite okvir za opsecanje · prevlačenje unutra pomera · ivice menjaju veličinu ({ratio} odnos, {centre} centar) · razmaknica pomera tokom crtanja · {commit} potvrđuje · Esc otkazuje - -# Character, Paragraph and Glyphs panels Kerning: Metrics, Optical or a value in 1/1000 em (Alt+←/→ at the caret) Kerning: metrički, optički ili vrednost u 1/1000 em (Alt+←/→ kod kursora) Basic Latin Osnovna latinica Latin 1 Latinica 1 @@ -4124,14 +4192,9 @@ layerLabel Magenta Magenta Currency Valute Math Symbols Matematički simboli Arrows Strelice - Save Path Sačuvaj putanju - -# Camera Raw labels cameraRaw Highlights Svetla cameraRaw Shadows Senke - -# Keyboard Shortcuts and Menus editor All shortcuts reset to Photoshop defaults. Sve prečice su vraćene na podrazumevane vrednosti Photoshop-a. Temporary Privremeno none nijedna @@ -4142,8 +4205,6 @@ cameraRaw Shadows Senke blue plava violet ljubičasta gray siva - -# Color Settings dialog Working Rgb Radni RGB Working Cmyk Radni CMYK Working Gray Radna siva @@ -4166,10 +4227,7 @@ cameraRaw Shadows Senke Coated-cmyk Premazani CMYK Sgray sGray Gray-gamma-2.2 Siva gama 2.2 - Import Photoshop brushes (.abr) Uvezi Photoshop četkice (.abr) - -# Camera Raw chrome, tone, curve, color mixer, grading, detail and effects cameraRaw Effects Efekti cameraRaw Exposure Ekspozicija cameraRaw Contrast Kontrast @@ -4187,12 +4245,8 @@ cameraRaw Feather Omekšavanje cameraRaw Midpoint Središte cameraRaw Roundness Zaobljenost cameraRaw Size Veličina - -# New Document, Home and Image Size Default Photoshop Size Podrazumevana Photoshop veličina document Orientation Orijentacija - -# Warp, Liquify, Perspective and Puppet Arc Lower Donji luk Arc Upper Gornji luk Forward Warp Guranje napred @@ -4206,15 +4260,10 @@ document Orientation Orijentacija Freeze Lasso Laso za zamrzavanje Reconstruct All Rekonstruiši sve Mask None Bez maske - -# Contextual labels colorRange Invert Invertuj layers Fill Popuna layers Fill: Popuna: shape Appearance Izgled - -# Added on merge with main (spelling, Camera Raw settings files, printing, Object Finder, brush -# controls, actions, gradient presets, Pen Auto Add/Delete) Add to Dictionary Dodaj u rečnik No Spelling Suggestions Nema predloga za pravopis Save Settings… Sačuvaj podešavanja… @@ -4256,25 +4305,16 @@ shape Appearance Izgled Import .GRD Uvezi .GRD Choose a gradient file (.grd). Izaberite datoteku gradijenta (.grd). Auto Add/Delete Automatsko dodavanje/brisanje - -# Native Windows printing qualification 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… Sent to {printer} Poslato na {printer} set in Print Settings… podešava se u podešavanjima štampanja… -# Custom print paper (#3820) Paper Width Širina papira Paper Height Visina papira - -# ICO dimensions ICO is limited to 256 × 256 pixels ICO je ograničen na 256 × 256 piksela - -# Layer Mask Display Options (the layer mask rubylith's colour and opacity) Mask Options… Opcije maske… Layer Mask Display Options… Opcije prikaza maske sloja… - -# Channel Options and New Spot Channel (#3761) Channel Color Boja kanala Color Indicates: Boja označava: Ink Characteristics Karakteristike mastila @@ -4318,15 +4358,12 @@ shape Appearance Izgled Slab Serif Плочасти серифи TrueType font TrueType фонт Variable font Варијабилни фонт - -# Bevel & Emboss shading controls. Highlight Mode Режим осветљења Highlight Color Боја осветљења Highlight Opacity Непрозирност осветљења Shadow Mode Режим сенке Shadow Color Боја сенке Shadow Opacity Непрозирност сенке -# Edit › Content-Aware Fill workspace Sampling Brush Tool Alatka četkica za uzorkovanje Sampling Area Overlay Preklop oblasti uzorkovanja Show Sampling Area Prikaži oblast uzorkovanja @@ -4343,29 +4380,22 @@ shape Appearance Izgled Output Settings Podešavanja izlaza Output To Izlaz u Response curve Kriva odziva -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Koristi ugrađeni profil ({profile}) Convert to the working space ({profile}) Pretvori u radni prostor ({profile}) Remember this choice for future images Zapamti ovaj izbor za buduće slike Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Pitanje ponovo uključite opcijom Ask On Mismatch u Uređivanje › Podešavanja boja. Button Mode Režim dugmadi Button Mode On Režim dugmadi uključen - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Zatamni interfejs Lighten Interface Posvetli interfejs -# Bevel & Emboss Technique. Technique Tehnika Chisel Hard Tvrdo klesanje Chisel Soft Meko klesanje Open color-less EXR as ACEScg Otvori EXR bez podatka o bojama kao ACEScg Do not append "copy" to filename when saving a copy Ne dodaji „copy“ u ime fajla pri čuvanju kopije Show home recent files Prikaži nedavne datoteke na početnom ekranu - -# View › Guides › right-click a guide Edit Selected Guides Uredi izabrane vodilje Clear Selected Guides Ukloni izabrane vodilje - Bicubic Automatic Bikubično automatski Bicubic Smoother Bikubično glađe Bicubic Sharper Bikubično oštrije @@ -4388,8 +4418,6 @@ shape Appearance Izgled set name ime skupa {set} (modified) {set} (izmenjen) Show file name in title Prikaži naziv datoteke u naslovu - -# Image › Mode › Bitmap (#5559) 50% Threshold Prag 50% Pattern Dither Dither šarom Diffusion Dither Difuzni dither @@ -4399,8 +4427,6 @@ shape Appearance Izgled Lines/Inch Linija/inč Lines/Centimeter Linija/centimetar Ellipse Elipsa - -# Layers panel options Add “copy” to Copied Layers and Groups Dodaj „kopija” kopiranim slojevima i grupama Animation Options Opcije animacije Entire Document Ceo dokument @@ -4417,8 +4443,6 @@ shape Appearance Izgled Thumbnail Contents Sadržaj sličice Thumbnail Size Veličina sličice Use Default Masks on Fill Layers Koristi podrazumevane maske na slojevima popune - -# Smart Filter editors Blending Options ({filter}) Opcije stapanja ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Sakrij efekte i pametne filtere sloja ({key}-klik: svi slojevi) Opacity must be between 0% and 100%. Neprozirnost mora biti između 0% i 100%. @@ -4434,10 +4458,8 @@ shape Appearance Izgled Undo Changes Poništi izmene {shortcut} is reserved by the system and can't be assigned. {shortcut} je rezervisana od strane sistema i ne može se dodeliti. Low-Latency Drawing (vsync off, applies at next launch) Crtanje sa malim kašnjenjem (bez vsync-a, primenjuje se pri sledećem pokretanju) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Slobodna transformacija se još primenjuje; pokušajte ponovo kad se završi. The transform couldn't be applied. Transformacija nije mogla da se primeni. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Njegovim slojevima treba {needed} GPU memorije; budžet im ostavlja {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Podesite GPU memoriju u Podešavanja › Performanse na onoliko koliko vaša grafička kartica može da primi, najviše 3/8 njene memorije. Automatski prati Korišćenje memorije, u okviru četvrtine memorije ovog računara i 3/8 memorije kartice, i ne računa dokument kod kartice čija je memorija poznata. Dok ne staju, statusna traka prikazuje GPU memorija je puna. GPU Memory Full GPU memorija je puna @@ -4463,8 +4485,6 @@ shape Appearance Izgled The fastest and the softest, with colour 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}“. - Move Up Pomeri nagore - Move Down Pomeri nadole Previous Brush Prethodna četkica Next Brush Sledeća četkica First Brush Prva četkica @@ -4479,26 +4499,17 @@ shape Appearance Izgled Use Koristi In Front Ispred Behind Iza - -# DDS Options (#1327) DDS Options DDS opcije Generate Mipmaps Generiši mipmape - -# Color Table (.act) dialog There is no color table to save. Нема табеле боја за чување. @plural Saved {n} color to {file}|Saved {n} colors to {file} Сачувана је {n} боја у {file}|Сачуване су {n} боје у {file}|Сачувано је {n} боја у {file} - -# Graphics Adapter preference (#1885) GPU adapter GPU adapter - -# Styles panel: Import / Export Styles (.asl) Import Styles… Uvezi stilove… Export Selected Styles… Izvezi izabrane stilove… Export Styles… Izvezi stilove… {file} is not a style library (.asl) {file} nije biblioteka stilova (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Uvezen je {n} stil iz {file}|Uvezena su {n} stila iz {file}|Uvezeno je {n} stilova iz {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Izvezen je {n} stil u {file}|Izvezena su {n} stila u {file}|Izvezeno je {n} stilova u {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Prvo potvrdite ili otkažite otvoreni dijalog koraka radnje Pro Medium Gray Pro srednje siva Solarized Solarized @@ -4507,28 +4518,11 @@ shape Appearance Izgled Pro Light Pro svetla Resize Windows to Fit Prilagodi veličinu prozora EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Automatski smer pasusa Left-to-right paragraph direction Smer pasusa sleva nadesno Right-to-left paragraph direction Smer pasusa zdesna nalevo Not rendered: this adjustment ({key}) is kept as imported. Није приказано: ово прилагођавање ({key}) је задржано онако како је увезено. -# Print preview image (#8236) Print preview image Print preview image - Color Aware Prema boji - Decontaminate Colors Dekontaminiraj boje - Edge Detection Detekcija ivice - Global Refinements Globalna doterivanja - High Quality Preview Pregled visokog kvaliteta - Object Aware Prema objektu - Real-Time Refinement Doterivanje u realnom vremenu - Refine Edge Brush Tool Alatka četkica za doterivanje ivice - Refine Hair Doteraj kosu - Refine Mode Režim doterivanja - Remember Settings Zapamti podešavanja - View Mode Režim prikaza - Object Aware needs a segmentation model, which isn't available yet Režim Prema objektu zahteva model segmentacije, koji još nije dostupan - Refine Hair needs hair detection, which isn't available yet Doterivanje kose zahteva detekciju kose, koja još nije dostupna -# PhotoCraft release checks. Check for Updates… Proveri ažuriranja… PhotoCraft Updates Ažuriranja za PhotoCraft Checking for updates… Provera ažuriranja… @@ -4541,7 +4535,6 @@ shape Appearance Izgled Automatically Check for Updates Automatski proveravaj ažuriranja Installed version: {version} Instalirana verzija: {version} PhotoCraft {version} is available. Dostupan je PhotoCraft {version}. -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Kocka nijanse Brightness Cube Kocka osvetljenosti Color Wheel Točak boja @@ -4557,9 +4550,8 @@ shape Appearance Izgled Grayscale Ramp Skala nijansi sive Current Colors Trenutne boje Make Ramp Web Safe Učini skalu bezbednom za veb - Select and Mask was closed: its document is no longer the active one Izaberi i maskiraj je zatvoren: njegov dokument više nije aktivan - Select and Mask was closed: another layer was selected Izaberi i maskiraj je zatvoren: izabran je drugi sloj -# Art History Brush (#213). + The path was kept as the Work Path Putanja je sačuvana kao radna putanja + The path was discarded Putanja je odbačena Art History Brush Tool Alatka umetnička četkica istorije Tight Short Usko kratko Tight Medium Usko srednje @@ -4573,3 +4565,21 @@ shape Appearance Izgled Font size presets Unapred podešene veličine fonta Leading presets Unapred podešeni proredi Tracking presets Unapred podešeni razmaci slova + Color Aware Prema boji + Decontaminate Colors Dekontaminiraj boje + Edge Detection Detekcija ivice + Global Refinements Globalna doterivanja + High Quality Preview Pregled visokog kvaliteta + Object Aware Prema objektu + Real-Time Refinement Doterivanje u realnom vremenu + Refine Edge Brush Tool Alatka četkica za doterivanje ivice + Refine Hair Doteraj kosu + Refine Mode Režim doterivanja + Remember Settings Zapamti podešavanja + View Mode Režim prikaza + Object Aware needs a segmentation model, which isn't available yet Režim Prema objektu zahteva model segmentacije, koji još nije dostupan + Refine Hair needs hair detection, which isn't available yet Doterivanje kose zahteva detekciju kose, koja još nije dostupna + Select and Mask was closed: its document is no longer the active one Izaberi i maskiraj je zatvoren: njegov dokument više nije aktivan + Select and Mask was closed: another layer was selected Izaberi i maskiraj je zatvoren: izabran je drugi sloj + Select Layer Under Cursor Izaberi sloj ispod kursora + Drag to move the selected path Prevucite da pomerite izabranu putanju diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e904d0da92..c4db1c2743 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4770,3 +4770,10 @@ cameraRaw Show Vectorscope Visa vektorskop cameraRaw Tone Histogram Tonhistogram cameraRaw Vignetting Vinjettering cameraRaw White Balance: As Shot Vitbalans: som tagen + Current Layer: Aktuellt lager: + Delete effect Ta bort effekt + Move effect down Flytta effekten nedåt + Move effect up Flytta effekten uppåt + Path operations Banåtgärder + The path was discarded Banan kasserades + The path was kept as the Work Path Banan behölls som arbetsbana diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b02cd742b7..f914649d2d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8,9 +8,51 @@ # stay as they are; the trailing "…" of dialog commands is kept. # # Custom paper dimensions in Print Settings. + + + +# Edit › Content-Aware Fill workspace + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop + +# Native Windows printing qualification + +# Layer Mask Display Options (the layer mask rubylith's colour and opacity) + +# Channel Options and New Spot Channel (#3761) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) + +# Layers panel options and Smart Filter editors + +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). Paper Width Kağıt Genişliği Paper Height Kağıt Yüksekliği - Rows Satırlar Number Sayı Top: Üst: @@ -429,6 +471,7 @@ Intersect Shape Areas Şekil Alanlarını Kesiştir Exclude Overlapping Shapes Çakışan Şekilleri Hariç Tut Merge Shape Components Şekil Bileşenlerini Birleştir + Path operations Yol işlemleri Align Hizala Top Edges Üst Kenarlar Vertical Centers Dikey Merkezler @@ -957,7 +1000,6 @@ Contiguous Bitişik Contrast Kontrast Control: Kontrol: - Convert to sRGB sRGB'ye dönüştür Copies Kopyalar Copper Bakır @@ -1537,7 +1579,6 @@ Use Default Varsayılanı Kullan Use Legacy Eskiyi Kullan Use Measurement Scale Ölçüm Ölçeğini Kullan - Variables bind a layer's visibility, text or pixels to a named data slot. Değişkenler bir katmanın görünürlüğünü, metnini veya piksellerini adlandırılmış bir veri yuvasına bağlar. Vertical scale Dikey ölçek Vibrance Canlılık @@ -3879,7 +3920,6 @@ cameraData Lens Lens Delete Contour Konturu sil Loaded contours from {file} Konturlar {file} dosyasından yüklendi Saved contours to {file} Konturlar {file} dosyasına kaydedildi -# Edit › Content-Aware Fill workspace Excluded Area Hariç Tutulan Alan Fill Settings Dolgu Ayarları Full Tam @@ -3900,8 +3940,6 @@ cameraData Lens Lens Clear Brush Controls Fırça Denetimlerini Temizle Reset All Locked Settings Tüm Kilitli Ayarları Sıfırla Copy Texture to Other Tools Dokuyu Diğer Araçlara Kopyala - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Eylemleri Yükle… Save Actions… Eylemleri Kaydet… New Action… Yeni Eylem… @@ -3913,9 +3951,7 @@ cameraData Lens Lens @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} adımın PhotoCraft’ta henüz karşılığı yok @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} eylem {file} dosyasına kaydedildi @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop karşılığı olmayan {n} adım atlandı - Starting serial Başlangıç sıra numarası -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Durdurma Ekle… Save Set… Seti Kaydet… Message: İleti: @@ -3939,20 +3975,14 @@ cameraData Lens Lens Loaded Camera Raw settings from {file} Camera Raw ayarları {file} dosyasından yüklendi Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw ayarları {file} dosyasından yüklendi ({n} desteklenmiyor) Auto Add/Delete Otomatik Ekle/Sil - -# Native Windows printing qualification 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… 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 - -# Layer Mask Display Options (the layer mask rubylith's colour and opacity) Mask Options… Maske Seçenekleri… Layer Mask Display Options… Katman Maskesi Görüntüleme Seçenekleri… - -# Channel Options and New Spot Channel (#3761) Channel Color Kanal Rengi Color Indicates: Rengin Gösterdiği: Ink Characteristics Mürekkep Özellikleri @@ -3996,7 +4026,6 @@ cameraData Lens Lens Slab Serif Kalın tırnaklı TrueType font TrueType yazı tipi Variable font Değişken yazı tipi -# Bevel & Emboss shading controls. Highlight Mode Vurgu Modu Highlight Color Vurgu Rengi Highlight Opacity Vurgu Opaklığı @@ -4015,25 +4044,19 @@ cameraData Lens Lens Automatically Check for Updates Güncellemeleri Otomatik Denetle Installed version: {version} Yüklü sürüm: {version} PhotoCraft {version} is available. PhotoCraft {version} kullanılabilir. -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Gömülü profili kullanın ({profile}) Convert to the working space ({profile}) Çalışma alanına dönüştürün ({profile}) Remember this choice for future images Bu seçimi sonraki görüntüler için hatırla Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Soruyu Düzen › Renk Ayarları'ndaki Ask On Mismatch ile yeniden açabilirsiniz. Button Mode Düğme modu Button Mode On Düğme modu açık - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Arayüzü koyulaştır Lighten Interface Arayüzü açıklaştır -# Bevel & Emboss Technique. Technique Teknik Chisel Hard Sert Keski Chisel Soft Yumuşak Keski Open color-less EXR as ACEScg Renk bilgisi olmayan EXR'yi ACEScg olarak aç Do not append "copy" to filename when saving a copy Kopya kaydederken dosya adına "copy" ekleme - -# View › Guides › right-click a guide Edit Selected Guides Seçili Kılavuzları Düzenle Clear Selected Guides Seçili Kılavuzları Temizle Bicubic Automatic Bikübik Otomatik @@ -4058,8 +4081,6 @@ cameraData Lens Lens set name küme adı {set} (modified) {set} (değiştirildi) Show file name in title Başlıkta dosya adını göster - -# Image › Mode › Bitmap (#5559) 50% Threshold %50 Eşik Pattern Dither Desen Titreklik Diffusion Dither Difüzyon Titreklik @@ -4069,8 +4090,6 @@ cameraData Lens Lens Lines/Inch Çizgi/İnç Lines/Centimeter Çizgi/Santimetre Ellipse Elips - -# Layers panel options and Smart Filter editors Add “copy” to Copied Layers and Groups Kopyalanan Katman ve Gruplara “kopya” Ekle Animation Options Animasyon Seçenekleri Entire Document Tüm Belge @@ -4087,7 +4106,6 @@ cameraData Lens Lens Thumbnail Contents Küçük Resim İçeriği Thumbnail Size Küçük Resim Boyutu Use Default Masks on Fill Layers Dolgu Katmanlarında Varsayılan Maskeleri Kullan - Blending Options ({filter}) Karışım Seçenekleri ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini gizle ({key}-tık: tüm katmanlar) Opacity must be between 0% and 100%. Opaklık %0 ile %100 arasında olmalıdır. @@ -4103,10 +4121,8 @@ cameraData Lens Lens Undo Changes Değişiklikleri Geri Al {shortcut} is reserved by the system and can't be assigned. {shortcut} sistem tarafından ayrılmıştır ve atanamaz. Low-Latency Drawing (vsync off, applies at next launch) Düşük gecikmeli çizim (dikey eşitleme kapalı, sonraki açılışta geçerli) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Serbest Dönüştürme hâlâ uygulanıyor; bittiğinde yeniden deneyin. The transform couldn't be applied. Dönüştürme uygulanamadı. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Katmanlarının {needed} GPU belleğine ihtiyacı var; bütçe onlara {budget} bırakıyor. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Tercihler › Performans içindeki GPU Belleği'ni ekran kartınızın kaldırabileceği miktara, en fazla belleğinin 3/8'ine ayarlayın. Otomatik, Bellek kullanımını izler; bu bilgisayarın belleğinin dörtte biri ve kartın belleğinin 3/8'i içinde kalır, belleği bilinen bir kartta belgeyi hesaba katmaz. Sığmadıkları sürece durum çubuğu GPU Belleği Dolu gösterir. GPU Memory Full GPU Belleği Dolu @@ -4132,8 +4148,6 @@ cameraData Lens Lens 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ğı. “{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. - Move Up Yukarı taşı - Move Down Aşağı taşı Previous Brush Önceki fırça Next Brush Sonraki fırça First Brush İlk fırça @@ -4148,26 +4162,17 @@ cameraData Lens Lens Use Kullan In Front Önde Behind Arkada - -# DDS Options (#1327) DDS Options DDS Seçenekleri Generate Mipmaps Mipmap oluştur - -# Color Table (.act) dialog There is no color table to save. Kaydedilecek renk tablosu yok. @plural Saved {n} color to {file}|Saved {n} colors to {file} {n} renk {file} konumuna kaydedildi - -# Graphics Adapter preference (#1885) GPU adapter GPU bağdaştırıcısı - -# Styles panel: Import / Export Styles (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} {file} dosyasından {n} stil içe aktarıldı @plural Exported {n} style to {file}|Exported {n} styles to {file} {n} stil {file} dosyasına dışa aktarıldı Import Styles… Stilleri İçe Aktar… Export Selected Styles… Seçili Stilleri Dışa Aktar… Export Styles… Stilleri Dışa Aktar… {file} is not a style library (.asl) {file} bir stil kitaplığı değil (.asl) -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Önce açık eylem adımı iletişim kutusunu onaylayın veya iptal edin Pro Medium Gray Pro Orta Gri Solarized Solarized @@ -4176,28 +4181,11 @@ cameraData Lens Lens Pro Light Pro Açık Resize Windows to Fit Pencereleri sığacak şekilde boyutlandır EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Otomatik paragraf yönü Left-to-right paragraph direction Soldan sağa paragraf yönü Right-to-left paragraph direction Sağdan sola paragraf yönü Not rendered: this adjustment ({key}) is kept as imported. Görüntülenmiyor: bu ayarlama ({key}) içe aktarıldığı gibi korunuyor. -# Print preview image (#8236) Print preview image Baskı Önizleme Görüntüsü - Color Aware Renge Duyarlı - Decontaminate Colors Renkleri Arındır - Edge Detection Kenar Algılama - Global Refinements Genel Hassaslaştırmalar - High Quality Preview Yüksek Kaliteli Önizleme - Object Aware Nesneye Duyarlı - Real-Time Refinement Gerçek Zamanlı Hassaslaştırma - Refine Edge Brush Tool Kenarı Hassaslaştırma Fırçası Aracı - Refine Hair Saçı Hassaslaştır - Refine Mode Hassaslaştırma Modu - Remember Settings Ayarları Hatırla - View Mode Görünüm Modu - Object Aware needs a segmentation model, which isn't available yet Nesneye Duyarlı mod henüz kullanılamayan bir bölütleme modeli gerektirir - Refine Hair needs hair detection, which isn't available yet Saçı Hassaslaştır henüz kullanılamayan saç algılama gerektirir -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Renk Tonu Küpü Brightness Cube Parlaklık Küpü Color Wheel Renk Çarkı @@ -4213,9 +4201,8 @@ cameraData Lens Lens Grayscale Ramp Gri Tonlama Şeridi Current Colors Geçerli Renkler Make Ramp Web Safe Şeridi Web Renkleriyle Sınırla - Select and Mask was closed: its document is no longer the active one Seç ve Maskele kapatıldı: belgesi artık etkin değil - Select and Mask was closed: another layer was selected Seç ve Maskele kapatıldı: başka bir katman seçildi -# Art History Brush (#213). + The path was kept as the Work Path Yol, Çalışma Yolu olarak korundu + The path was discarded Yol atıldı Art History Brush Tool Sanat Tarihi Fırçası Aracı Tight Short Sıkı Kısa Tight Medium Sıkı Orta @@ -4229,3 +4216,25 @@ cameraData Lens Lens Font size presets Yazı tipi boyutu hazır ayarları Leading presets Satır aralığı hazır ayarları Tracking presets İzleme hazır ayarları + Color Aware Renge Duyarlı + Decontaminate Colors Renkleri Arındır + Edge Detection Kenar Algılama + Global Refinements Genel Hassaslaştırmalar + High Quality Preview Yüksek Kaliteli Önizleme + Object Aware Nesneye Duyarlı + Real-Time Refinement Gerçek Zamanlı Hassaslaştırma + Refine Edge Brush Tool Kenarı Hassaslaştırma Fırçası Aracı + Refine Hair Saçı Hassaslaştır + Refine Mode Hassaslaştırma Modu + Remember Settings Ayarları Hatırla + View Mode Görünüm Modu + Object Aware needs a segmentation model, which isn't available yet Nesneye Duyarlı mod henüz kullanılamayan bir bölütleme modeli gerektirir + Refine Hair needs hair detection, which isn't available yet Saçı Hassaslaştır henüz kullanılamayan saç algılama gerektirir + Select and Mask was closed: its document is no longer the active one Seç ve Maskele kapatıldı: belgesi artık etkin değil + Select and Mask was closed: another layer was selected Seç ve Maskele kapatıldı: başka bir katman seçildi + Move effect up Efekti yukarı taşı + Move effect down Efekti aşağı taşı + Delete effect Efekti sil + Current Layer: Geçerli Katman: + Underlying Layer: Alttaki Katman: + Drag to move the selected path Seçili yolu taşımak için sürükleyin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 00d192a037..8507592c6c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9,20 +9,206 @@ # Licensed MIT OR Apache-2.0. See LICENSE-translations.txt and ATTRIBUTION.md. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Параметри маски… - Layer Mask Display Options… Параметри відображення маски шару… # Channel Options and New Spot Channel (#3761) - Channel Color Колір каналу - Color Indicates: Кольором позначено: - Solidity: Щільність: - Ink Characteristics Характеристики фарби # Menus # Guide layout dialog # Custom print paper (#3820) + + +# File + +# Edit + +# Image + +# Layer + +# Type + +# Select +# Select and Mask dialog labels + +# Filter +# Field Blur pins (#3373) + +# View + +# Window + +# Help + +# Tools and options bar + +# Panels, dialogs and common widgets + +# Preferences dialog + +# Document and canvas status bar + +# Layers panel + +# Channels panel + +# Color picker and swatches + +# Filters and adjustments dialogs + +# Camera Raw and lens dialogs + +# Adjustments panel + +# History panel + +# Navigator panel + +# Brush Settings panel + +# Tool presets + +# Paragraph and character panels + +# Glyphs panel + +# Paths panel + +# Clone Source panel + +# Timeline panel + +# Info panel + +# Layer Comps panel + +# Analysis and variables + +# Automate + +# Color Settings dialog + +# Themes + +# Workspaces + +# New Document dialog + +# Placeholders, tooltips, status and keyboard hints + +# Transform / warp overlays + +# Vanishing Point + +# Misc dialog strings + +# Blend modes + +# Saved views and other bits + +# Plurals + +# Remaining menu strings (second pass) + +# tl! literals (third pass) +# Gradient Editor window, opened from the options bar's gradient swatch. + +# Preference dialog: generated setting labels and dropdown choices +# Rendering mode and recovery +# Camera Raw: contextual controls and window title + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Additional shell controls, dynamic dialog fields and command labels. + +# Layers-panel trash confirmation + + +# Native macOS application menu. + +# Painting symmetry presets. + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice +# Dynamic color-picker titles and warnings about losing editable layer content. + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) + Mask Options… Параметри маски… + Layer Mask Display Options… Параметри відображення маски шару… + Channel Color Колір каналу + Color Indicates: Кольором позначено: + Solidity: Щільність: + Ink Characteristics Характеристики фарби Paper Width Ширина паперу Paper Height Висота паперу Rows Рядки @@ -40,7 +226,6 @@ 5 Columns, 3 Rows 5 стовпців, 3 рядки 8 Columns 8 стовпців 12 Columns 12 стовпців - File Файл Edit Редагування Image Зображення @@ -57,8 +242,6 @@ View Перегляд Window Вікно Help Довідка - -# File New… Створити… New from Clipboard Створити з буфера обміну New Створити @@ -100,8 +283,6 @@ Save for Web (Legacy)… Зберегти для вебу (застаріле)… Generate Генерувати Image Assets Ресурси зображення - -# Edit Undo Скасувати Redo Повторити Fade… Послабити… @@ -125,8 +306,6 @@ Define Pattern… Визначити візерунок… Define Custom Shape… Визначити довільну фігуру… Purge Очистити пам'ять - -# Image Image Size… Розмір зображення… Image Size Розмір зображення Canvas Size… Розмір полотна… @@ -165,8 +344,6 @@ Duotone… Дуплекс… Duotone Дуплекс Trap… Трепінг… - -# Layer Layer via Copy Шар через копіювання Layer via Cut Шар через вирізання Duplicate Layer… Дублювати шар… @@ -251,8 +428,6 @@ Scale Effects… Масштабувати ефекти… New Layer… Новий шар… Delete Layer… Видалити шар… - -# Type Font Шрифт Font Preview Size Розмір перегляду шрифту Orientation Орієнтація @@ -279,8 +454,6 @@ Load Default Type Styles Завантажити типові текстові стилі Save Default Type Styles Зберегти типові текстові стилі Type… Текст… - -# Select All Усе Deselect Зняти виділення Reselect Відновити виділення @@ -288,7 +461,6 @@ Inverse Інвертувати Color Range… Колірний діапазон… Select and Mask… Виділити та маскувати… -# Select and Mask dialog labels Smart Radius Розумний радіус Shift Edge Змістити край Decontaminate Очистити @@ -316,8 +488,6 @@ Current Layer Поточний шар Refine Strokes Штрихи уточнення Edits Правки - -# Filter Last Filter Останній фільтр Filter Gallery… Галерея фільтрів… Liquify… Пластика… @@ -328,7 +498,6 @@ Oil Paint… Олійний живопис… Blur Gallery Галерея розмиття Field Blur… Розмиття поля… -# Field Blur pins (#3373) No pin selected Шпильку не вибрано Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Клацніть зображення, щоб додати шпильку; перетягніть шпильку, щоб перемістити її, або її кільце, щоб змінити розмиття. Delete видаляє вибрану шпильку. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Перетягуйте маркери на контурі, щоб змінити розмір і повернути його, квадрат — щоб заокруглити кути, а точки всередині — щоб задати, де починається розмиття. @@ -417,8 +586,6 @@ Mezzotint… Мецотинто… Color Halftone… Колірний растр… Layer… Шар… - -# View Proof Setup Налаштування кольоропроби Proof Colors Кольори кольоропроби Pixel Aspect Ratio Співвідношення сторін пікселя @@ -465,8 +632,6 @@ Canvas rotation Поворот полотна Zoom in Збільшити Zoom out Зменшити - -# Window Cascade Каскадом Tile Плиткою 2-up Horizontal 2 по горизонталі @@ -515,8 +680,6 @@ 3D 3D Toolbars Панелі інструментів Hide All Приховати все - -# Help About PhotoCraft Про PhotoCraft PhotoCraft Website Вебсайт PhotoCraft PhotoCraft on GitHub PhotoCraft на GitHub @@ -524,8 +687,6 @@ ArtCraft Website Вебсайт ArtCraft Join the ArtCraft Discord… Приєднатися до Discord ArtCraft… System Info… Інформація про систему… - -# Tools and options bar Move Переміщення Marquee Прямокутне виділення Lasso Ласо @@ -586,8 +747,6 @@ Rotation Обертання Align Вирівняти Aligned Вирівняно - -# Panels, dialogs and common widgets OK Гаразд Cancel Скасувати Cancel (Esc) Скасувати (Esc) @@ -647,8 +806,6 @@ Select Data Points… Вибрати точки даних… Set Measurement Scale… Установити масштаб вимірювань… Use Measurement Scale Використовувати масштаб вимірювань - -# Preferences dialog Preferences Налаштування General… Загальні… Interface… Інтерфейс… @@ -673,8 +830,6 @@ Thumbnail size (smallest: list) Розмір мініатюр (найменший: список) Reset GPU Backend Скинути графічний бекенд Applies at next launch. Набуде чинності після перезапуску. - -# Document and canvas status bar Untitled Без назви Untitled-1 Без назви-1 Doc: {flat}/{layered} Документ: {flat}/{layered} @@ -713,8 +868,6 @@ Both Axes Обидві осі Horizontally Горизонтально Vertically Вертикально - -# Layers panel Layers to Files… Шари у файли… Duplicate Layers… Дублювати шари… Group name Назва групи @@ -744,8 +897,6 @@ Smart Filter Смартфільтр Fill Content Вміст заливки Adjustment Preview Перегляд корекції - -# Channels panel Channel: Канал: Channel Mixer… Змішувач каналів… Output Channel: Вихідний канал: @@ -760,8 +911,6 @@ Spot Channel Канал плашкового кольору Mask All Маскувати все Mask All Objects Маскувати всі об'єкти - -# Color picker and swatches Color Колір Color: Колір: Colors Кольори @@ -776,8 +925,6 @@ Overlay Opacity Непрозорість накладання Glow Color Колір світіння Web Snap Прив'язка до вебкольорів - -# Filters and adjustments dialogs Brightness Яскравість Contrast Контрастність Brightness/Contrast… Яскравість/контрастність… @@ -838,8 +985,6 @@ Working Yellow Plate Робоча жовта форма Working Black Plate Робоча чорна форма Working Gray Plate Робоча сіра форма - -# Camera Raw and lens dialogs Basic Основні Detail Деталі HSL/Grayscale HSL/градації сірого @@ -936,8 +1081,6 @@ Selected Areas Виділені області Spot Color Плашковий колір Color indicates Колір позначає - -# Adjustments panel Curves Криві Levels Рівні Color Balance Колірний баланс @@ -950,8 +1093,6 @@ Channel Mixer Змішувач каналів Gradient Map Карта градієнта Selective Color Вибіркова корекція кольору - -# History panel History Log… Журнал історії… Create Snapshot Створити знімок стану Delete Snapshot Видалити знімок стану @@ -966,14 +1107,10 @@ Automatically Create New Snapshot When Saving Автоматично створювати знімок стану під час збереження Show New Snapshot Dialog by Default Типово показувати діалог нового знімка стану Clear History Очистити історію - -# Navigator panel Panel Options… Параметри панелі… View menu Меню перегляду Keep view in sync Синхронізувати перегляд {zoom}% {zoom}% - -# Brush Settings panel Brush name Назва пензля Brush Preview Перегляд пензля Brush Tip Shape Форма кінчика пензля @@ -1057,8 +1194,6 @@ Override Tilt Y Перевизначити нахил Y Override Rotation Перевизначити обертання Apply the pen's tilt and rotation to the tip shape Застосувати нахил і обертання пера до форми кінчика - -# Tool presets Preset Type Тип набору Preset Manager… Менеджер наборів… Rename Tool Preset… Перейменувати набір інструмента… @@ -1072,8 +1207,6 @@ Preset: Набір: Preset Набір Presets: Набори: - -# Paragraph and character panels Font Size: Розмір шрифту: Type: Тип: Style Стиль @@ -1150,8 +1283,6 @@ Indent First Відступ першого рядка Center По центру Justify По ширині - -# Glyphs panel Glyph Гліф Select a type layer or click into text to insert glyphs Виберіть текстовий шар або клацніть у тексті, щоб вставити гліфи Entire Font Увесь шрифт @@ -1171,8 +1302,6 @@ Ordinals Порядкові числа East Asian Features Східноазійські можливості Middle Eastern Features Близькосхідні можливості - -# Paths panel Path Контур Path: Контур: Work Path Робочий контур @@ -1189,11 +1318,9 @@ Current Path Поточний контур Vector Mask from Current Path Векторна маска з поточного контуру Create new shape from the current path Створити нову фігуру з поточного контуру - Drag to move the active shape's path or the Work Path Перетягніть, щоб перемістити контур активної фігури або робочий контур + Drag to move the selected path Перетягніть, щоб перемістити вибраний контур Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Клацання: вибрати вузол · Перетягування: перемістити вузол, ручку або сегмент · {shift}+клацання: додати · {alt}+клацання: увесь підконтур Draw with the Pen tool (P) or make a work path from a selection. Малюйте пером (P) або створіть робочий контур із виділення. - -# Clone Source panel Source: not set ({key}-click with Clone Stamp) Джерело: не задано ({key}+клацання клонувальним штампом) Clone source {n} ({key}-click with Clone Stamp to set) Джерело клонування {n} ({key}+клацання клонувальним штампом для встановлення) {key}-click to set the source {key}+клацання, щоб установити джерело @@ -1216,8 +1343,6 @@ Frame Sync Синхронізація кадрів Quick Sync Швидка синхронізація Enabled Увімкнено - -# Timeline panel Create Video Timeline Створити відеошкалу часу Open a document to use the timeline. Відкрийте документ, щоб користуватися шкалою часу. Video Layers Відеошари @@ -1259,8 +1384,6 @@ Repeat Повторення Play Once Відтворити один раз Video Cache Відеокеш - -# Info panel Info Options… Параметри інформації… First Color Readout Перше колірне значення Second Color Readout Друге колірне значення @@ -1283,8 +1406,6 @@ Mouse Coordinates Координати миші Ruler Units Одиниці лінійки Hide Приховати - -# Layer Comps panel Layer Comps to Files… Композиції шарів у файли… Apply next selected layer comp Застосувати наступну вибрану композицію шарів Apply previous selected layer comp Застосувати попередню вибрану композицію шарів @@ -1302,8 +1423,6 @@ Visibility Видимість Position Положення Appearance (Layer Style) Вигляд (стиль шару) - -# Analysis and variables Analysis Аналіз Variables Змінні Variable Data Sets… Набори даних змінних… @@ -1385,8 +1504,6 @@ Version {version} Версія {version} Advanced Розширені Import… Імпортувати… - -# Automate Automate Автоматизація Batch… Пакетна обробка… Create Droplet… Створити дроплет… @@ -1417,8 +1534,6 @@ Stop For Errors Зупинятися в разі помилок Log Errors To File Записувати помилки у файл Errors Помилки - -# Color Settings dialog Color Settings… Налаштування кольору… Settings Налаштування Settings: Налаштування: @@ -1447,8 +1562,6 @@ SMPTE C SMPTE C HDTV (Rec. 709) HDTV (Rec. 709) CIE RGB CIE RGB - -# Themes Theme Тема Switch theme Перемкнути тему Next Theme Наступна тема @@ -1473,8 +1586,6 @@ Pro Medium Gray Theme Середньосіра тема «Профі» Pro Light Gray Theme Світло-сіра тема «Профі» Pro Light Theme Світла тема «Профі» - -# Workspaces Workspace… Робочий простір… Essentials Основне New Workspace… Новий робочий простір… @@ -1502,8 +1613,6 @@ Collapse Panel Group Згорнути групу панелей Expand Panel Group Розгорнути групу панелей Close Tab Group Закрити групу вкладок - -# New Document dialog PRESET DETAILS ПАРАМЕТРИ НАБОРУ BLANK DOCUMENT PRESETS ({n}) НАБОРИ ПОРОЖНІХ ДОКУМЕНТІВ ({n}) Create a new document or open an existing file. Створіть новий документ або відкрийте наявний файл. @@ -1550,8 +1659,6 @@ Points Пункти Picas Піки Columns Стовпці - -# Placeholders, tooltips, status and keyboard hints {name} options Параметри: {name} Align {what} Вирівняти: {what} Untagged {mode} {mode} без профілю @@ -1728,8 +1835,6 @@ Current Поточний {added}, {removed} subtracted {added}, віднято {removed} Filter: Фільтр: - -# Transform / warp overlays Free Transform Вільна трансформація Free Transform a Copy Вільна трансформація копії Transform Трансформація @@ -1781,8 +1886,6 @@ Rotate Fixed Фіксоване обертання Adaptive Wide Angle isn't open Адаптивний широкий кут не відкрито Liquify is not open Пластику не відкрито - -# Vanishing Point Create Plane Створити площину Edit Plane Редагувати площину Select Plane Вибрати площину @@ -1796,8 +1899,6 @@ Blend Змішування Brush Size Розмір пензля Heal Color Відновити колір - -# Misc dialog strings Mask Маска Channel Канал Rectangle Прямокутник @@ -1820,8 +1921,6 @@ Add to Додати до Subtract from Відняти від Intersect with Перетнути з - -# Blend modes Pass Through Наскрізне Dissolve Розчинення Darken Затемнення @@ -1843,19 +1942,13 @@ Difference Різниця Exclusion Виключення Luminosity Світність - -# Saved views and other bits Capture Comp Зберегти композицію No Layer Comps Немає композицій шарів - -# Plurals @plural {n} item|{n} items {n} елемент|{n} елементи|{n} елементів @plural {n} Layer|{n} Layers {n} Шар|{n} Шари|{n} Шарів @plural {n} layer|{n} layers {n} шар|{n} шари|{n} шарів @plural Group · {n} layer|Group · {n} layers Група · {n} шар|Група · {n} шари|Група · {n} шарів @plural {n} sample|{n} samples {n} зразок|{n} зразки|{n} зразків - -# Remaining menu strings (second pass) 180° 180° 32-bit Preview Options… Параметри 32-бітного перегляду… 90° Clockwise 90° за годинниковою стрілкою @@ -1952,6 +2045,7 @@ Merge Group Об'єднати групу Merge Layers Об'єднати шари Merge Shape Components Об'єднати компоненти фігури + Path operations Операції з контурами Merge Visible Об'єднати видимі Stamp Visible Створити об'єднану копію видимих Select Layer Above Вибрати шар вище @@ -2024,8 +2118,6 @@ Video Frames to Layers… Відеокадри в шари… WIA Support… Підтримка WIA… Working CMY Plate Робоча форма CMY - -# tl! literals (third pass) Absolute Абсолютний Action Дія Adaptive Адаптивний @@ -2059,7 +2151,6 @@ Capture Зберегти стан Center Crop Marks Центральні мітки обрізання Centre the gradient (offset 0, 0) Центрувати градієнт (зсув 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor Редактор градієнтів Gradient picker Вибір градієнта Gradient stops Точки градієнта @@ -2276,8 +2367,6 @@ Whites Білі тони Yellow Жовтий Yellow · Blue Жовтий · Синій - -# Preference dialog: generated setting labels and dropdown choices Adobe Adobe Adobe rgb Adobe RGB Allow agent control Дозволити керування агентом @@ -2500,7 +2589,6 @@ 4 x 4 4 x 4 5 x 5 5 x 5 Grid: Сітка: -# Rendering mode and recovery Rendering Mode Режим рендерингу Automatic (recommended) Автоматичний (рекомендовано) CPU / Compatibility CPU / сумісність @@ -2527,7 +2615,6 @@ Tone Histogram Тонова гістограма Show Selected Region Показувати вибрану область cameraRaw Light Світло -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Фільтр Camera Raw ({layer}) Camera Raw ({name}) Camera Raw ({name}) Aqua Аквамариновий @@ -2557,14 +2644,10 @@ cameraRaw Roughness Шорсткість Transform On Drop Трансформувати після відпускання Scale or rotate the moved area, then press {key} Змініть масштаб або поверніть переміщену область, потім натисніть {key} Edit Type Редагувати текст - - New Style… Новий стиль… Style {name} saved Стиль {name} збережено - Create new style (from the selected type) Створити новий стиль (із вибраного тексту) Create new style from the selected layer Створити новий стиль із вибраного шару - Make Default Зробити типовим Reset to Default Скинути до типового Full-resolution preview unavailable Перегляд у повній роздільності недоступний @@ -2593,9 +2676,6 @@ cameraRaw Roughness Шорсткість Magnetic Lasso Tool Інструмент «Магнітне ласо» Frequency Частота Use tablet pressure to change pen width Використовувати натиск планшета для зміни ширини пера - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About Про програму Contributors Учасники Models Моделі @@ -2626,8 +2706,6 @@ cameraRaw Roughness Шорсткість % of all commits % усіх комітів Lines +/− Рядки +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} комітів, +{added} / −{deleted} рядків (Δ {delta}), +{binAdded} / −{binDeleted} бінарних ресурсів, {first} – {last} - -# Swatches panel Create new swatch Створити новий зразок кольору New Swatch… Новий зразок кольору… New Swatch Group… Нова група зразків кольорів… @@ -2637,13 +2715,12 @@ cameraRaw Roughness Шорсткість Export Swatches for Exchange… Експортувати зразки кольорів для обміну… Reset Swatches Скинути зразки кольорів Add to Swatches Додати до зразків кольорів -# Layer Style > Blending Options (Advanced Blending) Blend If: Накладати, якщо: + Current Layer: Поточний шар: + Underlying Layer: Нижній шар: Channels: Канали: Knockout Вибивання Apply At Canvas Bounds Застосувати на межах полотна - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) Вибір кольору (колір тексту) Color Picker ({name}) Вибір кольору ({name}) Color Picker (Fill Color) Вибір кольору (колір заливки) @@ -2660,8 +2737,6 @@ cameraRaw Roughness Шорсткість Show/Hide Panels Показати/приховати панелі Could not open Не вдалося відкрити {path}: the path is not valid Unicode; rename the file and open it again. {path}: шлях не є коректним Unicode; перейменуйте файл і відкрийте його знову. - -# Fill dialog, layer style contours and Image Size Contents: Вміст: Custom Pattern: Довільний візерунок: Foreground Color Колір переднього плану @@ -2687,14 +2762,12 @@ cameraRaw Roughness Шорсткість Rounded Steps Заокруглені сходинки Sawtooth 1 Пилка 1 Linear Лінійний - Red Eye Tool Інструмент «Червоні очі» Pupil Size Розмір зіниці Darken Amount Величина затемнення Click a red pupil to neutralize it Клацніть червону зіницю, щоб усунути ефект open source відкритий код …and {n} more …і ще {n} - Eyedroppers: Піпетки: Set Black Point Установити точку чорного Set Neutral Gray Point Установити точку нейтрального сірого @@ -2704,8 +2777,6 @@ cameraRaw Roughness Шорсткість Black Matte Чорна підкладка White Matte Біла підкладка Quick Mask Швидка маска - -# Layer colour labels. Seafoam Морська піна Indigo Індиго Fuchsia Фуксія @@ -2725,17 +2796,16 @@ fontWeight Bold Жирний fontWeight ExtraBold Екстражирний fontWeight Black Наджирний fontWeight Italic Курсивний - -# Pattern Stamp tool Pattern Stamp Tool Інструмент «Візерунковий штамп» Impressionist Імпресіоністичний Rotate View Tool Інструмент «Поворот перегляду» Reset View Скинути перегляд Drag around the centre to rotate the view · Shift constrains to 15° Перетягніть навколо центру, щоб повернути перегляд · Shift обмежує крок до 15° - -# Additional shell controls, dynamic dialog fields and command labels. (coming soon) (незабаром) Add a layer style Додати стиль шару + Move effect up Перемістити ефект вгору + Move effect down Перемістити ефект вниз + Delete effect Видалити ефект Add a mask (from the selection; {key} inverts) Додати маску (із виділення; {key} інвертує) Add an adjustment Додати корекцію Add space after paragraph Додати інтервал після абзацу @@ -2770,8 +2840,6 @@ fontWeight Italic Курсивний Merged Layers Об'єднані шари Delete Cropped Pixels Видаляти обрізані пікселі Delete current state Видалити поточний стан - -# Layers-panel trash confirmation Delete layer ‘{name}’? Видалити шар «{name}»? Delete {count} layers? {names} Видалити шари ({count})? {names} Delete layer? Видалити шар? @@ -2780,7 +2848,6 @@ fontWeight Italic Курсивний Missing delete command Відсутня команда видалення Invalid delete command Недійсна команда видалення Layer deleted, but confirmation preference could not be saved: {error} Шар видалено, але не вдалося зберегти налаштування підтвердження: {error} - Delete layer Видалити шар Diamond Gradient Ромбічний градієнт Enable airbrush-style build-up effects Увімкнути ефекти накопичення як в аерографі @@ -3598,8 +3665,6 @@ cameraRaw Masking Маскування Expand group (⌥-click: all groups) Розгорнути групу (⌥+клацання: усі групи) Hide the layer's effects (⌥-click: all layers) Приховати ефекти шару (⌥+клацання: усі шари) Show the layer's effects (⌥-click: all layers) Показати ефекти шару (⌥+клацання: усі шари) - -# Native macOS application menu. About {app} Про {app} Hide {app} Приховати {app} Quit {app} Вийти з {app} @@ -3623,12 +3688,9 @@ cameraRaw Masking Маскування Show Sampling Ring Показувати кільце вибірки Transparency Threshold Поріг прозорості Opacity Threshold Поріг непрозорості - -# Painting symmetry presets. Dual Axis Подвійна вісь Diagonal Діагональна Transform Symmetry Трансформувати симетрію - Rasterize svg groups deeper than Растеризувати групи SVG глибше цього рівня 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 вимикає цей поріг; групи SVG із вкладеністю понад 100 рівнів завжди растеризуються. Rule of Thirds Правило третин @@ -3641,8 +3703,6 @@ cameraRaw Masking Маскування Cycle Orientation Змінити орієнтацію Set the overlay options for the Crop tool Задати параметри накладання для інструмента «Рамка» Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-клік перехопило робоче середовище, яке переміщує вікна через Alt-перетягування. Призначте для переміщення вікон клавішу Super або зафіксуйте Alt у меню Вікно › Клавіші-модифікатори. - -# Shared Layer Style color picker Color Picker (Layer Style Color) Палітра кольорів (колір стилю шару) Auto Hide Notifications Автоматично приховувати сповіщення Notification Duration (seconds) Тривалість сповіщення (секунди) @@ -3717,7 +3777,6 @@ cameraRaw Masking Маскування Appearance Settings… Налаштування вигляду… Add to favorites Додати до вибраного Remove from favorites Видалити з вибраного -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). cameraData Make Виробник cameraData Model Модель cameraData Date Taken Дата зйомки @@ -3727,7 +3786,6 @@ cameraData ISO Speed Світлочутливість ISO cameraData Focal Length Фокусна відстань cameraData Focal Length (35 mm) Фокусна відстань (35 мм) cameraData Lens Об'єктив -# Shared panel docking Activate Panel Активувати панель Change Panel Group Змінити групу панелей Change Panel Layout Змінити розташування панелей @@ -3760,7 +3818,6 @@ cameraData Lens Об'єктив Search settings… Пошук налаштувань… No matching settings Немає відповідних налаштувань PhotoCraft — Screen Color Picker PhotoCraft — Піпетка кольору екрана -# Edit › Content-Aware Fill workspace Sampling Brush Tool Пензель області вибірки Sampling Area Overlay Накладання області вибірки Show Sampling Area Показати область вибірки @@ -3776,7 +3833,6 @@ cameraData Lens Об'єктив Mirror Віддзеркалення Output Settings Параметри виводу Output To Вивести в - Animation Options Параметри анімації Entire Document Увесь документ Filter Options Параметри фільтрів @@ -3793,8 +3849,6 @@ cameraData Lens Об'єктив Add “copy” to Copied Layers and Groups Додавати «копія» до скопійованих шарів і груп Preview on canvas when reordering layers Попередній перегляд на полотні під час зміни порядку шарів Show layer mask badges Показувати позначки масок шарів - -# Smart Filter editors Blending Options ({filter}) Параметри накладання ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Приховати ефекти шару та смарт-фільтри ({key}-клік: усі шари) Show the layer's effects and Smart Filters ({key}-click: all layers) Показати ефекти шару та смарт-фільтри ({key}-клік: усі шари) @@ -3825,7 +3879,6 @@ curves Smooth Згладити Fix the red plane first: its corners must form a convex quad Спершу виправте червону площину: її кути мають утворювати опуклий чотирикутник Alt-click a plane to set the clone source Клацніть площину з Alt, щоб задати джерело клонування Too many clone strokes: apply Vanishing Point first Забагато мазків клонування: спочатку застосуйте «Точку сходження» -# Select and Mask view modes (#1754) Onion Skin Калька Marching Ants Мурашки On Black На чорному @@ -3834,7 +3887,6 @@ curves Smooth Згладити Show Edge Показати край Show Original Показати початкове F cycles the views; hold X to see the image F перемикає види; утримуйте X, щоб побачити зображення -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) Пензель уточнення краю (R) Expand Detection Area Розширити область виявлення Restore Original Edge Відновити початковий край @@ -3854,19 +3906,13 @@ curves Smooth Згладити Scale: Масштаб: Snap to Origin Прив'язати до початку координат Presentation Представлення - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Клацніть, щоб розмістити · Alt-клацання або перетягування за межі полотна для видалення No document open Документ не відкрито {n} of {max} sample points {n} з {max} точок вимірювання - -# History panel menu (#2966) New Snapshot… Новий знімок стану… History Options… Параметри історії… -# History panel › History Options… (#2966) Allow Non-Linear History Дозволити нелінійну історію Make Layer Visibility Changes Undoable Дозволити скасування змін видимості шарів -# Print dialog (#2697) Emulsion Down Емульсією донизу Functions Функції Print Resolution: Роздільна здатність друку: @@ -3878,7 +3924,6 @@ curves Smooth Згладити Apply mask to layer before removing? Застосувати маску до шару перед видаленням? The layer or its mask changed. Drag the mask onto the Trash again. Шар або його маска змінилися. Перетягніть маску до кошика ще раз. Delete the vector mask? Видалити векторну маску? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} Експортовано {n} зразок кольору до {file}|Експортовано {n} зразки кольорів до {file}|Експортовано {n} зразків кольорів до {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} Імпортовано {n} пензель з {group}|Імпортовано {n} пензлі з {group}|Імпортовано {n} пензлів з {group} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} Імпортовано {n} зразок кольору з {file}|Імпортовано {n} зразки кольорів з {file}|Імпортовано {n} зразків кольорів з {file} @@ -3893,7 +3938,6 @@ curves Smooth Згладити @plural {n} step|{n} steps {n} крок|{n} кроки|{n} кроків @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (і ще {n} попередження щодо наборів пензлів)|{warning} (і ще {n} попередження щодо наборів пензлів)|{warning} (і ще {n} попереджень щодо наборів пензлів) @plural {what} with {n} warning|{what} with {n} warnings {what}: {n} попередження|{what}: {n} попередження|{what}: {n} попереджень -# View › Guides › New Guide… › Color Light Blue Світло-синій Light Red Світло-червоний Medium Blue Середньо-синій @@ -3914,8 +3958,6 @@ curves Smooth Згладити Clear Brush Controls Очистити параметри пензля Reset All Locked Settings Скинути всі заблоковані параметри Copy Texture to Other Tools Скопіювати текстуру в інші інструменти - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Завантажити операції… Save Actions… Зберегти операції… New Action… Нова операція… @@ -3927,10 +3969,8 @@ curves Smooth Згладити @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} крок ще не має відповідника в PhotoCraft|{n} кроки ще не мають відповідника в PhotoCraft|{n} кроків ще не мають відповідника в PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Збережено {n} операцію до {file}|Збережено {n} операції до {file}|Збережено {n} операцій до {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Пропущено {n} крок без відповідника в Photoshop|Пропущено {n} кроки без відповідника в Photoshop|Пропущено {n} кроків без відповідника в Photoshop - File Naming Іменування файлів Starting serial Початковий порядковий номер -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Вставити зупинку… Save Set… Зберегти набір… Message: Повідомлення: @@ -3941,11 +3981,8 @@ curves Smooth Згладити Step {step} is waiting for its dialog Крок {step} очікує на свій діалог @plural {n} action|{n} actions {n} операція|{n} операції|{n} операцій Background (Default) Фон (типовий) -# Batch / Image Processor Include All Subfolders Включити всі вкладені папки Auto Add/Delete Автододавання/видалення - -# 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… Не забудьте вимкнути керування кольором самого принтера в параметрах друку… @@ -3990,7 +4027,6 @@ curves Smooth Згладити Could not write {name}: {error} Не вдалося записати {name}: {error} Kept {name}: written by another application {name} залишено без змін: записаний іншою програмою Shadow Tint Відтінок тіней -# PhotoCraft release checks. Check for Updates… Перевірити оновлення… PhotoCraft Updates Оновлення PhotoCraft Checking for updates… Перевірка оновлень… @@ -4003,35 +4039,27 @@ curves Smooth Згладити Automatically Check for Updates Автоматично перевіряти оновлення Installed version: {version} Встановлена версія: {version} PhotoCraft {version} is available. Доступна версія PhotoCraft {version}. -# History panel › History Brush source (#2966) Paints from the History panel's source state Малює з вихідного стану панелі «Історія» Sets the source for the history brush Задає джерело для пензля історії -# Bevel & Emboss shading controls. Highlight Mode Режим світлих тонів Highlight Color Колір світлих тонів Highlight Opacity Непрозорість світлих тонів Shadow Mode Режим тіней Shadow Color Колір тіней Shadow Opacity Непрозорість тіней -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Використати вбудований профіль ({profile}) Convert to the working space ({profile}) Перетворити в робочий простір ({profile}) Remember this choice for future images Запам’ятати цей вибір для наступних зображень Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Знову ввімкнути запитання можна параметром Ask On Mismatch у Редагування › Налаштування кольору. Button Mode Режим кнопок Button Mode On Режим кнопок увімкнено - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Зробити інтерфейс темнішим Lighten Interface Зробити інтерфейс світлішим -# Bevel & Emboss Technique. Technique Метод Chisel Hard Жорстке різьблення Chisel Soft М'яке різьблення Open color-less EXR as ACEScg Відкривати EXR без колірного профілю як ACEScg Do not append "copy" to filename when saving a copy Не додавати «copy» до імені файлу під час збереження копії - -# View › Guides › right-click a guide Edit Selected Guides Редагувати вибрані напрямні Clear Selected Guides Очистити вибрані напрямні Bicubic Automatic Бікубічна, автоматично @@ -4056,8 +4084,6 @@ curves Smooth Згладити set name назва набору {set} (modified) {set} (змінено) Show file name in title Показувати ім’я файла в заголовку - -# Image › Mode › Bitmap (#5559) 50% Threshold Поріг 50% Pattern Dither Візерунковий дизеринг Diffusion Dither Дифузійний дизеринг @@ -4075,10 +4101,8 @@ curves Smooth Згладити Undo Changes Скасувати зміни {shortcut} is reserved by the system and can't be assigned. {shortcut} зарезервовано системою, його не можна призначити. Low-Latency Drawing (vsync off, applies at next launch) Малювання з малою затримкою (без вертикальної синхронізації, після перезапуску) -# Free Transform: a new layer while the box is open (#5859) Free Transform is still being applied; try again when it has finished. Вільне трансформування ще застосовується; спробуйте знову, коли воно завершиться. The transform couldn't be applied. Не вдалося застосувати трансформування. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Його шарам потрібно {needed} пам'яті GPU; бюджет залишає їм {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Задайте «Пам'ять GPU» в Налаштування › Продуктивність відповідно до того, скільки вміщує ваша відеокарта, не більше 3/8 її пам'яті. «Автоматично» стежить за використанням пам'яті, у межах чверті пам'яті цього комп'ютера й 3/8 пам'яті відеокарти, і не враховує документ на відеокарті з відомим обсягом пам'яті. Поки шари не вміщуються, рядок стану показує «Пам'ять GPU заповнена». GPU Memory Full Пам'ять GPU заповнена @@ -4103,7 +4127,6 @@ curves Smooth Згладити First Brush Перший пензель Last Brush Останній пензель Preview size Preview size -# Dynamic color-picker titles and warnings about losing editable layer content. Color Picker (Background Color) Вибір кольору (колір тла) Color Picker (Foreground Color) Вибір кольору (основний колір) Color Picker (Custom Canvas Color) Вибір кольору (власний колір полотна) @@ -4118,8 +4141,6 @@ curves Smooth Згладити 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. Найшвидший і найм'якший, з кольоровою облямівкою на дрібних деталях. - Move Up Перемістити вгору - Move Down Перемістити вниз Memory Usage Використання пам’яті Per-document RAM limit (MB) Ліміт RAM на документ (МБ) Installed RAM: {ram} MB; this limit: {percent}% Встановлено RAM: {ram} МБ; цей ліміт: {percent}% @@ -4129,27 +4150,18 @@ curves Smooth Згладити Use Використати In Front Спереду Behind Ззаду - -# DDS Options (#1327) DDS Options Параметри DDS Compression Стиснення Generate Mipmaps Створити MIP-карти - -# Color Table (.act) dialog There is no color table to save. Немає таблиці кольорів для збереження. @plural Saved {n} color to {file}|Saved {n} colors to {file} Збережено {n} колір у {file}|Збережено {n} кольори у {file}|Збережено {n} кольорів у {file} - -# Graphics Adapter preference (#1885) GPU adapter Адаптер GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Імпортувати стилі… Export Selected Styles… Експортувати вибрані стилі… Export Styles… Експортувати стилі… {file} is not a style library (.asl) {file} не є бібліотекою стилів (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Імпортовано {n} стиль з {file}|Імпортовано {n} стилі з {file}|Імпортовано {n} стилів з {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Експортовано {n} стиль до {file}|Експортовано {n} стилі до {file}|Експортовано {n} стилів до {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Спочатку підтвердьте або скасуйте відкритий діалог кроку операції Pro Medium Gray Середньосіра «Профі» Solarized Solarized @@ -4158,29 +4170,11 @@ curves Smooth Згладити Pro Light Світла «Профі» Resize Windows to Fit Підганяти розмір вікон EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Автоматичний напрямок абзацу Left-to-right paragraph direction Напрямок абзацу зліва направо Right-to-left paragraph direction Напрямок абзацу справа наліво Not rendered: this adjustment ({key}) is kept as imported. Не відображається: це коригування ({key}) збережено як було імпортовано. -# Print preview image (#8236) Print preview image Print preview image - Clear Selection Очистити виділення - Color Aware З урахуванням кольору - Decontaminate Colors Очистити кольори - Edge Detection Виявлення краю - Global Refinements Глобальне уточнення - High Quality Preview Високоякісний перегляд - Object Aware З урахуванням об'єктів - Real-Time Refinement Уточнення в реальному часі - Refine Edge Brush Tool Інструмент «Пензель уточнення краю» - Refine Hair Уточнити волосся - Refine Mode Режим уточнення - Remember Settings Запам'ятати параметри - View Mode Режим перегляду - Object Aware needs a segmentation model, which isn't available yet Для режиму «З урахуванням об'єктів» потрібна модель сегментації, яка ще недоступна - Refine Hair needs hair detection, which isn't available yet Для уточнення волосся потрібне розпізнавання волосся, яке ще недоступне -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Куб тону Brightness Cube Куб яскравості Color Wheel Колірне коло @@ -4196,9 +4190,8 @@ curves Smooth Згладити Grayscale Ramp Шкала градацій сірого Current Colors Поточні кольори Make Ramp Web Safe Зробити шкалу безпечною для вебу - Select and Mask was closed: its document is no longer the active one Вікно «Виділити та маскувати» закрито: його документ більше не активний - Select and Mask was closed: another layer was selected Вікно «Виділити та маскувати» закрито: вибрано інший шар -# Art History Brush (#213). + The path was kept as the Work Path Контур збережено як робочий контур + The path was discarded Контур видалено Art History Brush Tool Інструмент «Художній пензель історії» Tight Short Щільний короткий Tight Medium Щільний середній @@ -4209,9 +4202,24 @@ curves Smooth Згладити Tight Curl Щільний завиток Loose Curl Вільний завиток Stylized dabs from a history state Стилізовані мазки зі стану історії - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Ціль Font size presets Набори розмірів шрифту Leading presets Набори інтерліньяжу Tracking presets Набори трекінгу + Clear Selection Очистити виділення + Color Aware З урахуванням кольору + Decontaminate Colors Очистити кольори + Edge Detection Виявлення краю + Global Refinements Глобальне уточнення + High Quality Preview Високоякісний перегляд + Object Aware З урахуванням об'єктів + Real-Time Refinement Уточнення в реальному часі + Refine Edge Brush Tool Інструмент «Пензель уточнення краю» + Refine Hair Уточнити волосся + Refine Mode Режим уточнення + Remember Settings Запам'ятати параметри + View Mode Режим перегляду + Object Aware needs a segmentation model, which isn't available yet Для режиму «З урахуванням об'єктів» потрібна модель сегментації, яка ще недоступна + Refine Hair needs hair detection, which isn't available yet Для уточнення волосся потрібне розпізнавання волосся, яке ще недоступне + Select and Mask was closed: its document is no longer the active one Вікно «Виділити та маскувати» закрито: його документ більше не активний + Select and Mask was closed: another layer was selected Вікно «Виділити та маскувати» закрито: вибрано інший шар diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 19e66e6287..7c0032b164 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -21,20 +21,151 @@ # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… Tùy chọn mặt nạ… - Layer Mask Display Options… Tùy chọn hiển thị mặt nạ lớp… # Channel Options and New Spot Channel (#3761) + +# Phase 3.1 — top-level menus, File menu, Edit menu +# Custom paper dimensions in Print Settings. + + + +# Phase 3.2 — Image menu, Layer menu + + +# Phase 3.3 — Type menu, Select menu + + +# Phase 3.4 — Filter menu +# Field Blur pins (#3373) + + +# Phase 3.5 — View menu + + +# Phase 3.6 — Window menu, Help menu + + +# Phase 3.7 — tool names + Tool Options bar + + +# Phase 3.8 — Layers + Properties + History panel internals + + +# Phase 3.9 — Character + Paragraph + Glyphs typography panels + + +# Phase 3.10 — Brushes + Brush Settings panel internals + +# Phase 3.11 — Gradients + Patterns + Swatches asset panels + +# Phase 3.12 — Channels + Paths + Navigator + Info + Histogram + +# Mixer Brush (required for every registered non-English language) + +# Camera Raw labels (required for every registered non-English language) + +# Phase 4.1 — Preferences dialog + + +# Phase 4.2 — general dialogs, status/progress, warnings/errors + +# Phase 4.3 — Keyboard Shortcuts and Menus editor + +# Phase 4.4 — Color Settings dialog + +# Phase 4.5 — Preset Manager + Export/Import Presets + +# Phase 4.6 — Camera Raw chrome + Light/Color basics (tone, WB, presence) + +# Phase 4.7 — Camera Raw Curve + Color Mixer + +# Phase 4.8 — Camera Raw Color Grading + Detail + +# Phase 4.10 — Camera Raw Effects (Texture/Clarity/Dehaze + Vignetting + Grain) + +# Phase 4.13 — New Document + Home + Image Size + +# Phase 4.14 — Export / Save for Web / TIFF options + +# Phase 4.15 — Warp / Liquify / Perspective / Puppet + +# Gap Batch 4 — Layer Comps / Styles leftovers / Color Range / plurals / command palette + +# Visual QA finalization + +# Post-rebase gate-required strings + +# Phase 5.1 — tools / paths / assets / filters / layers + +# Phase 5.2 — dialogs / chrome / preferences / file UI / engine labels + +# Phase 5.3A — print / proof + +# Phase 5.3B — specialist workflows + +# Phase 5.4 — Help / About / credits + +# Phase 5.5 — final stable-key completion + +# Phase 5.6 — upstream kys first-launch import prompt + +# Upstream sync after rebase onto main + +# Labels added on main since this catalog was written (maintainer pass) + +# Rows from @tonguyenducmanh's Vietnamese catalog (#3453), merged here so the catalog is complete + +# Remaining labels (maintainer pass) +# Edit › Content-Aware Fill workspace + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Batch / Image Processor + +# Native Windows printing qualification +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) + +# Layers panel options and Smart Filter editors + +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) + Mask Options… Tùy chọn mặt nạ… + Layer Mask Display Options… Tùy chọn hiển thị mặt nạ lớp… Channel Color Màu kênh Color Indicates: Màu biểu thị: Solidity: Độ đặc: Ink Characteristics Đặc tính mực - -# Phase 3.1 — top-level menus, File menu, Edit menu -# Custom paper dimensions in Print Settings. Paper Width Chiều rộng giấy Paper Height Chiều cao giấy - Again Lặp lại AI Integrations… Tích hợp AI… All Tất cả @@ -200,9 +331,6 @@ WIA Support… Hỗ trợ WIA… Window Cửa sổ Workspace… Không gian làm việc… - - -# Phase 3.2 — Image menu, Layer menu 16 Bits/Channel 16 bit/kênh 180° 180° 32 Bits/Channel 32 bit/kênh @@ -335,6 +463,7 @@ Median Trung vị Merge Layers Gộp lớp Merge Shape Components Gộp thành phần hình + Path operations Thao tác đường dẫn Merge Visible Gộp các lớp hiển thị Minimum Cực tiểu Mode Chế độ @@ -410,9 +539,6 @@ Vibrance… Độ sống động… Video Video Video Layers Lớp video - - -# Phase 3.3 — Type menu, Select menu Anti-Alias Khử răng cưa Border… Viền… Character Panel Bảng ký tự @@ -486,9 +612,6 @@ Warp Text… Biến dạng chữ… Windows Windows Windows LCD Windows LCD - - -# Phase 3.4 — Filter menu Adaptive Wide Angle… Góc rộng thích ứng… Add Noise… Thêm nhiễu… Average Trung bình @@ -513,7 +636,6 @@ Facet Mặt cắt Fibers… Sợi… Field Blur… Làm mờ vùng… -# Field Blur pins (#3373) No pin selected Chưa chọn ghim nào Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Bấm vào ảnh để thêm ghim; kéo ghim để di chuyển, hoặc kéo vòng của ghim để đổi độ mờ. Delete xóa ghim đã chọn. Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. Kéo các tay nắm trên đường viền để đổi kích thước và xoay, kéo ô vuông để bo tròn góc, và kéo các chấm bên trong để đặt nơi bắt đầu làm mờ. @@ -575,9 +697,6 @@ Wave… Sóng… Wind… Gió… ZigZag… Zigzag… - - -# Phase 3.5 — View menu 100% 100% 105% 105% 110% 110% @@ -654,9 +773,6 @@ Working Yellow Plate Bản Yellow làm việc Zoom In Phóng to Zoom Out Thu nhỏ - - -# Phase 3.6 — Window menu, Help menu 2-up Horizontal 2 cửa sổ ngang 2-up Vertical 2 cửa sổ dọc 3-up Horizontal 3 cửa sổ ngang @@ -729,9 +845,6 @@ Tool Presets Thiết lập sẵn công cụ Tools Công cụ Workspace Không gian làm việc - - -# Phase 3.7 — tool names + Tool Options bar Move Tool Công cụ Di chuyển Rectangular Marquee Tool Công cụ Vùng chọn chữ nhật Elliptical Marquee Tool Công cụ Vùng chọn elip @@ -923,11 +1036,9 @@ Align horizontal centers Căn tâm ngang Align right edges Căn cạnh phải Drag to move the active shape's path or the Work Path Kéo để di chuyển đường dẫn hình đang chọn hoặc Đường dẫn làm việc + Drag to move the selected path Kéo để di chuyển đường dẫn đã chọn Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Bấm: góc · Kéo: mượt · Bấm điểm đầu: đóng · {key} xong · Esc hủy Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath Bấm: chọn điểm neo · Kéo: di chuyển điểm neo, tay nắm hoặc đoạn · {shift}-bấm: thêm · {alt}-bấm: cả nhánh con - - -# Phase 3.8 — Layers + Properties + History panel internals Pixel Layer Lớp pixel Type Layer Lớp chữ Shape Layer Lớp hình @@ -957,6 +1068,9 @@ Delete layer Xóa lớp Link layers Liên kết lớp Add a layer style Thêm kiểu lớp + Move effect up Chuyển hiệu ứng lên + Move effect down Chuyển hiệu ứng xuống + Delete effect Xóa hiệu ứng Add a mask (from the selection; {key} inverts) Thêm mặt nạ (từ vùng chọn; {key} đảo) No document Không có tài liệu Collapse Thu gọn @@ -1057,9 +1171,6 @@ Use Legacy Dùng bản cũ Violet, Orange Tím, Cam Yellow · Blue Vàng · Xanh dương - - -# Phase 3.9 — Character + Paragraph + Glyphs typography panels Font size Cỡ chữ Leading Giãn dòng Leading (set to the font size × auto-leading when Auto) Giãn dòng (đặt bằng cỡ chữ × giãn dòng tự động khi Tự động) @@ -1131,9 +1242,6 @@ Symbols Ký hiệu Math Symbols Ký hiệu toán Arrows Mũi tên - - -# Phase 3.10 — Brushes + Brush Settings panel internals Brush Tip Shape Hình dạng đầu cọ Shape Dynamics Biến thiên hình dạng Scattering Phân tán @@ -1231,8 +1339,6 @@ Linear Burn Đốt tuyến tính Hard Mix Trộn cứng Linear Height Cao tuyến tính - -# Phase 3.11 — Gradients + Patterns + Swatches asset panels Gradient Chuyển sắc Gradient Options Tùy chọn chuyển sắc Linear Tuyến tính @@ -1254,8 +1360,6 @@ Thumbnail size (smallest: list) Cỡ hình thu nhỏ (nhỏ nhất: danh sách) Color & Swatches Màu & Mẫu màu Click sets foreground · right-click sets background Bấm đặt nền trước · chuột phải đặt nền - -# Phase 3.12 — Channels + Paths + Navigator + Info + Histogram Show the layer mask as an overlay Hiện mặt nạ lớp dạng phủ Toggle visibility Hiện/ẩn Load channel as selection Tải kênh thành vùng chọn @@ -1308,8 +1412,6 @@ Median: Trung vị: Pixels: Pixel: Cache Level: Mức đệm: - -# Mixer Brush (required for every registered non-English language) Mixer Brush Cọ trộn Mixer Brush Tool Công cụ Cọ trộn Wet Ướt @@ -1322,8 +1424,6 @@ Mix Trộn Flow Lưu lượng Sample All Layers Lấy mẫu mọi lớp - -# Camera Raw labels (required for every registered non-English language) Amount Mức Aqua Xanh ngọc Balance Cân bằng @@ -1408,8 +1508,6 @@ cameraRaw Masking Mặt nạ cameraRaw Blending Độ hòa trộn cameraRaw Highlights Vùng sáng cameraRaw Shadows Vùng tối - -# Phase 4.1 — Preferences dialog 125% 125% 150% 150% 175% 175% @@ -1559,9 +1657,6 @@ cameraRaw Shadows Vùng tối Vulkan Vulkan Webp WebP Zoom with scroll wheel Thu phóng bằng bánh xe cuộn - - -# Phase 4.2 — general dialogs, status/progress, warnings/errors Yes Có No Không Don't Save Không lưu @@ -1621,8 +1716,6 @@ cameraRaw Shadows Vùng tối Retry GPU tries the graphics processor again now. Thử lại GPU sẽ thử lại bộ xử lý đồ họa ngay bây giờ. GPU acceleration resumed. Đã tiếp tục tăng tốc GPU. Keep Using CPU Tiếp tục dùng CPU - -# Phase 4.3 — Keyboard Shortcuts and Menus editor Keyboard Shortcuts and Menus Phím tắt và menu Keyboard Shortcuts Phím tắt Menus Menu @@ -1653,8 +1746,6 @@ cameraRaw Shadows Vùng tối blue Xanh dương violet Tím gray Xám - -# Phase 4.4 — Color Settings dialog Color Settings Cài đặt màu Black Point Compensation Bù điểm đen Working Rgb RGB làm việc @@ -1688,8 +1779,6 @@ cameraRaw Shadows Vùng tối Color Management Policies Chính sách quản lý màu Relative Colorimetric Đo màu tương đối Absolute Colorimetric Đo màu tuyệt đối - -# Phase 4.5 — Preset Manager + Export/Import Presets Preset Manager Quản lý thiết lập sẵn Export/Import Presets Xuất/Nhập thiết lập sẵn Preset Type Loại thiết lập sẵn @@ -1701,8 +1790,6 @@ cameraRaw Shadows Vùng tối Action Thao tác Export Presets Xuất thiết lập sẵn Import Presets Nhập thiết lập sẵn - -# Phase 4.6 — Camera Raw chrome + Light/Color basics (tone, WB, presence) Fit in View Vừa khung nhìn Camera Raw Camera Raw cameraRaw Color Màu @@ -1716,8 +1803,6 @@ cameraRaw Dehaze Khử sương cameraRaw Temperature Nhiệt độ màu cameraRaw Vibrance Độ sống động cameraRaw Saturation Độ bão hòa - -# Phase 4.7 — Camera Raw Curve + Color Mixer cameraRaw Curve Đường cong cameraRaw Color Mixer Bộ trộn màu cameraRaw Hue Sắc màu @@ -1730,8 +1815,6 @@ cameraRaw Aqua Xanh ngọc cameraRaw Blue Xanh dương cameraRaw Purple Tím cameraRaw Magenta Đỏ tía - -# Phase 4.8 — Camera Raw Color Grading + Detail cameraRaw Color Grading Phân cấp màu cameraRaw Midtones Tông trung gian cameraRaw Global Tổng thể @@ -1740,15 +1823,11 @@ cameraRaw Detail Chi tiết cameraRaw Radius Bán kính cameraRaw Luminance Detail Chi tiết độ sáng cameraRaw Color Detail Chi tiết màu - -# Phase 4.10 — Camera Raw Effects (Texture/Clarity/Dehaze + Vignetting + Grain) cameraRaw Feather Độ mềm cạnh cameraRaw Midpoint Điểm giữa cameraRaw Roundness Độ tròn cameraRaw Roughness Độ thô cameraRaw Size Kích thước - -# Phase 4.13 — New Document + Home + Image Size Home Trang chủ Recent Gần đây Photo Ảnh @@ -1798,8 +1877,6 @@ document Orientation Hướng trang 32 bit (float) 32-bit (float) Integer Số nguyên Floating point Số thực - -# Phase 4.14 — Export / Save for Web / TIFF options File Settings Cài đặt tệp Transparency Độ trong suốt TIFF Options Tùy chọn TIFF @@ -1828,8 +1905,6 @@ document Orientation Hướng trang All Slices Mọi lát cắt All User Slices Mọi lát cắt người dùng Matte Matte - -# Phase 4.15 — Warp / Liquify / Perspective / Puppet Warp: Biến dạng: Bend: Độ uốn: Split: Chia: @@ -1904,8 +1979,6 @@ document Orientation Hướng trang Fixed Cố định Remove All Pins Xóa mọi ghim Commit Puppet Warp ({key}) Áp dụng biến dạng con rối ({key}) - -# Gap Batch 4 — Layer Comps / Styles leftovers / Color Range / plurals / command palette Last Document State Trạng thái tài liệu cuối Capture the visibility, position and style of every layer with + below, then switch between versions. Dùng + bên dưới để ghi hiển thị, vị trí và kiểu của mọi lớp, rồi chuyển giữa các phiên bản. Visibility Hiển thị @@ -1990,8 +2063,6 @@ colorRange Invert Đảo ngược No matching commands Không tìm thấy lệnh ↑↓ navigate {key} run esc close ↑↓ điều hướng {key} chạy esc đóng Tool Công cụ - -# Visual QA finalization New document… Tài liệu mới… Join us on Discord Tham gia Discord PhotoCraft website Trang web PhotoCraft @@ -1999,8 +2070,6 @@ colorRange Invert Đảo ngược Canvas extension color: Màu mở rộng canvas: layers Fill Độ tô layers Fill: Độ tô: - -# Post-rebase gate-required strings Pattern Stamp Tool Công cụ Con dấu họa tiết Pattern Stamp Con dấu họa tiết Impressionist Ấn tượng @@ -2009,8 +2078,6 @@ layers Fill: Độ tô: Open Mở Camera Raw ({name}) Camera Raw ({name}) Developing {name} Đang xử lý {name} - -# Phase 5.1 — tools / paths / assets / filters / layers 101 by 101 Average Trung bình 101 × 101 11 by 11 Average Trung bình 11 × 11 3 by 3 Average Trung bình 3 × 3 @@ -2030,6 +2097,8 @@ layers Fill: Độ tô: Bitmap… Bitmap… Blend If Điều kiện hòa trộn Blend If: Điều kiện hòa trộn: + Current Layer: Lớp hiện tại: + Underlying Layer: Lớp bên dưới: Bottom Left Dưới trái Bottom Right Dưới phải Brush Name Tên cọ @@ -2148,8 +2217,6 @@ layers Fill: Độ tô: Weight Độ dày Zoom in Phóng to Zoom out Thu nhỏ - -# Phase 5.2 — dialogs / chrome / preferences / file UI / engine labels A save to {name} is still running; try again when it finishes Đang lưu {name}; thử lại khi hoàn tất Adwaita Dark Theme Chủ đề Adwaita tối Adwaita Light Theme Chủ đề Adwaita sáng @@ -2239,8 +2306,6 @@ layers Fill: Độ tô: {size} (was {old}) {size} (trước là {old}) {w} px x {h} px ({ppi} ppi) {w} px x {h} px ({ppi} ppi) …and {n} more …và {n} nữa - -# Phase 5.3A — print / proof (print to the printer) (in ra máy in) Adobe RGB (1998) compatible Tương thích Adobe RGB (1998) Center Crop Marks Dấu cắt giữa @@ -2256,8 +2321,6 @@ layers Fill: Độ tô: Printer Setup Thiết lập máy in Printing Marks Dấu in Registration Marks Dấu chồng màu - -# Phase 5.3B — specialist workflows + Add variable + Thêm biến 30 frames @ 30 fps 30 khung hình @ 30 fps 3D LUT File Tệp 3D LUT @@ -2317,8 +2380,6 @@ layers Fill: Độ tô: Suggestions: Gợi ý: Text Position: Vị trí văn bản: Variables bind a layer's visibility, text or pixels to a named data slot. Biến gắn trạng thái hiện, văn bản hoặc pixel của lớp với một khe dữ liệu có tên. - -# Phase 5.4 — Help / About / credits % of all commits % tổng số commit @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commit, dòng +{added} / −{deleted} (Δ {delta}), tài sản nhị phân +{binAdded} / −{binDeleted}, {first} – {last} 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 0 tắt ngưỡng này; nhóm SVG lồng nhau sâu hơn 100 cấp luôn được raster hóa. @@ -2349,8 +2410,6 @@ layers Fill: Độ tô: Table Bảng Username Tên người dùng Version Phiên bản - -# Phase 5.5 — final stable-key completion Active Đang dùng Add Thêm Appearance Giao diện @@ -2377,16 +2436,12 @@ shape Appearance Diện mạo Tetrahedral Tetrahedral Top Trên Trilinear Trilinear - -# Phase 5.6 — upstream kys first-launch import prompt Show channels in color Hiện kênh bằng màu Import keyboard shortcuts? Nhập phím tắt? PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it? PhotoCraft tìm thấy bộ phím tắt {set} từ trình chỉnh sửa ảnh khác trên máy này: {n} phím tắt khác với PhotoCraft. Nhập vào? Edit › Keyboard Shortcuts › Reset All to Defaults undoes an import. Chỉnh sửa › Phím tắt › Đặt lại tất cả về mặc định sẽ hoàn tác lần nhập. Don't Import Không nhập The keyboard shortcut set was not imported: {error} Không nhập được bộ phím tắt: {error} - -# Upstream sync after rebase onto main Auto Center Preview Tự động căn giữa xem trước Brush Cọ Color Picker ({name}) Bộ chọn màu ({name}) @@ -2402,8 +2457,6 @@ shape Appearance Diện mạo Use Classic Mode Dùng chế độ cổ điển W x H x Resolution Rộng x Cao x Độ phân giải Block Khối - -# Labels added on main since this catalog was written (maintainer pass) (No neutral color exists for {mode} mode.) (Không có màu trung tính cho chế độ {mode}.) 24 bits/pixel 24 bit/pixel 32 bits/pixel 32 bit/pixel @@ -2558,8 +2611,6 @@ shape Appearance Diện mạo @plural {n} step|{n} steps {n} bước @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} cảnh báo thiết lập sẵn cọ khác) @plural {what} with {n} warning|{what} with {n} warnings {what} với {n} cảnh báo - -# Rows from @tonguyenducmanh's Vietnamese catalog (#3453), merged here so the catalog is complete (coming soon) (sắp có) Add beauty precomp from the AOVs Thêm precomp beauty từ các AOV Show in Explorer Hiện trong Explorer @@ -3596,8 +3647,6 @@ cameraData Lens Ống kính sRGB IEC61966-2.1 sRGB IEC61966-2.1 shortcut phím tắt Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Kéo (dây mềm) hoặc bấm các điểm (đa giác) · {add} thêm · {sub} trừ - -# Remaining labels (maintainer pass) Selected Artboards Các artboard đã chọn 5 Columns, 3 Rows 5 cột, 3 hàng 8 Columns 8 cột @@ -3646,7 +3695,6 @@ curves Smooth Làm mượt Delete Contour Xóa đường viền Loaded contours from {file} Đã tải đường viền từ {file} Saved contours to {file} Đã lưu đường viền vào {file} -# Edit › Content-Aware Fill workspace Excluded Area Vùng loại trừ Fill Settings Cài đặt tô Full Toàn phần @@ -3666,8 +3714,6 @@ curves Smooth Làm mượt Clear Brush Controls Xóa điều khiển cọ Reset All Locked Settings Đặt lại tất cả cài đặt đã khóa Copy Texture to Other Tools Sao chép họa tiết sang các công cụ khác - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… Nạp hành động… Save Actions… Lưu hành động… New Action… Hành động mới… @@ -3679,10 +3725,8 @@ curves Smooth Làm mượt @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} bước chưa có chức năng tương ứng trong PhotoCraft @plural Saved {n} action to {file}|Saved {n} actions to {file} Đã lưu {n} hành động vào {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Đã bỏ qua {n} bước không có chức năng tương ứng trong Photoshop - File Naming Đặt tên tệp Starting serial Số thứ tự bắt đầu -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… Chèn điểm dừng… Save Set… Lưu bộ… Message: Thông báo: @@ -3692,24 +3736,19 @@ curves Smooth Làm mượt Action playback stopped Đã dừng phát hành động Step {step} is waiting for its dialog Bước {step} đang chờ hộp thoại của nó @plural {n} action|{n} actions {n} hành động -# History panel menu (#2966) Step Forward Tiến một bước New Snapshot… Ảnh chụp trạng thái mới… Clear History Xóa lịch sử History Options… Tùy chọn lịch sử… Background (Default) Nền (mặc định) -# History panel › History Options… (#2966) Allow Non-Linear History Cho phép lịch sử không tuyến tính Make Layer Visibility Changes Undoable Cho phép hoàn tác thay đổi hiển thị lớp Presentation Trình bày -# Batch / Image Processor Include All Subfolders Bao gồm tất cả thư mục con Gradient Preset Options Tùy chọn thiết lập sẵn chuyển sắc Import .GRD Nhập .GRD Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd). Auto Add/Delete Tự động thêm/xóa - -# Native Windows printing qualification 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… @@ -3766,35 +3805,27 @@ curves Smooth Làm mượt Automatically Check for Updates Tự động kiểm tra bản cập nhật Installed version: {version} Phiên bản đã cài: {version} PhotoCraft {version} is available. PhotoCraft {version} đã có sẵn. -# History panel › History Brush source (#2966) Paints from the History panel's source state Vẽ từ trạng thái nguồn của bảng Lịch sử Sets the source for the history brush Đặt nguồn cho cọ lịch sử -# Bevel & Emboss shading controls. Highlight Mode Chế độ vùng sáng Highlight Color Màu vùng sáng Highlight Opacity Độ mờ vùng sáng Shadow Mode Chế độ bóng Shadow Color Màu bóng Shadow Opacity Độ mờ bóng -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) Dùng hồ sơ nhúng ({profile}) Convert to the working space ({profile}) Chuyển sang không gian làm việc ({profile}) Remember this choice for future images Ghi nhớ lựa chọn này cho các ảnh sau Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. Bật lại câu hỏi bằng Ask On Mismatch trong Chỉnh sửa › Cài đặt màu. Button Mode Chế độ nút Button Mode On Chế độ nút bật - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface Làm tối giao diện Lighten Interface Làm sáng giao diện -# Bevel & Emboss Technique. Technique Kỹ thuật Chisel Hard Đục cứng Chisel Soft Đục mềm Open color-less EXR as ACEScg Mở EXR không khai báo màu sắc dưới dạng ACEScg Do not append "copy" to filename when saving a copy Không thêm "copy" vào tên tệp khi lưu bản sao - -# View › Guides › right-click a guide Edit Selected Guides Sửa đường căn đã chọn Clear Selected Guides Xóa đường căn đã chọn Bicubic Automatic Bicubic tự động @@ -3819,8 +3850,6 @@ curves Smooth Làm mượt set name tên bộ {set} (modified) {set} (đã sửa đổi) Show file name in title Hiển thị tên tệp trong tiêu đề - -# Image › Mode › Bitmap (#5559) 50% Threshold Ngưỡng 50% Pattern Dither Hòa sắc họa tiết Diffusion Dither Hòa sắc khuếch tán @@ -3830,8 +3859,6 @@ curves Smooth Làm mượt Lines/Inch Đường/inch Lines/Centimeter Đường/centimet Ellipse Elip - -# Layers panel options and Smart Filter editors Add “copy” to Copied Layers and Groups Thêm “bản sao” vào lớp và nhóm được sao chép Animation Options Tùy chọn hoạt ảnh Entire Document Toàn bộ tài liệu @@ -3849,7 +3876,6 @@ curves Smooth Làm mượt Thumbnail Contents Nội dung hình thu nhỏ Thumbnail Size Kích thước hình thu nhỏ Use Default Masks on Fill Layers Dùng mặt nạ mặc định cho lớp tô - Blending Options ({filter}) Tùy chọn hòa trộn ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Ẩn hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp) Opacity must be between 0% and 100%. Độ mờ phải nằm trong khoảng từ 0% đến 100%. @@ -3865,11 +3891,9 @@ curves Smooth Làm mượt Undo Changes Hoàn tác thay đổi {shortcut} is reserved by the system and can't be assigned. {shortcut} được hệ thống dành riêng và không thể gán. Low-Latency Drawing (vsync off, applies at next launch) Vẽ độ trễ thấp (tắt vsync, áp dụng ở lần khởi động sau) -# Free Transform: a new layer while the box is open (#5859) Reference point location Vị trí điểm tham chiếu Free Transform is still being applied; try again when it has finished. Biến đổi tự do vẫn đang được áp dụng; hãy thử lại khi hoàn tất. The transform couldn't be applied. Không thể áp dụng phép biến đổi. -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. Các lớp cần {needed} bộ nhớ GPU; ngân sách chỉ dành cho chúng {budget}. Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. Đặt Bộ nhớ GPU trong Tùy chọn › Hiệu năng bằng mức card đồ họa của bạn chứa được, tối đa 3/8 bộ nhớ của card. Tự động theo mức sử dụng bộ nhớ, trong giới hạn một phần tư bộ nhớ máy này và 3/8 bộ nhớ card, và không tính tài liệu vào card đã biết dung lượng bộ nhớ. Khi chúng chưa vừa, thanh trạng thái hiện Bộ nhớ GPU đầy. GPU Memory Full Bộ nhớ GPU đầy @@ -3896,8 +3920,6 @@ curves Smooth Làm mượt 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ỏ. “{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}”. - Move Up Di chuyển lên - Move Down Di chuyển xuống Previous Brush Cọ trước Next Brush Cọ tiếp theo First Brush Cọ đầu tiên @@ -3912,27 +3934,18 @@ curves Smooth Làm mượt Use Dùng In Front Phía trước Behind Phía sau - -# DDS Options (#1327) DDS Options Tùy chọn DDS Compression Nén Generate Mipmaps Tạo mipmap - -# Color Table (.act) dialog There is no color table to save. Không có bảng màu nào để lưu. @plural Saved {n} color to {file}|Saved {n} colors to {file} Đã lưu {n} màu vào {file} - -# Graphics Adapter preference (#1885) GPU adapter Bộ điều hợp GPU - -# Styles panel: Import / Export Styles (.asl) Import Styles… Nhập kiểu… Export Selected Styles… Xuất các kiểu đã chọn… Export Styles… Xuất kiểu… {file} is not a style library (.asl) {file} không phải là thư viện kiểu (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} Đã nhập {n} kiểu từ {file} @plural Exported {n} style to {file}|Exported {n} styles to {file} Đã xuất {n} kiểu sang {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first Hãy xác nhận hoặc hủy hộp thoại bước hành động đang mở trước Pro Medium Gray Pro xám vừa Solarized Solarized @@ -3941,29 +3954,11 @@ curves Smooth Làm mượt Pro Light Pro sáng Resize Windows to Fit Đổi cỡ cửa sổ cho vừa ảnh EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction Hướng đoạn văn tự động Left-to-right paragraph direction Hướng đoạn văn từ trái sang phải Right-to-left paragraph direction Hướng đoạn văn từ phải sang trái Not rendered: this adjustment ({key}) is kept as imported. Không được kết xuất: điều chỉnh này ({key}) được giữ nguyên như khi nhập. -# Print preview image (#8236) Print preview image Print preview image - Clear Selection Xóa vùng chọn - Color Aware Nhận biết màu - Decontaminate Colors Khử nhiễm màu - Edge Detection Phát hiện cạnh - Global Refinements Tinh chỉnh tổng thể - High Quality Preview Xem trước chất lượng cao - Object Aware Nhận biết đối tượng - Real-Time Refinement Tinh chỉnh theo thời gian thực - Refine Edge Brush Tool Công cụ cọ tinh chỉnh cạnh - Refine Hair Tinh chỉnh tóc - Refine Mode Chế độ tinh chỉnh - Remember Settings Ghi nhớ cài đặt - View Mode Chế độ xem - Object Aware needs a segmentation model, which isn't available yet Nhận biết đối tượng cần mô hình phân đoạn, hiện chưa có - Refine Hair needs hair detection, which isn't available yet Tinh chỉnh tóc cần tính năng phát hiện tóc, hiện chưa có -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube Khối sắc màu Brightness Cube Khối độ sáng Color Wheel Bánh xe màu @@ -3980,9 +3975,8 @@ curves Smooth Làm mượt Grayscale Ramp Dải thang xám Current Colors Màu hiện tại Make Ramp Web Safe Giới hạn dải màu ở màu web - Select and Mask was closed: its document is no longer the active one Đã đóng Chọn và Mặt nạ: tài liệu của nó không còn là tài liệu đang hoạt động - Select and Mask was closed: another layer was selected Đã đóng Chọn và Mặt nạ: một lớp khác đã được chọn -# Art History Brush (#213). + The path was kept as the Work Path Đường dẫn được giữ lại làm Đường dẫn làm việc + The path was discarded Đường dẫn đã bị loại bỏ Art History Brush Cọ lịch sử nghệ thuật Art History Brush Tool Công cụ Cọ lịch sử nghệ thuật Tight Short Chặt ngắn @@ -3994,9 +3988,25 @@ curves Smooth Làm mượt Tight Curl Xoắn chặt Loose Curl Xoắn lỏng Stylized dabs from a history state Các chấm cách điệu từ một trạng thái lịch sử - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Tỷ lệ khung hình Font size presets Cỡ chữ đặt sẵn Leading presets Giãn dòng đặt sẵn Tracking presets Khoảng cách chữ đặt sẵn + Clear Selection Xóa vùng chọn + Color Aware Nhận biết màu + Decontaminate Colors Khử nhiễm màu + Edge Detection Phát hiện cạnh + Global Refinements Tinh chỉnh tổng thể + High Quality Preview Xem trước chất lượng cao + Object Aware Nhận biết đối tượng + Real-Time Refinement Tinh chỉnh theo thời gian thực + Refine Edge Brush Tool Công cụ cọ tinh chỉnh cạnh + Refine Hair Tinh chỉnh tóc + Refine Mode Chế độ tinh chỉnh + Remember Settings Ghi nhớ cài đặt + View Mode Chế độ xem + Object Aware needs a segmentation model, which isn't available yet Nhận biết đối tượng cần mô hình phân đoạn, hiện chưa có + Refine Hair needs hair detection, which isn't available yet Tinh chỉnh tóc cần tính năng phát hiện tóc, hiện chưa có + Select and Mask was closed: its document is no longer the active one Đã đóng Chọn và Mặt nạ: tài liệu của nó không còn là tài liệu đang hoạt động + Select and Mask was closed: another layer was selected Đã đóng Chọn và Mặt nạ: một lớp khác đã được chọn + Select Layer Under Cursor Chọn lớp dưới con trỏ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1b423c1c29..8f59bf7098 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -12,10 +12,114 @@ # Product and technology names retain their spelling. See docs/localization-zh-hans.md. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… 蒙版选项… - Layer Mask Display Options… 图层蒙版显示选项… # Channel Options and New Spot Channel (#3761) + +# Guide layout dialog + +# Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) +# Counted status and panel messages + + +# Layers-panel trash confirmation + +# Camera Raw: contextual controls and window title +# Current shell labels and shortcut templates. Keep {key} platform-dependent. +# Gradient Editor window, opened from the options bar's gradient swatch. +# Layer navigation, copy transforms and cancellable opening (labels added on main since this catalog). +# Rendering mode and recovery + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# Export As metadata and profile options + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) + +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# File opening, export status and graphics driver information + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) +# Smart Filter row actions (#1265) + + Mask Options… 蒙版选项… + Layer Mask Display Options… 图层蒙版显示选项… Channel Color 通道颜色 Color Indicates: 色彩指示: Solidity: 密度: @@ -23,10 +127,6 @@ Selected Areas 所选区域 Spot Color 专色 Ink Characteristics 油墨特性 - -# Guide layout dialog - -# Custom print paper (#3820) Paper Width 纸张宽度 Paper Height 纸张高度 Columns 列 @@ -46,7 +146,6 @@ 5 Columns, 3 Rows 5列,3行 8 Columns 8列 12 Columns 12列 - File 文件 Edit 编辑 Image 图像 @@ -458,6 +557,7 @@ Intersect Shape Areas 形状区域相交 Exclude Overlapping Shapes 排除重叠形状 Merge Shape Components 合并形状组件 + Path operations 路径操作 Align 对齐 Top Edges 顶边 Vertical Centers 垂直居中 @@ -537,7 +637,6 @@ Color Range… 色彩范围… Focus Area… 焦点区域… Select and Mask… 选择与蒙版… -# Select and Mask dialog labels Smart Radius 智能半径 Shift Edge 移动边缘 Decontaminate 净化 @@ -564,7 +663,6 @@ Blur 模糊 Blur Gallery 模糊库 Field Blur… 场景模糊… -# Field Blur pins (#3373) No pin selected 未选择图钉 Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 单击图像以添加图钉;拖动图钉可移动它,拖动其圆环可更改模糊程度。按 Delete 键删除所选图钉。 Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. 拖动轮廓上的手柄可调整大小并旋转,拖动方块可将角变圆,拖动内部的点可设置模糊开始的位置。 @@ -829,7 +927,6 @@ Statistics… 统计… Refine Strokes 调整描边 Edits 编辑 -# Counted status and panel messages @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} 已将 {n} 个色板导出到 {file} @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} 已从 {file} 导入 {n} 个色板 @plural Imported {n} brush from {group}|Imported {n} brushes from {group} 已从 {group} 导入 {n} 个画笔 @@ -844,7 +941,6 @@ @plural {n} slice|{n} slices {n} 个切片 @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning}(另有 {n} 条画笔预设警告) @plural {what} with {n} warning|{what} with {n} warnings {what},含 {n} 条警告 - @plural {n} item|{n} items {n} 项 Auto 自动 (print to the printer) (输出到打印机) @@ -860,6 +956,9 @@ Add Layer Mask 添加图层蒙版 Add Stop 添加色标 Add a layer style 添加图层样式 + Move effect up 上移效果 + Move effect down 下移效果 + Delete effect 删除效果 Add a mask (from the selection; ⌥ inverts) 添加蒙版 (基于选区;⌥ 反相) Add an adjustment 添加调整 Add disk 添加磁盘 @@ -1090,8 +1189,6 @@ Delete current channel 删除当前通道 Delete current state 删除当前状态 Delete effect layer 删除效果图层 - -# Layers-panel trash confirmation Delete layer ‘{name}’? 删除图层“{name}”? Delete {count} layers? {names} 删除 {count} 个图层?{names} Delete layer? 删除图层? @@ -1100,7 +1197,6 @@ Missing delete command 缺少删除命令 Invalid delete command 无效的删除命令 Layer deleted, but confirmation preference could not be saved: {error} 图层已删除,但无法保存确认设置:{error} - Delete layer 删除图层 Delete layer comp 删除图层复合 Delete note 删除注释 @@ -1133,7 +1229,6 @@ Dots 点 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 保持水平或垂直;右键单击约束可更改或删除。 - Drag to move the active shape's path or the Work Path 拖动以移动当前形状的路径或工作路径 Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath 单击:选择锚点 · 拖动:移动锚点、手柄或线段 · {shift}-单击:添加 · {alt}-单击:整个子路径 Draw with the Pen tool (P) or make a work path from a selection. 使用钢笔工具(P)绘制,或从选区创建工作路径。 Drop an image or PSD anywhere to open it. 将图像或 PSD 拖放到任意位置即可打开。 @@ -2171,7 +2266,6 @@ Tone Histogram 色调直方图 Show Selected Region 显示选定区域 cameraRaw Light 光线 -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Camera Raw 滤镜({layer}) Camera Raw ({name}) Camera Raw({name}) cameraRaw Lights 亮调 @@ -2187,7 +2281,6 @@ cameraRaw Blending 混合 Transform On Drop 放下时变换 Scale or rotate the moved area, then press {key} 缩放或旋转移动的区域,然后按 {key} Now drag the selection onto another area 现在将选区拖动到另一个区域 -# Current shell labels and shortcut templates. Keep {key} platform-dependent. Add a mask (from the selection; {key} inverts) 添加蒙版 (基于选区;{key} 反相) Add to selection ({key}) 添加到选区 ({key}) Click the first point or press {key} to close · Esc cancels 单击起点或按 {key} 闭合 · Esc 取消 @@ -2282,7 +2375,6 @@ cameraRaw Blending 混合 Align with layer 与图层对齐 Reset Alignment 重置对齐 Centre the gradient (offset 0, 0) 将渐变居中(偏移量 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor 渐变编辑器 Gradient picker 渐变拾色器 Save As Preset 存储为预设 @@ -2313,7 +2405,6 @@ cameraRaw Blending 混合 Use tablet pressure 使用数位板压感 Vulkan Vulkan No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 没有可用于生成选区的路径:请用钢笔工具绘制路径,或在路径面板中选择路径。 -# Layer navigation, copy transforms and cancellable opening (labels added on main since this catalog). Cancel opening 取消打开 Cancelled opening {name} 已取消打开 {name} Damaged Photoshop document 已损坏的 Photoshop 文档 @@ -2338,7 +2429,6 @@ cameraRaw Blending 混合 Opening… 正在打开… Reading… 正在读取… Working… 正在处理… -# Rendering mode and recovery Rendering Mode 渲染模式 Automatic (recommended) 自动(推荐) CPU / Compatibility CPU / 兼容模式 @@ -2356,14 +2446,10 @@ cameraRaw Blending 混合 Details 详细信息 Rendering mode 渲染模式 Edit Type 编辑文字 - - New Style… 新建样式… Style {name} saved 已保存样式 {name} - Create new style (from the selected type) 新建样式(基于所选文本) Create new style from the selected layer 从所选图层新建样式 - Make Default 设为默认 Reset to Default 重置为默认 Full-resolution preview unavailable 全分辨率预览不可用 @@ -2392,9 +2478,6 @@ cameraRaw Blending 混合 Magnetic Lasso Tool 磁性套索工具 Frequency 频率 Use tablet pressure to change pen width 使用绘图板压力以更改钢笔宽度 - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About 关于 Contributors 贡献者 Models 模型 @@ -2426,8 +2509,6 @@ cameraRaw Blending 混合 % of all commits 占全部提交的 % Lines +/− 行数 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}:{prs} 个 PR,{commits} 次提交,行 +{added} / −{deleted}(Δ {delta}),二进制文件 +{binAdded} / −{binDeleted},{first} – {last} - -# Swatches panel Create new swatch 创建新色板 New Swatch… 新建色板… New Swatch Group… 新建色板组… @@ -2437,13 +2518,12 @@ cameraRaw Blending 混合 Export Swatches for Exchange… 导出色板以供交换… Reset Swatches 复位色板 Add to Swatches 添加到色板 -# Layer Style > Blending Options (Advanced Blending) Blend If: 混合颜色带: + Current Layer: 当前图层: + Underlying Layer: 下一图层: Channels: 通道: Knockout 挖空 Apply At Canvas Bounds 应用画布边界的效果 - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) 拾色器(文字颜色) Color Picker ({name}) 拾色器({name}) Color Picker (Fill Color) 拾色器(填充颜色) @@ -2460,8 +2540,6 @@ cameraRaw Blending 混合 Show/Hide Panels 显示/隐藏面板 Could not open 无法打开 {path}: the path is not valid Unicode; rename the file and open it again. {path}:路径不是有效的 Unicode;请重命名文件后再打开。 - -# Fill dialog, layer style contours and Image Size Contents: 内容: Custom Pattern: 自定义图案: Foreground Color 前景色 @@ -2489,7 +2567,6 @@ cameraRaw Blending 混合 Rolling Slope - Descending 滚动斜坡 - 递减 Rounded Steps 圆角梯形 Sawtooth 1 锯齿 1 - Red Eye Tool 红眼工具 Red Eye 红眼 Pupil Size 瞳孔大小 @@ -2497,7 +2574,6 @@ cameraRaw Blending 混合 Click a red pupil to neutralize it 单击红色瞳孔以消除反光 open source 开源 …and {n} more …以及另外 {n} 项 - Eyedroppers: 吸管: Set Black Point 设置黑场 Set Neutral Gray Point 设置中性灰场 @@ -2506,8 +2582,6 @@ cameraRaw Blending 混合 Selection Preview: 选区预览: Black Matte 黑色背景 White Matte 白色背景 - -# Layer colour labels. Seafoam 海沫色 Indigo 靛蓝色 Fuchsia 紫红色 @@ -2528,8 +2602,6 @@ fontWeight Bold 粗体 fontWeight ExtraBold 特粗 fontWeight Black 黑体 fontWeight Italic 斜体 - -# Pattern Stamp tool Pattern Stamp Tool 图案图章工具 Pattern Stamp 图案图章 Impressionist 印象派 @@ -2537,13 +2609,9 @@ fontWeight Italic 斜体 Rotate View Tool 旋转视图工具 Reset View 重置视图 Drag around the centre to rotate the view · Shift constrains to 15° 绕中心拖动以旋转视图 · Shift 限制为 15° - -# Painting symmetry presets. Dual Axis 双轴 Diagonal 对角线 Transform Symmetry 变换对称轴 - -# Eyedropper Sample Size and Sample (#1649). Point Sample 采样点 3 by 3 Average 3 × 3 平均 5 by 5 Average 5 × 5 平均 @@ -2555,15 +2623,12 @@ fontWeight Italic 斜体 All Layers No Adjustments 所有图层(不含调整) Current & Below No Adjustments 当前及下方图层(不含调整) 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 不是 Web 颜色:单击使用最接近的 Web 颜色 Color to Alpha… 颜色转为 Alpha… Transparency Threshold 透明度阈值 Opacity Threshold 不透明度阈值 PhotoCraft — Screen Color Picker PhotoCraft — 屏幕取色器 - Rasterize svg groups deeper than 栅格化超过此深度的 SVG 组 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 设为 0 可关闭此阈值;嵌套超过 100 层的 SVG 组始终会被栅格化。 Rule of Thirds 三等分 @@ -2577,8 +2642,6 @@ fontWeight Italic 斜体 Cycle Orientation 循环切换取向 Set the overlay options for the Crop tool 设置裁剪工具的叠加选项 Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 单击被桌面环境截获了,它用 Alt 拖动来移动窗口。请把桌面的窗口移动键改为 Super,或在 窗口 › 修饰键 中锁定 Alt。 - -# Shared Layer Style color picker Color Picker (Layer Style Color) 拾色器(图层样式颜色) Auto Hide Notifications 自动隐藏通知 Notification Duration (seconds) 通知持续时间(秒) @@ -2659,7 +2722,6 @@ fontWeight Italic 斜体 Appearance Settings… 外观设置… Add to favorites 添加到收藏 Remove from favorites 从收藏中移除 -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data 相机数据 cameraData Make 制造商 cameraData Model 型号 @@ -2670,7 +2732,6 @@ cameraData ISO Speed ISO 感光度 cameraData Focal Length 焦距 cameraData Focal Length (35 mm) 焦距(35 毫米等效) cameraData Lens 镜头 -# Shared panel docking Activate Panel 激活面板 Change Panel Group 更改面板组 Change Panel Layout 更改面板布局 @@ -2710,7 +2771,6 @@ cameraData Lens 镜头 Snap to Origin 贴紧原点 Search settings… 搜索设置… No matching settings 没有匹配的设置 -# Edit › Content-Aware Fill workspace Sampling Brush Tool 取样画笔工具 Sampling Area Overlay 取样区域叠加 Show Sampling Area 显示取样区域 @@ -2730,7 +2790,6 @@ cameraData Lens 镜头 Output To 输出到 Duplicate Layer 复制图层 Contract 收缩 - Animation Options 动画选项 Entire Document 整个文档 Filter Options 过滤选项 @@ -2751,8 +2810,6 @@ cameraData Lens 镜头 Add “copy” to Copied Layers and Groups 为复制的图层和组添加“副本” Preview on canvas when reordering layers 重新排列图层时在画布上预览 Show layer mask badges 显示图层蒙版标记 - -# Smart Filter editors Blending Options ({filter}) 混合选项 ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) 隐藏图层效果和智能滤镜 ({key} 单击:所有图层) Show the layer's effects and Smart Filters ({key}-click: all layers) 显示图层效果和智能滤镜 ({key} 单击:所有图层) @@ -2792,7 +2849,6 @@ curves Smooth 平滑 Alt-click a plane to set the clone source 按住 Alt 键单击平面以设置仿制源 Too many clone strokes: apply Vanishing Point first 仿制描边过多:请先应用消失点 Stamp 图章 -# Select and Mask view modes (#1754) Onion Skin 洋葱皮 Marching Ants 蚂蚁线 On Black 黑底 @@ -2801,7 +2857,6 @@ curves Smooth 平滑 Show Edge 显示边缘 Show Original 显示原始 F cycles the views; hold X to see the image 按 F 切换视图;按住 X 查看图像 -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) 调整边缘画笔 (R) Expand Detection Area 扩展检测区域 Restore Original Edge 恢复原始边缘 @@ -2815,22 +2870,16 @@ curves Smooth 平滑 Enter a name for the crop preset 输入裁剪预设的名称 There is no crop size or ratio to save 没有可保存的裁剪大小或比例 Presentation 演示 - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove 单击以放置 · Alt 单击或拖到画布外以移除 No document open 未打开任何文档 {n} of {max} sample points {max} 个取样点中的 {n} 个 - -# History panel menu (#2966) Step Forward 前进一步 Step Backward 后退一步 Clear History 清除历史记录 New Snapshot… 新建快照… History Options… 历史记录选项… -# History panel › History Options… (#2966) Allow Non-Linear History 允许非线性历史记录 Make Layer Visibility Changes Undoable 允许撤销图层可见性更改 -# Print dialog (#2697) Emulsion Down 药膜朝下 Functions 功能 Print Resolution: 打印分辨率: @@ -2842,7 +2891,6 @@ curves Smooth 平滑 Apply mask to layer before removing? 移去之前将蒙版应用到图层吗? The layer or its mask changed. Drag the mask onto the Trash again. 图层或其蒙版已更改。请再次将蒙版拖到垃圾桶。 Delete the vector mask? 要删除矢量蒙版吗? -# View › Guides › New Guide… › Color Light Blue 浅蓝色 Light Red 浅红色 Medium Blue 中蓝色 @@ -2864,8 +2912,6 @@ curves Smooth 平滑 Clear Brush Controls 清除画笔控件 Reset All Locked Settings 复位所有锁定的设置 Copy Texture to Other Tools 将纹理复制到其他工具 - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… 载入动作… Save Actions… 存储动作… New Action… 新建动作… @@ -2877,10 +2923,8 @@ curves Smooth 平滑 @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 个步骤在 PhotoCraft 中尚无对应功能 @plural Saved {n} action to {file}|Saved {n} actions to {file} 已将 {n} 个动作存储到 {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已省略 {n} 个没有 Photoshop 对应功能的步骤 - File Naming 文件命名 Starting serial 起始序号 -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… 插入停止… Save Set… 存储组… Message: 信息: @@ -2892,11 +2936,8 @@ curves Smooth 平滑 @plural {n} action|{n} actions {n} 个动作 Background (Default) 背景(默认) Content-Aware Fill 内容识别填充 -# Batch / Image Processor Include All Subfolders 包含所有子文件夹 Auto Add/Delete 自动添加/删除 - -# 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… 请记得在打印设置中关闭打印机自身的色彩管理… @@ -2941,7 +2982,6 @@ curves Smooth 平滑 Could not write {name}: {error} 无法写入 {name}:{error} Kept {name}: written by another application 已保留 {name}:由其他应用程序写入 Shadow Tint 阴影色调 -# PhotoCraft release checks. Check for Updates… 检查更新… PhotoCraft Updates PhotoCraft 更新 Checking for updates… 正在检查更新… @@ -2954,38 +2994,29 @@ curves Smooth 平滑 Automatically Check for Updates 自动检查更新 Installed version: {version} 已安装版本:{version} PhotoCraft {version} is available. PhotoCraft {version} 已发布。 -# History panel › History Brush source (#2966) Paints from the History panel's source state 从历史记录面板的源状态绘画 Sets the source for the history brush 设置历史记录画笔的源 -# Bevel & Emboss shading controls. Highlight Mode 高光模式 Highlight Color 高光颜色 Highlight Opacity 高光不透明度 Shadow Mode 阴影模式 Shadow Color 阴影颜色 Shadow Opacity 阴影不透明度 -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) 使用嵌入的配置文件({profile}) Convert to the working space ({profile}) 转换到工作空间({profile}) Remember this choice for future images 以后打开的图像都使用此选择 Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. 可在 编辑 › 颜色设置 中打开 Ask On Mismatch,重新显示此提示。 Button Mode 按钮模式 Button Mode On 按钮模式 开 - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface 界面变暗 Lighten Interface 界面变亮 -# Bevel & Emboss Technique. Technique 方法 Chisel Hard 雕刻清晰 Chisel Soft 雕刻柔和 Open color-less EXR as ACEScg 将无色彩空间信息的 EXR 以 ACEScg 打开 Do not append "copy" to filename when saving a copy 存储副本时不在文件名后添加“copy” -# Export As metadata and profile options Color Profile 颜色配置文件 EXIF EXIF - -# View › Guides › right-click a guide Edit Selected Guides 编辑所选参考线 Clear Selected Guides 清除所选参考线 Make Selection 建立选区 @@ -3012,8 +3043,6 @@ curves Smooth 平滑 {set} (modified) {set}(已修改) Random 随机 Show file name in title 标题中显示文件名 - -# Image › Mode › Bitmap (#5559) 50% Threshold 50% 阈值 Pattern Dither 图案仿色 Diffusion Dither 扩散仿色 @@ -3033,11 +3062,9 @@ curves Smooth 平滑 Undo Changes 撤消更改 {shortcut} is reserved by the system and can't be assigned. {shortcut} 由系统保留,无法指定。 Low-Latency Drawing (vsync off, applies at next launch) 低延迟绘画(关闭垂直同步,下次启动时生效) -# Free Transform: a new layer while the box is open (#5859) Reference point location 参考点位置 Free Transform is still being applied; try again when it has finished. 自由变换仍在应用中;请在完成后重试。 The transform couldn't be applied. 无法应用变换。 -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. 其图层需要 {needed} GPU 内存;预算只留给它们 {budget}。 Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. 在 首选项 › 性能 中将 GPU 内存设置为显卡能容纳的大小,最多为其显存的 3/8。自动跟随内存使用量,不超过本机内存的四分之一和显卡显存的 3/8,且在显存已知的显卡上不把文档计入。在图层放不下期间,状态栏显示“GPU 内存已满”。 GPU Memory Full GPU 内存已满 @@ -3064,8 +3091,6 @@ curves Smooth 平滑 The fastest and the softest, with colour fringing on fine detail. 最快也最柔和,细节处有色边。 “{name}” already exists. Replace it? “{name}”已存在。要替换它吗? The name in the save dialog was “{name}”. 存储对话框中的名称是“{name}”。 - Move Up 上移 - Move Down 下移 Previous Brush 上一个画笔 Next Brush 下一个画笔 First Brush 第一个画笔 @@ -3081,27 +3106,18 @@ curves Smooth 平滑 In Front 前面 Behind 后面 Blend 混合 - -# DDS Options (#1327) DDS Options DDS 选项 Compression 压缩 Generate Mipmaps 生成 Mipmap - -# Color Table (.act) dialog There is no color table to save. 没有可保存的色表。 @plural Saved {n} color to {file}|Saved {n} colors to {file} 已将 {n} 种颜色保存到 {file} - -# Graphics Adapter preference (#1885) GPU adapter GPU 适配器 - -# Styles panel: Import / Export Styles (.asl) Import Styles… 导入样式… Export Selected Styles… 导出所选样式… Export Styles… 导出样式… {file} is not a style library (.asl) {file} 不是样式库 (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} 已从 {file} 导入 {n} 个样式 @plural Exported {n} style to {file}|Exported {n} styles to {file} 已将 {n} 个样式导出到 {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first 请先确认或取消打开的动作步骤对话框 Pro Medium Gray 专业中灰 Solarized Solarized @@ -3110,30 +3126,11 @@ curves Smooth 平滑 Pro Light 专业浅色 Resize Windows to Fit 调整窗口大小以适合 EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction 自动段落方向 Left-to-right paragraph direction 从左到右的段落方向 Right-to-left paragraph direction 从右到左的段落方向 Not rendered: this adjustment ({key}) is kept as imported. 未渲染:此调整({key})按导入时的原样保留。 -# Print preview image (#8236) Print preview image 打印预览图像 - Clear Selection 清除选区 - Color Aware 颜色识别 - Decontaminate Colors 净化颜色 - Edge Detection 边缘检测 - Global Refinements 全局调整 - High Quality Preview 高品质预览 - Object Aware 对象识别 - Real-Time Refinement 实时调整 - Refine Edge Brush Tool 调整边缘画笔工具 - Refine Hair 调整细线 - Refine Mode 调整模式 - Remember Settings 记住设置 - View Mode 视图模式 - Object Aware needs a segmentation model, which isn't available yet 对象识别需要分割模型,目前尚不可用 - Refine Hair needs hair detection, which isn't available yet 调整细线需要毛发检测,目前尚不可用 - -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 色相立方体 Brightness Cube 亮度立方体 Color Wheel 色轮 @@ -3150,16 +3147,13 @@ curves Smooth 平滑 Grayscale Ramp 灰度色带 Current Colors 当前颜色 Make Ramp Web Safe 使色带成为 Web 安全色 - -# File opening, export status and graphics driver information Couldn't open {name}: {error} 无法打开 {name}:{error} Exported {path} ({size}) 已导出 {path}({size}) Exported {path} 已导出 {path} Exported {n} files 已导出 {n} 个文件 Driver: {driver} 驱动程序:{driver} - Select and Mask was closed: its document is no longer the active one 已关闭“选择与蒙版”:其文档不再是当前文档 - Select and Mask was closed: another layer was selected 已关闭“选择与蒙版”:已选择另一个图层 -# Art History Brush (#213). + The path was kept as the Work Path 路径已保留为工作路径 + The path was discarded 路径已丢弃 Art History Brush 艺术历史画笔 Art History Brush Tool 艺术历史画笔工具 Tight Short 紧密短 @@ -3172,8 +3166,6 @@ curves Smooth 平滑 Loose Curl 宽松卷曲 Area 区域 Stylized dabs from a history state 从历史状态绘制风格化点涂 - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio 长宽比 Category 类别 Color Table 颜色表 @@ -3185,3 +3177,21 @@ curves Smooth 平滑 Font size presets 字号预设 Leading presets 行距预设 Tracking presets 字距调整预设 + Clear Selection 清除选区 + Color Aware 颜色识别 + Decontaminate Colors 净化颜色 + Edge Detection 边缘检测 + Global Refinements 全局调整 + High Quality Preview 高品质预览 + Object Aware 对象识别 + Real-Time Refinement 实时调整 + Refine Edge Brush Tool 调整边缘画笔工具 + Refine Hair 调整细线 + Refine Mode 调整模式 + Remember Settings 记住设置 + View Mode 视图模式 + Object Aware needs a segmentation model, which isn't available yet 对象识别需要分割模型,目前尚不可用 + Refine Hair needs hair detection, which isn't available yet 调整细线需要毛发检测,目前尚不可用 + Select and Mask was closed: its document is no longer the active one 已关闭“选择与蒙版”:其文档不再是当前文档 + Select and Mask was closed: another layer was selected 已关闭“选择与蒙版”:已选择另一个图层 + Drag to move the selected path 拖动以移动选中的路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b44c261364..06a9a40d07 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -20,10 +20,108 @@ # separators as in the English. # Layer Mask Display Options (the layer mask rubylith's colour and opacity) - Mask Options… 遮色片選項… - Layer Mask Display Options… 圖層遮色片顯示選項… # Channel Options and New Spot Channel (#3761) + +# Guide layout dialog + +# Custom print paper (#3820) + +# Select and Mask dialog labels +# Field Blur pins (#3373) + +# Layers-panel trash confirmation + +# Gradient Editor window, opened from the options bar's gradient swatch. +# Rendering mode and recovery +# Camera Raw: contextual controls and window title + + + + + + +# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) + +# Swatches panel +# Layer Style > Blending Options (Advanced Blending) + +# Shared screen eyedropper and text Color Picker (#1128). + +# Fill dialog, layer style contours and Image Size + + + +# Layer colour labels. + +# Pattern Stamp tool + +# Painting symmetry presets. + +# Eyedropper Sample Size and Sample (#1649). + +# Color Picker warnings + + +# Shared Layer Style color picker +# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). +# Shared panel docking +# Edit › Content-Aware Fill workspace + + +# Smart Filter editors +# Select and Mask view modes (#1754) +# Select and Mask Refine Edge Brush (#2972) + +# Color Sampler (added with the i18n coverage repair) + +# History panel menu (#2966) +# History panel › History Options… (#2966) +# Print dialog (#2697) +# Counted status messages and labels (#3454; adapted from PR #3821) +# View › Guides › New Guide… › Color + +# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps + +# Actions panel: set folders, dialog toggle, Insert Stop +# Batch / Image Processor + +# Native Windows printing qualification +# PhotoCraft release checks. +# History panel › History Brush source (#2966) +# Bevel & Emboss shading controls. +# Embedded Profile Mismatch: profile names beside the choices, Remember this choice + +# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) +# Bevel & Emboss Technique. +# Export As metadata and profile options + +# View › Guides › right-click a guide + +# Image › Mode › Bitmap (#5559) +# Free Transform: a new layer while the box is open (#5859) +# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice + +# DDS Options (#1327) + +# Color Table (.act) dialog + +# Graphics Adapter preference (#1885) + +# Styles panel: Import / Export Styles (.asl) +# Actions: a step dialog holds a suspended recording (#7365) +# Paragraph direction (TYPE-218-2) +# Print preview image (#8236) +# Color panel menu: modes, copy commands and colour ramps (#6000) + +# Pen draft after a refused commit (#7648) +# Art History Brush (#213). + +# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) +# Smart Filter row actions (#1265) + + Mask Options… 遮色片選項… + Layer Mask Display Options… 圖層遮色片顯示選項… Channel Color 色版顏色 Color Indicates: 色彩指示: Solidity: 硬度: @@ -31,10 +129,6 @@ Selected Areas 選取區域 Spot Color 特別色 Ink Characteristics 油墨特性 - -# Guide layout dialog - -# Custom print paper (#3820) Paper Width 紙張寬度 Paper Height 紙張高度 Columns 欄 @@ -54,7 +148,6 @@ 5 Columns, 3 Rows 5欄,3列 8 Columns 8欄 12 Columns 12欄 - File 檔案 Edit 編輯 Image 影像 @@ -463,6 +556,7 @@ Intersect Shape Areas 交集形狀區域 Exclude Overlapping Shapes 排除重疊形狀 Merge Shape Components 合併形狀元件 + Path operations 路徑操作 Align 對齊 Top Edges 頂端邊緣 Vertical Centers 垂直置中 @@ -542,7 +636,6 @@ Color Range… 顏色範圍… Focus Area… 焦點區域… Select and Mask… 選取並遮住… -# Select and Mask dialog labels Smart Radius 智慧型半徑 Shift Edge 移動邊緣 Decontaminate 淨化 @@ -569,7 +662,6 @@ Blur 模糊 Blur Gallery 模糊收藏館 Field Blur… 區域模糊… -# Field Blur pins (#3373) No pin selected 未選取圖釘 Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 按一下影像即可新增圖釘;拖移圖釘可移動它,拖移其圓環可變更模糊程度。按 Delete 鍵刪除所選圖釘。 Drag the handles on the outline to resize and turn it, the square to round its corners, and the dots inside to set where the blur starts. 拖移輪廓上的控點可調整大小並旋轉,拖移方塊可將角變圓,拖移內部的點可設定模糊開始的位置。 @@ -849,6 +941,9 @@ Add Layer Mask 新增圖層遮色片 Add Stop 新增色標 Add a layer style 新增圖層樣式 + Move effect up 上移效果 + Move effect down 下移效果 + Delete effect 刪除效果 Add a mask (from the selection; {key} inverts) 新增遮色片 (依選取範圍;{key} 反轉) Add an adjustment 新增調整 Add disk 新增磁碟 @@ -1077,8 +1172,6 @@ Delete current channel 刪除目前色版 Delete current state 刪除目前狀態 Delete effect layer 刪除效果圖層 - -# Layers-panel trash confirmation Delete layer ‘{name}’? 刪除圖層「{name}」? Delete {count} layers? {names} 刪除 {count} 個圖層?{names} Delete layer? 刪除圖層? @@ -1087,7 +1180,6 @@ Missing delete command 缺少刪除指令 Invalid delete command 無效的刪除指令 Layer deleted, but confirmation preference could not be saved: {error} 圖層已刪除,但無法儲存確認設定:{error} - Delete layer 刪除圖層 Delete layer comp 刪除圖層構圖 Delete note 刪除註解 @@ -1120,7 +1212,6 @@ Dots 點 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 可限制水平/垂直;在限制線上按右鍵可變更或刪除。 - Drag to move the active shape's path or the Work Path 拖曳以移動作用中形狀的路徑或工作路徑 Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath 按一下:選取錨點 · 拖曳:移動錨點、把手或線段 · {shift}-按一下:增加 · {alt}-按一下:整個子路徑 Draw with the Pen tool (P) or make a work path from a selection. 使用筆型工具 (P) 繪製,或從選取範圍建立工作路徑。 Drop an image or PSD anywhere to open it. 將影像或 PSD 拖放到任何位置即可開啟。 @@ -2200,7 +2291,6 @@ Align with layer 與圖層對齊 Reset Alignment 重設對齊 Centre the gradient (offset 0, 0) 置中漸層 (位移 0, 0) -# Gradient Editor window, opened from the options bar's gradient swatch. Gradient Editor 漸層編輯器 Gradient picker 漸層挑選器 Save As Preset 儲存為預設 @@ -2260,7 +2350,6 @@ 4 x 4 4 × 4 5 x 5 5 × 5 Grid: 格點: -# Rendering mode and recovery Rendering Mode 渲染模式 Automatic (recommended) 自動(建議) CPU / Compatibility CPU / 相容模式 @@ -2287,7 +2376,6 @@ Tone Histogram 色調直方圖 Show Selected Region 顯示選取區域 cameraRaw Light 光線 -# Camera Raw: contextual controls and window title Camera Raw Filter ({layer}) Camera Raw 濾鏡({layer}) Camera Raw ({name}) Camera Raw({name}) cameraRaw Lights 亮調 @@ -2305,14 +2393,10 @@ cameraRaw Blending 混合 Scale or rotate the moved area, then press {key} 縮放或旋轉移動的區域,然後按 {key} Now drag the selection onto another area 現在將選取範圍拖曳到另一個區域 Edit Type 編輯文字 - - New Style… 新增樣式… Style {name} saved 已儲存樣式 {name} - Create new style (from the selected type) 新增樣式(基於所選文字) Create new style from the selected layer 從所選圖層新增樣式 - Make Default 設為預設 Reset to Default 重設為預設 Full-resolution preview unavailable 無法使用完整解析度預覽 @@ -2341,9 +2425,6 @@ cameraRaw Blending 混合 Magnetic Lasso Tool 磁性套索工具 Frequency 頻率 Use tablet pressure to change pen width 使用繪圖板壓力以變更鋼筆寬度 - - -# About ▸ Contributors / Models (credits, craftrules standards/contributors.md) About 關於 Contributors 貢獻者 Models 模型 @@ -2375,8 +2456,6 @@ cameraRaw Blending 混合 % of all commits 佔全部提交的 % Lines +/− 行數 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}:{prs} 個 PR,{commits} 次提交,行 +{added} / −{deleted}(Δ {delta}),二進位檔 +{binAdded} / −{binDeleted},{first} – {last} - -# Swatches panel Create new swatch 建立新色票 New Swatch… 新增色票… New Swatch Group… 新增色票群組… @@ -2386,13 +2465,12 @@ cameraRaw Blending 混合 Export Swatches for Exchange… 匯出色票以供交換… Reset Swatches 重設色票 Add to Swatches 加入色票 -# Layer Style > Blending Options (Advanced Blending) Blend If: 混合範圍: + Current Layer: 目前圖層: + Underlying Layer: 下一圖層: Channels: 色版: Knockout 去底色 Apply At Canvas Bounds 套用效果至版面邊界 - -# Shared screen eyedropper and text Color Picker (#1128). Color Picker (Text Color) 檢色器(文字顏色) Color Picker ({name}) 檢色器({name}) Color Picker (Fill Color) 檢色器(填滿顏色) @@ -2409,8 +2487,6 @@ cameraRaw Blending 混合 Show/Hide Panels 顯示/隱藏面板 Could not open 無法開啟 {path}: the path is not valid Unicode; rename the file and open it again. {path}:路徑不是有效的 Unicode;請重新命名檔案後再開啟。 - -# Fill dialog, layer style contours and Image Size Contents: 內容: Custom Pattern: 自訂圖樣: Foreground Color 前景色 @@ -2438,7 +2514,6 @@ cameraRaw Blending 混合 Rolling Slope - Descending 滾動斜坡 - 遞減 Rounded Steps 圓角梯形 Sawtooth 1 鋸齒 1 - Red Eye Tool 紅眼工具 Red Eye 紅眼 Pupil Size 瞳孔大小 @@ -2446,7 +2521,6 @@ cameraRaw Blending 混合 Click a red pupil to neutralize it 按一下紅色瞳孔以消除反光 open source 開源 …and {n} more …以及另外 {n} 項 - Eyedroppers: 滴管: Set Black Point 設定黑點 Set Neutral Gray Point 設定中性灰點 @@ -2455,8 +2529,6 @@ cameraRaw Blending 混合 Selection Preview: 選取範圍預視: Black Matte 黑色背景 White Matte 白色背景 - -# Layer colour labels. Seafoam 海沫色 Indigo 靛藍色 Fuchsia 紫紅色 @@ -2477,8 +2549,6 @@ fontWeight Bold 粗體 fontWeight ExtraBold 特粗 fontWeight Black 黑體 fontWeight Italic 斜體 - -# Pattern Stamp tool Pattern Stamp Tool 圖案圖章工具 Pattern Stamp 圖案圖章 Impressionist 印象派 @@ -2486,13 +2556,9 @@ fontWeight Italic 斜體 Rotate View Tool 旋轉檢視工具 Reset View 重設檢視 Drag around the centre to rotate the view · Shift constrains to 15° 繞中心拖曳以旋轉檢視 · Shift 限制為 15° - -# Painting symmetry presets. Dual Axis 雙軸 Diagonal 對角線 Transform Symmetry 變形對稱軸 - -# Eyedropper Sample Size and Sample (#1649). Point Sample 取樣點 3 by 3 Average 3 × 3 平均 5 by 5 Average 5 × 5 平均 @@ -2504,15 +2570,12 @@ fontWeight Italic 斜體 All Layers No Adjustments 所有圖層(不含調整) Current & Below No Adjustments 目前及以下(不含調整) 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 不是網頁顏色:按一下以使用最接近的網頁顏色 Color to Alpha… 顏色轉為 Alpha… Transparency Threshold 透明度臨界值 Opacity Threshold 不透明度臨界值 PhotoCraft — Screen Color Picker PhotoCraft — 螢幕取色器 - Rasterize svg groups deeper than 點陣化超過此深度的 SVG 群組 0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized. 設為 0 可關閉此臨界值;巢狀超過 100 層的 SVG 群組一律會點陣化。 Rule of Thirds 三等分 @@ -2526,8 +2589,6 @@ fontWeight Italic 斜體 Cycle Orientation 循環切換方向 Set the overlay options for the Crop tool 設定裁切工具的覆蓋選項 Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 按一下被桌面環境攔截了,它用 Alt 拖曳來移動視窗。請把桌面的視窗移動鍵改為 Super,或在 視窗 › 輔助鍵 中鎖定 Alt。 - -# Shared Layer Style color picker Color Picker (Layer Style Color) 檢色器(圖層樣式顏色) Auto Hide Notifications 自動隱藏通知 Notification Duration (seconds) 通知持續時間(秒) @@ -2608,7 +2669,6 @@ fontWeight Italic 斜體 Appearance Settings… 外觀設定… Add to favorites 加入最愛 Remove from favorites 從最愛移除 -# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb). Camera Data 相機資料 cameraData Make 製造商 cameraData Model 型號 @@ -2619,7 +2679,6 @@ cameraData ISO Speed ISO 感光度 cameraData Focal Length 焦距 cameraData Focal Length (35 mm) 焦距(35 公釐等效) cameraData Lens 鏡頭 -# Shared panel docking Activate Panel 啟用面板 Change Panel Group 變更面板群組 Change Panel Layout 變更面板配置 @@ -2659,7 +2718,6 @@ cameraData Lens 鏡頭 Snap to Origin 靠齊原點 Search settings… 搜尋設定… No matching settings 沒有符合的設定 -# Edit › Content-Aware Fill workspace Sampling Brush Tool 取樣筆刷工具 Sampling Area Overlay 取樣區域覆蓋 Show Sampling Area 顯示取樣區域 @@ -2679,7 +2737,6 @@ cameraData Lens 鏡頭 Output To 輸出至 Duplicate Layer 複製圖層 Contract 縮減 - Animation Options 動畫選項 Entire Document 整份文件 Filter Options 篩選選項 @@ -2700,8 +2757,6 @@ cameraData Lens 鏡頭 Add “copy” to Copied Layers and Groups 為複製的圖層和群組加上「副本」 Preview on canvas when reordering layers 重新排列圖層時在畫布上預覽 Show layer mask badges 顯示圖層遮色片標記 - -# Smart Filter editors Blending Options ({filter}) 混合選項 ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) 隱藏圖層效果和智慧型濾鏡 ({key} 點擊:所有圖層) Show the layer's effects and Smart Filters ({key}-click: all layers) 顯示圖層效果和智慧型濾鏡 ({key} 點擊:所有圖層) @@ -2741,7 +2796,6 @@ curves Smooth 平滑 Alt-click a plane to set the clone source 按住 Alt 鍵按一下平面以設定仿製來源 Too many clone strokes: apply Vanishing Point first 仿製筆畫過多:請先套用消失點 Stamp 印章 -# Select and Mask view modes (#1754) Onion Skin 洋蔥皮 Marching Ants 螞蟻線 On Black 黑底 @@ -2750,7 +2804,6 @@ curves Smooth 平滑 Show Edge 顯示邊緣 Show Original 顯示原始 F cycles the views; hold X to see the image 按 F 切換檢視;按住 X 檢視影像 -# Select and Mask Refine Edge Brush (#2972) Refine Edge Brush (R) 調整邊緣筆刷 (R) Expand Detection Area 擴展偵測區域 Restore Original Edge 恢復原始邊緣 @@ -2764,22 +2817,16 @@ curves Smooth 平滑 Enter a name for the crop preset 輸入裁切預設集的名稱 There is no crop size or ratio to save 沒有可儲存的裁切尺寸或比例 Presentation 呈現 - -# Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove 按一下以放置 · Alt 按一下或拖曳至畫布外以移除 No document open 未開啟任何文件 {n} of {max} sample points {max} 個取樣點中的 {n} 個 - -# History panel menu (#2966) Step Forward 向前一步 Step Backward 向後一步 Clear History 清除步驟記錄 New Snapshot… 新增快照… History Options… 步驟記錄選項… -# History panel › History Options… (#2966) Allow Non-Linear History 允許非線性步驟記錄 Make Layer Visibility Changes Undoable 允許復原圖層可見度變更 -# Print dialog (#2697) Emulsion Down 感光乳劑面朝下 Functions 功能 Print Resolution: 列印解析度: @@ -2791,7 +2838,6 @@ curves Smooth 平滑 Apply mask to layer before removing? 移除之前將遮色片套用到圖層嗎? The layer or its mask changed. Drag the mask onto the Trash again. 圖層或其遮色片已變更。請再次將遮色片拖曳到垃圾桶。 Delete the vector mask? 要刪除向量遮色片嗎? -# Counted status messages and labels (#3454; adapted from PR #3821) @plural Exported {n} swatch to {file}|Exported {n} swatches to {file} 已將 {n} 個色票匯出至 {file} @plural Imported {n} brush from {group}|Imported {n} brushes from {group} 已從 {group} 匯入 {n} 個筆刷 @plural Imported {n} swatch from {file}|Imported {n} swatches from {file} 已從 {file} 匯入 {n} 個色票 @@ -2806,7 +2852,6 @@ curves Smooth 平滑 @plural {n} step|{n} steps {n} 個步驟 @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (另有 {n} 個筆刷預設集警告) @plural {what} with {n} warning|{what} with {n} warnings {what} ({n} 個警告) -# View › Guides › New Guide… › Color Light Blue 淺藍色 Light Red 淺紅色 Medium Blue 中藍色 @@ -2828,8 +2873,6 @@ curves Smooth 平滑 Clear Brush Controls 清除筆刷控制項 Reset All Locked Settings 重設所有鎖定的設定 Copy Texture to Other Tools 複製紋理至其他工具 - -# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps Load Actions… 載入動作… Save Actions… 儲存動作… New Action… 新增動作… @@ -2841,10 +2884,8 @@ curves Smooth 平滑 @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 個步驟在 PhotoCraft 中尚無對應功能 @plural Saved {n} action to {file}|Saved {n} actions to {file} 已將 {n} 個動作儲存到 {file} @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已略過 {n} 個沒有 Photoshop 對應功能的步驟 - File Naming 檔案命名 Starting serial 起始序號 -# Actions panel: set folders, dialog toggle, Insert Stop Insert Stop… 插入停止… Save Set… 儲存組合… Message: 訊息: @@ -2856,11 +2897,8 @@ curves Smooth 平滑 @plural {n} action|{n} actions {n} 個動作 Background (Default) 背景(預設) Content-Aware Fill 內容感知填滿 -# Batch / Image Processor Include All Subfolders 包含所有子資料夾 Auto Add/Delete 自動增加/刪除 - -# 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… 請記得在列印設定中關閉印表機本身的色彩管理… @@ -2905,7 +2943,6 @@ curves Smooth 平滑 Could not write {name}: {error} 無法寫入 {name}:{error} Kept {name}: written by another application 已保留 {name}:由其他應用程式寫入 Shadow Tint 陰影色調 -# PhotoCraft release checks. Check for Updates… 檢查更新… PhotoCraft Updates PhotoCraft 更新 Checking for updates… 正在檢查更新… @@ -2918,38 +2955,29 @@ curves Smooth 平滑 Automatically Check for Updates 自動檢查更新 Installed version: {version} 已安裝版本:{version} PhotoCraft {version} is available. PhotoCraft {version} 已發佈。 -# History panel › History Brush source (#2966) Paints from the History panel's source state 從步驟記錄面板的來源狀態繪畫 Sets the source for the history brush 設定步驟記錄筆刷的來源 -# Bevel & Emboss shading controls. Highlight Mode 亮部模式 Highlight Color 亮部顏色 Highlight Opacity 亮部不透明度 Shadow Mode 陰影模式 Shadow Color 陰影顏色 Shadow Opacity 陰影不透明度 -# Embedded Profile Mismatch: profile names beside the choices, Remember this choice Use the embedded profile ({profile}) 使用內嵌描述檔 ({profile}) Convert to the working space ({profile}) 轉換為工作空間 ({profile}) Remember this choice for future images 之後開啟的影像都使用此選擇 Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. 可在 編輯 › 色彩設定 中開啟 Ask On Mismatch,重新顯示此提示。 Button Mode 按鈕模式 Button Mode On 按鈕模式 開 - -# Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) Darken Interface 介面變暗 Lighten Interface 介面變亮 -# Bevel & Emboss Technique. Technique 方法 Chisel Hard 雕刻清晰 Chisel Soft 雕刻柔和 Open color-less EXR as ACEScg 將無色彩空間資訊的 EXR 以 ACEScg 開啟 Do not append "copy" to filename when saving a copy 儲存副本時不在檔名後加上「copy」 -# Export As metadata and profile options Color Profile 色彩描述檔 EXIF EXIF - -# View › Guides › right-click a guide Edit Selected Guides 編輯所選參考線 Clear Selected Guides 清除所選參考線 Make Selection 建立選取範圍 @@ -2976,8 +3004,6 @@ curves Smooth 平滑 {set} (modified) {set}(已修改) Random 隨機 Show file name in title 標題中顯示檔案名稱 - -# Image › Mode › Bitmap (#5559) 50% Threshold 50% 臨界值 Pattern Dither 圖樣混色 Diffusion Dither 擴散混色 @@ -2997,11 +3023,9 @@ curves Smooth 平滑 Undo Changes 還原變更 {shortcut} is reserved by the system and can't be assigned. {shortcut} 由系統保留,無法指定。 Low-Latency Drawing (vsync off, applies at next launch) 低延遲繪圖(關閉垂直同步,下次啟動時生效) -# Free Transform: a new layer while the box is open (#5859) Reference point location 參考點位置 Free Transform is still being applied; try again when it has finished. 任意變形仍在套用中;請在完成後再試一次。 The transform couldn't be applied. 無法套用變形。 -# Preferences › Performance › GPU Memory; the status bar and slow-redraw notice Its layers need {needed} of GPU memory; the budget leaves them {budget}. 其圖層需要 {needed} GPU 記憶體;預算只留給它們 {budget}。 Set GPU Memory in Preferences › Performance to what your graphics card can hold, at most 3/8 of its memory. Automatic follows Memory Usage, within a quarter of this computer's memory and 3/8 of the card's, and doesn't count the document against a card whose memory is known. The status bar shows GPU Memory Full while they don't fit. 在 偏好設定 › 效能 中將 GPU 記憶體設為顯示卡能容納的大小,最多為其記憶體的 3/8。自動會跟隨記憶體使用量,不超過本機記憶體的四分之一和顯示卡記憶體的 3/8,且在記憶體已知的顯示卡上不把文件計入。在圖層放不下期間,狀態列會顯示「GPU 記憶體已滿」。 GPU Memory Full GPU 記憶體已滿 @@ -3028,8 +3052,6 @@ curves Smooth 平滑 The fastest and the softest, with colour fringing on fine detail. 最快也最柔和,細節處有色邊。 “{name}” already exists. Replace it? 「{name}」已存在。要取代它嗎? The name in the save dialog was “{name}”. 儲存對話框中的名稱是「{name}」。 - Move Up 上移 - Move Down 下移 Previous Brush 上一個筆刷 Next Brush 下一個筆刷 First Brush 第一個筆刷 @@ -3045,27 +3067,18 @@ curves Smooth 平滑 In Front 前面 Behind 後面 Blend 混合 - -# DDS Options (#1327) DDS Options DDS 選項 Compression 壓縮 Generate Mipmaps 產生 Mipmap - -# Color Table (.act) dialog There is no color table to save. 沒有可儲存的色表。 @plural Saved {n} color to {file}|Saved {n} colors to {file} 已將 {n} 種顏色儲存至 {file} - -# Graphics Adapter preference (#1885) GPU adapter GPU 介面卡 - -# Styles panel: Import / Export Styles (.asl) Import Styles… 匯入樣式… Export Selected Styles… 匯出所選樣式… Export Styles… 匯出樣式… {file} is not a style library (.asl) {file} 不是樣式庫 (.asl) @plural Imported {n} style from {file}|Imported {n} styles from {file} 已從 {file} 匯入 {n} 個樣式 @plural Exported {n} style to {file}|Exported {n} styles to {file} 已將 {n} 個樣式匯出至 {file} -# Actions: a step dialog holds a suspended recording (#7365) Confirm or cancel the open action step dialog first 請先確認或取消開啟中的動作步驟對話框 Pro Medium Gray 專業中灰 Solarized Solarized @@ -3074,29 +3087,11 @@ curves Smooth 平滑 Pro Light 專業淺色 Resize Windows to Fit 調整視窗大小以符合 EXR EXR -# Paragraph direction (TYPE-218-2) Automatic paragraph direction 自動段落方向 Left-to-right paragraph direction 由左至右的段落方向 Right-to-left paragraph direction 由右至左的段落方向 Not rendered: this adjustment ({key}) is kept as imported. 未算繪:此調整({key})依匯入時的原樣保留。 -# Print preview image (#8236) Print preview image Print preview image - Clear Selection 清除選取範圍 - Color Aware 顏色感知 - Decontaminate Colors 淨化顏色 - Edge Detection 邊緣偵測 - Global Refinements 整體調整 - High Quality Preview 高品質預視 - Object Aware 物件感知 - Real-Time Refinement 即時調整 - Refine Edge Brush Tool 調整邊緣筆刷工具 - Refine Hair 調整毛髮 - Refine Mode 調整模式 - Remember Settings 記住設定 - View Mode 檢視模式 - Object Aware needs a segmentation model, which isn't available yet 物件感知需要分割模型,目前尚無法使用 - Refine Hair needs hair detection, which isn't available yet 調整毛髮需要毛髮偵測,目前尚無法使用 -# Color panel menu: modes, copy commands and colour ramps (#6000) Hue Cube 色相立方體 Brightness Cube 亮度立方體 Color Wheel 色輪 @@ -3113,9 +3108,8 @@ curves Smooth 平滑 Grayscale Ramp 灰階色帶 Current Colors 目前色彩 Make Ramp Web Safe 讓色帶成為網頁安全色 - Select and Mask was closed: its document is no longer the active one 已關閉「選取並遮住」:其文件已不是使用中的文件 - Select and Mask was closed: another layer was selected 已關閉「選取並遮住」:已選取另一個圖層 -# Art History Brush (#213). + The path was kept as the Work Path 路徑已保留為工作路徑 + The path was discarded 路徑已捨棄 Art History Brush 藝術歷史畫筆 Art History Brush Tool 藝術歷史畫筆工具 Tight Short 緊密短 @@ -3128,8 +3122,6 @@ curves Smooth 平滑 Loose Curl 寬鬆捲曲 Area 區域 Stylized dabs from a history state 從歷史狀態繪製風格化點塗 - -# Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio 外觀比例 Category 類別 Color Table 色彩表 @@ -3141,3 +3133,21 @@ curves Smooth 平滑 Font size presets 字體大小預設 Leading presets 行距預設 Tracking presets 字距調整預設 + Clear Selection 清除選取範圍 + Color Aware 顏色感知 + Decontaminate Colors 淨化顏色 + Edge Detection 邊緣偵測 + Global Refinements 整體調整 + High Quality Preview 高品質預視 + Object Aware 物件感知 + Real-Time Refinement 即時調整 + Refine Edge Brush Tool 調整邊緣筆刷工具 + Refine Hair 調整毛髮 + Refine Mode 調整模式 + Remember Settings 記住設定 + View Mode 檢視模式 + Object Aware needs a segmentation model, which isn't available yet 物件感知需要分割模型,目前尚無法使用 + Refine Hair needs hair detection, which isn't available yet 調整毛髮需要毛髮偵測,目前尚無法使用 + Select and Mask was closed: its document is no longer the active one 已關閉「選取並遮住」:其文件已不是使用中的文件 + Select and Mask was closed: another layer was selected 已關閉「選取並遮住」:已選取另一個圖層 + Drag to move the selected path 拖曳以移動選取的路徑 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 18101a5903..4dfa76479b 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -104,6 +104,12 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("palette", include_bytes!("../../../assets/icons/palette.svg")), ("panel-right", include_bytes!("../../../assets/icons/panel-right.svg")), ("panels-top-left", include_bytes!("../../../assets/icons/panels-top-left.svg")), + ("path-op-combine", include_bytes!("../../../assets/icons/path-op-combine.svg")), + ("path-op-exclude", include_bytes!("../../../assets/icons/path-op-exclude.svg")), + ("path-op-intersect", include_bytes!("../../../assets/icons/path-op-intersect.svg")), + ("path-op-merge", include_bytes!("../../../assets/icons/path-op-merge.svg")), + ("path-op-new-layer", include_bytes!("../../../assets/icons/path-op-new-layer.svg")), + ("path-op-subtract", include_bytes!("../../../assets/icons/path-op-subtract.svg")), ("pen-curvature", include_bytes!("../../../assets/icons/pen-curvature.svg")), ("pen-freeform", include_bytes!("../../../assets/icons/pen-freeform.svg")), ("pen-add-anchor", include_bytes!("../../../assets/icons/pen-add-anchor.svg")), @@ -121,6 +127,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("rectangle-horizontal", include_bytes!("../../../assets/icons/rectangle-horizontal.svg")), ("rectangle-vertical", include_bytes!("../../../assets/icons/rectangle-vertical.svg")), ("redo-2", include_bytes!("../../../assets/icons/redo-2.svg")), + ("rotate-ccw", include_bytes!("../../../assets/icons/rotate-ccw.svg")), ("rotate-cw", include_bytes!("../../../assets/icons/rotate-cw.svg")), ("ruler", include_bytes!("../../../assets/icons/ruler.svg")), ("sampler", include_bytes!("../../../assets/icons/sampler.svg")), diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 7251859a5e..8a2fbec54e 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -705,6 +705,59 @@ fn cmd_is_not_the_move_tool_for_selection_hand_zoom_pen_shape_or_type_tools() { } } +/// With the Hand tool, ⌘ (Ctrl off the Mac) held is Zoom In and ⌥ Zoom Out, as in Photoshop; the +/// Hand is back when the key comes up (#6434). +#[test] +fn cmd_and_alt_with_the_hand_tool_zoom_in_and_out_while_held() { + let mut h = harness(Tool::Hand); + let z0 = h.state().ui.views[0].zoom; + hold_mods(&mut h, Modifiers::COMMAND); + assert_eq!(held_tool(h.state(), &h.ctx), Some(Temporary::ZoomIn)); + click(&mut h, 200.0, 150.0, Modifiers::COMMAND); + let z1 = h.state().ui.views[0].zoom; + assert!(z1 > z0, "{z0} -> {z1}"); + hold_mods(&mut h, Modifiers::ALT); + assert_eq!(held_tool(h.state(), &h.ctx), Some(Temporary::ZoomOut)); + click(&mut h, 200.0, 150.0, Modifiers::ALT); + let z2 = h.state().ui.views[0].zoom; + assert!(z2 < z1, "{z1} -> {z2}"); + hold_mods(&mut h, Modifiers::COMMAND | Modifiers::ALT); + assert_eq!(held_tool(h.state(), &h.ctx), Some(Temporary::ZoomOut), "⌥ turns ⌘'s Zoom In around"); + hold_mods(&mut h, Modifiers::NONE); + assert_eq!(held_tool(h.state(), &h.ctx), None); + // Released: a drag pans again. + let (center, zoom) = (h.state().ui.views[0].center, h.state().ui.views[0].zoom); + drag_with(&mut h, Modifiers::NONE, 200.0, 150.0, 260.0, 190.0); + assert_ne!(h.state().ui.views[0].center, center, "the Hand pans"); + assert_eq!(h.state().ui.views[0].zoom, zoom); + assert_eq!(h.state().ui.tool, Tool::Hand); +} + +/// ⌘ pressed in the middle of a Hand drag doesn't stop the pan, and an open Free Transform keeps ⌘ +/// for its handles. +#[test] +fn cmd_mid_pan_or_during_free_transform_is_not_the_hand_tools_zoom() { + let mut h = harness(Tool::Hand); + let z0 = h.state().ui.views[0].zoom; + press_at(&mut h, 200.0, 150.0); + hold_mods(&mut h, Modifiers::COMMAND); + let center = h.state().ui.views[0].center; + move_to(&mut h, 300.0, 150.0); + assert_ne!(h.state().ui.views[0].center, center, "the drag kept panning after ⌘ went down"); + release(&mut h, 300.0, 150.0, Modifiers::COMMAND); + hold_mods(&mut h, Modifiers::NONE); + assert_eq!(h.state().ui.views[0].zoom, z0, "no zoom"); + + with_layer(&mut h); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().ui.transform.is_some()); + hold_mods(&mut h, Modifiers::COMMAND); + assert_eq!(held_tool(h.state(), &h.ctx), None); + hold_mods(&mut h, Modifiers::NONE); +} + /// The params of the last brush stroke (`paint.stroke`, or the Pencil's `paint.pencil`). fn last_stroke(app: &PhotocraftApp) -> serde_json::Value { let journal = &app.session.journal; diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index fff3299099..e6a20bae55 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -488,6 +488,7 @@ fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { // However the tool was picked (toolbar, flyout, shortcut, automation), its group's key brings // it back later (#2608). app.ui.remember_group_tool(); + 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 // below it covers the canvas, so canvas zoom keys are blocked too. @@ -695,10 +696,15 @@ fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f } } // Pen path in progress: ↩ and Esc both end it as an open path and keep it, as in Photoshop (#1769). - if app.ui.pen.is_some() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_key(Modifiers::NONE, Key::Escape)) { + // When the document refuses it, ↩ keeps the draft to commit again; Esc keeps it as the Work Path. + if app.ui.pen.is_some() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { crate::vector_ui::pen_commit(app, false); return true; } + if app.ui.pen.is_some() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + crate::vector_ui::pen_end(app); + return true; + } // A finished work path shown by the Pen or Path Selection: ⌫/Delete deletes it, as in // Photoshop (#5702), never Edit › Clear on the pixels under it. if focus != crate::shortcut_dispatch::Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) { @@ -812,6 +818,7 @@ fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f if !untouched && pressed(Key::Escape) { app.ui.polygon.clear(); app.ui.polygon_mode.clear(); + app.ui.polygon_doc = None; crate::crop_ui::cancel(app); return true; } @@ -856,8 +863,10 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } return; } - // ⇧+ / ⇧− step the blend mode and ⇧⌥ letters pick one (`blend_keys`). Before the tool - // letters: `consume_key` ignores extra ⇧ and ⌥, so ⇧⌥M would otherwise pick a tool. + // + / − pick a Path Operation with the Pen tools and Path Selection (`path_components`)… + crate::path_components::handle_keys(app, ctx); + // … and otherwise ⇧+ / ⇧− step the blend mode and ⇧⌥ letters pick one (`blend_keys`). Before the + // tool letters: `consume_key` ignores extra ⇧ and ⌥, so ⇧⌥M would otherwise pick a tool. crate::blend_keys::handle(app, ctx); // Tool keys; pressing the key of the current group cycles within it. With Preferences › // Tools › Use Shift Key for Tool Switch, only ⇧+key cycles and the plain key keeps the diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 4826872457..d40943d1ca 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -1022,6 +1022,35 @@ fn paint_bucket_shows_a_bucket_cursor() { assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Crosshair, "Precise keeps the crosshair"); } +#[test] +fn move_alt_copy_cursor_follows_the_latched_duplication_drag() { + let mut h = harness(); + h.state_mut().run("shape.create", json!({"kind": "rect", "rect": [150, 100, 100, 100], "fill": "#ff0000"})).unwrap(); + h.state_mut().ui.tool = crate::state::Tool::Move; + h.state_mut().ui.tool_options.move_show_transform = false; + let before = h.state().session.active().unwrap().doc.layers.len(); + let p = h.state().last_canvas_rect.center(); + h.hover_at(p); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default); + h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Copy); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), before, "hovering never duplicates"); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }); + h.run_steps(1); + let end = p + vec2(25.0, 15.0); + h.hover_at(end); + h.run_steps(2); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Copy, "releasing Alt does not undo an active copy"); + h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), before + 1); +} + /// The Hand tool, and Space held over another tool, show an open hand while hovering and a fist /// while they pan (#2196). The OS draws those everywhere but Windows, where winit maps `Grab` to /// the four-arrow move cursor, so the app hands it a bitmap there (`Crosshair` is the fallback). @@ -1099,7 +1128,9 @@ fn hand_pointer_over_the_canvas_under_a_dialog() { fn esc_ends_a_pen_path_and_keeps_it() { let mut h = harness(); h.state_mut().ui.tool = crate::state::Tool::Pen; - h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3], [[150.0, 120.0]; 3]], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = + Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3], [[150.0, 120.0]; 3]], owner, ..Default::default() }); h.key_press(Key::Escape); h.run_steps(2); assert!(h.state().ui.pen.is_none(), "the Pen leaves drawing state"); @@ -1118,7 +1149,8 @@ fn esc_ends_a_pen_path_and_keeps_it() { fn pen_shows_the_close_path_pointer_over_the_first_anchor() { let mut h = harness(); h.state_mut().ui.tool = crate::state::Tool::Pen; - h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3]], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3]], owner, ..Default::default() }); let screen = |h: &Harness<'static, PhotocraftApp>, x: f32, y: f32| { let v = &h.state().ui.views[0]; let c = h.state().last_canvas_rect.center(); @@ -1289,6 +1321,54 @@ fn move_tool_controls_rotate_from_just_outside_the_box() { assert!((tilt - 90.0).abs() < 8.0 || (tilt + 270.0).abs() < 8.0, "rotated about a quarter turn, got {tilt}° (zoom {zoom})"); } +#[test] +fn assignable_pick_layer_shortcut_follows_transformed_canvas_without_editing() { + let mut h = harness(); + let base = h.state().session.active().unwrap().active_layer.unwrap(); + h.state_mut().run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + let paint = h.state().session.active().unwrap().active_layer.unwrap(); + h.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + h.state_mut().run("select.deselect", json!({})).unwrap(); + h.state_mut().run("layer.new.layer", json!({"name": "Empty"})).unwrap(); + h.state_mut().run("prefs.set", json!({"path": "shortcuts.layer.selectUnderCursor", "value": "Cmd+Alt+K"})).unwrap(); + h.state_mut().ui.tool = crate::state::Tool::Brush; + for (zoom, rotation, flip) in [(1.0, 0.0, false), (2.0, 37.0, true), (0.5, -90.0, false)] { + h.state_mut().ui.views[0].zoom = zoom; + h.state_mut().ui.views[0].rotation = rotation; + h.state_mut().ui.views[0].center = [180.0, 145.0]; + h.state_mut().ui.view.flip_horizontal = flip; + h.run_steps(2); + for (point, expected) in [([120.0, 120.0], paint), ([155.0, 155.0], base)] { + let pos = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(point[0], point[1]); + let history = h.state().session.active().unwrap().history.past_len(); + h.hover_at(pos); + h.key_press_modifiers(Modifiers::COMMAND | Modifiers::ALT, Key::K); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(expected)); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history, "picking never adds a document edit"); + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke")); + } + } + h.state_mut().run("layer.setProps", json!({"layer": paint.0, "visible": false})).unwrap(); + let p = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(120.0, 120.0); + h.hover_at(p); + h.key_press_modifiers(Modifiers::COMMAND | Modifiers::ALT, Key::K); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(base)); + // Outside the document and modal dialogs preserve the current selection. + h.state_mut().run("layer.select", json!({"layer": paint.0})).unwrap(); + h.hover_at(pos2(0.0, 0.0)); + h.key_press_modifiers(Modifiers::COMMAND | Modifiers::ALT, Key::K); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(paint)); + open_dialog(&mut h); + h.hover_at(p); + h.key_press_modifiers(Modifiers::COMMAND | Modifiers::ALT, Key::K); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(paint)); +} + #[test] fn marquee_drag_after_hiding_extras_restores_selection_visibility() { let mut h = harness(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 59c2c70bed..11967c496d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -22,6 +22,7 @@ macro_rules! tl { $crate::i18n::t($s) }; } +mod brush_mode_menu; pub mod canvas; pub mod control; pub mod dialogs; @@ -207,6 +208,7 @@ pub use panels::brushes_tab; pub use panels::channels_panel; pub use panels::chrome_ui; pub use panels::clip_line_ui; +pub use panels::color_hud; pub use panels::color_panel_ui; pub use panels::comps_ui; pub use panels::doc_props_ui; @@ -281,6 +283,7 @@ pub use tools::move_hover; pub use tools::move_lock; pub use tools::move_mods; pub use tools::object_finder; +use tools::path_components; pub use tools::perspective_crop_ui; pub use tools::perspective_ui; pub use tools::puppet_ui; @@ -340,6 +343,9 @@ pub struct PhotocraftApp { monitors: monitor_status::State, checker: Option, drag: Option, + /// An owned vector drag was cancelled (`canvas::cancel_stale_vector_drag`): the rest of its + /// pointer events go nowhere. + pub(crate) cancelled_vector_drag: bool, /// A Move-tool press landed on a locked layer: the first pointer move shows Photoshop's /// message (`move_lock`), a plain click shows nothing. pub(crate) move_blocked: bool, @@ -461,6 +467,9 @@ pub struct PhotocraftApp { pub(crate) drop_places: std::collections::VecDeque, /// The document each of `ui.views` belongs to, as of the last [`Self::sync_views`]. view_docs: Vec, + /// The document `ui.selected_path` belongs to, as of the last [`Self::sync_views`]: a Paths + /// panel selection never carries over to a same-named path in another tab. + path_document: Option<(DocId, u64, std::sync::Weak)>, pub fps: f32, pub(crate) last_frame_time: f64, thumbs: HashMap<(photocraft_doc::LayerId, u8), (u64, egui::TextureHandle)>, @@ -860,3 +869,9 @@ mod browse_field_tests; mod options_hit_area_tests; #[cfg(test)] mod select_and_mask_button_tests; + +#[cfg(test)] +mod saved_path_edit_tests; + +#[cfg(test)] +mod pen_path_ownership_tests; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index fdafe87eae..68af926b5e 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -296,6 +296,9 @@ fn invoke_file_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, } pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + if id == "layer.selectUnderCursor" { + return select_layer_under_cursor(app, ctx); + } if let Some(result) = invoke_early_commands(app, ctx, id, ¶ms) { return result; } @@ -650,7 +653,7 @@ fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) let doc = app.session.active_index().ok_or("no document")?; let wid = app.ui.alloc_id(); let view = app.ui.views[doc].clone(); - app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); + app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, floating: false, focused: false, position: None }); Ok(json!({"window": wid})) })()), "window.theme.toggle" => { @@ -800,3 +803,25 @@ pub fn apply_workspace(app: &mut PhotocraftApp) { app.ui.timeline.playing = false; } } + +/// Pointer-dependent shell command; pixel picking and selection remain engine commands. +fn select_layer_under_cursor(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result { + if app.drag.is_some() || app.brush_resize.is_some() { + return Ok(json!({"layer": null})); + } + let Some(xf) = crate::canvas::ViewXform::active(app) else { return Ok(json!({"layer": null})) }; + let Some(pointer) = ctx.pointer_hover_pos().filter(|p| xf.rect.contains(*p)) else { return Ok(json!({"layer": null})) }; + let [x, y] = xf.to_doc(pointer); + let inside = app + .session + .active() + .is_some_and(|st| x.is_finite() && y.is_finite() && x >= 0.0 && y >= 0.0 && x < f64::from(st.doc.size.width) && y < f64::from(st.doc.size.height)); + if !inside { + return Ok(json!({"layer": null})); + } + let picked = app.run("layer.pickAt", json!({"x": x, "y": y, "target": "layer", "select": false}))?; + if let Some(layer) = picked.get("layer").and_then(Value::as_u64) { + app.run("layer.select", json!({"layer": layer, "mode": "replace"}))?; + } + Ok(picked) +} diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 7baa0b9bf6..c932ca092c 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -3,6 +3,9 @@ use super::items::MenuItem; use super::{DOCUMENT_ITEM, PhotocraftApp, Value}; pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { + if id == "layer.selectUnderCursor" { + return app.session.active().is_some() && app.drag.is_none() && app.brush_resize.is_none(); + } if crate::tool_shortcuts::tool(id).is_some() { return true; } diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 3bc850e12f..bbe985ab6e 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -19,14 +19,14 @@ mod dispatch; mod options; pub use arrange::cells; -pub(crate) use arrange::float_window; +pub(crate) use arrange::{document_is_floating, float_window}; pub(crate) use dialogs::write_copy; #[cfg(test)] use dialogs::{form, front, label_of}; pub use dialogs::{form_body, form_keys, reset_form}; #[cfg(test)] use dispatch::is_enabled_with_engine; -pub use dispatch::{checked, handles, invoke, is_enabled}; +pub use dispatch::{checked, handles, invoke, is_enabled, leave_full_screen_without_document}; #[cfg(test)] use options::screen_mode_commands; pub use options::{persist, pixel_aspect_ratio, restore}; diff --git a/crates/ui-egui/src/menus/view_cmds/arrange.rs b/crates/ui-egui/src/menus/view_cmds/arrange.rs index 0759cf4b56..9cf7a61d80 100644 --- a/crates/ui-egui/src/menus/view_cmds/arrange.rs +++ b/crates/ui-egui/src/menus/view_cmds/arrange.rs @@ -36,7 +36,7 @@ fn screen_position(v: &Value) -> Option<[f32; 2]> { Some([n(0)?, n(1)?]) } -pub(crate) fn float_window(app: &mut PhotocraftApp, doc: usize, offset: usize) -> u64 { +pub(crate) fn float_window(app: &mut PhotocraftApp, doc: usize, offset: usize, floating: bool) -> u64 { let wid = app.ui.alloc_id(); let mut view = app.ui.views.get(doc).cloned().unwrap_or_default(); view.zoom_animating = false; @@ -44,7 +44,7 @@ pub(crate) fn float_window(app: &mut PhotocraftApp, doc: usize, offset: usize) - view.zoom_transition = None; view.display_camera = None; view.fit_pending = offset > 0 || view.fit_pending; - app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); + app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, floating, focused: false, position: None }); wid } @@ -63,7 +63,7 @@ pub(super) fn arrange(app: &mut PhotocraftApp, k: &str, p: &Value) -> Result { let doc = app.session.active_index().ok_or("no document")?; - Ok(json!({"window": float_window(app, doc, 0)})) + Ok(json!({"window": float_window(app, doc, 0, false)})) } // Optional `document` (index; default the active one) and `position` (`[x, y]`, the // window's screen position in points): dragging a tab off the tab strip uses both (#3733). @@ -79,7 +79,14 @@ pub(super) fn arrange(app: &mut PhotocraftApp, k: &str, p: &Value) -> Result None, Some(v) => Some(screen_position(v).ok_or("position must be [x, y] in points")?), }; - let wid = float_window(app, doc, 0); + // Tearing off the same tab again must not create another viewport for the + // same document. Keep its existing view and position if it is already open. + if let Some(w) = app.ui.windows.iter().find(|w| w.open && w.floating && w.document == doc) { + let wid = w.id; + app.session.set_active(doc); + return Ok(json!({"window": wid})); + } + let wid = float_window(app, doc, 0, true); if let Some(w) = app.ui.windows.iter_mut().find(|w| w.id == wid) { w.position = position; } @@ -88,7 +95,7 @@ pub(super) fn arrange(app: &mut PhotocraftApp, k: &str, p: &Value) -> Result { let n = app.session.documents().len(); - let ids: Vec = (0..n).map(|d| float_window(app, d, d)).collect(); + let ids: Vec = (0..n).map(|d| float_window(app, d, d, true)).collect(); Ok(json!({"windows": ids})) } "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => { @@ -121,6 +128,10 @@ pub(super) fn arrange(app: &mut PhotocraftApp, k: &str, p: &Value) -> Result bool { + app.ui.windows.iter().any(|w| w.open && w.floating && w.document == doc) +} + /// Screen rectangles for `n` documents in an arrangement (`None` = tabs). The active document /// always gets a cell; n-up layouts show that many documents starting from the active one. pub fn cells(layout: &str, rect: egui::Rect, n: usize) -> Option> { diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index f4bcd87542..fe6dee7e2e 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -136,7 +136,18 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { // Data-driven labels (a per-part checkbox shows the part's name, not a catalogue entry) // come from `__labels` verbatim; everything else goes through the catalogue. let labels = f.get("__labels").cloned().unwrap_or(Value::Null); - let label = |k: &str| labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string); + let file_info = f.get("__command").and_then(Value::as_str) == Some("file.fileInfo"); + let label = |k: &str| { + if file_info { + match k { + "title" => return tl!("Document Title").to_owned(), + "copyright" => return tl!("Copyright Notice").to_owned(), + "copyrightUrl" => return tl!("Copyright Info URL").to_owned(), + _ => {} + } + } + labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string) + }; let keys = form_keys(f); let mut browse: Option = None; egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { @@ -185,13 +196,22 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { crate::widgets::dropdown(ui, &format!("form-{k}"), &label(&k), &mut s, &refs, 200.0); } None => { - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(label(&k)); - // A folder field gets the system folder picker (#7942, #9357). - if crate::dialogs::is_folder_field(&k) && crate::widgets::secondary_button(ui, tl!("Browse…"), 0.0).clicked() { - browse = Some(k.clone()); - } - }); + if file_info && matches!(k.as_str(), "description" | "keywords" | "copyright") { + egui::ScrollArea::vertical().id_salt(("form-text", &k)).max_height(80.0).show(ui, |ui| { + let response = ui.add(egui::TextEdit::multiline(&mut s).desired_rows(3).desired_width(260.0)).accessible_name(label(&k)); + if response.has_focus() { + ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + } + }); + } else { + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(label(&k)); + // A folder field gets the system folder picker (#7942, #9357). + if crate::dialogs::is_folder_field(&k) && crate::widgets::secondary_button(ui, tl!("Browse…"), 0.0).clicked() { + browse = Some(k.clone()); + } + }); + } } } json!(s) @@ -396,7 +416,7 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para let (_, _, name) = doc?; dialog( app, - json!({"dir": dir, "prefix": name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a), "format": "png", "visibleOnly": true}), + json!({"dir": dir, "prefix": name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a), "format": "png", "visibleOnly": true, "trim": false}), json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}), ) } diff --git a/crates/ui-egui/src/menus/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs index 4a9884c6c0..80e8d41c88 100644 --- a/crates/ui-egui/src/menus/view_cmds/dispatch.rs +++ b/crates/ui-egui/src/menus/view_cmds/dispatch.rs @@ -82,7 +82,10 @@ pub(super) fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabl } let doc = app.session.active().is_some(); Some(match id { - "view.screenMode.cycle" => app.ui.text_edit.is_none(), + // Full Screen Mode shows a document, so without one it is unavailable, as in Photoshop + // (#9349); with none open, Cycle can only bring a full screen mode back to Standard. + "view.screenMode.cycle" => app.ui.text_edit.is_none() && (doc || app.ui.view.screen_mode != "standard"), + "view.screenMode.fullScreen" | "view.screenMode.fullScreenWithMenuBar" => doc, "view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" | "view.rotateView" | "view.resetView" => doc, "view.fitArtboardOnScreen" => app.session.active().is_some_and(|d| d.doc.has_artboards()), i if i.starts_with("window.arrange.") => match &i["window.arrange.".len()..] { @@ -105,6 +108,14 @@ pub(super) fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabl }) } +/// A full screen mode with no document left (the last one closed) goes back to Standard Screen +/// Mode, rather than showing the start screen on the full screen pasteboard (#9349). +pub fn leave_full_screen_without_document(app: &mut PhotocraftApp, ctx: &egui::Context) { + if app.ui.view.screen_mode != "standard" && app.session.documents().is_empty() { + let _ = crate::menus::invoke(app, ctx, "view.screenMode.standard", json!({})); + } +} + pub fn checked(app: &PhotocraftApp, id: &str) -> Option { let o = &app.ui.view; if let Some(k) = id.strip_prefix("view.show.") { @@ -318,7 +329,16 @@ fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Res return Ok(json!(*slot)); } if let Some(k) = id.strip_prefix("view.screenMode.") { - let next = if k == "cycle" { + // Full Screen Mode shows a document (#9349): refused without one, from any caller (the + // toolbar's list, automation), before a viewport command can go out. + if matches!(k, "fullScreen" | "fullScreenWithMenuBar") && app.session.documents().is_empty() { + return Err("Full Screen Mode needs an open document".into()); + } + let next = if k == "cycle" && app.session.documents().is_empty() { + // Without a document Cycle can only leave a full screen mode (#9349): straight back + // to Standard, not on to the next full screen mode. + "standard" + } else if k == "cycle" { let i = SCREEN_MODES.iter().position(|m| *m == o.screen_mode).unwrap_or(0); SCREEN_MODES[(i + 1) % SCREEN_MODES.len()] } else { diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 05c1f1bb60..3ef2ab13fa 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -456,9 +456,12 @@ fn float_in_window_takes_a_document_and_position() { let w = app.ui.windows.last().unwrap(); assert_eq!(r, json!({"window": w.id})); assert_eq!((w.document, w.position), (1, Some([1950.0, 40.5]))); - assert_eq!(app.session.active_index(), Some(1)); - menu(&mut app, &ctx, "window.arrange.floatInWindow", json!({})).unwrap(); - assert_eq!(app.ui.windows.last().map(|w| (w.document, w.position)), Some((1, None)), "defaults: the active document, placed by the OS"); + assert!(w.floating); + assert_eq!(app.session.active_index(), Some(1), "the floated document stays active"); + let again = menu(&mut app, &ctx, "window.arrange.floatInWindow", json!({"document": 1})).unwrap(); + assert_eq!(again, r, "tearing off the same document reuses its window"); + assert_eq!(app.ui.windows.len(), 1); + assert_eq!(app.ui.windows[0].position, Some([1950.0, 40.5])); for bad in [ json!({"document": 3}), json!({"document": -1}), @@ -470,7 +473,31 @@ fn float_in_window_takes_a_document_and_position() { ] { assert!(menu(&mut app, &ctx, "window.arrange.floatInWindow", bad.clone()).is_err(), "{bad}"); } - assert_eq!(app.ui.windows.len(), 2, "rejected params open no window"); + assert_eq!(app.ui.windows.len(), 1, "rejected params open no window"); + app.ui.windows[0].open = false; + let reopened = menu(&mut app, &ctx, "window.arrange.floatInWindow", json!({"document": 1})).unwrap(); + assert_ne!(reopened, r, "a closed window can be floated again"); + assert_eq!(app.ui.windows.last().map(|w| (w.document, w.position)), Some((1, None))); +} + +#[test] +fn float_in_window_defaults_to_the_active_document() { + let (mut app, ctx) = app_with(3); + app.session.set_active(1); + let r = menu(&mut app, &ctx, "window.arrange.floatInWindow", json!({})).unwrap(); + let window = app.ui.windows.last().unwrap(); + assert_eq!(r, json!({"window": window.id})); + assert_eq!(window.document, 1); + assert!(window.floating); + assert_eq!(app.session.active_index(), Some(1)); +} + +#[test] +fn float_all_in_windows_gives_each_document_its_own_view() { + let (mut app, ctx) = app_with(3); + menu(&mut app, &ctx, "window.arrange.floatAllInWindows", json!({})).unwrap(); + assert_eq!(app.ui.windows.iter().map(|w| w.document).collect::>(), [0, 1, 2]); + assert!(app.ui.windows.iter().all(|w| w.floating)); } #[test] @@ -778,3 +805,41 @@ fn form_keys_orders_by_order_then_catalogue() { let f = json!({"zeta": "", "alpha": ""}).as_object().unwrap().clone(); assert_eq!(form_keys(&f).iter().map(String::as_str).collect::>(), ["alpha", "zeta"]); } + +/// #9349: Full Screen Mode shows a document. Photoshop refuses it with none open, so the start +/// screen never sits on the full screen pasteboard; closing the last document in a full screen +/// mode goes back to Standard. +#[test] +fn full_screen_modes_need_a_document() { + let (mut app, ctx) = app_with(0); + for id in ["view.screenMode.fullScreen", "view.screenMode.fullScreenWithMenuBar", "view.screenMode.cycle"] { + assert_eq!(is_enabled(&app, id), Some(false), "{id} without a document"); + } + // #9354 review: run anyway (the toolbar list, automation), they are refused and Standard stays. + for id in ["view.screenMode.fullScreen", "view.screenMode.fullScreenWithMenuBar"] { + assert!(menu(&mut app, &ctx, id, json!({})).is_err(), "{id} is refused without a document"); + assert_eq!(app.ui.view.screen_mode, "standard", "{id}"); + } + assert_eq!(is_enabled(&app, "view.screenMode.standard"), Some(true)); + let (mut with_doc, _) = app_with(1); + for id in ["view.screenMode.fullScreen", "view.screenMode.fullScreenWithMenuBar", "view.screenMode.cycle"] { + assert_eq!(is_enabled(&with_doc, id), Some(true), "{id} with a document"); + } + // The last document closed in Full Screen Mode: back to Standard. + menu(&mut with_doc, &ctx, "view.screenMode.fullScreen", json!({})).unwrap(); + leave_full_screen_without_document(&mut with_doc, &ctx); + assert_eq!(with_doc.ui.view.screen_mode, "fullScreen", "a document is still open"); + with_doc.run("file.close", json!({"save": false})).unwrap(); + assert!(with_doc.session.documents().is_empty()); + leave_full_screen_without_document(&mut with_doc, &ctx); + assert_eq!(with_doc.ui.view.screen_mode, "standard"); + // A full screen mode reached anyway (automation) with no document drops back the same way. + app.ui.view.screen_mode = "fullScreenWithMenuBar".into(); + assert_eq!(is_enabled(&app, "view.screenMode.cycle"), Some(true), "Cycle can still leave it"); + // #9354 review: and Cycle itself goes straight back to Standard, not on to Full Screen. + menu(&mut app, &ctx, "view.screenMode.cycle", json!({})).unwrap(); + assert_eq!(app.ui.view.screen_mode, "standard", "Cycle without a document returns to Standard"); + app.ui.view.screen_mode = "fullScreenWithMenuBar".into(); + leave_full_screen_without_document(&mut app, &ctx); + assert_eq!(app.ui.view.screen_mode, "standard"); +} diff --git a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs index 1c65cf5ec9..48a15b4224 100644 --- a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs +++ b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs @@ -56,11 +56,14 @@ fn the_wheel_over_the_brush_mode_dropdown_steps_the_painting_mode() { wheel(&mut h, at, -1.0); assert_eq!(brush_mode(&h), BlendMode::Dissolve); wheel(&mut h, at, -1.0); - assert!(h.state().ui.tool_options.brush_clear, "Clear follows Dissolve, as in Photoshop"); + assert!(h.state().session.tools.brush.behind, "Behind follows Dissolve"); + wheel(&mut h, at, -1.0); + assert!(h.state().ui.tool_options.brush_clear, "Clear follows Behind"); + assert!(!h.state().session.tools.brush.behind); wheel(&mut h, at, -1.0); assert!(!h.state().ui.tool_options.brush_clear); assert_eq!(brush_mode(&h), BlendMode::Darken); - wheel(&mut h, at, 3.0); + wheel(&mut h, at, 4.0); assert_eq!(brush_mode(&h), BlendMode::Normal, "up steps back and stops at the first mode"); } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 523fc92ec8..be80f832bb 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -25,6 +25,7 @@ pub mod channels_panel; pub mod chrome_ui; pub mod clip_line_ui; mod color; +pub mod color_hud; pub mod color_panel_ui; pub mod comps_ui; pub mod doc_props_ui; @@ -87,7 +88,7 @@ pub(crate) use layer_drag::{dropped_on, layer_drag_edge_scroll}; pub(crate) use layer_row::thumb_load_badge; #[cfg(test)] use layer_row::{layer_thumb_fit, paint_clipping_indicator}; -pub(crate) use layers::blend_options; +pub(crate) use layers::{blend_options, fx_button}; #[cfg(test)] use layers::{layers, opacity_row_layout, simple_lock_toggle}; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 092ada6a43..c1ba436d22 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -130,6 +130,14 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option) failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", actions_cmds::MAX_PLAYBACK_STEPS)})); break; } + let resolved = match actions_cmds::playback_params(&app.session, id, p) { + Ok(p) => p, + Err(e) => { + failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); + break; + } + }; + let p = &resolved; // The gate judges the step before its dialog opens: a denied step neither runs nor // pauses. if let Some(auth) = app.session.authorize @@ -157,6 +165,8 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option) let target = app.session.active().map(|d| d.doc.id); let result = if id == "actions.play" { play(app, p) + } else if actions_cmds::saves_smart_contents(&app.session, id) { + app.session.execute(actions_cmds::SAVE_CONTENTS, json!({})).map_err(|e| e.to_string()) } else if actions_cmds::shell_save_command(id) { // Write synchronously, so the next step doesn't meet a document locked by a // background save. diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 551bcf7b21..a2f7629513 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -105,6 +105,23 @@ fn a_function_key_with_shift_and_command_plays_its_action() { assert_eq!(layers(&app), before + 1, "Cmd+Shift+F2 plays it"); } +#[test] +fn shell_playback_resolves_recorded_eye_target_on_new_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({"name": "Target"})).unwrap(); + app.run("actions.record", json!({"name": "Hide"})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({"name": "Target"})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let result = play(&mut app, &json!({"action": "Hide"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(!app.session.active().unwrap().doc.layer(id).unwrap().visible); +} + #[test] fn double_clicking_an_action_name_renames_it_in_place() { use egui_kittest::{Harness, kittest::Queryable}; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 49cc070205..d618999d9f 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -13,13 +13,21 @@ pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (Some(*m), m.label())).collect(); - let at = opts.iter().position(|o| o.0 == Some(BlendMode::Dissolve)).map_or(opts.len(), |i| i + 1); - opts.insert(at, (None, "Clear")); - let mut mode = if *clear || held { None } else { Some(b.mode) }; + let opts = crate::brush_mode_menu::choices(); + let mut mode = if *clear || held { + (None, false) + } else if b.behind { + (None, true) + } else { + (Some(b.mode), false) + }; if !widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0.is_empty() { - *clear = mode.is_none(); - if let Some(m) = mode { + *clear = mode == (None, false); + b.behind = mode.1; + if mode.1 { + b.mode = BlendMode::Normal; + } + if let Some(m) = mode.0 { b.mode = m; } } diff --git a/crates/ui-egui/src/panels/brush_panel.rs b/crates/ui-egui/src/panels/brush_panel.rs index 615610fa15..8d45e78de3 100644 --- a/crates/ui-egui/src/panels/brush_panel.rs +++ b/crates/ui-egui/src/panels/brush_panel.rs @@ -1,7 +1,7 @@ //! Window › Brush Settings (F5) and Window › Brushes: Photoshop's floating brush panel. //! -//! Brush Settings: the section list with enable boxes on the left (clicking a controls section -//! shows and enables it; the last five rows only toggle), the selected section's controls on the right (see [`crate::brush_sections`]), +//! Brush Settings: the section list with enable boxes on the left (selecting a controls section +//! shows its options without enabling it; the last five rows only toggle), the selected section's controls on the right (see [`crate::brush_sections`]), //! and a live stroke preview strip below, rendered with the real brush engine and cached on the //! settings (it re-renders only when they change). Brushes: the presets in collapsible groups with //! tip thumbnails and stroke previews, a size slider and a search field. @@ -242,7 +242,7 @@ pub(crate) fn full_uv() -> egui::Rect { egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)) } -/// Clicking a controls section shows and enables it; the final five rows only toggle, keeping +/// Selecting a controls section shows its settings without enabling it; the final five rows toggle, keeping /// the current controls open. The lock on the right is a separate hit target. fn section_list(app: &mut PhotocraftApp, ui: &mut egui::Ui, b: &mut BrushSettings) { let t = Tokens::get(ui.ctx()); @@ -284,6 +284,7 @@ fn section_list(app: &mut PhotocraftApp, ui: &mut egui::Ui, b: &mut BrushSetting ui.painter().rect_filled(r, t.radius_sm, t.hover); } let mut x = r.left() + 6.0; + let mut box_clicked = false; if *has_box && let Some(flag) = section_flag(b, i) { let br = egui::Rect::from_center_size(egui::pos2(x + 6.0, r.center().y), vec2(13.0, 13.0)); // A checkbox-only row is one accessible checkbox across its whole width. A @@ -296,15 +297,14 @@ fn section_list(app: &mut PhotocraftApp, ui: &mut egui::Ui, b: &mut BrushSetting resp }); let on_lock = resp.interact_pointer_pos().is_some_and(|p| p.x > r.right() - 22.0); - // A press on the row (but not its lock) presses the box too: a release there - // turns the section on, or toggles a checkbox-only row (#4476). - let pressed = box_resp.as_ref().is_some_and(|b| b.is_pointer_button_down_on()) || (resp.is_pointer_button_down_on() && !on_lock); + // For controls sections, only the checkbox toggles the setting; a row + // click selects the settings without enabling them (#5136). + let pressed = box_resp.as_ref().is_some_and(|b| b.is_pointer_button_down_on()) || (toggle_only && resp.is_pointer_button_down_on() && !on_lock); let hovered = box_resp.as_ref().is_some_and(|b| b.hovered()) || (toggle_only && resp.hovered()); widgets::check_box(ui.painter(), br, *flag, hovered, pressed, &t); - if box_resp.is_some_and(|resp| resp.clicked()) || (toggle_only && resp.clicked() && !on_lock) { + box_clicked = box_resp.as_ref().is_some_and(|resp| resp.clicked()); + if box_clicked || (toggle_only && resp.clicked() && !on_lock) { *flag = !*flag; - } else if !toggle_only && resp.clicked() && !on_lock { - *flag = true; } x += 20.0; } else { @@ -338,7 +338,7 @@ fn section_list(app: &mut PhotocraftApp, ui: &mut egui::Ui, b: &mut BrushSetting lock_clicked = true; } } - if !toggle_only && resp.clicked() && !lock_clicked { + if !toggle_only && resp.clicked() && !lock_clicked && !box_clicked { app.ui.brush_section = i; } if i == 0 { diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index e0e15cb4f5..7099ee2b1f 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -31,6 +31,48 @@ fn sections_with_boxes_have_flags() { assert!(b.texture.enabled); } +#[test] +fn selecting_a_controls_section_keeps_its_enabled_flag_and_brush_history() { + use egui_kittest::kittest::Queryable; + + for (section, name) in [(1, "Shape Dynamics"), (2, "Scattering"), (3, "Texture")] { + let mut h = harness(0, 0); + let before = h.state().session.tools.brush.clone(); + let journal = h.state().session.journal.len(); + + h.get_by_label(name).click(); + h.run_steps(3); + + assert_eq!(h.state().ui.brush_section, section, "{name} settings are visible"); + assert_eq!(h.state().session.tools.brush, before, "{name} remains disabled"); + assert_eq!(h.state().session.journal.len(), journal, "selecting {name} is not a brush edit"); + } +} + +#[test] +fn controls_section_checkbox_toggles_without_selecting_its_settings() { + use egui_kittest::kittest::Queryable; + + let mut h = harness(0, 0); + let row = h.get_by_label("Scattering").rect(); + let checkbox = egui::pos2(row.left() + 12.0, row.center().y); + let journal = h.state().session.journal.len(); + + for enabled in [true, false] { + h.hover_at(checkbox); + h.run_steps(1); + h.drag_at(checkbox); + h.run_steps(1); + h.drop_at(checkbox); + h.run_steps(3); + + assert_eq!(h.state().session.tools.brush.scattering.enabled, enabled); + assert_eq!(h.state().ui.brush_section, 0, "the checkbox does not select Scattering"); + assert_eq!(last_journal(h.state()).unwrap().1["brush"], json!({"scattering": {"enabled": enabled}})); + } + assert_eq!(h.state().session.journal.len(), journal + 2); +} + /// What each section's controls edit, set to non-default values. fn edit_section(i: usize, b: &mut BrushSettings) { let dynamic = |jitter: f32, control: Control, minimum: f32| paint::Dynamic { jitter, control, fade_steps: 40, minimum, ..Default::default() }; @@ -1424,22 +1466,20 @@ fn f5_edits_the_default_brush_with_every_section() { for (name, _) in SECTIONS { assert!(h.query_all_by_label(name).next().is_some(), "{name} listed"); } - // Clicking a section's name shows it and turns it on: one tools.setBrush. + // Clicking a section's name shows its settings without changing its enable flag. let n = h.state().session.journal.len(); + let shape_enabled = h.state().session.tools.brush.shape_dynamics.enabled; h.get_by_label("Shape Dynamics").click(); h.run_steps(3); assert_eq!(h.state().ui.brush_section, 1); - assert!(h.state().session.tools.brush.shape_dynamics.enabled); - assert_eq!(h.state().session.journal.len(), n + 1); - let (id, p) = last_journal(h.state()).unwrap(); - assert_eq!(id, "tools.setBrush"); - assert_eq!(p["brush"]["shapeDynamics"]["enabled"], json!(true)); + assert_eq!(h.state().session.tools.brush.shape_dynamics.enabled, shape_enabled); + assert_eq!(h.state().session.journal.len(), n); // A section's box toggles it without showing it. h.get_by_label("Enable Transfer").click(); h.run_steps(3); assert!(h.state().session.tools.brush.transfer.enabled); assert_eq!(h.state().ui.brush_section, 1); - assert_eq!(h.state().session.journal.len(), n + 2); + assert_eq!(h.state().session.journal.len(), n + 1); // The rest of the brush is untouched. let b = &h.state().session.tools.brush; assert_eq!((b.size, b.hardness, &b.tip), (fresh.size, fresh.hardness, &fresh.tip)); @@ -1807,13 +1847,21 @@ fn section_boxes_show_a_pressed_state() { let row = h.get_by_label("Shape Dynamics").rect(); assert!(!h.state().session.tools.brush.shape_dynamics.enabled); assert_eq!(box_fill(&h, boxr), Some(widgets::check_box_fill(false, false, &t))); - // Held on the row's name: the unchecked box darkens; the release turns the section on. + // Selecting the controls row leaves its checkbox untouched, including while held. let at = egui::pos2(row.center().x, row.center().y); h.drag_at(at); h.run_steps(2); - assert_eq!(box_fill(&h, boxr), Some(widgets::check_box_fill(false, true, &t)), "pressed, unchecked"); + assert_eq!(box_fill(&h, boxr), Some(widgets::check_box_fill(false, false, &t)), "row press leaves checkbox untouched"); h.drop_at(at); h.run_steps(3); + assert!(!h.state().session.tools.brush.shape_dynamics.enabled); + assert_eq!(box_fill(&h, boxr), Some(widgets::check_box_fill(false, false, &t))); + // The checkbox itself still shows its pressed state and toggles the section. + h.drag_at(boxr.center()); + h.run_steps(2); + assert_eq!(box_fill(&h, boxr), Some(widgets::check_box_fill(false, true, &t)), "pressed, unchecked"); + h.drop_at(boxr.center()); + h.run_steps(3); assert!(h.state().session.tools.brush.shape_dynamics.enabled); assert_eq!(box_fill(&h, boxr), Some(widgets::check_box_fill(true, false, &t))); // Held on the checked box itself: less opaque, then the release turns it off. diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 90cfa9d8e6..59539891aa 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -121,8 +121,10 @@ pub(crate) fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let (kx, ky) = if brightness { (hsva.h, 1.0 - hsva.s) } else { (hsva.s, 1.0 - hsva.v) }; let knob = pos2(field.left() + kx * field.width(), field.top() + ky * field.height()); - ui.painter().circle_stroke(knob, 5.0, Stroke::new(1.5, Color32::WHITE)); - ui.painter().circle_stroke(knob, 6.5, Stroke::new(1.0, Color32::from_black_alpha(160))); + // At the extremes the knob sits on the edge: clip it to the field (#8968). + let painter = ui.painter().with_clip_rect(field); + painter.circle_stroke(knob, 5.0, Stroke::new(1.5, Color32::WHITE)); + painter.circle_stroke(knob, 6.5, Stroke::new(1.0, Color32::from_black_alpha(160))); // The strip: hue (red at both ends, as Photoshop's) or brightness (the colour down to black). let (strip, sresp) = ui.allocate_exact_size(vec2(strip_w, h), Sense::click_and_drag()); let strip_at = |f: f32| { diff --git a/crates/ui-egui/src/panels/color_hud.rs b/crates/ui-egui/src/panels/color_hud.rs new file mode 100644 index 0000000000..5f15c9f954 --- /dev/null +++ b/crates/ui-egui/src/panels/color_hud.rs @@ -0,0 +1,502 @@ +//! Photoshop's HUD Color Picker (#6098): with a painting tool, Shift+Alt+right-click on the +//! canvas opens a floating hue strip and saturation/value square anchored under the pointer. +//! While the right button stays down, moving the pointer over the HUD picks the foreground colour +//! live (`tools.setColors` calls sharing one `coalesce` key, so the gesture is one history step, +//! Rule 1); releasing the button keeps the colour and closes the HUD, Escape restores the colour +//! the gesture started from. A left press closes it too, which is how the control channel ends a +//! gesture it opened with `ui.pointer`. +//! +//! The HUD is drawn as plain meshes and hit-tested from the raw pointer position rather than with +//! interactive widgets: the selection follows the pointer while the *right* button is held, which +//! egui's widgets (left-button only) cannot express. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use egui::{Color32, Mesh, PointerButton, Rect, Stroke, Vec2, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use photocraft_color::convert::{hsb_to_rgb, rgb_to_hsb}; + +use crate::PhotocraftApp; +use crate::paint_mouse::has_brush_picker; +use crate::state::UiState; + +/// Width of the hue strip. +const HUE_W: f32 = 16.0; +/// Side of the saturation/value square, and the strip's height. +const SQUARE: f32 = 128.0; +/// Gap between the strip and the square. +const GAP: f32 = 8.0; +/// The HUD's content size (the frame's chrome sits around it). +pub const SIZE: [f32; 2] = [HUE_W + GAP + SQUARE, SQUARE]; + +/// The HUD Color Picker while it is open. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Hud { + /// Where the gesture began, in screen points: the HUD anchors just below it. + pub anchor: [f32; 2], + /// The colour being picked: hue 0..360, saturation and value 0..1. + pub hsv: [f32; 3], + /// The foreground colour when the gesture began; Escape restores it. + pub start: [f32; 4], + /// The `coalesce` key of this gesture's `tools.setColors` calls. + pub key: u64, + /// Begun by a real right-press: it ends when the right button comes up. One opened through + /// the control channel ends with its Up event instead. + pub hold: bool, + /// The gesture has just opened: near a screen edge the clamped HUD can sit under the still + /// pointer, so hover picking waits until the pointer moves from the anchor. + #[serde(default)] + pub just_opened: bool, +} + +pub(crate) fn hud_id() -> egui::Id { + egui::Id::unique("canvas-color-hud") +} + +/// Is the HUD open? +pub fn is_open(ui: &UiState) -> bool { + ui.color_hud.is_some() +} + +/// Open the HUD at `at`, seeded from the current foreground colour. `hold` marks a real-mouse +/// gesture (see [`Hud::hold`]). +pub fn open(app: &mut PhotocraftApp, at: [f32; 2], hold: bool) { + static KEY: AtomicU64 = AtomicU64::new(0); + let fg = app.session.tools.foreground; + let hsv = rgb_to_hsb([fg[0], fg[1], fg[2]]); + app.ui.color_hud = Some(Hud { anchor: at, hsv: [hsv[0], hsv[1], hsv[2]], start: fg, key: KEY.fetch_add(1, Ordering::Relaxed), hold, just_opened: true }); +} + +/// Close the HUD, keeping the picked colour. +pub fn close(ui: &mut UiState) { + ui.color_hud = None; +} + +/// Close a control-channel HUD on its Up event; a real-mouse HUD closes on the button release. +pub fn release(ui: &mut UiState) { + if ui.color_hud.is_some_and(|h| !h.hold) { + close(ui); + } +} + +/// The hue, saturation and value a pointer at `p` selects inside these rects (Photoshop's strip +/// runs red at the top down through the spectrum; the square is saturation left→right, value +/// top→bottom). `None` when the point is on neither. +pub fn pick_at(hsv: [f32; 3], strip: Rect, square: Rect, p: egui::Pos2) -> Option<[f32; 3]> { + if square.contains(p) { + let s = ((p.x - square.left()) / square.width()).clamp(0.0, 1.0); + let v = 1.0 - ((p.y - square.top()) / square.height()).clamp(0.0, 1.0); + Some([hsv[0], s, v]) + } else if strip.contains(p) { + let h = ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0) * 360.0; + Some([h, hsv[1], hsv[2]]) + } else { + None + } +} + +fn rgb_color(c: [f32; 3]) -> Color32 { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgb(q(c[0]), q(c[1]), q(c[2])) +} + +/// The vertical hue strip: red at the top, a full spectrum cycle. One mesh of bands, so its cost +/// doesn't grow with the HUD. Row `k` (of `n + 1`) holds the left vertex at index `2k` and the +/// right one at `2k + 1`; band `k` joins rows `k` and `k + 1`. +fn hue_strip_mesh(r: Rect) -> Mesh { + let n = 12; + let mut mesh = Mesh::default(); + for k in 0..=n { + let y = r.top() + r.height() * k as f32 / n as f32; + let c = rgb_color(hsb_to_rgb([k as f32 / n as f32 * 360.0, 1.0, 1.0])); + mesh.colored_vertex(egui::pos2(r.left(), y), c); + mesh.colored_vertex(egui::pos2(r.right(), y), c); + } + for k in 0..n { + let (a, b) = (2 * k, 2 * k + 1); + mesh.add_triangle(a, b, b + 2); + mesh.add_triangle(a, b + 2, a + 2); + } + mesh +} + +fn paint_hue_strip(painter: &egui::Painter, r: Rect) { + painter.add(hue_strip_mesh(r)); +} + +/// The saturation/value square for `hue`: white→hue horizontally, then clear→black vertically. +fn paint_sv_square(painter: &egui::Painter, r: Rect, hue: f32) { + let hue_c = rgb_color(hsb_to_rgb([hue, 1.0, 1.0])); + let mut mesh = Mesh::default(); + mesh.colored_vertex(r.left_top(), Color32::WHITE); + mesh.colored_vertex(r.right_top(), hue_c); + mesh.colored_vertex(r.left_bottom(), Color32::WHITE); + mesh.colored_vertex(r.right_bottom(), hue_c); + mesh.add_triangle(0, 1, 3); + mesh.add_triangle(0, 3, 2); + painter.add(mesh); + let mut mesh = Mesh::default(); + mesh.colored_vertex(r.left_top(), Color32::TRANSPARENT); + mesh.colored_vertex(r.right_top(), Color32::TRANSPARENT); + mesh.colored_vertex(r.left_bottom(), Color32::BLACK); + mesh.colored_vertex(r.right_bottom(), Color32::BLACK); + mesh.add_triangle(0, 1, 3); + mesh.add_triangle(0, 3, 2); + painter.add(mesh); +} + +/// Draw the HUD and track the pointer: called once per frame while a gesture is open. +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(mut hud) = app.ui.color_hud else { return }; + if !has_brush_picker(app.ui.tool) { + close(&mut app.ui); + return; + } + let (released, esc, pressed_left, hover) = ctx.input(|i| { + ( + i.pointer.button_released(PointerButton::Secondary), + i.key_pressed(egui::Key::Escape), + i.pointer.button_pressed(PointerButton::Primary), + i.pointer.hover_pos(), + ) + }); + if esc { + let start = hud.start; + let changed = app.session.tools.foreground != start; + close(&mut app.ui); + if changed { + set_foreground(app, start, hud.key); + } + return; + } + if (hud.hold && released) || pressed_left { + close(&mut app.ui); + return; + } + // Keep the HUD on screen: anchored just under the press point, pulled in at the edges. + let screen = ctx.content_rect(); + let style = ctx.global_style(); + let size = Vec2::from(SIZE) + style.spacing.menu_margin.sum() + egui::Vec2::splat(2.0 * style.visuals.window_stroke().width); + let at = egui::pos2(hud.anchor[0], hud.anchor[1] + 4.0); + let pos = egui::pos2(at.x.min(screen.right() - size.x).max(screen.left()), at.y.min(screen.bottom() - size.y).max(screen.top())); + let area = egui::Area::new(hud_id()).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| { + egui::Frame::popup(ui.style()) + .show(ui, |ui| { + let (rect, _) = ui.allocate_exact_size(vec2(SIZE[0], SIZE[1]), egui::Sense::hover()); + let strip = Rect::from_min_size(rect.min, vec2(HUE_W, SQUARE)); + let square = Rect::from_min_max(rect.min + vec2(HUE_W + GAP, 0.0), rect.max); + let p = ui.painter(); + paint_hue_strip(p, strip); + paint_sv_square(p, square, hud.hsv[0]); + p.rect_stroke(strip, 0.0, Stroke::new(1.0, Color32::from_black_alpha(120)), egui::StrokeKind::Inside); + p.rect_stroke(square, 0.0, Stroke::new(1.0, Color32::from_black_alpha(120)), egui::StrokeKind::Inside); + // Markers: a ring in the square at the picked s/v, a bar on the strip at the hue. + let sv = egui::pos2(square.left() + hud.hsv[1] * square.width(), square.top() + (1.0 - hud.hsv[2]) * square.height()); + p.circle(sv, 4.0, Color32::TRANSPARENT, Stroke::new(1.5, Color32::WHITE)); + p.circle(sv, 5.5, Color32::TRANSPARENT, Stroke::new(1.0, Color32::from_black_alpha(160))); + let hy = strip.top() + hud.hsv[0] / 360.0 * strip.height(); + p.line_segment([egui::pos2(strip.left() + 1.0, hy), egui::pos2(strip.right(), hy)], Stroke::new(2.0, Color32::WHITE)); + (strip, square) + }) + .inner + }); + let (strip, square) = area.inner; + // Near a screen edge the clamped HUD can appear under the stationary pointer: picking starts + // only once the pointer has moved from where the gesture began, so the opening press alone + // never changes the colour. + if hud.just_opened && hover.is_some_and(|p| p != egui::pos2(hud.anchor[0], hud.anchor[1])) { + hud.just_opened = false; + } + if !hud.just_opened + && let Some(p) = hover + && let Some(new) = pick_at(hud.hsv, strip, square, p) + && new != hud.hsv + { + hud.hsv = new; + let [r, g, b] = hsb_to_rgb(new); + let fg = app.session.tools.foreground; + if (r - fg[0]).abs() > f32::EPSILON || (g - fg[1]).abs() > f32::EPSILON || (b - fg[2]).abs() > f32::EPSILON { + set_foreground(app, [r, g, b, hud.start[3]], hud.key); + } + } + app.ui.color_hud = Some(hud); + // The selection follows the pointer even when it rests between frames. + ctx.request_repaint(); +} + +/// One foreground-colour edit of the gesture: coalesced under `key`, so the whole pick is a single +/// history step (the colour is tool state, so it never touches the document). +fn set_foreground(app: &mut PhotocraftApp, rgba: [f32; 4], key: u64) { + let p = json!({ "foreground": rgba, "coalesce": format!("color-hud:{key}") }); + if let Err(e) = app.run("tools.setColors", p) { + app.ui.status = e; + } +} + +#[cfg(test)] +mod tests { + use egui::{Modifiers, PointerButton, Pos2, vec2}; + use egui_kittest::Harness; + use serde_json::json; + + use super::*; + use crate::state::Tool; + + const SHIFT_ALT: Modifiers = Modifiers { alt: true, ctrl: false, shift: true, mac_cmd: false, command: false }; + + fn harness() -> Harness<'static, PhotocraftApp> { + harness_size(400, 300) + } + + fn harness_size(width: u32, height: u32) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": width, "height": height})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#0000ff"})).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 button(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) { + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers }); + h.run_steps(2); + } + + /// The HUD's strip and square rects as drawn this frame. + fn rects(h: &Harness<'static, PhotocraftApp>) -> (Rect, Rect) { + let area = h.ctx.memory(|m| m.area_rect(hud_id())).expect("the HUD is shown"); + let style = h.ctx.global_style(); + let m = style.spacing.menu_margin; + let w = style.visuals.window_stroke().width; + let inner = + Rect::from_min_max(area.min + vec2(f32::from(m.left) + w, f32::from(m.top) + w), area.max - vec2(f32::from(m.right) + w, f32::from(m.bottom) + w)); + let strip = Rect::from_min_size(inner.min, vec2(HUE_W, SQUARE)); + (strip, Rect::from_min_max(inner.min + vec2(HUE_W + GAP, 0.0), inner.max)) + } + + fn foreground(h: &Harness<'static, PhotocraftApp>) -> [f32; 4] { + h.state().session.tools.foreground + } + + #[test] + fn shift_alt_right_press_opens_the_hud_not_the_picker() { + let mut h = harness(); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, SHIFT_ALT); + let hud = h.state().ui.color_hud.expect("the HUD opened"); + assert!(hud.hold); + assert_eq!(hud.start, [0.0, 0.0, 1.0, 1.0], "seeded from the foreground"); + assert_eq!(h.state().ui.brush_picker, None, "the Brush Preset picker stays closed"); + // The HUD shows under the pointer, on screen. + let (strip, square) = rects(&h); + assert!(strip.height() > 100.0 && square.width() > 100.0); + assert!(square.right() < h.ctx.content_rect().right()); + // Nothing painted. + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke")); + } + + /// Quick Selection's canvas right-click is the selection menu (#7268), so Shift+Alt+right + /// must not open the HUD from the same gesture (#6098). + #[test] + fn quick_selections_shift_alt_right_opens_only_the_selection_menu() { + let mut h = harness(); + h.state_mut().ui.tool = Tool::QuickSelection; + h.run_steps(1); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, SHIFT_ALT); + assert_eq!(h.state().ui.color_hud, None, "no HUD for Quick Selection"); + assert_eq!(h.state().ui.brush_picker, None, "and no Brush Preset picker"); + button(&mut h, c, false, SHIFT_ALT); + assert_eq!(h.state().ui.color_hud, None, "the release does not open it either"); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the selection menu opens, once"); + } + + /// A press near the bottom-right edge clamps the HUD under the still pointer: the opening + /// press alone must not pick — the colour changes only once the pointer moves (#6098). + #[test] + fn a_hud_clamped_under_the_still_pointer_picks_nothing_until_it_moves() { + let mut h = harness_size(1200, 800); + let near = egui::pos2(h.state().last_canvas_rect.max.x - 10.0, h.state().last_canvas_rect.max.y - 10.0); + h.event(egui::Event::PointerMoved(near)); + h.run_steps(1); + button(&mut h, near, true, SHIFT_ALT); + assert!(h.state().ui.color_hud.is_some_and(|hud| hud.just_opened), "the HUD opened under the pointer"); + let (_strip, square) = rects(&h); + assert!(square.contains(near), "the clamped HUD sits under the pointer: {near:?} in {square:?}"); + h.run_steps(4); + assert_eq!(foreground(&h), [0.0, 0.0, 1.0, 1.0], "the stationary opening pointer picks nothing"); + // Moving inside the HUD now picks, as during any other gesture. + let to = square.min + vec2(1.0, square.height() - 1.0); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(2); + assert_ne!(foreground(&h), [0.0, 0.0, 1.0, 1.0], "the move picks"); + button(&mut h, to, false, SHIFT_ALT); + } + + #[test] + fn dragging_over_the_hud_picks_the_foreground_live_and_release_keeps_it() { + let mut h = harness(); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, SHIFT_ALT); + let j0 = h.state().session.journal.len(); + let (_strip, square) = rects(&h); + // Top-right of the square: full saturation, full value at the current hue (blue). + let pick = egui::pos2(square.max.x - 1.0, square.min.y + 1.0); + h.event(egui::Event::PointerMoved(pick)); + h.run_steps(2); + let fg = foreground(&h); + assert!(fg[2] > 0.9 && fg[0] < 0.1 && fg[1] < 0.1, "still blue at the top of the square: {fg:?}"); + // Bottom-left: value 0 → black. + h.event(egui::Event::PointerMoved(square.min + vec2(1.0, square.height() - 1.0))); + h.run_steps(2); + let fg = foreground(&h); + assert!(fg[..3].iter().all(|v| *v < 0.02), "black at the bottom: {fg:?}"); + // The hue strip: its middle is cyan-ish (180°), at the square's current s/v. + let (strip, _) = rects(&h); + h.event(egui::Event::PointerMoved(egui::pos2(square.max.x - 1.0, square.min.y + 1.0))); + h.run_steps(2); + h.event(egui::Event::PointerMoved(strip.center())); + h.run_steps(2); + let fg = foreground(&h); + assert!(fg[2] > 0.5 && fg[0] < 0.5, "hue moved off red: {fg:?}"); + // The gesture's edits share one coalesce key (one history step, like the brush HUD). + let sets: Vec<&serde_json::Value> = h.state().session.journal[j0..].iter().filter(|(id, _)| id == "tools.setColors").map(|(_, p)| p).collect(); + assert!(!sets.is_empty(), "the picks are journaled"); + let keys: Vec<&str> = sets.iter().map(|p| p["coalesce"].as_str().unwrap()).collect(); + assert!(keys.windows(2).all(|w| w[0] == w[1]), "one gesture, one key: {keys:?}"); + // Releasing the right button closes the HUD and keeps the colour. + let kept = foreground(&h); + button(&mut h, strip.center(), false, SHIFT_ALT); + assert_eq!(h.state().ui.color_hud, None); + assert_eq!(foreground(&h), kept); + } + + #[test] + fn escape_restores_the_starting_colour() { + let mut h = harness(); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, SHIFT_ALT); + let (_strip, square) = rects(&h); + h.event(egui::Event::PointerMoved(square.center())); + h.run_steps(2); + assert_ne!(foreground(&h), [0.0, 0.0, 1.0, 1.0], "the pick is live"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.color_hud, None); + assert_eq!(foreground(&h), [0.0, 0.0, 1.0, 1.0], "Escape restores the colour"); + } + + #[test] + fn plain_right_click_still_opens_the_picker_and_alt_drag_still_resizes() { + let mut h = harness(); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, Modifiers::NONE); + button(&mut h, c, false, Modifiers::NONE); + assert!(h.state().ui.brush_picker.is_some() && h.state().ui.color_hud.is_none()); + // Alt+right-drag (no Shift) resizes the brush, as before. + h.state_mut().ui.brush_picker = None; + h.run_steps(1); + h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, Modifiers::ALT); + h.event(egui::Event::PointerMoved(c + vec2(40.0, 0.0))); + h.run_steps(2); + assert!(h.state().brush_resize.is_some_and(|r| r.secondary), "Alt+right still resizes"); + assert!(h.state().ui.color_hud.is_none()); + button(&mut h, c + vec2(40.0, 0.0), false, Modifiers::ALT); + } + + #[test] + fn shift_alt_right_drag_does_not_resize_the_brush() { + let mut h = harness(); + let size0 = h.state().session.tools.brush.size; + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, true, SHIFT_ALT); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(c + vec2(20.0 * k as f32, 0.0))); + h.run_steps(1); + } + assert!(h.state().brush_resize.is_none(), "the HUD gesture is not a resize"); + assert_eq!(h.state().session.tools.brush.size, size0); + button(&mut h, c + vec2(120.0, 0.0), false, SHIFT_ALT); + } + + #[test] + fn the_control_channel_opens_and_closes_the_hud() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + let (req, _rx) = crate::control::ControlRequest::new( + "ui.pointer", + json!({"button": "right", "shift": true, "alt": true, "events": [{"kind": "down", "x": 50, "y": 50}, {"kind": "up", "x": 50, "y": 50}]}), + ); + let _ = crate::control::handle(&mut app, &ctx, &req); + assert!(app.ui.color_hud.is_none(), "the Up event closed it"); + assert!(app.ui.brush_picker.is_none(), "the picker stayed closed"); + // A down without its up leaves the HUD open for the next frame's edits. + let (req, _rx) = crate::control::ControlRequest::new( + "ui.pointer", + json!({"button": "right", "shift": true, "alt": true, "events": [{"kind": "down", "x": 50, "y": 50}]}), + ); + let _ = crate::control::handle(&mut app, &ctx, &req); + assert!(app.ui.color_hud.is_some_and(|h| !h.hold)); + } + + #[test] + fn hue_strip_mesh_indices_stay_within_its_rows() { + let mesh = hue_strip_mesh(Rect::from_min_size(Pos2::ZERO, vec2(HUE_W, SQUARE))); + let rows = 13; // n + 1 rows, two vertices each + assert_eq!(mesh.vertices.len(), 2 * rows); + assert_eq!(mesh.indices.len(), 3 * 2 * (rows - 1), "two triangles per band"); + for (j, tri) in mesh.indices.chunks(3).enumerate() { + // Band k = j/2 joins rows k and k+1: vertices 2k..=2k+3, nothing further ahead. + let k = j / 2; + for &i in tri { + assert!((2 * k) as u32 <= i && i <= (2 * k + 3) as u32, "band {k} uses index {i}: {tri:?}"); + assert!((i as usize) < mesh.vertices.len(), "index {i} out of range"); + } + } + } + + #[test] + fn pick_at_maps_the_rects_and_ignores_the_gaps() { + let strip = Rect::from_min_size(Pos2::new(0.0, 0.0), vec2(HUE_W, SQUARE)); + let square = Rect::from_min_max(vec2(HUE_W + GAP, 0.0).to_pos2(), Pos2::new(HUE_W + GAP + SQUARE, SQUARE)); + assert_eq!(pick_at([120.0, 0.5, 0.5], strip, square, square.center()), Some([120.0, 0.5, 0.5])); + let p = pick_at([120.0, 0.5, 0.5], strip, square, square.left_top() + vec2(1.0, 1.0)).expect("in the square"); + assert!(p[0] == 120.0 && p[1] < 0.02 && p[2] > 0.98, "top-left is saturated and bright: {p:?}"); + assert_eq!(pick_at([0.0, 0.5, 0.5], strip, square, strip.center()), Some([180.0, 0.5, 0.5])); + assert_eq!(pick_at([0.0, 0.5, 0.5], strip, square, Pos2::new(HUE_W + GAP / 2.0, 10.0)), None, "the gap picks nothing"); + assert_eq!(pick_at([0.0, 0.5, 0.5], strip, square, Pos2::new(1e9, -1e9)), None); + } +} diff --git a/crates/ui-egui/src/panels/color_panel_ui.rs b/crates/ui-egui/src/panels/color_panel_ui.rs index 798e24dea1..22665b2150 100644 --- a/crates/ui-egui/src/panels/color_panel_ui.rs +++ b/crates/ui-egui/src/panels/color_panel_ui.rs @@ -768,3 +768,26 @@ pub(crate) fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.separator(); ramp_menu(app, ui); } + +/// Remember the Color panel's options in the preferences when they change, so they survive a +/// restart (#9592). Cheap: a small JSON compare per frame. +pub fn persist(app: &mut PhotocraftApp) { + let stored = app.session.prefs().color_panel.clone(); + // Changed outside the panel since the last sync (`prefs.set`, a reset): the panel takes it. + if app.ui.color_panel_synced.as_ref().is_some_and(|synced| *synced != stored) { + restore(app); + app.ui.color_panel_synced = Some(stored); + return; + } + let Ok(now) = serde_json::to_value(app.ui.color_panel) else { return }; + if stored != now { + app.session.prefs.edit(|p| p.color_panel = now.clone()); + } + app.ui.color_panel_synced = Some(now); +} + +/// Restore the remembered Color panel options (at launch, or after a preference change made +/// outside the panel); none stored (a reset) or unreadable ones are the defaults. +pub fn restore(app: &mut PhotocraftApp) { + app.ui.color_panel = serde_json::from_value(app.session.prefs().color_panel.clone()).unwrap_or_default(); +} diff --git a/crates/ui-egui/src/panels/color_tests.rs b/crates/ui-egui/src/panels/color_tests.rs index 8abdec859a..30ecfaf3e7 100644 --- a/crates/ui-egui/src/panels/color_tests.rs +++ b/crates/ui-egui/src/panels/color_tests.rs @@ -409,6 +409,36 @@ fn docked_color_field_keeps_rgb_readout_at_compact_height() { assert!(h.query_by_role(egui::accesskit::Role::TextInput).is_some(), "hex field stays visible"); } +/// #8968: the round cursor sits on the field's edge at the extremes and must not paint past it +/// (over the hue strip or the chips). +#[test] +fn color_field_cursor_stays_inside_the_field() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // Black is s = 0, v = 0: the bottom-left corner. + app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + let h = field_harness(app); + let mut field = None; + let mut circles = Vec::new(); + for clipped in &h.output().shapes { + match &clipped.shape { + // The saturation/brightness field is the 17 x 17 mesh; the hue strip is a 25 x 25 grid. + egui::Shape::Mesh(m) if m.vertices.len() == 17 * 17 => field = Some(m.calc_bounds()), + egui::Shape::Circle(c) => circles.push((c.center, c.radius, clipped.clip_rect)), + _ => {} + } + } + let field = field.expect("colour field drawn"); + let expected_center = pos2(field.left(), field.bottom()); + let rings: Vec<_> = + circles.into_iter().filter(|(center, radius, _)| center.distance(expected_center) < 0.01 && (*radius == 5.0 || *radius == 6.5)).collect(); + assert!(rings.iter().any(|(_, radius, _)| *radius == 5.0), "inner ring sits at the field's bottom-left corner"); + assert!(rings.iter().any(|(_, radius, _)| *radius == 6.5), "outer ring sits at the field's bottom-left corner"); + for (center, radius, clip) in rings { + let visible = egui::Rect::from_center_size(center, vec2(2.0 * radius, 2.0 * radius)).intersect(clip); + assert!(field.contains_rect(visible), "cursor ring {visible:?} leaves the field {field:?}"); + } +} + fn field_harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> { // 60 fps steps, so two clicks a frame apart are a double-click. let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 200.0)).with_step_dt(1.0 / 60.0).build_ui_state( diff --git a/crates/ui-egui/src/panels/dock.rs b/crates/ui-egui/src/panels/dock.rs index 4bc72ab57b..5784e0042d 100644 --- a/crates/ui-egui/src/panels/dock.rs +++ b/crates/ui-egui/src/panels/dock.rs @@ -16,6 +16,7 @@ pub fn dock_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui)); crate::dock::persist(app, ui.ctx()); + crate::color_panel_ui::persist(app); } /// The docking layout's protected canvas panel: the document area, with the icon rail on its end diff --git a/crates/ui-egui/src/panels/layer_pct_slider_tests.rs b/crates/ui-egui/src/panels/layer_pct_slider_tests.rs index 1d22cd255f..e8d73d94a2 100644 --- a/crates/ui-egui/src/panels/layer_pct_slider_tests.rs +++ b/crates/ui-egui/src/panels/layer_pct_slider_tests.rs @@ -178,3 +178,23 @@ fn opacity_and_fill_stay_visible_but_disabled_with_no_layer_selected() { assert!(node.accesskit_node().is_disabled(), "{name}: should be greyed out"); } } + +/// #9546: the layer list starts at the same place with or without a selected layer. With none, +/// the greyed-out Blend/Opacity and Lock/Fill rows sat in one disabled wrapper, which added an +/// item gap under them: in the themes whose docks keep item spacing (Studio, Classic) the first +/// row moved down 6 points. +#[test] +fn layer_rows_do_not_move_when_no_layer_is_selected() { + for theme in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Classic, crate::theme::ThemeKind::ProMedium] { + let mut h = harness(); + PhotocraftApp::setup_context(&h.ctx, theme); + h.run_steps(4); + let row_top = |h: &Harness<'_, PhotocraftApp>| by_role(h, "Paint", Role::Button).map(|r| r.top()); + let selected = row_top(&h); + h.state_mut().session.execute("select.deselectLayers", json!({})).unwrap(); + h.run_steps(4); + let none = row_top(&h); + assert!(selected.is_some(), "{theme:?}: the layer row"); + assert_eq!(none, selected, "{theme:?}: the row moved with no layer selected"); + } +} diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index 6bc0ac85b2..f510ccafdd 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -405,19 +405,20 @@ fn select_row_on_click(app: &mut PhotocraftApp, ui: &egui::Ui, rc: &RowCtx<'_>, let mask = if v.filter { "filter" } else { "layer" }; actions.push((photocraft_engine::mask_view_cmds::ID.into(), json!({"layer": l.id.0, "mode": "off", "mask": mask}))); } - let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_)); + let adjustment = matches!(l.content, LayerContent::Adjustment(_)); + let fill_mask = matches!(l.content, LayerContent::Fill(_)) && l.mask.is_some(); if on_vector { // The vector mask thumbnail targets the vector mask: the path tools edit it and the // Paths panel selects the layer's path. app.ui.selected_path = Some("layer".into()); actions.push(("ui.vectorMaskTarget".into(), json!(true))); - } else if on_mask || (content_less && l.mask.is_some() && !on_thumb) { + } else if on_mask || (fill_mask && !on_thumb) { if on_mask { // The mask thumbnail also switches Properties to the mask (#3369). app.ui.properties_layer = None; } actions.push(("ui.maskTarget".into(), json!(true))); - } else if on_thumb || !row.primary { + } else if on_thumb || adjustment || !row.primary { actions.push(("ui.maskTarget".into(), json!(false))); } // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index fe0f8c9577..d83c1cbbb4 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -49,56 +49,59 @@ pub(super) fn opacity_row_layout(available: f32, label_width: f32, gap: f32) -> /// greyed out at Normal, 100% and unlocked, instead of removing them (#8880). Same layout as the /// active layer's rows in `layers`. fn inactive_blend_rows(ui: &mut egui::Ui, pro: bool) { - ui.add_enabled_ui(false, |ui| { - ui.horizontal(|ui| { - let opacity_label = if pro { tl!("Opacity:") } else { tl!("Opacity") }; - let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); - let mut m = BlendMode::Normal; - let options = blend_options(false, m); - widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut o = 100.0; - widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); - if show_opacity_label { - scrub_pct_label(ui, opacity_label, &mut o, ui.available_width()); + // Each row is disabled on its own and laid out as the active layer's rows are: a disabled + // wrapper around both added an item gap under the Fill row, which pushed the layer list down + // in the themes whose docks keep item spacing (#9546). + ui.horizontal(|ui| { + ui.disable(); + let opacity_label = if pro { tl!("Opacity:") } else { tl!("Opacity") }; + let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); + let mut m = BlendMode::Normal; + let options = blend_options(false, m); + widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut o = 100.0; + widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); + if show_opacity_label { + scrub_pct_label(ui, opacity_label, &mut o, ui.available_width()); + } + }); + }); + ui.add_space((theme::ROW_GAP - ui.spacing().item_spacing.y).max(0.0)); + ui.horizontal(|ui| { + ui.disable(); + let lock_label = if pro { tl!("Lock:") } else { tl!("Lock") }; + let lang = crate::i18n::current(); + let fill_label = if pro { crate::i18n::tr_ctx(lang, "layers", "Fill:") } else { crate::i18n::tr_ctx(lang, "layers", "Fill") }; + let gap = ui.spacing().item_spacing.x; + let icons_w = if pro { 5.0 * 20.0 + gap } else { 22.0 + gap }; + let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width(); + if fits { + label(ui, lock_label); + } + if pro { + ui.scope(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + for (icon, tip) in [ + ("grid-3x3", tl!("Lock transparent pixels")), + ("brush", tl!("Lock image pixels")), + ("move", tl!("Lock position")), + ("scan", tl!("Prevent auto-nesting in and out of Artboards and Frames")), + ("lock", tl!("Lock all")), + ] { + icons::button(ui, icon, 20.0, false, tip); } }); + } else { + icons::button(ui, "lock-open", 22.0, false, tl!("Lock layer")); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut f = 100.0; + widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W); + scrub_pct_label(ui, fill_label, &mut f, ui.available_width()); }); - ui.add_space((theme::ROW_GAP - ui.spacing().item_spacing.y).max(0.0)); - ui.horizontal(|ui| { - let lock_label = if pro { tl!("Lock:") } else { tl!("Lock") }; - let lang = crate::i18n::current(); - let fill_label = if pro { crate::i18n::tr_ctx(lang, "layers", "Fill:") } else { crate::i18n::tr_ctx(lang, "layers", "Fill") }; - let gap = ui.spacing().item_spacing.x; - let icons_w = if pro { 5.0 * 20.0 + gap } else { 22.0 + gap }; - let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width(); - if fits { - label(ui, lock_label); - } - if pro { - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - for (icon, tip) in [ - ("grid-3x3", tl!("Lock transparent pixels")), - ("brush", tl!("Lock image pixels")), - ("move", tl!("Lock position")), - ("scan", tl!("Prevent auto-nesting in and out of Artboards and Frames")), - ("lock", tl!("Lock all")), - ] { - icons::button(ui, icon, 20.0, false, tip); - } - }); - } else { - icons::button(ui, "lock-open", 22.0, false, tl!("Lock layer")); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut f = 100.0; - widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W); - scrub_pct_label(ui, fill_label, &mut f, ui.available_width()); - }); - }); - ui.add_space(2.0); }); + ui.add_space(2.0); } pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -573,7 +576,7 @@ fn footer_menu_button(ui: &mut egui::Ui, icon: &str, size: f32, tip: &str) -> eg } /// Photoshop's italic "fx" footer button (no icon-font equivalent). -fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response { +pub(crate) fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response { let t = Tokens::get(ui.ctx()); let (r, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click()); if resp.hovered() { 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 f5ea5f9fc1..f0ab8faad5 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs @@ -611,7 +611,9 @@ fn clicking_the_vector_mask_targets_it_for_the_path_tools() { let k = layer(&h, masked).vector_mask.unwrap().path.subpaths[0].knots[0].anchor; assert_eq!((k.x, k.y), (25.0, 12.0)); // The Pen adds a subpath to it. - h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[150.0, 10.0]; 3], [[190.0, 10.0]; 3], [[190.0, 40.0]; 3]], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = + Some(crate::vector_ui::PenPath { knots: vec![[[150.0, 10.0]; 3], [[190.0, 10.0]; 3], [[190.0, 40.0]; 3]], owner, ..Default::default() }); crate::vector_ui::pen_commit(h.state_mut(), true); assert_eq!(layer(&h, masked).vector_mask.unwrap().path.subpaths.len(), 2); assert!(h.state().session.active().unwrap().doc.work_path.is_none(), "not a work path"); @@ -804,7 +806,8 @@ fn a_new_adjustment_or_fill_layer_shows_its_settings_until_the_mask_thumbnail_is // Clicking the row (not a thumbnail) keeps the settings. let row = h.get_by_label(&layer(&h, id).name).rect().center(); click_with(&mut h, row, Modifiers::NONE); - assert!(h.state().ui.mask_target); + assert_eq!(h.state().ui.mask_target, command.starts_with("layer.newFillLayer.")); + assert!(!h.state().ui.vector_mask_target); assert!(h.query_all_by_label("Density").next().is_none(), "{command}: a row click keeps the settings"); // The mask thumbnail switches Properties to the mask. let r = mask_rect(&h, id, MaskKind::Pixel); @@ -836,3 +839,41 @@ fn a_new_adjustment_layer_brings_properties_to_the_front() { assert!(!h.state().ui.dock.is_collapsed(crate::dock::Group::Properties), "the group is expanded"); assert!(h.query_all_by_label("Reset to defaults").next().is_some(), "the Curves settings show"); } + +#[test] +fn adjustment_names_target_contents_instead_of_masks() { + for command in ["layer.newAdjustmentLayer.hueSaturation", "layer.newAdjustmentLayer.curves"] { + for ppp in [1.0, 2.0] { + let (mut s, _, other) = session(); + s.execute(command, json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + let path = json!({"subpaths": [{"knots": [[20, 10], [120, 10], [120, 90], [20, 90]]}]}); + s.execute("layer.vectorMask.add", json!({"layer": id, "path": path})).unwrap(); + let mut h = harness(s, 0, ppp, 360.0); + for kind in [MaskKind::Pixel, MaskKind::Vector] { + let at = mask_rect(&h, id, kind).center(); + click_with(&mut h, at, Modifiers::NONE); + assert_eq!(h.state().ui.mask_target, kind == MaskKind::Pixel); + assert_eq!(h.state().ui.vector_mask_target, kind == MaskKind::Vector); + let name = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id).unwrap().name.unwrap().center(); + click_with(&mut h, name, Modifiers::NONE); + assert!(!h.state().ui.mask_target && !h.state().ui.vector_mask_target, "{command} @{ppp}x after {kind:?}"); + let thumb = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id).unwrap().thumbnail.unwrap(); + assert!(near(super::brackets(&h.ctx).unwrap(), thumb.expand(3.0)), "the content thumbnail is selected"); + assert_eq!(h.state().session.active().unwrap().active_layer.unwrap().0, id); + } + let name = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == other).unwrap().name.unwrap().center(); + click_with(&mut h, name, Modifiers::NONE); + let name = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id).unwrap().name.unwrap().center(); + click_with(&mut h, name, Modifiers::NONE); + assert_eq!(h.state().session.active().unwrap().active_layer.unwrap().0, id); + assert!(!h.state().ui.mask_target && !h.state().ui.vector_mask_target, "{command} @{ppp}x from another layer"); + assert_eq!(crate::canvas::paint_target(h.state()), json!("mask")); + let content = layer(&h, id).content; + h.state_mut().run("edit.fill", json!({"contents": "black"})).unwrap(); + assert_eq!(layer(&h, id).content, content, "filling must preserve the adjustment or fill content"); + assert_eq!(layer(&h, id).mask.unwrap().surface.sample_channel(50, 50, 0), 0.0, "Fill edits the mask"); + assert!(!h.state().ui.mask_target && !h.state().ui.vector_mask_target, "painting leaves the content thumbnail selected"); + } + } +} diff --git a/crates/ui-egui/src/panels/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs index fcd33e89cb..2387b2ea9d 100644 --- a/crates/ui-egui/src/panels/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -383,6 +383,7 @@ fn draw_group_header(ui: &mut egui::Ui, group: &GroupView, context: GroupHeaderC if response.hovered() || response.dragged() { ui.painter().rect_filled(rect, 2.0, tokens.hover.gamma_multiply(0.5)); } + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), open, &group.name)); let triangle = Rect::from_center_size(pos2(rect.left() + 9.0, rect.center().y), vec2(12.0, 12.0)); crate::icons::paint(ui, triangle, if open { "chevron-down" } else { "chevron-right" }, 10.0, tokens.text_dim); let folder = Rect::from_center_size(pos2(rect.left() + 25.0, rect.center().y), vec2(14.0, 14.0)); diff --git a/crates/ui-egui/src/panels/preset_panels/panels.rs b/crates/ui-egui/src/panels/preset_panels/panels.rs index 7aa89c5ccc..4b0e05fbd6 100644 --- a/crates/ui-egui/src/panels/preset_panels/panels.rs +++ b/crates/ui-egui/src/panels/preset_panels/panels.rs @@ -47,7 +47,11 @@ pub fn gradients_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // ------------------------------------------------------------------ Patterns pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - photocraft_engine::presets::patterns::sync(&mut app.session); + // Until the preset store has loaded the saved patterns, their folder entries would look + // deleted: don't prune them yet. + if app.services.preset_store.is_none() { + photocraft_engine::presets::patterns::sync(&mut app.session); + } let lib = app.session.patterns.items.clone(); let groups: Vec = app .session diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index c6c7a3567d..6ad68bda02 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -326,7 +326,14 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { { let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); } - let sm = icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips); + // Greyed out while Cycle is unavailable (no document in Standard, #9349): its + // list would offer nothing else either. + let cycle_enabled = crate::view_cmds::is_enabled(app, "view.screenMode.cycle").unwrap_or(true); + let sm = ui + .add_enabled_ui(cycle_enabled, |ui| { + icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips) + }) + .inner; paint_toolbar_flyout_indicator(ui, &t, &sm); // Right-click, or click and hold like the tool flyouts (#4444), lists the modes, @@ -366,7 +373,8 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ("view.screenMode.fullScreen", tl!("Full Screen Mode")), ] { let on = crate::view_cmds::checked(app, id).unwrap_or(false); - if ui.add(egui::Button::selectable(on, label)).clicked() { + let enabled = crate::view_cmds::is_enabled(app, id).unwrap_or(true); + if ui.add_enabled(enabled, egui::Button::selectable(on, label)).clicked() { let _ = crate::menus::invoke(app, &ctx, id, json!({})); ui.close(); } diff --git a/crates/ui-egui/src/panels/type_flyout_tests.rs b/crates/ui-egui/src/panels/type_flyout_tests.rs index 27659cf8b5..7678f4263e 100644 --- a/crates/ui-egui/src/panels/type_flyout_tests.rs +++ b/crates/ui-egui/src/panels/type_flyout_tests.rs @@ -46,11 +46,54 @@ fn long_press_type_button_selects_type_then_vertical_from_the_flyout() { assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_none()); } +/// #9354 review: with no document in Standard Screen Mode, Cycle is unavailable (#9349), so +/// Change Screen Mode is greyed out: a click sends no viewport command. +#[test] +fn screen_mode_button_is_inert_without_a_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"width": 64, "height": 48})).unwrap(); + 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 }; + // Found while a document makes it clickable: the toolbar's last button. + let at = 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) + .max_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left()))) + }) + .unwrap() + .center(); + app.run("file.close", serde_json::json!({"save": false})).unwrap(); + frame(&mut app, &ctx, 1.0, vec![]); + assert_eq!(crate::view_cmds::is_enabled(&app, "view.screenMode.cycle"), Some(false)); + let pointer = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let mut sent = Vec::new(); + for (t, events) in [(2.0, vec![egui::Event::PointerMoved(at), pointer(true)]), (2.1, vec![pointer(false)]), (2.15, vec![])] { + let mut out = ctx.run_ui( + egui::RawInput { time: Some(t), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() }, + |ui| toolbar(&mut app, ui), + ); + out.textures_delta.clear(); + sent.extend(out.viewport_output.values().flat_map(|v| v.commands.clone())); + } + assert!(!sent.iter().any(|c| matches!(c, egui::ViewportCommand::Fullscreen(_))), "no screen mode change was sent: {sent:?}"); + assert_eq!(app.ui.view.screen_mode, "standard"); +} + /// #4444: click and hold on Change Screen Mode opens its list like the tool flyouts, without /// cycling the mode on release; a plain click still cycles, and right-click still opens it. #[test] fn long_press_screen_mode_opens_the_modes_without_cycling() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // A document open: Full Screen Mode needs one (#9349), so without it a click can't cycle. + app.run("file.new", serde_json::json!({"width": 64, "height": 48})).unwrap(); let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); frame(&mut app, &ctx, 0.0, vec![]); diff --git a/crates/ui-egui/src/pen_gesture_owner_tests.rs b/crates/ui-egui/src/pen_gesture_owner_tests.rs new file mode 100644 index 0000000000..6f6a093d19 --- /dev/null +++ b/crates/ui-egui/src/pen_gesture_owner_tests.rs @@ -0,0 +1,92 @@ +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app.ui.extras.snap = false; + app +} + +fn down(app: &mut PhotocraftApp) { + tool_event(app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 50.0, y: 35.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 90.0, y: 80.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.drag.is_some()); +} + +#[test] +fn freeform_and_path_selection_releases_cannot_edit_a_different_document() { + for tool in [Tool::FreeformPen, Tool::PathSelection] { + let mut app = app(tool); + app.run("path.set", json!({"path": {"subpaths": [{"knots": [[20, 20], [50, 35], [90, 80]]}]}})).unwrap(); + let original = app.session.active().unwrap().doc.work_path.clone(); + down(&mut app); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + let revision = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 100.0 }, Modifiers::NONE); + assert!(app.drag.is_none()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.documents()[0].doc.work_path, original); + } +} + +#[test] +fn freeform_release_cancels_after_revision_or_target_change() { + for change in ["revision", "selected", "mode"] { + let mut app = app(Tool::FreeformPen); + down(&mut app); + match change { + "revision" => { + app.run("path.set", json!({"path": {"subpaths": [{"knots": [[10, 10], [15, 15]]}]}})).unwrap(); + } + "selected" => app.ui.selected_path = Some("Another path".into()), + _ => app.ui.tool_options.vector_mode = "shape".into(), + } + let before = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 100.0 }, Modifiers::NONE); + assert!(app.drag.is_none()); + assert_eq!(app.session.active().unwrap().doc.work_path, before.work_path); + assert_eq!(app.session.active().unwrap().doc.layers, before.layers); + assert_eq!(app.session.active().unwrap().revision, revision); + } +} + +#[test] +fn freeform_valid_release_is_one_undoable_path_edit() { + let mut app = app(Tool::FreeformPen); + let history = app.session.active().unwrap().history.entries().len(); + down(&mut app); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 100.0 }, Modifiers::NONE); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + assert_eq!(app.session.active().unwrap().history.entries().len(), history + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + app.run("edit.redo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); +} + +#[test] +fn frame_cancellation_consumes_old_events_after_switching_tools() { + let mut app = app(Tool::FreeformPen); + down(&mut app); + app.ui.tool = Tool::PolygonLasso; + app.ui.polygon = vec![[10.0, 10.0], [20.0, 20.0]]; + let polygon = app.ui.polygon.clone(); + app.sync_views(); + assert!(app.drag.is_none()); + let modifiers = Modifiers { alt: true, ..Modifiers::NONE }; + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 100.0, pressure: 1.0 }, modifiers); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 100.0 }, modifiers); + assert_eq!(app.ui.polygon, polygon, "old pointer events must not become a Polygonal Lasso gesture"); + assert!(!app.cancelled_vector_drag); +} diff --git a/crates/ui-egui/src/pen_path_ownership_tests.rs b/crates/ui-egui/src/pen_path_ownership_tests.rs new file mode 100644 index 0000000000..ea2363a67b --- /dev/null +++ b/crates/ui-egui/src/pen_path_ownership_tests.rs @@ -0,0 +1,478 @@ +//! Pen drafts and explicit document paths retain their destination until a single commit. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, Path}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::vector_ui; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = tool; + app +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn seed(app: &mut PhotocraftApp, name: &str, y: f64) { + app.run("path.set", json!({"name": name, "path": {"subpaths": [{"closed": false, "knots": [[10.0, y], [90.0, y]]}]}})).unwrap(); +} + +fn path(app: &PhotocraftApp, name: &str) -> Path { + let doc = &app.session.active().unwrap().doc; + if name == "work" { doc.work_path.clone().unwrap() } else { doc.paths.iter().find(|p| p.name == name).unwrap().path.clone() } +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64) { + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x, y }, Modifiers::NONE); +} + +fn draft(app: &mut PhotocraftApp) { + click(app, 30.0, 60.0); + click(app, 130.0, 60.0); +} + +#[test] +fn selected_work_and_saved_paths_append_pen_and_curvature_components_once() { + for tool in [Tool::Pen, Tool::CurvaturePen] { + for name in ["work", "Saved drawing"] { + let mut app = app(tool); + seed(&mut app, "work", 20.0); + seed(&mut app, "Saved drawing", 40.0); + app.ui.selected_path = Some(name.into()); + let (original, other) = (path(&app, name), path(&app, if name == "work" { "Saved drawing" } else { "work" })); + let n = steps(&app); + draft(&mut app); + assert_eq!(steps(&app), n, "placing anchors is not a history step"); + vector_ui::pen_commit(&mut app, false); + let after = path(&app, name); + assert_eq!(after.subpaths.len(), 2, "{tool:?}: {name}"); + assert_eq!(after.subpaths[0], original.subpaths[0]); + let anchors: Vec<_> = after.subpaths[1].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + assert_eq!(anchors, [[30.0, 60.0], [130.0, 60.0]]); + assert_eq!(path(&app, if name == "work" { "Saved drawing" } else { "work" }), other); + assert_eq!(app.ui.selected_path.as_deref(), Some(name)); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(path(&app, name), original); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(path(&app, name), after); + } + } +} + +#[test] +fn deselected_work_path_is_replaced_without_touching_saved_paths() { + let mut app = app(Tool::Pen); + seed(&mut app, "work", 20.0); + seed(&mut app, "Saved drawing", 40.0); + app.ui.selected_path = None; + let (before, saved, n) = (path(&app, "work"), path(&app, "Saved drawing"), steps(&app)); + draft(&mut app); + vector_ui::pen_commit(&mut app, false); + let after = path(&app, "work"); + assert_eq!(after.subpaths.len(), 1); + assert_eq!(after.subpaths[0].knots[0].anchor.y, 60.0); + assert_eq!(path(&app, "Saved drawing"), saved); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(path(&app, "work"), before); +} + +#[test] +fn captured_path_and_shape_mode_do_not_follow_later_ui_selection() { + for shape in [false, true] { + let mut app = app(Tool::Pen); + seed(&mut app, "work", 20.0); + seed(&mut app, "Saved drawing", 40.0); + app.ui.selected_path = Some("Saved drawing".into()); + app.ui.tool_options.vector_mode = if shape { "shape" } else { "path" }.into(); + let (work, saved, n) = (path(&app, "work"), path(&app, "Saved drawing"), steps(&app)); + click(&mut app, 30.0, 60.0); + app.ui.selected_path = Some("work".into()); + app.ui.tool_options.vector_mode = if shape { "path" } else { "shape" }.into(); + app.ui.vector_mask_target = true; + click(&mut app, 130.0, 60.0); + vector_ui::pen_commit(&mut app, false); + assert_eq!(path(&app, "work"), work); + if shape { + let st = app.session.active().unwrap(); + assert!(matches!(st.doc.layer(st.active_layer.unwrap()).unwrap().content, LayerContent::Shape(_))); + assert_eq!(path(&app, "Saved drawing"), saved); + assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); + } else { + assert_eq!(path(&app, "Saved drawing").subpaths.len(), 2); + assert_eq!(app.ui.selected_path.as_deref(), Some("Saved drawing")); + } + assert_eq!(steps(&app), n + 1); + } +} + +#[test] +fn captured_pen_paint_preserves_float_colour_and_alpha_after_toolbar_changes() { + for closed in [false, true] { + let mut app = app(Tool::Pen); + app.ui.tool_options.vector_mode = "shape".into(); + app.ui.tool_options.shape_fill = true; + app.ui.tool_options.stroke_width = 3.0; + let foreground = [0.12345, 0.34567, 0.56789, 0.375]; + let background = [0.76543, 0.54321, 0.32109, 0.625]; + app.session.tools.foreground = foreground; + app.session.tools.background = background; + click(&mut app, 30.0, 60.0); + app.session.tools.foreground = [1.0; 4]; + app.session.tools.background = [0.0; 4]; + click(&mut app, 130.0, 60.0); + if closed { + click(&mut app, 90.0, 130.0); + } + vector_ui::pen_commit(&mut app, closed); + let st = app.session.active().unwrap(); + let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("expected Pen shape") }; + let paint = |c: [f32; 4]| photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(c[0], c[1], c[2], c[3])); + assert_eq!(shape.fill, closed.then(|| paint(foreground))); + assert_eq!(shape.stroke.as_ref().unwrap().paint, paint(if closed { background } else { foreground })); + } +} + +#[test] +fn stale_drafts_are_cancelled_before_tool_switch_or_pointer_input() { + for tool in [Tool::Pen, Tool::CurvaturePen] { + for change in ["document", "revision", "reopen"] { + let mut app = app(tool); + seed(&mut app, "Saved drawing", 20.0); + app.ui.selected_path = Some("Saved drawing".into()); + draft(&mut app); + let source = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + match change { + "document" => { + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("path.set", json!({"name":"Saved drawing", "path": {"subpaths": [{"knots": [[50, 50], [80, 80]]}]}})).unwrap(); + } + "revision" => { + app.session.execute("path.set", json!({"name":"work", "path": {"subpaths": [{"knots": [[50, 50], [80, 80]]}]}})).unwrap(); + } + "reopen" => { + app.session.close(0).unwrap(); + app.session.add_document((*source).clone(), None); + app.session.active_mut().unwrap().revision = revision; + } + _ => panic!("unknown document-change fixture: {change}"), + } + let (current, n) = (app.session.active().unwrap().doc.clone(), steps(&app)); + app.ui.tool = Tool::Brush; + vector_ui::finish_pen_if_left(&mut app); + assert!(app.ui.pen.is_none(), "{tool:?}: {change}"); + vector_ui::pen_move(&mut app, 160.0, 80.0, false); + vector_ui::curvature_move(&mut app, 160.0, 80.0); + vector_ui::pen_up(&mut app); + vector_ui::curvature_up(&mut app); + vector_ui::pen_commit(&mut app, false); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, ¤t)); + assert_eq!(steps(&app), n); + assert_eq!(source.paths[0].path.subpaths.len(), 1); + } + } +} + +#[test] +fn sync_views_and_input_apis_discard_unowned_or_closed_document_drafts() { + for entry in ["sync", "move", "up", "commit", "undo", "toggle", "down"] { + let mut app = app(Tool::CurvaturePen); + draft(&mut app); + app.session.close(0).unwrap(); + match entry { + "sync" => app.sync_views(), + "move" => vector_ui::curvature_move(&mut app, 160.0, 80.0), + "up" => vector_ui::curvature_up(&mut app), + "commit" => { + vector_ui::pen_commit(&mut app, false); + } + "undo" => { + assert!(!vector_ui::pen_undo_last_point(&mut app), "a closed document has no current draft point to undo"); + } + "toggle" => vector_ui::curvature_toggle(&mut app, 30.0, 60.0), + "down" => vector_ui::curvature_down(&mut app, 160.0, 80.0), + _ => panic!("unknown stale-draft entry fixture: {entry}"), + } + assert!(app.ui.pen.is_none(), "{entry}"); + } + let mut app = app(Tool::Pen); + draft(&mut app); + let restored = serde_json::from_value(serde_json::to_value(app.ui.pen.as_ref().unwrap()).unwrap()).unwrap(); + app.ui.pen = Some(restored); + let n = steps(&app); + vector_ui::pen_commit(&mut app, false); + assert!(app.ui.pen.is_none()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert_eq!(steps(&app), n); +} + +#[test] +fn same_named_saved_paths_do_not_share_selection_or_drafts_across_tabs() { + let mut app = app(Tool::Pen); + seed(&mut app, "Saved drawing", 20.0); + let first = path(&app, "Saved drawing"); + app.run("file.new", json!({"width":200,"height":200})).unwrap(); + seed(&mut app, "Saved drawing", 90.0); + let second = path(&app, "Saved drawing"); + assert!(app.session.set_active(0)); + app.sync_views(); + app.ui.selected_path = Some("Saved drawing".into()); + draft(&mut app); + assert!(app.session.set_active(1)); + app.sync_views(); + assert!(app.ui.selected_path.is_none()); + assert!(app.ui.pen.is_none()); + let n = steps(&app); + vector_ui::pen_commit(&mut app, false); + assert_eq!(path(&app, "Saved drawing"), second); + assert_eq!(steps(&app), n); + // A fresh drawing without explicitly selecting B's saved path creates a work path. + draft(&mut app); + vector_ui::pen_commit(&mut app, false); + assert_eq!(path(&app, "Saved drawing"), second); + assert_eq!(path(&app, "work").subpaths[0].knots[0].anchor.y, 60.0); + assert!(app.session.set_active(0)); + app.sync_views(); + assert!(app.ui.selected_path.is_none()); + // The captured-target reconciliation preserves main's valid-source commit on a tab + // switch. Only the original path receives that draft; the same-named B path stayed exact. + let committed = path(&app, "Saved drawing"); + assert_eq!(committed.subpaths.len(), first.subpaths.len() + 1); + assert_eq!(committed.subpaths[0], first.subpaths[0]); + assert_eq!(committed.subpaths.last().unwrap().knots[0].anchor.y, 60.0); +} + +#[test] +fn reopened_same_id_and_revision_do_not_reuse_the_saved_path_selection() { + let mut app = app(Tool::Pen); + seed(&mut app, "Saved drawing", 20.0); + app.ui.selected_path = Some("Saved drawing".into()); + let original = path(&app, "Saved drawing"); + draft(&mut app); + let closed = app.session.close(0).unwrap(); + // Recovery can preserve both the document ID and revision before another frame is drawn. + app.session.add_document((*closed.doc).clone(), None); + app.session.active_mut().unwrap().revision = closed.revision; + assert_eq!(app.session.active().unwrap().doc.id, closed.doc.id); + app.sync_views(); + assert!(app.ui.selected_path.is_none()); + assert!(app.ui.pen.is_none()); + draft(&mut app); + vector_ui::pen_commit(&mut app, false); + assert_eq!(path(&app, "Saved drawing"), original); + assert_eq!(path(&app, "work").subpaths[0].knots[0].anchor.y, 60.0); +} + +#[test] +fn ordinary_path_edits_undo_and_redo_preserve_the_explicit_saved_path_selection() { + let mut app = app(Tool::Pen); + seed(&mut app, "Saved drawing", 20.0); + app.ui.selected_path = Some("Saved drawing".into()); + let original = path(&app, "Saved drawing"); + let revision = app.session.active().unwrap().revision; + seed(&mut app, "Saved drawing", 90.0); + assert!(app.session.active().unwrap().revision > revision); + assert_eq!(app.ui.selected_path.as_deref(), Some("Saved drawing")); + let changed = path(&app, "Saved drawing"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(path(&app, "Saved drawing"), original); + assert_eq!(app.ui.selected_path.as_deref(), Some("Saved drawing")); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(path(&app, "Saved drawing"), changed); + assert_eq!(app.ui.selected_path.as_deref(), Some("Saved drawing")); + app.sync_views(); + assert_eq!(app.ui.selected_path.as_deref(), Some("Saved drawing")); +} + +#[test] +fn failed_pen_and_curvature_commits_keep_the_exact_draft_and_do_not_retry_each_frame() { + for tool in [Tool::Pen, Tool::CurvaturePen] { + let mut app = app(tool); + click(&mut app, 30.0, 60.0); + click(&mut app, 1e40, 60.0); + let (before, original, n) = (app.session.active().unwrap().doc.clone(), app.ui.pen.clone().unwrap(), steps(&app)); + vector_ui::pen_commit(&mut app, false); + let failed = app.ui.pen.as_ref().expect("invalid geometry leaves an editable draft"); + assert_eq!(failed.knots, original.knots); + assert_eq!(failed.unlinked, original.unlinked); + assert_eq!(failed.owner, original.owner); + assert!(failed.commit_failed && app.ui.status_error); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(steps(&app), n); + app.ui.tool = Tool::Brush; + let journal = app.session.journal.len(); + vector_ui::finish_pen_if_left(&mut app); + assert_eq!(app.session.journal.len(), journal, "tool switch must not continually retry a failing commit"); + assert!(vector_ui::path_to_selection(&mut app, Value::Null).is_err(), "a failed draft cannot select an unrelated path"); + app.ui.pen.as_mut().unwrap().knots[1] = [[130.0, 60.0]; 3]; + vector_ui::pen_commit(&mut app, false); + assert!(app.ui.pen.is_none()); + assert_eq!(path(&app, "work").subpaths[0].knots[1].anchor.x, 130.0); + assert_eq!(steps(&app), n + 1); + } +} + +#[test] +fn ordinary_tool_switch_commits_the_owned_draft_once() { + for tool in [Tool::Pen, Tool::CurvaturePen] { + let mut app = app(tool); + draft(&mut app); + let n = steps(&app); + app.ui.tool = Tool::Brush; + vector_ui::finish_pen_if_left(&mut app); + vector_ui::finish_pen_if_left(&mut app); + assert_eq!(path(&app, "work").subpaths[0].knots.len(), 2); + assert_eq!(steps(&app), n + 1); + assert!(app.ui.pen.is_none()); + } +} + +#[test] +fn selected_saved_paths_move_and_free_transform_without_changing_work_or_shape() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut app = app(tool); + app.run("shape.create", json!({"kind": "rect", "rect": [110, 110, 50, 40]})).unwrap(); + let shape = app.run("shape.info", json!({})).unwrap(); + seed(&mut app, "work", 20.0); + seed(&mut app, "Saved drawing", 40.0); + app.ui.selected_path = Some("Saved drawing".into()); + let (original, work, n) = (path(&app, "Saved drawing"), path(&app, "work"), steps(&app)); + let (params, selected) = vector_ui::free_transform_path(&app).unwrap(); + assert_eq!(params, json!({"name":"Saved drawing"})); + assert_eq!(selected, original); + vector_ui::path_selection_finish(&mut app, [0.0, 0.0], [10.4, -4.6]); + let moved = path(&app, "Saved drawing"); + for (a, b) in original.subpaths[0].knots.iter().zip(&moved.subpaths[0].knots) { + assert_eq!(b.anchor.x, a.anchor.x + 10.0); + assert_eq!(b.anchor.y, a.anchor.y - 5.0); + assert_eq!(b.in_ctrl.x, a.in_ctrl.x + 10.0); + assert_eq!(b.out_ctrl.y, a.out_ctrl.y - 5.0); + } + assert_eq!(path(&app, "work"), work); + assert_eq!(app.run("shape.info", json!({})).unwrap(), shape); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(path(&app, "Saved drawing"), original); + let mut params = params; + params["matrix"] = json!([1, 0, 0, 1, 7, 9]); + app.run("path.transform", params).unwrap(); + assert_eq!(path(&app, "Saved drawing").subpaths[0].knots[0].anchor.x, 17.0); + assert_eq!(path(&app, "work"), work); + assert_eq!(app.run("shape.info", json!({})).unwrap(), shape); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(path(&app, "Saved drawing"), original); + app.ui.selected_path = None; + assert_eq!(vector_ui::free_transform_path(&app).unwrap().0["name"], "layer", "deselection restores the shape fallback"); + } +} + +#[test] +fn explicit_work_path_precedes_vector_mask_and_deselection_restores_mask_fallback() { + let mut app = app(Tool::PathSelection); + seed(&mut app, "work", 20.0); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.vectorMask.add", json!({"layer":layer.0,"path":{"subpaths":[{"knots":[[30,40],[80,40]]}]}})).unwrap(); + app.ui.vector_mask_target = true; + app.ui.selected_path = Some("work".into()); + assert_eq!(vector_ui::free_transform_path(&app).unwrap().0, json!({"name":"work"})); + app.ui.selected_path = None; + assert_eq!(vector_ui::free_transform_path(&app).unwrap().0, json!({"name":"layer","layer":layer.0})); +} + +#[test] +fn pen_keeps_its_captured_vector_mask_when_another_path_is_selected() { + let mut app = app(Tool::Pen); + seed(&mut app, "Saved drawing", 20.0); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.vectorMask.add", json!({"layer":layer.0,"path":{"subpaths":[{"knots":[[30,40],[80,40]]}]}})).unwrap(); + app.ui.selected_path = None; + app.ui.vector_mask_target = true; + let (saved, original, n) = (path(&app, "Saved drawing"), app.session.active().unwrap().doc.layer(layer).unwrap().vector_mask.clone().unwrap(), steps(&app)); + click(&mut app, 30.0, 60.0); + app.ui.vector_mask_target = false; + app.ui.selected_path = Some("Saved drawing".into()); + click(&mut app, 130.0, 60.0); + vector_ui::pen_commit(&mut app, false); + let mask = app.session.active().unwrap().doc.layer(layer).unwrap().vector_mask.clone().unwrap(); + assert_eq!(mask.path.subpaths.len(), 2); + assert_eq!(mask.path.subpaths[0], original.path.subpaths[0]); + assert_eq!(mask.path.subpaths[1].knots[0].anchor.y, 60.0); + assert_eq!(path(&app, "Saved drawing"), saved); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layer(layer).unwrap().vector_mask.as_ref(), Some(&original)); +} + +#[test] +fn freeform_finish_uses_its_captured_saved_path_and_rejects_foreign_documents() { + let mut app = app(Tool::FreeformPen); + seed(&mut app, "work", 20.0); + seed(&mut app, "Saved drawing", 40.0); + app.ui.selected_path = Some("Saved drawing".into()); + let owner = vector_ui::capture_pen_owner(&app).unwrap(); + let points = [[30.0, 60.0, 1.0], [80.0, 60.0, 1.0], [130.0, 60.0, 1.0]]; + let (original, work, n) = (path(&app, "Saved drawing"), path(&app, "work"), steps(&app)); + app.ui.selected_path = Some("work".into()); + app.ui.tool_options.vector_mode = "shape".into(); + vector_ui::freeform_finish_owned(&mut app, &points, &[], owner); + assert_eq!(path(&app, "Saved drawing").subpaths.len(), 2); + assert_eq!(path(&app, "Saved drawing").subpaths[0], original.subpaths[0]); + assert_eq!(path(&app, "work"), work); + assert_eq!(steps(&app), n + 1); + app.ui.tool_options.vector_mode = "path".into(); + let owner = vector_ui::capture_pen_owner(&app).unwrap(); + app.session.execute("file.new", json!({"width":200,"height":200})).unwrap(); + let (source, n) = (app.session.active().unwrap().doc.clone(), steps(&app)); + vector_ui::freeform_finish_owned(&mut app, &points, &[], owner); + assert!(std::sync::Arc::ptr_eq(&source, &app.session.active().unwrap().doc)); + assert_eq!(steps(&app), n); +} + +#[test] +fn tab_switch_commits_only_the_valid_original_captured_saved_path() { + let mut app = app(Tool::Pen); + seed(&mut app, "Saved drawing", 20.0); + app.ui.selected_path = Some("Saved drawing".into()); + draft(&mut app); + let source = app.session.active().unwrap().doc.id; + app.session.execute("file.new", json!({"width":200,"height":200})).unwrap(); + // Seed through the engine so UI sync cannot process the tab switch before this assertion. + app.session.execute("path.set", json!({"name":"Destination", "path":{"subpaths":[{"closed":false,"knots":[[10.0,100.0],[90.0,100.0]]}]}})).unwrap(); + app.ui.selected_path = Some("Destination".into()); + let current = app.session.active().unwrap().doc.clone(); + assert!(vector_ui::cancel_stale_pen(&mut app)); + assert!(app.ui.pen.is_none()); + app.sync_views(); + assert_eq!(app.ui.selected_path.as_deref(), Some("Destination")); + assert!(std::sync::Arc::ptr_eq(¤t, &app.session.active().unwrap().doc)); + let old = app.session.documents().iter().find(|s| s.doc.id == source).unwrap(); + assert_eq!(old.doc.paths.iter().find(|p| p.name == "Saved drawing").unwrap().path.subpaths.len(), 2); + assert!(old.doc.work_path.is_none()); +} +#[test] +fn deleting_the_captured_target_cancels_without_recreating_it() { + let mut app = app(Tool::Pen); + seed(&mut app, "Saved drawing", 20.0); + app.ui.selected_path = Some("Saved drawing".into()); + draft(&mut app); + app.session.execute("path.delete", json!({"name":"Saved drawing"})).unwrap(); + let current = app.session.active().unwrap().doc.clone(); + let n = steps(&app); + vector_ui::cancel_stale_pen(&mut app); + assert!(app.ui.pen.is_none()); + assert!(app.ui.status_error); + assert!(std::sync::Arc::ptr_eq(¤t, &app.session.active().unwrap().doc)); + assert_eq!(steps(&app), n); + assert!(app.session.active().unwrap().doc.paths.is_empty()); +} diff --git a/crates/ui-egui/src/pen_path_visual_tests.rs b/crates/ui-egui/src/pen_path_visual_tests.rs new file mode 100644 index 0000000000..6fc23e8ade --- /dev/null +++ b/crates/ui-egui/src/pen_path_visual_tests.rs @@ -0,0 +1,101 @@ +//! Synthetic offscreen evidence for editing a selected saved path beside the Work Path. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::kittest::Queryable; +use photocraft_doc::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; + +fn path(app: &PhotocraftApp, name: &str) -> Path { + let doc = &app.session.active().unwrap().doc; + if name == "work" { doc.work_path.clone().unwrap() } else { doc.paths.iter().find(|p| p.name == name).unwrap().path.clone() } +} + +fn translated(mut path: Path, dx: f64, dy: f64) -> Path { + for knot in path.subpaths.iter_mut().flat_map(|s| &mut s.knots) { + for point in [&mut knot.anchor, &mut knot.in_ctrl, &mut knot.out_ctrl] { + point.x += dx; + point.y += dy; + } + } + path +} + +fn button(pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } +} + +/// Run explicitly with a wgpu adapter. PHOTOCRAFT_PEN_VISUAL_DIR chooses the output directory; +/// PHOTOCRAFT_PEN_VISUAL_BASELINE=1 characterizes the old Work Path targeting for a before capture. +#[test] +#[ignore = "manual offscreen visual fixture; writes synthetic screenshots"] +fn saved_path_drag_visual_fixture() { + let baseline = std::env::var("PHOTOCRAFT_PEN_VISUAL_BASELINE").is_ok_and(|v| v == "1"); + let output = std::env::var_os("PHOTOCRAFT_PEN_VISUAL_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| "log/pen-path-visual".into()); + std::fs::create_dir_all(&output).expect("create synthetic screenshot directory"); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(64).wgpu().build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.edit_prefs(|p| p.interface.language = "en".into()); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app.run("file.new", json!({"name": "Saved path targeting", "width": 400, "height": 260, "background": "white"})).unwrap(); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [[40, 80], [140, 80], [90, 180]]}]}})).unwrap(); + app.run( + "path.set", + json!({"name": "Saved drawing", "path": {"subpaths": [{"closed": false, "knots": [ + {"anchor": [220, 90], "in": [220, 90], "out": [260, 40]}, + {"anchor": [320, 180], "in": [280, 230], "out": [320, 180]} + ]}]}}), + ) + .unwrap(); + app.sync_views(); + app.ui.tool = Tool::PathSelection; + app.ui.extras.snap = false; + app.ui.dock_tabs.layers = 2; + app.ui.views[0].fit_pending = false; + app.ui.views[0].zoom = 1.5; + app.ui.views[0].center = [200.0, 130.0]; + app + }); + h.run_steps(8); + h.get_by_label("Saved drawing").click(); + h.run_steps(4); + assert_eq!(h.state().ui.selected_path.as_deref(), Some("Saved drawing"), "the Paths panel row selects the saved path"); + let (work, saved) = (path(h.state(), "work"), path(h.state(), "Saved drawing")); + let history = h.state().session.active().unwrap().history.past_len(); + let mode = if baseline { "baseline" } else { "fixed" }; + let before = output.join(format!("{mode}-before.png")); + h.render().expect("render initial scene").save(&before).expect("save initial scene"); + + // Screen coordinates come from the real full-app layout, including its dock and rulers. + let xf = ViewXform::active(h.state()).expect("active document canvas"); + let start = xf.to_screen(220.0, 90.0); + let end = xf.to_screen(245.0, 70.0); + assert!(xf.rect.contains(start) && xf.rect.contains(end)); + h.event(Event::PointerMoved(start)); + h.event(button(start, true)); + h.step(); + h.event(Event::PointerMoved(end)); + h.step(); + assert!(h.state().drag.is_some(), "native movement past the drag threshold starts a path gesture"); + h.event(button(end, false)); + h.step(); + h.run_steps(12); + assert!(h.state().drag.is_none()); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1, "one native drag is one Undo step"); + if baseline { + assert_eq!(path(h.state(), "Saved drawing"), saved, "baseline incorrectly leaves the selected saved path untouched"); + assert_eq!(path(h.state(), "work"), translated(work, 25.0, -20.0), "baseline incorrectly moves the Work Path"); + } else { + assert_eq!(path(h.state(), "work"), work, "editing a saved path preserves the Work Path"); + assert_eq!(path(h.state(), "Saved drawing"), translated(saved, 25.0, -20.0), "the selected saved path and its curve handles move together"); + } + let after = output.join(format!("{mode}-after.png")); + h.render().expect("render completed drag").save(&after).expect("save completed drag"); + println!("{mode}: selected Saved drawing; native drag (+25, -20); screenshots: {}, {}", before.display(), after.display()); +} diff --git a/crates/ui-egui/src/pen_variants_tests.rs b/crates/ui-egui/src/pen_variants_tests.rs index 330f2bc6f3..4b5cf04d61 100644 --- a/crates/ui-egui/src/pen_variants_tests.rs +++ b/crates/ui-egui/src/pen_variants_tests.rs @@ -211,7 +211,8 @@ fn the_pen_carries_on_an_open_path_from_either_end() { } /// #6593 review: carrying on a subpath keeps its path operation, and a draft whose subpath changed -/// meanwhile is added as a new subpath instead of overwriting another one. +/// meanwhile refuses without overwriting newer work. The historical test name is retained +/// for reviewed-head provenance; captured-revision validation supersedes its stale fallback. #[test] fn a_resumed_subpath_keeps_its_operation_and_a_stale_draft_adds_a_new_one() { let mut app = app(Tool::Pen); @@ -223,21 +224,28 @@ fn a_resumed_subpath_keeps_its_operation_and_a_stale_draft_adds_a_new_one() { let work = work_path(&app); assert_eq!((work.subpaths.len(), work.subpaths[0].knots.len()), (1, 3)); assert_eq!(work.subpaths[0].op, photocraft_doc::vector::PathOp::Subtract, "the operation is kept"); - // The work path is replaced while the draft is open: the draft becomes a new subpath. + // Replacing the source invalidates the draft; neither explicit commit nor a frame retries it. click(&mut app, 20.0, 20.0); click(&mut app, 20.0, 80.0); app.run("path.set", json!({"name": "work", "path": {"subpaths": [open(120.0, 180.0, "combine")]}})).unwrap(); + let newer = work_path(&app); + let steps = app.session.active().unwrap().history.past_len(); crate::vector_ui::pen_commit(&mut app, false); let work = work_path(&app); - assert_eq!(work.subpaths.len(), 2, "a new subpath, the replaced one untouched"); + assert_eq!(work, newer, "the replaced source is unchanged by a stale draft"); + assert_eq!(work.subpaths.len(), 1); + assert!(app.ui.pen.is_none() && app.ui.status_error); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); assert_eq!(work.subpaths[0].knots.iter().map(|k| k.anchor.x).collect::>(), [120.0, 180.0]); - // The same with nothing selected in the Paths panel: still added to the Work Path it came from. + // Deselecting the path does not allow a stale draft to replace the newer source. click(&mut app, 180.0, 20.0); click(&mut app, 180.0, 90.0); app.ui.selected_path = None; app.run("path.set", json!({"name": "work", "path": {"subpaths": [open(120.0, 160.0, "combine")]}})).unwrap(); crate::vector_ui::pen_commit(&mut app, false); - assert_eq!(work_path(&app).subpaths.len(), 2, "added, not replacing the Work Path"); + assert_eq!(work_path(&app).subpaths.len(), 1, "no stale component is appended"); + assert_eq!(work_path(&app).subpaths[0].knots.iter().map(|k| k.anchor.x).collect::>(), [120.0, 160.0]); + assert!(app.ui.pen.is_none() && app.ui.status_error); // And with another path selected: the draft still goes back to the path it came from. app.run("path.set", json!({"name": "Other", "path": {"subpaths": [open(10.0, 30.0, "combine")]}})).unwrap(); click(&mut app, 160.0, 20.0); @@ -245,7 +253,9 @@ fn a_resumed_subpath_keeps_its_operation_and_a_stale_draft_adds_a_new_one() { app.ui.selected_path = Some("Other".into()); app.run("path.set", json!({"name": "work", "path": {"subpaths": [open(120.0, 150.0, "combine")]}})).unwrap(); crate::vector_ui::pen_commit(&mut app, false); - assert_eq!(work_path(&app).subpaths.len(), 2, "joined the Work Path it came from"); + assert_eq!(work_path(&app).subpaths.len(), 1, "neither selected path accepts stale geometry"); + assert_eq!(work_path(&app).subpaths[0].knots.iter().map(|k| k.anchor.x).collect::>(), [120.0, 150.0]); + assert!(app.ui.pen.is_none() && app.ui.status_error); let st = app.session.active().unwrap(); let other = st.doc.paths.iter().find(|p| p.name == "Other").unwrap(); assert_eq!(other.path.subpaths.len(), 1, "the selected path is untouched"); diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs index 6101436a17..f3f713ed6f 100644 --- a/crates/ui-egui/src/polygon_lasso_tests.rs +++ b/crates/ui-egui/src/polygon_lasso_tests.rs @@ -26,6 +26,7 @@ fn harness() -> Harness<'static, PhotocraftApp> { } crate::shortcuts::handle(app, &ctx); egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + crate::dialogs::show(app, &ctx); }, app, ); @@ -209,6 +210,217 @@ fn steps(h: &Harness<'static, PhotocraftApp>) -> usize { h.state().session.active().unwrap().history.entries().len() } +fn zoomed_polygon() -> Harness<'static, PhotocraftApp> { + let mut h = harness(); + h.state_mut().ui.views[0].zoom = 4.0; + h.run_steps(2); + click(&mut h, 170.0, 130.0, Modifiers::NONE); + h.run_steps(30); + h +} + +#[test] +fn polygon_edge_scroll_continues_with_button_up_and_keeps_vertices_fixed() { + for (dx, dy, flip, rotation) in [ + (-1.0, 0.0, false, 0.0), + (1.0, 0.0, false, 0.0), + (0.0, -1.0, false, 0.0), + (0.0, 1.0, false, 0.0), + (-1.0, -1.0, false, 0.0), + (1.0, -1.0, false, 0.0), + (-1.0, 1.0, false, 0.0), + (1.0, 1.0, false, 0.0), + (1.0, 0.0, true, 0.0), + (1.0, 0.0, false, 90.0), + ] { + let mut h = zoomed_polygon(); + h.state_mut().ui.view.flip_horizontal = flip; + h.state_mut().ui.views[0].rotation = rotation; + h.run_steps(1); + let xf = ViewXform::active(h.state()).unwrap(); + // Just beyond each viewport edge, still inside the application's window. + let at = xf.rect.center() + vec2(dx * (xf.rect.width() / 2.0 + 4.0), dy * (xf.rect.height() / 2.0 + 4.0)); + let points = h.state().ui.polygon.clone(); + let before = steps(&h); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + let first = h.state().ui.views[0].center; + h.run_steps(4); // No pointer events or pressed buttons: scrolling must keep going. + let next = h.state().ui.views[0].center; + let direction = xf.unmap_vec(vec2(dx, dy)); + let movement = vec2(next[0] - xf.center[0], next[1] - xf.center[1]); + assert!(movement.dot(direction) > 0.1, "edge ({dx},{dy}), flip={flip}, rotation={rotation}: {movement:?}"); + assert!((movement.x * direction.y - movement.y * direction.x).abs() < 0.001, "scroll follows the displayed axes"); + assert!((next[0] - first[0]).hypot(next[1] - first[1]) > 0.1, "stationary pointer keeps scrolling"); + assert_eq!(h.state().ui.polygon, points, "view motion never adds or moves vertices"); + assert_eq!(steps(&h), before); + assert!(selection(&h).is_none()); + assert!(!h.ctx.input(|i| i.pointer.any_down())); + assert!(h.output().viewport_output[&egui::ViewportId::ROOT].repaint_delay.is_zero()); + h.event(egui::Event::PointerMoved(xf.rect.center())); + h.run_steps(1); + let stopped = h.state().ui.views[0].center; + h.run_steps(4); + assert_eq!(h.state().ui.views[0].center, stopped, "returning to the interior stops scrolling"); + } + + let mut h = zoomed_polygon(); + h.state_mut().run("prefs.set", json!({"path":"tools.overscroll","value":false})).unwrap(); + let xf = ViewXform::active(h.state()).unwrap(); + let (points, before) = (h.state().ui.polygon.clone(), steps(&h)); + h.event(egui::Event::PointerMoved(xf.rect.right_center() + vec2(4.0, 0.0))); + h.run_steps(90); + let center = h.state().ui.views[0].center; + assert!((center[0] - (400.0 - xf.rect.width() / (2.0 * xf.zoom))).abs() < 0.001, "Overscroll off stops at the image's right edge"); + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, center, "a long edge hold stays clamped"); + assert_eq!(h.state().ui.polygon, points); + assert_eq!(steps(&h), before); +} + +#[test] +fn polygon_edge_scroll_places_the_next_vertex_in_the_panned_view_and_commits_once() { + let mut h = zoomed_polygon(); + let before = steps(&h); + let original = ViewXform::active(h.state()).unwrap(); + h.event(egui::Event::PointerMoved(original.rect.right_center() - vec2(4.0, 0.0))); + h.run_steps(10); + let panned = ViewXform::active(h.state()).unwrap(); + assert!(panned.center[0] > original.center[0], "the zoomed image pans toward the right edge"); + let at = panned.rect.center() + vec2(60.0, 0.0); + let expected = panned.to_doc(at); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(20); + button(&mut h, at, true, Modifiers::NONE); + button(&mut h, at, false, Modifiers::NONE); + assert_eq!(h.state().ui.polygon[1], expected, "the next click uses the updated view transform"); + h.run_steps(30); + click(&mut h, expected[0] as f32, 190.0, Modifiers::NONE); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.polygon.is_empty()); + assert!(selection(&h).is_some_and(|r| near(r, 170, 130, expected[0].ceil() as i32, 190)), "{:?}", selection(&h)); + assert_eq!(steps(&h), before + 1); + let finished_center = h.state().ui.views[0].center; + h.event(egui::Event::PointerMoved(original.rect.right_center())); + h.run_steps(4); + assert_eq!(h.state().ui.views[0].center, finished_center, "a finished polygon never scrolls"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(selection(&h).is_none(), "one undo removes the completed selection"); +} + +#[test] +fn polygon_edge_scroll_keeps_pixel_aspect_and_shift_constrained_segments() { + for (flip, rotation) in [(false, 0.0), (true, 0.0), (false, 45.0), (true, 90.0)] { + let mut h = zoomed_polygon(); + h.state_mut().ui.view.pixel_aspect = "custom:2:Wide".into(); + h.state_mut().ui.view.flip_horizontal = flip; + h.state_mut().ui.views[0].rotation = rotation; + h.run_steps(2); + let original = ViewXform::active(h.state()).unwrap(); + let points = h.state().ui.polygon.clone(); + h.event(egui::Event::PointerMoved(original.rect.right_center() + vec2(4.0, 0.0))); + h.run_steps(5); + let panned = ViewXform::active(h.state()).unwrap(); + let movement = original.map_vec(vec2(panned.center[0] - original.center[0], panned.center[1] - original.center[1])); + assert!(movement.x > 1.0 && movement.y.abs() < 0.001, "wide pixels, flip={flip}, rotation={rotation}: {movement:?}"); + assert_eq!(h.state().ui.polygon, points, "scrolling keeps existing document-space vertices"); + + let at = panned.rect.center() + vec2(60.0, 30.0); + let expected = crate::canvas::constrained_polygon_point(points[0], panned.to_doc(at)); + h.event(egui::Event::PointerMoved(at)); + h.event(egui::Event::ModifiersChanged(Modifiers::SHIFT)); + h.run_steps(30); + button(&mut h, at, true, Modifiers::SHIFT); + button(&mut h, at, false, Modifiers::SHIFT); + assert_eq!(h.state().ui.polygon.len(), 2); + assert_eq!(h.state().ui.polygon[1], expected, "Shift still snaps in document space after panning"); + assert_eq!(h.state().ui.polygon_mode, "replace", "Shift after the first vertex does not change selection intent"); + } + + let mut h = zoomed_polygon(); + h.state_mut().ui.view.pixel_aspect = "custom:2:Wide".into(); + h.state_mut().run("prefs.set", json!({"path":"tools.overscroll","value":false})).unwrap(); + let xf = ViewXform::active(h.state()).unwrap(); + h.event(egui::Event::PointerMoved(xf.rect.right_center() + vec2(4.0, 0.0))); + h.run_steps(180); + let center = h.state().ui.views[0].center; + let rightmost = 400.0 - xf.rect.width() / (2.0 * xf.zoom_x()); + assert!((center[0] - rightmost).abs() < 0.001, "Overscroll off clamps using the displayed pixel aspect"); + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, center); +} + +#[test] +fn polygon_edge_scroll_pauses_for_dialogs_and_temporary_navigation() { + for pause in ["dialog", "space", "middle"] { + let mut h = zoomed_polygon(); + let rect = ViewXform::active(h.state()).unwrap().rect; + let edge = rect.right_center() + vec2(4.0, 0.0); + h.event(egui::Event::PointerMoved(edge)); + h.run_steps(1); + match pause { + "dialog" => { + h.state_mut().ui.open_dialog(crate::state::DialogKind::Error, json!({"message":"Pause"}).as_object().unwrap().clone()); + } + "space" => h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }), + _ => h.event(egui::Event::PointerButton { pos: edge, button: PointerButton::Middle, pressed: true, modifiers: Modifiers::NONE }), + } + h.run_steps(2); + let center = h.state().ui.views[0].center; + let points = h.state().ui.polygon.clone(); + h.run_steps(5); + assert_eq!(h.state().ui.views[0].center, center, "paused for {pause}"); + assert_eq!(h.state().ui.polygon, points, "{pause} retains the unfinished selection"); + } +} + +#[test] +fn polygon_edge_scroll_never_moves_an_inactive_pane_or_survives_a_document_or_tool_switch() { + let mut h = zoomed_polygon(); + // Creating a document now cancels the old polygon immediately. Start a fresh one after + // returning, so the inactive-pane and Enter checks exercise an outline that can commit. + h.state_mut().run("file.new", json!({"width":400,"height":300})).unwrap(); + h.state_mut().session.set_active(0); + h.run_steps(2); + for (x, y) in [(170.0, 130.0), (200.0, 130.0), (200.0, 170.0)] { + click(&mut h, x, y, Modifiers::NONE); + h.run_steps(30); + } + assert_eq!(h.state().ui.polygon.len(), 3); + h.state_mut().ui.views[1].zoom = 4.0; + h.state_mut().ui.views[1].center = [200.0, 150.0]; + h.state_mut().ui.views[1].fit_pending = false; + h.state_mut().ui.view.arrange = "twoUpVertical".into(); + h.run_steps(2); + let other = crate::canvas::arranged_cells(h.state(), h.state().last_canvas_rect).unwrap().into_iter().find(|(i, _)| *i == 1).unwrap().1; + let centers: Vec<_> = h.state().ui.views.iter().map(|v| v.center).collect(); + h.event(egui::Event::PointerMoved(other.left_center() + vec2(4.0, 0.0))); + h.run_steps(5); + assert_eq!(h.state().ui.views.iter().map(|v| v.center).collect::>(), centers, "hovering the other pane never pans either view"); + assert_eq!(h.state().ui.polygon.len(), 3, "the active polygon is still unfinished"); + h.state_mut().session.set_active(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.polygon.is_empty(), "the old document's unfinished polygon is discarded before Enter"); + assert!(selection(&h).is_none()); + + let mut h = zoomed_polygon(); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(2); + assert!(h.state().ui.polygon.is_empty(), "changing tools drops the polygon"); + h.state_mut().ui.tool = Tool::PolygonLasso; + click(&mut h, 170.0, 130.0, Modifiers::NONE); + h.key_press(egui::Key::Escape); + h.run_steps(2); + let center = h.state().ui.views[0].center; + let edge = ViewXform::active(h.state()).unwrap().rect.right_center(); + h.event(egui::Event::PointerMoved(edge)); + h.run_steps(5); + assert!(h.state().ui.polygon.is_empty()); + assert_eq!(h.state().ui.views[0].center, center, "Escape stops edge scrolling"); +} + /// A new polygon hides the selection it will replace; Esc brings it back untouched. #[test] fn a_new_polygon_hides_the_selection_and_esc_restores_it() { diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs index c7853067aa..f59bf278e8 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs @@ -200,6 +200,27 @@ fn shift_is_recorded_when_modifier_key_events_carry_no_bits() { assert_eq!(field(&h, id, "capture"), json!(false)); } +/// ⌘Z can be bound like any other key (#9487): while a field waits for keys it is the shortcut +/// to record, not the dialog's own Undo (#4697), which used to undo the click that started the +/// capture. Once recorded, ⌘Z steps the dialog back again. +#[test] +fn cmd_z_is_recorded_while_capturing_and_undoes_otherwise() { + let (mut h, id) = dialog(1.0, "edit.search", "search…"); + capture(&mut h, &crate::shortcuts::pretty("Cmd+F"), Key::ControlLeft, Modifiers::COMMAND, Key::Z); + assert_eq!(field(&h, id, "overrides")["edit.search"], json!("Cmd+Z")); + assert_eq!(field(&h, id, "capture"), json!(false)); + key(&mut h, Key::Z, true, Modifiers::COMMAND); + h.run_steps(2); + assert_ne!(field(&h, id, "overrides")["edit.search"], json!("Cmd+Z"), "⌘Z outside a capture undoes the change"); + assert_eq!(field(&h, id, "capture"), json!(false), "and doesn't wait for keys again"); + // CodeRabbit on #9504: clearing the restored capture isn't a new edit, so Redo still works. + h.run_steps(2); + key(&mut h, Key::Z, true, Modifiers::COMMAND | Modifiers::SHIFT); + h.run_steps(2); + assert_eq!(field(&h, id, "overrides")["edit.search"], json!("Cmd+Z"), "⇧⌘Z redoes the recorded shortcut"); + assert_eq!(field(&h, id, "capture"), json!(false)); +} + #[test] fn ctrl_k_is_recorded_as_ctrl_k_not_the_control_key() { for ppp in [1.0, 2.0] { diff --git a/crates/ui-egui/src/prefs/prefs_ui/startup.rs b/crates/ui-egui/src/prefs/prefs_ui/startup.rs index 1d4005f17a..e1789138ee 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/startup.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/startup.rs @@ -41,6 +41,7 @@ pub fn load(app: &mut PhotocraftApp) { } } crate::dock::restore(app); + crate::color_panel_ui::restore(app); crate::brush_picker::restore(app); crate::last_brush::restore(app); sync_rulers(app); diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index e96ddc220e..9f4df0ae13 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1128,15 +1128,17 @@ fn tool_options_survive_a_restart() { tick(&mut app, &ctx); app.ui.tool_options.move_auto_select = false; app.ui.tool_options.feather = 12.0; + app.ui.tool_options.transform_interpolation = Some(photocraft_engine::prefs::Interpolation::Nearest); crate::tool_memory::persist(&mut app, &ctx); tick(&mut app, &ctx); // Only what differs from the defaults is stored. - assert_eq!(stored(&store)["toolOptions"], json!({"move_auto_select": false, "feather": 12.0})); + assert_eq!(stored(&store)["toolOptions"], json!({"move_auto_select": false, "feather": 12.0, "transform_interpolation": "nearestNeighbor"})); let saved = store.lock().unwrap().clone().unwrap(); let (mut app2, _) = app_with_saved(Some(saved)); tick(&mut app2, &ctx); assert!(!app2.ui.tool_options.move_auto_select); assert_eq!(app2.ui.tool_options.feather, 12.0); + assert_eq!(app2.ui.tool_options.transform_interpolation, Some(photocraft_engine::prefs::Interpolation::Nearest)); assert_eq!(app2.ui.tool_options.tolerance, crate::state::ToolOptions::default().tolerance); // A hand-edited file: unreadable fields keep their defaults, the good ones still load. for bad in [json!("junk"), json!({"move_auto_select": "no", "feather": 1e300, "tolerance": 5.0, "unknown": 1})] { diff --git a/crates/ui-egui/src/saved_path_edit_tests.rs b/crates/ui-egui/src/saved_path_edit_tests.rs new file mode 100644 index 0000000000..efa3d9faf1 --- /dev/null +++ b/crates/ui-egui/src/saved_path_edit_tests.rs @@ -0,0 +1,192 @@ +//! #8478: the saved path selected in the Paths panel is Photoshop's target path, and Path +//! Selection, Direct Selection and the anchor tools edit it, as they edit the work path. It was +//! drawn (#6550) but none of the tools picked it, so a path that arrived in a PSD ("Path 1") could +//! not be selected or changed. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use photocraft_geom::Point; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::direct_select::PathRef; +use crate::state::Tool; + +const NAME: &str = "Path 1"; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app +} + +fn square(x: f64, y: f64, w: f64) -> serde_json::Value { + json!({"subpaths": [{"closed": true, "knots": [[x, y], [x + w, y], [x + w, y + w], [x, y + w]]}]}) +} + +/// A saved path, a square from (40, 40) to (120, 120), selected in the Paths panel. +fn with_saved_path(app: &mut PhotocraftApp) { + app.run("path.set", json!({"name": NAME, "path": square(40.0, 40.0, 80.0)})).unwrap(); + app.ui.selected_path = Some(NAME.into()); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == NAME).unwrap().path.clone() +} + +fn anchors(p: &Path) -> Vec { + p.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor)).collect() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +#[test] +fn direct_selection_drags_an_anchor_of_the_selected_saved_path() { + let mut app = app(Tool::DirectSelection); + with_saved_path(&mut app); + let (before, n) = (saved(&app), steps(&app)); + drag(&mut app, [120.5, 120.5], [130.5, 135.5], Modifiers::NONE); + let after = saved(&app); + assert_eq!(after.subpaths[0].knots[2].anchor, Point::new(130.0, 135.0), "the dragged anchor moved"); + assert_eq!(after.subpaths[0].knots[0].anchor, Point::new(40.0, 40.0), "the others stay"); + assert_eq!(steps(&app), n + 1, "one history step"); + assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Saved(0)), vec![[0, 2]])); + assert!(app.session.active().unwrap().doc.work_path.is_none(), "no work path was made"); + assert!(app.session.undo()); + assert_eq!(saved(&app), before); +} + +#[test] +fn direct_selection_marquee_selects_and_arrow_params_name_the_saved_path() { + let mut app = app(Tool::DirectSelection); + with_saved_path(&mut app); + drag(&mut app, [30.0, 30.0], [50.0, 50.0], Modifiers::NONE); + assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Saved(0)), vec![[0, 0]])); + assert_eq!(PathRef::Saved(0).params(&app), json!({"name": NAME})); + // A path that is gone gets no name, which the engine refuses instead of editing another one. + assert_eq!(PathRef::Saved(7).params(&app), json!({"name": ""})); + assert!(app.run("path.moveAnchors", json!({"name": "", "anchors": [[0, 0]], "move": [1, 1]})).is_err()); +} + +#[test] +fn the_saved_path_is_only_edited_while_the_paths_panel_selects_it() { + let mut app = app(Tool::DirectSelection); + with_saved_path(&mut app); + app.ui.selected_path = None; + let before = saved(&app); + drag(&mut app, [120.5, 120.5], [130.5, 135.5], Modifiers::NONE); + assert_eq!(saved(&app), before, "an unselected saved path is not the target path"); + assert!(!crate::direct_select::active_paths(&app).iter().any(|(r, _)| matches!(r, PathRef::Saved(_)))); +} + +#[test] +fn the_selected_saved_path_comes_before_the_work_path() { + let mut app = app(Tool::DirectSelection); + with_saved_path(&mut app); + // A work path on top of the same square: the saved path the panel selects wins. + app.run("path.set", json!({"name": "work", "path": square(40.0, 40.0, 80.0)})).unwrap(); + let work = app.session.active().unwrap().doc.work_path.clone().unwrap(); + let refs: Vec = crate::direct_select::active_paths(&app).into_iter().map(|(r, _)| r).collect(); + assert_eq!(refs, vec![PathRef::Saved(0), PathRef::Work]); + drag(&mut app, [40.5, 40.5], [20.5, 30.5], Modifiers::NONE); + assert_eq!(saved(&app).subpaths[0].knots[0].anchor, Point::new(20.0, 30.0)); + assert_eq!(app.session.active().unwrap().doc.work_path.clone().unwrap(), work, "the work path is untouched"); +} + +#[test] +fn path_selection_moves_the_selected_saved_path() { + let mut app = app(Tool::PathSelection); + with_saved_path(&mut app); + let n = steps(&app); + drag(&mut app, [80.0, 40.0], [90.0, 55.0], Modifiers::NONE); + assert_eq!( + anchors(&saved(&app)), + vec![Point::new(50.0, 55.0), Point::new(130.0, 55.0), Point::new(130.0, 135.0), Point::new(50.0, 135.0)], + "the whole path moved by (10, 15)" + ); + assert_eq!(steps(&app), n + 1); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +#[test] +fn free_transform_path_names_the_selected_saved_path() { + let mut app = app(Tool::PathSelection); + with_saved_path(&mut app); + let (params, path) = crate::vector_ui::free_transform_path(&app).expect("the saved path is transformable"); + assert_eq!(params, json!({"name": NAME})); + assert_eq!(path, saved(&app)); +} + +#[test] +fn add_and_delete_anchor_point_edit_the_selected_saved_path() { + let mut app = app(Tool::AddAnchorPoint); + with_saved_path(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 80.0, y: 40.0 }, Modifiers::NONE); + assert_eq!(anchors(&saved(&app)).len(), 5, "an anchor was added on the top segment"); + app.ui.tool = Tool::DeleteAnchorPoint; + tool_event(&mut app, ToolEvent::Down { x: 120.0, y: 120.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 120.0 }, Modifiers::NONE); + assert!(!anchors(&saved(&app)).contains(&Point::new(120.0, 120.0)), "the corner anchor was deleted"); +} + +/// The report's file: a PSD whose saved path "Path 1" is picked in the Paths panel. A synthetic +/// one, written and read back through the PSD codec. +#[test] +fn a_saved_path_read_from_a_psd_is_editable() { + let mut src = app(Tool::DirectSelection); + with_saved_path(&mut src); + let doc = src.session.active().unwrap().doc.clone(); + let bytes = photocraft_io::export(&doc, "psd", &Default::default()).unwrap().bytes; + let mut app = app(Tool::DirectSelection); + photocraft_engine::file_cmds::open_bytes_as(&mut app.session, "paths.psd", &bytes, None, None).unwrap(); + app.sync_views(); + assert!(app.session.active().unwrap().doc.paths.iter().any(|p| p.name == NAME), "the PSD keeps its saved path"); + app.ui.selected_path = Some(NAME.into()); + let n = steps(&app); + drag(&mut app, [120.5, 120.5], [130.5, 135.5], Modifiers::NONE); + // PSD stores path points as 8.24 fixed-point fractions of the canvas: compare loosely. + let a = saved(&app).subpaths[0].knots[2].anchor; + assert!((a.x - 130.0).abs() < 1e-3 && (a.y - 135.0).abs() < 1e-3, "the anchor moved to (130, 135): {a:?}"); + assert_eq!(steps(&app), n + 1); +} + +/// Anchors selected on one saved path are dropped once the Paths panel picks another: the arrow +/// keys must not nudge a path that is no longer the target path. +#[test] +fn arrows_leave_a_saved_path_the_paths_panel_no_longer_selects() { + let mut app = app(Tool::DirectSelection); + with_saved_path(&mut app); + app.run("path.set", json!({"name": "Path 2", "path": square(10.0, 10.0, 20.0)})).unwrap(); + drag(&mut app, [30.0, 30.0], [50.0, 50.0], Modifiers::NONE); + assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Saved(0)), vec![[0, 0]])); + // One → press through the canvas arrow keys, as egui delivers it. + let arrow = |app: &mut PhotocraftApp| { + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + i.events.push(egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }) + }); + crate::direct_select::arrow_keys(app, &ctx) + }; + assert!(arrow(&mut app), "the selected path's anchor is nudged"); + assert_eq!(saved(&app).subpaths[0].knots[0].anchor, Point::new(41.0, 40.0)); + app.ui.selected_path = Some("Path 2".into()); + let (one, two) = (saved(&app), app.session.active().unwrap().doc.paths[1].path.clone()); + assert!(!arrow(&mut app), "no key is used for a path that is not the target"); + assert_eq!(saved(&app), one, "Path 1 stays"); + assert_eq!(app.session.active().unwrap().doc.paths[1].path, two, "Path 2 stays"); + assert_eq!(app.ui.direct_selection.target, None, "the stale anchor selection is dropped"); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5f2bb869ce..d055150af4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -190,6 +190,12 @@ pub struct DocWindow { pub document: usize, pub view: View, pub open: bool, + /// This window owns the document's view; the document is removed from the main canvas. + #[serde(default)] + pub floating: bool, + /// Transient focus edge used to activate the document once when this viewport gains focus. + #[serde(skip)] + pub focused: bool, /// Where the window opens on screen (outer top-left, in points); `None` lets the OS place it. /// A tab dragged off the tab strip opens its window where it was dropped (#3733). #[serde(default)] @@ -278,6 +284,9 @@ pub struct UiState { /// its screen position (points). #[serde(default)] pub brush_picker: Option<[f32; 2]>, + /// Brush Mode menu opened by Shift+right-click: screen position in points. + #[serde(default)] + pub brush_mode_menu: Option<[f32; 2]>, /// The Brush Preset picker's preset list: search, collapsed groups, view, a rename in progress. #[serde(default = "crate::brush_picker::list_state")] pub brush_picker_list: crate::brush_panel::BrushesPanelState, @@ -285,6 +294,10 @@ pub struct UiState { /// ([`crate::brush_picker::DEFAULT_SIZE`] before that). #[serde(default)] pub brush_picker_size: Option<[f32; 2]>, + /// Photoshop's HUD Color Picker (#6098), open while Shift+Alt+right-click is held on the + /// canvas with a painting tool (`crate::color_hud`). + #[serde(default)] + pub color_hud: Option, /// Layers under the pointer, listed by a right-click on the canvas with the Move tool or /// ⌘/Ctrl+right-click with any tool (`layer_pick_ui`, #307). #[serde(default)] @@ -413,6 +426,10 @@ pub struct UiState { /// Which chip the Color panel edits, and how it shows the colour. #[serde(default)] pub color_panel: ColorPanelState, + /// The Color panel options as last synced with the preferences: a stored value that differs + /// from it was changed outside the panel (`prefs.set`, a reset) and is taken, not overwritten. + #[serde(skip)] + pub color_panel_synced: Option, /// Histogram panel options: view, channel, statistics, colours, source. #[serde(default)] pub histogram_panel: crate::histogram_panel::HistogramPanelState, @@ -514,8 +531,10 @@ impl Default for UiState { filter_mask_target: None, properties_layer: None, brush_picker: None, + brush_mode_menu: None, brush_picker_list: crate::brush_picker::list_state(), brush_picker_size: None, + color_hud: None, layer_menu: None, canvas_tool_menu: None, selected_guide: None, @@ -568,6 +587,7 @@ impl Default for UiState { docking_collapsed: Vec::new(), docking_reveal: None, color_panel: Default::default(), + color_panel_synced: None, brush_section: 0, brush_tab: 0, brushes_panel: Default::default(), diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 8b8bad1630..d577475103 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -91,6 +91,11 @@ pub struct ToolOptions { pub enhance_edge: bool, /// Pen: "path" (work path) or "shape" (shape layer). pub vector_mode: String, + /// Pen, Freeform Pen and Curvature Pen › Path Operations (#1397): how a new path combines with + /// the path or shape it is drawn into: "newLayer" (Shape mode: a new shape layer; Path mode + /// draws it as "combine"), "combine", "subtract", "intersect" or "exclude". + #[serde(default = "default_pen_path_op")] + pub pen_path_op: String, /// Shape tools: fill with the foreground colour, stroke width (0 = none), rectangle corner /// radius, polygon sides, line weight. pub shape_fill: bool, @@ -139,6 +144,9 @@ pub struct ToolOptions { pub move_target: String, #[serde(default)] pub move_show_transform: bool, + /// Last interpolation selected in the Transform options bar; unset follows General's default. + #[serde(default)] + pub transform_interpolation: Option, /// Crop options bar: aspect ratio ("" = Ratio/unconstrained, "w:h", or "original") and /// Delete Cropped Pixels. #[serde(default)] @@ -262,6 +270,10 @@ fn default_move_target() -> String { "group".into() } +fn default_pen_path_op() -> String { + "newLayer".into() +} + fn default_curve_fit() -> f32 { 2.0 } @@ -402,6 +414,7 @@ impl Default for ToolOptions { finger_painting: false, enhance_edge: false, vector_mode: "path".into(), + pen_path_op: default_pen_path_op(), shape_fill: true, stroke_width: 0.0, shape_stroke: Default::default(), @@ -422,6 +435,7 @@ impl Default for ToolOptions { move_auto_select: true, move_target: default_move_target(), move_show_transform: false, + transform_interpolation: None, crop_ratio: String::new(), crop_custom_ratio_width: 0.0, crop_custom_ratio_height: 0.0, diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9b435ed283..2c08f63faa 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -363,7 +363,9 @@ impl Tokens { radius_lg: 12.0, bevel: false, pro: false, - round_chips: true, + // Studio Dark uses the compact overlapping square foreground/background + // chips rather than the large stacked circles (#3494). + round_chips: false, tab_strip: Color32::TRANSPARENT, row_selected: Color32::TRANSPARENT, histogram_bg: Color32::from_rgb(14, 14, 15), diff --git a/crates/ui-egui/src/theme/tests.rs b/crates/ui-egui/src/theme/tests.rs index e6b548089d..d869649853 100644 --- a/crates/ui-egui/src/theme/tests.rs +++ b/crates/ui-egui/src/theme/tests.rs @@ -191,6 +191,14 @@ fn applying_a_palette_clears_a_pinned_native_appearance_preference() { } } +#[test] +fn studio_dark_keeps_square_colour_chips() { + assert!(!Tokens::for_kind(ThemeKind::Studio).round_chips); + // Only the dark variant changes; the light palette retains its layout. + assert!(Tokens::for_kind(ThemeKind::StudioLight).round_chips); + assert!(!Tokens::for_kind(ThemeKind::Pro).round_chips); +} + #[test] fn studio_text_contrast_is_high() { let t = Tokens::for_kind(ThemeKind::Studio); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 27dfed9190..9131f1c674 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -28,6 +28,7 @@ pub mod move_hover; pub mod move_lock; pub mod move_mods; pub mod object_finder; +pub mod path_components; pub mod perspective_crop_ui; pub mod perspective_ui; pub mod puppet_ui; diff --git a/crates/ui-egui/src/tools/align_bar.rs b/crates/ui-egui/src/tools/align_bar.rs index 0a8ca4b3be..ebe159471e 100644 --- a/crates/ui-egui/src/tools/align_bar.rs +++ b/crates/ui-egui/src/tools/align_bar.rs @@ -29,18 +29,20 @@ const DISTRIBUTE: [(&str, &str, &str); 8] = [ ]; /// 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). 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, 24.0, 16.0, false, &tip)).inner.clicked() { + 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(ui, "ellipsis", 24.0, false, tl!("Align and distribute")); + let more = icons::button_with_icon_size(ui, "ellipsis", 28.0, 20.0, false, tl!("Align and distribute")); egui::Popup::menu(&more).show(|ui| { ui.set_min_width(200.0); let mut section = |ui: &mut egui::Ui, title: &str, items: &[(&str, &str, &str)]| { diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index 62384c330a..e280b3382c 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -1,6 +1,6 @@ //! Add Anchor Point and Delete Anchor Point tools (P group with the Pen, #1044), as in Photoshop. -//! They edit the paths Direct Selection edits, front first: the targeted vector mask or the active -//! shape layer's path, then the work path. +//! They edit the paths Direct Selection edits, front first: the work or saved path selected in the +//! Paths panel, the targeted vector mask or the active shape layer's path, then the work path. //! //! * Add Anchor Point: hovering a segment highlights it and shows where the anchor would go; a //! click inserts it there (`path.addAnchor`). A curve is split without changing its shape. @@ -38,9 +38,7 @@ pub fn effective(tool: Tool, mods: Modifiers) -> Option { /// segment (Add) or anchor (Delete) hit on it. An anchor hit with Add, or a segment with Delete, /// edits nothing. fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - let (r, path, hit) = - crate::direct_select::candidates(app).into_iter().find_map(|(r, path)| edit::hit(&path, Point::new(p[0], p[1]), tol, &[]).map(|h| (r, path, h)))?; + let (r, path, hit) = crate::direct_select::hit_target(app, p, false)?; match (tool, hit) { (Tool::AddAnchorPoint, Hit::Segment(..)) | (Tool::DeleteAnchorPoint, Hit::Anchor(_)) => Some((r, path, hit)), _ => None, @@ -135,12 +133,12 @@ fn apply(app: &mut PhotocraftApp, r: PathRef, hit: Hit) { Hit::Handle(..) => return, }; // A hit right at a segment's end is an anchor (anchors win the hit test), so `t` is inside. - if let (Some(o), Some(t)) = (params.as_object_mut(), r.params().as_object()) { + if let (Some(o), Some(t)) = (params.as_object_mut(), r.params(app).as_object()) { o.extend(t.clone()); } match app.run(id, params) { // The anchors shift: a Direct Selection on this path would point at the wrong ones. - Ok(_) if app.ui.direct_selection.target == Some(r) => app.ui.direct_selection = DirectSelection { target: Some(r), ..Default::default() }, + Ok(_) if app.ui.direct_selection.target.as_ref() == Some(&r) => app.ui.direct_selection = DirectSelection { target: Some(r), ..Default::default() }, Ok(_) => {} Err(e) => { app.ui.status = e; diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index c21cc5aaf6..02d0f45dc8 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -231,6 +231,32 @@ fn the_pen_cursor_shows_what_auto_add_delete_would_do() { assert_eq!(badge(&app, Tool::Pen, Modifiers::NONE), None); } +#[test] +fn add_and_delete_anchor_tools_edit_the_selected_saved_path() { + let mut app = app(Tool::AddAnchorPoint); + with_path(&mut app); + let before_work = work(&app); + let path = photocraft_engine::vector_cmds::path_json(&before_work); + app.run("path.set", json!({"name":"Saved", "path":path})).unwrap(); + app.ui.selected_path = Some("Saved".into()); + let n = steps(&app); + click(&mut app, [80.0, 120.0], Modifiers::NONE); + let saved = || app.session.active().unwrap().doc.paths.iter().find(|path| path.name == "Saved").unwrap().path.clone(); + let added = saved(); + assert_eq!(added.subpaths[0].knots.len(), 5); + assert_eq!(work(&app), before_work); + assert_eq!(steps(&app), n + 1); + app.ui.tool = Tool::DeleteAnchorPoint; + let anchor = added.subpaths[0].knots[3].anchor; + click(&mut app, [anchor.x, anchor.y], Modifiers::NONE); + let deleted = app.session.active().unwrap().doc.paths.iter().find(|path| path.name == "Saved").unwrap().path.clone(); + assert_eq!(deleted.subpaths[0].knots.len(), 4); + assert_eq!(work(&app), before_work); + assert_eq!(steps(&app), n + 2); + assert!(app.session.undo()); + assert_eq!(app.session.active().unwrap().doc.paths.iter().find(|path| path.name == "Saved").unwrap().path, added); +} + fn pen_anchors(app: &PhotocraftApp) -> Vec<[f64; 2]> { app.ui.pen.as_ref().map(|p| p.knots.iter().map(|k| k[0]).collect()).unwrap_or_default() } diff --git a/crates/ui-egui/src/tools/brush_resize.rs b/crates/ui-egui/src/tools/brush_resize.rs index 0878c6167e..e22faf2347 100644 --- a/crates/ui-egui/src/tools/brush_resize.rs +++ b/crates/ui-egui/src/tools/brush_resize.rs @@ -49,9 +49,10 @@ pub fn is_gesture(mods: egui::Modifiers) -> bool { } /// Alt (Option) with the right button: Photoshop's Windows gesture (#297). The left button with -/// Alt alone stays the painting tools' eyedropper. +/// Alt alone stays the painting tools' eyedropper. Shift+Alt+right is Photoshop's HUD Color +/// Picker (#6098), so Shift disqualifies the resize gesture. pub fn is_right_gesture(mods: egui::Modifiers) -> bool { - mods.alt + mods.alt && !mods.shift } /// The diameter and hardness a drag from `start` by (`dx`, `dy`) document pixels gives at `zoom`. @@ -168,6 +169,37 @@ fn preview_tint(app: &PhotocraftApp) -> Color32 { }) } +/// Liquify density preview, kept separate from the paint engine's hardness falloff. +/// A round tip of `radius` screen points: solid out to `hardness` of the radius, fading to clear +/// at the edge. One mesh (two rings and a centre), so its cost doesn't grow with the brush. +pub(crate) fn liquify_tip_preview(painter: &egui::Painter, c: Pos2, radius: f32, hardness: f32, color: Color32) { + let clip = painter.clip_rect(); + if !clip.expand(radius).contains(c) { + return; + } + // Enough segments for a smooth edge at any size, capped so huge brushes stay cheap. + let n = ((radius * 0.5) as usize).clamp(24, 160); + let inner = radius * hardness.clamp(0.0, 1.0); + let clear = Color32::TRANSPARENT; + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(c, color); + for k in 0..n { + let a = k as f32 / n as f32 * std::f32::consts::TAU; + let d = vec2(a.cos(), a.sin()); + mesh.colored_vertex(c + d * inner, color); + mesh.colored_vertex(c + d * radius, clear); + } + let n = n as u32; + for k in 0..n { + let (i0, o0) = (1 + 2 * k, 2 + 2 * k); + let (i1, o1) = (1 + 2 * ((k + 1) % n), 2 + 2 * ((k + 1) % n)); + mesh.add_triangle(0, i0, i1); + mesh.add_triangle(i0, o0, o1); + mesh.add_triangle(i0, o1, i1); + } + painter.add(mesh); +} + /// The round tip as the brush engine paints it: `radius` document pixels at `zoom` screen points /// per document pixel, solid out to its core and then the engine's falloff (`tip_falloff`) out to /// its reach, past the radius for a soft tip, so the disc shows what a dab of this hardness covers. diff --git a/crates/ui-egui/src/tools/brush_resize/tests.rs b/crates/ui-egui/src/tools/brush_resize/tests.rs index bf6cacc396..3cba8bef99 100644 --- a/crates/ui-egui/src/tools/brush_resize/tests.rs +++ b/crates/ui-egui/src/tools/brush_resize/tests.rs @@ -422,3 +422,26 @@ fn stylus_barrel_button_resizes_with_alt_and_never_samples_color() { h.run_steps(2); assert!(h.state().brush_resize.is_none()); } + +/// Liquify density keeps its radius-bounded preview; the paint engine's soft-brush reach is +/// deliberately used only by the paint HUD. +#[test] +fn liquify_density_preview_stays_inside_its_radius() { + let ctx = egui::Context::default(); + let radius = 50.0; + let mut output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.painter().with_clip_rect(egui::Rect::from_center_size(Pos2::ZERO, vec2(400.0, 400.0))); + liquify_tip_preview(&painter, Pos2::ZERO, radius, 0.0, Color32::RED); + }); + output.textures_delta.clear(); + let mesh = output + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) => Some(mesh), + _ => None, + }) + .expect("the Liquify preview is drawn"); + assert!(mesh.vertices.iter().all(|v| v.pos.to_vec2().length() <= radius + 0.01)); + assert!(mesh.vertices.iter().any(|v| v.pos.to_vec2().length() >= radius - 0.01)); +} diff --git a/crates/ui-egui/src/tools/cam_transform.rs b/crates/ui-egui/src/tools/cam_transform.rs index 9f853b153c..d6e58bd1fd 100644 --- a/crates/ui-egui/src/tools/cam_transform.rs +++ b/crates/ui-egui/src/tools/cam_transform.rs @@ -51,7 +51,7 @@ pub(crate) fn begin(app: &mut PhotocraftApp, offset: [i32; 2]) -> bool { rect: r, quad: [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]], pivot: [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0], - interpolation: "bilinear".into(), + interpolation: crate::transform_tool::default_interpolation(app).into(), warp: None, selection: false, target: None, diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 577ecda468..86df553ddc 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -41,17 +41,24 @@ pub enum PathRef { Layer(u64), /// A type layer's Type Path (#9114), apart from a vector mask the layer may have. TypePath(u64), + /// A saved path, by its index in the document's `paths`: the one selected in the Paths panel. + Saved(usize), /// The Pen path being drawn (`ui.pen`): edited in place, not through the engine. Pen, } impl PathRef { - /// The engine's target params for this path. - pub(crate) fn params(self) -> Value { + /// The engine's target params for this path. A saved path goes by its name; one that is gone + /// gets an empty name, which the engine refuses. + pub(crate) fn params(self, app: &PhotocraftApp) -> Value { match self { PathRef::Work => json!({"name": "work"}), PathRef::Layer(id) => json!({"name": "layer", "layer": id}), PathRef::TypePath(id) => json!({"name": "layer", "layer": id, "typePath": true}), + PathRef::Saved(i) => { + let name = app.session.active().and_then(|st| st.doc.paths.get(i)).map(|p| p.name.clone()).unwrap_or_default(); + json!({"name": name}) + } // Never sent: edits to the Pen path being drawn don't go through the engine. PathRef::Pen => json!({}), } @@ -74,6 +81,94 @@ pub struct DirectSelection { /// adds the anchor it then drags, and both are one step. #[serde(skip)] pub coalesce: Option, + #[serde(skip)] + pub(crate) owner: Option, + #[serde(skip)] + pub(crate) cancelled_drag: bool, +} + +/// Runtime selection ownership is never restored from settings onto another document. +#[derive(Clone, Debug)] +pub(crate) struct Owner { + document: photocraft_doc::DocId, + source: std::sync::Weak, + revision: u64, + layer: Option, + selected_path: Option, + vector_mask: bool, + tool: Tool, +} + +impl PartialEq for Owner { + fn eq(&self, other: &Self) -> bool { + self.source.ptr_eq(&other.source) + && (self.document, self.revision, self.layer, &self.selected_path, self.vector_mask, self.tool) + == (other.document, other.revision, other.layer, &other.selected_path, other.vector_mask, other.tool) + } +} + +impl Owner { + pub(crate) fn current(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + Some(Self { + document: st.doc.id, + source: std::sync::Arc::downgrade(&st.doc), + revision: st.revision, + layer: st.active_layer, + selected_path: app.ui.selected_path.clone(), + vector_mask: app.ui.vector_mask_target || st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::VectorMask, + tool: app.ui.tool, + }) + } + + fn same_target(&self, app: &PhotocraftApp) -> bool { + self.same_path_target(app) && app.ui.tool == self.tool + } + + fn same_path_target(&self, app: &PhotocraftApp) -> bool { + app.session.active().is_some_and(|st| { + st.doc.id == self.document + && st.active_layer == self.layer + && (app.ui.vector_mask_target || st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::VectorMask) == self.vector_mask + }) && app.ui.selected_path == self.selected_path + } + + fn valid(&self, app: &PhotocraftApp) -> bool { + self.valid_path(app) && app.ui.tool == self.tool + } + + fn valid_path(&self, app: &PhotocraftApp) -> bool { + self.same_path_target(app) + && app.session.active().is_some_and(|st| st.revision == self.revision && self.source.ptr_eq(&std::sync::Arc::downgrade(&st.doc))) + } +} + +/// Is `ds` still about the document, revision and target it was made on? Convert Point works on +/// the handles selected with Direct Selection, so an idle selection crosses those two tools; a +/// drag keeps its own tool. +pub(crate) fn still_valid(app: &PhotocraftApp, ds: &DirectSelection) -> bool { + ds.owner.as_ref().is_some_and(|owner| owner.valid(app) || (ds.drag.is_none() && owns(owner.tool) && owns(app.ui.tool) && owner.valid_path(app))) +} + +/// Clear stale anchors and gestures, keeping the pointer until the old release arrives. True +/// when a drag was cancelled. +pub(crate) fn cancel_stale(app: &mut PhotocraftApp) -> bool { + let ds = &app.ui.direct_selection; + let empty = ds.target.is_none() && ds.anchors.is_empty() && ds.segment.is_none() && ds.drag.is_none(); + if (ds.owner.is_none() && empty) || still_valid(app, ds) { + return false; + } + let cancelled_drag = ds.cancelled_drag || ds.drag.is_some(); + app.ui.direct_selection = DirectSelection { cancelled_drag, ..Default::default() }; + cancelled_drag +} + +/// Rebind a selection to the revision its own command made; another target or tool drops it. +pub(crate) fn keep_after_command(app: &mut PhotocraftApp, mut selection: DirectSelection) { + if selection.owner.as_ref().is_some_and(|owner| owner.same_target(app)) { + selection.owner = Owner::current(app); + app.ui.direct_selection = selection; + } } #[derive(Clone, Debug, PartialEq)] @@ -174,12 +269,20 @@ pub(crate) fn active_paths(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { .or_else(|| crate::vector_ui::active_shape_path(app)) .map(|(id, p)| (PathRef::Layer(id), p)) .or_else(|| crate::vector_ui::active_type_path(app).map(|(id, p)| (PathRef::TypePath(id), p))); - let work = app.session.active().and_then(|st| st.doc.work_path.clone()).filter(|_| crate::vector_ui::work_path_shown(app)); - layer.into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() + let saved = crate::vector_ui::selected_saved_path_index(app).map(|(i, p)| (PathRef::Saved(i), p)); + let work = app.session.active().and_then(|st| st.doc.work_path.clone()).filter(|_| crate::vector_ui::work_path_shown(app)).map(|p| (PathRef::Work, p)); + let mut out: Vec<_> = saved.into_iter().chain(layer).chain(work).collect(); + if app.ui.selected_path.as_deref() == Some("work") + && let Some(index) = out.iter().position(|(target, _)| *target == PathRef::Work) + { + out.swap(0, index); + } + out.retain(|(target, _)| writable(app, target)); + out } -/// The paths Direct Selection edits, front first: the Pen path being drawn, the active paths, then -/// every visible shape layer. +/// The paths Direct Selection edits, front first: the Pen path being drawn, the active paths, every +/// visible shape layer, then the work path. pub(crate) fn candidates(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { let active = app.session.active().map(|st| st.doc.id); let pen = app @@ -201,10 +304,37 @@ pub(crate) fn candidates(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { out.push((PathRef::Layer(l.id.0), sh.path.clone())); } } + if !out.iter().any(|(r, _)| *r == PathRef::Work) { + out.extend(st.doc.work_path.clone().map(|p| (PathRef::Work, p))); + } } out } +/// Can `target` be edited: a layer's path only while the layer is not locked. +pub(crate) fn writable(app: &PhotocraftApp, target: &PathRef) -> bool { + match target { + PathRef::Layer(id) | PathRef::TypePath(id) => app.session.active().is_some_and(|st| { + let id = photocraft_doc::LayerId(*id); + let locks = st.doc.effective_locks(id); + st.doc.layer(id).is_some() && !locks.all && !locks.pixels + }), + _ => app.session.active().is_some(), + } +} + +/// The frontmost editable path under `p` and what is hit on it: the handles shown on a selection +/// still valid count when `handles` is set. The hover and the press share it. +pub(crate) fn hit_target(app: &PhotocraftApp, p: [f64; 2], handles: bool) -> Option<(PathRef, Path, Hit)> { + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + let ds = &app.ui.direct_selection; + let valid = handles && still_valid(app, ds); + candidates(app).into_iter().filter(|(r, _)| writable(app, r)).find_map(|(r, path)| { + let shown = if valid && ds.target.as_ref() == Some(&r) { shown_handles(ds, &path) } else { Vec::new() }; + edit::hit(&path, Point::new(p[0], p[1]), tol, &shown).map(|h| (r, path, h)) + }) +} + fn retracted(k: &photocraft_doc::Knot, h: Handle) -> bool { let c = if h == Handle::In { k.in_ctrl } else { k.out_ctrl }; (c.x - k.anchor.x).abs() < 1e-9 && (c.y - k.anchor.y).abs() < 1e-9 @@ -230,6 +360,18 @@ fn shown_handles(ds: &DirectSelection, path: &Path) -> Vec<([usize; 2], Handle)> /// Canvas pointer events for Direct Selection and the Pen's ⌘ / ⌥ modes; false when the event is /// not theirs. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool { + cancel_stale(app); + if app.ui.direct_selection.cancelled_drag { + // The rest of a gesture cancelled on another document or target goes nowhere. + match ev { + ToolEvent::Down { .. } => app.ui.direct_selection.cancelled_drag = false, + ToolEvent::Up { .. } => { + app.ui.direct_selection.cancelled_drag = false; + return true; + } + ToolEvent::Move { .. } => return true, + } + } let tool = app.ui.tool; match ev { ToolEvent::Down { x, y, .. } => { @@ -244,12 +386,20 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool } if !pen_idle && tool != Tool::DirectSelection && !hits_pen(app, [x, y]) { // ⌘-click off the path being drawn ends it, which becomes editable, as in - // Photoshop. A press on it edits it in place and the Pen carries on (#4022). - crate::vector_ui::pen_commit(app, false); + // Photoshop. A press on it edits it in place and the Pen carries on (#4022). A + // refused commit keeps the draft and the press does nothing more. + if !crate::vector_ui::pen_commit(app, false) { + app.ui.direct_selection.cancelled_drag = true; + return true; + } } if tool == Tool::FreeformPen { // The same for a Freeform Pen path waiting for its next ⌥-click. crate::lasso_ui::commit(app); + if app.ui.pen.is_some() { + app.ui.direct_selection.cancelled_drag = true; + return true; + } } press(app, [x, y], mods, convert) } @@ -283,29 +433,21 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool /// Does a press at `p` hit the Pen path being drawn: one of its anchors, shown handles or segments? fn hits_pen(app: &PhotocraftApp, p: [f64; 2]) -> bool { - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - let ds = &app.ui.direct_selection; - candidates(app).into_iter().filter(|(r, _)| *r == PathRef::Pen).any(|(r, path)| { - let handles = if ds.target == Some(r) { shown_handles(ds, &path) } else { Vec::new() }; - edit::hit(&path, Point::new(p[0], p[1]), tol, &handles).is_some() - }) + hit_target(app, p, true).is_some_and(|(r, ..)| r == PathRef::Pen) } /// A press: pick what's under the pointer and start a drag. False lets the Pen handle a ⌥-press /// that hit nothing; the Convert Point tool has nothing else to do, so it keeps the press. fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) -> bool { let own_tool = app.ui.tool == Tool::ConvertPoint; - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - let ds = &app.ui.direct_selection; - let found = candidates(app).into_iter().find_map(|(r, path)| { - let handles = if ds.target == Some(r) { shown_handles(ds, &path) } else { Vec::new() }; - edit::hit(&path, Point::new(p[0], p[1]), tol, &handles).map(|h| (r, path, h)) - }); - let Some((target, base, hit)) = found else { + let Some((target, base, hit)) = hit_target(app, p, true) else { if convert { return own_tool; } - app.ui.direct_selection.drag = Some(Drag::Marquee { start: p, end: p, add: mods.shift }); + let owner = Owner::current(app); + let ds = &mut app.ui.direct_selection; + ds.drag = Some(Drag::Marquee { start: p, end: p, add: mods.shift }); + ds.owner = owner; return true; }; if let PathRef::Layer(id) | PathRef::TypePath(id) = target @@ -313,10 +455,12 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - { let _ = app.run("layer.select", json!({"layer": id})); } + let owner = Owner::current(app); let ds = &mut app.ui.direct_selection; - if ds.target != Some(target) { + if ds.target.as_ref() != Some(&target) { *ds = DirectSelection { target: Some(target), ..Default::default() }; } + ds.owner = owner; let edit = match hit { Hit::Handle(k, h) => { let kn = base.subpaths.get(k[0]).and_then(|s| s.knots.get(k[1])); @@ -393,7 +537,7 @@ pub fn curvature_hover(app: &PhotocraftApp, p: [f64; 2], mods: Modifiers) -> Opt pub(crate) fn curvature_toggle_active(app: &mut PhotocraftApp, p: [f64; 2]) { let Some((target, _, Hit::Anchor([s, k]))) = curvature_target(app, p) else { return }; let mut params = json!({"subpath": s, "knot": k, "curvature": true}); - if let (Some(o), Some(tp)) = (params.as_object_mut(), target.params().as_object()) { + if let (Some(o), Some(tp)) = (params.as_object_mut(), target.params(app).as_object()) { o.extend(tp.clone()); } if let Err(e) = app.run("path.convertPoint", params) { @@ -416,7 +560,7 @@ fn curvature_press(app: &mut PhotocraftApp, p: [f64; 2]) -> bool { Hit::Segment([s, k], t) => { let key = format!("curvature-add-{}", app.ui.alloc_id()); let mut params = json!({"subpath": s, "knot": k, "t": t.clamp(0.01, 0.99), "coalesce": key}); - if let (Some(o), Some(tp)) = (params.as_object_mut(), target.params().as_object()) { + if let (Some(o), Some(tp)) = (params.as_object_mut(), target.params(app).as_object()) { o.extend(tp.clone()); } let added = match app.run("path.addAnchor", params) { @@ -437,7 +581,7 @@ fn curvature_press(app: &mut PhotocraftApp, p: [f64; 2]) -> bool { } Hit::Handle(..) => return false, }; - app.ui.direct_selection = DirectSelection { target: Some(target), anchors: vec![k], coalesce, ..Default::default() }; + app.ui.direct_selection = DirectSelection { target: Some(target), anchors: vec![k], coalesce, owner: Owner::current(app), ..Default::default() }; app.ui.direct_selection.drag = Some(Drag::Edit { target, base, edit: Edit::Curvature(vec![k]), start: p, end: p, preview: None }); true } @@ -465,15 +609,24 @@ fn release(app: &mut PhotocraftApp, target: PathRef, base: &Path, edit: &Edit, s _ if !moved => return, e => e.command(start, end), }; - if let (Some(p), Some(t)) = (params.as_object_mut(), target.params().as_object()) { + if let (Some(p), Some(t)) = (params.as_object_mut(), target.params(app).as_object()) { p.extend(t.clone()); } if let (Some(p), Some(key)) = (params.as_object_mut(), app.ui.direct_selection.coalesce.take()) { p.insert("coalesce".into(), json!(key)); } - if let Err(e) = app.run(id, params) { - app.ui.status = e; - app.ui.status_error = true; + // sync_views checks ownership while the command runs: keep this selection off the live UI + // until its own command is done, then bind it to the revision that made. + let selection = std::mem::take(&mut app.ui.direct_selection); + match app.run(id, params) { + Ok(_) => keep_after_command(app, selection), + Err(e) => { + if selection.owner.as_ref().is_some_and(|owner| owner.valid(app)) { + app.ui.direct_selection = selection; + } + app.ui.status = e; + app.ui.status_error = true; + } } } @@ -482,9 +635,10 @@ fn release(app: &mut PhotocraftApp, target: PathRef, base: &Path, edit: &Edit, s fn marquee(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], add: bool) { let rect = [start[0], start[1], end[0], end[1]]; let hits = candidates(app).into_iter().map(|(r, path)| (r, edit::anchors_in(&path, rect))).find(|(_, a)| !a.is_empty()); + let owner = Owner::current(app); let ds = &mut app.ui.direct_selection; match hits { - Some((r, anchors)) if add && ds.target == Some(r) => { + Some((r, anchors)) if add && ds.target.as_ref() == Some(&r) => { for a in anchors { if !ds.anchors.contains(&a) { ds.anchors.push(a); @@ -499,17 +653,26 @@ fn marquee(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], add: bool) { ds.segment = None; } } + ds.owner = owner; } /// Arrow keys with Direct Selection and selected anchors (#4486), as in Photoshop: nudge them /// 1 px (⇧ 10 px) through `path.moveAnchors`, one history step per press. Not while a drag is /// in progress. Returns true when a key was used. pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + cancel_stale(app); let ds = &app.ui.direct_selection; let Some(target) = ds.target.filter(|_| app.ui.tool == Tool::DirectSelection && !ds.anchors.is_empty() && ds.drag.is_none()) else { return false; }; - let anchors = ds.anchors.clone(); + // The anchors belong to a path the canvas no longer offers (another saved path picked in the + // Paths panel, the path deleted): drop them rather than nudge that path, or another one that + // took its index. + if !candidates(app).iter().any(|(r, _)| *r == target) { + app.ui.direct_selection = DirectSelection::default(); + return false; + } + let anchors = app.ui.direct_selection.anchors.clone(); use egui::Key; let keys = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)]; for (key, ux, uy) in keys { @@ -518,12 +681,18 @@ pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if ctx.input_mut(|i| i.consume_key(mods, key)) { let k = if mods.shift { 10.0 } else { 1.0 }; let mut params = json!({"anchors": anchors, "move": [ux * k, uy * k]}); - if let (Some(p), Some(t)) = (params.as_object_mut(), target.params().as_object()) { + if let (Some(p), Some(t)) = (params.as_object_mut(), target.params(app).as_object()) { p.extend(t.clone()); } - if let Err(e) = app.run("path.moveAnchors", params) { - app.ui.status = e; - app.ui.status_error = true; + // The nudge makes a new revision: the selection follows it, as after a drag. + let selection = std::mem::take(&mut app.ui.direct_selection); + match app.run("path.moveAnchors", params) { + Ok(_) => keep_after_command(app, selection), + Err(e) => { + app.ui.direct_selection = selection; + app.ui.status = e; + app.ui.status_error = true; + } } return true; } @@ -551,7 +720,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn F _ => path, }; crate::vector_ui::draw_outline(painter, &path, to_scr, accent); - let ours = ds.target == Some(r); + let ours = ds.target.as_ref() == Some(&r); for &(k, h) in if ours { shown_handles(ds, &path) } else { Vec::new() }.iter() { if let Some(kn) = path.subpaths.get(k[0]).and_then(|s| s.knots.get(k[1])) { let c = if h == Handle::In { kn.in_ctrl } else { kn.out_ctrl }; @@ -572,3 +741,70 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn F #[cfg(test)] mod tests; + +#[cfg(test)] +mod freeform_command_tests { + use super::*; + + /// Is a Direct Selection drag under way on the document and target it started on? + fn captured_drag(app: &PhotocraftApp) -> bool { + app.ui.direct_selection.drag.is_some() && app.ui.direct_selection.owner.as_ref().is_some_and(|owner| owner.valid(app)) + } + + fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + for name in ["work", "Saved drawing"] { + app.run("path.set", json!({"name": name, "path":{"subpaths":[{"knots":[[20,20],[120,20]]}]}})).unwrap(); + } + app.sync_views(); + app.ui.tool = tool; + app.ui.selected_path = Some("Saved drawing".into()); + app + } + + #[test] + fn command_with_freeform_and_curvature_edits_the_selected_saved_path_after_modifier_release() { + for tool in [Tool::FreeformPen, Tool::CurvaturePen] { + let mut app = app(tool); + let original = app.session.active().unwrap().doc.clone(); + let n = app.session.active().unwrap().history.past_len(); + let command = Modifiers { command: true, ctrl: true, ..Default::default() }; + assert!(pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, command)); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Saved(0))); + assert!(captured_drag(&app)); + assert!(pointer(&mut app, ToolEvent::Move { x: 30.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE)); + assert!(pointer(&mut app, ToolEvent::Up { x: 30.0, y: 40.0 }, Modifiers::NONE)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.work_path, original.work_path); + assert_eq!(st.doc.paths[0].path.subpaths[0].knots[0].anchor, Point::new(30.0, 40.0)); + assert_eq!(st.history.past_len(), n + 1); + assert!(app.ui.direct_selection.owner.as_ref().unwrap().valid(&app)); + assert!(!captured_drag(&app)); + assert!(app.session.undo()); + assert_eq!(app.session.active().unwrap().doc.paths, original.paths); + } + } + + #[test] + fn command_cannot_edit_an_existing_path_when_the_freeform_trace_failed_to_finish() { + let mut app = app(Tool::FreeformPen); + let original = app.session.active().unwrap().doc.clone(); + let n = app.session.active().unwrap().history.past_len(); + for [x, y] in [[40.0, 60.0], [1e40, 60.0], [140.0, 80.0]] { + assert!(crate::lasso_ui::pointer(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::ALT)); + assert!(crate::lasso_ui::pointer(&mut app, ToolEvent::Up { x, y }, Modifiers::ALT)); + } + let command = Modifiers { command: true, ctrl: true, ..Default::default() }; + assert!(pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, command)); + let pen = app.ui.pen.as_ref().expect("failed Freeform commit must preserve its fitted draft"); + assert!(pen.commit_failed && pen.owner.is_some()); + assert!(app.ui.direct_selection.drag.is_none()); + assert!(app.ui.direct_selection.cancelled_drag); + assert!(pointer(&mut app, ToolEvent::Up { x: 30.0, y: 40.0 }, command)); + assert!(app.ui.direct_selection.drag.is_none()); + assert_eq!(app.session.active().unwrap().doc.paths, original.paths); + assert_eq!(app.session.active().unwrap().doc.work_path, original.work_path); + assert_eq!(app.session.active().unwrap().history.past_len(), n); + } +} diff --git a/crates/ui-egui/src/tools/direct_select/tests.rs b/crates/ui-egui/src/tools/direct_select/tests.rs index 27a9fc59d8..c7c5dfec77 100644 --- a/crates/ui-egui/src/tools/direct_select/tests.rs +++ b/crates/ui-egui/src/tools/direct_select/tests.rs @@ -569,3 +569,251 @@ fn a_targeted_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { assert!((type_path(&app).subpaths[0].knots[1].anchor.x - 160.0).abs() < 1e-6); assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0)); } + +fn save_path(app: &mut PhotocraftApp) { + let path = photocraft_engine::vector_cmds::path_json(&work(app)); + app.run("path.set", json!({"name": "Saved", "path": path})).unwrap(); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|path| path.name == "Saved").unwrap().path.clone() +} + +/// The arrow keys nudge the anchors of the selected saved path, and the selection follows each +/// nudge's new revision; the work path stays. +#[test] +fn arrow_keys_nudge_the_selected_saved_path() { + let mut app = app(Tool::DirectSelection); + with_path(&mut app); + save_path(&mut app); + app.ui.selected_path = Some("Saved".into()); + click(&mut app, [40.0, 120.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Saved(0))); + let (work_before, n) = (work(&app), steps(&app)); + assert!(press(&mut app, egui::Key::ArrowRight, Modifiers::NONE)); + assert!(press(&mut app, egui::Key::ArrowRight, Modifiers::NONE)); + assert_eq!(saved(&app).subpaths[0].knots[3].anchor, Point::new(42.0, 120.0)); + assert_eq!(work(&app), work_before); + assert_eq!(steps(&app), n + 2); +} + +#[test] +fn selected_saved_and_work_paths_win_overlapping_shape_hits() { + for name in ["Saved", "work"] { + let mut app = app(Tool::DirectSelection); + app.ui.extras.snap = false; // This case isolates hit priority and exact anchor movement. + let id = app.run("shape.create", json!({"kind":"rect", "rect":[40,40,80,80]})).unwrap()["layer"].as_u64().unwrap(); + with_path(&mut app); + save_path(&mut app); + app.ui.selected_path = Some(name.into()); + let (before_work, before_saved, n) = (work(&app), saved(&app), steps(&app)); + let before_shape = app.run("shape.info", json!({"layer":id})).unwrap()["path"].clone(); + drag(&mut app, [40.0, 120.0], [55.0, 130.0], Modifiers::NONE); + let (actual, unchanged, target) = if name == "Saved" { (saved(&app), work(&app), PathRef::Saved(0)) } else { (work(&app), saved(&app), PathRef::Work) }; + assert_eq!(actual.subpaths[0].knots[3].anchor, Point::new(55.0, 130.0)); + assert_eq!(unchanged, if name == "Saved" { before_work.clone() } else { before_saved.clone() }); + assert_eq!(app.ui.direct_selection.target.as_ref(), Some(&target)); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.run("shape.info", json!({"layer":id})).unwrap()["path"], before_shape); + assert!(app.session.undo()); + assert_eq!(work(&app), before_work); + assert_eq!(saved(&app), before_saved); + app.sync_views(); + assert!(app.ui.direct_selection.anchors.is_empty(), "undo invalidates runtime anchor ownership"); + } +} + +fn start_command_drag(app: &mut PhotocraftApp) { + assert!(super::pointer(app, ToolEvent::Down { x: 40.0, y: 120.0, pressure: 1.0 }, Modifiers::COMMAND)); + assert!(matches!(app.ui.direct_selection.drag, Some(Drag::Edit { .. }))); +} + +fn consume_stale_drag(app: &mut PhotocraftApp) { + assert!(super::pointer(app, ToolEvent::Move { x: 60.0, y: 140.0, pressure: 1.0 }, Modifiers::NONE)); + assert!(super::pointer(app, ToolEvent::Up { x: 60.0, y: 140.0 }, Modifiers::NONE)); + assert!(app.ui.direct_selection.drag.is_none()); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert!(!app.ui.direct_selection.cancelled_drag); +} + +#[test] +fn direct_selection_cannot_apply_to_another_document_or_a_reopened_identity() { + for reopen in [false, true] { + let mut app = app(Tool::Pen); + with_path(&mut app); + let source = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + start_command_drag(&mut app); + if reopen { + app.session.close(0).unwrap(); + } + app.session.add_document((*source).clone(), None); + app.session.active_mut().unwrap().revision = revision; + let (before, n) = (work(&app), steps(&app)); + if !reopen { + assert_ne!(source.id, app.session.active().unwrap().doc.id); + } else { + assert_eq!(source.id, app.session.active().unwrap().doc.id, "a reopened document may preserve its ID"); + } + // The frame hook may cancel before the old pointer event arrives. + app.sync_views(); + consume_stale_drag(&mut app); + assert_eq!(work(&app), before); + assert_eq!(steps(&app), n); + assert!(app.ui.pen.is_none(), "an old release must not start a new Pen draft"); + if !reopen { + assert_eq!(app.session.documents()[0].doc.work_path.as_ref(), source.work_path.as_ref()); + } + } +} + +#[test] +fn external_revision_cancels_preview_and_preserves_the_new_path() { + let mut app = app(Tool::Pen); + with_path(&mut app); + start_command_drag(&mut app); + assert!(super::pointer(&mut app, ToolEvent::Move { x: 50.0, y: 130.0, pressure: 1.0 }, Modifiers::COMMAND)); + app.session.execute("path.moveAnchors", json!({"name":"work", "anchors":[[0,0]], "move":[-5,7]})).unwrap(); + let (before, n) = (work(&app), steps(&app)); + consume_stale_drag(&mut app); + assert_eq!(work(&app), before); + assert_eq!(steps(&app), n); + assert!(app.ui.pen.is_none()); +} + +#[test] +fn layer_path_and_tool_changes_cancel_the_owned_edit() { + for change in ["layer", "path", "vectorMask", "tool"] { + let mut app = app(Tool::Pen); + with_path(&mut app); + save_path(&mut app); + let first = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let second = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.select", json!({"layer":first.0})).unwrap(); + start_command_drag(&mut app); + match change { + "layer" => { + app.session.execute("layer.select", json!({"layer":second.0})).unwrap(); + } + "path" => app.ui.selected_path = Some("Saved".into()), + "vectorMask" => app.ui.vector_mask_target = true, + "tool" => app.ui.tool = Tool::Brush, + _ => panic!("unknown target-change fixture: {change}"), + } + let (before_work, before_saved, n) = (work(&app), saved(&app), steps(&app)); + consume_stale_drag(&mut app); + assert_eq!(work(&app), before_work, "{change}"); + assert_eq!(saved(&app), before_saved, "{change}"); + assert_eq!(steps(&app), n, "{change}"); + assert!(app.ui.pen.is_none()); + } +} + +#[test] +fn closing_a_document_and_changing_marquee_target_discard_old_events() { + let mut app = app(Tool::Pen); + with_path(&mut app); + start_command_drag(&mut app); + let closed = app.session.close(0).unwrap(); + app.sync_views(); + consume_stale_drag(&mut app); + assert_eq!(closed.doc.work_path.as_ref().unwrap().subpaths[0].knots[3].anchor, Point::new(40.0, 120.0)); + + app.session.add_document((*closed.doc).clone(), None); + app.sync_views(); + save_path(&mut app); + app.ui.tool = Tool::DirectSelection; + assert!(super::pointer(&mut app, ToolEvent::Down { x: 30.0, y: 110.0, pressure: 1.0 }, Modifiers::NONE)); + assert!(matches!(app.ui.direct_selection.drag, Some(Drag::Marquee { .. }))); + app.ui.selected_path = Some("Saved".into()); + let n = steps(&app); + consume_stale_drag(&mut app); + assert_eq!(steps(&app), n); +} + +#[test] +fn serialized_anchor_selection_has_no_runtime_ownership_and_is_not_restored() { + let mut app = app(Tool::DirectSelection); + with_path(&mut app); + click(&mut app, [40.0, 120.0], Modifiers::NONE); + let serialized = serde_json::to_value(&app.ui.direct_selection).unwrap(); + assert!(serialized.get("owner").is_none()); + assert!(serialized.get("drag").is_none()); + assert!(serialized.get("cancelled_drag").is_none()); + app.ui.direct_selection = serde_json::from_value(serialized).unwrap(); + assert!(app.ui.direct_selection.owner.is_none()); + super::cancel_stale(&mut app); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert!(app.ui.direct_selection.target.is_none()); +} + +#[test] +fn command_drag_after_failed_pen_commit_preserves_draft_and_existing_work_path() { + let mut app = app(Tool::Pen); + with_path(&mut app); + app.ui.extras.snap = false; + for [x, y] in [[1e40, 0.0], [40.0, 120.0]] { + tool_event(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x, y }, Modifiers::NONE); + } + let before_draft = app.ui.pen.as_ref().unwrap().knots.clone(); + let (before_work, n, revision) = (work(&app), steps(&app), app.session.active().unwrap().revision); + // ⌘ off the draft ends it (a press on it would edit it in place, #4022); here that fails. + tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, Modifiers::COMMAND); + assert!(app.ui.pen.as_ref().unwrap().commit_failed); + assert!(app.ui.direct_selection.drag.is_none(), "the press must not go on to edit the old work path"); + assert!(app.ui.direct_selection.cancelled_drag); + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 140.0, pressure: 1.0 }, Modifiers::COMMAND); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 140.0 }, Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, before_draft); + assert_eq!(work(&app), before_work); + assert_eq!(steps(&app), n); + assert_eq!(app.session.active().unwrap().revision, revision); + assert!(app.ui.status_error); + assert!(!app.ui.direct_selection.cancelled_drag); +} + +#[test] +fn switching_between_selection_and_convert_tools_cancels_an_in_flight_drag() { + for (from, to) in [(Tool::DirectSelection, Tool::ConvertPoint), (Tool::ConvertPoint, Tool::DirectSelection)] { + let mut app = app(from); + with_path(&mut app); + let (before, n) = (work(&app), steps(&app)); + tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 120.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.ui.direct_selection.drag.is_some()); + app.ui.tool = to; + app.sync_views(); + consume_stale_drag(&mut app); + assert_eq!((work(&app), steps(&app)), (before, n)); + } +} + +#[test] +fn the_convert_point_tool_edits_selected_saved_paths_without_changing_the_work_path() { + let mut app = app(Tool::ConvertPoint); + with_path(&mut app); + save_path(&mut app); + app.ui.selected_path = Some("Saved".into()); + let (before_work, before_saved, n) = (work(&app), saved(&app), steps(&app)); + click(&mut app, [120.0, 40.0], Modifiers::NONE); + assert_eq!(saved(&app).subpaths[0].knots[1], photocraft_doc::Knot::corner(120.0, 40.0)); + assert_eq!(work(&app), before_work); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Saved(0))); + assert!(app.session.undo()); + assert_eq!(saved(&app), before_saved); +} + +#[test] +fn changing_the_channel_vector_mask_target_cancels_an_owned_edit() { + let mut app = app(Tool::DirectSelection); + with_path(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 120.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.ui.direct_selection.drag.is_some()); + let (before, n) = (work(&app), steps(&app)); + app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::VectorMask; + assert!(!app.ui.vector_mask_target, "the channel target can change before the UI syncs its mask flag"); + consume_stale_drag(&mut app); + assert_eq!((work(&app), steps(&app)), (before, n)); +} diff --git a/crates/ui-egui/src/tools/eyedropper_ui.rs b/crates/ui-egui/src/tools/eyedropper_ui.rs index 1a225592af..10fcaaa603 100644 --- a/crates/ui-egui/src/tools/eyedropper_ui.rs +++ b/crates/ui-egui/src/tools/eyedropper_ui.rs @@ -94,6 +94,32 @@ mod tests { tool_event(app, ToolEvent::Up { x, y }, mods); } + #[test] + fn mask_sampling_sets_gray_swatches_without_changing_pixel_sampling() { + for depth in [8, 16, 32] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 20, "depth": depth, "background": "transparent"})).unwrap(); + app.session + .edit("red", |doc, _| { + let surface = doc.layers[0].surface_mut().unwrap(); + surface.fill_rect(photocraft_geom::Rect::new(0, 0, 20, 20), &photocraft_raster::from_rgba(&surface.format(), [1.0, 0.0, 0.0, 1.0])); + doc.layers[0].mask = Some(photocraft_doc::LayerMask::reveal_all()); + Ok(()) + }) + .unwrap(); + app.ui.tool = Tool::Eyedropper; + app.ui.mask_target = true; + click(&mut app, 5.0, 5.0, egui::Modifiers::NONE); + let gray = photocraft_color::convert::rgb_to_gray([1.0, 0.0, 0.0]); + assert_eq!(fg(&app), [gray, gray, gray, 1.0], "depth {depth}"); + click(&mut app, 5.0, 5.0, egui::Modifiers::ALT); + assert_eq!(app.session.tools.background, [gray, gray, gray, 1.0]); + app.ui.mask_target = false; + click(&mut app, 5.0, 5.0, egui::Modifiers::NONE); + assert_eq!(fg(&app), [1.0, 0.0, 0.0, 1.0]); + } + } + #[test] fn a_click_samples_the_average_of_the_sample_size() { let mut app = app(); diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index 4ea5da8a72..5bc7542761 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -845,7 +845,9 @@ fn stops_editor_for(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: F }, None => {} } - properties_panel::stop_fields(app, ui, sink); + // A preset invalidates an in-progress numeric draft from the old stop list. + let generation = ui.data(|d| d.get_temp::(selection_key.with("generation"))).unwrap_or_default(); + ui.push_id((selection_key, generation), |ui| properties_panel::stop_fields(app, ui, sink)); } /// A shared stop strip keeps previews local; its caller chooses the command or paint target. diff --git a/crates/ui-egui/src/tools/lasso_ui.rs b/crates/ui-egui/src/tools/lasso_ui.rs index 72f486378e..38dfaecdb1 100644 --- a/crates/ui-egui/src/tools/lasso_ui.rs +++ b/crates/ui-egui/src/tools/lasso_ui.rs @@ -155,7 +155,18 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool if !p.iter().all(|n| n.is_finite()) { return true; } + if tool == Tool::FreeformPen && matches!(ev, ToolEvent::Down { .. }) && !active(app) && crate::vector_ui::freeform_locked_shape(app) { + app.ui.status = tl!("Locked").into(); + app.ui.status_error = true; + return true; + } modifiers(app, mods); + // A fitted path whose commit failed remains the user's draft. Starting another trace + // must neither retry it automatically nor replace it on the next release. Releasing Alt + // in this press may itself have finished the previous trace into that failed draft. + if tool == Tool::FreeformPen && matches!(ev, ToolEvent::Down { .. }) && !active(app) && app.ui.pen.is_some() { + return true; + } match ev { ToolEvent::Down { .. } => { if active(app) { @@ -200,6 +211,9 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool let polygonal = mods.alt && nothing_selected; let intent = if polygonal { Modifiers { alt: false, ..mods } } else { mods }; let mut d = Drag::new(tool, p, vec![[p[0], p[1], 1.0]], intent, false); + if tool == Tool::FreeformPen { + d.capture_vector_owners(app); + } let document = app.session.active().map(|st| st.doc.id); d.lasso = Some(Lasso { cursor: p, down: true, polygonal, document, straight: Vec::new() }); app.drag = Some(d); diff --git a/crates/ui-egui/src/tools/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs index 71a5b68777..af1d45a2e0 100644 --- a/crates/ui-egui/src/tools/lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/lasso_ui/tests.rs @@ -170,6 +170,142 @@ fn mouse(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, kind: &str, x: f h.run_steps(2); } +fn freeform_harness() -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut h = harness(); + let app = h.state_mut(); + for name in ["work", "Saved drawing"] { + app.run("path.set", json!({"name": name, "path":{"subpaths":[{"knots":[[20,20],[220,20]]}]}})).unwrap(); + } + app.ui.tool = Tool::FreeformPen; + app.ui.tool_options.vector_mode = "path".into(); + app.ui.selected_path = Some("Saved drawing".into()); + app.ui.extras.snap = false; + h.run_steps(2); + h +} + +fn freeform_run_and_straight_click(h: &mut egui_kittest::Harness<'static, PhotocraftApp>) { + mouse(h, "down", 50.0, 50.0, Modifiers::NONE); + mouse(h, "move", 90.0, 40.0, Modifiers::NONE); + mouse(h, "move", 120.0, 50.0, Modifiers::NONE); + mouse(h, "up", 120.0, 50.0, Modifiers::ALT); + assert!(active(h.state()), "Alt-held release keeps the fitted path in progress"); + mouse(h, "down", 180.0, 100.0, Modifiers::ALT); + mouse(h, "up", 180.0, 100.0, Modifiers::ALT); + assert!(active(h.state())); +} + +#[test] +fn real_freeform_freehand_and_alt_straight_segments_append_to_the_owned_saved_path_once() { + let mut h = freeform_harness(); + let original = h.state().session.active().unwrap().doc.clone(); + let n = h.state().session.active().unwrap().history.past_len(); + freeform_run_and_straight_click(&mut h); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); + let app = h.state(); + assert!(!active(app) && app.ui.pen.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.work_path, original.work_path); + let path = &st.doc.paths[0].path; + assert_eq!(path.subpaths.len(), 2); + assert_eq!(path.subpaths[0], original.paths[0].path.subpaths[0]); + let knots = &path.subpaths[1].knots; + assert_eq!(knots.last().unwrap().anchor, photocraft_geom::Point::new(180.0, 100.0)); + assert_eq!(knots.last().unwrap().in_ctrl, knots.last().unwrap().anchor); + assert_eq!(knots[knots.len() - 2].out_ctrl, knots[knots.len() - 2].anchor); + assert_eq!(st.history.past_len(), n + 1); + assert!(h.state_mut().session.undo()); + assert_eq!(h.state().session.active().unwrap().doc.paths, original.paths); +} + +#[test] +fn real_freeform_stale_target_source_revision_and_document_cancel_without_finishing_elsewhere() { + for change in ["target", "source", "revision", "document"] { + let mut h = freeform_harness(); + freeform_run_and_straight_click(&mut h); + let app = h.state_mut(); + match change { + "target" => app.ui.selected_path = Some("work".into()), + "source" => { + let st = app.session.active_mut().unwrap(); + st.doc = std::sync::Arc::new((*st.doc).clone()); + } + "revision" => app.session.active_mut().unwrap().revision += 1, + "document" => { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + } + _ => panic!("unexpected stale-gesture test case: {change}"), + } + let source = h.state().session.active().unwrap().doc.clone(); + let n = h.state().session.active().unwrap().history.past_len(); + mouse(&mut h, "move", 200.0, 120.0, Modifiers::ALT); + mouse(&mut h, "up", 200.0, 120.0, Modifiers::NONE); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let app = h.state(); + assert!(!active(app) && app.ui.pen.is_none(), "{change}: no stale trace remains"); + assert!(std::sync::Arc::ptr_eq(&source, &app.session.active().unwrap().doc), "{change}: late input changed document pixels or paths"); + assert_eq!(app.session.active().unwrap().history.past_len(), n, "{change}"); + } +} + +#[test] +fn another_freeform_trace_cannot_replace_a_failed_owned_draft_or_retry_it_automatically() { + let mut app = app(); + app.ui.tool = Tool::FreeformPen; + app.ui.extras.snap = false; + for [x, y] in [[40.0, 60.0], [1e40, 60.0], [140.0, 80.0]] { + event(&mut app, "down", x, y, Modifiers::ALT); + event(&mut app, "up", x, y, Modifiers::ALT); + } + modifiers(&mut app, Modifiers::NONE); + let failed = app.ui.pen.clone().expect("invalid fitted trace must remain available"); + assert!(failed.commit_failed && failed.owner.is_some()); + assert!(!active(&app)); + let source = app.session.active().unwrap().doc.clone(); + let n = app.session.active().unwrap().history.past_len(); + let journal = app.session.journal.len(); + for middle in [[1e40, 90.0], [220.0, 90.0]] { + for [x, y] in [[160.0, 120.0], middle, [260.0, 140.0]] { + event(&mut app, "down", x, y, Modifiers::ALT); + event(&mut app, "move", x + 10.0, y + 10.0, Modifiers::ALT); + event(&mut app, "up", x, y, Modifiers::ALT); + assert!(!active(&app), "pending fitted draft owns the next drawing attempt"); + } + modifiers(&mut app, Modifiers::NONE); + assert_eq!(app.ui.pen.as_ref(), Some(&failed)); + assert!(std::sync::Arc::ptr_eq(&source, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), n); + assert_eq!(app.session.journal.len(), journal, "drawing must not retry the failed engine command"); + } +} + +#[test] +fn freeform_alt_release_in_the_next_press_keeps_the_failed_fit() { + let mut app = app(); + app.ui.tool = Tool::FreeformPen; + for [x, y] in [[40.0, 60.0], [1e40, 60.0], [140.0, 80.0]] { + event(&mut app, "down", x, y, Modifiers::ALT); + event(&mut app, "up", x, y, Modifiers::ALT); + } + assert!(active(&app)); + let source = app.session.active().unwrap().doc.clone(); + let n = app.session.active().unwrap().history.past_len(); + // No separate modifier-change event: this press both releases Alt and tries a new trace. + event(&mut app, "down", 200.0, 100.0, Modifiers::NONE); + let failed = app.ui.pen.clone().expect("failed fit must survive the press that finished it"); + assert!(failed.commit_failed && failed.owner.is_some()); + assert!(!active(&app)); + let journal = app.session.journal.len(); + event(&mut app, "move", 240.0, 120.0, Modifiers::NONE); + event(&mut app, "up", 240.0, 120.0, Modifiers::NONE); + assert_eq!(app.ui.pen.as_ref(), Some(&failed)); + assert_eq!(app.session.journal.len(), journal); + assert!(std::sync::Arc::ptr_eq(&source, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), n); +} + #[test] fn real_canvas_alt_clicks_enter_escape_and_resume() { for finish in ["enter", "escape", "resume", "close"] { diff --git a/crates/ui-egui/src/tools/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs index ff9d425f84..aef1f315ef 100644 --- a/crates/ui-egui/src/tools/move_hover.rs +++ b/crates/ui-egui/src/tools/move_hover.rs @@ -185,7 +185,7 @@ mod tests { assert_eq!(active_outline(&mut app, None, false, false), Some(a)); // When a drag or transform is in progress, no outline: - app.guide_drag = Some(crate::rulers::GuideDrag { vertical: false, index: None, pos: 10.0, press: 10.0, over_ruler: false }); + app.guide_drag = Some(crate::rulers::GuideDrag { vertical: false, index: None, pos: 10.0, press: 10.0, over_ruler: false, flipped: false }); assert_eq!(active_outline(&mut app, None, false, false), None); app.guide_drag = None; diff --git a/crates/ui-egui/src/tools/move_mods.rs b/crates/ui-egui/src/tools/move_mods.rs index 84bf2c085f..b134bb62fd 100644 --- a/crates/ui-egui/src/tools/move_mods.rs +++ b/crates/ui-egui/src/tools/move_mods.rs @@ -84,6 +84,11 @@ fn moving(app: &PhotocraftApp) -> bool { app.drag.as_ref().is_some_and(|d| d.tool == Tool::Move) } +/// The pointer reflects the pending copy, then the latched duplication for the whole drag. +pub fn copying(app: &PhotocraftApp, alt: bool) -> bool { + if moving(app) && app.move_mods.start.is_some() { app.move_mods.alt || app.move_mods.dup_from.is_some() } else { alt } +} + /// Duplicates the selected layers (the copies become the selection), remembering the history /// length before so [`fold_history`] can merge the copy and the move into one step. fn duplicate(app: &mut PhotocraftApp) -> Option { diff --git a/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs new file mode 100644 index 0000000000..33aef52d8d --- /dev/null +++ b/crates/ui-egui/src/tools/path_components.rs @@ -0,0 +1,217 @@ +//! Selected path components and their Path Operations, as in Photoshop. Path Selection (A) clicks a +//! component to select it (⇧ adds or removes one, a click off every component deselects) and drags +//! the selected components. With components selected, Path Selection's Path Operations menu and +//! its keys (`+` Combine Shapes, `-` Subtract Front Shape) change their operation through +//! `path.setOperation`, one History step; with none selected, and always with the Pen tools (which +//! show no component selection), they set how the next path is added. The first component always +//! combines, so it keeps its operation. The selection is Direct Selection's: every anchor of a +//! selected component. + +use egui::{Event, Key}; +use photocraft_doc::{Path, PathOp}; +use photocraft_geom::Point; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::direct_select::{DirectSelection, PathRef, active_paths}; +use crate::state::Tool; + +/// The `pen_path_op` value of an operation (`Join` belongs to its component's first subpath). +fn op_value(op: PathOp) -> &'static str { + match op { + PathOp::Combine | PathOp::Join => "combine", + PathOp::Subtract => "subtract", + PathOp::Intersect => "intersect", + PathOp::Exclude => "exclude", + } +} + +/// The path Path Selection selects in: the targeted vector mask or the active shape layer's +/// path, else the Work Path (`active_paths`, front first). +fn target(app: &PhotocraftApp) -> Option<(PathRef, Path)> { + active_paths(app).into_iter().next() +} + +/// The selected components: their path and the first subpath of each, in order. `None` with +/// nothing selected, a selection on a path that is not an active one any more, or a tool other +/// than Path Selection (the only one that shows it, so the only one that acts on it). +pub(crate) fn selected(app: &PhotocraftApp) -> Option<(PathRef, Path, Vec)> { + if app.ui.tool != Tool::PathSelection { + return None; + } + let sel = &app.ui.direct_selection; + if !crate::direct_select::still_valid(app, sel) { + return None; + } + let r = sel.target.filter(|r| *r != PathRef::Pen)?; + let (_, path) = active_paths(app).into_iter().find(|(p, _)| *p == r)?; + let components = path.components(); + let mut heads: Vec = sel.anchors.iter().filter_map(|[s, _]| components.iter().find(|c| c.contains(s)).map(|c| c.start)).collect(); + heads.sort_unstable(); + heads.dedup(); + (!heads.is_empty()).then_some((r, path, heads)) +} + +/// The operation every selected component has, for the menu's icon; `None` when they differ. +pub(crate) fn selected_op(app: &PhotocraftApp) -> Option<&'static str> { + let (_, path, heads) = selected(app)?; + let mut ops = heads.iter().filter(|h| **h < path.subpaths.len()).map(|h| op_value(path.effective_op(*h))); + let first = ops.next()?; + ops.all(|o| o == first).then_some(first) +} + +/// A Path Operations pick (menu or key): the selected components take `op`, and the tool keeps it +/// for the next path. New Layer is not an operation a component can have: it only sets the tool. +/// The first component always combines (it is what the others act on), so it keeps its operation. +pub(crate) fn set_op(app: &mut PhotocraftApp, op: &str) -> Result<(), String> { + app.ui.tool_options.pen_path_op = op.into(); + if op == "newLayer" { + return Ok(()); + } + let Some((r, path, heads)) = selected(app) else { return Ok(()) }; + let heads: Vec = heads.into_iter().filter(|h| *h != 0).collect(); + if heads.iter().all(|h| path.subpaths.get(*h).is_some_and(|s| op_value(s.op) == op)) { + return Ok(()); + } + let mut params = r.params(app); + params["subpaths"] = json!(heads); + params["op"] = json!(op); + run_selected_command(app, "path.setOperation", params) +} + +fn run_selected_command(app: &mut PhotocraftApp, id: &str, params: serde_json::Value) -> Result<(), String> { + let selection = std::mem::take(&mut app.ui.direct_selection); + let result = app.run(id, params); + if result.is_ok() || crate::direct_select::still_valid(app, &selection) { + crate::direct_select::keep_after_command(app, selection); + } + result.map(|_| ()) +} + +/// The component of `path` under `at`: on its outline within `tol`, else inside it. The frontmost +/// (last) component wins. +fn component_at(path: &Path, at: [f64; 2], tol: f64) -> Option> { + let components = path.components(); + if let Some(hit) = photocraft_vector::edit::hit(path, Point::new(at[0], at[1]), tol, &[]) { + let s = match hit { + photocraft_vector::edit::Hit::Anchor([s, _]) + | photocraft_vector::edit::Hit::Handle([s, _], _) + | photocraft_vector::edit::Hit::Segment([s, _], _) => s, + }; + return components.into_iter().find(|c| c.contains(&s)); + } + components.into_iter().rev().find(|c| { + // Even-odd over the component's flattened subpaths: a hole in it is not inside. + let crossings: usize = path + .subpaths + .get(c.clone()) + .unwrap_or_default() + .iter() + .filter(|s| s.closed) + .map(|s| crossings(&photocraft_vector::flatten::flatten_subpath(s, 0.25).pts, at)) + .sum(); + crossings % 2 == 1 + }) +} + +/// How many edges of the closed polygon `pts` a ray from `at` to the right crosses. +fn crossings(pts: &[(f64, f64)], at: [f64; 2]) -> usize { + let n = pts.len(); + (0..n) + .filter(|&i| { + let (Some(&(xi, yi)), Some(&(xj, yj))) = (pts.get(i), pts.get((i + 1) % n)) else { return false }; + (yi > at[1]) != (yj > at[1]) && at[0] < (xj - xi) * (at[1] - yi) / (yj - yi) + xi + }) + .count() +} + +/// Path Selection's press at `at`: selects the component there (⇧ adds or removes it). Pressing a +/// selected component keeps the selection, so the drag moves all of it; pressing off every +/// component deselects, unless ⇧ is held. +pub(crate) fn press(app: &mut PhotocraftApp, at: [f64; 2], shift: bool) { + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + let Some((r, path)) = target(app) else { + app.ui.direct_selection = DirectSelection::default(); + return; + }; + let current = selected(app).filter(|(sr, ..)| *sr == r).map(|(.., heads)| heads).unwrap_or_default(); + let Some(hit) = component_at(&path, at, tol) else { + if !shift { + app.ui.direct_selection = DirectSelection::default(); + } + return; + }; + let was_selected = current.contains(&hit.start); + let heads: Vec = match (shift, was_selected) { + (true, true) => current.into_iter().filter(|h| *h != hit.start).collect(), + (true, false) => current.into_iter().chain([hit.start]).collect(), + (false, true) => current, + (false, false) => vec![hit.start], + }; + let components = path.components(); + let anchors = components + .iter() + .filter(|c| heads.contains(&c.start)) + .flat_map(|c| c.clone()) + .flat_map(|s| (0..path.subpaths.get(s).map_or(0, |sp| sp.knots.len())).map(move |k| [s, k])) + .collect::>(); + app.ui.direct_selection = if anchors.is_empty() { + DirectSelection::default() + } else { + DirectSelection { target: Some(r), anchors, owner: crate::direct_select::Owner::current(app), ..Default::default() } + }; +} + +/// Path Selection's drag by `d` with components selected on the path it edits: moves those +/// components, one History step. `None` with none or all of them selected: the whole path moves +/// instead, which keeps a live rectangle or ellipse live. +pub(crate) fn move_selected(app: &mut PhotocraftApp, d: [f64; 2]) -> Option> { + let (r, path, heads) = selected(app)?; + if target(app).map(|(t, _)| t) != Some(r) || heads.len() >= path.components().len() { + return None; + } + let mut params = r.params(app); + params["anchors"] = json!(app.ui.direct_selection.anchors); + params["move"] = json!(d); + Some(run_selected_command(app, "path.moveAnchors", params)) +} + +/// Do `+` and `-` pick a Path Operation with `tool`? The tools whose options bar has the menu. +fn has_keys(tool: Tool) -> bool { + matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::PathSelection) +} + +/// Consumes this frame's `+` (Combine Shapes) and `-` (Subtract Front Shape) presses while a tool +/// with the Path Operations menu is active, as in Photoshop. `+` is ⇧= on many layouts and the +/// keypad's key on all, so ⇧ is allowed; with these tools ⇧+ / ⇧− step no blend mode. +pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + if !has_keys(app.ui.tool) { + return; + } + let ops: Vec<&str> = ctx.input_mut(|i| { + let mut out = Vec::new(); + i.events.retain(|e| match e { + Event::Key { key, pressed: true, modifiers, .. } if !modifiers.command && !modifiers.ctrl && !modifiers.alt => { + let op = match key { + Key::Plus => "combine", + Key::Equals if modifiers.shift => "combine", + Key::Minus => "subtract", + _ => return true, + }; + out.push(op); + false + } + _ => true, + }); + out + }); + for op in ops { + if let Err(e) = set_op(app, op) { + app.ui.status = e; + app.ui.status_error = true; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/tools/path_components/tests.rs b/crates/ui-egui/src/tools/path_components/tests.rs new file mode 100644 index 0000000000..e883cf6d4d --- /dev/null +++ b/crates/ui-egui/src/tools/path_components/tests.rs @@ -0,0 +1,324 @@ +//! Path components after they are drawn (feedback on #7648): Path Selection selects them, the +//! Path Operations menu and `+` / `-` change their operation, and the Pen carries on an open +//! shape path from its endpoint. + +use egui::Key; +use photocraft_doc::vector::PathOp; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::direct_select::PathRef; +use crate::state::Tool; +use crate::vector_ui::{pen_commit, pen_down, pen_up}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = Tool::Pen; + app.ui.tool_options.vector_mode = "shape".into(); + app +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64) { + pen_down(app, x, y, false); + pen_up(app); +} + +/// Clicks a closed square with the Pen, from `(x, y)` with side `side`. +fn square(app: &mut PhotocraftApp, x: f64, y: f64, side: f64) { + for (dx, dy) in [(0.0, 0.0), (side, 0.0), (side, side), (0.0, side), (0.5, 0.5)] { + click(app, x + dx, y + dy); + } +} + +fn shape(app: &PhotocraftApp) -> (LayerId, photocraft_doc::ShapeLayer) { + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + match &st.doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => (id, sh.clone()), + _ => panic!("not a shape layer"), + } +} + +fn ops(path: &Path) -> Vec { + path.subpaths.iter().map(|s| s.op).collect() +} + +fn covered(path: &Path, x: i32, y: i32) -> f32 { + photocraft_vector::fill_rasterizer(path, photocraft_vector::DEFAULT_TOLERANCE).render(photocraft_geom::Rect::from_xywh(x, y, 1, 1))[0] +} + +fn history(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// Feeds one key press through the app's shortcut handling. +fn key(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: egui::Modifiers) { + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, ctx); + ctx.end_pass().textures_delta.clear(); +} + +/// A body and an inner square drawn with Combine Shapes: the inner one is selected with Path +/// Selection and turned into a hole with the menu's Subtract Front Shape, one History step. +#[test] +fn a_selected_component_takes_the_picked_operation() { + let mut app = app(); + square(&mut app, 20.0, 20.0, 120.0); + app.ui.tool_options.pen_path_op = "combine".into(); + square(&mut app, 60.0, 60.0, 40.0); + let (id, sh) = shape(&app); + assert_eq!(covered(&sh.path, 80, 80), 1.0); + app.ui.tool = Tool::PathSelection; + super::press(&mut app, [80.0, 80.0], false); + let (r, _, heads) = super::selected(&app).expect("the inner square is selected"); + assert_eq!((r, heads), (PathRef::Layer(id.0), vec![1])); + let steps = history(&app); + super::set_op(&mut app, "subtract").unwrap(); + let (_, sh) = shape(&app); + assert_eq!(ops(&sh.path), [PathOp::Combine, PathOp::Subtract]); + assert_eq!((covered(&sh.path, 80, 80), covered(&sh.path, 30, 30)), (0.0, 1.0), "a hole"); + assert_eq!(history(&app), steps + 1); + assert_eq!(super::selected_op(&app), Some("subtract"), "the menu shows the component's"); + // Picking what it already has adds no step; New Layer only sets the tool. + super::set_op(&mut app, "subtract").unwrap(); + super::set_op(&mut app, "newLayer").unwrap(); + assert_eq!(history(&app), steps + 1); + assert!(app.session.undo()); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Combine]); +} + +/// `+` and `-` with the Pen tools or Path Selection: Combine Shapes and Subtract Front Shape, on +/// the selected components and for the next path. `+` arrives as ⇧= on a US keyboard, which +/// otherwise steps the blend mode; with the Move tool it still does. +#[test] +fn plus_and_minus_pick_combine_and_subtract() { + let ctx = egui::Context::default(); + let mut app = app(); + square(&mut app, 20.0, 20.0, 120.0); + app.ui.tool_options.pen_path_op = "combine".into(); + square(&mut app, 60.0, 60.0, 40.0); + app.ui.tool = Tool::PathSelection; + super::press(&mut app, [80.0, 80.0], false); + key(&mut app, &ctx, Key::Minus, egui::Modifiers::NONE); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Subtract]); + assert_eq!(app.ui.tool_options.pen_path_op, "subtract"); + key(&mut app, &ctx, Key::Equals, egui::Modifiers::SHIFT); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Combine]); + key(&mut app, &ctx, Key::Minus, egui::Modifiers::NONE); + key(&mut app, &ctx, Key::Plus, egui::Modifiers::NONE); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Combine], "the keypad's +"); + // With nothing selected the Pen's next path takes it. + app.ui.direct_selection = Default::default(); + app.ui.tool = Tool::Pen; + key(&mut app, &ctx, Key::Minus, egui::Modifiers::NONE); + assert_eq!(app.ui.tool_options.pen_path_op, "subtract"); + // The blend mode is the Move tool's to step. + let blend = |app: &PhotocraftApp| app.session.active().unwrap().doc.layer(shape(app).0).unwrap().blend; + let before = blend(&app); + key(&mut app, &ctx, Key::Equals, egui::Modifiers::SHIFT); + assert_eq!(blend(&app), before, "the Pen picks Combine, not a blend mode"); + assert_eq!(app.ui.tool_options.pen_path_op, "combine"); + app.ui.tool = Tool::Move; + key(&mut app, &ctx, Key::Equals, egui::Modifiers::SHIFT); + assert_ne!(blend(&app), before); + assert_eq!(app.ui.tool_options.pen_path_op, "combine"); +} + +/// ⇧-click adds and removes components, a click off them deselects, and a drag moves only the +/// selected ones. +#[test] +fn path_selection_selects_and_moves_components() { + let mut app = app(); + square(&mut app, 10.0, 10.0, 40.0); + app.ui.tool_options.pen_path_op = "combine".into(); + square(&mut app, 100.0, 10.0, 40.0); + square(&mut app, 100.0, 100.0, 40.0); + app.ui.tool = Tool::PathSelection; + let heads = |app: &PhotocraftApp| super::selected(app).map(|(.., h)| h).unwrap_or_default(); + super::press(&mut app, [30.0, 30.0], false); + super::press(&mut app, [120.0, 120.0], true); + assert_eq!(heads(&app), [0, 2]); + // Pressing a selected one keeps both, for the drag. + super::press(&mut app, [120.0, 120.0], false); + assert_eq!(heads(&app), [0, 2]); + crate::vector_ui::path_selection_finish(&mut app, [120.0, 120.0], [125.0, 130.0]); + let (_, sh) = shape(&app); + let first = |s: usize| sh.path.subpaths[s].knots[0].anchor; + assert_eq!((first(0).x, first(0).y), (15.0, 20.0)); + assert_eq!((first(1).x, first(1).y), (100.0, 10.0), "not selected: stays"); + assert_eq!((first(2).x, first(2).y), (105.0, 110.0)); + super::press(&mut app, [125.0, 130.0], true); + assert_eq!(heads(&app), [0]); + super::press(&mut app, [190.0, 190.0], false); + assert!(super::selected(&app).is_none(), "a click off every component deselects"); +} + +/// A selection left on a path that has fewer subpaths now (undone, edited elsewhere) selects +/// nothing and changes nothing, never panics. +#[test] +fn a_stale_selection_changes_nothing() { + let mut app = app(); + square(&mut app, 10.0, 10.0, 40.0); + let (id, _) = shape(&app); + app.ui.tool = Tool::PathSelection; + app.ui.direct_selection = crate::direct_select::DirectSelection { target: Some(PathRef::Layer(id.0)), anchors: vec![[5, 0]], ..Default::default() }; + assert!(super::selected(&app).is_none()); + let steps = history(&app); + super::set_op(&mut app, "subtract").unwrap(); + assert_eq!(history(&app), steps); + assert_eq!(super::move_selected(&mut app, [3.0, 3.0]), None); +} + +/// The first component always draws as Combine (feedback on #7648): selected alone, `-` and the +/// menu leave it as it is, with no History step, and the menu shows Combine; selected with +/// another, only the other takes the operation. +#[test] +fn the_first_component_keeps_combining() { + let ctx = egui::Context::default(); + let mut app = app(); + square(&mut app, 20.0, 20.0, 120.0); + app.ui.tool_options.pen_path_op = "combine".into(); + square(&mut app, 60.0, 60.0, 40.0); + app.ui.tool = Tool::PathSelection; + super::press(&mut app, [30.0, 30.0], false); + assert_eq!(super::selected(&app).map(|(.., h)| h), Some(vec![0])); + let steps = history(&app); + key(&mut app, &ctx, Key::Minus, egui::Modifiers::NONE); + super::set_op(&mut app, "intersect").unwrap(); + assert_eq!(history(&app), steps, "no step"); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Combine]); + assert_eq!(super::selected_op(&app), Some("combine"), "the menu shows what it draws as"); + super::press(&mut app, [80.0, 80.0], true); + super::set_op(&mut app, "subtract").unwrap(); + assert_eq!(history(&app), steps + 1); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Subtract]); + assert_eq!(super::selected_op(&app), None, "they differ"); +} + +/// A component selection is Path Selection's: with the Pen, which doesn't show it, `-` and the +/// menu set the next path's operation and leave the components alone (feedback on #7648). +#[test] +fn the_pen_does_not_edit_a_hidden_component_selection() { + let ctx = egui::Context::default(); + let mut app = app(); + square(&mut app, 20.0, 20.0, 120.0); + app.ui.tool_options.pen_path_op = "combine".into(); + square(&mut app, 60.0, 60.0, 40.0); + app.ui.tool = Tool::PathSelection; + super::press(&mut app, [80.0, 80.0], false); + assert!(super::selected(&app).is_some()); + app.ui.tool = Tool::Pen; + let steps = history(&app); + key(&mut app, &ctx, Key::Minus, egui::Modifiers::NONE); + assert_eq!(app.ui.tool_options.pen_path_op, "subtract", "the next path's"); + assert_eq!(super::selected_op(&app), None); + assert_eq!(history(&app), steps); + assert_eq!(ops(&shape(&app).1.path), [PathOp::Combine, PathOp::Combine]); +} + +/// Dragging a live rectangle or ellipse with Path Selection (its only component selected by the +/// press) moves the whole shape, which stays live: its corner-radius widgets stay (feedback on +/// #7648). +#[test] +fn dragging_a_live_shape_keeps_it_live() { + for kind in ["rect", "ellipse"] { + let mut app = app(); + app.run("shape.create", json!({"kind": kind, "rect": [20, 20, 60, 40], "fill": "#ff0000"})).unwrap(); + assert!(shape(&app).1.live.is_some(), "{kind}"); + app.ui.tool = Tool::PathSelection; + super::press(&mut app, [50.0, 40.0], false); + assert_eq!(super::selected(&app).map(|(.., h)| h), Some(vec![0]), "{kind}"); + let steps = history(&app); + crate::vector_ui::path_selection_finish(&mut app, [50.0, 40.0], [60.0, 45.0]); + let (_, sh) = shape(&app); + assert_eq!(history(&app), steps + 1, "{kind}"); + let (x0, y0, ..) = sh.path.control_bounds().unwrap(); + assert_eq!((x0.round(), y0.round()), (30.0, 25.0), "{kind}: moved"); + match sh.live { + Some(photocraft_doc::vector::LiveShape::Rect { rect, .. } | photocraft_doc::vector::LiveShape::Ellipse { rect }) => { + assert_eq!(rect, [30.0, 25.0, 60.0, 40.0], "{kind}") + } + other => panic!("{kind}: still live, got {other:?}"), + } + } +} + +/// A shape path left open (Enter before closing it) is carried on from its endpoint and closed on +/// its first anchor: the same layer and subpath, one History step, and it takes the options bar's +/// fill and stroke as if it had been drawn closed. +#[test] +fn the_pen_carries_on_an_open_shape_path() { + let mut app = app(); + app.ui.tool_options.shape_fill = true; + app.ui.tool_options.stroke_width = 0.0; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + click(&mut app, x, y); + } + assert!(pen_commit(&mut app, false)); + let (id, sh) = shape(&app); + assert!(sh.fill.is_none() && sh.stroke.is_some(), "an open path is stroked"); + let count = app.session.active().unwrap().doc.layers.len(); + let steps = history(&app); + click(&mut app, 120.0, 120.0); // its last anchor: carry on + click(&mut app, 20.0, 120.0); + click(&mut app, 20.5, 20.5); // its first anchor: close + assert!(app.ui.pen.is_none(), "closing commits"); + let (same, sh) = shape(&app); + assert_eq!((same, app.session.active().unwrap().doc.layers.len()), (id, count), "no new layer"); + assert_eq!(sh.path.subpaths.len(), 1); + assert!(sh.path.subpaths[0].closed); + assert_eq!(sh.path.subpaths[0].knots.len(), 4); + assert!(sh.fill.is_some() && sh.stroke.is_none(), "filled like a path drawn closed"); + assert_eq!(history(&app), steps + 1); + assert!(app.session.undo()); + assert!(!shape(&app).1.path.subpaths[0].closed); +} + +/// From the first anchor too, and a closed component's fill and stroke are the layer's own. +#[test] +fn an_open_component_of_a_filled_shape_keeps_its_paint() { + let mut app = app(); + square(&mut app, 10.0, 10.0, 60.0); + let (id, before) = shape(&app); + // An open component added to the layer. + app.ui.tool_options.pen_path_op = "combine".into(); + for (x, y) in [(100.0, 100.0), (150.0, 100.0)] { + click(&mut app, x, y); + } + assert!(pen_commit(&mut app, false)); + app.ui.tool_options.shape_fill = false; + click(&mut app, 100.0, 100.0); // its first anchor + click(&mut app, 100.0, 150.0); + assert!(pen_commit(&mut app, false)); + let (same, sh) = shape(&app); + assert_eq!(same, id); + assert_eq!(sh.path.subpaths.len(), 2); + assert_eq!(sh.path.subpaths[1].knots.len(), 3); + assert_eq!((sh.fill, sh.stroke), (before.fill, before.stroke)); +} + +/// A targeted vector mask's open subpath is carried on in place too. +#[test] +fn the_pen_carries_on_a_vector_masks_open_subpath() { + let mut app = app(); + app.ui.tool_options.vector_mode = "path".into(); + app.run("layer.new.layer", json!({})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap().0; + let open = json!({"subpaths": [{"closed": false, "knots": [[20, 20], [120, 20]]}]}); + app.run("layer.vectorMask.add", json!({"layer": id, "path": open})).unwrap(); + app.ui.vector_mask_target = true; + click(&mut app, 120.0, 20.0); + click(&mut app, 120.0, 120.0); + assert!(pen_commit(&mut app, false)); + let st = app.session.active().unwrap(); + let mask = st.doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap(); + assert_eq!(mask.path.subpaths.len(), 1); + assert_eq!(mask.path.subpaths[0].knots.len(), 3); + assert!(st.doc.work_path.is_none()); +} diff --git a/crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs b/crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs index fe83b3bbee..cfa3ba432b 100644 --- a/crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs +++ b/crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs @@ -77,7 +77,8 @@ fn escape_dismisses_stroke_child_then_parent_without_deselecting_the_document() #[test] fn enter_selects_a_stroke_style_and_escape_closes_its_popups_without_committing_pen() { let mut app = app(Tool::Pen); - app.ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[12.0, 12.0]; 3], [[60.0, 40.0]; 3]], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(&app); + app.ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[12.0, 12.0]; 3], [[60.0, 40.0]; 3]], owner, ..Default::default() }); let pen = app.ui.pen.clone(); let original = app.session.active().unwrap().doc.clone(); let history = app.session.active().unwrap().history.past_len(); diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 6381244af3..701914b0b9 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -156,7 +156,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { }}; } match tool { - Tool::Move => reset!(move_auto_select, move_target, move_show_transform), + Tool::Move => reset!(move_auto_select, move_target, move_show_transform, transform_interpolation), 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), @@ -208,9 +208,9 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Dodge | Tool::Burn => reset!(tone_range, exposure, protect_tones), Tool::Sponge => reset!(sponge_mode, vibrance), Tool::Slice => reset!(slice_style, slice_width, slice_height), - Tool::Pen => reset!(vector_mode, pen_auto_add_delete), - Tool::CurvaturePen => reset!(vector_mode), - Tool::FreeformPen => reset!(vector_mode, curve_fit), + Tool::Pen => reset!(vector_mode, pen_path_op, pen_auto_add_delete), + Tool::CurvaturePen => reset!(vector_mode, pen_path_op), + Tool::FreeformPen => reset!(vector_mode, pen_path_op, curve_fit), Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => { reset!(vector_mode, shape_fill, stroke_width, shape_stroke, shape_fill_gradient, shape_stroke_gradient, corner_radius, polygon_sides, line_weight) } diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 1a2b741bc2..0db62d7750 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -315,5 +315,15 @@ pub(crate) fn corners(r: [f64; 4]) -> [[f64; 2]; 4] { [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]] } +/// The transform choices supported by the options bar, using its remembered choice or the general default. +pub(crate) fn default_interpolation(app: &PhotocraftApp) -> &'static str { + use photocraft_engine::prefs::Interpolation; + match app.ui.tool_options.transform_interpolation.unwrap_or(app.session.prefs().general.image_interpolation) { + Interpolation::Nearest => "nearest", + Interpolation::Bilinear => "bilinear", + _ => "bicubic", + } +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index f3da463d2f..280cf1f86f 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -4,7 +4,7 @@ use super::draw::texture_quad; use super::preview::{Above, preview_image}; use super::{ Arc, BezierMesh, CAS_ONLY_SCALES, Color32, DocId, Document, Follow, Homography, LOCKED, LayerContent, LayerId, MadeLayer, PhotocraftApp, Several, Steps, - TransformPreview, TransformSession, Warp, WarpStyle, corners, json, + TransformPreview, TransformSession, Warp, WarpStyle, corners, default_interpolation, json, }; /// Start Free Transform on the active layer (or its selected pixels), or on the targeted unlinked @@ -96,7 +96,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> rect, quad: corners(rect), pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bicubic".into(), + interpolation: default_interpolation(app).into(), warp: None, selection: false, target: None, @@ -111,6 +111,16 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> Ok(()) } +pub(super) fn interpolation_preference(interpolation: &str) -> Option { + use photocraft_engine::prefs::Interpolation; + match interpolation { + "nearest" => Some(Interpolation::Nearest), + "bilinear" => Some(Interpolation::Bilinear), + "bicubic" => Some(Interpolation::Bicubic), + _ => None, + } +} + /// Free Transform of the selected layers `ids` together (#6501): the box frames them all, and the /// preview moves their composite, drawn over the layers they cover. `active` stays the session's /// `layer`, so picking another layer still applies the box. The selected pixels of each pixel @@ -193,7 +203,7 @@ fn begin_several(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc Result<( rect, quad: corners(rect), pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bilinear".into(), + interpolation: default_interpolation(app).into(), warp: None, selection: true, target: None, diff --git a/crates/ui-egui/src/tools/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs index c9393810b5..64778476b4 100644 --- a/crates/ui-egui/src/tools/transform_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/transform_tool/options_bar.rs @@ -1,4 +1,4 @@ -use super::begin::{enter_warp, leave_warp, warps_type}; +use super::begin::{enter_warp, interpolation_preference, leave_warp, warps_type}; use super::commit::{cancel, commit}; use super::pointer::point_on_quad; use super::warp::edit_session_warp; @@ -240,9 +240,11 @@ fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSes let mut interp = t.interpolation.clone(); let opts = [("bicubic".to_string(), tl!("Bicubic")), ("bilinear".to_string(), tl!("Bilinear")), ("nearest".to_string(), tl!("Nearest Neighbor"))]; if crate::widgets::dropdown(ui, "transform-interp", tl!("Interpolation"), &mut interp, &opts, 130.0) + && let Some(preference) = interpolation_preference(&interp) && let Some(s) = app.ui.transform.as_mut() { s.interpolation = interp; + app.ui.tool_options.transform_interpolation = Some(preference); } } diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 74411efb38..2546c14941 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -130,6 +130,47 @@ fn transform_bar_pins_warp_cancel_and_commit() { assert!(h.state().ui.transform.is_none()); } +#[test] +fn interpolation_selection_is_reused_for_the_next_transform() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + let app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let mut h = Harness::builder().with_size(vec2(2400.0, 360.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal_centered(|ui| options_bar(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + let ctx = h.ctx.clone(); + begin(h.state_mut(), &ctx).unwrap(); + h.run_steps(6); + assert!(h.state().ui.transform.is_some(), "transform stays open while the bar renders"); + + h.get_by_role(Role::ComboBox).click(); + h.run(); + assert!(h.state().ui.transform.is_some(), "opening interpolation dropdown keeps the transform open"); + h.key_press(egui::Key::ArrowDown); + h.run(); + assert!(h.state().ui.transform.is_some(), "first interpolation step keeps the transform open"); + h.key_press(egui::Key::ArrowDown); + h.run(); + assert!(h.state().ui.transform.is_some(), "second interpolation step keeps the transform open"); + assert_eq!(h.state().ui.transform.as_ref().unwrap().interpolation, "nearest"); + assert_eq!(h.state().ui.tool_options.transform_interpolation, Some(photocraft_engine::prefs::Interpolation::Nearest)); + assert_eq!(h.state().session.prefs().general.image_interpolation, photocraft_engine::prefs::Interpolation::BicubicAutomatic); + + let transform = h.state_mut().ui.transform.as_mut().unwrap(); + transform.quad = transform.quad.map(|[x, y]| [x + 1.0, y]); + commit(h.state_mut()); + assert!(h.state().ui.transform.is_none()); + begin(h.state_mut(), &ctx).unwrap(); + assert_eq!(h.state().ui.transform.as_ref().unwrap().interpolation, "nearest"); +} + #[test] fn free_transform_bar_buttons_follow_the_fields_on_a_wide_bar() { use egui_kittest::Harness; @@ -3222,3 +3263,20 @@ fn applying_the_box_hides_no_pointer() { assert_eq!(cursor(&app, &xf, [32.0, 32.0], cmd()), Some(CursorIcon::ResizeNwSe)); assert_eq!(cursor(&app, &xf, [96.0, 32.0], cmd()), Some(CursorIcon::ResizeVertical)); } + +#[test] +fn several_layers_reuse_the_transform_interpolation_preference() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active_mut().unwrap(); + let first = st.active_layer.unwrap(); + let mut second = photocraft_doc::Layer::raster("second", photocraft_color::PixelFormat::RGBA8); + second.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(32, 8, 48, 24), &[0., 1., 0., 1.]); + let second_id = second.id; + Arc::make_mut(&mut st.doc).layers.push(second); + st.selected_layers = vec![first, second_id]; + app.ui.tool_options.transform_interpolation = Some(photocraft_engine::prefs::Interpolation::Nearest); + begin(&mut app, &egui::Context::default()).unwrap(); + let transform = app.ui.transform.as_ref().unwrap(); + assert_eq!(transform.layers.len(), 2); + assert_eq!(transform.interpolation, "nearest"); +} diff --git a/crates/ui-egui/src/tools/type_tool/layout.rs b/crates/ui-egui/src/tools/type_tool/layout.rs index 45e7cafa3a..3c25568e63 100644 --- a/crates/ui-egui/src/tools/type_tool/layout.rs +++ b/crates/ui-egui/src/tools/type_tool/layout.rs @@ -77,11 +77,11 @@ pub(crate) fn offset_at(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> let (tx, ty) = to_text(&aff, x, y); // Type on a path: the point's place along the path is the position in the (single) line. let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); - let (tx, ty) = match shape { - Some(photocraft_doc::text::TextShape::Path { path, start, flip }) => { - photocraft_text::warp::arc_length_at(&path, flip, f64::from(tx), f64::from(ty)).map_or((tx, ty), |s| ((s - f64::from(start)) as f32, -1.0)) - } - _ => (tx, ty), - }; + let text_start = l.bounds().map_or(0.0, |bounds| f64::from(bounds[0])); + let (tx, ty) = shape + .as_ref() + .and_then(|shape| photocraft_text::warp::Warp::on_path_with_text_start(shape, text_start)) + .and_then(|warp| warp.path_text_x_near_text(f64::from(tx), f64::from(ty), l.bounds().map_or(0.0, |bounds| f64::from(bounds[2])))) + .map_or((tx, ty), |offset| (offset as f32, -1.0)); photocraft_text::hit_char(&l, &text, tx, ty).0 } diff --git a/crates/ui-egui/src/tools/type_tool/overlay.rs b/crates/ui-egui/src/tools/type_tool/overlay.rs index fbac016e3d..5cd4d06538 100644 --- a/crates/ui-egui/src/tools/type_tool/overlay.rs +++ b/crates/ui-egui/src/tools/type_tool/overlay.rs @@ -26,7 +26,8 @@ pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewX }; let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); // Type on a path: the caret, selection and underline follow the curve the glyphs sit on. - let bend = shape.as_ref().and_then(photocraft_text::warp::Warp::on_path); + let text_start = l.bounds().map_or(0.0, |bounds| f64::from(bounds[0])); + let bend = shape.as_ref().and_then(|shape| photocraft_text::warp::Warp::on_path_with_text_start(shape, text_start)); // Line space (lines, clusters, carets) → screen: vertical type turns it 90° clockwise. let scr = |x: f32, y: f32| -> Pos2 { let (x, y) = l.to_text(x, y); diff --git a/crates/ui-egui/src/tools/type_tool/tests.rs b/crates/ui-egui/src/tools/type_tool/tests.rs index 77c3db56c2..dbcb62d6a5 100644 --- a/crates/ui-egui/src/tools/type_tool/tests.rs +++ b/crates/ui-egui/src/tools/type_tool/tests.rs @@ -163,6 +163,109 @@ fn click_creates_placeholder_selected_and_typing_replaces_it() { assert!(app.ui.text_edit.is_none()); } +// Independent perimeter oracle for the rectangle used by the endpoint hit tests. +fn closed_path_endpoint_test_point(s: f64) -> (f64, f64) { + if s < 200.0 { + (20.0 + s, 20.0) + } else if s < 300.0 { + (220.0, 20.0 + s - 200.0) + } else if s < 500.0 { + (220.0 - (s - 300.0), 120.0) + } else { + (20.0, 120.0 - (s - 500.0)) + } +} + +#[test] +fn closed_path_forward_hit_after_last_caret() { + for align in ["left", "center", "right"] { + let mut app = app(); + app.ui.tool_options.type_align = align.into(); + let path = photocraft_vector::shapes::rect(20.0, 20.0, 200.0, 100.0); + app.run("path.set", json!({"path": photocraft_engine::vector_cmds::path_json(&path)})).unwrap(); + pointer_up(&mut app, [20.0, 45.0], [20.0, 45.0]); + insert(&mut app, "ssssssssssss"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let (l, _, _) = layout(&mut app, id).unwrap(); + let (last, _, _) = l.caret(12); + let s = (575.0 + f64::from(last) + 2.0).rem_euclid(600.0); + let (x, y) = closed_path_endpoint_test_point(s); + assert_eq!(offset_at(&mut app, id, x, y), 12, "{align}"); + } +} + +#[test] +fn open_path_hits_keep_endpoint_clamping() { + let mut app = app(); + let path = photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polyline(&[(20.0, 100.0), (380.0, 100.0)])]); + app.run("path.set", json!({"path": photocraft_engine::vector_cmds::path_json(&path)})).unwrap(); + pointer_up(&mut app, [200.0, 100.0], [200.0, 100.0]); + insert(&mut app, "ssss"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + assert_eq!(offset_at(&mut app, id, 198.0, 100.0), 0); + assert_eq!(offset_at(&mut app, id, 20.0, 100.0), 0); + assert_eq!(offset_at(&mut app, id, 380.0, 100.0), 4); +} + +#[test] +fn closed_path_backward_hit_before_first_caret() { + for align in ["left", "center", "right"] { + let mut app = app(); + app.ui.tool_options.type_align = align.into(); + let path = photocraft_vector::shapes::rect(20.0, 20.0, 200.0, 100.0); + app.run("path.set", json!({"path": photocraft_engine::vector_cmds::path_json(&path)})).unwrap(); + pointer_up(&mut app, [20.0, 45.0], [20.0, 45.0]); + insert(&mut app, "ssssssssssss"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let (l, _, _) = layout(&mut app, id).unwrap(); + // The rectangle runs clockwise; the text origin is perimeter distance 575. + // Project 2 px backward from the first caret, using an independent oracle. + let (first, _, _) = l.caret(0); + let s = (575.0 + f64::from(first) - 2.0).rem_euclid(600.0); + let (x, y) = closed_path_endpoint_test_point(s); + assert_eq!(offset_at(&mut app, id, x, y), 0, "{align}"); + } +} + +#[test] +fn closed_path_upstream_caret_rectangle_left_edge_roundtrip() { + let mut app = app(); + let path = photocraft_vector::shapes::rect(20.0, 20.0, 200.0, 100.0); + app.run("path.set", json!({"path": photocraft_engine::vector_cmds::path_json(&path)})).unwrap(); + pointer_up(&mut app, [20.0, 45.0], [20.0, 45.0]); + insert(&mut app, "ssssssssssss"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let (layout, _, _) = layout(&mut app, id).unwrap(); + let shape = text_layer(&app.session.active().unwrap().doc, id).unwrap().shape.clone(); + let photocraft_doc::text::TextShape::Path { start, .. } = shape else { + assert!(matches!(shape, photocraft_doc::text::TextShape::Path { .. }), "outline click must attach path text"); + return; + }; + // Independent rectangle perimeter oracle: never use the warp under test to + // generate expected caret coordinates. Start is 25 px before the top-left seam. + assert!((f64::from(start) - 575.0).abs() < 0.5); + let mut tested_after_seam = false; + for index in [1, 4, 7, 10] { + let (x, _, _) = layout.caret(index); + let distance = f64::from(start) + f64::from(x); + tested_after_seam |= distance > 600.0; + let s = distance.rem_euclid(600.0); + let point = if s < 200.0 { + Point::new(20.0 + s, 20.0) + } else if s < 300.0 { + Point::new(220.0, 20.0 + s - 200.0) + } else if s < 500.0 { + Point::new(220.0 - (s - 300.0), 120.0) + } else { + Point::new(20.0, 120.0 - (s - 500.0)) + }; + // The rectangle oracle already returns document coordinates. + let doc = point; + assert_eq!(offset_at(&mut app, id, doc.x, doc.y), index, "caret round trip at {index}"); + } + assert!(tested_after_seam, "fixture must cross the seam"); +} + /// TYPE-218-1: a Type tool click on the work path starts type on the path from the point /// clicked, in one history step with the placeholder selected; a click off it is point text. #[test] @@ -450,3 +553,35 @@ fn double_click_from_move_tool_restores_move_tool_on_commit_and_cancel() { commit(&mut app); assert_eq!(app.ui.tool, crate::state::Tool::Type, "Layers-thumbnail edit stays on Type tool"); } + +#[test] +fn closed_path_aligned_selection_highlights_every_visible_cluster() { + for align in ["center", "right"] { + let mut app = app(); + app.ui.tool_options.type_align = align.into(); + let path = photocraft_vector::shapes::rect(20.0, 20.0, 200.0, 100.0); + app.run("path.set", json!({"path":photocraft_engine::vector_cmds::path_json(&path)})).unwrap(); + pointer_up(&mut app, [20.0, 45.0], [20.0, 45.0]); + insert(&mut app, "ssssssssssss"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let (l, _, _) = layout(&mut app, id).unwrap(); + assert!(l.bounds().unwrap()[0] < 0.0, "{align} must exercise negative text coordinates"); + let text_layer = text_layer(&app.session.active().unwrap().doc, id).unwrap(); + let rendered = photocraft_text::render::layout_deform(&l, text_layer).unwrap(); + let visible = l.clusters.iter().filter(|c| rendered.place_glyph(f64::from(c.x + c.advance / 2.0)) != photocraft_text::warp::Placement::Hidden).count(); + assert_eq!(visible, l.clusters.len()); + let ed = app.ui.text_edit.as_mut().unwrap(); + ed.anchor = 0; + ed.caret = 12; + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(Default::default(), |ui| { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom: 1.0, center: [120.0, 70.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(&mut app, &painter, &xf); + }); + output.textures_delta.clear(); + let highlights = output.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Path(p) if p.closed && p.fill.a() == 110)).count(); + assert_eq!(highlights, visible, "{align}: every visible selected cluster needs its highlight"); + } +} diff --git a/crates/ui-egui/src/tools/type_transform.rs b/crates/ui-egui/src/tools/type_transform.rs index b725bbb0b8..73264dc214 100644 --- a/crates/ui-egui/src/tools/type_transform.rs +++ b/crates/ui-egui/src/tools/type_transform.rs @@ -129,7 +129,7 @@ pub(crate) fn frame(app: &mut PhotocraftApp) -> Option { rect, quad, pivot, - interpolation: "bicubic".into(), + interpolation: crate::transform_tool::default_interpolation(app).into(), warp: None, selection: false, target: None, diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index c86ad3a1cd..72ec518f81 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -33,6 +33,7 @@ use options::{corner_radii_patch, solid_paint}; pub(crate) use options::{enabled_stroke_width, paint_gesture}; pub use options::{options_bar, shape_properties}; pub use overlay::draw_overlay; +pub(crate) use overlay::selected_saved_path_index; #[cfg(test)] use overlay::{MAX_CURVE_PIECES, bezier}; #[cfg(test)] @@ -51,8 +52,12 @@ pub use paths_panel::{PathEntry, PathRow, path_rows, paths_footer, paths_panel}; pub(crate) use pen::over_first_anchor; #[cfg(test)] use pen::pen_to_json; -pub use pen::{cancel_stale, closes_path_at, freeform_finish, pen_break_handle, pen_commit, pen_down, pen_grab_handle, pen_move, pen_undo_last_point, pen_up}; -pub(crate) use pen::{pen_path, pen_replace}; +pub(crate) use pen::{PATH_OPS, pen_path, pen_replace}; +pub use pen::{ + cancel_stale, closes_path_at, freeform_finish, pen_break_handle, pen_commit, pen_down, pen_end, pen_grab_handle, pen_move, pen_undo_last_point, pen_up, +}; +#[cfg(test)] +use pen::{closing, pen_path_op}; pub use shapes::{create_shape, draw_shape_preview, finish_shape, is_shape_tool, shape_bounds}; #[cfg(test)] use shapes::{shape_geometry, shape_preview}; @@ -69,6 +74,11 @@ pub struct PenPath { /// Re-dragging the final anchor changes its outgoing control only; the incoming curve stays put. #[serde(skip)] pub adjusting_last: bool, + /// Space moves the anchor and both handles together during a Pen drag. + #[serde(skip)] + pub reposition: bool, + #[serde(skip)] + pub last_pointer: Option<[f64; 2]>, /// ⌥/Alt-dragging the final anchor's incoming handle: it turns alone (#6077). #[serde(skip)] pub adjusting_in: bool, @@ -79,6 +89,13 @@ pub struct PenPath { /// Curvature Pen: the anchor being dragged. #[serde(skip)] pub moving: Option, + /// The document and target the first anchor was placed on; a draft without one (restored + /// from settings) is never committed. + #[serde(skip)] + pub(crate) owner: Option, + /// The last commit failed: the draft stays as it was and isn't retried on its own. + #[serde(skip)] + pub(crate) commit_failed: bool, /// Drawing carries on from an endpoint of this open subpath of a document path (#6593): the /// commit replaces that subpath instead of adding one. #[serde(default)] @@ -91,7 +108,11 @@ pub struct PenPath { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resumed { pub doc: u64, + /// A document path's name ("work" or a saved path's), or "layer" for `layer`'s. pub path: String, + /// The shape layer (Shape mode) or targeted vector mask whose path it is. + #[serde(default)] + pub layer: Option, pub index: usize, pub was: photocraft_doc::vector::Subpath, } @@ -112,5 +133,145 @@ mod path_selection_tests; #[cfg(test)] mod pen_draw_tests; +#[cfg(test)] +mod pen_path_ops_tests; + #[cfg(test)] mod paint_tests; + +pub(crate) use pen::freeform_locked_shape; + +/// Where a Pen draft goes, captured at its first anchor. +#[derive(Clone, Debug)] +pub(crate) struct PenOwner { + document: DocId, + revision: u64, + source: Weak, + target: PenTarget, + options: ToolOptions, + layer: Option, + vector_mask: bool, + foreground: [f32; 4], + background: [f32; 4], +} + +impl PartialEq for PenOwner { + fn eq(&self, other: &Self) -> bool { + self.document == other.document && self.revision == other.revision && self.source.ptr_eq(&other.source) && self.target == other.target + } +} + +#[derive(Clone, Debug, PartialEq)] +enum PenTarget { + /// A new shape layer, with the paint chosen when drawing began. + Shape { + fill: Value, + stroke: Value, + open_stroke: Value, + }, + VectorMask(u64), + /// The work path or a saved path; `append` adds the draft as a subpath (#4721). + Path { + name: String, + append: bool, + }, +} + +/// Where the Pen draws now: a new shape layer (Shape mode), else the work or saved path selected +/// in the Paths panel (the new path joins it, #4721), else the targeted vector mask, else a new +/// Work Path that replaces the old one. +pub(crate) fn capture_pen_owner(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + let target = if app.ui.tool_options.vector_mode == "shape" { + let mut open_stroke = app.ui.tool_options.shape_stroke.params(); + open_stroke["width"] = json!(app.ui.tool_options.stroke_width.max(1.0)); + open_stroke["color"] = json!(app.session.tools.foreground); + PenTarget::Shape { fill: fill_param(app), stroke: stroke_param(app), open_stroke } + } else if let Some((name, _)) = selected_document_geometry(app) { + PenTarget::Path { name, append: true } + } else if let Some(id) = targeted_vector_mask_id(app) { + PenTarget::VectorMask(id) + } else { + PenTarget::Path { name: "work".into(), append: false } + }; + Some(PenOwner { + document: st.doc.id, + revision: st.revision, + source: Arc::downgrade(&st.doc), + target, + options: app.ui.tool_options.clone(), + layer: st.active_layer, + vector_mask: app.ui.vector_mask_target, + foreground: app.session.tools.foreground, + background: app.session.tools.background, + }) +} + +impl PenOwner { + fn valid(&self, app: &PhotocraftApp) -> bool { + app.session.active().is_some_and(|st| st.doc.id == self.document && st.revision == self.revision && self.source.ptr_eq(&Arc::downgrade(&st.doc))) + } +} + +use photocraft_doc::DocId; +use std::sync::{Arc, Weak}; + +use path_ops::{selected_document_geometry, targeted_vector_mask_id}; +pub(crate) use pen::{finish_pen_if_left, freeform_finish_owned}; +use shapes::{fill_param, stroke_param}; + +/// Commit a valid source-owned draft on a tab switch; otherwise cancel with an actionable diagnostic. +pub(crate) fn cancel_stale_pen(app: &mut PhotocraftApp) -> bool { + let Some(pen) = app.ui.pen.as_ref() else { return false }; + if pen.owner.as_ref().is_some_and(|o| o.valid(app)) { + return false; + } + if pen.commit_failed { + return false; + } + let owner = pen.owner.clone(); + if let Some(owner) = owner.as_ref() { + let index = app + .session + .documents() + .iter() + .position(|st| st.doc.id == owner.document && st.revision == owner.revision && owner.source.ptr_eq(&Arc::downgrade(&st.doc))); + if let Some(index) = index { + let active = app.session.active_index(); + let saved_ui = app.ui.clone(); + let draft = app.ui.pen.take(); + app.session.set_active(index); + app.ui.pen = draft; + // This source matches the immutable owner; normal commit validation still applies. + let result = pen::try_pen_commit(app, false); + if let Some(active) = active { + app.session.set_active(active); + } + let failed = app.ui.pen.take(); + let message = app.ui.status.clone(); + // The temporary source commit ran sync_views on that document. Rebind its runtime + // tracker before restoring the destination UI, so the next frame cannot clear + // an unrelated saved-path selection in the destination tab. + app.path_document = app.session.active().map(|st| (st.doc.id, st.revision, Arc::downgrade(&st.doc))); + app.ui = saved_ui; + app.ui.pen = if result.is_ok() { None } else { failed }; + if result.is_ok() && app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + app.ui.direct_selection = Default::default(); + } + if result.is_err() { + app.ui.status = message; + app.ui.status_error = true; + } + app.ui.pen_doc = app.ui.pen.as_ref().and_then(|p| p.owner.as_ref().map(|o| o.document)); + return true; + } + } + app.ui.pen = None; + app.ui.pen_doc = None; + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + app.ui.direct_selection = Default::default(); + } + app.ui.status = "Pen draft cancelled because its source document or path changed; newer work was preserved".into(); + app.ui.status_error = true; + true +} diff --git a/crates/ui-egui/src/tools/vector_ui/curvature.rs b/crates/ui-egui/src/tools/vector_ui/curvature.rs index 5506beb8f7..ebd62becdb 100644 --- a/crates/ui-egui/src/tools/vector_ui/curvature.rs +++ b/crates/ui-egui/src/tools/vector_ui/curvature.rs @@ -32,8 +32,9 @@ pub fn curvature_down(app: &mut PhotocraftApp, x: f64, y: f64) { if !cancel_stale(app) { return; } - if app.ui.pen.as_ref().is_some_and(|p| !p.curvature) { - pen_commit(app, false); + // A Pen draft whose commit is refused stays as it is: no Curvature anchor is added to it. + if app.ui.pen.as_ref().is_some_and(|p| !p.curvature) && !pen_commit(app, false) { + return; } let hit = curvature_hit(app, x, y); if hit == Some(0) && app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 3) { @@ -43,7 +44,12 @@ pub fn curvature_down(app: &mut PhotocraftApp, x: f64, y: f64) { if app.ui.pen.is_none() { app.ui.pen_doc = app.session.active().map(|st| st.doc.id); } + let Some(owner) = capture_pen_owner(app) else { return }; let pen = app.ui.pen.get_or_insert_with(|| PenPath { curvature: true, ..Default::default() }); + if pen.owner.is_none() { + pen.owner = Some(owner); + } + pen.commit_failed = false; if hit.is_none() { pen.knots.push([[x, y]; 3]); } @@ -52,6 +58,7 @@ pub fn curvature_down(app: &mut PhotocraftApp, x: f64, y: f64) { } pub fn curvature_move(app: &mut PhotocraftApp, x: f64, y: f64) { + cancel_stale_pen(app); if let Some(pen) = app.ui.pen.as_mut().filter(|p| p.curvature) && let Some(k) = pen.moving.and_then(|i| pen.knots.get_mut(i)) { @@ -61,6 +68,7 @@ pub fn curvature_move(app: &mut PhotocraftApp, x: f64, y: f64) { } pub fn curvature_up(app: &mut PhotocraftApp) { + cancel_stale_pen(app); if let Some(pen) = app.ui.pen.as_mut() { pen.moving = None; } @@ -75,6 +83,7 @@ pub fn curvature_toggle(app: &mut PhotocraftApp, x: f64, y: f64) { crate::direct_select::curvature_toggle_active(app, [x, y]); return; } + cancel_stale_pen(app); let Some(i) = curvature_hit(app, x, y) else { return }; let Some(pen) = app.ui.pen.as_mut() else { return }; if let Some(at) = pen.unlinked.iter().position(|&c| c == i) { @@ -84,3 +93,5 @@ pub fn curvature_toggle(app: &mut PhotocraftApp, x: f64, y: f64) { } curvature_refresh(pen, false); } + +use super::{cancel_stale_pen, capture_pen_owner}; diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index e87dd825d9..7d5d1c39c9 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -1,4 +1,5 @@ use super::path_ops::active_path_name; +use super::pen::path_operations_menu; use super::shapes::is_shape_tool; use super::{GradientChoices, LayerContent, PaintChange, PhotocraftApp, Tokens, Tool, Value, json, paint_param, swatch}; @@ -21,10 +22,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo // The caption scrubs and names the control drawn right after it. crate::widgets::scrub_option_label(ui, &label); }; - let o = &mut app.ui.tool_options; let target = selected_shape(&app.session); + if tool == Tool::PathSelection && !crate::direct_select::active_paths(app).is_empty() { + path_operations_menu(app, ui); + crate::widgets::vline(ui, 22.0); + } + let o = &mut app.ui.tool_options; if tool == Tool::PathSelection && target.is_none() { - lbl(ui, if app.ui.vector_mask_target { "Drag to move the targeted vector mask" } else { tl!("Drag to move the active shape's path or the Work Path") }); + lbl(ui, if app.ui.vector_mask_target { "Drag to move the targeted vector mask" } else { tl!("Drag to move the selected path") }); return true; } if tool == Tool::DirectSelection && target.is_none() { @@ -60,6 +65,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo o.stroke_width = enabled_stroke_width(o.stroke_width); } } + crate::widgets::vline(ui, 22.0); + path_operations_menu(app, ui); + let o = &mut app.ui.tool_options; if tool == Tool::Pen { crate::widgets::vline(ui, 22.0); crate::widgets::checkbox(ui, &mut o.pen_auto_add_delete, tl!("Auto Add/Delete")); @@ -110,7 +118,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } /// Whether the active layer supplies the selected-shape options. -fn selected_shape(session: &photocraft_engine::Session) -> Option { +pub(super) fn selected_shape(session: &photocraft_engine::Session) -> Option { let st = session.active()?; let layer = st.active_layer?; matches!(st.doc.layer(layer)?.content, LayerContent::Shape(_)).then_some(layer) diff --git a/crates/ui-egui/src/tools/vector_ui/overlay.rs b/crates/ui-egui/src/tools/vector_ui/overlay.rs index 7e2b6ab4e6..b72bdd64c5 100644 --- a/crates/ui-egui/src/tools/vector_ui/overlay.rs +++ b/crates/ui-egui/src/tools/vector_ui/overlay.rs @@ -120,6 +120,13 @@ pub(crate) fn selected_saved_path(app: &PhotocraftApp) -> Option<&Path> { app.session.active()?.doc.paths.iter().find(|p| p.name == sel).map(|p| &p.path) } +/// [`selected_saved_path`] with its index in the document's `paths`: the saved path Path +/// Selection and Direct Selection edit (#8478). +pub(crate) fn selected_saved_path_index(app: &PhotocraftApp) -> Option<(usize, Path)> { + let sel = app.ui.selected_path.as_deref().filter(|s| !matches!(*s, "work" | "layer"))?; + app.session.active()?.doc.paths.iter().enumerate().find(|(_, p)| p.name == sel).map(|(i, p)| (i, p.path.clone())) +} + /// Work path / active shape path / selected saved path outlines, anchors, and the pen path in /// progress. pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) { @@ -141,10 +148,6 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform // Direct Selection (or the Pen with ⌘/Ctrl held) draws the paths it edits (#790). crate::direct_select::draw_overlay(app, painter, &to_scr, accent, paths); if paths { - // The selected saved path shows too, though Direct Selection doesn't edit it yet. - if let Some(p) = selected_saved_path(app) { - draw_path(p, true); - } crate::anchor_tools::draw_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers)); } } else if paths { @@ -177,6 +180,15 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some((_, p)) = active_type_path(app) { draw_path(&p, anchors); } + // Path Selection's selected components show solid anchors, as in Photoshop. + if tool == Tool::PathSelection + && st.is_some_and(|s| s.doc.id == doc.id) + && let Some((_, path, _)) = crate::path_components::selected(app) + { + for k in app.ui.direct_selection.anchors.iter().filter_map(|[s, k]| path.subpaths.get(*s).and_then(|sp| sp.knots.get(*k))) { + draw_anchor(painter, to_scr([k.anchor.x, k.anchor.y]), true, accent); + } + } crate::corner_radius::draw(app, painter, &to_scr, accent); } // Pen path in progress, with handles of the last knot and a rubber band to the pointer. While diff --git a/crates/ui-egui/src/tools/vector_ui/paint_tests.rs b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs index d71a8fca78..892565e38c 100644 --- a/crates/ui-egui/src/tools/vector_ui/paint_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs @@ -383,7 +383,7 @@ fn transparent_and_absent_paints_remain_distinct_and_open_pen_keeps_foreground() let foreground = [0.836521, 0.125468, 0.745632, 0.438271]; app.run("tools.setColors", json!({"foreground": foreground, "background": [0.0, 1.0, 0.0, 1.0]})).unwrap(); app.ui.tool_options.vector_mode = "shape".into(); - app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[80.0, 60.0]; 3]], ..Default::default() }); + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[80.0, 60.0]; 3]], owner: super::capture_pen_owner(&app), ..Default::default() }); pen_commit(&mut app, false); assert!(shape(&app).fill.is_none()); assert!(!shape(&app).path.subpaths[0].closed); 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 a0f3ca4e6d..e6c3a1a6cc 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -1,3 +1,4 @@ +use super::overlay::selected_saved_path_index; use super::paths_panel::{PathEntry, PathRow, path_rows}; use super::pen::pen_commit; use super::{Affine, Document, LayerContent, Path, PhotocraftApp, Tool, Value, json}; @@ -59,9 +60,9 @@ pub fn with_active_path(app: &PhotocraftApp, id: &str, params: Value) -> Value { pub fn path_to_selection(app: &mut PhotocraftApp, params: Value) -> Result { if app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2) { // The finished path becomes the work path, or a shape layer's path or a vector mask. - let on_layer = app.ui.tool_options.vector_mode == "shape" || targeted_vector_mask(app).is_some(); - pen_commit(app, false); - app.ui.selected_path = Some(if on_layer { "layer" } else { "work" }.into()); + if !pen_commit(app, false) { + return Err(app.ui.status.clone()); + } } let name = active_path_name(app) .ok_or_else(|| tl!("No path to make a selection from: draw one with the Pen tool or select one in the Paths panel.").to_string())?; @@ -115,16 +116,35 @@ pub(super) enum PathTarget { Shape(u64), /// The active layer's vector mask, when its Layers thumbnail is targeted (#196). VectorMask(u64), + /// The saved path selected in the Paths panel, by name (#8478). + Saved(String), Work, } +/// The work or saved path explicitly selected in the Paths panel, by name, and its geometry. Only +/// such a selection overrides the active layer's path. +pub(super) fn selected_document_geometry(app: &PhotocraftApp) -> Option<(String, &Path)> { + let st = app.session.active()?; + match app.ui.selected_path.as_deref()? { + "work" => st.doc.work_path.as_ref().map(|p| ("work".into(), p)), + "layer" => None, + name => st.doc.paths.iter().find(|p| p.name == name).map(|p| (p.name.clone(), &p.path)), + } +} + /// The targeted vector mask of the active layer, if the Layers panel targets it. pub(crate) fn targeted_vector_mask(app: &PhotocraftApp) -> Option<(u64, Path)> { + let id = targeted_vector_mask_id(app)?; + let mask = app.session.active()?.doc.layer(photocraft_doc::LayerId(id))?.vector_mask.as_ref()?; + Some((id, mask.path.clone())) +} + +pub(super) fn targeted_vector_mask_id(app: &PhotocraftApp) -> Option { let st = app.session.active()?; let l = st.active_layer.and_then(|id| st.doc.layer(id))?; let targeted = app.ui.vector_mask_target || st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::VectorMask; (targeted && !matches!(l.content, LayerContent::Shape(_))).then_some(())?; - l.vector_mask.as_ref().map(|m| (l.id.0, m.path.clone())) + l.vector_mask.as_ref().map(|_| l.id.0) } /// The active type layer's path in document space, if it is type on a path (#9114). @@ -160,15 +180,23 @@ pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { && matches!(target_path(app), Some((PathTarget::Work, _))) } -/// The path Path Selection edits: the targeted vector mask, the active shape layer's path, else -/// the work path. +/// The path Path Selection edits: the targeted vector mask, the active shape layer's path, the +/// saved path selected in the Paths panel (#8478), else the work path. pub(super) fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> { + if let Some((name, p)) = selected_document_geometry(app) { + return Some((if name == "work" { PathTarget::Work } else { PathTarget::Saved(name) }, p.clone())); + } if let Some((id, p)) = targeted_vector_mask(app) { return Some((PathTarget::VectorMask(id), p)); } if let Some((id, p)) = active_shape_path(app) { return Some((PathTarget::Shape(id), p)); } + if let Some(name) = app.ui.selected_path.as_deref() + && let Some((_, p)) = selected_saved_path_index(app) + { + return Some((PathTarget::Saved(name.to_string()), p)); + } if !work_path_shown(app) { return None; } @@ -185,6 +213,7 @@ pub(crate) fn free_transform_path(app: &PhotocraftApp) -> Option<(Value, Path)> path.control_bounds()?; let params = match target { PathTarget::Shape(id) | PathTarget::VectorMask(id) => json!({"name": "layer", "layer": id}), + PathTarget::Saved(name) => json!({"name": name}), PathTarget::Work => json!({"name": "work"}), }; Some((params, path)) @@ -282,6 +311,14 @@ pub fn path_selection_finish(app: &mut PhotocraftApp, start: [f64; 2], end: [f64 let _ = app.run("layer.select", json!({"layer": id.0})); } } + // Selected components move on their own (`path_components`); with none, the whole path. + if let Some(r) = crate::path_components::move_selected(app, [dx.round(), dy.round()]) { + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } + return; + } let Some((target, path)) = target_path(app) else { return }; let _ = match target { PathTarget::Shape(id) => app.run("shape.edit", json!({"layer": id, "move": [dx.round(), dy.round()]})), @@ -293,5 +330,9 @@ pub fn path_selection_finish(app: &mut PhotocraftApp, start: [f64; 2], end: [f64 let moved = path.transform(&Affine::translate(dx.round(), dy.round())); app.run("path.set", json!({"name": "work", "path": photocraft_engine::vector_cmds::path_json(&moved)})) } + PathTarget::Saved(name) => { + let moved = path.transform(&Affine::translate(dx.round(), dy.round())); + app.run("path.set", json!({"name": name, "path": photocraft_engine::vector_cmds::path_json(&moved)})) + } }; } diff --git a/crates/ui-egui/src/tools/vector_ui/path_selection_tests.rs b/crates/ui-egui/src/tools/vector_ui/path_selection_tests.rs index 8cab12747a..75e4b8a007 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_selection_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_selection_tests.rs @@ -67,7 +67,8 @@ fn cmd_enter_while_drawing_finishes_the_path_and_loads_it() { let mut h = harness(); h.state_mut().ui.tool = Tool::Pen; let p = |x: f64, y: f64| [[x, y], [x, y], [x, y]]; - h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], owner, ..Default::default() }); h.run_steps(2); press(&mut h, Key::Enter, command()); let app = h.state(); @@ -80,7 +81,8 @@ fn cmd_enter_while_drawing_finishes_the_path_and_loads_it() { // Plain ↩ still only finishes a path. let mut h = harness(); h.state_mut().ui.tool = Tool::Pen; - h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], owner, ..Default::default() }); h.run_steps(2); press(&mut h, Key::Enter, Modifiers::NONE); assert!(h.state().session.active().unwrap().doc.work_path.is_some()); @@ -94,7 +96,8 @@ fn selecting_a_saved_path_keeps_the_hidden_work_path_hidden() { h.state_mut().run("path.set", json!({"name": "Saved", "path": rect_path(100.0, 40.0, 60.0, 50.0)})).unwrap(); h.state_mut().ui.tool = Tool::Pen; let p = |x: f64, y: f64| [[x, y], [x, y], [x, y]]; - h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], owner, ..Default::default() }); h.run_steps(2); press(&mut h, Key::Enter, command()); assert!(!crate::vector_ui::work_path_shown(h.state()), "⌘↩ hid the work path"); @@ -123,7 +126,8 @@ fn reselecting_the_hidden_work_path_ends_the_hide() { let mut h = harness(); h.state_mut().ui.tool = Tool::Pen; let p = |x: f64, y: f64| [[x, y], [x, y], [x, y]]; - h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], ..Default::default() }); + let owner = crate::vector_ui::capture_pen_owner(h.state()); + h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], owner, ..Default::default() }); h.run_steps(2); press(&mut h, Key::Enter, command()); assert!(!crate::vector_ui::work_path_shown(h.state()), "⌘↩ hid the work path"); diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index 56b6d79449..baa536f3b8 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -1,7 +1,8 @@ use super::curvature::{curvature_hit, curvature_refresh}; -use super::path_ops::{targeted_vector_mask, work_path_shown}; +use super::options::selected_shape; +use super::path_ops::{active_shape_path, targeted_vector_mask, work_path_shown}; use super::shapes::{fill_param, stroke_param}; -use super::{Document, Path, PenPath, PhotocraftApp, Resumed, Tool, Value, json}; +use super::{Document, LayerContent, Path, PenPath, PhotocraftApp, Resumed, Tokens, Tool, ToolOptions, Value, json, vec2}; // --------------------------------------------------------------------------------------------- // Pen @@ -51,8 +52,15 @@ pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { { app.ui.pen = Some(resumed); } + let Some(owner) = capture_pen_owner(app) else { return }; let pen = app.ui.pen.get_or_insert_with(PenPath::default); + if pen.owner.is_none() { + pen.owner = Some(owner); + } + pen.commit_failed = false; pen.adjusting_in = false; + pen.last_pointer = Some([x, y]); + pen.reposition = false; if let Some(first) = pen.knots.first().map(|k| k[0]) && on_closing_anchor(pen, x, y, tol) { @@ -89,11 +97,22 @@ pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { /// Pen drag: pull out the handles of the anchor just placed. ⇧ (read live, as it is held) /// turns the handle to the nearest 45° direction from its anchor. pub fn pen_move(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { + cancel_stale_pen(app); if let Some(pen) = app.ui.pen.as_mut() && pen.dragging { let (adjusting_last, adjusting_in) = (pen.adjusting_last, pen.adjusting_in); if let Some(k) = pen.knots.last_mut() { + if pen.reposition { + if let Some([px, py]) = pen.last_pointer { + for point in k { + point[0] += x - px; + point[1] += y - py; + } + } + pen.last_pointer = Some([x, y]); + return; + } let a = k[0]; let [x, y] = shift_45(a, [x, y], shift); if adjusting_in { @@ -105,6 +124,7 @@ pub fn pen_move(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { k[1] = [2.0 * a[0] - x, 2.0 * a[1] - y]; } } + pen.last_pointer = Some([x, y]); } } @@ -118,6 +138,9 @@ pub(super) fn shift_45(origin: [f64; 2], p: [f64; 2], shift: bool) -> [f64; 2] { /// clicking the first anchor commits the path. Therefore Cmd/Ctrl+Z must consume one /// knot rather than undoing an unrelated, already committed document operation. pub fn pen_undo_last_point(app: &mut PhotocraftApp) -> bool { + if cancel_stale_pen(app) { + return false; + } if !cancel_stale(app) { return false; } @@ -155,10 +178,13 @@ pub fn pen_undo_last_point(app: &mut PhotocraftApp) -> bool { } pub fn pen_up(app: &mut PhotocraftApp) { + cancel_stale_pen(app); let jitter = 2.0 / f64::from(app.point_zoom().max(0.01)); let Some(pen) = app.ui.pen.as_mut() else { return }; pen.dragging = false; pen.adjusting_last = false; + pen.reposition = false; + pen.last_pointer = None; pen.adjusting_in = false; if closing(pen) { // A click on the first anchor closes the path and leaves that anchor's handles alone. @@ -175,6 +201,7 @@ pub fn pen_up(app: &mut PhotocraftApp) { /// ⌥/Alt during a Pen drag breaks the pair of handles being pulled out: from then on only the /// outgoing handle follows the pointer and the incoming curve stays as it is (#3306). pub fn pen_break_handle(app: &mut PhotocraftApp) { + cancel_stale_pen(app); let Some(pen) = app.ui.pen.as_mut().filter(|p| p.dragging && !p.adjusting_last) else { return }; let Some(i) = pen.knots.len().checked_sub(1) else { return }; if !pen.unlinked.contains(&i) { @@ -186,6 +213,7 @@ pub fn pen_break_handle(app: &mut PhotocraftApp) { /// ⌥/Alt-press on one of the last anchor's handles while drawing grabs that handle alone: the /// drag turns it and the other handle stays put (#3306, #6077). False when the press misses both. pub fn pen_grab_handle(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { + cancel_stale_pen(app); let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); let Some(pen) = app.ui.pen.as_mut() else { return false }; let Some((i, k)) = pen.knots.len().checked_sub(1).zip(pen.knots.last()) else { return false }; @@ -207,6 +235,8 @@ pub fn pen_grab_handle(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { } pen.dragging = true; pen.adjusting_last = true; + pen.reposition = false; + pen.last_pointer = Some([x, y]); pen.adjusting_in = incoming; true } @@ -281,68 +311,109 @@ pub(crate) fn pen_replace(app: &mut PhotocraftApp, path: &Path) { } } -/// Preserve a foreign document's draft as its Work Path before another document can edit it. -/// A failed commit retains the draft and blocks the caller until it can be retried. pub fn cancel_stale(app: &mut PhotocraftApp) -> bool { - let active = app.session.active().map(|st| st.doc.id); - if app.ui.pen.is_none() { - app.ui.pen_doc = None; - return true; - } - let Some(owner) = app.ui.pen_doc.filter(|d| Some(*d) != active) else { return true }; - if let Some(index) = app.session.documents().iter().position(|d| d.doc.id == owner) { - let Some(mut pen) = app.ui.pen.clone() else { return true }; - if pen.curvature { - curvature_refresh(&mut pen, false); - } - let active = app.session.active_index(); - app.session.set_active(index); - // Bypass shell targets and sync_views: both belong to the newly active document. - let result = app.session.execute("path.set", json!({"name": "work", "op": "combine", "path": pen_to_json(&pen, false)})); - if let Some(index) = active { - app.session.set_active(index); - } - if let Err(e) = result { - app.ui.status = e.to_string(); - app.ui.status_error = true; - return false; - } - } - app.ui.pen = None; - app.ui.pen_doc = None; - if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { - app.ui.direct_selection = Default::default(); - } - true + cancel_stale_pen(app); + !app.ui.pen.as_ref().is_some_and(|p| p.commit_failed && p.owner.as_ref().is_some_and(|o| !o.valid(app))) } -/// Finish the pen path: a work path (Path mode) or a new shape layer (Shape mode). -pub fn pen_commit(app: &mut PhotocraftApp, closed: bool) { - // The control channel is drained after `sync_views`, so a document switch in this frame has - // not been seen yet: never commit the path into the document it was not drawn on. - if !cancel_stale(app) { +pub fn pen_commit(app: &mut PhotocraftApp, closed: bool) -> bool { + try_pen_commit(app, closed).is_ok() +} + +/// Finish the draft as [`pen_commit`] does. On failure the draft stays as it was, marked +/// `commit_failed`, and the error is shown and returned. +pub(super) fn try_pen_commit(app: &mut PhotocraftApp, closed: bool) -> Result<(), String> { + // This is an explicit commit request; passive frame reconciliation never clears this flag. + if let Some(pen) = app.ui.pen.as_mut() { + pen.commit_failed = false; + } + if cancel_stale_pen(app) { + return if app.ui.pen.is_none() { Ok(()) } else { Err(app.ui.status.clone()) }; + } + let Some(mut pen) = app.ui.pen.take() else { return Ok(()) }; + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + // Its anchors are no longer the Pen's: the committed path is another path. + app.ui.direct_selection = Default::default(); + } + let mut original = pen.clone(); + original.dragging = false; + original.adjusting_last = false; + if pen.curvature { + curvature_refresh(&mut pen, closed); + } + if let Err(e) = commit_path(app, &pen, closed) { + app.ui.pen = Some(PenPath { commit_failed: true, ..original }); + app.ui.status = e.clone(); + app.ui.status_error = true; + return Err(e); + } + app.ui.pen_doc = None; + Ok(()) +} + +/// Another tool finishes the Pen's draft, once: a draft whose commit failed waits for the user. +pub(crate) fn finish_pen_if_left(app: &mut PhotocraftApp) { + cancel_stale_pen(app); + let shape_fallback = + app.ui.pen.as_ref().is_some_and(|p| { + !p.drawn_with(app.ui.tool) && p.owner.as_ref().is_some_and(|o| o.valid(app) && matches!(o.target, super::PenTarget::Shape { .. })) + }); + if shape_fallback { + pen_end(app); + } else if app.ui.pen.as_ref().is_some_and(|p| !p.commit_failed && !p.drawn_with(app.ui.tool)) { + pen_commit(app, false); + } +} + +/// End the Pen path for good (Esc, or switching to another tool): commit it, and when the +/// document refuses that (a locked shape layer or vector mask to add to…) keep it as the Work Path +/// instead, so what was drawn is neither lost nor retried on every frame. A draft even the Work +/// Path refuses is dropped; the status bar says which happened. +pub fn pen_end(app: &mut PhotocraftApp) { + if pen_commit(app, false) { + return; + } + let active = app.session.active().map(|st| st.doc.id); + if app.ui.pen_doc.is_some_and(|d| Some(d) != active) { + // Drawn on another document that refused it (`cancel_stale`): left as it was. return; } let Some(mut pen) = app.ui.pen.take() else { return }; app.ui.pen_doc = None; if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { - // Its anchors are no longer the Pen's: the committed path is another path. app.ui.direct_selection = Default::default(); } if pen.curvature { - curvature_refresh(&mut pen, closed); + curvature_refresh(&mut pen, false); } - commit_path(app, &pen, closed); + let refused = std::mem::take(&mut app.ui.status); + let kept = app.run("path.set", json!({"name": "work", "op": "combine", "path": pen_to_json(&pen, false)})).is_ok(); + if kept { + app.ui.selected_path = Some("work".into()); + } + let outcome = if kept { tl!("The path was kept as the Work Path") } else { tl!("The path was discarded") }; + app.ui.status = format!("{refused} ({outcome})"); + app.ui.status_error = true; } -/// Commit a finished Pen, Freeform Pen or Curvature Pen path, as one History step: a new shape -/// layer (Shape mode), else a subpath of the targeted vector mask, else the work path. -fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) { - if pen.knots.len() < 2 { - return; +/// Commit a finished Pen, Freeform Pen or Curvature Pen path, as one History step: in Shape mode a +/// new shape layer, or with a Path Operation other than New Layer a subpath of the selected shape +/// layer; in Path mode a subpath of the targeted vector mask, else of the selected path or a new +/// work path. An added subpath takes the options bar's Path Operation (#1397). `false` when the +/// document refused it, with the reason in the status bar. +fn commit_path_current(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) -> bool { + if pen.knots.is_empty() || (pen.knots.len() < 2 && app.ui.tool_options.vector_mode == "shape") { + return true; } let path = pen_to_json(pen, closed); - let r = if app.ui.tool_options.vector_mode == "shape" { + let op = pen_path_op(&app.ui.tool_options); + let into_shape = op.and_then(|_| selected_shape(&app.session)).map(|id| id.0); + let r = if let Some(r) = commit_resumed_on_layer(app, pen, &path, closed) { + r + } else if let (Some(op), Some(layer), "shape") = (op, into_shape, app.ui.tool_options.vector_mode.as_str()) { + // The selected shape layer keeps its fill and stroke; the new component cuts, intersects… + app.run("shape.create", json!({"kind": "path", "path": path, "addTo": layer, "op": op})) + } else if app.ui.tool_options.vector_mode == "shape" { let fill = if closed { fill_param(app) } else { Value::Null }; let stroke = if closed { stroke_param(app) @@ -362,7 +433,10 @@ fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) { // A targeted vector mask takes the new subpath (#196), as in Photoshop. let mut p = photocraft_engine::vector_cmds::path_json(&existing); if let (Some(subs), Some(new)) = (p.get_mut("subpaths").and_then(Value::as_array_mut), path.get("subpaths").and_then(Value::as_array)) { - subs.extend(new.iter().cloned()); + subs.extend(new.iter().cloned().map(|mut sp| { + sp["op"] = json!(op.unwrap_or("combine")); + sp + })); } app.run("layer.vectorMask.edit", json!({"layer": id, "path": p})) } else { @@ -372,19 +446,22 @@ fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) { // A resumed draft whose subpath changed meanwhile joins the path it came from, as a new // subpath, even with nothing selected in the Paths panel. let exists = |n: &String| app.session.active().is_some_and(|st| path_exists(&st.doc, n)); - let resumed_from = pen.resumes.as_ref().filter(|r| app.session.active().is_some_and(|st| st.doc.id.0 == r.doc)).map(|r| r.path.clone()); + let resumed_from = + pen.resumes.as_ref().filter(|r| r.layer.is_none() && app.session.active().is_some_and(|st| st.doc.id.0 == r.doc)).map(|r| r.path.clone()); let target = resumed_from.filter(exists).or_else(|| app.ui.selected_path.clone().filter(exists)); let name = target.clone().unwrap_or_else(|| "work".into()); let mut params = json!({"name": name, "path": path}); if target.is_some() { - params["op"] = json!("combine"); + params["op"] = json!(op.unwrap_or("combine")); } app.run("path.set", params).inspect(|_| app.ui.selected_path = Some(name)) }; if let Err(e) = r { app.ui.status = e; app.ui.status_error = true; + return false; } + true } /// Does `doc` have the path the Paths panel calls `name`: "work", or a saved path's name? @@ -397,23 +474,30 @@ fn doc_path<'a>(doc: &'a Document, name: &str) -> Option<&'a Path> { if name == "work" { doc.work_path.as_ref() } else { doc.paths.iter().find(|p| p.name == name).map(|p| &p.path) } } -/// The open subpath of the path a new Pen path would join (the one selected in the Paths panel, -/// else the work path) that has its first or last anchor at `(x, y)`, as a Pen path to carry on -/// drawing from there (#6593). Its knots run towards that anchor: reversed, handles swapped, when -/// it is the first. Shape mode and a targeted vector mask take new paths, so they resume nothing. +/// The open subpath that has its first or last anchor at `(x, y)`, as a Pen path to carry on +/// drawing from there (#6593): of a targeted vector mask, else in Shape mode of the selected shape +/// layer, else of the path a new Pen path would join (the one selected in the Paths panel, else +/// the work path). Its knots run towards that anchor: reversed, handles swapped, when it is the +/// first. fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { - if app.ui.tool_options.vector_mode == "shape" || targeted_vector_mask(app).is_some() { - return None; - } let st = app.session.active()?; let doc = st.doc.id.0; - let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); - // A Work Path hidden by Make Selection isn't carried on: a new path replaces it (#6079). - if name == "work" && !work_path_shown(app) { - return None; - } + let (name, layer, path) = if let Some((id, p)) = targeted_vector_mask(app) { + ("layer".to_string(), Some(id), p) + } else if app.ui.tool_options.vector_mode == "shape" { + let (id, p) = active_shape_path(app)?; + ("layer".to_string(), Some(id), p) + } else { + let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); + // A Work Path hidden by Make Selection isn't carried on: a new path replaces it (#6079). + if name == "work" && !work_path_shown(app) { + return None; + } + let p = doc_path(&st.doc, &name)?.clone(); + (name, None, p) + }; let near = |k: &photocraft_doc::Knot| (k.anchor.x - x).hypot(k.anchor.y - y) < tol; - doc_path(&st.doc, &name)?.subpaths.iter().enumerate().filter(|(_, s)| !s.closed).find_map(|(i, s)| { + path.subpaths.iter().enumerate().filter(|(_, s)| !s.closed).find_map(|(i, s)| { let reversed = if s.knots.last().is_some_and(near) { false } else if s.knots.first().is_some_and(near) { @@ -429,7 +513,7 @@ fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { } } let unlinked = knots.iter().enumerate().filter(|(_, (_, smooth))| !smooth).map(|(i, _)| i).collect(); - let resumes = Resumed { doc, path: name.clone(), index: i, was: s.clone() }; + let resumes = Resumed { doc, path: name.clone(), layer, index: i, was: s.clone() }; Some(PenPath { knots: knots.into_iter().map(|(k, _)| k).collect(), unlinked, resumes: Some(resumes), ..Default::default() }) }) } @@ -438,7 +522,7 @@ fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { /// anchors and closing, which keeps its other settings (its path operation). `None` when the /// subpath is no longer the one drawing resumed (another document, or the path changed). fn with_resumed_subpath(doc: &Document, r: &Resumed, drawn: &Value) -> Option { - let path = doc_path(doc, &r.path).filter(|_| doc.id.0 == r.doc)?; + let path = resumed_path(doc, r)?; if path.subpaths.get(r.index) != Some(&r.was) { return None; } @@ -451,13 +535,169 @@ fn with_resumed_subpath(doc: &Document, r: &Resumed, drawn: &Value) -> Option(doc: &'a Document, r: &Resumed) -> Option<&'a Path> { + if doc.id.0 != r.doc { + return None; + } + let Some(id) = r.layer else { return doc_path(doc, &r.path) }; + let l = doc.layer(photocraft_doc::LayerId(id))?; + match &l.content { + LayerContent::Shape(sh) => Some(&sh.path), + _ => l.vector_mask.as_ref().map(|m| &m.path), + } +} + +/// Commit a resumed Pen path (#6593) into a shape layer or vector mask: the carried-on subpath +/// takes its old place, one step. Closing the open path a shape layer was made of gives it the +/// options bar's fill and stroke, as drawing it closed would have. `None` when the draft resumes +/// a document path, or its subpath changed meanwhile. +fn commit_resumed_on_layer(app: &mut PhotocraftApp, pen: &PenPath, path: &Value, closed: bool) -> Option> { + let r = pen.resumes.as_ref()?; + let id = r.layer?; + let st = app.session.active()?; + let p = with_resumed_subpath(&st.doc, r, path)?; + let layer = st.doc.layer(photocraft_doc::LayerId(id))?; + let LayerContent::Shape(sh) = &layer.content else { + return Some(app.run("layer.vectorMask.edit", json!({"layer": id, "path": p}))); + }; + let mut params = json!({"layer": id, "path": p}); + if closed && sh.fill.is_none() && sh.path.subpaths.iter().all(|s| !s.closed) { + params["fill"] = fill_param(app); + params["stroke"] = stroke_param(app); + } + Some(app.run("shape.edit", params)) +} + +/// The Pen's Path Operations (#1397), in Photoshop's menu order: the `pen_path_op` value, its +/// label and its icon. +pub(crate) const PATH_OPS: [(&str, &str, &str); 5] = [ + ("newLayer", "New Layer", "path-op-new-layer"), + ("combine", "Combine Shapes", "path-op-combine"), + ("subtract", "Subtract Front Shape", "path-op-subtract"), + ("intersect", "Intersect Shape Areas", "path-op-intersect"), + ("exclude", "Exclude Overlapping Shapes", "path-op-exclude"), +]; + +/// The operation (`path.set` / `shape.create` `op`) a new Pen path is added with; None for a new +/// shape layer (New Layer, in Shape mode). Path mode has no New Layer: there it combines. +pub(crate) fn pen_path_op(o: &ToolOptions) -> Option<&'static str> { + let op = PATH_OPS.iter().map(|(v, ..)| *v).find(|v| *v == o.pen_path_op).unwrap_or("newLayer"); + match op { + "newLayer" if o.vector_mode == "shape" => None, + "newLayer" => Some("combine"), + op => Some(op), + } +} + +/// What the Path Operations menu's Merge Shape Components merges, as a command, its params and +/// the number of shape components there: with Path Selection the path it selects in; in Shape +/// mode the selected shape layer; in Path mode the path the Pen draws into (a targeted vector +/// mask, the selected path, else the Work Path). +fn merge_target(app: &PhotocraftApp) -> Option<(&'static str, Value, usize)> { + if app.ui.tool == Tool::PathSelection { + let (r, p) = crate::direct_select::active_paths(app).into_iter().next()?; + return Some(("path.mergeShapeComponents", r.params(app), p.components().len())); + } + let st = app.session.active()?; + if app.ui.tool_options.vector_mode == "shape" { + let id = st.active_layer?; + let LayerContent::Shape(sh) = &st.doc.layer(id)?.content else { return None }; + return Some(("layer.combineShapes.mergeShapeComponents", json!({"layer": id.0}), sh.path.components().len())); + } + if let Some((id, p)) = targeted_vector_mask(app) { + return Some(("path.mergeShapeComponents", json!({"name": "layer", "layer": id}), p.components().len())); + } + let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); + let path = if name == "work" { st.doc.work_path.as_ref() } else { st.doc.paths.iter().find(|p| p.name == name).map(|p| &p.path) }?; + Some(("path.mergeShapeComponents", json!({"name": name}), path.components().len())) +} + +/// The Path Operations button of the Pen, Freeform Pen, Curvature Pen and Path Selection (#1397), +/// Photoshop's: the operation of the selected path components, or with none selected how the next +/// path combines with the shape or path it is drawn into; and Merge Shape Components. Its icon +/// shows the selected components' operation, else the tool's. +pub(super) fn path_operations_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // New Layer makes a shape layer: Path mode and Path Selection have none. + let shape = app.ui.tool_options.vector_mode == "shape" && app.ui.tool != Tool::PathSelection; + let current = crate::path_components::selected_op(app) + .or_else(|| pen_path_op(&app.ui.tool_options)) + .map_or("newLayer", |op| if op == "newLayer" && !shape { "combine" } else { op }); + let icon = PATH_OPS.iter().find(|(v, ..)| *v == current).map_or("path-op-combine", |(.., i)| *i); + let resp = crate::icons::button_with_icon_size(ui, icon, 24.0, 16.0, false, tl!("Path operations")); + let resp = crate::brush_picker::named(resp, "Path operations"); + let merge = merge_target(app).filter(|(.., n)| *n > 1); + let mut run = None; + let mut pick = None; + egui::Popup::menu(&resp).show(|ui| { + ui.set_min_width(240.0); + for (value, label, glyph) in PATH_OPS { + if ui.add_enabled_ui(shape || value != "newLayer", |ui| path_op_button(ui, glyph, tl!(label), value == current)).inner.clicked() { + pick = Some(value); + ui.close(); + } + } + ui.separator(); + if ui.add_enabled_ui(merge.is_some(), |ui| path_op_button(ui, "path-op-merge", tl!("Merge Shape Components"), false)).inner.clicked() { + run = merge.clone(); + ui.close(); + } + }); + if let Some(op) = pick + && let Err(e) = crate::path_components::set_op(app, op) + { + app.ui.status = e; + app.ui.status_error = true; + } + if let Some((id, params, _)) = run + && let Err(e) = app.run(id, params) + { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// A Path Operations menu row: its icon and label, highlighted when it is the current operation. +fn path_op_button(ui: &mut egui::Ui, glyph: &str, label: &str, checked: bool) -> egui::Response { + let icon = egui::IdSalt::new((glyph, "icon")); + let b = egui::Button::new((egui::Atom::custom(icon, vec2(16.0, 16.0)), label, egui::Atom::grow())).selected(checked).atom_ui(ui); + if let Some(r) = b.rect(icon) { + crate::icons::paint(ui, r, glyph, 16.0, Tokens::get(ui.ctx()).icon); + } + b.response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), checked, label)); + b.response +} + // --------------------------------------------------------------------------------------------- // Freeform Pen and Curvature Pen +/// Refuse a Freeform stroke before drawing when its selected shape cannot be edited. +pub(crate) fn freeform_locked_shape(app: &PhotocraftApp) -> bool { + if app.ui.tool_options.vector_mode != "shape" || pen_path_op(&app.ui.tool_options).is_none() { + return false; + } + let Some(id) = selected_shape(&app.session) else { return false }; + app.session.active().is_some_and(|st| { + let locks = st.doc.effective_locks(id); + locks.all || locks.pixels + }) +} + /// Freeform Pen release: fit the drag's trace within the options bar's Curve Fit and commit it /// as the Pen does. Releasing on the start point closes the path; a click draws nothing. The /// points at indices `straight` were ⌥-clicked: the segment into each one stays straight. pub fn freeform_finish(app: &mut PhotocraftApp, points: &[[f64; 3]], straight: &[usize]) { + let Some(owner) = capture_pen_owner(app) else { return }; + freeform_finish_owned(app, points, straight, owner); +} + +/// [`freeform_finish`] to the destination captured when the trace began. A trace of another +/// document commits nothing; a failed commit keeps the fitted path as a draft. +pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]], straight: &[usize], owner: PenOwner) { + if !owner.valid(app) { + return; + } let trace: Vec<[f64; 2]> = points.iter().map(|p| [p[0], p[1]]).collect(); let (Some(first), Some(last)) = (trace.first(), trace.last()) else { return }; let tol = 6.0 / app.point_zoom().max(0.01) as f64; @@ -472,7 +712,13 @@ pub fn freeform_finish(app: &mut PhotocraftApp, points: &[[f64; 3]], straight: & } else { fit_with_straight_segments(&trace, straight, fit, closed.then_some(tol)) }; - commit_path(app, &pen.0, pen.1); + let (mut pen, closed) = pen; + pen.owner = Some(owner); + if let Err(e) = commit_path(app, &pen, closed) { + app.ui.pen = Some(PenPath { commit_failed: true, ..pen }); + app.ui.status = e; + app.ui.status_error = true; + } } fn knot_points(k: &photocraft_doc::Knot) -> [[f64; 2]; 3] { @@ -530,3 +776,40 @@ fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, corners.dedup(); (PenPath { knots, unlinked: corners, ..Default::default() }, closed) } + +use super::{PenOwner, cancel_stale_pen, capture_pen_owner}; + +fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) -> Result<(), String> { + let Some(owner) = pen.owner.as_ref().filter(|o| o.valid(app)) else { return Err("Pen draft target is stale; no path was changed".into()) }; + let options = std::mem::replace(&mut app.ui.tool_options, owner.options.clone()); + let vector_mask = std::mem::replace(&mut app.ui.vector_mask_target, owner.vector_mask); + app.ui.selected_path = match &owner.target { + super::PenTarget::Path { name, append } => append.then(|| name.clone()), + _ => None, + }; + if let Some(st) = app.session.active_mut() { + st.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); + if let Some(st) = app.session.active_mut() { + st.channel_view.target = if matches!(owner.target, super::PenTarget::VectorMask(_)) { + photocraft_engine::channel_cmds::ChannelTarget::VectorMask + } else { + photocraft_engine::channel_cmds::ChannelTarget::Composite + }; + } + let result = commit_path_current(app, pen, closed); + if result && matches!(owner.target, super::PenTarget::Shape { .. } | super::PenTarget::VectorMask(_)) { + app.ui.selected_path = Some("layer".into()); + } + if let (Some(st), Some(channel)) = (app.session.active_mut(), channel) { + st.channel_view.target = channel; + } + app.session.tools.foreground = foreground; + app.session.tools.background = background; + app.ui.tool_options = options; + app.ui.vector_mask_target = vector_mask; + if result { Ok(()) } else { Err(app.ui.status.clone()) } +} diff --git a/crates/ui-egui/src/tools/vector_ui/pen_draw_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_draw_tests.rs index e11bd4abf2..720cd7e611 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_draw_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_draw_tests.rs @@ -96,6 +96,34 @@ fn near(a: [f64; 2], b: [f64; 2]) -> bool { (a[0] - b[0]).abs() < 0.05 && (a[1] - b[1]).abs() < 0.05 } +#[test] +fn space_repositions_a_pen_anchor_and_keeps_its_handles() { + let mut h = harness(); + h.state_mut().ui.extras.snap = false; + click(&mut h, [20.0, 20.0]); + let center = h.state().ui.views[0].center; + let p = screen(&h, [80.0, 50.0]); + h.event(egui::Event::PointerMoved(p)); + button(&mut h, p, true, Modifiers::NONE); + move_to(&mut h, [80.0, 50.0], [100.0, 60.0]); + h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + move_to(&mut h, [100.0, 60.0], [120.0, 90.0]); + let k = h.state().ui.pen.as_ref().unwrap().knots[1]; + assert!(near(k[0], [100.0, 80.0]) && near(k[1], [80.0, 70.0]) && near(k[2], [120.0, 90.0]), "anchor and handles moved together: {k:?}"); + assert_eq!(h.state().ui.views[0].center, center, "the canvas never pans"); + h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + move_to(&mut h, [120.0, 90.0], [130.0, 80.0]); + let p = screen(&h, [130.0, 80.0]); + button(&mut h, p, false, Modifiers::NONE); + let k = h.state().ui.pen.as_ref().unwrap().knots[1]; + assert!(near(k[0], [100.0, 80.0]) && near(k[1], [70.0, 80.0]) && near(k[2], [130.0, 80.0]), "releasing Space resumes handle shaping: {k:?}"); + h.key_press(Key::Enter); + h.run_steps(2); + assert!(h.state().session.active().unwrap().doc.work_path.is_some()); +} + #[test] fn alt_breaks_the_handle_being_dragged_and_grabs_the_last_outgoing_handle() { let mut h = harness(); diff --git a/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs new file mode 100644 index 0000000000..25ae41650b --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/pen_path_ops_tests.rs @@ -0,0 +1,350 @@ +//! The Pen's Path Operations (#1397, #7533): New Layer, Combine Shapes, Subtract Front Shape, +//! Intersect Shape Areas and Exclude Overlapping Shapes decide how a new path joins the shape or +//! path it is drawn into, and Merge Shape Components bakes them, as in Photoshop's options bar. + +use egui::vec2; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::vector::PathOp; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use super::{pen_down, pen_path_op, pen_up}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = Tool::Pen; + app +} + +/// Clicks a closed square with the Pen, from `(x, y)` with side `side`. +fn square(app: &mut PhotocraftApp, x: f64, y: f64, side: f64) { + for (dx, dy) in [(0.0, 0.0), (side, 0.0), (side, side), (0.0, side)] { + pen_down(app, x + dx, y + dy, false); + pen_up(app); + } + pen_down(app, x + 0.5, y + 0.5, false); // close + pen_up(app); +} + +fn shape_path(app: &PhotocraftApp) -> (LayerId, Path) { + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + match &st.doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => (id, sh.path.clone()), + _ => panic!("not a shape layer"), + } +} + +fn work(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.work_path.clone().expect("a work path") +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +fn covered(path: &Path, x: i32, y: i32) -> f32 { + photocraft_vector::fill_rasterizer(path, photocraft_vector::DEFAULT_TOLERANCE).render(photocraft_geom::Rect::from_xywh(x, y, 1, 1))[0] +} + +/// The issue's mug: the body is drawn, then the hole in its handle is cut out of the same shape +/// layer with Subtract Front Shape, one History step each. +#[test] +fn subtract_front_shape_cuts_a_hole_in_the_selected_shape_layer() { + let mut app = app(); + app.ui.tool_options.vector_mode = "shape".into(); + assert_eq!(app.ui.tool_options.pen_path_op, "newLayer", "Photoshop's default in Shape mode"); + square(&mut app, 20.0, 20.0, 100.0); + let (id, _) = shape_path(&app); + let count = layers(&app); + app.ui.tool_options.pen_path_op = "subtract".into(); + square(&mut app, 50.0, 50.0, 40.0); + let (same, path) = shape_path(&app); + assert_eq!((same, layers(&app)), (id, count), "no new layer"); + assert_eq!(path.subpaths.iter().map(|s| s.op).collect::>(), [PathOp::Combine, PathOp::Subtract]); + assert_eq!((covered(&path, 70, 70), covered(&path, 30, 30)), (0.0, 1.0), "a hole in the body"); + app.session.undo(); + assert_eq!(shape_path(&app).1.subpaths.len(), 1, "undo takes back only the hole"); + app.session.redo(); + // Intersect and Exclude are stored the same way. + for (op, want) in [("intersect", PathOp::Intersect), ("exclude", PathOp::Exclude), ("combine", PathOp::Combine)] { + app.ui.tool_options.pen_path_op = op.into(); + square(&mut app, 10.0, 10.0, 30.0); + assert_eq!(shape_path(&app).1.subpaths.last().map(|s| s.op), Some(want), "{op}"); + } + assert_eq!(layers(&app), count); + // New Layer makes another shape layer again. + app.ui.tool_options.pen_path_op = "newLayer".into(); + square(&mut app, 10.0, 10.0, 30.0); + assert_eq!(layers(&app), count + 1); + assert_ne!(shape_path(&app).0, id); +} + +/// A locked shape layer refuses the new component: the path drawn stays as the Pen's draft, and +/// the document and History are unchanged. Unlocking advances the source revision, so the old +/// captured draft refuses; a fresh draft on the unlocked source cuts the hole. +#[test] +fn a_locked_shape_layer_keeps_the_drawn_path() { + for lock in ["all", "pixels"] { + let mut app = app(); + app.ui.tool_options.vector_mode = "shape".into(); + square(&mut app, 20.0, 20.0, 100.0); + let (id, body) = shape_path(&app); + app.run("layer.lockLayers", json!({lock: true})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + app.ui.tool_options.pen_path_op = "subtract".into(); + square(&mut app, 50.0, 50.0, 40.0); + let draft = app.ui.pen.clone().unwrap_or_else(|| panic!("{lock}: the draft is kept")); + // The four corners and the close's stand-in on the first: still a closed path. + assert!(draft.knots.len() == 5 && super::closing(&draft), "{lock}: {:?}", draft.knots); + assert!(app.ui.status_error, "{lock}: {}", app.ui.status); + assert_eq!(shape_path(&app), (id, body.clone()), "{lock}: the shape is unchanged"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "{lock}: no History step"); + // Undo takes back the lock, not the drawn path. + app.session.undo(); + assert!(app.ui.pen.is_some(), "{lock}"); + assert!(super::pen_commit(&mut app, false), "{lock}: {}", app.ui.status); // ↩ + assert!(app.ui.pen.is_none(), "{lock}"); + assert_eq!(shape_path(&app), (id, body.clone()), "a stale draft cannot overwrite the unlocked source"); + assert!(app.ui.status_error && app.ui.status.contains("newer work was preserved")); + square(&mut app, 50.0, 50.0, 40.0); + let (same, path) = shape_path(&app); + assert_eq!(same, id, "{lock}"); + assert_eq!(path.subpaths.iter().map(|s| (s.op, s.closed)).collect::>(), [(PathOp::Combine, true), (PathOp::Subtract, true)], "{lock}"); + assert_eq!(covered(&path, 70, 70), 0.0, "{lock}: the hole"); + } +} + +/// A hole drawn for a locked shape layer: the Pen's draft, refused, and the History length then. +fn refused_hole(app: &mut PhotocraftApp) -> (LayerId, Path, usize) { + app.ui.tool_options.vector_mode = "shape".into(); + square(app, 20.0, 20.0, 100.0); + let (id, body) = shape_path(app); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + app.ui.tool_options.pen_path_op = "subtract".into(); + square(app, 50.0, 50.0, 40.0); + assert!(app.ui.pen.is_some() && app.ui.status_error, "refused: {}", app.ui.status); + (id, body, steps) +} + +/// The refused hole ended for good: kept, closed, as the Work Path, one History step; the locked +/// shape is as it was. +fn assert_kept_as_work_path(app: &PhotocraftApp, id: LayerId, body: &Path, steps: usize) { + assert!(app.ui.pen.is_none() && app.ui.pen_doc.is_none()); + assert_eq!(shape_path(app), (id, body.clone()), "the locked shape is unchanged"); + let w = work(app); + assert_eq!(w.subpaths.len(), 1); + assert_eq!(w.subpaths[0].knots.len(), 4); + assert!(w.subpaths[0].closed); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); + assert!(app.ui.status.contains(tl!("The path was kept as the Work Path")), "{}", app.ui.status); +} + +/// Switching to another tool with a refused draft (feedback on #7648): it was committed again on +/// every frame, re-running `shape.create` and the error. Now it is ended once: kept as the Work +/// Path, and later frames do nothing more. +#[test] +fn switching_tools_ends_a_refused_draft_once() { + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app() + }); + h.run_steps(2); + let (id, body, steps) = refused_hole(h.state_mut()); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(2); + assert_kept_as_work_path(h.state(), id, &body, steps); + let status = h.state().ui.status.clone(); + h.run_steps(4); + assert_eq!(h.state().ui.status, status, "no retry"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); +} + +/// Esc with a refused draft ends it the same way; ↩ keeps it as the draft, to commit again once +/// the layer is unlocked. +#[test] +fn esc_ends_a_refused_draft_and_return_keeps_it() { + let ctx = egui::Context::default(); + let key = |app: &mut PhotocraftApp, key: egui::Key| { + let raw = egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + for lang in crate::i18n::Lang::all() { + crate::i18n::with_language(lang, || { + for message in ["The path was kept as the Work Path", "The path was discarded"] { + if lang != crate::i18n::Lang::EN { + assert!(crate::i18n::has(lang, message), "{}: {message}", lang.code()); + } + } + let mut app = app(); + let (id, body, steps) = refused_hole(&mut app); + let draft = app.ui.pen.clone(); + key(&mut app, egui::Key::Enter); + assert_eq!(app.ui.pen, draft, "↩ keeps the draft"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + let refused = app.ui.status.clone(); + key(&mut app, egui::Key::Escape); + assert_kept_as_work_path(&app, id, &body, steps); + assert_eq!(app.ui.status, format!("{refused} ({})", tl!("The path was kept as the Work Path"))); + }); + } +} + +/// With no shape layer selected, an operation other than New Layer still starts a shape layer +/// (Photoshop: there is nothing to combine with), and the next path joins it. +#[test] +fn an_operation_without_a_selected_shape_starts_a_new_shape_layer() { + let mut app = app(); + app.ui.tool_options.vector_mode = "shape".into(); + app.ui.tool_options.pen_path_op = "subtract".into(); + let count = layers(&app); + square(&mut app, 20.0, 20.0, 100.0); + let (id, path) = shape_path(&app); + assert_eq!((layers(&app), path.subpaths.len()), (count + 1, 1)); + assert_eq!(covered(&path, 60, 60), 1.0, "a lone first component draws"); + square(&mut app, 50.0, 50.0, 40.0); + assert_eq!((shape_path(&app).0, layers(&app)), (id, count + 1)); +} + +/// Path mode has no New Layer (it combines); the other operations are stored on each subpath +/// added to the Work Path, a selected saved path or a targeted vector mask. +#[test] +fn path_mode_adds_subpaths_with_the_operation() { + let mut app = app(); + assert_eq!(pen_path_op(&app.ui.tool_options), Some("combine")); + square(&mut app, 20.0, 20.0, 100.0); + square(&mut app, 30.0, 30.0, 10.0); + app.ui.tool_options.pen_path_op = "intersect".into(); + square(&mut app, 50.0, 50.0, 100.0); + assert_eq!(work(&app).subpaths.iter().map(|s| s.op).collect::>(), [PathOp::Combine, PathOp::Combine, PathOp::Intersect]); + // A selected saved path. + app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"closed": true, "knots": [[2, 2], [60, 2], [60, 60]]}]}})).unwrap(); + app.ui.selected_path = Some("Saved".into()); + app.ui.tool_options.pen_path_op = "exclude".into(); + square(&mut app, 10.0, 10.0, 20.0); + let saved = app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Saved").unwrap().path.clone(); + assert_eq!(saved.subpaths.last().map(|s| s.op), Some(PathOp::Exclude)); + // A targeted vector mask. + let id = app.session.active().unwrap().active_layer.unwrap().0; + app.run("layer.vectorMask.add", json!({"layer": id, "path": {"subpaths": [{"closed": true, "knots": [[0, 0], [100, 0], [100, 100], [0, 100]]}]}})).unwrap(); + app.ui.vector_mask_target = true; + app.ui.tool_options.pen_path_op = "subtract".into(); + square(&mut app, 20.0, 20.0, 30.0); + let vm = app.session.active().unwrap().doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap(); + assert_eq!(vm.path.subpaths.iter().map(|s| s.op).collect::>(), [PathOp::Combine, PathOp::Subtract]); +} + +/// The options bar's Path Operations button sets the operation, offers New Layer only in Shape +/// mode, and its Merge Shape Components bakes the path the Pen draws into. +#[test] +fn the_options_bar_menu_sets_the_operation_and_merges() { + let mut app = app(); + square(&mut app, 20.0, 20.0, 100.0); + app.ui.tool_options.pen_path_op = "subtract".into(); + square(&mut app, 50.0, 50.0, 40.0); + app.ui.tool_options.pen_path_op = "combine".into(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1100.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal(|ui| super::options_bar(app, ui, Tool::Pen)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + let open = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + h.get_by_label("Path operations").click(); + h.run_steps(3); + }; + open(&mut h); + assert!(h.get_by_label("New Layer").accesskit_node().is_disabled(), "Path mode has no New Layer"); + h.get_by_label("Exclude Overlapping Shapes").click(); + h.run_steps(3); + assert_eq!(h.state().ui.tool_options.pen_path_op, "exclude"); + assert!(h.query_by_label("Exclude Overlapping Shapes").is_none(), "choosing closes the menu"); + // Merge Shape Components: the Work Path's hole stays a hole, now as plain outlines. + let before = work(h.state()); + open(&mut h); + h.get_by_label("Merge Shape Components").click(); + h.run_steps(3); + let merged = work(h.state()); + assert_ne!(merged, before); + assert_eq!((covered(&merged, 70, 70), covered(&merged, 30, 30)), (0.0, 1.0)); + // Shape mode offers New Layer. + h.state_mut().ui.tool_options.vector_mode = "shape".into(); + h.run_steps(2); + open(&mut h); + assert!(!h.get_by_label("New Layer").accesskit_node().is_disabled()); + h.get_by_label("New Layer").click(); + h.run_steps(3); + assert_eq!(pen_path_op(&h.state().ui.tool_options), None); +} + +/// Merge Shape Components is disabled where there is nothing to merge: one component, or in Shape +/// mode no shape layer selected. +#[test] +fn merge_is_disabled_with_fewer_than_two_components() { + let mut app = app(); + square(&mut app, 20.0, 20.0, 100.0); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1100.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal(|ui| super::options_bar(app, ui, Tool::Pen)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h.get_by_label("Path operations").click(); + h.run_steps(3); + assert!(h.get_by_label("Merge Shape Components").accesskit_node().is_disabled()); +} + +/// An unknown stored operation (an edited settings file) falls back to New Layer, never panics. +#[test] +fn an_unknown_operation_falls_back_to_new_layer() { + let mut app = app(); + app.ui.tool_options.pen_path_op = "melt".into(); + assert_eq!(pen_path_op(&app.ui.tool_options), Some("combine")); + app.ui.tool_options.vector_mode = "shape".into(); + assert_eq!(pen_path_op(&app.ui.tool_options), None); + let count = layers(&app); + square(&mut app, 20.0, 20.0, 50.0); + square(&mut app, 30.0, 30.0, 50.0); + assert_eq!(layers(&app), count + 2); +} + +#[test] +fn freeform_refuses_a_locked_shape_before_starting_a_stroke() { + use crate::canvas::{ToolEvent, tool_event}; + for lock in ["all", "pixels"] { + let mut app = app(); + app.ui.tool_options.vector_mode = "shape".into(); + square(&mut app, 20.0, 20.0, 100.0); + let (id, body) = shape_path(&app); + app.run("layer.lockLayers", json!({lock: true})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + app.ui.tool = Tool::FreeformPen; + app.ui.tool_options.pen_path_op = "subtract".into(); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none(), "{lock}: stroke was not started"); + assert!(app.ui.status_error, "{lock}"); + assert_eq!(shape_path(&app), (id, body), "{lock}"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "{lock}"); + app.session.undo(); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_some(), "{lock}: unlocked stroke can start"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs index 31de3650e9..1fa3fa1c5e 100644 --- a/crates/ui-egui/src/tools/vector_ui/tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/tests.rs @@ -78,7 +78,7 @@ fn all_shape_tools_and_open_pen_use_the_complete_stroke_defaults() { a.run("edit.redo", json!({})).unwrap(); assert_eq!(a.run("shape.info", json!({})).unwrap(), info); a.ui.tool_options.vector_mode = "shape".into(); - a.ui.pen = Some(PenPath { knots: vec![[[30.0, 40.0]; 3], [[80.0, 40.0]; 3]], ..Default::default() }); + a.ui.pen = Some(PenPath { knots: vec![[[30.0, 40.0]; 3], [[80.0, 40.0]; 3]], owner: capture_pen_owner(&a), ..Default::default() }); pen_commit(&mut a, false); let open = a.run("shape.info", json!({})).unwrap(); assert_eq!(open["stroke"]["dashes"], info["stroke"]["dashes"]); @@ -86,6 +86,44 @@ fn all_shape_tools_and_open_pen_use_the_complete_stroke_defaults() { } } +#[test] +fn freeform_straight_segments_keep_the_captured_saved_path_and_reject_a_foreign_document() { + let mut app = app(); + app.ui.tool = Tool::FreeformPen; + let seed = json!({"subpaths":[{"knots":[[20,20],[120,20]]}]}); + for name in ["work", "Saved drawing"] { + app.run("path.set", json!({"name": name, "path": seed})).unwrap(); + } + app.ui.selected_path = Some("Saved drawing".into()); + let owner = capture_pen_owner(&app).unwrap(); + let original = app.session.active().unwrap().doc.clone(); + let n = app.session.active().unwrap().history.past_len(); + let points = [[20.0, 60.0, 1.0], [60.0, 60.0, 1.0], [100.0, 80.0, 1.0], [140.0, 80.0, 1.0]]; + app.ui.selected_path = Some("work".into()); + app.ui.tool_options.vector_mode = "shape".into(); + freeform_finish_owned(&mut app, &points, &[1, 3], owner); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.work_path, original.work_path); + let saved = &st.doc.paths.iter().find(|p| p.name == "Saved drawing").unwrap().path; + assert_eq!(saved.subpaths[0], original.paths[0].path.subpaths[0]); + assert_eq!(saved.subpaths.len(), 2); + let knots = &saved.subpaths[1].knots; + assert_eq!(knots.len(), 4); + for (a, b) in [(0, 1), (2, 3)] { + assert_eq!(knots[a].out_ctrl, knots[a].anchor, "straight segment starts at its anchor"); + assert_eq!(knots[b].in_ctrl, knots[b].anchor, "straight segment ends at its anchor"); + } + assert_eq!(st.history.past_len(), n + 1); + assert!(app.ui.pen.is_none()); + app.ui.tool_options.vector_mode = "path".into(); + let owner = capture_pen_owner(&app).unwrap(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let (source, n) = (app.session.active().unwrap().doc.clone(), app.session.active().unwrap().history.past_len()); + freeform_finish_owned(&mut app, &points, &[1, 3], owner); + assert!(Arc::ptr_eq(&source, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), n); +} + fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); @@ -121,6 +159,24 @@ fn paths_context_menu_uses_the_clicked_row_and_dispatches_commands() { assert_eq!(duplicate["name"], "First copy 2", "duplicate must not overwrite an existing path"); } +#[test] +fn failed_freeform_straight_segment_commit_keeps_its_owned_fitted_draft() { + let mut app = app(); + app.ui.tool = Tool::FreeformPen; + let owner = capture_pen_owner(&app).unwrap(); + let (source, n) = (app.session.active().unwrap().doc.clone(), app.session.active().unwrap().history.past_len()); + let points = [[20.0, 60.0, 1.0], [1e40, 60.0, 1.0], [140.0, 80.0, 1.0]]; + freeform_finish_owned(&mut app, &points, &[1, 2], owner.clone()); + let pen = app.ui.pen.as_ref().expect("invalid fitted geometry must remain available after its failed commit"); + assert!(pen.commit_failed); + assert_eq!(pen.owner.as_ref(), Some(&owner)); + assert!(owner.valid(&app)); + assert_eq!(pen.knots.len(), 3); + assert_eq!(pen.knots[1], [[1e40, 60.0]; 3]); + assert!(Arc::ptr_eq(&source, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), n); +} + #[test] fn work_path_context_save_and_layer_path_deletion_rules() { let mut app = app(); @@ -232,7 +288,7 @@ fn pen_keeps_anchors_of_a_finished_path() { let mut app = app(); app.ui.tool = Tool::Pen; let knots = vec![[[10.0, 10.0]; 3], [[80.0, 10.0]; 3], [[80.0, 80.0]; 3]]; - app.ui.pen = Some(PenPath { knots, ..Default::default() }); + app.ui.pen = Some(PenPath { knots, owner: capture_pen_owner(&app), ..Default::default() }); pen_commit(&mut app, true); assert!(app.ui.pen.is_none()); assert!(app.session.active().unwrap().doc.work_path.is_some()); @@ -329,7 +385,7 @@ fn show_target_path_and_extras_hide_the_path_outlines() { } // The Pen's path in progress is a gesture, not the target path: it stays visible. app.ui.tool = Tool::Pen; - app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[60.0, 40.0]; 3]], ..Default::default() }); + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[60.0, 40.0]; 3]], owner: capture_pen_owner(&app), ..Default::default() }); toggle(&mut app, "view.show.targetPath"); assert!(overlay_shapes(&app, &ctx) > 0, "the pen path in progress is still drawn"); } @@ -340,7 +396,7 @@ fn making_a_selection_from_the_pen_path_deselects_and_hides_it() { let ctx = egui::Context::default(); let mut app = app(); app.ui.tool = Tool::Pen; - app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[120.0, 20.0]; 3], [[120.0, 80.0]; 3]], ..Default::default() }); + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[120.0, 20.0]; 3], [[120.0, 80.0]; 3]], owner: capture_pen_owner(&app), ..Default::default() }); path_to_selection(&mut app, json!({})).unwrap(); let st = app.session.active().unwrap(); assert!(st.doc.selection.is_some(), "the selection is made"); @@ -376,14 +432,14 @@ fn making_a_selection_from_the_pen_path_deselects_and_hides_it() { // A new path drawn after the deselect replaces the work path and is shown. path_to_selection(&mut app, json!({})).unwrap(); assert_eq!(overlay_shapes(&app, &ctx), 0); - app.ui.pen = Some(PenPath { knots: vec![[[10.0, 10.0]; 3], [[40.0, 10.0]; 3]], ..Default::default() }); + app.ui.pen = Some(PenPath { knots: vec![[[10.0, 10.0]; 3], [[40.0, 10.0]; 3]], owner: capture_pen_owner(&app), ..Default::default() }); pen_commit(&mut app, false); assert_eq!(app.ui.selected_path.as_deref(), Some("work")); assert_eq!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths.len(), 1, "replaced, not combined"); assert!(overlay_shapes(&app, &ctx) > 0); // A shape layer's path stays the active path: layer targeting is unchanged. app.ui.tool_options.vector_mode = "shape".into(); - app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[120.0, 20.0]; 3], [[120.0, 80.0]; 3]], ..Default::default() }); + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[120.0, 20.0]; 3], [[120.0, 80.0]; 3]], owner: capture_pen_owner(&app), ..Default::default() }); path_to_selection(&mut app, json!({})).unwrap(); assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); assert!(active_shape_path(&app).is_some()); @@ -734,12 +790,14 @@ fn failed_stale_pen_commit_preserves_the_draft_until_retry() { let mut app = app(); app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[5, 5], [10, 10]]}]}})).unwrap(); let original = app.session.active().unwrap().doc.work_path.clone().unwrap(); + app.ui.selected_path = Some("work".into()); app.ui.tool = Tool::Pen; for (x, y) in [(20.0, 20.0), (80.0, 60.0)] { pen_down(&mut app, x, y, false); pen_up(&mut app); } - let draft = app.ui.pen.clone(); + let mut draft = app.ui.pen.clone(); + draft.as_mut().unwrap().commit_failed = true; let owner = app.ui.pen_doc; app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); app.ui.tool_options.vector_mode = "shape".into(); @@ -749,7 +807,9 @@ fn failed_stale_pen_commit_preserves_the_draft_until_retry() { "pen" => pen_down(&mut app, 150.0, 150.0, false), "curvature" => curvature_down(&mut app, 150.0, 150.0), "undo" => assert!(!pen_undo_last_point(&mut app)), - "commit" => pen_commit(&mut app, true), + "commit" => { + pen_commit(&mut app, true); + } _ => { assert!(app.run("file.close", json!({})).is_err()); } @@ -763,6 +823,9 @@ fn failed_stale_pen_commit_preserves_the_draft_until_retry() { assert!(!crate::direct_select::candidates(&app).iter().any(|(target, _)| *target == crate::direct_select::PathRef::Pen)); app.session.authorize = None; app.sync_views(); + assert_eq!(app.ui.pen, draft, "passive frames do not retry a refused commit"); + assert_eq!(app.session.documents()[0].doc.work_path.as_ref(), Some(&original)); + assert!(pen_commit(&mut app, false), "the user explicitly retries the valid captured target"); assert!(app.ui.pen.is_none()); assert_eq!(app.session.active_index(), Some(1)); assert_eq!(app.ui.selected_path.as_deref(), Some("foreign named path")); @@ -784,7 +847,8 @@ fn new_document_reports_a_failed_work_path_save_and_retains_the_draft() { pen_up(&mut app); pen_down(&mut app, 80.0, 60.0, false); pen_up(&mut app); - let draft = app.ui.pen.clone(); + let mut draft = app.ui.pen.clone(); + draft.as_mut().unwrap().commit_failed = true; app.session.authorize = Some(|id, _| if id == "path.set" { Err(photocraft_engine::EngineError::Other("test rejection".into())) } else { Ok(()) }); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); assert!(app.ui.status_error); @@ -794,6 +858,9 @@ fn new_document_reports_a_failed_work_path_save_and_retains_the_draft() { assert!(app.session.documents().iter().all(|d| d.doc.work_path.is_none())); app.session.authorize = None; app.sync_views(); + assert_eq!(app.ui.pen, draft, "passive frames retain the refused draft"); + assert!(app.session.documents().iter().all(|d| d.doc.work_path.is_none())); + assert!(pen_commit(&mut app, false), "explicit retry commits to the captured source"); assert!(app.ui.pen.is_none()); assert!(app.session.documents()[0].doc.work_path.is_some()); assert!(app.session.documents()[1].doc.work_path.is_none()); @@ -853,7 +920,9 @@ fn stale_pen_commits_to_its_owner_across_document_changes() { "pen" => pen_down(&mut app, 150.0, 150.0, false), "curvature" => curvature_down(&mut app, 150.0, 150.0), "undo" => assert!(!pen_undo_last_point(&mut app)), - "commit" => pen_commit(&mut app, true), + "commit" => { + pen_commit(&mut app, true); + } _ => app.sync_views(), } let source = app.session.documents().iter().find(|d| d.doc.id == owner).unwrap(); @@ -1117,7 +1186,8 @@ fn pen_last_anchor_hit_tolerance_tracks_zoom_and_draft_round_trips() { assert_eq!(pen.knots[1][2], pen.knots[1][0]); let saved = serde_json::to_value(pen).unwrap(); let restored: PenPath = serde_json::from_value(saved).unwrap(); - assert_eq!(restored, *pen); + // The runtime owner isn't saved: a restored draft belongs to no document. + assert_eq!(restored, PenPath { owner: None, ..pen.clone() }); assert_eq!(pen_to_json(&restored, false)["subpaths"][0]["knots"][1]["smooth"], false); pen_down(&mut app, 100.0 + 7.0 / f64::from(zoom), 100.0, false); assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 3); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 72a09569f2..752e40a2bf 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -7,7 +7,7 @@ use crate::theme::{self, Tokens}; mod angle_dial; mod color_count; -pub use angle_dial::angle_dial_row; +pub use angle_dial::{angle_dial_line, angle_dial_row}; pub use color_count::color_count_row; mod type_ahead; pub use type_ahead::list_open as dropdown_list_open; @@ -57,7 +57,7 @@ pub use panel::{ pub use scrub::{scrub_label, scrub_option_icon, scrub_option_label}; #[cfg(test)] use slider::DOUBLE_CLICK_S; -pub use slider::{RowGestures, second_click, slider, slider_row, slider_row_prec, slider_row_with}; +pub use slider::{RowGestures, row_label, second_click, slider, slider_line, slider_row, slider_row_prec, slider_row_with}; pub(crate) use slider::{count_notches, wheel_notches_of}; #[cfg(test)] pub(crate) use slider::{curve_fraction, curve_value}; diff --git a/crates/ui-egui/src/widgets/angle_dial.rs b/crates/ui-egui/src/widgets/angle_dial.rs index a21b453ded..1fd693051b 100644 --- a/crates/ui-egui/src/widgets/angle_dial.rs +++ b/crates/ui-egui/src/widgets/angle_dial.rs @@ -2,19 +2,32 @@ //! Drop Shadow's light (#882), Motion Blur and the other direction angles of the filter //! dialogs (#3152) share it, as Photoshop's dialogs do. -use super::{Response, Sense, Stroke, Tokens, Ui, value_field, vec2}; +use super::{Response, Sense, Stroke, Tokens, Ui, row_label, value_field, vec2}; /// `Label (dial) [field°]` for a direction in document angles: counter-clockwise from three /// o'clock, y up. The dial points anywhere in -180..=180; the result is clamped to `range`, and /// the field accepts the whole of `range` (Motion Blur takes -360..=360, so a typed or /// remembered 270° stays 270°). pub fn angle_dial_row(ui: &mut Ui, label: &str, angle: &mut f32, range: std::ops::RangeInclusive) -> Response { + angle_dial_line(ui, label, None, angle, range) +} + +/// [`angle_dial_row`] with its label right-aligned in a `label_w` column ([`row_label`]) when +/// given, lined up with the [`slider_line`] rows around it (Layer Style). +pub fn angle_dial_line(ui: &mut Ui, label: &str, label_w: Option, angle: &mut f32, range: std::ops::RangeInclusive) -> Response { let t = Tokens::get(ui.ctx()); // The dial clamps with max/min, not `f32::clamp`, which panics if a malformed spec // reverses the range. let (lo, hi) = (*range.start(), *range.end()); ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!(label)).color(t.text_dim)); + match label_w { + Some(w) => { + row_label(ui, label, w); + } + None => { + ui.label(egui::RichText::new(tl!(label)).color(t.text_dim)); + } + } let (rect, mut dial) = ui.allocate_exact_size(vec2(42.0, 42.0), Sense::click_and_drag()); dial.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), tl!(label))); if (dial.clicked() || dial.dragged()) diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs index c4112fecb5..72f2987a41 100644 --- a/crates/ui-egui/src/widgets/slider.rs +++ b/crates/ui-egui/src/widgets/slider.rs @@ -1,4 +1,4 @@ -use super::fields::{FieldOpts, value_field_in}; +use super::fields::{FieldOpts, VALUE_FIELD_H, value_field_in}; use super::panel::surface; use super::scrub::scrub_label_within; use super::{Color32, Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, pos2, vec2}; @@ -287,3 +287,46 @@ pub fn slider_row_prec( ui.add_space(4.0); r } + +/// A dialog row's label, right-aligned in a column `width` wide, so the controls after it line up +/// (Photoshop's label column in Layer Style). A label too long for it, as some translations are, +/// is cut short and shows in full on hover. +pub fn row_label(ui: &mut Ui, label: &str, width: f32) -> Response { + let t = Tokens::get(ui.ctx()); + ui.allocate_ui_with_layout(vec2(width, VALUE_FIELD_H), egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.set_min_width(width); + ui.add(egui::Label::new(egui::RichText::new(tl!(label)).color(t.text_dim)).truncate()) + }) + .inner +} + +/// [`slider_row`] on one line, as Photoshop lays out Layer Style: the label in a `label_w` column +/// ([`row_label`]), the slider, then the value field. The label still scrubs the field. +pub fn slider_line(ui: &mut Ui, label: &str, label_w: f32, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str) -> Response { + const FIELD_W: f32 = 64.0; + let mut field = None; + let s = ui + .horizontal(|ui| { + let l = row_label(ui, label, label_w); + scrub_label_within(ui, &l, f32::INFINITY); + let w = (ui.available_width() - FIELD_W - ui.spacing().item_spacing.x).max(60.0); + let s = ui + .allocate_ui_with_layout(vec2(w, VALUE_FIELD_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { + slider_with(ui, value, range.clone(), None, RowGestures::default()) + }) + .inner; + field = Some(value_field_in(ui, value, range.clone(), suffix, FIELD_W, 0.0, FieldOpts::default(), Some(label)).0); + s + }) + .inner; + let mut r = s.clone(); + if let Some(v) = field { + if v.changed() { + r.mark_changed(); + } + // A scrub of the field or its label is one drag, like the slider's, for history. + use egui::response::Flags; + r.flags |= v.flags & (Flags::DRAG_STARTED | Flags::DRAGGED | Flags::DRAG_STOPPED); + } + r +} diff --git a/crates/ui-egui/tests/it/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/adjust_preview_gpu.rs index d3880b04fd..2fdae54cbe 100644 --- a/crates/ui-egui/tests/it/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/it/adjust_preview_gpu.rs @@ -23,7 +23,9 @@ fn block_on(f: F) -> F::Output { } fn gpu() -> Option<(wgpu::Device, wgpu::Queue, Compositor)> { - let adapter = match block_on(wgpu::Instance::default().request_adapter(&wgpu::RequestAdapterOptions::default())) { + let adapter = match block_on( + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&wgpu::RequestAdapterOptions::default()), + ) { Ok(a) => a, Err(e) => { eprintln!("skipping adjustment preview GPU parity: no adapter ({e})"); diff --git a/crates/ui-egui/tests/it/layout_perf.rs b/crates/ui-egui/tests/it/layout_perf.rs index 2b5cf73bf1..b8f43f4733 100644 --- a/crates/ui-egui/tests/it/layout_perf.rs +++ b/crates/ui-egui/tests/it/layout_perf.rs @@ -232,7 +232,9 @@ fn layout_document_composites_on_the_gpu_like_the_cpu() { std::thread::yield_now(); } } - let Ok(adapter) = block_on(wgpu::Instance::default().request_adapter(&wgpu::RequestAdapterOptions::default())) else { + let Ok(adapter) = + block_on(wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()).request_adapter(&wgpu::RequestAdapterOptions::default())) + else { eprintln!("skipping: no GPU adapter"); return; }; diff --git a/crates/vector/src/feather.rs b/crates/vector/src/feather.rs index 5048916d49..2e3cd10d08 100644 --- a/crates/vector/src/feather.rs +++ b/crates/vector/src/feather.rs @@ -42,6 +42,21 @@ pub fn path_area(path: &Path, sigma: f32) -> Rect { } } +/// The largest buffer (in `f32`s) the blur has allocated, for tests of its working set. +#[cfg(test)] +static LARGEST_BUFFER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Tests make [`line_buffers`] fail for lines of this many samples (0: never). +#[cfg(test)] +static FAIL_LINE_BUFFERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Notes a blur buffer of `len` floats ([`LARGEST_BUFFER`]); nothing outside tests. +fn note_buffer(len: usize) { + #[cfg(test)] + LARGEST_BUFFER.fetch_max(len, std::sync::atomic::Ordering::Relaxed); + let _ = len; +} + /// One box pass: weight 1 on `±r` around each sample and `end` (0..1) on the two samples just /// beyond, so the pass's variance is any real number, not only the `r(r+1)/3` of whole boxes. #[derive(Clone, Copy, Debug, PartialEq)] @@ -99,34 +114,77 @@ fn blur_line(line: &mut [f32], scratch: &mut [f32], pass: BoxPass) { /// Apply three clamped box passes to independent contiguous rows. Scoped OS threads are used /// instead of Rayon because mask construction can happen inside a Rayon tile job; nested Rayon /// work here can deadlock when every worker waits on the same OnceLock (#276). -fn blur_rows_chunk(v: &mut [f32], w: usize, pass: BoxPass) { - let mut scratch = vec![0.0; w]; +fn blur_rows_chunk(v: &mut [f32], w: usize, pass: BoxPass, halo: usize, buffers: &mut (Vec, Vec)) { + let (padded, scratch) = buffers; for row in v.chunks_mut(w) { - for _ in 0..3 { - blur_line(row, &mut scratch, pass); - } + blur_padded_line(row, padded, scratch, pass, halo); } } -fn blur_rows(v: &mut [f32], w: usize, pass: BoxPass) { - if w == 0 || v.is_empty() { +/// A padded line and its scratch for lines of `len` samples with `halo` more on each side; `None` +/// when they don't fit in memory. +fn line_buffers(len: usize, halo: usize) -> Option<(Vec, Vec)> { + #[cfg(test)] + if FAIL_LINE_BUFFERS.load(std::sync::atomic::Ordering::Relaxed) == len { + return None; + } + let n = halo.checked_mul(2)?.checked_add(len)?; + let (mut padded, mut scratch) = (Vec::new(), Vec::new()); + padded.try_reserve_exact(n).ok()?; + scratch.try_reserve_exact(n).ok()?; + padded.resize(n, 0.0); + scratch.resize(n, 0.0); + note_buffer(n); + Some((padded, scratch)) +} + +/// The three box passes on `line` continued `halo` samples past each end with its end values, as +/// Photoshop continues a mask past the canvas edge (#9475). Padding each line, row pass then +/// column pass, gives exactly what padding the whole plane would: the plane's padded corners +/// repeat its corner values, which is what the padded rows' own row pass leaves there. `padded` +/// and `scratch` hold `line.len() + 2 * halo` samples. +fn blur_padded_line(line: &mut [f32], padded: &mut [f32], scratch: &mut [f32], pass: BoxPass, halo: usize) { + let (Some(&a), Some(&b)) = (line.first(), line.last()) else { return }; + let n = line.len() + 2 * halo; + let (Some(padded), Some(scratch)) = (padded.get_mut(..n), scratch.get_mut(..n)) else { return }; + padded[..halo].fill(a); + padded[halo..halo + line.len()].copy_from_slice(line); + padded[halo + line.len()..].fill(b); + for _ in 0..3 { + blur_line(padded, scratch, pass); + } + line.copy_from_slice(&padded[halo..halo + line.len()]); +} + +/// How many workers blur `lines` lines of `len` samples. +fn row_workers(lines: usize, len: usize) -> usize { + if cfg!(target_arch = "wasm32") || lines.saturating_mul(len) < 1 << 16 { + 1 + } else { + std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16).min(lines.max(1)) + } +} + +/// Line buffers for each of [`row_workers`]; `None` unless every one fits in memory. +fn worker_buffers(lines: usize, len: usize, halo: usize) -> Option, Vec)>> { + (0..row_workers(lines, len)).map(|_| line_buffers(len, halo)).collect() +} + +/// Blurs the rows of `v` on one worker per entry of `buffers` (from [`worker_buffers`]). +fn blur_rows(v: &mut [f32], w: usize, pass: BoxPass, halo: usize, buffers: &mut [(Vec, Vec)]) { + if w == 0 || v.is_empty() || buffers.is_empty() { return; } let h = v.len() / w; - let threads = if cfg!(target_arch = "wasm32") || v.len() < 1 << 16 { - 1 - } else { - std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16).min(h.max(1)) - }; - if threads == 1 { - blur_rows_chunk(v, w, pass); + if let [only] = buffers { + blur_rows_chunk(v, w, pass, halo, only); return; } - let rows_per_worker = h.div_ceil(threads); + let rows_per_worker = h.div_ceil(buffers.len()); let chunk_len = rows_per_worker.saturating_mul(w); std::thread::scope(|scope| { - for chunk in v.chunks_mut(chunk_len) { - scope.spawn(move || blur_rows_chunk(chunk, w, pass)); + for (chunk, buffers) in v.chunks_mut(chunk_len).zip(buffers.iter_mut()) { + scope.spawn(move || blur_rows_chunk(chunk, w, pass, halo, buffers)); } }); } @@ -147,50 +205,62 @@ fn transpose_into(v: &[f32], out: &mut [f32], w: usize, h: usize) { } /// Approximate Gaussian blur of a `w`×`h` plane: three box passes per axis whose variance is -/// exactly `sigma²` ([`BoxPass`]; edges clamp, which is exact here since the planes extend into -/// constant mask regions). Whole-pixel boxes rounded the variance (a 6 px feather blurred like -/// 6.48 px, a 3 px one like 3.46) and missed Photoshop's feathered edges by up to 4 levels -/// (psd-tools mask-parameters-no-real-channel.psd); the exact variance is within 1.5. The axes -/// are processed in parallel on bounded OS threads, preserving each line's floating-point +/// exactly `sigma²` ([`BoxPass`]). Beyond its edges the plane continues with its edge values, as +/// Photoshop feathers a mask at the canvas edge: a mask white up to the edge stays white there, +/// one black there stays black (#9475). Whole-pixel boxes rounded the variance (a 6 px feather +/// blurred like 6.48 px, a 3 px one like 3.46) and missed Photoshop's feathered edges by up to 4 +/// levels (psd-tools mask-parameters-no-real-channel.psd); the exact variance is within 1.5. The +/// axes are processed in parallel on bounded OS threads, preserving each line's floating-point /// operation order. pub fn gaussian(v: &mut [f32], w: usize, h: usize, sigma: f32) { if w == 0 || h == 0 || v.len() != w.saturating_mul(h) { return; } let Some(pass) = BoxPass::for_sigma(sigma) else { return }; - // Reserve before modifying the input so allocation failure can use the sequential fallback - // without leaving a half-blurred mask. + // Each pass reads `r + 1` samples past a pixel, so three see `3(r + 1)` past the edge. Clamping + // every pass at the edge instead repeated the blurred values there, which brightened a 32 px + // feather by up to 12 levels where the canvas cut it off. + let m = pass.r.saturating_add(1).saturating_mul(3); + blur_plane(v, w, h, pass, m); +} + +/// Three box passes along each axis of the `w`×`h` plane, every line continued `halo` samples +/// past its ends ([`blur_padded_line`]). +fn blur_plane(v: &mut [f32], w: usize, h: usize, pass: BoxPass, halo: usize) { + // Reserve everything before modifying the input, so an allocation failure can use the + // sequential fallback (which also reserves first) and never leaves a half-blurred mask. let mut transposed = Vec::new(); - if transposed.try_reserve_exact(v.len()).is_err() { - gaussian_sequential(v, w, h, pass); + let buffers = if transposed.try_reserve_exact(v.len()).is_ok() { worker_buffers(h, w, halo).zip(worker_buffers(w, h, halo)) } else { None }; + let Some((mut rows, mut columns)) = buffers else { + gaussian_sequential(v, w, h, pass, halo); return; - } + }; transposed.resize(v.len(), 0.0); - blur_rows(v, w, pass); + note_buffer(v.len()); + blur_rows(v, w, pass, halo, &mut rows); transpose_into(v, &mut transposed, w, h); - blur_rows(&mut transposed, h, pass); + blur_rows(&mut transposed, h, pass, halo, &mut columns); transpose_into(&transposed, v, h, w); } -/// Allocation-light reference path used if parallel transpose storage cannot be reserved. -fn gaussian_sequential(v: &mut [f32], w: usize, h: usize, pass: BoxPass) { +/// Allocation-light reference path used if parallel transpose storage cannot be reserved. It +/// reserves its lines before touching `v`: without them the plane is left as it was, never half +/// blurred. +fn gaussian_sequential(v: &mut [f32], w: usize, h: usize, pass: BoxPass, halo: usize) { let mut line = Vec::new(); - let mut scratch = Vec::new(); let len = w.max(h); - if line.try_reserve_exact(len).is_err() || scratch.try_reserve_exact(len).is_err() { + if line.try_reserve_exact(len).is_err() { return; } line.resize(len, 0.0); - scratch.resize(len, 0.0); + let Some((mut padded, mut scratch)) = line_buffers(len, halo) else { return }; for axis in [false, true] { let (lines, line_len) = if axis { (w, h) } else { (h, w) }; for k in 0..lines { for i in 0..line_len { line[i] = if axis { v[i * w + k] } else { v[k * w + i] }; } - for _ in 0..3 { - blur_line(&mut line[..line_len], &mut scratch[..line_len], pass); - } + blur_padded_line(&mut line[..line_len], &mut padded, &mut scratch, pass, halo); for i in 0..line_len { if axis { v[i * w + k] = line[i]; @@ -254,9 +324,31 @@ mod tests { let mut parallel: Vec<_> = (0..w * h).map(|i| ((i * 37 % 1009) as f32) / 1008.0).collect(); let mut sequential = parallel.clone(); let pass = BoxPass::for_sigma(sigma).unwrap(); - gaussian_sequential(&mut sequential, w, h, pass); - gaussian(&mut parallel, w, h, sigma); - assert_eq!(parallel, sequential, "parallel blur must retain the exact per-line arithmetic"); + let source = parallel.clone(); + for halo in [0, 3 * (pass.r + 1)] { + parallel.copy_from_slice(&source); + sequential.copy_from_slice(&source); + gaussian_sequential(&mut sequential, w, h, pass, halo); + blur_plane(&mut parallel, w, h, pass, halo); + assert_eq!(parallel, sequential, "parallel blur must retain the exact per-line arithmetic (halo {halo})"); + } + } + + /// Padding each line (#9493) blurs exactly as padding the whole plane with its edge values + /// and cropping it afterwards does, without the padded plane. + #[test] + fn padding_each_line_matches_padding_the_plane() { + let (w, h, sigma): (usize, usize, f32) = (90, 70, 9.0); + let source: Vec = (0..w * h).map(|i| ((i * 37 % 1009) as f32) / 1008.0).collect(); + let pass = BoxPass::for_sigma(sigma).unwrap(); + let m = 3 * (pass.r + 1); + let (pw, ph) = (w + 2 * m, h + 2 * m); + let mut plane: Vec = (0..pw * ph).map(|i| source[((i / pw).clamp(m, m + h - 1) - m) * w + (i % pw).clamp(m, m + w - 1) - m]).collect(); + blur_plane(&mut plane, pw, ph, pass, 0); + let want: Vec = (0..w * h).map(|i| plane[(i / w + m) * pw + i % w + m]).collect(); + let mut got = source; + gaussian(&mut got, w, h, sigma); + assert_eq!(got, want); } #[test] @@ -269,7 +361,7 @@ mod tests { let source: Vec<_> = (0..w * h).map(|i| ((i * 37 % 1009) as f32) / 1008.0).collect(); let mut sequential = source.clone(); let start = Instant::now(); - gaussian_sequential(&mut sequential, w, h, pass); + gaussian_sequential(&mut sequential, w, h, pass, 3 * (pass.r + 1)); let sequential_time = start.elapsed(); let mut parallel = source; let start = Instant::now(); @@ -278,4 +370,36 @@ mod tests { assert_eq!(parallel, sequential); eprintln!("50 MP mask blur: sequential={sequential_time:?}, parallel={parallel_time:?}"); } + + /// CodeRabbit on #9493: continuing the mask past the plane's edge must not build a padded copy + /// of the whole plane. At the 1000 px maximum feather the halo is about 3000 px a side, so a + /// padded 400 × 400 plane would be 6400 × 6400 floats; the blur needs only the plane's + /// transpose and one padded line per worker. + #[test] + fn a_maximum_feather_does_not_pad_the_whole_plane() { + let (w, h) = (400usize, 400usize); + let mut v: Vec = (0..w * h).map(|i| if (i % w) < w / 2 { 1.0 } else { 0.0 }).collect(); + gaussian(&mut v, w, h, feather_sigma(1000.0)); + let largest = LARGEST_BUFFER.load(std::sync::atomic::Ordering::Relaxed); + assert!(largest <= w * h, "the blur allocated a buffer of {largest} floats for a {w} × {h} plane"); + assert!(v.iter().all(|x| x.is_finite())); + } + + /// CodeRabbit on #9493: when a line buffer can't be had, the mask is never left half blurred + /// (rows untouched but columns blurred, or some workers' rows only): the plane is either fully + /// blurred or untouched. + #[test] + fn a_failed_line_buffer_never_leaves_a_half_blurred_mask() { + let (w, h, sigma): (usize, usize, f32) = (433, 211, 7.0); + let source: Vec = (0..w * h).map(|i| ((i * 37 % 1009) as f32) / 1008.0).collect(); + let mut want = source.clone(); + gaussian(&mut want, w, h, sigma); + for fail in [w, h] { + FAIL_LINE_BUFFERS.store(fail, std::sync::atomic::Ordering::Relaxed); + let mut got = source.clone(); + gaussian(&mut got, w, h, sigma); + FAIL_LINE_BUFFERS.store(0, std::sync::atomic::Ordering::Relaxed); + assert!(got == want || got == source, "lines of {fail} failing left a partly blurred plane"); + } + } } diff --git a/crates/vector/src/flatten.rs b/crates/vector/src/flatten.rs index a586dfa1bf..cc50817c74 100644 --- a/crates/vector/src/flatten.rs +++ b/crates/vector/src/flatten.rs @@ -73,28 +73,51 @@ fn eval(seg: &[Point; 4], t: f64) -> (f64, f64) { /// Validate before interactive rendering: finite coordinates and a bounded tessellation and /// dash workload. Arc length is bounded by the cubic control polygon, without allocating pixels. pub fn validate_shape(path: &Path, stroke: Option<&photocraft_doc::ShapeStroke>) -> Result<(), &'static str> { + validate_workload(path, stroke, 1_000_000.0, "shape coordinates must be finite and within ±1000000 px") +} + +fn validate_workload( + path: &Path, + stroke: Option<&photocraft_doc::ShapeStroke>, + coordinate_limit: f64, + coordinate_error: &'static str, +) -> Result<(), &'static str> { let knots = path.subpaths.iter().try_fold(0usize, |n, s| n.checked_add(s.knots.len())).ok_or("too many path knots")?; if knots > 4096 || path.subpaths.len() > 4096 { - return Err("shape path exceeds 4096 knots/subpaths"); + return Err("path exceeds 4096 knots/subpaths"); } let mut points = 0usize; let mut length = 0.0; for sub in &path.subpaths { for k in &sub.knots { for p in [k.anchor, k.in_ctrl, k.out_ctrl] { - if !p.x.is_finite() || !p.y.is_finite() || p.x.abs() > 1_000_000.0 || p.y.abs() > 1_000_000.0 { - return Err("shape coordinates must be finite and within ±1000000 px"); + if !p.x.is_finite() || !p.y.is_finite() || p.x.abs() > coordinate_limit || p.y.abs() > coordinate_limit { + return Err(coordinate_error); } } } points = points.saturating_add(1); for seg in sub.segments() { + let mut segment_length = 0.0; + for pair in seg.windows(2) { + let (dx, dy) = (pair[1].x - pair[0].x, pair[1].y - pair[0].y); + if !dx.is_finite() || !dy.is_finite() { + return Err("path geometry arithmetic must be finite"); + } + segment_length += dx.hypot(dy); + if !segment_length.is_finite() { + return Err("path geometry arithmetic must be finite"); + } + } + length += segment_length; + if !length.is_finite() { + return Err("path geometry arithmetic must be finite"); + } points = points.saturating_add(if is_line(&seg) { 1 } else { pieces(&seg, crate::DEFAULT_TOLERANCE) }); - length += seg.windows(2).map(|w| (w[1].x - w[0].x).hypot(w[1].y - w[0].y)).sum::(); } } if points > 100_000 { - return Err("shape tessellation exceeds 100000 points"); + return Err("path tessellation exceeds 100000 points"); } if let Some(s) = stroke { s.validate()?; @@ -109,6 +132,12 @@ pub fn validate_shape(path: &Path, stroke: Option<&photocraft_doc::ShapeStroke>) Ok(()) } +/// Work and saved paths may extend far beyond the canvas. Keep their coordinates usable by the +/// f32 UI while bounding the complete path's flattening workload before publishing an edit. +pub fn validate_path(path: &Path) -> Result<(), &'static str> { + validate_workload(path, None, f64::from(f32::MAX), "path coordinates must be finite and representable as f32") +} + /// Points one flattened path may hold. Paths that never pass [`validate_shape`] (vector masks /// from files, imported SVG, effect outlines) are flattened more coarsely past it, so hostile /// curves cannot exhaust memory. @@ -203,6 +232,58 @@ mod tests { } } + #[test] + fn general_paths_bound_total_knots_subpaths_and_combined_tessellation() { + let line = Subpath::polygon(&[(0.0, 0.0)]); + let mut paths = Path { subpaths: vec![line.clone(); 4096], ..Default::default() }; + assert!(validate_path(&paths).is_ok()); + paths.subpaths.push(line); + assert_eq!(validate_path(&paths), Err("path exceeds 4096 knots/subpaths")); + let knots = Path { subpaths: vec![Subpath::polygon(&vec![(0.0, 0.0); 4097])], ..Default::default() }; + assert_eq!(validate_path(&knots), Err("path exceeds 4096 knots/subpaths")); + + let curve = shapes::ellipse(0.0, 0.0, 1000.0, 1000.0).subpaths.remove(0); + let points = 1 + curve.segments().iter().map(|s| if is_line(s) { 1 } else { pieces(s, crate::DEFAULT_TOLERANCE) }).sum::(); + let half = 100_000 / points / 2 + 1; + let mut combined = Path { subpaths: vec![curve.clone(); half], ..Default::default() }; + assert!(validate_path(&combined).is_ok()); + assert!(validate_shape(&combined, None).is_ok()); + combined.subpaths.extend(vec![curve; half]); + assert!(combined.subpaths.len() < 4096 && combined.subpaths.iter().map(|s| s.knots.len()).sum::() < 4096); + assert_eq!(validate_path(&combined), Err("path tessellation exceeds 100000 points")); + assert_eq!(validate_shape(&combined, None), Err("path tessellation exceeds 100000 points")); + } + + #[test] + fn general_paths_reject_coordinates_that_overflow_the_ui_or_segment_arithmetic() { + for extent in [f64::from(f32::MAX) * 2.0, 1.0e308, f64::INFINITY, f64::NAN] { + let path = Path { subpaths: vec![Subpath::polygon(&[(-extent, 0.0), (extent, 0.0)])], ..Default::default() }; + assert_eq!(validate_path(&path), Err("path coordinates must be finite and representable as f32")); + } + // The shared arithmetic guard also rejects overflow independently of coordinate policy. + let overflowing_difference = Path { subpaths: vec![Subpath::polygon(&[(-1.0e308, 0.0), (1.0e308, 0.0)])], ..Default::default() }; + assert_eq!(validate_workload(&overflowing_difference, None, f64::MAX, "coordinates"), Err("path geometry arithmetic must be finite")); + let overflowing_length = Path { subpaths: vec![Subpath::polygon(&[(0.0, 0.0), (f64::MAX, f64::MAX)])], ..Default::default() }; + assert_eq!(validate_workload(&overflowing_length, None, f64::MAX, "coordinates"), Err("path geometry arithmetic must be finite")); + } + + #[test] + fn general_paths_keep_large_straight_coordinates_and_shape_limits_stay_put() { + let at_shape_limit = Path { subpaths: vec![Subpath::polygon(&[(0.0, 0.0), (1_000_000.0, 0.0)])], ..Default::default() }; + assert!(validate_shape(&at_shape_limit, None).is_ok()); + let outside_shape = Path { subpaths: vec![Subpath::polygon(&[(0.0, 0.0), (1_000_001.0, 0.0)])], ..Default::default() }; + assert_eq!(validate_shape(&outside_shape, None), Err("shape coordinates must be finite and within ±1000000 px")); + assert!(validate_path(&outside_shape).is_ok()); + for extent in [3.0e9, f64::from(f32::MAX)] { + let path = Path { subpaths: vec![Subpath::polygon(&[(0.0, 0.0), (extent, 0.0), (extent, extent)])], ..Default::default() }; + assert!(validate_path(&path).is_ok()); + let line = flatten_subpath(&path.subpaths[0], crate::DEFAULT_TOLERANCE); + assert_eq!(line.pts, [(0.0, 0.0), (extent, 0.0), (extent, extent)]); + assert!(line.pts.iter().all(|(x, y)| (*x as f32).is_finite() && (*y as f32).is_finite())); + assert!(validate_shape(&path, None).is_err()); + } + } + #[test] fn hostile_curves_flatten_within_the_point_budget() { // Unvalidated paths (a vector mask from a file, an imported SVG) can carry handles far diff --git a/docs/brush-parity.md b/docs/brush-parity.md index 23d0b422c3..691e5c1beb 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-25 · **Change:** minor (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-10-28 · **Change:** minor (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 @@ -76,6 +76,7 @@ tablets against Photoshop side by side. | ⇧-click draws a straight line from the last point | done | | | Hold `~` with the Brush or Pencil to erase with its brush: Clear mode while held (rebindable under Tools › Temporary) | done | `hold_keys.rs`, #3439 | | Clear painting mode in the Brush and Pencil Mode menus | done | `paint_mode_dropdown` in `panels.rs`, `"mode": "clear"`, #3439 | +| Shift+right-click with Brush opens its Mode menu, including Clear; Alt and Command/Ctrl keep their existing gestures | done | #4929; shared options-bar choices, `tools.setBrush`, canvas/control interaction regressions and synthetic offscreen checks | | Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980), macOS issue #2360 | | Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor requested (#2662, #1057) | | Brush choice kept per tool (Brush, Eraser, Blur each their own) | partial | #2542 | @@ -130,7 +131,9 @@ tablets against Photoshop side by side. | 2026-10-12 | minor | A shaped tip's cursor outline turns and flips with a rotated or flipped view, and follows pixel aspect correction | | 2026-10-13 | minor | Shape Dynamics and Transfer minimum inputs follow their Control and retain their values while disabled (#3825, partial). No brush-feel estimate changed. | | 2026-10-13 | minor | Hue Jitter uses the same themed amount slider as other jitter controls (#3825, partial). No brush-feel estimate changed. | +| 2026-10-13 | minor | Brush-only Shift+right-click Mode menu shares options-bar choices, including Clear; preserves existing right-click gestures and consumes outside dismissal without painting (#4929). No brush-feel estimate changed. | | 2026-10-13 | minor | Transfer Wetness/Mix controls follow the active tool and retain their settings while disabled (#3825, partial). No brush-feel estimate changed. | | 2026-10-14 | minor | The 12 existing Brush Settings section locks expose translated names and locked state to AccessKit and show themed keyboard focus (#3477 workflow); icons, hit targets and command behavior retained. No brush-feel estimate changed. | | 2026-10-14 | minor | Options-bar Mode for Clone Stamp, Pattern Stamp, History Brush and Healing (kept in each tool's brush) and Paint Bucket (with Clear); each tool's first brush starts in Normal. No brush-feel estimate changed. | | 2026-10-13 | minor | Dragging a brush preset shows its cached tip thumbnail and name in the Brushes panel and preset picker (#4225, partial). No brush-feel estimate changed. | +| 2026-10-23 | minor | Escape also consumes a held right-button release after a rapid second press, so the Brush Mode picker stays dismissed without painting or changing history (#4929). | diff --git a/docs/color-picker.md b/docs/color-picker.md index a30311c4be..b53ce499a9 100644 --- a/docs/color-picker.md +++ b/docs/color-picker.md @@ -2,6 +2,10 @@ Click the color swatch in the Type options bar or Character panel to open the full Color Picker. It offers the color field, component strip, HSB/RGB/Lab/CMYK and hex fields, and current/new swatches. Selecting characters targets that range; with no character selection, the active text layer is targeted. **OK** applies through `type.setStyle`; **Cancel** leaves the text and history unchanged. The foreground color is independent of this dialog. +## HUD Color Picker + +With a painting tool, **Shift+Alt+right-click** on the canvas opens Photoshop's HUD Color Picker under the pointer: a hue strip and a saturation/value square. While the right button stays down, moving the pointer over the HUD sets the foreground color live; releasing the button keeps it. **Esc** restores the color the gesture started from. The whole gesture is one coalesced `tools.setColors` history step. The agents' equivalent is `ui.pointer` with `"button": "right"`, `"shift": true, "alt": true` (the down opens the HUD, the up closes it). + The existing canvas eyedropper continues to sample the document while the Color Picker is open, including canvas zoom and pan. This works without operating-system screen-capture permission. ## Pick a color outside PhotoCraft diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a99b863d31..473c6fe4ff 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -60,11 +60,14 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Brush Pose's `pose.overrideTiltX` and `pose.overrideTiltY` are independent booleans. For example, `engine.execute {"command":"tools.setBrush","params":{"pose":{"enabled":true,"tiltX":45,"overrideTiltX":true,"overrideTiltY":false}}}` fixes X at 45° while Y follows the stylus. Pose tilts are degrees (±90); the Brush Settings panel displays percentages (±100). Old stored `overrideTilt` values migrate to both axes. In command patches, `overrideTilt` sets both axes unless an explicit axis field in the same patch overrides it. `brush.get` includes both axis flags and the legacy combined readback (`overrideTilt` is true only when both flags are true). Axis-only journals omit that derived combined key so replay retains the other axis. Present flag values must be booleans; null and other types return an error. - `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks, as four floats 0..1 (not 0..255). - `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`auto`: only while the crop box is dragged, Photoshop's default; `always`; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box. +- `ui.set` also accepts the Pen tools' options bar (#1397): `penMode` (`path` or `shape`) and `penPathOp`, the Path Operations menu (`newLayer`, `combine`, `subtract`, `intersect`, `exclude`): how the next Pen, Freeform Pen or Curvature Pen path joins the selected shape layer (Shape mode; `newLayer` makes a new one) or the targeted vector mask, selected path or Work Path (Path mode, where `newLayer` combines). `ui.inspect` reports them under `toolOptions` (`vector_mode`, `pen_path_op`). Merge Shape Components is the engine command `path.mergeShapeComponents` (work, saved or `layer` path) or `layer.combineShapes.mergeShapeComponents` (shape layers). - `ui.set` also accepts `cropFill` (`background`, Photoshop's Background (Default), or `contentAware`), the Crop tool's Fill dropdown (#3823): with `contentAware`, committing a turned or extending frame passes `contentAware: true` to `image.crop`, which fills the area the image doesn't cover from its surroundings. `ui.inspect` reports it as `toolOptions.crop_content_aware`. Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them. - `ui.set` also accepts the Crop tool's gear menu (#1919) as `cropShield`, an object patching any of `show_cropped_area` (Show Cropped Area; off hides everything outside the box behind the canvas colour, H in the app), `enabled` (Enable Crop Shield), `color` (`matchCanvas`, the pasteboard colour, or `custom`), `custom_color` (`[r, g, b]`, 0..255), `opacity` (0..100, default 75), `auto_adjust` (Auto Adjust Opacity: half the opacity while the box is dragged), `classic_mode` (Use Classic Mode, default off: the box turns and moves over the image; off is Photoshop's default mode, where the box stays upright and the view turns and pans the image behind it while the Crop tool shows a frame, P in the app; in both modes picking the tool turns a rotated view upright about its centre, Classic Mode keeping the camera upright with the frame drawn turned, and the view stays upright after a commit or cancel; Classic Mode greys out Show Cropped Area, which then acts as on, and Auto Center Preview) and `auto_center_preview` (default on: in default mode a box being resized keeps its centre where it is on screen, also after a pan, a drawn one moves to the middle of the canvas, and X re-centres it; a move never re-centres the box). `ui.inspect` reports it as `toolOptions.crop_shield`. The pending frame (`crop_rect`, `crop_angle`: its turn on the image) and the `image.crop` a commit runs are the same in both modes. - `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}` (`layer.new.group` / `layer.new.groupFromLayers` open the New Group dialog: fields `name`, `color`, `mode`, `opacity`), `newCropPreset` / `deleteCropPreset`: the Crop tool's New / Delete Crop Preset… dialogs, fields `name` and `selected: [names]`; crop presets are `crop` tool presets, so `tool.presets.new/list/edit {"tool":"crop"}` drive them too) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once - A Layer Style color field opens the shared picker with `ui.dialog.open {"kind":"colorPicker","parent":12,"effect":"fx2","field":"color"}`. `parent` is the Layer Style dialog id; `effect` is its effect instance id. `field` must be one of that instance's color parameters (`color`, or `from`/`to` for Gradient Overlay). The picker previews over the pending style without changing the document. Picker OK changes only the parent parameter; Cancel discards the preview. Confirm the parent afterwards to apply the style. Parent confirmation is refused while its picker is open; parent cancellation closes both. The binding is exposed in `ui.inspect` as `__layerStyleColor`; changed/closed targets or a document switch invalidate it. + + - Gradient Overlay color stops use `colorPicker {parent, effect, field: "stops", stop: index}`; the stop must exist. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "dontSave" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. @@ -78,11 +81,13 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - 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. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows -- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen, or with a Type tool on text being edited or on committed type, it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. +- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen, or with a Type tool on text being edited or on committed type, it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. For Brush Shift+right-click, see the Mode menu exception below. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. - Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape. - Image › Adjustments › Curves on top, no eyedropper armed (#7325): a `down` with `command: true` adds a point on the curve the dialog shows (its Channel popup), at the pixel's tone (RGB: Rec. 709 luma; Gray: the mean) and at the curve's current output there, so the preview does not change; with `shift: true` as well, one point on each of Red, Green and Blue at that channel's value. It samples the merged image like the eyedroppers, never moves an existing point (a point already within 2 levels is selected instead, a 16-point curve takes no more), and the tool is not driven. Nothing is added with a pencil-drawn curve, in Lab or CMYK, or with a mask, saved channel or Quick Mask targeted. - Levels or Curves adjustment layer, Properties eyedropper armed (`layerPicker` in `ui.inspect`: `{layer, point, tool}`, set by the panel's Set Black/Neutral Gray/White Point buttons): a `down` sets that point from the image below the layer as one `layer.setAdjustment {"layer", "eyedropper": {"point", "at": [x, y], "size"}}` (send that command directly to skip the UI) and the tool is not driven; Esc, another tool or another layer disarms it. + - With Brush, Shift+right-click (without Alt, Ctrl or Command) opens the Mode menu even when right-click painting is set to Erase. `ui.inspect.brushModeMenu` reports its screen position, current mode and choices. Pick a row with `ui.click`; the choice uses `tools.setBrush`. Clear has the same painting-only erase meaning as the options bar. Escape, an outside press or a tool change closes the menu without changing the brush or document. - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` (or `secondary`) or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing + - `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`. `{"key": "AltLeft"}` is a tap on Alt, which puts the keyboard on the in-window menu bar (then `ArrowRight`, `ArrowDown`, `Enter`, `Escape` or a menu's letter drive it); `{"key": "F", "alt": true}` opens the menu with that mnemonic (#4988) - `ui.pointer`, `ui.click`, `ui.move`, `ui.key` and `ui.screenshot` validate every parameter before acting, as `ui.set` does: an unknown field (top-level, under `modifiers` or in an event), a value of the wrong JSON type (`"x": "abc"`, `"ctrl": "yes"`), a `button`, `kind`, `tool` or `key` outside the accepted set, or a number outside its range (`pressure`, tilt, `rotation`, `count`) is an error naming the parameter, and nothing is queued or applied. A `null` field counts as omitted and takes its default - Engine commands (`engine.execute`, `photocraft-cli run`, MCP `command_run`) reject a param key their `params` doc does not name for the commands listed in `STRICT` (`crates/engine/src/param_check.rs`, today `layer.hideLayers` and `layer.showLayers`): `{"ids":[4]}` is the error `unknown parameter \`ids\` (expected: layer)`, and nothing runs. Other commands still ignore unknown keys until their `params` doc is complete and they are added to that list (`coalesce` and `target` are always accepted). @@ -105,7 +110,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?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; automation never shows JPEG 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, `..` 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?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; automation never shows JPEG 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.quit` ## Engine commands @@ -115,7 +120,7 @@ Change the UI language without restarting with `prefs.set`: are documented in [UI localisation](localization.md). `prefs.get` and the existing preference store expose and persist the same setting; scripts keep using canonical command IDs. -`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled (reply shape: [Command list replies](#command-list-replies)). Each row carries `enabled` (bool), `disabledReason` (`null` when enabled, otherwise the precondition that failed, such as `"no document open"`, `"no selection"` or `"the clipboard is empty"`) and `needsDocument` (true when the command is off because no document is open, so the first step is to create or open one; a command may still have its own precondition after that, such as an active text layer. False when enabled or off for another reason). With no document open, nearly every document command reports `enabled: false, needsDocument: true`; plan around `needsDocument` rather than reading `enabled` alone (#3664). Examples: +`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled (reply shape: [Command list replies](#command-list-replies)). Each row carries `enabled` (bool), `disabledReason` (`null` when enabled, otherwise the precondition that failed, such as `"no document open"`, `"no selection"` or `"the clipboard is empty"`) and `needsDocument` (true when the command is off because no document is open, so the first step is to create or open one; a command may still have its own precondition after that, such as an active text layer. False when enabled or off for another reason). With no document open, nearly every document command reports `enabled: false, needsDocument: true`; plan around `needsDocument` rather than reading `enabled` alone (#3664). An unknown command id or method name fails with up to three near matches, for example ``unknown command `engine.commands`; did you mean `command.list`?``; a protocol method sent through `engine.execute`, or an engine command id sent as a method, says which of the two it is. Examples: | Command | Params | |---|---| @@ -156,6 +161,10 @@ store expose and persist the same setting; scripts keep using canonical command The Actions list fills the resizable dock group. +Newly recorded Layers eye gestures resolve their targets by layer name and duplicate-name +ordinal during playback rather than retaining a document-local layer id. A missing target +reports a failed step instead of changing another layer. + The Actions panel shows replayable steps immediately while recording. Click an individual step to select it, then use the trash button to remove that step; selecting the action heading instead targets the whole action. Step deletion also works during recording @@ -743,3 +752,7 @@ dock target. The panel menu and icon rail remain available in custom workspaces. `window.panel. {show:true}` always reveals, selects and expands the panel, including when another tab is selected. Workspace snapshots retain custom collapse settings and Timeline visibility. + +### Select the layer under the pointer + +Assign **Select Layer Under Cursor** in Keyboard Shortcuts to choose the topmost visible, pickable layer beneath the canvas pointer. Empty pixels and points outside the document leave the selection unchanged; dialogs, strokes and brush-resize gestures block it. The command follows zoom, pan, view rotation and horizontal flipping. Agents can invoke `ui.menu.invoke {"id":"layer.selectUnderCursor"}` after moving the screen pointer with `ui.move {"x": ..., "y": ...}`. The command has no default shortcut. diff --git a/docs/development.md b/docs/development.md index 71e34e7ebb..75482b7cb1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -153,7 +153,7 @@ The window itself draws with the same device (or, with the CPU canvas, one it wa ## Logs -The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. A launch while another PhotoCraft is still running leaves that instance's log where it is and writes its own `photocraft-.log` next to it (the newest two of those are kept once their instances have exited; the `PhotoCraft , log file ` line at startup names the file in use). The file stops growing at 16 MiB. `--version` and command-line errors write no file. +The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. A launch while another PhotoCraft is still running leaves that instance's log where it is and writes its own `photocraft-.log` next to it (the newest two of those are kept once their instances have exited; the `PhotoCraft , log file ` line at startup names the file in use). The file stops growing at 16 MiB. `--version` and command-line errors write no file. A desktop start that fails before any window exists logs the error and, when no terminal, automation client or headless session can report it, shows it in a dialog naming this file (#7643). By default PhotoCraft's own crates log at `info` and everything else at `warn`. `RUST_LOG` replaces that with env_logger-style directives, for example `RUST_LOG=debug`, `RUST_LOG=warn,photocraft_gpu=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`photocraft*=debug`). The logger is `apps/photocraft/src/logging.rs`; the web build logs to the browser console instead. @@ -174,7 +174,7 @@ By default PhotoCraft's own crates log at `info` and everything else at `warn`. | `PHOTOCRAFT_CPU_CANVAS=1` | Force the CPU canvas path instead of the wgpu shader canvas | | `PHOTOCRAFT_NATIVE_WAYLAND=1` | Linux: stay on native Wayland when a pen is attached (by default the window then opens through Xwayland, because Wayland gives the app no pen input; #639). A pen is an input device with `BTN_TOOL_PEN` and the `ABS_X`/`ABS_Y` axes; virtual keyboards that claim every key are not pens (#1072) | | `PHOTOCRAFT_GPU_ADAPTER=nvidia` | Linux: use the graphics adapter whose name contains this (case-insensitive); overrides `performance.gpuAdapter` for one launch | -| `WGPU_BACKEND=dx12` | Pick the wgpu backend(s) (`vulkan`, `dx12`, `metal`, `gl`); overrides `performance.gpuBackend` and the startup fallback | +| `WGPU_BACKEND=dx12` | Pick the wgpu backend(s) (`vulkan`, `dx12`, `metal`, `gl`); overrides `performance.gpuBackend` and the startup fallback. Tests read it too: on Windows with an Intel GPU, run them with `WGPU_BACKEND=dx12`, since loading the Intel Vulkan driver crashes the test process with `STATUS_ACCESS_VIOLATION` (#4) | | `WGPU_DX12_COMPILER=fxc` | DX12 shader compiler (`fxc`, `dxc`, `auto`); `dxc` and `auto` look `dxcompiler.dll` up through the DLL search path | | `PHOTOCRAFT_GPU_TILE=2048` | Force GPU canvas tiling (tests tile seams) | | `PHOTOCRAFT_TEXEL_GUARD=1` (or `=0`) | Force on (off) uploading egui's fully transparent texels as alpha 1/255. On by default only for Intel Iris Xe on DX12, whose driver shows stale memory in all-zero texture blocks: red squares in brush previews and tool icons (`ui-egui/src/texel_guard.rs`; check a GPU with `cargo run --release -p photocraft-gpu --example zero_block_probe -- dx12 400`) | @@ -251,6 +251,17 @@ cargo run -p photocraft-cli -- commands --filter blur # the c cargo run -p photocraft-cli --example man-and-completions -- out/ # man pages + bash/zsh/fish/elvish/PowerShell completions ``` +The Linux AppImage includes the same CLI. Select it with a leading `--cli`: + +```sh +./photocraft--linux-x86_64.AppImage --cli --help +./photocraft--linux-x86_64.AppImage --cli mcp +ln -s photocraft--linux-x86_64.AppImage photocraft-cli +./photocraft-cli commands --filter blur +``` + +The `--cli` selector is removed; all remaining arguments, stdin, stdout, stderr and the exit status are passed through. CLI launches skip desktop integration. The symlink form uses the AppImage runtime's `ARGV0`; the normal AppImage name launches the GUI. + `actions.json` holds the steps of a recorded action: `[["", {…}], …]`, `[{"command": "", "params": {…}}, …]` or bare ids, as a list or wrapped in `{"actions": …}` or `{"steps": …}`; a droplet file works too. It can also be an Actions set (the Actions panel's `actions.json`, `{"actions": [{"name": …, "steps": […]}, …]}`): `--action ` picks the action to play (optional when the set holds one), and the whole set is loaded for each file, so a step that plays another action of the set works. `batch` refuses an `--out` folder that is the `--in` folder, since the results would replace the originals, unless `--in-place` is given. `run` prints one JSON line per command result. ## Native format (.pcraft) @@ -492,6 +503,8 @@ cargo run --release -p photocraft-ui-egui --example perf_scenarios -- \ That writes the row's own report and stops there: it does **not** evaluate the budget, so read `p50_ms`/`p95_ms`/`max_ms` out of the JSON yourself. Use `cargo xtask perf --bench ` when you want the verdict, the merged `results.json`/`summary.md` and the regression check. +Every `--bench` name must match a `[[bench]]` name in `perf/budgets.toml`; an unknown name +is rejected before any benchmark runs or any report or baseline is written. Read the sample count before quoting a percentile. `--reps` defaults to 7 in `--quick` and 15 otherwise, it is per bench, and some rows cap it themselves (the `#211` algorithm rows use diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ff3d18f593..6c9a6b65ba 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -214,4 +214,5 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | 2026-10-11 | minor | PSD smart filters: Filter Gallery (`GEfc`) maps to `filter.filterGallery` when every effect is modelled (Chrome so far), editable from the Layers panel | | 2026-10-11 | minor | D5100 image area and fitted-look preservation in Camera Raw tuning | | 2026-10-11 | minor | PDF write now covers Save As / Save a Copy / CLI (`io::pdf::export`, #3401): one flattened RGB/Gray/CMYK page at the document's print size with the embedded profile. Read (#2541), multi-page save, PDF presentation, vector/text output still open +| 2026-10-11 | minor | Sony encrypted applied WB/black and measured ILCE-6000 crop; camera calibration remains partial | | 2026-10-10 | major | First version: Photoshop 2026 27.11.0's formats from its bundle, against our codecs; Affinity notes moved from `roadmap.md` | diff --git a/docs/gaps.md b/docs/gaps.md index ecd19c55c3..5c9285c995 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -499,5 +499,6 @@ what an agent can't finish alone. | 2026-10-11 | minor | G8: Character panel OpenType buttons landed (TYPE-218-5, #3752); Numerals and Stylistic Sets submenus still missing | | 2026-10-11 | minor | G10: one-page flattened PDF write shipped (io::pdf, #3401); FILE-215-10 now partial | | 2026-10-10 | minor | G2: recorded Tilt-Shift computation/filtered-proxy measurements and limits; gap and estimate remain open +| 2026-10-11 | minor | G14 Sony metadata/crop progress recorded without closing camera colour or tone gaps | | 2026-10-10 | minor | Checked against the alpha gate (no alpha blockers); #2374 marked closed | | 2026-10-10 | major | First version, from the full re-measure against Photoshop 2026 27.11.0 and the open issues | diff --git a/docs/integration-testing/approval-refresh.json b/docs/integration-testing/approval-refresh.json new file mode 100644 index 0000000000..9801df95f1 --- /dev/null +++ b/docs/integration-testing/approval-refresh.json @@ -0,0 +1,2602 @@ +{ + "refreshed_at": "2026-10-29T12:06:14.628928+00:00", + "frozen_count": 108, + "currently_qualifying_frozen_heads": 107, + "prs": [ + { + "number": 9703, + "url": "https://github.com/storytold/photocraft/pull/9703", + "frozen_head": "3605d30c38294c4d970e52f4a02f44f97e8bc1a9", + "current_head": "3605d30c38294c4d970e52f4a02f44f97e8bc1a9", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T17:06:00Z", + "url": "https://github.com/storytold/photocraft/pull/9703#pullrequestreview-5655990760", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "3605d30c38294c4d970e52f4a02f44f97e8bc1a9" + } + } + }, + { + "number": 9651, + "url": "https://github.com/storytold/photocraft/pull/9651", + "frozen_head": "67666bdf72a58066df868868cef82e5b9cc838de", + "current_head": "67666bdf72a58066df868868cef82e5b9cc838de", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T11:38:57Z", + "url": "https://github.com/storytold/photocraft/pull/9651#pullrequestreview-5651366614", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "67666bdf72a58066df868868cef82e5b9cc838de" + } + } + }, + { + "number": 9623, + "url": "https://github.com/storytold/photocraft/pull/9623", + "frozen_head": "652075f4da7fe905ad651eebc3a6c276fe1d7a5d", + "current_head": "652075f4da7fe905ad651eebc3a6c276fe1d7a5d", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T08:29:25Z", + "url": "https://github.com/storytold/photocraft/pull/9623#pullrequestreview-5649212328", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "652075f4da7fe905ad651eebc3a6c276fe1d7a5d" + } + } + }, + { + "number": 9606, + "url": "https://github.com/storytold/photocraft/pull/9606", + "frozen_head": "6cc516a3d20120b678040050d95ccadc8d1dfd3f", + "current_head": "6cc516a3d20120b678040050d95ccadc8d1dfd3f", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T05:50:41Z", + "url": "https://github.com/storytold/photocraft/pull/9606#pullrequestreview-5647898187", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "6cc516a3d20120b678040050d95ccadc8d1dfd3f" + } + } + }, + { + "number": 9598, + "url": "https://github.com/storytold/photocraft/pull/9598", + "frozen_head": "47aea89e9220b996f0d5a0d2bb8b5938100b4ad1", + "current_head": "47aea89e9220b996f0d5a0d2bb8b5938100b4ad1", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T05:45:19Z", + "url": "https://github.com/storytold/photocraft/pull/9598#pullrequestreview-5647858443", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "47aea89e9220b996f0d5a0d2bb8b5938100b4ad1" + } + } + }, + { + "number": 9597, + "url": "https://github.com/storytold/photocraft/pull/9597", + "frozen_head": "9429df26b371c04c2afa65228a60ded739b5fbc2", + "current_head": "9429df26b371c04c2afa65228a60ded739b5fbc2", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T07:55:42Z", + "url": "https://github.com/storytold/photocraft/pull/9597#pullrequestreview-5648898287", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "9429df26b371c04c2afa65228a60ded739b5fbc2" + } + } + }, + { + "number": 9596, + "url": "https://github.com/storytold/photocraft/pull/9596", + "frozen_head": "e62013cfd652fa60470a0f7a185fbc8f3d2a2c92", + "current_head": "e62013cfd652fa60470a0f7a185fbc8f3d2a2c92", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T05:46:37Z", + "url": "https://github.com/storytold/photocraft/pull/9596#pullrequestreview-5647870259", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "e62013cfd652fa60470a0f7a185fbc8f3d2a2c92" + } + } + }, + { + "number": 9595, + "url": "https://github.com/storytold/photocraft/pull/9595", + "frozen_head": "75fa71a4f55a098061b12d91508b514565ab8dcf", + "current_head": "75fa71a4f55a098061b12d91508b514565ab8dcf", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T05:48:01Z", + "url": "https://github.com/storytold/photocraft/pull/9595#pullrequestreview-5647882992", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "75fa71a4f55a098061b12d91508b514565ab8dcf" + } + } + }, + { + "number": 9594, + "url": "https://github.com/storytold/photocraft/pull/9594", + "frozen_head": "46512521fec2b4b462c29d9fefd16398cb81212c", + "current_head": "46512521fec2b4b462c29d9fefd16398cb81212c", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T05:49:21Z", + "url": "https://github.com/storytold/photocraft/pull/9594#pullrequestreview-5647890395", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "46512521fec2b4b462c29d9fefd16398cb81212c" + } + } + }, + { + "number": 9590, + "url": "https://github.com/storytold/photocraft/pull/9590", + "frozen_head": "a9744ed44dc782613b19a97b8c159a091f73e669", + "current_head": "a9744ed44dc782613b19a97b8c159a091f73e669", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T05:54:47Z", + "url": "https://github.com/storytold/photocraft/pull/9590#pullrequestreview-5647923229", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "a9744ed44dc782613b19a97b8c159a091f73e669" + } + } + }, + { + "number": 9589, + "url": "https://github.com/storytold/photocraft/pull/9589", + "frozen_head": "da157945077190e550b53a5e14b0536f62761292", + "current_head": "da157945077190e550b53a5e14b0536f62761292", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T03:32:19Z", + "url": "https://github.com/storytold/photocraft/pull/9589#pullrequestreview-5647036365", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "da157945077190e550b53a5e14b0536f62761292" + } + } + }, + { + "number": 9584, + "url": "https://github.com/storytold/photocraft/pull/9584", + "frozen_head": "fc0f7b1132f799b5bba7be642c9047499d95a887", + "current_head": "fc0f7b1132f799b5bba7be642c9047499d95a887", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T03:41:38Z", + "url": "https://github.com/storytold/photocraft/pull/9584#pullrequestreview-5647082363", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "fc0f7b1132f799b5bba7be642c9047499d95a887" + } + } + }, + { + "number": 9523, + "url": "https://github.com/storytold/photocraft/pull/9523", + "frozen_head": "728782c595e768bdb6febc7f30e4d1456d13fd36", + "current_head": "728782c595e768bdb6febc7f30e4d1456d13fd36", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T23:36:04Z", + "url": "https://github.com/storytold/photocraft/pull/9523#pullrequestreview-5645920841", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "728782c595e768bdb6febc7f30e4d1456d13fd36" + } + } + }, + { + "number": 9517, + "url": "https://github.com/storytold/photocraft/pull/9517", + "frozen_head": "81b434c6149732eadc94e0465fea81bd075facd4", + "current_head": "81b434c6149732eadc94e0465fea81bd075facd4", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T19:39:44Z", + "url": "https://github.com/storytold/photocraft/pull/9517#pullrequestreview-5644911791", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "81b434c6149732eadc94e0465fea81bd075facd4" + } + } + }, + { + "number": 9512, + "url": "https://github.com/storytold/photocraft/pull/9512", + "frozen_head": "6c55561128caf5ac917eb3d174e8e7bb4bd48e23", + "current_head": "6c55561128caf5ac917eb3d174e8e7bb4bd48e23", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T19:23:44Z", + "url": "https://github.com/storytold/photocraft/pull/9512#pullrequestreview-5644863033", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "6c55561128caf5ac917eb3d174e8e7bb4bd48e23" + } + } + }, + { + "number": 9509, + "url": "https://github.com/storytold/photocraft/pull/9509", + "frozen_head": "d78d7493d3f0b6e760c88de969ac810e9bc5d910", + "current_head": "d78d7493d3f0b6e760c88de969ac810e9bc5d910", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T18:46:42Z", + "url": "https://github.com/storytold/photocraft/pull/9509#pullrequestreview-5644707748", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "d78d7493d3f0b6e760c88de969ac810e9bc5d910" + } + } + }, + { + "number": 9504, + "url": "https://github.com/storytold/photocraft/pull/9504", + "frozen_head": "993c9ed167c6acd9bc8f87c6cff6e2c7abba17a8", + "current_head": "993c9ed167c6acd9bc8f87c6cff6e2c7abba17a8", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T18:30:54Z", + "url": "https://github.com/storytold/photocraft/pull/9504#pullrequestreview-5644657832", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "993c9ed167c6acd9bc8f87c6cff6e2c7abba17a8" + } + } + }, + { + "number": 9493, + "url": "https://github.com/storytold/photocraft/pull/9493", + "frozen_head": "61a413d8df9e90ee545eb08e57c5615aa2b29cea", + "current_head": "61a413d8df9e90ee545eb08e57c5615aa2b29cea", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T18:35:43Z", + "url": "https://github.com/storytold/photocraft/pull/9493#pullrequestreview-5644672718", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "61a413d8df9e90ee545eb08e57c5615aa2b29cea" + } + } + }, + { + "number": 9481, + "url": "https://github.com/storytold/photocraft/pull/9481", + "frozen_head": "7937adff961027154d795b8905e821244ae4f929", + "current_head": "7937adff961027154d795b8905e821244ae4f929", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T18:03:55Z", + "url": "https://github.com/storytold/photocraft/pull/9481#pullrequestreview-5644538284", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "7937adff961027154d795b8905e821244ae4f929" + } + } + }, + { + "number": 9478, + "url": "https://github.com/storytold/photocraft/pull/9478", + "frozen_head": "cc208ee0440bbdf1858565dca49667272a490c56", + "current_head": "cc208ee0440bbdf1858565dca49667272a490c56", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T17:58:39Z", + "url": "https://github.com/storytold/photocraft/pull/9478#pullrequestreview-5644503679", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "cc208ee0440bbdf1858565dca49667272a490c56" + } + } + }, + { + "number": 9472, + "url": "https://github.com/storytold/photocraft/pull/9472", + "frozen_head": "4bab657cd4fb4a91ced44d3721e63a002ca5068c", + "current_head": "4bab657cd4fb4a91ced44d3721e63a002ca5068c", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T19:17:41Z", + "url": "https://github.com/storytold/photocraft/pull/9472#pullrequestreview-5644841088", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "4bab657cd4fb4a91ced44d3721e63a002ca5068c" + } + } + }, + { + "number": 9457, + "url": "https://github.com/storytold/photocraft/pull/9457", + "frozen_head": "2863c3281c2a22dade0ce92d42bf8900074f76c6", + "current_head": "2863c3281c2a22dade0ce92d42bf8900074f76c6", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T15:24:36Z", + "url": "https://github.com/storytold/photocraft/pull/9457#pullrequestreview-5643852329", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "2863c3281c2a22dade0ce92d42bf8900074f76c6" + } + } + }, + { + "number": 9436, + "url": "https://github.com/storytold/photocraft/pull/9436", + "frozen_head": "819f2692db4302019638c57b6ea34cd1e8f4c24b", + "current_head": "819f2692db4302019638c57b6ea34cd1e8f4c24b", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T22:16:33Z", + "url": "https://github.com/storytold/photocraft/pull/9436#pullrequestreview-5645623601", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "819f2692db4302019638c57b6ea34cd1e8f4c24b" + } + } + }, + { + "number": 9418, + "url": "https://github.com/storytold/photocraft/pull/9418", + "frozen_head": "da4b838e54f6073cda4798fa7b63b3b7214aaf93", + "current_head": "da4b838e54f6073cda4798fa7b63b3b7214aaf93", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T18:18:42Z", + "url": "https://github.com/storytold/photocraft/pull/9418#pullrequestreview-5644614398", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "da4b838e54f6073cda4798fa7b63b3b7214aaf93" + } + } + }, + { + "number": 9416, + "url": "https://github.com/storytold/photocraft/pull/9416", + "frozen_head": "742b06805284d8d76d5a29ec1821193f4835fedf", + "current_head": "742b06805284d8d76d5a29ec1821193f4835fedf", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T11:36:34Z", + "url": "https://github.com/storytold/photocraft/pull/9416#pullrequestreview-5642992245", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "742b06805284d8d76d5a29ec1821193f4835fedf" + } + } + }, + { + "number": 9401, + "url": "https://github.com/storytold/photocraft/pull/9401", + "frozen_head": "f241bba1adfb9c7ec5dd5ed9d86f95b63c7bc2c3", + "current_head": "f241bba1adfb9c7ec5dd5ed9d86f95b63c7bc2c3", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T11:13:17Z", + "url": "https://github.com/storytold/photocraft/pull/9401#pullrequestreview-5642877921", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "f241bba1adfb9c7ec5dd5ed9d86f95b63c7bc2c3" + } + } + }, + { + "number": 9354, + "url": "https://github.com/storytold/photocraft/pull/9354", + "frozen_head": "41eb1de5cff17f5f5b9c22913e48b71565b56a2a", + "current_head": "41eb1de5cff17f5f5b9c22913e48b71565b56a2a", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T06:55:52Z", + "url": "https://github.com/storytold/photocraft/pull/9354#pullrequestreview-5641946837", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "41eb1de5cff17f5f5b9c22913e48b71565b56a2a" + } + } + }, + { + "number": 9342, + "url": "https://github.com/storytold/photocraft/pull/9342", + "frozen_head": "c46a74621d36adae9707ab8f3eb39cf6b4c302b9", + "current_head": "c46a74621d36adae9707ab8f3eb39cf6b4c302b9", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T07:21:10Z", + "url": "https://github.com/storytold/photocraft/pull/9342#pullrequestreview-5642054720", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "c46a74621d36adae9707ab8f3eb39cf6b4c302b9" + } + } + }, + { + "number": 9339, + "url": "https://github.com/storytold/photocraft/pull/9339", + "frozen_head": "393645ab91460af2e37cc3ba8f6921e7551f676e", + "current_head": "393645ab91460af2e37cc3ba8f6921e7551f676e", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T07:36:38Z", + "url": "https://github.com/storytold/photocraft/pull/9339#pullrequestreview-5642090549", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "393645ab91460af2e37cc3ba8f6921e7551f676e" + } + } + }, + { + "number": 9282, + "url": "https://github.com/storytold/photocraft/pull/9282", + "frozen_head": "20803d1f15900ed6ecc7b5c79b4c68f6c3d6dcce", + "current_head": "20803d1f15900ed6ecc7b5c79b4c68f6c3d6dcce", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-26T04:14:47Z", + "url": "https://github.com/storytold/photocraft/pull/9282#pullrequestreview-5647322262", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "20803d1f15900ed6ecc7b5c79b4c68f6c3d6dcce" + } + } + }, + { + "number": 9172, + "url": "https://github.com/storytold/photocraft/pull/9172", + "frozen_head": "8ebb04999d25790f71f9bd88f7a268a6a2754aec", + "current_head": "8ebb04999d25790f71f9bd88f7a268a6a2754aec", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T18:18:17Z", + "url": "https://github.com/storytold/photocraft/pull/9172#pullrequestreview-5639390920", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "8ebb04999d25790f71f9bd88f7a268a6a2754aec" + } + } + }, + { + "number": 9110, + "url": "https://github.com/storytold/photocraft/pull/9110", + "frozen_head": "2e716f93b2e2135944e07d821be4eb38fce13ec9", + "current_head": "2e716f93b2e2135944e07d821be4eb38fce13ec9", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:41:50Z", + "url": "https://github.com/storytold/photocraft/pull/9110#pullrequestreview-5639002103", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "2e716f93b2e2135944e07d821be4eb38fce13ec9" + } + } + }, + { + "number": 9019, + "url": "https://github.com/storytold/photocraft/pull/9019", + "frozen_head": "364c4be1c19728aefa601ee924bc7a0cd6a09789", + "current_head": "364c4be1c19728aefa601ee924bc7a0cd6a09789", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:33:36Z", + "url": "https://github.com/storytold/photocraft/pull/9019#pullrequestreview-5638973719", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "364c4be1c19728aefa601ee924bc7a0cd6a09789" + } + } + }, + { + "number": 9015, + "url": "https://github.com/storytold/photocraft/pull/9015", + "frozen_head": "afb4364a8795c42e6353762891b4890d878f9a68", + "current_head": "afb4364a8795c42e6353762891b4890d878f9a68", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:33:42Z", + "url": "https://github.com/storytold/photocraft/pull/9015#pullrequestreview-5638974295", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "afb4364a8795c42e6353762891b4890d878f9a68" + } + } + }, + { + "number": 9004, + "url": "https://github.com/storytold/photocraft/pull/9004", + "frozen_head": "39cf823cdfe486bb967cf81df725d229f7eed903", + "current_head": "39cf823cdfe486bb967cf81df725d229f7eed903", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:33:48Z", + "url": "https://github.com/storytold/photocraft/pull/9004#pullrequestreview-5638974843", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "39cf823cdfe486bb967cf81df725d229f7eed903" + } + } + }, + { + "number": 8986, + "url": "https://github.com/storytold/photocraft/pull/8986", + "frozen_head": "390dfbbcb026b33d46c52c62360b65deca00f258", + "current_head": "390dfbbcb026b33d46c52c62360b65deca00f258", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:36:01Z", + "url": "https://github.com/storytold/photocraft/pull/8986#pullrequestreview-5638981860", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "390dfbbcb026b33d46c52c62360b65deca00f258" + } + } + }, + { + "number": 8985, + "url": "https://github.com/storytold/photocraft/pull/8985", + "frozen_head": "8e695caf885b529f01f482b3f0c90cdb34df1915", + "current_head": "8e695caf885b529f01f482b3f0c90cdb34df1915", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:33:54Z", + "url": "https://github.com/storytold/photocraft/pull/8985#pullrequestreview-5638975214", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "8e695caf885b529f01f482b3f0c90cdb34df1915" + } + } + }, + { + "number": 8931, + "url": "https://github.com/storytold/photocraft/pull/8931", + "frozen_head": "d42dd4c6302c77c1f9dc46b7b53ffa5eb0047a13", + "current_head": "d42dd4c6302c77c1f9dc46b7b53ffa5eb0047a13", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:59:36Z", + "url": "https://github.com/storytold/photocraft/pull/8931#pullrequestreview-5639059166", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "d42dd4c6302c77c1f9dc46b7b53ffa5eb0047a13" + } + } + }, + { + "number": 8905, + "url": "https://github.com/storytold/photocraft/pull/8905", + "frozen_head": "0fdc6259193aab32b8feab7347ddc36196f40a19", + "current_head": "0fdc6259193aab32b8feab7347ddc36196f40a19", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:38:23Z", + "url": "https://github.com/storytold/photocraft/pull/8905#pullrequestreview-5638989196", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "0fdc6259193aab32b8feab7347ddc36196f40a19" + } + } + }, + { + "number": 8903, + "url": "https://github.com/storytold/photocraft/pull/8903", + "frozen_head": "d387f52f1f2f5681b2c7d1c517aa5b5992c7bc88", + "current_head": "d387f52f1f2f5681b2c7d1c517aa5b5992c7bc88", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:38:30Z", + "url": "https://github.com/storytold/photocraft/pull/8903#pullrequestreview-5638989541", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "d387f52f1f2f5681b2c7d1c517aa5b5992c7bc88" + } + } + }, + { + "number": 8897, + "url": "https://github.com/storytold/photocraft/pull/8897", + "frozen_head": "eb06798f15516eb7e4fac24c98346fd9052e7f8e", + "current_head": "eb06798f15516eb7e4fac24c98346fd9052e7f8e", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:38:48Z", + "url": "https://github.com/storytold/photocraft/pull/8897#pullrequestreview-5638990476", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "eb06798f15516eb7e4fac24c98346fd9052e7f8e" + } + } + }, + { + "number": 8896, + "url": "https://github.com/storytold/photocraft/pull/8896", + "frozen_head": "19fa473039ef11deda7c3200c8fac1de41309086", + "current_head": "19fa473039ef11deda7c3200c8fac1de41309086", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-28T13:25:04Z", + "url": "https://github.com/storytold/photocraft/pull/8896#pullrequestreview-5683297464", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "19fa473039ef11deda7c3200c8fac1de41309086" + } + } + }, + { + "number": 8892, + "url": "https://github.com/storytold/photocraft/pull/8892", + "frozen_head": "9267c4fcf83a260d4bae0e441dc1af9bc48aa23b", + "current_head": "9267c4fcf83a260d4bae0e441dc1af9bc48aa23b", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-24T16:40:01Z", + "url": "https://github.com/storytold/photocraft/pull/8892#pullrequestreview-5638996509", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "9267c4fcf83a260d4bae0e441dc1af9bc48aa23b" + } + } + }, + { + "number": 8347, + "url": "https://github.com/storytold/photocraft/pull/8347", + "frozen_head": "2b1364393cfcd09380cf18a221e7cdd325fc4deb", + "current_head": "2b1364393cfcd09380cf18a221e7cdd325fc4deb", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T17:48:01Z", + "url": "https://github.com/storytold/photocraft/pull/8347#pullrequestreview-5644437741", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "2b1364393cfcd09380cf18a221e7cdd325fc4deb" + } + } + }, + { + "number": 8193, + "url": "https://github.com/storytold/photocraft/pull/8193", + "frozen_head": "864024609b872de3d869879f1632b951c896c6cd", + "current_head": "864024609b872de3d869879f1632b951c896c6cd", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T12:43:15Z", + "url": "https://github.com/storytold/photocraft/pull/8193#pullrequestreview-5643244034", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "864024609b872de3d869879f1632b951c896c6cd" + } + } + }, + { + "number": 8192, + "url": "https://github.com/storytold/photocraft/pull/8192", + "frozen_head": "412e3b7cf1f4836a5772d93391d21728dbe1f74f", + "current_head": "412e3b7cf1f4836a5772d93391d21728dbe1f74f", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T09:50:41Z", + "url": "https://github.com/storytold/photocraft/pull/8192#pullrequestreview-5642599218", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "412e3b7cf1f4836a5772d93391d21728dbe1f74f" + } + } + }, + { + "number": 8191, + "url": "https://github.com/storytold/photocraft/pull/8191", + "frozen_head": "91e4cec43525ca739c05cff614701fbd3576e389", + "current_head": "91e4cec43525ca739c05cff614701fbd3576e389", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T09:46:29Z", + "url": "https://github.com/storytold/photocraft/pull/8191#pullrequestreview-5642584382", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "91e4cec43525ca739c05cff614701fbd3576e389" + } + } + }, + { + "number": 8074, + "url": "https://github.com/storytold/photocraft/pull/8074", + "frozen_head": "290f924d0fecc3bf6bea159c0d9e86255d326a96", + "current_head": "290f924d0fecc3bf6bea159c0d9e86255d326a96", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-22T10:39:23Z", + "url": "https://github.com/storytold/photocraft/pull/8074#pullrequestreview-5612886202", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "290f924d0fecc3bf6bea159c0d9e86255d326a96" + } + } + }, + { + "number": 8039, + "url": "https://github.com/storytold/photocraft/pull/8039", + "frozen_head": "5579cf5439856fed93f41a669a3fc9b56d5813cf", + "current_head": "5579cf5439856fed93f41a669a3fc9b56d5813cf", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T22:54:54Z", + "url": "https://github.com/storytold/photocraft/pull/8039#pullrequestreview-5592809677", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "5579cf5439856fed93f41a669a3fc9b56d5813cf" + } + } + }, + { + "number": 7903, + "url": "https://github.com/storytold/photocraft/pull/7903", + "frozen_head": "5c30699087b02edcaa23397a0f7076bf503be048", + "current_head": "5c30699087b02edcaa23397a0f7076bf503be048", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T12:55:08Z", + "url": "https://github.com/storytold/photocraft/pull/7903#pullrequestreview-5643279271", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "5c30699087b02edcaa23397a0f7076bf503be048" + } + } + }, + { + "number": 7848, + "url": "https://github.com/storytold/photocraft/pull/7848", + "frozen_head": "389a1d5bd67072d5581c27989080222a7065b585", + "current_head": "389a1d5bd67072d5581c27989080222a7065b585", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T14:05:42Z", + "url": "https://github.com/storytold/photocraft/pull/7848#pullrequestreview-5586186420", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "389a1d5bd67072d5581c27989080222a7065b585" + } + } + }, + { + "number": 7743, + "url": "https://github.com/storytold/photocraft/pull/7743", + "frozen_head": "fd6fc92015fd08560362b4b32844edf97722f292", + "current_head": "fd6fc92015fd08560362b4b32844edf97722f292", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-19T17:02:06Z", + "url": "https://github.com/storytold/photocraft/pull/7743#pullrequestreview-5574964336", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "fd6fc92015fd08560362b4b32844edf97722f292" + } + } + }, + { + "number": 7742, + "url": "https://github.com/storytold/photocraft/pull/7742", + "frozen_head": "ab844f9cbcd1f1839ed7f286776331cb72e399aa", + "current_head": "ab844f9cbcd1f1839ed7f286776331cb72e399aa", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T14:12:28Z", + "url": "https://github.com/storytold/photocraft/pull/7742#pullrequestreview-5586281249", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "ab844f9cbcd1f1839ed7f286776331cb72e399aa" + } + } + }, + { + "number": 7648, + "url": "https://github.com/storytold/photocraft/pull/7648", + "frozen_head": "d24669d412f64ab079a668b0b8520ddbc607410c", + "current_head": "d24669d412f64ab079a668b0b8520ddbc607410c", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-28T17:15:54Z", + "url": "https://github.com/storytold/photocraft/pull/7648#pullrequestreview-5686770506", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "d24669d412f64ab079a668b0b8520ddbc607410c" + } + } + }, + { + "number": 7255, + "url": "https://github.com/storytold/photocraft/pull/7255", + "frozen_head": "1b810052bc3a876c1eaf1a8766870ffdba9f8a80", + "current_head": "1b810052bc3a876c1eaf1a8766870ffdba9f8a80", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-19T23:37:36Z", + "url": "https://github.com/storytold/photocraft/pull/7255#pullrequestreview-5579038009", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "1b810052bc3a876c1eaf1a8766870ffdba9f8a80" + } + } + }, + { + "number": 7153, + "url": "https://github.com/storytold/photocraft/pull/7153", + "frozen_head": "6f5d929d6172cf211a070f12cde9507aca9eb30a", + "current_head": "6f5d929d6172cf211a070f12cde9507aca9eb30a", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-27T23:20:12Z", + "url": "https://github.com/storytold/photocraft/pull/7153#pullrequestreview-5675752399", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "6f5d929d6172cf211a070f12cde9507aca9eb30a" + } + } + }, + { + "number": 6621, + "url": "https://github.com/storytold/photocraft/pull/6621", + "frozen_head": "ead45134d320cb1002724d5ef44f5c56588bbe1d", + "current_head": "ead45134d320cb1002724d5ef44f5c56588bbe1d", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T15:33:29Z", + "url": "https://github.com/storytold/photocraft/pull/6621#pullrequestreview-5643879866", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "ead45134d320cb1002724d5ef44f5c56588bbe1d" + } + } + }, + { + "number": 6510, + "url": "https://github.com/storytold/photocraft/pull/6510", + "frozen_head": "8bb0a5e67474d36ae08d565251edb1ae780dd044", + "current_head": "8bb0a5e67474d36ae08d565251edb1ae780dd044", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-27T08:54:40Z", + "url": "https://github.com/storytold/photocraft/pull/6510#pullrequestreview-5664421033", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "8bb0a5e67474d36ae08d565251edb1ae780dd044" + } + } + }, + { + "number": 6492, + "url": "https://github.com/storytold/photocraft/pull/6492", + "frozen_head": "657cfd503d4ce276df6b5e9f763cb3a5cf2deaeb", + "current_head": "657cfd503d4ce276df6b5e9f763cb3a5cf2deaeb", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T09:49:00Z", + "url": "https://github.com/storytold/photocraft/pull/6492#pullrequestreview-5583441089", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "657cfd503d4ce276df6b5e9f763cb3a5cf2deaeb" + } + } + }, + { + "number": 6449, + "url": "https://github.com/storytold/photocraft/pull/6449", + "frozen_head": "25c38a0b69b7bff31badcdbe2ef9f2ff6aba1c63", + "current_head": "25c38a0b69b7bff31badcdbe2ef9f2ff6aba1c63", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T14:07:53Z", + "url": "https://github.com/storytold/photocraft/pull/6449#pullrequestreview-5548906956", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "25c38a0b69b7bff31badcdbe2ef9f2ff6aba1c63" + } + } + }, + { + "number": 6387, + "url": "https://github.com/storytold/photocraft/pull/6387", + "frozen_head": "8bfbbf816025942b74130adf16fb07265817b691", + "current_head": "8bfbbf816025942b74130adf16fb07265817b691", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-17T00:45:37Z", + "url": "https://github.com/storytold/photocraft/pull/6387#pullrequestreview-5555146754", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "8bfbbf816025942b74130adf16fb07265817b691" + } + } + }, + { + "number": 6383, + "url": "https://github.com/storytold/photocraft/pull/6383", + "frozen_head": "74aadae69e3b3f5cd257bca1926acc1b1297b1a2", + "current_head": "74aadae69e3b3f5cd257bca1926acc1b1297b1a2", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T13:09:48Z", + "url": "https://github.com/storytold/photocraft/pull/6383#pullrequestreview-5548207780", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "74aadae69e3b3f5cd257bca1926acc1b1297b1a2" + } + } + }, + { + "number": 6236, + "url": "https://github.com/storytold/photocraft/pull/6236", + "frozen_head": "ce546dd4b5451a17b843ef1e129bdb40fbfe3160", + "current_head": "ce546dd4b5451a17b843ef1e129bdb40fbfe3160", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-25T16:15:01Z", + "url": "https://github.com/storytold/photocraft/pull/6236#pullrequestreview-5644088784", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "ce546dd4b5451a17b843ef1e129bdb40fbfe3160" + } + } + }, + { + "number": 6139, + "url": "https://github.com/storytold/photocraft/pull/6139", + "frozen_head": "e2347f8ead85d929193044f139788b850e31c06f", + "current_head": "e2347f8ead85d929193044f139788b850e31c06f", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T02:15:01Z", + "url": "https://github.com/storytold/photocraft/pull/6139#pullrequestreview-5542220545", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "e2347f8ead85d929193044f139788b850e31c06f" + } + } + }, + { + "number": 6026, + "url": "https://github.com/storytold/photocraft/pull/6026", + "frozen_head": "248ba660576f4896f69cbb6639353e2f1d295271", + "current_head": "248ba660576f4896f69cbb6639353e2f1d295271", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T09:43:20Z", + "url": "https://github.com/storytold/photocraft/pull/6026#pullrequestreview-5545897025", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "248ba660576f4896f69cbb6639353e2f1d295271" + } + } + }, + { + "number": 5939, + "url": "https://github.com/storytold/photocraft/pull/5939", + "frozen_head": "7348e060b4be7204fb69b59079c3b9d808e9aad3", + "current_head": "7348e060b4be7204fb69b59079c3b9d808e9aad3", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-17T23:23:14Z", + "url": "https://github.com/storytold/photocraft/pull/5939#pullrequestreview-5560602826", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "7348e060b4be7204fb69b59079c3b9d808e9aad3" + } + } + }, + { + "number": 5870, + "url": "https://github.com/storytold/photocraft/pull/5870", + "frozen_head": "f9de0a6abc78aa405b1ef46f5da6cba424106204", + "current_head": "f9de0a6abc78aa405b1ef46f5da6cba424106204", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T18:02:42Z", + "url": "https://github.com/storytold/photocraft/pull/5870#pullrequestreview-5551781697", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "f9de0a6abc78aa405b1ef46f5da6cba424106204" + } + } + }, + { + "number": 5744, + "url": "https://github.com/storytold/photocraft/pull/5744", + "frozen_head": "50b1f6734799cf7b5d45dd84868976afd31aa711", + "current_head": "50b1f6734799cf7b5d45dd84868976afd31aa711", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T00:22:49Z", + "url": "https://github.com/storytold/photocraft/pull/5744#pullrequestreview-5593443602", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "50b1f6734799cf7b5d45dd84868976afd31aa711" + } + } + }, + { + "number": 5650, + "url": "https://github.com/storytold/photocraft/pull/5650", + "frozen_head": "4b1bd6fb6d264f885cb9caa3b8a6578ee527bd7b", + "current_head": "4b1bd6fb6d264f885cb9caa3b8a6578ee527bd7b", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T00:12:41Z", + "url": "https://github.com/storytold/photocraft/pull/5650#pullrequestreview-5593380251", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "4b1bd6fb6d264f885cb9caa3b8a6578ee527bd7b" + } + } + }, + { + "number": 5515, + "url": "https://github.com/storytold/photocraft/pull/5515", + "frozen_head": "375d4894a119b6cd5933d53e8fe7f506d2783392", + "current_head": "375d4894a119b6cd5933d53e8fe7f506d2783392", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T00:12:20Z", + "url": "https://github.com/storytold/photocraft/pull/5515#pullrequestreview-5593377843", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "375d4894a119b6cd5933d53e8fe7f506d2783392" + } + } + }, + { + "number": 5493, + "url": "https://github.com/storytold/photocraft/pull/5493", + "frozen_head": "f97eb2849a68e1ed1c08c5b378770cf35cbcb72d", + "current_head": "67f57c3cf1e7de045aee03a305663d9560daa3e3", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": false, + "exclusions": [ + "head changed; newer head remains excluded", + "latest FredApps review is not an approval of current head" + ], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-27T12:23:56Z", + "url": "https://github.com/storytold/photocraft/pull/5493#pullrequestreview-5666969724", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "f97eb2849a68e1ed1c08c5b378770cf35cbcb72d" + } + } + }, + { + "number": 5453, + "url": "https://github.com/storytold/photocraft/pull/5453", + "frozen_head": "e22a9baedceefd97daffe84403b23c99c56d6919", + "current_head": "e22a9baedceefd97daffe84403b23c99c56d6919", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-17T20:51:16Z", + "url": "https://github.com/storytold/photocraft/pull/5453#pullrequestreview-5560030568", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "e22a9baedceefd97daffe84403b23c99c56d6919" + } + } + }, + { + "number": 5270, + "url": "https://github.com/storytold/photocraft/pull/5270", + "frozen_head": "9db1c7ae1d48ce4f31622b5f9029c70c590842f8", + "current_head": "9db1c7ae1d48ce4f31622b5f9029c70c590842f8", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T13:29:14Z", + "url": "https://github.com/storytold/photocraft/pull/5270#pullrequestreview-5585703891", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "9db1c7ae1d48ce4f31622b5f9029c70c590842f8" + } + } + }, + { + "number": 5176, + "url": "https://github.com/storytold/photocraft/pull/5176", + "frozen_head": "c96891c298151c5cb11a55928b9e1c27911f38bd", + "current_head": "c96891c298151c5cb11a55928b9e1c27911f38bd", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T13:39:04Z", + "url": "https://github.com/storytold/photocraft/pull/5176#pullrequestreview-5585830576", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "c96891c298151c5cb11a55928b9e1c27911f38bd" + } + } + }, + { + "number": 5165, + "url": "https://github.com/storytold/photocraft/pull/5165", + "frozen_head": "27bc6e4b37b701480efa69559ab13eafc52bd94c", + "current_head": "27bc6e4b37b701480efa69559ab13eafc52bd94c", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T15:13:12Z", + "url": "https://github.com/storytold/photocraft/pull/5165#pullrequestreview-5549755629", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "27bc6e4b37b701480efa69559ab13eafc52bd94c" + } + } + }, + { + "number": 5090, + "url": "https://github.com/storytold/photocraft/pull/5090", + "frozen_head": "61d9e8cc1aed29ed6bea0d0fd2702fa87c4f0206", + "current_head": "61d9e8cc1aed29ed6bea0d0fd2702fa87c4f0206", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T13:46:28Z", + "url": "https://github.com/storytold/photocraft/pull/5090#pullrequestreview-5585928498", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "61d9e8cc1aed29ed6bea0d0fd2702fa87c4f0206" + } + } + }, + { + "number": 5082, + "url": "https://github.com/storytold/photocraft/pull/5082", + "frozen_head": "23bab3cc9204568aaeb012b9e1da70a2caacb879", + "current_head": "23bab3cc9204568aaeb012b9e1da70a2caacb879", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-18T09:23:19Z", + "url": "https://github.com/storytold/photocraft/pull/5082#pullrequestreview-5562323692", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "23bab3cc9204568aaeb012b9e1da70a2caacb879" + } + } + }, + { + "number": 5010, + "url": "https://github.com/storytold/photocraft/pull/5010", + "frozen_head": "cc865221894e21f846d92b721cce7421ea338363", + "current_head": "cc865221894e21f846d92b721cce7421ea338363", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T13:51:11Z", + "url": "https://github.com/storytold/photocraft/pull/5010#pullrequestreview-5585991159", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "cc865221894e21f846d92b721cce7421ea338363" + } + } + }, + { + "number": 4993, + "url": "https://github.com/storytold/photocraft/pull/4993", + "frozen_head": "81964dc5ef77a71a2ae2a938958cf3ed77d90719", + "current_head": "81964dc5ef77a71a2ae2a938958cf3ed77d90719", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T15:10:55Z", + "url": "https://github.com/storytold/photocraft/pull/4993#pullrequestreview-5549725641", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "81964dc5ef77a71a2ae2a938958cf3ed77d90719" + } + } + }, + { + "number": 4992, + "url": "https://github.com/storytold/photocraft/pull/4992", + "frozen_head": "194a8976cd6c14441222b287b9b4f4841a0eb2f9", + "current_head": "194a8976cd6c14441222b287b9b4f4841a0eb2f9", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T15:10:53Z", + "url": "https://github.com/storytold/photocraft/pull/4992#pullrequestreview-5549725271", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "194a8976cd6c14441222b287b9b4f4841a0eb2f9" + } + } + }, + { + "number": 4985, + "url": "https://github.com/storytold/photocraft/pull/4985", + "frozen_head": "1dc98f80f60e993f3edf20af815391b6a7e7add7", + "current_head": "1dc98f80f60e993f3edf20af815391b6a7e7add7", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-28T08:02:27Z", + "url": "https://github.com/storytold/photocraft/pull/4985#pullrequestreview-5679506261", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "1dc98f80f60e993f3edf20af815391b6a7e7add7" + } + } + }, + { + "number": 4938, + "url": "https://github.com/storytold/photocraft/pull/4938", + "frozen_head": "63b7c921634835259139e4d3e7b9d3c396998b4d", + "current_head": "63b7c921634835259139e4d3e7b9d3c396998b4d", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T13:55:39Z", + "url": "https://github.com/storytold/photocraft/pull/4938#pullrequestreview-5586050980", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "63b7c921634835259139e4d3e7b9d3c396998b4d" + } + } + }, + { + "number": 4890, + "url": "https://github.com/storytold/photocraft/pull/4890", + "frozen_head": "ab84cab7355ac999fb1be226950978bafec39605", + "current_head": "ab84cab7355ac999fb1be226950978bafec39605", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T00:37:37Z", + "url": "https://github.com/storytold/photocraft/pull/4890#pullrequestreview-5593534344", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "ab84cab7355ac999fb1be226950978bafec39605" + } + } + }, + { + "number": 4883, + "url": "https://github.com/storytold/photocraft/pull/4883", + "frozen_head": "ea500486fb40511d3b4782dfacbb89fbff846d8a", + "current_head": "ea500486fb40511d3b4782dfacbb89fbff846d8a", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:27:22Z", + "url": "https://github.com/storytold/photocraft/pull/4883#pullrequestreview-5583810948", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "ea500486fb40511d3b4782dfacbb89fbff846d8a" + } + } + }, + { + "number": 4783, + "url": "https://github.com/storytold/photocraft/pull/4783", + "frozen_head": "a9d62726bed607bc540db9d09c8dc1be4f9895aa", + "current_head": "a9d62726bed607bc540db9d09c8dc1be4f9895aa", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:26:56Z", + "url": "https://github.com/storytold/photocraft/pull/4783#pullrequestreview-5583807081", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "a9d62726bed607bc540db9d09c8dc1be4f9895aa" + } + } + }, + { + "number": 4763, + "url": "https://github.com/storytold/photocraft/pull/4763", + "frozen_head": "f2804a7cf013519d9ba8bac1da3d96458c4f656b", + "current_head": "f2804a7cf013519d9ba8bac1da3d96458c4f656b", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:17:19Z", + "url": "https://github.com/storytold/photocraft/pull/4763#pullrequestreview-5583718187", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "f2804a7cf013519d9ba8bac1da3d96458c4f656b" + } + } + }, + { + "number": 4742, + "url": "https://github.com/storytold/photocraft/pull/4742", + "frozen_head": "b7145b5a8afb85d0eef3922931d6749436966943", + "current_head": "b7145b5a8afb85d0eef3922931d6749436966943", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-16T15:12:19Z", + "url": "https://github.com/storytold/photocraft/pull/4742#pullrequestreview-5549743037", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "b7145b5a8afb85d0eef3922931d6749436966943" + } + } + }, + { + "number": 4711, + "url": "https://github.com/storytold/photocraft/pull/4711", + "frozen_head": "db546ff4822a011a7915b66af3834f94c05767db", + "current_head": "db546ff4822a011a7915b66af3834f94c05767db", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T03:44:19Z", + "url": "https://github.com/storytold/photocraft/pull/4711#pullrequestreview-5594717250", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "db546ff4822a011a7915b66af3834f94c05767db" + } + } + }, + { + "number": 4547, + "url": "https://github.com/storytold/photocraft/pull/4547", + "frozen_head": "a08f7a2295488c2692f68902835a693322017b64", + "current_head": "a08f7a2295488c2692f68902835a693322017b64", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:18:20Z", + "url": "https://github.com/storytold/photocraft/pull/4547#pullrequestreview-5583727527", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "a08f7a2295488c2692f68902835a693322017b64" + } + } + }, + { + "number": 4305, + "url": "https://github.com/storytold/photocraft/pull/4305", + "frozen_head": "1b74873991dbb2e9803d228a969291f09c6f1032", + "current_head": "1b74873991dbb2e9803d228a969291f09c6f1032", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T03:52:30Z", + "url": "https://github.com/storytold/photocraft/pull/4305#pullrequestreview-5594762253", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "1b74873991dbb2e9803d228a969291f09c6f1032" + } + } + }, + { + "number": 4042, + "url": "https://github.com/storytold/photocraft/pull/4042", + "frozen_head": "f05098562220a663d052ee3918fd36c8c3e17a51", + "current_head": "f05098562220a663d052ee3918fd36c8c3e17a51", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:20:17Z", + "url": "https://github.com/storytold/photocraft/pull/4042#pullrequestreview-5583745473", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "f05098562220a663d052ee3918fd36c8c3e17a51" + } + } + }, + { + "number": 4035, + "url": "https://github.com/storytold/photocraft/pull/4035", + "frozen_head": "15ebf8fc940031abdf772e5fdd687c8b55938639", + "current_head": "15ebf8fc940031abdf772e5fdd687c8b55938639", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T04:40:10Z", + "url": "https://github.com/storytold/photocraft/pull/4035#pullrequestreview-5595033656", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "15ebf8fc940031abdf772e5fdd687c8b55938639" + } + } + }, + { + "number": 4023, + "url": "https://github.com/storytold/photocraft/pull/4023", + "frozen_head": "303a5346fcb5961cf3a776024db58507b401e4ea", + "current_head": "303a5346fcb5961cf3a776024db58507b401e4ea", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T04:44:05Z", + "url": "https://github.com/storytold/photocraft/pull/4023#pullrequestreview-5595056228", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "303a5346fcb5961cf3a776024db58507b401e4ea" + } + } + }, + { + "number": 3967, + "url": "https://github.com/storytold/photocraft/pull/3967", + "frozen_head": "3a77519ce2cef0fb60cebd4ea796d599f68868cb", + "current_head": "3a77519ce2cef0fb60cebd4ea796d599f68868cb", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T04:46:51Z", + "url": "https://github.com/storytold/photocraft/pull/3967#pullrequestreview-5595072511", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "3a77519ce2cef0fb60cebd4ea796d599f68868cb" + } + } + }, + { + "number": 3874, + "url": "https://github.com/storytold/photocraft/pull/3874", + "frozen_head": "92488307722c3b840507827cac7ee9a88470fc8a", + "current_head": "92488307722c3b840507827cac7ee9a88470fc8a", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T04:51:17Z", + "url": "https://github.com/storytold/photocraft/pull/3874#pullrequestreview-5595098959", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "92488307722c3b840507827cac7ee9a88470fc8a" + } + } + }, + { + "number": 3748, + "url": "https://github.com/storytold/photocraft/pull/3748", + "frozen_head": "c45d01eafe84e600bb28033a6853cc19c827b7bf", + "current_head": "c45d01eafe84e600bb28033a6853cc19c827b7bf", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:26:31Z", + "url": "https://github.com/storytold/photocraft/pull/3748#pullrequestreview-5583803054", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "c45d01eafe84e600bb28033a6853cc19c827b7bf" + } + } + }, + { + "number": 3554, + "url": "https://github.com/storytold/photocraft/pull/3554", + "frozen_head": "dd21e325b515cbf67fd4a461ae5b3e1b195aa53d", + "current_head": "dd21e325b515cbf67fd4a461ae5b3e1b195aa53d", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:23:03Z", + "url": "https://github.com/storytold/photocraft/pull/3554#pullrequestreview-5583771056", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "dd21e325b515cbf67fd4a461ae5b3e1b195aa53d" + } + } + }, + { + "number": 3520, + "url": "https://github.com/storytold/photocraft/pull/3520", + "frozen_head": "d36ec9a21e9c1ed70de2e0d185efd7e084644157", + "current_head": "d36ec9a21e9c1ed70de2e0d185efd7e084644157", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:19:14Z", + "url": "https://github.com/storytold/photocraft/pull/3520#pullrequestreview-5583735883", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "d36ec9a21e9c1ed70de2e0d185efd7e084644157" + } + } + }, + { + "number": 3519, + "url": "https://github.com/storytold/photocraft/pull/3519", + "frozen_head": "807de6c043a512cb947d86b944c758b3db1277c7", + "current_head": "807de6c043a512cb947d86b944c758b3db1277c7", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-20T10:19:34Z", + "url": "https://github.com/storytold/photocraft/pull/3519#pullrequestreview-5583738841", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "807de6c043a512cb947d86b944c758b3db1277c7" + } + } + }, + { + "number": 3464, + "url": "https://github.com/storytold/photocraft/pull/3464", + "frozen_head": "1eecd00b2dff4ae4c642269cec211cd06ce1c3aa", + "current_head": "1eecd00b2dff4ae4c642269cec211cd06ce1c3aa", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T08:42:37Z", + "url": "https://github.com/storytold/photocraft/pull/3464#pullrequestreview-5597090618", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "1eecd00b2dff4ae4c642269cec211cd06ce1c3aa" + } + } + }, + { + "number": 3461, + "url": "https://github.com/storytold/photocraft/pull/3461", + "frozen_head": "5d8cb2a39ad70e31260f1f3fc2010ca132daff65", + "current_head": "5d8cb2a39ad70e31260f1f3fc2010ca132daff65", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T08:45:31Z", + "url": "https://github.com/storytold/photocraft/pull/3461#pullrequestreview-5597122170", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "5d8cb2a39ad70e31260f1f3fc2010ca132daff65" + } + } + }, + { + "number": 3455, + "url": "https://github.com/storytold/photocraft/pull/3455", + "frozen_head": "d84fa7955d260505378a1a596ec80d602036319d", + "current_head": "d84fa7955d260505378a1a596ec80d602036319d", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T08:46:06Z", + "url": "https://github.com/storytold/photocraft/pull/3455#pullrequestreview-5597131410", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "d84fa7955d260505378a1a596ec80d602036319d" + } + } + }, + { + "number": 3387, + "url": "https://github.com/storytold/photocraft/pull/3387", + "frozen_head": "58b83f42a4b39cf56751be53ec8d227efee70f68", + "current_head": "58b83f42a4b39cf56751be53ec8d227efee70f68", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T08:51:49Z", + "url": "https://github.com/storytold/photocraft/pull/3387#pullrequestreview-5597200428", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "58b83f42a4b39cf56751be53ec8d227efee70f68" + } + } + }, + { + "number": 3345, + "url": "https://github.com/storytold/photocraft/pull/3345", + "frozen_head": "bfb691f84896fe68543980426632153dc4b4ea69", + "current_head": "bfb691f84896fe68543980426632153dc4b4ea69", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T08:57:39Z", + "url": "https://github.com/storytold/photocraft/pull/3345#pullrequestreview-5597265645", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "bfb691f84896fe68543980426632153dc4b4ea69" + } + } + }, + { + "number": 3142, + "url": "https://github.com/storytold/photocraft/pull/3142", + "frozen_head": "e2ed234e654e574109ffcdb9756f8e8d1b8a00b2", + "current_head": "e2ed234e654e574109ffcdb9756f8e8d1b8a00b2", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T09:18:10Z", + "url": "https://github.com/storytold/photocraft/pull/3142#pullrequestreview-5597503674", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "e2ed234e654e574109ffcdb9756f8e8d1b8a00b2" + } + } + }, + { + "number": 3139, + "url": "https://github.com/storytold/photocraft/pull/3139", + "frozen_head": "4da79e8d16ded8b51f06c1ac64e50ccba288274e", + "current_head": "4da79e8d16ded8b51f06c1ac64e50ccba288274e", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T09:17:33Z", + "url": "https://github.com/storytold/photocraft/pull/3139#pullrequestreview-5597496876", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "4da79e8d16ded8b51f06c1ac64e50ccba288274e" + } + } + }, + { + "number": 2300, + "url": "https://github.com/storytold/photocraft/pull/2300", + "frozen_head": "ebf3777aec961d1815aa141d9987eaa645c2273f", + "current_head": "ebf3777aec961d1815aa141d9987eaa645c2273f", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-18T18:14:16Z", + "url": "https://github.com/storytold/photocraft/pull/2300#pullrequestreview-5564229610", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "ebf3777aec961d1815aa141d9987eaa645c2273f" + } + } + }, + { + "number": 1991, + "url": "https://github.com/storytold/photocraft/pull/1991", + "frozen_head": "202266b90613280e16ae285b53dd4e10d5f0c7ac", + "current_head": "202266b90613280e16ae285b53dd4e10d5f0c7ac", + "state": "OPEN", + "isDraft": false, + "current_rollup": { + "state": "SUCCESS" + }, + "currently_qualifies": true, + "exclusions": [], + "approval_receipt": { + "state": "APPROVED", + "submittedAt": "2026-10-21T09:51:24Z", + "url": "https://github.com/storytold/photocraft/pull/1991#pullrequestreview-5597895651", + "author": { + "login": "FredApps" + }, + "commit": { + "oid": "202266b90613280e16ae285b53dd4e10d5f0c7ac" + } + } + } + ] +} diff --git a/docs/integration-testing/approved-bugfix-parity-2026-10-29.md b/docs/integration-testing/approved-bugfix-parity-2026-10-29.md new file mode 100644 index 0000000000..b6643f7ca8 --- /dev/null +++ b/docs/integration-testing/approved-bugfix-parity-2026-10-29.md @@ -0,0 +1,326 @@ +> HISTORICAL 108-PR BUILD: this record describes the earlier source and artifact. The current branch has 21 requested PRs removed. See [trimmed integration](trimmed-integration-2026-10-29.md) for current scope and validation. Do not use the old portable artifact to validate these removals. + +# PhotoCraft integration test plan + +Status: TEST BUILD PREPARED; automated validation passed. Every manual case is NOT RUN. +This plan supplements the existing gates. It does not claim Photoshop parity or authorize disabling checks. + +## Provenance and release gate + +At selection freeze, GitHub showed 108 open, non-draft, unmerged PRs, each with the latest +FredApps review APPROVED at its exact current head, no unresolved inline threads, and successful +current-head check rollup. Full heads, review receipts, checks, changed files and authored regression +descriptions are in [approved-selection.json](approved-selection.json). Successful rollup can include +skipped Windows/GPU jobs; record actual job and adapter execution separately. Recheck heads before final delivery. + +Base: `5f9b4391874aabc9deb2fcb905267613e4d93ec8`. Branch: `integration/approved-bugfix-parity-2026-10-29`. +Record the final commit SHA, toolchain, OS, adapter/backend, font inputs, corpus pins, commands, +pass/fail/ignored counts, duration, output log/artifact URLs, and every skipped or unavailable stage. +Require every selected head to be an ancestor of the tested SHA. Never equate a merged-head ancestry +check with preservation of its behavior: rerun the regressions after conflict resolutions. + +## Source checkout checks (PowerShell) + +These commands require a source checkout, Rust and the repository's documented dependencies. They are separate from testing the portable ZIP. Use a dedicated PowerShell session in the checkout: + +```powershell +$env:PHOTOCRAFT_NO_PRINT = '1' +$env:LPDEST = 'photocraft-no-such-printer' +$env:PHOTOCRAFT_FULL_SWEEP = '1' +# Optional isolated build output (can require rebuilding dependencies): +$env:CARGO_TARGET_DIR = Join-Path $PWD 'target\integration-approved' +cargo test --workspace --locked +``` + +Only the Windows Intel/DX12 case (#9110) requests `$env:WGPU_BACKEND = 'dx12'`; set it in that dedicated test session and record the actual adapter/backend. Do not infer GPU execution from a green test that returned early. Portable ZIP testers do not need Cargo; use the Windows execution sheet below. + +## Automated execution + +Set `PHOTOCRAFT_NO_PRINT=1` and `LPDEST=photocraft-no-such-printer` before tests. +Use `CARGO_TARGET_DIR=target/integration-approved` for local work. Keep the checked-in lockfile and +repository Cargo configuration; no source substitutions or dependency pin changes to bypass failures. + +1. `cargo fmt --all -- --check`; `cargo metadata --locked --format-version 1`. +2. `cargo xtask ci` (the checked-in gate: formatting, strict clippy, layers, scorecard, tests, + command panic hunt, doctests, wasm and i18n reporting). Capture each constituent stage. +3. Set `PHOTOCRAFT_FULL_SWEEP=1`; run `cargo test --workspace --locked`. Daily quarter sweeps + are insufficient for the final gate. Repeat affected crates after each substantive resolution. +4. `cargo xtask test-corpus`: fetch pinned SHA256-verified corpora and execute opt-in corpus tests. + Plain workspace tests omit these. Record pin revisions and corpus floors, never lower them. +5. `cargo test -p photocraft-engine --test panic_hunt -- --ignored` for command changes; + `cargo xtask layers`; `cargo xtask wasm`; command additions require `cargo xtask parity`. +6. Run CPU and GPU parity regressions with an actual adapter. Record backend/adapter and tests that + return early without one. Include 8/16/32f, RGB/Gray/CMYK where supported, masks, clipping, + Fill versus Opacity, extreme finite HDR and malformed-input refusal. +7. Run performance examples in release on public synthetic 24–36 MP images. Record baseline and + integrated times, peak memory, dimensions, threads and output equivalence. No timing claims + from debug builds or while other builds contend for the machine. +8. Dispatch existing `ci.yml` manually on the fork branch. A branch push does not trigger this + workflow. Manual dispatch selects Windows and web. Capture Linux, Windows unit/integration, + corpus, wasm/web size, HEIF/non-HEIF and font-enabled job outcomes separately. macOS native + interaction requires separate execution; a Windows/Linux pass does not cover it. + +## Manual matrix — all NOT RUN + +For each case save inputs, steps, screenshots/output files, expected versus actual, application versions, +exact PhotoCraft SHA, tester and date. Use public-domain or synthetic images and licensed fonts. + +| Case | Steps | Expected result | Status | +|---|---|---|---| +| M01 File exchange | Open Photoshop-authored layered PSD/PSB; edit type, masks, Blend If and smart filters; save native and PSD; reopen each in PhotoCraft and PSD in Photoshop. | Structure, editable properties and appearance survive; Photoshop accepts the exported file. PhotoCraft round-trip alone does not satisfy this oracle. | NOT RUN | +| M02 Effective profile | Untagged RGB with sRGB, Display P3 and Adobe RGB working spaces; export sRGB at 8/16/32f, with embedding on/off; repeat tagged-source precedence, Gray and CMYK; inspect preview and actual ICC/pixels. | Real conversion uses captured source profile, tagged sources win, preview invalidates on working-space change; embedding off writes none; sources unchanged. | NOT RUN | +| M03 Combined adjustment regressions | Constant bounded lookup over huge positive/negative 32f backdrop at full coverage; then each special-eight mode at reduced Fill, Opacity and mask, unclipped and clipped; compare CPU/GPU and Photoshop reference. | #9509 exact full-coverage result remains; #9512 Fill changes blend while Opacity/mask control coverage, and clipping follows the intended rule. Preserve both regression suites. | NOT RUN | +| M04 Blend If | Split/rejoin handles with Alt, hard boundaries at 8/16-bit and Gray; adjust opacity on This Layer; Pass Through group with Blend If. | Correct Photoshop boundary and feathering behavior; group isolation; CPU/GPU agree within established tolerance. | NOT RUN | +| M05 Typography | Vertical upright/rotated Roman type, closed-path seam caret clicks and wrapping, hanging punctuation; copy type between 72/300 ppi then edit; save PSD and reopen in Photoshop. | Layout/caret stable, pixel size survives edits, metadata and editable text retained. Font-dependent skips are explicit. | NOT RUN | +| M06 Painting | 1 px Pencil turns; Smudge pickup; Mixer Brush Alt sampling; brush blur size and section selections; selections/masks and Undo/Redo at all depths. | Continuous intended strokes, correct sampling and bounded buffers; one expected history step, no source corruption. | NOT RUN | +| M07 Selection and geometry | Fixed-size Marquee; Polygonal Lasso edge scrolling; guide drag/rotate/delete; crop menu; saved-path Pen edits and gestures; Select and Mask; transform interpolation. | Correct target/document ownership, dimensions and modifier behavior; cancellation and Undo/Redo preserve state. | NOT RUN | +| M08 UI and modal safety | Short-window Layer Style, defaults and dependent layout changes; Color panel persistence; shortcut capture; detached document; home screen disabled controls; modal automation requests. | Controls reachable at supported scales/themes, state persists correctly, no edits behind modal dialogs, no focus/gesture leakage. | NOT RUN | +| M09 Actions and automation | Import/export JSON actions including nested references, record/replay layer visibility and fractional params; undo definition edits; invalid paths, occupied control port and plugin memory budget. | Replay targets intended named layers; malformed input refuses atomically, workspace authorization holds, failures are clear and bounded. | NOT RUN | +| M10 Platform/package | Launch native app and CLI from portable Windows zip, Linux AppImage and macOS droplet bundle; test spaced paths, exit status and stdio; check startup failures and macOS creation time. | Correct bundles/CLI routing and diagnostics, stable metadata; no print side effects. | NOT RUN | +| M11 Independent rerender | Change a smart-filter or type property after import to invalidate cached pixels; render through the engine; compare against authored Photoshop oracle. | Actual engine rerender meets the asserted oracle. Cached PSD composite tests alone are insufficient. | NOT RUN | + +## Integration risk and order + +Preserve Cutout dependency order #8191 → #8192 → #8193 → #7903 and Layer Style #4938 → #5010. +#9339 and #9342 are complementary: session-aware Export As conversion versus IO/Save for Web +profile embedding. Their shared export tests must retain both expectations. #9509/#9512 modify +`blend_back`: retain Fill-aware `blend_rgb_fill` and numerically stable `b*(1-k)+s*k` together. +Older branches predate engine/UI module splits; migrate each changed behavior and regression into +the current modules rather than resurrecting obsolete monolithic files. Substantive choices require +parent review. Verify no feature silently disappears in conflict resolution. + +## Per-PR regression inventory + +See the [executable case appendix](per-pr-regressions.md) for fixture/setup, action, expected outcome and blank result fields for every selected PR. Full reviewed-head receipts and checks are in [selection evidence](approved-selection.json). + +### Actions and automation + +- [#1991](https://github.com/storytold/photocraft/pull/1991) feat(actions): import and export reusable Actions JSON files — NOT RUN +- [#3455](https://github.com/storytold/photocraft/pull/3455) Undo and redo action definition edits from the Actions panel — NOT RUN +- [#3461](https://github.com/storytold/photocraft/pull/3461) Replay recorded layer visibility on the intended named layer — NOT RUN +- [#3748](https://github.com/storytold/photocraft/pull/3748) control: suggest near matches for unknown command ids and methods (#3674) — NOT RUN +- [#4993](https://github.com/storytold/photocraft/pull/4993) Prevent control-channel engine commands from editing behind modal dialogs — NOT RUN +- [#5090](https://github.com/storytold/photocraft/pull/5090) Actions: add editable PhotoCraft Essentials starter presets — NOT RUN +- [#5176](https://github.com/storytold/photocraft/pull/5176) Play CopyCat, AJ and Line and Color action sets; keep patterns across restarts; Shift Edge scale — NOT RUN +- [#6492](https://github.com/storytold/photocraft/pull/6492) Fail control startup promptly when its port is occupied — NOT RUN +- [#6510](https://github.com/storytold/photocraft/pull/6510) Automation: resolve configured root aliases for absolute paths (#6426) — NOT RUN +- [#7742](https://github.com/storytold/photocraft/pull/7742) Actions: a fractional setting an integer field cannot hold is refused, not rounded — NOT RUN +- [#8905](https://github.com/storytold/photocraft/pull/8905) fix(plugins): bound a run's total plug-in memory, not just each instance — NOT RUN + +### Compositing and filters + +- [#3874](https://github.com/storytold/photocraft/pull/3874) fix(layer-style): support Blend If Alt-split handle feathering and throttle live preview — NOT RUN +- [#3967](https://github.com/storytold/photocraft/pull/3967) Add move and delete actions to Smart Filter rows — NOT RUN +- [#4305](https://github.com/storytold/photocraft/pull/4305) Filter > Other > Frequency Separation (#1714) — NOT RUN +- [#4711](https://github.com/storytold/photocraft/pull/4711) Treat Dissolve as a per-pixel choice — NOT RUN +- [#4992](https://github.com/storytold/photocraft/pull/4992) Preserve Dissolve coverage when compositing clipped layers — NOT RUN +- [#7153](https://github.com/storytold/photocraft/pull/7153) Smart Filters: double-clicking a Liquify filter reopens it in the Liquify workspace — NOT RUN +- [#7903](https://github.com/storytold/photocraft/pull/7903) Filter Gallery › Cutout 4/4: trace the image into flat paper shapes — NOT RUN +- [#8039](https://github.com/storytold/photocraft/pull/8039) Compose: Extend Softer outer glows past Size (#7899) — NOT RUN +- [#8191](https://github.com/storytold/photocraft/pull/8191) Filter Gallery › Cutout 1/4: colour and palette stage — NOT RUN +- [#8192](https://github.com/storytold/photocraft/pull/8192) Filter Gallery › Cutout 2/4: regions stage — NOT RUN +- [#8193](https://github.com/storytold/photocraft/pull/8193) Filter Gallery › Cutout 3/4: edges and curves stage — NOT RUN +- [#8903](https://github.com/storytold/photocraft/pull/8903) Box-filter minified patterns in the CPU and GPU samplers (#8831) — NOT RUN +- [#8931](https://github.com/storytold/photocraft/pull/8931) feat(algo): describe the Gaussian blur as data for other devices — NOT RUN +- [#9472](https://github.com/storytold/photocraft/pull/9472) fix(io): import a Displace smart filter that names its map file without embedding it (#9162) — NOT RUN +- [#9509](https://github.com/storytold/photocraft/pull/9509) fix: an edit at full coverage keeps its result over huge 32-bit values — NOT RUN +- [#9512](https://github.com/storytold/photocraft/pull/9512) fix(compose, gpu): adjustment layers apply Fill inside the special eight blend modes — NOT RUN +- [#9584](https://github.com/storytold/photocraft/pull/9584) fix(compose, gpu): Blend If hard points match Photoshop at 16 bits and for Gray — NOT RUN +- [#9589](https://github.com/storytold/photocraft/pull/9589) fix(compose, gpu): an adjustment layer's This Layer range judges its result before Opacity — NOT RUN +- [#9595](https://github.com/storytold/photocraft/pull/9595) fix(compose, gpu): a Pass Through group with Blend If renders isolated — NOT RUN +- [#9651](https://github.com/storytold/photocraft/pull/9651) perf(algo): row-parallel local_sharpen with fast-path protect_detail (#5426) — NOT RUN + +### File fidelity and colour + +- [#3142](https://github.com/storytold/photocraft/pull/3142) Read applied Sony RAW metadata and crop ILCE-6000 images — NOT RUN +- [#3387](https://github.com/storytold/photocraft/pull/3387) feat(codecs): add lossless JPEG XL export for 8/16-bit images — NOT RUN +- [#3519](https://github.com/storytold/photocraft/pull/3519) feat(export): optionally trim transparent margins from layer files — NOT RUN +- [#4035](https://github.com/storytold/photocraft/pull/4035) fix(cmyk): Flatten Image and merges keep the inks of a tagged CMYK document (#3778) — NOT RUN +- [#5870](https://github.com/storytold/photocraft/pull/5870) fix(format): reject duplicate native layer identities — NOT RUN +- [#6387](https://github.com/storytold/photocraft/pull/6387) Video Frames to Layers: every page of a multi-page TIFF (part of #6379) — NOT RUN +- [#8897](https://github.com/storytold/photocraft/pull/8897) fix(io): read linked smart objects for PSD export as regular files only — NOT RUN +- [#9339](https://github.com/storytold/photocraft/pull/9339) fix(export): embed requested sRGB profile for untagged sources (#9325) — NOT RUN +- [#9342](https://github.com/storytold/photocraft/pull/9342) fix(io, engine): Embed Color Profile writes sRGB for an untagged document (#9325) — NOT RUN +- [#9401](https://github.com/storytold/photocraft/pull/9401) fix(format): a save on macOS keeps the file's creation time (#9388) — NOT RUN +- [#9416](https://github.com/storytold/photocraft/pull/9416) Affinity reader: contiguous curve records and a cheaper object tag index — NOT RUN +- [#9418](https://github.com/storytold/photocraft/pull/9418) Color Lookup: honour the .3dl Mesh header's cube edge and output depth (#9078, #9073) — NOT RUN +- [#9457](https://github.com/storytold/photocraft/pull/9457) raw: faster tone stage (Shadows, Highlights, Clarity, Texture, Dehaze), same bytes — NOT RUN +- [#9590](https://github.com/storytold/photocraft/pull/9590) fix(io): PSD layer-effect contours keep at most 16 points — NOT RUN +- [#9596](https://github.com/storytold/photocraft/pull/9596) fix(io): drop a kept Txt2 once no type layers are left — NOT RUN + +### Painting + +- [#4763](https://github.com/storytold/photocraft/pull/4763) refactor(liquify): reuse native brush resizing and anchored HUD feedback — NOT RUN +- [#4985](https://github.com/storytold/photocraft/pull/4985) feat(ui): add Shift+right-click brush mode picker — NOT RUN +- [#5082](https://github.com/storytold/photocraft/pull/5082) Mixer Brush Alt-click loads reservoir while preserving foreground — NOT RUN +- [#5165](https://github.com/storytold/photocraft/pull/5165) Fix: brush section selection — NOT RUN +- [#5939](https://github.com/storytold/photocraft/pull/5939) fix(paint): scale blur sigma with brush size (#5892) — NOT RUN +- [#6139](https://github.com/storytold/photocraft/pull/6139) Fix painting workflows, File Info and layer selection — NOT RUN +- [#6236](https://github.com/storytold/photocraft/pull/6236) Shift+Alt+right-click opens Photoshop's HUD Color Picker (#6098) — NOT RUN +- [#7848](https://github.com/storytold/photocraft/pull/7848) fix(retouch): preserve Smudge pickup with live-pixel stroke commits — NOT RUN +- [#9623](https://github.com/storytold/photocraft/pull/9623) Pencil: keep a 1 px freehand line connected where it turns — NOT RUN + +### Platform and reliability + +- [#3554](https://github.com/storytold/photocraft/pull/3554) fix(packaging): launch bundled CLI directly from AppImage — NOT RUN +- [#4742](https://github.com/storytold/photocraft/pull/4742) fix(macos): bundle photocraft-cli and resolve it from droplet scripts — NOT RUN +- [#6383](https://github.com/storytold/photocraft/pull/6383) Windows releases ship a symbols zip: the release build's PDBs for profilers (#688) — NOT RUN +- [#7743](https://github.com/storytold/photocraft/pull/7743) packaging: the portable zip holds the files, not a folder with the files in it — NOT RUN +- [#9015](https://github.com/storytold/photocraft/pull/9015) fix(xtask): reject leading zeroes in numeric prerelease identifiers — NOT RUN +- [#9019](https://github.com/storytold/photocraft/pull/9019) fix(xtask): reject unknown performance benchmark selections — NOT RUN +- [#9110](https://github.com/storytold/photocraft/pull/9110) test: GPU tests honour WGPU_BACKEND, so they run on Windows with an Intel GPU (#4) — NOT RUN +- [#9436](https://github.com/storytold/photocraft/pull/9436) Startup: a failed launch says why in a dialog instead of closing silently (#7643) — NOT RUN + +### Selection, paths and transforms + +- [#2300](https://github.com/storytold/photocraft/pull/2300) Scroll the viewport while outlining with Polygonal Lasso — NOT RUN +- [#3464](https://github.com/storytold/photocraft/pull/3464) fix(vector): target selected saved paths and own Pen gestures — NOT RUN +- [#5453](https://github.com/storytold/photocraft/pull/5453) Shapes: independent fill and stroke paints (solid, gradient, pattern), part 1 — NOT RUN +- [#5493](https://github.com/storytold/photocraft/pull/5493) Import Photoshop custom shape sets into the Shapes panel — NOT RUN +- [#5515](https://github.com/storytold/photocraft/pull/5515) Selecting subject now automatically applies to selected layer, and us… — NOT RUN +- [#5650](https://github.com/storytold/photocraft/pull/5650) Guides: ⌥ turns a dragged guide; dropping one on either ruler deletes it (#5034) — NOT RUN +- [#6026](https://github.com/storytold/photocraft/pull/6026) Marquee: Fixed Size selects exactly the entered width and height (fixes #6015) — NOT RUN +- [#6621](https://github.com/storytold/photocraft/pull/6621) Crop: right-click on the pending crop opens the crop menu (#6561) — NOT RUN +- [#7648](https://github.com/storytold/photocraft/pull/7648) Pen: Path Operations menu, as in Photoshop (#1397) — NOT RUN +- [#8074](https://github.com/storytold/photocraft/pull/8074) Transform: remember selected interpolation (#8067) — NOT RUN +- [#8896](https://github.com/storytold/photocraft/pull/8896) Select and Mask: Photoshop's full-window workspace (#7069, #8148) — NOT RUN +- [#8986](https://github.com/storytold/photocraft/pull/8986) Path tools: edit the saved path selected in the Paths panel (#8478) — NOT RUN +- [#9493](https://github.com/storytold/photocraft/pull/9493) fix(vector): a mask feather continues the mask past the canvas edge — NOT RUN + +### Type and typography + +- [#3139](https://github.com/storytold/photocraft/pull/3139) Draw right-to-left layer names in visual word order — NOT RUN +- [#4783](https://github.com/storytold/photocraft/pull/4783) Fix/4758 type extreme finite geometry 20261013s1215 — NOT RUN +- [#8347](https://github.com/storytold/photocraft/pull/8347) Type: Roman Hanging Punctuation (trailing marks hang, don't steer the alignment) — NOT RUN +- [#9478](https://github.com/storytold/photocraft/pull/9478) fix(text): vertical type sets roman letters upright, one per em, as Photoshop does (#9470) — NOT RUN +- [#9523](https://github.com/storytold/photocraft/pull/9523) Fix Type on a Path wrapping and caret positioning across closed-path seams — NOT RUN +- [#9594](https://github.com/storytold/photocraft/pull/9594) fix(engine): copied type keeps its size across resolutions after an edit — NOT RUN + +### UI and workflow + +- [#3345](https://github.com/storytold/photocraft/pull/3345) Add grouped gradient presets and selectable style icons — NOT RUN +- [#3520](https://github.com/storytold/photocraft/pull/3520) fix(ui): restore square color chips in Studio Dark theme — NOT RUN +- [#4023](https://github.com/storytold/photocraft/pull/4023) i18n(es): add 548 missing rows, fix five filter and video terms — NOT RUN +- [#4042](https://github.com/storytold/photocraft/pull/4042) feat(canvas): rotate view with Shift + middle-mouse drag — NOT RUN +- [#4547](https://github.com/storytold/photocraft/pull/4547) fix(icons): PhotoCraft icon corner radius matches other Craft apps (#4478) — NOT RUN +- [#4883](https://github.com/storytold/photocraft/pull/4883) feat(ui): show selection and active-layer bounds in the status bar — NOT RUN +- [#4890](https://github.com/storytold/photocraft/pull/4890) Add scrollbar visibility preferences (#3262) — NOT RUN +- [#4938](https://github.com/storytold/photocraft/pull/4938) Layer Style: one dialog size on every page, and it fits short screens — NOT RUN +- [#5010](https://github.com/storytold/photocraft/pull/5010) Layer Style: Photoshop's layout (three columns, OK/Cancel/New Style/Preview on the right, one-line rows) [depends on #4938] — NOT RUN +- [#5270](https://github.com/storytold/photocraft/pull/5270) Layer Style: Gradient Overlay takes any number of colour stops (#5177) — NOT RUN +- [#5744](https://github.com/storytold/photocraft/pull/5744) fix(ui): keep detached documents in one interactive window — NOT RUN +- [#6449](https://github.com/storytold/photocraft/pull/6449) Hand tool: Cmd held zooms in and Alt zooms out, as in Photoshop — NOT RUN +- [#7255](https://github.com/storytold/photocraft/pull/7255) fix(engine): guard trim and duplicate merged against documents exceeding render limits (#7223) — NOT RUN +- [#8892](https://github.com/storytold/photocraft/pull/8892) ui: larger Align icons and overflow button; Save for Web keeps its width on an invalid Matte — NOT RUN +- [#8985](https://github.com/storytold/photocraft/pull/8985) Color panel and Color Picker: clip the round cursor to the colour field — NOT RUN +- [#9004](https://github.com/storytold/photocraft/pull/9004) fix(ui): enlarge Move tool alignment icons for legibility — NOT RUN +- [#9172](https://github.com/storytold/photocraft/pull/9172) Gradient Fill layer: default to Foreground to Transparent (#8708) — NOT RUN +- [#9282](https://github.com/storytold/photocraft/pull/9282) feat(ui): Preset menus for Levels, Exposure, Black & White and Channel Mixer — NOT RUN +- [#9354](https://github.com/storytold/photocraft/pull/9354) fix(ui): Full Screen Mode needs a document (#9349) — NOT RUN +- [#9481](https://github.com/storytold/photocraft/pull/9481) fix(ui): new layer effects start from the Make Default values — NOT RUN +- [#9504](https://github.com/storytold/photocraft/pull/9504) fix(ui): Keyboard Shortcuts records ⌘Z instead of undoing the capture — NOT RUN +- [#9517](https://github.com/storytold/photocraft/pull/9517) fix(ui): Layer Style scrolls on a short window so OK stays on screen — NOT RUN +- [#9597](https://github.com/storytold/photocraft/pull/9597) fix(ui): the layer list doesn't move with no layer selected — NOT RUN +- [#9598](https://github.com/storytold/photocraft/pull/9598) fix(ui): Liquify's Twirl Counterclockwise gets a mirrored twirl icon — NOT RUN +- [#9606](https://github.com/storytold/photocraft/pull/9606) fix(ui): the Color panel remembers its options across restarts — NOT RUN +- [#9703](https://github.com/storytold/photocraft/pull/9703) Fix adjustment layer name clicks targeting masks — NOT RUN + +## Frozen execution record and acceptance + +- Upstream base: `5f9b4391874aabc9deb2fcb905267613e4d93ec8`. +Validated and packaged source: `f5b3f1238bb414b43851ebe86f3a58ce83bb9b48`. Base: `5f9b4391874aabc9deb2fcb905267613e4d93ec8`. +Version: `0.17.0-integration.20261029.f5b3f123`; Windows x64; pinned fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`. +[Full-sweep CI](https://github.com/FredApps/photocraft/actions/runs/40858867520); [portable build](https://github.com/FredApps/photocraft/actions/runs/40867283787); +[download artifact](https://github.com/FredApps/photocraft/actions/runs/40867283787/artifacts/12895845995). Portable ZIP: `photocraft-0.17.0-integration.20261029.f5b3f123-windows-x64-portable.zip`. +SHA256: `4125eccd5b009f30dc2d72f64bfafcf32220dc5574f765d0b3664ac4d9f992ba`. Artifact ID `12895845995`, job ID `123425396034`. +The source SHA was checked against the run and artifact metadata. The ZIP was inspected for portable +content and x64 PE executables; this is not a claim that GUI/manual cases passed. +Release workflow 390299892 was temporarily enabled for the authorized dispatch and its original +`disabled_manually` state was restored while the accepted run continued. No stable publication or installation. +This test build is **unsigned** because the fork has no Windows signing secrets. The packaging job +executed the CLI version check and printed the expected version and `f5b3f1238` source prefix. + +- PR heads and approval receipts: `approved-selection.json`; current per-head ancestry/status: `integration-status.json`. +- Dependencies: Cutout #8191 → #8192 → #8193 → #7903; Layer Style #4938 → #5010; #7848 prerequisite #7281 is merged upstream. +- Executable per-PR cases and blank result fields: [per-pr-regressions.md](per-pr-regressions.md) and [regression-results.json](regression-results.json). + +Entry: exact frozen build; all selected heads ancestors; no unresolved integration conflicts; fixtures, fonts, corpus pins and adapter available. The branch meets the ancestry and resolved-merge prerequisites. The exact portable artifact is recorded below. Manual entry still requires the specified fixtures/fonts/oracles; manual execution has not begun. +Exit: relevant automated gates PASSED; P0 manual cases PASSED; no crash/data-loss regression; residual exclusions, unsupported cases and skipped stages explicitly listed. Do not lower corpus/parity floors or tolerances. PASSED means executed with supporting output; FAILED means an assertion or expected result failed; BLOCKED means a prerequisite prevented execution; SKIPPED needs a deliberate reason; NOT RUN means no execution was attempted. + +P0 scenarios are M01 file exchange, M02 profile fidelity, M03 combined precision/Fill, M04 Blend If, M09 bounded/authorized automation and M11 real engine rerender. Also prioritize these combined flows on synthetic/public fixtures: + +- Selection → mask → transform → PNG: preserve target ownership, selection geometry, cancellation and one-step Undo/Redo across the selected path/marquee/mask fixes. +- Retouch → adjustment → export: preserve Smudge/Pencil results, mask coverage, HDR/Fill blending and captured output profile; Undo/Redo restores each step. +- Preview Cancel across layer styles, transforms and filters: source document, history and cached previews return to the pre-preview state. +- Actions replay on a second document with different IDs and duplicate layer names: intended named targets change, unrelated layers and source files remain unchanged. +- Native save/reopen and malformed inputs: keep valid work intact on refusal, duplicate layer IDs, extreme type geometry, occupied control port and invalid plugin/automation input. Recovery behavior beyond the selected fixes is an exploratory gap, not a claimed new capability. +- CPU/GPU comparison plus large-document zoom/pan/brush: record actual adapter/backend, fallback reasons, output differences, latency and peak memory; GPU early-return skips do not establish parity. +- Workspace/modal focus with repeated key/pointer input: no background command edits, stale gesture ownership or unexpected shortcut history routing. + +For Photoshop acceptance, record Photoshop version/platform, reference fixture identity, profiles and depth, rendering/export options, expected tolerance and its exact repository-document source, and actual image/diff evidence. Use the repository's established oracle thresholds for the specific path; do not invent one universal tolerance. A PhotoCraft CPU/GPU comparison is a separate test from a Photoshop oracle. Reopen exported PSD/PSB in Photoshop before claiming Photoshop acceptance. + +## Final automated execution and portable build + +Validated and packaged source: `f5b3f1238bb414b43851ebe86f3a58ce83bb9b48`. Base: `5f9b4391874aabc9deb2fcb905267613e4d93ec8`. +Version: `0.17.0-integration.20261029.f5b3f123`; Windows x64; pinned fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`. +[Full-sweep CI](https://github.com/FredApps/photocraft/actions/runs/40858867520); [portable build](https://github.com/FredApps/photocraft/actions/runs/40867283787); +[download artifact](https://github.com/FredApps/photocraft/actions/runs/40867283787/artifacts/12895845995). Portable ZIP: `photocraft-0.17.0-integration.20261029.f5b3f123-windows-x64-portable.zip`. +SHA256: `4125eccd5b009f30dc2d72f64bfafcf32220dc5574f765d0b3664ac4d9f992ba`. Artifact ID `12895845995`, job ID `123425396034`. +The source SHA was checked against the run and artifact metadata. The ZIP was inspected for portable +content and x64 PE executables; this is not a claim that GUI/manual cases passed. +Release workflow 390299892 was temporarily enabled for the authorized dispatch and its original +`disabled_manually` state was restored while the accepted run continued. No stable publication or installation. +This test build is **unsigned** because the fork has no Windows signing secrets. The packaging job +executed the CLI version check and printed the expected version and `f5b3f1238` source prefix. + +| Gate | State | Evidence / limitation | +|---|---|---| +| Frozen selected-head ancestry | PASSED | 108/108 selected heads are ancestors of `f5b3f1238bb414b43851ebe86f3a58ce83bb9b48`. | +| Full Linux gate | PASSED | 12,904 passed, 97 skipped; fmt, strict Clippy, layers, scorecard, tests, panic hunt, doctests, wasm and i18n passed. | +| Command panic hunt | PASSED | One requested ignored test executed and passed; one other test skipped. | +| Windows unit | PASSED | 10,326 passed, 79 skipped; one nextest leaky-process warning. | +| Windows integration | PASSED | 2,501 passed, 19 skipped; two nextest leaky-process warnings. | +| Without HEIF | PASSED | 1,887 passed, 14 skipped. | +| Pinned corpus / actual engine rerender | PASSED | Separate corpus job passed, including 2,428 engine tests and smart-filter rerender cases; cached IO round-trip is separate coverage. | +| Morphology / quick performance / web-wasm | PASSED | All three requested jobs passed at the frozen source. No general large-image performance claim follows. | +| Packaging lint / conflict scan | PASSED | All four packaging-lint jobs passed; zero conflict-marker hits across 2,630 tracked files. Both independent packaging jobs preserved. | +| Portable archive | VERIFIED | Exact-source artifact and ZIP/PE inspection; see build record. GUI acceptance remains NOT RUN. | +| Optional fuzz | SKIPPED | Not requested for this CI dispatch. | +| Manual / Photoshop / platform acceptance | NOT RUN | Use the Windows entry sheet and per-PR appendix; unavailable required capabilities are BLOCKED, not PASSED. | + +### Remaining coverage and historical failures + +All 108 manual case records remain NOT RUN, with blank Actual/Evidence/Tester fields. Photoshop +reopening and reference diffs, macOS droplets, Unix FIFO behavior on Windows, actual Windows Intel/DX12 +hardware, same-run executable/PDB identity, and selected large-image hot paths require their specified +environments and evidence. Two Cairo-dependent local text cases returned early because the required +font was unavailable; their geometry coverage remains BLOCKED. A green runner result alone cannot +establish that a GPU/font-dependent assertion executed. + +Nextest reported leaky-process warnings for the passing Windows tests +`panels::histogram_panel::tests::cache_levels_one_still_throttles_recounts_and_an_uncached_refresh_does_not`, +`workspace_presets::custom_workspaces_restore_timeline_visibility_and_dock_after_presets`, and +`workspace_presets::open_timeline_is_saved_without_saving_playback`. Preserve those warnings for follow-up; +they were not assertion failures and were not hidden by changing thresholds. + +Earlier checkpoints failed localization, overwrite-protection fixture, style-source and ownership/UI +regressions. Their fixes preserved the assertions and protections. A broad local UI attempt at `c3d1e816c` +aborted with Windows `0xc0000005` after 3,788 completed success lines and three assertion failures; +it was not an aggregate pass. The three targeted corrections passed afterward and final process-isolated +hosted suites passed. The monolithic local abort is retained as a historical gap rather than claimed fixed. + +The packaging run's macOS universal job could not start because GitHub reported account payment/spending +restrictions for its runner. No billing, credentials, permissions or environment settings were changed. +FreeBSD aarch64 also failed VM provisioning because its configured package repositories lacked `cmake`; +that job did not compile PhotoCraft. Neither job passes its platform's acceptance requirements. +Record the overall packaging conclusion separately from the successful Windows artifact job. + +### Selection refresh + +107 of the 108 frozen selected heads still matched open, non-draft, current-head FredApps approvals +at the 2026-10-29 12:06 UTC refresh ([receipts](approval-refresh.json)). #5493 advanced without a matching approval: approved +`f97eb2849a68e1ed1c08c5b378770cf35cbcb72d` remains integrated; newer +`67f57c3cf1e7de045aee03a305663d9560daa3e3` is excluded. #5493 does not count toward the 107 current +matching approvals. The minimum of 100 remains satisfied. Immutable approval receipts are preserved. + +See [Windows portable test entry sheet](windows-portable-test-protocol.md) for practical GUI steps. diff --git a/docs/integration-testing/approved-selection.json b/docs/integration-testing/approved-selection.json new file mode 100644 index 0000000000..41268b9e96 --- /dev/null +++ b/docs/integration-testing/approved-selection.json @@ -0,0 +1,17409 @@ +{ + "source": "fresh GitHub GraphQL and REST reads", + "captured_at": "2026-10-29T02:24:09.464811+00:00", + "count": 108, + "prs": [ + { + "number": 9703, + "title": "Fix adjustment layer name clicks targeting masks", + "url": "https://github.com/storytold/photocraft/pull/9703", + "body": "Fixes #9694\n\nClicking an adjustment layer's name now selects its contents instead of its mask, including when that same layer's pixel or vector mask was previously selected. Explicit mask-thumbnail clicks and new-layer creation keep their existing behavior. Fill-layer row targeting and rasterization prompts, and ordinary raster-layer row behavior, are unchanged.\n\nRegression coverage uses actual native UI clicks at 1x and 2x, checks the selected content-thumbnail brackets, and preserves the existing #3369 Properties/creation regression. The new regression fails on the base revision and passes with this fix. An actual Fill-black regression verifies that adjustment content is preserved and only its mask changes. Pixel painting on adjustment layers retains its existing mask fallback.\n\nValidation:\n- 29 mask-thumbnail tests pass; independent code review found no blocker.\n- Strict all-target UI Clippy, formatting, layering, and WebAssembly checks pass.\n- Full UI library run: 4,013 passed, 26 failed, 18 ignored. Integration: 132 passed, 1 failed, 1 ignored. All 27 failures are missing-glyph panics in egui 0.37 with the fonts available in this local build; the full suite is not green. Doctests pass (0 tests).\n- Native macOS offscreen screenshots rendered and visually inspected. Windows/Linux UI has not been manually tested.\n\nBefore (mask thumbnail selected after clicking the name):\n\n![Before](https://raw.githubusercontent.com/vanvo/photocraft/d879000b88edd76743a7774a0517b5bcd2e63ebd/before.png)\n\nAfter (content thumbnail selected after the same click):\n\n![After](https://raw.githubusercontent.com/vanvo/photocraft/d879000b88edd76743a7774a0517b5bcd2e63ebd/after.png)\n\n[Image attribution and licenses](https://raw.githubusercontent.com/vanvo/photocraft/d879000b88edd76743a7774a0517b5bcd2e63ebd/ATTRIBUTION.md)", + "state": "OPEN", + "isDraft": false, + "merged": false, + "headRefOid": "3605d30c38294c4d970e52f4a02f44f97e8bc1a9", + "baseRefName": "main", + "files": { + "nodes": [ + { + "path": "crates/ui-egui/src/mask_thumbs_ui/tests.rs" + }, + { + "path": "crates/ui-egui/src/panels.rs" + } + ], + "pageInfo": { + "hasNextPage": false + } + }, + "commits": { + "nodes": [ + { + "commit": { + "statusCheckRollup": { + "state": "SUCCESS", + "contexts": { + "nodes": [ + { + "name": "select platforms", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682358085" + }, + { + "name": "sonarcloud / Plan coverage shards", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095888/job/121681757819" + }, + { + "name": "sonarcloud / Build instrumented test archive", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095888/job/121681861941" + }, + { + "name": "gate / gate (ubuntu-24.04)", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682358927" + }, + { + "name": "sonarcloud / Tests ${{ matrix.shard }}/${{ inputs.shards }}", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095888/job/121681862838" + }, + { + "name": "test (without heif)", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682358648" + }, + { + "name": "corpus tests", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682359068" + }, + { + "name": "sonarcloud / SonarCloud Scan", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095888/job/121681860253" + }, + { + "name": "fuzz (${{ matrix.target.crate }}/${{ matrix.target.name }})", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682361404" + }, + { + "name": "test (windows-latest, unit)", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682729957" + }, + { + "name": "test (windows-latest, integration)", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682729898" + }, + { + "name": "web build and wasm size gate", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40354095607/job/121682729794" + }, + { + "context": "CodeRabbit", + "state": "SUCCESS", + "targetUrl": null + } + ], + "pageInfo": { + "hasNextPage": false + } + } + } + } + } + ] + }, + "approval": { + "state": "APPROVED", + "submittedAt": "2026-10-26T17:06:00Z", + "url": "https://github.com/storytold/photocraft/pull/9703#pullrequestreview-5655990760", + "body": "Reviewed at SHA 3605d30.\n\nFixes #9694: clicking an adjustment layer's name in the Layers panel now selects its content, not its mask (`ui.maskTarget` false), including when that layer's pixel or vector mask was selected before. In `layer_row` the old `content_less` rule (adjustment and fill rows default to the mask) is split: fills with a mask keep the mask default; adjustments take the `maskTarget false` branch (`on_thumb || adjustment || !row.primary`). Clicking a mask thumbnail still targets that mask, the vector mask thumbnail still targets the vector mask, and creating a layer keeps its existing behaviour.\n\nChecked: the whole `panels.rs` change (the branch order is unchanged, only the conditions); the edited expectation in the existing #3369 test (fill rows still target the mask, adjustments do not, no vector mask target); the new test across two adjustment kinds at 1x and 2x: mask thumbnail clicks, name click after each, bracket on the content thumbnail, another-layer-then-name, `paint_target` still \"mask\", and Fill black editing the mask and not the adjustment content.\nNote: this is a deliberate behaviour change for adjustment rows, whereas fill rows keep the old default; it is covered by the tests and matches the issue, but it is a product choice I did not check against the other app.\nNot verified: I did not run the tests; the author reports 29 mask-thumbnail tests passing and a local failure set of font-glyph panics that predates this change, which I did not reproduce.\n", + "commit": { + "oid": "3605d30c38294c4d970e52f4a02f44f97e8bc1a9" + }, + "author": { + "login": "FredApps" + } + }, + "manual_status": "NOT RUN", + "subsystem": "UI and workflow", + "new_test_names": [ + "adjustment_names_target_contents_instead_of_masks" + ], + "regression_source": "https://github.com/storytold/photocraft/pull/9703" + }, + { + "number": 9651, + "title": "perf(algo): row-parallel local_sharpen with fast-path protect_detail (#5426)", + "url": "https://github.com/storytold/photocraft/pull/9651", + "body": "Refs #5426. Follow-up to #5499.\n\n## Problem\n\n#5499 parallelized `local_blur` and the per-dab mix in `DabTool::Focus`, but `local_sharpen` (`crates/algo/src/retouch.rs`) stayed single-threaded. `protect_detail` also recomputed boundary clamping and strided lookups for the 8-neighbour window inside the per-channel loop, for every pixel in the dab. With large brushes (500–2500 px) interactive strokes lagged badly and stalled the application.\n\n## Change\n\n- `local_sharpen` processes window rows in parallel (`out.par_chunks_mut(stride)`), with a `wasm32` serial fallback like `local_blur`.\n- `protect_detail` computes the 3×3 neighbourhood offsets once, outside the channel loop.\n- Interior pixels (`x > 0 && x + 1 < w && y > 0 && y + 1 < h`) use direct stride offsets and skip boundary clamping, which covers over 99.9% of pixels in large dabs.\n- New `retouch_sharpen_exact` integration test compares against the frozen scalar oracle bit for bit across layouts, edges and channels.\n- New `bench_sharpen_tool` example, matching `bench_blur_tool`.\n\n## Timings\n\nGitHub Actions `rc-bench`, 4 vCPU AMD EPYC 9V45. Output is bit-identical at every size (fingerprint `96d1f22de93b16ec` at 8-bit, `9282e5cfc9e3ec48` at 16-bit).\n\n| Depth | Brush | Before | After | Less time |\n| --- | ---: | ---: | ---: | ---: |\n| 8-bit | 100 px | 40.75 ms | 27.37 ms | 33% |\n| 8-bit | 500 px | 214.14 ms | 153.37 ms | 28% |\n| 8-bit | 1000 px | 738.67 ms | 571.52 ms | 23% |\n| 16-bit | 100 px | 39.94 ms | 27.42 ms | 31% |\n| 16-bit | 500 px | 196.86 ms | 134.26 ms | 32% |\n| 16-bit | 1000 px | 597.21 ms | 447.68 ms | 25% |\n\n## Tests\n\n- `cargo test -p photocraft-algo --test it -- retouch_sharpen_exact` (2 passed)\n- Bit-identical fingerprints between base and this PR at every depth and size.\n- Wasm size gate and clean `cargo clippy`.", + "state": "OPEN", + "isDraft": false, + "merged": false, + "headRefOid": "67666bdf72a58066df868868cef82e5b9cc838de", + "baseRefName": "main", + "files": { + "nodes": [ + { + "path": "crates/algo/src/retouch.rs" + }, + { + "path": "crates/algo/tests/it/main.rs" + }, + { + "path": "crates/algo/tests/it/retouch_sharpen_exact.rs" + }, + { + "path": "crates/engine/examples/bench_sharpen_tool.rs" + } + ], + "pageInfo": { + "hasNextPage": false + } + }, + "commits": { + "nodes": [ + { + "commit": { + "statusCheckRollup": { + "state": "SUCCESS", + "contexts": { + "nodes": [ + { + "name": "select platforms", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393509820" + }, + { + "name": "select platforms", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510766804" + }, + { + "name": "sonarcloud / Plan coverage shards", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685377/job/121510767326" + }, + { + "name": "gate", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393597582" + }, + { + "name": "sonarcloud / Build instrumented test archive", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685377/job/121510848043" + }, + { + "name": "gate / gate (ubuntu-24.04)", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510766978" + }, + { + "name": "test (without heif)", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393508322" + }, + { + "name": "sonarcloud / Tests ${{ matrix.shard }}/${{ inputs.shards }}", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685377/job/121510849890" + }, + { + "name": "test (without heif)", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510766972" + }, + { + "name": "corpus tests", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393560877" + }, + { + "name": "corpus tests", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510766515" + }, + { + "name": "sonarcloud / SonarCloud Scan", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685377/job/121510847640" + }, + { + "name": "fuzz (${{ matrix.target.crate }}/${{ matrix.target.name }})", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510769284" + }, + { + "name": "fuzz (${{ matrix.target.crate }}/${{ matrix.target.name }})", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393509224" + }, + { + "name": "selection-morphology", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393564915" + }, + { + "name": "test (windows-latest, ${{ matrix.part }})", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510958391" + }, + { + "name": "selection-morphology-quick-perf", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393558240" + }, + { + "name": "web build and wasm size gate", + "status": "COMPLETED", + "conclusion": "SUCCESS", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40304685201/job/121510956808" + }, + { + "name": "test (windows-latest, ${{ matrix.part }})", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393511108" + }, + { + "name": "web build and wasm size gate", + "status": "COMPLETED", + "conclusion": "SKIPPED", + "detailsUrl": "https://github.com/storytold/photocraft/actions/runs/40562083384/job/122393511236" + }, + { + "context": "CodeRabbit", + "state": "SUCCESS", + "targetUrl": null + } + ], + "pageInfo": { + "hasNextPage": false + } + } + } + } + } + ] + }, + "approval": { + "state": "APPROVED", + "submittedAt": "2026-10-26T11:38:57Z", + "url": "https://github.com/storytold/photocraft/pull/9651#pullrequestreview-5651366614", + "body": "Reviewed at SHA 67666bd.\n\nWhat it does: `local_sharpen` in `algo/src/retouch.rs` is now row-parallel with rayon (a sequential `chunks_mut` on wasm32). For `protect_detail` it computes the 3x3 neighbour offsets once per pixel, using a branch-free fast path for interior pixels and the old clamped lookup at the edges. An empty window or zero channels returns an empty Vec early (#5426).\n\nChecked: each output row is a disjoint `stride = ow*ch` chunk, so the rows are independent. The interior test (`x>0 && x+10 && y+1