diff --git a/contributors/people.toml b/contributors/people.toml index 37220e0e80a..53bd154aceb 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -17,6 +17,10 @@ # To remove your names, delete your entry (or set fields empty) in a PR. The next # contributors.py run, and the next build, drop them. +[people.jonathanwxh-cell] +display_name = "jonathnwxh" +sync_github_name = false + [people.Skyfuller1303] display_name = "Skyfuller" sync_github_name = true diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index e684f87b968..1480ec2b3ee 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -368,7 +368,8 @@ fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Opt any = true; let o = ((y - t.y0) as usize * w + (x - t.x0) as usize) * n; for c in 0..a { - outp[o + c] = (acc[c] / al).clamp(0.0, 1.0) as f32; + // Integer storage clips on write; float colours retain their signed/HDR range. + outp[o + c] = (acc[c] / al) as f32; } outp[o + a] = al as f32; } @@ -482,6 +483,44 @@ mod tests { } } + #[test] + fn translation_preserves_colour_range_at_every_depth() { + use photocraft_color::{ColorMode, SampleType}; + + let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); + for sample in SampleType::ALL { + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + for alpha in [false, true] { + let mut s = Surface::new(PixelFormat::new(mode, sample, alpha)); + let mut pixel = if mode == ColorMode::Rgb { vec![2.0, -0.25, 0.5] } else { vec![2.0] }; + if alpha { + pixel.push(0.5); + } + s.fill_rect(Rect::new(4, 4, 8, 8), &pixel); + let mut expected = s.pixel(5, 5); + if !alpha { + expected.push(1.0); + } + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); + assert_eq!(out.pixel(12, 2), expected, "{sample:?}/{mode:?}/alpha={alpha}/{interp:?}"); + assert_eq!(out.pixel(0, 0).last(), Some(&0.0)); + } + } + } + } + } + + #[test] + fn bilinear_translation_interpolates_signed_hdr_colours() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.write_pixel(0, 0, &[2.0, -0.5, 0.25, 0.5]); + s.write_pixel(1, 0, &[4.0, -0.25, 0.75, 0.5]); + let h = Homography([1.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let out = warp_surface(&s, s.content_bounds(), &h, Interp::Bilinear).unwrap(); + assert_eq!(out.pixel(1, 0), vec![3.0, -0.375, 0.5, 0.5]); + } + #[test] fn scale_doubles_size_and_rotation_keeps_area() { let mut s = rgba(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 01087f49372..c059d9c8b27 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -24,6 +24,7 @@ pub mod fill_layout; pub mod gradient_fill; pub mod masks; pub mod multichannel; +pub mod native; pub mod pattern; pub mod proxy; pub mod psblend; @@ -232,20 +233,38 @@ pub fn band_rows_for(width: u32, requested: i32) -> i32 { /// The document's composite as a pixel surface in `fmt` (straight RGBA converted to its model /// and depth), optionally flattened over an opaque `background`; rendered and written in bands, /// so no full-size float composite is held. Tiles equal to the default pixel are pruned. +/// A CMYK document of plain Normal layers is composited in its ink values instead +/// ([`native::flatten_cmyk`]), so flattening doesn't round-trip its pixels through RGB (#3778). pub fn flatten_to_surface(doc: &Document, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { + composite_to_surface(doc, doc.bounds(), fmt, background) +} + +/// [`flatten_to_surface`] over `rect` only (the rest of the surface stays empty). +pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { + let paper = background.is_some_and(|bg| bg == [1.0; 3]); + if (background.is_none() || paper) + && let Some(s) = native::flatten_cmyk(doc, rect, fmt, paper) + { + return s; + } let mut s = Surface::new(fmt); let n = fmt.channels(); let mut data = Vec::new(); - let _ = render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> { + // The composite separates back to CMYK through the document's own profile, the one its + // pixels were read through. + let cmyk = cmyk_space(doc); + let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> { let band = match background { Some(bg) => band.over_background(bg), None => band, }; data.clear(); data.resize(band.px.len() * n, 0.0); - for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { - photocraft_raster::from_rgba_into(&fmt, *p, out); - } + photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { + photocraft_raster::from_rgba_into(&fmt, *p, out); + } + }); s.write_region(band.rect, &data); Ok(()) }); diff --git a/crates/compose/src/native.rs b/crates/compose/src/native.rs new file mode 100644 index 00000000000..9eafd18cc6f --- /dev/null +++ b/crates/compose/src/native.rs @@ -0,0 +1,101 @@ +//! Mode-native flattening of plain CMYK layer stacks (#3778). +//! +//! The compositor works in display RGB, so flattening a CMYK document through it reads every ink +//! value through the profile and separates it again: even a lone Background comes back with +//! different ink. When every visible layer is a plain raster layer in Normal mode (no masks, +//! effects, clipping or advanced blending), the composite needs no colour conversion at all: +//! Normal mixes ink values linearly, as Photoshop does in CMYK, so it is worked out on the stored +//! values and an opaque layer keeps them exactly. + +use photocraft_color::blend::BlendMode; +use photocraft_color::{ColorMode, PixelFormat}; +use photocraft_doc::{Document, Layer, LayerContent}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; + +/// Process channels of a CMYK pixel. +const INKS: usize = 4; + +/// A layer the native path can composite: a visible raster layer the compositor would only blend +/// Normally at its opacity. +fn plain(layer: &Layer) -> Option<&Surface> { + let LayerContent::Raster(s) = &layer.content else { return None }; + let simple = layer.blend == BlendMode::Normal + && !layer.clipped + && layer.mask.as_ref().is_none_or(|m| !m.enabled) + && layer.vector_mask.as_ref().is_none_or(|v| !v.enabled) + && !crate::effects::has_effects(layer) + && layer.excluded_channels == 0 + && layer.blend_if.is_default() + && layer.advanced.is_default() + && layer.video.is_none() + && s.format().mode == ColorMode::Cmyk; + simple.then_some(s) +} + +/// The composite of `doc` over `rect` in `fmt`, worked out in ink values, or `None` when the +/// document isn't CMYK or a visible layer needs the full compositor (see the module docs). +/// `paper` flattens onto white paper (no ink) and makes the result opaque. +pub fn flatten_cmyk(doc: &Document, rect: Rect, fmt: PixelFormat, paper: bool) -> Option { + if doc.mode != ColorMode::Cmyk || fmt.mode != ColorMode::Cmyk || doc.layers.iter().any(|l| l.clipped) { + return None; + } + let mut stack = Vec::new(); + for layer in doc.layers.iter().filter(|l| l.visible) { + let alpha = (layer.opacity * layer.fill_opacity).clamp(0.0, 1.0); + stack.push((plain(layer)?, alpha)); + } + let mut out = Surface::new(fmt); + if rect.is_empty() { + return Some(out); + } + let n = fmt.channels(); + let w = rect.width() as usize; + let rows = crate::band_rows_for(rect.width(), 0); + let (mut acc, mut src, mut data) = (Vec::new(), Vec::new(), Vec::new()); + let mut y = rect.y0; + while y < rect.y1 { + let band = Rect::new(rect.x0, y, rect.x1, y.saturating_add(rows).min(rect.y1)); + // Straight C, M, Y, K, alpha per pixel, starting transparent. + acc.clear(); + acc.resize(w * band.height() as usize, [0.0f32; INKS + 1]); + for &(surf, opacity) in &stack { + if opacity <= 0.0 || (surf.content_bounds().intersect(&band).is_empty() && surf.default_pixel().iter().all(|v| *v == 0.0)) { + continue; + } + let sf = surf.format(); + let sn = sf.channels(); + surf.read_region_into(band, &mut src); + for (d, s) in acc.iter_mut().zip(src.chunks_exact(sn)) { + let sa = if sf.alpha { s[INKS] } else { 1.0 } * opacity; + if sa <= 0.0 { + continue; + } + let oa = sa + d[INKS] * (1.0 - sa); + let keep = d[INKS] * (1.0 - sa); + for c in 0..INKS { + // An opaque pixel replaces what is below exactly (no rounding through the mix). + d[c] = if sa >= 1.0 { s[c] } else { (s[c] * sa + d[c] * keep) / oa }; + } + d[INKS] = oa; + } + } + data.clear(); + data.resize(acc.len() * n, 0.0); + for (p, o) in acc.iter().zip(data.chunks_exact_mut(n)) { + // White paper carries no ink, so flattening onto it scales the ink by coverage. + let a = p[INKS]; + let k = if paper && a < 1.0 { a } else { 1.0 }; + for c in 0..INKS { + o[c] = p[c] * k; + } + if fmt.alpha { + o[INKS] = if paper { 1.0 } else { a }; + } + } + out.write_region(band, &data); + y = band.y1; + } + out.prune(); + Some(out) +} diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 614127f2978..03b28143364 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -4,7 +4,9 @@ //! Groups are the panel's top-level folders ([`BrushPreset::group`]); a group can hold nested //! folders ([`BrushPreset::folder`], a path inside the group, e.g. the folders of an imported //! `.abr` file). The group commands take an optional `folder` path to act on a nested folder -//! instead of the whole group. A folder exists while a preset is in it (or below it). +//! instead of the whole group, and `moveGroup` can move a group or folder `into` another folder +//! or group, or out to the top level (dragging a folder onto a folder in Photoshop's panel). A +//! folder exists while a preset is in it (or below it). //! //! The library order is the panel order: groups appear in order of their first preset, and a //! group's folders and presets in order of their first preset too. Every @@ -247,9 +249,116 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) Ok(json!({ "group": g, "folder": f, "index": at })) } +/// Where `into` puts a folder: `Some(None)` = the top level (it becomes a group), `Some(Some((group, +/// folder)))` = inside that folder of that group (`[]`: directly in the group). `None` without `into`. +type Dest = Option<(String, Vec)>; + +fn into_param(s: &Session, p: &Value, cmd: &str) -> Result> { + let into = match p.get("into") { + None | Some(Value::Null) => return Ok(None), + Some(v @ Value::Object(_)) => v, + Some(_) => return Err(bad(cmd, "`into` must be an object {group?, folder?}")), + }; + let Some(g) = group_param(into, "group", cmd)? else { + if folder_param(into, cmd)?.is_some_and(|f| !f.is_empty()) { + return Err(bad(cmd, "`into.folder` needs `into.group`")); + } + return Ok(Some(None)); + }; + group_block(s, &g, cmd)?; + let f = folder_param(into, cmd)?.unwrap_or_default(); + if !s.tools.presets.iter().any(|x| in_folder(x, &g, &f)) { + return Err(bad(cmd, format!("no folder `{}` in brush preset group `{g}`", f.join("/")))); + } + Ok(Some(Some((g, f)))) +} + +/// Move folder `f` of group `g` (the whole group when `f` is empty) into `dest`, keeping its +/// content and the order of its presets: Photoshop's drag of a folder onto another folder. It +/// lands at the end of the destination, or before the sibling folder (group at the top level) +/// named by `before`. +fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, cmd: &str) -> Result { + if p.get("index").is_some_and(|v| !v.is_null()) { + return Err(bad(cmd, "`index` can't be combined with `into` (use `before`)")); + } + let leaf = match f.last() { + Some(l) => l.clone(), + None if g.is_empty() => return Err(bad(cmd, "the ungrouped presets are not a folder that can be moved")), + None => g.clone(), + }; + let moving = |x: &BrushPreset| in_folder(x, &g, &f); + let rest_of = |x: &BrushPreset| x.folder.get(f.len()..).unwrap_or_default().to_vec(); + let before = match p.get("before") { + None | Some(Value::Null) => None, + Some(Value::String(b)) => Some(b.trim().to_string()), + Some(_) => return Err(bad(cmd, "`before` must be a folder name")), + }; + // The destination's own folders and groups, without the one being moved. + let others: Vec = s.tools.presets.iter().filter(|x| !moving(x)).cloned().collect(); + let (new_group, new_prefix, siblings) = match &dest { + None => { + if f.is_empty() { + return Err(bad(cmd, "`into`: the group is already at the top level")); + } + (leaf.clone(), Vec::new(), group_order(&others)) + } + Some((dg, df)) => { + if *dg == g && df.starts_with(&f) { + return Err(bad(cmd, "`into` names the folder being moved or one of its own folders")); + } + let mut prefix = df.clone(); + prefix.push(leaf.clone()); + (dg.clone(), prefix, subfolder_order(&others, dg, df)) + } + }; + if siblings.contains(&leaf) { + return Err(bad(cmd, format!("a folder named `{leaf}` already exists there"))); + } + if let Some(b) = &before + && !siblings.contains(b) + { + return Err(bad(cmd, format!("`before`: no folder named `{b}` there"))); + } + let deepest = s.tools.presets.iter().filter(|x| moving(x)).map(|x| new_prefix.len() + rest_of(x).len()).max().unwrap_or(0); + if deepest > MAX_FOLDER_DEPTH { + return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep"))); + } + let lib = std::mem::take(&mut s.tools.presets); + let (mut block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); + for x in &mut block { + let tail = rest_of(x); + x.group.clone_from(&new_group); + x.folder = new_prefix.iter().cloned().chain(tail).collect(); + x.builtin = false; + } + let pos = match (&dest, &before) { + (None, Some(b)) => rest.iter().position(|x| x.group == *b), + (None, None) => None, + (Some((dg, df)), Some(b)) => { + let sib: Vec = df.iter().cloned().chain(std::iter::once(b.clone())).collect(); + rest.iter().position(|x| in_folder(x, dg, &sib)) + } + (Some((dg, df)), None) => rest.iter().rposition(|x| in_folder(x, dg, df)).map(|k| k + 1), + }; + let tail = rest.split_off(pos.unwrap_or(rest.len()).min(rest.len())); + rest.extend(block); + rest.extend(tail); + s.tools.presets = rest; + s.brush_presets_changed(); + let folder = new_prefix.get(..new_prefix.len().saturating_sub(1)).unwrap_or_default(); + let at = match &dest { + None => group_order(&s.tools.presets).iter().position(|x| *x == new_group), + Some(_) => subfolder_order(&s.tools.presets, &new_group, folder).iter().position(|x| *x == leaf), + }; + Ok(json!({ "group": new_group, "folder": new_prefix, "index": at.unwrap_or(0) })) +} + fn move_group(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.moveGroup"; let (g, f) = target_folder(s, p, cmd)?; + if let Some(dest) = into_param(s, p, cmd)? { + return move_into(s, p, g, f, dest, cmd); + } if !f.is_empty() { return move_folder(s, p, g, f, cmd); } @@ -348,7 +457,7 @@ pub fn specs() -> Vec { spec!( "brush.presets.moveGroup", "Move Brush Group", - r##"{"group":string,"folder":[name]? (move this nested folder among its sibling folders instead),"before":group? (or sibling folder name) | "index":n? (group or sibling folder position)=end} → {group, folder?, index}"##, + r##"{"group":string,"folder":[name]? (move this nested folder instead),"into":{"group":string?,"folder":[name]?}? (move it inside that folder of that group, [] = directly in the group; no group = out to the top level as a group of its own; the folder keeps its content),"before":group? (or sibling folder name, in its new place with `into`) | "index":n? (group or sibling folder position, without `into`)=end} → {group, folder?, index}"##, move_group ), spec!( @@ -572,4 +681,84 @@ mod tests { assert_eq!(s.tools.presets, before); s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "index": u64::MAX})).unwrap(); } + + fn paths(s: &Session) -> Vec { + s.tools.presets.iter().filter(|x| !x.builtin).map(|x| format!("{}:{}:{}", x.group, x.folder.join("/"), x.name)).collect() + } + + /// `with_folders` plus group "Other" holding O1, and folder Box (B1) in it. + fn with_two_groups() -> Session { + let mut s = with_folders(); + for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { + let folder = f.iter().map(|x| x.to_string()).collect(); + s.tools.presets.push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, group: "Other".into(), folder }); + } + s + } + + #[test] + fn folders_move_into_folders_and_groups() { + let mut s = with_two_groups(); + // A nested folder into a sibling folder: its subtree follows, order kept. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}})).unwrap(); + assert_eq!(r, json!({"group": "Set", "folder": ["Ink", "Fine", "Dry"], "index": 0})); + assert_eq!(folder_of(&s, "D1"), ["Ink", "Fine", "Dry"]); + // Into another group, before one of its folders. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Other"}, "before": "Box"})).unwrap(); + assert_eq!(r["folder"], json!(["Ink"])); + assert_eq!(paths(&s), ["Set::S0", "Other::O1", "Other:Ink:I1", "Other:Ink/Fine:F1", "Other:Ink/Fine/Dry:D1", "Other:Ink:I2", "Other:Box:B1"]); + // Out to the top level: the folder becomes a group of its own. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Other", "folder": ["Ink", "Fine"], "into": {}})).unwrap(); + assert_eq!(r["group"], "Fine"); + assert_eq!(folder_of(&s, "D1"), ["Dry"]); + assert_eq!(photocraft_paint::presets::find(&s.tools.presets, "F1").unwrap().group, "Fine"); + // A whole group into another group's folder. + s.execute("brush.presets.moveGroup", json!({"group": "Fine", "into": {"group": "Set"}})).unwrap(); + assert!(names(&s, "Fine").is_empty()); + assert_eq!(folder_of(&s, "D1"), ["Fine", "Dry"]); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Fine"]); + } + + #[test] + fn bad_moves_into_folders_fail_without_changes() { + let mut s = with_two_groups(); + // A chain 31 deep under Set/Deep. + let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); + s.tools.presets.push(BrushPreset { name: "Z".into(), brush: Default::default(), builtin: false, group: "Set".into(), folder: deep.clone() }); + s.tools.presets.push(BrushPreset { name: "Y".into(), brush: Default::default(), builtin: false, group: "Other".into(), folder: vec!["Dry".into()] }); + let before = s.tools.presets.clone(); + let deep_json = json!(deep); + for p in [ + // Into itself or its own descendant. + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink"]}}), + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), + json!({"group": "Set", "into": {"group": "Set", "folder": ["Dry"]}}), + json!({"group": "Set", "into": {"group": "Set"}}), + // A group already at the top level; the ungrouped presets. + json!({"group": "Set", "into": {}}), + // A name clash at the destination. + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}}), + json!({"group": "Other", "folder": ["Box"], "into": {"group": "Set", "folder": ["Ink"]}, "before": "Nope"}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink"]}, "index": 0}), + // Missing destinations and bad shapes. + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Nope"}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other", "folder": ["Nope"]}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"folder": ["Box"]}}), + json!({"group": "Set", "folder": ["Dry"], "into": "Other"}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": 5}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}, "before": 3}), + // Deeper than MAX_FOLDER_DEPTH once moved (Ink/Fine is 2 deep: 2 + 31 > 32). + json!({"group": "Set", "folder": ["Deep"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": deep_json}}), + ] { + assert!(s.execute("brush.presets.moveGroup", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.tools.presets, before); + // Ink/Fine into Set itself: a clash with nothing, so it moves up a level. + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); + assert_eq!(folder_of(&s, "F1"), ["Fine"]); + // An ungrouped preset's group can't move. + s.tools.presets.push(BrushPreset { name: "U".into(), brush: Default::default(), builtin: false, group: String::new(), folder: Vec::new() }); + assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err()); + } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 48caf85b28e..a47bde9fff4 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -774,7 +774,7 @@ fn build() -> Vec { below.push(idx - 1); let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone(); let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); - let merged = pixels::merge_down(doc.bounds(), &lower, &upper, doc.pixel_format()); + let merged = pixels::merge_down(doc, &lower, &upper); doc.remove(id); *doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged; *active = Some(lower.id); diff --git a/crates/engine/src/flatten_cmyk_tests.rs b/crates/engine/src/flatten_cmyk_tests.rs new file mode 100644 index 00000000000..4fd187ceeda --- /dev/null +++ b/crates/engine/src/flatten_cmyk_tests.rs @@ -0,0 +1,169 @@ +//! #3778: Flatten Image, Merge Visible and Merge Down keep a CMYK document's ink values instead +//! of round-tripping them through RGB. + +use photocraft_cms::synth::{CmykParams, cmyk_profile}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, Size}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::json; + +use crate::Session; + +const W: i32 = 16; +const H: i32 = 8; + +fn canvas() -> Rect { + Rect::new(0, 0, W, H) +} + +/// Ink values that vary per pixel and per channel, away from the 8-bit grid. +fn ink(x: i32, y: i32) -> [f32; 4] { + let f = |k: i32| ((x * 7 + y * 13 + k * 29) % 97) as f32 / 96.0 * 0.9 + 0.0371; + [f(0), f(1), f(2), f(3)] +} + +/// A 16-bit CMYK document tagged with a synthetic profile (not the built-in coated CMYK), holding +/// just an opaque Background of varied ink. +fn cmyk_doc() -> Document { + let mut d = Document::new("cmyk", Size::new(W as u32, H as u32), ColorMode::Cmyk, SampleType::U16); + let profile = + cmyk_profile(&CmykParams { description: "Flatten Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }); + d.icc_profile = Some(profile.to_bytes()); + let mut bg = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::U16, false)); + for y in 0..H { + for x in 0..W { + bg.write_pixel(x, y, &ink(x, y)); + } + } + let mut layer = Layer::new("Background", LayerContent::Raster(bg)); + layer.locks.transparency = true; + layer.locks.position = true; + d.layers.push(layer); + d +} + +/// A layer above the Background: solid ink on the left half, half-transparent ink on a strip, +/// nothing on the rest. +fn upper_layer() -> Layer { + let mut s = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true)); + s.fill_rect(Rect::new(0, 0, W / 2, H), &[0.8123, 0.1234, 0.4567, 0.0789, 1.0]); + s.fill_rect(Rect::new(W / 2, 0, W / 2 + 2, H), &[0.25, 0.5, 0.75, 0.1, 0.5]); + Layer::new("Layer 1", LayerContent::Raster(s)) +} + +fn session(doc: Document) -> Session { + let mut s = Session::new(); + s.add_document(doc, None); + s +} + +/// The bottom layer's ink values (C, M, Y, K per pixel, without any alpha channel). +fn pixels(s: &Session) -> Vec { + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + let n = surf.channels(); + surf.read_region(canvas()).chunks_exact(n).flat_map(|p| p[..4].to_vec()).collect() +} + +fn bottom_format(s: &Session) -> PixelFormat { + s.active().unwrap().doc.layers[0].surface().unwrap().format() +} + +#[test] +fn flattening_a_lone_cmyk_background_keeps_its_pixels() { + let doc = cmyk_doc(); + let before = doc.layers[0].surface().unwrap().read_region(canvas()); + let mut s = session(doc); + s.execute("layer.flattenImage", json!({})).unwrap(); + let fmt = bottom_format(&s); + assert_eq!((fmt.mode, fmt.sample), (ColorMode::Cmyk, SampleType::U16), "16-bit CMYK stays 16-bit CMYK"); + let moved = pixels(&s).iter().zip(&before).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "a single Background must flatten to the same ink values"); +} + +/// What a Normal 100 % layer over the Background gives, worked out in ink values: the solid part +/// replaces the ink, the half-transparent strip mixes half and half, the rest shows the Background. +fn expected_two_layers() -> Vec { + let mut out = Vec::new(); + for y in 0..H { + for x in 0..W { + let below = ink(x, y); + let px = if x < W / 2 { + [0.8123, 0.1234, 0.4567, 0.0789] + } else if x < W / 2 + 2 { + let top = [0.25, 0.5, 0.75, 0.1]; + [0, 1, 2, 3].map(|c| top[c] * 0.5 + below[c] * 0.5) + } else { + below + }; + out.extend_from_slice(&px); + } + } + out +} + +fn assert_close(got: &[f32], want: &[f32], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: pixel count"); + // One 16-bit code (the stored value is quantised to 1/65535). + let worst = got.iter().zip(want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst <= 1.0 / 65535.0 + 1e-6, "{what}: ink values moved by up to {worst}"); +} + +#[test] +fn flattening_normal_cmyk_layers_composites_in_ink_values() { + let mut doc = cmyk_doc(); + doc.layers.push(upper_layer()); + let mut s = session(doc); + s.execute("layer.flattenImage", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert_eq!(bottom_format(&s).sample, SampleType::U16); + assert_close(&pixels(&s), &expected_two_layers(), "Flatten Image"); +} + +#[test] +fn merge_visible_and_merge_down_keep_cmyk_ink_values() { + for cmd in ["layer.mergeVisible", "layer.mergeDown"] { + let mut doc = cmyk_doc(); + let upper = upper_layer(); + let id = upper.id; + doc.layers.push(upper); + let mut s = session(doc); + s.execute(cmd, json!({"layer": id.0})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1, "{cmd}"); + assert_eq!(bottom_format(&s).sample, SampleType::U16, "{cmd}"); + assert_close(&pixels(&s), &expected_two_layers(), cmd); + } +} + +/// A stack the ink-value path can't take (a Multiply layer) still goes through the compositor, +/// but separates back through the document's profile, the one it read the ink through, so the +/// round trip lands near the original ink instead of on the built-in profile's separation. +#[test] +fn compositor_flatten_separates_through_the_documents_profile() { + let mut doc = cmyk_doc(); + // Light inks, inside the printable gamut, so a separation can give them back. + let bg = doc.layers[0].surface_mut().unwrap(); + for y in 0..H { + for x in 0..W { + bg.write_pixel(x, y, &ink(x, y).map(|v| v * 0.4)); + } + } + let before = doc.layers[0].surface().unwrap().read_region(canvas()); + let mut empty = Layer::new("Layer 1", LayerContent::Raster(Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true)))); + empty.blend = photocraft_color::blend::BlendMode::Multiply; + doc.layers.push(empty); + let mut s = session(doc); + s.execute("layer.flattenImage", json!({})).unwrap(); + // Compare what the inks print as (a CMYK colour has many separations): RGB through the profile. + let d = &s.active().unwrap().doc; + let space = photocraft_compose::cmyk_space(d); + let shown = |v: &[f32]| -> Vec<[f32; 3]> { + photocraft_color::convert::with_cmyk_space(space.as_ref(), || v.as_chunks::<4>().0.iter().map(|p| photocraft_color::convert::cmyk_to_rgb(*p)).collect()) + }; + let (a, b) = (shown(&pixels(&s)), shown(&before)); + let diffs: Vec = a.iter().zip(&b).flat_map(|(p, q)| (0..3).map(move |c| (p[c] - q[c]).abs())).collect(); + let mean = diffs.iter().sum::() / diffs.len() as f32; + // The synthetic profile's small tables don't round-trip exactly; the built-in profile's + // separation lands about 0.08 off on average. + assert!(mean < 0.03, "flattening shifted the printed colour by {mean} on average"); +} diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index 2ba5b5dcfd7..b19a1b270f3 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -21,32 +21,11 @@ pub fn composite_layers(solo: &Document, format: photocraft_color::PixelFormat, .reduce(|a, b| a.union(&b)) .unwrap_or(Rect::EMPTY) .intersect(&canvas); - let mut surface = Surface::new(format); if area.is_empty() { - return surface; + return Surface::new(format); } - - let channels = format.channels(); - let mut data = Vec::new(); - let _ = photocraft_compose::render_bands(solo, area, 0, |mut band| -> Result<(), ()> { - if let Some(color) = background { - for pixel in &mut band.px { - let alpha = pixel[3]; - for channel in 0..3 { - pixel[channel] = pixel[channel] * alpha + color[channel] * (1.0 - alpha); - } - pixel[3] = 1.0; - } - } - data.resize(band.px.len() * channels, 0.0); - for (pixel, encoded) in band.px.iter().zip(data.chunks_exact_mut(channels)) { - photocraft_raster::from_rgba_into(&format, *pixel, encoded); - } - surface.write_region(band.rect, &data); - Ok(()) - }); - surface.prune(); - surface + // Also keeps a plain CMYK stack in its ink values (#3778). + photocraft_compose::composite_to_surface(solo, area, format, background) } /// Apply an adjustment destructively to a surface, weighted by an optional selection. @@ -77,6 +56,9 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf s.put_tiles(done); } +#[cfg(test)] +#[path = "flatten_cmyk_tests.rs"] +mod flatten_cmyk_tests; #[cfg(test)] #[path = "pixels_tests.rs"] mod tests; @@ -296,9 +278,12 @@ pub fn remap_surface(s: &Surface, map: impl Fn(i32, i32) -> (i32, i32)) -> Surfa } /// Merge `upper` onto `lower` producing a raster layer (Layer → Merge Down). -pub fn merge_down(doc_bounds: Rect, lower: &Layer, upper: &Layer, format: photocraft_color::PixelFormat) -> Layer { +pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer { + let format = doc.pixel_format(); let stack = vec![lower.clone(), upper.clone()]; - let mut tmp = Document::new("merge", doc_bounds.size(), format.mode, format.sample); + let mut tmp = Document::new("merge", doc.size, format.mode, format.sample); + // The pair is read (and a CMYK one separated again) through the document's own profile. + tmp.icc_profile = doc.icc_profile.clone(); tmp.layers = stack; let s = composite_layers(&tmp, format, None); let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(s)); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index c99c3cbb716..208cee016fd 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -869,6 +869,15 @@ impl Default for TypePrefs { } } +impl TypePrefs { + /// Preferences ▸ Type ▸ Missing Glyph Protection: with it on (the default, as in Photoshop), + /// glyphs the chosen face lacks fall back through the coverage fonts (#1909). The text engine + /// applies this in `Session::apply_prefs`. + pub fn missing_glyph_protection(&self) -> bool { + self.missing_glyph_protection + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct EnhancedControls { @@ -1049,7 +1058,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "plugIns.showExtensionPanels", "plugIns.allowScriptsToConnect", "plugIns.generatorEnabled", - "type.missingGlyphProtection", "type.textEngine", "type.recentFonts", "enhancedControls.scrubbySliderAcceleration", @@ -1484,8 +1492,8 @@ impl Session { r } - /// Push engine-relevant preferences into live state: every document's history limit and - /// the layer-effect cache budget. + /// Push engine-relevant preferences into live state: every document's history limit, the + /// layer-effect cache budget and the text engine's missing-glyph protection. pub fn apply_prefs(&mut self) { let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_budget_bytes(); @@ -1496,6 +1504,9 @@ impl Session { st.history.trim(&st.doc); } photocraft_compose::set_effect_cache_budget(budget << 20); + if let Ok(mut engine) = photocraft_text::shared().lock() { + engine.fonts.set_missing_glyph_protection(self.prefs().type_.missing_glyph_protection()); + } crate::plugin_cmds::sync_prefs(self); } diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index b7f175867c3..513bc56c15b 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -624,6 +624,40 @@ fn imported_abr_folders_persist_and_old_stores_load_flat() { assert!(photocraft_paint::presets::find(&d.tools.presets, "Blank").unwrap().folder.is_empty()); } +/// Moving a group into another group's folder rewrites the target group's file and removes the +/// moved group's; moving a folder out to the top level makes a group file for it (#2014). +#[test] +fn folders_moved_into_other_folders_persist() { + let dir = TempDir::new("folder-into"); + let (mut s, _) = session(&dir); + let set = abr_with_folders(&[("Kit Loose", &[]), ("Kit Pen", &["Inks"]), ("Kit Nib", &["Inks", "Fine"])]); + let other = abr_with_folders(&[("Pack Chalk", &["Dry"])]); + s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&set), "group": "Kit"})).unwrap(); + s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&other), "group": "Pack"})).unwrap(); + let group_files = |d: &TempDir| -> Vec { d.files().into_iter().filter(|f| f.ends_with(".pcbrushes")).collect() }; + let mut both = vec![group_file_name("Kit"), group_file_name("Pack")]; + both.sort(); + assert_eq!(group_files(&dir), both); + s.execute("brush.presets.moveGroup", json!({"group": "Pack", "into": {"group": "Kit", "folder": ["Inks"]}})).unwrap(); + assert_eq!(group_files(&dir), [group_file_name("Kit")]); + let (t, w) = session(&dir); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(user(&t), user(&s)); + let folder = |s: &Session, n: &str| { + let p = photocraft_paint::presets::find(&s.tools.presets, n).unwrap(); + format!("{}:{}", p.group, p.folder.join("/")) + }; + assert_eq!(folder(&t, "Pack Chalk"), "Kit:Inks/Pack/Dry"); + // Out to the top level: a group (and file) of its own. + s.execute("brush.presets.moveGroup", json!({"group": "Kit", "folder": ["Inks", "Pack"], "into": {}})).unwrap(); + let mut both = vec![group_file_name("Kit"), group_file_name("Pack")]; + both.sort(); + assert_eq!(group_files(&dir), both); + let (t, _) = session(&dir); + assert_eq!(folder(&t, "Pack Chalk"), "Pack:Dry"); + assert_eq!(folder(&t, "Kit Nib"), "Kit:Inks/Fine"); +} + #[test] fn a_group_file_that_failed_to_load_is_not_overwritten() { // e.g. written by a newer PhotoCraft: skipped on load, so a save must not replace it. diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 1d728f14d4d..21fc1a92a44 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -140,6 +140,9 @@ pub struct FontDb { /// PostScript name → (family, weight, italic), filled lazily. ps_cache: HashMap>, fallbacks: Vec, + /// Preferences ▸ Type ▸ Missing Glyph Protection: route glyphs the chosen face lacks through + /// [`Self::fallback_stack`] (#1909). Off, only the default family shapes the text. + missing_glyph_protection: bool, face_cache: HashMap>, face_aliases: HashMap<(String, usize), String>, } @@ -159,6 +162,7 @@ impl FontDb { system_loaded: false, ps_cache: HashMap::new(), fallbacks: Vec::new(), + missing_glyph_protection: true, face_cache: HashMap::new(), face_aliases: HashMap::new(), }; @@ -272,8 +276,20 @@ impl FontDb { } /// Families available after the requested one (bundled default + installed coverage fonts). + /// With missing glyph protection off (Preferences ▸ Type), only the default family shapes. pub(crate) fn fallback_stack(&self) -> impl Iterator { - std::iter::once(DEFAULT_FAMILY).chain(self.fallbacks.iter().map(String::as_str)) + let fallbacks = self.missing_glyph_protection.then_some(self.fallbacks.iter().map(String::as_str)); + std::iter::once(DEFAULT_FAMILY).chain(fallbacks.into_iter().flatten()) + } + + /// Preferences ▸ Type ▸ Missing Glyph Protection, applied by the engine's `apply_prefs`. + pub fn set_missing_glyph_protection(&mut self, on: bool) { + self.missing_glyph_protection = on; + } + + /// Is missing glyph protection on? + pub fn missing_glyph_protection(&self) -> bool { + self.missing_glyph_protection } /// All family names, sorted. diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index b1a1949cac6..dc8df9e5e3e 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1580,6 +1580,25 @@ fn a_served_script_fallback_joins_the_fallback_stack_once_it_arrives() { assert!(db.fallback_stack().any(|f| f == "Cairo"), "{:?}", db.fallback_stack().collect::>()); } +/// Preferences ▸ Type ▸ Missing Glyph Protection: off, only the default family is in the +/// fallback stack, so a face without the glyph shows the missing-glyph box instead of a +/// fallback's glyph (#1909). +#[test] +fn missing_glyph_protection_can_turn_the_fallback_stack_off() { + let Some(cairo) = crate::CRAFT_FONTS.iter().find(|f| f.family == "Cairo") else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let mut db = fonts::FontDb::new(); + db.register_font_data(cairo.bytes.to_vec()); + assert!(db.missing_glyph_protection(), "on by default, as in Photoshop"); + assert!(db.fallback_stack().any(|f| f == "Cairo")); + db.set_missing_glyph_protection(false); + assert_eq!(db.fallback_stack().collect::>(), [fonts::DEFAULT_FAMILY], "only the default family remains"); + db.set_missing_glyph_protection(true); + assert!(db.fallback_stack().any(|f| f == "Cairo"), "turning it back on restores the coverage fonts"); +} + #[test] fn translate_tysh_moves_only_the_translation() { let mut t = point("Hello!", 26.0); diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rs index c61b48c1be8..7d5a51e4fbb 100644 --- a/crates/ui-egui/src/brush_panel_tests.rs +++ b/crates/ui-egui/src/brush_panel_tests.rs @@ -635,6 +635,90 @@ fn folder_actions_become_folder_commands() { assert_eq!(last_journal(&app).unwrap(), ("brush.presets.moveGroup".to_string(), json!({ "group": "Kit", "folder": ["Dry"], "before": "Inks" }))); } +/// Dragging a folder or group header onto another header (#2014): the upper edge places it +/// before, the rest puts it inside; the action runs `brush.presets.moveGroup` with `into`. +#[test] +fn folder_drops_map_to_move_commands() { + use crate::brushes_tab::{Action, apply, folder_drop}; + let v = |p: &[&str]| p.iter().map(|s| s.to_string()).collect::>(); + // Into: a folder onto another folder, a group onto a group. + assert_eq!( + folder_drop("Kit", &v(&["Dry"]), "Kit", &v(&["Inks"]), false), + Some(Action::MoveInto { group: "Kit".into(), folder: v(&["Dry"]), into: Some(("Kit".into(), v(&["Inks"]))), before: None }) + ); + assert_eq!( + folder_drop("Pack", &[], "Kit", &v(&["Inks"]), false), + Some(Action::MoveInto { group: "Pack".into(), folder: vec![], into: Some(("Kit".into(), v(&["Inks"]))), before: None }) + ); + // Onto itself, into its own folder, or into the folder it is already in: nothing. + assert_eq!(folder_drop("Kit", &v(&["Inks"]), "Kit", &v(&["Inks"]), false), None); + assert_eq!(folder_drop("Kit", &v(&["Inks"]), "Kit", &v(&["Inks", "Fine"]), true), None); + assert_eq!(folder_drop("Kit", &[], "Kit", &v(&["Inks"]), false), None); + assert_eq!(folder_drop("Kit", &v(&["Inks", "Fine"]), "Kit", &v(&["Inks"]), false), None); + // Upper edge: siblings reorder; a nested folder before a group goes to the top level; a + // folder before a folder elsewhere moves next to it. + assert_eq!( + folder_drop("Kit", &v(&["Dry"]), "Kit", &v(&["Inks"]), true), + Some(Action::MoveGroup { group: "Kit".into(), folder: v(&["Dry"]), before: Some("Inks".into()) }) + ); + assert_eq!(folder_drop("Pack", &[], "Kit", &[], true), Some(Action::MoveGroup { group: "Pack".into(), folder: vec![], before: Some("Kit".into()) })); + assert_eq!( + folder_drop("Kit", &v(&["Inks", "Fine"]), "Pack", &[], true), + Some(Action::MoveInto { group: "Kit".into(), folder: v(&["Inks", "Fine"]), into: None, before: Some("Pack".into()) }) + ); + assert_eq!( + folder_drop("Kit", &v(&["Inks", "Fine"]), "Pack", &v(&["Box"]), true), + Some(Action::MoveInto { group: "Kit".into(), folder: v(&["Inks", "Fine"]), into: Some(("Pack".into(), vec![])), before: Some("Box".into()) }) + ); + + let mut app = app(); + for p in [kit("Kit Pen", &["Inks"]), kit("Kit Nib", &["Inks", "Fine"]), kit("Kit Chalk", &["Dry"])] { + app.session.tools.presets.push(p); + } + let into = folder_drop("Kit", &v(&["Dry"]), "Kit", &v(&["Inks", "Fine"]), false).unwrap(); + apply(&mut app, vec![into]); + assert_eq!(paint::presets::find(&app.session.tools.presets, "Kit Chalk").unwrap().folder, ["Inks", "Fine", "Dry"]); + assert_eq!( + last_journal(&app).unwrap(), + ("brush.presets.moveGroup".to_string(), json!({ "group": "Kit", "folder": ["Dry"], "into": {"group": "Kit", "folder": ["Inks", "Fine"]} })) + ); + // Out to the top level, before a group. + let out = folder_drop("Kit", &v(&["Inks", "Fine"]), "Kit", &[], true).unwrap(); + apply(&mut app, vec![out]); + let chalk = paint::presets::find(&app.session.tools.presets, "Kit Chalk").unwrap(); + assert_eq!((chalk.group.as_str(), chalk.folder.clone()), ("Fine", v(&["Dry"]))); + let order = photocraft_engine::brush_preset_cmds::group_order(&app.session.tools.presets); + assert!(order.iter().position(|g| g == "Fine") < order.iter().position(|g| g == "Kit")); +} + +/// A folder header dragged onto another folder's header in the Brushes panel goes inside it. +#[test] +fn dragging_a_folder_header_onto_another_moves_it_inside() { + use egui_kittest::kittest::Queryable; + let mut h = harness(1, 0); + let builtin_groups: Vec = grouped_presets(&h.state().session.tools.presets).into_iter().map(|(g, _)| g).collect(); + h.state_mut().ui.brushes_panel.collapsed = builtin_groups; + for p in [kit("Kit Pen", &["Test Inks"]), kit("Kit Chalk", &["Test Dry"])] { + h.state_mut().session.tools.presets.push(p); + } + h.run_steps(3); + let from = h.get_by_label("Test Dry").rect().center(); + let to = h.get_by_label("Test Inks").rect(); + let to = egui::pos2(to.center().x, to.top() + to.height() * 0.7); + h.hover_at(from); + h.run(); + h.drag_at(from); + h.run(); + for k in 1..=6 { + h.hover_at(from + (to - from) * (k as f32 / 6.0)); + h.run(); + } + h.drop_at(to); + h.run_steps(3); + assert_eq!(paint::presets::find(&h.state().session.tools.presets, "Kit Chalk").unwrap().folder, ["Test Inks", "Test Dry"]); + assert_eq!(last_journal(h.state()).unwrap().0, "brush.presets.moveGroup"); +} + /// A fresh session with the Brush tool: shortcuts, the options bar and the Brush Settings window, /// in the default theme (#258). fn app_harness() -> Harness<'static, PhotocraftApp> { diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rs index b6d96f6bd26..31c1161b94d 100644 --- a/crates/ui-egui/src/brushes_tab.rs +++ b/crates/ui-egui/src/brushes_tab.rs @@ -2,9 +2,10 @@ //! preview, name) or a grid of tips, with a size slider and a search field. //! //! Presets and groups are organised like Photoshop's panel: drag a preset within its group or -//! into another group or folder (onto a preset, or onto a header to append), drag a group's -//! header to reorder groups (a nested folder's header to reorder it among its sibling folders), -//! and right-click for Rename and Delete. Groups hold nested folders ([`BrushPreset::folder`], +//! into another group or folder (onto a preset, or onto a header to append), drag a group's or +//! folder's header onto another header to put it inside that folder (or onto the header's upper +//! edge to place it before, which reorders siblings and moves a folder out to the top level), and +//! right-click for Rename and Delete. Groups hold nested folders ([`BrushPreset::folder`], //! e.g. an imported `.abr` file's own folders), drawn indented under their group and opened or //! closed like groups. Every change is a `brush.presets.*` command, so it is journaled, drivable, //! and persisted by the preset store. @@ -59,6 +60,15 @@ pub enum Action { folder: Vec, before: Option, }, + /// Move a group (`folder` empty) or nested folder into another folder: `into` is (group, + /// folder path, `[]` = directly in the group), or `None` for the top level (it becomes a + /// group). `before` is a folder (or top-level group) there to land before. + MoveInto { + group: String, + folder: Vec, + into: Option<(String, Vec)>, + before: Option, + }, /// View only: show the rename bar for a preset or group ([`preset_list`] applies it). BeginRename(Renaming), /// Commit a rename typed in the rename bar. @@ -238,6 +248,20 @@ pub fn apply(app: &mut PhotocraftApp, acts: Vec) { } run_or_status(app, "brush.presets.moveGroup", p); } + Action::MoveInto { group, folder, into, before } => { + let into = match into { + Some((g, f)) => json!({ "group": g, "folder": f }), + None => json!({}), + }; + let mut p = json!({ "group": group, "into": into }); + if !folder.is_empty() { + p["folder"] = json!(folder); + } + if let Some(b) = before { + p["before"] = json!(b); + } + run_or_status(app, "brush.presets.moveGroup", p); + } Action::Rename(r) => { let text = r.text.trim().to_string(); let old = r.folder.last().unwrap_or(&r.name); @@ -582,9 +606,41 @@ fn preset_card( /// Indent of one nested folder level. const FOLDER_INDENT: f32 = 16.0; -/// A group's or nested folder's header: chevron, folder, name, count. Click toggles; drag -/// reorders groups (a folder among its sibling folders); a preset dropped here moves to the end of -/// the group or folder. `key` is the group key, `folder` the nested folder's path (empty for the +/// What dropping the group or folder (`src_group`, `src_folder`; a group when `src_folder` is +/// empty) on the header of (`group`, `folder`) does, as in Photoshop's Brushes panel: on the +/// header's upper edge (`edge`) it lands before that folder, next to it (reordering when they are +/// siblings); anywhere else it goes into that folder. `None` when the drop does nothing: onto +/// itself, into one of its own folders, or into the folder it is already in. +pub fn folder_drop(src_group: &str, src_folder: &[String], group: &str, folder: &[String], edge: bool) -> Option { + if src_group == group && folder.starts_with(src_folder) { + return None; + } + let src = (src_group.to_string(), src_folder.to_vec()); + if !edge { + let parent = src_folder.split_last().map(|(_, p)| p); + if src_group == group && parent == Some(folder) { + return None; + } + return Some(Action::MoveInto { group: src.0, folder: src.1, into: Some((group.to_string(), folder.to_vec())), before: None }); + } + match folder.split_last() { + // Before a top-level group: groups reorder; a nested folder moves out to the top level. + None if src_folder.is_empty() => Some(Action::MoveGroup { group: src.0, folder: src.1, before: Some(group.to_string()) }), + None => Some(Action::MoveInto { group: src.0, folder: src.1, into: None, before: Some(group.to_string()) }), + Some((leaf, parent)) => { + let sibling = src_group == group && src_folder.split_last().map(|(_, p)| p) == Some(parent); + if sibling { + Some(Action::MoveGroup { group: src.0, folder: src.1, before: Some(leaf.clone()) }) + } else { + Some(Action::MoveInto { group: src.0, folder: src.1, into: Some((group.to_string(), parent.to_vec())), before: Some(leaf.clone()) }) + } + } + } +} + +/// A group's or nested folder's header: chevron, folder, name, count. Click toggles; a group or +/// folder dragged here lands before it (its upper edge) or goes into it ([`folder_drop`]); a +/// preset dropped here moves to the end of the group or folder. `key` is the group key, `folder` the nested folder's path (empty for the /// group), `label` the group's panel label. fn group_header(ui: &mut egui::Ui, label: &str, key: &str, folder: &[String], open: bool, count: usize, acts: &mut Vec) { let t = Tokens::get(ui.ctx()); @@ -616,31 +672,27 @@ fn group_header(ui: &mut egui::Ui, label: &str, key: &str, folder: &[String], op [] => BrushDrag::Group(key.to_string()), f => BrushDrag::Folder { group: key.to_string(), folder: f.to_vec() }, }; - // A folder moves among its siblings: same group, same parent, not itself. - let sibling = |g: &str, f: &[String]| { - g == key && !folder.is_empty() && f.len() == folder.len() && f != folder && f.split_last().map(|x| x.1) == folder.split_last().map(|x| x.1) - }; resp.dnd_set_drag_payload(me); + // The upper third of the header places a dragged folder before this one; the rest drops it in. + let edge = ui.ctx().pointer_interact_pos().is_some_and(|p| p.y < r.top() + r.height() / 3.0); + let folder_action = |d: &BrushDrag| match d { + BrushDrag::Group(g) => folder_drop(g, &[], key, folder, edge), + BrushDrag::Folder { group, folder: f } => folder_drop(group, f, key, folder, edge), + BrushDrag::Preset(_) => None, + }; if let Some(d) = resp.dnd_hover_payload::() { - match &*d { - BrushDrag::Group(g) if folder.is_empty() && g != key => widgets::drop_line(ui, r, false, false, &t), - BrushDrag::Folder { group, folder: f } if sibling(group, f) => widgets::drop_line(ui, r, false, false, &t), - BrushDrag::Preset(_) => { + match (&*d, folder_action(&d)) { + (BrushDrag::Preset(_), _) | (_, Some(Action::MoveInto { before: None, .. })) => { ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); } + (_, Some(_)) => widgets::drop_line(ui, r, false, false, &t), _ => {} } } if let Some(d) = resp.dnd_release_payload::() { match &*d { - BrushDrag::Group(g) if folder.is_empty() && g != key => { - acts.push(Action::MoveGroup { group: g.clone(), folder: Vec::new(), before: Some(key.to_string()) }) - } - BrushDrag::Folder { group, folder: f } if sibling(group, f) => { - acts.push(Action::MoveGroup { group: group.clone(), folder: f.clone(), before: Some(shown.to_string()) }) - } BrushDrag::Preset(n) => acts.push(Action::Move { name: n.clone(), group: key.to_string(), folder: Some(folder.to_vec()), index: None }), - _ => {} + other => acts.extend(folder_action(other)), } } if resp.clicked() { diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rs index b0846382e5f..ea99cff25c3 100644 --- a/crates/vector/src/edit.rs +++ b/crates/vector/src/edit.rs @@ -184,7 +184,9 @@ pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2 let a = *knot_mut(path, knot)?; let b = *knot_mut(path, end)?; let new = if retracted(&a, Handle::Out) && retracted(&b, Handle::In) { - let p = lerp(a.anchor, b.anchor, t); + // Hit testing and hover feedback use the cubic parameter, which is not linear even + // when both handles are retracted. Keep the inserted corner at that same point. + let p = eval(&[a.anchor, a.out_ctrl, b.in_ctrl, b.anchor], t); Knot::corner(p.x, p.y) } else { let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t)); @@ -453,6 +455,28 @@ mod tests { } } + #[test] + fn adding_to_a_straight_segment_uses_the_hit_position() { + for (points, closed) in [ + (vec![(0.0, 0.0), (100.0, 0.0)], false), + (vec![(0.0, 0.0), (0.0, 100.0)], false), + (vec![(0.0, 0.0), (100.0, 100.0)], false), + (vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], true), + ] { + for t in [0.25, 0.75] { + let sp = if closed { Subpath::polygon(&points) } else { Subpath::polyline(&points) }; + let mut p = Path::new(vec![sp]); + let segment = if closed { 2 } else { 0 }; + let clicked = eval(&p.subpaths[0].segments()[segment], t); + let Some(Hit::Segment(knot, hit_t)) = hit(&p, clicked, 1.0, &[]) else { panic!("expected a segment hit at {clicked:?}") }; + let added = add_anchor(&mut p, knot, hit_t).unwrap(); + let inserted = at(&p, added[0], added[1]); + assert!(dist(inserted.anchor, clicked) < 1e-9, "t={t}: inserted {:?}, clicked {clicked:?}", inserted.anchor); + assert_eq!(inserted, Knot::corner(clicked.x, clicked.y), "straight segments retain retracted handles"); + } + } + } + #[test] fn adding_to_a_straight_segment_makes_a_corner_on_the_line() { let mut p = tri(); @@ -460,7 +484,7 @@ mod tests { assert_eq!(add_anchor(&mut p, [0, 2], 0.5).unwrap(), [0, 3]); assert_eq!(at(&p, 0, 3), Knot::corner(25.0, 40.0)); assert_eq!(add_anchor(&mut p, [0, 0], 0.25).unwrap(), [0, 1]); - assert_eq!(at(&p, 0, 1), Knot::corner(25.0, 0.0)); + assert_eq!(at(&p, 0, 1), Knot::corner(15.625, 0.0)); assert_eq!(p.subpaths[0].knots.len(), 5); assert!(p.subpaths[0].closed); } diff --git a/docs/scorecard.md b/docs/scorecard.md index c1cb82e1ca0..4fd5c62ecef 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 6 | 13 | 8 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 30 of 155 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 29 of 155 (target 0) | | [Type](#type) | 4 | 2 | 3 | | | [Automation](#automation) | 4 | 2 | 5 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,9 +176,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 30 of 155** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 29 of 155** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `file_handling.save_in_background`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.missing_glyph_protection`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `file_handling.save_in_background`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. | Id | Target | Status | Issue | Note | |---|---|---|---|---|