From f5f994d0666e1a0098a39bb143ee34155185349c Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:01:31 +0700 Subject: [PATCH 01/87] feat(type): add size, leading and tracking preset menus --- crates/ui-egui/src/type_tool.rs | 82 +++++++++++++++++++++++++-- crates/ui-egui/src/type_tool_tests.rs | 37 ++++++++++++ 2 files changed, 115 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index d80e234dd5..83945b1568 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1529,6 +1529,65 @@ fn num_field(ui: &mut egui::Ui, label: &str, tip: &str, v: f32, range: std::ops: out } +/// Common Photoshop-style choices for the Character panel. The text field stays editable: +/// these menus are shortcuts, not constraints on the value the user may type. +const SIZE_PRESETS: &[f32] = &[6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 18.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0, 96.0]; +const LEADING_PRESETS: &[f32] = &[6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0, 96.0]; +const TRACKING_PRESETS: &[f32] = &[-100.0, -75.0, -50.0, -25.0, -10.0, 0.0, 10.0, 25.0, 50.0, 75.0, 100.0, 200.0]; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum MetricChoice { + Value(f32), + Auto, +} + +/// Label, editable numeric value and a preset chevron sharing one Character-panel cell. +/// Returned values follow the same engine-command path as typing into the numeric field. +fn metric_field( + ui: &mut egui::Ui, + salt: &str, + label: &str, + tip: &str, + value: f32, + range: std::ops::RangeInclusive, + unit: &str, + width: f32, + presets: &[f32], + auto_selected: Option, +) -> Option { + let mut chosen = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + if let Some(v) = num_field(ui, label, tip, value, range, unit, (width - 28.0).max(24.0)) { + chosen = Some(MetricChoice::Value(v)); + } + let (press, close) = crate::press_menu::PressCombo::before(ui, salt); + let combo = egui::ComboBox::from_id_salt(salt) + .selected_text("") + .width(16.0) + .height(420.0) + .icon(crate::widgets::chevron_icon) + .close_behavior(close) + .show_ui(ui, |ui| { + if let Some(selected) = auto_selected { + let item = ui.selectable_label(selected, tl!("Auto")); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Auto); + } + } + for &preset in presets { + let text = if unit.is_empty() { format!("{preset}") } else { format!("{preset} {unit}") }; + let item = ui.selectable_label((preset - value).abs() < f32::EPSILON && auto_selected != Some(true), text); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Value(preset)); + } + } + }); + press.after(&combo.response); + }); + chosen +} + /// Photoshop's paragraph alignment glyphs: four text lines whose widths/offsets show the mode /// (justify variants run full width, with the last line placed left/centre/right). fn align_glyph(p: &egui::Painter, r: egui::Rect, a: photocraft_doc::text::TextAlign, c: Color32) { @@ -1631,13 +1690,26 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa }); row(ui, &mut |ui| { let k = shown_scale(app); - if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k, 0.1..=1296.0, "pt", w) { + if let Some(MetricChoice::Value(v)) = metric_field(ui, "props-font-size-presets", "tT", "Font size", c.size_pt * k, 0.1..=1296.0, "pt", w, SIZE_PRESETS, None) { app.ui.tool_options.type_size = v; apply(app, ui.ctx(), json!({"size": v, "metricsAsShown": true})); } let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; - if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead, 0.1..=5000.0, "pt", w) { - apply(app, ui.ctx(), json!({"leading": v, "metricsAsShown": true})); + match metric_field( + ui, + "props-leading-presets", + "A↕", + "Leading (Auto uses font size × auto-leading)", + lead, + 0.1..=5000.0, + "pt", + w, + LEADING_PRESETS, + Some(c.leading_pt.is_none()), + ) { + Some(MetricChoice::Value(v)) => apply(app, ui.ctx(), json!({"leading": v, "metricsAsShown": true})), + Some(MetricChoice::Auto) => apply(app, ui.ctx(), json!({"leading": "auto"})), + None => {} } }); row(ui, &mut |ui| { @@ -1649,7 +1721,9 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa apply_kerning(app, ui.ctx(), v); } }); - if let Some(v) = num_field(ui, "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w) { + if let Some(MetricChoice::Value(v)) = + metric_field(ui, "props-tracking-presets", "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w, TRACKING_PRESETS, None) + { apply(app, ui.ctx(), json!({"tracking": v})); } }); diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index aa74b0be92..91a05a87f4 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -1309,6 +1309,43 @@ mod multi_layer_formatting { }); } + #[test] + fn character_panel_preset_menus_edit_size_leading_and_tracking() { + let (app, ids) = fixture(); + let untouched = style(&app, ids[2], 0); + let mut h = controls(app, true); + + // The three chevrons are additional combo boxes after family and face. + // They use the same setStyle path as the adjacent editable fields. + h.get_all_by_role(Role::ComboBox).nth(2).expect("size presets").click(); + h.run(); + h.get_by_label("72 pt").click(); + h.run(); + + h.get_all_by_role(Role::ComboBox).nth(3).expect("leading presets").click(); + h.run(); + h.get_by_label("Auto").click(); + h.run(); + + h.get_all_by_role(Role::ComboBox).nth(5).expect("tracking presets").click(); + h.run(); + h.get_by_label("50").click(); + h.run(); + + for id in &ids[..2] { + let c = style(h.state(), *id, 0); + assert_eq!(c.size_pt, 72.0); + assert_eq!(c.leading_pt, None, "Auto restores font-relative line spacing"); + assert_eq!(c.tracking, 50.0); + } + assert_eq!(style(h.state(), ids[2], 0), untouched, "unselected type layers are unchanged"); + + // The numeric spin boxes must remain usable beside their preset chevrons. + number(&mut h, 0, "40"); + assert_eq!(style(h.state(), ids[0], 0).size_pt, 40.0); + assert_eq!(style(h.state(), ids[1], 0).size_pt, 40.0); + } + #[test] fn options_font_family_preserves_peer_faces_and_batches_layer_flags() { let (app, ids) = fixture(); From 9448e4efa7778e0732a330ed9fae99b214b3b131 Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:05:44 +0700 Subject: [PATCH 02/87] refactor(type): group Character metric field options --- crates/ui-egui/src/type_tool.rs | 68 ++++++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 83945b1568..9cb48f8fe8 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1543,18 +1543,20 @@ enum MetricChoice { /// Label, editable numeric value and a preset chevron sharing one Character-panel cell. /// Returned values follow the same engine-command path as typing into the numeric field. -fn metric_field( - ui: &mut egui::Ui, - salt: &str, - label: &str, - tip: &str, +struct MetricField<'a> { + salt: &'a str, + label: &'a str, + tip: &'a str, value: f32, range: std::ops::RangeInclusive, - unit: &str, + unit: &'a str, width: f32, - presets: &[f32], + presets: &'a [f32], auto_selected: Option, -) -> Option { +} + +fn metric_field(ui: &mut egui::Ui, field: MetricField<'_>) -> Option { + let MetricField { salt, label, tip, value, range, unit, width, presets, auto_selected } = field; let mut chosen = None; ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; @@ -1690,22 +1692,37 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa }); row(ui, &mut |ui| { let k = shown_scale(app); - if let Some(MetricChoice::Value(v)) = metric_field(ui, "props-font-size-presets", "tT", "Font size", c.size_pt * k, 0.1..=1296.0, "pt", w, SIZE_PRESETS, None) { + if let Some(MetricChoice::Value(v)) = metric_field( + ui, + MetricField { + salt: "props-font-size-presets", + label: "tT", + tip: "Font size", + value: c.size_pt * k, + range: 0.1..=1296.0, + unit: "pt", + width: w, + presets: SIZE_PRESETS, + auto_selected: None, + }, + ) { app.ui.tool_options.type_size = v; apply(app, ui.ctx(), json!({"size": v, "metricsAsShown": true})); } let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; match metric_field( ui, - "props-leading-presets", - "A↕", - "Leading (Auto uses font size × auto-leading)", - lead, - 0.1..=5000.0, - "pt", - w, - LEADING_PRESETS, - Some(c.leading_pt.is_none()), + MetricField { + salt: "props-leading-presets", + label: "A↕", + tip: "Leading (Auto uses font size × auto-leading)", + value: lead, + range: 0.1..=5000.0, + unit: "pt", + width: w, + presets: LEADING_PRESETS, + auto_selected: Some(c.leading_pt.is_none()), + }, ) { Some(MetricChoice::Value(v)) => apply(app, ui.ctx(), json!({"leading": v, "metricsAsShown": true})), Some(MetricChoice::Auto) => apply(app, ui.ctx(), json!({"leading": "auto"})), @@ -1722,7 +1739,20 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa } }); if let Some(MetricChoice::Value(v)) = - metric_field(ui, "props-tracking-presets", "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w, TRACKING_PRESETS, None) + metric_field( + ui, + MetricField { + salt: "props-tracking-presets", + label: "VA", + tip: "Tracking (1/1000 em)", + value: c.tracking, + range: -1000.0..=10000.0, + unit: "", + width: w, + presets: TRACKING_PRESETS, + auto_selected: None, + }, + ) { apply(app, ui.ctx(), json!({"tracking": v})); } From 80544b344a129859e31e3f03139227b3f77e35d1 Mon Sep 17 00:00:00 2001 From: buivanvu94 Date: Sun, 11 Oct 2026 23:34:28 +0700 Subject: [PATCH 03/87] fix(app): add missing supported file formats to Save As file picker (#3400) --- apps/photocraft/src/services.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 8ac1c69084..7dcf588220 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -55,11 +55,15 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("PhotoCraft", &["pcraft"]), ("OpenRaster", &["ora"]), ("PNG", &["png"]), - ("JPEG", &["jpg"]), + ("JPEG", &["jpg", "jpeg"]), ("WebP", &["webp"]), - ("TIFF", &["tif"]), + ("TIFF", &["tif", "tiff"]), ("Targa", &["tga"]), ("OpenEXR", &["exr"]), + ("GIF", &["gif"]), + ("BMP", &["bmp", "dib"]), + ("Netpbm", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]), + ("Radiance HDR", &["hdr"]), ]; /// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog @@ -637,6 +641,12 @@ mod tests { assert!(save_filters(name)[0].1.iter().any(|e| e == ext), "{name}: {:?}", save_filters(name)[0]); } assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default"); + let untitled = save_filters("Untitled"); + let untitled_filters: Vec<&str> = untitled.iter().map(|(n, _)| n.as_str()).collect(); + assert!(untitled_filters.contains(&"GIF")); + assert!(untitled_filters.contains(&"BMP")); + assert!(untitled_filters.contains(&"Netpbm")); + assert!(untitled_filters.contains(&"Radiance HDR")); } #[test] From d55f3dce0f84ba3a9d05b610af7077c1b69753e5 Mon Sep 17 00:00:00 2001 From: scott <1591011+dottedt@users.noreply.github.com> Date: Mon, 12 Oct 2026 06:41:08 -0500 Subject: [PATCH 04/87] feat(engine): paint.stroke fills the enclosed region with fill:true (#3659) A closed-outline gesture intended as an organic filled dab rendered as a ring: paint.stroke stamps along the outline only. Add fill:true, which fills the polygon the points enclose with the brush colour and opacity, its edge anti-aliased and softened by the brush hardness, in one history step, honouring the selection and alpha locking. Fewer than three points, non-finite points and the Eraser are rejected. Tests: crates/engine/src/brush_cmds/tests.rs fill_fills_the_enclosed_region_not_the_outline. --- crates/engine/src/brush_cmds.rs | 74 +++++++++++++++++++++++++++ crates/engine/src/brush_cmds/tests.rs | 44 ++++++++++++++++ crates/engine/src/commands.rs | 2 +- 3 files changed, 119 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs index dd5c46608c..005d50b115 100644 --- a/crates/engine/src/brush_cmds.rs +++ b/crates/engine/src/brush_cmds.rs @@ -399,9 +399,83 @@ pub fn paint_stroke(s: &mut Session, p: &Value) -> Result { let pts = parse_points(p, "paint.stroke")?; let brush = with_blend_mode(resolve_brush(s, p, "paint.stroke")?, p); let label = if brush.erase && !clear_mode(p) { "Eraser" } else { "Brush Tool" }; + if flag(p, "fill", false) { + return fill_region(s, p, label, brush, pts); + } stroke_with(s, "paint.stroke", p, label, brush, pts, false) } +/// `paint.stroke {fill: true}`: fill the region enclosed by `points` (their polygon) with the +/// brush's colour and opacity, its edge anti-aliased and softened by the brush hardness, instead of +/// stamping the outline. A closed gesture then paints a filled dab, not a ring (#3659). +fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec) -> Result { + if clear_mode(p) { + // `clear` maps onto the eraser; a clear fill would erase the region the outline encloses, + // which a selection + delete does deliberately (#3659). Reject before the eraser check so + // the message names the real conflict. + return Err(bad("paint.stroke", "\"fill\" cannot be combined with \"mode\":\"clear\"; select the enclosed region and delete it instead")); + } + if brush.erase { + return Err(bad("paint.stroke", "\"fill\" does not support the Eraser")); + } + if pts.len() < 3 { + return Err(bad("paint.stroke", "\"fill\" needs at least three points (a closed region)")); + } + let (id, brush, _zoom) = stroke_target(s, p, brush)?; + // A hard brush (hardness 1) keeps the anti-aliased polygon edge; a soft one feathers it by half + // the brush width, the way its tip fades. + let feather_px = ((1.0 - brush.hardness.clamp(0.0, 1.0)) * brush.size * 0.5).max(0.0); + let (color, opacity, mode) = (brush.color, brush.opacity.clamp(0.0, 1.0), brush.mode); + let cmyk = doc_cmyk_space(s); + let dmg = photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + let canvas = doc.bounds(); + let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; + // The polygon's whole-pixel bounds, grown by the feather so a soft edge is not clipped. + let (mut bx0, mut by0, mut bx1, mut by1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for sp in &pts { + if !(sp.x.is_finite() && sp.y.is_finite()) { + return Err(bad("paint.stroke", "non-finite point in a fill")); + } + bx0 = bx0.min(sp.x); + by0 = by0.min(sp.y); + bx1 = bx1.max(sp.x); + by1 = by1.max(sp.y); + } + let ix = |v: f64| v.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32; + let pad = (feather_px.ceil() as i64).clamp(0, i64::from(i32::MAX) / 4) as i32 + 2; + let bounds = Rect::new( + ix(bx0.floor()).saturating_sub(pad), + ix(by0.floor()).saturating_sub(pad), + ix(bx1.ceil()).saturating_add(pad), + ix(by1.ceil()).saturating_add(pad), + ) + .intersect(&canvas); + if bounds.is_empty() { + return Ok(Rect::new(0, 0, 0, 0)); + } + let (w, h) = (bounds.width() as usize, bounds.height() as usize); + let xy: Vec<(f32, f32)> = pts.iter().map(|sp| (sp.x as f32, sp.y as f32)).collect(); + let mut cov = photocraft_algo::selection::polygon(&xy, bounds, true); + if feather_px > 0.01 { + cov = photocraft_algo::selection::feather(&cov, w, h, feather_px); + } + if let Some(sel) = sel.as_ref() { + let mut sv = Vec::new(); + sel.read_region_into(bounds, &mut sv); + for (c, s) in cov.iter_mut().zip(&sv) { + *c *= s.clamp(0.0, 1.0); + } + } + let coverage = photocraft_algo::selection::mask_to_surface(&cov, bounds); + crate::fill_cmds::blend_color_mask(surf, bounds, color, &coverage, mode, opacity, lock)?; + Ok(bounds) + }) + })?; + Ok(damage_json(s, dmg)) +} + /// A `paint.stroke` rendered while it is drawn, onto a copy of the active document, so the canvas /// shows the real dabs before the stroke commits. Committing the same params and points with /// `"seed": live.seed` gives the same pixels. diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rs index 3a04a470fb..d2e6d74016 100644 --- a/crates/engine/src/brush_cmds/tests.rs +++ b/crates/engine/src/brush_cmds/tests.rs @@ -31,6 +31,50 @@ fn stroke_backwards_compatible() { assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } +#[test] +fn fill_fills_the_enclosed_region_not_the_outline() { + // #3659: a closed gesture with `fill` paints the interior, not a ring. + let mut s = session(60, 60); + s.execute( + "paint.stroke", + json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "size": 4, "color": "#ff0000", "brush": {"hardness": 1.0}}), + ) + .unwrap(); + assert!(rgba(&s, 30, 30)[0] > 0.9 && rgba(&s, 30, 30)[3] > 0.9, "interior filled: {:?}", rgba(&s, 30, 30)); + assert_eq!(rgba(&s, 5, 30)[3], 0.0, "outside untouched"); + assert_eq!(rgba(&s, 30, 5)[3], 0.0, "outside untouched"); + // A soft brush feathers the edge outside the polygon; a hard one keeps a crisp edge. + let mut soft = session(60, 60); + soft.execute( + "paint.stroke", + json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "size": 40, "color": "#ff0000", "brush": {"hardness": 0.0}}), + ) + .unwrap(); + assert!(rgba(&soft, 8, 30)[3] > 0.0, "a soft edge paints outside the polygon: {:?}", rgba(&soft, 8, 30)); + // Graceful failures: fewer than three points, and the Eraser. + assert!(s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10]], "fill": true})).is_err()); + assert!(s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10], [50, 50]], "fill": true, "erase": true})).is_err()); + // One history step, like a normal stroke. + let before = s.active().unwrap().history.past_len(); + s.execute("paint.stroke", json!({"points": [[12, 12], [48, 12], [48, 48], [12, 48]], "fill": true, "color": "#0000ff"})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "fill is one history step"); +} + +#[test] +fn fill_is_rejected_with_clear_mode() { + // #3659 review: `"mode":"clear"` maps onto the eraser, so a clear fill would erase the region + // the outline encloses. Reject it; a selection + delete does that deliberately. + let mut s = session(60, 60); + let poly = json!([[10, 10], [50, 10], [50, 50], [10, 50]]); + assert!(s.execute("paint.stroke", json!({"points": poly.clone(), "fill": true, "mode": "clear"})).is_err()); + // `clear` without `fill` still erases along the outline (main's behaviour), unchanged. + s.execute("paint.stroke", json!({"points": poly, "fill": true, "size": 4, "color": "#ff0000"})).unwrap(); + assert!(rgba(&s, 30, 30)[3] > 0.9, "the region is filled first"); + s.execute("paint.stroke", json!({"points": [[30, 2], [30, 58]], "size": 10, "mode": "clear"})).unwrap(); + assert!(rgba(&s, 30, 30)[3] < 0.01, "a clear stroke erased what it crossed"); + assert!(rgba(&s, 12, 30)[3] > 0.9, "pixels the clear stroke missed remain"); +} + #[test] fn stroke_accepts_full_points_brush_and_preset() { let mut s = session(200, 100); diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 48caf85b28..3a0ad3c271 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -931,7 +931,7 @@ fn build() -> Vec { "Brush Stroke", [], None, - r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##, + r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##, has_paintable, crate::brush_cmds::paint_stroke ), From d8360a1e777a174e5ddeab84e76bbd913453e516 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 15:02:47 +0000 Subject: [PATCH 05/87] Layers: New Group button groups the selection, New Group dialog, groups from layers start collapsed (#2561) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Layers panel's New Group button now does what Photoshop CC 2014 and later do: - a click with two or more layers selected puts them in a new group (Group Layers); with one layer or none it adds an empty group; ⇧-click groups the selection, as before; - ⌥-click asks first in Photoshop's New Group dialog (Name, Color, Mode, Opacity), New Group from Layers with several layers selected; - ⌘-click adds an empty group below the active layer (never under the Background). The same dialog opens from Layer › New › Group… and Group from Layers…, from the Layers panel menu's new New Group… / New Group from Layers… items (above Collapse All Groups) and from the row menu's Group from Layers…, now offered for a multi-layer selection too. Group Layers (⌘G) stays immediate; explicit params from Actions, CLI and MCP run the engine directly. layer.new.group, layer.groupLayers and layer.new.groupFromLayers take name, color, mode and opacity (percent; new engine module group_options.rs), so the dialog's OK is one history step; layer.new.group also takes below. Bad values are refused without touching the document. A colour labels the layers inside too, like Layer › Layer Color. Groups made from layers start collapsed (PSD closed folder), as in Photoshop; selecting a layer inside still opens the group. Grouping refuses artboards: inside a group they would stop being boards. Russian: Layer › New › Group… reads «Группа…». New strings in every complete catalog. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyBcWJNZ3eRotC5HNZuwge --- crates/engine/src/commands.rs | 44 +++- crates/engine/src/group_options.rs | 228 ++++++++++++++++++ crates/engine/src/group_view_cmds.rs | 3 + crates/engine/src/layer_multi_cmds.rs | 53 +++- crates/engine/src/layer_nav_cmds.rs | 2 + crates/engine/src/lib.rs | 1 + .../engine/tests/layer_range_panel_order.rs | 2 + crates/ui-egui/src/dialog_blend_ui.rs | 2 +- crates/ui-egui/src/dialogs.rs | 5 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/layer_menu_ui.rs | 31 ++- crates/ui-egui/src/layer_row_ui.rs | 11 + crates/ui-egui/src/layer_row_ui/tests.rs | 19 ++ crates/ui-egui/src/layer_tree_ui/tests.rs | 2 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 9 + crates/ui-egui/src/new_group_button_tests.rs | 120 +++++++-- crates/ui-egui/src/new_group_ui.rs | 127 ++++++++++ crates/ui-egui/src/new_group_ui_tests.rs | 136 +++++++++++ crates/ui-egui/src/panels.rs | 24 +- crates/ui-egui/src/shortcut_dispatch/tests.rs | 2 + docs/context-menu-inventory.md | 2 +- docs/control-protocol.md | 2 +- docs/ui-parity.md | 6 +- 40 files changed, 818 insertions(+), 50 deletions(-) create mode 100644 crates/engine/src/group_options.rs create mode 100644 crates/ui-egui/src/new_group_ui.rs create mode 100644 crates/ui-egui/src/new_group_ui_tests.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 5524388c71..56f57d5f6f 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -553,22 +553,44 @@ fn build() -> Vec { has_doc, crate::new_layer::run ), - cmd!("layer.new.group", "Group…", ["Layer", "New"], None, r##"{"name":str?}"##, has_doc, |s, p| { - let id = s.edit("New Group", |doc, active| { - let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| doc.next_layer_name("Group")); - let id = doc.insert_above(*active, Layer::group(name, vec![])); - *active = Some(id); - Ok(id) - })?; - crate::layer_multi_cmds::note_inert_insert(s, id); - Ok(json!({ "layer": id.0 })) - }), + cmd!( + "layer.new.group", + "Group…", + ["Layer", "New"], + None, + r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"below":bool=false (under the active layer, as ⌘-click on the Layers panel's New Group button)}"##, + has_doc, + |s, p| { + let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; + let below = match p.get("below").filter(|v| !v.is_null()) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad("layer.new.group", "`below` must be a boolean"))?, + }; + let id = s.edit("New Group", |doc, active| { + let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); + let mut group = Layer::group(name, vec![]); + opts.apply(&mut group); + let bg = crate::background_cmds::background_id(doc); + // Below only a layer that is in the document, and never under the Background. + let under = (*active).filter(|a| below && Some(*a) != bg && doc.path_of(*a).is_some()); + let id = doc.insert_above(*active, group); + if under.is_some() { + doc.shift(id, -1); + } + crate::background_cmds::keep_background_at_bottom(bg, doc)?; + *active = Some(id); + Ok(id) + })?; + crate::layer_multi_cmds::note_inert_insert(s, id); + Ok(json!({ "layer": id.0 })) + } + ), cmd!( "layer.groupLayers", "Group Layers", ["Layer"], Some("Cmd+G"), - r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##, + r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##, has_layer, crate::layer_multi_cmds::group_layers ), diff --git a/crates/engine/src/group_options.rs b/crates/engine/src/group_options.rs new file mode 100644 index 0000000000..60b965be37 --- /dev/null +++ b/crates/engine/src/group_options.rs @@ -0,0 +1,228 @@ +//! The options of Photoshop's New Group dialog (Name, Color, Mode, Opacity), shared by +//! Layer › New › Group… (`layer.new.group`) and Group from Layers (`layer.new.groupFromLayers`, +//! `layer.groupLayers`), so the dialog's OK is a single history step. + +use photocraft_color::BlendMode; +use photocraft_doc::{LabelColor, Layer}; +use serde_json::Value; + +use crate::{EngineError, Result}; + +/// New Group options parsed from command params; an absent (or `null`) key keeps the default. +#[derive(Debug, Default)] +pub(crate) struct GroupOptions { + /// `None` (or an empty name) takes the next "Group N". + pub name: Option, + color: Option, + blend: Option, + opacity: Option, +} + +impl GroupOptions { + /// Parses `name`, `color` (a layer colour id), `mode` (a blend mode, Pass Through included) + /// and `opacity` (percent, clamped to 0..100). Validates everything before any edit runs. + pub(crate) fn parse(cmd: &str, p: &Value) -> Result { + let bad = |msg: &str| EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }; + let get = |key: &str| p.get(key).filter(|v| !v.is_null()); + let name = match get("name") { + None => None, + Some(v) => Some(v.as_str().ok_or_else(|| bad("`name` must be a string"))?.to_string()).filter(|n| !n.trim().is_empty()), + }; + let color = match get("color") { + None => None, + Some(v) => Some(v.as_str().and_then(LabelColor::from_id).ok_or_else(|| { + bad("`color` must be a layer colour id (none, red, orange, yellow, green, seafoam, blue, indigo, magenta, fuchsia, violet, gray)") + })?), + }; + let blend = match get("mode") { + None => None, + Some(v) => Some( + v.as_str() + .and_then(crate::commands::blend_from_str) + .ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?, + ), + }; + let opacity = match get("opacity") { + None => None, + Some(v) => { + let o = v.as_f64().filter(|o| o.is_finite()).ok_or_else(|| bad("`opacity` must be a number (percent, 0..100)"))?; + Some((o.clamp(0.0, 100.0) / 100.0) as f32) + } + }; + Ok(Self { name, color, blend, opacity }) + } + + /// Sets the mode, opacity and colour of a new `group`. A colour also reaches every layer inside + /// it, as Layer › Layer Color does on a group; "No Color" leaves the layers' own colours alone. + pub(crate) fn apply(&self, group: &mut Layer) { + if let Some(blend) = self.blend { + group.blend = blend; + } + if let Some(opacity) = self.opacity { + group.opacity = opacity; + } + match self.color { + Some(LabelColor::None) | None => {} + Some(color) => { + // Explicit stack: documents can nest groups deeply. + let mut stack = vec![group]; + while let Some(l) = stack.pop() { + l.label = color; + if let Some(children) = l.children_mut() { + stack.extend(children.iter_mut()); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use photocraft_color::BlendMode; + use photocraft_doc::{Document, LabelColor, Layer, LayerContent, LayerId}; + use serde_json::{Value, json}; + + use crate::Session; + + /// Background, then `A` and `B` (`B` active). + fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let a = id(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()); + let b = id(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()); + (s, a, b) + } + + fn id(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) + } + + fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc + } + + fn layer(s: &Session, id: LayerId) -> &Layer { + doc(s).layer(id).unwrap() + } + + fn expanded(s: &Session, id: LayerId) -> bool { + matches!(&layer(s, id).content, LayerContent::Group(g) if g.expanded) + } + + fn steps(s: &Session) -> usize { + s.active().unwrap().history.entries().len() + } + + fn top(s: &Session) -> Vec { + doc(s).layers.iter().map(|l| l.id).collect() + } + + #[test] + fn new_group_defaults_and_dialog_options() { + let (mut s, _, _) = session(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Group 1", BlendMode::PassThrough, 1.0, LabelColor::None)); + assert!(expanded(&s, g), "an empty new group stays open"); + let before = steps(&s); + let g = id(s.execute("layer.new.group", json!({"name": "Sky", "color": "red", "mode": "multiply", "opacity": 40})).unwrap()); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.label), ("Sky", BlendMode::Multiply, LabelColor::Red)); + assert!((l.opacity - 0.4).abs() < 1e-6); + assert_eq!(steps(&s), before + 1, "the dialog's OK is one history step"); + // Labels as shown in the dialog work too; opacity is clamped to 0..100 %, a blank name is "Group N". + let g = id(s.execute("layer.new.group", json!({"name": " ", "mode": "Linear Dodge (Add)", "opacity": 250})).unwrap()); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.opacity), ("Group 2", BlendMode::LinearDodge, 1.0)); + let g = id(s.execute("layer.new.group", json!({"opacity": -5, "name": null, "color": null, "mode": null, "below": null})).unwrap()); + assert_eq!(layer(&s, g).opacity, 0.0); + } + + #[test] + fn group_from_layers_is_collapsed_and_takes_the_dialog_options() { + let (mut s, a, b) = session(); + s.execute("layer.setLabelColor", json!({"layer": a.0, "color": "red"})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let before = steps(&s); + let g = id(s.execute("layer.new.groupFromLayers", json!({"name": "Pair", "color": "none", "mode": "normal", "opacity": 50})).unwrap()); + assert_eq!(steps(&s), before + 1, "one history step"); + let l = layer(&s, g); + assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Pair", BlendMode::Normal, 0.5, LabelColor::None)); + assert!(!expanded(&s, g), "Photoshop shows a group made from layers closed"); + assert_eq!(layer(&s, a).label, LabelColor::Red, "No Color leaves the layers' own colours alone"); + let inspect = s.execute("document.inspect", json!({})).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == json!(g.0)).unwrap().clone(); + assert_eq!(row["expanded"], false, "document.inspect reports it"); + // Undo removes the group; redo brings it back closed. + s.undo(); + assert!(doc(&s).layer(g).is_none()); + s.redo(); + assert!(!expanded(&s, g)); + // ⌘G with a colour labels the group and every layer in it, like Layer › Layer Color. + s.undo(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let g = id(s.execute("layer.groupLayers", json!({"color": "green"})).unwrap()); + assert!(!expanded(&s, g)); + for l in [g, a, b] { + assert_eq!(layer(&s, l).label, LabelColor::Green); + } + } + + #[test] + fn below_puts_the_new_group_under_the_active_layer() { + let (mut s, a, b) = session(); + let bg = top(&s)[0]; + let g = id(s.execute("layer.new.group", json!({"below": true})).unwrap()); + assert_eq!(top(&s), vec![bg, a, g, b]); + // Inside a group it stays inside, under the active layer. + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let outer = id(s.execute("layer.groupLayers", json!({})).unwrap()); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let inner = id(s.execute("layer.new.group", json!({"below": true})).unwrap()); + let children: Vec = layer(&s, outer).children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![inner, b]); + // Nothing goes under the Background: the group goes above it instead. + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + let g2 = id(s.execute("layer.new.group", json!({"below": true})).unwrap()); + assert_eq!(top(&s)[..2], [bg, g2]); + // With no active layer it goes to the top, like a plain New Group. + s.execute("select.deselectLayers", json!({})).unwrap(); + let g3 = id(s.execute("layer.new.group", json!({"below": true})).unwrap()); + assert_eq!(top(&s).last(), Some(&g3)); + } + + #[test] + fn bad_options_fail_without_touching_the_document() { + let (mut s, a, b) = session(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + for cmd in ["layer.new.group", "layer.new.groupFromLayers", "layer.groupLayers"] { + let mut bad = vec![ + json!({"name": 7}), + json!({"color": 5}), + json!({"color": "pink"}), + json!({"color": "Red"}), + json!({"mode": ""}), + json!({"mode": 3}), + json!({"mode": "sparkle"}), + json!({"opacity": "x"}), + json!({"opacity": [50]}), + ]; + if cmd == "layer.new.group" { + bad.push(json!({"below": "yes"})); + } + for p in bad { + let before = (doc(&s).clone(), s.active().unwrap().revision, steps(&s)); + assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p} must be refused"); + assert_eq!((doc(&s).clone(), s.active().unwrap().revision, steps(&s)), before, "{cmd} {p} changed nothing"); + } + // A huge but finite opacity clamps to 100 % instead of failing. + let g = id(s.execute(cmd, json!({"opacity": f64::MAX})).unwrap()); + assert_eq!(layer(&s, g).opacity, 1.0); + s.undo(); + } + } +} diff --git a/crates/engine/src/group_view_cmds.rs b/crates/engine/src/group_view_cmds.rs index 32a22f5e39..b93074670c 100644 --- a/crates/engine/src/group_view_cmds.rs +++ b/crates/engine/src/group_view_cmds.rs @@ -102,6 +102,9 @@ mod tests { s.execute("layer.new.layer", json!({"name": "deep"})).unwrap(); let inner = s.execute("layer.groupLayers", json!({"name": "inner"})).unwrap()["layer"].as_u64().unwrap(); let outer = s.execute("layer.groupLayers", json!({"layer": inner, "name": "outer"})).unwrap()["layer"].as_u64().unwrap(); + // Like Photoshop, Group Layers makes collapsed groups; these tests start from open ones. + assert!(!expanded(&s, inner) && !expanded(&s, outer)); + s.execute(ID, json!({"all": true, "expanded": true})).unwrap(); (s, inner, outer) } diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index db96c3c1b4..570dd597b6 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -1187,6 +1187,8 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { /// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves /// into a new group placed where the top-most of them was. Bottom-to-top order is preserved. +/// Like Photoshop the new group starts collapsed; the New Group dialog's colour, mode and opacity +/// are set in the same history step. pub fn group_layers(s: &mut Session, p: &Value) -> Result { let ids = match p.get("layer").and_then(Value::as_u64) { Some(id) => vec![LayerId(id)], @@ -1195,17 +1197,27 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(EngineError::Other("no layer selected".into())); } - let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let opts = crate::group_options::GroupOptions::parse("layer.groupLayers", p)?; let gid = s.edit("Group Layers", |doc, active| { let ids = top_level(doc, &ids); + // Artboards stay at the top level: inside a group they would stop being boards. + if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) { + return Err(EngineError::Other("artboards can't go into a group".into())); + } let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; - let name = name.unwrap_or_else(|| doc.next_layer_name("Group")); - let gid = doc.insert_above(Some(top), Layer::group(name, vec![])); + let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); + let mut group = Layer::group(name, vec![]); + if let LayerContent::Group(g) = &mut group.content { + g.expanded = false; + } + let gid = doc.insert_above(Some(top), group); let mut children = Vec::with_capacity(ids.len()); for id in &ids { children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); } - *doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children; + let group = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; + *group.children_mut().ok_or(EngineError::NoLayer(gid))? = children; + opts.apply(group); check_group_depth(doc, "Group Layers")?; *active = Some(gid); Ok(gid) @@ -1405,7 +1417,15 @@ pub fn specs() -> Vec { link_layers(s) }), spec!("layer.mergeLayers", "Merge Layers", &["Layer"], Some("Cmd+E"), "{} (one layer selected: Merge Down)", has_layer, |s, _| merge_layers(s)), - spec!("layer.new.groupFromLayers", "Group from Layers…", &["Layer", "New"], None, r##"{"name":str?}"##, has_layer, group_layers), + spec!( + "layer.new.groupFromLayers", + "Group from Layers…", + &["Layer", "New"], + None, + r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (every selected layer; the new group starts collapsed)"##, + has_layer, + group_layers + ), spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)), spec!( "layer.lockLayers", @@ -2101,6 +2121,29 @@ mod tests { assert_eq!(doc(&s).layers.len(), 4); } + /// Artboards are top-level groups; grouping them (now a plain click on the Layers panel's New + /// Group button with two boards selected) is refused and leaves them as they were. + #[test] + fn grouping_artboards_is_refused() { + let mut s = session(8); + let a = LayerId(s.execute("layer.new.artboard", json!({"rect": [0, 0, 100, 80]})).unwrap()["layer"].as_u64().unwrap()); + let b = LayerId(s.execute("layer.new.artboard", json!({"rect": [120, 0, 100, 80]})).unwrap()["layer"].as_u64().unwrap()); + select_all(&mut s, &[a, b]); + let before = doc(&s).clone(); + let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); + assert!(err.to_string().contains("artboards"), "{err}"); + assert!(s.execute("layer.groupLayers", json!({"layer": a.0})).is_err(), "one board is refused too"); + assert_eq!(doc(&s).layers.iter().map(|l| l.id).collect::>(), before.layers.iter().map(|l| l.id).collect::>()); + assert_eq!(doc(&s).artboards().len(), 2); + // A layer inside a board still groups, inside its board. + let inner = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[inner]); + let c = LayerId(s.execute("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(doc(&s).artboard_of(inner), Some(c)); + let g = LayerId(s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(doc(&s).artboard_of(g), Some(c)); + } + #[test] fn grouping_is_capped_at_the_document_nesting_limit() { let mut s = session(8); diff --git a/crates/engine/src/layer_nav_cmds.rs b/crates/engine/src/layer_nav_cmds.rs index bd1ecb661a..3b52343f71 100644 --- a/crates/engine/src/layer_nav_cmds.rs +++ b/crates/engine/src/layer_nav_cmds.rs @@ -118,6 +118,8 @@ mod tests { s.execute("layer.select", json!({"layer": c.0, "mode": "add"})).unwrap(); s.execute("layer.groupLayers", json!({})).unwrap(); let group = s.active().unwrap().doc.layers.iter().find(|l| l.is_group()).unwrap().id; + // Group Layers makes a collapsed group; open it so the panel shows B and C. + s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})).unwrap(); let d = id(&mut s, "layer.new.layer", json!({"name": "D"})); (s, [bg, a, group, b, c, d]) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c9cb725518..43aeeefbe0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -48,6 +48,7 @@ pub mod fx_view_cmds; pub mod fx_visibility_cmds; pub mod gallery_cmds; pub mod gradient_fill_cmds; +mod group_options; pub mod group_view_cmds; pub mod guide_layout; pub mod hidden_target; diff --git a/crates/engine/tests/layer_range_panel_order.rs b/crates/engine/tests/layer_range_panel_order.rs index 0e6199d539..484d41edad 100644 --- a/crates/engine/tests/layer_range_panel_order.rs +++ b/crates/engine/tests/layer_range_panel_order.rs @@ -20,6 +20,8 @@ fn shift_range_follows_visible_rows_on_both_sides_of_an_expanded_group() { select(&mut s, b, "replace"); select(&mut s, c, "add"); let group = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + // Group Layers makes a collapsed group, as in Photoshop; open it so B and C are visible rows. + s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap(); let d = s.execute("layer.new.layer", json!({"name": "D"})).unwrap()["layer"].as_u64().unwrap(); for (anchor, target, wanted) in diff --git a/crates/ui-egui/src/dialog_blend_ui.rs b/crates/ui-egui/src/dialog_blend_ui.rs index 0eb8207eb5..8915c20a99 100644 --- a/crates/ui-egui/src/dialog_blend_ui.rs +++ b/crates/ui-egui/src/dialog_blend_ui.rs @@ -54,7 +54,7 @@ fn label(ui: &mut egui::Ui, text: &str) { } /// The `mode` param naming a blend mode ("normal", "colorBurn"…), parsed by the engine. -fn mode_key(m: photocraft_color::BlendMode) -> String { +pub(crate) fn mode_key(m: photocraft_color::BlendMode) -> String { let s = format!("{m:?}"); let mut c = s.chars(); c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1573d5ec31..1d1f2a2331 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -229,6 +229,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields), + DialogKind::Command if crate::new_group_ui::owns(&fields) => crate::new_group_ui::body(ui, &mut fields), DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields), DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields), DialogKind::Command if crate::new_layer_ui::owns(&fields) => crate::new_layer_ui::body(ui, &mut fields), @@ -486,6 +487,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), + DialogKind::Command if crate::new_group_ui::owns(&d.fields) => crate::new_group_ui::confirm(app, &d.fields), DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields), DialogKind::Command if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields), @@ -554,6 +556,9 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) if command == crate::stroke_ui::COMMAND { return crate::stroke_ui::open(app); } + if crate::new_group_ui::fronts(command) { + return crate::new_group_ui::open(app, command); + } if command == crate::color_range_ui::COMMAND { return crate::color_range_ui::open(app); } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e7de3409af..f8856854de 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -285,6 +285,8 @@ Layer… Vrstva… Group… Skupina… Group from Layers… Skupina z vrstev… + New Group… Nová skupina… + New Group from Layers… Nová skupina z vrstev… Artboard… Kreslicí plocha… Artboard from Group… Kreslicí plocha ze skupiny… Artboard from Layers… Kreslicí plocha z vrstev… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ac313154db..8dd4aab572 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -281,6 +281,8 @@ Layer… Ebene… Group… Gruppe… Group from Layers… Gruppe aus Ebenen… + New Group… Neue Gruppe… + New Group from Layers… Neue Gruppe aus Ebenen… Artboard… Zeichenbereich… Artboard from Group… Zeichenbereich aus Gruppe… Artboard from Layers… Zeichenbereich aus Ebenen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e5be105597..c9c71543af 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -197,6 +197,8 @@ Tools… Εργαλεία… History Log… Καταγραφή ιστορικού… Group from Layers… Ομαδοποίηση από επίπεδα… + New Group… Νέα ομάδα… + New Group from Layers… Νέα ομάδα από επίπεδα… Artboard from Layers… Πίνακας σχεδίασης από επίπεδα… Delete Filter Mask Διαγραφή μάσκας φίλτρου Disable Filter Mask Απενεργοποίηση μάσκας φίλτρου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b986956544..5f030069f3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -278,6 +278,8 @@ Layer… Capa… Group… Grupo… Group from Layers… Grupo a partir de capas… + New Group… Nuevo grupo… + New Group from Layers… Nuevo grupo a partir de capas… Artboard… Mesa de trabajo… Artboard from Group… Mesa de trabajo a partir de grupo… Artboard from Layers… Mesa de trabajo a partir de capas… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f426b28c56..90e1bab6d3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -276,6 +276,8 @@ Layer… Calque… Group… Groupe… Group from Layers… Groupe d'après des calques… + New Group… Nouveau groupe… + New Group from Layers… Nouveau groupe d'après des calques… Artboard… Plan de travail… Artboard from Group… Plan de travail d'après un groupe… Artboard from Layers… Plan de travail d'après des calques… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 420600cf3f..de27f7e0f6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -269,6 +269,8 @@ Layer… Layer… Group… Grup… Group from Layers… Grup dari Layer… + New Group… Grup Baru… + New Group from Layers… Grup Baru dari Layer… Artboard… Artboard… Artboard from Group… Artboard dari Grup… Artboard from Layers… Artboard dari Layer… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 410ab8f609..be3fe90009 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -278,6 +278,8 @@ Layer… Livello… Group… Gruppo… Group from Layers… Gruppo da livelli… + New Group… Nuovo gruppo… + New Group from Layers… Nuovo gruppo da livelli… Artboard… Tavola da disegno… Artboard from Group… Tavola da gruppo… Artboard from Layers… Tavola da livelli… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 7e5e65a639..fa3b49bced 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -279,6 +279,8 @@ Layer… レイヤー… Group… グループ… Group from Layers… レイヤーからグループ… + New Group… 新規グループ… + New Group from Layers… レイヤーから新規グループ… Artboard… アートボード… Artboard from Group… グループからアートボード… Artboard from Layers… レイヤーからアートボード… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f48633c2cb..8661a65fe5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -263,6 +263,8 @@ Layer… 레이어… Group… 그룹… Group from Layers… 레이어로 그룹 만들기… + New Group… 새 그룹… + New Group from Layers… 레이어에서 새 그룹… Artboard… 아트보드… Artboard from Group… 그룹으로 아트보드 만들기… Artboard from Layers… 레이어로 아트보드 만들기… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3778a8a1de..9e00862d26 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -271,6 +271,8 @@ Layer… Laag… Group… Groep… Group from Layers… Groep uit lagen… + New Group… Nieuwe groep… + New Group from Layers… Nieuwe groep uit lagen… Artboard… Tekengebied… Artboard from Group… Tekengebied uit groep… Artboard from Layers… Tekengebied uit lagen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ce9387b623..26629bf09d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -277,6 +277,8 @@ Layer… Warstwa… Group… Grupa… Group from Layers… Grupa z warstw… + New Group… Nowa grupa… + New Group from Layers… Nowa grupa z warstw… Artboard… Obszar roboczy… Artboard from Group… Obszar roboczy z grupy… Artboard from Layers… Obszar roboczy z warstw… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 92e9c238b1..fc99e53465 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -272,6 +272,8 @@ Layer… Camada… Group… Grupo… Group from Layers… Grupo a partir de camadas… + New Group… Novo grupo… + New Group from Layers… Novo grupo a partir de camadas… Artboard… Prancheta… Artboard from Group… Prancheta a partir de grupo… Artboard from Layers… Prancheta a partir de camadas… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7e1d12bbb1..6fef240f56 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -174,9 +174,11 @@ Background from Layer Фон из слоя Background From Layer Фон из слоя Group Layers Сгруппировать слои - Group… Группировать… + Group… Группа… Ungroup Layers Разгруппировать слои Group from Layers… Группа из слоёв… + New Group… Новая группа… + New Group from Layers… Новая группа из слоёв… Hide Layers Скрыть слои Arrange Упорядочить Bring to Front На передний план diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 11a4caa9cf..9c51205c3b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -166,6 +166,8 @@ Group… Група… Ungroup Layers Розгрупувати шари Group from Layers… Група із шарів… + New Group… Нова група… + New Group from Layers… Нова група із шарів… Hide Layers Приховати шари Arrange Упорядкувати Bring to Front На передній план diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ca091c14d8..a56b047d48 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -262,6 +262,8 @@ Gradient… Chuyển sắc… Grayscale Thang xám Group from Layers… Nhóm từ các lớp… + New Group… Nhóm mới… + New Group from Layers… Nhóm mới từ các lớp… Group Layers Nhóm các lớp Group… Nhóm… HDR Toning… Tông HDR… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d0309166ce..0e34bcdd14 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -280,6 +280,8 @@ Layer… 图层… Group… 组… Group from Layers… 从图层创建组… + New Group… 新建组… + New Group from Layers… 从图层新建组… Artboard… 画板… Artboard from Group… 从组创建画板… Artboard from Layers… 从图层创建画板… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8698dfc078..5799019586 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -285,6 +285,8 @@ Layer… 圖層… Group… 群組… Group from Layers… 從圖層建立群組… + New Group… 新增群組… + New Group from Layers… 從圖層新增群組… Artboard… 工作區域… Artboard from Group… 從群組建立工作區域… Artboard from Layers… 從圖層建立工作區域… diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs index 5be01c750a..a097f1a540 100644 --- a/crates/ui-egui/src/layer_menu_ui.rs +++ b/crates/ui-egui/src/layer_menu_ui.rs @@ -55,9 +55,9 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec { v.push(None); v.push(Some((if multi { tl!("Duplicate Layers…") } else { tl!("Duplicate Layer…") }, "layer.duplicate"))); v.push(Some((if multi { tl!("Delete Layers") } else { tl!("Delete Layer") }, "layer.delete"))); - if !multi { - v.push(Some((tl!("Group from Layers…"), "layer.groupLayers"))); - } + // Groups the clicked layer, or the whole selection when several layers are selected, after + // Photoshop's New Group dialog. + v.push(Some((tl!("Group from Layers…"), "layer.new.groupFromLayers"))); v.push(None); v.push(Some((tl!("Quick Export As PNG"), "layer.quickExportAsPng"))); v.push(Some((tl!("Export As…"), "layer.exportAs"))); @@ -567,6 +567,29 @@ mod tests { assert_eq!(h.state().session.active().unwrap().selected_layers().len(), 2, "the selection survives"); } + /// Group from Layers is offered for a multi-layer selection too (it used to be dropped from + /// the menu then). As in Photoshop it asks in the New Group from Layers dialog first; OK puts + /// every selected layer in one new group, leaving the rest alone. + #[test] + fn group_from_layers_groups_every_selected_layer() { + use egui_kittest::kittest::Queryable; + use photocraft_doc::LayerId; + let (mut h, [text, shape, other]) = open_multi_selection_menu(); + let at = h.get_by_label("Group from Layers…").rect().center(); + click(&mut h, at, egui::PointerButton::Primary); + let dialog = h.state().ui.dialogs.last().map(|d| (d.id, d.fields.clone())).expect("the New Group dialog opened"); + assert!(crate::new_group_ui::owns(&dialog.1)); + assert_eq!(dialog.1["__command"], "layer.new.groupFromLayers"); + crate::dialogs::confirm(h.state_mut(), dialog.0).unwrap(); + h.run_steps(2); + let doc = &h.state().session.active().unwrap().doc; + let groups: Vec<_> = doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).collect(); + assert_eq!(groups.len(), 1); + let children: Vec = groups[0].children().unwrap().iter().map(|l| l.id).collect(); + assert_eq!(children, vec![LayerId(text), LayerId(shape)], "both selected layers, in order"); + assert!(doc.layers.iter().any(|l| l.id == LayerId(other)), "an unselected layer stays at the top level"); + } + /// Items with no single target are greyed for a multi-layer selection (they used to run on /// whichever layer happened to be active, not the one right-clicked); the ones that act on the /// whole selection, including adding a mask, stay available. @@ -583,6 +606,7 @@ mod tests { "Add Layer Mask", "Duplicate Layers…", "Delete Layers", + "Group from Layers…", "Convert to Smart Object", "Rasterize Layers", "Link Layers", @@ -618,6 +642,7 @@ mod tests { "layer.exportAs", "layer.duplicate", "layer.delete", + "layer.new.groupFromLayers", "layer.rasterize.layer", "layer.smartObjects.convertToSmartObject", "layer.createClippingMask", diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rs index fb229fcbc8..5590c8c34b 100644 --- a/crates/ui-egui/src/layer_row_ui.rs +++ b/crates/ui-egui/src/layer_row_ui.rs @@ -195,6 +195,17 @@ pub fn label(painter: &Painter, x: f32, cy: f32, right: f32, text: &str, font: F /// The Layers panel's own items at the top of its panel menu (Photoshop's flyout). pub fn panel_menu(app: &mut crate::PhotocraftApp, ui: &mut egui::Ui) { + // New Group… and New Group from Layers… open the New Group dialog, like their Layer › New twins. + for (label, id) in [(tl!("New Group…"), crate::new_group_ui::NEW_GROUP), (tl!("New Group from Layers…"), crate::new_group_ui::FROM_LAYERS)] { + if ui.add_enabled(crate::menus::is_enabled(app, id), egui::Button::new(label)).clicked() { + let ctx = ui.ctx().clone(); + if let Err(e) = crate::menus::invoke(app, &ctx, id, json!({})) { + app.ui.status = e; + app.ui.status_error = true; + } + ui.close(); + } + } let can = app.session.is_enabled("layer.setExpanded"); if ui.add_enabled(can, egui::Button::new(tl!("Collapse All Groups"))).clicked() { if let Err(e) = app.run("layer.setExpanded", json!({"all": true, "expanded": false})) { diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rs index f2ac633ba2..13d3d79e4a 100644 --- a/crates/ui-egui/src/layer_row_ui/tests.rs +++ b/crates/ui-egui/src/layer_row_ui/tests.rs @@ -37,6 +37,8 @@ fn busy() -> photocraft_engine::Session { s.execute("layer.layerStyle.dropShadow", json!({"layer": g})).unwrap(); prev = Some(g); } + // Group Layers makes collapsed groups, as in Photoshop; these tests need every row shown. + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s } @@ -226,6 +228,23 @@ fn collapse_all_groups_from_the_panel_menu_and_it_is_saved() { } } +/// Photoshop's panel menu has New Group… and New Group from Layers… just above Collapse All +/// Groups; both open the New Group dialog. +#[test] +fn new_group_items_in_the_panel_menu_open_the_dialog() { + for (label, command) in [("New Group…", "layer.new.group"), ("New Group from Layers…", "layer.new.groupFromLayers")] { + let mut h = harness(busy(), 1.0, "promedium", 290.0); + let menu = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == crate::dock::Group::Layers).expect("layers group").1; + click(&mut h, pos2(menu.right() - 14.0, menu.top() + 14.0)); + let item = h.get_by_label(label).rect(); + assert!(item.top() < h.get_by_label("Collapse All Groups").rect().top(), "{label} comes before Collapse All Groups"); + click(&mut h, item.center()); + let fields = h.state().ui.dialogs.last().map(|d| d.fields.clone()).expect("the New Group dialog opened"); + assert!(crate::new_group_ui::owns(&fields)); + assert_eq!(fields["__command"], command); + } +} + /// Dragging down the eye column hides (or shows) every layer swept over, in one history step, and /// never reorders the layers, even when one pointer move jumps several rows; a hidden layer's eye /// box is empty and a click shows it again. diff --git a/crates/ui-egui/src/layer_tree_ui/tests.rs b/crates/ui-egui/src/layer_tree_ui/tests.rs index 13e73353b3..f56fc6ccfb 100644 --- a/crates/ui-egui/src/layer_tree_ui/tests.rs +++ b/crates/ui-egui/src/layer_tree_ui/tests.rs @@ -21,6 +21,8 @@ fn layered() -> photocraft_engine::Session { s.execute("layer.new.layer", json!({"name": "in-outer"})).unwrap(); s.execute("layer.select", json!({"layer": outer})).unwrap(); s.execute("layer.new.layer", json!({"name": "top"})).unwrap(); + // Group Layers makes collapsed groups, as in Photoshop; these tests start from open ones. + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 08e3464dde..586d787f06 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -126,6 +126,7 @@ pub mod move_mods; pub mod move_ui; pub mod native_menu; pub mod new_doc_ui; +pub mod new_group_ui; pub mod new_guide_ui; pub mod new_layer_ui; pub mod notices; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 18f1d6afb3..c5e57004f5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -461,6 +461,15 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } Ok(json!({"dialog": crate::stroke_ui::open(app)})) } + // Layer › New › Group… / Group from Layers… (and the Layers panel's menu, ⌥-click on its + // New Group button): Photoshop's New Group dialog. Explicit params run the engine directly, + // and Group Layers (⌘G) never asks. + _ if crate::new_group_ui::fronts(id) && params.as_object().is_none_or(|o| o.is_empty()) => { + if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) { + return Err(why); + } + Ok(json!({"dialog": crate::new_group_ui::open(app, id)})) + } // Photoshop's "Select and Mask…" is the engine's select.refineEdge. // Select › Color Range… from the menu: the dialog (with params: the engine directly). "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::color_range_ui::open(app)})), diff --git a/crates/ui-egui/src/new_group_button_tests.rs b/crates/ui-egui/src/new_group_button_tests.rs index e236ad74ec..8198c43e05 100644 --- a/crates/ui-egui/src/new_group_button_tests.rs +++ b/crates/ui-egui/src/new_group_button_tests.rs @@ -1,21 +1,26 @@ -//! #2561: the Layers panel New Group button. Like Photoshop a plain click adds an empty group -//! and Shift-click groups the selected layers. +//! #2561: the Layers panel New Group button. Like Photoshop CC 2014 and later, a click with two or +//! more layers selected puts them in a new, collapsed group, and with one layer it adds an empty +//! group. Shift-click (the older way) groups the selection too, ⌥-click asks in the New Group +//! dialog first and ⌘-click adds the empty group below the active layer. use egui::Modifiers; use egui_kittest::kittest::Queryable; -use photocraft_doc::{Layer, LayerId}; +use photocraft_doc::{Layer, LayerContent, LayerId}; use serde_json::json; use crate::PhotocraftApp; -/// Background, then `A` and `B` on top of it with both selected (`B` active). -fn two_selected() -> (egui_kittest::Harness<'static, PhotocraftApp>, LayerId, LayerId) { +/// Background, then `A` and `B` on top of it; `A` and `B` are selected when `both`, otherwise +/// only `B` is (`B` active either way). +fn selected(both: bool) -> (egui_kittest::Harness<'static, PhotocraftApp>, LayerId, LayerId) { let mut s = photocraft_engine::Session::new(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); let a = LayerId(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap()); let b = LayerId(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + if both { + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + } let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); PhotocraftApp::new(s, crate::Services::default()) @@ -28,28 +33,103 @@ fn groups(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Vec { h.state().session.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).cloned().collect() } -#[test] -fn shift_click_groups_the_selected_layers_in_order() { - let (mut h, a, b) = two_selected(); - h.get_by_label("Create a new group").click_modifiers(Modifiers::SHIFT); - h.run_steps(4); - let groups = groups(&h); +/// The one group holds `[a, b]` in order, sits next to the background, is the only selected layer +/// and, as in Photoshop, is collapsed: its layers' rows are not drawn. +fn assert_grouped(h: &egui_kittest::Harness<'static, PhotocraftApp>, a: LayerId, b: LayerId) { + let groups = groups(h); assert_eq!(groups.len(), 1); let children: Vec = groups[0].children().unwrap().iter().map(|l| l.id).collect(); assert_eq!(children, vec![a, b]); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.layers.len(), 2, "background and the new group stay at the top level"); + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc.layers.len(), 2, "background and the new group stay at the top level"); + assert_eq!(st.selected_layers(), vec![groups[0].id], "the new group is selected"); + assert!(matches!(&groups[0].content, LayerContent::Group(g) if !g.expanded), "the new group is collapsed"); + let rows: Vec = crate::layer_row_ui::recorded(&h.ctx).into_iter().map(|r| r.layer).collect(); + assert!(rows.contains(&groups[0].id.0) && !rows.contains(&a.0) && !rows.contains(&b.0), "only the group's row shows: {rows:?}"); } #[test] -fn plain_click_still_adds_an_empty_group() { - let (mut h, a, b) = two_selected(); +fn plain_click_groups_the_selected_layers_in_order() { + let (mut h, a, b) = selected(true); + h.get_by_label("Create a new group").click(); + h.run_steps(4); + assert_grouped(&h, a, b); + // One step: a single undo puts both layers back where they were. + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert!(groups(&h).is_empty()); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top[1..], [a, b]); +} + +#[test] +fn shift_click_groups_the_selected_layers_in_order() { + let (mut h, a, b) = selected(true); + h.get_by_label("Create a new group").click_modifiers(Modifiers::SHIFT); + h.run_steps(4); + assert_grouped(&h, a, b); +} + +#[test] +fn plain_click_with_one_selected_layer_adds_an_empty_group() { + let (mut h, a, b) = selected(false); h.get_by_label("Create a new group").click(); h.run_steps(4); let groups = groups(&h); assert_eq!(groups.len(), 1); assert!(groups[0].children().unwrap().is_empty()); - let doc = &h.state().session.active().unwrap().doc; - let top: Vec = doc.layers.iter().map(|l| l.id).collect(); - assert_eq!(top[1..3], [a, b], "the selected layers stay where they were"); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top[1..], [a, b, groups[0].id], "the layers stay where they were; the group goes above the active one"); +} + +/// Selecting a layer inside the collapsed group opens it, as in Photoshop. +#[test] +fn selecting_a_grouped_layer_opens_the_group() { + let (mut h, a, b) = selected(true); + h.get_by_label("Create a new group").click(); + h.run_steps(4); + assert_grouped(&h, a, b); + h.state_mut().run("layer.select", json!({"layer": a.0})).unwrap(); + h.run_steps(4); + let rows: Vec = crate::layer_row_ui::recorded(&h.ctx).into_iter().map(|r| r.layer).collect(); + assert!(rows.contains(&a.0) && rows.contains(&b.0), "{rows:?}"); +} + +/// ⌥-click asks in the New Group dialog first: New Group from Layers with several layers +/// selected, New Group with one. Nothing changes until OK. +#[test] +fn alt_click_opens_the_new_group_dialog() { + for (both, command) in [(true, "layer.new.groupFromLayers"), (false, "layer.new.group")] { + let (mut h, a, b) = selected(both); + h.get_by_label("Create a new group").click_modifiers(Modifiers::ALT); + h.run_steps(4); + assert!(groups(&h).is_empty(), "nothing happens before OK"); + let (id, fields) = h.state().ui.dialogs.last().map(|d| (d.id, d.fields.clone())).expect("the New Group dialog opened"); + assert!(crate::new_group_ui::owns(&fields)); + assert_eq!(fields["__command"], command); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(4); + if both { + assert_grouped(&h, a, b); + } else { + let groups = groups(&h); + assert_eq!(groups.len(), 1); + assert!(groups[0].children().unwrap().is_empty()); + } + } +} + +/// ⌘-click adds an empty group below the active layer, even with several layers selected. +#[test] +fn command_click_adds_an_empty_group_below_the_active_layer() { + for both in [true, false] { + let (mut h, a, b) = selected(both); + h.get_by_label("Create a new group").click_modifiers(Modifiers::COMMAND); + h.run_steps(4); + let groups = groups(&h); + assert_eq!(groups.len(), 1); + assert!(groups[0].children().unwrap().is_empty()); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top[1..], [a, groups[0].id, b]); + } } diff --git a/crates/ui-egui/src/new_group_ui.rs b/crates/ui-egui/src/new_group_ui.rs new file mode 100644 index 0000000000..9a6cf50836 --- /dev/null +++ b/crates/ui-egui/src/new_group_ui.rs @@ -0,0 +1,127 @@ +//! Photoshop's New Group dialog (Name, Color, Mode, Opacity), opened by Layer › New › Group… and +//! Group from Layers…, the Layers panel menu's New Group… / New Group from Layers… and ⌥-click on +//! the panel's New Group button. OK runs `layer.new.group` / `layer.new.groupFromLayers` with the +//! options as one history step; explicit params from Actions, CLI and MCP run the engine directly. + +use egui::{Align2, Sense, pos2, vec2}; +use photocraft_color::BlendMode; +use photocraft_doc::LabelColor; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub const NEW_GROUP: &str = "layer.new.group"; +pub const FROM_LAYERS: &str = "layer.new.groupFromLayers"; +const MARK: &str = "__newGroup"; +const KEYS: [&str; 4] = ["name", "color", "mode", "opacity"]; + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Whether the dialog fronts command `id`. +pub fn fronts(id: &str) -> bool { + id == NEW_GROUP || id == FROM_LAYERS +} + +/// Photoshop's defaults: the next "Group N", no colour, Pass Through, 100 %. Unlike Stroke the +/// choices are not remembered, as in Photoshop. +pub fn fields(app: &PhotocraftApp, command: &str) -> Map { + let name = app.session.active().map(|st| st.doc.next_layer_name("Group")).unwrap_or_else(|| "Group 1".into()); + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!(if command == FROM_LAYERS { FROM_LAYERS } else { NEW_GROUP })); + // The window title, as in Photoshop. + f.insert("__label".into(), json!(if command == FROM_LAYERS { "New Group from Layers…" } else { "New Group…" })); + f.insert("name".into(), json!(name)); + f.insert("color".into(), json!(LabelColor::None.id())); + f.insert("mode".into(), json!(crate::dialog_blend_ui::mode_key(BlendMode::PassThrough))); + f.insert("opacity".into(), json!(100.0)); + f +} + +pub fn open(app: &mut PhotocraftApp, command: &str) -> u64 { + let f = fields(app, command); + app.ui.open_dialog(crate::state::DialogKind::Command, f) +} + +/// Only the New Group params are passed to the engine; private UI markers are ignored. +pub fn params(f: &Map) -> Value { + Value::Object(KEYS.iter().filter_map(|k| f.get(*k).map(|v| (k.to_string(), v.clone()))).collect()) +} + +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + let command = f.get("__command").and_then(Value::as_str).filter(|c| fronts(c)).unwrap_or(NEW_GROUP).to_string(); + app.run(&command, params(f)) +} + +fn label(ui: &mut egui::Ui, text: &str) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(64.0, 22.0), Sense::hover()); + ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim); +} + +/// The label colour's swatch beside its menu: a crossed box for No Color, as in the layer menu. +fn swatch(ui: &mut egui::Ui, color: LabelColor) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); + let p = ui.painter(); + if let Some((fill, _)) = t.layer_label_colors(color) { + p.rect_filled(r, t.radius_sm, fill); + } else { + let stroke = egui::Stroke::new(1.0, t.text_dim); + p.rect_stroke(r, t.radius_sm, stroke, egui::StrokeKind::Inside); + let x = r.shrink(4.0); + p.line_segment([x.left_top(), x.right_bottom()], stroke); + p.line_segment([x.right_top(), x.left_bottom()], stroke); + } +} + +pub fn body(ui: &mut egui::Ui, f: &mut Map) { + ui.spacing_mut().item_spacing.y = 8.0; + ui.horizontal(|ui| { + label(ui, tl!("Name:")); + let mut name = f.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(252.0)); + if r.changed() { + f.insert("name".into(), json!(name)); + } + crate::field_tab::register(ui.ctx(), r.id); + // Photoshop opens the dialog with the name selected, so typing replaces it. + if !f.contains_key("__focused") { + f.insert("__focused".into(), json!(true)); + crate::field_tab::focus(ui.ctx(), r.id); + } + if r.gained_focus() { + crate::field_tab::select_all(ui.ctx(), r.id, &name); + } + }); + ui.horizontal(|ui| { + label(ui, tl!("Color:")); + let mut color = f.get("color").and_then(Value::as_str).and_then(LabelColor::from_id).unwrap_or(LabelColor::None); + let options: Vec<(LabelColor, &str)> = LabelColor::ALL.iter().map(|c| (*c, crate::layer_menu_ui::color_name(*c))).collect(); + if crate::widgets::dropdown(ui, "new-group-color", &mut color, &options, 130.0) { + f.insert("color".into(), json!(color.id())); + } + swatch(ui, color); + }); + ui.horizontal(|ui| { + label(ui, tl!("Mode:")); + let mut mode = f.get("mode").and_then(Value::as_str).and_then(photocraft_engine::commands::blend_from_str).unwrap_or(BlendMode::PassThrough); + let options = crate::panels::blend_options(true, mode); + if crate::widgets::dropdown(ui, "new-group-mode", &mut mode, &options, 130.0) { + f.insert("mode".into(), json!(crate::dialog_blend_ui::mode_key(mode))); + } + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Opacity:")).size(12.0).color(Tokens::get(ui.ctx()).text_dim)); + let mut opacity = f.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32; + if crate::widgets::value_field(ui, &mut opacity, 0.0..=100.0, "%", 64.0).changed() { + f.insert("opacity".into(), json!(opacity.round())); + } + }); +} + +#[cfg(test)] +#[path = "new_group_ui_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/new_group_ui_tests.rs b/crates/ui-egui/src/new_group_ui_tests.rs new file mode 100644 index 0000000000..2ff93afd3d --- /dev/null +++ b/crates/ui-egui/src/new_group_ui_tests.rs @@ -0,0 +1,136 @@ +use photocraft_color::BlendMode; +use photocraft_doc::{LabelColor, Layer, LayerContent, LayerId}; +use serde_json::json; + +use super::*; + +/// Background, then `A` and `B` (`B` active). +fn app() -> (PhotocraftApp, LayerId, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + let a = LayerId(app.run("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap()); + let b = LayerId(app.run("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap()); + (app, a, b) +} + +fn groups(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| l.is_group()).cloned().collect() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn menu_invocations_open_the_dialog_but_explicit_params_run_directly() { + let (mut app, _, _) = app(); + let ctx = egui::Context::default(); + for (command, title) in [(NEW_GROUP, "New Group…"), (FROM_LAYERS, "New Group from Layers…")] { + let opened = crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); + let id = opened["dialog"].as_u64().unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert!(owns(fields)); + assert_eq!((fields["__command"].as_str(), fields["__label"].as_str()), (Some(command), Some(title))); + assert!(groups(&app).is_empty(), "nothing happens until OK"); + app.ui.close_dialog(id); + // `ui.dialog.open {kind: "command"}` gets the same dialog. + let id = crate::dialogs::open_command_dialog(&mut app, command, "Group…"); + assert!(owns(&app.ui.dialogs.last().unwrap().fields)); + app.ui.close_dialog(id); + } + // Explicit params (Actions, CLI, MCP) run the engine without asking. + crate::menus::invoke(&mut app, &ctx, NEW_GROUP, json!({"name": "Direct"})).unwrap(); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(groups(&app)[0].name, "Direct"); + // Group Layers (⌘G) never asks. + crate::menus::invoke(&mut app, &ctx, "layer.groupLayers", json!({})).unwrap(); + assert!(app.ui.dialogs.is_empty()); + // Without a document nothing opens. + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert!(crate::menus::invoke(&mut empty, &ctx, NEW_GROUP, json!({})).is_err()); + assert!(crate::menus::invoke(&mut empty, &ctx, FROM_LAYERS, json!({})).is_err()); + assert!(empty.ui.dialogs.is_empty()); +} + +#[test] +fn defaults_are_photoshops_and_private_fields_do_not_leak() { + let (app, _, _) = app(); + let f = fields(&app, NEW_GROUP); + let out = params(&f); + assert_eq!(out, json!({"name": "Group 1", "color": "none", "mode": "passThrough", "opacity": 100.0})); + assert!(out.as_object().unwrap().keys().all(|k| !k.starts_with("__"))); +} + +#[test] +fn ok_creates_the_group_with_the_options_in_one_step_and_cancel_changes_nothing() { + let (mut app, _, b) = app(); + let initial = steps(&app); + let cancelled = open(&mut app, NEW_GROUP); + app.ui.dialog_mut(cancelled).unwrap().fields.insert("name".into(), json!("Nope")); + app.ui.close_dialog(cancelled); + assert_eq!(steps(&app), initial); + assert!(groups(&app).is_empty()); + + let id = open(&mut app, NEW_GROUP); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("name".into(), json!("Sky")); + d.fields.insert("color".into(), json!("blue")); + d.fields.insert("mode".into(), json!("multiply")); + d.fields.insert("opacity".into(), json!(60.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(steps(&app), initial + 1, "one history step"); + let g = &groups(&app)[0]; + assert_eq!((g.name.as_str(), g.label, g.blend), ("Sky", LabelColor::Blue, BlendMode::Multiply)); + assert!((g.opacity - 0.6).abs() < 1e-6); + let top: Vec = app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top.last(), Some(&g.id), "an empty group above the active layer B"); + assert_eq!(top[top.len() - 2], b); +} + +#[test] +fn ok_from_layers_groups_the_selection_collapsed() { + let (mut app, a, b) = app(); + app.run("layer.select", json!({"layer": a.0})).unwrap(); + app.run("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let id = open(&mut app, FROM_LAYERS); + app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("Pair")); + crate::dialogs::confirm(&mut app, id).unwrap(); + let g = &groups(&app)[0]; + assert_eq!(g.name, "Pair"); + assert_eq!(g.children().unwrap().iter().map(|l| l.id).collect::>(), vec![a, b]); + assert!(matches!(&g.content, LayerContent::Group(g) if !g.expanded), "collapsed, as in Photoshop"); +} + +/// The dialog draws its fields, opens with the name selected so typing replaces it, and Enter +/// runs OK. +#[test] +fn typing_replaces_the_selected_name_and_enter_confirms() { + use egui_kittest::kittest::Queryable; + let (app, _, _) = app(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), NEW_GROUP); + h.run_steps(4); + for label in ["OK", "Cancel"] { + assert!(h.query_by_label(label).is_some(), "{label} is shown"); + } + let name = h.get_by_role(egui::accesskit::Role::TextInput); + assert!(name.is_focused(), "the dialog opens on the name"); + name.type_text("Clouds"); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.last().unwrap().fields["name"], "Clouds"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(groups(h.state())[0].name, "Clouds"); +} + +#[test] +fn new_group_dialog_labels_are_translated_in_every_catalog() { + const LABELS: &[&str] = &["New Group…", "New Group from Layers…", "Name:", "Color:", "Mode:", "Opacity:", "Pass Through"]; + for lang in crate::i18n::Lang::all().filter(|lang| lang.complete_menus()) { + for label in LABELS { + assert!(crate::i18n::has(lang, label), "{} is missing New Group dialog label: {label}", lang.code()); + } + } +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 0f6a1b83bf..c38354909a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2021,7 +2021,7 @@ fn simple_lock_toggle(background: bool, l: &Layer) -> (String, Value) { /// The Layers panel's blend modes: Photoshop's, plus the layer's own Paint.NET mode when it has one /// (an imported `.pdn`), so the menu matches Photoshop's for every other layer. -fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> { +pub(crate) fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> { let own = Some(current).filter(|m| !m.has_psd_equivalent()); std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect() } @@ -2346,11 +2346,23 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate")); let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group")); if group.clicked() { - // Like Photoshop a plain click adds an empty group; Shift-click groups the selected - // layers, the same as Layer › Group Layers (#2561). - let shift = ui.input(|i| i.modifiers.shift); - let cmd = if shift && active_layer.is_some() { "layer.groupLayers" } else { "layer.new.group" }; - actions.push((cmd.into(), json!({}))); + // Like Photoshop CC 2014 and later, a click with two or more layers selected puts them + // in the new group (Layer › Group Layers); with one layer or none it adds an empty + // group above the active layer. Shift-click, the older way, groups the selection too + // (#2561). ⌥-click asks first in the New Group dialog, ⌘-click adds an empty group + // below the active layer. + let m = ui.input(|i| i.modifiers); + let groups = selection.len() >= 2 || (m.shift && active_layer.is_some()); + if m.alt { + // Null params go through the menu path, which opens the dialog. + let cmd = if groups { crate::new_group_ui::FROM_LAYERS } else { crate::new_group_ui::NEW_GROUP }; + actions.push((cmd.into(), Value::Null)); + } else if m.command { + actions.push(("layer.new.group".into(), json!({"below": true}))); + } else { + let cmd = if groups { "layer.groupLayers" } else { "layer.new.group" }; + actions.push((cmd.into(), json!({}))); + } } actions.extend(footer_drop(ui, &group, footer_drag, "layer.groupLayers")); let adj = footer_menu_button(ui, "adjustment-layer", 26.0, tl!("Create new fill or adjustment layer")); diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs index 9174da3ee9..a40886dd8d 100644 --- a/crates/ui-egui/src/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs @@ -21,6 +21,8 @@ fn realistic() -> photocraft_engine::Session { s.execute("file.new", json!({"width": 240, "height": 160})).unwrap(); s.execute("layer.new.layer", json!({"name": "in-group"})).unwrap(); s.execute("layer.groupLayers", json!({"name": "group"})).unwrap(); + // Group Layers makes a collapsed group; open it so the panel shows the layer inside. + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello"})).unwrap(); let paint = s.execute("layer.new.layer", json!({"name": "paint"})).unwrap()["layer"].as_u64().unwrap(); s.execute("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 60})).unwrap(); diff --git a/docs/context-menu-inventory.md b/docs/context-menu-inventory.md index 3d7bc522fb..55f1d830e6 100644 --- a/docs/context-menu-inventory.md +++ b/docs/context-menu-inventory.md @@ -29,7 +29,7 @@ Canvas invariant: secondary click must not accidentally start a paint stroke, co | Surface | Current entries or behavior | Command route / gap | |---|---|---| -| Layers panel row | Blending Options; Duplicate/Delete; Group from Layers; Quick Export PNG / Export As; Artboard/Frame from Layers; Convert to Smart Object; content-specific Rasterize; Add/Disable/Apply/Delete Layer Mask; Create/Release Clipping Mask; Link/Select Linked; Copy/Paste/Clear Layer Style; Merge Layers/Down, Merge Visible, Flatten Image; Rename Layer. Multi-select changes duplicate/delete/merge labels and target. | `layer_menu_ui::entries` supplies IDs for all except inline rename, then `menus::invoke` or engine dispatch. Missing or disabled commands are filtered/greyed. Check menu visibility and enabled state for groups, backgrounds, masks, type, adjustment/fill, smart objects, and multi-selection. | +| Layers panel row | Blending Options; Duplicate/Delete; Group from Layers (New Group from Layers dialog, also for a multi-selection); Quick Export PNG / Export As; Artboard/Frame from Layers; Convert to Smart Object; content-specific Rasterize; Add/Disable/Apply/Delete Layer Mask; Create/Release Clipping Mask; Link/Select Linked; Copy/Paste/Clear Layer Style; Merge Layers/Down, Merge Visible, Flatten Image; Rename Layer. Multi-select changes duplicate/delete/merge labels and target. | `layer_menu_ui::entries` supplies IDs for all except inline rename, then `menus::invoke` or engine dispatch. Missing or disabled commands are filtered/greyed. Check menu visibility and enabled state for groups, backgrounds, masks, type, adjustment/fill, smart objects, and multi-selection. | | Channels panel row | Alpha: Duplicate/Delete/Rename, spot conversion or merge, selection-display and overlay controls. Quick Mask: Exit, display and overlay. Composite/color: Duplicate. Layer mask: Enable/Disable, Delete. Common: New Channel, New Spot Channel, Split, Merge. | `channel.*`, `layer.layerMask.*`, `select.editInQuickMaskMode`, `ui.renameChannel`. Check selection loading/saving, channel options, and per-row enablement against Photoshop. | | Brushes panel preset | Rename Brush, Delete Brush. | Routed through `brush.presets.*` panel actions. Check duplicate/export/import and library organization. | | Brushes panel group | Rename Group, Delete Group. | Routed through preset panel actions; confirm group deletion consequences. | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 72d1902cf7..0997a42e92 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -57,7 +57,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `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. Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them. - `ui.set` also accepts the Crop tool's gear menu (#1919) as `cropShield`, an object patching any of `show_cropped_area` (Show Cropped Area; off hides everything outside the box behind the canvas colour, H in the app), `enabled` (Enable Crop Shield), `color` (`matchCanvas`, the pasteboard colour, or `custom`), `custom_color` (`[r, g, b]`, 0..255), `opacity` (0..100, default 75), `auto_adjust` (Auto Adjust Opacity: half the opacity while the box is dragged), `classic_mode` (Use Classic Mode, default off: the box turns and moves over the image; off is Photoshop's default mode, where the box stays upright and the view turns and pans the image behind it while the Crop tool shows a frame, P in the app; in both modes picking the tool turns a rotated view upright about its centre, Classic Mode keeping the camera upright with the frame drawn turned, and the view stays upright after a commit or cancel; Classic Mode greys out Show Cropped Area, which then acts as on, and Auto Center Preview) and `auto_center_preview` (default on: in default mode a box being resized keeps its centre where it is on screen, also after a pan, a drawn one moves to the middle of the canvas, and X re-centres it; a move never re-centres the box). `ui.inspect` reports it as `toolOptions.crop_shield`. The pending frame (`crop_rect`, `crop_angle`: its turn on the image) and the `image.crop` a commit runs are the same in both modes. -- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`, `newCropPreset` / `deleteCropPreset`: the Crop tool's New / Delete Crop Preset… dialogs, fields `name` and `selected: [names]`; crop presets are `crop` tool presets, so `tool.presets.new/list/edit {"tool":"crop"}` drive them too) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once +- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}` (`layer.new.group` / `layer.new.groupFromLayers` open the New Group dialog: fields `name`, `color`, `mode`, `opacity`), `newCropPreset` / `deleteCropPreset`: the Crop tool's New / Delete Crop Preset… dialogs, fields `name` and `selected: [names]`; crop presets are `crop` tool presets, so `tool.presets.new/list/edit {"tool":"crop"}` drive them too) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once - A Layer Style color field opens the shared picker with `ui.dialog.open {"kind":"colorPicker","parent":12,"effect":"fx2","field":"color"}`. `parent` is the Layer Style dialog id; `effect` is its effect instance id. `field` must be one of that instance's color parameters (`color`, or `from`/`to` for Gradient Overlay). The picker previews over the pending style without changing the document. Picker OK changes only the parent parameter; Cancel discards the preview. Confirm the parent afterwards to apply the style. Parent confirmation is refused while its picker is open; parent cancellation closes both. The binding is exposed in `ui.inspect` as `__layerStyleColor`; changed/closed targets or a document switch invalidate it. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 76b59de719..ba5bcca7b3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (New Group dialog, ⌥/⌘-click New Group, groups from layers start collapsed) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -207,12 +207,16 @@ Paragraph; the rest open as in-app floating windows. | Themes: Photoshop's four greys | partial | five themes; #2661 | | Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 | | Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 | +| Layers panel New Group button: click with 2+ layers selected groups them (CC 2014+), ⇧-click groups, one layer gives an empty group, ⌥-click opens the New Group dialog, ⌘-click adds the group below the active layer | done | #2561, `new_group_button_tests.rs` | +| New Group dialog (Name, Color, Mode, Opacity) for Layer › New › Group… / Group from Layers…, the Layers panel menu and the row menu; ⌘G stays immediate | done | `new_group_ui.rs`, `new_group_ui_tests.rs` | +| Groups made from layers (⌘G, New Group button, Group from Layers) start collapsed; selecting a layer inside opens the group | done | `group_options.rs` tests, `new_group_button_tests.rs` | ## Revision history | Date | Change | Summary | |---|---|---| | 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues | +| 2026-10-12 | minor | New Group button groups two or more selected layers (CC 2014+); New Group dialog (Layer › New, Layers panel menu, row menu, ⌥-click); ⌘-click New Group adds the group below; groups made from layers start collapsed (#2561) | | 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions | | 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning | | 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) | From 532e8587e8afb431159066a9a5f7e08bca2f1ca4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 15:24:30 +0000 Subject: [PATCH 06/87] Layers: new layers go into an open group and join the clip group they land in (#2203) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new layer now goes where Photoshop puts it: as the top layer of an open active group (an artboard takes it when its content is on the board), above a closed group, and on top of the stack with nothing active. A new layer or group lands inside a clip group's run and joins it (the #2203 rule upstream's clip_group applies), so it never becomes the clipped layers' empty base. ⌘-click on the Layers panel's New Layer button adds the layer below the active one (layer.new.layer gains `below`; ⌥-click still opens the New Layer dialog). New module crates/engine/src/layer_place.rs (insert_new with Place::Auto / Above / Below), used by New Layer (with upstream's options and clip_group::settle), New Group, adjustment and fill layers, gradient fill (and its live preview), type and shape layers, paste (several layers: the first where a new layer goes, the rest above it, with the group depth check), place, Stamp Visible, video layers, Render and Vanishing Point new layers and copies to another document. Layer via Copy/Cut, a Content-Aware Fill new layer, Stamp Down, Auto-Blend and the Remove tool's new layer stay above their source but join its clip group. Artboards are never nested or clipped (a copied board goes beside the anchor's top-level layer, past any clip group above it); a fully or partly locked group keeps new layers out; a copied clipped layer pasted with nothing below it is released. A new frame starts closed, so the next new layer goes above it rather than into it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyBcWJNZ3eRotC5HNZuwge --- crates/engine/src/align_cmds.rs | 2 +- crates/engine/src/commands.rs | 18 +- crates/engine/src/edit_cmds.rs | 10 +- crates/engine/src/edit_menu_cmds.rs | 2 +- crates/engine/src/file_cmds.rs | 2 +- crates/engine/src/frame_cmds.rs | 10 +- crates/engine/src/gradient_fill_cmds.rs | 2 +- crates/engine/src/group_options.rs | 24 ++ crates/engine/src/layer_copy_cmds.rs | 6 +- crates/engine/src/layer_multi_cmds.rs | 4 +- crates/engine/src/layer_nav_cmds.rs | 3 +- crates/engine/src/layer_place.rs | 105 ++++++ crates/engine/src/layer_place_tests.rs | 298 ++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/new_layer.rs | 7 +- crates/engine/src/pattern_cmds.rs | 2 +- crates/engine/src/presets/gradients.rs | 3 +- crates/engine/src/render_cmds.rs | 2 +- crates/engine/src/retouch_cmds/remove.rs | 3 +- crates/engine/src/stamp_cmds.rs | 4 +- crates/engine/src/tests.rs | 3 +- crates/engine/src/type_cmds.rs | 2 +- crates/engine/src/vector_cmds.rs | 2 +- crates/engine/src/video_cmds.rs | 8 +- crates/engine/src/vp_cmds.rs | 2 +- .../engine/tests/layer_range_panel_order.rs | 3 +- crates/ui-egui/src/gradient_ui.rs | 5 +- crates/ui-egui/src/layer_tree_ui/tests.rs | 2 +- crates/ui-egui/src/new_group_button_tests.rs | 15 + crates/ui-egui/src/panels.rs | 14 +- crates/ui-egui/src/shortcut_dispatch/tests.rs | 5 +- docs/ui-parity.md | 6 +- 32 files changed, 527 insertions(+), 48 deletions(-) create mode 100644 crates/engine/src/layer_place.rs create mode 100644 crates/engine/src/layer_place_tests.rs diff --git a/crates/engine/src/align_cmds.rs b/crates/engine/src/align_cmds.rs index 26cd1acc39..893c322c5d 100644 --- a/crates/engine/src/align_cmds.rs +++ b/crates/engine/src/align_cmds.rs @@ -239,7 +239,7 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result { surf.write_region(area, px); surf.prune(); } - let nid = doc.insert_above(Some(top), l); + let nid = crate::layer_place::insert_new(doc, Some(top), l, crate::layer_place::Place::Above); *active = Some(nid); Ok(Some(nid)) })?; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 56f57d5f6f..968de4cb66 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -315,7 +315,7 @@ fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Res let id = s.edit(&label, |doc, active| { let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj)); mask_new_layer(doc, &mut l, p, cmd)?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; @@ -549,7 +549,7 @@ fn build() -> Vec { "Layer…", ["Layer", "New"], Some("Cmd+Shift+N"), - r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error)}"##, + r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"below":bool=false (under the active layer, as ⌘-click on the Layers panel's New Layer button)} (above the active layer, or the top layer inside it when it is an open group)"##, has_doc, crate::new_layer::run ), @@ -558,7 +558,7 @@ fn build() -> Vec { "Group…", ["Layer", "New"], None, - r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"below":bool=false (under the active layer, as ⌘-click on the Layers panel's New Group button)}"##, + r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"below":bool=false (under the active layer, as ⌘-click on the Layers panel's New Group button)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##, has_doc, |s, p| { let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?; @@ -566,17 +566,13 @@ fn build() -> Vec { None => false, Some(v) => v.as_bool().ok_or_else(|| bad("layer.new.group", "`below` must be a boolean"))?, }; + let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; let id = s.edit("New Group", |doc, active| { let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); let mut group = Layer::group(name, vec![]); opts.apply(&mut group); let bg = crate::background_cmds::background_id(doc); - // Below only a layer that is in the document, and never under the Background. - let under = (*active).filter(|a| below && Some(*a) != bg && doc.path_of(*a).is_some()); - let id = doc.insert_above(*active, group); - if under.is_some() { - doc.shift(id, -1); - } + let id = crate::layer_place::insert_new(doc, *active, group, place); crate::background_cmds::keep_background_at_bottom(bg, doc)?; *active = Some(id); Ok(id) @@ -837,7 +833,7 @@ fn build() -> Vec { let fill = Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode); let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill)); mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor")?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; @@ -868,7 +864,7 @@ fn build() -> Vec { .in_mode(doc.mode); let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient")?; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index d4de2d548e..ed558d2599 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -318,7 +318,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { let id = s.edit("Paste", |doc, active| { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = surf; - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); doc.selection = None; Ok(id) @@ -342,9 +342,13 @@ fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result< let patterns: Vec<_> = copies.patterns.iter().filter(|pat| !d.doc.patterns.iter().any(|q| q.id == pat.id)).cloned().collect(); let id = s.edit("Paste", |doc, active| { doc.patterns.extend(patterns); + // The first pasted layer goes where a new layer would; the rest stack above it. + let mut place = crate::layer_place::Place::Auto; for l in copies.layers { - *active = Some(doc.insert_above(*active, l)); + *active = Some(crate::layer_place::insert_new(doc, *active, l, place)); + place = crate::layer_place::Place::Above; } + crate::layer_multi_cmds::check_group_depth(doc, "Paste")?; doc.selection = None; active.ok_or(EngineError::Other("nothing to paste".into())) })?; @@ -445,7 +449,7 @@ fn layer_via(s: &mut Session, cut: bool) -> Result { } let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format()); *crate::pixels_mut(&mut l)? = clip.surface; - let nid = doc.insert_above(Some(id), l); + let nid = crate::layer_place::insert_new(doc, Some(id), l, crate::layer_place::Place::Above); *active = Some(nid); // Photoshop deselects: a following Free Transform moves the whole new layer (#1096). doc.selection = None; diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs index 103a5edc6e..c3505af224 100644 --- a/crates/engine/src/edit_menu_cmds.rs +++ b/crates/engine/src/edit_menu_cmds.rs @@ -503,7 +503,7 @@ fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: & s.write_region(window, &px); s.prune(); } - let nid = doc.insert_above(Some(id), l); + let nid = crate::layer_place::insert_new(doc, Some(id), l, crate::layer_place::Place::Above); *active = Some(nid); return Ok(nid); } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5aa2441a1f..b181915ba8 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -494,7 +494,7 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option Result { crate::layer_multi_cmds::check_group_depth(doc, "New Frame")?; gid } - None => doc.insert_above(*active, Layer::group(name, vec![])), + None => crate::layer_place::insert_new(doc, *active, Layer::group(name, vec![]), crate::layer_place::Place::Auto), }; - doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?.mask = Some(mask); + let frame = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; + frame.mask = Some(mask); + // A frame is one row, as in Photoshop: closed, so the next new layer goes above it rather + // than into it. + if let LayerContent::Group(g) = &mut frame.content { + g.expanded = false; + } *active = Some(gid); Ok(gid) })?; diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rs index 041d311691..29987e9ecb 100644 --- a/crates/engine/src/gradient_fill_cmds.rs +++ b/crates/engine/src/gradient_fill_cmds.rs @@ -318,7 +318,7 @@ fn create(s: &mut Session, p: &Value) -> Result { new_layer(s, &d.doc, p)? }; let id = s.edit("New Gradient Fill Layer", |doc, active| { - let id = doc.insert_above(*active, layer); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/group_options.rs b/crates/engine/src/group_options.rs index 60b965be37..f68156f8a8 100644 --- a/crates/engine/src/group_options.rs +++ b/crates/engine/src/group_options.rs @@ -194,6 +194,30 @@ mod tests { assert_eq!(top(&s).last(), Some(&g3)); } + /// A group added inside a clipping mask (⌘-click under a clipped layer, or a plain New Group + /// on the base) joins the mask, as in Photoshop: the clipped layers keep their base and stay + /// visible, and nothing needs recompositing. + #[test] + fn a_group_added_inside_a_clipping_mask_joins_it() { + let (mut s, a, b) = session(); + s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap(); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let g = id(s.execute("layer.new.group", json!({"below": true})).unwrap()); + assert_eq!(top(&s)[1..], [a, g, b]); + assert!(layer(&s, g).clipped, "under a clipped layer the group is clipped too"); + assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY), "B still clips to A"); + // On the base itself: the new group goes between A and its clipped layers. + s.undo(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + assert_eq!(top(&s)[1..], [a, g, b]); + assert!(layer(&s, g).clipped); + // Outside a clipping mask nothing changes. + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + assert!(!layer(&s, g).clipped); + } + #[test] fn bad_options_fail_without_touching_the_document() { let (mut s, a, b) = session(); diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/layer_copy_cmds.rs index 9a42778de2..bde1b2db1b 100644 --- a/crates/engine/src/layer_copy_cmds.rs +++ b/crates/engine/src/layer_copy_cmds.rs @@ -195,11 +195,15 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result { doc.patterns.extend(patterns); let mut above = *active; let mut new = Vec::with_capacity(copies.layers.len()); + // The first copy goes where a new layer would; the rest stack above it. + let mut place = crate::layer_place::Place::Auto; for l in copies.layers { - let id = doc.insert_above(above, l); + let id = crate::layer_place::insert_new(doc, above, l, place); + place = crate::layer_place::Place::Above; above = Some(id); new.push(id); } + crate::layer_multi_cmds::check_group_depth(doc, "Duplicate Layers")?; *active = above; Ok(new) }); diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 570dd597b6..3fb5d5af32 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -2135,7 +2135,9 @@ mod tests { assert!(s.execute("layer.groupLayers", json!({"layer": a.0})).is_err(), "one board is refused too"); assert_eq!(doc(&s).layers.iter().map(|l| l.id).collect::>(), before.layers.iter().map(|l| l.id).collect::>()); assert_eq!(doc(&s).artboards().len(), 2); - // A layer inside a board still groups, inside its board. + // A layer inside a board still groups, inside its board. (Made with no layer selected: a + // new layer with a board selected goes into that board, as in Photoshop.) + s.execute("select.deselectLayers", json!({})).unwrap(); let inner = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); select_all(&mut s, &[inner]); let c = LayerId(s.execute("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); diff --git a/crates/engine/src/layer_nav_cmds.rs b/crates/engine/src/layer_nav_cmds.rs index 3b52343f71..bf02936418 100644 --- a/crates/engine/src/layer_nav_cmds.rs +++ b/crates/engine/src/layer_nav_cmds.rs @@ -118,9 +118,10 @@ mod tests { s.execute("layer.select", json!({"layer": c.0, "mode": "add"})).unwrap(); s.execute("layer.groupLayers", json!({})).unwrap(); let group = s.active().unwrap().doc.layers.iter().find(|l| l.is_group()).unwrap().id; + // D goes above the closed group (an open one would take it inside, as in Photoshop). + let d = id(&mut s, "layer.new.layer", json!({"name": "D"})); // Group Layers makes a collapsed group; open it so the panel shows B and C. s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})).unwrap(); - let d = id(&mut s, "layer.new.layer", json!({"name": "D"})); (s, [bg, a, group, b, c, d]) } diff --git a/crates/engine/src/layer_place.rs b/crates/engine/src/layer_place.rs new file mode 100644 index 0000000000..9b5b5cda17 --- /dev/null +++ b/crates/engine/src/layer_place.rs @@ -0,0 +1,105 @@ +//! Where a new layer goes, as in Photoshop. Above the active layer, or as the top layer inside the +//! active group when that group is open (an artboard, open or closed, when the layer's content is +//! on the board); with nothing active, at the top of the stack. A layer that lands inside a clipping mask joins it: it is clipped when the layer +//! just above its slot is clipped, the rule Photoshop follows on every insert (#2203), so a new +//! layer (or group) between a base and its clipped layers never becomes their (empty) base. +//! Artboards are never nested or clipped: a new one goes to the top level. + +use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerPath, MAX_GROUP_DEPTH}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Place { + /// New Layer, New Group, new adjustment, fill, type and shape layers, Paste…: inside the anchor + /// when it is an open, unlocked group (or an artboard the content is on), else directly above it. + Auto, + /// Directly above the anchor, never inside it: a layer made from another layer, or the second + /// and later of several new layers. + Above, + /// Directly below the anchor (⌘-click on the Layers panel's New Layer or New Group button). Never + /// under the Background, where it goes above instead. + Below, +} + +/// The slot `layer` would take: its parent's path (empty for the root) and its index among the +/// parent's children (bottom to top). A missing or stale `anchor` means the top of the stack. +pub fn insertion_point(doc: &Document, anchor: Option, layer: &Layer, place: Place) -> (LayerPath, usize) { + let root_top = (Vec::new(), doc.layers.len()); + let Some(path) = anchor.and_then(|a| doc.path_of(a)) else { return root_top }; + // An artboard stays at the top level: beside the anchor's top-level layer. + let path = if layer.artboard().is_some() { path.get(..1).map(<[usize]>::to_vec).unwrap_or_default() } else { path }; + let (Some((&k, parent)), Some(target)) = (path.split_last(), doc.layer_at(&path)) else { return root_top }; + match place { + Place::Auto if takes_new_layers(target, path.len(), layer) => (path.clone(), target.children().map_or(0, <[Layer]>::len)), + Place::Below if crate::background_cmds::background_id(doc) != Some(target.id) => (parent.to_vec(), k), + _ => (parent.to_vec(), k + 1), + } +} + +/// Inserts `layer` at its [`insertion_point`], clipped when it lands inside a clipping mask (a +/// flag it already has is kept unless nothing is below it to clip to; an artboard is never +/// clipped); returns its id. Never fails: a slot that can't be reached puts +/// the layer on top of the stack. +pub fn insert_new(doc: &mut Document, anchor: Option, mut layer: Layer, place: Place) -> LayerId { + let id = layer.id; + let (parent, index) = insertion_point(doc, anchor, &layer, place); + let sib = if parent.is_empty() { Some(&mut doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) }; + if let Some(sib) = sib { + let mut index = index.min(sib.len()); + if layer.artboard().is_some() { + // Past the clipped layers above the slot, so their clipping mask stays whole. + while sib.get(index).is_some_and(|above| above.clipped) { + index += 1; + } + layer.clipped = false; + } else if sib.get(index).is_some_and(|above| above.clipped) { + layer.clipped = true; + } else if index == 0 { + // Nothing below to clip to (a copied clipped layer pasted into an empty group). + layer.clipped = false; + } + sib.insert(index, layer); + } else { + doc.layers.push(layer); + } + id +} + +/// Does the group `target` at depth `depth` (its path length) take a new `layer` as its top +/// child? An open group or an artboard does, unless it is locked (the layer would be born locked: +/// no painting, rendering or moving it) or nesting would pass [`MAX_GROUP_DEPTH`]. An artboard +/// takes a layer with content only when that content is centred on the board, as callers place +/// it for the canvas (Place, Paste, a Type or Shape click): elsewhere the board would clip it. +fn takes_new_layers(target: &Layer, depth: usize, layer: &Layer) -> bool { + let LayerContent::Group(g) = &target.content else { return false }; + let k = &target.locks; + let locked = k.all || k.pixels || k.transparency || k.position; + let on_board = |rect: photocraft_geom::Rect| { + crate::layer_multi_cmds::layer_bounds(layer).is_none_or(|b| { + let (cx, cy) = (b.x0 / 2 + b.x1 / 2, b.y0 / 2 + b.y1 / 2); + rect.contains(cx, cy) + }) + }; + let open = match &g.artboard { + Some(board) => on_board(board.rect), + None => g.expanded, + }; + open && !locked && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH +} + +/// Group nesting inside `layer` itself: 0 for a layer or an empty group, as +/// [`Document::max_group_depth`] counts it. Explicit stack: pasted groups can be deep. +fn subtree_depth(layer: &Layer) -> usize { + let mut max = 0; + let mut stack: Vec<(&Layer, usize)> = vec![(layer, 0)]; + while let Some((l, depth)) = stack.pop() { + if let Some(children) = l.children().filter(|c| !c.is_empty()) { + max = max.max(depth + 1); + stack.extend(children.iter().map(|c| (c, depth + 1))); + } + } + max +} + +#[cfg(test)] +#[path = "layer_place_tests.rs"] +mod tests; diff --git a/crates/engine/src/layer_place_tests.rs b/crates/engine/src/layer_place_tests.rs new file mode 100644 index 0000000000..84f3a22643 --- /dev/null +++ b/crates/engine/src/layer_place_tests.rs @@ -0,0 +1,298 @@ +use photocraft_doc::{Document, Layer, LayerContent, LayerId, MAX_GROUP_DEPTH}; +use serde_json::{Value, json}; + +use super::*; +use crate::Session; + +/// Background, then `A` and `B` (`B` active). +fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let a = id(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()); + let b = id(s.execute("layer.new.layer", json!({"name": "B"})).unwrap()); + (s, a, b) +} + +fn id(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn top(s: &Session) -> Vec { + doc(s).layers.iter().map(|l| l.id).collect() +} + +fn children(s: &Session, group: LayerId) -> Vec { + doc(s).layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect() +} + +fn set_expanded(s: &mut Session, group: LayerId, expanded: bool) { + s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": expanded})).unwrap(); +} + +fn select(s: &mut Session, layer: LayerId) { + s.execute("layer.select", json!({"layer": layer.0})).unwrap(); +} + +#[test] +fn a_new_layer_goes_inside_an_open_active_group_and_above_a_closed_one() { + let (mut s, a, b) = session(); + select(&mut s, a); + let g = id(s.execute("layer.groupLayers", json!({})).unwrap()); + // A group made from layers starts closed: the new layer goes above it. + let above = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(top(&s)[1..], [g, above, b]); + assert_eq!(children(&s, g), vec![a]); + // Opened, it takes the new layer as its top layer. + select(&mut s, g); + set_expanded(&mut s, g, true); + let inside = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![a, inside]); + // A new empty group is open, so the next new layer goes into it (New Group, then New Layer). + s.execute("select.deselectLayers", json!({})).unwrap(); + let empty = id(s.execute("layer.new.group", json!({})).unwrap()); + let first = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, empty), vec![first]); + // The same goes for the other new layers: adjustment, fill, type and shape layers. + select(&mut s, empty); + for (cmd, p) in [ + ("layer.newAdjustmentLayer.invert", json!({})), + ("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})), + ("type.create", json!({"x": 2, "y": 10, "text": "Hi"})), + ("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5]})), + ] { + select(&mut s, empty); + let l = id(s.execute(cmd, p).unwrap()); + assert_eq!(children(&s, empty).last(), Some(&l), "{cmd} goes inside the open group"); + } +} + +#[test] +fn artboards_take_new_layers_and_locked_groups_do_not() { + let (mut s, _, b) = session(); + let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 16, 16]})).unwrap()); + set_expanded(&mut s, board, false); + select(&mut s, board); + let l = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(doc(&s).artboard_of(l), Some(board), "an artboard takes the layer even when closed"); + // A fully locked group would lock the new layer: it goes above instead. + select(&mut s, b); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + s.execute("layer.setProps", json!({"layer": g.0, "locks": {"all": true}})).unwrap(); + select(&mut s, g); + let above = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(children(&s, g).is_empty()); + assert!(doc(&s).layers.iter().any(|l| l.id == above)); +} + +#[test] +fn below_puts_the_new_layer_under_the_active_layer() { + let (mut s, a, b) = session(); + let bg = top(&s)[0]; + let l = id(s.execute("layer.new.layer", json!({"below": true})).unwrap()); + assert_eq!(top(&s), vec![bg, a, l, b]); + // Never under the Background, and never inside an open group. + select(&mut s, bg); + let l2 = id(s.execute("layer.new.layer", json!({"below": true})).unwrap()); + assert_eq!(top(&s)[..2], [bg, l2]); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + let l3 = id(s.execute("layer.new.layer", json!({"below": true})).unwrap()); + assert!(children(&s, g).is_empty()); + let root = top(&s); + assert_eq!(root.iter().position(|x| *x == l3).unwrap() + 1, root.iter().position(|x| *x == g).unwrap()); + assert!(s.execute("layer.new.layer", json!({"below": "yes"})).is_err()); +} + +/// The clipping rule Photoshop follows on every insert (#2203): a new layer is clipped exactly +/// when the layer just above its slot is clipped. +#[test] +fn a_new_layer_joins_the_clipping_mask_it_lands_in() { + let (mut s, base, c1) = session(); + let c2 = id(s.execute("layer.new.layer", json!({"name": "C2"})).unwrap()); + for c in [c1, c2] { + s.execute("layer.setProps", json!({"layer": c.0, "clipped": true})).unwrap(); + } + let clipped = |s: &Session, l: LayerId| doc(s).layer(l).unwrap().clipped; + // On the base: between the base and its clipped layers. + select(&mut s, base); + let on_base = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(clipped(&s, on_base)); + // In the middle of the chain. + select(&mut s, c1); + let mid = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(clipped(&s, mid)); + // Above the top clipped layer it is outside the mask. + select(&mut s, c2); + let above = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(!clipped(&s, above)); + // ⌘-click New Layer under a clipped layer joins it too; under the base it does not. + select(&mut s, c2); + let l = id(s.execute("layer.new.layer", json!({"below": true})).unwrap()); + assert!(clipped(&s, l)); + select(&mut s, base); + let l = id(s.execute("layer.new.layer", json!({"below": true})).unwrap()); + assert!(!clipped(&s, l)); + // A group joins as well (Photoshop clips groups too), and so do the other new layers. + select(&mut s, base); + let l = id(s.execute("layer.new.group", json!({})).unwrap()); + assert!(clipped(&s, l)); + select(&mut s, base); + let l = id(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()); + assert!(clipped(&s, l)); + // A layer made from a clipped layer (Layer via Copy) stays in its mask. + select(&mut s, c1); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + let l = id(s.execute("layer.new.layerViaCopy", json!({})).unwrap()); + assert!(clipped(&s, l)); +} + +#[test] +fn a_pasted_layer_goes_into_an_open_group() { + let (mut s, a, _) = session(); + // A whole pixel layer on the clipboard (no selection). + select(&mut s, a); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let into = id(s.execute("layer.new.group", json!({"name": "Into"})).unwrap()); + let pasted = id(s.execute("edit.paste", json!({})).unwrap()); + assert_eq!(children(&s, into), vec![pasted]); +} + +/// The second and later of several new layers stack above the first, even when the first is an +/// open group: it must not swallow them. +#[test] +fn later_layers_of_a_batch_go_above_the_first() { + let (s, _, b) = session(); + let mut d = doc(&s).clone(); + let first = insert_new(&mut d, Some(b), Layer::group("open", vec![]), Place::Auto); + let next = Layer::raster("next", d.pixel_format()); + let second = insert_new(&mut d, Some(first), next, Place::Above); + let root: Vec = d.layers.iter().map(|l| l.id).collect(); + assert_eq!(root[root.len() - 2..], [first, second]); + assert!(d.layer(first).unwrap().children().unwrap().is_empty()); +} + +#[test] +fn nesting_stops_at_the_group_depth_limit() { + let mut doc = Document::new("deep", photocraft_doc::Size::new(8, 8), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + // A chain of open groups as deep as allowed, with a layer at the bottom. + let mut inner = Layer::raster("deep", doc.pixel_format()); + let deep_id = inner.id; + let mut ids = Vec::new(); + for i in 0..MAX_GROUP_DEPTH { + let g = Layer::group(format!("g{i}"), vec![inner]); + ids.push(g.id); + inner = g; + } + doc.layers.push(inner); + assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH); + let innermost = *ids.first().unwrap(); + // A plain layer fits beside `deep`, inside the innermost group (the depth stays the same)… + let layer = Layer::raster("fits", doc.pixel_format()); + let l = insert_new(&mut doc, Some(innermost), layer, Place::Auto); + assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH); + assert!(doc.layer(innermost).unwrap().children().unwrap().iter().any(|c| c.id == l)); + // …but a group with a layer in it would go one deeper: it goes beside the group instead. + let nested = Layer::group("nested", vec![Layer::raster("x", doc.pixel_format())]); + let n = insert_new(&mut doc, Some(innermost), nested, Place::Auto); + assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH); + assert!(!doc.layer(innermost).unwrap().children().unwrap().iter().any(|c| c.id == n)); + assert!(doc.layer(deep_id).is_some()); +} + +#[test] +fn a_missing_or_stale_anchor_means_the_top_of_the_stack() { + let (s, _, _) = session(); + let mut d = doc(&s).clone(); + for anchor in [None, Some(LayerId(u64::MAX))] { + for place in [Place::Auto, Place::Above, Place::Below] { + let layer = Layer::raster("x", d.pixel_format()); + let l = insert_new(&mut d, anchor, layer, place); + assert_eq!(d.layers.last().map(|x| x.id), Some(l), "{anchor:?} {place:?}"); + } + } + assert!(matches!(d.layers.last().unwrap().content, LayerContent::Raster(_))); +} + +/// A partly locked group (pixels, transparency or position) would lock a layer created in it, so +/// Render and Vanishing Point could not draw into their new layer: it goes above the group. +#[test] +fn a_partly_locked_group_keeps_new_layers_out() { + for locks in [json!({"pixels": true}), json!({"transparency": true}), json!({"position": true})] { + let (mut s, _, b) = session(); + select(&mut s, b); + let g = id(s.execute("layer.new.group", json!({})).unwrap()); + s.execute("layer.setProps", json!({"layer": g.0, "locks": locks})).unwrap(); + select(&mut s, g); + s.execute("filter.render.tree", json!({})).unwrap(); + let l = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert!(children(&s, g).is_empty(), "{locks}"); + assert!(top(&s).contains(&l)); + } +} + +/// An artboard takes a new layer whose content is centred on it, and a new empty layer; content +/// placed elsewhere (Place and Paste centre on the canvas) stays at the top level instead of +/// being clipped away by the board. +#[test] +fn an_artboard_takes_only_content_that_is_on_it() { + let (mut s, _, _) = session(); + let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 8, 8]})).unwrap()); + let mut d = doc(&s).clone(); + let raster = |d: &Document, r: photocraft_geom::Rect| { + let mut l = Layer::raster("content", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + l + }; + let on = raster(&d, photocraft_geom::Rect::new(1, 1, 5, 5)); + let on = insert_new(&mut d, Some(board), on, Place::Auto); + assert_eq!(d.artboard_of(on), Some(board)); + let off = raster(&d, photocraft_geom::Rect::new(10, 10, 16, 16)); + let off = insert_new(&mut d, Some(board), off, Place::Auto); + assert_eq!(d.artboard_of(off), None); + let root: Vec = d.layers.iter().map(|l| l.id).collect(); + assert_eq!(root.iter().position(|x| *x == off), root.iter().position(|x| *x == board).map(|i| i + 1)); +} + +/// An artboard is never nested or clipped: a copied board goes beside the anchor's top-level +/// layer, even after a first copy went into a group, and never joins a clipping mask. +#[test] +fn artboards_stay_at_the_top_level_and_unclipped() { + let (mut s, a, b) = session(); + let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 8, 8]})).unwrap()); + s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap(); + let mut d = doc(&s).clone(); + let copy = d.layer(board).unwrap().duplicate(); + // On a clipping base: at the top level above its clipping mask (B keeps A as its base), not + // clipped. + let c = insert_new(&mut d, Some(a), copy.duplicate(), Place::Auto); + let root: Vec = d.layers.iter().map(|l| l.id).collect(); + let at = |id: LayerId| root.iter().position(|x| *x == id).unwrap(); + assert_eq!((at(b), at(c)), (at(a) + 1, at(a) + 2)); + assert!(!d.layer(c).unwrap().clipped); + // After a layer that went into an open group: beside the group, not inside it. + let g = insert_new(&mut d, Some(a), Layer::group("open", vec![]), Place::Above); + let first = Layer::raster("first", d.pixel_format()); + let first = insert_new(&mut d, Some(g), first, Place::Auto); + assert!(d.layer(g).unwrap().children().unwrap().iter().any(|l| l.id == first)); + let second = insert_new(&mut d, Some(first), copy, Place::Above); + assert!(d.layers.iter().any(|l| l.id == second), "the board is not nested in the group"); + assert_eq!(d.artboards().len(), 3); +} + +/// A copied clipped layer pasted into an empty group has nothing below it to clip to. +#[test] +fn a_clipped_layer_with_nothing_below_is_released() { + let (s, _, b) = session(); + let mut d = doc(&s).clone(); + let g = insert_new(&mut d, Some(b), Layer::group("empty", vec![]), Place::Auto); + let mut l = Layer::raster("was clipped", d.pixel_format()); + l.clipped = true; + let l = insert_new(&mut d, Some(g), l, Place::Auto); + assert!(d.layer(g).unwrap().children().unwrap().iter().any(|c| c.id == l)); + assert!(!d.layer(l).unwrap().clipped); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 43aeeefbe0..db75e97663 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -64,6 +64,7 @@ pub mod layer_mask_props_cmds; pub mod layer_menu_cmds; pub mod layer_multi_cmds; pub mod layer_nav_cmds; +pub mod layer_place; pub mod layer_style; pub mod lens_cmds; pub mod link_watch; diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rs index ca814e6d4c..8b9ed31464 100644 --- a/crates/engine/src/new_layer.rs +++ b/crates/engine/src/new_layer.rs @@ -24,7 +24,9 @@ pub fn neutral_color(mode: BlendMode) -> Option<([f32; 3], &'static str)> { } } -/// `layer.new.layer`: a pixel layer above the active one, joining the clip group it lands in. +/// `layer.new.layer`: a pixel layer where Photoshop puts a new one ([`crate::layer_place`]: above +/// the active layer, inside it when it is an open group, below it with `below`), joining the clip +/// group it lands in. pub fn run(s: &mut Session, p: &Value) -> Result { let flag = |k: &str| match p.get(k) { None | Some(Value::Null) => Ok(false), @@ -32,6 +34,7 @@ pub fn run(s: &mut Session, p: &Value) -> Result { }; let clip = flag("clipToPrevious")?; let fill_neutral = flag("fillNeutral")?; + let place = if flag("below")? { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto }; let mode = match p.get("mode") { None | Some(Value::Null) => BlendMode::Normal, Some(v) => { @@ -65,7 +68,7 @@ pub fn run(s: &mut Session, p: &Value) -> Result { let px = photocraft_raster::from_rgba(&surface.format(), [rgb[0], rgb[1], rgb[2], 1.0]); surface.fill_rect(bounds, &px); } - let id = doc.insert_above(*active, layer); + let id = crate::layer_place::insert_new(doc, *active, layer, place); crate::clip_group::settle(doc, &[id], &Default::default(), clip); *active = Some(id); Ok(id) diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rs index d58fd9e827..6c86420bc8 100644 --- a/crates/engine/src/pattern_cmds.rs +++ b/crates/engine/src/pattern_cmds.rs @@ -313,7 +313,7 @@ pub(crate) fn insert_fill_layer(doc: &mut Document, active: &mut Option Result { let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); let id = s.edit("New Gradient Fill Layer", |doc, active| { let fill = Fill::gradient(stops, angle, scale, style, reverse).in_mode(doc.mode); - let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill))); + let layer = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/render_cmds.rs b/crates/engine/src/render_cmds.rs index c6e4318e3d..e45e567f46 100644 --- a/crates/engine/src/render_cmds.rs +++ b/crates/engine/src/render_cmds.rs @@ -109,7 +109,7 @@ fn draw(s: &mut Session, label: &str, p: &Value, prims: Vec, extra: Value) let raster = id.and_then(|i| doc.layer(i)).is_some_and(|l| matches!(l.content, LayerContent::Raster(_))); let (id, created) = if want_new || !raster { let l = Layer::new(label.trim_end_matches('…'), LayerContent::Raster(Surface::new(doc.pixel_format()))); - let nid = doc.insert_above(*active, l); + let nid = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(nid); (nid, true) } else { diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/retouch_cmds/remove.rs index 4e256fb7fc..e1ad8af948 100644 --- a/crates/engine/src/retouch_cmds/remove.rs +++ b/crates/engine/src/retouch_cmds/remove.rs @@ -199,7 +199,8 @@ fn fill_to_new_layer(doc: &mut Document, id: Option, out: &Region, hole } let mut l = Layer::raster(doc.next_layer_name("Layer"), fmt); crate::pixels_mut(&mut l)?.write_region(out.rect, &data); - let nid = doc.insert_above(id, l); + // Above the sampled layer and in its clipping mask, like Layer via Copy. + let nid = crate::layer_place::insert_new(doc, id, l, crate::layer_place::Place::Above); Ok((out.rect, nid)) } diff --git a/crates/engine/src/stamp_cmds.rs b/crates/engine/src/stamp_cmds.rs index a525d138b5..a5fb00feb2 100644 --- a/crates/engine/src/stamp_cmds.rs +++ b/crates/engine/src/stamp_cmds.rs @@ -66,7 +66,7 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("there are no visible layers to stamp".into())); } let layer = stamp_layer(doc, doc.next_layer_name("Layer"))?; - let id = doc.insert_above(*active, layer); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; @@ -133,7 +133,7 @@ fn stamp_selected(s: &mut Session, sel: &[LayerId]) -> Result { } let name = format!("{} (merged)", doc.layer(top).map_or("Layer", |l| l.name.as_str())); let layer = stamp_layer(&solo, name)?; - let id = doc.insert_above(Some(top), layer); + let id = crate::layer_place::insert_new(doc, Some(top), layer, crate::layer_place::Place::Above); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 08e17bd39c..fbf5dd084b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1042,7 +1042,8 @@ fn move_selected_layers_keeps_selected_group_children_and_supports_above_below() let b = s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap(); let c = s.execute("layer.new.layer", json!({"name": "C"})).unwrap()["layer"].as_u64().unwrap(); let group = s.execute("layer.new.group", json!({"name": "G"})).unwrap()["layer"].as_u64().unwrap(); - // Made before B moves into G: a new group goes above the active layer, which would then be inside G. + // Made from C, not from G: like Photoshop a new group goes inside an open active group. + s.execute("layer.select", json!({"layer": c})).unwrap(); let target = s.execute("layer.new.group", json!({"name": "Target"})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.moveTo", json!({"layer": b, "target": group, "position": "into"})).unwrap(); diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index 4a4cb347bf..224111709e 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -723,7 +723,7 @@ pub fn specs() -> Vec { let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| layer_name(&t.text)); let id = s.edit("New Type Layer", |doc, active| { refresh(doc, &mut t); - let id = doc.insert_above(*active, Layer::new(name, LayerContent::Text(t))); + let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs index b732ff2629..ee38cce190 100644 --- a/crates/engine/src/vector_cmds.rs +++ b/crates/engine/src/vector_cmds.rs @@ -685,7 +685,7 @@ fn shape_create(s: &mut Session, p: &Value) -> Result { let id = s.edit("New Shape Layer", |doc, active| { refresh_shape(doc, &mut sh); let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind))); - let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh))); + let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Shape(sh)), crate::layer_place::Place::Auto); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rs index dbb51d82d2..21c75a123b 100644 --- a/crates/engine/src/video_cmds.rs +++ b/crates/engine/src/video_cmds.rs @@ -110,7 +110,7 @@ fn new_blank(s: &mut Session, _p: &Value) -> Result { let name = doc.next_layer_name("Video Layer"); let mut l = Layer::raster(name, fmt); l.video = Some(VideoData::new(frames, fps)); - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); sync(doc); Ok(id) @@ -304,7 +304,7 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result { v.original_frames = Some(v.frames.clone()); v.source = photocraft_doc::VideoSource::File { path: path.clone() }; l.video = Some(v); - let id = doc.insert_above(*active, l); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(id); sync(doc); Ok(id) @@ -373,12 +373,14 @@ fn frames_to_layers(s: &mut Session, p: &Value) -> Result { let n = frames.len(); s.edit("Video Frames to Layers", |doc, active| { let mut above = *active; + let mut place = crate::layer_place::Place::Auto; for (i, f) in frames.into_iter().enumerate() { let mut l = Layer::raster(format!("Frame {}", i + 1), fmt); if let LayerContent::Raster(surf) = &mut l.content { *surf = f; } - above = Some(doc.insert_above(above, l)); + above = Some(crate::layer_place::insert_new(doc, above, l, place)); + place = crate::layer_place::Place::Above; } *active = above; Ok(()) diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index 185930298a..014a13f4d0 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -140,7 +140,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { let target = s.edit("Vanishing Point", |doc: &mut Document, active| { let id = if new_layer { let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format()); - let nid = doc.insert_above(*active, l); + let nid = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); *active = Some(nid); nid } else { diff --git a/crates/engine/tests/layer_range_panel_order.rs b/crates/engine/tests/layer_range_panel_order.rs index 484d41edad..86b4ad81c8 100644 --- a/crates/engine/tests/layer_range_panel_order.rs +++ b/crates/engine/tests/layer_range_panel_order.rs @@ -20,9 +20,10 @@ fn shift_range_follows_visible_rows_on_both_sides_of_an_expanded_group() { select(&mut s, b, "replace"); select(&mut s, c, "add"); let group = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + // D goes above the closed group (an open one would take it inside, as in Photoshop). + let d = s.execute("layer.new.layer", json!({"name": "D"})).unwrap()["layer"].as_u64().unwrap(); // Group Layers makes a collapsed group, as in Photoshop; open it so B and C are visible rows. s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap(); - let d = s.execute("layer.new.layer", json!({"name": "D"})).unwrap()["layer"].as_u64().unwrap(); for (anchor, target, wanted) in [(d, group, vec![d, group]), (group, d, vec![d, group]), (group, b, vec![group, c, b]), (b, group, vec![group, c, b]), (c, b, vec![c, b])] diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rs index 5fd87393d3..2db876fd17 100644 --- a/crates/ui-egui/src/gradient_ui.rs +++ b/crates/ui-egui/src/gradient_ui.rs @@ -388,8 +388,9 @@ pub fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc if cmd == cmds::CREATE { let mut l = cmds::new_layer(&app.session, &doc, &p).ok()?; l.id = PREVIEW_LAYER; - let above = app.session.active().and_then(|s| s.active_layer); - shown.insert_above(above, l); + // Where the committed layer will go, so the preview doesn't jump on release. + let active = app.session.active().and_then(|s| s.active_layer); + photocraft_engine::layer_place::insert_new(&mut shown, active, l, photocraft_engine::layer_place::Place::Auto); } else { let l = doc.layer(layer)?; let f = edited_fill(app, l, doc.bounds(), cmd, &p)?; diff --git a/crates/ui-egui/src/layer_tree_ui/tests.rs b/crates/ui-egui/src/layer_tree_ui/tests.rs index f56fc6ccfb..2baa40e9f7 100644 --- a/crates/ui-egui/src/layer_tree_ui/tests.rs +++ b/crates/ui-egui/src/layer_tree_ui/tests.rs @@ -17,7 +17,7 @@ fn layered() -> photocraft_engine::Session { let inner = s.execute("layer.groupLayers", json!({"name": "inner"})).unwrap()["layer"].as_u64().unwrap(); let outer = s.execute("layer.groupLayers", json!({"layer": inner, "name": "outer"})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.select", json!({"layer": inner})).unwrap(); - // `layer.new.layer` lands above the active layer, inside `outer`. + // `layer.new.layer` lands above the active (closed) group `inner`, inside `outer`. s.execute("layer.new.layer", json!({"name": "in-outer"})).unwrap(); s.execute("layer.select", json!({"layer": outer})).unwrap(); s.execute("layer.new.layer", json!({"name": "top"})).unwrap(); diff --git a/crates/ui-egui/src/new_group_button_tests.rs b/crates/ui-egui/src/new_group_button_tests.rs index 8198c43e05..495d10be54 100644 --- a/crates/ui-egui/src/new_group_button_tests.rs +++ b/crates/ui-egui/src/new_group_button_tests.rs @@ -133,3 +133,18 @@ fn command_click_adds_an_empty_group_below_the_active_layer() { assert_eq!(top[1..], [a, groups[0].id, b]); } } + +/// Its neighbour, the New Layer button: ⌘-click adds the layer below the active one, a plain +/// click above it, as in Photoshop. +#[test] +fn command_click_on_new_layer_adds_it_below_the_active_layer() { + for (modifiers, below) in [(Modifiers::COMMAND, true), (Modifiers::NONE, false)] { + let (mut h, a, b) = selected(false); + h.get_by_label("Create a new layer").click_modifiers(modifiers); + h.run_steps(4); + let top: Vec = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(top.len(), 4); + let new = *top.iter().find(|id| ![a, b].contains(id) && **id != top[0]).unwrap(); + assert_eq!(top[1..], if below { [a, new, b] } else { [a, b, new] }); + } +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index c38354909a..78dc1d2ab0 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2339,9 +2339,17 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { trash.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(label))); let new_layer = icons::button(ui, "square-plus", 26.0, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer")); if new_layer.clicked() { - // A click makes the layer; ⌥-click asks first (the New Layer dialog), as in Photoshop. - let alt = ui.input(|i| i.modifiers.alt); - actions.push(("layer.new.layer".into(), if alt { Value::Null } else { json!({}) })); + // A click makes the layer; ⌥-click asks first (the New Layer dialog) and ⌘-click adds it + // below the active layer, as in Photoshop. + let m = ui.input(|i| i.modifiers); + let params = if m.alt { + Value::Null + } else if m.command { + json!({"below": true}) + } else { + json!({}) + }; + actions.push(("layer.new.layer".into(), params)); } actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate")); let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group")); diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs index a40886dd8d..4fc5930f10 100644 --- a/crates/ui-egui/src/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs @@ -21,13 +21,14 @@ fn realistic() -> photocraft_engine::Session { s.execute("file.new", json!({"width": 240, "height": 160})).unwrap(); s.execute("layer.new.layer", json!({"name": "in-group"})).unwrap(); s.execute("layer.groupLayers", json!({"name": "group"})).unwrap(); - // Group Layers makes a collapsed group; open it so the panel shows the layer inside. - s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello"})).unwrap(); let paint = s.execute("layer.new.layer", json!({"name": "paint"})).unwrap()["layer"].as_u64().unwrap(); s.execute("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 60})).unwrap(); s.execute("edit.fill", json!({"color": "#3070c0"})).unwrap(); s.execute("layer.select", json!({"layer": paint})).unwrap(); + // Group Layers makes a collapsed group; open it so the panel shows the layer inside. (Opened + // last: an open active group would take the new layers above inside it, as in Photoshop.) + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).unwrap(); s } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ba5bcca7b3..de8eee6b29 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (New Group dialog, ⌥/⌘-click New Group, groups from layers start collapsed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (new layers go into an open active group and join a clipping mask; ⌘-click New Layer) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -210,6 +210,9 @@ Paragraph; the rest open as in-app floating windows. | Layers panel New Group button: click with 2+ layers selected groups them (CC 2014+), ⇧-click groups, one layer gives an empty group, ⌥-click opens the New Group dialog, ⌘-click adds the group below the active layer | done | #2561, `new_group_button_tests.rs` | | New Group dialog (Name, Color, Mode, Opacity) for Layer › New › Group… / Group from Layers…, the Layers panel menu and the row menu; ⌘G stays immediate | done | `new_group_ui.rs`, `new_group_ui_tests.rs` | | Groups made from layers (⌘G, New Group button, Group from Layers) start collapsed; selecting a layer inside opens the group | done | `group_options.rs` tests, `new_group_button_tests.rs` | +| New layers (New Layer/Group, adjustment, fill, type, shape, paste, place…) go in as the top layer of an open active group (or an artboard the new content is on), above a closed one; a new frame starts closed | done | `layer_place.rs`, `layer_place_tests.rs` | +| A new layer or group inside a clipping mask joins it (clipped when the layer above its slot is), so the clipped layers keep their base | done | `layer_place_tests.rs` (#2203) | +| Layers panel New Layer button: ⌘-click adds the layer below the active one (never under the Background) | done | `layer_place_tests.rs`, `new_group_button_tests.rs` | ## Revision history @@ -217,6 +220,7 @@ Paragraph; the rest open as in-app floating windows. |---|---|---| | 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues | | 2026-10-12 | minor | New Group button groups two or more selected layers (CC 2014+); New Group dialog (Layer › New, Layers panel menu, row menu, ⌥-click); ⌘-click New Group adds the group below; groups made from layers start collapsed (#2561) | +| 2026-10-12 | minor | New layers go into an open active group (or the artboard their content is on) and join the clip group they land in (#2203); ⌘-click New Layer adds below | | 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions | | 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning | | 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) | From da13d0312c4d2b1874b44ae1bf1edba9ba46a22d Mon Sep 17 00:00:00 2001 From: Catur Sura Date: Wed, 14 Oct 2026 11:50:03 +0700 Subject: [PATCH 07/87] feat(transform): show distort and skew cursor indicators when holding ctrl --- crates/ui-egui/src/canvas.rs | 7 +- crates/ui-egui/src/transform_tool.rs | 194 ++++++++++++++++++++++++--- 2 files changed, 180 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c982dd9afa..871e2e1215 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3380,9 +3380,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }); if let Some((vertical, _)) = guide_hover { ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical }); - } else if let Some(c) = - response.hover_pos().and_then(|p| crate::transform_tool::cursor(app, xf.to_doc(p), ui.input(|i| i.modifiers.alt || i.modifiers.command))) - { + } else if let Some(c) = response.interact_pointer_pos().or_else(|| response.hover_pos()).and_then(|p| { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + crate::transform_tool::cursor(app, xf.to_doc(p), mods) + }) { ui.ctx().set_cursor_icon(c); } else if let Some(c) = response.hover_pos().and_then(|p| crate::cam_transform::cursor(app, &ctx, &xf, p)) { ui.ctx().set_cursor_icon(c); diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 6d1c22886a..b72a51a044 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -1828,11 +1828,11 @@ fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 { /// Where the rotate cursor's arc bends at document point `p`, or `None` outside the rotate zone: /// just outside a corner, or anywhere while a rotate drag is on. It points into the box along the /// bisector of the nearest corner, so each corner gets its own arrow and they turn with the box. -pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> { - rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app)) +pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> Option<[f64; 2]> { + rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app), mods) } -fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> { +fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64, mods: egui::Modifiers) -> Option<[f64; 2]> { // Content-Aware Scale's box only scales, and Skew doesn't rotate: no rotate arrow. if !(p[0].is_finite() && p[1].is_finite()) || t.warp.is_some() @@ -1842,6 +1842,9 @@ fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], return None; } let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); + if !rotating && mods.command { + return None; + } if !rotating && !near_rotate_corner(t, p, tol) { return None; } @@ -1858,9 +1861,9 @@ fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], (l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l]) } -/// Cursor for hovering a document point while transforming. `quick_split` is Ctrl or Option, -/// which arms a quick split while a warp is active. -pub fn cursor(app: &PhotocraftApp, p: [f64; 2], quick_split: bool) -> Option { +/// Cursor for hovering a document point while transforming. `mods` provides modifier keys +/// (Command for Distort on corners / Skew on edges; Alt/Command for quick split in warp). +pub fn cursor(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> Option { let t = app.ui.transform.as_ref()?; let tol = handle_tolerance(app); if let Some(w) = &t.warp { @@ -1870,7 +1873,7 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2], quick_split: bool) -> Option Option CursorIcon::None, Hit::Corner(0 | 2) => CursorIcon::ResizeNwSe, Hit::Corner(_) => CursorIcon::ResizeNeSw, + Hit::Edge(_) if skew_armed => CursorIcon::None, Hit::Edge(0 | 2) => CursorIcon::ResizeVertical, Hit::Edge(_) => CursorIcon::ResizeHorizontal, Hit::Pivot => CursorIcon::Crosshair, @@ -1897,6 +1906,56 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2], quick_split: bool) -> Option 1e-6 { toward / len } else { vec2(-1.0, -1.0).normalized() }; + let perp = vec2(-u.y, u.x); + let tokens = crate::theme::Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("transform-distort-cursor"))); + + // An arrowhead dart pointing along `u` with tip at `at`. + let tip = at; + const LENGTH: f32 = 16.0; + const HALF_WIDTH: f32 = 7.0; + let base = tip - u * LENGTH; + let left = base + perp * HALF_WIDTH; + let right = base - perp * HALF_WIDTH; + let notch = tip - u * (LENGTH * 0.65); + + // Convex decomposition: two triangles meeting along [tip, notch]. + painter.add(egui::Shape::convex_polygon(vec![tip, left, notch], tokens.accent_text, Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(vec![tip, notch, right], tokens.accent_text, Stroke::NONE)); + painter.add(egui::Shape::closed_line(vec![tip, left, notch, right], Stroke::new(1.5, tokens.shadow))); +} + +/// Draws the Skew cursor at `at`: opposing parallel arrows aligned with the edge tangent `tangent`. +pub fn draw_skew_cursor(ctx: &egui::Context, at: Pos2, tangent: egui::Vec2) { + let len = tangent.length(); + let u = if len.is_finite() && len > 1e-6 { tangent / len } else { vec2(1.0, 0.0) }; + let perp = vec2(-u.y, u.x); + let tokens = crate::theme::Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("transform-skew-cursor"))); + + for (offset, dir) in [(4.0f32, 1.0f32), (-4.0f32, -1.0f32)] { + let center = at + perp * offset; + let p_start = center - u * (dir * 9.0); + let p_end = center + u * (dir * 9.0); + painter.line_segment([p_start, p_end], Stroke::new(3.5, tokens.shadow)); + painter.line_segment([p_start, p_end], Stroke::new(1.5, tokens.accent_text)); + + let tip = p_end + u * (dir * 3.5); + let wing1 = p_end - u * (dir * 2.5) + perp * 3.5; + let wing2 = p_end - u * (dir * 2.5) - perp * 3.5; + painter.add(egui::Shape::convex_polygon( + vec![tip, wing1, wing2], + tokens.accent_text, + Stroke::new(1.0, tokens.shadow), + )); + } +} + /// Warped preview of the moving pixels plus the box, handles and reference point. pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; @@ -1968,10 +2027,30 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform painter.circle_stroke(c, 5.0, Stroke::new(0.5, Color32::BLACK)); painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::WHITE)); painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE)); - if let Some(at) = painter.ctx().pointer_hover_pos().filter(|p| xf.rect.contains(*p)) { + if let Some(at) = painter.ctx().input(|i| i.pointer.interact_pos().or(i.pointer.hover_pos())).filter(|p| xf.rect.contains(*p)) { let p = xf.to_doc(at); let tol = HANDLE_PX / f64::from(xf.zoom.max(0.01)); - if let Some(k) = rotate_dir(t, Some(pv), p, tol) { + let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); + let active_hit = pv.gesture.map(|g| g.hit); + let h = active_hit.unwrap_or_else(|| hit(t, p, tol)); + let distort_armed = (mods.command || t.mode == TransformMode::Distort) && !distort_refused(app, t) && t.content_aware.is_none(); + let skew_armed = (mods.command || t.mode == TransformMode::Skew) && t.content_aware.is_none(); + + if let Hit::Corner(i) = h + && distort_armed + { + let corner_scr = scr(t.quad[i]); + let pivot_scr = scr(t.pivot); + let toward = corner_scr - pivot_scr; + draw_distort_cursor(painter.ctx(), at, toward); + } else if let Hit::Edge(i) = h + && skew_armed + { + let a_scr = scr(t.quad[i]); + let b_scr = scr(t.quad[(i + 1) % 4]); + let tangent = b_scr - a_scr; + draw_skew_cursor(painter.ctx(), at, tangent); + } else if let Some(k) = rotate_dir(t, Some(pv), p, tol, mods) { // Through the view, so the arc bends round the corner as it shows under a turned or // flipped view. let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; @@ -3688,13 +3767,13 @@ mod tests { let tol = handle_tolerance(&app); let h = std::f64::consts::FRAC_1_SQRT_2; let (tl, br) = ([32.0 - tol * 1.5, 32.0 - tol * 1.5], [160.0 + tol * 1.5, 160.0 + tol * 1.5]); - assert_eq!(cursor(&app, tl, false), Some(CursorIcon::None), "the arrow is drawn instead"); - assert!(near2(rotate_cursor_dir(&app, tl), [h, h]), "{:?}", rotate_cursor_dir(&app, tl)); - assert!(near2(rotate_cursor_dir(&app, br), [-h, -h]), "bends round the bottom-right corner"); - assert_eq!(cursor(&app, [60.0, 60.0], false), Some(CursorIcon::Move)); - assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0]), None, "inside moves"); - assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0]), None, "the corner handle scales"); - assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0]), None); + assert_eq!(cursor(&app, tl, egui::Modifiers::NONE), Some(CursorIcon::None), "the arrow is drawn instead"); + assert!(near2(rotate_cursor_dir(&app, tl, egui::Modifiers::NONE), [h, h]), "{:?}", rotate_cursor_dir(&app, tl, egui::Modifiers::NONE)); + assert!(near2(rotate_cursor_dir(&app, br, egui::Modifiers::NONE), [-h, -h]), "bends round the bottom-right corner"); + assert_eq!(cursor(&app, [60.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::Move)); + assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0], egui::Modifiers::NONE), None, "inside moves"); + assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0], egui::Modifiers::NONE), None, "the corner handle scales"); + assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0], egui::Modifiers::NONE), None); } /// #1767: the readout beside the pointer during a drag (Photoshop's transformation values): @@ -4476,4 +4555,83 @@ mod tests { assert!(matches!(&st.doc.layer(st.active_layer.unwrap()).unwrap().content, LayerContent::Text(t) if t.warp.is_none())); assert_eq!(past(&app), before + 2); } + + #[test] + fn hovering_corner_with_ctrl_shows_distort_cursor() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let tol = handle_tolerance(&app); + let corner = [32.0, 32.0]; + let mut command = egui::Modifiers::NONE; + command.command = true; + + // Without Ctrl: corner handle gives standard diagonal scale cursor. + assert_eq!(cursor(&app, corner, egui::Modifiers::NONE), Some(CursorIcon::ResizeNwSe)); + + // With Ctrl: corner handle arms free distort, hiding OS cursor so custom pointer is drawn. + assert_eq!(cursor(&app, corner, command), Some(CursorIcon::None)); + + // Holding Ctrl suppresses rotation around corners. + let near_corner = [32.0 - tol * 1.5, 32.0 - tol * 1.5]; + assert_eq!(rotate_cursor_dir(&app, near_corner, command), None); + assert!(rotate_cursor_dir(&app, near_corner, egui::Modifiers::NONE).is_some()); + } + + #[test] + fn hovering_edge_with_ctrl_shows_skew_cursor() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let edge = [96.0, 32.0]; // top edge midpoint + let mut command = egui::Modifiers::NONE; + command.command = true; + + // Without Ctrl: edge handle gives axis resize cursor. + assert_eq!(cursor(&app, edge, egui::Modifiers::NONE), Some(CursorIcon::ResizeVertical)); + + // With Ctrl: edge handle arms skew, hiding OS cursor so custom skew indicator is drawn. + assert_eq!(cursor(&app, edge, command), Some(CursorIcon::None)); + } + + #[test] + fn hovering_corner_on_text_layer_with_ctrl_retains_resize_cursor() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.run("type.create", json!({"x": 10, "y": 60, "text": "Hello"})).unwrap(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + + let t = app.ui.transform.as_ref().unwrap(); + let corner = t.quad[0]; + let mut command = egui::Modifiers::NONE; + command.command = true; + + // Editable type refuses distort, so holding Ctrl retains standard resize cursor on corners. + let c = cursor(&app, corner, command); + assert!( + matches!(c, Some(CursorIcon::ResizeNwSe | CursorIcon::ResizeNeSw)), + "text layer must retain resize cursor, got: {:?}", + c + ); + } + + #[test] + fn cursor_during_drag_stays_stable() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let mut command = egui::Modifiers::NONE; + command.command = true; + + // Start dragging corner [32.0, 32.0] with Command held. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, command); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 60.0, pressure: 1.0 }, command); + + // While dragging, cursor anywhere stays CursorIcon::None (distort custom cursor). + assert_eq!(cursor(&app, [50.0, 60.0], command), Some(CursorIcon::None)); + assert_eq!(cursor(&app, [200.0, 200.0], command), Some(CursorIcon::None)); + + // Release drag + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 60.0 }, command); + } } From bcc694b8a350bf4f72fcbea6cf6278adb0976da8 Mon Sep 17 00:00:00 2001 From: Catur Sura Date: Thu, 15 Oct 2026 10:37:24 +0700 Subject: [PATCH 08/87] fix(transform): restore front_vertices and clean up rotate cursor suppression --- crates/ui-egui/src/canvas.rs | 13 ++++++---- crates/ui-egui/src/transform_tool.rs | 36 ++++++++++++++++------------ 2 files changed, 29 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e38942008b..eaf6d00f2a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3699,15 +3699,18 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }); if let Some((vertical, _)) = guide_hover { ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical }); - } else if let Some(c) = response.interact_pointer_pos().or_else(|| response.hover_pos()).and_then(|p| { - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - crate::transform_tool::cursor(app, xf.to_doc(p), mods) - }) { + } else if let Some(p) = response.interact_pointer_pos().or_else(|| response.hover_pos()) + && let Some(c) = { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + crate::transform_tool::cursor(app, xf.to_doc(p), mods) + } + { ui.ctx().set_cursor_icon(c); // CursorIcon::None hides the pointer; the curved arrow has to be drawn or the // rotate zone looks like a plain cursor (#4050). let d = xf.to_doc(p); - if let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + if !mods.command && let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; crate::crop_ui::draw_turn_cursor(&ctx, p, toward); } diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 8a6b946a5e..8ca8c7c341 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -1967,11 +1967,11 @@ fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 { /// Where the rotate cursor's arc bends at document point `p`, or `None` outside the rotate zone: /// just outside a corner, or anywhere while a rotate drag is on. It points into the box along the /// bisector of the nearest corner, so each corner gets its own arrow and they turn with the box. -pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> Option<[f64; 2]> { - rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app), mods) +pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> { + rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app)) } -fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64, mods: egui::Modifiers) -> Option<[f64; 2]> { +fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> { // Content-Aware Scale's box only scales, and Skew doesn't rotate: no rotate arrow. if !(p[0].is_finite() && p[1].is_finite()) || t.warp.is_some() @@ -1981,9 +1981,6 @@ fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], return None; } let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); - if !rotating && mods.command { - return None; - } if !rotating && !near_rotate_corner(t, p, tol) { return None; } @@ -2025,7 +2022,7 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> Option if !mode_allows(t.mode, h) || (t.content_aware.is_some() && h == Hit::Outside) { return Some(CursorIcon::Default); } - if rotate_cursor_dir(app, p, mods).is_some() { + if !mods.command && rotate_cursor_dir(app, p).is_some() { // The overlay draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. return Some(CursorIcon::None); } @@ -2095,6 +2092,15 @@ pub fn draw_skew_cursor(ctx: &egui::Context, at: Pos2, tangent: egui::Vec2) { } } +/// For each vertex of the preview's `n` × `n` grid over the unit square (row by row), whether it +/// maps to the front side of `h`'s horizon. A Distort dragged past the horizon sends the rest of +/// the image to the far side, where its cells would wrap round infinity; the preview leaves them +/// out, as the committed warp does (#4863). +fn front_vertices(h: &Homography, n: usize) -> Vec { + let front = h.front_side([0.0, 0.0, 1.0, 1.0]); + (0..=n).flat_map(|j| (0..=n).map(move |i| (i as f64 / n as f64, j as f64 / n as f64))).map(|(u, v)| front * h.w(u, v) > 1e-9).collect() +} + /// Warped preview of the moving pixels plus the box, handles and reference point. pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; @@ -2207,7 +2213,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform let b_scr = scr(t.quad[(i + 1) % 4]); let tangent = b_scr - a_scr; draw_skew_cursor(painter.ctx(), at, tangent); - } else if let Some(k) = rotate_dir(t, Some(pv), p, tol, mods) { + } else if !mods.command && let Some(k) = rotate_dir(t, Some(pv), p, tol) { // Through the view, so the arc bends round the corner as it shows under a turned or // flipped view. let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; @@ -4154,12 +4160,12 @@ mod tests { let h = std::f64::consts::FRAC_1_SQRT_2; let (tl, br) = ([32.0 - tol * 1.5, 32.0 - tol * 1.5], [160.0 + tol * 1.5, 160.0 + tol * 1.5]); assert_eq!(cursor(&app, tl, egui::Modifiers::NONE), Some(CursorIcon::None), "the arrow is drawn instead"); - assert!(near2(rotate_cursor_dir(&app, tl, egui::Modifiers::NONE), [h, h]), "{:?}", rotate_cursor_dir(&app, tl, egui::Modifiers::NONE)); - assert!(near2(rotate_cursor_dir(&app, br, egui::Modifiers::NONE), [-h, -h]), "bends round the bottom-right corner"); + assert!(near2(rotate_cursor_dir(&app, tl), [h, h]), "{:?}", rotate_cursor_dir(&app, tl)); + assert!(near2(rotate_cursor_dir(&app, br), [-h, -h]), "bends round the bottom-right corner"); assert_eq!(cursor(&app, [60.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::Move)); - assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0], egui::Modifiers::NONE), None, "inside moves"); - assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0], egui::Modifiers::NONE), None, "the corner handle scales"); - assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0], egui::Modifiers::NONE), None); + assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0]), None, "inside moves"); + assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0]), None, "the corner handle scales"); + assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0]), None); } /// #1767: the readout beside the pointer during a drag (Photoshop's transformation values): @@ -5020,8 +5026,8 @@ mod tests { // Holding Ctrl suppresses rotation around corners. let near_corner = [32.0 - tol * 1.5, 32.0 - tol * 1.5]; - assert_eq!(rotate_cursor_dir(&app, near_corner, command), None); - assert!(rotate_cursor_dir(&app, near_corner, egui::Modifiers::NONE).is_some()); + assert_eq!(cursor(&app, near_corner, command), Some(CursorIcon::Alias)); + assert_eq!(cursor(&app, near_corner, egui::Modifiers::NONE), Some(CursorIcon::None)); } #[test] From e11e296944af21db5eaccb232820a7835032cb20 Mon Sep 17 00:00:00 2001 From: D-monized Date: Fri, 16 Oct 2026 02:18:41 -0600 Subject: [PATCH 09/87] Font menu: favourites, recent fonts, class and similar-font filters, live preview MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The font menu gains Photoshop's local font library and filters (everything but Adobe Fonts): - Favourites: a star on every row (never picks the font) and a favourites-only filter. Kept in the preferences (type.favoriteFonts). - Recent fonts: up to five, most recent first, above a divider. Wires the dead Preferences > Type > Recent Fonts (now 0..5, default 5; older saved values are capped on load). - Class list: All Classes, Serif, Slab Serif, Sans Serif, Script, Monospace, Handwritten, Blackletter, Decorative, read from each font's OS/2 sFamilyClass, PANOSE and post tables (photocraft_text::font_class), else its name. Fonts that state nothing stay unclassified. - Show Variable Fonts, Show Similar Fonts (PANOSE/class/weight distance to the current font) and Clear All; the class list collapses with «. - Each row: style expander (">") that picks a family in a given style, and an O / TT / VAR format badge. - A preview at the top sets the type layer's own text (or the selection being typed) in the font under the pointer. - The search field and filters stay fixed while only the list scrolls, and the search field lines up with the font list. Commands: type.font.favorite, type.font.noteRecent, type.font.clearRecent, type.font.library. Two original icons (font-similar, font-variable). Co-Authored-By: Claude Opus 5.5 --- ATTRIBUTION.md | 3 +- assets/icons/font-similar.svg | 14 + assets/icons/font-variable.svg | 16 + crates/engine/src/commands.rs | 1 + crates/engine/src/font_library_cmds.rs | 166 +++++++++ crates/engine/src/font_library_cmds/tests.rs | 103 ++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/prefs.rs | 19 +- crates/text/src/font_class.rs | 286 +++++++++++++++ crates/text/src/fonts.rs | 24 ++ crates/text/src/lib.rs | 2 + crates/ui-egui/src/font_filters.rs | 277 ++++++++++++++ crates/ui-egui/src/font_preview.rs | 38 ++ crates/ui-egui/src/i18n/cs.tsv | 28 ++ crates/ui-egui/src/i18n/de.tsv | 28 ++ crates/ui-egui/src/i18n/el.tsv | 28 ++ crates/ui-egui/src/i18n/es.tsv | 28 ++ crates/ui-egui/src/i18n/fr.tsv | 28 ++ crates/ui-egui/src/i18n/hu.tsv | 28 ++ crates/ui-egui/src/i18n/id.tsv | 28 ++ crates/ui-egui/src/i18n/it.tsv | 28 ++ crates/ui-egui/src/i18n/ja.tsv | 28 ++ crates/ui-egui/src/i18n/ko.tsv | 28 ++ crates/ui-egui/src/i18n/nl.tsv | 28 ++ crates/ui-egui/src/i18n/pl.tsv | 28 ++ crates/ui-egui/src/i18n/pt-br.tsv | 28 ++ crates/ui-egui/src/i18n/ru.tsv | 28 ++ crates/ui-egui/src/i18n/sr.tsv | 28 ++ crates/ui-egui/src/i18n/tr.tsv | 28 ++ crates/ui-egui/src/i18n/uk.tsv | 28 ++ crates/ui-egui/src/i18n/vi.tsv | 28 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 28 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 28 ++ crates/ui-egui/src/icon_data.rs | 3 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/type_font_picker_tests.rs | 256 +++++++++++++ crates/ui-egui/src/type_panels_ui.rs | 22 +- crates/ui-egui/src/type_tool.rs | 362 ++++++++++++++++--- docs/scorecard.md | 6 +- 39 files changed, 2097 insertions(+), 63 deletions(-) create mode 100644 assets/icons/font-similar.svg create mode 100644 assets/icons/font-variable.svg create mode 100644 crates/engine/src/font_library_cmds.rs create mode 100644 crates/engine/src/font_library_cmds/tests.rs create mode 100644 crates/text/src/font_class.rs create mode 100644 crates/ui-egui/src/font_filters.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 227aee8ac9..1f585f312d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -26,10 +26,11 @@ next to them. | `crates/ui-egui/src/i18n/sr.tsv` | Serbian (Latin, Ekavian) UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) | | `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`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.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` (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`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.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` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | diff --git a/assets/icons/font-similar.svg b/assets/icons/font-similar.svg new file mode 100644 index 0000000000..e2399f7ab0 --- /dev/null +++ b/assets/icons/font-similar.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/font-variable.svg b/assets/icons/font-variable.svg new file mode 100644 index 0000000000..4415bcd32a --- /dev/null +++ b/assets/icons/font-variable.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index a32c5feb8d..f05b73bf36 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -1309,6 +1309,7 @@ fn build() -> Vec { v.extend(crate::distort_cmds::specs()); v.extend(crate::analysis_cmds::specs()); v.extend(crate::notes_cmds::specs()); + v.extend(crate::font_library_cmds::specs()); v.extend(crate::history_cmds::specs()); v.extend(crate::history_select_cmds::specs()); v.extend(crate::proof_sim::specs()); diff --git a/crates/engine/src/font_library_cmds.rs b/crates/engine/src/font_library_cmds.rs new file mode 100644 index 0000000000..6e466a3edf --- /dev/null +++ b/crates/engine/src/font_library_cmds.rs @@ -0,0 +1,166 @@ +//! The font menu's local library: favourite font families (the star beside each font, kept until +//! un-starred) and recently used ones (most recent first, at most +//! [`MAX_RECENT_FONTS`] and fewer when Preferences ▸ Type ▸ Number of Recent Fonts says so). Both +//! live in the preferences, so they survive a restart, and are plain family names: a favourite +//! whose font is uninstalled stays listed until removed, as in Photoshop. + +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +/// The most recent fonts the font menu lists. +pub const MAX_RECENT_FONTS: u32 = 5; +/// The most favourites kept (a hand-edited preferences file can't grow the menu without bound). +pub const MAX_FAVORITE_FONTS: usize = 1000; +/// The longest family name accepted, in characters. +const MAX_FAMILY_CHARS: usize = 256; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +/// The `family` param: a non-empty name without control characters, trimmed. +fn family(p: &Value, cmd: &str) -> Result { + let name = p.get("family").and_then(Value::as_str).ok_or_else(|| bad(cmd, "pass `family`, a font family name"))?.trim(); + if name.is_empty() { + return Err(bad(cmd, "`family` is empty")); + } + if name.chars().count() > MAX_FAMILY_CHARS { + return Err(bad(cmd, format!("`family` is longer than {MAX_FAMILY_CHARS} characters"))); + } + if name.chars().any(char::is_control) { + return Err(bad(cmd, "`family` contains control characters")); + } + Ok(name.to_string()) +} + +/// How many recent fonts are kept: the preference, capped at [`MAX_RECENT_FONTS`]. +pub fn recent_capacity(s: &Session) -> usize { + s.prefs().type_.recent_fonts.min(MAX_RECENT_FONTS) as usize +} + +/// The recent fonts as the menu shows them: valid names, once each, at most the capacity. +pub fn recent_fonts(s: &Session) -> Vec { + let mut out: Vec = Vec::new(); + for f in &s.prefs().type_.recent_font_list { + if out.len() >= recent_capacity(s) { + break; + } + if !f.trim().is_empty() && !out.contains(f) { + out.push(f.clone()); + } + } + out +} + +/// The favourites as the menu shows them: valid names, once each, at most [`MAX_FAVORITE_FONTS`]. +pub fn favorite_fonts(s: &Session) -> Vec { + let mut out: Vec = Vec::new(); + for f in &s.prefs().type_.favorite_fonts { + if out.len() >= MAX_FAVORITE_FONTS { + break; + } + if !f.trim().is_empty() && !out.contains(f) { + out.push(f.clone()); + } + } + out +} + +/// Star or un-star a family (`on` sets it; without it the star toggles). +fn favorite(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "type.font.favorite"; + let name = family(p, CMD)?; + let mut list = favorite_fonts(s); + let on = match p.get("on") { + None => !list.contains(&name), + Some(v) => v.as_bool().ok_or_else(|| bad(CMD, "`on` must be true or false"))?, + }; + list.retain(|f| *f != name); + if on { + if list.len() >= MAX_FAVORITE_FONTS { + return Err(bad(CMD, format!("at most {MAX_FAVORITE_FONTS} favourite fonts"))); + } + list.push(name.clone()); + } + let stored = list.clone(); + s.prefs.edit(|p| p.type_.favorite_fonts = stored); + Ok(json!({"family": name, "favorite": on, "favorites": list})) +} + +/// Record a family as just used: it moves to the front of the recent list. +fn note_recent(s: &mut Session, p: &Value) -> Result { + let name = family(p, "type.font.noteRecent")?; + let cap = recent_capacity(s); + let mut list = recent_fonts(s); + list.retain(|f| *f != name); + if cap > 0 { + list.insert(0, name); + } + list.truncate(cap); + let stored = list.clone(); + s.prefs.edit(|p| p.type_.recent_font_list = stored); + Ok(json!({"recent": list})) +} + +fn clear_recent(s: &mut Session, _: &Value) -> Result { + s.prefs.edit(|p| p.type_.recent_font_list.clear()); + Ok(json!({"recent": []})) +} + +fn library(s: &mut Session, _: &Value) -> Result { + Ok(json!({"recent": recent_fonts(s), "favorites": favorite_fonts(s), "recentCapacity": recent_capacity(s)})) +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "type.font.favorite", + label: "Add to Favorites", + menu: &[], + shortcut: None, + params: r#"{"family":str,"on":bool?=toggle} → family, favorite, favorites"#, + enabled: always, + run: favorite, + journal: true, + }, + CommandSpec { + id: "type.font.noteRecent", + label: "Note Recent Font", + menu: &[], + shortcut: None, + params: r#"{"family":str} → recent (most recent first, at most 5)"#, + enabled: always, + run: note_recent, + journal: true, + }, + CommandSpec { + id: "type.font.clearRecent", + label: "Clear Recent Font List", + menu: &[], + shortcut: None, + params: "{}", + enabled: always, + run: clear_recent, + journal: true, + }, + CommandSpec { + id: "type.font.library", + label: "Font Library", + menu: &[], + shortcut: None, + params: "{} → recent, favorites, recentCapacity", + enabled: always, + run: library, + journal: false, + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/font_library_cmds/tests.rs b/crates/engine/src/font_library_cmds/tests.rs new file mode 100644 index 0000000000..46198af387 --- /dev/null +++ b/crates/engine/src/font_library_cmds/tests.rs @@ -0,0 +1,103 @@ +use serde_json::json; + +use super::*; + +fn session() -> Session { + Session::new() +} + +#[test] +fn starring_toggles_and_on_sets_a_favourite() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap(); + assert_eq!(favorite_fonts(&s), ["Arial", "Bebas Neue"]); + // Toggling again removes it; `on` sets it either way. + let r = s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + assert_eq!(r["favorite"], false); + s.execute("type.font.favorite", json!({"family": "Bebas Neue", "on": true})).unwrap(); + assert_eq!(favorite_fonts(&s), ["Bebas Neue"], "on: true doesn't duplicate"); + s.execute("type.font.favorite", json!({"family": "Bebas Neue", "on": false})).unwrap(); + assert!(favorite_fonts(&s).is_empty()); +} + +#[test] +fn recent_fonts_are_most_recent_first_once_each_and_at_most_five() { + let mut s = session(); + assert_eq!(recent_capacity(&s), 5, "the default keeps five"); + for f in ["A", "B", "C", "D", "E", "F", "B"] { + s.execute("type.font.noteRecent", json!({"family": f})).unwrap(); + } + assert_eq!(recent_fonts(&s), ["B", "F", "E", "D", "C"]); + // A larger preference (an older default of 10, or a hand-edited file) still keeps five. + s.prefs.edit(|p| p.type_.recent_fonts = 50); + s.execute("type.font.noteRecent", json!({"family": "G"})).unwrap(); + assert_eq!(recent_fonts(&s).len(), 5); + // Fewer when the preference asks; 0 keeps none. + s.prefs.edit(|p| p.type_.recent_fonts = 2); + assert_eq!(recent_fonts(&s), ["G", "B"]); + s.prefs.edit(|p| p.type_.recent_fonts = 0); + s.execute("type.font.noteRecent", json!({"family": "H"})).unwrap(); + assert!(recent_fonts(&s).is_empty()); + s.prefs.edit(|p| p.type_.recent_fonts = 5); + s.execute("type.font.noteRecent", json!({"family": "H"})).unwrap(); + s.execute("type.font.clearRecent", json!({})).unwrap(); + assert!(recent_fonts(&s).is_empty()); +} + +#[test] +fn the_library_survives_a_preferences_round_trip_and_hostile_lists_are_tidied() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + s.execute("type.font.noteRecent", json!({"family": "Courier"})).unwrap(); + let saved = serde_json::to_value(s.prefs()).unwrap(); + assert_eq!(saved["type"]["favoriteFonts"], json!(["Arial"])); + assert_eq!(saved["type"]["recentFontList"], json!(["Courier"])); + let mut t = session(); + let prefs = serde_json::from_value(saved).unwrap(); + t.prefs.edit(|p| *p = prefs); + let lib = t.execute("type.font.library", json!({})).unwrap(); + assert_eq!(lib, json!({"recent": ["Courier"], "favorites": ["Arial"], "recentCapacity": 5})); + // Duplicates, blanks and an oversized list from a hand-edited file are tidied on read. + t.prefs.edit(|p| { + p.type_.favorite_fonts = (0..5000).map(|i| format!("F{}", i % 1200)).chain([String::new()]).collect(); + p.type_.recent_font_list = vec!["X".into(), "X".into(), " ".into(), "Y".into()]; + }); + assert_eq!(favorite_fonts(&t).len(), MAX_FAVORITE_FONTS); + assert_eq!(recent_fonts(&t), ["X", "Y"]); +} + +#[test] +fn an_older_recent_fonts_count_loads_capped_and_saving_still_works() { + let mut s = session(); + let mut saved = serde_json::to_value(s.prefs()).unwrap(); + saved["type"]["recentFonts"] = json!(10); + s.load_prefs_json(&saved.to_string()).unwrap(); + assert_eq!(s.prefs().type_.recent_fonts, MAX_RECENT_FONTS); + // The whole Type section saves back through the range check. + let ty = serde_json::to_value(s.prefs()).unwrap()["type"].clone(); + let values: serde_json::Map = + ty.as_object().unwrap().iter().filter(|(_, v)| !v.is_array()).map(|(k, v)| (format!("type.{k}"), v.clone())).collect(); + s.execute("prefs.set", json!({ "values": values })).unwrap(); + assert!(s.execute("prefs.set", json!({"values": {"type.recentFonts": 6}})).is_err(), "more than five is refused"); +} + +#[test] +fn bad_params_are_errors_and_change_nothing() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap(); + for (id, p) in [ + ("type.font.favorite", json!({})), + ("type.font.favorite", json!({"family": 42})), + ("type.font.favorite", json!({"family": " "})), + ("type.font.favorite", json!({"family": "a\u{0}b"})), + ("type.font.favorite", json!({"family": "x".repeat(300)})), + ("type.font.favorite", json!({"family": "Arial", "on": "yes"})), + ("type.font.noteRecent", json!({"family": null})), + ("type.font.noteRecent", json!({"family": ["Arial"]})), + ] { + assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); + } + assert_eq!(favorite_fonts(&s), ["Arial"]); + assert!(recent_fonts(&s).is_empty()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ff3cde6e4c..8dd92adddd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ pub mod fill_key_cmds; pub mod filters; pub mod filters_ext; pub mod float_cmds; +pub mod font_library_cmds; mod frame_cmds; pub mod fx_view_cmds; pub mod fx_visibility_cmds; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5e728cb546..ef89da86da 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -859,7 +859,14 @@ pub struct TypePrefs { pub text_engine: TextEngine, pub font_preview: FontPreview, pub fill_new_type_layers_with_placeholder: bool, + /// Number of Recent Fonts to Display: how many recently used families the font menu lists + /// at its top (at most `font_library_cmds::MAX_RECENT_FONTS`; 0 shows none). pub recent_fonts: u32, + /// Recently used font families, most recent first (`type.font.noteRecent`). + pub recent_font_list: Vec, + /// Favourite font families, starred in the font menu (`type.font.favorite`), in the order + /// they were added. + pub favorite_fonts: Vec, } impl Default for TypePrefs { @@ -872,7 +879,9 @@ impl Default for TypePrefs { text_engine: TextEngine::WorldReady, font_preview: FontPreview::Medium, fill_new_type_layers_with_placeholder: true, - recent_fonts: 10, + recent_fonts: crate::font_library_cmds::MAX_RECENT_FONTS, + recent_font_list: Vec::new(), + favorite_fonts: Vec::new(), } } } @@ -1068,7 +1077,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "plugIns.allowScriptsToConnect", "plugIns.generatorEnabled", "type.textEngine", - "type.recentFonts", "enhancedControls.scrubbySliderAcceleration", "enhancedControls.touchGestures", "rawDefaults.colorSpace", @@ -1150,7 +1158,7 @@ pub fn range(path: &str) -> Option<(f64, f64)> { "unitsAndRulers.printResolution" | "unitsAndRulers.screenResolution" | "rawDefaults.resolution" => (1.0, 10_000.0), "guidesGridAndSlices.gridlineEvery" => (0.001, 10_000.0), "guidesGridAndSlices.subdivisions" => (1.0, 100.0), - "type.recentFonts" => (0.0, 50.0), + "type.recentFonts" => (0.0, crate::font_library_cmds::MAX_RECENT_FONTS as f64), "integrations.controlPort" => (0.0, 65535.0), _ => return None, }) @@ -1557,7 +1565,10 @@ impl Session { } let color = v.as_object_mut().and_then(|m| m.remove("colorSettings")); let presets = v.as_object_mut().and_then(|m| m.remove("presets")); - let prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?; + let mut prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?; + // Recent Fonts was 0..50 (default 10) before the font menu listed at most five: a value + // saved then would fail `prefs.set`'s range check when the dialog saves. + prefs.type_.recent_fonts = prefs.type_.recent_fonts.min(crate::font_library_cmds::MAX_RECENT_FONTS); if let Some(c) = color { self.color.settings = serde_json::from_value(c).unwrap_or_default(); photocraft_compose::psblend::set_text_gamma(self.color.settings.blend_text_gamma); diff --git a/crates/text/src/font_class.rs b/crates/text/src/font_class.rs new file mode 100644 index 0000000000..ccdef3576e --- /dev/null +++ b/crates/text/src/font_class.rs @@ -0,0 +1,286 @@ +//! What a font menu filters and sorts by: a family's classification (Serif, Sans Serif, Script…), +//! its outline format and whether it is variable, read from the font's own tables (OS/2 +//! `sFamilyClass` and PANOSE, `post.isFixedPitch`, `fvar`, `CFF `/`glyf`) and, where those say +//! nothing, from its name. Photoshop's font menu offers the same classes. + +use skrifa::raw::{FontRef, TableProvider}; + +/// A family's classification, as the font menu's class filter lists them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum FontClass { + Serif, + SlabSerif, + SansSerif, + Script, + Monospace, + Handwritten, + Blackletter, + Decorative, +} + +impl FontClass { + /// Every class, in menu order. + pub const ALL: [FontClass; 8] = [ + FontClass::Serif, + FontClass::SlabSerif, + FontClass::SansSerif, + FontClass::Script, + FontClass::Monospace, + FontClass::Handwritten, + FontClass::Blackletter, + FontClass::Decorative, + ]; + + /// The English menu label (translated by the UI). + pub fn label(self) -> &'static str { + match self { + FontClass::Serif => "Serif", + FontClass::SlabSerif => "Slab Serif", + FontClass::SansSerif => "Sans Serif", + FontClass::Script => "Script", + FontClass::Monospace => "Monospace", + FontClass::Handwritten => "Handwritten", + FontClass::Blackletter => "Blackletter", + FontClass::Decorative => "Decorative", + } + } + + /// The stable key for commands and saved filters (`"slabSerif"`). + pub fn key(self) -> &'static str { + match self { + FontClass::Serif => "serif", + FontClass::SlabSerif => "slabSerif", + FontClass::SansSerif => "sansSerif", + FontClass::Script => "script", + FontClass::Monospace => "monospace", + FontClass::Handwritten => "handwritten", + FontClass::Blackletter => "blackletter", + FontClass::Decorative => "decorative", + } + } + + /// The class with this [`Self::key`]. + pub fn from_key(key: &str) -> Option { + Self::ALL.into_iter().find(|c| c.key() == key) + } +} + +/// How a family's outlines are stored, as the font menu's format badge shows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FontFormat { + /// OpenType with PostScript (CFF) outlines. + OpenType, + /// TrueType outlines (`glyf`), including OpenType fonts that use them. + TrueType, + /// A variable font (`fvar`), whatever its outlines. + Variable, +} + +impl FontFormat { + /// The badge text: Photoshop's "O", "TT" and "VAR". + pub fn badge(self) -> &'static str { + match self { + FontFormat::OpenType => "O", + FontFormat::TrueType => "TT", + FontFormat::Variable => "VAR", + } + } +} + +/// What the font menu knows about a family, from its representative (regular) face. +#[derive(Clone, Debug, PartialEq)] +pub struct FamilyTraits { + pub class: Option, + pub format: FontFormat, + /// The 10 PANOSE digits (all 0 when the font doesn't say). + pub panose: [u8; 10], + /// `usWeightClass` (400 when absent). + pub weight: u16, +} + +impl FamilyTraits { + pub fn variable(&self) -> bool { + self.format == FontFormat::Variable + } +} + +/// Read a face's traits. Missing or malformed tables fall back to "unknown", never to an error. +pub fn traits_of(family: &str, font: &FontRef) -> FamilyTraits { + let os2 = font.os2().ok(); + let family_class = os2.as_ref().map_or(0, |t| t.s_family_class()); + let mut panose = [0u8; 10]; + if let Some(bytes) = os2.as_ref().map(|t| t.panose_10()) { + for (slot, b) in panose.iter_mut().zip(bytes.iter()) { + *slot = *b; + } + } + let weight = os2.as_ref().map_or(400, |t| t.us_weight_class()).clamp(1, 1000); + let fixed_pitch = font.post().ok().is_some_and(|p| p.is_fixed_pitch() != 0); + let format = if font.fvar().is_ok() { + FontFormat::Variable + } else if font.cff().is_ok() || font.cff2().is_ok() { + FontFormat::OpenType + } else { + FontFormat::TrueType + }; + FamilyTraits { class: classify(family, family_class, panose, fixed_pitch), format, panose, weight } +} + +/// Name fragments (lowercase) that mark a blackletter face; the tables have no class for it. +const BLACKLETTER: [&str; 7] = ["fraktur", "blackletter", "black letter", "textura", "old english", "schwabacher", "rotunda"]; + +/// Classify from the OS/2 `sFamilyClass` (high byte: the IBM class), the PANOSE digits, the +/// `post` fixed-pitch flag and, last, the family name. +pub fn classify(family: &str, family_class: i16, panose: [u8; 10], fixed_pitch: bool) -> Option { + let name = family.to_lowercase(); + let has = |words: &[&str]| words.iter().any(|w| name.contains(w)); + // PANOSE Latin Text proportion 9 is monospaced. + if fixed_pitch || (panose[0] == 2 && panose[3] == 9) || has(&[" mono", "mono ", "monospace", "code", "consol", "courier"]) { + return Some(FontClass::Monospace); + } + if has(&BLACKLETTER) { + return Some(FontClass::Blackletter); + } + // PANOSE family kind: 3 Latin Hand Written, 4 Latin Decoratives, 5 Latin Symbol. + match panose[0] { + 3 => return Some(if family_class >> 8 == 10 { FontClass::Script } else { FontClass::Handwritten }), + 4 | 5 => return Some(FontClass::Decorative), + _ => {} + } + match family_class >> 8 { + // 4 is Clarendon: bracketed serifs (Georgia), not slabs. + 1..=4 | 7 => return Some(FontClass::Serif), + 5 => return Some(FontClass::SlabSerif), + 8 => return Some(FontClass::SansSerif), + 9 | 12 => return Some(FontClass::Decorative), + 10 => return Some(if has(&["hand", "marker", "brush", "pen", "chalk"]) { FontClass::Handwritten } else { FontClass::Script }), + _ => {} + } + // PANOSE Latin Text serif style: 11-15 are sans (normal, obtuse, perpendicular, flared, + // rounded); square (6) is a slab; the rest, the square coves (bracketed serifs, as Georgia's) + // included, are serifs. + if panose[0] == 2 { + match panose[1] { + 11..=15 => return Some(FontClass::SansSerif), + 6 => return Some(FontClass::SlabSerif), + 2..=10 => return Some(FontClass::Serif), + _ => {} + } + } + // Last, the name. + if has(&["slab"]) { + Some(FontClass::SlabSerif) + } else if has(&["sans", "grotesk", "grotesque", "gothic"]) { + Some(FontClass::SansSerif) + } else if has(&["serif", "roman", "garamond", "times", "bodoni", "baskerville", "caslon"]) { + Some(FontClass::Serif) + } else if has(&["hand", "marker", "brush", "chalk"]) { + Some(FontClass::Handwritten) + } else if has(&["script"]) { + Some(FontClass::Script) + } else { + None + } +} + +/// How unlike `b` is to `a`: 0 for the same traits, larger the more they differ. Used to list +/// similar fonts (Photoshop's "Show similar fonts"): the class matters most, then the PANOSE +/// digits both fonts state (serif style, weight, proportion, contrast…), then the weight. +pub fn difference(a: &FamilyTraits, b: &FamilyTraits) -> f32 { + let mut d = 0.0; + if a.class != b.class { + d += 20.0; + } + // Digits 1..=9; 0 and 1 mean "any"/"no fit", so only stated digits count. + for (x, y) in a.panose.iter().zip(b.panose.iter()).skip(1) { + if *x > 1 && *y > 1 { + d += f32::from(x.abs_diff(*y)).min(6.0); + } + } + d + f32::from(a.weight.abs_diff(b.weight)) / 100.0 +} + +#[cfg(test)] +mod tests { + use super::*; + + const NONE: [u8; 10] = [0; 10]; + + #[test] + fn the_os2_class_wins_over_the_name() { + assert_eq!(classify("Georgia", 0x0105, NONE, false), Some(FontClass::Serif)); + assert_eq!(classify("Georgia", 0x0405, NONE, false), Some(FontClass::Serif), "Clarendon is a serif"); + assert_eq!(classify("Rockwell", 0x0501, NONE, false), Some(FontClass::SlabSerif)); + assert_eq!(classify("Arial", 0x0805, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Edwardian Script ITC", 0x0a05, NONE, false), Some(FontClass::Script)); + assert_eq!(classify("Wingdings", 0x0c00, NONE, false), Some(FontClass::Decorative)); + } + + #[test] + fn panose_classifies_fonts_without_an_os2_class() { + let sans = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4]; + let slab = [2, 6, 6, 3, 2, 2, 2, 2, 2, 4]; + let serif = [2, 2, 6, 3, 5, 4, 5, 2, 3, 4]; + let hand = [3, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + let deco = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + let mono = [2, 11, 6, 9, 2, 2, 2, 2, 2, 4]; + assert_eq!(classify("A", 0, sans, false), Some(FontClass::SansSerif)); + assert_eq!(classify("B", 0, slab, false), Some(FontClass::SlabSerif)); + assert_eq!(classify("C", 0, serif, false), Some(FontClass::Serif)); + assert_eq!(classify("D", 0, hand, false), Some(FontClass::Handwritten)); + assert_eq!(classify("E", 0, deco, false), Some(FontClass::Decorative)); + assert_eq!(classify("F", 0, mono, false), Some(FontClass::Monospace)); + // Georgia: square cove serifs are bracketed serifs, not slabs. + assert_eq!(classify("Georgia", 0, [2, 4, 5, 2, 5, 4, 5, 2, 3, 3], false), Some(FontClass::Serif)); + } + + #[test] + fn fixed_pitch_and_names_decide_the_rest() { + assert_eq!(classify("Anything", 0x0805, NONE, true), Some(FontClass::Monospace), "fixed pitch beats the class"); + assert_eq!(classify("UnifrakturMaguntia", 0, NONE, false), Some(FontClass::Blackletter)); + assert_eq!(classify("Old English Text MT", 0x0805, NONE, false), Some(FontClass::Blackletter)); + assert_eq!(classify("Roboto Slab", 0, NONE, false), Some(FontClass::SlabSerif)); + assert_eq!(classify("Noto Serif", 0, NONE, false), Some(FontClass::Serif)); + assert_eq!(classify("Noto Sans", 0, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Fira Code", 0, NONE, false), Some(FontClass::Monospace)); + assert_eq!(classify("Permanent Marker", 0, NONE, false), Some(FontClass::Handwritten)); + assert_eq!(classify("Unknowable", 0, NONE, false), None); + // Out-of-range or garbage table values don't panic or misfile. + assert_eq!(classify("X", i16::MIN, [255; 10], false), None); + assert_eq!(classify("X", -1, [2, 200, 0, 0, 0, 0, 0, 0, 0, 0], false), None); + } + + #[test] + fn similar_fonts_share_class_shape_and_weight() { + let t = |class, panose, weight| FamilyTraits { class: Some(class), format: FontFormat::TrueType, panose, weight }; + let arial = t(FontClass::SansSerif, [2, 11, 6, 4, 2, 2, 2, 2, 2, 4], 400); + let helvetica = t(FontClass::SansSerif, [2, 11, 6, 4, 2, 2, 2, 2, 2, 4], 400); + let arial_black = t(FontClass::SansSerif, [2, 11, 10, 4, 2, 1, 2, 2, 2, 4], 900); + let times = t(FontClass::Serif, [2, 2, 6, 3, 5, 4, 5, 2, 3, 4], 400); + assert_eq!(difference(&arial, &helvetica), 0.0); + assert!(difference(&arial, &arial_black) < difference(&arial, ×)); + assert!(difference(&arial, ×) >= 20.0, "another class is far away"); + } + + #[test] + fn bundled_families_are_read_from_their_tables() { + let mut db = crate::FontDb::new(); + let mono = db.family_traits(crate::fonts::MONO_FAMILY).expect("the bundled mono font"); + assert_eq!(mono.class, Some(FontClass::Monospace)); + // Inter states no class or PANOSE: it is read, but left unclassified rather than guessed. + let sans = db.family_traits(crate::fonts::DEFAULT_FAMILY).expect("the bundled UI font"); + assert!(sans.class.is_none() || sans.class == Some(FontClass::SansSerif), "{:?}", sans.class); + assert!((1..=1000).contains(&sans.weight)); + assert_eq!(db.family_traits("No Such Family"), None); + assert_eq!(db.family_traits(crate::fonts::DEFAULT_FAMILY), Some(sans), "cached"); + } + + #[test] + fn class_keys_round_trip() { + for c in FontClass::ALL { + assert_eq!(FontClass::from_key(c.key()), Some(c)); + } + assert_eq!(FontClass::from_key("slabSerif"), Some(FontClass::SlabSerif)); + assert_eq!(FontClass::from_key("nope"), None); + } +} diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 5ce71e59ac..d54efd31c8 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -194,6 +194,9 @@ pub struct FontDb { /// [`Self::fallback_stack`] (#1909). Off, only the default family shapes the text. missing_glyph_protection: bool, face_cache: HashMap>, + /// Each family's [`crate::FamilyTraits`] (font menu filters), filled lazily; `None` for a + /// family whose fonts can't be read. + traits_cache: HashMap>, face_aliases: HashMap<(String, usize), String>, /// This is the shared engine's database: registrations also move [`shared_generation`]. shared: bool, @@ -216,6 +219,7 @@ impl FontDb { fallbacks: Vec::new(), missing_glyph_protection: true, face_cache: HashMap::new(), + traits_cache: HashMap::new(), face_aliases: HashMap::new(), shared: false, }; @@ -267,6 +271,7 @@ impl FontDb { } self.ps_cache.clear(); self.face_cache.clear(); + self.traits_cache.clear(); self.refresh_generics(); } } @@ -297,6 +302,7 @@ impl FontDb { names.sort_by_key(|n| (is_hidden_family(n), n.to_lowercase())); self.ps_cache.clear(); self.face_cache.clear(); + self.traits_cache.clear(); self.refresh_generics(); GENERATION.fetch_add(1, Ordering::Relaxed); if self.shared { @@ -456,6 +462,24 @@ impl FontDb { faces } + /// What the font menu filters and sorts a family by ([`crate::font_class`]), read from its + /// regular face (the upright face nearest weight 400). `None` when the family is unknown or + /// none of its fonts can be read. + pub fn family_traits(&mut self, family: &str) -> Option { + if let Some(t) = self.traits_cache.get(family) { + return t.clone(); + } + let traits = (|| { + let info = self.fcx.collection.family_by_name(family)?; + let face = info.fonts().iter().min_by_key(|f| (!matches!(f.style(), FontStyle::Normal), (f.weight().value() - 400.0).abs() as u32))?.clone(); + let blob = face.load(Some(&mut self.fcx.source_cache))?; + let font = skrifa::FontRef::from_index(blob.as_ref(), face.index()).ok()?; + Some(crate::font_class::traits_of(family, &font)) + })(); + self.traits_cache.insert(family.to_string(), traits.clone()); + traits + } + /// Resolve a menu style to its actual metadata instead of guessing from its spelling. pub fn named_face(&mut self, family: &str, style: &str) -> Option { self.faces(family).into_iter().find(|f| f.style.eq_ignore_ascii_case(style)) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7909199a6f..4f5e901f77 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -19,6 +19,7 @@ pub mod cjk; pub mod craft_fonts; pub mod engine_data; +pub mod font_class; pub mod fonts; pub mod glyphs; pub mod layout; @@ -36,6 +37,7 @@ use photocraft_color::PixelFormat; use photocraft_doc::TextLayer; pub use craft_fonts::{CRAFT_FONTS, CraftFont}; +pub use font_class::{FamilyTraits, FontClass, FontFormat}; pub use fonts::{FaceInfo, FontDb, ResolvedFont}; pub use layout::{ ClusterInfo, LineInfo, PlacedGlyph, TextLayout, byte_index, char_index, hit_char, line_edge, line_index, line_step, text_point_inside, word_boundary, diff --git a/crates/ui-egui/src/font_filters.rs b/crates/ui-egui/src/font_filters.rs new file mode 100644 index 0000000000..3ba4439f47 --- /dev/null +++ b/crates/ui-egui/src/font_filters.rs @@ -0,0 +1,277 @@ +//! The font menu's filters, as in Photoshop's font menu (except its Adobe Fonts parts): a class +//! list (Serif, Sans Serif, Script…), Show Variable Fonts, Show Favorite Fonts and Show Similar +//! Fonts, and Clear All. Each family's class, format and shape come from its own tables +//! ([`photocraft_text::font_class`]), read once per font list and cached here. + +use std::collections::HashMap; +use std::sync::{Arc, PoisonError}; + +use photocraft_text::{FamilyTraits, FontClass, FontFormat}; + +/// How many fonts Show Similar Fonts lists (the current one first). +pub(crate) const SIMILAR_COUNT: usize = 30; + +/// The filter bar's state, per font menu (kept for the session). +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct FontFilters { + /// Only fonts of this class (`None`: All Classes). + pub class: Option, + pub favorites: bool, + pub variable: bool, + /// Fonts like the current one, most alike first. + pub similar: bool, + /// The class list is collapsed (the « button). + pub hide_classes: bool, +} + +impl FontFilters { + /// Whether any filter narrows the list (Clear All is enabled). + pub fn any(&self) -> bool { + self.class.is_some() || self.favorites || self.variable || self.similar + } + + /// Clear All: every filter off; the class list stays as it was. + pub fn clear(&mut self) { + *self = FontFilters { hide_classes: self.hide_classes, ..Default::default() }; + } +} + +/// Family traits by family name; `None` for a family that can't be read (or a served font not +/// fetched yet). +pub(crate) type TraitsMap = HashMap>; + +/// The traits of `family` from the shared font database, cached until fonts are registered. +pub(crate) fn traits(family: &str) -> Option { + type Cached = Option<(u64, TraitsMap)>; + static CACHE: std::sync::Mutex = std::sync::Mutex::new(None); + let generation = photocraft_text::fonts::shared_generation(); + let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); + if cache.as_ref().is_none_or(|(g, _)| *g != generation) { + *cache = Some((generation, HashMap::new())); + } + let (_, map) = cache.as_mut()?; + if let Some(t) = map.get(family) { + return t.clone(); + } + // Only once the background font scan is done: never block the UI on it. + let t = photocraft_text::try_shared()?.lock().unwrap_or_else(PoisonError::into_inner).fonts.family_traits(family); + map.insert(family.to_string(), t.clone()); + t +} + +/// Narrow and order the menu's `rows` by `filters`. `current` is the font Show Similar Fonts +/// compares with; `lookup` gives a family's traits. Returns false when Show Similar Fonts is on +/// but the current font has nothing to compare (its rows are then left as they were). +pub(crate) fn apply<'a>( + rows: &mut Vec<(&'a String, &'a str)>, + filters: &FontFilters, + favorites: &[String], + current: &str, + lookup: &dyn Fn(&str) -> Option, +) -> bool { + if filters.favorites { + rows.retain(|(f, _)| favorites.contains(f)); + } + if filters.variable { + rows.retain(|(f, _)| lookup(f).is_some_and(|t| t.variable())); + } + if let Some(class) = filters.class { + rows.retain(|(f, _)| lookup(f).is_some_and(|t| t.class == Some(class))); + } + if !filters.similar { + return true; + } + let Some(reference) = lookup(current).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1)) else { + return false; + }; + let mut scored: Vec<(f32, (&String, &str))> = rows + .drain(..) + .filter_map(|row| lookup(row.0).map(|t| (if row.0 == current { -1.0 } else { photocraft_text::font_class::difference(&reference, &t) }, row))) + .collect(); + scored.sort_by(|a, b| a.0.total_cmp(&b.0)); + rows.extend(scored.into_iter().take(SIMILAR_COUNT).map(|(_, row)| row)); + true +} + +/// The translated class name. +pub(crate) fn class_label(class: FontClass) -> &'static str { + match class { + FontClass::Serif => tl!("Serif"), + FontClass::SlabSerif => tl!("Slab Serif"), + FontClass::SansSerif => tl!("Sans Serif"), + FontClass::Script => tl!("Script"), + FontClass::Monospace => tl!("Monospace"), + FontClass::Handwritten => tl!("Handwritten"), + FontClass::Blackletter => tl!("Blackletter"), + FontClass::Decorative => tl!("Decorative"), + } +} + +/// The format badge's tooltip. +pub(crate) fn format_tip(format: FontFormat) -> &'static str { + match format { + FontFormat::OpenType => tl!("OpenType font"), + FontFormat::TrueType => tl!("TrueType font"), + FontFormat::Variable => tl!("Variable font"), + } +} + +/// The class list's width; the filter buttons sit above it. +pub(crate) const CLASS_COLUMN_WIDTH: f32 = 118.0; + +/// The filter buttons: the class-list toggle and the three filters. Returns true when a filter +/// changed. +pub(crate) fn filter_buttons(ui: &mut egui::Ui, filters: &mut FontFilters) -> bool { + let before = filters.clone(); + let (icon, tip) = if filters.hide_classes { ("chevrons-right", tl!("Show Font Classes")) } else { ("chevrons-left", tl!("Hide Font Classes")) }; + if crate::icons::button(ui, icon, 22.0, false, tip).clicked() { + filters.hide_classes = !filters.hide_classes; + } + if crate::icons::button(ui, "font-variable", 22.0, filters.variable, tl!("Show Variable Fonts")).clicked() { + filters.variable = !filters.variable; + } + let tip = if filters.favorites { tl!("Show All Fonts") } else { tl!("Show Favorite Fonts") }; + if crate::icons::button(ui, if filters.favorites { "star-filled" } else { "star" }, 22.0, filters.favorites, tip).clicked() { + filters.favorites = !filters.favorites; + } + if crate::icons::button(ui, "font-similar", 22.0, filters.similar, tl!("Show Similar Fonts")).clicked() { + filters.similar = !filters.similar; + } + *filters != before +} + +/// Clear All: turns every filter off. Returns true when it did. +pub(crate) fn clear_all(ui: &mut egui::Ui, filters: &mut FontFilters) -> bool { + let clicked = ui.add_enabled(filters.any(), egui::Button::new(tl!("Clear All")).small()).clicked(); + if clicked { + filters.clear(); + } + clicked +} + +/// The preview banner's height. +pub(crate) const PREVIEW_HEIGHT: f32 = 64.0; + +/// The preview at the top of the font menu: `family` (the font under the pointer, else the +/// current one) named and set large, `width` wide. It sets `text`, the user's own type, when +/// there is some, else a sample. +pub(crate) fn preview_banner(ui: &mut egui::Ui, family: &str, label: &str, text: Option<&str>, width: f32) { + let (rect, response) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_HEIGHT), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, format!("{} {label}", tl!("Font preview:")))); + if !ui.is_rect_visible(rect) { + return; + } + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, t.radius_sm, t.canvas); + ui.painter().text(rect.left_top() + egui::vec2(10.0, 8.0), egui::Align2::LEFT_TOP, label, egui::FontId::proportional(11.0), t.text_dim); + if let Some(text) = text { + let line = egui::Rect::from_min_max(rect.left_top() + egui::vec2(10.0, 20.0), rect.right_bottom() - egui::vec2(10.0, 2.0)); + crate::font_preview::paint_text(ui, family, text, line, 30.0); + return; + } + let Some((size, _)) = crate::font_preview::sample(photocraft_engine::prefs::FontPreview::Huge) else { return }; + crate::font_preview::paint(ui, family, rect.translate(egui::vec2(0.0, 6.0)), size); +} + +/// The class list beside the fonts. Returns true when the class changed. +pub(crate) fn class_list(ui: &mut egui::Ui, filters: &mut FontFilters) -> bool { + let before = filters.class; + ui.vertical(|ui| { + ui.set_width(CLASS_COLUMN_WIDTH); + if ui.add(egui::Button::selectable(filters.class.is_none(), tl!("All Classes")).truncate()).clicked() { + filters.class = None; + } + for class in FontClass::ALL { + if ui.add(egui::Button::selectable(filters.class == Some(class), class_label(class)).truncate()).clicked() { + filters.class = Some(class); + } + } + }); + filters.class != before +} + +/// Traits a test hands the menu instead of reading installed fonts. +pub(crate) fn lookup_in(map: Option>) -> impl Fn(&str) -> Option { + move |family| match &map { + Some(map) => map.get(family).cloned().flatten(), + None => traits(family), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn t(class: FontClass, format: FontFormat, panose: [u8; 10], weight: u16) -> Option { + Some(FamilyTraits { class: Some(class), format, panose, weight }) + } + + fn fixture() -> (Vec, TraitsMap) { + let sans = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4]; + let serif = [2, 2, 6, 3, 5, 4, 5, 2, 3, 4]; + let map: TraitsMap = [ + ("Arial", t(FontClass::SansSerif, FontFormat::TrueType, sans, 400)), + ("Arial Black", t(FontClass::SansSerif, FontFormat::TrueType, [2, 11, 10, 4, 2, 1, 2, 2, 2, 4], 900)), + ("Bahnschrift", t(FontClass::SansSerif, FontFormat::Variable, sans, 400)), + ("Consolas", t(FontClass::Monospace, FontFormat::TrueType, [2, 11, 6, 9, 2, 2, 4, 3, 2, 4], 400)), + ("Georgia", t(FontClass::Serif, FontFormat::TrueType, serif, 400)), + ("Minion", t(FontClass::Serif, FontFormat::OpenType, serif, 400)), + ("Mystery", None), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let mut families: Vec = map.keys().cloned().collect(); + families.sort(); + (families, map) + } + + fn run(filters: &FontFilters, favorites: &[&str], current: &str) -> (Vec, bool) { + let (families, map) = fixture(); + let mut rows: Vec<(&String, &str)> = families.iter().map(|f| (f, f.as_str())).collect(); + let favorites: Vec = favorites.iter().map(|s| s.to_string()).collect(); + let lookup = lookup_in(Some(Arc::new(map))); + let ok = apply(&mut rows, filters, &favorites, current, &lookup); + (rows.into_iter().map(|(f, _)| f.clone()).collect(), ok) + } + + #[test] + fn class_variable_and_favorite_filters_narrow_and_combine() { + let class = |c| FontFilters { class: Some(c), ..Default::default() }; + assert_eq!(run(&class(FontClass::Serif), &[], "Arial").0, ["Georgia", "Minion"]); + assert_eq!(run(&class(FontClass::Monospace), &[], "Arial").0, ["Consolas"]); + assert!(run(&class(FontClass::Blackletter), &[], "Arial").0.is_empty()); + let variable = FontFilters { variable: true, ..Default::default() }; + assert_eq!(run(&variable, &[], "Arial").0, ["Bahnschrift"]); + let both = FontFilters { favorites: true, class: Some(FontClass::SansSerif), ..Default::default() }; + assert_eq!(run(&both, &["Georgia", "Arial Black"], "Arial").0, ["Arial Black"]); + // Nothing on: every font, unknown ones too. + assert_eq!(run(&FontFilters::default(), &[], "Arial").0.len(), 7); + } + + #[test] + fn similar_fonts_start_with_the_current_one_most_alike_first() { + let similar = FontFilters { similar: true, ..Default::default() }; + let (rows, ok) = run(&similar, &[], "Arial"); + assert!(ok); + assert_eq!(rows[0], "Arial", "the current font first"); + assert_eq!(rows[1], "Bahnschrift", "same class and shape"); + let georgia = rows.iter().position(|f| f == "Georgia").unwrap(); + let black = rows.iter().position(|f| f == "Arial Black").unwrap(); + assert!(black < georgia, "another weight of the class is nearer than another class"); + assert!(!rows.contains(&"Mystery".to_string()), "unreadable fonts can't be compared"); + // A current font with nothing to compare leaves the list alone and says so. + let (rows, ok) = run(&similar, &[], "Mystery"); + assert!(!ok); + assert_eq!(rows.len(), 7); + } + + #[test] + fn clear_all_keeps_the_class_list_state() { + let mut f = FontFilters { class: Some(FontClass::Script), favorites: true, variable: true, similar: true, hide_classes: true }; + assert!(f.any()); + f.clear(); + assert_eq!(f, FontFilters { hide_classes: true, ..Default::default() }); + assert!(!f.any()); + } +} diff --git a/crates/ui-egui/src/font_preview.rs b/crates/ui-egui/src/font_preview.rs index 74c334d682..23e6dacc07 100644 --- a/crates/ui-egui/src/font_preview.rs +++ b/crates/ui-egui/src/font_preview.rs @@ -174,6 +174,44 @@ pub(crate) fn paint(ui: &egui::Ui, family: &str, row: Rect, size: f32) { } } +/// The few lines of the user's own text the font menu's preview keeps rendered: family, text, +/// display scale, font generation, point size and width. +type TextKey = (String, String, u32, u64, u32, u32); +#[derive(Clone, Default)] +struct TextCache(VecDeque<(TextKey, Option)>); +const TEXT_CACHE_LIMIT: usize = 16; + +/// `text` set in `family` at `size`, from the left of `rect` and vertically centred; what doesn't +/// fit is cut at the right. The font menu's preview of the user's own text. +pub(crate) fn paint_text(ui: &egui::Ui, family: &str, text: &str, rect: Rect, size: f32) { + let ctx = ui.ctx(); + let scale = ctx.pixels_per_point().ceil().clamp(1.0, 4.0) as u32; + let slot = rect.width().clamp(1.0, 4096.0); + let key: TextKey = (family.to_owned(), text.to_owned(), scale, photocraft_text::fonts::shared_generation(), size as u32, slot as u32); + let id = egui::Id::new("font-menu-text-previews"); + let cached = ctx.data_mut(|d| d.get_temp_mut_or_default::(id).0.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone())); + let texture = cached.unwrap_or_else(|| { + let mut engine = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner); + let image = engine.fonts.has_family(family).then(|| render(&mut engine, family, text, slot, scale, size)).flatten(); + drop(engine); + let texture = image.map(|image| ctx.load_texture(format!("font-text-{family}"), image, TextureOptions::LINEAR)); + ctx.data_mut(|d| { + let cache = d.get_temp_mut_or_default::(id); + if cache.0.len() >= TEXT_CACHE_LIMIT { + cache.0.pop_front(); + } + cache.0.push_back((key, texture.clone())); + }); + texture + }); + if let Some(texture) = texture { + let h = scaled(HEIGHT, size); + let at = Rect::from_min_size(pos2(rect.left(), rect.center().y - h / 2.0), vec2(slot, h)); + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + ui.painter().image(texture.id(), at, uv, crate::theme::Tokens::get(ctx).text); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 01a8b9e4d9..3ff86956f7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3752,3 +3752,31 @@ navigator Zoom Zvětšení Sent to {printer} Odesláno do {printer} set in Print Settings… nastavuje se v nastavení tisku… ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů + Show Favorite Fonts Zobrazit oblíbená písma + No favorite fonts yet: click the star beside a font to add it. Zatím žádná oblíbená písma: přidejte písmo kliknutím na hvězdičku vedle něj. + Favorite fonts Oblíbená písma + Recent font list Seznam posledních písem + Add to Favorites Přidat do oblíbených + Remove from Favorites Odebrat z oblíbených + Show All Fonts Zobrazit všechna písma + All Classes Všechny třídy + Blackletter Lomená písma + Decorative Dekorativní + Font preview: Náhled písma: + Handwritten Ručně psaná + Hide Font Classes Skrýt třídy písem + Hide Styles Skrýt řezy + Monospace Neproporcionální + No fonts match these filters. Filtrům neodpovídají žádná písma. + No similar fonts: the current font doesn't say what it looks like. Žádná podobná písma: u aktuálního písma chybí popis vzhledu. + OpenType font Písmo OpenType + Sans Serif Bezpatková + Script Skriptová + Serif Patková + Show Font Classes Zobrazit třídy písem + Show Similar Fonts Zobrazit podobná písma + Show Styles Zobrazit řezy + Show Variable Fonts Zobrazit variabilní písma + Slab Serif Slabová patková + TrueType font Písmo TrueType + Variable font Variabilní písmo diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 489647ed21..e615085b78 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3142,3 +3142,31 @@ curves Smooth Glätten Sent to {printer} An {printer} gesendet set in Print Settings… in den Druckeinstellungen festlegen… ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt + Show Favorite Fonts Favorisierte Schriften anzeigen + No favorite fonts yet: click the star beside a font to add it. Noch keine favorisierten Schriften: Klicken Sie auf den Stern neben einer Schrift, um sie hinzuzufügen. + Favorite fonts Favorisierte Schriften + Recent font list Liste zuletzt verwendeter Schriften + Add to Favorites Zu Favoriten hinzufügen + Remove from Favorites Aus Favoriten entfernen + Show All Fonts Alle Schriften anzeigen + All Classes Alle Klassen + Blackletter Gebrochene Schriften + Decorative Dekorativ + Font preview: Schriftvorschau: + Handwritten Handschriftlich + Hide Font Classes Schriftklassen ausblenden + Hide Styles Schnitte ausblenden + Monospace Nichtproportional + No fonts match these filters. Keine Schriften entsprechen diesen Filtern. + No similar fonts: the current font doesn't say what it looks like. Keine ähnlichen Schriften: Die aktuelle Schrift beschreibt ihr Aussehen nicht. + OpenType font OpenType-Schrift + Sans Serif Serifenlos + Script Schreibschrift + Serif Serifen + Show Font Classes Schriftklassen einblenden + Show Similar Fonts Ähnliche Schriften anzeigen + Show Styles Schnitte einblenden + Show Variable Fonts Variable Schriften anzeigen + Slab Serif Serifenbetont + TrueType font TrueType-Schrift + Variable font Variable Schrift diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 410da1a188..bb81b7ec73 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3842,3 +3842,31 @@ curves Smooth Εξομάλυνση Sent to {printer} Στάλθηκε στον {printer} set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης… ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία + Show Favorite Fonts Εμφάνιση αγαπημένων γραμματοσειρών + No favorite fonts yet: click the star beside a font to add it. Δεν υπάρχουν ακόμη αγαπημένες γραμματοσειρές: κάντε κλικ στο αστέρι δίπλα σε μια γραμματοσειρά για να την προσθέσετε. + Favorite fonts Αγαπημένες γραμματοσειρές + Recent font list Λίστα πρόσφατων γραμματοσειρών + Add to Favorites Προσθήκη στα αγαπημένα + Remove from Favorites Αφαίρεση από τα αγαπημένα + Show All Fonts Εμφάνιση όλων των γραμματοσειρών + All Classes Όλες οι κατηγορίες + Blackletter Γοτθικές + Decorative Διακοσμητικές + Font preview: Προεπισκόπηση γραμματοσειράς: + Handwritten Χειρόγραφες + Hide Font Classes Απόκρυψη κατηγοριών γραμματοσειρών + Hide Styles Απόκρυψη στυλ + Monospace Σταθερού πλάτους + No fonts match these filters. Καμία γραμματοσειρά δεν ταιριάζει με αυτά τα φίλτρα. + No similar fonts: the current font doesn't say what it looks like. Καμία παρόμοια γραμματοσειρά: η τρέχουσα γραμματοσειρά δεν περιγράφει την εμφάνισή της. + OpenType font Γραμματοσειρά OpenType + Sans Serif Χωρίς πατούρες + Script Καλλιγραφικές + Serif Με πατούρες + Show Font Classes Εμφάνιση κατηγοριών γραμματοσειρών + Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών + Show Styles Εμφάνιση στυλ + Show Variable Fonts Εμφάνιση μεταβλητών γραμματοσειρών + Slab Serif Με πλακοειδείς πατούρες + TrueType font Γραμματοσειρά TrueType + Variable font Μεταβλητή γραμματοσειρά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b5db4e9925..095ed8a917 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2829,3 +2829,31 @@ curves Smooth Suavizar Sent to {printer} Enviado a {printer} set in Print Settings… se establece en Ajustes de impresión… ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles + Show Favorite Fonts Mostrar fuentes favoritas + No favorite fonts yet: click the star beside a font to add it. Aún no hay fuentes favoritas: haz clic en la estrella junto a una fuente para añadirla. + Favorite fonts Fuentes favoritas + Recent font list Lista de fuentes recientes + Add to Favorites Añadir a favoritos + Remove from Favorites Quitar de favoritos + Show All Fonts Mostrar todas las fuentes + All Classes Todas las clases + Blackletter Gótica + Decorative Decorativa + Font preview: Vista previa de fuente: + Handwritten Manuscrita + Hide Font Classes Ocultar clases de fuente + Hide Styles Ocultar estilos + Monospace Monoespaciada + No fonts match these filters. Ninguna fuente coincide con estos filtros. + No similar fonts: the current font doesn't say what it looks like. No hay fuentes similares: la fuente actual no describe su aspecto. + OpenType font Fuente OpenType + Sans Serif Sans serif + Script Caligráfica + Serif Serif + Show Font Classes Mostrar clases de fuente + Show Similar Fonts Mostrar fuentes similares + Show Styles Mostrar estilos + Show Variable Fonts Mostrar fuentes variables + Slab Serif Serif egipcia + TrueType font Fuente TrueType + Variable font Fuente variable diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ab0cca6f40..e2102535b6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3146,3 +3146,31 @@ curves Smooth Lisser Sent to {printer} Envoyé à {printer} set in Print Settings… défini dans les paramètres d’impression… ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels + Show Favorite Fonts Afficher les polices favorites + No favorite fonts yet: click the star beside a font to add it. Aucune police favorite pour l’instant : cliquez sur l’étoile à côté d’une police pour l’ajouter. + Favorite fonts Polices favorites + Recent font list Liste des polices récentes + Add to Favorites Ajouter aux favoris + Remove from Favorites Retirer des favoris + Show All Fonts Afficher toutes les polices + All Classes Toutes les classes + Blackletter Gothique + Decorative Décorative + Font preview: Aperçu de la police : + Handwritten Manuscrite + Hide Font Classes Masquer les classes de polices + Hide Styles Masquer les styles + Monospace Chasse fixe + No fonts match these filters. Aucune police ne correspond à ces filtres. + No similar fonts: the current font doesn't say what it looks like. Aucune police similaire : la police actuelle ne décrit pas son apparence. + OpenType font Police OpenType + Sans Serif Sans empattement + Script Scripte + Serif Avec empattement + Show Font Classes Afficher les classes de polices + Show Similar Fonts Afficher les polices similaires + Show Styles Afficher les styles + Show Variable Fonts Afficher les polices variables + Slab Serif Égyptienne + TrueType font Police TrueType + Variable font Police variable diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9a7283a5a1..f4c1c1fd54 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4065,3 +4065,31 @@ cameraRaw Yellow Sárga Ink Characteristics Festék jellemzői Solidity: Fedőképesség: Redrawing Újrarajzolás + Show Favorite Fonts Kedvenc betűtípusok megjelenítése + No favorite fonts yet: click the star beside a font to add it. Még nincsenek kedvenc betűtípusok: kattintson a betűtípus melletti csillagra a hozzáadáshoz. + Favorite fonts Kedvenc betűtípusok + Recent font list Legutóbbi betűtípusok listája + Add to Favorites Hozzáadás a kedvencekhez + Remove from Favorites Eltávolítás a kedvencek közül + Show All Fonts Összes betűtípus megjelenítése + All Classes Összes osztály + Blackletter Gót betűs + Decorative Díszítő + Font preview: Betűtípus előnézete: + Handwritten Kézírásos + Hide Font Classes Betűtípus-osztályok elrejtése + Hide Styles Stílusok elrejtése + Monospace Fix szélességű + No fonts match these filters. Egy betűtípus sem felel meg ezeknek a szűrőknek. + No similar fonts: the current font doesn't say what it looks like. Nincsenek hasonló betűtípusok: a jelenlegi betűtípus nem írja le a megjelenését. + OpenType font OpenType betűtípus + Sans Serif Talpatlan + Script Írott + Serif Talpas + Show Font Classes Betűtípus-osztályok megjelenítése + Show Similar Fonts Hasonló betűtípusok megjelenítése + Show Styles Stílusok megjelenítése + Show Variable Fonts Változó betűtípusok megjelenítése + Slab Serif Talpas (szögletes) + TrueType font TrueType betűtípus + Variable font Változó betűtípus diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6924c45609..dcb36bd603 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3133,3 +3133,31 @@ curves Smooth Haluskan Sent to {printer} Dikirim ke {printer} set in Print Settings… diatur di Pengaturan Cetak… ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel + Show Favorite Fonts Tampilkan Font Favorit + No favorite fonts yet: click the star beside a font to add it. Belum ada font favorit: klik bintang di samping font untuk menambahkannya. + Favorite fonts Font favorit + Recent font list Daftar font terbaru + Add to Favorites Tambahkan ke Favorit + Remove from Favorites Hapus dari Favorit + Show All Fonts Tampilkan Semua Font + All Classes Semua Kelas + Blackletter Blackletter + Decorative Dekoratif + Font preview: Pratinjau font: + Handwritten Tulisan tangan + Hide Font Classes Sembunyikan Kelas Font + Hide Styles Sembunyikan Gaya + Monospace Monospasi + No fonts match these filters. Tidak ada font yang cocok dengan filter ini. + No similar fonts: the current font doesn't say what it looks like. Tidak ada font serupa: font saat ini tidak menjelaskan tampilannya. + OpenType font Font OpenType + Sans Serif Sans Serif + Script Skrip + Serif Serif + Show Font Classes Tampilkan Kelas Font + Show Similar Fonts Tampilkan Font Serupa + Show Styles Tampilkan Gaya + Show Variable Fonts Tampilkan Font Variabel + Slab Serif Slab Serif + TrueType font Font TrueType + Variable font Font variabel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2d42c550cc..c22f4d5f32 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4107,3 +4107,31 @@ navigator Zoom Zoom Sent to {printer} Inviato a {printer} set in Print Settings… impostato nelle impostazioni di stampa… ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel + Show Favorite Fonts Mostra font preferiti + No favorite fonts yet: click the star beside a font to add it. Ancora nessun font preferito: fai clic sulla stella accanto a un font per aggiungerlo. + Favorite fonts Font preferiti + Recent font list Elenco dei font recenti + Add to Favorites Aggiungi ai preferiti + Remove from Favorites Rimuovi dai preferiti + Show All Fonts Mostra tutti i font + All Classes Tutte le classi + Blackletter Gotico + Decorative Decorativo + Font preview: Anteprima font: + Handwritten Scrittura a mano + Hide Font Classes Nascondi classi di font + Hide Styles Nascondi stili + Monospace Monospaziato + No fonts match these filters. Nessun font corrisponde a questi filtri. + No similar fonts: the current font doesn't say what it looks like. Nessun font simile: il font corrente non descrive il proprio aspetto. + OpenType font Font OpenType + Sans Serif Senza grazie + Script Corsivo calligrafico + Serif Con grazie + Show Font Classes Mostra classi di font + Show Similar Fonts Mostra font simili + Show Styles Mostra stili + Show Variable Fonts Mostra font variabili + Slab Serif Egiziano + TrueType font Font TrueType + Variable font Font variabile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e05f27d718..bb1cb6eecf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3821,3 +3821,31 @@ curves Smooth スムーズ Reset All Locked Settings ロックされた設定をすべて初期化 Copy Texture to Other Tools テクスチャを他のツールにコピー ICO is limited to 256 × 256 pixels ICO は 256 × 256 ピクセルまでです + Show Favorite Fonts お気に入りのフォントを表示 + No favorite fonts yet: click the star beside a font to add it. お気に入りのフォントはまだありません。フォントの横の星をクリックして追加してください。 + Favorite fonts お気に入りのフォント + Recent font list 最近使用したフォントのリスト + Add to Favorites お気に入りに追加 + Remove from Favorites お気に入りから削除 + Show All Fonts すべてのフォントを表示 + All Classes すべての分類 + Blackletter ブラックレター + Decorative 装飾 + Font preview: フォントのプレビュー: + Handwritten 手書き + Hide Font Classes フォントの分類を隠す + Hide Styles スタイルを隠す + Monospace 等幅 + No fonts match these filters. このフィルターに一致するフォントはありません。 + No similar fonts: the current font doesn't say what it looks like. 類似フォントはありません。現在のフォントは外観の情報を持っていません。 + OpenType font OpenType フォント + Sans Serif サンセリフ + Script スクリプト + Serif セリフ + Show Font Classes フォントの分類を表示 + Show Similar Fonts 類似フォントを表示 + Show Styles スタイルを表示 + Show Variable Fonts バリアブルフォントを表示 + Slab Serif スラブセリフ + TrueType font TrueType フォント + Variable font バリアブルフォント diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7de9f61f10..0889b75944 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3319,3 +3319,31 @@ curves Smooth 매끄럽게 Sent to {printer} {printer}(으)로 전송됨 set in Print Settings… 인쇄 설정에서 지정… ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 + Show Favorite Fonts 즐겨찾는 글꼴 표시 + No favorite fonts yet: click the star beside a font to add it. 아직 즐겨찾는 글꼴이 없습니다. 글꼴 옆의 별을 클릭하여 추가하세요. + Favorite fonts 즐겨찾는 글꼴 + Recent font list 최근 글꼴 목록 + Add to Favorites 즐겨찾기에 추가 + Remove from Favorites 즐겨찾기에서 제거 + Show All Fonts 모든 글꼴 표시 + All Classes 모든 분류 + Blackletter 블랙레터 + Decorative 장식 + Font preview: 글꼴 미리 보기: + Handwritten 손글씨 + Hide Font Classes 글꼴 분류 숨기기 + Hide Styles 스타일 숨기기 + Monospace 고정폭 + No fonts match these filters. 이 필터와 일치하는 글꼴이 없습니다. + No similar fonts: the current font doesn't say what it looks like. 비슷한 글꼴 없음: 현재 글꼴에 모양 정보가 없습니다. + OpenType font OpenType 글꼴 + Sans Serif 산세리프 + Script 스크립트 + Serif 세리프 + Show Font Classes 글꼴 분류 표시 + Show Similar Fonts 비슷한 글꼴 표시 + Show Styles 스타일 표시 + Show Variable Fonts 가변 글꼴 표시 + Slab Serif 슬래브 세리프 + TrueType font TrueType 글꼴 + Variable font 가변 글꼴 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4ed7d8a744..71a52b2f77 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3904,3 +3904,31 @@ curves Smooth Vloeiend maken Sent to {printer} Verzonden naar {printer} set in Print Settings… instellen in de afdrukinstellingen… ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels + Show Favorite Fonts Favoriete lettertypen tonen + No favorite fonts yet: click the star beside a font to add it. Nog geen favoriete lettertypen: klik op de ster naast een lettertype om het toe te voegen. + Favorite fonts Favoriete lettertypen + Recent font list Lijst met recente lettertypen + Add to Favorites Toevoegen aan favorieten + Remove from Favorites Verwijderen uit favorieten + Show All Fonts Alle lettertypen tonen + All Classes Alle klassen + Blackletter Gebroken letter + Decorative Decoratief + Font preview: Lettertypevoorbeeld: + Handwritten Handgeschreven + Hide Font Classes Lettertypeklassen verbergen + Hide Styles Stijlen verbergen + Monospace Monospace + No fonts match these filters. Geen lettertypen voldoen aan deze filters. + No similar fonts: the current font doesn't say what it looks like. Geen vergelijkbare lettertypen: het huidige lettertype beschrijft zijn uiterlijk niet. + OpenType font OpenType-lettertype + Sans Serif Schreefloos + Script Script + Serif Schreef + Show Font Classes Lettertypeklassen tonen + Show Similar Fonts Vergelijkbare lettertypen tonen + Show Styles Stijlen tonen + Show Variable Fonts Variabele lettertypen tonen + Slab Serif Slab-schreef + TrueType font TrueType-lettertype + Variable font Variabel lettertype diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a27cb4af8d..65df560249 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3742,3 +3742,31 @@ curves Smooth Wygładź Sent to {printer} Wysłano do {printer} set in Print Settings… ustawiane w ustawieniach druku… ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli + Show Favorite Fonts Pokaż ulubione czcionki + No favorite fonts yet: click the star beside a font to add it. Brak ulubionych czcionek: kliknij gwiazdkę obok czcionki, aby ją dodać. + Favorite fonts Ulubione czcionki + Recent font list Lista ostatnich czcionek + Add to Favorites Dodaj do ulubionych + Remove from Favorites Usuń z ulubionych + Show All Fonts Pokaż wszystkie czcionki + All Classes Wszystkie klasy + Blackletter Pismo gotyckie + Decorative Ozdobne + Font preview: Podgląd czcionki: + Handwritten Odręczne + Hide Font Classes Ukryj klasy czcionek + Hide Styles Ukryj style + Monospace O stałej szerokości + No fonts match these filters. Żadna czcionka nie pasuje do tych filtrów. + No similar fonts: the current font doesn't say what it looks like. Brak podobnych czcionek: bieżąca czcionka nie opisuje swojego wyglądu. + OpenType font Czcionka OpenType + Sans Serif Bezszeryfowe + Script Pisane + Serif Szeryfowe + Show Font Classes Pokaż klasy czcionek + Show Similar Fonts Pokaż podobne czcionki + Show Styles Pokaż style + Show Variable Fonts Pokaż czcionki zmienne + Slab Serif Szeryfowe prostokątne + TrueType font Czcionka TrueType + Variable font Czcionka zmienna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0a64497704..ab6e826104 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3934,3 +3934,31 @@ layerLabel No Color Sem cor Sent to {printer} Enviado para {printer} set in Print Settings… definido nas configurações de impressão… ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels + Show Favorite Fonts Mostrar fontes favoritas + No favorite fonts yet: click the star beside a font to add it. Ainda não há fontes favoritas: clique na estrela ao lado de uma fonte para adicioná-la. + Favorite fonts Fontes favoritas + Recent font list Lista de fontes recentes + Add to Favorites Adicionar aos favoritos + Remove from Favorites Remover dos favoritos + Show All Fonts Mostrar todas as fontes + All Classes Todas as classes + Blackletter Gótica + Decorative Decorativa + Font preview: Visualização da fonte: + Handwritten Manuscrita + Hide Font Classes Ocultar classes de fonte + Hide Styles Ocultar estilos + Monospace Monoespaçada + No fonts match these filters. Nenhuma fonte corresponde a estes filtros. + No similar fonts: the current font doesn't say what it looks like. Nenhuma fonte semelhante: a fonte atual não descreve sua aparência. + OpenType font Fonte OpenType + Sans Serif Sem serifa + Script Cursiva + Serif Com serifa + Show Font Classes Mostrar classes de fonte + Show Similar Fonts Mostrar fontes semelhantes + Show Styles Mostrar estilos + Show Variable Fonts Mostrar fontes variáveis + Slab Serif Serifa egípcia + TrueType font Fonte TrueType + Variable font Fonte variável diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2dbbf4003c..85e47d201c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3110,3 +3110,31 @@ curves Smooth Сгладить Gray Value (Median) Уровень серого (медиана) Integrated Density Интегральная плотность Length Длина + Show Favorite Fonts Показать избранные шрифты + No favorite fonts yet: click the star beside a font to add it. Избранных шрифтов пока нет: нажмите на звёздочку рядом со шрифтом, чтобы добавить его. + Favorite fonts Избранные шрифты + Recent font list Список последних шрифтов + Add to Favorites Добавить в избранное + Remove from Favorites Удалить из избранного + Show All Fonts Показать все шрифты + All Classes Все классы + Blackletter Готические + Decorative Декоративные + Font preview: Предпросмотр шрифта: + Handwritten Рукописные + Hide Font Classes Скрыть классы шрифтов + Hide Styles Скрыть начертания + Monospace Моноширинные + No fonts match these filters. Нет шрифтов, подходящих под эти фильтры. + No similar fonts: the current font doesn't say what it looks like. Нет похожих шрифтов: текущий шрифт не описывает свой вид. + OpenType font Шрифт OpenType + Sans Serif Без засечек + Script Каллиграфические + Serif С засечками + Show Font Classes Показать классы шрифтов + Show Similar Fonts Показать похожие шрифты + Show Styles Показать начертания + Show Variable Fonts Показать вариативные шрифты + Slab Serif С брусковыми засечками + TrueType font Шрифт TrueType + Variable font Вариативный шрифт diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 4a5f7459df..4c59e8b6cf 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4219,3 +4219,31 @@ shape Appearance Izgled Ink Characteristics Karakteristike mastila Solidity: Punoća: Redrawing Ponovno iscrtavanje + Show Favorite Fonts Прикажи омиљене фонтове + No favorite fonts yet: click the star beside a font to add it. Још нема омиљених фонтова: кликните на звездицу поред фонта да бисте га додали. + Favorite fonts Омиљени фонтови + Recent font list Листа недавних фонтова + Add to Favorites Додај у омиљене + Remove from Favorites Уклони из омиљених + Show All Fonts Прикажи све фонтове + All Classes Све класе + Blackletter Готица + Decorative Декоративни + Font preview: Преглед фонта: + Handwritten Рукописни + Hide Font Classes Сакриј класе фонтова + Hide Styles Сакриј стилове + Monospace Фиксне ширине + No fonts match these filters. Ниједан фонт не одговара овим филтерима. + No similar fonts: the current font doesn't say what it looks like. Нема сличних фонтова: тренутни фонт не описује свој изглед. + OpenType font OpenType фонт + Sans Serif Без серифа + Script Скрипт + Serif Са серифима + Show Font Classes Прикажи класе фонтова + Show Similar Fonts Прикажи сличне фонтове + Show Styles Прикажи стилове + Show Variable Fonts Прикажи варијабилне фонтове + Slab Serif Плочасти серифи + TrueType font TrueType фонт + Variable font Варијабилни фонт diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 01c37a18b2..d0db2f65dc 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3876,3 +3876,31 @@ cameraData Lens Lens Ink Characteristics Mürekkep Özellikleri Solidity: Doluluk: Redrawing Yeniden çiziliyor + Show Favorite Fonts Favori yazı tiplerini göster + No favorite fonts yet: click the star beside a font to add it. Henüz favori yazı tipi yok: eklemek için bir yazı tipinin yanındaki yıldıza tıklayın. + Favorite fonts Favori yazı tipleri + Recent font list Son kullanılan yazı tipleri listesi + Add to Favorites Favorilere ekle + Remove from Favorites Favorilerden kaldır + Show All Fonts Tüm yazı tiplerini göster + All Classes Tüm sınıflar + Blackletter Gotik + Decorative Dekoratif + Font preview: Yazı tipi önizlemesi: + Handwritten El yazısı + Hide Font Classes Yazı tipi sınıflarını gizle + Hide Styles Stilleri gizle + Monospace Eş aralıklı + No fonts match these filters. Bu filtrelerle eşleşen yazı tipi yok. + No similar fonts: the current font doesn't say what it looks like. Benzer yazı tipi yok: geçerli yazı tipi görünümünü tanımlamıyor. + OpenType font OpenType yazı tipi + Sans Serif Tırnaksız + Script Kaligrafik + Serif Tırnaklı + Show Font Classes Yazı tipi sınıflarını göster + Show Similar Fonts Benzer yazı tiplerini göster + Show Styles Stilleri göster + Show Variable Fonts Değişken yazı tiplerini göster + Slab Serif Kalın tırnaklı + TrueType font TrueType yazı tipi + Variable font Değişken yazı tipi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 79ebc8df36..6067adcd00 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3843,3 +3843,31 @@ curves Smooth Згладити Sent to {printer} Надіслано на {printer} set in Print Settings… задається в параметрах друку… ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів + Show Favorite Fonts Показати вибрані шрифти + No favorite fonts yet: click the star beside a font to add it. Вибраних шрифтів ще немає: натисніть зірочку біля шрифту, щоб додати його. + Favorite fonts Вибрані шрифти + Recent font list Список останніх шрифтів + Add to Favorites Додати до вибраного + Remove from Favorites Видалити з вибраного + Show All Fonts Показати всі шрифти + All Classes Усі класи + Blackletter Готичні + Decorative Декоративні + Font preview: Попередній перегляд шрифту: + Handwritten Рукописні + Hide Font Classes Сховати класи шрифтів + Hide Styles Сховати накреслення + Monospace Моноширинні + No fonts match these filters. Жоден шрифт не відповідає цим фільтрам. + No similar fonts: the current font doesn't say what it looks like. Немає схожих шрифтів: поточний шрифт не описує свій вигляд. + OpenType font Шрифт OpenType + Sans Serif Без засічок + Script Каліграфічні + Serif Із засічками + Show Font Classes Показати класи шрифтів + Show Similar Fonts Показати схожі шрифти + Show Styles Показати накреслення + Show Variable Fonts Показати варіативні шрифти + Slab Serif Із брускуватими засічками + TrueType font Шрифт TrueType + Variable font Варіативний шрифт diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1fea5e6b38..38efd27527 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3631,3 +3631,31 @@ curves Smooth Làm mượt Sent to {printer} Đã gửi tới {printer} set in Print Settings… đặt trong thiết lập in… ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel + Show Favorite Fonts Hiển thị phông chữ yêu thích + No favorite fonts yet: click the star beside a font to add it. Chưa có phông chữ yêu thích: nhấp vào ngôi sao bên cạnh phông chữ để thêm. + Favorite fonts Phông chữ yêu thích + Recent font list Danh sách phông chữ gần đây + Add to Favorites Thêm vào mục yêu thích + Remove from Favorites Xóa khỏi mục yêu thích + Show All Fonts Hiển thị tất cả phông chữ + All Classes Tất cả các lớp + Blackletter Blackletter + Decorative Trang trí + Font preview: Xem trước phông chữ: + Handwritten Viết tay + Hide Font Classes Ẩn lớp phông chữ + Hide Styles Ẩn kiểu + Monospace Đơn cách + No fonts match these filters. Không có phông chữ nào khớp với các bộ lọc này. + No similar fonts: the current font doesn't say what it looks like. Không có phông chữ tương tự: phông chữ hiện tại không mô tả hình dáng của nó. + OpenType font Phông chữ OpenType + Sans Serif Không chân + Script Viết tay nghệ thuật + Serif Có chân + Show Font Classes Hiện lớp phông chữ + Show Similar Fonts Hiện phông chữ tương tự + Show Styles Hiện kiểu + Show Variable Fonts Hiện phông chữ biến thiên + Slab Serif Chân vuông + TrueType font Phông chữ TrueType + Variable font Phông chữ biến thiên diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 375b61c40b..4da7ca771c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2754,3 +2754,31 @@ curves Smooth 平滑 Sent to {printer} 已发送到 {printer} set in Print Settings… 在打印设置中设置… ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 + Show Favorite Fonts 显示收藏的字体 + No favorite fonts yet: click the star beside a font to add it. 还没有收藏的字体:点击字体旁边的星标即可添加。 + Favorite fonts 收藏的字体 + Recent font list 最近使用的字体列表 + Add to Favorites 添加到收藏 + Remove from Favorites 从收藏中移除 + Show All Fonts 显示所有字体 + All Classes 所有类别 + Blackletter 哥特体 + Decorative 装饰体 + Font preview: 字体预览: + Handwritten 手写体 + Hide Font Classes 隐藏字体类别 + Hide Styles 隐藏样式 + Monospace 等宽 + No fonts match these filters. 没有符合这些筛选条件的字体。 + No similar fonts: the current font doesn't say what it looks like. 没有相似字体:当前字体没有描述其外观。 + OpenType font OpenType 字体 + Sans Serif 无衬线 + Script 手写花体 + Serif 衬线 + Show Font Classes 显示字体类别 + Show Similar Fonts 显示相似字体 + Show Styles 显示样式 + Show Variable Fonts 显示可变字体 + Slab Serif 粗衬线 + TrueType font TrueType 字体 + Variable font 可变字体 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index de931038db..76720267db 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2739,3 +2739,31 @@ curves Smooth 平滑 Sent to {printer} 已傳送至 {printer} set in Print Settings… 在列印設定中設定… ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 + Show Favorite Fonts 顯示我的最愛字體 + No favorite fonts yet: click the star beside a font to add it. 尚無我的最愛字體:按一下字體旁的星號即可加入。 + Favorite fonts 我的最愛字體 + Recent font list 最近使用的字體清單 + Add to Favorites 加入我的最愛 + Remove from Favorites 從我的最愛移除 + Show All Fonts 顯示所有字體 + All Classes 所有類別 + Blackletter 哥德體 + Decorative 裝飾體 + Font preview: 字體預覽: + Handwritten 手寫體 + Hide Font Classes 隱藏字體類別 + Hide Styles 隱藏樣式 + Monospace 等寬 + No fonts match these filters. 沒有符合這些篩選條件的字體。 + No similar fonts: the current font doesn't say what it looks like. 沒有相似字體:目前的字體沒有描述其外觀。 + OpenType font OpenType 字體 + Sans Serif 無襯線 + Script 手寫花體 + Serif 襯線 + Show Font Classes 顯示字體類別 + Show Similar Fonts 顯示相似字體 + Show Styles 顯示樣式 + Show Variable Fonts 顯示可變字體 + Slab Serif 粗襯線 + TrueType font TrueType 字體 + Variable font 可變字體 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 4839fdfc76..ffe041c342 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -126,6 +126,9 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("stamp", include_bytes!("../../../assets/icons/stamp.svg")), ("star", include_bytes!("../../../assets/icons/star.svg")), ("star-filled", include_bytes!("../../../assets/icons/star-filled.svg")), + // PhotoCraft originals: the font menu's Show Similar Fonts and Show Variable Fonts filters. + ("font-similar", include_bytes!("../../../assets/icons/font-similar.svg")), + ("font-variable", include_bytes!("../../../assets/icons/font-variable.svg")), ("sun", include_bytes!("../../../assets/icons/sun.svg")), ("symmetry-diagonal", include_bytes!("../../../assets/icons/symmetry-diagonal.svg")), ("symmetry-dual", include_bytes!("../../../assets/icons/symmetry-dual.svg")), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 38118955c3..61332f3213 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -93,6 +93,7 @@ mod filter_preview_ui; #[cfg(not(target_arch = "wasm32"))] mod filter_preview_worker; pub mod flick_pan; +mod font_filters; mod font_preview; pub mod frame_tool; pub mod gallery_ui; diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_font_picker_tests.rs index f17032523d..ed18a902f0 100644 --- a/crates/ui-egui/src/type_font_picker_tests.rs +++ b/crates/ui-egui/src/type_font_picker_tests.rs @@ -1,5 +1,7 @@ //! The Type tool's searchable font menu (#1369): it keeps its height and focuses its search field. +use std::collections::HashMap; + use super::font_picker_in; use egui::accesskit::Role; use egui::{Key, Modifiers, Rect, vec2}; @@ -490,3 +492,257 @@ fn wheel_family_index_clamps_to_the_ends() { assert_eq!(super::wheel_family_index(1, 3, 0.0), None); assert_eq!(super::wheel_family_index(0, 0, -1.0), None); } + +/// A picker over the test families with a recent/favourite library; the library is kept in the +/// state so a test can read the star that was clicked. +struct LibState { + current: String, + families: Vec, + library: super::FontLibrary, +} + +fn library_harness(recent: &[&str], favorites: &[&str]) -> Harness<'static, LibState> { + library_harness_with(recent, favorites, None, None) +} + +fn library_harness_with( + recent: &[&str], + favorites: &[&str], + traits: Option, + styles: Option>>, +) -> Harness<'static, LibState> { + let mut families: Vec = (0..20).map(|i| format!("Family {i:02}")).collect(); + families.push("Zeta Sans".into()); + let library = super::FontLibrary { + recent: recent.iter().map(|s| s.to_string()).collect(), + favorites: favorites.iter().map(|s| s.to_string()).collect(), + traits: traits.map(std::sync::Arc::new), + styles: styles.map(std::sync::Arc::new), + ..Default::default() + }; + let state = LibState { current: "Family 00".into(), families, library }; + let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state( + |ui, s: &mut LibState| { + let fams = s.families.clone(); + super::family_picker_in(ui, "type-font", &mut s.current, 170.0, &fams, FontPreview::Medium, &mut s.library); + }, + state, + ); + h.run(); + h.query_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run(); + h +} + +/// The tops of every row labelled `label`, top to bottom. +fn row_tops(h: &Harness<'static, LibState>, label: &str) -> Vec { + let mut tops: Vec = h.query_all_by_label(label).map(|n| n.rect().top()).collect(); + tops.sort_by(f32::total_cmp); + tops +} + +#[test] +fn recent_fonts_come_first_and_stay_in_the_alphabetical_list() { + let h = library_harness(&["Zeta Sans", "Family 05", "Not Installed"], &[]); + let zeta = row_tops(&h, "Zeta Sans"); + let five = row_tops(&h, "Family 05"); + let first = row_tops(&h, "Family 00"); + assert_eq!(zeta.len(), 2, "Zeta Sans is listed as recent and in its alphabetical place"); + assert_eq!(five.len(), 2); + assert!(zeta[0] < five[0] && five[0] < first[0], "recent first, most recent on top: {zeta:?} {five:?} {first:?}"); + assert!(h.query_by_label("Not Installed").is_none(), "a recent font that is no longer installed isn't listed"); +} + +#[test] +fn a_search_hides_the_recent_section() { + let mut h = library_harness(&["Zeta Sans"], &[]); + h.get_by_role(Role::TextInput).type_text("zeta"); + h.run(); + assert_eq!(row_tops(&h, "Zeta Sans").len(), 1); +} + +#[test] +fn clicking_a_star_marks_the_font_without_picking_it_or_closing_the_menu() { + let mut h = library_harness(&[], &[]); + let row = h.get_by_label("Family 03").rect(); + // The star sits left of the style expander's slot, which is left of the row's button. + let star = egui::pos2(row.left() - 2.0 - 16.0 - 2.0 - 11.0, row.center().y); + h.hover_at(star); + h.run(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: star, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run(); + } + assert_eq!(h.state().library.toggled.as_deref(), Some("Family 03")); + assert_eq!(h.state().current, "Family 00", "the star doesn't pick the font"); + assert!(h.query_by_label("Family 10").is_some(), "the menu stays open"); +} + +#[test] +fn the_favorites_filter_lists_only_starred_fonts() { + let mut h = library_harness(&["Family 01"], &["Zeta Sans", "Family 07"]); + assert_eq!(h.query_all_by_label("Remove from Favorites").count(), 2, "starred rows show a filled star"); + h.get_by_label("Show Favorite Fonts").click(); + h.run(); + assert!(h.query_by_label("Zeta Sans").is_some() && h.query_by_label("Family 07").is_some()); + assert!(h.query_by_label("Family 01").is_none(), "neither other fonts nor the recent section show"); + assert!(h.query_by_label("Family 02").is_none()); +} + +#[test] +fn the_favorites_filter_explains_an_empty_library() { + let mut h = library_harness(&[], &[]); + h.get_by_label("Show Favorite Fonts").click(); + h.run(); + assert!(h.query_by_label_contains("No favorite fonts yet").is_some()); +} + +#[test] +fn a_clicked_star_is_saved_to_the_preferences_library() { + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let mut library = super::FontLibrary::of(&app); + library.toggled = Some("Bebas Neue".into()); + library.finish(&mut app); + assert_eq!(app.session.prefs().type_.favorite_fonts, ["Bebas Neue"]); + assert_eq!(super::FontLibrary::of(&app).favorites, ["Bebas Neue"]); + super::note_recent_font(&mut app, "Arial"); + assert_eq!(super::FontLibrary::of(&app).recent, ["Arial"]); +} + +fn traits(class: photocraft_text::FontClass, format: photocraft_text::FontFormat, panose: [u8; 10]) -> Option { + Some(photocraft_text::FamilyTraits { class: Some(class), format, panose, weight: 400 }) +} + +/// Family 00-02 serif, 03 a variable sans, 04 monospace, Zeta Sans a sans like 03; the rest +/// unknown. Family 01 has three styles. +fn filter_harness() -> Harness<'static, LibState> { + use photocraft_text::{FontClass, FontFormat}; + let serif = [2, 2, 6, 3, 5, 4, 5, 2, 3, 4]; + let sans = [2, 11, 6, 4, 2, 2, 2, 2, 2, 4]; + let map: crate::font_filters::TraitsMap = [ + ("Family 00", traits(FontClass::Serif, FontFormat::TrueType, serif)), + ("Family 01", traits(FontClass::Serif, FontFormat::OpenType, serif)), + ("Family 02", traits(FontClass::Serif, FontFormat::TrueType, serif)), + ("Family 03", traits(FontClass::SansSerif, FontFormat::Variable, sans)), + ("Family 04", traits(FontClass::Monospace, FontFormat::TrueType, [2, 11, 6, 9, 2, 2, 2, 2, 2, 4])), + ("Zeta Sans", traits(FontClass::SansSerif, FontFormat::TrueType, sans)), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let styles: HashMap> = + [("Family 01".to_string(), vec!["Regular".to_string(), "Bold".to_string(), "Italic".to_string()])].into_iter().collect(); + library_harness_with(&[], &[], Some(map), Some(styles)) +} + +#[test] +fn the_class_list_narrows_the_fonts_and_all_classes_brings_them_back() { + let mut h = filter_harness(); + h.get_by_label("Serif").click(); + h.run(); + for f in ["Family 00", "Family 01", "Family 02"] { + assert!(h.query_by_label(f).is_some(), "{f} is a serif"); + } + assert!(h.query_by_label("Family 03").is_none() && h.query_by_label("Zeta Sans").is_none()); + h.get_by_label("Monospace").click(); + h.run(); + assert!(h.query_by_label("Family 04").is_some() && h.query_by_label("Family 00").is_none()); + h.get_by_label("All Classes").click(); + h.run(); + assert!(h.query_by_label("Family 10").is_some(), "unclassified fonts are back"); +} + +#[test] +fn variable_and_similar_filters_and_clear_all() { + let mut h = filter_harness(); + h.get_by_label("Show Variable Fonts").click(); + h.run(); + assert!(h.query_by_label("Family 03").is_some()); + assert!(h.query_by_label("Family 00").is_none() && h.query_by_label("Zeta Sans").is_none()); + h.get_by_label("Clear All").click(); + h.run(); + assert!(h.query_by_label("Family 10").is_some(), "Clear All turns every filter off"); + // Similar to the current Family 00 (a serif): the serifs first, sans after, unknown never. + h.get_by_label("Show Similar Fonts").click(); + h.run(); + let top = |label: &str| h.query_by_label(label).map(|n| n.rect().top()); + let (current, serif, sans) = (top("Family 00").unwrap(), top("Family 02").unwrap(), top("Zeta Sans").unwrap()); + assert!(current < serif && serif < sans, "{current} {serif} {sans}"); + assert!(h.query_by_label("Family 10").is_none(), "fonts that can't be compared aren't listed"); +} + +#[test] +fn a_style_picked_under_the_expander_picks_the_family_in_that_style() { + let mut h = filter_harness(); + assert_eq!(h.query_all_by_label("Show Styles").count(), 1, "only a family with several styles expands"); + h.get_by_label("Show Styles").click(); + h.run(); + h.get_by_label("Bold").click(); + h.run(); + assert_eq!(h.state().current, "Family 01"); + assert_eq!(h.state().library.picked_style.as_deref(), Some("Bold")); + assert!(h.query_by_label("Family 10").is_none(), "picking a style closes the menu"); +} + +#[test] +fn the_search_field_stays_in_place_while_the_list_scrolls() { + let mut h = library_harness(&[], &[]); + let search = h.get_by_role(Role::TextInput).rect(); + let row = h.get_by_label("Family 01").rect(); + h.hover_at(row.center()); + h.run(); + h.event(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, -300.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE }); + h.run_steps(4); + assert_eq!(h.get_by_role(Role::TextInput).rect(), search, "the field doesn't scroll away"); + assert!(h.query_by_label("Family 01").is_none_or(|n| n.rect().top() < row.top()), "the list scrolled"); +} + +#[test] +fn the_preview_follows_the_font_under_the_pointer_and_the_menu_keeps_its_width() { + let mut h = library_harness(&[], &[]); + assert!(h.query_by_label("Font preview: Family 00").is_some(), "the current font first"); + let width = popup_width(&h); + h.hover_at(h.get_by_label("Family 03").rect().center()); + h.run_steps(3); + assert!(h.query_by_label("Font preview: Family 03").is_some()); + // Filtering never widens the menu past its list (no empty strip). + h.get_by_label("Show Favorite Fonts").click(); + h.run_steps(3); + assert!((popup_width(&h) - width).abs() < 1.0, "{} vs {width}", popup_width(&h)); +} + +fn popup_width(h: &Harness<'static, LibState>) -> f32 { + let preview = h.query_all_by_label_contains("Font preview:").next().unwrap().rect(); + preview.width() +} + +#[test] +fn the_preview_sets_the_type_layers_text_or_the_selection_being_typed() { + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert_eq!(super::preview_text(&app), None, "no document"); + app.run("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + let id = app.run("type.create", serde_json::json!({"text": "Hello\rworld ", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", serde_json::json!({"id": id})).ok(); + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id, + caret: 0, + anchor: 0, + session: "s".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + assert_eq!(super::preview_text(&app).as_deref(), Some("Hello world"), "the whole text, on one line"); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 6; + ed.caret = 11; + } + assert_eq!(super::preview_text(&app).as_deref(), Some("world"), "only the selection while typing"); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 50; + ed.caret = 400; + } + assert_eq!(super::preview_text(&app), None, "an out-of-range selection is blank, not a panic"); +} diff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/type_panels_ui.rs index 499e8eac44..8ec038689e 100644 --- a/crates/ui-egui/src/type_panels_ui.rs +++ b/crates/ui-egui/src/type_panels_ui.rs @@ -373,6 +373,8 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s let defined = |attrs: &Value, k: &str| attrs.get(k).is_some(); // Preferences ▸ Type ▸ Font Preview Size sizes the family picker's samples. let preview = app.session.prefs().type_.font_preview; + // The font picker's favourites and recent fonts; a star clicked in it is applied below. + let mut library = crate::type_tool::FontLibrary::of(app); // Preferences ▸ Units & Rulers ▸ Type: the model stores points; the fields may show pixels // (by the document's resolution) or millimetres. let (type_unit, unit_label) = crate::type_tool::type_unit(app); @@ -399,7 +401,7 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s ui.add_enabled_ui(on, |ui| match kind { "font" => { let mut f = v.as_str().unwrap_or("").to_string(); - if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f, preview) { + if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f, preview, &mut library) { set = Some(json!({ panel: f })); } } @@ -495,6 +497,7 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s } } }); + library.finish(app); if let Some(attrs) = set { let _ = run(app, &format!("{prefix}.set"), json!({ "id": id, "attrs": attrs })); } @@ -517,13 +520,19 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s } } -/// Searchable family combo box. -fn family_picker(ui: &mut egui::Ui, salt: &str, current: &mut String, preview: photocraft_engine::prefs::FontPreview) -> bool { +/// Searchable family combo box, starring and listing first the fonts of `library`. +fn family_picker( + ui: &mut egui::Ui, + salt: &str, + current: &mut String, + preview: photocraft_engine::prefs::FontPreview, + library: &mut crate::type_tool::FontLibrary, +) -> bool { if !crate::type_tool::fonts_ready(ui, 140.0) { return false; } let mut shown = if current.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { current.clone() }; - let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families(), preview); + let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families(), preview, library); if changed { *current = shown; } @@ -617,7 +626,10 @@ pub fn glyphs_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Font family + style. ui.horizontal(|ui| { let mut f = family.clone(); - if family_picker(ui, "glyph-family", &mut f, app.session.prefs().type_.font_preview) { + let mut library = crate::type_tool::FontLibrary::of(app); + let picked = family_picker(ui, "glyph-family", &mut f, app.session.prefs().type_.font_preview, &mut library); + library.finish(app); + if picked { app.ui.type_panels.glyph_family = f; app.ui.type_panels.glyph_style = tl!("Regular").into(); } diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index f00fb57157..f8f96b3385 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1397,18 +1397,103 @@ pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool { false } -/// Searchable font-family combo box. -fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32, preview: photocraft_engine::prefs::FontPreview) -> bool { - family_picker_in(ui, "type-font", current, width, &families(), preview) +/// The font menu's local library (`photocraft_engine::font_library_cmds`): the recent fonts it +/// lists first and the favourites it stars, read before the menu is drawn, plus the font whose +/// star was clicked, starred or un-starred by [`FontLibrary::finish`] afterwards, and the style +/// picked from a family's expanded styles. +#[derive(Clone, Debug, Default)] +pub(crate) struct FontLibrary { + pub recent: Vec, + pub favorites: Vec, + pub toggled: Option, + /// The style picked under a family's ">" (with the family), for the caller to apply. + pub picked_style: Option, + /// Family traits to filter by instead of the installed fonts' (tests). + pub traits: Option>, + /// Each family's style names instead of the installed fonts' (tests). + pub styles: Option>>>, + /// The user's own text for the preview at the top of the menu (else it shows a sample). + pub preview_text: Option, } -/// Maximum height of the font menu. -const FONT_MENU_HEIGHT: f32 = 460.0; +/// The text the font menu's preview sets: the selected characters while typing, else the type +/// target's whole text, on one line and at most 60 characters. `None` without a type target or +/// with blank text (the preview then shows its sample). +fn preview_text(app: &PhotocraftApp) -> Option { + let (layer, range) = target(app)?; + let text = &text_layer(&app.session.active()?.doc, LayerId(layer))?.text; + let chosen: String = match range { + Some([a, b]) => text.chars().skip(a).take(b.saturating_sub(a)).collect(), + None => text.clone(), + }; + let line = chosen.split(['\n', '\r', '\u{2028}', '\u{2029}']).map(str::trim).filter(|s| !s.is_empty()).collect::>().join(" "); + let line: String = line.chars().take(60).collect(); + (!line.is_empty()).then_some(line) +} + +impl FontLibrary { + pub(crate) fn of(app: &PhotocraftApp) -> Self { + use photocraft_engine::font_library_cmds as lib; + Self { recent: lib::recent_fonts(&app.session), favorites: lib::favorite_fonts(&app.session), ..Default::default() } + } + + /// The style names a family's ">" expands to. + fn styles_of(&self, family: &str) -> Vec { + match &self.styles { + Some(map) => map.get(family).cloned().unwrap_or_else(|| vec!["Regular".into()]), + None => styles(family), + } + } + + /// Star or un-star the clicked font, through the engine command. + pub(crate) fn finish(self, app: &mut PhotocraftApp) { + if let Some(family) = self.toggled + && let Err(e) = app.run("type.font.favorite", json!({"family": family})) + { + app.ui.status = e; + } + } +} + +/// Record `family` as just used, for the font menu's recent fonts. +pub(crate) fn note_recent_font(app: &mut PhotocraftApp, family: &str) { + if let Err(e) = app.run("type.font.noteRecent", json!({"family": family})) { + app.ui.status = e; + } +} + +/// Searchable font-family combo box, with the recent and favourite fonts of `app`. `Some` when a +/// family was picked, holding the style when it was picked from the family's expanded styles. +fn font_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, current: &mut String, width: f32) -> Option> { + let preview = app.session.prefs().type_.font_preview; + let mut library = FontLibrary { preview_text: preview_text(app), ..FontLibrary::of(app) }; + let changed = family_picker_in(ui, "type-font", current, width, &families(), preview, &mut library); + let style = library.picked_style.take(); + library.finish(app); + if !changed { + return None; + } + note_recent_font(app, current); + Some(style) +} + +/// Maximum height of the font menu: room for the search/filter bar over the font list, so only +/// the list scrolls. +const FONT_MENU_HEIGHT: f32 = 520.0; +/// The font list's height (it scrolls inside the menu, under the fixed search field). +const FONT_LIST_HEIGHT: f32 = 440.0; +/// The font list's width: star, style expander, name, format badge and sample. +const FONT_LIST_WIDTH: f32 = 420.0; +/// Room the search row keeps for Clear All, and for the filter buttons when they follow the field. +const FONT_CLEAR_WIDTH: f32 = 84.0; +const FONT_BUTTONS_WIDTH: f32 = 112.0; +/// Room for the format badge (O, TT, VAR) left of the sample. +const FONT_BADGE_WIDTH: f32 = 28.0; /// [`font_picker`] over a given family list (tests pass their own). #[cfg(test)] fn font_picker_in(ui: &mut egui::Ui, current: &mut String, width: f32, families: &[String], preview: photocraft_engine::prefs::FontPreview) -> bool { - family_picker_in(ui, "type-font", current, width, families, preview) + family_picker_in(ui, "type-font", current, width, families, preview, &mut FontLibrary::default()) } /// Shared by the Type options, Character, style and Glyphs panels. Selection changes still @@ -1420,6 +1505,7 @@ pub(crate) fn family_picker_in( width: f32, families: &[String], preview: photocraft_engine::prefs::FontPreview, + library: &mut FontLibrary, ) -> bool { let mut changed = false; let search_id = ui.id().with(("font-search", salt)); @@ -1438,7 +1524,7 @@ pub(crate) fn family_picker_in( .close_behavior(if matches!(close, egui::PopupCloseBehavior::IgnoreClicks) { close } else { egui::PopupCloseBehavior::CloseOnClickOutside }); let response = combo.show_ui(ui, |ui| { - let (pass_id, focus_id, height_id) = (search_id.with("pass"), search_id.with("focus"), search_id.with("height")); + let (pass_id, focus_id) = (search_id.with("pass"), search_id.with("focus")); let pass = ui.ctx().cumulative_pass_nr(); let last_pass: Option = ui.data(|d| d.get_temp(pass_id)); // Freshly opened (not drawn last pass): focus the search field whatever the query, and keep @@ -1450,7 +1536,58 @@ pub(crate) fn family_picker_in( let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); let enter = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); - let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text(tl!("Search fonts")).desired_width(200.0)); + // The filter bar beside the search field, as in Photoshop: the class list toggle, Show + // Variable / Favorite / Similar Fonts and Clear All (`font_filters`). + let filters_id = search_id.with("filters"); + let mut filters: crate::font_filters::FontFilters = ui.data(|d| d.get_temp(filters_id)).unwrap_or_default(); + // The preview on top: the font last under the pointer, else the current one. + let preview_id = search_id.with("preview-font"); + if opened { + ui.data_mut(|d| d.remove::(preview_id)); + } + let previewed: String = ui.data(|d| d.get_temp(preview_id)).unwrap_or_else(|| current.clone()); + let previewed_label = labels.and_then(|l| l.get(previewed.as_str())).map_or(previewed.as_str(), String::as_str).to_string(); + // Everything above the list is as wide as the class and font lists below, measured last + // frame: never wider, so the menu has no empty strip beside the list. + let (list_left_id, body_id) = (search_id.with("list-left"), search_id.with("body")); + let class_w = crate::font_filters::CLASS_COLUMN_WIDTH; + let estimate = FONT_LIST_WIDTH + 16.0 + if filters.hide_classes { 0.0 } else { class_w + 14.0 }; + let body: Option = ui.data(|d| d.get_temp(body_id)); + let menu_width = body.map_or(estimate, |b| b.width()); + // Divider lines span the space they are given: cap it, or they stretch the menu. + if body.is_some() { + ui.set_max_width(menu_width); + } + crate::font_filters::preview_banner(ui, &previewed, &previewed_label, library.preview_text.as_deref(), menu_width); + // The filter buttons over the class list, and the search field over the fonts, starting + // where the list does. + let list_left: Option = ui.data(|d| d.get_temp(list_left_id)); + let menu_right = body.map(|b| b.right()); + let r = ui + .horizontal(|ui| { + if !filters.hide_classes { + ui.allocate_ui_with_layout(egui::vec2(class_w, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + crate::font_filters::filter_buttons(ui, &mut filters); + }); + } + if let Some(x) = list_left.filter(|_| !filters.hide_classes) { + let pad = x - ui.cursor().min.x; + if pad > 0.0 { + ui.add_space(pad); + } + } + // The field fills the row up to Clear All (and the buttons, which follow it when + // the class list is hidden). + let trailing = FONT_CLEAR_WIDTH + if filters.hide_classes { FONT_BUTTONS_WIDTH } else { 0.0 }; + let search_w = menu_right.map_or(FONT_LIST_WIDTH - trailing, |right| right - ui.cursor().min.x - trailing).clamp(120.0, FONT_LIST_WIDTH); + let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text(tl!("Search fonts")).desired_width(search_w)); + if filters.hide_classes { + crate::font_filters::filter_buttons(ui, &mut filters); + } + crate::font_filters::clear_all(ui, &mut filters); + r + }) + .inner; if r.has_focus() { focus = false; } else if focus { @@ -1462,7 +1599,9 @@ pub(crate) fn family_picker_in( d.insert_temp(search_id, q.clone()); }); let ql = q.to_lowercase(); - let rows = font_menu_rows(families, labels, &ql); + let lookup = crate::font_filters::lookup_in(library.traits.clone()); + let mut rows = font_menu_rows(families, labels, &ql); + let comparable = crate::font_filters::apply(&mut rows, &filters, &library.favorites, current, &lookup); if down || up { let index = rows.iter().position(|(f, _)| *f == current); let next = match index { @@ -1485,45 +1624,155 @@ pub(crate) fn family_picker_in( } let preview = crate::font_preview::sample(preview); let row_h = preview.map_or(28.0, |(_, [_, h])| (h + 4.0).max(28.0)); - + // The recently used fonts come first, above a line, as in Photoshop; they stay in the + // alphabetical list too. Not while searching or filtering. + let recent: Vec<(&String, &str)> = if ql.is_empty() && !filters.any() { + library + .recent + .iter() + .filter_map(|r| families.iter().find(|f| *f == r)) + .map(|f| (f, labels.and_then(|l| l.get(f)).map_or(f.as_str(), String::as_str))) + .collect() + } else { + Vec::new() + }; + let expanded_id = search_id.with("expanded"); + let mut expanded: Vec = ui.data(|d| d.get_temp(expanded_id)).unwrap_or_default(); let mut hovered: Option = None; - for (f, label) in rows { - let mut button = egui::Button::selectable(f == current, label).truncate(); - if let Some((size, [_, h])) = preview { - button = - button.right_text(egui::Atom::custom(ui.id().with(("font-sample", f)), egui::vec2(crate::font_preview::slot_width(ui.ctx(), f, size), h))); + ui.separator(); + let body = ui.horizontal_top(|ui| { + if !filters.hide_classes { + crate::font_filters::class_list(ui, &mut filters); + ui.separator(); } - let response = ui.add_sized([330.0, row_h], button); - if (down || up) && f == current { - response.scroll_to_me(Some(egui::Align::Center)); + // The list scrolls under the fixed search field and filters, and keeps one height + // whatever it holds (egui never grows a popup back after a short list, #1369). + let list = egui::ScrollArea::vertical().id_salt(search_id.with("list")).max_height(FONT_LIST_HEIGHT).auto_shrink([true, false]); + // Top to bottom, though the list sits beside the class list. + let shown = list.show(ui, |ui| { + ui.vertical(|ui| { + ui.set_width(FONT_LIST_WIDTH); + let weak = |ui: &mut egui::Ui, text: &str| { + ui.label(egui::RichText::new(text).weak()); + }; + if filters.similar && !comparable { + weak(ui, tl!("No similar fonts: the current font doesn't say what it looks like.")); + } + if rows.is_empty() { + weak( + ui, + if filters.favorites && library.favorites.is_empty() { + tl!("No favorite fonts yet: click the star beside a font to add it.") + } else { + tl!("No fonts match these filters.") + }, + ); + } + let entries = recent.iter().map(|(f, l)| (*f, *l, true)).chain(rows.iter().map(|(f, l)| (*f, *l, false))).collect::>(); + let mut in_recent = false; + for (f, label, recent_row) in entries { + if in_recent && !recent_row { + ui.separator(); + } + in_recent = recent_row; + // Only rows on screen read their font's format and styles. + let visible = ui.is_rect_visible(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(FONT_LIST_WIDTH, row_h))); + let format = if visible { lookup(f).map(|t| t.format) } else { None }; + let styles = if visible { library.styles_of(f) } else { Vec::new() }; + let open = !recent_row && expanded.contains(f); + let favorite = library.favorites.contains(f); + let slot = preview.map_or(0.0, |(size, _)| crate::font_preview::slot_width(ui.ctx(), f, size)); + let mut button = egui::Button::selectable(f == current, label).truncate(); + let [_, h] = preview.map_or([0.0, 16.0], |(_, b)| b); + button = button.right_text(egui::Atom::custom(ui.id().with(("font-sample", f, recent_row)), egui::vec2(slot + FONT_BADGE_WIDTH, h))); + let response = ui + .allocate_ui_with_layout(egui::vec2(FONT_LIST_WIDTH, row_h), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 2.0; + // The star adds the font to (or removes it from) the favourites; it never picks it. + let tip = if favorite { tl!("Remove from Favorites") } else { tl!("Add to Favorites") }; + if crate::icons::button(ui, if favorite { "star-filled" } else { "star" }, 22.0, false, tip).clicked() { + library.toggled = Some(f.clone()); + } + // A family with several styles expands to list them (">"). + if styles.len() > 1 && !recent_row { + let (icon, tip) = if open { ("chevron-down", tl!("Hide Styles")) } else { ("chevron-right", tl!("Show Styles")) }; + if crate::icons::button(ui, icon, 16.0, false, tip).clicked() { + if open { + expanded.retain(|e| e != f); + } else { + expanded.push(f.clone()); + } + } + } else { + ui.add_space(16.0); + } + ui.add_sized([ui.available_width(), row_h], button) + }) + .inner; + if (down || up) && f == current && !recent_row { + response.scroll_to_me(Some(egui::Align::Center)); + } + if let Some((size, _)) = preview + && ui.is_rect_visible(response.rect) + { + crate::font_preview::paint(ui, f, response.rect, size); + } + // The format badge (O, TT, VAR) just left of the sample. + if let Some(format) = format { + let center = egui::pos2(response.rect.right() - 8.0 - slot - FONT_BADGE_WIDTH / 2.0, response.rect.center().y); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().text(center, egui::Align2::CENTER_CENTER, format.badge(), egui::FontId::proportional(10.0), t.text_dim); + let tip = egui::Rect::from_center_size(center, egui::vec2(FONT_BADGE_WIDTH, 14.0)); + ui.interact(tip, ui.id().with(("font-format", f, recent_row)), egui::Sense::hover()) + .on_hover_text(crate::font_filters::format_tip(format)); + } + if response.hovered() { + hovered = Some(f.clone()); + } + if press.chosen(ui, &response) { + *current = f.clone(); + // A served family not fetched yet: start now, before any text needs it. + photocraft_text::served::request(f); + changed = true; + ui.data_mut(|d| d.remove::(search_id)); + hovered = None; + ui.close(); + } + if !open { + continue; + } + // The family's styles, each picking the family in that style. + for style in &styles { + let picked = ui + .horizontal(|ui| { + ui.add_space(46.0); + ui.add_sized([ui.available_width(), 22.0], egui::Button::selectable(false, style_label(style)).truncate()) + }) + .inner; + if picked.clicked() { + *current = f.clone(); + photocraft_text::served::request(f); + library.picked_style = Some(style.clone()); + changed = true; + ui.data_mut(|d| d.remove::(search_id)); + hovered = None; + ui.close(); + } + } + } + }) + }); + ui.data_mut(|d| d.insert_temp(list_left_id, shown.inner_rect.left())); + }); + let body = body.response.rect; + ui.data_mut(|d| { + d.insert_temp(filters_id, filters); + d.insert_temp(expanded_id, expanded); + d.insert_temp(body_id, body); + if let Some(f) = &hovered { + d.insert_temp(preview_id, f.clone()); } - if let Some((size, _)) = preview - && ui.is_rect_visible(response.rect) - { - crate::font_preview::paint(ui, f, response.rect, size); - } - if response.hovered() { - hovered = Some(f.clone()); - } - if press.chosen(ui, &response) { - *current = f.clone(); - // A served family not fetched yet: start now, before any text needs it. - photocraft_text::served::request(f); - changed = true; - ui.data_mut(|d| d.remove::(search_id)); - hovered = None; - ui.close(); - } - } - // egui measures a popup only when it opens and never lets it grow back, so a filtered - // list would leave the menu short after the query is cleared (#1369). Keep the unfiltered - // height while searching. - if ql.is_empty() { - let h = ui.min_rect().height(); - ui.data_mut(|d| d.insert_temp(height_id, h)); - } else if let Some(h) = ui.data(|d| d.get_temp::(height_id)) { - ui.set_min_height(h.min(FONT_MENU_HEIGHT)); - } + }); if accept { None } else { hovered } }); press.after(&response.response); @@ -1713,12 +1962,22 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // Font family and style menus (one placeholder in their place while the fonts load). if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { - if font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview) { + if let Some(picked) = font_picker(app, ui, &mut fam, 170.0) { app.ui.tool_options.type_font = fam.clone(); let st = styles(&fam); - style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) }; + let picked = picked.filter(|s| st.contains(s)); + style = match &picked { + Some(s) => s.clone(), + None if st.contains(&style) => style, + None => st.first().cloned().unwrap_or_else(|| "Regular".into()), + }; app.ui.tool_options.type_style = style.clone(); - apply(app, ui.ctx(), json!({"font": fam})); + // Only a style picked under the family's ">" is set: otherwise each selected layer + // keeps its own face in the new family (#3556). + match picked { + Some(s) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": s})), + None => apply(app, ui.ctx(), json!({"font": fam})), + } } let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), style_label(&s))).collect(); let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); @@ -2131,9 +2390,12 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa let mut ready = true; row(ui, &mut |ui| { ready = fonts_ready(ui, full); - if ready && font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview) { + if ready && let Some(picked) = font_picker(app, ui, &mut fam, full) { app.ui.tool_options.type_font = fam.clone(); - apply(app, ui.ctx(), json!({"font": fam})); + match picked { + Some(style) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": style})), + None => apply(app, ui.ctx(), json!({"font": fam})), + } } }); row(ui, &mut |ui| { diff --git a/docs/scorecard.md b/docs/scorecard.md index 92f9315ebd..c02e3783f3 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) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 157 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 159 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 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: 26 of 157** (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: 25 of 159** (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_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `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`. +Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `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`, `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 | |---|---|---|---|---| From bed6d0931c2301921f2ebf9edb73503767f78ffc Mon Sep 17 00:00:00 2001 From: D-monized <341904702+D-monized@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:36:37 -0600 Subject: [PATCH 10/87] Font menu: no empty strip beside the list after the window moves the menu The menu kept the list's left edge and its own right edge as screen positions from the previous frame. When the window's edge pushed the popup (after a minimize and restore, or from the Character panel near the right edge), those went stale, the search row padded out to the old position and widened the menu, which was pushed further left, settling 214 px wider than its lists. They are now kept relative to the menu's left edge. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/type_font_picker_tests.rs | 53 +++++++++++++++++++- crates/ui-egui/src/type_tool.rs | 20 ++++++-- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_font_picker_tests.rs index ed18a902f0..534829bddb 100644 --- a/crates/ui-egui/src/type_font_picker_tests.rs +++ b/crates/ui-egui/src/type_font_picker_tests.rs @@ -499,6 +499,7 @@ struct LibState { current: String, families: Vec, library: super::FontLibrary, + popup: egui::Id, } fn library_harness(recent: &[&str], favorites: &[&str]) -> Harness<'static, LibState> { @@ -520,10 +521,11 @@ fn library_harness_with( styles: styles.map(std::sync::Arc::new), ..Default::default() }; - let state = LibState { current: "Family 00".into(), families, library }; + let state = LibState { current: "Family 00".into(), families, library, popup: egui::Id::NULL }; let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state( |ui, s: &mut LibState| { let fams = s.families.clone(); + s.popup = ui.make_persistent_id(egui::IdSalt::new("type-font")).with("popup"); super::family_picker_in(ui, "type-font", &mut s.current, 170.0, &fams, FontPreview::Medium, &mut s.library); }, state, @@ -746,3 +748,52 @@ fn the_preview_sets_the_type_layers_text_or_the_selection_being_typed() { } assert_eq!(super::preview_text(&app), None, "an out-of-range selection is blank, not a panic"); } + +/// Minimizing the window (a zero-size screen for a few frames) and restoring it must not leave +/// the menu wider than its lists: an empty strip appeared beside the list after a minimize. +#[test] +fn minimizing_and_restoring_the_window_keeps_the_menu_as_wide_as_its_lists() { + let mut h = library_harness(&[], &[]); + h.set_size(vec2(1286.0, 900.0)); + h.run_steps(3); + let width = |h: &Harness<'static, LibState>| h.ctx.memory(|m| m.area_rect(h.state().popup)).map(|r| r.width()); + let before = width(&h).expect("menu open"); + for size in [vec2(1.0, 1.0), vec2(0.0, 0.0), vec2(1286.0, 900.0)] { + h.set_size(size); + h.run_steps(3); + } + let after = width(&h).expect("menu still open"); + assert!((after - before).abs() < 1.0, "menu width {after} after a minimize, {before} before"); +} + +/// The same with the font button near the right edge, as in the Character panel, where the +/// popup is pushed left against the window's edge. +#[test] +fn a_menu_opened_from_the_right_edge_stays_narrow_after_a_minimize() { + let mut families: Vec = (0..20).map(|i| format!("Family {i:02}")).collect(); + families.push("Zeta Sans".into()); + let state = LibState { current: "Family 00".into(), families, library: Default::default(), popup: egui::Id::NULL }; + let mut h = Harness::builder().with_size(vec2(1286.0, 900.0)).build_ui_state( + |ui, s: &mut LibState| { + ui.horizontal(|ui| { + ui.add_space(940.0); + s.popup = ui.make_persistent_id(egui::IdSalt::new("type-font")).with("popup"); + let fams = s.families.clone(); + super::family_picker_in(ui, "type-font", &mut s.current, 300.0, &fams, FontPreview::Medium, &mut s.library); + }); + }, + state, + ); + h.run(); + h.query_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run_steps(4); + let width = |h: &Harness<'static, LibState>| h.ctx.memory(|m| m.area_rect(h.state().popup)).map(|r| r.width()); + let before = width(&h).expect("menu open"); + for size in [vec2(0.0, 0.0), vec2(300.0, 200.0), vec2(1286.0, 900.0)] { + h.set_size(size); + h.run_steps(4); + } + h.run_steps(4); + let after = width(&h).expect("menu open again"); + assert!(after <= before + 1.0, "menu width {after} after a minimize, {before} before"); +} diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index f8f96b3385..b2f71779e1 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1487,6 +1487,8 @@ const FONT_LIST_WIDTH: f32 = 420.0; /// Room the search row keeps for Clear All, and for the filter buttons when they follow the field. const FONT_CLEAR_WIDTH: f32 = 84.0; const FONT_BUTTONS_WIDTH: f32 = 112.0; +/// Room right of the font list's viewport for its scroll bar. +const FONT_SCROLL_BAR_WIDTH: f32 = 14.0; /// Room for the format badge (O, TT, VAR) left of the sample. const FONT_BADGE_WIDTH: f32 = 28.0; @@ -1524,6 +1526,10 @@ pub(crate) fn family_picker_in( .close_behavior(if matches!(close, egui::PopupCloseBehavior::IgnoreClicks) { close } else { egui::PopupCloseBehavior::CloseOnClickOutside }); let response = combo.show_ui(ui, |ui| { + // Positions kept between frames are relative to the menu's left edge: the menu moves + // (the window's edge pushes it after a resize), and screen positions from an earlier + // frame would pad the search row out and widen the menu, an empty strip beside the list. + let origin = ui.cursor().min.x; let (pass_id, focus_id) = (search_id.with("pass"), search_id.with("focus")); let pass = ui.ctx().cumulative_pass_nr(); let last_pass: Option = ui.data(|d| d.get_temp(pass_id)); @@ -1561,8 +1567,8 @@ pub(crate) fn family_picker_in( crate::font_filters::preview_banner(ui, &previewed, &previewed_label, library.preview_text.as_deref(), menu_width); // The filter buttons over the class list, and the search field over the fonts, starting // where the list does. - let list_left: Option = ui.data(|d| d.get_temp(list_left_id)); - let menu_right = body.map(|b| b.right()); + let list_left: Option = ui.data(|d| d.get_temp::(list_left_id)).map(|x| origin + x); + let menu_right = body.map(|b| origin + b.right()); let r = ui .horizontal(|ui| { if !filters.hide_classes { @@ -1762,13 +1768,17 @@ pub(crate) fn family_picker_in( } }) }); - ui.data_mut(|d| d.insert_temp(list_left_id, shown.inner_rect.left())); + ui.data_mut(|d| d.insert_temp(list_left_id, shown.inner_rect.left() - origin)); + shown.inner_rect.right() }); - let body = body.response.rect; + // The lists' own extent, from the class list to the font list's scroll bar: the row + // itself stretches with the popup, so it can't tell when the popup is too wide. + let list_right = body.inner + FONT_SCROLL_BAR_WIDTH; + let body = egui::Rect::from_min_max(body.response.rect.min, egui::pos2(list_right.min(body.response.rect.right()), body.response.rect.bottom())); ui.data_mut(|d| { d.insert_temp(filters_id, filters); d.insert_temp(expanded_id, expanded); - d.insert_temp(body_id, body); + d.insert_temp(body_id, body.translate(egui::vec2(-origin, 0.0))); if let Some(f) = &hovered { d.insert_temp(preview_id, f.clone()); } From d067466a6b2e35cd689ae5dcc10e213f2066a6ee Mon Sep 17 00:00:00 2001 From: D-monized <341904702+D-monized@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:36:37 -0600 Subject: [PATCH 11/87] Faux Bold: thicken the outline instead of stamping eight copies Faux bold drew each glyph at eight offsets (3.6% of the size) and merged them. At large sizes the copies didn't join on corners and stroke ends: stair-step notches (46 px offsets at 1278 pt). The glyph outline is now thickened before drawing, each point moved outward along its corner's bisector and capped by its shorter edge (as FreeType's FT_Outline_EmboldenXY), so curves stay curves and corners stay square at any size, with the same weight. Faux italic and scaling still apply after. Each bold glyph is drawn once instead of eight times. New tests: a 600 pt bold "l" keeps square corners (the old stamping cut them away), a bold "O" curves as smoothly as the regular one, and unit tests for the thickening (windings, counters, curves, degenerate outlines, sharp corners). Co-Authored-By: Claude Opus 5.5 --- crates/text/src/embolden.rs | 287 ++++++++++++++++++++++++++++++++++++ crates/text/src/lib.rs | 1 + crates/text/src/render.rs | 109 +++++--------- crates/text/src/tests.rs | 47 ++++++ 4 files changed, 375 insertions(+), 69 deletions(-) create mode 100644 crates/text/src/embolden.rs diff --git a/crates/text/src/embolden.rs b/crates/text/src/embolden.rs new file mode 100644 index 0000000000..37ecad3ca0 --- /dev/null +++ b/crates/text/src/embolden.rs @@ -0,0 +1,287 @@ +//! Faux bold by thickening the glyph outline itself: every point moves outward along the bisector +//! of its two edges, so the stroke grows by the same amount everywhere and curves stay curves (the +//! approach of FreeType's `FT_Outline_EmboldenXY`). Stamping the glyph at several offsets instead +//! leaves stair-step notches on curves and corners at large sizes. + +use skrifa::outline::OutlinePen; + +/// One recorded outline segment; its points are in [`Contour::pts`]. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Verb { + Line, + Quad, + Cubic, +} + +/// A closed contour: `pts[0]` is its start, then each segment's points in order. +#[derive(Clone, Debug, Default, PartialEq)] +struct Contour { + verbs: Vec, + pts: Vec<(f64, f64)>, +} + +/// A glyph outline in font units at the drawn size (y up), recorded to be thickened and replayed. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Outline { + contours: Vec, +} + +impl OutlinePen for Outline { + fn move_to(&mut self, x: f32, y: f32) { + self.contours.push(Contour { verbs: Vec::new(), pts: vec![(f64::from(x), f64::from(y))] }); + } + fn line_to(&mut self, x: f32, y: f32) { + self.push(Verb::Line, &[(x, y)]); + } + fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + self.push(Verb::Quad, &[(cx0, cy0), (x, y)]); + } + fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + self.push(Verb::Cubic, &[(cx0, cy0), (cx1, cy1), (x, y)]); + } + fn close(&mut self) {} +} + +impl Outline { + fn push(&mut self, verb: Verb, pts: &[(f32, f32)]) { + // A segment before any move starts a contour at the origin, as a pen would. + if self.contours.is_empty() { + self.contours.push(Contour { verbs: Vec::new(), pts: vec![(0.0, 0.0)] }); + } + if let Some(c) = self.contours.last_mut() { + c.verbs.push(verb); + c.pts.extend(pts.iter().map(|&(x, y)| (f64::from(x), f64::from(y)))); + } + } + + /// Twice the signed area of all contours (shoelace over every point): positive when the outer + /// contours run counter-clockwise (y up, PostScript order), negative for TrueType's clockwise. + fn signed_area(&self) -> f64 { + let mut a = 0.0; + for c in &self.contours { + // Each point with the next, the last with the first. + for (p, q) in c.pts.iter().zip(c.pts.iter().cycle().skip(1)) { + a += p.0 * q.1 - q.0 * p.1; + } + } + a + } + + /// Grow the ink by `r` on every side (the stems get `2r` heavier, counters `2r` smaller). + /// Points, on and off the curve, move along the bisector of their neighbouring edges by + /// `r / cos(half the turn)`, capped by the shorter neighbouring edge so short segments and + /// sharp inner corners can't spike. Nothing moves for a non-finite or non-positive `r`, or an + /// outline without area. + pub(crate) fn embolden(&mut self, r: f64) { + if !(r.is_finite() && r > 0.0) { + return; + } + let area = self.signed_area(); + if !area.is_finite() || area == 0.0 { + return; + } + // Outward is right of travel for counter-clockwise ink, left for clockwise. + let sign = if area > 0.0 { 1.0 } else { -1.0 }; + for c in &mut self.contours { + let shifts = shifts(&c.pts, r, sign); + for (p, s) in c.pts.iter_mut().zip(shifts) { + p.0 += s.0; + p.1 += s.1; + } + } + } + + /// Draw the outline into `pen`. + pub(crate) fn replay(&self, pen: &mut impl OutlinePen) { + let f = |v: f64| v as f32; + for c in &self.contours { + let Some(start) = c.pts.first() else { continue }; + pen.move_to(f(start.0), f(start.1)); + let mut i = 1; + for verb in &c.verbs { + let n = match verb { + Verb::Line => 1, + Verb::Quad => 2, + Verb::Cubic => 3, + }; + let Some(p) = c.pts.get(i..i + n) else { break }; + match (verb, p) { + (Verb::Line, [a]) => pen.line_to(f(a.0), f(a.1)), + (Verb::Quad, [a, b]) => pen.quad_to(f(a.0), f(a.1), f(b.0), f(b.1)), + (Verb::Cubic, [a, b, d]) => pen.curve_to(f(a.0), f(a.1), f(b.0), f(b.1), f(d.0), f(d.1)), + _ => break, + } + i += n; + } + pen.close(); + } + } +} + +/// How far each point of one closed contour moves (see [`Outline::embolden`]). +fn shifts(pts: &[(f64, f64)], r: f64, sign: f64) -> Vec<(f64, f64)> { + let n = pts.len(); + let mut out = vec![(0.0, 0.0); n]; + if n < 2 { + return out; + } + // The nearest point in direction `step` that differs from `pts[i]`, and the edge to it. + let neighbour = |i: usize, forward: bool| -> Option<(f64, f64, f64)> { + let p = pts[i]; + (1..n).find_map(|k| { + let j = if forward { (i + k) % n } else { (i + n - k) % n }; + let (dx, dy) = if forward { (pts[j].0 - p.0, pts[j].1 - p.1) } else { (p.0 - pts[j].0, p.1 - pts[j].1) }; + let len = dx.hypot(dy); + (len > 1e-9 && len.is_finite()).then(|| (dx / len, dy / len, len)) + }) + }; + for (i, shift) in out.iter_mut().enumerate() { + let (Some((ix, iy, l_in)), Some((ox, oy, l_out))) = (neighbour(i, false), neighbour(i, true)) else { continue }; + let dot = ix * ox + iy * oy; + // A near reversal (a spike) has no useful bisector: leave it. + if dot <= -0.9375 { + continue; + } + let d = 1.0 + dot; + let (sx, sy) = (sign * (iy + oy), -sign * (ix + ox)); + // How sharply the contour turns towards the ink at this point (negative: away). + let q = sign * (ox * iy - oy * ix); + let l = l_in.min(l_out); + let scale = if r * q <= l * d { r / d } else { l / q }; + if scale.is_finite() { + *shift = (sx * scale, sy * scale); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: f32, y0: f32, x1: f32, y1: f32, ccw: bool) -> Outline { + let mut o = Outline::default(); + add_square(&mut o, x0, y0, x1, y1, ccw); + o + } + + fn add_square(o: &mut Outline, x0: f32, y0: f32, x1: f32, y1: f32, ccw: bool) { + o.move_to(x0, y0); + if ccw { + o.line_to(x1, y0); + o.line_to(x1, y1); + o.line_to(x0, y1); + } else { + o.line_to(x0, y1); + o.line_to(x1, y1); + o.line_to(x1, y0); + } + o.line_to(x0, y0); + o.close(); + } + + fn bounds(o: &Outline) -> [f64; 4] { + let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN]; + for c in &o.contours { + for p in &c.pts { + b = [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)]; + } + } + b + } + + fn close(a: [f64; 4], b: [f64; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6) + } + + #[test] + fn a_square_grows_by_the_radius_on_every_side_in_either_winding() { + for ccw in [true, false] { + let mut o = square(0.0, 0.0, 10.0, 10.0, ccw); + o.embolden(1.0); + assert!(close(bounds(&o), [-1.0, -1.0, 11.0, 11.0]), "ccw {ccw}: {:?}", bounds(&o)); + } + } + + #[test] + fn counters_shrink_while_the_outer_edge_grows() { + // A ring: outer counter-clockwise, hole clockwise (y up, as fonts are drawn). + let mut o = square(0.0, 0.0, 20.0, 20.0, true); + add_square(&mut o, 5.0, 5.0, 15.0, 15.0, false); + o.embolden(1.0); + let hole = &o.contours[1]; + let xs: Vec = hole.pts.iter().map(|p| p.0).collect(); + let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); + assert!((lo - 6.0).abs() < 1e-6 && (hi - 14.0).abs() < 1e-6, "the hole narrows: {lo}..{hi}"); + assert!(close(bounds(&o), [-1.0, -1.0, 21.0, 21.0])); + } + + #[test] + fn curves_keep_their_segments_and_move_their_control_points() { + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(10.0, 0.0); + o.quad_to(15.0, 5.0, 10.0, 10.0); + o.curve_to(7.0, 12.0, 3.0, 12.0, 0.0, 10.0); + o.line_to(0.0, 0.0); + o.close(); + let before = o.clone(); + o.embolden(0.5); + assert_eq!(o.contours[0].verbs, before.contours[0].verbs, "the same segments, not stamped copies"); + assert_ne!(o.contours[0].pts, before.contours[0].pts); + let mut replayed = Outline::default(); + o.replay(&mut replayed); + // Pens take f32 points, so the replay matches to f32 precision. + let (a, b) = (&replayed.contours[0], &o.contours[0]); + assert_eq!(a.verbs, b.verbs, "replay draws the thickened outline's segments"); + let near = |p: &(f64, f64), q: &(f64, f64)| (p.0 - q.0).abs() < 1e-4 && (p.1 - q.1).abs() < 1e-4; + assert!(a.pts.len() == b.pts.len() && a.pts.iter().zip(&b.pts).all(|(p, q)| near(p, q))); + } + + #[test] + fn degenerate_outlines_and_hostile_radii_change_nothing_and_never_produce_nan() { + let line = { + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(5.0, 0.0); + o.line_to(0.0, 0.0); + o + }; + let dots = { + let mut o = Outline::default(); + o.move_to(3.0, 3.0); + o.line_to(3.0, 3.0); + o.line_to(3.0, 3.0); + o + }; + for base in [line, dots, Outline::default()] { + for r in [1.0, 0.0, -1.0, f64::NAN, f64::INFINITY] { + let mut o = base.clone(); + o.embolden(r); + assert_eq!(o, base, "r {r}"); + } + } + // A square with repeated points still grows cleanly. + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + o.line_to(x, y); + } + o.embolden(1.0); + assert!(close(bounds(&o), [-1.0, -1.0, 11.0, 11.0]), "{:?}", bounds(&o)); + assert!(o.contours.iter().flat_map(|c| c.pts.iter()).all(|p| p.0.is_finite() && p.1.is_finite())); + } + + #[test] + fn a_sharp_inner_corner_is_capped_by_its_short_edge() { + // A thin spike: its tip turns almost back on itself and stays put. + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(10.0, 0.0); + o.line_to(0.0, 0.2); + o.line_to(0.0, 0.0); + o.embolden(5.0); + let b = bounds(&o); + assert!(b.iter().all(|v| v.abs() < 60.0), "no runaway miter: {b:?}"); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 4f5e901f77..7d4c414a92 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -18,6 +18,7 @@ pub mod cjk; pub mod craft_fonts; +mod embolden; pub mod engine_data; pub mod font_class; pub mod fonts; diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index af29dd10d6..d80f3188e0 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -51,32 +51,9 @@ impl LineSink for WarpSink<'_, S> { /// Draws every glyph and decoration of `layout` whose style colour is `color` (or all of them /// when `color` is `None`) into `sink`, through `transform` (text space → sink space), bending -/// the outlines with `warp` first (in text space). +/// the outlines with `warp` first (in text space). Faux bold glyphs are drawn from their outline +/// thickened by [`FAUX_BOLD_RADIUS`] ([`crate::embolden`]). fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_color: Option<&Color>, warp: Option<&Warp>) { - draw_pass(layout, transform, sink, only_color, warp, Pass::All); -} - -/// Which part of the layout [`draw_pass`] emits. Faux bold draws each glyph at several offsets; -/// summing those into one coverage buffer saturates the antialiased edge pixels (hard, pixelated -/// stems), so the rasteriser draws every offset into its own buffer and merges them with `max`. -#[derive(Clone, Copy, PartialEq)] -enum Pass { - /// Everything, all offsets (bounds, outlines). - All, - /// Non-bold glyphs and decorations. - Plain, - /// Bold glyphs at one offset (index into [`BOLD_OFFSETS`]). - Bold(usize), -} - -const BOLD_OFFSETS: [(f64, f64); 8] = [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, -0.7), (0.7, -0.7), (-0.7, 0.7)]; - -fn is_bold(layout: &TextLayout, g: &PlacedGlyph) -> bool { - let face_bold = layout.faces.get(g.face as usize).is_some_and(|f| f.embolden); - layout.styles.get(g.style as usize).is_some_and(|s| s.faux_bold) || face_bold -} - -fn draw_pass(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_color: Option<&Color>, warp: Option<&Warp>, pass: Pass) { for g in &layout.glyphs { let st = &layout.styles[g.style as usize]; if only_color.is_some_and(|c| c != &st.color) { @@ -103,41 +80,27 @@ fn draw_pass(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, o } } } - let bold = st.faux_bold || face.embolden; - let r = (face.size_px * FAUX_BOLD_RADIUS) as f64; - let single = [(0.0, 0.0)]; - let offsets: &[(f64, f64)] = match (pass, bold) { - (Pass::Plain, true) => continue, - (Pass::Bold(_), false) => continue, - (Pass::Bold(k), true) => match BOLD_OFFSETS.get(k..=k) { - Some(o) => o, - None => continue, - }, - (Pass::All, true) => &BOLD_OFFSETS, - (_, false) => &single, - }; - for &(ox, oy) in offsets { - let local = glyph.mul(&Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r])); - let settings = DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords)); - match bend { - Some(w) => { - let mut ws = WarpSink { inner: &mut *sink, warp: w, post: *transform }; - let mut pen = Pen::new(&mut ws, local); - if outline.draw(settings, &mut pen).is_ok() { - skrifa::outline::OutlinePen::close(&mut pen); - } - } - None => { - let mut pen = Pen::new(&mut *sink, transform.mul(&local)); - if outline.draw(settings, &mut pen).is_ok() { - skrifa::outline::OutlinePen::close(&mut pen); - } - } + let settings = || DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords)); + // Faux bold thickens the outline in font units, before faux italic and scaling, so the + // slant and proportions apply to the bold shape as they do to a real bold face. Other + // glyphs draw straight into the pen. + let mut bold = None; + if st.faux_bold || face.embolden { + let mut shape = crate::embolden::Outline::default(); + if outline.draw(settings(), &mut shape).is_err() { + continue; } + shape.embolden(f64::from(face.size_px * FAUX_BOLD_RADIUS)); + bold = Some(shape); + } + let settings = settings(); + match bend { + Some(w) => { + let mut ws = WarpSink { inner: &mut *sink, warp: w, post: *transform }; + draw_glyph(&outline, settings, bold.as_ref(), &mut Pen::new(&mut ws, glyph)); + } + None => draw_glyph(&outline, settings, bold.as_ref(), &mut Pen::new(&mut *sink, transform.mul(&glyph))), } - } - if matches!(pass, Pass::Bold(_)) { - return; } for d in &layout.decorations { let st = &layout.styles[d.style as usize]; @@ -154,6 +117,23 @@ fn draw_pass(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, o } } +/// One glyph into `pen`: its thickened `bold` outline when there is one, else the font's own. +fn draw_glyph( + outline: &skrifa::outline::OutlineGlyph, + settings: DrawSettings, + bold: Option<&crate::embolden::Outline>, + pen: &mut impl skrifa::outline::OutlinePen, +) { + match bold { + Some(shape) => shape.replay(pen), + None => { + if outline.draw(settings, &mut *pen).is_ok() { + pen.close(); + } + } + } +} + /// Font units (scaled to px, y up) → text space for a placed glyph: scales, faux italic, /// baseline shift, and the vertical-type orientation. fn glyph_xform(layout: &TextLayout, g: &PlacedGlyph, face_skew_deg: f32) -> Xform { @@ -263,17 +243,8 @@ pub fn rasterize_warped(layout: &TextLayout, transform: &Affine, format: PixelFo } for c in &colors { let mut cov = Coverage::new(w, h); - draw_pass(layout, &xf, &mut cov, Some(c), warp, Pass::Plain); - let mut cov = cov.finish(); - if layout.glyphs.iter().any(|g| is_bold(layout, g)) { - for k in 0..BOLD_OFFSETS.len() { - let mut bc = Coverage::new(w, h); - draw_pass(layout, &xf, &mut bc, Some(c), warp, Pass::Bold(k)); - for (a, b) in cov.iter_mut().zip(bc.finish()) { - *a = a.max(b); - } - } - } + draw(layout, &xf, &mut cov, Some(c), warp); + let cov = cov.finish(); let comps = color_in(&format, c); let a = c.alpha.clamp(0.0, 1.0); for (i, &cv) in cov.iter().enumerate() { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 13de665ccd..63ca46c9c8 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2008,3 +2008,50 @@ fn hyphenless_postscript_names_split_trailing_styles() { assert_eq!((r.family.as_str(), r.weight, r.italic), (family, weight, italic), "{ps}"); } } + +/// Thickening moves each outline point along its bisector; this guards that curves stay as smooth +/// as the regular glyph's at a large size (the bend of a bold "O"'s edge between rows matches the +/// regular one's). See also `faux_bold_keeps_square_corners_square`. +#[test] +fn faux_bold_curves_stay_smooth_at_large_sizes() { + let mut e = TextEngine::new(); + // The largest bend of the left edge between consecutive rows, in pixels (second difference + // of its sub-pixel position), over the middle of the glyph's height. + let bumpiness = |e: &mut TextEngine, bold: bool| -> f64 { + let style = CharStyle { size_pt: 600.0, faux_bold: bold, ..Default::default() }; + let (_, r) = e.render(&TextLayer { transform: Affine::translate(60.0, 640.0), ..styled("O", style) }, 72.0, PixelFormat::RGBA8); + let alpha = |x: i32, y: i32| alpha_sum(&r.surface, photocraft_geom::Rect::new(x, y, x + 1, y + 1)); + let h = r.rect.height() as i32; + let mut edges = Vec::new(); + for y in (r.rect.y0 + h * 15 / 100)..(r.rect.y0 + h * 85 / 100) { + if let Some(x) = (r.rect.x0..r.rect.x1).find(|&x| alpha(x, y) > 0.01) { + edges.push(f64::from(x) + 1.0 - alpha(x, y)); + } + } + edges.windows(3).map(|w| (w[2] - 2.0 * w[1] + w[0]).abs()).fold(0.0, f64::max) + }; + let plain = bumpiness(&mut e, false); + let bold = bumpiness(&mut e, true); + eprintln!("bumpiness plain {plain} bold {bold}"); + assert!(bold < plain + 0.5, "faux bold's edge is notched: bends {bold} px vs {plain} px regular"); +} + +/// The notches showed most at corners and stroke ends: eight stamped copies leave a stepped bite +/// out of a square corner. Thickened outlines keep corners square, as a bold "l" shows. +#[test] +fn faux_bold_keeps_square_corners_square() { + let mut e = TextEngine::new(); + for bold in [false, true] { + let style = CharStyle { size_pt: 600.0, faux_bold: bold, ..Default::default() }; + let (_, r) = e.render(&TextLayer { transform: Affine::translate(60.0, 640.0), ..styled("l", style) }, 72.0, PixelFormat::RGBA8); + let alpha = |x: i32, y: i32| alpha_sum(&r.surface, photocraft_geom::Rect::new(x, y, x + 1, y + 1)); + // The ink's own top-left and top-right corners (the raster rect pads the ink by a pixel). + let top = (r.rect.y0..r.rect.y1).find(|&y| (r.rect.x0..r.rect.x1).any(|x| alpha(x, y) > 0.5)).unwrap(); + let left = (r.rect.x0..r.rect.x1).find(|&x| (r.rect.y0..r.rect.y1).any(|y| alpha(x, y) > 0.5)).unwrap(); + let right = (r.rect.x0..r.rect.x1).rev().find(|&x| (r.rect.y0..r.rect.y1).any(|y| alpha(x, y) > 0.5)).unwrap(); + for (x, corner) in [(left + 1, "top-left"), (right - 1, "top-right")] { + let a = alpha(x, top + 1); + assert!(a > 0.9, "bold {bold}: the {corner} corner is cut away (alpha {a})"); + } + } +} From 4776d20b7a281ca2eab4162af96dacb1f32ea861 Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:31:58 +0200 Subject: [PATCH 12/87] perf(compression): Use zlib-rs with runtime detection Isolate the workspace backend choice and verify PNG, PSD and complete native-format decoding. Record standalone timing and compressed-size tradeoffs. --- Cargo.lock | 1 + Cargo.toml | 2 +- crates/io/Cargo.toml | 1 + crates/io/tests/deflate_compatibility.rs | 123 +++++++++++++++++++++++ docs/deflate-zlib-rs-performance.md | 57 +++++++++++ 5 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 crates/io/tests/deflate_compatibility.rs create mode 100644 docs/deflate-zlib-rs-performance.md diff --git a/Cargo.lock b/Cargo.lock index aff38ac01b..d1c7213be2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4895,6 +4895,7 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "miniz_oxide 0.9.1", "photocraft-affinity", "photocraft-algo", "photocraft-cms", diff --git a/Cargo.toml b/Cargo.toml index 3f8dbb0a72..834062aeef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,7 @@ serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" arc-swap = "1" bytemuck = { version = "1", features = ["derive"] } -flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1", default-features = false, features = ["zlib-rs", "runtime_detection"] } image = { version = "0.25", default-features = false } # Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg. zune-core = "0.5" diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index eb8c0b00d7..c458441386 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -49,6 +49,7 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } [dev-dependencies] +miniz_oxide = "0.9" crc32fast = "1.5" photocraft-affinity = { workspace = true, features = ["synth"] } flate2 = { workspace = true } diff --git a/crates/io/tests/deflate_compatibility.rs b/crates/io/tests/deflate_compatibility.rs new file mode 100644 index 0000000000..b9e6365833 --- /dev/null +++ b/crates/io/tests/deflate_compatibility.rs @@ -0,0 +1,123 @@ +//! Backend compatibility, including native-format tile data rather than ZIP assembly alone. +mod common; + +use std::{hint::black_box, io::Read, time::Instant}; + +use photocraft_codecs::{ChannelLayout, Format, Image, SampleType as CodecSample}; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent}; +use photocraft_format::{SaveOptions, load_from_bytes, read_thumbnail, save_to_bytes}; +use photocraft_geom::Size; +use photocraft_io::{PsdExportOptions, document_to_psd_with, import}; +use photocraft_psd::Compression; +use photocraft_raster::Rgba8Image; + +fn document(depth: SampleType, size: Size) -> Document { + let mut doc = Document::new("compatibility", size, ColorMode::Rgb, depth); + doc.layers.push(Layer::new("pixels", LayerContent::Raster(common::pattern(doc.pixel_format(), doc.bounds(), 3, false)))); + doc +} + +fn old_and_new_inflate(bytes: &[u8]) { + let old = miniz_oxide::inflate::decompress_to_vec_zlib(bytes) + .unwrap_or_else(|e| panic!("old decoder: {:?}, header {:?}", e.status, &bytes[..bytes.len().min(8)])); + let mut new = Vec::new(); + flate2::read::ZlibDecoder::new(bytes).read_to_end(&mut new).unwrap(); + assert_eq!(new, old); +} + +fn check_png(bytes: &[u8], image: &Image) { + assert_eq!(photocraft_codecs::decode(bytes).unwrap().data(), image.data()); + let mut idat = Vec::new(); + let mut offset = 8; + while offset < bytes.len() { + let len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize; + if &bytes[offset + 4..offset + 8] == b"IDAT" { + idat.extend_from_slice(&bytes[offset + 8..offset + 8 + len]); + } + offset += 12 + len; + } + old_and_new_inflate(&idat); +} + +#[test] +fn png_psd_and_pcraft_decode_identically() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let doc = document(depth, Size::new(257, 131)); + let pixels = doc.layers[0].surface().unwrap().read_region(doc.bounds()); + if depth != SampleType::F32 { + let sample = if depth == SampleType::U8 { CodecSample::U8 } else { CodecSample::U16 }; + let image = Image::from_normalized(257, 131, ChannelLayout::Rgba, sample, &pixels).unwrap(); + check_png(&photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(), &image); + } + for compression in [Compression::Zip, Compression::ZipPrediction] { + let opts = PsdExportOptions { merged_compression: compression, merged_matte: false, ..Default::default() }; + let mut file = document_to_psd_with(&doc, &opts).0; + // The IO exporter normally chooses Raw for float composites; also cover ZIP here. + if depth == SampleType::F32 { + file.image_data = photocraft_psd::ImageData::encode(compression, &file.image_data.decode(&file.header).unwrap(), &file.header).unwrap(); + } + let bytes = file.to_bytes().unwrap(); + let parsed = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(parsed.image_data.compression, compression); + old_and_new_inflate(&parsed.image_data.data); + let back = import("compatibility.psd", &bytes).unwrap().document; + assert_eq!(back.layers[0].surface().unwrap().read_region(doc.bounds()), pixels); + } + let mut thumbnail = Rgba8Image::new(7, 3); + thumbnail.pixels = (0..84).map(|i| (i * 37) as u8).collect(); + let opts = SaveOptions { thumbnail: Some(thumbnail.clone()), ..Default::default() }; + let bytes = save_to_bytes(&doc, &opts).unwrap(); + assert!(load_from_bytes(&bytes).unwrap() == doc, "all tile bytes, {depth:?}"); + let image = Image::from_u8(7, 3, ChannelLayout::Rgba, thumbnail.pixels).unwrap(); + check_png(&read_thumbnail(&bytes).unwrap().unwrap(), &image); + } +} + +#[test] +#[ignore = "manual 24 MP release benchmark; run on main and the backend branch"] +fn benchmark_deflate_formats() { + for pattern in ["ramp", "noise"] { + let mut doc = document(SampleType::U8, Size::new(6000, 4000)); + if pattern == "noise" { + let mut seed = 0x9e3779b9u32; + let raw: Vec = (0..96_000_000usize) + .map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } + }) + .collect(); + doc.layers[0].content = LayerContent::Raster(photocraft_raster::Surface::from_interleaved(doc.pixel_format(), doc.bounds(), &raw)); + } + let pixels = doc.layers[0].surface().unwrap().read_region(doc.bounds()); + let image = Image::from_normalized(6000, 4000, ChannelLayout::Rgba, CodecSample::U8, &pixels).unwrap(); + drop(pixels); + let psd_opts = PsdExportOptions { merged_compression: Compression::Zip, merged_matte: false, ..Default::default() }; + let save_opts = SaveOptions { thumbnail: Some(Rgba8Image::new(256, 170)), ..Default::default() }; + let png = photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(); + let psd = document_to_psd_with(&doc, &psd_opts).0.to_bytes().unwrap(); + let pcraft = save_to_bytes(&doc, &save_opts).unwrap(); + for trial in 0..6 { + for op in ["png-encode", "png-decode", "psd-encode", "psd-decode", "pcraft-save", "pcraft-load"] { + let start = Instant::now(); + let size = match op { + "png-encode" => black_box(photocraft_codecs::encode(black_box(&image), Format::Png, &Default::default()).unwrap()).len(), + "png-decode" => black_box(photocraft_codecs::decode(black_box(&png)).unwrap()).data().len(), + "psd-encode" => black_box(document_to_psd_with(black_box(&doc), &psd_opts).0.to_bytes().unwrap()).len(), + "psd-decode" => { + black_box(import("bench.psd", black_box(&psd)).unwrap()); + psd.len() + } + "pcraft-save" => black_box(save_to_bytes(black_box(&doc), &save_opts).unwrap()).len(), + _ => { + black_box(load_from_bytes(black_box(&pcraft)).unwrap()); + pcraft.len() + } + }; + println!("deflate,{pattern}-{op},{trial},{:.3},{size}", start.elapsed().as_secs_f64() * 1000.0); + } + } + } +} diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md new file mode 100644 index 0000000000..82e685fd91 --- /dev/null +++ b/docs/deflate-zlib-rs-performance.md @@ -0,0 +1,57 @@ +# Deflate backend comparison + +Only the workspace flate2 backend changes from miniz_oxide to zlib-rs with runtime CPU detection. The 24 MP (6000×4000) RGBA8 cases are a repeating ramp and deterministic noise; inputs are prepared outside the timers. + +Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max +(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that +base; none of the other performance splits is applied. Release uses optimization +level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. +Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal +priority with no concurrent builds. Timings are medians of five samples after one +warm-up, except the compositor's ten Criterion samples. These synthetic workloads +are reproducible checks of this change, not a representative image corpus. + +| Workload | Main ms | This change ms | Time change | +|---|---:|---:|---:| +| ramp-png-encode | 42.114 | 43.989 | +4.5% | +| ramp-png-decode | 47.100 | 8.697 | -81.5% | +| ramp-psd-encode | 200.218 | 162.012 | -19.1% | +| ramp-psd-decode | 45.092 | 31.839 | -29.4% | +| ramp-pcraft-save | 82.126 | 83.149 | +1.2% | +| ramp-pcraft-load | 1.424 | 1.474 | +3.5% | +| noise-png-encode | 206.339 | 152.328 | -26.2% | +| noise-png-decode | 187.408 | 183.032 | -2.3% | +| noise-psd-encode | 1191.777 | 1002.312 | -15.9% | +| noise-psd-decode | 30.907 | 30.394 | -1.7% | +| noise-pcraft-save | 177.713 | 175.379 | -1.3% | +| noise-pcraft-load | 103.026 | 101.085 | -1.9% | + +| Encoded file | Main bytes | This change bytes | +|---|---:|---:| +| ramp-png-encode | 107,506 | 478,751 | +| ramp-psd-encode | 73,268,469 | 73,503,868 | +| ramp-pcraft-save | 88,188 | 88,214 | +| noise-png-encode | 82,731,323 | 82,272,418 | +| noise-psd-encode | 144,983,563 | 144,994,193 | +| noise-pcraft-save | 96,670,862 | 96,670,888 | + +Compressed bytes are not identical across backends. The ramp PNG gets larger; the noise case and decode timings must be considered alongside encode time. The native format stores Zstandard tiles and STORE ZIP entries, so this switch only changes its PNG previews; the repeating ramp deduplicates many tiles. No tile-compression speedup is attributed to deflate. + +The committed compatibility test compares old miniz_oxide and flate2 inflation of PNG IDAT and PSD ZIP/ZIP-prediction streams, checks exact decoded PNG/PSD pixels at supported depths, and compares complete .pcraft documents at U8/U16/F32 (tiles included) plus their PNG thumbnail. Float PSD composites are explicitly ZIP-encoded in the test because the IO exporter normally chooses Raw. The same test passed on the base and this branch. + +Reproduce with the same release profile environment: + +```sh +CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-io --test deflate_compatibility --no-run +# Run the printed executable at normal priority: + benchmark_deflate_formats --ignored --nocapture --test-threads=1 +``` + +## Local validation + +- `cargo test -p photocraft-codecs -p photocraft-psd -p photocraft-format -p photocraft-io --locked`: passed (1956 passed, 9 ignored). +- `cargo clippy -p photocraft-codecs -p photocraft-psd -p photocraft-format -p photocraft-io --locked --all-targets -- -D warnings`: passed. +- `cargo xtask layers`: passed. +- `cargo xtask wasm`: passed. +- `cargo xtask test-corpus -p psd -p codecs -p io`: passed (1853 passed, 9 ignored). +- The compatibility test also passed with the main backend before measurements. To reproduce the main comparison, copy only this test and its miniz_oxide dev-dependency into a clean main worktree. From a37198d4fac09fafc916110dc2ec1558d8efe8bf Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:14:37 +0200 Subject: [PATCH 13/87] docs(perf): record real image deflate tradeoffs --- docs/deflate-zlib-rs-performance.md | 96 +++++++++++++++++------------ 1 file changed, 56 insertions(+), 40 deletions(-) diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md index 82e685fd91..d2560f0afc 100644 --- a/docs/deflate-zlib-rs-performance.md +++ b/docs/deflate-zlib-rs-performance.md @@ -1,53 +1,69 @@ # Deflate backend comparison -Only the workspace flate2 backend changes from miniz_oxide to zlib-rs with runtime CPU detection. The 24 MP (6000×4000) RGBA8 cases are a repeating ramp and deterministic noise; inputs are prepared outside the timers. +Replace the workspace flate2 Rust backend with zlib-rs and runtime CPU detection. Tiles in .pcraft remain Zstandard; deflate changes its PNG previews. -Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max -(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that -base; none of the other performance splits is applied. Release uses optimization -level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. -Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal -priority with no concurrent builds. Timings are medians of five samples after one -warm-up, except the compositor's ten Criterion samples. These synthetic workloads -are reproducible checks of this change, not a representative image corpus. +Retained with explicitly accepted tradeoffs. Some PSD ZIP files grow by up to 0.71%; the 16-bit city PSD import is about 6% slower in confirmation; the small web-layout PNG grows by 598 bytes (+1.40%); one .pcraft preview adds 25 bytes. Real photo PNGs become smaller and encode faster. Compression-effort probes recovered size only by introducing other speed regressions, so no effort change is applied. There is no native-format tile speedup from deflate. -| Workload | Main ms | This change ms | Time change | -|---|---:|---:|---:| -| ramp-png-encode | 42.114 | 43.989 | +4.5% | -| ramp-png-decode | 47.100 | 8.697 | -81.5% | -| ramp-psd-encode | 200.218 | 162.012 | -19.1% | -| ramp-psd-decode | 45.092 | 31.839 | -29.4% | -| ramp-pcraft-save | 82.126 | 83.149 | +1.2% | -| ramp-pcraft-load | 1.424 | 1.474 | +3.5% | -| noise-png-encode | 206.339 | 152.328 | -26.2% | -| noise-png-decode | 187.408 | 183.032 | -2.3% | -| noise-psd-encode | 1191.777 | 1002.312 | -15.9% | -| noise-psd-decode | 30.907 | 30.394 | -1.7% | -| noise-pcraft-save | 177.713 | 175.379 | -1.3% | -| noise-pcraft-load | 103.026 | 101.085 | -1.9% | +Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. -| Encoded file | Main bytes | This change bytes | -|---|---:|---:| -| ramp-png-encode | 107,506 | 478,751 | -| ramp-psd-encode | 73,268,469 | 73,503,868 | -| ramp-pcraft-save | 88,188 | 88,214 | -| noise-png-encode | 82,731,323 | 82,272,418 | -| noise-psd-encode | 144,983,563 | 144,994,193 | -| noise-pcraft-save | 96,670,862 | 96,670,888 | +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. -Compressed bytes are not identical across backends. The ramp PNG gets larger; the noise case and decode timings must be considered alongside encode time. The native format stores Zstandard tiles and STORE ZIP entries, so this switch only changes its PNG previews; the repeating ramp deduplicates many tiles. No tile-compression speedup is attributed to deflate. +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. -The committed compatibility test compares old miniz_oxide and flate2 inflation of PNG IDAT and PSD ZIP/ZIP-prediction streams, checks exact decoded PNG/PSD pixels at supported depths, and compares complete .pcraft documents at U8/U16/F32 (tiles included) plus their PNG thumbnail. Float PSD composites are explicitly ZIP-encoded in the test because the IO exporter normally chooses Raw. The same test passed on the base and this branch. +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| canon-16 | psd-import (confirm) | 168.891 | 178.614 | +5.8% | +3.5..+5.9% | 140,673,004 / 140,673,004 | +| panasonic-8 | save | 166.659 | 162.322 | -2.6% | -3.9..-1.0% | 49,643,217 / 49,643,242 | +| panasonic-8 | load-common | 410.794 | 409.622 | -0.3% | -0.5..+0.3% | 49,643,217 / 49,643,217 | +| panasonic-8 | png-encode | 373.880 | 165.381 | -55.8% | -56.3..-47.4% | 24,569,965 / 24,238,416 | +| panasonic-8 | png-decode | 168.141 | 167.247 | -0.5% | -2.0..+1.0% | 24,569,965 / 24,569,965 | +| panasonic-8 | psd-export | 2938.276 | 1115.740 | -62.0% | -62.3..-61.6% | 98,823,859 / 98,837,585 | +| panasonic-8 | psd-import | 275.713 | 174.046 | -36.9% | -38.8..-34.7% | 98,823,859 / 98,823,859 | +| panasonic-16 | save | 357.998 | 355.900 | -0.6% | -1.8..+0.5% | 175,681,852 / 175,681,844 | +| panasonic-16 | load-common | 387.986 | 391.411 | +0.9% | -1.3..+1.1% | 175,681,852 / 175,681,852 | +| panasonic-16 | png-encode | 354.924 | 288.664 | -18.7% | -27.8..-14.2% | 111,583,441 / 109,241,690 | +| panasonic-16 | png-decode | 434.083 | 433.645 | -0.1% | -1.0..+1.7% | 111,583,441 / 111,583,441 | +| panasonic-16 | psd-export | 2645.838 | 2249.281 | -15.0% | -15.6..-13.8% | 274,409,683 / 275,654,405 | +| panasonic-16 | psd-import | 371.291 | 374.777 | +0.9% | -1.1..+1.8% | 274,409,683 / 274,409,683 | +| panasonic-32 | save | 639.677 | 631.556 | -1.3% | -5.2..+1.8% | 252,231,671 / 252,231,663 | +| panasonic-32 | load-common | 1338.160 | 1326.936 | -0.8% | -1.1..-0.2% | 252,231,671 / 252,231,671 | +| panasonic-32 | psd-export | 2522.700 | 1352.144 | -46.4% | -49.6..-44.6% | 461,042,978 / 459,545,262 | +| panasonic-32 | psd-import | 356.077 | 310.425 | -12.8% | -20.2..-4.7% | 461,042,978 / 461,042,978 | +| canon-8 | save | 89.139 | 85.965 | -3.6% | -8.9..+2.7% | 26,151,631 / 26,151,203 | +| canon-8 | load-common | 219.711 | 219.088 | -0.3% | -0.3..+1.0% | 26,151,631 / 26,151,631 | +| canon-8 | png-encode | 179.944 | 80.123 | -55.5% | -60.8..-40.0% | 13,720,268 / 13,551,023 | +| canon-8 | png-decode | 69.704 | 70.040 | +0.5% | -0.4..+0.6% | 13,720,268 / 13,720,268 | +| canon-8 | psd-export | 1074.094 | 475.802 | -55.7% | -56.1..-55.4% | 56,209,597 / 56,608,401 | +| canon-8 | psd-import | 142.523 | 96.323 | -32.4% | -34.4..-26.9% | 56,209,597 / 56,209,597 | +| canon-16 | save | 185.898 | 183.472 | -1.3% | -2.8..-0.2% | 88,750,003 / 88,749,555 | +| canon-16 | load-common | 193.409 | 193.704 | +0.2% | -0.2..+0.8% | 88,750,003 / 88,750,003 | +| canon-16 | png-encode | 169.432 | 135.364 | -20.1% | -26.2..-15.4% | 58,279,529 / 57,568,207 | +| canon-16 | png-decode | 211.947 | 211.829 | -0.1% | -0.4..+0.5% | 58,279,529 / 58,279,529 | +| canon-16 | psd-export | 1295.076 | 1130.697 | -12.7% | -13.5..-9.9% | 140,673,004 / 141,105,829 | +| canon-32 | save | 340.781 | 334.426 | -1.9% | -5.3..+0.7% | 120,957,984 / 120,957,536 | +| canon-32 | load-common | 774.663 | 778.401 | +0.5% | -1.3..+8.5% | 120,957,984 / 120,957,984 | +| canon-32 | psd-export | 1028.651 | 647.483 | -37.1% | -40.5..-36.1% | 228,234,238 / 227,497,106 | +| canon-32 | psd-import | 177.500 | 146.373 | -17.5% | -18.5..-17.1% | 228,234,238 / 228,234,238 | +| layout-masks | save | 18.588 | 18.268 | -1.7% | -2.7..+0.6% | 433,949 / 433,924 | +| layout-masks | load-common | 16.099 | 16.080 | -0.1% | -1.5..+0.6% | 433,949 / 433,949 | +| layout-masks | png-encode | 3.911 | 2.557 | -34.6% | -36.0..-32.3% | 42,842 / 43,440 | +| layout-masks | png-decode | 0.781 | 0.767 | -1.8% | -2.5..+2.2% | 42,842 / 42,842 | +| layout-masks | psd-export | 56.043 | 46.949 | -16.2% | -18.5..-15.9% | 493,006 / 493,145 | +| layout-masks | psd-import | 12.324 | 12.334 | +0.1% | -4.8..+2.3% | 493,006 / 493,006 | +| layout-mask-index | save | 7.367 | 7.202 | -2.2% | -5.5..-0.7% | 344,892 / 344,746 | +| layout-mask-index | load-common | 6.601 | 6.602 | +0.0% | -2.8..+4.7% | 344,892 / 344,892 | +| layout-mask-index | png-encode | 11.520 | 5.971 | -48.2% | -49.5..-46.0% | 115,229 / 114,892 | +| layout-mask-index | png-decode | 1.451 | 1.444 | -0.5% | -4.2..+0.5% | 115,229 / 115,229 | +| layout-mask-index | psd-export | 19.135 | 12.721 | -33.5% | -34.0..-31.5% | 411,435 / 411,594 | +| layout-mask-index | psd-import | 3.362 | 2.721 | -19.1% | -21.3..-11.2% | 411,435 / 411,435 | -Reproduce with the same release profile environment: +Every PNG encode decodes to identical source pixels, each PSD operation produces the same decoded layer/mask samples as main, and complete .pcraft documents compare equal at every depth. Compressed bytes may differ. The committed compatibility test independently inflates PNG IDAT and PSD ZIP/ZIP-prediction data using old miniz_oxide and checks .pcraft tiles plus thumbnails. -```sh -CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-io --test deflate_compatibility --no-run -# Run the printed executable at normal priority: - benchmark_deflate_formats --ignored --nocapture --test-threads=1 -``` +Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. -## Local validation +## Earlier split validation + +These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. - `cargo test -p photocraft-codecs -p photocraft-psd -p photocraft-format -p photocraft-io --locked`: passed (1956 passed, 9 ignored). - `cargo clippy -p photocraft-codecs -p photocraft-psd -p photocraft-format -p photocraft-io --locked --all-targets -- -D warnings`: passed. From 687c3011acaf4fea0bd5e1df67a9a8d6627bfc64 Mon Sep 17 00:00:00 2001 From: D-monized Date: Tue, 20 Oct 2026 01:17:43 -0600 Subject: [PATCH 14/87] Font menu: review fixes (recent only on a pick, picked styles, "code" names, no Actions steps) - Only a font picked from the open menu joins the recent fonts; the wheel and the arrow keys on the closed field step past many families and no longer fill the list. - The style picked under a family's ">" is applied in the Glyphs panel and in Character/Paragraph Style Options, as the options bar and Character panel already did. - Monospace by name matches whole words and only where the font's tables say nothing, so "Encode Sans" is a sans serif, not a "code" font. - The favourite and recent-font commands are no longer recorded into Actions, so playing an action back doesn't rewrite the user's font lists. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/font_library_cmds.rs | 6 ++-- crates/engine/src/font_library_cmds/tests.rs | 8 +++++ crates/engine/src/type_styles_cmds/tests.rs | 11 ++++++ crates/text/src/font_class.rs | 13 +++++-- crates/ui-egui/src/type_font_picker_tests.rs | 37 ++++++++++++++++++++ crates/ui-egui/src/type_panels_ui.rs | 9 +++-- crates/ui-egui/src/type_tool.rs | 10 +++++- 7 files changed, 86 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/font_library_cmds.rs b/crates/engine/src/font_library_cmds.rs index 6e466a3edf..7b11a7f706 100644 --- a/crates/engine/src/font_library_cmds.rs +++ b/crates/engine/src/font_library_cmds.rs @@ -127,7 +127,7 @@ pub fn specs() -> Vec { params: r#"{"family":str,"on":bool?=toggle} → family, favorite, favorites"#, enabled: always, run: favorite, - journal: true, + journal: false, }, CommandSpec { id: "type.font.noteRecent", @@ -137,7 +137,7 @@ pub fn specs() -> Vec { params: r#"{"family":str} → recent (most recent first, at most 5)"#, enabled: always, run: note_recent, - journal: true, + journal: false, }, CommandSpec { id: "type.font.clearRecent", @@ -147,7 +147,7 @@ pub fn specs() -> Vec { params: "{}", enabled: always, run: clear_recent, - journal: true, + journal: false, }, CommandSpec { id: "type.font.library", diff --git a/crates/engine/src/font_library_cmds/tests.rs b/crates/engine/src/font_library_cmds/tests.rs index 46198af387..693cd691f7 100644 --- a/crates/engine/src/font_library_cmds/tests.rs +++ b/crates/engine/src/font_library_cmds/tests.rs @@ -101,3 +101,11 @@ fn bad_params_are_errors_and_change_nothing() { assert_eq!(favorite_fonts(&s), ["Arial"]); assert!(recent_fonts(&s).is_empty()); } + +#[test] +fn font_library_edits_are_not_recorded_into_actions() { + // Playing an action back must not rewrite the user's recent or favourite fonts. + for id in ["type.font.favorite", "type.font.noteRecent", "type.font.clearRecent", "type.font.library"] { + assert!(!crate::actions_cmds::replayable(id), "{id}"); + } +} diff --git a/crates/engine/src/type_styles_cmds/tests.rs b/crates/engine/src/type_styles_cmds/tests.rs index 0a5761d58b..6f6f735ff0 100644 --- a/crates/engine/src/type_styles_cmds/tests.rs +++ b/crates/engine/src/type_styles_cmds/tests.rs @@ -243,3 +243,14 @@ fn preview_options_validates_without_mutating_source() { assert_ne!(shown.text_styles, before); assert_eq!(doc.text_styles, before); } + +#[test] +fn style_options_take_a_family_with_the_style_picked_under_it() { + // The font menu's ">" picks a family in one of its styles: Style Options sends both. + let (mut s, _) = session("Hello"); + let cs = s.execute("type.characterStyle.new", json!({"attrs": {"size": 20}, "fromSelection": false})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.characterStyle.set", json!({"id": cs, "attrs": {"font": "Arial", "fontStyle": "Bold Italic"}})).unwrap(); + let attrs = s.execute("type.characterStyle.list", json!({})).unwrap()["styles"][1]["attrs"].clone(); + assert_eq!(attrs["font_family"], "Arial", "{attrs}"); + assert_eq!(attrs["font_style"], "Bold Italic", "{attrs}"); +} diff --git a/crates/text/src/font_class.rs b/crates/text/src/font_class.rs index ccdef3576e..edf518d9e7 100644 --- a/crates/text/src/font_class.rs +++ b/crates/text/src/font_class.rs @@ -134,8 +134,10 @@ const BLACKLETTER: [&str; 7] = ["fraktur", "blackletter", "black letter", "textu pub fn classify(family: &str, family_class: i16, panose: [u8; 10], fixed_pitch: bool) -> Option { let name = family.to_lowercase(); let has = |words: &[&str]| words.iter().any(|w| name.contains(w)); + // Whole words of the name, so "Encode Sans" isn't read as a "code" font. + let words: Vec<&str> = name.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect(); // PANOSE Latin Text proportion 9 is monospaced. - if fixed_pitch || (panose[0] == 2 && panose[3] == 9) || has(&[" mono", "mono ", "monospace", "code", "consol", "courier"]) { + if fixed_pitch || (panose[0] == 2 && panose[3] == 9) { return Some(FontClass::Monospace); } if has(&BLACKLETTER) { @@ -168,7 +170,9 @@ pub fn classify(family: &str, family_class: i16, panose: [u8; 10], fixed_pitch: } } // Last, the name. - if has(&["slab"]) { + if words.iter().any(|w| matches!(*w, "mono" | "monospace" | "monospaced" | "code" | "courier") || w.starts_with("consol")) { + Some(FontClass::Monospace) + } else if has(&["slab"]) { Some(FontClass::SlabSerif) } else if has(&["sans", "grotesk", "grotesque", "gothic"]) { Some(FontClass::SansSerif) @@ -243,6 +247,11 @@ mod tests { assert_eq!(classify("Noto Serif", 0, NONE, false), Some(FontClass::Serif)); assert_eq!(classify("Noto Sans", 0, NONE, false), Some(FontClass::SansSerif)); assert_eq!(classify("Fira Code", 0, NONE, false), Some(FontClass::Monospace)); + assert_eq!(classify("Space Mono", 0, NONE, false), Some(FontClass::Monospace)); + // "code" inside a word, or a name the tables contradict, doesn't make a monospace. + assert_eq!(classify("Encode Sans", 0, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Encode Sans", 0x0805, NONE, false), Some(FontClass::SansSerif)); + assert_eq!(classify("Code Pro Sans", 0x0805, NONE, false), Some(FontClass::SansSerif), "the class beats the name"); assert_eq!(classify("Permanent Marker", 0, NONE, false), Some(FontClass::Handwritten)); assert_eq!(classify("Unknowable", 0, NONE, false), None); // Out-of-range or garbage table values don't panic or misfile. diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_font_picker_tests.rs index fdfcad30f2..21ed18fe12 100644 --- a/crates/ui-egui/src/type_font_picker_tests.rs +++ b/crates/ui-egui/src/type_font_picker_tests.rs @@ -1022,3 +1022,40 @@ fn options_bar_hover_previews_with_the_character_picker_also_shown() { h.run(); assert_eq!(font(&mut h), "Inter", "leaving the row restores the committed font"); } + +/// Each change of font with whether it was picked from the menu (only those are recent fonts). +#[test] +fn only_a_font_picked_from_the_menu_counts_as_picked_not_one_stepped_to() { + struct S { + current: String, + families: Vec, + library: super::FontLibrary, + changes: Vec<(String, bool)>, + } + let families: Vec = (0..20).map(|i| format!("Family {i:02}")).collect(); + let state = S { current: "Family 00".into(), families, library: super::FontLibrary::default(), changes: Vec::new() }; + let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state( + |ui, s: &mut S| { + let fams = s.families.clone(); + if super::family_picker_in(ui, "type-font", &mut s.current, 170.0, &fams, FontPreview::Medium, &mut s.library) { + s.changes.push((s.current.clone(), s.library.picked)); + } + }, + state, + ); + h.run(); + let button = h.query_all_by_role(Role::ComboBox).next().unwrap().rect().center(); + // The wheel over the closed button steps through three families. + h.hover_at(button); + h.run(); + h.event(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, -3.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE }); + h.run(); + assert_eq!(h.state().current, "Family 03"); + assert!(h.state().changes.iter().all(|(_, picked)| !picked), "stepping with the wheel picks nothing: {:?}", h.state().changes); + // A click on a row of the open menu is a pick. + h.query_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run(); + h.get_by_label("Family 07").click(); + h.run(); + assert_eq!(h.state().changes.last(), Some(&("Family 07".to_string(), true))); +} diff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/type_panels_ui.rs index b9afe693c8..962cd8e380 100644 --- a/crates/ui-egui/src/type_panels_ui.rs +++ b/crates/ui-egui/src/type_panels_ui.rs @@ -402,7 +402,11 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s "font" => { let mut f = v.as_str().unwrap_or("").to_string(); if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f, preview, &mut library) { - set = Some(json!({ panel: f })); + // A style picked under the family's ">" comes with it. + set = Some(match library.picked_style.take() { + Some(style) => json!({ panel: f, "fontStyle": style }), + None => json!({ panel: f }), + }); } } "pt" | "num" | "leading" => { @@ -628,10 +632,11 @@ pub fn glyphs_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut f = family.clone(); let mut library = crate::type_tool::FontLibrary::of(app); let picked = family_picker(ui, "glyph-family", &mut f, app.session.prefs().type_.font_preview, &mut library); + let picked_style = library.picked_style.take(); library.finish(app); if picked { app.ui.type_panels.glyph_family = f; - app.ui.type_panels.glyph_style = tl!("Regular").into(); + app.ui.type_panels.glyph_style = picked_style.unwrap_or_else(|| tl!("Regular").into()); } let styles = crate::type_tool::styles(&family); let mut s = style.clone(); diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index d20dd44a1c..7d3b79ab74 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1448,6 +1448,9 @@ pub(crate) struct FontLibrary { pub toggled: Option, /// The style picked under a family's ">" (with the family), for the caller to apply. pub picked_style: Option, + /// Whether a font was picked from the open menu (click or Enter), not stepped to with the + /// wheel or the arrow keys: only a picked font joins the recent fonts. + pub picked: bool, /// Family traits to filter by instead of the installed fonts' (tests). pub traits: Option>, /// Each family's style names instead of the installed fonts' (tests). @@ -1509,11 +1512,15 @@ fn font_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, current: &mut String, let mut library = FontLibrary { preview_text: preview_text(app), ..FontLibrary::of(app) }; let changed = family_picker_in(ui, "type-font", current, width, &families(), preview, &mut library); let style = library.picked_style.take(); + let picked = library.picked; library.finish(app); if !changed { return None; } - note_recent_font(app, current); + // Only a font picked from the menu is recent: the wheel and the arrows step past many. + if picked { + note_recent_font(app, current); + } Some(style) } @@ -1908,6 +1915,7 @@ pub(crate) fn family_picker_in( } } + library.picked = picked; changed } From b83182d0de709b0652cb46b59436c2a1f758e52e Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:30:52 +0700 Subject: [PATCH 15/87] fix(type): keep Character preset controls within panel columns --- crates/ui-egui/src/props_layout_tests.rs | 9 +++++---- crates/ui-egui/src/type_tool.rs | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/props_layout_tests.rs b/crates/ui-egui/src/props_layout_tests.rs index 74fd29121a..d563470702 100644 --- a/crates/ui-egui/src/props_layout_tests.rs +++ b/crates/ui-egui/src/props_layout_tests.rs @@ -174,14 +174,15 @@ fn type_controls_fill_the_panel_at_every_width_and_scale() { .filter(|r| r.top() >= transform.bottom() && r.bottom() <= header.top()) .map(|r| r.right()) .fold(f32::MIN, f32::max); - // (Both rows have a unit suffix: compare with the size/leading row.) - // Variable-font axes can precede the size/leading row and have no unit suffix. - // Compare the intended point-valued controls, retaining the same edge tolerance. + // Preset-bearing fields reserve the right edge for their combo button. + // Verify the complete field (editable value plus preset) aligns with Transform. let lead = ["Font size", "Leading (set to the font size × auto-leading when Auto)"] .into_iter() .map(|label| h.get_by_role_and_label(egui::accesskit::Role::SpinButton, label).rect().right()) .fold(f32::MIN, f32::max); - assert!((t_right - lead).abs() < 0.5, "{what}: Transform fields end at {t_right}, Character at {lead}"); + let lead_combo = combos[3].right(); // Family, style, size presets, leading presets. + assert!(lead + 20.0 <= lead_combo, "{what}: the leading preset must not overlap its editable field"); + assert!((t_right - lead_combo).abs() <= 2.0, "{what}: Transform fields end at {t_right}, Character controls at {lead_combo}"); // Quick Actions buttons span the panel too. let qa = h.get_by_label("Rasterize Type").rect(); assert!(qa.right() >= header.right() - 2.0 && qa.right() <= header.right() + 1.0, "{what}: {qa:?}"); diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 50b5dfa1e9..53ef03589f 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -2051,7 +2051,7 @@ fn metric_field(ui: &mut egui::Ui, field: MetricField<'_>) -> Option Date: Tue, 20 Oct 2026 20:13:24 +0700 Subject: [PATCH 16/87] fix(type): align Character preset controls with Properties column --- crates/ui-egui/src/type_tool.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 53ef03589f..2ea96fdba3 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -2051,7 +2051,10 @@ fn metric_field(ui: &mut egui::Ui, field: MetricField<'_>) -> Option Date: Tue, 20 Oct 2026 20:28:02 +0700 Subject: [PATCH 17/87] fix(type): preserve a valid numeric editor slot at minimum dock width --- crates/ui-egui/src/type_tool.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 2ea96fdba3..5f39d2a10c 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1999,12 +1999,25 @@ fn icon_label(ui: &mut egui::Ui, icon: &str, tip: &str) { /// Labelled numeric field (Photoshop's icon + value pairs). Returns the new value when edited. fn num_field(ui: &mut egui::Ui, label: &str, tip: &str, v: f32, range: std::ops::RangeInclusive, unit: &str, width: f32) -> Option { + num_field_with_label(ui, label, tip, v, range, unit, width, 22.0) +} + +fn num_field_with_label( + ui: &mut egui::Ui, + label: &str, + tip: &str, + v: f32, + range: std::ops::RangeInclusive, + unit: &str, + width: f32, + label_width: f32, +) -> Option { let t = crate::theme::Tokens::get(ui.ctx()); let mut v = v; let mut out = None; ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; - let (r, resp) = ui.allocate_exact_size(egui::vec2(22.0, 22.0), egui::Sense::hover()); + let (r, resp) = ui.allocate_exact_size(egui::vec2(label_width, 22.0), egui::Sense::hover()); ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, crate::theme::semibold(10.0), t.text_dim); crate::widgets::scrub_label(ui, &resp.on_hover_text(tl!(tip))); let response = crate::widgets::value_field(ui, &mut v, range, unit, width); @@ -2051,10 +2064,10 @@ fn metric_field(ui: &mut egui::Ui, field: MetricField<'_>) -> Option Date: Tue, 20 Oct 2026 20:32:17 +0700 Subject: [PATCH 18/87] fix(type): keep compact numeric sizing helper within clippy argument limit --- crates/ui-egui/src/type_tool.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 5f39d2a10c..ae03b2b266 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1999,7 +1999,7 @@ fn icon_label(ui: &mut egui::Ui, icon: &str, tip: &str) { /// Labelled numeric field (Photoshop's icon + value pairs). Returns the new value when edited. fn num_field(ui: &mut egui::Ui, label: &str, tip: &str, v: f32, range: std::ops::RangeInclusive, unit: &str, width: f32) -> Option { - num_field_with_label(ui, label, tip, v, range, unit, width, 22.0) + num_field_with_label(ui, label, tip, v, range, unit, (width, 22.0)) } fn num_field_with_label( @@ -2009,9 +2009,9 @@ fn num_field_with_label( v: f32, range: std::ops::RangeInclusive, unit: &str, - width: f32, - label_width: f32, + widths: (f32, f32), ) -> Option { + let (width, label_width) = widths; let t = crate::theme::Tokens::get(ui.ctx()); let mut v = v; let mut out = None; @@ -2067,7 +2067,7 @@ fn metric_field(ui: &mut egui::Ui, field: MetricField<'_>) -> Option Date: Tue, 20 Oct 2026 17:41:28 +0200 Subject: [PATCH 19/87] perf(format): avoid buffering compressed ZIP slices Decode archive slices directly to remove a 32 KiB input allocation and its compressed-data copies. Preserve size limits and CRC checks, with an equivalence and corruption test. Remove the unused synthetic timing test and refresh the performance notes with public x86 evidence. --- crates/format/src/zip.rs | 30 +++++++++++++- crates/io/tests/deflate_compatibility.rs | 50 +----------------------- docs/deflate-zlib-rs-performance.md | 37 ++++++++++++------ 3 files changed, 55 insertions(+), 62 deletions(-) diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs index 9ec92c2fba..3da497b3f9 100644 --- a/crates/format/src/zip.rs +++ b/crates/format/src/zip.rs @@ -214,7 +214,7 @@ impl<'a> ZipReader<'a> { // small forged archive must not reserve gigabytes up front, so the // preallocation is capped (DEFLATE expands at most ~1032x). let mut out = Vec::with_capacity(e.uncompressed.min(raw.len().saturating_mul(1032)).min(64 << 20)); - flate2::read::DeflateDecoder::new(raw) + flate2::bufread::DeflateDecoder::new(raw) .take((max as u64).saturating_add(1)) .read_to_end(&mut out) .map_err(|err| FormatError::corrupt(format!("zip entry `{}`: {err}", e.name)))?; @@ -327,6 +327,34 @@ mod tests { assert!(r.read_by_name("a", 100).is_err()); } + #[test] + fn slice_deflate_matches_buffered_reader_and_preserves_checks() { + use std::io::Write as _; + + let content = b"PhotoCraft ZIP payload".repeat(5000); + let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::none()); + encoder.write_all(&content).unwrap(); + let compressed = encoder.finish().unwrap(); + assert!(compressed.len() > 32 * 1024); + let mut previous = Vec::new(); + flate2::read::DeflateDecoder::new(compressed.as_slice()).read_to_end(&mut previous).unwrap(); + let mut writer = ZipWriter::new(); + writer.add("payload", &compressed).unwrap(); + let bytes = writer.finish().unwrap(); + let reader = ZipReader::new(&bytes).unwrap(); + let mut entry = reader.entries[0].clone(); + entry.method = 8; + entry.uncompressed = content.len(); + entry.crc = crc32(&content); + assert_eq!(reader.read(&entry, content.len()).unwrap(), previous); + assert!(matches!(reader.read(&entry, content.len() - 1), Err(FormatError::LimitExceeded(_)))); + entry.crc ^= 1; + assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_)))); + entry.crc ^= 1; + entry.compressed /= 2; + assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_)))); + } + /// A valid DEFLATE-compressed bundle may be read with an effectively /// unlimited caller budget (e.g. corruption/round-trip checks). On 64-bit /// targets `usize::MAX as u64 + 1` overflows, so the decoder must saturate. diff --git a/crates/io/tests/deflate_compatibility.rs b/crates/io/tests/deflate_compatibility.rs index b9e6365833..1d3d7438d6 100644 --- a/crates/io/tests/deflate_compatibility.rs +++ b/crates/io/tests/deflate_compatibility.rs @@ -1,7 +1,7 @@ //! Backend compatibility, including native-format tile data rather than ZIP assembly alone. mod common; -use std::{hint::black_box, io::Read, time::Instant}; +use std::io::Read; use photocraft_codecs::{ChannelLayout, Format, Image, SampleType as CodecSample}; use photocraft_color::{ColorMode, SampleType}; @@ -73,51 +73,3 @@ fn png_psd_and_pcraft_decode_identically() { check_png(&read_thumbnail(&bytes).unwrap().unwrap(), &image); } } - -#[test] -#[ignore = "manual 24 MP release benchmark; run on main and the backend branch"] -fn benchmark_deflate_formats() { - for pattern in ["ramp", "noise"] { - let mut doc = document(SampleType::U8, Size::new(6000, 4000)); - if pattern == "noise" { - let mut seed = 0x9e3779b9u32; - let raw: Vec = (0..96_000_000usize) - .map(|i| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } - }) - .collect(); - doc.layers[0].content = LayerContent::Raster(photocraft_raster::Surface::from_interleaved(doc.pixel_format(), doc.bounds(), &raw)); - } - let pixels = doc.layers[0].surface().unwrap().read_region(doc.bounds()); - let image = Image::from_normalized(6000, 4000, ChannelLayout::Rgba, CodecSample::U8, &pixels).unwrap(); - drop(pixels); - let psd_opts = PsdExportOptions { merged_compression: Compression::Zip, merged_matte: false, ..Default::default() }; - let save_opts = SaveOptions { thumbnail: Some(Rgba8Image::new(256, 170)), ..Default::default() }; - let png = photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(); - let psd = document_to_psd_with(&doc, &psd_opts).0.to_bytes().unwrap(); - let pcraft = save_to_bytes(&doc, &save_opts).unwrap(); - for trial in 0..6 { - for op in ["png-encode", "png-decode", "psd-encode", "psd-decode", "pcraft-save", "pcraft-load"] { - let start = Instant::now(); - let size = match op { - "png-encode" => black_box(photocraft_codecs::encode(black_box(&image), Format::Png, &Default::default()).unwrap()).len(), - "png-decode" => black_box(photocraft_codecs::decode(black_box(&png)).unwrap()).data().len(), - "psd-encode" => black_box(document_to_psd_with(black_box(&doc), &psd_opts).0.to_bytes().unwrap()).len(), - "psd-decode" => { - black_box(import("bench.psd", black_box(&psd)).unwrap()); - psd.len() - } - "pcraft-save" => black_box(save_to_bytes(black_box(&doc), &save_opts).unwrap()).len(), - _ => { - black_box(load_from_bytes(black_box(&pcraft)).unwrap()); - pcraft.len() - } - }; - println!("deflate,{pattern}-{op},{trial},{:.3},{size}", start.elapsed().as_secs_f64() * 1000.0); - } - } - } -} diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md index d2560f0afc..b3fa75bfd8 100644 --- a/docs/deflate-zlib-rs-performance.md +++ b/docs/deflate-zlib-rs-performance.md @@ -2,9 +2,19 @@ Replace the workspace flate2 Rust backend with zlib-rs and runtime CPU detection. Tiles in .pcraft remain Zstandard; deflate changes its PNG previews. -Retained with explicitly accepted tradeoffs. Some PSD ZIP files grow by up to 0.71%; the 16-bit city PSD import is about 6% slower in confirmation; the small web-layout PNG grows by 598 bytes (+1.40%); one .pcraft preview adds 25 bytes. Real photo PNGs become smaller and encode faster. Compression-effort probes recovered size only by introducing other speed regressions, so no effort change is applied. There is no native-format tile speedup from deflate. +Size, import-speed and dependency tradeoffs remain maintainer decisions. +Some PSD ZIP files grow by up to 0.71%. The macOS 16-bit city PSD import is about 6% slower in confirmation. +The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 25 bytes. +Real photo PNGs become smaller and encode faster. Compression levels are unchanged. +There is no native-format tile speedup from deflate. -Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. +Measured on 2026-10-19 against main `d95fdf31`, independently of the other performance changes. +Host: Apple M4 Max, 16 CPUs, 128 GiB RAM, macOS arm64, rustc 1.99.1. +Release settings: optimization level 3, no LTO, 16 codegen units and no debug information. +Builds finish before measurement. Measurements use default priority without concurrent builds or profiling. +Five alternating pairs follow a warmup. Confirmation uses nine pairs. +Time changes compare medians, and intervals resample paired ratios. Negative changes mean less elapsed time. +Small differences are not automatically established improvements or regressions. The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. @@ -59,15 +69,18 @@ The shared harness times in-memory operations. Input loading, image conversion, Every PNG encode decodes to identical source pixels, each PSD operation produces the same decoded layer/mask samples as main, and complete .pcraft documents compare equal at every depth. Compressed bytes may differ. The committed compatibility test independently inflates PNG IDAT and PSD ZIP/ZIP-prediction data using old miniz_oxide and checks .pcraft tiles plus thumbnails. -Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. +## Linux and Windows x86-64 validation -## Earlier split validation +[GitHub Actions run](https://github.com/reneleonhardt/photocraft/actions/runs/39444647224) passed the deflate compatibility test, +the full IO/codecs/format package tests and `cargo xtask wasm` on Ubuntu 24.04 and Windows 2022 x86-64. +The temporary `ci/deflate-zlib-rs-x86` branch at `46232997` contains the workflow and benchmark setup. +The run's `deflate-x86-results` artifact contains all raw samples, the full table, input and binary hashes, backend features and host details. -These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. - -- `cargo test -p photocraft-codecs -p photocraft-psd -p photocraft-format -p photocraft-io --locked`: passed (1956 passed, 9 ignored). -- `cargo clippy -p photocraft-codecs -p photocraft-psd -p photocraft-format -p photocraft-io --locked --all-targets -- -D warnings`: passed. -- `cargo xtask layers`: passed. -- `cargo xtask wasm`: passed. -- `cargo xtask test-corpus -p psd -p codecs -p io`: passed (1853 passed, 9 ignored). -- The compatibility test also passed with the main backend before measurements. To reproduce the main comparison, copy only this test and its miniz_oxide dev-dependency into a clean main worktree. +The timing host used an Intel Xeon 6973P-C with four vCPUs and rustc 1.99.1. +Main at `d95fdf31` and the backend change at `a37198d4` used matching release settings. +One warmup preceded nine alternating pairs on the same 12/24 MP photos at U8/U16. +Both importers received the same baseline-encoded PSD files. Loading, conversion, hashes and checks stayed outside the elapsed-time measurements. +PNG encode time fell 23.8–56.8%, PSD export time 18.1–58.2%, and PSD import time 7.8–21.6%. +The 16-bit city import fell from 440.733 to 402.057 ms (-8.78%); the macOS slowdown did not recur on this runner. +Photo PNGs became 1.2–2.1% smaller. Exported PSDs grew by 0.014–0.709%. +All decoded pixels, dimensions, depths and profiles matched. These results cover this Linux host; Windows and F32 were not timed. From 1121b7979bc61f398619c2951c9ece1fb8c8fc08 Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:59:52 +0200 Subject: [PATCH 20/87] fix(format): bound ZIP expansion by declared size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stop after one byte beyond the declared output length. This avoids expanding a forged entry up to the caller’s larger budget. Add tests for surplus output, empty streams and truncated endings. Clarify that the backend timings do not measure the ZIP changes. --- crates/format/src/zip.rs | 35 +++++++++++++++++++++++++---- docs/deflate-zlib-rs-performance.md | 3 +++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs index 3da497b3f9..d3467171ce 100644 --- a/crates/format/src/zip.rs +++ b/crates/format/src/zip.rs @@ -214,8 +214,9 @@ impl<'a> ZipReader<'a> { // small forged archive must not reserve gigabytes up front, so the // preallocation is capped (DEFLATE expands at most ~1032x). let mut out = Vec::with_capacity(e.uncompressed.min(raw.len().saturating_mul(1032)).min(64 << 20)); + // One surplus byte proves a false size without expanding to the caller's larger budget. flate2::bufread::DeflateDecoder::new(raw) - .take((max as u64).saturating_add(1)) + .take((e.uncompressed as u64).saturating_add(1)) .read_to_end(&mut out) .map_err(|err| FormatError::corrupt(format!("zip entry `{}`: {err}", e.name)))?; out @@ -355,9 +356,35 @@ mod tests { assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_)))); } - /// A valid DEFLATE-compressed bundle may be read with an effectively - /// unlimited caller budget (e.g. corruption/round-trip checks). On 64-bit - /// targets `usize::MAX as u64 + 1` overflows, so the decoder must saturate. + /// A false small size must stop expansion before decoding the rest of the stream. + #[test] + fn deflate_surplus_stops_before_a_corrupt_suffix() { + // Non-final stored block, then an invalid block type after its payload. + let raw = [&[0, 32, 0, 0xdf, 0xff][..], &[b'x'; 32], &[7]].concat(); + let reader = ZipReader { bytes: &raw, entries: Vec::new(), by_name: HashMap::new() }; + for declared in [0, 7] { + let entry = Entry { name: "surplus".into(), method: 8, crc: 0, compressed: raw.len(), uncompressed: declared, data_offset: 0 }; + let err = reader.read(&entry, usize::MAX).unwrap_err(); + assert!(err.to_string().contains("wrong size"), "{err}"); + } + } + + /// Correct output length and CRC do not replace the final DEFLATE block. + #[test] + fn deflate_requires_a_complete_stream_including_empty_entries() { + for (raw, content) in [(&[0, 1, 0, 0xfe, 0xff, b'x', 1, 0, 0, 0xff, 0xff][..], &b"x"[..]), (&[3, 0][..], &b""[..])] { + let reader = ZipReader { bytes: raw, entries: Vec::new(), by_name: HashMap::new() }; + let mut entry = + Entry { name: "complete".into(), method: 8, crc: crc32(content), compressed: raw.len(), uncompressed: content.len(), data_offset: 0 }; + assert_eq!(reader.read(&entry, content.len()).unwrap(), content); + for cut in 0..raw.len() { + entry.compressed = cut; + assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_))), "cut at {cut}"); + } + } + } + + /// An unlimited caller budget still checks a DEFLATE entry's declared size. #[test] fn deflated_entry_with_unbounded_limit_round_trips() { use std::io::Write as _; diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md index b3fa75bfd8..886383a4ac 100644 --- a/docs/deflate-zlib-rs-performance.md +++ b/docs/deflate-zlib-rs-performance.md @@ -8,6 +8,9 @@ The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 2 Real photo PNGs become smaller and encode faster. Compression levels are unchanged. There is no native-format tile speedup from deflate. +These timings measure the backend switch before the ZIP input-buffer removal and output-size guard. +Neither ZIP change was benchmarked. + Measured on 2026-10-19 against main `d95fdf31`, independently of the other performance changes. Host: Apple M4 Max, 16 CPUs, 128 GiB RAM, macOS arm64, rustc 1.99.1. Release settings: optimization level 3, no LTO, 16 codegen units and no debug information. From 404c010ca3e5187f26c6dfe768b6db8d29da293d Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:07:04 +0200 Subject: [PATCH 21/87] test(io): cover legacy miniz deflate streams Generate legacy PNG IDAT and PSD ZIP streams directly with miniz. Read both PSD ZIP variants through the parser, plane decoder and streaming helper. Compare PNG pixels with their source and PSD merged data with an uncompressed export. --- crates/io/tests/deflate_compatibility.rs | 49 +++++++++++++++++++----- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/crates/io/tests/deflate_compatibility.rs b/crates/io/tests/deflate_compatibility.rs index 1d3d7438d6..493c7dba6a 100644 --- a/crates/io/tests/deflate_compatibility.rs +++ b/crates/io/tests/deflate_compatibility.rs @@ -18,28 +18,48 @@ fn document(depth: SampleType, size: Size) -> Document { doc } -fn old_and_new_inflate(bytes: &[u8]) { +/// Compare both decoders and generate a legacy stream without flate2 compression. +fn old_and_new_inflate(bytes: &[u8]) -> (Vec, Vec) { let old = miniz_oxide::inflate::decompress_to_vec_zlib(bytes) .unwrap_or_else(|e| panic!("old decoder: {:?}, header {:?}", e.status, &bytes[..bytes.len().min(8)])); - let mut new = Vec::new(); - flate2::read::ZlibDecoder::new(bytes).read_to_end(&mut new).unwrap(); - assert_eq!(new, old); + let legacy = miniz_oxide::deflate::compress_to_vec_zlib(&old, 6); + for stream in [bytes, legacy.as_slice()] { + let mut new = Vec::new(); + flate2::read::ZlibDecoder::new(stream).read_to_end(&mut new).unwrap(); + assert_eq!(new, old); + } + (old, legacy) } +/// Read new PNGs and PNGs with legacy-miniz IDAT data through the codec. fn check_png(bytes: &[u8], image: &Image) { assert_eq!(photocraft_codecs::decode(bytes).unwrap().data(), image.data()); let mut idat = Vec::new(); + let mut legacy_png = bytes[..8].to_vec(); + let mut idat_offset = None; let mut offset = 8; while offset < bytes.len() { let len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize; + let end = offset + 12 + len; if &bytes[offset + 4..offset + 8] == b"IDAT" { + idat_offset.get_or_insert(legacy_png.len()); idat.extend_from_slice(&bytes[offset + 8..offset + 8 + len]); + } else { + legacy_png.extend_from_slice(&bytes[offset..end]); } - offset += 12 + len; + offset = end; } - old_and_new_inflate(&idat); + let (_, legacy) = old_and_new_inflate(&idat); + let mut chunk = (legacy.len() as u32).to_be_bytes().to_vec(); + chunk.extend_from_slice(b"IDAT"); + chunk.extend_from_slice(&legacy); + chunk.extend_from_slice(&crc32fast::hash(&chunk[4..]).to_be_bytes()); + let at = idat_offset.unwrap(); + legacy_png.splice(at..at, chunk); + assert_eq!(photocraft_codecs::decode(&legacy_png).unwrap().data(), image.data()); } +/// New zlib-rs streams and legacy-miniz streams preserve the same document samples. #[test] fn png_psd_and_pcraft_decode_identically() { for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { @@ -50,19 +70,28 @@ fn png_psd_and_pcraft_decode_identically() { let image = Image::from_normalized(257, 131, ChannelLayout::Rgba, sample, &pixels).unwrap(); check_png(&photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(), &image); } + let raw_opts = PsdExportOptions { merged_compression: Compression::Raw, merged_matte: false, ..Default::default() }; + let merged = document_to_psd_with(&doc, &raw_opts).0.image_data.data; for compression in [Compression::Zip, Compression::ZipPrediction] { let opts = PsdExportOptions { merged_compression: compression, merged_matte: false, ..Default::default() }; let mut file = document_to_psd_with(&doc, &opts).0; // The IO exporter normally chooses Raw for float composites; also cover ZIP here. if depth == SampleType::F32 { - file.image_data = photocraft_psd::ImageData::encode(compression, &file.image_data.decode(&file.header).unwrap(), &file.header).unwrap(); + file.image_data = photocraft_psd::ImageData::encode(compression, &merged, &file.header).unwrap(); } let bytes = file.to_bytes().unwrap(); let parsed = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); assert_eq!(parsed.image_data.compression, compression); - old_and_new_inflate(&parsed.image_data.data); - let back = import("compatibility.psd", &bytes).unwrap().document; - assert_eq!(back.layers[0].surface().unwrap().read_region(doc.bounds()), pixels); + let (inflated, legacy) = old_and_new_inflate(&parsed.image_data.data); + // The PSD streaming helper uses a different flate2 reader from plane decoding. + assert_eq!(photocraft_psd::compression::zip_decompress(&legacy, inflated.len()).unwrap(), inflated); + file.image_data.data = legacy; + for fixture in [bytes, file.to_bytes().unwrap()] { + let parsed = photocraft_psd::PsdFile::from_bytes(&fixture).unwrap(); + assert_eq!(parsed.image_data.decode(&parsed.header).unwrap(), merged); + let back = import("compatibility.psd", &fixture).unwrap().document; + assert_eq!(back.layers[0].surface().unwrap().read_region(doc.bounds()), pixels); + } } let mut thumbnail = Rgba8Image::new(7, 3); thumbnail.pixels = (0..84).map(|i| (i * 37) as u8).collect(); From b4b8b52569b3e9ddf7a741d51557290e776832ea Mon Sep 17 00:00:00 2001 From: Catur Sura Date: Wed, 21 Oct 2026 14:56:01 +0700 Subject: [PATCH 22/87] fix(transform): address review feedback on formatting, test assertions, and duplicate sticky_mods --- crates/ui-egui/src/canvas.rs | 16 ++++++++-------- crates/ui-egui/src/transform_tool.rs | 20 +++++++++++++------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f0251cbd68..2e108dd475 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3822,18 +3822,18 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }); if let Some((vertical, _)) = guide_hover { ui.ctx().set_cursor_icon(crate::rulers::guide_cursor(&xf, vertical)); - } else if let Some(p) = response.hover_pos() - && let Some(c) = { - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - crate::transform_tool::cursor(app, &xf, xf.to_doc(p), mods) - } - { + } else if let Some((p, mods, c)) = response.hover_pos().and_then(|p| { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + let c = crate::transform_tool::cursor(app, &xf, xf.to_doc(p), mods)?; + Some((p, mods, c)) + }) { ui.ctx().set_cursor_icon(c); // CursorIcon::None hides the pointer; the curved arrow has to be drawn or the // rotate zone looks like a plain cursor (#4050). let d = xf.to_doc(p); - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - if !mods.command && let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { + if !mods.command + && let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) + { let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; crate::crop_ui::draw_turn_cursor(&ctx, p, toward); } diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 04faf636b8..722ae9ed5e 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -2153,11 +2153,7 @@ pub fn draw_skew_cursor(ctx: &egui::Context, at: Pos2, tangent: egui::Vec2) { let tip = p_end + u * (dir * 3.5); let wing1 = p_end - u * (dir * 2.5) + perp * 3.5; let wing2 = p_end - u * (dir * 2.5) - perp * 3.5; - painter.add(egui::Shape::convex_polygon( - vec![tip, wing1, wing2], - tokens.accent_text, - Stroke::new(1.0, tokens.shadow), - )); + painter.add(egui::Shape::convex_polygon(vec![tip, wing1, wing2], tokens.accent_text, Stroke::new(1.0, tokens.shadow))); } } @@ -2300,7 +2296,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform let b_scr = scr(t.quad[(i + 1) % 4]); let tangent = b_scr - a_scr; draw_skew_cursor(painter.ctx(), at, tangent); - } else if !mods.command && let Some(k) = rotate_dir(t, Some(pv), p, tol) { + } else if !mods.command + && let Some(k) = rotate_dir(t, Some(pv), p, tol) + { // Through the view, so the arc bends round the corner as it shows under a turned or // flipped view. let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; @@ -4503,7 +4501,10 @@ mod tests { let t = app.ui.transform.clone().unwrap(); let xf = ViewXform::active(&app).unwrap(); let mid = |i: usize| [(t.quad[i][0] + t.quad[(i + 1) % 4][0]) / 2.0, (t.quad[i][1] + t.quad[(i + 1) % 4][1]) / 2.0]; - let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], egui::Modifiers::NONE)).chain((0..4).map(|i| cursor(&app, &xf, mid(i), egui::Modifiers::NONE))).collect(); + let got: Vec<_> = (0..4) + .map(|i| cursor(&app, &xf, t.quad[i], egui::Modifiers::NONE)) + .chain((0..4).map(|i| cursor(&app, &xf, mid(i), egui::Modifiers::NONE))) + .collect(); let want = [want[0], want[1], want[0], want[1], want[2], want[3], want[2], want[3]].map(Some); assert_eq!(got, want, "box {deg}°, view {view}°, flip {flip}"); } @@ -5497,5 +5498,10 @@ mod tests { // Release drag crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 60.0 }, command); + + // Once released, dragging has ended: far outside returns the commit-on-click cursor, + // and hovering the corner without Command restores normal resize cursor. + assert_eq!(cursor(&app, &xf, [200.0, 200.0], command), Some(CursorIcon::Alias)); + assert_ne!(cursor(&app, &xf, [50.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::None)); } } From df6a7e7b5ad245ae09a9a0d2d72da99f7bd8bc3c Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:59:34 +0200 Subject: [PATCH 23/87] perf(format): reduce ZIP archive allocations Reserve complete bundles and directories from compressed sizes, and borrow UTF-8 entry paths in the lookup index. Preserve lossy names and first-entry lookup for duplicates. Check ZIP field lengths before writing, bound metadata reservations, and cover byte equivalence, overflow and incremental saves. ZIP entry paths have a format limit independent of filesystem path constraints. --- crates/format/src/store.rs | 16 ++-- crates/format/src/zip.rs | 110 ++++++++++++++++++++++++---- crates/format/tests/roundtrip.rs | 6 +- docs/deflate-zlib-rs-performance.md | 7 +- 4 files changed, 115 insertions(+), 24 deletions(-) diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 7da5dd6b53..dbde3952dc 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -771,15 +771,21 @@ impl PcraftWriter { pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec, SaveStats)> { let p = self.prepare(doc, opts)?; let mut stats = p.stats; - let mut z = ZipWriter::new(); - z.add(MANIFEST, &p.manifest)?; - for (name, data) in &p.previews { - z.add(name, data)?; - } let mut next = HashMap::with_capacity(p.objects.len()); // New objects are compressed on all cores first (zstd dominates a full save). let todo: Vec<(&String, &Object)> = p.objects.iter().filter(|(path, _)| !self.compressed.contains_key(*path)).collect(); let mut fresh: HashMap<&String, Arc>> = par_compress(&todo)?.into_iter().collect(); + let entries = std::iter::once((MANIFEST, p.manifest.len())).chain(p.previews.iter().map(|(name, data)| (*name, data.len()))).chain( + p.objects.keys().map(|path| { + let size = self.compressed.get(path).or_else(|| fresh.get(path)).map_or(0, |data| data.len()); + (path.as_str(), size) + }), + ); + let mut z = ZipWriter::with_entries(entries)?; + z.add(MANIFEST, &p.manifest)?; + for (name, data) in &p.previews { + z.add(name, data)?; + } for (path, obj) in &p.objects { let data = match self.compressed.get(path) { Some(d) => { diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs index d3467171ce..f57d0a45ab 100644 --- a/crates/format/src/zip.rs +++ b/crates/format/src/zip.rs @@ -3,6 +3,7 @@ //! unzipped and re-zipped by another tool still loads). No ZIP64, no //! encryption, no multi-disk archives. +use std::borrow::Cow; use std::collections::HashMap; use std::io::Read; @@ -31,18 +32,41 @@ impl Default for ZipWriter { } impl ZipWriter { + /// Creates an empty archive of STORE entries. pub fn new() -> Self { ZipWriter { out: Vec::new(), central: Vec::new(), count: 0 } } + /// Reserves the complete archive from its entry names and payload sizes. + pub(crate) fn with_entries<'a>(entries: impl IntoIterator) -> Result { + let (size, directory) = entries.into_iter().try_fold((22usize, 0usize), |(size, directory), (name, bytes)| { + let directory = directory.checked_add(46 + name.len()); + let size = size.checked_add(76).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(bytes)); + size.zip(directory).ok_or_else(|| FormatError::Unsupported("zip size overflow".into())) + })?; + let mut writer = Self::new(); + writer.out.try_reserve_exact(size).map_err(|_| FormatError::LimitExceeded("not enough memory for zip".into()))?; + writer.central.try_reserve_exact(directory).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?; + Ok(writer) + } + + /// Adds a STORE entry, rejecting names or data that exceed ZIP field limits. + /// The entry path has a 16-bit byte length, independent of filesystem limits. pub fn add(&mut self, name: &str, data: &[u8]) -> Result<(), FormatError> { if self.count == u16::MAX { return Err(FormatError::Unsupported("more than 65535 zip entries (ZIP64 not supported)".into())); } let size = u32::try_from(data.len()).map_err(|_| FormatError::Unsupported("zip entry over 4 GiB".into()))?; let offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?; - let crc = crc32(data); let name_b = name.as_bytes(); + let name_len = u16::try_from(name_b.len()).map_err(|_| FormatError::Unsupported("zip entry path exceeds the 65535-byte format limit".into()))?; + let local_len = 30usize + .checked_add(name_b.len()) + .and_then(|n| n.checked_add(data.len())) + .ok_or_else(|| FormatError::Unsupported("zip entry size overflow".into()))?; + self.out.try_reserve(local_len).map_err(|_| FormatError::LimitExceeded("not enough memory for zip entry".into()))?; + self.central.try_reserve(46 + name_b.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?; + let crc = crc32(data); // Local file header. let o = &mut self.out; o.extend_from_slice(&LOCAL_SIG.to_le_bytes()); @@ -54,7 +78,7 @@ impl ZipWriter { o.extend_from_slice(&crc.to_le_bytes()); o.extend_from_slice(&size.to_le_bytes()); o.extend_from_slice(&size.to_le_bytes()); - o.extend_from_slice(&(name_b.len() as u16).to_le_bytes()); + o.extend_from_slice(&name_len.to_le_bytes()); o.extend_from_slice(&0u16.to_le_bytes()); o.extend_from_slice(name_b); o.extend_from_slice(data); @@ -70,7 +94,7 @@ impl ZipWriter { c.extend_from_slice(&crc.to_le_bytes()); c.extend_from_slice(&size.to_le_bytes()); c.extend_from_slice(&size.to_le_bytes()); - c.extend_from_slice(&(name_b.len() as u16).to_le_bytes()); + c.extend_from_slice(&name_len.to_le_bytes()); c.extend_from_slice(&[0; 8]); // extra len, comment len, disk, internal attrs c.extend_from_slice(&0u32.to_le_bytes()); // external attrs c.extend_from_slice(&offset.to_le_bytes()); @@ -79,9 +103,11 @@ impl ZipWriter { Ok(()) } + /// Appends the central directory and returns the complete archive. pub fn finish(mut self) -> Result, FormatError> { let cd_offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?; - let cd_size = self.central.len() as u32; + let cd_size = u32::try_from(self.central.len()).map_err(|_| FormatError::Unsupported("zip directory over 4 GiB".into()))?; + self.out.try_reserve(self.central.len().saturating_add(22)).map_err(|_| FormatError::LimitExceeded("not enough memory to finish zip".into()))?; self.out.extend_from_slice(&self.central); self.out.extend_from_slice(&EOCD_SIG.to_le_bytes()); self.out.extend_from_slice(&[0; 4]); // disk numbers @@ -112,7 +138,7 @@ pub struct ZipReader<'a> { pub entries: Vec, /// Name -> index of the first entry with that name, so `find` is O(1) /// instead of a scan per lookup (a bundle reads one entry per tile). - by_name: HashMap, + by_name: HashMap, usize>, } fn u16_at(b: &[u8], o: usize) -> Result { @@ -123,6 +149,7 @@ fn u32_at(b: &[u8], o: usize) -> Result { } impl<'a> ZipReader<'a> { + /// Checks ZIP record bounds and indexes the first entry for each name. pub fn new(bytes: &'a [u8]) -> Result { if bytes.len() < 22 { return Err(FormatError::corrupt("not a zip archive (too short)")); @@ -137,7 +164,8 @@ impl<'a> ZipReader<'a> { let cd_size = u32_at(bytes, eocd + 12)? as usize; let cd_off = u32_at(bytes, eocd + 16)? as usize; let cd_end = cd_off.checked_add(cd_size).filter(|end| *end <= eocd).ok_or_else(|| FormatError::corrupt("zip central directory out of range"))?; - let mut entries = Vec::with_capacity(count.min(bytes.len() / 46)); + let mut entries = Vec::with_capacity(count.min(cd_size / 46)); + let mut by_name = HashMap::with_capacity(entries.capacity()); let mut p = cd_off; for _ in 0..count { let header_end = p.checked_add(46).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("truncated zip central directory entry"))?; @@ -155,7 +183,7 @@ impl<'a> ZipReader<'a> { let local = u32_at(bytes, p + 42)? as usize; let name_end = header_end.checked_add(nlen).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("zip entry name out of range"))?; let name = bytes.get(header_end..name_end).ok_or_else(|| FormatError::corrupt("truncated zip name"))?; - let name = String::from_utf8_lossy(name).into_owned(); + let name = String::from_utf8_lossy(name); if flags & 1 != 0 { return Err(FormatError::Unsupported("encrypted zip entries".into())); } @@ -181,14 +209,11 @@ impl<'a> ZipReader<'a> { if data_offset.checked_add(compressed).is_none_or(|end| end > bytes.len()) { return Err(FormatError::corrupt(format!("zip entry `{name}` out of range"))); } - entries.push(Entry { name, method, crc, compressed, uncompressed, data_offset }); + // The index borrows valid UTF-8 names; duplicate names keep the first entry. + by_name.entry(name.clone()).or_insert(entries.len()); + entries.push(Entry { name: name.into_owned(), method, crc, compressed, uncompressed, data_offset }); p = entry_end; } - let mut by_name = HashMap::with_capacity(entries.len()); - for (i, e) in entries.iter().enumerate() { - // Duplicate names: the first entry wins, as with a front-to-back scan. - by_name.entry(e.name.clone()).or_insert(i); - } Ok(ZipReader { bytes, entries, by_name }) } @@ -249,6 +274,20 @@ mod tests { assert_eq!(crc32(b"123456789"), 0xCBF4_3926); } + /// ZIP entry paths have a format limit even when each component is short. + #[test] + fn entry_path_length_is_checked_before_writing() { + let mut writer = ZipWriter::new(); + for name in ["dir/".repeat(16384), "é/".repeat(21846)] { + assert!(matches!(writer.add(&name, b"invalid"), Err(FormatError::Unsupported(_)))); + assert!(writer.out.is_empty() && writer.central.is_empty()); + } + let name = "dir/".repeat(16383) + "end"; + writer.add(&name, b"valid").unwrap(); + let bytes = writer.finish().unwrap(); + assert_eq!(ZipReader::new(&bytes).unwrap().read_by_name(&name, 5).unwrap(), b"valid"); + } + #[test] fn roundtrip() { let mut w = ZipWriter::new(); @@ -262,6 +301,7 @@ mod tests { assert_eq!(r.read_by_name("dir/b.bin", 100).unwrap(), [0, 1, 2, 3]); assert!(r.read_by_name("empty", 0).unwrap().is_empty()); assert!(matches!(r.read_by_name("a.txt", 3), Err(FormatError::LimitExceeded(_)))); + assert!(r.by_name.keys().all(|name| matches!(name, Cow::Borrowed(_)))); } #[test] @@ -317,6 +357,46 @@ mod tests { assert_eq!(r.read_by_name("b", 100).unwrap(), b"other"); } + /// Reservation changes neither entry bytes nor final output, and avoids growth. + #[test] + fn whole_archive_reservation_preserves_output() { + let entries = [("层/é.png", &b"image"[..]), ("empty", &b""[..]), ("empty", &b"duplicate"[..])]; + for entries in [&entries[..0], &entries[..]] { + let mut previous = ZipWriter::new(); + let mut reserved = ZipWriter::with_entries(entries.iter().map(|(name, data)| (*name, data.len()))).unwrap(); + let (capacity, directory) = (reserved.out.capacity(), reserved.central.capacity()); + for (name, data) in entries { + previous.add(name, data).unwrap(); + reserved.add(name, data).unwrap(); + } + assert_eq!(reserved.central.capacity(), directory); + let bytes = reserved.finish().unwrap(); + assert_eq!(bytes.capacity(), capacity); + assert_eq!(bytes, previous.finish().unwrap()); + } + assert!(matches!(ZipWriter::with_entries([("x", usize::MAX)]), Err(FormatError::Unsupported(_)))); + assert!(matches!(ZipWriter::with_entries([("x", isize::MAX as usize)]), Err(FormatError::LimitExceeded(_)))); + } + + /// Invalid UTF-8 names retain their lossy spelling and first-entry lookup. + #[test] + fn name_index_borrows_unicode_and_owns_lossy_names() { + let mut writer = ZipWriter::new(); + for name in ["层/é.png", "a", "b"] { + writer.add(name, name.as_bytes()).unwrap(); + } + let mut bytes = writer.finish().unwrap(); + let mut p = u32_at(&bytes, bytes.len() - 6).unwrap() as usize; + p += 46 + "层/é.png".len(); + bytes[p + 46] = 0xff; + bytes[p + 47 + 46] = 0xfe; + let reader = ZipReader::new(&bytes).unwrap(); + assert_eq!(reader.read_by_name("层/é.png", 100).unwrap(), "层/é.png".as_bytes()); + assert!(matches!(reader.by_name.get_key_value("层/é.png").unwrap().0, Cow::Borrowed(_))); + assert!(matches!(reader.by_name.get_key_value("�").unwrap().0, Cow::Owned(_))); + assert_eq!(reader.read_by_name("�", 1).unwrap(), b"a"); + } + #[test] fn crc_mismatch_detected() { let mut w = ZipWriter::new(); @@ -359,8 +439,8 @@ mod tests { /// A false small size must stop expansion before decoding the rest of the stream. #[test] fn deflate_surplus_stops_before_a_corrupt_suffix() { - // Non-final stored block, then an invalid block type after its payload. - let raw = [&[0, 32, 0, 0xdf, 0xff][..], &[b'x'; 32], &[7]].concat(); + // Exceed miniz's internal 32 KiB output buffer before the corrupt block. + let raw = [&[0, 0xff, 0xff, 0, 0][..], &[b'x'; 65535], &[7]].concat(); let reader = ZipReader { bytes: &raw, entries: Vec::new(), by_name: HashMap::new() }; for declared in [0, 7] { let entry = Entry { name: "surplus".into(), method: 8, crc: 0, compressed: raw.len(), uncompressed: declared, data_offset: 0 }; diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rs index f78e93947e..5c7fe070c7 100644 --- a/crates/format/tests/roundtrip.rs +++ b/crates/format/tests/roundtrip.rs @@ -217,10 +217,11 @@ fn exhausted_document_ids_and_maximal_text_runs_roundtrip() { fn zip_incremental_only_new_tiles() { let mut doc = rich_doc(ColorMode::Rgb, SampleType::U16); let mut w = PcraftWriter::new(); - let (_, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); + let (first, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); assert!(s1.tiles_total > 5); assert_eq!(s1.tiles_written, s1.tiles_total); - let (_, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); + let (cached, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); + assert_eq!(first, cached); assert_eq!(s2.tiles_written, 0); assert_eq!(s2.tiles_reused, s2.tiles_total); assert_eq!(s2.blobs_written, 0); @@ -230,6 +231,7 @@ fn zip_incremental_only_new_tiles() { let (bytes, s3) = w.save_zip(&doc, &SaveOptions::default()).unwrap(); assert_eq!(s3.tiles_written, 1); assert_eq!(load_from_bytes(&bytes).unwrap(), doc); + assert_eq!(bytes, PcraftWriter::new().save_zip(&doc, &SaveOptions::default()).unwrap().0); } #[test] diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md index 886383a4ac..ce096ee1db 100644 --- a/docs/deflate-zlib-rs-performance.md +++ b/docs/deflate-zlib-rs-performance.md @@ -8,8 +8,7 @@ The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 2 Real photo PNGs become smaller and encode faster. Compression levels are unchanged. There is no native-format tile speedup from deflate. -These timings measure the backend switch before the ZIP input-buffer removal and output-size guard. -Neither ZIP change was benchmarked. +The timings below measure only the backend switch. They exclude the later ZIP allocation and validation changes. Measured on 2026-10-19 against main `d95fdf31`, independently of the other performance changes. Host: Apple M4 Max, 16 CPUs, 128 GiB RAM, macOS arm64, rustc 1.99.1. @@ -72,6 +71,10 @@ The shared harness times in-memory operations. Input loading, image conversion, Every PNG encode decodes to identical source pixels, each PSD operation produces the same decoded layer/mask samples as main, and complete .pcraft documents compare equal at every depth. Compressed bytes may differ. The committed compatibility test independently inflates PNG IDAT and PSD ZIP/ZIP-prediction data using old miniz_oxide and checks .pcraft tiles plus thumbnails. +## Allocation and validation changes + +ZIP lookup keys borrow valid UTF-8 entry paths, avoiding a second string allocation per entry. Invalid names keep their previous lossy spelling and duplicate-name lookup still selects the first entry. The bundle writer reserves the complete archive after compression, including its central directory. It rejects entry paths that exceed ZIP's 65,535-byte field before writing and checks that the central-directory size fits its ZIP field. These archive paths are independent of filesystem path limits. + ## Linux and Windows x86-64 validation [GitHub Actions run](https://github.com/reneleonhardt/photocraft/actions/runs/39444647224) passed the deflate compatibility test, From eb7e497aaf3994dcf02a38752b6da00c3b5f7d79 Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:59:34 +0200 Subject: [PATCH 24/87] perf(compression): decode compressed slices without buffering Use the buffered-input decoders directly for Affinity zlib entries, deep EXR ZIP chunks and SVGZ data already held in memory. This avoids a 32 KiB input allocation and copy per decoder. Keep output limits and checksum handling, with coverage for truncated EXR streams and concatenated SVG gzip members. --- crates/affinity/src/container.rs | 2 +- crates/codecs/src/codecs/deep_exr.rs | 3 ++- crates/io/src/svg.rs | 2 +- crates/io/tests/svg.rs | 3 +++ docs/deflate-zlib-rs-performance.md | 4 +++- 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs index 880b7236d1..2b626e5697 100644 --- a/crates/affinity/src/container.rs +++ b/crates/affinity/src/container.rs @@ -312,7 +312,7 @@ fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { } fn inflate(data: &[u8], size: usize) -> Result, Error> { - read_bounded(flate2::read::ZlibDecoder::new(data), size) + read_bounded(flate2::bufread::ZlibDecoder::new(data), size) } fn unzstd(data: &[u8], size: usize) -> Result, Error> { diff --git a/crates/codecs/src/codecs/deep_exr.rs b/crates/codecs/src/codecs/deep_exr.rs index 29f3762ebc..e630dece78 100644 --- a/crates/codecs/src/codecs/deep_exr.rs +++ b/crates/codecs/src/codecs/deep_exr.rs @@ -187,7 +187,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s // `read_to_end`, whose doubling reserves past `expected`. Once `expected` bytes are // in, a one-byte read checks that the stream ends there. let malformed = || err(format!("{what}: zlib data is malformed")); - let mut zlib = flate2::read::ZlibDecoder::new(packed); + let mut zlib = flate2::bufread::ZlibDecoder::new(packed); let mut out = Vec::new(); let mut filled = 0; while filled < expected { @@ -737,6 +737,7 @@ mod tests { let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); z.write_all(&p).expect("write to a Vec"); let zips = z.finish().expect("finish a Vec"); + assert!(decompress(Compression::ZIP1, &zips[..zips.len() - 1], n, "the table").is_err()); // RLE: the first byte as a literal, then runs of up to 128 copies of the next. let mut rle = vec![0xFF, p[0]]; for run in p[1..].chunks(128) { diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 8afefb733d..bd6455fb53 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -122,7 +122,7 @@ fn inflate(bytes: &[u8]) -> Result, IoError> { return Ok(std::borrow::Cow::Borrowed(bytes)); } let mut out = Vec::new(); - let mut reader = flate2::read::MultiGzDecoder::new(bytes).take(MAX_INFLATED_BYTES.saturating_add(1)); + let mut reader = flate2::bufread::MultiGzDecoder::new(bytes).take(MAX_INFLATED_BYTES.saturating_add(1)); reader.read_to_end(&mut out).map_err(|e| IoError::Svg(format!("the compressed SVG couldn't be inflated: {e}")))?; if u64::try_from(out.len()).unwrap_or(u64::MAX) > MAX_INFLATED_BYTES { return Err(IoError::Svg(format!("the compressed SVG inflates past {} MB", MAX_INFLATED_BYTES >> 20))); diff --git a/crates/io/tests/svg.rs b/crates/io/tests/svg.rs index 4f21bd5dcb..c68f8118ae 100644 --- a/crates/io/tests/svg.rs +++ b/crates/io/tests/svg.rs @@ -340,6 +340,9 @@ fn svgz_is_inflated_with_a_size_cap() { let r = import("drawing.svgz", &gzip(plain.as_bytes())).unwrap(); assert_eq!(r.document.layers.len(), 1); assert!(close(px(&r.document, 4, 4), [0.0, 0.0, 1.0, 1.0])); + let split = plain.len() / 2; + let members = [gzip(&plain.as_bytes()[..split]), gzip(&plain.as_bytes()[split..])].concat(); + assert!(close(px(&import("members.svgz", &members).unwrap().document, 4, 4), [0.0, 0.0, 1.0, 1.0])); // A bomb: a few hundred KB of gzip holding more than the cap of whitespace. let mut bomb = format!("").into_bytes(); bomb.resize(usize::try_from(svg::MAX_INFLATED_BYTES).unwrap() + 1024, b' '); diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md index ce096ee1db..f924f4d8ea 100644 --- a/docs/deflate-zlib-rs-performance.md +++ b/docs/deflate-zlib-rs-performance.md @@ -8,7 +8,7 @@ The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 2 Real photo PNGs become smaller and encode faster. Compression levels are unchanged. There is no native-format tile speedup from deflate. -The timings below measure only the backend switch. They exclude the later ZIP allocation and validation changes. +The timings below measure only the backend switch. They exclude the later ZIP allocation, validation and slice decoder changes. Measured on 2026-10-19 against main `d95fdf31`, independently of the other performance changes. Host: Apple M4 Max, 16 CPUs, 128 GiB RAM, macOS arm64, rustc 1.99.1. @@ -75,6 +75,8 @@ Every PNG encode decodes to identical source pixels, each PSD operation produces ZIP lookup keys borrow valid UTF-8 entry paths, avoiding a second string allocation per entry. Invalid names keep their previous lossy spelling and duplicate-name lookup still selects the first entry. The bundle writer reserves the complete archive after compression, including its central directory. It rejects entry paths that exceed ZIP's 65,535-byte field before writing and checks that the central-directory size fits its ZIP field. These archive paths are independent of filesystem path limits. +Affinity zlib entries, deep EXR ZIP chunks and compressed SVG input now decode directly from their byte slices. This removes flate2's 32 KiB input-buffer allocation and copy for each decoder. Output bounds, checksums and SVG concatenated gzip members remain covered by tests. These are structural allocation reductions, not measured timing gains. + ## Linux and Windows x86-64 validation [GitHub Actions run](https://github.com/reneleonhardt/photocraft/actions/runs/39444647224) passed the deflate compatibility test, From 9c2f6db42c718dbdd0504c1c73b70efc75996ebb Mon Sep 17 00:00:00 2001 From: D-monized Date: Thu, 22 Oct 2026 02:23:17 -0600 Subject: [PATCH 25/87] Text tests: restore the braces the 21 Oct web merge cut from faux_bold_keeps_square_corners_square Co-Authored-By: Claude Opus 5.5 --- crates/text/src/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index ae67a9ff45..dfe1562195 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2327,6 +2327,9 @@ fn faux_bold_keeps_square_corners_square() { let a = alpha(x, top + 1); assert!(a > 0.9, "bold {bold}: the {corner} corner is cut away (alpha {a})"); } + } +} + #[test] fn text_rebuild_preserves_imported_font_metadata() { use crate::engine_data::Value as E; From 29d55618c51c96c4ffbd0ba50f127468c390ac40 Mon Sep 17 00:00:00 2001 From: D-monized Date: Thu, 22 Oct 2026 03:53:49 -0600 Subject: [PATCH 26/87] docs: regenerate the scorecard Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 9fd35b7e25..b66a33cd61 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 | 26 | 60 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 22 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 9 | 12 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 36 | 8 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 14 | 6 | 3 | settings that do nothing: 24 of 171 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 14 | 6 | 3 | settings that do nothing: 23 of 173 (target 0) | | [Type](#type) | 5 | 3 | 1 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -181,9 +181,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 24 of 171** (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: 23 of 173** (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.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `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.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`, `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 | |---|---|---|---|---| From a33854e5b4a44ec3405726e6c006acd652129193 Mon Sep 17 00:00:00 2001 From: D-monized Date: Thu, 22 Oct 2026 03:53:58 -0600 Subject: [PATCH 27/87] Font menu test: set TextEdit's new document field Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/type_font_picker_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_font_picker_tests.rs index b599d63b6f..c7dfc0c2d9 100644 --- a/crates/ui-egui/src/type_font_picker_tests.rs +++ b/crates/ui-egui/src/type_font_picker_tests.rs @@ -961,6 +961,7 @@ fn the_preview_sets_the_type_layers_text_or_the_selection_being_typed() { app.run("layer.select", serde_json::json!({"id": id})).ok(); app.ui.text_edit = Some(crate::state::TextEdit { layer: id, + document: None, caret: 0, anchor: 0, session: "s".into(), From fb04b02893c55e359ab86f4d0fdcc6165e8b0b47 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Thu, 22 Oct 2026 22:26:11 +0100 Subject: [PATCH 28/87] fix(codecs): check header dimensions against the file size before allocating JPEG, the image-crate formats (GIF, BMP, TGA, ICO, QOI, HDR), PCX, XPM and flat EXR sized their output buffers from header dimensions, checked only against the absolute limits. A few-KB file could declare ~3 GB and the decoder allocated it before finding the data missing (on wasm that aborts the tab). Each now refuses, before allocating, a file too small to hold the declared image at that format's best compression ratio, the guard PNG, WebP and IFF already use. XPM checks its text rows up front. Fixes #8597 Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/exr.rs | 6 ++ crates/codecs/src/codecs/jpeg.rs | 4 ++ crates/codecs/src/codecs/pcx.rs | 3 + crates/codecs/src/codecs/via_image.rs | 9 ++- crates/codecs/src/codecs/xpm.rs | 11 ++-- crates/codecs/tests/it/limits.rs | 86 +++++++++++++++++++++++++++ 6 files changed, 114 insertions(+), 5 deletions(-) diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index 2b32a2b7c4..9640d69d5d 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -49,6 +49,12 @@ pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result limits.max_alloc { return Err(CodecError::LimitExceeded(format!("{total} bytes across {} parts exceed max_alloc {}", meta.headers.len(), limits.max_alloc))); } + // The `exr` crate allocates a flat part's samples before reading its chunks, so the file + // must be able to hold them (#8597). Lossless EXR compression stays far below 2^16:1 even + // against this f32 budget; deep parts size their samples from the file's own counts. + if !meta.requirements.has_deep_data { + Limits::check_plausible(total, bytes.len(), 1 << 16)?; + } Ok(meta) } diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index cf1c9fca43..a8abc0c626 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -190,6 +190,10 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result let meta = scan_metadata(bytes); if let Some((w, h, nc)) = meta.frame { limits.check_bytes(w, h, u64::from(nc.max(1)))?; + // Huffman coding spends at least a bit per 8x8 block per component (about 1024:1 for + // a flat 4:2:0 image), so a file far smaller than that cannot hold the frame. zune-jpeg + // only needs one byte of scan data before it allocates the whole output (#8597). + Limits::check_plausible(u64::from(w) * u64::from(h) * u64::from(nc.max(1)), bytes.len(), 1 << 12)?; } let options = DecoderOptions::default().set_strict_mode(false).set_max_width(65535).set_max_height(65535); let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), options); diff --git a/crates/codecs/src/codecs/pcx.rs b/crates/codecs/src/codecs/pcx.rs index f89a781e9d..ae32e76f34 100644 --- a/crates/codecs/src/codecs/pcx.rs +++ b/crates/codecs/src/codecs/pcx.rs @@ -65,6 +65,9 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { limits.check(w, h, ChannelLayout::Rgb, SampleType::U8)?; let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66))); let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?; + // An RLE packet expands two bytes to at most 63, so the file must hold at least 1/32 of + // the declared scanlines before the output is allocated (#8597). + Limits::check_plausible((row_len as u64).saturating_mul(u64::from(h)), b.len(), 32)?; let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(3)).ok_or_else(|| bad("pixel size overflow"))?; // The last 769 bytes are the optional VGA palette for 8-bit indexed images. let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c; diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs index 81f4a369ca..4e9d9ccfc4 100644 --- a/crates/codecs/src/codecs/via_image.rs +++ b/crates/codecs/src/codecs/via_image.rs @@ -93,7 +93,14 @@ fn open<'a>(f: Format, bytes: &'a [u8], limits: &Limits) -> Result], limits: &Limits) -> Result } } let row_len = width.checked_mul(cpp).ok_or_else(|| bad("row byte count overflow"))?; + let rows = lines.get(1 + colours..required).ok_or_else(|| bad("truncated image rows"))?; + // The rows are plain text, so check every one before allocating the output: a header + // declaring a huge width over short rows must not reserve gigabytes first (#8597). + if rows.iter().any(|line| line.len() != row_len) { + return Err(bad("XPM row has the wrong width")); + } let mut pixels = vec![0u8; width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or_else(|| bad("pixel size overflow"))?]; - for (y, line) in lines[1 + colours..required].iter().enumerate() { - if line.len() != row_len { - return Err(bad("XPM row has the wrong width")); - } + for (y, line) in rows.iter().enumerate() { for x in 0..width { let key = &line[x * cpp..(x + 1) * cpp]; let rgba = palette.get(key).ok_or_else(|| bad("unknown palette key"))?; diff --git a/crates/codecs/tests/it/limits.rs b/crates/codecs/tests/it/limits.rs index c1873771f6..38b161e628 100644 --- a/crates/codecs/tests/it/limits.rs +++ b/crates/codecs/tests/it/limits.rs @@ -456,3 +456,89 @@ fn limits_check_api() { assert!(l.check(10, 10, ChannelLayout::Rgba, SampleType::U8).is_err()); assert!(l.check(10, 10, ChannelLayout::Rgb, SampleType::U8).is_ok()); } + +/// #8597: a small file whose header declares about 3 GB, inside the default limits, is refused +/// by the size-against-file check before the decoder allocates its output. +fn refused_as_implausible(f: Format, b: &[u8]) { + match decode(b) { + Err(CodecError::LimitExceeded(m)) => assert!(m.contains("cannot hold"), "{f:?}: {m}"), + other => panic!("{f:?}: expected an implausible-size refusal, got {:?}", other.map(|i| (i.width(), i.height()))), + } +} + +fn find(b: &[u8], needle: &[u8]) -> usize { + b.windows(needle.len()).position(|w| w == needle).unwrap() +} + +#[test] +fn jpeg_header_declaring_gigabytes_needs_a_plausible_file_size() { + let mut b = encoded(Format::Jpeg); + // SOF0: marker, length, precision, then height and width (big-endian). + let sof = find(&b, &[0xFF, 0xC0]); + b[sof + 5..sof + 7].copy_from_slice(&16000u16.to_be_bytes()); + b[sof + 7..sof + 9].copy_from_slice(&65000u16.to_be_bytes()); + refused_as_implausible(Format::Jpeg, &b); +} + +#[test] +fn image_crate_headers_declaring_gigabytes_need_a_plausible_file_size() { + let side = 30000u32; + let mut bmp = encoded(Format::Bmp); + bmp[18..22].copy_from_slice(&(side as i32).to_le_bytes()); + bmp[22..26].copy_from_slice(&(side as i32).to_le_bytes()); + refused_as_implausible(Format::Bmp, &bmp); + let mut qoi = encoded(Format::Qoi); + // The qoi crate refuses more than 400 M pixels itself, so 20000 x 20000 (1.6 GB). + qoi[4..8].copy_from_slice(&20000u32.to_be_bytes()); + qoi[8..12].copy_from_slice(&20000u32.to_be_bytes()); + refused_as_implausible(Format::Qoi, &qoi); + let mut gif = encoded(Format::Gif); + gif[6..8].copy_from_slice(&(side as u16).to_le_bytes()); + gif[8..10].copy_from_slice(&(side as u16).to_le_bytes()); + refused_as_implausible(Format::Gif, &gif); +} + +#[test] +fn pcx_header_declaring_gigabytes_needs_a_plausible_file_size() { + // 24-bit (three 8-bit planes) 65535 x 16384, with one row of data. + let mut b = vec![0u8; 128]; + b[0] = 0x0a; + b[1] = 5; + b[2] = 1; + b[3] = 8; + b[8..10].copy_from_slice(&65534u16.to_le_bytes()); + b[10..12].copy_from_slice(&16383u16.to_le_bytes()); + b[65] = 3; + b[66..68].copy_from_slice(&65535u16.to_le_bytes()); + b[68..70].copy_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&[0xff, 0]); + refused_as_implausible(Format::Pcx, &b); +} + +#[test] +fn xpm_rows_shorter_than_the_header_declares_are_refused_before_allocating() { + let b = b"/* XPM */\nstatic char *x[] = {\n\"30000 30000 1 1\",\n\". c #000000\",\n\".\",\n};\n".to_vec(); + match decode(&b) { + Err(CodecError::Malformed { .. }) => {} + other => panic!("expected a malformed-row error, got {:?}", other.map(|i| (i.width(), i.height()))), + } +} + +#[test] +fn exr_header_declaring_gigabytes_needs_a_plausible_file_size() { + let mut b = encoded(Format::OpenExr); + // dataWindow: name, type, size, then xMin, yMin, xMax, yMax (little-endian i32). + let at = find(&b, b"dataWindow\0box2i\0") + b"dataWindow\0box2i\0".len() + 4; + b[at + 8..at + 12].copy_from_slice(&15999i32.to_le_bytes()); + b[at + 12..at + 16].copy_from_slice(&15999i32.to_le_bytes()); + refused_as_implausible(Format::OpenExr, &b); +} + +#[test] +fn highly_compressible_jpeg_and_gif_still_decode() { + let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap(); + for f in [Format::Jpeg, Format::Gif, Format::Qoi, Format::OpenExr] { + let b = encode(&img, f, &EncodeOptions::default()).unwrap(); + assert_eq!(decode(&b).unwrap().width(), 3000, "{f:?}"); + } +} From 2c00ba2e36f9198fdfcfb4504a0f1c30887fd727 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Thu, 22 Oct 2026 23:40:32 +0100 Subject: [PATCH 29/87] fix(codecs): exempt Radiance HDR from the size-ratio check Its old-style RLE repeat markers multiply their counts by 256 each in a row, so a valid file has no ratio bound; the allocation limit still applies. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/via_image.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs index 4e9d9ccfc4..5269c94b12 100644 --- a/crates/codecs/src/codecs/via_image.rs +++ b/crates/codecs/src/codecs/via_image.rs @@ -98,7 +98,9 @@ fn open<'a>(f: Format, bytes: &'a [u8], limits: &Limits) -> Result Date: Fri, 23 Oct 2026 04:25:01 -0600 Subject: [PATCH 30/87] docs: leave the scorecard count to the integration batch This branch adds one preference; the 'settings that do nothing' total is recounted when the batch is integrated, so two open PRs don't keep conflicting on the same two lines. Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 654b96529d..6e84b9847e 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 | 26 | 60 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 22 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 9 | 13 | 5 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/256, round trip ≥ 258/256 | | [Tools](#tools) | 36 | 8 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 14 | 6 | 3 | settings that do nothing: 21 of 177 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 14 | 6 | 3 | settings that do nothing: 21 of 176 (target 0) | | [Type](#type) | 5 | 4 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -181,7 +181,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 21 of 177** (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: 21 of 176** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From e9d00facd96e64fcf6ce4dddbd4a8c074053cdb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Fri, 23 Oct 2026 18:49:56 +0200 Subject: [PATCH 31/87] fix(ui): Remove Tool trail tints all a stroke removes; brush trails follow hardness (#8916) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Remove Tool's tint (while dragging, and for waiting strokes) was a hard capsule at the brush's nominal radius, but the removal takes every pixel the stroke's dabs touch (`remove::hole`: coverage > 0). A soft tip reaches about 1.73 × its radius, so an 80 px soft brush tinted 80 px and removed ~140 px. The Mixer Brush, and tools whose live stroke didn't start, showed the same hard capsule. - `Trail::feed_reach` / `feed_stroke_reach`: the stroke's dabs (the brush engine, as `feed_dabs`) where they reach at all, in full. Waiting strokes keep the earlier ones' tint under them (`base`). - Remove uses them; the Mixer Brush and the fallback trail use `feed_dabs` (soft); Quick Selection keeps its capsule (`select.quick` reads the size). - `Trail::feed_stroke` (the capsule for waiting strokes) is gone. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 88 ++++++++++++++++------------- crates/ui-egui/src/retouch_ui.rs | 4 +- crates/ui-egui/src/stroke_trail.rs | 89 +++++++++++++++++++++++++----- 3 files changed, 127 insertions(+), 54 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d2543a54c2..15e673a353 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5520,11 +5520,16 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &View let size = [st.doc.size.width, st.doc.size.height]; let doc_rect = xf.doc_rect(st.doc.bounds()); let trail = app.trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)); - if t == Tool::SpotHealing { - // What the heal covers, dab by dab: soft edges, pressure and shape dynamics (#2364). - trail.feed_dabs(&d.points, || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({}))); - } else { - trail.feed(&d.points, app.session.tools.brush.size); + let brush = || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + match t { + // Quick Selection reads the brush's size alone (`select.quick`). + Tool::QuickSelection => trail.feed(&d.points, app.session.tools.brush.size), + // Remove removes every pixel a dab touches, so its whole reach is tinted: a soft + // tip's reaches well past the nominal radius. + Tool::Remove => trail.feed_reach(&d.points, brush), + // What the stroke covers, dab by dab: soft edges, pressure and shape dynamics + // (Spot Healing #2364; the Mixer Brush, and a tool whose live stroke didn't start). + _ => trail.feed_dabs(&d.points, brush), } trail.draw(painter, doc_rect, xf.flip, col); } @@ -9031,43 +9036,48 @@ mod tests { #[test] fn retouch_drags_show_the_footprint_without_wedges() { // The retouching tools' trail was the same brush-wide polyline (#189): now a mask of the - // footprint, with nothing outside the brush radius of the path, however small the steps. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 30}})).unwrap(); - // Remove: the dab tools draw their stroke live instead of a trail, and Spot Healing's - // trail is its dabs' coverage. - app.ui.tool = Tool::Remove; - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - let mut pts = vec![[20.0, 30.0]]; - for i in 1..80 { - let t = f64::from(i) * 0.5; - let p = [20.0 + t, 30.0 + (t / 2.0).sin() * 3.0]; - tool_event(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE); - pts.push(p); - if i % 20 == 0 { - // One mesh for the trail, however long the drag. - let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); - assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); - } - } - drag_preview_shapes(&mut app, &ctx, 12.0); - let trail = app.trail.as_ref().unwrap(); - assert_eq!(trail.scale(), 1.0); - for y in 0..60 { - for x in 0..120 { - let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min); - if d < 14.0 { - assert_eq!(trail.coverage(x, y), 255, "({x}, {y}) inside the footprint"); - } else if d > 16.0 { - assert_eq!(trail.coverage(x, y), 0, "({x}, {y}) outside the footprint"); + // footprint, with nothing outside it, however small the steps. The Remove Tool's is where + // the stroke's dabs reach at all, which is what it removes, so a soft tip's whole reach + // past the radius is tinted. + for hardness in [1.0, 0.0] { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": hardness}})).unwrap(); + app.ui.tool = Tool::Remove; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for i in 1..80 { + let t = f64::from(i) * 0.5; + tool_event(&mut app, ToolEvent::Move { x: 20.0 + t, y: 30.0 + (t / 2.0).sin() * 3.0, pressure: 1.0 }, egui::Modifiers::NONE); + if i % 20 == 0 { + // One mesh for the trail, however long the drag. + let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); } } + drag_preview_shapes(&mut app, &ctx, 12.0); + // The stroke the removal gets on release, and the pixels its hole takes. + let points = app.drag.as_ref().unwrap().points.iter().map(|p| photocraft_paint::StrokePoint::new(p[0], p[1], p[2] as f32)).collect(); + let brush = photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + let (b, cov) = photocraft_paint::retouch::stroke_coverage(&photocraft_paint::Stroke { brush, points }); + let trail = app.trail.as_ref().unwrap(); + assert_eq!(trail.scale(), 1.0); + let mut beyond = 0; + for y in 0..60 { + for x in 0..120 { + let removed = b.contains(x, y) && cov[(y - b.y0) as usize * b.width() as usize + (x - b.x0) as usize] > 0.0; + assert_eq!(trail.coverage(x as usize, y as usize), if removed { 255 } else { 0 }, "hardness {hardness}: ({x}, {y})"); + // Past the 15 px radius of the path's ends and sides (y 27..33). + beyond += usize::from(removed && !(12..=48).contains(&y)); + } + } + if hardness == 0.0 { + assert!(beyond > 100, "a soft tip's removal reaches past its radius: {beyond} px"); + } + tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); + drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(app.trail.is_none(), "the trail ends with the drag"); } - tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); - drag_preview_shapes(&mut app, &ctx, 12.0); - assert!(app.trail.is_none(), "the trail ends with the drag"); } #[test] diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs index 495a1babf6..472f1a838b 100644 --- a/crates/ui-egui/src/retouch_ui.rs +++ b/crates/ui-egui/src/retouch_ui.rs @@ -208,8 +208,8 @@ pub fn remove_pending_add(app: &mut PhotocraftApp, points: &[[f64; 3]]) { app.remove_trail = None; app.remove_pending_target = Some(target); } - let diameter = app.session.tools.brush.size; - app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed_stroke(points, diameter); + let brush = || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed_stroke_reach(points, brush); app.remove_pending.push(points.to_vec()); app.ui.status = crate::i18n::fmt(tl!("Strokes to remove: {n} (Enter applies, Esc cancels)"), &[("n", &app.remove_pending.len().to_string())]); app.ui.status_error = false; diff --git a/crates/ui-egui/src/stroke_trail.rs b/crates/ui-egui/src/stroke_trail.rs index af09fca1c4..0ea62c6a97 100644 --- a/crates/ui-egui/src/stroke_trail.rs +++ b/crates/ui-egui/src/stroke_trail.rs @@ -4,7 +4,8 @@ //! It is a coverage mask in document space, stamped segment by segment as the pointer moves and //! drawn as one texture over the document. The Spot Healing Brush's trail is instead the coverage //! of the brush's own dabs ([`Trail::feed_dabs`]): hardness, pressure and shape dynamics show as -//! they heal (#2364). It used to be an egui polyline as wide as the brush: +//! they heal (#2364). The Remove Tool's is where those dabs reach at all ([`Trail::feed_reach`]), +//! which is what it removes. It used to be an egui polyline as wide as the brush: //! egui tessellates a polyline whose width is much larger than its steps (any zoomed-in drag) //! into hard pie wedges fanning out across the canvas (#189), and translucent overlaps doubled up. @@ -31,11 +32,16 @@ pub struct Trail { tex: Option, /// The stroke's dabs, when the trail shows their coverage ([`Self::feed_dabs`]). dabs: Option, + /// Coverage earlier strokes in the same mask left (the Remove Tool's waiting strokes); empty + /// when there are none. A dab stroke's restamp keeps the larger of the two. + base: Vec, } /// The brush stroke behind a [`Trail::feed_dabs`] trail. struct Dabs { renderer: StrokeRenderer, + /// Any coverage counts in full ([`Trail::feed_reach`]). + reach: bool, /// Document pixels the last "finish now" tail (a lone first dab, smoothing catch-up) covered. tail: photocraft_geom::Rect, } @@ -44,7 +50,7 @@ impl Trail { pub fn new(doc: [u32; 2]) -> Self { let k = doc[0].max(doc[1]).div_ceil(MAX_SIDE).max(1); let (w, h) = (doc[0].div_ceil(k).max(1) as usize, doc[1].div_ceil(k).max(1) as usize); - Self { doc, k: k as f32, w, h, cov: vec![0; w * h], fed: 0, dirty: None, tex: None, dabs: None } + Self { doc, k: k as f32, w, h, cov: vec![0; w * h], fed: 0, dirty: None, tex: None, dabs: None, base: Vec::new() } } /// Coverage at a mask pixel (tests). @@ -74,22 +80,36 @@ impl Trail { self.fed = points.len(); } - /// Stamp a whole new drag into the same mask (the Remove tool's waiting strokes, #6555): its - /// points are counted from its own start, not from where the previous drag ended. - pub fn feed_stroke(&mut self, points: &[[f64; 3]], diameter: f32) { - self.fed = 0; - self.feed(points, diameter); - } - /// Show the coverage the brush's own dabs leave along the drag, as the stroke commit renders /// it (`photocraft_paint::retouch::stroke_coverage`): soft edges for a soft brush, the size and /// shape each dab takes from pen pressure and dynamics. `brush` is asked for once, on the first /// call. What finishing the stroke now would add (the press's lone first dab) shows too. pub fn feed_dabs(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings) { + self.feed_dabs_with(points, brush, false); + } + + /// Show where the brush's own dabs reach at all, in full: the Remove Tool removes every pixel a + /// dab covers, however faintly (`retouch_cmds::remove`'s hole), so a soft tip's whole reach is + /// tinted, not just its nominal radius or its opaque core. + pub fn feed_reach(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings) { + self.feed_dabs_with(points, brush, true); + } + + /// [`Self::feed_reach`] for a whole new drag into the same mask (the Remove Tool's waiting + /// strokes, #6555): the earlier strokes' tint stays under it. + pub fn feed_stroke_reach(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings) { + self.base.clone_from(&self.cov); + self.dabs = None; + self.fed = 0; + self.feed_reach(points, brush); + } + + fn feed_dabs_with(&mut self, points: &[[f64; 3]], brush: impl FnOnce() -> BrushSettings, reach: bool) { if self.dabs.is_some() && self.fed >= points.len() { return; } - let mut dabs = self.dabs.take().unwrap_or_else(|| Dabs { renderer: StrokeRenderer::new(&brush(), None, 1.0), tail: photocraft_geom::Rect::EMPTY }); + let mut dabs = + self.dabs.take().unwrap_or_else(|| Dabs { renderer: StrokeRenderer::new(&brush(), None, 1.0), reach, tail: photocraft_geom::Rect::EMPTY }); let new: Vec = points .get(self.fed..) .unwrap_or(&[]) @@ -105,7 +125,8 @@ impl Trail { changed = changed.union(&dabs.tail); let tail = tail.map(|(_, t)| t); let renderer = &dabs.renderer; - self.restamp(changed, |x, y| renderer.coverage_at(x, y).max(tail.as_ref().map_or(0.0, |t| t.coverage_at(x, y)))); + let full = |c: f32| if dabs.reach && c > 0.0 { 1.0 } else { c }; + self.restamp(changed, |x, y| full(renderer.coverage_at(x, y).max(tail.as_ref().map_or(0.0, |t| t.coverage_at(x, y))))); self.dabs = Some(dabs); } @@ -129,7 +150,9 @@ impl Trail { let dx = ((x as f64 + 0.5) * k).floor() as i32; let c = cov(dx, dy); let c = if c.is_finite() { (c.clamp(0.0, 1.0) * 255.0).round() as u8 } else { 0 }; - if let Some(v) = self.cov.get_mut(y * self.w + x) { + let i = y * self.w + x; + let c = c.max(self.base.get(i).copied().unwrap_or(0)); + if let Some(v) = self.cov.get_mut(i) { *v = c; } } @@ -239,8 +262,9 @@ mod tests { &[[50.0, 120.0, 1.0], [120.0, 120.0, 1.0]], &[[50.0, 200.0, 1.0], [80.0, 200.0, 1.0], [120.0, 200.0, 1.0], [160.0, 200.0, 1.0], [200.0, 200.0, 1.0], [260.0, 200.0, 1.0]], ]; + let brush = BrushSettings { size: 10.0, ..Default::default() }; for s in strokes { - t.feed_stroke(s, 10.0); + t.feed_stroke_reach(s, || brush.clone()); } for (x, y) in [(50, 50), (85, 50), (199, 50), (50, 120), (85, 120), (119, 120), (50, 200), (65, 200), (100, 200), (259, 200)] { assert_eq!(t.coverage(x, y), 255, "({x}, {y}) lies on a stroke"); @@ -249,6 +273,45 @@ mod tests { assert_eq!(t.coverage(150, 160), 0); } + /// The Remove Tool removes every pixel a dab touches: its trail is the dabs' whole reach in + /// full, a soft tip's well past the nominal radius, and never less than the coverage itself. + #[test] + fn a_reach_trail_tints_all_a_soft_tip_touches() { + let pts = [[50.0, 50.0, 1.0], [150.0, 50.0, 1.0]]; + let brush = BrushSettings { size: 20.0, hardness: 0.0, ..Default::default() }; + let mut reach = Trail::new([200, 100]); + reach.feed_reach(&pts, || brush.clone()); + let mut soft = Trail::new([200, 100]); + soft.feed_dabs(&pts, || brush.clone()); + let r = photocraft_paint::tip_reach(10.0, 0.0); + assert!(r > 15.0, "a soft tip reaches past its 10 px radius: {r}"); + assert_eq!(reach.coverage(100, 50 + 14), 255, "4 px past the radius, still removed"); + assert!(soft.coverage(100, 50 + 14) < 128, "where the soft coverage is faint"); + assert_eq!(reach.coverage(100, 50 + r.ceil() as usize + 2), 0, "nothing past the reach"); + // Where the soft trail shows anything the reach is tinted in full (it also takes coverage + // too faint to show as a soft trail's 8 bits). + for y in 0..100 { + for x in 0..200 { + assert!(soft.coverage(x, y) == 0 || reach.coverage(x, y) == 255, "({x}, {y})"); + assert!(matches!(reach.coverage(x, y), 0 | 255), "({x}, {y}): all or nothing"); + } + } + } + + /// A waiting Remove stroke keeps its tint where a later one crosses it (each restamps only the + /// area it changed, over what was there). + #[test] + fn a_later_reach_stroke_keeps_the_earlier_ones_tint() { + let mut t = Trail::new([200, 200]); + let brush = BrushSettings { size: 20.0, ..Default::default() }; + t.feed_stroke_reach(&[[20.0, 100.0, 1.0], [180.0, 100.0, 1.0]], || brush.clone()); + t.feed_stroke_reach(&[[100.0, 20.0, 1.0], [100.0, 180.0, 1.0]], || brush.clone()); + for (x, y) in [(40, 100), (95, 100), (100, 100), (105, 100), (160, 100), (100, 40), (100, 160)] { + assert_eq!(t.coverage(x, y), 255, "({x}, {y}) lies on a stroke"); + } + assert_eq!(t.coverage(40, 40), 0); + } + #[test] fn hostile_points_and_huge_documents_are_safe() { let mut t = Trail::new([300_000, 2]); From b0b100643bb880923a664b3c9226468c2b70178e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Fri, 23 Oct 2026 20:54:19 +0200 Subject: [PATCH 32/87] fix: waiting Remove strokes keep the brush they were drawn with (#8923 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A waiting stroke (Remove after each stroke off) was tinted with the brush it was drawn with but removed with the brush at ↩, so changing the brush in between made the tint and the removal disagree. - `paint.remove`: a `strokes` entry may be `{"points", "size"?, "hardness"?, "spacing"?}`, which override the call's for that stroke; a plain point list still takes the call's. - The UI keeps each waiting stroke as such an entry with the brush it was drawn with; its tint (`stroke_brush` of it) and its removal both use it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/retouch_cmds.rs | 2 +- crates/engine/src/retouch_cmds/remove.rs | 25 ++++++++++++--- crates/engine/src/retouch_cmds/tests.rs | 21 +++++++++++++ crates/ui-egui/src/lib.rs | 4 ++- crates/ui-egui/src/retouch_ui.rs | 39 ++++++++++++++++++++++-- 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index 005377328f..8634a30364 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -1444,7 +1444,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","strokes":[[[x,y,pressure?],…],…]? (several strokes removed together, as one job and one undo step; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"# + r#","strokes":[[[x,y,pressure?],…]|{"points":[…],"size"?,"hardness"?,"spacing"?},…]? (several strokes removed together, as one job and one undo step, each with its own size, hardness and spacing when given; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"# ), enabled: has_pixel_layer, run: remove::remove, diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/retouch_cmds/remove.rs index d298e8f02c..eb9ecd1028 100644 --- a/crates/engine/src/retouch_cmds/remove.rs +++ b/crates/engine/src/retouch_cmds/remove.rs @@ -74,17 +74,32 @@ fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec, Option reject_huge_stroke(CMD, &stroke)?; return Ok((vec![stroke], id)); }; - let list = list.as_array().ok_or_else(|| bad(CMD, "`strokes` is a list of point lists"))?; + const ENTRY: &str = "each `strokes` entry is a point list or {\"points\", \"size\"?, \"hardness\"?, \"spacing\"?}"; + let list = list.as_array().ok_or_else(|| bad(CMD, ENTRY))?; if list.is_empty() { return Err(bad(CMD, "`strokes` is empty")); } let mut strokes = Vec::with_capacity(list.len()); let mut id = None; - for points in list { + for entry in list { let mut one = p.clone(); - if let Some(o) = one.as_object_mut() { - o.remove("strokes"); - o.insert("points".into(), points.clone()); + let Some(o) = one.as_object_mut() else { return Err(bad(CMD, "params must be an object")) }; + o.remove("strokes"); + match entry { + // A stroke drawn with another brush than the rest (the waiting strokes of Remove after + // each stroke off keep the size, hardness and spacing each was drawn with). + Value::Object(e) => { + let points = e.get("points").ok_or_else(|| bad(CMD, ENTRY))?; + o.insert("points".into(), points.clone()); + for k in ["size", "hardness", "spacing"] { + if let Some(v) = e.get(k) { + o.insert(k.into(), v.clone()); + } + } + } + points => { + o.insert("points".into(), points.clone()); + } } let (stroke, layer) = parse_brush(s, &one, CMD)?; reject_huge_stroke(CMD, &stroke)?; diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs index 7f60b72c16..45f314f490 100644 --- a/crates/engine/src/retouch_cmds/tests.rs +++ b/crates/engine/src/retouch_cmds/tests.rs @@ -2034,6 +2034,27 @@ fn remove_several_strokes_apply_as_one_job_and_one_undo_step() { } } +/// A `strokes` entry may carry its own size, hardness and spacing: the Remove Tool's waiting +/// strokes keep the brush each was drawn with, whatever the brush is when they are applied. +#[test] +fn remove_strokes_each_keep_their_own_brush() { + let entry = |pts: Value, size: f64| json!({"points": pts, "size": size, "hardness": 100, "spacing": 25}); + let removed = |strokes: Value, size: f64| { + let mut s = square_session(8, "rgb"); + let bg = rgba(&s, 10, 10); + s.execute("paint.remove", json!({"strokes": strokes, "size": size})).unwrap(); + [(41, 30), (46, 30), (51, 30)].iter().all(|&(x, y)| near(rgba(&s, x, y), bg, 0.03)) + }; + let (a, b) = (json!([[38, 30], [45, 30]]), json!([[47, 30], [54, 30]])); + assert!(removed(json!([entry(a.clone(), 16.0), entry(b.clone(), 16.0)]), 2.0), "each entry's 16 px, not the 2 px of the call"); + assert!(!removed(json!([entry(a.clone(), 2.0), entry(b.clone(), 2.0)]), 16.0), "each entry's 2 px, not the 16 px of the call"); + assert!(removed(json!([entry(a, 16.0), b]), 16.0), "a plain point list takes the call's brush"); + let mut s = square_session(8, "rgb"); + for strokes in [json!([{"size": 16}]), json!([{"points": "x"}]), json!([{"points": []}]), json!([7])] { + assert!(s.execute("paint.remove", json!({"strokes": strokes, "size": 16})).is_err(), "{strokes}"); + } +} + #[test] fn remove_to_a_new_layer_leaves_the_target_untouched() { let mut s = square_session(8, "rgb"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6ea5992d43..0df819b495 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -720,7 +720,9 @@ pub struct PhotocraftApp { trail: Option, /// Remove tool strokes waiting to be applied together (Remove after each stroke off), the /// document, layer and channel they belong to, and their tint on the canvas (`retouch_ui`). - pub(crate) remove_pending: Vec>, + /// Each as a `paint.remove` `strokes` entry: its points and the size, hardness and spacing it + /// was drawn with, which its tint shows and its removal uses. + pub(crate) remove_pending: Vec, pub(crate) remove_pending_target: Option, pub(crate) remove_trail: Option, /// The open menus' items, reused between frames (`menus::ItemCache`). diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs index 472f1a838b..cc01a2d669 100644 --- a/crates/ui-egui/src/retouch_ui.rs +++ b/crates/ui-egui/src/retouch_ui.rs @@ -208,9 +208,13 @@ pub fn remove_pending_add(app: &mut PhotocraftApp, points: &[[f64; 3]]) { app.remove_trail = None; app.remove_pending_target = Some(target); } - let brush = || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + // The brush it was drawn with goes with it: the tint shows it, the removal uses it, however + // the brush changes before ↩. + let b = &app.session.tools.brush; + let entry = json!({"points": points, "size": b.size, "hardness": b.hardness * 100.0, "spacing": b.spacing * 100.0}); + let brush = || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &entry); app.remove_trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)).feed_stroke_reach(points, brush); - app.remove_pending.push(points.to_vec()); + app.remove_pending.push(entry); app.ui.status = crate::i18n::fmt(tl!("Strokes to remove: {n} (Enter applies, Esc cancels)"), &[("n", &app.remove_pending.len().to_string())]); app.ui.status_error = false; } @@ -1170,6 +1174,35 @@ mod tests { assert!(px.iter().zip(bg).all(|(a, b)| (a - b).abs() < 0.02), "{px:?} vs {bg:?}"); } + /// A waiting Remove stroke keeps the brush it was drawn with (#8923 review): changing the brush + /// before ↩ neither changes its tint nor what its removal takes. + #[test] + fn waiting_remove_strokes_keep_their_own_brush() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + let m = egui::Modifiers::NONE; + let stroke = |app: &mut PhotocraftApp, x: f64| { + tool_event(app, ToolEvent::Down { x, y: 20.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x, y: 40.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x, y: 40.0 }, m); + }; + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap(); + stroke(&mut app, 25.0); + let tint = |app: &PhotocraftApp| app.remove_trail.as_ref().map(|t| (0..100).filter(|&x| t.coverage(x, 30) > 0).count()); + let first = tint(&app); + app.run("tools.setBrush", json!({"brush": {"size": 4, "hardness": 1.0}})).unwrap(); + stroke(&mut app, 75.0); + assert!(tint(&app).unwrap() > first.unwrap(), "the second stroke adds its tint"); + assert!((0..100).filter(|&x| app.remove_trail.as_ref().unwrap().coverage(x, 30) > 0).any(|x| x < 25 - 10), "the first keeps its soft 20 px reach"); + assert!(remove_pending_commit(&mut app)); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (_, p) = app.session.journal.last().cloned().expect("a journaled command"); + let sizes: Vec<_> = p["strokes"].as_array().unwrap().iter().map(|e| (e["size"].as_f64(), e["hardness"].as_f64())).collect(); + assert_eq!(sizes, [(Some(20.0), Some(0.0)), (Some(4.0), Some(100.0))], "each stroke is removed with its own brush"); + } + #[test] fn remove_after_each_stroke_off_collects_strokes_until_enter_or_escape() { let mut app = app(); @@ -1296,7 +1329,7 @@ mod tests { app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); remove_pending_add(&mut app, &[[40.0, 10.0, 1.0], [44.0, 12.0, 1.0]]); assert_eq!(app.remove_pending.len(), 1, "strokes from different layers must not be combined"); - assert_eq!(app.remove_pending[0][0][0], 40.0); + assert_eq!(app.remove_pending[0]["points"][0][0], 40.0); assert!(remove_pending_live(&mut app)); } From 07f91c6d37d0c7d9e299efa604bda6511b7ca76c Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Fri, 23 Oct 2026 23:57:23 +0100 Subject: [PATCH 33/87] fix(codecs): one JPEG frame-size guard for truncated and complete files main gained a guard refusing truncated scans too short for their frame; this branch's own header check refused those files first with a different error. Drop it and widen main's guard instead: a complete file is measured on its length (the scan walk may stop early on odd marker layouts), a truncated one on its scan data as before. A frame needs at least a one-bit DC code per 8x8 block, so 2048 pixels a byte stays far above any real JPEG. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/jpeg.rs | 27 ++++++++++++++------------- crates/codecs/tests/it/limits.rs | 7 ++++++- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index c2a0983382..2ddd683875 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -190,9 +190,10 @@ fn err(e: impl std::fmt::Display) -> CodecError { CodecError::malformed(F, e) } -/// Most pixels one byte of truncated scan data may account for. Even a flat image costs a few -/// bits per 8×8 block, and truncated photographs are far above this. -const MAX_TRUNCATED_PIXELS_PER_BYTE: u64 = 2048; +/// Most pixels one byte of a JPEG may account for. Every 8×8 block of a frame needs at least a +/// one-bit DC code (512 pixels a byte for a flat image under ideal Huffman tables), and real files, +/// truncated or not, are far above this. +const MAX_PIXELS_PER_BYTE: u64 = 2048; pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { let (end, scan_bytes) = data_end(bytes); @@ -202,10 +203,6 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result let meta = scan_metadata(bytes); if let Some((w, h, nc)) = meta.frame { limits.check_bytes(w, h, u64::from(nc.max(1)))?; - // Huffman coding spends at least a bit per 8x8 block per component (about 1024:1 for - // a flat 4:2:0 image), so a file far smaller than that cannot hold the frame. zune-jpeg - // only needs one byte of scan data before it allocates the whole output (#8597). - Limits::check_plausible(u64::from(w) * u64::from(h) * u64::from(nc.max(1)), bytes.len(), 1 << 12)?; } let options = DecoderOptions::default().set_strict_mode(false).set_max_width(65535).set_max_height(65535); let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), options); @@ -220,12 +217,16 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result _ => (ColorSpace::RGB, ChannelLayout::Rgb), }; limits.check(w, h, layout, SampleType::U8)?; - // The backend fills whatever the scan no longer describes, so a short scan under a large - // frame is a gigabyte of synthesized output from a few kilobytes of file. The budget is + // The backend fills whatever the scan no longer describes, and allocates the whole output + // once a scan holds a byte, so a short scan under a large frame is a gigabyte of synthesized + // output from a few kilobytes of file (#8597), truncated or not. A truncated file's budget is // measured on the scan data itself: APP padding can inflate `bytes.len()` arbitrarily - // without describing one more pixel. - if end == DataEnd::Truncated && u64::from(w) * u64::from(h) / MAX_TRUNCATED_PIXELS_PER_BYTE > scan_bytes { - return Err(err("the truncated scan is too short for the frame it declares")); + // without describing one more pixel. A complete one is measured on the file length, since + // the walk may stop early on odd marker layouts (`DataEnd::Complete`). + let budget = if end == DataEnd::Truncated { scan_bytes } else { bytes.len() as u64 }; + if u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > budget { + let what = if end == DataEnd::Truncated { "the truncated scan" } else { "the file" }; + return Err(err(format!("{what} is too short for the frame it declares"))); } dec.set_options(dec.options().jpeg_set_out_colorspace(out_cs)); let mut px = dec.decode().map_err(err)?; @@ -495,7 +496,7 @@ mod tests { assert_eq!(data_end(&padded).0, DataEnd::Truncated); // Well above the frame's pixels / budget, yet far above the scan data: the old // file-length bound admitted this frame. - assert!(padded.len() > (u64::from(20_000u32) * u64::from(20_000u32) / MAX_TRUNCATED_PIXELS_PER_BYTE) as usize, "padding too small"); + assert!(padded.len() > (u64::from(20_000u32) * u64::from(20_000u32) / MAX_PIXELS_PER_BYTE) as usize, "padding too small"); assert!(crate::decode_as(Format::Jpeg, &padded).is_ok()); let sof = padded.windows(2).position(|w| w == [0xFF, 0xC0] || w == [0xFF, 0xC2]).unwrap(); let mut huge = padded.clone(); diff --git a/crates/codecs/tests/it/limits.rs b/crates/codecs/tests/it/limits.rs index 6c956e5cac..951257bb82 100644 --- a/crates/codecs/tests/it/limits.rs +++ b/crates/codecs/tests/it/limits.rs @@ -477,7 +477,12 @@ fn jpeg_header_declaring_gigabytes_needs_a_plausible_file_size() { let sof = find(&b, &[0xFF, 0xC0]); b[sof + 5..sof + 7].copy_from_slice(&16000u16.to_be_bytes()); b[sof + 7..sof + 9].copy_from_slice(&65000u16.to_be_bytes()); - refused_as_implausible(Format::Jpeg, &b); + // The decoder's own scan-size guard refuses it (one refusal path for truncated and complete + // files alike), before the backend allocates the frame. + match decode(&b) { + Err(e) => assert!(e.to_string().contains("too short for the frame"), "{e}"), + Ok(i) => panic!("decoded a {}×{} frame from {} bytes", i.width(), i.height(), b.len()), + } } #[test] From 8f782cab1cf98fecca7af994ea574cc547e07b8c Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Sat, 24 Oct 2026 01:27:34 +0100 Subject: [PATCH 34/87] fix(codecs): bound complete JPEGs by their scan data too A complete file's frame-size budget was its length, which APP padding inflates. Every file is now measured on the scan data the walk crossed; where the walk stops early on an odd layout, what it couldn't read counts as scan data, so such files still decode while padding before that point never counts. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/jpeg.rs | 50 ++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index 2ddd683875..f05ab3b491 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -149,8 +149,9 @@ fn data_end(b: &[u8]) -> (DataEnd, u64) { loop { let Some(&byte) = b.get(i) else { return cut(scan_data, scanned) }; if byte != 0xFF { - // Not where a marker should be: too odd to judge. - return (DataEnd::Complete, scanned); + // Not where a marker should be: too odd to judge. What the walk couldn't read may all + // be scan data, so it counts as such (padding before this point still doesn't). + return (DataEnd::Complete, scanned.saturating_add(u64::try_from(b.len().saturating_sub(i)).unwrap_or(u64::MAX))); } let Some(&code) = b.get(i + 1) else { return cut(scan_data, scanned) }; match code { @@ -219,13 +220,11 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result limits.check(w, h, layout, SampleType::U8)?; // The backend fills whatever the scan no longer describes, and allocates the whole output // once a scan holds a byte, so a short scan under a large frame is a gigabyte of synthesized - // output from a few kilobytes of file (#8597), truncated or not. A truncated file's budget is - // measured on the scan data itself: APP padding can inflate `bytes.len()` arbitrarily - // without describing one more pixel. A complete one is measured on the file length, since - // the walk may stop early on odd marker layouts (`DataEnd::Complete`). - let budget = if end == DataEnd::Truncated { scan_bytes } else { bytes.len() as u64 }; - if u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > budget { - let what = if end == DataEnd::Truncated { "the truncated scan" } else { "the file" }; + // output from a few kilobytes of file (#8597), truncated or not. The budget is the scan data + // itself, not `bytes.len()`, which APP padding can inflate without describing one more pixel; + // where the walk stops early on an odd layout, what it couldn't read counts as scan data. + if u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > scan_bytes { + let what = if end == DataEnd::Truncated { "the truncated scan" } else { "the scan data" }; return Err(err(format!("{what} is too short for the frame it declares"))); } dec.set_options(dec.options().jpeg_set_out_colorspace(out_cs)); @@ -505,6 +504,39 @@ mod tests { assert!(e.to_string().contains("too short"), "{e}"); } + /// A complete file is measured on its scan data too: padding can't admit an oversized frame. + /// The same padded file at its real size decodes, and so does an odd layout whose unread tail + /// counts as scan data. + #[test] + fn app_padding_cannot_admit_an_oversized_complete_frame() { + let img = Image::from_raw(16, 16, ChannelLayout::Rgb, SampleType::U8, vec![128; 16 * 16 * 3]).unwrap(); + let full = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap(); + let fill = [b'p'; 65533]; + let mut padded = full[..2].to_vec(); + for _ in 0..4 { + padded.extend_from_slice(&[0xFF, 0xFE]); + padded.extend_from_slice(&0xFFFFu16.to_be_bytes()); + padded.extend_from_slice(&fill); + } + padded.extend_from_slice(&full[2..]); + let (end, scanned) = data_end(&padded); + assert_eq!(end, DataEnd::Complete); + assert!(scanned < 1024, "the padding isn't scan data: {scanned}"); + assert!(padded.len() as u64 > u64::from(20_000u32) * 20_000 / MAX_PIXELS_PER_BYTE, "padding too small"); + assert!(crate::decode_as(Format::Jpeg, &padded).is_ok()); + let sof = padded.windows(2).position(|w| w == [0xFF, 0xC0] || w == [0xFF, 0xC2]).unwrap(); + let mut huge = padded.clone(); + huge[sof + 5..sof + 9].copy_from_slice(&[0x4E, 0x20, 0x4E, 0x20]); + let e = crate::decode_as(Format::Jpeg, &huge).unwrap_err(); + assert!(e.to_string().contains("too short"), "{e}"); + // A stray byte where a marker should be: the walk stops, and the rest counts. + let mut odd = full.clone(); + odd.insert(2, 0x00); + let (end, scanned) = data_end(&odd); + assert_eq!(end, DataEnd::Complete); + assert_eq!(scanned, (odd.len() - 2) as u64); + } + /// CMYK JPEG output must omit JFIF while retaining Adobe's CMYK marker. #[test] fn cmyk_jpeg_omits_jfif_but_keeps_adobe_cmyk_marker() { From d03c23e12f1d3f6cce39975110c3cff694e193d7 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Sat, 24 Oct 2026 01:34:39 +0100 Subject: [PATCH 35/87] fix(codecs): skip stray bytes in the JPEG walk instead of stopping A stray byte before APP padding stopped the walk, and the unread tail, padding included, counted as scan data. The walk now resynchronises at the next marker, as a lenient decoder does, so padding after stray bytes is still recognised; the skipped bytes count as scan data. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/jpeg.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index f05ab3b491..06a482c720 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -149,9 +149,15 @@ fn data_end(b: &[u8]) -> (DataEnd, u64) { loop { let Some(&byte) = b.get(i) else { return cut(scan_data, scanned) }; if byte != 0xFF { - // Not where a marker should be: too odd to judge. What the walk couldn't read may all - // be scan data, so it counts as such (padding before this point still doesn't). - return (DataEnd::Complete, scanned.saturating_add(u64::try_from(b.len().saturating_sub(i)).unwrap_or(u64::MAX))); + // Not where a marker should be: skip to the next one, as a lenient decoder does, so + // segments after the stray bytes (padding among them) are still recognised. The + // skipped bytes count as scan data; with no marker left, the file is too odd to judge. + let Some(p) = b.get(i..).and_then(|r| r.iter().position(|&v| v == 0xFF)) else { + return (DataEnd::Complete, scanned.saturating_add(u64::try_from(b.len().saturating_sub(i)).unwrap_or(u64::MAX))); + }; + scanned = scanned.saturating_add(p as u64); + i += p; + continue; } let Some(&code) = b.get(i + 1) else { return cut(scan_data, scanned) }; match code { @@ -529,12 +535,20 @@ mod tests { huge[sof + 5..sof + 9].copy_from_slice(&[0x4E, 0x20, 0x4E, 0x20]); let e = crate::decode_as(Format::Jpeg, &huge).unwrap_err(); assert!(e.to_string().contains("too short"), "{e}"); - // A stray byte where a marker should be: the walk stops, and the rest counts. - let mut odd = full.clone(); + // A stray byte where a marker should be, before the padding: the walk skips it and still + // recognises the padding, so an oversized frame is refused there too. + let mut odd = huge.clone(); odd.insert(2, 0x00); let (end, scanned) = data_end(&odd); assert_eq!(end, DataEnd::Complete); - assert_eq!(scanned, (odd.len() - 2) as u64); + assert!(scanned < 1024, "the padding after a stray byte isn't scan data: {scanned}"); + let e = crate::decode_as(Format::Jpeg, &odd).unwrap_err(); + assert!(e.to_string().contains("too short"), "{e}"); + // Bytes with no marker after them are too odd to judge: they all count. + let tail = [0x00u8; 4096]; + let mut trailing = vec![0xFF, 0xD8]; + trailing.extend_from_slice(&tail); + assert_eq!(data_end(&trailing), (DataEnd::Complete, tail.len() as u64)); } /// CMYK JPEG output must omit JFIF while retaining Adobe's CMYK marker. From fc29726a5d50c913754febbad074359e783a7c59 Mon Sep 17 00:00:00 2001 From: denstu473 <63150090+denstu473@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:36:41 +0200 Subject: [PATCH 36/87] fix(io): preserve Halftone Pattern smart filters in PSD/PSB --- crates/io/src/smart_map.rs | 45 ++++++- crates/io/src/smart_map/halftone_tests.rs | 154 ++++++++++++++++++++++ docs/file-format-parity.md | 5 +- docs/gaps.md | 4 +- 4 files changed, 201 insertions(+), 7 deletions(-) create mode 100644 crates/io/src/smart_map/halftone_tests.rs diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index fcc9eec3f9..ba6d660cc3 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -37,6 +37,10 @@ use serde_json::{Map, Value as J, json}; use crate::blocks::{enum_of, get_desc, num}; +#[cfg(test)] +#[path = "smart_map/halftone_tests.rs"] +mod halftone_tests; + #[path = "camera_raw_map.rs"] mod camera_raw; #[path = "displace_map.rs"] @@ -721,7 +725,13 @@ struct GalleryCode { settings: &'static [(&'static str, &'static str)], } -const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }]; +const GALLERY_EFFECTS: [GalleryCode; 2] = [ + GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }, + GalleryCode { key: "halftonePattern", code: "HlfS", settings: &[("Sz ", "size"), ("Cntr", "contrast")] }, +]; + +// Photoshop 27.11 writes Halftone Pattern's shape as an enum, not a numeric choice index. +const HALFTONE_PATTERNS: [(&[u8; 4], &str); 3] = [(b"Dt ", "dot"), (b"Crc ", "circle"), (b"Ln ", "line")]; /// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. fn rgbc_colour(d: &Descriptor) -> Option { @@ -781,8 +791,21 @@ fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { let code = enum_of(e, "GEfk")?; let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?; let mut params = Map::new(); + if g.key == "halftonePattern" { + // Do not turn an unfamiliar shape or malformed setting into the engine's defaults: + // keeping the whole item opaque preserves it through a subsequent save. + if !only_keys(e, &["GEfk", "Sz ", "Cntr", "Ptrn", "GELv"]) + || !matches!(e.get("GEfk"), Some(Value::Enumerated { type_id, .. }) if type_id.is("GEft")) + || e.get("GELv").is_some_and(|v| !matches!(v, Value::Boolean(_))) + { + return None; + } + int_in(e, "Sz ", 1, 12)?; + int_in(e, "Cntr", 0, 50)?; + params.insert("patternType".into(), json!(enum_name(e, "Ptrn", "HlfT", &HALFTONE_PATTERNS)?)); + } for (k, v) in &e.items { - if k.is("GEfk") || k.is("GELv") { + if k.is("GEfk") || k.is("GELv") || g.key == "halftonePattern" && k.is("Ptrn") { continue; } let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; @@ -835,13 +858,25 @@ fn gallery_item(f: &SmartFilter) -> Result { let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?; let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e); if let Some(k) = params.as_object().and_then(|o| { - o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k)) + o.keys().find(|k| { + !is_meta(k) + && !["filter", "params", "visible"].contains(&k.as_str()) + && !g.settings.iter().any(|(_, ours)| ours == k) + && !(key == "halftonePattern" && *k == "patternType") + }) }) { return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent")); } let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); - let settings: Vec<(&str, Value)> = - g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect(); + let settings: Vec<(&str, Value)> = if key == "halftonePattern" { + vec![ + ("Sz ", whole(pf_range(params, "size", 1.0, 1.0, 12.0)?, (1, 12), "size")?), + ("Cntr", whole(pf_range(params, "contrast", 5.0, 0.0, 50.0)?, (0, 50), "contrast")?), + ("Ptrn", enum_param(params, "patternType", "dot", "HlfT", &HALFTONE_PATTERNS)?), + ] + } else { + g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect() + }; out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true))); } let gallery = || { diff --git a/crates/io/src/smart_map/halftone_tests.rs b/crates/io/src/smart_map/halftone_tests.rs new file mode 100644 index 0000000000..dd949abf98 --- /dev/null +++ b/crates/io/src/smart_map/halftone_tests.rs @@ -0,0 +1,154 @@ +//! Halftone Pattern descriptors measured in Photoshop 27.11.0 (#8940). +use super::*; + +fn filter(pattern: &str, size: i32, contrast: i32) -> SmartFilter { + SmartFilter { + command: GALLERY_COMMAND.into(), + params: json!({ + "effects": [{"filter": "halftonePattern", "params": {"size": size, "contrast": contrast, "patternType": pattern}, "visible": true}], + "foreground": [0.2, 0.4, 0.6, 1.0], "background": [0.8, 0.6, 0.4, 1.0], + }), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + } +} + +fn native_effect(pattern: &str, size: i32, contrast: i32) -> Descriptor { + let mut d = Descriptor::new("GEfc") + .with("GEfk", enumv("GEft", "HlfS")) + .with("Sz ", Value::Integer(size)) + .with("Cntr", Value::Integer(contrast)) + .with("Ptrn", enumv("HlfT", pattern)); + d.name = UnicodeString::new_nul("Filter Gallery"); + d +} + +fn native_item(effect: Descriptor) -> Descriptor { + let f = filter("dot", 2, 5); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) + .with("blendOptions", blend_options(&f)) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", colour_rgbc(f.params.get("foreground"), 0.0).unwrap()) + .with("BckC", colour_rgbc(f.params.get("background"), 1.0).unwrap()) + .with("Fltr", Value::Descriptor(effect)) + .with("filterID", Value::Integer(code(b"GEfc"))) +} + +#[test] +fn halftone_pattern_reads_and_writes_photoshop_inline_descriptors() { + for (pattern, native) in [("dot", "Dt "), ("circle", "Crc "), ("line", "Ln ")] { + for (size, contrast) in [(1, 0), (2, 5), (7, 31), (12, 50)] { + let expected = filter(pattern, size, contrast); + let native = native_item(native_effect(native, size, contrast)); + assert_eq!(filter_from_item(&native), expected); + let written = item_for_filter(&expected).unwrap(); + assert_eq!(get_desc(&written, "Fltr"), get_desc(&native, "Fltr")); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&written.to_bytes()).unwrap()), expected); + } + } +} + +#[test] +fn halftone_pattern_defaults_and_mixed_hidden_stack_round_trip() { + let defaults = SmartFilter { params: json!({"effects": [{"filter": "halftonePattern"}]}), ..filter("dot", 1, 5) }; + assert_eq!(filter_from_item(&item_for_filter(&defaults).unwrap()).params["effects"][0]["params"], json!({"size": 1, "contrast": 5, "patternType": "dot"})); + let mut f = filter("circle", 8, 22); + f.params["effects"][0]["visible"] = json!(false); + f.params["effects"].as_array_mut().unwrap().push(json!({"filter": "chrome", "params": {"detail": 4, "smoothness": 7}, "visible": true})); + f.opacity = 0.5; + f.blend = BlendMode::Multiply; + f.visible = false; + let item = item_for_filter(&f).unwrap(); + assert!(get_desc(&item, "Fltr").unwrap().get("GEfs").is_some()); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()), f); +} + +#[test] +fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { + let valid = native_effect("Dt ", 2, 5); + let mut invalid = vec![ + valid.clone().with("futureSetting", Value::Integer(1)), + valid.clone().with("Sz ", Value::Integer(3)), // repeated key + ]; + for (key, value) in [ + ("GEfk", enumv("wrong", "HlfS")), + ("Ptrn", enumv("HlfT", "????")), + ("Ptrn", enumv("wrong", "Dt ")), + ("Ptrn", Value::Integer(0)), + ("Sz ", Value::Integer(0)), + ("Sz ", Value::Integer(13)), + ("Sz ", Value::Double(2.0)), + ("Cntr", Value::Integer(-1)), + ("Cntr", Value::Integer(51)), + ("GELv", Value::Integer(1)), + ] { + let mut effect = valid.clone(); + effect.items.retain(|(id, _)| !id.is(key)); + effect.items.push((Id::new(key), value)); + invalid.push(effect); + } + for missing in ["Sz ", "Cntr", "Ptrn"] { + let mut effect = valid.clone(); + effect.items.retain(|(id, _)| !id.is(missing)); + invalid.push(effect); + } + for effect in invalid { + let item = native_item(effect); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn halftone_pattern_invalid_export_settings_are_reported() { + for (key, value) in [ + ("patternType", json!("triangle")), + ("patternType", json!(2)), + ("size", json!(0)), + ("size", json!(13)), + ("size", json!("2")), + ("size", json!(2.5)), + ("contrast", json!(-1)), + ("contrast", json!(51)), + ("contrast", json!(1e100)), + ("contrast", json!(5.5)), + ("futureSetting", json!(1)), + ] { + let mut f = filter("dot", 2, 5); + f.params["effects"][0]["params"][key] = value; + assert!(item_for_filter(&f).is_err(), "{key}: {}", f.params); + } +} + +#[test] +fn halftone_pattern_survives_complete_psd_and_psb_export() { + use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource}; + use photocraft_geom::Size; + use std::sync::Arc; + + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for pattern in ["dot", "circle", "line"] { + let mut source = Document::new("synthetic contents", Size::new(2, 2), ColorMode::Rgb, sample); + let mut pixels = Surface::new(source.pixel_format()); + pixels.fill_rect(source.bounds(), &[0.5, 0.5, 0.5, 1.0]); + source.layers.push(Layer::new("pixels", LayerContent::Raster(pixels.clone()))); + let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).unwrap(); + let mut smart = + SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, Some(pixels)); + smart.smart_filters.push(filter(pattern, 2, 5)); + let mut doc = Document::new("halftone", Size::new(2, 2), ColorMode::Rgb, sample); + doc.layers.push(Layer::new("halftone", LayerContent::Smart(smart))); + for ext in ["psd", "psb"] { + let out = crate::export(&doc, ext, &crate::ExportOptions::default()).unwrap(); + assert!(!out.warnings.iter().any(|w| w.contains("smart filter")), "{ext}: {:?}", out.warnings); + let back = crate::import(ext, &out.bytes).unwrap().document; + let LayerContent::Smart(smart) = &back.layers[0].content else { panic!("smart object lost") }; + assert_eq!(smart.smart_filters, vec![filter(pattern, 2, 5)], "{ext} {sample:?} {pattern}"); + } + } + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index fbfcfa6f9e..a3855e3fb9 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,8 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-22 · **Change:** minor (legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-23 · **Change:** minor (PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 + +**PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export. PSD/PSB metadata round trips pass at 8/16/32 bits; six Photoshop 27.11 reopen checks retain the effect and its settings. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write @@ -142,6 +144,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways; PSD/PSB round trips at 8/16/32 bits, six Photoshop 27.11 reopen checks, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | 32-bit Hue/Saturation as Photoshop does it: the raised saturation isn't clipped (saturated colours leave 0..1), the chroma is scaled around the lightness by Photoshop's saturation factor (measured at every whole percent), so colours at or above lightness 1 keep their hue, and Colorize builds its colour with the saturation times 1 − \|Lightness\| (8 and 16 bits unchanged): photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-19 | minor | JPEG Options on File › Save, Save As and Save a Copy (FILE-215-19 partial: no Matte, progressive Scans or size preview) | | 2026-10-18 | minor | Scripted TIFF saves take `tiffCompression` (none, LZW, ZIP), and the CLI `--tiff-compression` (#5301) | diff --git a/docs/gaps.md b/docs/gaps.md index d878a675f5..679d42ad9e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -40,6 +40,7 @@ what an agent can't finish alone. ## Feature gaps ### G1. PSD fidelity and Photoshop acceptance +- **Done 2026-10-23 (#8940):** Filter Gallery Halftone Pattern preserves size, contrast and dot/circle/line through PSD/PSB import/export. Six Photoshop 27.11 reopen checks retain editable settings. Other unsupported gallery effects remain opaque on import or produce an export warning. - **Missing:** PSDs we write are not always accepted by Photoshop, and Photoshop-authored files don't always render as Photoshop renders them. - **Partial (2026-10-15, #5972 A1):** `GdFl` noise fills render when all three RGB ranges are @@ -358,6 +359,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways; PSD/PSB round trips at 8/16/32 bits, six Photoshop 27.11 reopen checks, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | G17: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; estimate unchanged | | 2026-10-22 | minor | G1: 32-bit Hue/Saturation unclipped with Photoshop's saturation factor, bright colours keep their hue, Colorize's saturation scaled by 1 − \|Lightness\|; photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-21 | minor | G9: adjustment clipping remains visible in compact Properties (#5231); no readiness percentage or estimate changed | From f98983fff4ef0b6e91d7a9914f9c7f8014031c29 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Sat, 24 Oct 2026 01:39:56 +0100 Subject: [PATCH 37/87] fix(codecs): stray bytes in a JPEG never count as scan data Junk where a marker should be (which the decoder skips) bought frame budget as padding did. The walk still resynchronises at the next marker but no longer counts the skipped bytes, and junk with no marker after it ends the image data there. Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/jpeg.rs | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/codecs/src/codecs/jpeg.rs b/crates/codecs/src/codecs/jpeg.rs index 06a482c720..2033fd6b20 100644 --- a/crates/codecs/src/codecs/jpeg.rs +++ b/crates/codecs/src/codecs/jpeg.rs @@ -150,12 +150,10 @@ fn data_end(b: &[u8]) -> (DataEnd, u64) { let Some(&byte) = b.get(i) else { return cut(scan_data, scanned) }; if byte != 0xFF { // Not where a marker should be: skip to the next one, as a lenient decoder does, so - // segments after the stray bytes (padding among them) are still recognised. The - // skipped bytes count as scan data; with no marker left, the file is too odd to judge. - let Some(p) = b.get(i..).and_then(|r| r.iter().position(|&v| v == 0xFF)) else { - return (DataEnd::Complete, scanned.saturating_add(u64::try_from(b.len().saturating_sub(i)).unwrap_or(u64::MAX))); - }; - scanned = scanned.saturating_add(p as u64); + // segments after the stray bytes (padding among them) are still recognised. Stray + // bytes are not scan data, so they never count (junk would buy budget as padding + // did); with no marker left, the image data ends here. + let Some(p) = b.get(i..).and_then(|r| r.iter().position(|&v| v == 0xFF)) else { return cut(scan_data, scanned) }; i += p; continue; } @@ -544,11 +542,21 @@ mod tests { assert!(scanned < 1024, "the padding after a stray byte isn't scan data: {scanned}"); let e = crate::decode_as(Format::Jpeg, &odd).unwrap_err(); assert!(e.to_string().contains("too short"), "{e}"); - // Bytes with no marker after them are too odd to judge: they all count. - let tail = [0x00u8; 4096]; - let mut trailing = vec![0xFF, 0xD8]; - trailing.extend_from_slice(&tail); - assert_eq!(data_end(&trailing), (DataEnd::Complete, tail.len() as u64)); + // Stray bytes never count: 256 KiB of junk where a marker should be (the decoder skips + // it), then the oversized frame's segments, is refused. (Bytes after a scan starts are + // entropy-coded data, any value, and count as such.) + let mut junk = huge[..2].to_vec(); + junk.extend(std::iter::repeat_n(0x00u8, 4 * 65536)); + junk.extend_from_slice(&huge[2..]); + let (end, scanned) = data_end(&junk); + assert_eq!(end, DataEnd::Complete); + assert!(scanned < 1024, "junk isn't scan data: {scanned}"); + let e = crate::decode_as(Format::Jpeg, &junk).unwrap_err(); + assert!(e.to_string().contains("too short"), "{e}"); + // Junk with no marker after it: no image data at all. + let mut tail = vec![0xFF, 0xD8]; + tail.extend(std::iter::repeat_n(0x00u8, 4096)); + assert_eq!(data_end(&tail), (DataEnd::Empty, 0)); } /// CMYK JPEG output must omit JFIF while retaining Adobe's CMYK marker. From 0efeadc1ee0408ec8f88f463e975d65291beff14 Mon Sep 17 00:00:00 2001 From: VishnuByrraju Date: Sat, 24 Oct 2026 07:23:59 +0530 Subject: [PATCH 38/87] perf(gpu): NVIDIA's own memory on Linux, so many-layer documents stay off the CPU budget penalty video_memory() on Linux only ever read amdgpu's sysfs mem_info_vram_total file. NVIDIA's proprietary driver never writes it, so every NVIDIA Linux user still had the document's pixels charged against the GPU memory budget that #5973 stopped charging discrete cards for elsewhere - P60/P61 (opacity/hide among 150 full-canvas layers) measured 1.5 s against a 30 ms budget here, same as before that fix. detect_video_memory now falls back to nvidia-smi's own CSV report when the vendor id is NVIDIA's and the sysfs file is absent: parsed by a pure, unit-tested function against this machine's real nvidia-smi output; an absent or failing nvidia-smi degrades to the old (correct, if pessimistic) behaviour, never a panic or a hang. --- crates/ui-egui/src/gpu_canvas.rs | 68 +++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index d99db8c25e..27dbe4f629 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -1546,7 +1546,44 @@ fn detect_video_memory(vendor: u32, device: u32) -> Option { #[cfg(target_os = "linux")] fn detect_video_memory(vendor: u32, device: u32) -> Option { - drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device) + drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device).or_else(|| nvidia_video_memory(vendor, device)) +} + +/// PCI vendor id of NVIDIA, whose proprietary Linux driver writes none of amdgpu's +/// `mem_info_vram_total` sysfs files (a card of its own still reads as [`None`] above): without +/// this, a discrete NVIDIA card was charged for the document's pixels like an integrated one, +/// `memory_budget` shrank to Memory Usage minus them, and a many-layer document whose pages then +/// missed that budget redrew whole-document edits on the CPU every time (P60/P61 on an NVIDIA +/// Linux box: 1.5 s where the fix's own benchmark measures tens of milliseconds elsewhere). +#[cfg(any(target_os = "linux", test))] +const NVIDIA_VENDOR: u32 = 0x10de; + +/// NVIDIA's own memory size on Linux, from `nvidia-smi` (installed with the driver that put this +/// adapter there in the first place): absent, slow to answer or odd output all read as `None`, +/// never a hang or a panic. +#[cfg(target_os = "linux")] +fn nvidia_video_memory(vendor: u32, device: u32) -> Option { + if vendor != NVIDIA_VENDOR { + return None; + } + let out = std::process::Command::new("nvidia-smi").args(["--query-gpu=pci.device_id,memory.total", "--format=csv,noheader,nounits"]).output().ok()?; + out.status.success().then(|| parse_nvidia_smi(&String::from_utf8_lossy(&out.stdout), vendor, device)).flatten() +} + +/// `nvidia-smi --query-gpu=pci.device_id,memory.total --format=csv,noheader,nounits`'s own +/// format: one `0xDDDDVVVV, size-in-MiB` line per card (device id the high half, vendor id the +/// low, as `lspci -n` and wgpu's own ids read them). The matching line's size, in bytes; `None` +/// when no line names this `vendor`/`device`, or the output isn't shaped like that at all. +#[cfg(any(target_os = "linux", test))] +fn parse_nvidia_smi(output: &str, vendor: u32, device: u32) -> Option { + output.lines().find_map(|line| { + let (id, mb) = line.split_once(',')?; + let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?; + if id & 0xffff != vendor || id >> 16 != device { + return None; + } + mb.trim().parse::().ok()?.checked_mul(1 << 20) + }) } /// amdgpu's VRAM size (`/device/mem_info_vram_total`, bytes) of the card under `drm` (the @@ -2843,6 +2880,35 @@ mod tests { std::fs::remove_dir_all(&drm).unwrap(); } + /// #P60/P61: amdgpu's sysfs files have no NVIDIA equivalent, so a discrete NVIDIA card's own + /// memory comes from `nvidia-smi`'s CSV instead (real output: `0x2C0510DE, 16303`, device id + /// the high half of the hex, vendor the low). A second card, an upper-case `0X` prefix, extra + /// spaces, a non-matching id, a missing comma, a non-numeric size, empty output and a size + /// that would overflow all give nothing rather than the wrong (or a panicking) answer. + #[test] + fn parses_nvidia_smis_own_report_of_the_cards_memory() { + let two = "0x2C0510DE, 16303\n0x061C10DE, 24576\n"; + assert_eq!(parse_nvidia_smi(two, 0x10de, 0x2c05), Some(16303 << 20)); + assert_eq!(parse_nvidia_smi(two, 0x10de, 0x061c), Some(24576 << 20)); + assert_eq!(parse_nvidia_smi("0X2C0510DE, 16303 \n", 0x10de, 0x2c05), Some(16303 << 20), "upper-case prefix, loose spacing"); + assert_eq!(parse_nvidia_smi(two, 0x10de, 0xdead), None, "no such device id"); + assert_eq!(parse_nvidia_smi(two, 0x1002, 0x2c05), None, "no such vendor id"); + assert_eq!(parse_nvidia_smi("not csv at all", 0x10de, 0x2c05), None); + assert_eq!(parse_nvidia_smi("0x2C0510DE 16303\n", 0x10de, 0x2c05), None, "no comma"); + assert_eq!(parse_nvidia_smi("0x2C0510DE, lots\n", 0x10de, 0x2c05), None, "not a number"); + assert_eq!(parse_nvidia_smi("", 0x10de, 0x2c05), None, "empty output"); + assert_eq!(parse_nvidia_smi(&format!("0x2C0510DE, {}\n", u64::MAX), 0x10de, 0x2c05), None, "would overflow"); + } + + /// Only a discrete NVIDIA adapter asks `nvidia-smi`: nothing else spawns a process whose + /// answer it would then ignore anyway (`nvidia_video_memory` gates on the vendor id first). + #[cfg(target_os = "linux")] + #[test] + fn nvidia_video_memory_only_asks_for_an_nvidia_vendor_id() { + assert_eq!(nvidia_video_memory(0x1002, 0x73bf), None, "an AMD id never runs nvidia-smi"); + assert_eq!(nvidia_video_memory(0x8086, 0x9a49), None, "an Intel id never runs nvidia-smi"); + } + /// Windows used to report no RAM at all, so the budget assumed 16 GB on every machine. #[cfg(windows)] #[test] From d0b08abc65909ffbdcfe74c58f0e2749c2227c3e Mon Sep 17 00:00:00 2001 From: VishnuByrraju Date: Sat, 24 Oct 2026 07:37:06 +0530 Subject: [PATCH 39/87] fix(gpu): use NVIDIA_VENDOR in the cross-platform parser test, not a bare literal cargo clippy --all-targets on Windows (and the same would hit macOS) found the constant dead: the functions that use it outside tests are Linux-only, and the test exercising parse_nvidia_smi was written against the literal 0x10de instead of the constant, so nothing referenced it under cfg(test) on a non-Linux target. --- crates/ui-egui/src/gpu_canvas.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 27dbe4f629..4524820b6e 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -2888,16 +2888,16 @@ mod tests { #[test] fn parses_nvidia_smis_own_report_of_the_cards_memory() { let two = "0x2C0510DE, 16303\n0x061C10DE, 24576\n"; - assert_eq!(parse_nvidia_smi(two, 0x10de, 0x2c05), Some(16303 << 20)); - assert_eq!(parse_nvidia_smi(two, 0x10de, 0x061c), Some(24576 << 20)); - assert_eq!(parse_nvidia_smi("0X2C0510DE, 16303 \n", 0x10de, 0x2c05), Some(16303 << 20), "upper-case prefix, loose spacing"); - assert_eq!(parse_nvidia_smi(two, 0x10de, 0xdead), None, "no such device id"); + assert_eq!(parse_nvidia_smi(two, NVIDIA_VENDOR, 0x2c05), Some(16303 << 20)); + assert_eq!(parse_nvidia_smi(two, NVIDIA_VENDOR, 0x061c), Some(24576 << 20)); + assert_eq!(parse_nvidia_smi("0X2C0510DE, 16303 \n", NVIDIA_VENDOR, 0x2c05), Some(16303 << 20), "upper-case prefix, loose spacing"); + assert_eq!(parse_nvidia_smi(two, NVIDIA_VENDOR, 0xdead), None, "no such device id"); assert_eq!(parse_nvidia_smi(two, 0x1002, 0x2c05), None, "no such vendor id"); - assert_eq!(parse_nvidia_smi("not csv at all", 0x10de, 0x2c05), None); - assert_eq!(parse_nvidia_smi("0x2C0510DE 16303\n", 0x10de, 0x2c05), None, "no comma"); - assert_eq!(parse_nvidia_smi("0x2C0510DE, lots\n", 0x10de, 0x2c05), None, "not a number"); - assert_eq!(parse_nvidia_smi("", 0x10de, 0x2c05), None, "empty output"); - assert_eq!(parse_nvidia_smi(&format!("0x2C0510DE, {}\n", u64::MAX), 0x10de, 0x2c05), None, "would overflow"); + assert_eq!(parse_nvidia_smi("not csv at all", NVIDIA_VENDOR, 0x2c05), None); + assert_eq!(parse_nvidia_smi("0x2C0510DE 16303\n", NVIDIA_VENDOR, 0x2c05), None, "no comma"); + assert_eq!(parse_nvidia_smi("0x2C0510DE, lots\n", NVIDIA_VENDOR, 0x2c05), None, "not a number"); + assert_eq!(parse_nvidia_smi("", NVIDIA_VENDOR, 0x2c05), None, "empty output"); + assert_eq!(parse_nvidia_smi(&format!("0x2C0510DE, {}\n", u64::MAX), NVIDIA_VENDOR, 0x2c05), None, "would overflow"); } /// Only a discrete NVIDIA adapter asks `nvidia-smi`: nothing else spawns a process whose From 2f15dd673b53b76ae4b8dfb7b736824cf7f47661 Mon Sep 17 00:00:00 2001 From: denstu473 <63150090+denstu473@users.noreply.github.com> Date: Sat, 24 Oct 2026 08:37:08 +0200 Subject: [PATCH 40/87] fix(io): preserve unfamiliar Halftone descriptor classes Reject nested Halftone descriptors with unexpected class IDs before mapping them into editable filters, so saving preserves the original Gallery stack. Add a regression covering standalone and mixed stacks, and document the Halftone test helpers and cases flagged by CodeRabbit. --- crates/io/src/smart_map.rs | 3 ++- crates/io/src/smart_map/halftone_tests.rs | 24 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index ba6d660cc3..37a4b140d7 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -794,7 +794,8 @@ fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { if g.key == "halftonePattern" { // Do not turn an unfamiliar shape or malformed setting into the engine's defaults: // keeping the whole item opaque preserves it through a subsequent save. - if !only_keys(e, &["GEfk", "Sz ", "Cntr", "Ptrn", "GELv"]) + if !e.class_id.is(GALLERY_CLASS) + || !only_keys(e, &["GEfk", "Sz ", "Cntr", "Ptrn", "GELv"]) || !matches!(e.get("GEfk"), Some(Value::Enumerated { type_id, .. }) if type_id.is("GEft")) || e.get("GELv").is_some_and(|v| !matches!(v, Value::Boolean(_))) { diff --git a/crates/io/src/smart_map/halftone_tests.rs b/crates/io/src/smart_map/halftone_tests.rs index dd949abf98..7f53043aa5 100644 --- a/crates/io/src/smart_map/halftone_tests.rs +++ b/crates/io/src/smart_map/halftone_tests.rs @@ -1,6 +1,7 @@ //! Halftone Pattern descriptors measured in Photoshop 27.11.0 (#8940). use super::*; +/// Builds an editable Halftone Pattern filter with explicit foreground/background colours. fn filter(pattern: &str, size: i32, contrast: i32) -> SmartFilter { SmartFilter { command: GALLERY_COMMAND.into(), @@ -14,6 +15,7 @@ fn filter(pattern: &str, size: i32, contrast: i32) -> SmartFilter { } } +/// Builds the inline Halftone descriptor measured in Photoshop. fn native_effect(pattern: &str, size: i32, contrast: i32) -> Descriptor { let mut d = Descriptor::new("GEfc") .with("GEfk", enumv("GEft", "HlfS")) @@ -24,6 +26,7 @@ fn native_effect(pattern: &str, size: i32, contrast: i32) -> Descriptor { d } +/// Wraps a Gallery descriptor in a Photoshop smart-filter item. fn native_item(effect: Descriptor) -> Descriptor { let f = filter("dot", 2, 5); Descriptor::new("filterFX") @@ -37,6 +40,7 @@ fn native_item(effect: Descriptor) -> Descriptor { .with("filterID", Value::Integer(code(b"GEfc"))) } +/// Checks the measured pattern enums and editable settings in both mapping directions. #[test] fn halftone_pattern_reads_and_writes_photoshop_inline_descriptors() { for (pattern, native) in [("dot", "Dt "), ("circle", "Crc "), ("line", "Ln ")] { @@ -51,6 +55,7 @@ fn halftone_pattern_reads_and_writes_photoshop_inline_descriptors() { } } +/// Keeps defaults, hidden effects, stack order, and blending intact on round trip. #[test] fn halftone_pattern_defaults_and_mixed_hidden_stack_round_trip() { let defaults = SmartFilter { params: json!({"effects": [{"filter": "halftonePattern"}]}), ..filter("dot", 1, 5) }; @@ -66,6 +71,7 @@ fn halftone_pattern_defaults_and_mixed_hidden_stack_round_trip() { assert_eq!(filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()), f); } +/// Preserves unfamiliar and malformed settings instead of substituting editable defaults. #[test] fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { let valid = native_effect("Dt ", 2, 5); @@ -103,6 +109,23 @@ fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { } } +/// Keeps a whole Gallery stack opaque when a Halftone entry has an unfamiliar class ID. +#[test] +fn halftone_pattern_unknown_nested_class_stays_verbatim() { + let valid = native_effect("Dt ", 2, 5); + let mut unknown = valid.clone(); + unknown.class_id = Id::new("Xxxx"); + for effects in [vec![unknown.clone()], vec![valid.clone(), unknown.clone()], vec![unknown, valid]] { + let gallery = Descriptor::new(GALLERY_CLASS).with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect())); + let item = native_item(gallery); + let parsed = Descriptor::from_bytes(&item.to_bytes()).unwrap(); + let filter = filter_from_item(&parsed); + assert_eq!(filter.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&filter).unwrap().to_bytes(), item.to_bytes()); + } +} + +/// Rejects unsupported export values instead of silently changing their meaning. #[test] fn halftone_pattern_invalid_export_settings_are_reported() { for (key, value) in [ @@ -124,6 +147,7 @@ fn halftone_pattern_invalid_export_settings_are_reported() { } } +/// Checks complete PSD/PSB round trips for every pattern at 8-, 16-, and 32-bit depth. #[test] fn halftone_pattern_survives_complete_psd_and_psb_export() { use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource}; From 55df342307838f8e70f6018141f74c69c1a6a50b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 01:41:54 -0700 Subject: [PATCH 41/87] Batch: folder sources take every format PhotoCraft opens The folder listing behind Batch and the other folder inputs used a hand-kept extension list that lacked formats PhotoCraft opens: Cineon, DICOM, Amiga IFF, PCX, XPM, DDS, PBM, PAM, PFM, Photoshop templates and the CR3, ORF, RW2, RAF, SRF and SR2 raws. Those files were left out of a batch without a message. The listing now takes every extension of a format photocraft-codecs reads in the build and every camera raw extension, and keeps its own list only for the document and vector formats. With Format "Same", inputs that PhotoCraft opens but does not write (DICOM, Amiga IFF, GIMP's .xcf and .xcf.gz, .psdt, and any codec format without a writer) are saved as PSD, as camera raws already were. Without this, each such file would fail to save. --- crates/engine/src/file_cmds.rs | 42 ++++++++++++++++++-------- crates/engine/src/file_cmds/tests.rs | 44 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 6e81656bdb..a78a9a78f3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -116,21 +116,22 @@ pub fn list_images(dir: &str) -> Result> { Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) } -/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, or GIMP's -/// gzipped `.xcf.gz`, whose last extension alone says nothing. +/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, an extension +/// of a format `photocraft-codecs` reads in this build, a camera raw extension, or GIMP's gzipped +/// `.xcf.gz`, whose last extension alone says nothing. #[cfg(not(target_arch = "wasm32"))] fn openable_name(path: &str) -> bool { let lower = file_name(path).to_ascii_lowercase(); - lower.ends_with(".xcf.gz") || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext)) + lower.ends_with(".xcf.gz") + || lower.rsplit_once('.').is_some_and(|(_, ext)| { + OPENABLE.contains(&ext) || photocraft_io::raw::EXTENSIONS.contains(&ext) || photocraft_codecs::from_extension(ext).is_some_and(|f| f.caps().read) + }) } -/// Extensions the batch commands pick up from a folder. +/// Extensions of the document and vector formats the batch commands pick up from a folder: +/// those `photocraft_io::import` reads outside `photocraft-codecs` and the camera raw reader. #[cfg(not(target_arch = "wasm32"))] -const OPENABLE: &[&str] = &[ - "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", - "ico", "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", - "afphoto", "afpub", -]; +const OPENABLE: &[&str] = &["pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "af", "afdesign", "afphoto", "afpub"]; /// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone /// Background layer). The UI asks before such a save when the "ask before saving layered TIFF" @@ -1348,12 +1349,16 @@ pub(crate) fn process_tree( /// The extension a batch output takes with Format "Same": the input's own, except for formats /// PhotoCraft opens but can't write, camera raws above all (#5799: a folder of ARWs failed on -/// every file). Those are saved as PSD, the format Photoshop's Save As offers for a raw. An input -/// whose file name has no extension (a dot in a folder name doesn't count) is saved as PNG. +/// every file), GIMP files (`gz` is the last extension of `.xcf.gz`), Photoshop templates and the +/// codec formats without a writer in this build. Those are saved as PSD, the format Photoshop's +/// Save As offers for a raw. An input whose file name has no extension (a dot in a folder name +/// doesn't count) is saved as PNG. fn same_format(path: &str) -> String { - const IMPORT_ONLY: &[&str] = &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm"]; + const IMPORT_ONLY: &[&str] = + &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm", "xcf", "xcfgz", "gz", "psdt"]; let ext = extension(path).unwrap_or_else(|| "png".into()); - if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) { "psd".into() } else { ext } + let no_writer = photocraft_codecs::from_extension(&ext).is_some_and(|f| !f.caps().write); + if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) || no_writer { "psd".into() } else { ext } } #[cfg(test)] @@ -1365,6 +1370,17 @@ fn same_format_takes_the_file_names_extension() { assert_eq!(same_format("/in/IMG_0001.HEIC"), "psd"); assert_eq!(same_format("/in/logo.svg"), "psd"); assert_eq!(same_format("/in/scan.cin"), "psd"); + // Formats PhotoCraft opens and does not write are saved as PSD. + for name in ["/in/scan.dcm", "/in/scan.DICOM", "/in/scan.dc3", "/in/page.xcf", "/in/page.xcf.gz", "/in/page.xcfgz", "/in/card.psdt"] { + assert_eq!(same_format(name), "psd", "{name}"); + } + for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read && !f.caps().write) { + for ext in f.extensions() { + assert_eq!(same_format(&format!("/in/a.{ext}")), "psd", "{f:?} .{ext}"); + } + } + assert_eq!(same_format("/in/a.pam"), "pam"); + assert_eq!(same_format("/in/a.dds"), "dds"); // No extension in the file name: PNG, not the path after a dot in a folder name. assert_eq!(same_format("/in/v1.2/scan"), "png"); assert_eq!(same_format("C:\\in.d\\scan"), "png"); diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs index 2a23dde9f1..27a05101b7 100644 --- a/crates/engine/src/file_cmds/tests.rs +++ b/crates/engine/src/file_cmds/tests.rs @@ -1835,6 +1835,50 @@ fn folder_listing_recognises_gzipped_xcf_by_its_double_extension() { assert!(!super::openable_name("notes.txt")); } +/// A folder batch picks up every extension that the codecs and the camera raw reader open: +/// Cineon, DICOM, Amiga IFF, PCX, XPM, DDS, the Netpbm family, Photoshop templates and the CR3, +/// ORF, RW2, RAF, SRF and SR2 raws. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn folder_listing_takes_every_format_photocraft_opens() { + for name in [ + "a.cin", "a.dcm", "a.dicom", "a.dc3", "a.iff", "a.lbm", "a.ilbm", "a.pcx", "a.xpm", "a.dds", "a.pbm", "a.pam", "a.pfm", "a.psdt", "a.cr3", "a.orf", + "a.rw2", "a.raf", "a.srf", "a.sr2", "A.PCX", + ] { + assert!(super::openable_name(name), "{name}"); + } + for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read) { + for ext in f.extensions() { + assert!(super::openable_name(&format!("a.{ext}")), "{f:?} .{ext}"); + } + } + for ext in photocraft_io::raw::EXTENSIONS { + assert!(super::openable_name(&format!("a.{ext}")), ".{ext}"); + } + // PhotoCraft does not read AVIF. + assert!(!super::openable_name("a.avif")); +} + +/// A batch over a folder processes PAM, PFM and DDS files instead of skipping them. +#[test] +fn batch_folder_processes_netpbm_and_dds_files() { + let dir = tmp("batch-folder-formats"); + let src = join(&dir, "in"); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "#ff0000"})).unwrap(); + for name in ["a.pam", "b.pfm", "c.dds"] { + save_doc(doc(&s), &join(&src, name), None).unwrap(); + } + std::fs::write(join(&src, "notes.txt"), b"not an image").unwrap(); + let out = join(&dir, "out"); + let r = Session::new().execute("file.automate.batch", json!({"steps": [], "input": src, "output": out, "format": "png"})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let mut files: Vec = r["files"].as_array().unwrap().iter().map(|f| file_name(f.as_str().unwrap())).collect(); + files.sort(); + assert_eq!(files, ["a.png", "b.png", "c.png"], "{r}"); +} + /// The Compression tag (259) of a TIFF's first directory. fn tiff_compression_tag(b: &[u8]) -> Option { let le = b.get(..2)? == b"II"; From b13274419f4b5a49352ad2e055d31c99ffb3a08b Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:41:22 -0400 Subject: [PATCH 42/87] feat: Artboard from Layers takes a size of your own (#9087) layer.new.artboardFromLayers takes width and height: the board gets that size from the layers' top left (0 or none keeps their bounds), and Layer > New > Artboard from Layers... opens a dialog with Name, Background, Color, Width and Height instead of running at once. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/artboard_cmds.rs | 14 ++++++++++---- crates/engine/src/artboard_cmds/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/filter_dialog.rs | 1 + 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs index d9d002ee84..a00c3921a8 100644 --- a/crates/engine/src/artboard_cmds.rs +++ b/crates/engine/src/artboard_cmds.rs @@ -307,8 +307,12 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { let sel = crate::layer_multi_cmds::selected(s); let d = s.active().ok_or(EngineError::NoDocument)?; let canvas = d.doc.bounds(); - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let background = background_param(p, "layer.new.artboardFromLayers")?.unwrap_or_default(); + let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); + let cmd = "layer.new.artboardFromLayers"; + let background = background_param(p, cmd)?.unwrap_or_default(); + // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps + // their bounds on that axis (#9087). + let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; let (gid, rect) = s.edit("Artboard from Layers", |doc, active| { let ids = crate::layer_multi_cmds::top_level(doc, &sel); if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) { @@ -318,7 +322,9 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { for id in &ids { children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); } - let rect = children.iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas); + let bounds = children.iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas); + let [x, y, w, h] = xywh(bounds); + let rect = board_rect(cmd, [x, y, size[0].unwrap_or(w), size[1].unwrap_or(h)])?; let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), children); set_artboard(&mut g, Artboard { rect, background, preset: String::new() }); let gid = doc.insert_above(None, g); @@ -670,7 +676,7 @@ pub fn specs() -> Vec { "layer.new.artboardFromLayers", "Artboard from Layers…", &["Layer", "New"], - r##"{"name":str?,"background":…?} (the selected layers) → {layer, rect}"##, + r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 0 keeps their bounds) → {layer, rect}"##, has_free_layers, artboard_from_layers ), diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/artboard_cmds/tests.rs index b7ad123f9d..14b3ee4f7d 100644 --- a/crates/engine/src/artboard_cmds/tests.rs +++ b/crates/engine/src/artboard_cmds/tests.rs @@ -661,3 +661,23 @@ fn add_beside_duplicate_honors_panel_copy_name_preference() { assert_eq!(doc(&s), &before); } } + +/// #9087: Artboard from Layers takes a size of the user's own, from the layers' top left; 0 or +/// none keeps their bounds on that axis, and a negative size is refused. +#[test] +fn artboard_from_layers_takes_a_custom_size() { + for (params, want) in [ + (json!({"width": 108, "height": 135}), [10, 10, 108, 135]), + (json!({"width": 0, "height": 0}), [10, 10, 20, 20]), + (json!({"width": 60}), [10, 10, 60, 20]), + ] { + let mut s = session(8); + add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); + let r = s.execute("layer.new.artboardFromLayers", params.clone()).unwrap(); + assert_eq!(r["rect"], json!(want), "{params}"); + } + let mut s = session(8); + add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); + assert!(s.execute("layer.new.artboardFromLayers", json!({"width": -5})).is_err()); + assert!(doc(&s).artboards().is_empty(), "a refused size changes nothing"); +} diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index b611b9ac64..b8b7d758f2 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -325,6 +325,7 @@ pub fn has_dialog(command: &str) -> bool { | "image.mode.colorTable" | "edit.definePattern" | "select.convertToShape" + | "layer.new.artboardFromLayers" )) && photocraft_engine::commands::find(command).is_some_and(|c| !parse_spec(c.params).is_empty()) } From 58b8308569916fb66197ef4963739df5166ba563 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:40:58 -0400 Subject: [PATCH 43/87] feat: type on a path follows its path when the path is edited (#9114) Type on a path keeps its own path, but nothing could edit it: the path tools showed and edited the work path it was made from, so the text stayed put. Its own path is now Photoshop's Type Path: with the type layer selected, Direct Selection (and the anchor tools) show and edit it, the path.* commands take it with "name": "layer", path.list names it " Type Path", and the type is laid along it again. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/path_edit_cmds.rs | 13 ++++++++ crates/engine/src/type_extra_cmds.rs | 29 ++++++++++++++++++ crates/engine/src/type_extra_cmds/tests.rs | 35 ++++++++++++++++++++++ crates/engine/src/vector_cmds.rs | 3 ++ crates/ui-egui/src/direct_select.rs | 8 +++-- crates/ui-egui/src/direct_select_tests.rs | 23 ++++++++++++++ crates/ui-egui/src/vector_ui.rs | 10 +++++++ 7 files changed, 118 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/path_edit_cmds.rs b/crates/engine/src/path_edit_cmds.rs index 503ac8efae..2c3b7d83b9 100644 --- a/crates/engine/src/path_edit_cmds.rs +++ b/crates/engine/src/path_edit_cmds.rs @@ -49,6 +49,19 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> { fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result { let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); let layer = if name == "layer" { Some(layer_id(s, p)?) } else { None }; + // Type on a path: its own path, the text laid along it again (#9114). + let typed = layer.filter(|id| { + s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(&l.content, LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some())) + }); + if let Some(id) = typed { + let path = crate::type_extra_cmds::with_text(s, &json!({"layer": id.0}), label, |t, _| { + let mut path = crate::type_extra_cmds::type_path(t).ok_or_else(|| bad(cmd, "the type layer is not on a path"))?; + f(&mut path).map_err(|e| bad(cmd, e))?; + crate::type_extra_cmds::set_type_path(t, &path)?; + Ok(path_json(&path)) + })?; + return Ok(json!({ "name": name, "path": path })); + } let shape = layer.filter(|id| s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)))); let path = match shape { Some(id) => with_shape(s, id, label, |sh, _| { diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rs index 99538edb70..59ed4799b5 100644 --- a/crates/engine/src/type_extra_cmds.rs +++ b/crates/engine/src/type_extra_cmds.rs @@ -415,6 +415,35 @@ fn attach_to_path(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "start": start, "flip": flip})) } +/// Type on a path's own path in document space (#9114): what the Direct Selection tool shows and +/// edits, as Photoshop's Type Path. `None` unless `t` is type on a path. +pub fn type_path(t: &TextLayer) -> Option { + let TextShape::Path { path, .. } = &t.shape else { return None }; + let map = |q: Point| t.transform.apply(q); + let knots = path.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect(); + Some(Path::new(vec![Subpath { closed: path.closed, knots, op: path.op }])) +} + +/// Puts an edited [`type_path`] back into `t` (its text space), keeping where the type starts and +/// which side it runs on. It must still be one subpath with two or more points. +pub(crate) fn set_type_path(t: &mut TextLayer, edited: &Path) -> Result<()> { + let TextShape::Path { start, flip, .. } = &t.shape else { return Err(EngineError::Other("the type layer is not on a path".into())) }; + let (start, flip) = (*start, *flip); + let [sub] = edited.subpaths.as_slice() else { return Err(EngineError::Other("type on a path follows one path".into())) }; + if sub.knots.len() < 2 { + return Err(EngineError::Other("type on a path needs a path of two or more points".into())); + } + let inv = t.transform.inverse().ok_or_else(|| EngineError::Other("the type layer's transform cannot be inverted".into()))?; + let map = |q: Point| inv.apply(q); + let knots: Vec = + sub.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect(); + if !knots.iter().all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|q| q.x.is_finite() && q.y.is_finite())) { + return Err(EngineError::Other("the path cannot be mapped into the type layer".into())); + } + t.shape = TextShape::Path { path: Subpath { closed: sub.closed, knots, op: sub.op }, start, flip }; + Ok(()) +} + fn is_path_text(s: &Session) -> std::result::Result<(), String> { match active_text(s)?.shape { TextShape::Path { .. } | TextShape::Area { .. } => Ok(()), diff --git a/crates/engine/src/type_extra_cmds/tests.rs b/crates/engine/src/type_extra_cmds/tests.rs index d1bc3c39f1..ecb3e01f10 100644 --- a/crates/engine/src/type_extra_cmds/tests.rs +++ b/crates/engine/src/type_extra_cmds/tests.rs @@ -314,6 +314,41 @@ fn type_attaches_to_a_path_and_releases_it() { assert!(matches!(text(&s, id).shape, TextShape::Path { .. })); } +/// #9114: type on a path follows its own path when the path is edited (Direct Selection's +/// `path.*` commands with `"name": "layer"`), as Photoshop's Type Path does; the Paths list names +/// it, an edit is one undo step, and an edit that leaves no path is refused. +#[test] +fn type_follows_its_path_when_the_path_is_edited() { + let mut s = session(8); + let id = text_layer(&mut s, "Hello path"); + s.edit("path", |doc, _| { + doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); + Ok(()) + }) + .unwrap(); + s.execute("type.attachToPath", json!({"start": 4})).unwrap(); + // In document space, the type path is where the work path was. + let path = crate::type_extra_cmds::type_path(text(&s, id)).unwrap(); + let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect(); + assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}"); + let listed = s.execute("path.list", json!({})).unwrap(); + assert_eq!(listed["layerPath"]["kind"], "typePath", "{listed}"); + // Swing the path's end to the right: the type now runs down and to the right. + let before = ink(&s, id); + let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap(); + assert_eq!(r["name"], "layer"); + let after = ink(&s, id); + assert!(after.width() > before.width() + 20, "{before:?} → {after:?}"); + assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0), "where the type starts is kept"); + // The work path it came from is untouched; Undo puts the type path back. + assert_eq!(s.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor.x, 150.0); + assert!(s.undo()); + assert_eq!(ink(&s, id), before); + // An edit that would leave fewer than two points is refused and changes nothing. + assert!(s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id.0, "subpath": 0, "knot": 0})).is_err()); + assert_eq!(ink(&s, id), before); +} + /// The Type tool's click on a path: `"at"` starts the type where the path passes nearest the /// click, and the paragraph alignment is kept about that point, as in Photoshop. #[test] diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs index ccfc3a472a..d90fb3595e 100644 --- a/crates/engine/src/vector_cmds.rs +++ b/crates/engine/src/vector_cmds.rs @@ -853,6 +853,9 @@ fn paths_list(s: &Session) -> Result { let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::(); let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content { LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })), + // Type on a path: Photoshop's Type Path, which Direct Selection edits (#9114). + LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some() => crate::type_extra_cmds::type_path(t) + .map(|p| json!({ "kind": "typePath", "layer": l.id.0, "name": format!("{} Type Path", l.name), "knots": knots(&p) })), _ => { l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) })) } diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs index 71fccc3870..305e954339 100644 --- a/crates/ui-egui/src/direct_select.rs +++ b/crates/ui-egui/src/direct_select.rs @@ -163,10 +163,12 @@ pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool { || matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint) } -/// The active paths, front first: the targeted vector mask or the active shape layer's path, then -/// the work path. The Pen's Auto Add/Delete edits these (`anchor_tools::pen_auto`). +/// The active paths, front first: the targeted vector mask, the active shape layer's path or the +/// active type layer's Type Path (#9114), then the work path. The Pen's Auto Add/Delete edits these +/// (`anchor_tools::pen_auto`). pub(crate) fn active_paths(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { - let layer = crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app)); + let layer = + crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app)).or_else(|| crate::vector_ui::active_type_path(app)); let work = app.session.active().and_then(|st| st.doc.work_path.clone()); layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() } diff --git a/crates/ui-egui/src/direct_select_tests.rs b/crates/ui-egui/src/direct_select_tests.rs index 31a16bfcda..38064a8c07 100644 --- a/crates/ui-egui/src/direct_select_tests.rs +++ b/crates/ui-egui/src/direct_select_tests.rs @@ -517,3 +517,26 @@ fn a_curvature_pen_double_click_through_the_canvas_rounds_a_corner() { assert!(k.smooth && k.in_ctrl != k.anchor, "the double-clicked corner is smooth: {k:?}"); assert!(h.state().ui.pen.is_none(), "and no path was started"); } + +/// #9114: with type on a path selected, Direct Selection reshapes the type's own path (in front of +/// the work path it was made from) and the type follows, in one undoable step. +#[test] +fn dragging_an_anchor_of_type_on_a_path_moves_the_type() { + let mut app = app(Tool::DirectSelection); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap(); + let id = app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + app.run("type.attachToPath", json!({})).unwrap(); + let type_path = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + photocraft_doc::LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).unwrap(), + _ => panic!("not a type layer"), + }; + let n = steps(&app); + drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(id)), "the type path, in front of the work path"); + let end = type_path(&app).subpaths[0].knots[1].anchor; + assert!((end.x - 160.0).abs() < 1e-6 && (end.y - 180.0).abs() < 1e-6, "{end:?}"); + assert_eq!(work(&app).subpaths[0].knots[1].anchor, Point::new(100.0, 180.0), "the work path stays"); + assert_eq!(steps(&app), n + 1); + assert!(app.session.undo()); + assert_eq!(type_path(&app).subpaths[0].knots[1].anchor.x.round(), 100.0); +} diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 81426ccb5e..a0da93d511 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -901,6 +901,16 @@ pub(crate) fn targeted_vector_mask(app: &PhotocraftApp) -> Option<(u64, Path)> { l.vector_mask.as_ref().map(|m| (l.id.0, m.path.clone())) } +/// The active type layer's path in document space, if it is type on a path (#9114). +pub(crate) fn active_type_path(app: &PhotocraftApp) -> Option<(u64, Path)> { + let st = app.session.active()?; + let l = st.active_layer.and_then(|id| st.doc.layer(id))?; + match &l.content { + LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).map(|p| (l.id.0, p)), + _ => None, + } +} + /// The active shape layer's path, if the active layer is a shape layer. pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> { let st = app.session.active()?; From 295d73950869567f0663f51c0a87c2d455b7a710 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 25 Oct 2026 06:48:16 -0600 Subject: [PATCH 44/87] fix(ui): Select and Mask starts from its defaults unless Remember Settings is on (#9423) Select and Mask reopened with the last settings used (Radius, Smooth, Feather, ...), like the filter dialogs, so each use started from the previous refinement instead of a neutral mask. Photoshop's Select and Mask has a Remember Settings checkbox, off by default, and without it reopens at its defaults. The dialog gains Remember Settings (off by default). OK with it off remembers only that choice, so the next Select and Mask starts from the defaults; with it on, the settings carry over as before. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/filter_dialog.rs | 59 +++++++++++++++++++++++++- crates/ui-egui/src/select_mask_view.rs | 13 ++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index b611b9ac64..8a329594a0 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -343,6 +343,15 @@ fn rememberable(kind: &Kind, value: &Value) -> bool { fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &mut Map) { let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(command) else { return }; + // Select and Mask starts from its defaults unless Remember Settings was on, as in Photoshop + // (#9423). + if command == crate::select_mask_view::COMMAND { + let remember = crate::select_mask_view::remembers(saved); + fields.insert(crate::select_mask_view::REMEMBER.into(), json!(remember)); + if !remember { + return; + } + } for p in parse_spec(spec) { if let Some(v) = saved.get(&p.key).filter(|v| rememberable(&p.kind, v)) { fields.insert(p.key, v.clone()); @@ -356,8 +365,17 @@ pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map = + let mut saved: Map = parse_spec(spec.params).into_iter().filter_map(|p| fields.get(&p.key).filter(|v| rememberable(&p.kind, v)).map(|v| (p.key, v.clone()))).collect(); + // Select and Mask with Remember Settings off keeps only that choice, so the next one starts + // from the defaults (#9423). + if command == crate::select_mask_view::COMMAND { + let remember = crate::select_mask_view::remembers(fields); + if !remember { + saved.clear(); + } + saved.insert(crate::select_mask_view::REMEMBER.into(), json!(remember)); + } if !saved.is_empty() { app.session.prefs.edit(|prefs| prefs.dialogs.insert(command.into(), Value::Object(saved))); } @@ -1851,6 +1869,45 @@ mod tests { assert!(!has_dialog("filter.stylize.findEdges")); } + /// #9423: Select and Mask starts from its defaults each time, as in Photoshop, unless Remember + /// Settings was on when it was last OKed; turning it off forgets the settings again. + #[test] + fn select_and_mask_remembers_settings_only_when_asked() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let cmd = crate::select_mask_view::COMMAND; + let fields = |app: &PhotocraftApp, id: u64| app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); + let opened = |app: &mut PhotocraftApp| { + let id = open(app, cmd).unwrap(); + let f = fields(app, id); + app.ui.dialogs.retain(|d| d.id != id); + f + }; + let first = opened(&mut app); + assert_eq!(first["smooth"], json!(0.0)); + assert_eq!(first.get(crate::select_mask_view::REMEMBER), None, "off by default"); + // OK with Smooth 10 and Remember Settings off: the next one starts from the defaults. + let mut f = first.clone(); + f.insert("smooth".into(), json!(10.0)); + f.insert(crate::select_mask_view::REMEMBER.into(), json!(false)); + remember(&mut app, cmd, &f); + let next = opened(&mut app); + assert_eq!(next["smooth"], json!(0.0), "not remembered"); + assert_eq!(next[crate::select_mask_view::REMEMBER], json!(false)); + // With Remember Settings on, the next one starts from them. + f.insert(crate::select_mask_view::REMEMBER.into(), json!(true)); + remember(&mut app, cmd, &f); + let next = opened(&mut app); + assert_eq!(next["smooth"], json!(10.0), "remembered"); + assert_eq!(next[crate::select_mask_view::REMEMBER], json!(true)); + // Turning it off again forgets them. + let mut off = next.clone(); + off.insert(crate::select_mask_view::REMEMBER.into(), json!(false)); + remember(&mut app, cmd, &off); + assert_eq!(opened(&mut app)["smooth"], json!(0.0)); + } + /// Select and Mask's Output To lists all six output targets. #[test] fn select_and_mask_output_lists_all_six_targets() { diff --git a/crates/ui-egui/src/select_mask_view.rs b/crates/ui-egui/src/select_mask_view.rs index 9f5440c4aa..37dc9effdc 100644 --- a/crates/ui-egui/src/select_mask_view.rs +++ b/crates/ui-egui/src/select_mask_view.rs @@ -197,12 +197,25 @@ pub fn controls(ui: &mut egui::Ui, fields: &mut Map) { fields.insert(field.into(), json!(on)); } ui.label(egui::RichText::new(tl!("F cycles the views; hold X to see the image")).color(t.text_dim).small()); + // Photoshop's Remember Settings, off by default: the next Select and Mask starts from these + // settings instead of the defaults (#9423). + let mut remember = remembers(fields); + crate::widgets::checkbox(ui, &mut remember, tl!("Remember Settings")); + fields.insert(REMEMBER.into(), json!(remember)); ui.add_space(4.0); crate::widgets::hairline(ui); ui.add_space(6.0); brush_controls(ui, fields); } +/// The dialog field behind Remember Settings. +pub const REMEMBER: &str = "__remember"; + +/// Whether Remember Settings is on in `fields` (a dialog's, or the remembered ones). +pub fn remembers(fields: &Map) -> bool { + flag(fields, REMEMBER) +} + /// The Refine Edge Brush (R): painting on the canvas sets where edge refinement happens. fn brush_controls(ui: &mut egui::Ui, fields: &mut Map) { let t = Tokens::get(ui.ctx()); From 9e2426f6c12a0d2348bcf74ea37842a88ddb4317 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 14:52:26 +0100 Subject: [PATCH 45/87] Format the AHD bit-for-bit test with rustfmt Co-Authored-By: Claude Sonnet 5.5 --- crates/raw/src/demosaic.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index f691c9584b..6e768c0b2d 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -811,7 +811,11 @@ mod tests { let mut want = vec![0.0f32; w * h * 3]; ahd_ref(&p, phase, &m, &mut want, jobs); let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); - assert_eq!(want.iter().map(|v| v.to_bits()).collect::>(), got.iter().map(|v| v.to_bits()).collect::>(), "{w}x{h} {phase:?} {jobs}"); + assert_eq!( + want.iter().map(|v| v.to_bits()).collect::>(), + got.iter().map(|v| v.to_bits()).collect::>(), + "{w}x{h} {phase:?} {jobs}" + ); } } } From 4915f0970e3e1356839d606b45bd97b709c70c78 Mon Sep 17 00:00:00 2001 From: Phil Trinh Date: Fri, 16 Oct 2026 18:25:59 +0800 Subject: [PATCH 46/87] PSD/PSB open without reading the whole file: channel data read as it is decoded, in bands straight into tiles (#5106) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Opening a 2.14 GB PSD (2000×2000, 109 layers, 821 MB of embedded smart objects) peaked at 7.28 GB and took 6.8 s; it now peaks at 3.00 GB and takes 3.6 s (macOS peak memory footprint, `cargo run --release -p photocraft-io --example psd_open_mem`). - photocraft-psd: `PsdFile::from_source` parses from a `ReadAt` source (`FileSource`: pread / seek_read in bounded reads). Channel data and the merged image become `Stored` ranges read when decoded; the model equals `from_bytes`'s and writes back the same bytes (tests compare the two on every generated file, including Lr16/Lr32 layer blocks and truncated files). - `ChannelData::row_decoder` decodes any band of rows: RLE via its row table (a stored channel reads only the band's bytes), raw by offset, ZIP inflated once. - photocraft-io: `import_file` opens a path; PSD/PSB through `from_source`, other formats read whole. Layers decode in bands of whole tile rows (~32 MB) into tiles: no whole-layer plane or interleaved buffer. Global blocks move into the document instead of being copied; finding an embedded smart object no longer copies every file in `lnk2`. - photocraft-raster: `Surface::share_uniform_tiles` + `TileInterner`; the PSD import shares single-value tiles (backgrounds, fill caches, masks) across layers. - The background open job and the CLI/MCP (`automation::files::open`) use `import_file`. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/automation/Cargo.toml | 1 + crates/automation/src/files.rs | 18 +- crates/engine/src/jobs.rs | 45 ++- crates/io/examples/psd_open_mem.rs | 56 +++ crates/io/src/lib.rs | 79 +++- crates/io/src/linked.rs | 29 +- crates/io/src/multichannel_map.rs | 2 +- crates/io/src/palette_map.rs | 2 +- crates/io/src/psd_export.rs | 4 +- crates/io/src/psd_import.rs | 197 +++++++--- crates/io/src/tiff_layers.rs | 2 +- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/psd_damaged_merged.rs | 4 +- crates/io/tests/it/psd_import_file.rs | 155 ++++++++ crates/io/tests/it/psd_structure.rs | 11 +- crates/io/tests/it/psd_unknown_adjustment.rs | 2 +- crates/psd/README.md | 11 +- crates/psd/examples/bench_layer_block.rs | 4 +- crates/psd/src/error.rs | 3 + crates/psd/src/file.rs | 37 +- crates/psd/src/image_data.rs | 56 ++- crates/psd/src/layer.rs | 79 +++- crates/psd/src/lazy.rs | 378 +++++++++++++++++++ crates/psd/src/lib.rs | 7 + crates/psd/src/rows.rs | 234 ++++++++++++ crates/psd/src/source.rs | 270 +++++++++++++ crates/psd/src/tagged.rs | 4 +- crates/psd/src/testgen.rs | 4 +- crates/raster/src/lib.rs | 72 ++++ 30 files changed, 1646 insertions(+), 122 deletions(-) create mode 100644 crates/io/examples/psd_open_mem.rs create mode 100644 crates/io/tests/it/psd_import_file.rs create mode 100644 crates/psd/src/lazy.rs create mode 100644 crates/psd/src/rows.rs create mode 100644 crates/psd/src/source.rs diff --git a/Cargo.lock b/Cargo.lock index 794e35b1ff..334bedc2fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4827,6 +4827,7 @@ dependencies = [ "photocraft-engine", "photocraft-format", "photocraft-io", + "photocraft-raster", "photocraft-raw", "rmcp", "rustix 1.1.5", diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 5421640a84..d4e7d14e73 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] photocraft-doc = { workspace = true } +photocraft-raster = { workspace = true } photocraft-compose = { workspace = true } photocraft-codecs = { workspace = true } photocraft-io = { workspace = true } diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index fc4526eedb..0b8ff103aa 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -33,9 +33,23 @@ pub fn open(path: &Path) -> Result { let document = photocraft_format::load_path(path)?; return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); } - let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - open_bytes(&name, &bytes) + // A PSD/PSB is parsed from the open file (channel data read as it is decoded), so a CLI + // convert or info of a 2 GB file does not hold the file in memory next to the document. + #[cfg(any(unix, windows))] + { + let r = + photocraft_io::import_file(&name, path, &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE).map_err(|e| match e { + photocraft_io::IoError::Read(msg) => AutomationError::Io(msg), + e => e.into(), + })?; + Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) + } + #[cfg(not(any(unix, windows)))] + { + let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + open_bytes(&name, &bytes) + } } /// Previews for a `.pcraft` bundle. diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 5c26e41cba..d106fc0faf 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -330,14 +330,25 @@ fn independent_of_document(id: &str) -> bool { } #[cfg(not(target_arch = "wasm32"))] -fn read_path(path: &str) -> Result> { - // Bounded reads, and a clear error for a file larger than memory (#375). - photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +fn import_path( + name: &str, + path: &str, + opts: &photocraft_io::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> { + // Bounded reads, and a clear error for a file larger than memory (#375); a PSD/PSB is + // parsed from the open file instead of being read whole. + photocraft_io::import_file_for_open_with(name, std::path::Path::new(path), opts, ctl) } #[cfg(target_arch = "wasm32")] -fn read_path(path: &str) -> Result> { - Err(EngineError::Other(format!("cannot open paths on the web: {path}"))) +fn import_path( + _: &str, + path: &str, + _: &photocraft_io::ImportOptions, + _: &photocraft_raster::Interrupt, +) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> { + Err(photocraft_io::IoError::Read(format!("cannot open paths on the web: {path}"))) } /// Run a job-capable command's heavy part. `work` runs on a worker thread when the command was @@ -553,17 +564,19 @@ impl Session { false, move |ctx| { ctx.progress(0.0, "Reading"); - let bytes = match source { - OpenSource::Bytes(b) => b, - OpenSource::Path(p) => Arc::new(read_path(&p)?), - }; - ctx.check()?; - ctx.progress(0.02, "Decoding"); - let imported = - ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)).map_err(|e| match e { - photocraft_io::IoError::Cancelled => EngineError::Cancelled, - e => EngineError::Other(e.to_string()), - })?; + let imported = match source { + OpenSource::Bytes(bytes) => { + ctx.check()?; + ctx.progress(0.02, "Decoding"); + ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)) + } + // A PSD/PSB is decoded straight from the file, which is never read whole. + OpenSource::Path(p) => ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, ctl)), + } + .map_err(|e| match e { + photocraft_io::IoError::Cancelled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + })?; ctx.progress(0.95, "Preparing layers"); warm_layer_bounds(&imported.0.document, || ctx.check())?; // Type layers need the shared text engine, whose first use waits for the diff --git a/crates/io/examples/psd_open_mem.rs b/crates/io/examples/psd_open_mem.rs new file mode 100644 index 0000000000..903eb35af9 --- /dev/null +++ b/crates/io/examples/psd_open_mem.rs @@ -0,0 +1,56 @@ +//! Opens a file the way the app's background open does and reports the time. Run it under +//! `/usr/bin/time -l` for the peak memory. `--read` reads the whole file first and imports the +//! bytes, as opens did before `import_file` (to compare). +//! +//! `cargo run --release -p photocraft-io --example psd_open_mem -- [--read]` + +fn main() { + let Some(path) = std::env::args().nth(1).filter(|a| a != "--read") else { + eprintln!("usage: psd_open_mem "); + std::process::exit(2); + }; + if std::env::args().any(|a| a == "--read") { + read_then_import(&path); + return; + } + let t = std::time::Instant::now(); + let res = + match photocraft_io::import_file(&path, std::path::Path::new(&path), &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE) { + Ok(r) => r, + Err(e) => { + eprintln!("{path}: open failed: {e}"); + std::process::exit(1); + } + }; + report(&path, &format!("open {:.2}s", t.elapsed().as_secs_f64()), &res); +} + +fn read_then_import(path: &str) { + let t = std::time::Instant::now(); + let bytes = match photocraft_format::read_file(std::path::Path::new(path)) { + Ok(b) => b, + Err(e) => { + eprintln!("{path}: read failed: {e}"); + std::process::exit(1); + } + }; + let read_s = t.elapsed().as_secs_f64(); + let t = std::time::Instant::now(); + let res = match photocraft_io::import_with(path, &bytes, &photocraft_raster::Interrupt::NONE) { + Ok(r) => r, + Err(e) => { + eprintln!("{path}: open failed: {e}"); + std::process::exit(1); + } + }; + drop(bytes); + report(path, &format!("read {read_s:.2}s, import {:.2}s", t.elapsed().as_secs_f64()), &res); +} + +fn report(path: &str, times: &str, res: &photocraft_io::ImportResult) { + let doc = &res.document; + println!("{path}: {times}, {} layers ({} top level)", doc.walk().len(), doc.layers.len()); + for w in &res.warnings { + println!(" warning: {w}"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 44beb59d47..b666c47d02 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -125,6 +125,9 @@ pub enum IoError { /// An SVG that does not parse (or is too large to rasterise). #[error("SVG: {0}")] Svg(String), + /// The file could not be read. + #[error("{0}")] + Read(String), /// A background import or save was cancelled ([`import_with`], [`export_with`]). #[error("cancelled")] Cancelled, @@ -373,26 +376,82 @@ pub fn import_for_open_with(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: Ok((result, damaged)) } -fn import_psd(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, damaged: &mut bool) -> Result { +/// The PSD/PSB part of an import, from a parse that takes [`PsdFile::from_bytes_and_merged_recovering`]'s +/// `want` and `recover`: of the file's bytes, or of the file itself ([`import_file_for_open_with`]). +fn import_psd( + name: &str, + ctl: &photocraft_raster::Interrupt, + damaged: &mut bool, + parse: impl FnOnce(&dyn Fn(&PsdFile) -> bool, &dyn Fn(&PsdFile) -> bool) -> photocraft_psd::Result<(PsdFile, Option>>)>, +) -> Result { // A merged image the import reads is decoded with the parse: a ZIP one is inflated once. - let (file, merged) = PsdFile::from_bytes_and_merged_recovering( - bytes, - |f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f), - psd_import::can_recover_layers, - )?; + // A failed read of the file (one parsed from its source) is a read error, as reading the + // whole file first would report it. + let (file, merged) = + parse(&|f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f), &psd_import::can_recover_layers).map_err(|e| match e { + photocraft_psd::PsdError::Read(msg) => IoError::Read(msg), + e => e.into(), + })?; // Nesting past the document model's cap could never be saved; reject the file with the // actionable limit. psd_import::check_group_depth(&file)?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(0.05); - let (mut document, warnings, psd_damaged) = psd_import::psd_to_document_decoded_integrity(&file, ctl, merged).ok_or(IoError::Cancelled)?; + // Read before the conversion, which moves the global blocks into the document. + let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); + let (mut document, warnings, psd_damaged, read_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?; + // The file became unreadable while its layers were read from it (`import_file_for_open_with`): + // the open fails, rather than opening with those layers empty. + if let Some(e) = read_error { + return Err(IoError::Read(e)); + } *damaged = psd_damaged; document.name = name.to_string(); - let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); text_import::prepare(&mut document, txt2.as_ref()); Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false }) } +/// [`import_for_open_with`] for the file at `path`. A PSD/PSB is parsed from the open file +/// ([`PsdFile::from_source`]) rather than read whole: its channel data is read layer by layer as +/// it is decoded, so opening it needs memory for the document, not for the document plus the +/// file. A read that fails meanwhile (the file is truncated or rewritten, its drive goes away) +/// fails the open. Other formats are read whole. +#[cfg(any(unix, windows))] +pub fn import_file_for_open_with( + name: &str, + path: &std::path::Path, + opts: &ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result<(ImportResult, bool), IoError> { + let read_failed = |e: std::io::Error| IoError::Read(format!("{}: {e}", path.display())); + ctl.check().map_err(|_| IoError::Cancelled)?; + let source = photocraft_psd::FileSource::open(path).map_err(read_failed)?; + let mut magic = [0u8; 4]; + let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic); + if !psd { + drop(source); + let bytes = photocraft_format::read_file(path).map_err(read_failed)?; + return import_for_open_with(name, &bytes, opts, ctl); + } + import_source_for_open_with(name, photocraft_psd::Source::new(source), ctl) +} + +/// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source. +pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut damaged = false; + let r = import_psd(name, ctl, &mut damaged, |want, recover| PsdFile::from_source_and_merged_recovering(source, want, recover))?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(1.0); + Ok((r, damaged)) +} + +/// [`import_file_for_open_with`] without the damage flag. +#[cfg(any(unix, windows))] +pub fn import_file(name: &str, path: &std::path::Path, opts: &ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result { + import_file_for_open_with(name, path, opts, ctl).map(|(result, _)| result) +} + /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { @@ -404,7 +463,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus // preview_never_saves_back_to_its_native_or_renamed_source). if is_psd(bytes) { - return import_psd(name, bytes, ctl, damaged); + return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover)); } if affinity::is_affinity(bytes) || affinity::has_extension(name) { return affinity::import(name, bytes); @@ -437,7 +496,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of // `codec: unrecognized image format` (#5258). Magic already returned above. if is_psd_input(name, bytes) { - return import_psd(name, bytes, ctl, damaged); + return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover)); } flat::import_flat(name, bytes) } diff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rs index e200b875ea..dcf7ecd98d 100644 --- a/crates/io/src/linked.rs +++ b/crates/io/src/linked.rs @@ -118,7 +118,30 @@ pub fn find_in_blocks<'a>(blocks: impl IntoIterator(blocks: impl IntoIterator, uuid: &str) -> Option<(String, String, &'a [u8])> { + if uuid.is_empty() { + return None; + } + blocks.into_iter().filter(|(k, _)| matches!(*k, b"lnk2" | b"lnk3" | b"lnkD")).find_map(|(_, d)| { + let mut r = Rd { d, p: 0 }; + while let Some(len) = r.u64() { + let Ok(len) = usize::try_from(len) else { return None }; + let item = r.take(len)?; + let found = item_header(item).filter(|h| h.0 == uuid).and_then(|(id, name, start, n)| Some((id, name, item.get(start..start.checked_add(n)?)?))); + if found.is_some() { + return found; + } + r.p = r.p.next_multiple_of(4); + } + None + }) } /// The size of embedded file `uuid` among PSD global blocks given as (key, data), when it is there @@ -128,11 +151,11 @@ pub(crate) fn source_size_in_blocks<'a>( uuid: &str, ctl: &photocraft_raster::Interrupt, ) -> Option<(f64, f64)> { - let f = find_in_blocks(blocks, uuid)?; + let (_, _, bytes) = find_slice_in_blocks(blocks, uuid)?; if ctl.cancelled() { return None; } - source_size_probe(&f.bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0) + source_size_probe(bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0) } /// Pixel size of an embedded source file from its header: PSD/PSB, TIFF (the default page's diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index e9437deb6c..f5b2933041 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -116,7 +116,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec< let header = Header::new(version, doc.size.width, doc.size.height, channels.len().max(1) as u16, psd_depth(sample), PsdMode::Multichannel); let image_data = ImageData::encode(Compression::Rle, &planes, &header) .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + .unwrap_or(ImageData::new(Compression::Raw, planes)); let mut resources = vec![ ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index 45b8168f1c..b4aa1ff0c6 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -45,7 +45,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> Option<(PsdFil let header = Header::new(version, doc.size.width, doc.size.height, 1, depth, mode); let image_data = ImageData::encode(Compression::Rle, &plane, &header) .or_else(|_| ImageData::encode(Compression::Raw, &plane, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: plane }); + .unwrap_or(ImageData::new(Compression::Raw, plane)); let mut resources = vec![ ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 4835397822..351e33331b 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -368,7 +368,7 @@ impl Ex { let compression = if w == 0 || h == 0 { Compression::Raw } else { self.compression() }; ChannelData::encode(id, compression, plane, w, h, depth, self.version) .or_else(|_| ChannelData::encode(id, Compression::Raw, plane, w, h, depth, self.version)) - .unwrap_or(ChannelData { id, compression: Some(Compression::Raw), data: plane.to_vec() }) + .unwrap_or(ChannelData::new(id, Some(Compression::Raw), plane.to_vec())) } fn empty_channels(&self) -> Vec { @@ -1833,7 +1833,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; let image_data = ImageData::encode(mcomp, &planes, &header) .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + .unwrap_or(ImageData::new(Compression::Raw, planes)); ctl.progress(1.0); // Resources. diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 717f848716..f646e1f665 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -4,7 +4,8 @@ use std::sync::Arc; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{ - AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer, + AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, PsdGlobalBlock, ShapeLayer, SmartContentsId, SmartObject, SmartSource, + TextLayer, }; use photocraft_geom::{Rect, Size, TILE_SIZE}; use photocraft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK}; @@ -46,6 +47,8 @@ pub(crate) const REGENERATED: [&[u8; 4]; 9] = [b"luni", b"lyid", b"lsct", b"lsdk pub(crate) struct Ctx<'a> { pub file: &'a PsdFile, + /// The file's global blocks, as the document keeps them. + pub global: Vec, pub fmt: PixelFormat, pub mask_fmt: PixelFormat, pub cc: usize, @@ -53,6 +56,9 @@ pub(crate) struct Ctx<'a> { pub warnings: Vec, /// Decoding encountered damaged PSD data; interactive opens ask whether to continue. pub damaged: bool, + /// Reading the file's channel data failed (it is read as it is decoded: see + /// `PsdFile::from_source`): the open fails with it, rather than leaving layers empty. + pub read_error: Option, /// Document resolution (type sizes are converted to points with it). pub dpi: f32, /// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning). @@ -74,9 +80,35 @@ pub(crate) struct Ctx<'a> { pub ctl: photocraft_raster::Interrupt<'a>, /// Layer records decoded so far, out of `total` (progress). pub done: usize, + /// Tiles of one pixel value, shared by every surface the import decodes. + pub uniform: photocraft_raster::TileInterner, pub total: usize, } +/// Bytes of interleaved pixels a band decoded into tiles at once aims at: whole layers up to this +/// size decode in one band, larger ones in bands of whole tile rows. +const BAND_BYTES: usize = 32 << 20; + +/// Row ranges (`0..h`, relative to a layer whose first row is at document row `top`) to decode a +/// layer in: each ends on a tile row boundary, so no tile is written by two bands, and holds +/// about [`BAND_BYTES`] of `row_bytes`-byte rows. +fn band_rows(top: i32, h: usize, row_bytes: usize) -> Vec<(usize, usize)> { + let tile = TILE_SIZE as usize; + let rows = (BAND_BYTES / row_bytes.max(1)).max(tile) / tile * tile; + // The first band ends at the first tile boundary at least `rows` rows in. + let into_tile = usize::try_from(top.rem_euclid(TILE_SIZE)).unwrap_or(0); + let mut out = Vec::new(); + let mut r0 = 0; + let mut r1 = rows - into_tile; + while r0 < h { + let end = r1.min(h); + out.push((r0, end)); + r0 = end; + r1 = end + rows; + } + out +} + fn doc_mode(m: PsdMode) -> Option { Some(match m { PsdMode::Bitmap => ColorMode::Bitmap, @@ -148,6 +180,17 @@ impl Ctx<'_> { self.warn(s); } + /// A channel that failed to decode: a failed read of the file is kept to fail the open + /// (`true`); damaged data is warned about, its layer left empty (`false`). + fn channel_failed(&mut self, name: &str, id: i16, e: &photocraft_psd::PsdError) -> bool { + if let photocraft_psd::PsdError::Read(msg) = e { + self.read_error.get_or_insert_with(|| format!("layer \"{name}\": {msg}")); + return true; + } + self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty")); + false + } + /// Source id, transform, (Distort/Perspective) projective placement and warp of a placed /// layer that has only a `PlLd` block, as Photoshop CS2 and older write it (#2465). `PlLd` /// stores the placed corners but not the source size, which comes from the embedded file. @@ -168,11 +211,11 @@ impl Ctx<'_> { return Placement::default(); } }; - let (file, ctl) = (self.file, self.ctl); + let (global, ctl) = (&self.global, self.ctl); let size = *self .plld_sizes .entry(id.clone()) - .or_insert_with(|| crate::linked::source_size_in_blocks(file.global_blocks.iter().map(|b| (&b.key, b.data.as_slice())), &id, &ctl)); + .or_insert_with(|| crate::linked::source_size_in_blocks(global.iter().map(|(_, k, d)| (k, d.as_slice())), &id, &ctl)); // Without the source (missing or unreadable), it is taken as placed at 100 %. let (transform, perspective) = blocks::plld_transform(&p, size, warp.as_ref()); Placement { id, transform, perspective, warp } @@ -181,72 +224,83 @@ impl Ctx<'_> { /// Decodes a PSD layer channel, marking the document damaged if its data is unreadable. fn channel_plane(&mut self, rec: &LayerRecord, id: i16, name: &str) -> Option> { rec.channel(id)?; + if self.read_error.is_some() { + return None; + } match rec.decode_channel(id, self.file.header.depth, self.file.header.version) { Ok(p) => Some(p), Err(e) => { - self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty")); + self.channel_failed(name, id, &e); None } } } - /// [`Self::channel_plane`] without the warnings sink, so a layer's channels decode - /// concurrently (their RLE rows are the bulk of the open time on full-canvas layers). - fn channel_plane_decoded(&self, rec: &LayerRecord, id: i16) -> Option> { - rec.channel(id)?; - rec.decode_channel(id, self.file.header.depth, self.file.header.version).ok() - } - /// Builds a raster surface from the layer channels, leaving the surface empty if /// any present channel fails to decode rather than inventing replacement pixels. fn record_surface(&mut self, rec: &LayerRecord, name: &str) -> Surface { let r = rec.rect; - if r.is_empty() || r.size().is_err() { + // Once the file couldn't be read the open fails: nothing more is decoded. + if r.is_empty() || r.size().is_err() || self.read_error.is_some() { return Surface::new(self.fmt); } let (w, h) = r.size().unwrap_or((0, 0)); let s = self.fmt.sample; + let (depth, version) = (self.file.header.depth, self.file.header.version); let ids: Vec = (0..self.cc as i16).chain([CHANNEL_TRANSPARENCY]).collect(); - let planes: Vec>> = if cfg!(target_arch = "wasm32") { - ids.iter().map(|&id| self.channel_plane(rec, id, name)).collect() - } else { - // The channels decode independently; their RLE rows are the bulk of the open - // time for full-canvas layers, so they run side by side and the warnings land - // in the same order afterwards. - // par_map reuses the crate's worker pool (one OS thread per channel per layer - // would spawn thousands on a file with many layers). - let decoded: Vec>> = crate::pixels::par_map(ids.to_vec(), |id| self.channel_plane_decoded(rec, id)); - let mut planes: Vec>> = Vec::with_capacity(decoded.len()); - for (&id, p) in ids.iter().zip(decoded) { - if p.is_none() && rec.channel(id).is_some() { - self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded; treated as empty")); - } - planes.push(p); + // A decoder per channel present (a ZIP channel is inflated here, the channels side by + // side); the rows are then decoded and interleaved a band at a time straight into the + // tiles, so no buffer of the whole layer (planes or interleaved) is ever held. + // par_map reuses the crate's worker pool (one OS thread per channel per layer would + // spawn thousands on a file with many layers). + let decoders: Vec>>> = + crate::pixels::par_map(ids.to_vec(), |id| rec.channel(id).map(|ch| ch.row_decoder(w, h, depth, version))); + let mut failed = false; + for (&id, d) in ids.iter().zip(&decoders) { + if let Some(Err(e)) = d { + self.channel_failed(name, id, e); + failed = true; } - planes - }; + } // A channel that is in the file but could not be decoded leaves the layer empty, as the // warning says. Filling in for it would paint an opaque black layer over the document. - if ids.iter().zip(planes.iter()).any(|(&id, p)| p.is_none() && rec.channel(id).is_some()) { + if failed { return Surface::new(self.fmt); } // Only decoded channel data justifies a buffer: the decoders bound their output by the // bytes in the file, but a bare rectangle can declare 300000² pixels in a few bytes (#755). - if planes.iter().all(Option::is_none) { + if decoders.iter().all(Option::is_none) { self.warn_unreadable_data(format!("layer \"{name}\": no channel data for its {w}x{h} bounds; treated as empty")); return Surface::new(self.fmt); } - let refs: Vec> = planes.iter().map(|p| p.as_deref()).collect(); let mut fill: Vec> = vec![zero_sample(s); self.cc]; fill.push(max_sample(s)); let mut invert = vec![self.cmyk; self.cc]; invert.push(false); - let mut bytes = interleave(&refs, &fill, w * h, s, &invert); - if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 { - crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true); + let mut surf = Surface::new(self.fmt); + for (b0, b1) in band_rows(r.top, h, w * (self.cc + 1) * s.bytes()) { + let planes: Vec>>> = + crate::pixels::par_map(decoders.iter().collect(), |d| d.as_ref().and_then(|d| d.as_ref().ok()).map(|d| d.rows(b0, b1))); + let mut refs: Vec> = Vec::with_capacity(planes.len()); + for (&id, p) in ids.iter().zip(&planes) { + match p { + Some(Err(e)) => { + self.channel_failed(name, id, e); + return Surface::new(self.fmt); + } + Some(Ok(p)) => refs.push(Some(p)), + None => refs.push(None), + } + } + let mut bytes = interleave(&refs, &fill, w * (b1 - b0), s, &invert); + if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 { + crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true); + } + surf.write_interleaved(Rect::new(r.left, r.top + b0 as i32, r.right, r.top + b1 as i32), &bytes); } - let mut surf = Surface::from_interleaved(self.fmt, Rect::new(r.left, r.top, r.right, r.bottom), &bytes); surf.prune(); + // A white background, a solid fill's cache: one tile per value, shared across layers. + surf.share_uniform_tiles(&mut self.uniform); surf } @@ -270,6 +324,7 @@ impl Ctx<'_> { let bytes = interleave(&[Some(&plane)], &[zero_sample(s)], w * h, s, &[false]); surface.write_interleaved(Rect::new(rect.left, rect.top, rect.right, rect.bottom), &bytes); surface.prune(); + surface.share_uniform_tiles(&mut self.uniform); } let params = m.parameters; Some(LayerMask { @@ -910,6 +965,38 @@ pub(crate) fn psd_to_document_decoded_integrity( ctl: &photocraft_raster::Interrupt, decoded: Option>>, ) -> Option<(Document, Vec, bool)> { + let global = file.global_blocks.iter().map(|b| (b.signature, b.key, Arc::new(b.data.clone()))).collect(); + psd_to_document_global(file, ctl, decoded, global).map(|(document, warnings, damaged, _)| (document, warnings, damaged)) +} + +/// [`psd_to_document_decoded_integrity`] taking the file: its global blocks move into the +/// document rather than being copied (an embedded smart object's `lnk2` block can be most of a +/// file). The file's channel data may still be in its source ([`PsdFile::from_source`]): the +/// fourth value is a failure to read it, which fails the open (a layer is never left empty +/// because its file became unreadable while it opened). +pub(crate) fn psd_to_document_owned( + mut file: PsdFile, + ctl: &photocraft_raster::Interrupt, + decoded: Option>>, +) -> Option<(Document, Vec, bool, Option)> { + let global = file + .global_blocks + .iter_mut() + .map(|b| { + // A layer block is still read by `unreadable_layer_block` (to say why it failed). + let data = if matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr") { b.data.clone() } else { std::mem::take(&mut b.data) }; + (b.signature, b.key, Arc::new(data)) + }) + .collect(); + psd_to_document_global(&file, ctl, decoded, global) +} + +fn psd_to_document_global( + file: &PsdFile, + ctl: &photocraft_raster::Interrupt, + decoded: Option>>, + global: Vec, +) -> Option<(Document, Vec, bool, Option)> { let h = &file.header; let mut warnings = Vec::new(); let mode = doc_mode(h.color_mode).unwrap_or_else(|| { @@ -970,9 +1057,7 @@ pub(crate) fn psd_to_document_decoded_integrity( } } crate::guides_map::apply_colors(&mut doc); - for b in &file.global_blocks { - doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone()))); - } + doc.metadata.psd_global_blocks.extend(global.iter().cloned()); // A 16/32-bit file whose layer block can't be parsed would otherwise open as a flattened // file without a word (#2700). The raw block is kept, but a PSD save writes the document's // own layers in its place (see `psd_export`). @@ -998,14 +1083,16 @@ pub(crate) fn psd_to_document_decoded_integrity( let cc = fmt.mode.color_channels(); let mut cx = Ctx { file, + global: global.clone(), fmt, mask_fmt: PixelFormat::new(ColorMode::Grayscale, depth, false), cc, cmyk: fmt.mode == ColorMode::Cmyk, warnings, damaged, + read_error: None, dpi: doc.resolution_dpi, - txt2: file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)), + txt2: global.iter().find(|(_, k, _)| k == b"Txt2").and_then(|(_, _, d)| photocraft_text::psd::parse_txt2(d)), filter_effects: Vec::new(), filter_masks: Default::default(), unfiltered: Default::default(), @@ -1014,16 +1101,17 @@ pub(crate) fn psd_to_document_decoded_integrity( plld_sizes: Default::default(), ctl: *ctl, done: 0, + uniform: Default::default(), total: file.layers().len(), }; - for b in file.global_blocks.iter().filter(|b| matches!(&b.key, b"FEid" | b"FXid")) { + for (_, key, data) in cx.global.clone().iter().filter(|(_, k, _)| matches!(k, b"FEid" | b"FXid")) { // Smart-filter caches can be large: a cancelled open stops between blocks. if ctl.cancelled() { return None; } - match photocraft_psd::filter_effects::FilterEffects::parse(&b.data) { + match photocraft_psd::filter_effects::FilterEffects::parse(data) { Ok(fx) => cx.filter_effects.extend(fx.items), - Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", b.key_str())), + Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", String::from_utf8_lossy(key))), } } if ctl.cancelled() { @@ -1239,7 +1327,7 @@ pub(crate) fn psd_to_document_decoded_integrity( return None; } ctl.progress(1.0); - Some((doc, cx.warnings, cx.damaged)) + Some((doc, cx.warnings, cx.damaged, cx.read_error)) } #[cfg(test)] @@ -1349,4 +1437,25 @@ mod tests { assert_eq!(merged_plane(&all, 2, 2), None); assert_eq!(merged_plane(&all, usize::MAX, 2), None); } + + #[test] + fn layer_bands_end_on_tile_rows_and_cover_the_layer() { + let t = TILE_SIZE as usize; + for (top, h, row_bytes) in [(0, 2000, 8000), (-37, 15000, 80_000), (100, 5, 4), (255, 1, 4), (-256, 40_000, 1 << 20), (7, 0, 4)] { + let bands = band_rows(top, h, row_bytes); + let mut next = 0; + for &(a, b) in &bands { + assert_eq!(a, next); + assert!(b > a); + if b < h { + assert_eq!((top + b as i32).rem_euclid(TILE_SIZE), 0, "{top} {h}: band ends inside a tile row"); + assert!((b - a) * row_bytes <= BAND_BYTES + t * row_bytes || b - a <= t); + } + next = b; + } + assert_eq!(next, h); + } + // A small layer is one band. + assert_eq!(band_rows(0, 2000, 8000), vec![(0, 2000)]); + } } diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 25c2df5010..cc833f1434 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -104,7 +104,7 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result Self { + let dir = std::env::temp_dir().join(format!("photocraft-import-file-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } + + fn write(&self, name: &str, bytes: &[u8]) -> std::path::PathBuf { + let path = self.0.join(name); + std::fs::write(&path, bytes).unwrap(); + path + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The document's debug form with every `…Id(n)` number blanked. +fn without_ids(doc: &photocraft_doc::Document) -> String { + let s = format!("{doc:?}"); + let mut out = String::with_capacity(s.len()); + let mut rest = s.as_str(); + while let Some(at) = rest.find("Id(") { + out.push_str(&rest[..at + 3]); + rest = rest[at + 3..].trim_start_matches(|c: char| c.is_ascii_digit()); + } + out.push_str(rest); + out +} + +fn open(name: &str, path: &std::path::Path) -> Result { + import_file(name, path, &photocraft_io::ImportOptions::default(), &Interrupt::NONE) +} + +#[test] +fn import_file_opens_what_importing_the_bytes_opens() { + let dir = TempDir::new("same"); + let mut checked = 0; + for case in testgen::all_cases() { + let ext = if case.file.header.version.is_psb() { "psb" } else { "psd" }; + let name = format!("case.{ext}"); + let bytes = case.file.to_bytes().unwrap(); + let path = dir.write(&name, &bytes); + let from_bytes = import(&name, &bytes); + let from_file = open(&name, &path); + match (from_bytes, from_file) { + (Ok(a), Ok(b)) => { + // Ids come from a process-wide counter, so the two opens differ only there. + assert!(without_ids(&b.document) == without_ids(&a.document), "{}", case.name); + assert_eq!(b.warnings, a.warnings, "{}", case.name); + checked += 1; + } + (Err(_), Err(_)) => {} + (a, b) => panic!("{}: bytes {:?}, file {:?}", case.name, a.map(|r| r.warnings), b.map(|r| r.warnings)), + } + } + assert!(checked > 50, "only {checked} cases opened"); +} + +#[test] +fn import_file_reads_other_formats_whole() { + let dir = TempDir::new("other"); + let doc = photocraft_doc::Document::new("x", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let png = photocraft_io::export(&doc, "x.png", &Default::default()).unwrap().bytes; + let path = dir.write("x.png", &png); + let r = open("x.png", &path).unwrap(); + assert_eq!(r.document.size, doc.size); +} + +#[test] +fn import_file_fails_cleanly() { + let dir = TempDir::new("fail"); + assert!(open("missing.psd", &dir.0.join("missing.psd")).is_err()); + let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Rle).to_bytes().unwrap(); + // Cut inside the layer records, inside the channel data, and inside the merged image. + for cut in [10, 60, bytes.len() / 2, bytes.len() - 5] { + let name = format!("cut{cut}.psd"); + let path = dir.write(&name, &bytes[..cut]); + let from_bytes = import(&name, &bytes[..cut]); + let from_file = open(&name, &path); + // The merged image is not read when the layers are what opens, so a file cut inside it + // can open from the file where the strict parse of its bytes refused it. + if from_bytes.is_ok() { + assert!(from_file.is_ok(), "cut at {cut}"); + } + } +} + +#[test] +fn a_cancelled_import_file_reports_cancelled() { + let dir = TempDir::new("cancel"); + let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap(); + let path = dir.write("c.psd", &bytes); + let cancel = || true; + let ctl = Interrupt::cancel_only(&cancel); + assert!(matches!(import_file("c.psd", &path, &photocraft_io::ImportOptions::default(), &ctl), Err(photocraft_io::IoError::Cancelled))); +} + +/// A read that fails while the layers are decoded from the file (it is truncated or rewritten, +/// its drive goes away) fails the open: no layer is left empty for a save to lose. +#[test] +fn a_read_failing_while_layers_decode_fails_the_open() { + use photocraft_psd::ReadAt; + /// The file's bytes, failing every read of channel data (as a dropped network share or a + /// truncated file would) except the 2-byte compression fields the parse reads. + struct Failing { + bytes: Vec, + data: Vec<(u64, u64)>, + } + impl ReadAt for Failing { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + let end = offset + buf.len() as u64; + if self.data.iter().any(|&(a, b)| offset < b && end > a) { + return Err(photocraft_psd::PsdError::Read("the drive went away".into())); + } + self.bytes.as_slice().read_at(offset, buf) + } + } + for c in [photocraft_psd::Compression::Rle, photocraft_psd::Compression::Raw, photocraft_psd::Compression::Zip] { + let file = testgen::layered(photocraft_psd::Version::Psd, photocraft_psd::ColorMode::Rgb, 8, c); + let bytes = file.to_bytes().unwrap(); + let lazy = photocraft_psd::PsdFile::from_source(photocraft_psd::Source::new(bytes.clone())).unwrap(); + let data: Vec<(u64, u64)> = lazy + .layers() + .iter() + .flat_map(|l| &l.channels) + .filter_map(|ch| ch.stored.as_ref()) + .filter(|s| s.len > 0) + .map(|s| (s.offset, s.offset + s.len)) + .collect(); + assert!(!data.is_empty()); + // Opening the same file whole succeeds: only the failed reads fail the open. + assert!(import("x.psd", &bytes).is_ok()); + let r = photocraft_io::import_source_for_open_with("x.psd", photocraft_psd::Source::new(Failing { bytes, data }), &Interrupt::NONE); + match r { + Err(photocraft_io::IoError::Read(msg)) => assert!(msg.contains("the drive went away"), "{c:?}: {msg}"), + r => panic!("{c:?}: the open didn't fail: {:?}", r.map(|(r, damaged)| (r.warnings, damaged))), + } + } +} diff --git a/crates/io/tests/it/psd_structure.rs b/crates/io/tests/it/psd_structure.rs index a110fbd367..e263f83a6b 100644 --- a/crates/io/tests/it/psd_structure.rs +++ b/crates/io/tests/it/psd_structure.rs @@ -658,7 +658,7 @@ fn fill_layer_keeps_photoshop_pixels() { VersionedDescriptor::new(Descriptor::new("null").with("Clr ", Value::Descriptor(c))).to_bytes() }; // Photoshop-rendered pixels deliberately differ from the parametric fill. - let plane = |v: u8| ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![v; 4] }; + let plane = |v: u8| ChannelData::new(0, Some(Compression::Raw), vec![v; 4]); let mut chans = vec![plane(255), plane(10), plane(20), plane(30)]; for (i, c) in chans.iter_mut().enumerate() { c.id = i as i16 - 1; @@ -762,7 +762,7 @@ fn merged_composite_unmattes_photoshop_white() { let mut f = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1); f.header.channels = 4; // straight red at alpha 0.5, matted: r = 1, g = b = 0.5 - f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: vec![255, 128, 128, 128] }; + f.image_data = photocraft_psd::ImageData::new(Compression::Raw, vec![255, 128, 128, 128]); let m = merged_composite(&f).unwrap(); assert!((m[0][0] - 1.0).abs() < 0.01 && m[0][1] < 0.01 && m[0][2] < 0.01, "{:?}", m[0]); let (d, _) = psd_to_document(&f); @@ -772,8 +772,7 @@ fn merged_composite_unmattes_photoshop_white() { // HDR and negative straight samples must survive the actual F32 PSD import boundary. let mut hdr = testgen::merged_only(Version::Psd, ColorMode::Rgb, 32, Compression::Raw, 1, 1); hdr.header.channels = 4; - hdr.image_data = - photocraft_psd::ImageData { compression: Compression::Raw, data: [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect() }; + hdr.image_data = photocraft_psd::ImageData::new(Compression::Raw, [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect()); assert_eq!(merged_composite(&hdr).unwrap(), vec![[2.0, -0.5, 0.0, 0.5]]); let mut deep = testgen::merged_only(Version::Psd, ColorMode::Rgb, 16, Compression::Raw, 1, 1); deep.header.channels = 4; @@ -793,7 +792,7 @@ fn vector_rendered_mask_not_doubled_on_shapes() { f.layers_mut().push(LayerRecord { name: b"shape".to_vec(), mask: photocraft_psd::MaskData::Mask(mask), - channels: vec![photocraft_psd::ChannelData { id: -2, compression: Some(Compression::Raw), data: vec![] }], + channels: vec![photocraft_psd::ChannelData::new(-2, Some(Compression::Raw), vec![])], blocks: vec![TaggedBlock::unicode_name("shape"), TaggedBlock::new(*b"SoCo", vec![]), TaggedBlock::new(*b"vmsk", vec![0; 8])], ..Default::default() }); @@ -805,7 +804,7 @@ fn vector_rendered_mask_not_doubled_on_shapes() { let record = f.layers_mut().last_mut().unwrap(); let photocraft_psd::MaskData::Mask(mask) = &mut record.mask else { panic!("fixture has a mask") }; mask.real = Some(photocraft_psd::RealMask { flags: 0, background: 255, rect: photocraft_psd::Rect { top: 0, left: 0, bottom: 1, right: 1 } }); - record.channels.push(photocraft_psd::ChannelData { id: -3, compression: Some(Compression::Raw), data: vec![64] }); + record.channels.push(photocraft_psd::ChannelData::new(-3, Some(Compression::Raw), vec![64])); let (imported, _) = psd_to_document(&f); assert_eq!(imported.layers.last().unwrap().content.kind_name(), "Shape"); let mask = imported.layers.last().unwrap().mask.as_ref().expect("selected real mask must survive synthetic cleanup"); diff --git a/crates/io/tests/it/psd_unknown_adjustment.rs b/crates/io/tests/it/psd_unknown_adjustment.rs index 8b1f0cbdd3..58bc909c57 100644 --- a/crates/io/tests/it/psd_unknown_adjustment.rs +++ b/crates/io/tests/it/psd_unknown_adjustment.rs @@ -77,7 +77,7 @@ fn pixel_layers_with_unknown_blocks_stay_pixel_layers() { // A normal pixel layer (pixels, flag clear) carrying an unknown block. f.layers_mut()[0].blocks.push(extra()); // Flagged but with pixels: never dropped for an adjustment. - let plane = |id: i16| ChannelData { id, compression: Some(Compression::Raw), data: vec![200; 4] }; + let plane = |id: i16| ChannelData::new(id, Some(Compression::Raw), vec![200; 4]); let mut painted = adjustment_record("painted", vec![extra()]); painted.rect = Rect::from_xywh(0, 0, 2, 2); painted.channels = (-1..3).map(plane).collect(); diff --git a/crates/psd/README.md b/crates/psd/README.md index 421d706ab7..71d12e9f12 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -13,6 +13,7 @@ A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB | `PsdFile::from_bytes(b)?.to_bytes()? == b` for unmodified files | Channel data keeps its original encoding. Unknown blocks and resources are stored raw. Exact padding is recorded wherever it can vary: tagged blocks, layer info, section trailers. | | `from_bytes(to_bytes(f)) == f` for any model `f` | Canonical defaults: `padding: None` means "zero-pad to even", and the parser yields `None` whenever the file used that default. | | Lazy decoding | The parser only copies encoded bytes. Channels are decoded when asked (`ChannelData::decode`, `ImageData::decode`). | +| Lazy reading | `PsdFile::from_source` reads only the structure. Channel data and the merged image stay in the source as `Stored` ranges and are read when decoded, so opening a 2 GB file doesn't need 2 GB for the file itself. The model equals what `from_bytes` builds, and it writes back the same bytes. | | No compositing | `PsdBuilder` takes the merged image from the caller. Without one, it writes a white placeholder and sets `has_real_merged_data = false` in resource 1057. | ## Public API (overview) @@ -22,6 +23,8 @@ A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB PsdFile::from_bytes(&[u8]) -> Result PsdFile::from_bytes_and_merged(&[u8], want) -> Result<(PsdFile, Option>>)> // + decode_merged() when want(&file): ZIP inflated once +PsdFile::from_source(Source) -> Result // channel data and merged image left in the source +PsdFile::from_source_and_merged_recovering(Source, want, recover) PsdFile::to_bytes(&self) -> Result> PsdFile::open(path) / save(path) // native only PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement, @@ -36,6 +39,11 @@ PsdFile::composite_rgba8() -> Result PsdFile::resource(id), global_block(key), icc_profile(), resolution(), has_real_merged_data(), merged_has_alpha(), validate() +// Sources (lazy reading) +trait ReadAt { len(), read_at(offset, buf) } // [u8], Vec, Arc, FileSource (pread / seek_read) +Source::new(impl ReadAt) / read_vec(offset, len) // shared handle; equal when the same source +Stored { source, offset, len }::read() / read_part(at, len) + // Header Header { version: Version::{Psd,Psb}, channels, width, height, depth, color_mode, reserved } ColorMode::{Bitmap, Grayscale, Indexed, Rgb, Cmyk, Multichannel, Duotone, Lab, Unknown(u16)} @@ -47,7 +55,8 @@ LayerRecord { rect, channels: Vec, blend_mode, opacity, clipping, f LayerRecord::name() // prefers `luni` LayerRecord::section_divider(), section_type(), layer_id(), fill_opacity(), is_visible(), block(key), block_mut(key), channel(id), channel_rect(id), decode_channel(id, depth, version) -ChannelData { id, compression: Option, data } // encoded bytes kept verbatim +ChannelData { id, compression: Option, data, stored: Option } // encoded bytes kept verbatim +ChannelData::new(id, compression, data); encoded() -> Cow<[u8]>; encoded_len(); load() ChannelData::encode(id, compression, decoded, w, h, depth, version) ChannelData::decode(w, h, depth, version); set_decoded(...) MaskData::{None, Mask(LayerMask), Raw(Vec)} diff --git a/crates/psd/examples/bench_layer_block.rs b/crates/psd/examples/bench_layer_block.rs index 4d34f9b8f3..2b48de1d28 100644 --- a/crates/psd/examples/bench_layer_block.rs +++ b/crates/psd/examples/bench_layer_block.rs @@ -11,12 +11,12 @@ fn main() -> Result<()> { let plane_bytes = 6000 * 4000 * usize::from(depth / 8); let mut layer = LayerRecord { rect: Rect::from_xywh(0, 0, 6000, 4000), name: b"RGB".to_vec(), ..Default::default() }; for id in 0..3 { - layer.channels.push(ChannelData { id, compression: Some(Compression::Raw), data: vec![0; plane_bytes] }); + layer.channels.push(ChannelData::new(id, Some(Compression::Raw), vec![0; plane_bytes])); } file.layer_info = Some(LayerInfo { merged_alpha: false, layers: vec![layer], padding: None }); file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: if depth == 16 { *b"Lr16" } else { *b"Lr32" }, padding: None }; - file.image_data = ImageData { compression: Compression::Raw, data: vec![0; plane_bytes * 3] }; + file.image_data = ImageData::new(Compression::Raw, vec![0; plane_bytes * 3]); black_box(file.to_bytes()?); let mut samples = Vec::new(); let mut size = 0; diff --git a/crates/psd/src/error.rs b/crates/psd/src/error.rs index da519e6698..a1fc1a5c98 100644 --- a/crates/psd/src/error.rs +++ b/crates/psd/src/error.rs @@ -37,6 +37,9 @@ pub enum PsdError { /// A compressed stream could not be decoded. #[error("decompression failed: {0}")] Decompress(String), + /// Reading from a [`crate::source::ReadAt`] source failed. + #[error("read failed: {0}")] + Read(String), /// An operation is not supported for this data (e.g. unknown compression). #[error("unsupported: {0}")] Unsupported(String), diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs index fab262732b..fe1bb0fda0 100644 --- a/crates/psd/src/file.rs +++ b/crates/psd/src/file.rs @@ -174,14 +174,27 @@ impl PsdFile { layer_mask_trailing = s.peek_rest().to_vec(); } } - let image_data = ImageData { compression: Compression::Raw, data: Vec::new() }; + let image_data = ImageData::new(Compression::Raw, Vec::new()); let mut file = PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement, global_layer_mask, global_blocks, layer_mask_trailing, image_data }; + let want = want(&file); + let merged = file.read_merged_section(&mut r, want, recover)?; + Ok((file, merged)) + } + + /// Reads the merged image section from `rest` (the bytes after the layer and mask section) as + /// [`Self::from_bytes_and_merged_recovering`] does, decoding it. + pub(crate) fn read_merged_recovering(&mut self, rest: &[u8], recover: impl FnOnce(&PsdFile) -> bool) -> Result>>> { + self.read_merged_section(&mut Reader::new(rest), true, recover) + } + + fn read_merged_section(&mut self, r: &mut Reader<'_>, want: bool, recover: impl FnOnce(&PsdFile) -> bool) -> Result>>> { + let file = self; let mut encoded = r.clone(); - let merged = if want(&file) { - file.read_merged_decoded(&mut r).map(Some) + let merged = if want { + file.read_merged_decoded(r).map(Some) } else { - ImageData::read(&mut r, &file.header).map(|image| { + ImageData::read(r, &file.header).map(|image| { file.image_data = image; None }) @@ -189,7 +202,7 @@ impl PsdFile { let merged = match merged { Ok(merged) => merged, Err(error) => { - if matches!(error, PsdError::LimitExceeded(_)) || !recover(&file) { + if matches!(error, PsdError::LimitExceeded(_)) || !recover(file) { return Err(error); } let compression = Compression::from_u16(encoded.u16()?); @@ -197,11 +210,11 @@ impl PsdFile { let mut data = Vec::new(); data.try_reserve_exact(source.len()).map_err(|_| PsdError::LimitExceeded("not enough memory to retain the damaged merged image"))?; data.extend_from_slice(source); - file.image_data = ImageData { compression, data }; + file.image_data = ImageData::new(compression, data); Some(Err(error)) } }; - Ok((file, merged)) + Ok(merged) } /// Reads the merged image into `self.image_data` and decodes it. A ZIP stream within the @@ -224,7 +237,7 @@ impl PsdFile { if decoded.is_err() { validate_planes(compression, data, &layout)?; } - self.image_data = ImageData { compression, data: data.to_vec() }; + self.image_data = ImageData::new(compression, data.to_vec()); r.skip(data.len())?; Ok(decoded) } @@ -235,7 +248,11 @@ impl PsdFile { let psb = v.is_psb(); // Reserve the pixel data up front: appending it to an empty Vec reallocates and copies // repeatedly. Everything else (headers, resources, records) is small by comparison. - let hint = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len).saturating_add(self.image_data.data.len()); + let hint = self + .layer_info + .as_ref() + .map_or(0, LayerInfo::channel_data_len) + .saturating_add(usize::try_from(self.image_data.encoded_len()).unwrap_or(usize::MAX)); let mut out = Vec::new(); out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?; self.header.write(&mut out); @@ -289,7 +306,7 @@ impl PsdFile { out.end_len(at, psb)?; out.put_u16(self.image_data.compression.as_u16()); - out.put(&self.image_data.data); + out.put(&self.image_data.encoded()?); Ok(out) } diff --git a/crates/psd/src/image_data.rs b/crates/psd/src/image_data.rs index 864486b4ac..9e27af2917 100644 --- a/crates/psd/src/image_data.rs +++ b/crates/psd/src/image_data.rs @@ -1,13 +1,20 @@ //! Merged (composite) image data section. +use std::borrow::Cow; + use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, validate_planes}; use crate::error::Result; use crate::header::Header; use crate::io::Reader; +use crate::source::Stored; /// The merged image: compression plus the encoded bytes of all channels /// (to the end of the file), kept verbatim. -#[derive(Debug, Clone, PartialEq, Eq)] +/// +/// As with [`crate::ChannelData`], a file parsed by +/// [`PsdFile::from_source`](crate::PsdFile::from_source) may leave the bytes in the source +/// (`stored`, with `data` empty); equality compares the bytes wherever they are. +#[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ImageData { /// Compression method for the whole image. @@ -15,9 +22,50 @@ pub struct ImageData { /// Encoded data. For RLE: the byte-count table for every row of every /// channel followed by the rows. pub data: Vec, + /// Where the encoded bytes are when they were left in the source. (Not serialized.) + #[cfg_attr(feature = "serde", serde(skip))] + pub stored: Option, } +impl PartialEq for ImageData { + fn eq(&self, other: &Self) -> bool { + if self.compression != other.compression || self.encoded_len() != other.encoded_len() { + return false; + } + match (self.encoded(), other.encoded()) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } + } +} + +impl Eq for ImageData {} + impl ImageData { + /// A merged image whose encoded bytes are in memory. + pub fn new(compression: Compression, data: Vec) -> Self { + ImageData { compression, data, stored: None } + } + + /// The encoded bytes: borrowed from `data`, or read from the source. + pub fn encoded(&self) -> Result> { + crate::source::encoded(&self.data, self.stored.as_ref()) + } + + /// Number of encoded bytes, wherever they are. + pub fn encoded_len(&self) -> u64 { + self.stored.as_ref().map_or(self.data.len() as u64, |s| s.len) + } + + /// Reads bytes left in the source into `data`. + pub fn load(&mut self) -> Result<()> { + if let Some(s) = &self.stored { + self.data = s.read()?; + self.stored = None; + } + Ok(()) + } + /// Plane layout for the merged image described by `header`. pub fn layout(header: &Header) -> PlaneLayout { PlaneLayout { @@ -31,12 +79,12 @@ impl ImageData { /// Encodes planar data (`channels × height × row_bytes`). pub fn encode(compression: Compression, decoded: &[u8], header: &Header) -> Result { - Ok(ImageData { compression, data: encode_planes(compression, decoded, &Self::layout(header))? }) + Ok(ImageData::new(compression, encode_planes(compression, decoded, &Self::layout(header))?)) } /// Decodes all channels into planar big-endian samples. pub fn decode(&self, header: &Header) -> Result> { - decode_planes(self.compression, &self.data, &Self::layout(header)) + decode_planes(self.compression, &self.encoded()?, &Self::layout(header)) } pub(crate) fn read(r: &mut Reader<'_>, header: &Header) -> Result { @@ -45,6 +93,6 @@ impl ImageData { validate_planes(compression, data, &Self::layout(header))?; let data = data.to_vec(); r.skip(data.len())?; - Ok(ImageData { compression, data }) + Ok(ImageData::new(compression, data)) } } diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index 5b11411dfb..407a92233d 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -1,10 +1,13 @@ //! Layer records, layer masks, blending ranges and per-layer channel data. +use std::borrow::Cow; + use crate::blend::BlendMode; use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; use crate::error::{PsdError, Result}; use crate::header::{MAX_DIMENSION, Version}; use crate::io::{Reader, WriteExt, decode_legacy_name, read_pascal, write_pascal}; +use crate::source::Stored; use crate::tagged::{BlockData, SectionDivider, SectionType, TaggedBlock, read_blocks, uses_long_length, write_blocks}; /// Channel id of the transparency mask. @@ -368,7 +371,12 @@ impl BlendingRanges { } /// Encoded image data for one layer channel. -#[derive(Debug, Clone, PartialEq, Eq)] +/// +/// The encoded bytes are in `data`, or, for a file parsed by +/// [`PsdFile::from_source`](crate::PsdFile::from_source), still in the source at `stored` (and +/// `data` is empty). Every method here reads them from wherever they are; two channels are equal +/// when their bytes are, wherever each one keeps them. +#[derive(Debug, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ChannelData { /// Channel id: 0.. color channels, -1 transparency, -2 user mask, @@ -377,22 +385,65 @@ pub struct ChannelData { /// Compression; `None` when the stored length was 0 (no compression /// field at all). pub compression: Option, - /// Encoded bytes following the compression field, kept verbatim. + /// Encoded bytes following the compression field, kept verbatim (empty while `stored`). pub data: Vec, + /// Where the encoded bytes are when they were left in the source: see [`Self::load`]. + /// (Not serialized: load the channel first.) + #[cfg_attr(feature = "serde", serde(skip))] + pub stored: Option, } +impl PartialEq for ChannelData { + fn eq(&self, other: &Self) -> bool { + if self.id != other.id || self.compression != other.compression || self.encoded_len() != other.encoded_len() { + return false; + } + match (self.encoded(), other.encoded()) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } + } +} + +impl Eq for ChannelData {} + impl ChannelData { /// Encodes planar samples (`height × row_bytes`). pub fn encode(id: i16, compression: Compression, decoded: &[u8], width: usize, height: usize, depth: u16, version: Version) -> Result { let layout = PlaneLayout { planes: 1, width, height, depth, version }; - Ok(ChannelData { id, compression: Some(compression), data: encode_planes(compression, decoded, &layout)? }) + Ok(ChannelData::new(id, Some(compression), encode_planes(compression, decoded, &layout)?)) + } + + /// A channel whose encoded bytes are in memory. + pub fn new(id: i16, compression: Option, data: Vec) -> Self { + ChannelData { id, compression, data, stored: None } + } + + /// The encoded bytes (after the compression field): borrowed from `data`, or read from the + /// source when they were left there. + pub fn encoded(&self) -> Result> { + crate::source::encoded(&self.data, self.stored.as_ref()) + } + + /// Number of encoded bytes, wherever they are. + pub fn encoded_len(&self) -> u64 { + self.stored.as_ref().map_or(self.data.len() as u64, |s| s.len) + } + + /// Reads bytes left in the source into `data`, so the channel no longer needs its source. + pub fn load(&mut self) -> Result<()> { + if let Some(s) = &self.stored { + self.data = s.read()?; + self.stored = None; + } + Ok(()) } /// Decodes into planar big-endian samples. pub fn decode(&self, width: usize, height: usize, depth: u16, version: Version) -> Result> { let layout = PlaneLayout { planes: 1, width, height, depth, version }; match self.compression { - Some(c) => decode_planes(c, &self.data, &layout), + Some(c) => decode_planes(c, &self.encoded()?, &layout), None => { if layout.decoded_len()? == 0 { Ok(Vec::new()) @@ -412,7 +463,7 @@ impl ChannelData { fn stored_len(&self) -> u64 { match self.compression { - Some(_) => 2 + self.data.len() as u64, + Some(_) => 2 + self.encoded_len(), None => 0, } } @@ -556,7 +607,7 @@ impl LayerRecord { ch.decode(w, h, depth, version) } - fn read(r: &mut Reader<'_>, version: Version) -> Result<(Self, Vec)> { + pub(crate) fn read(r: &mut Reader<'_>, version: Version) -> Result<(Self, Vec)> { let rect = Rect::read(r)?; let nch = r.u16()?; if nch > MAX_LAYER_CHANNELS { @@ -567,7 +618,7 @@ impl LayerRecord { for _ in 0..nch { let id = r.i16()?; let len = r.len_field(version.is_psb())?; - channels.push(ChannelData { id, compression: None, data: Vec::new() }); + channels.push(ChannelData::new(id, None, Vec::new())); lens.push(len); } let sig = r.array::<4>()?; @@ -716,7 +767,7 @@ impl LayerInfo { n = n.saturating_add(l.encoded_len(version)?); } for c in self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()) { - n = n.saturating_add(2).saturating_add(c.data.len() as u64); + n = n.saturating_add(2).saturating_add(c.encoded_len()); } Ok(n) } @@ -740,7 +791,11 @@ impl LayerInfo { /// Bytes of channel data and their compression fields: the part of the body worth reserving up /// front (the records are small next to the pixels). Saturates instead of overflowing. pub(crate) fn channel_data_len(&self) -> usize { - self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()).fold(0usize, |n, c| n.saturating_add(2).saturating_add(c.data.len())) + self.layers + .iter() + .flat_map(|l| &l.channels) + .filter(|c| c.compression.is_some()) + .fold(0usize, |n, c| n.saturating_add(2).saturating_add(usize::try_from(c.encoded_len()).unwrap_or(usize::MAX))) } /// Serializes the body without any trailing padding (the padding field is ignored). @@ -754,7 +809,7 @@ impl LayerInfo { for c in &l.channels { if let Some(comp) = c.compression { out.put_u16(comp.as_u16()); - out.put(&c.data); + out.put(&c.encoded()?); } } } @@ -835,7 +890,7 @@ mod tests { #[test] fn psb_channel_lengths_are_8_bytes() { let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![] }); + rec.channels.push(ChannelData::new(0, Some(Compression::Raw), vec![])); let info = LayerInfo { layers: vec![rec], ..Default::default() }; let psd = rt(&info, Version::Psd); let psb = rt(&info, Version::Psb); @@ -1075,7 +1130,7 @@ mod tests { #[test] fn zero_length_channel() { let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: None, data: vec![] }); + rec.channels.push(ChannelData::new(0, None, vec![])); let info = LayerInfo { layers: vec![rec], ..Default::default() }; rt(&info, Version::Psd); assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); diff --git a/crates/psd/src/lazy.rs b/crates/psd/src/lazy.rs new file mode 100644 index 0000000000..d22661abb5 --- /dev/null +++ b/crates/psd/src/lazy.rs @@ -0,0 +1,378 @@ +//! Parsing from a [`Source`] without reading the whole file: [`PsdFile::from_source`]. +//! +//! The structure (header, resources, layer records, global blocks) is read into memory as +//! [`PsdFile::from_bytes`] would hold it. The bulk of a layered file is left in the source: every +//! channel's encoded bytes and the merged image become [`Stored`] ranges, read when they are +//! decoded. Apart from those ranges, the model is the one `from_bytes` builds from the same bytes +//! (the parse tests hold the two to that), with one difference: a merged image the caller does +//! not ask for is not read, so it is not checked either. + +use crate::compression::Compression; +use crate::error::{PsdError, Result}; +use crate::file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; +use crate::header::{Header, Version}; +use crate::image_data::ImageData; +use crate::io::Reader; +use crate::layer::{LayerInfo, LayerRecord}; +use crate::resources::ImageResource; +use crate::source::{Source, Stored}; +use crate::tagged::{TaggedBlock, is_sig, uses_long_length}; + +/// Bytes read per attempt at the layer records; doubled until they all fit. (Small in tests, so +/// they grow it.) +const RECORDS_CHUNK: u64 = if cfg!(test) { 64 } else { 1 << 20 }; + +/// A bounds-checked cursor over `start..end` of a source. +struct Cursor<'a> { + src: &'a Source, + pos: u64, + end: u64, +} + +impl<'a> Cursor<'a> { + fn new(src: &'a Source) -> Self { + Cursor { src, pos: 0, end: src.get().len() } + } + + fn remaining(&self) -> u64 { + self.end.saturating_sub(self.pos) + } + + fn is_empty(&self) -> bool { + self.remaining() == 0 + } + + fn eof(&self, needed: u64) -> PsdError { + PsdError::UnexpectedEof { + offset: usize::try_from(self.pos).unwrap_or(usize::MAX), + needed: usize::try_from(needed.saturating_sub(self.remaining())).unwrap_or(usize::MAX), + } + } + + fn need(&self, n: u64) -> Result<()> { + if n > self.remaining() { Err(self.eof(n)) } else { Ok(()) } + } + + /// Reads `n` bytes. + fn bytes(&mut self, n: u64) -> Result> { + self.need(n)?; + let v = self.src.read_vec(self.pos, n)?; + self.pos += n; + Ok(v) + } + + /// Up to `n` bytes from the current position, without consuming. + fn peek(&self, n: u64) -> Result> { + self.src.read_vec(self.pos, n.min(self.remaining())) + } + + fn array(&mut self) -> Result<[u8; N]> { + self.need(N as u64)?; + let mut b = [0u8; N]; + self.src.get().read_at(self.pos, &mut b)?; + self.pos += N as u64; + Ok(b) + } + + fn u16(&mut self) -> Result { + self.array().map(u16::from_be_bytes) + } + + fn i16(&mut self) -> Result { + self.array().map(i16::from_be_bytes) + } + + fn u32(&mut self) -> Result { + self.array().map(u32::from_be_bytes) + } + + fn len_field(&mut self, long: bool) -> Result { + if long { self.array().map(u64::from_be_bytes) } else { self.u32().map(u64::from) } + } + + /// The next `n` bytes as a cursor of their own; this one moves past them. + fn sub(&mut self, n: u64) -> Result> { + self.need(n)?; + let sub = Cursor { src: self.src, pos: self.pos, end: self.pos + n }; + self.pos += n; + Ok(sub) + } + + fn skip(&mut self, n: u64) -> Result<()> { + self.need(n)?; + self.pos += n; + Ok(()) + } + + fn rest(&mut self) -> Result> { + self.bytes(self.remaining()) + } + + /// The rest as a stored range; the cursor moves to the end. + fn stored_rest(&mut self) -> Stored { + let s = Stored { source: self.src.clone(), offset: self.pos, len: self.remaining() }; + self.pos = self.end; + s + } +} + +impl PsdFile { + /// Parses a file from `source`, leaving channel data and the merged image in it: see + /// [`crate::source`]. Decoding a channel then reads its bytes from the source, which must + /// stay unchanged while the model is in use. + pub fn from_source(source: Source) -> Result { + Self::from_source_and_merged_recovering(source, |_| false, |_| false).map(|(file, _)| file) + } + + /// [`Self::from_bytes_and_merged_recovering`] for a [`Source`]: the merged image is read only + /// when `want` asks for it (and is then decoded as there, with the same recovery); otherwise + /// it stays in the source, unread and unchecked. + pub fn from_source_and_merged_recovering( + source: Source, + want: impl FnOnce(&PsdFile) -> bool, + recover: impl FnOnce(&PsdFile) -> bool, + ) -> Result<(Self, Option>>)> { + let mut c = Cursor::new(&source); + let header = Header::read(&mut Reader::new(&c.bytes(26)?))?; + let version = header.version; + let psb = version.is_psb(); + let cmd_len = c.u32()?; + let color_mode_data = c.bytes(u64::from(cmd_len))?; + let res_len = c.u32()?; + let res = c.bytes(u64::from(res_len))?; + let mut rr = Reader::new(&res); + let mut resources = Vec::new(); + while !rr.is_empty() { + resources.push(ImageResource::read(&mut rr)?); + } + + let lm_len = c.len_field(psb)?; + let mut s = c.sub(lm_len)?; + let mut layer_info = None; + let mut global_layer_mask = None; + let mut global_blocks = Vec::new(); + let mut layer_mask_trailing = Vec::new(); + let mut layer_info_placement = LayerInfoPlacement::Section; + if !s.is_empty() { + let li_len = s.len_field(psb)?; + if li_len > 0 { + layer_info = Some(read_layer_info(s.sub(li_len)?, version)?); + } + if s.remaining() >= 4 { + let n = s.u32()?; + global_layer_mask = Some(GlobalLayerMask { data: s.bytes(u64::from(n))? }); + let target_key = match header.depth { + 16 => Some(b"Lr16"), + 32 => Some(b"Lr32"), + _ => None, + }; + let mut candidate_seen = match target_key { + Some(_) => false, + None => layer_info.as_ref().is_some_and(|i: &LayerInfo| !i.layers.is_empty()), + }; + let trailing = read_blocks( + &mut s, + version, + |index, signature, key, data, padding| { + let is_candidate = match target_key { + Some(k) => &key == k, + None => matches!(&key, b"Layr" | b"Lr16" | b"Lr32"), + }; + if candidate_seen || !is_candidate { + return Ok(None); + } + candidate_seen = true; + let Ok(info) = read_layer_info(data, version) else { + if target_key.is_some() { + layer_info = None; + } + return Ok(None); + }; + layer_info = Some(info); + layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature, key, padding: padding.clone() }; + Ok(Some(())) + }, + &mut global_blocks, + )?; + layer_mask_trailing = trailing; + } else { + layer_mask_trailing = s.rest()?; + } + } + let mut file = PsdFile { + header, + color_mode_data, + resources, + layer_info, + layer_info_placement, + global_layer_mask, + global_blocks, + layer_mask_trailing, + image_data: ImageData::new(Compression::Raw, Vec::new()), + }; + if !want(&file) { + let compression = Compression::from_u16(c.u16()?); + file.image_data = ImageData { compression, data: Vec::new(), stored: Some(c.stored_rest()) }; + return Ok((file, None)); + } + // The merged image is wanted: read it and decode it as `from_bytes` does. + let rest = c.rest()?; + let merged = file.read_merged_recovering(&rest, recover)?; + Ok((file, merged)) + } +} + +/// Reads tagged blocks as [`crate::tagged::read_blocks_with`] does, from a cursor: `consume` +/// sees each block's data as a cursor and returns `Some` when it took the block; the others are +/// read into memory and pushed to `blocks`. Returns the trailing bytes. +fn read_blocks<'a>( + r: &mut Cursor<'a>, + version: Version, + mut consume: impl FnMut(usize, [u8; 4], [u8; 4], Cursor<'a>, &Option>) -> Result>, + blocks: &mut Vec, +) -> Result> { + const ALIGNMENT: usize = 4; + loop { + let head = r.peek(12)?; + if head.len() < 12 || !is_sig(&head) { + return r.rest(); + } + let signature = r.array::<4>()?; + let key = r.array::<4>()?; + let len = r.len_field(uses_long_length(version, &key))?; + let data = r.sub(len)?; + // Padding as `read_blocks_with` detects it: the smallest k in 0..=3 such that the next + // signature (or the end of the region) follows k bytes later. + let rest = r.peek(7)?; + let mut pad = None; + for k in 0..=3usize { + if k == rest.len() || rest.get(k..).is_some_and(is_sig) { + pad = Some(k); + break; + } + } + let default = TaggedBlock::default_padding((len % ALIGNMENT as u64) as usize, ALIGNMENT); + let pad = pad.unwrap_or_else(|| if rest.get(..default).is_some_and(|p| p.iter().all(|&b| b == 0)) { default } else { 0 }); + let pad_bytes = rest.get(..pad).map(<[u8]>::to_vec).unwrap_or_default(); + r.skip(pad as u64)?; + let padding = if pad_bytes.len() == default && pad_bytes.iter().all(|&b| b == 0) { None } else { Some(pad_bytes) }; + let (start, end) = (data.pos, data.end); + if consume(blocks.len(), signature, key, data, &padding)?.is_none() { + let data = Cursor { src: r.src, pos: start, end }.rest()?; + blocks.push(TaggedBlock { signature, key, data, padding }); + } + } +} + +/// [`LayerInfo::read_body`] from a cursor over the body: the records are read into memory, and +/// each channel's encoded bytes become a [`Stored`] range after its compression field. +fn read_layer_info(mut r: Cursor<'_>, version: Version) -> Result { + let body_start = r.pos; + let count = r.i16()?; + let merged_alpha = count < 0; + let n = count.unsigned_abs(); + // Minimum record size, as `read_body` checks it. + if u64::from(n) * 34 > r.remaining() { + return Err(r.eof(u64::from(n) * 34)); + } + // The records' total size is only known once they are parsed: read a chunk and grow it until + // they all fit (or the body is exhausted, when their error is the body's). + let mut chunk = RECORDS_CHUNK.min(r.remaining()); + let (layers, all_lens, used) = loop { + let buf = r.peek(chunk)?; + let mut rr = Reader::new(&buf); + let mut layers = Vec::with_capacity(usize::from(n)); + let mut all_lens = Vec::with_capacity(usize::from(n)); + let parsed = (0..n).try_for_each(|_| { + let (rec, lens) = LayerRecord::read(&mut rr, version)?; + layers.push(rec); + all_lens.push(lens); + Ok::<_, PsdError>(()) + }); + match parsed { + Ok(()) => break (layers, all_lens, rr.pos() as u64), + Err(PsdError::UnexpectedEof { .. }) if chunk < r.remaining() => chunk = chunk.saturating_mul(2).min(r.remaining()), + Err(e) => return Err(e), + } + }; + r.skip(used)?; + let mut layers = layers; + for (rec, lens) in layers.iter_mut().zip(all_lens) { + for (ch, len) in rec.channels.iter_mut().zip(lens) { + if len == 0 { + continue; + } + if len == 1 { + return Err(PsdError::invalid("channel data length 1")); + } + ch.compression = Some(Compression::from_u16(r.u16()?)); + let data = r.sub(len - 2)?; + ch.stored = Some(Stored { source: data.src.clone(), offset: data.pos, len: data.remaining() }); + } + } + let body_len = r.pos - body_start; + let rest = r.rest()?; + let padding = if rest.len() as u64 == body_len % 2 && rest.iter().all(|&b| b == 0) { None } else { Some(rest) }; + Ok(LayerInfo { merged_alpha, layers, padding }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testgen; + + /// Every generated file, plus the layered 16/32-bit ones with their layers in a global block. + fn samples() -> Vec> { + let mut v = Vec::new(); + for case in testgen::all_cases() { + let mut file = case.file; + v.push(file.to_bytes().unwrap()); + let key = match file.header.depth { + 16 => *b"Lr16", + 32 => *b"Lr32", + _ => continue, + }; + if file.layer_info.as_ref().is_some_and(|i| !i.layers.is_empty()) { + file.global_layer_mask.get_or_insert_with(GlobalLayerMask::default); + file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key, padding: None }; + v.push(file.to_bytes().unwrap()); + } + } + v + } + + fn same(bytes: Vec) { + let eager = PsdFile::from_bytes(&bytes).unwrap(); + let lazy = PsdFile::from_source(Source::new(bytes.clone())).unwrap(); + assert_eq!(lazy, eager); + assert_eq!(lazy.to_bytes().unwrap(), bytes); + assert!(lazy.layers().iter().flat_map(|l| &l.channels).all(|c| c.data.is_empty())); + assert!(lazy.image_data.data.is_empty() && lazy.image_data.stored.is_some()); + } + + #[test] + fn lazy_parse_matches_the_eager_one() { + for bytes in samples() { + same(bytes); + } + } + + #[test] + fn lazy_parse_fails_where_the_eager_one_does() { + for bytes in samples() { + for cut in [1, 2, 7, 26, 40, bytes.len() / 3, bytes.len() / 2, bytes.len() - 3] { + let Some(b) = bytes.get(..cut) else { continue }; + let eager = PsdFile::from_bytes(b); + let lazy = PsdFile::from_source(Source::new(b.to_vec())); + // A truncated merged image is only noticed when it is read. + match eager { + Ok(eager) => assert_eq!(lazy.unwrap(), eager, "cut at {cut}"), + Err(e) => { + let records_ok = PsdFile::from_bytes_and_merged_recovering(b, |_| false, |_| true).is_ok(); + assert!(lazy.is_err() || records_ok, "cut at {cut}: eager {e:?}"); + } + } + } + } + } +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 5248456d52..f5ffbed8b7 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -61,13 +61,16 @@ pub mod header; pub mod image_data; mod io; pub mod layer; +mod lazy; pub mod metadata; pub mod path; pub mod patterns; pub mod pixels; pub mod resources; +pub mod rows; pub mod shc; pub mod slices; +pub mod source; pub mod tagged; #[cfg(any(test, feature = "testgen"))] // Test-data generator (tests and fuzz seeds only): failing loudly is the point. @@ -87,5 +90,9 @@ pub use image_data::ImageData; pub use layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask, LayerRecord, MaskData, MaskParameters, RealMask, Rect}; pub use pixels::{GrayImage, Layer, RgbaImage}; pub use resources::{ImageResource, ResolutionInfo, ResourceData}; +pub use rows::RowDecoder; +#[cfg(any(unix, windows))] +pub use source::FileSource; +pub use source::{ReadAt, Source, Stored}; pub use tagged::{BlockData, SectionDivider, SectionType, TaggedBlock}; pub use tree::LayerNode; diff --git a/crates/psd/src/rows.rs b/crates/psd/src/rows.rs new file mode 100644 index 0000000000..6413c801df --- /dev/null +++ b/crates/psd/src/rows.rs @@ -0,0 +1,234 @@ +//! Decoding a channel a band of rows at a time: [`ChannelData::row_decoder`]. +//! +//! [`ChannelData::decode`] returns the whole plane, so turning a layer into tiles holds every +//! channel's plane plus an interleaved copy at once: for a 20000×15000 RGBA layer that is 2.4 GB +//! on top of the tiles. A [`RowDecoder`] hands out any band of rows instead. RLE and raw channels +//! are read band by band (a channel still in its [`Stored`](crate::Stored) source reads only the +//! band's bytes: RLE's per-row byte counts give each row's offset); ZIP streams cannot be entered +//! part way, so a ZIP channel is inflated once, when the decoder is made. + +use std::borrow::Cow; + +use crate::compression::{Compression, MAX_DECODED_BYTES, PlaneLayout, decode_planes, packbits}; +use crate::error::{PsdError, Result}; +use crate::header::Version; +use crate::layer::ChannelData; +use crate::source::Stored; + +/// Where a channel's encoded bytes are. +enum Bytes<'a> { + Memory(&'a [u8]), + Source(&'a Stored), +} + +impl Bytes<'_> { + fn len(&self) -> u64 { + match self { + Bytes::Memory(b) => b.len() as u64, + Bytes::Source(s) => s.len, + } + } + + fn get(&self, at: u64, len: u64) -> Result> { + match self { + Bytes::Memory(b) => { + let range = usize::try_from(at).ok().zip(usize::try_from(len).ok()).and_then(|(a, n)| b.get(a..a.checked_add(n)?)); + range + .map(Cow::Borrowed) + .ok_or(PsdError::UnexpectedEof { offset: usize::try_from(at).unwrap_or(usize::MAX), needed: usize::try_from(len).unwrap_or(usize::MAX) }) + } + Bytes::Source(s) => { + if at.checked_add(len).is_none_or(|end| end > s.len) { + return Err(PsdError::UnexpectedEof { + offset: usize::try_from(at).unwrap_or(usize::MAX), + needed: usize::try_from(len).unwrap_or(usize::MAX), + }); + } + s.read_part(at, len).map(Cow::Owned) + } + } + } +} + +enum Kind<'a> { + /// Rows at `row * row_bytes`. + Raw(Bytes<'a>), + /// `offsets[r]..offsets[r + 1]` are row `r`'s PackBits bytes (offsets from the start of the + /// data, after the count table). + Rle { bytes: Bytes<'a>, offsets: Vec }, + /// The whole decoded plane. + Decoded(Vec), + /// No data and no rows. + Empty, +} + +/// Decodes bands of rows of one channel: see the [module docs](self). +pub struct RowDecoder<'a> { + kind: Kind<'a>, + row_bytes: usize, + height: usize, +} + +impl ChannelData { + /// A decoder of this channel's rows, for a `width × height` plane. Fails where + /// [`Self::decode`] would on everything it can check without decoding the rows (sizes, the + /// RLE count table, the whole of a ZIP stream); a damaged row fails when its band is decoded. + pub fn row_decoder(&self, width: usize, height: usize, depth: u16, version: Version) -> Result> { + let layout = PlaneLayout { planes: 1, width, height, depth, version }; + let total = layout.decoded_len()?; + let row_bytes = layout.row_bytes(); + let bytes = match &self.stored { + Some(s) => Bytes::Source(s), + None => Bytes::Memory(&self.data), + }; + let kind = match self.compression { + None if total == 0 => Kind::Empty, + None => return Err(PsdError::invalid("channel has no data")), + Some(Compression::Raw) => { + if bytes.len() < total as u64 { + return Err(PsdError::UnexpectedEof { offset: usize::try_from(bytes.len()).unwrap_or(usize::MAX), needed: total - bytes.len() as usize }); + } + Kind::Raw(bytes) + } + Some(Compression::Rle) => { + let size: u64 = if version.is_psb() { 4 } else { 2 }; + let table_len = (height as u64).saturating_mul(size); + if table_len > bytes.len() { + return Err(PsdError::UnexpectedEof { offset: 0, needed: usize::try_from(table_len - bytes.len()).unwrap_or(usize::MAX) }); + } + let table = bytes.get(0, table_len)?; + let mut offsets = Vec::new(); + offsets.try_reserve_exact(height + 1).map_err(|_| PsdError::LimitExceeded("not enough memory for the RLE row table"))?; + let mut at = table_len; + offsets.push(at); + for c in table.chunks_exact(size as usize) { + let n = match *c { + [a, b] => u64::from(u16::from_be_bytes([a, b])), + [a, b, c, d] => u64::from(u32::from_be_bytes([a, b, c, d])), + _ => 0, + }; + at = at.saturating_add(n); + offsets.push(at); + } + let data_len = bytes.len() - table_len; + // As `decode_planes` checks: PackBits expands at most 64x. + if (total as u64) > data_len.saturating_mul(64) { + return Err(PsdError::Decompress("RLE data too short for declared size".into())); + } + if at > bytes.len() { + return Err(PsdError::UnexpectedEof { + offset: usize::try_from(bytes.len()).unwrap_or(usize::MAX), + needed: usize::try_from(at - bytes.len()).unwrap_or(usize::MAX), + }); + } + Kind::Rle { bytes, offsets } + } + Some(c) => Kind::Decoded(decode_planes(c, &self.encoded()?, &layout)?), + }; + Ok(RowDecoder { kind, row_bytes, height }) + } +} + +impl RowDecoder<'_> { + /// Bytes per decoded row. + pub fn row_bytes(&self) -> usize { + self.row_bytes + } + + /// Number of rows. + pub fn height(&self) -> usize { + self.height + } + + /// Rows `r0..r1` as planar big-endian samples (`(r1 - r0) × row_bytes` bytes). + pub fn rows(&self, r0: usize, r1: usize) -> Result> { + if r0 > r1 || r1 > self.height { + return Err(PsdError::invalid(format!("rows {r0}..{r1} outside 0..{}", self.height))); + } + let n = (r1 - r0).checked_mul(self.row_bytes).ok_or(PsdError::LimitExceeded("band size overflow"))?; + if n as u64 > MAX_DECODED_BYTES { + return Err(PsdError::LimitExceeded("decoded channel data exceeds MAX_DECODED_BYTES")); + } + let mut out = Vec::new(); + out.try_reserve_exact(n).map_err(|_| PsdError::LimitExceeded("not enough memory for the decoded channel data"))?; + match &self.kind { + Kind::Empty => {} + Kind::Raw(bytes) => out.extend_from_slice(&bytes.get((r0 * self.row_bytes) as u64, n as u64)?), + Kind::Decoded(plane) => { + out.extend_from_slice(plane.get(r0 * self.row_bytes..r1 * self.row_bytes).ok_or_else(|| PsdError::invalid("decoded plane too short"))?) + } + Kind::Rle { bytes, offsets } => { + let (Some(&start), Some(&end)) = (offsets.get(r0), offsets.get(r1)) else { + return Err(PsdError::invalid("RLE row table too short")); + }; + let band = bytes.get(start, end - start)?; + for r in r0..r1 { + let (Some(&a), Some(&b)) = (offsets.get(r), offsets.get(r + 1)) else { + return Err(PsdError::invalid("RLE row table too short")); + }; + let row = band.get((a - start) as usize..(b - start) as usize).ok_or_else(|| PsdError::invalid("RLE row outside its band"))?; + packbits::decode_into(row, self.row_bytes, &mut out)?; + } + } + } + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use crate::source::Source; + use crate::{PsdFile, testgen}; + + /// Every channel of every generated file, decoded in uneven bands from memory and from a + /// source, is its whole-plane decode. + #[test] + fn bands_join_up_to_the_whole_plane() { + let mut checked = 0; + for case in testgen::all_cases() { + let bytes = case.file.to_bytes().unwrap(); + let eager = PsdFile::from_bytes(&bytes).unwrap(); + let lazy = PsdFile::from_source(Source::new(bytes)).unwrap(); + let (d, v) = (eager.header.depth, eager.header.version); + for file in [&eager, &lazy] { + for rec in file.layers() { + for ch in &rec.channels { + let (w, h) = rec.channel_rect(ch.id).size().unwrap(); + let whole = ch.decode(w, h, d, v); + let dec = ch.row_decoder(w, h, d, v); + let (Ok(whole), Ok(dec)) = (whole, dec) else { continue }; + let mut joined = Vec::new(); + let mut r = 0; + for step in [1, 3, 2, 7].iter().cycle() { + if r >= h { + break; + } + let r1 = (r + step).min(h); + joined.extend(dec.rows(r, r1).unwrap()); + r = r1; + } + assert_eq!(joined, whole, "{}", case.name); + assert!(dec.rows(0, h + 1).is_err()); + checked += 1; + } + } + } + } + assert!(checked > 100, "{checked}"); + } + + #[test] + fn a_damaged_rle_row_fails_its_band() { + use crate::Compression; + use crate::layer::ChannelData; + // Two rows of 4 bytes: a valid row, then one that ends early. + let mut data = vec![0, 2, 0, 2]; + data.extend([0xFD, 7]); // header -3: 1 - (-3) = 4 copies of 7 + data.extend([0x01, 9]); // a literal of 2 bytes, only 1 present + let ch = ChannelData::new(0, Some(Compression::Rle), data); + let dec = ch.row_decoder(4, 2, 8, crate::Version::Psd).unwrap(); + assert_eq!(dec.rows(0, 1).unwrap(), vec![7; 4]); + assert!(dec.rows(1, 2).is_err()); + assert!(ch.decode(4, 2, 8, crate::Version::Psd).is_err()); + } +} diff --git a/crates/psd/src/source.rs b/crates/psd/src/source.rs new file mode 100644 index 0000000000..2e7c8039dd --- /dev/null +++ b/crates/psd/src/source.rs @@ -0,0 +1,270 @@ +//! Random-access byte sources, for parsing a file without reading all of it. +//! +//! [`PsdFile::from_source`](crate::PsdFile::from_source) reads the structure of a file (header, +//! resources, layer records, tagged blocks) and leaves the bulk of it, the encoded channel data +//! and the merged image, where it is: each [`ChannelData`](crate::ChannelData) records a +//! [`Stored`] range instead of a copy, and the bytes are read when the channel is decoded. A +//! 2 GB layered file then never needs 2 GB of memory just to be opened. + +use std::borrow::Cow; +use std::fmt; +use std::sync::Arc; + +use crate::error::{PsdError, Result}; + +/// Bytes that can be read at any offset, from any thread. +/// +/// Implemented for byte buffers and, on native targets, for [`std::fs::File`] (as +/// [`FileSource`]). The source must not change while a file parsed from it is in use: a +/// [`Stored`] range is an offset into it. +pub trait ReadAt: Send + Sync { + /// Total length in bytes. + fn len(&self) -> u64; + + /// `true` when the source holds no bytes. + fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Fills `buf` with the bytes at `offset..offset + buf.len()`. Fails, without a partial + /// result, when the range is not all inside the source or the read fails. + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()>; +} + +fn out_of_range(offset: u64, needed: usize, len: u64) -> PsdError { + PsdError::UnexpectedEof { + offset: usize::try_from(offset).unwrap_or(usize::MAX), + needed: needed.saturating_sub(usize::try_from(len.saturating_sub(offset)).unwrap_or(usize::MAX)), + } +} + +impl ReadAt for [u8] { + fn len(&self) -> u64 { + <[u8]>::len(self) as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + let src = usize::try_from(offset) + .ok() + .and_then(|start| self.get(start..start.checked_add(buf.len())?)) + .ok_or_else(|| out_of_range(offset, buf.len(), ReadAt::len(self)))?; + buf.copy_from_slice(src); + Ok(()) + } +} + +impl ReadAt for Vec { + fn len(&self) -> u64 { + self.as_slice().len() as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + self.as_slice().read_at(offset, buf) + } +} + +impl ReadAt for Arc { + fn len(&self) -> u64 { + (**self).len() + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + (**self).read_at(offset, buf) + } +} + +/// Largest single read from a [`FileSource`]. +#[cfg(any(unix, windows))] +const MAX_READ: usize = 64 << 20; + +/// An open file read at offsets (`pread` on Unix, `seek_read` on Windows), with its length taken +/// when it was opened. Reads from several threads at once need no lock. +#[cfg(any(unix, windows))] +#[derive(Debug)] +pub struct FileSource { + file: std::fs::File, + len: u64, +} + +#[cfg(any(unix, windows))] +impl FileSource { + /// Opens `path` for reading. + pub fn open(path: &std::path::Path) -> std::io::Result { + Self::new(std::fs::File::open(path)?) + } + + /// Wraps an open file. + pub fn new(file: std::fs::File) -> std::io::Result { + let len = file.metadata()?.len(); + Ok(FileSource { file, len }) + } + + /// The file. + pub fn file(&self) -> &std::fs::File { + &self.file + } +} + +#[cfg(any(unix, windows))] +impl ReadAt for FileSource { + fn len(&self) -> u64 { + self.len + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) { + return Err(out_of_range(offset, buf.len(), self.len)); + } + let n = buf.len(); + let failed = |e: std::io::Error| PsdError::Read(format!("reading {n} bytes at offset {offset}: {e}")); + // Bounded reads, as `photocraft-format`'s `read_file` makes them: some Windows file + // systems reject a single read of gigabytes (#375). + let mut done = 0usize; + while done < n { + let Some(rest) = buf.get_mut(done..n.min(done + MAX_READ)) else { break }; + let at = offset + done as u64; + #[cfg(unix)] + let read = { + use std::os::unix::fs::FileExt; + self.file.read_at(rest, at) + }; + #[cfg(windows)] + let read = { + use std::os::windows::fs::FileExt; + self.file.seek_read(rest, at) + }; + match read { + Ok(0) => return Err(failed(std::io::ErrorKind::UnexpectedEof.into())), + Ok(k) => done += k, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(failed(e)), + } + } + Ok(()) + } +} + +/// A shared [`ReadAt`]: what [`Stored`] ranges point into. Two handles are equal when they are +/// the same source. +#[derive(Clone)] +pub struct Source(Arc); + +impl Source { + /// Shares `source`. + pub fn new(source: impl ReadAt + 'static) -> Self { + Source(Arc::new(source)) + } + + /// Shares an already shared source. + pub fn from_arc(source: Arc) -> Self { + Source(source) + } + + /// The source. + pub fn get(&self) -> &dyn ReadAt { + &*self.0 + } + + /// Reads `len` bytes at `offset` into a new buffer. The buffer is reserved fallibly: a + /// range larger than memory is an error, not an abort. + pub fn read_vec(&self, offset: u64, len: u64) -> Result> { + let n = usize::try_from(len).map_err(|_| PsdError::LimitExceeded("length exceeds address space"))?; + if offset.checked_add(len).is_none_or(|end| end > self.0.len()) { + return Err(out_of_range(offset, n, self.0.len())); + } + let mut out = Vec::new(); + out.try_reserve_exact(n).map_err(|_| PsdError::LimitExceeded("not enough memory to read the data"))?; + out.resize(n, 0); + self.0.read_at(offset, &mut out)?; + Ok(out) + } +} + +impl fmt::Debug for Source { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Source({} bytes)", self.0.len()) + } +} + +impl PartialEq for Source { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for Source {} + +/// Encoded bytes left in their [`Source`] by a lazy parse: `len` bytes at `offset`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Stored { + /// Where the bytes are. + pub source: Source, + /// Offset of the first byte. + pub offset: u64, + /// Number of bytes. + pub len: u64, +} + +impl Stored { + /// Reads the bytes. + pub fn read(&self) -> Result> { + self.source.read_vec(self.offset, self.len) + } + + /// Reads `len` bytes starting `at` bytes into the range. + pub fn read_part(&self, at: u64, len: u64) -> Result> { + if at.checked_add(len).is_none_or(|end| end > self.len) { + return Err(PsdError::invalid("read past the end of stored data")); + } + self.source.read_vec(self.offset + at, len) + } +} + +/// The bytes of a value that is either in memory (`data`) or still in its source (`stored`). +pub(crate) fn encoded<'a>(data: &'a [u8], stored: Option<&Stored>) -> Result> { + match stored { + Some(s) => s.read().map(Cow::Owned), + None => Ok(Cow::Borrowed(data)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slice_reads_are_bounds_checked() { + let v = vec![1u8, 2, 3, 4]; + let mut b = [0u8; 2]; + v.read_at(2, &mut b).unwrap(); + assert_eq!(b, [3, 4]); + assert!(v.read_at(3, &mut b).is_err()); + assert!(v.read_at(u64::MAX, &mut b).is_err()); + let s = Source::new(v); + assert_eq!(s.read_vec(1, 2).unwrap(), vec![2, 3]); + assert!(s.read_vec(1, u64::MAX).is_err()); + let st = Stored { source: s.clone(), offset: 1, len: 3 }; + assert_eq!(st.read().unwrap(), vec![2, 3, 4]); + assert_eq!(st.read_part(1, 2).unwrap(), vec![3, 4]); + assert!(st.read_part(2, 2).is_err()); + assert_eq!(st.source, s); + assert_ne!(st.source, Source::new(vec![1u8, 2, 3, 4])); + } + + #[cfg(any(unix, windows))] + #[test] + fn file_source_reads_at_offsets() { + use std::io::Write; + let dir = std::env::temp_dir().join(format!("photocraft-psd-source-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("f.bin"); + std::fs::File::create(&path).unwrap().write_all(&[9, 8, 7, 6, 5]).unwrap(); + let f = FileSource::open(&path).unwrap(); + assert_eq!(ReadAt::len(&f), 5); + let mut b = [0u8; 3]; + f.read_at(2, &mut b).unwrap(); + assert_eq!(b, [7, 6, 5]); + assert!(f.read_at(3, &mut b).is_err()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 7728d53fd1..1574b1faab 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -160,7 +160,7 @@ impl TaggedBlock { String::from_utf8_lossy(&self.key).into_owned() } - fn default_padding(len: usize, alignment: usize) -> usize { + pub(crate) fn default_padding(len: usize, alignment: usize) -> usize { (alignment - len % alignment) % alignment } @@ -436,7 +436,7 @@ fn parse_section(d: &[u8]) -> Result { /// `8BIM` / `8B64`, or the markers `MIB8` / `46B8` that [`crate::tiff`] gives a block kept /// verbatim from a little-endian TIFF when its layout is unknown (its data is in that order). -fn is_sig(b: &[u8]) -> bool { +pub(crate) fn is_sig(b: &[u8]) -> bool { b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b) } diff --git a/crates/psd/src/testgen.rs b/crates/psd/src/testgen.rs index d2d4784cb9..5912009d41 100644 --- a/crates/psd/src/testgen.rs +++ b/crates/psd/src/testgen.rs @@ -113,7 +113,7 @@ pub fn merged_only(version: Version, mode: ColorMode, depth: u16, compression: C for c in 0..channels { planes.extend(pattern_plane(w as usize, h as usize, depth, u32::from(c))); } - let image_data = ImageData::encode(compression, &planes, &header).unwrap_or(ImageData { compression, data: Vec::new() }); + let image_data = ImageData::encode(compression, &planes, &header).unwrap_or(ImageData::new(compression, Vec::new())); PsdFile { header, color_mode_data: color_mode_data(mode), @@ -179,7 +179,7 @@ fn raster_layer(g: LayerGen<'_>) -> LayerRecord { fn group_record(header: &Header, name: &str, kind: SectionType, blend: BlendMode, id: u32) -> LayerRecord { let cc = mode_channels(header.color_mode) as i16; - let channels = (-1..cc).map(|c| ChannelData { id: c, compression: Some(Compression::Raw), data: Vec::new() }).collect(); + let channels = (-1..cc).map(|c| ChannelData::new(c, Some(Compression::Raw), Vec::new())).collect(); let lsct = if kind == SectionType::BoundingDivider { TaggedBlock::section_divider(kind, None, None) } else { diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index f3778ccbe5..c6616d86d5 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -35,6 +35,24 @@ impl fmt::Display for AllocationError { impl std::error::Error for AllocationError {} +/// One shared tile per pixel value (and tile size), for [`Surface::share_uniform_tiles`]. +#[derive(Debug, Default)] +pub struct TileInterner { + tiles: std::collections::HashMap, Arc>>, +} + +impl TileInterner { + /// Number of distinct uniform tiles held. + pub fn len(&self) -> usize { + self.tiles.values().map(|m| m.len()).sum() + } + + /// `true` when no tile is held. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + /// Pixel storage for one tile: `TILE_SIZE² × bytes_per_pixel`, row-major, interleaved channels. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Tile { @@ -415,6 +433,28 @@ impl Surface { out } + /// Makes every tile that holds one pixel value throughout share the interner's tile for that + /// value: a white background, an opaque mask or a solid fill then costs one tile however + /// large it is, and across every surface that shares `interner`. Tiles are copy-on-write, so + /// editing one splits it off again. Returns the bytes no longer held by this surface alone. + pub fn share_uniform_tiles(&mut self, interner: &mut TileInterner) -> usize { + let bpp = self.format.bytes_per_pixel(); + let mut saved = 0; + for t in self.tiles.values_mut() { + let mut px = t.data.chunks_exact(bpp); + let Some(p0) = px.next() else { continue }; + if !px.all(|p| p == p0) { + continue; + } + let shared = interner.tiles.entry(t.data.len()).or_default().entry(p0.to_vec()).or_insert_with(|| t.clone()); + if !Arc::ptr_eq(shared, t) { + saved += t.data.len(); + *t = shared.clone(); + } + } + saved + } + /// Drop tiles that are entirely the default pixel. pub fn prune(&mut self) { let dp = self.default_pixel.as_ref(); @@ -1295,6 +1335,38 @@ mod tests { seen.len() } + /// Uniform tiles written pixel by pixel end up as one shared tile per value, across + /// surfaces, with every pixel unchanged; editing one splits it off. + #[test] + fn uniform_tiles_are_shared() { + let mut interner = TileInterner::default(); + let r = Rect::new(0, 0, 1024, 600); + let mut bytes = Vec::new(); + for y in 0..600 { + for x in 0..1024 { + // White, except a gradient in the tiles of column 3. + bytes.extend(if x >= 768 { [x as u8, y as u8, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let mut a = Surface::from_interleaved(PixelFormat::RGBA8, r, &bytes); + let mut b = Surface::from_interleaved(PixelFormat::RGBA8, r, &bytes); + let before = a.to_interleaved(r); + assert_eq!(distinct_tiles(&a), 12); + // Rows 512..600 cover only part of their tiles: the rest is the default pixel, so those + // tiles are not uniform. + let saved = a.share_uniform_tiles(&mut interner); + assert_eq!(distinct_tiles(&a), 1 + 3 + 3); + assert_eq!(saved, 5 * TILE_SIZE as usize * TILE_SIZE as usize * 4); + b.share_uniform_tiles(&mut interner); + assert_eq!(interner.len(), 1); + assert!(Arc::ptr_eq(a.tile(TileCoord { tx: 0, ty: 0 }).unwrap(), b.tile(TileCoord { tx: 2, ty: 1 }).unwrap())); + assert_eq!(a.to_interleaved(r), before); + a.write_pixel(5, 5, &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(b.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]); + assert_eq!(a.pixel(5, 5), vec![0.0, 0.0, 0.0, 1.0]); + assert_eq!(a.pixel(300, 5), vec![1.0, 1.0, 1.0, 1.0]); + } + /// Converting or tone-mapping a surface keeps a shared tile shared (#4531) and gives the /// same pixels as converting each pixel: a filled background is one tile across the grid, /// plus some distinct tiles. From 3370667b39333ff2da2a3ddc9c3dff234255bb75 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 17:31:19 +0100 Subject: [PATCH 47/87] Integration: AHD scratch sized to the rows the memory check approved (#9450) Each AHD worker allocated scratch for a full 38-row band while develop's memory check budgets h.min(32) + 6 rows, so short images allocated more than was approved: a 262144 x 1 strip was budgeted ~106 MB and allocated ~580 MB (5.4x). The scratch is now sized from the same row count as the budget, and the budget also counts the two u32 vertical-sum rows, so budget == allocation (~109 MB there). Pixels are unchanged. Tests: ahd_scratch_fits_its_budget (budget equals the real scratch for h = 1..5000), ahd_matches_reference_with_reused_scratch (1100 rows, jobs 1 and 2, all four phases: one scratch serves many bands). Co-authored-by: vangel76 <271991477+vangel76@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 (1M context) (cherry picked from commit 630e32c4238df452d9d5e70357bdb968045ab8c3) --- crates/raw/src/demosaic.rs | 71 ++++++++++++++++++++++++++++++++++---- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 6e768c0b2d..ce7cb293fe 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -462,10 +462,19 @@ const AHD_BAND: usize = 32; /// Extra band rows above and below the output rows. const M: usize = 3; -/// Maximum scratch allocation of one AHD band: two green, RGB and Lab float -/// planes and two byte homogeneity planes, including their border rows. +/// Scratch rows one AHD worker allocates: the output rows of the tallest band +/// this image has, plus their border rows. +fn ahd_scratch_rows(h: usize) -> usize { + h.min(AHD_BAND) + 2 * M +} + +/// Scratch allocation of one AHD worker ([`AhdScratch::for_image`]): two green, +/// RGB and Lab float planes and two byte homogeneity planes over +/// [`ahd_scratch_rows`], plus the two `u32` rows of vertical sums. pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 { - w.saturating_add(2 * PAD as u64).saturating_mul(h.min(AHD_BAND as u64).saturating_add(2 * M as u64)).saturating_mul(58) + let s = w.saturating_add(2 * PAD as u64); + let rows = h.min(AHD_BAND as u64).saturating_add(2 * M as u64); + s.saturating_mul(rows.saturating_mul(58).saturating_add(8)) } pub(crate) fn ahd_bands(h: usize) -> usize { @@ -474,7 +483,7 @@ pub(crate) fn ahd_bands(h: usize) -> usize { pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 1) * 8; -/// One AHD band's working planes, reused for every band a worker runs (sized for a full band). +/// One AHD band's working planes, reused for every band a worker runs (sized for the tallest band). struct AhdScratch { /// Green interpolated horizontally (0) and vertically (1). g: [Vec; 2], @@ -498,6 +507,11 @@ impl AhdScratch { vs: [vec![0u32; s], vec![0u32; s]], } } + + /// The scratch for an image `h` rows tall with stride `s`: the size [`ahd_scratch`] budgets. + fn for_image(h: usize, s: usize) -> Self { + AhdScratch::new(ahd_scratch_rows(h) * s, s) + } } /// AHD (see [`ahd_ref`] for the plain statement): the same arithmetic in the same order, per @@ -513,9 +527,8 @@ fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) // A few groups per worker for balance; each group allocates its scratch once. let groups = (par::workers().min(jobs.max(1)) * 4).clamp(1, bands.max(1)); let per_group = bands.div_ceil(groups).max(1); - let cap = (AHD_BAND + 2 * M) * s; par::chunks_mut_limited(out, per_group * AHD_BAND * w * 3, jobs, |group, gchunk| { - let mut sc = AhdScratch::new(cap, s); + let mut sc = AhdScratch::for_image(h, s); for (j, chunk) in gchunk.chunks_mut(AHD_BAND * w * 3).enumerate() { ahd_band(d, w, s, phase, &m, &labf, group * per_group + j, chunk, &mut sc); } @@ -821,6 +834,52 @@ mod tests { } } + /// Bytes the scratch planes actually hold. + fn scratch_bytes(sc: &AhdScratch) -> u64 { + let f = sc.g.iter().chain(sc.rgb.iter().flatten()).chain(sc.lab.iter().flatten()).map(|v| v.capacity() * 4).sum::(); + let b = sc.hom.iter().map(Vec::capacity).sum::(); + let u = sc.vs.iter().map(|v| v.capacity() * 4).sum::(); + (f + b + u) as u64 + } + + /// The memory check in `develop` admits a file on [`ahd_scratch`] per worker; the scratch + /// `ahd` allocates must not exceed it. A short wide strip used to allocate the 38 rows of a + /// full band against a budget of `h + 6` rows (5.4x at `h = 1`). + #[test] + fn ahd_scratch_fits_its_budget() { + for w in [1usize, 2, 33, 4000] { + for h in [1usize, 2, 7, 31, 32, 33, 100, 5000] { + let s = w + 2 * PAD; + let sc = AhdScratch::for_image(h, s); + let budget = ahd_scratch(w as u64, h as u64); + assert_eq!(scratch_bytes(&sc), budget, "{w}x{h}: allocated vs budgeted bytes"); + // The tallest band `ahd` hands out (at most 32 rows, plus 3 above and below) fits. + assert!(sc.g[0].len() >= (h.min(32) + 6) * s, "{w}x{h}"); + } + } + } + + /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over 4 scratches + /// with jobs 1 and at most 8 with jobs 2), so a stage reading a cell left over from an earlier band would show. + #[test] + fn ahd_matches_reference_with_reused_scratch() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + for jobs in [1, 2] { + let groups = (par::workers().min(jobs) * 4).clamp(1, ahd_bands(h)); + assert!(ahd_bands(h).div_ceil(groups) >= 2, "jobs {jobs}: each scratch must serve several bands"); + for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert_eq!(want.len(), got.len()); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{w}x{h} {phase:?} jobs {jobs}"); + } + } + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() From 3bceaf4d66256ac1dbbb78fe3e11393ac39220c8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 23:14:30 +0100 Subject: [PATCH 48/87] raw: AHD allocates its scratch once per worker, not once per band The bands were split into four groups per worker, clamped to the number of bands. A 24 MP raw has 126 bands, so with 32 workers every group held one band and every band allocated and zeroed a fresh 16-plane scratch, which cost more than the reuse saved. The bands are now split into one group per worker, so the scratch is allocated once per worker whatever the thread count. Pixels are unchanged. Adds a test that runs 35 bands in groups of 9 on a 4-thread pool and compares the result with the reference bit for bit, so the band index of later groups and a scratch reused for several bands are checked. Co-Authored-By: Claude Sonnet 5.5 --- crates/raw/src/demosaic.rs | 40 +++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index ce7cb293fe..85af3c9ae4 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -477,6 +477,14 @@ pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 { s.saturating_mul(rows.saturating_mul(58).saturating_add(8)) } +/// Bands one scratch serves: the bands are split into one group per worker (at most `jobs`), so +/// the scratch is allocated and zeroed once per worker however many workers there are. More +/// groups than workers would allocate a fresh scratch for every band on a many-core machine. +fn ahd_bands_per_group(bands: usize, jobs: usize) -> usize { + let groups = par::workers().min(jobs.max(1)).clamp(1, bands.max(1)); + bands.div_ceil(groups).max(1) +} + pub(crate) fn ahd_bands(h: usize) -> usize { h.div_ceil(AHD_BAND) } @@ -524,9 +532,7 @@ fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) let m: [[f32; 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|j| to_xyz[i][j] as f32 / white[i])); let labf = LabF::new(); let bands = ahd_bands(h); - // A few groups per worker for balance; each group allocates its scratch once. - let groups = (par::workers().min(jobs.max(1)) * 4).clamp(1, bands.max(1)); - let per_group = bands.div_ceil(groups).max(1); + let per_group = ahd_bands_per_group(bands, jobs); par::chunks_mut_limited(out, per_group * AHD_BAND * w * 3, jobs, |group, gchunk| { let mut sc = AhdScratch::for_image(h, s); for (j, chunk) in gchunk.chunks_mut(AHD_BAND * w * 3).enumerate() { @@ -868,8 +874,7 @@ mod tests { let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); let p = Padded::from_plane(&cfa, w, h); for jobs in [1, 2] { - let groups = (par::workers().min(jobs) * 4).clamp(1, ahd_bands(h)); - assert!(ahd_bands(h).div_ceil(groups) >= 2, "jobs {jobs}: each scratch must serve several bands"); + assert!(ahd_bands_per_group(ahd_bands(h), jobs) >= 2, "jobs {jobs}: each scratch must serve several bands"); for phase in [[0, 1, 1, 2], [2, 1, 1, 0], [1, 0, 2, 1], [1, 2, 0, 1]] { let mut want = vec![0.0f32; w * h * 3]; ahd_ref(&p, phase, &m, &mut want, jobs); @@ -880,6 +885,31 @@ mod tests { } } + /// A 4-worker pool splits 35 bands into groups of 9 (the last of 8), so groups after the first + /// start at band `group * 9` and every scratch is reused for several bands: a wrong band index + /// or a stale scratch cell would change pixels. The group size does not depend on the machine. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn ahd_groups_of_several_bands_match_reference() { + let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; + let (w, h) = (37, 1100); + let cfa: Vec = (0..w * h).map(|i| ((i * 7919 + i / w * 104729) % 1013) as f32 / 1000.0 - 0.006).collect(); + let p = Padded::from_plane(&cfa, w, h); + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + assert_eq!(par::workers(), 4); + assert_eq!(ahd_bands_per_group(ahd_bands(h), 4), 9); + // One worker per group, never more groups than workers, however many bands there are. + assert_eq!(ahd_bands_per_group(126, 1000), 32); + for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, 4); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, 4); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?}"); + } + }); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() From 1e52abfb2803ac3e6cabfdc15d1d3514ef3ed663 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 01:15:47 +0100 Subject: [PATCH 49/87] raw: restore the LabF pair table that the main revert dropped from the merge Main reverted the earlier #9455 merge, which also removed the AHD changes that came in with it; keep this PR's AHD code and add clampf plus the NaN-plane test from main. Co-Authored-By: Claude Sonnet 5.5 --- crates/raw/src/demosaic.rs | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 63b3ed44f0..862dbb2ad6 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -426,9 +426,10 @@ const GRAD_EPS: f32 = 1.0 / 256.0; /// Regularizes the green-similarity weights of the colour differences. const DIFF_EPS: f32 = 1.0 / 64.0; -/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. +/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation. Each entry holds the +/// sample and the step to the next one (one load per lookup; the same `a + (b - a) * f`). struct LabF { - table: Vec, + pairs: Vec<[f32; 2]>, } const LABF_STEPS: usize = 1 << 14; @@ -436,7 +437,8 @@ const LABF_RANGE: f32 = 2.0; impl LabF { fn new() -> Self { - LabF { table: (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect() } + let table: Vec = (0..=LABF_STEPS + 1).map(|i| Self::exact(i as f32 * LABF_RANGE / LABF_STEPS as f32)).collect(); + LabF { pairs: table.windows(2).map(|p| [p[0], p[1] - p[0]]).collect() } } fn exact(t: f32) -> f32 { @@ -450,8 +452,8 @@ impl LabF { } let x = t * (LABF_STEPS as f32 / LABF_RANGE); let i = (x as usize).min(LABF_STEPS); - let a = self.table[i]; - a + (self.table[i + 1] - a) * (x - i as f32) + let [a, step] = self.pairs[i]; + a + step * (x - i as f32) } } @@ -487,7 +489,7 @@ pub(crate) fn ahd_bands(h: usize) -> usize { h.div_ceil(AHD_BAND) } -pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 2) * 4; +pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 1) * 8; /// `v` limited to `lo..=hi` like `f32::clamp`, without its panic on NaN bounds (hostile black /// levels can put NaN in the plane): same result for every non-NaN bound. @@ -846,12 +848,6 @@ mod tests { } } - #[test] - fn ahd_survives_nan_planes() { - let p = Padded::from_plane(&[f32::NAN; 64], 8, 8); - assert_eq!(demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, 1).len(), 192); - } - /// Bytes the scratch planes actually hold. fn scratch_bytes(sc: &AhdScratch) -> u64 { let f = sc.g.iter().chain(sc.rgb.iter().flatten()).chain(sc.lab.iter().flatten()).map(|v| v.capacity() * 4).sum::(); @@ -922,6 +918,12 @@ mod tests { }); } + #[test] + fn ahd_survives_nan_planes() { + let p = Padded::from_plane(&[f32::NAN; 64], 8, 8); + assert_eq!(demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, 1).len(), 192); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() From 2a83a24f2b2f2912ca02382f641bc1fe1394d70e Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 24 Oct 2026 10:08:34 -0600 Subject: [PATCH 50/87] Color panel: the cube modes warn when a colour can't print (#8672) Photoshop's Color panel shows the out-of-gamut warning and a chip of the nearest printable colour under the foreground/background chips in its Hue Cube, the default mode. PhotoCraft drew it only in the slider modes. The Hue and Brightness Cube now draw the same alerts (a click takes the nearest printable colour), when the field is tall enough to hold them. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/color_panel_tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/color_panel_ui.rs | 4 ++-- crates/ui-egui/src/panels.rs | 6 ++++++ docs/ui-parity.md | 5 +++-- 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index 6f7cc49729..3c18a3fa0a 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -226,6 +226,26 @@ fn web_sliders_snap_and_take_hex() { assert_eq!(bytes(h.state().session.tools.foreground), [0x66, 0xCC, 0]); } +#[test] +fn cube_modes_warn_when_the_colour_cannot_print() { + // #8672: Photoshop's Hue and Brightness Cube show the ⚠ and the nearest printable colour under + // the chips, as the slider modes do; a click takes that colour. + const GAMUT: &str = "Out of gamut for printing: click for the nearest printable colour"; + for mode in [ColorPanelMode::HueCube, ColorPanelMode::BrightnessCube] { + let mut h = color_tab(ThemeKind::Classic, mode, [0.0, 1.0, 0.0, 1.0]); + let near = crate::color_picker_ui::out_of_gamut([0.0, 1.0, 0.0]).expect("pure green can't print"); + let alert = h.get_by_label(GAMUT).rect().center(); + press(&mut h, alert, Modifiers::NONE); + let fg = h.state().session.tools.foreground; + assert_eq!(bytes(fg), bytes([near[0], near[1], near[2], 1.0]), "{mode:?}"); + h.run_steps(2); + assert!(h.query_by_label(GAMUT).is_none(), "{mode:?}: the printable colour still warns"); + // A printable colour shows no alert. + let h = color_tab(ThemeKind::Classic, mode, [0.5, 0.5, 0.5, 1.0]); + assert!(h.query_by_label(GAMUT).is_none(), "{mode:?}"); + } +} + #[test] fn ramp_picks_and_shift_click_cycles_and_alt_picks_the_other_colour() { let mut h = color_tab(ThemeKind::BreezeDark, ColorPanelMode::RgbSliders, [0.0, 0.0, 0.0, 1.0]); diff --git a/crates/ui-egui/src/color_panel_ui.rs b/crates/ui-egui/src/color_panel_ui.rs index 19f223b8a2..1d665497a8 100644 --- a/crates/ui-egui/src/color_panel_ui.rs +++ b/crates/ui-egui/src/color_panel_ui.rs @@ -109,7 +109,7 @@ impl Model { } /// The colour the panel edits. -fn active(app: &PhotocraftApp) -> [f32; 3] { +pub(crate) fn active(app: &PhotocraftApp) -> [f32; 3] { let c = if app.ui.color_panel.background { app.session.tools.background } else { app.session.tools.foreground }; [c[0], c[1], c[2]].map(|x| x.clamp(0.0, 1.0)) } @@ -347,7 +347,7 @@ fn sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, mode: ColorPanelMode) { /// Photoshop's alerts under the chips: ⚠ when the colour can't print (click: the nearest CMYK /// colour) and, for Web Color sliders, the cube when it isn't a web colour (click: the nearest). -fn alerts(app: &mut PhotocraftApp, ui: &mut egui::Ui, col: Rect, rgb: [f32; 3], web: bool) { +pub(crate) fn alerts(app: &mut PhotocraftApp, ui: &mut egui::Ui, col: Rect, rgb: [f32; 3], web: bool) { let t = Tokens::get(ui.ctx()); let background = app.ui.color_panel.background; let mut y = col.top() + CHIPS_W + 2.0; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index e82dc22020..6535277300 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -4304,6 +4304,12 @@ pub(crate) fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.x = 8.0; let (chips, _) = ui.allocate_exact_size(vec2(38.0, h), Sense::hover()); field_chips(app, ui, chips); + // Photoshop's ⚠ under the chips when the colour can't print, as in the slider modes + // (#8672); a compact field too short to hold it below the chips leaves it out. + if chips.height() >= 38.0 + 15.0 { + let rgb = crate::color_panel_ui::active(app); + crate::color_panel_ui::alerts(app, ui, chips, rgb, false); + } // Hue Cube: saturation across and brightness up, hue on the strip. Brightness Cube (the // Color Picker's B mode): hue across and saturation up, brightness on the strip. let brightness = app.ui.color_panel.mode == crate::state::ColorPanelMode::BrightnessCube; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 81b0ab81d6..76f815e7b8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour, #8672; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -224,7 +224,7 @@ Paragraph; the rest open as in-app floating windows. | Panel groups float and tear off into OS windows | missing | UI-217-5, #1828, #1213 | | Drag panels to reorder and regroup | partial | #2272, #2305 | | Docked resize pushes the neighbour | partial | #2573 | -| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000 | +| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders and both cubes); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | @@ -246,6 +246,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | | 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. | From 9d46aa750343ba9acd9b737636ec2bc68adfd9fd Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 24 Oct 2026 11:10:59 -0600 Subject: [PATCH 51/87] Re-run CI Co-Authored-By: Claude Opus 5.5 From 3183dd4efdec81084d5c1fc100e8432f453815a0 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 25 Oct 2026 09:30:31 -0600 Subject: [PATCH 52/87] docs: the cube modes' gamut alert needs a 53 pt field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit on #9154: the Hue Cube and Brightness Cube draw the ⚠ only when the chips column is at least 53 pt tall; the slider modes always do. The ui-parity row, history entry and status line now say so. Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 76f815e7b8..f2721843e5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour, #8672; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour, #8672; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -224,7 +224,7 @@ Paragraph; the rest open as in-app floating windows. | Panel groups float and tear off into OS windows | missing | UI-217-5, #1828, #1213 | | Drag panels to reorder and regroup | partial | #2272, #2305 | | Docked resize pushes the neighbour | partial | #2573 | -| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders and both cubes); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | +| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | @@ -246,6 +246,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | From 98956cfba190cc6c01974cf1b3a0485ec4d00833 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 25 Oct 2026 21:22:30 -0600 Subject: [PATCH 53/87] Tests: the cube modes' gamut alert sets the background chip too CodeRabbit nitpick on #9154 (color_panel_tests.rs 229-248): the test only covered the foreground chip. With the background chip active, the alert's click now must set the background and leave the foreground. Test: cube_modes_warn_when_the_colour_cannot_print Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/color_panel_tests.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index 3c18a3fa0a..1ae2195d49 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -243,6 +243,18 @@ fn cube_modes_warn_when_the_colour_cannot_print() { // A printable colour shows no alert. let h = color_tab(ThemeKind::Classic, mode, [0.5, 0.5, 0.5, 1.0]); assert!(h.query_by_label(GAMUT).is_none(), "{mode:?}"); + // CodeRabbit on #9154: with the background chip active, the click sets the background. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.5, 0.5, 0.5, 1.0]; + app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; + app.ui.color_panel.mode = mode; + app.ui.color_panel.background = true; + let mut h = color_tab_of(ThemeKind::Classic, app); + let alert = h.get_by_label(GAMUT).rect().center(); + press(&mut h, alert, Modifiers::NONE); + let tools = &h.state().session.tools; + assert_eq!(bytes(tools.background), bytes([near[0], near[1], near[2], 1.0]), "{mode:?}: background"); + assert_eq!(bytes(tools.foreground), bytes([0.5, 0.5, 0.5, 1.0]), "{mode:?}: the foreground is left alone"); } } From 1eb98b319e8cf0fffec06f4a214734781e6f6edd Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 25 Oct 2026 21:42:29 -0600 Subject: [PATCH 54/87] fix(ui): Camera Raw's Color Mixer Hue tracks show the neighbouring hues (#9550) Every Color Mixer slider's track ran from grey to its band's colour. A Hue slider turns its band towards the neighbouring colours, so its track now runs from the previous band's hue through its own to the next (Reds: magenta, red, orange). Saturation and Luminance keep grey to the colour. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/camera_raw_ui.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index 1ff5fb4bd1..2efc901b0a 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -1446,6 +1446,16 @@ fn tint_stops() -> Vec { } /// One labelled slider; marks the dialog dirty when it moves. +/// The track of Color Mixer band `k` on `tab` (0 Hue, 1 Saturation, 2 Luminance). A Hue slider +/// turns its band towards the neighbouring bands, so its track runs from the previous band's hue +/// through its own to the next one's (Reds: magenta, red, orange; #9550); Saturation and Luminance +/// run from grey to the band's colour. +fn mixer_gradient(tab: usize, k: usize) -> Vec { + let bands = &photocraft_algo::camera_raw::HSL_BANDS; + let hue = |i: usize| widgets::hue_color(bands.get(i % bands.len()).copied().unwrap_or(0.0)); + if tab == 0 { vec![hue(k + bands.len() - 1), hue(k), hue(k + 1)] } else { vec![Color32::from_gray(128), hue(k)] } +} + fn row(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive, grad: Option<&[Color32]>) { let _ = slider(ui, dirty, label, v, range, grad); } @@ -1746,9 +1756,7 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { _ => &mut p.hsl_lum, }; for (k, name) in BANDS.iter().enumerate() { - let c = photocraft_algo::camera_raw::HSL_BANDS[k]; - let base = widgets::hue_color(c); - let grad = [Color32::from_gray(128), base]; + let grad = mixer_gradient(d.mixer_tab, k); row(ui, &mut dirty, name, &mut arr[k], -100.0..=100.0, Some(&grad)); } }); @@ -1864,6 +1872,19 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { mod tests { use super::*; + /// #9550: a Color Mixer Hue track runs through the neighbouring bands' hues (Reds: magenta to + /// orange, wrapping round), not from grey; Saturation and Luminance keep grey to the colour. + #[test] + fn hue_tracks_run_between_the_neighbouring_bands() { + let hue = |d: f32| widgets::hue_color(d); + assert_eq!(mixer_gradient(0, 0), vec![hue(300.0), hue(0.0), hue(30.0)], "Reds"); + assert_eq!(mixer_gradient(0, 7), vec![hue(270.0), hue(300.0), hue(0.0)], "Magentas"); + assert_eq!(mixer_gradient(0, 3), vec![hue(60.0), hue(120.0), hue(180.0)], "Greens"); + for tab in [1, 2] { + assert_eq!(mixer_gradient(tab, 3), vec![Color32::from_gray(128), hue(120.0)]); + } + } + #[test] fn preview_texture_uses_linear_document_display_encoding() { let mut doc = photocraft_doc::Document::new("test", photocraft_geom::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::F32); From e2d0965d203fe70db5da7c7ec03823b26628e41d Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 25 Oct 2026 21:43:18 -0600 Subject: [PATCH 55/87] docs: keep the parity history newest first Rebasing onto main put this PR's history row above main's newer rows (CodeRabbit flagged the same on #9282). Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f2721843e5..f3b968dd1a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -246,10 +246,10 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| -| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed | -| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | +| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed | +| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. | | 2026-10-24 | minor | Type options bar: the alignment and paragraph-direction buttons show the edited or selected type layer's paragraph instead of the tool defaults, as Photoshop's bar does. Scores unchanged. | | 2026-10-24 | minor | Font menus (options bar, Character panel): the current family is marked in the recent group when it is a recent one, and the menu opens showing it, as Photoshop's does, scrolled to the marked row when it sits below the fold; the arrows walk on from the marked row (#9160). Scores unchanged. | From dbdd5da271c3ef98c4191e95a22d9990b58d0b51 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Mon, 26 Oct 2026 20:16:30 +0700 Subject: [PATCH 56/87] Free Transform: show the live W/H readout in the ruler unit (#9400) While a handle is dragged, the W/H readout beside the pointer showed the scale in percent whatever the Units & Rulers unit. It now shows the box's transformed size in the ruler unit at the document's resolution, as Photoshop does, through the marquee's `size_readout`. With the rulers in percent it keeps showing the scale of the original box, since a percent of the document size means nothing for the box. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/transform_tool.rs | 69 ++++++++++++++++++++++------ 1 file changed, 56 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 9cd31d2e29..13b1131f49 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -2329,7 +2329,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform } // Preferences › Tools › Show Transformation Values off hides it, as in Photoshop (#204). if let Some(r) = live_readout(app).filter(|_| app.session.prefs().tools.show_transformation_values) { - draw_live_readout(painter.ctx(), at, r); + draw_live_readout(app, painter.ctx(), at, r); } } } @@ -2430,8 +2430,8 @@ pub(crate) fn styled_frame(app: &PhotocraftApp, zoom: f32, dragging: bool) -> Op pub(crate) enum Readout { /// Clockwise degrees in document space (`rotation_degrees`), whatever the view's turn or flip. Angle(f64), - /// Width and height in percent of the original box. - Scale([f64; 2]), + /// Width and height in percent of the original box, and the box's size in document pixels. + Scale { percent: [f64; 2], px: [f64; 2] }, /// Document pixels moved since the press. Offset([f64; 2]), } @@ -2446,7 +2446,8 @@ pub(crate) fn live_readout(app: &PhotocraftApp) -> Option { Hit::Inside => Some(Readout::Offset([t.quad[0][0] - g.quad0[0][0], t.quad[0][1] - g.quad0[0][1]])), Hit::Corner(_) | Hit::Edge(_) if parallelogram(&t.quad) => { let (w, h, _, _) = readout(t); - (w.is_finite() && h.is_finite()).then_some(Readout::Scale([w, h])) + let px = [w / 100.0 * (t.rect[2] - t.rect[0]), h / 100.0 * (t.rect[3] - t.rect[1])]; + (w.is_finite() && h.is_finite()).then_some(Readout::Scale { percent: [w, h], px }) } Hit::Corner(_) | Hit::Edge(_) | Hit::Pivot => None, } @@ -2460,21 +2461,32 @@ fn parallelogram(q: &[[f64; 2]; 4]) -> bool { } /// [`live_readout`] as the rounded label beside the pointer (the marquee's and Crop's readout). -fn draw_live_readout(ctx: &egui::Context, at: Pos2, r: Readout) { - // Round first so a hair below zero never reads "-0". - let fixed = |v: f64, places: i32| { - let k = 10f64.powi(places); - let v = (v * k).round() / k; - if v == 0.0 { 0.0 } else { v } - }; +fn draw_live_readout(app: &PhotocraftApp, ctx: &egui::Context, at: Pos2, r: Readout) { let id = "transform-readout"; match r { Readout::Angle(a) => crate::canvas::draw_readout(ctx, id, at, ["Angle:"], [format!("{:.1}°", fixed(a, 1))]), - Readout::Scale([w, h]) => crate::canvas::draw_readout(ctx, id, at, ["W:", "H:"], [w, h].map(|v| format!("{:.1}%", fixed(v, 1)))), + Readout::Scale { percent, px } => crate::canvas::draw_readout(ctx, id, at, ["W:", "H:"], scale_values(app, percent, px)), Readout::Offset([dx, dy]) => crate::canvas::draw_readout(ctx, id, at, ["ΔX:", "ΔY:"], [dx, dy].map(|v| format!("{:.0} px", fixed(v, 0)))), } } +/// `v` rounded to `places` decimals, so a hair below zero never reads "-0". +fn fixed(v: f64, places: i32) -> f64 { + let k = 10f64.powi(places); + let v = (v * k).round() / k; + if v == 0.0 { 0.0 } else { v } +} + +/// The W and H rows of the scale readout: the box's size in the Units & Rulers unit at the +/// document's resolution, as Photoshop shows it (cm when the rulers are in centimeters, #9400); +/// the scale of the original box when the rulers are in percent. +pub(crate) fn scale_values(app: &PhotocraftApp, percent: [f64; 2], px: [f64; 2]) -> [String; 2] { + if app.session.prefs().units_and_rulers.rulers == photocraft_engine::prefs::Unit::Percent { + return percent.map(|v| format!("{:.1}%", fixed(v, 1))); + } + crate::canvas::size_readout(app, [0.0, 0.0, px[0], px[1]]) +} + /// Width and height of the document being transformed, in document pixels. fn canvas_size(pv: &TransformPreview) -> [f32; 2] { [pv.doc.size.width as f32, pv.doc.size.height as f32] @@ -5009,8 +5021,39 @@ mod tests { // The right edge doubles the width (proportional by default: the height too). ev(&mut app, ToolEvent::Down { x: 165.0, y: 93.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Move { x: 293.0, y: 93.0, pressure: 1.0 }); - let Some(Readout::Scale([w, h])) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; + let Some(Readout::Scale { percent: [w, h], px }) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; assert!((w - 200.0).abs() < 1e-6 && (h - 200.0).abs() < 1e-6, "{w} {h}"); + assert!((px[0] - 256.0).abs() < 1e-6 && (px[1] - 256.0).abs() < 1e-6, "{px:?}"); + } + + /// #9400: the W/H readout shows the box's size in the ruler unit, as Photoshop does, and + /// the scale of the original box when the rulers are in percent. + #[test] + fn the_scale_readout_follows_the_ruler_unit() { + use photocraft_engine::prefs::Unit; + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let ev = |app: &mut PhotocraftApp, e| crate::canvas::tool_event(app, e, egui::Modifiers::NONE); + // The right edge from 160 to 288: the 128 px box doubles (proportionally). + ev(&mut app, ToolEvent::Down { x: 160.0, y: 96.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 288.0, y: 96.0, pressure: 1.0 }); + let Some(Readout::Scale { percent, px }) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; + let shown = |app: &mut PhotocraftApp, unit: Unit| { + app.session.prefs.edit(|p| p.units_and_rulers.rulers = unit); + scale_values(app, percent, px) + }; + let dpi = app.session.active().unwrap().doc.resolution_dpi; + assert_eq!(dpi, 72.0, "the expected values below are at 72 ppi"); + assert_eq!(shown(&mut app, Unit::Pixels), ["256 px".to_string(), "256 px".to_string()]); + assert_eq!(shown(&mut app, Unit::Inches), ["3.556 in".to_string(), "3.556 in".to_string()]); + assert_eq!(shown(&mut app, Unit::Centimeters), ["9.03 cm".to_string(), "9.03 cm".to_string()]); + assert_eq!(shown(&mut app, Unit::Millimeters), ["90.31 mm".to_string(), "90.31 mm".to_string()]); + assert_eq!(shown(&mut app, Unit::Percent), ["200.0%".to_string(), "200.0%".to_string()]); + // A flipped box reads as a negative width, as in the options bar. + assert_eq!(scale_values(&app, [-50.0, 50.0], [-64.0, 64.0]), ["-50.0%".to_string(), "50.0%".to_string()]); + app.session.prefs.edit(|p| p.units_and_rulers.rulers = Unit::Pixels); + assert_eq!(scale_values(&app, [-50.0, 50.0], [-64.0, 64.0]), ["-64 px".to_string(), "64 px".to_string()]); } #[test] From 207f83d6f33ecde3d71bd6e7f18248d492cbd2cc Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Mon, 26 Oct 2026 20:33:04 +0700 Subject: [PATCH 57/87] Free Transform readout: offscreen test across ruler units Drags a Free Transform edge with real pointer events in the offscreen app and checks the W/H readout in pixels, centimeters and percent, and that the old percent readout is gone for the other units. Set PHOTOCRAFT_TRANSFORM_READOUT_EVIDENCE_DIR to save the frames as PNGs. Also note on Readout::Scale why the size is the scaled width and height rather than the skewed edge lengths. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/transform_tool.rs | 3 + crates/ui-egui/tests/it/main.rs | 1 + .../tests/it/transform_readout_units.rs | 116 ++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 crates/ui-egui/tests/it/transform_readout_units.rs diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 13b1131f49..d942a5b680 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -2431,6 +2431,9 @@ pub(crate) enum Readout { /// Clockwise degrees in document space (`rotation_degrees`), whatever the view's turn or flip. Angle(f64), /// Width and height in percent of the original box, and the box's size in document pixels. + /// The size is the scaled width and height (what W and H 100 % mean in the options bar), + /// not the edge lengths: a skew leans the sides, which lengthens them but not the height + /// between the top and bottom edges. Scale { percent: [f64; 2], px: [f64; 2] }, /// Document pixels moved since the press. Offset([f64; 2]), diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 2c90cf7981..e8d8b334ba 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -29,6 +29,7 @@ mod pattern_preview_canvas; mod radial_blur_center; mod remove_channel_target; mod system_locale; +mod transform_readout_units; mod ui_scale_canvas; mod variables_data_sets; mod workspace_presets; diff --git a/crates/ui-egui/tests/it/transform_readout_units.rs b/crates/ui-egui/tests/it/transform_readout_units.rs new file mode 100644 index 0000000000..9dd848e46a --- /dev/null +++ b/crates/ui-egui/tests/it/transform_readout_units.rs @@ -0,0 +1,116 @@ +//! #9400: while a Free Transform handle is dragged, the W/H readout beside the pointer shows the +//! box's size in the Units & Rulers unit (as Photoshop does), not always its scale in percent. +//! +//! The real app runs offscreen on wgpu with real egui pointer events. Skips when no GPU adapter +//! exists (like `drag_preview_canvas.rs`). Set `PHOTOCRAFT_TRANSFORM_READOUT_EVIDENCE_DIR` to save +//! the frames, mid-drag, as PNGs. + +use egui::{Modifiers, PointerButton, Pos2}; +use egui_kittest::kittest::Queryable; +use photocraft_engine::prefs::Unit; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::canvas::ViewXform; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +fn harness() -> Option { + let built = std::panic::catch_unwind(|| { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_max_steps(64).wgpu().build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + // The queries below use English labels; don't follow the system locale. + app.session.prefs.edit(|p| p.interface.language = "en".into()); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +fn xf(h: &Harness) -> ViewXform { + ViewXform::active(h.state()).expect("a view") +} + +fn press(h: &mut Harness, p: Pos2, pressed: bool) { + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); +} + +/// A 400 × 300 px document at 72 ppi, 100 %, with a 100 × 50 px box on its own layer at +/// (100, 100) and Free Transform open on it. +fn setup() -> Option { + let mut h = harness()?; + h.run_steps(4); + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).expect("new"); + app.run("layer.new.layer", json!({})).expect("layer"); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 50})).expect("select"); + app.run("edit.fill", json!({"color": "#3366cc"})).expect("fill"); + app.run("select.deselect", json!({})).expect("deselect"); + app.sync_views(); + app.ui.extras.rulers = true; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + } + control(&mut h, "ui.set", json!({"tool": "move", "zoom": 1.0, "center": [200, 150]})); + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + assert!(h.state().ui.transform.is_some(), "the box is open"); + Some(h) +} + +#[test] +fn the_scale_readout_shows_the_size_in_the_ruler_unit() { + // Windows WARP can access-violate when GPU harnesses initialize or tear down concurrently: + // hold the GPU lock for the whole test, harness included. + let _gpu = photocraft_testkit::gpu_lock(); + // The right edge from x 200 to 300 doubles the box (proportionally): 200 × 100 px, which at + // 72 ppi is 7.06 × 3.53 cm; 200 % of the original box with the rulers in percent. + for (unit, name, w, h_text) in + [(Unit::Pixels, "pixels", "200 px", "100 px"), (Unit::Centimeters, "centimeters", "7.06 cm", "3.53 cm"), (Unit::Percent, "percent", "200.0%", "200.0%")] + { + let Some(mut h) = setup() else { return }; + h.state_mut().session.prefs.edit(|p| p.units_and_rulers.rulers = unit); + let x = xf(&h); + let (from, to) = (x.to_screen(200.0, 125.0), x.to_screen(300.0, 125.0)); + press(&mut h, from, true); + for i in 1..=8 { + h.event(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.step(); + } + h.run_steps(2); + // `query_all`: in percent W and H both read 200.0%. + assert!(h.query_all_by_label(w).next().is_some(), "{name}: W reads {w}"); + assert!(h.query_all_by_label(h_text).next().is_some(), "{name}: H reads {h_text}"); + // The readout used to show percent whatever the ruler unit. + if unit != Unit::Percent { + assert!(h.query_all_by_label("200.0%").next().is_none(), "{name}: no percent readout"); + } + if let Some(dir) = std::env::var_os("PHOTOCRAFT_TRANSFORM_READOUT_EVIDENCE_DIR") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).expect("evidence directory"); + h.render().expect("render").save(dir.join(format!("transform-readout-{name}.png"))).expect("save evidence"); + } + press(&mut h, to, false); + h.key_press(egui::Key::Escape); + h.run_steps(3); + } +} From 473648732dceb0873847998275d7a5bec085336a Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 01:57:48 +0100 Subject: [PATCH 58/87] Integration: drop the duplicated Change entry and history row in ui-parity.md (#9154) The PR's follow-up commit appended the reworded entries instead of replacing the first ones, so both versions were in the doc. Keeps the "at least 53 pt tall" wording. Co-authored-by: hectorviov <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f3b968dd1a..11f20f40f3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour, #8672; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -249,7 +249,6 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | | 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed | -| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. | | 2026-10-24 | minor | Type options bar: the alignment and paragraph-direction buttons show the edited or selected type layer's paragraph instead of the tool defaults, as Photoshop's bar does. Scores unchanged. | | 2026-10-24 | minor | Font menus (options bar, Character panel): the current family is marked in the recent group when it is a recent one, and the menu opens showing it, as Photoshop's does, scrolled to the marked row when it sits below the fold; the arrows walk on from the marked row (#9160). Scores unchanged. | From ffd4d480bb7ca1a411debdebae3f9be59537dc7c Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 01:57:25 +0100 Subject: [PATCH 59/87] Integration: bound the nvidia-smi query, smallest of same-id cards (#9042) nvidia_video_memory ran `nvidia-smi` with Command::output(), which has no deadline. It runs on the UI thread at startup, under the video-memory cache lock, so a driver that never answers the query kept the window from opening. It now runs with a 2 s deadline (stdout read on a helper thread, try_wait polling), and a late process is killed and reaped on a detached thread. parse_nvidia_smi took the first line naming the vendor/device id. Two cards of one model with different memory (`0x2C0510DE, 16303` then `0x2C0510DE, 8192`) gave 16 GB though wgpu may be on the 8 GB one; it now takes the smallest. Co-authored-by: Vishnu Vardhan Varma Byrraju <112673081+VishnuByrraju@users.noreply.github.com> Co-authored-by: Khawar Zamman Wani <28915582+wanikhawar@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/gpu_canvas.rs | 148 +++++++++++++++++++++++++++---- 1 file changed, 129 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 4524820b6e..6bca19b6ed 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -1505,11 +1505,11 @@ fn detect_physical_memory() -> Option { } /// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports -/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size on Linux. `None` for -/// integrated and software adapters, whose textures live in system memory (the RAM-based -/// budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` overrides it -/// for any adapter, simulating a discrete card of that size: on an integrated GPU the budget then -/// stops charging the document's pixels too, as for a real card (a development switch). +/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size or `nvidia-smi`'s report on +/// Linux. `None` for integrated and software adapters, whose textures live in system memory (the +/// RAM-based budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` +/// overrides it for any adapter, simulating a discrete card of that size: on an integrated GPU the +/// budget then stops charging the document's pixels too, as for a real card (a development switch). pub fn video_memory(adapter: &wgpu::AdapterInfo) -> Option { if let Some(mb) = std::env::var("PHOTOCRAFT_VRAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { return mb.checked_mul(1 << 20).filter(|b| *b > 0); @@ -1558,32 +1558,91 @@ fn detect_video_memory(vendor: u32, device: u32) -> Option { #[cfg(any(target_os = "linux", test))] const NVIDIA_VENDOR: u32 = 0x10de; +/// How long `nvidia-smi` gets to answer: it runs on the UI thread while the window opens, and a +/// driver that hangs the query must not keep PhotoCraft from starting. +#[cfg(target_os = "linux")] +const NVIDIA_SMI_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2); + /// NVIDIA's own memory size on Linux, from `nvidia-smi` (installed with the driver that put this -/// adapter there in the first place): absent, slow to answer or odd output all read as `None`, -/// never a hang or a panic. +/// adapter there in the first place): absent, slower than [`NVIDIA_SMI_DEADLINE`] or odd output +/// all read as `None`, never a hang or a panic. #[cfg(target_os = "linux")] fn nvidia_video_memory(vendor: u32, device: u32) -> Option { if vendor != NVIDIA_VENDOR { return None; } - let out = std::process::Command::new("nvidia-smi").args(["--query-gpu=pci.device_id,memory.total", "--format=csv,noheader,nounits"]).output().ok()?; - out.status.success().then(|| parse_nvidia_smi(&String::from_utf8_lossy(&out.stdout), vendor, device)).flatten() + let mut cmd = std::process::Command::new("nvidia-smi"); + cmd.args(["--query-gpu=pci.device_id,memory.total", "--format=csv,noheader,nounits"]); + let out = bounded_output(cmd, NVIDIA_SMI_DEADLINE)?; + parse_nvidia_smi(&String::from_utf8_lossy(&out), vendor, device) +} + +/// The first 64 KiB of `cmd`'s stdout when it exits successfully within `deadline`; `None` when +/// it can't start, fails or is still running by then. A late one is killed and reaped on a thread +/// of its own (a process stuck in the driver may not die at once), so the caller waits about +/// `deadline` at most. +#[cfg(any(target_os = "linux", test))] +fn bounded_output(mut cmd: std::process::Command, deadline: std::time::Duration) -> Option> { + use std::io::Read; + use std::process::{Child, Stdio}; + use std::time::{Duration, Instant}; + fn abandon(mut child: Child) { + let _ = child.kill(); + let _ = std::thread::Builder::new().name("reap".into()).spawn(move || child.wait()); + } + let end = Instant::now().checked_add(deadline)?; + let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let Some(stdout) = child.stdout.take() else { + abandon(child); + return None; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let reader = std::thread::Builder::new().name("child-stdout".into()).spawn(move || { + let mut buf = Vec::new(); + let _ = stdout.take(64 << 10).read_to_end(&mut buf); + let _ = tx.send(buf); + }); + if reader.is_err() { + abandon(child); + return None; + } + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if Instant::now() < end => std::thread::sleep(Duration::from_millis(10)), + _ => { + abandon(child); + return None; + } + } + }; + if !status.success() { + return None; + } + // The child has exited, so its stdout is at EOF unless it handed the pipe on to a process of + // its own: bounded too, rather than joining the reader. + rx.recv_timeout(end.saturating_duration_since(Instant::now()).max(Duration::from_millis(50))).ok() } /// `nvidia-smi --query-gpu=pci.device_id,memory.total --format=csv,noheader,nounits`'s own /// format: one `0xDDDDVVVV, size-in-MiB` line per card (device id the high half, vendor id the -/// low, as `lspci -n` and wgpu's own ids read them). The matching line's size, in bytes; `None` -/// when no line names this `vendor`/`device`, or the output isn't shaped like that at all. +/// low, as `lspci -n` and wgpu's own ids read them). The matching line's size, in bytes, and the +/// smallest when several cards share those ids (the ids can't tell which one wgpu picked, so the +/// budget assumes the smaller); `None` when no line names this `vendor`/`device`, or the output +/// isn't shaped like that at all. #[cfg(any(target_os = "linux", test))] fn parse_nvidia_smi(output: &str, vendor: u32, device: u32) -> Option { - output.lines().find_map(|line| { - let (id, mb) = line.split_once(',')?; - let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?; - if id & 0xffff != vendor || id >> 16 != device { - return None; - } - mb.trim().parse::().ok()?.checked_mul(1 << 20) - }) + output + .lines() + .filter_map(|line| { + let (id, mb) = line.split_once(',')?; + let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?; + if id & 0xffff != vendor || id >> 16 != device { + return None; + } + mb.trim().parse::().ok()?.checked_mul(1 << 20).filter(|b| *b > 0) + }) + .min() } /// amdgpu's VRAM size (`/device/mem_info_vram_total`, bytes) of the card under `drm` (the @@ -2900,6 +2959,57 @@ mod tests { assert_eq!(parse_nvidia_smi(&format!("0x2C0510DE, {}\n", u64::MAX), NVIDIA_VENDOR, 0x2c05), None, "would overflow"); } + /// Two cards of one model (same vendor and device id) with different memory: wgpu's ids can't + /// tell which one it picked, so the budget assumes the smaller rather than whichever came first. + #[test] + fn nvidia_smi_cards_sharing_an_id_report_the_smaller_memory() { + assert_eq!(parse_nvidia_smi("0x2C0510DE, 16303\n0x2C0510DE, 8192\n", NVIDIA_VENDOR, 0x2c05), Some(8192 << 20)); + assert_eq!(parse_nvidia_smi("0x2C0510DE, 8192\n0x2C0510DE, 16303\n", NVIDIA_VENDOR, 0x2c05), Some(8192 << 20)); + assert_eq!(parse_nvidia_smi("0x2C0510DE, lots\n0x2C0510DE, 16303\n", NVIDIA_VENDOR, 0x2c05), Some(16303 << 20), "a bad line is skipped"); + assert_eq!(parse_nvidia_smi("0x2C0510DE, 0\n0x2C0510DE, 16303\n", NVIDIA_VENDOR, 0x2c05), Some(16303 << 20), "a zero size is no answer"); + } + + /// `nvidia-smi` runs on the UI thread at startup, so a query the driver never answers must + /// give up at the deadline instead of keeping the window from opening. + #[cfg(any(unix, windows))] + #[test] + fn a_child_that_never_answers_gives_up_at_the_deadline() { + let slow = if cfg!(windows) { + let mut c = std::process::Command::new("ping"); + c.args(["-n", "11", "127.0.0.1"]); + c + } else { + let mut c = std::process::Command::new("sleep"); + c.arg("10"); + c + }; + let start = std::time::Instant::now(); + assert_eq!(bounded_output(slow, std::time::Duration::from_millis(200)), None); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed()); + + let quick = if cfg!(windows) { + let mut c = std::process::Command::new("cmd"); + c.args(["/C", "echo 0x2C0510DE, 16303"]); + c + } else { + let mut c = std::process::Command::new("printf"); + c.arg("0x2C0510DE, 16303\n"); + c + }; + let out = bounded_output(quick, std::time::Duration::from_secs(10)).expect("a quick command answers"); + assert_eq!(parse_nvidia_smi(&String::from_utf8_lossy(&out), NVIDIA_VENDOR, 0x2c05), Some(16303 << 20)); + + let failing = if cfg!(windows) { + let mut c = std::process::Command::new("cmd"); + c.args(["/C", "exit 3"]); + c + } else { + std::process::Command::new("false") + }; + assert_eq!(bounded_output(failing, std::time::Duration::from_secs(10)), None, "a failed run"); + assert_eq!(bounded_output(std::process::Command::new("photocraft-no-such-tool"), std::time::Duration::from_secs(1)), None, "not installed"); + } + /// Only a discrete NVIDIA adapter asks `nvidia-smi`: nothing else spawns a process whose /// answer it would then ignore anyway (`nvidia_video_memory` gates on the vendor id first). #[cfg(target_os = "linux")] From 053f0b7198e0c7a0a29056d09ce7df0becd5bc98 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 02:05:47 +0100 Subject: [PATCH 60/87] Integration: level 3 instead of fast() under zlib-rs, io test into tests/it (#7689) zlib-rs maps level 1 to deflate_quick, which writes static Huffman blocks only, so every Compression::fast() caller (PDF export and print, brush presets, PNG Fast) wrote 5-32% bigger streams than miniz's level 1 did. Level 3 is the lowest level that is never bigger than miniz level 1 on the docs/images photos, raw and Up-filtered (level 2 was +0.9% on one); it is 0-16% smaller and takes 1.2-3.4 times as long. The new test exports a noisy-gradient RGB document as PDF and checks the image stream against miniz level 1 of the same samples: 603007 vs 547315 bytes with fast(), passes with level 3. The PR's doc no longer says the levels are unchanged. Main moved the io integration tests into crates/io/tests/it/, so the new deflate_compatibility.rs moves there and uses crate::common. Co-authored-by: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/png.rs | 13 ++++-- crates/engine/src/preset_store.rs | 3 +- crates/engine/src/print_cmds.rs | 6 ++- crates/io/src/pdf.rs | 6 ++- .../tests/{ => it}/deflate_compatibility.rs | 43 ++++++++++++++++++- crates/io/tests/it/main.rs | 1 + docs/deflate-zlib-rs-performance.md | 5 ++- 7 files changed, 66 insertions(+), 11 deletions(-) rename crates/io/tests/{ => it}/deflate_compatibility.rs (72%) diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 7fbbbc69db..e09115416c 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -419,7 +419,7 @@ fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression } let lvl = match level { PngCompression::None => flate2::Compression::none(), - PngCompression::Fast => flate2::Compression::fast(), + PngCompression::Fast => FAST, PngCompression::Default => flate2::Compression::default(), PngCompression::Best => flate2::Compression::best(), }; @@ -428,6 +428,11 @@ fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression z.finish().map_err(|e| CodecError::encode(F, e)) } +/// The deflate level of [`PngCompression::Fast`]: zlib-rs level 1 writes static Huffman blocks +/// only (20-30% bigger on filtered photos); level 3 is the lowest that is never bigger than +/// miniz's level 1 was, at about twice its time. +const FAST: flate2::Compression = flate2::Compression::new(3); + /// Images at least this large (bytes) are filtered and deflated on all cores. const PARALLEL_MIN_BYTES: usize = 4 << 20; @@ -456,7 +461,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio let band_rows = (BAND_BYTES / stride.saturating_add(1)).max(1); let bands: Vec<(usize, usize)> = (0..h).step_by(band_rows).map(|y| (y, (y + band_rows).min(h))).collect(); let lvl = match level { - PngCompression::Fast => flate2::Compression::fast(), + PngCompression::Fast => FAST, PngCompression::Best => flate2::Compression::best(), _ => flate2::Compression::default(), }; @@ -494,7 +499,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio let mut out = Vec::with_capacity(parts.iter().map(|p| p.1.len()).sum::() + 6); // zlib header: deflate, 32 K window; FLEVEL only advertises the effort. out.extend_from_slice(match level { - PngCompression::Fast => &[0x78, 0x01], + PngCompression::Fast => &[0x78, 0x5E], PngCompression::Best => &[0x78, 0xDA], _ => &[0x78, 0x9C], }); @@ -509,7 +514,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio /// Raw deflate of one band: ends on a sync flush, or finishes the stream for the `last` band. /// The output buffer is sized past deflate's worst case so that one call takes the whole band -/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's Rust +/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust /// backend) can return before compressing the last lookahead bytes, and the next call only /// drains the pending output, so a resumed flush silently drops data. `None` (the caller then /// uses the serial encoder) if the single call did not finish. diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index a065e48e6d..92ad78e5dd 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -254,7 +254,8 @@ pub fn encode_tip(t: &GrayTile) -> Vec { out.push(if eight { 8 } else { 16 }); out.extend_from_slice(&t.width.to_le_bytes()); out.extend_from_slice(&t.height.to_le_bytes()); - let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::fast()); + // Level 3: zlib-rs level 1 writes static Huffman blocks only, 13-30% bigger than miniz's level 1. + let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3)); let mut buf = Vec::with_capacity(8192); let mut ok = true; for chunk in t.data.chunks(4096) { diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index d115566a7c..ee39b373c1 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -341,8 +341,10 @@ fn pdf_string(s: &str) -> String { } fn deflate(data: &[u8]) -> Vec { - // Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default. - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static + // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger + // than miniz's level 1 was, at about twice its time. + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3)); let _ = e.write_all(data); e.finish().unwrap_or_default() } diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 4f992bc8fd..92a5a05850 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -59,8 +59,10 @@ fn pdf_string(s: &str) -> String { } fn deflate(data: &[u8]) -> Vec { - // Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default. - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static + // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger + // than miniz's level 1 was, at about twice its time. + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3)); let _ = e.write_all(data); e.finish().unwrap_or_default() } diff --git a/crates/io/tests/deflate_compatibility.rs b/crates/io/tests/it/deflate_compatibility.rs similarity index 72% rename from crates/io/tests/deflate_compatibility.rs rename to crates/io/tests/it/deflate_compatibility.rs index 493c7dba6a..b6f4331b07 100644 --- a/crates/io/tests/deflate_compatibility.rs +++ b/crates/io/tests/it/deflate_compatibility.rs @@ -1,5 +1,5 @@ //! Backend compatibility, including native-format tile data rather than ZIP assembly alone. -mod common; +use crate::common; use std::io::Read; @@ -102,3 +102,44 @@ fn png_psd_and_pcraft_decode_identically() { check_png(&read_thumbnail(&bytes).unwrap().unwrap(), &image); } } + +/// PDF export writes its image at the old backend's size or smaller: zlib-rs level 1 +/// (`Compression::fast()`) writes static Huffman blocks only, which made PDFs of photos +/// 5-30% bigger than miniz's level 1 did. +#[test] +fn pdf_image_stream_is_no_bigger_than_miniz_fast() { + let (w, h) = (512u32, 384u32); + let mut doc = Document::new("photo", Size::new(w, h), ColorMode::Rgb, SampleType::U8); + // A noisy gradient: smooth like a photo, with sensor-like grain. + let mut x32 = 0x9E37_79B9u32; + let mut samples = Vec::with_capacity((w * h * 3) as usize); + let mut vals = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + for c in 0..3 { + x32 ^= x32 << 13; + x32 ^= x32 >> 17; + x32 ^= x32 << 5; + let base = (x * 160 / w + y * 80 / h + c * 20) as i32; + let v = (base + (x32 % 9) as i32 - 4).clamp(0, 255) as u8; + samples.push(v); + vals.push(common::g(v)); + } + vals.push(1.0); + } + } + let mut surface = photocraft_raster::Surface::new(doc.pixel_format()); + surface.write_region(doc.bounds(), &vals); + doc.layers.push(Layer::new("photo", LayerContent::Raster(surface))); + let pdf = photocraft_io::export(&doc, "photo.pdf", &Default::default()).unwrap().bytes; + let at = pdf.windows(15).position(|s| s == b"/Subtype /Image").unwrap(); + let dict = &pdf[at..]; + let len_at = dict.windows(8).position(|s| s == b"/Length ").unwrap() + 8; + let digits = dict[len_at..].iter().take_while(|b| b.is_ascii_digit()).count(); + let len: usize = std::str::from_utf8(&dict[len_at..len_at + digits]).unwrap().parse().unwrap(); + let start = dict.windows(7).position(|s| s == b"stream\n").unwrap() + 7; + let stream = &dict[start..start + len]; + assert_eq!(miniz_oxide::inflate::decompress_to_vec_zlib(stream).unwrap(), samples); + let old = miniz_oxide::deflate::compress_to_vec_zlib(&samples, 1).len(); + assert!(len <= old, "PDF image stream {len} bytes, miniz level 1 wrote {old}"); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 94f4ba715d..88c1cad0ea 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -20,6 +20,7 @@ mod comps_artboards; mod corpus; mod corpus_regressions; mod cylinder_warp; +mod deflate_compatibility; mod effects_multi; mod exif_resolution; mod export_progress; diff --git a/docs/deflate-zlib-rs-performance.md b/docs/deflate-zlib-rs-performance.md index f924f4d8ea..af05ebae0f 100644 --- a/docs/deflate-zlib-rs-performance.md +++ b/docs/deflate-zlib-rs-performance.md @@ -5,7 +5,10 @@ Replace the workspace flate2 Rust backend with zlib-rs and runtime CPU detection Size, import-speed and dependency tradeoffs remain maintainer decisions. Some PSD ZIP files grow by up to 0.71%. The macOS 16-bit city PSD import is about 6% slower in confirmation. The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 25 bytes. -Real photo PNGs become smaller and encode faster. Compression levels are unchanged. +Real photo PNGs become smaller and encode faster. The default and best levels are unchanged; callers that +used level 1 (PDF export and print, brush tips, PNG Fast) now use level 3, because zlib-rs level 1 writes +static Huffman blocks only (13-32% bigger on photos). Level 3 is never bigger than miniz's level 1 on the +docs/images photos (0-16% smaller) and takes 1.2-3.4 times as long. There is no native-format tile speedup from deflate. The timings below measure only the backend switch. They exclude the later ZIP allocation, validation and slice decoder changes. From 714b8f304de0284976d5f66460f36d3f028becd3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 02:17:32 +0100 Subject: [PATCH 61/87] Integration: the reference application's Halftone Pattern keys HlSz/ScrT (#9031) The PR read and wrote Halftone Pattern as `Sz ` and `Ptrn` (enum `HlfT`: `Dt `/`Crc `/`Ln `). The reference application's Filter Gallery uses `HlSz` for the size and a `ScrT` enum (`ScrD` dot, `ScrC` circle, `ScrL` line), so a Halftone Pattern saved there still opened as an opaque filter, and one we saved lost its size and pattern there without a warning. The tests built their fixture with the same keys as the code, so they passed either way. Now the keys match, a default Halftone Pattern (HlSz 1, Cntr 5, ScrD) opens as {size 1, contrast 5, dot} (fails before this commit), and descriptors with the old keys stay verbatim. The docs no longer claim reopen checks in the reference application. Co-authored-by: denstu473 <63150090+denstu473@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/io/src/smart_map.rs | 18 +++---- crates/io/src/smart_map/halftone_tests.rs | 60 +++++++++++++++++------ docs/file-format-parity.md | 4 +- docs/gaps.md | 4 +- 4 files changed, 57 insertions(+), 29 deletions(-) diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 37a4b140d7..128b3c5b1e 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -727,11 +727,11 @@ struct GalleryCode { const GALLERY_EFFECTS: [GalleryCode; 2] = [ GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }, - GalleryCode { key: "halftonePattern", code: "HlfS", settings: &[("Sz ", "size"), ("Cntr", "contrast")] }, + GalleryCode { key: "halftonePattern", code: "HlfS", settings: &[("HlSz", "size"), ("Cntr", "contrast")] }, ]; -// Photoshop 27.11 writes Halftone Pattern's shape as an enum, not a numeric choice index. -const HALFTONE_PATTERNS: [(&[u8; 4], &str); 3] = [(b"Dt ", "dot"), (b"Crc ", "circle"), (b"Ln ", "line")]; +// Halftone Pattern's shape is a `ScrT` enum (Filter Gallery terminology: Dot, Circle, Line). +const HALFTONE_PATTERNS: [(&[u8; 4], &str); 3] = [(b"ScrD", "dot"), (b"ScrC", "circle"), (b"ScrL", "line")]; /// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. fn rgbc_colour(d: &Descriptor) -> Option { @@ -795,18 +795,18 @@ fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { // Do not turn an unfamiliar shape or malformed setting into the engine's defaults: // keeping the whole item opaque preserves it through a subsequent save. if !e.class_id.is(GALLERY_CLASS) - || !only_keys(e, &["GEfk", "Sz ", "Cntr", "Ptrn", "GELv"]) + || !only_keys(e, &["GEfk", "HlSz", "Cntr", "ScrT", "GELv"]) || !matches!(e.get("GEfk"), Some(Value::Enumerated { type_id, .. }) if type_id.is("GEft")) || e.get("GELv").is_some_and(|v| !matches!(v, Value::Boolean(_))) { return None; } - int_in(e, "Sz ", 1, 12)?; + int_in(e, "HlSz", 1, 12)?; int_in(e, "Cntr", 0, 50)?; - params.insert("patternType".into(), json!(enum_name(e, "Ptrn", "HlfT", &HALFTONE_PATTERNS)?)); + params.insert("patternType".into(), json!(enum_name(e, "ScrT", "ScrT", &HALFTONE_PATTERNS)?)); } for (k, v) in &e.items { - if k.is("GEfk") || k.is("GELv") || g.key == "halftonePattern" && k.is("Ptrn") { + if k.is("GEfk") || k.is("GELv") || g.key == "halftonePattern" && k.is("ScrT") { continue; } let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; @@ -871,9 +871,9 @@ fn gallery_item(f: &SmartFilter) -> Result { let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); let settings: Vec<(&str, Value)> = if key == "halftonePattern" { vec![ - ("Sz ", whole(pf_range(params, "size", 1.0, 1.0, 12.0)?, (1, 12), "size")?), + ("HlSz", whole(pf_range(params, "size", 1.0, 1.0, 12.0)?, (1, 12), "size")?), ("Cntr", whole(pf_range(params, "contrast", 5.0, 0.0, 50.0)?, (0, 50), "contrast")?), - ("Ptrn", enum_param(params, "patternType", "dot", "HlfT", &HALFTONE_PATTERNS)?), + ("ScrT", enum_param(params, "patternType", "dot", "ScrT", &HALFTONE_PATTERNS)?), ] } else { g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect() diff --git a/crates/io/src/smart_map/halftone_tests.rs b/crates/io/src/smart_map/halftone_tests.rs index 7f53043aa5..46cd68bc2c 100644 --- a/crates/io/src/smart_map/halftone_tests.rs +++ b/crates/io/src/smart_map/halftone_tests.rs @@ -1,4 +1,5 @@ -//! Halftone Pattern descriptors measured in Photoshop 27.11.0 (#8940). +//! Halftone Pattern descriptors with the keys from the reference application's Filter Gallery plug-in terminology (#8940): +//! `HlSz` size, `Cntr` contrast and a `ScrT` enum (`ScrD` dot, `ScrC` circle, `ScrL` line). use super::*; /// Builds an editable Halftone Pattern filter with explicit foreground/background colours. @@ -15,13 +16,13 @@ fn filter(pattern: &str, size: i32, contrast: i32) -> SmartFilter { } } -/// Builds the inline Halftone descriptor measured in Photoshop. +/// Builds the inline Halftone descriptor as the reference application writes it. fn native_effect(pattern: &str, size: i32, contrast: i32) -> Descriptor { let mut d = Descriptor::new("GEfc") .with("GEfk", enumv("GEft", "HlfS")) - .with("Sz ", Value::Integer(size)) + .with("HlSz", Value::Integer(size)) .with("Cntr", Value::Integer(contrast)) - .with("Ptrn", enumv("HlfT", pattern)); + .with("ScrT", enumv("ScrT", pattern)); d.name = UnicodeString::new_nul("Filter Gallery"); d } @@ -40,10 +41,10 @@ fn native_item(effect: Descriptor) -> Descriptor { .with("filterID", Value::Integer(code(b"GEfc"))) } -/// Checks the measured pattern enums and editable settings in both mapping directions. +/// Checks the pattern enums and editable settings in both mapping directions. #[test] fn halftone_pattern_reads_and_writes_photoshop_inline_descriptors() { - for (pattern, native) in [("dot", "Dt "), ("circle", "Crc "), ("line", "Ln ")] { + for (pattern, native) in [("dot", "ScrD"), ("circle", "ScrC"), ("line", "ScrL")] { for (size, contrast) in [(1, 0), (2, 5), (7, 31), (12, 50)] { let expected = filter(pattern, size, contrast); let native = native_item(native_effect(native, size, contrast)); @@ -71,22 +72,49 @@ fn halftone_pattern_defaults_and_mixed_hidden_stack_round_trip() { assert_eq!(filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()), f); } +/// A default Halftone Pattern as the reference application saves it (size 1, contrast 5, Dot) opens editable. +#[test] +fn halftone_pattern_photoshop_default_imports_editable() { + let f = filter_from_item(&native_item(native_effect("ScrD", 1, 5))); + assert_eq!(f.command, GALLERY_COMMAND); + assert_eq!(f.params["effects"][0]["filter"], json!("halftonePattern")); + assert_eq!(f.params["effects"][0]["params"], json!({"size": 1, "contrast": 5, "patternType": "dot"})); +} + +/// Keys the reference application's Filter Gallery doesn't use (`Sz `, `Ptrn` of type `HlfT`) are not taken for +/// Halftone settings: the item stays opaque and is written back as it was read. +#[test] +fn halftone_pattern_foreign_keys_stay_verbatim() { + for (pattern, shape) in [("Dt ", "dot"), ("Crc ", "circle"), ("Ln ", "line")] { + let mut d = Descriptor::new("GEfc") + .with("GEfk", enumv("GEft", "HlfS")) + .with("Sz ", Value::Integer(2)) + .with("Cntr", Value::Integer(5)) + .with("Ptrn", enumv("HlfT", pattern)); + d.name = UnicodeString::new_nul("Filter Gallery"); + let item = native_item(d); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{shape}"); + assert_eq!(item_for_filter(&f).unwrap(), item, "{shape}"); + } +} + /// Preserves unfamiliar and malformed settings instead of substituting editable defaults. #[test] fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { - let valid = native_effect("Dt ", 2, 5); + let valid = native_effect("ScrD", 2, 5); let mut invalid = vec![ valid.clone().with("futureSetting", Value::Integer(1)), - valid.clone().with("Sz ", Value::Integer(3)), // repeated key + valid.clone().with("HlSz", Value::Integer(3)), // repeated key ]; for (key, value) in [ ("GEfk", enumv("wrong", "HlfS")), - ("Ptrn", enumv("HlfT", "????")), - ("Ptrn", enumv("wrong", "Dt ")), - ("Ptrn", Value::Integer(0)), - ("Sz ", Value::Integer(0)), - ("Sz ", Value::Integer(13)), - ("Sz ", Value::Double(2.0)), + ("ScrT", enumv("ScrT", "????")), + ("ScrT", enumv("wrong", "ScrD")), + ("ScrT", Value::Integer(0)), + ("HlSz", Value::Integer(0)), + ("HlSz", Value::Integer(13)), + ("HlSz", Value::Double(2.0)), ("Cntr", Value::Integer(-1)), ("Cntr", Value::Integer(51)), ("GELv", Value::Integer(1)), @@ -96,7 +124,7 @@ fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { effect.items.push((Id::new(key), value)); invalid.push(effect); } - for missing in ["Sz ", "Cntr", "Ptrn"] { + for missing in ["HlSz", "Cntr", "ScrT"] { let mut effect = valid.clone(); effect.items.retain(|(id, _)| !id.is(missing)); invalid.push(effect); @@ -112,7 +140,7 @@ fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() { /// Keeps a whole Gallery stack opaque when a Halftone entry has an unfamiliar class ID. #[test] fn halftone_pattern_unknown_nested_class_stays_verbatim() { - let valid = native_effect("Dt ", 2, 5); + let valid = native_effect("ScrD", 2, 5); let mut unknown = valid.clone(); unknown.class_id = Id::new("Xxxx"); for effects in [vec![unknown.clone()], vec![valid.clone(), unknown.clone()], vec![unknown, valid]] { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a3855e3fb9..3b1fbd09c5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-23 · **Change:** minor (PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 -**PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export. PSD/PSB metadata round trips pass at 8/16/32 bits; six Photoshop 27.11 reopen checks retain the effect and its settings. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. +**PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write @@ -144,7 +144,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| -| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways; PSD/PSB round trips at 8/16/32 bits, six Photoshop 27.11 reopen checks, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | +| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`); PSD/PSB round trips at 8/16/32 bits, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | 32-bit Hue/Saturation as Photoshop does it: the raised saturation isn't clipped (saturated colours leave 0..1), the chroma is scaled around the lightness by Photoshop's saturation factor (measured at every whole percent), so colours at or above lightness 1 keep their hue, and Colorize builds its colour with the saturation times 1 − \|Lightness\| (8 and 16 bits unchanged): photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-19 | minor | JPEG Options on File › Save, Save As and Save a Copy (FILE-215-19 partial: no Matte, progressive Scans or size preview) | | 2026-10-18 | minor | Scripted TIFF saves take `tiffCompression` (none, LZW, ZIP), and the CLI `--tiff-compression` (#5301) | diff --git a/docs/gaps.md b/docs/gaps.md index 679d42ad9e..4c6ea2ccd0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -40,7 +40,7 @@ what an agent can't finish alone. ## Feature gaps ### G1. PSD fidelity and Photoshop acceptance -- **Done 2026-10-23 (#8940):** Filter Gallery Halftone Pattern preserves size, contrast and dot/circle/line through PSD/PSB import/export. Six Photoshop 27.11 reopen checks retain editable settings. Other unsupported gallery effects remain opaque on import or produce an export warning. +- **Done 2026-10-23 (#8940):** Filter Gallery Halftone Pattern preserves size, contrast and dot/circle/line through PSD/PSB import/export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`). Malformed descriptors stay verbatim. Other unsupported gallery effects remain opaque on import or produce an export warning. - **Missing:** PSDs we write are not always accepted by Photoshop, and Photoshop-authored files don't always render as Photoshop renders them. - **Partial (2026-10-15, #5972 A1):** `GdFl` noise fills render when all three RGB ranges are @@ -359,7 +359,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| -| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways; PSD/PSB round trips at 8/16/32 bits, six Photoshop 27.11 reopen checks, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | +| 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`); PSD/PSB round trips at 8/16/32 bits, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | G17: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; estimate unchanged | | 2026-10-22 | minor | G1: 32-bit Hue/Saturation unclipped with Photoshop's saturation factor, bright colours keep their hue, Colorize's saturation scaled by 1 − \|Lightness\|; photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | | 2026-10-21 | minor | G9: adjustment clipping remains visible in compact Properties (#5231); no readiness percentage or estimate changed | From 09f2c299aedf0d500249e21012189a29b9d99fe0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 02:31:46 +0100 Subject: [PATCH 62/87] Integration: keep vector-mask edits on the mask for type on a path (#9321) The Type Path branch in edit_path caught every `"name":"layer"` edit of a type-on-a-path layer, including edits of its targeted vector mask: Direct Selection showed the mask, but a drag moved the Type Path by the mask's knot indices and left the mask as it was. On main the same command edits the mask, and path.info / path.get / path.transform still read the mask. `"name":"layer"` now keeps that meaning: it edits the vector mask when the layer has one, and the Type Path only when it has none or with `"typePath": true`, which Direct Selection sends for the Type Path (PathRef::TypePath). path.list reports the Type Path under its own `typePath` key, so `layerPath` still names the vector mask, and an edited Type Path keeps the knot cap type.attachToPath enforces. Both points were found by CodeRabbit. The canvas also draws the Type Path with the other tools, as it does a shape's path: the Pen's Auto Add/Delete edits it, and before this a Pen click on the baseline added or deleted anchors the user couldn't see. Co-authored-by: DuBearte <130190089+DuBearte@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/path_edit_cmds.rs | 13 ++++--- crates/engine/src/type_extra_cmds.rs | 3 ++ crates/engine/src/type_extra_cmds/tests.rs | 41 +++++++++++++++++++++- crates/engine/src/vector_cmds.rs | 14 +++++--- crates/ui-egui/src/direct_select.rs | 17 +++++---- crates/ui-egui/src/direct_select_tests.rs | 31 +++++++++++++++- crates/ui-egui/src/vector_ui.rs | 17 +++++++++ 7 files changed, 119 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/path_edit_cmds.rs b/crates/engine/src/path_edit_cmds.rs index 2c3b7d83b9..d06b0fb29c 100644 --- a/crates/engine/src/path_edit_cmds.rs +++ b/crates/engine/src/path_edit_cmds.rs @@ -6,7 +6,8 @@ //! //! Every command targets a path like `path.transform`: `"name":"work"` (default), a saved path's //! name, or `"layer"` with `"layer":id?` for a shape layer's path (re-rendered; it stops being a -//! live shape) or a layer's vector mask. Knots are addressed by `subpath` and `knot` index, as +//! live shape), a layer's vector mask, or type on a path's Type Path (`"typePath":true` when the +//! type layer also has a vector mask). Knots are addressed by `subpath` and `knot` index, as //! listed by `path.info`, and the result is `{name, path}` in the compact JSON form. use photocraft_doc::{LayerContent, Path}; @@ -49,9 +50,13 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> { fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result { let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); let layer = if name == "layer" { Some(layer_id(s, p)?) } else { None }; - // Type on a path: its own path, the text laid along it again (#9114). + // Type on a path: its own path, the text laid along it again (#9114). A vector mask on the + // layer stays what `"layer"` edits, as with `path.info`, unless `"typePath": true`. + let type_path = p.get("typePath").and_then(Value::as_bool).unwrap_or(false); let typed = layer.filter(|id| { - s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(&l.content, LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some())) + s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| { + matches!(&l.content, LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some()) && (type_path || l.vector_mask.is_none()) + }) }); if let Some(id) = typed { let path = crate::type_extra_cmds::with_text(s, &json!({"layer": id.0}), label, |t, _| { @@ -162,7 +167,7 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result { } pub fn specs() -> Vec { - const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#; + const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path, a vector mask, or else type on a path's Type Path),"typePath":bool=false (with "layer": the Type Path even when the type layer has a vector mask)"#; let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result| CommandSpec { id, label, diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rs index 59ed4799b5..d8c11a52d6 100644 --- a/crates/engine/src/type_extra_cmds.rs +++ b/crates/engine/src/type_extra_cmds.rs @@ -433,6 +433,9 @@ pub(crate) fn set_type_path(t: &mut TextLayer, edited: &Path) -> Result<()> { if sub.knots.len() < 2 { return Err(EngineError::Other("type on a path needs a path of two or more points".into())); } + if sub.knots.len() > MAX_TYPE_PATH_KNOTS { + return Err(EngineError::Other("the type path has too many anchor points".into())); + } let inv = t.transform.inverse().ok_or_else(|| EngineError::Other("the type layer's transform cannot be inverted".into()))?; let map = |q: Point| inv.apply(q); let knots: Vec = diff --git a/crates/engine/src/type_extra_cmds/tests.rs b/crates/engine/src/type_extra_cmds/tests.rs index ecb3e01f10..8ae504cfa1 100644 --- a/crates/engine/src/type_extra_cmds/tests.rs +++ b/crates/engine/src/type_extra_cmds/tests.rs @@ -332,7 +332,7 @@ fn type_follows_its_path_when_the_path_is_edited() { let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect(); assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}"); let listed = s.execute("path.list", json!({})).unwrap(); - assert_eq!(listed["layerPath"]["kind"], "typePath", "{listed}"); + assert_eq!(listed["typePath"]["kind"], "typePath", "{listed}"); // Swing the path's end to the right: the type now runs down and to the right. let before = ink(&s, id); let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap(); @@ -349,6 +349,45 @@ fn type_follows_its_path_when_the_path_is_edited() { assert_eq!(ink(&s, id), before); } +/// #9114: a type-on-a-path layer's vector mask is still what `"name": "layer"` edits, as on main +/// and as `path.info` reads it; `"typePath": true` edits the Type Path; `path.list` reports both. +#[test] +fn a_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { + let mut s = session(8); + let id = text_layer(&mut s, "Hello path"); + s.edit("path", |doc, _| { + doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); + Ok(()) + }) + .unwrap(); + s.execute("type.attachToPath", json!({})).unwrap(); + let rect = json!({"subpaths": [{"closed": true, "knots": [[10, 10], [200, 10], [200, 100], [10, 100]]}]}); + s.execute("layer.vectorMask.add", json!({"layer": id.0, "path": rect})).unwrap(); + let listed = s.execute("path.list", json!({})).unwrap(); + assert_eq!((listed["layerPath"]["kind"].as_str(), listed["typePath"]["kind"].as_str()), (Some("vectorMask"), Some("typePath")), "{listed}"); + let type_path = |s: &Session| crate::type_extra_cmds::type_path(text(s, id)).unwrap(); + let before = type_path(&s); + let mask = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths[0].knots[0].anchor; + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 0]], "move": [10, 0]})).unwrap(); + assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask's corner moved"); + assert_eq!(type_path(&s), before, "the Type Path stays"); + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "typePath": true, "anchors": [[0, 1]], "move": [20, 0]})).unwrap(); + assert!((type_path(&s).subpaths[0].knots[1].anchor.x - before.subpaths[0].knots[1].anchor.x - 20.0).abs() < 1e-6, "the Type Path moved"); + assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask stays"); +} + +/// An edit can't grow the Type Path past the cap `type.attachToPath` keeps. +#[test] +fn an_edited_type_path_keeps_the_knot_cap() { + let mut s = session(8); + let id = text_layer(&mut s, "Hi"); + let knots: Vec<(f64, f64)> = (0..=MAX_TYPE_PATH_KNOTS).map(|i| (i as f64 * 0.001, 50.0)).collect(); + let mut t = text(&s, id).clone(); + t.shape = TextShape::Path { path: Subpath::polyline(&knots[..2]), start: 0.0, flip: false }; + assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots[..MAX_TYPE_PATH_KNOTS])])).is_ok()); + assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots)])).is_err()); +} + /// The Type tool's click on a path: `"at"` starts the type where the path passes nearest the /// click, and the paragraph alignment is kept about that point, as in Photoshop. #[test] diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs index d90fb3595e..4f54c9f788 100644 --- a/crates/engine/src/vector_cmds.rs +++ b/crates/engine/src/vector_cmds.rs @@ -851,11 +851,9 @@ fn paths_list(s: &Session) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let doc = &d.doc; let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::(); - let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content { + let active = d.active_layer.and_then(|id| doc.layer(id)); + let layer = active.and_then(|l| match &l.content { LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })), - // Type on a path: Photoshop's Type Path, which Direct Selection edits (#9114). - LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some() => crate::type_extra_cmds::type_path(t) - .map(|p| json!({ "kind": "typePath", "layer": l.id.0, "name": format!("{} Type Path", l.name), "knots": knots(&p) })), _ => { l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) })) } @@ -865,6 +863,12 @@ fn paths_list(s: &Session) -> Result { "workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })), "clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })), "layerPath": layer, + // Type on a path: Photoshop's Type Path, which Direct Selection edits (#9114). + "typePath": active.and_then(|l| match &l.content { + LayerContent::Text(t) => crate::type_extra_cmds::type_path(t) + .map(|p| json!({ "kind": "typePath", "layer": l.id.0, "name": format!("{} Type Path", l.name), "knots": knots(&p) })), + _ => None, + }), })) } @@ -1800,7 +1804,7 @@ pub fn specs() -> Vec { label: "List Paths", menu: &[], shortcut: None, - params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##, + params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask),typePath (active type layer's Type Path, if it is on a path)}"##, enabled: has_doc, run: |s, _| paths_list(s), journal: false, diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs index 305e954339..46aae92d05 100644 --- a/crates/ui-egui/src/direct_select.rs +++ b/crates/ui-egui/src/direct_select.rs @@ -1,7 +1,7 @@ //! Direct Selection tool (A, #790), the Convert Point tool (#3204), the Pens' ⌘/Ctrl (Direct //! Selection: the Pen, Freeform Pen and Curvature Pen) and the Pen's ⌥/Alt (Convert Point) -//! modifiers, as in Photoshop. It edits the paths the canvas shows: the targeted vector mask or -//! the active shape layer's path, and the work path. +//! modifiers, as in Photoshop. It edits the paths the canvas shows: the targeted vector mask, the +//! active shape layer's path or the active type layer's Type Path, and the work path. //! //! * Click an anchor to select it (⇧ adds or removes, ⌥ selects its whole subpath), drag on empty //! canvas to marquee-select anchors, click empty canvas to deselect. @@ -39,6 +39,8 @@ pub enum PathRef { Work, /// A layer's shape path, or its vector mask. Layer(u64), + /// A type layer's Type Path (#9114), apart from a vector mask the layer may have. + TypePath(u64), /// The Pen path being drawn (`ui.pen`): edited in place, not through the engine. Pen, } @@ -49,6 +51,7 @@ impl PathRef { match self { PathRef::Work => json!({"name": "work"}), PathRef::Layer(id) => json!({"name": "layer", "layer": id}), + PathRef::TypePath(id) => json!({"name": "layer", "layer": id, "typePath": true}), // Never sent: edits to the Pen path being drawn don't go through the engine. PathRef::Pen => json!({}), } @@ -167,10 +170,12 @@ pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool { /// active type layer's Type Path (#9114), then the work path. The Pen's Auto Add/Delete edits these /// (`anchor_tools::pen_auto`). pub(crate) fn active_paths(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { - let layer = - crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app)).or_else(|| crate::vector_ui::active_type_path(app)); + let layer = crate::vector_ui::targeted_vector_mask(app) + .or_else(|| crate::vector_ui::active_shape_path(app)) + .map(|(id, p)| (PathRef::Layer(id), p)) + .or_else(|| crate::vector_ui::active_type_path(app).map(|(id, p)| (PathRef::TypePath(id), p))); let work = app.session.active().and_then(|st| st.doc.work_path.clone()); - layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() + layer.into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() } /// The paths Direct Selection edits, front first: the Pen path being drawn, the active paths, then @@ -303,7 +308,7 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - app.ui.direct_selection.drag = Some(Drag::Marquee { start: p, end: p, add: mods.shift }); return true; }; - if let PathRef::Layer(id) = target + if let PathRef::Layer(id) | PathRef::TypePath(id) = target && app.session.active().and_then(|st| st.active_layer).map(|l| l.0) != Some(id) { let _ = app.run("layer.select", json!({"layer": id})); diff --git a/crates/ui-egui/src/direct_select_tests.rs b/crates/ui-egui/src/direct_select_tests.rs index 38064a8c07..27a9fc59d8 100644 --- a/crates/ui-egui/src/direct_select_tests.rs +++ b/crates/ui-egui/src/direct_select_tests.rs @@ -532,7 +532,7 @@ fn dragging_an_anchor_of_type_on_a_path_moves_the_type() { }; let n = steps(&app); drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE); - assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(id)), "the type path, in front of the work path"); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::TypePath(id)), "the type path, in front of the work path"); let end = type_path(&app).subpaths[0].knots[1].anchor; assert!((end.x - 160.0).abs() < 1e-6 && (end.y - 180.0).abs() < 1e-6, "{end:?}"); assert_eq!(work(&app).subpaths[0].knots[1].anchor, Point::new(100.0, 180.0), "the work path stays"); @@ -540,3 +540,32 @@ fn dragging_an_anchor_of_type_on_a_path_moves_the_type() { assert!(app.session.undo()); assert_eq!(type_path(&app).subpaths[0].knots[1].anchor.x.round(), 100.0); } + +/// #9114: with a type-on-a-path layer's vector mask targeted, Direct Selection edits the mask, not +/// the Type Path; untargeted, it edits the Type Path and the mask stays. +#[test] +fn a_targeted_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { + let mut app = app(Tool::DirectSelection); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap(); + let id = app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap()["layer"].as_u64().unwrap(); + app.run("type.attachToPath", json!({})).unwrap(); + let rect = json!({"subpaths": [{"closed": true, "knots": [[20, 20], [180, 20], [180, 160], [20, 160]]}]}); + app.run("layer.vectorMask.add", json!({"layer": id, "path": rect})).unwrap(); + app.ui.vector_mask_target = true; + let layer = |app: &PhotocraftApp| app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().clone(); + let type_path = |app: &PhotocraftApp| match &layer(app).content { + photocraft_doc::LayerContent::Text(t) => photocraft_engine::type_extra_cmds::type_path(t).unwrap(), + _ => panic!("not a type layer"), + }; + let before = type_path(&app); + drag(&mut app, [20.2, 20.2], [40.2, 30.2], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(id))); + assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0), "the mask's corner moved"); + assert_eq!(type_path(&app), before, "the Type Path stays"); + // With the mask no longer targeted, the Type Path is in front again and the mask stays. + app.ui.vector_mask_target = false; + drag(&mut app, [100.2, 180.2], [160.2, 180.2], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::TypePath(id))); + assert!((type_path(&app).subpaths[0].knots[1].anchor.x - 160.0).abs() < 1e-6); + assert_eq!(layer(&app).vector_mask.unwrap().path.subpaths[0].knots[0].anchor, Point::new(40.0, 30.0)); +} diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index a0da93d511..79442e9448 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -1229,6 +1229,10 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some((_, p)) = targeted_vector_mask(app) { draw_path(&p, anchors); } + // So does type on a path's Type Path, which the Pen's Auto Add/Delete edits (#9114). + if let Some((_, p)) = active_type_path(app) { + draw_path(&p, anchors); + } crate::corner_radius::draw(app, painter, &to_scr, accent); } // Pen path in progress, with handles of the last knot and a rubber band to the pointer. While @@ -2282,6 +2286,19 @@ mod tests { } } + /// #9114: the active type layer's Type Path shows with the Pen, whose Auto Add/Delete edits it. + #[test] + fn the_type_path_of_type_on_a_path_is_drawn_with_the_pen() { + let ctx = egui::Context::default(); + let mut app = app(); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[100, 20], [100, 180]]}]}})).unwrap(); + app.run("type.create", json!({"x": 20, "y": 70, "text": "On a path", "size": 24})).unwrap(); + app.run("type.attachToPath", json!({})).unwrap(); + app.run("path.delete", json!({"name": "work"})).unwrap(); + app.ui.tool = Tool::Pen; + assert!(overlay_shapes(&app, &ctx) > 0, "the Type Path is drawn"); + } + #[test] fn show_target_path_and_extras_hide_the_path_outlines() { // #1119: View › Show › Target Path only flipped its checkmark; the canvas kept drawing the From 041aac9ecbc0f3a9af39c0a89b19beae6602fb53 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 13:28:27 +0100 Subject: [PATCH 63/87] Integration: folder batches skip raws that open only as the preview (#9097) Listing every photocraft_raw extension also picked up CR3, ORF, RAF, RW2, SRF and SR2. The raw decoder can't read CR3, compressed ORF and RAF, or RW2 raw formats other than 3, 4 and 5 yet; import then falls back to the embedded JPEG preview with only a warning, so a folder batch would process the thumbnail silently. The folder list now takes the raws whose usual files decode (DNG, CR2, NEF, NRW, ARW, PEF), and the test pins both sides. Port of the reviewed fix-up 202ce9c2a (davidmann4/photocraft pr-9097-fixup) to this batch's file layout: same changed lines, in file_cmds.rs instead of main's later file_cmds/paths.rs split. Co-authored-by: .CooCoo <1206598+dotCooCoo@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/file_cmds.rs | 21 +++++++++++++-------- crates/engine/src/file_cmds/tests.rs | 18 +++++++++--------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ea7e77054e..2bf149675b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -117,21 +117,26 @@ pub fn list_images(dir: &str) -> Result> { } /// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, an extension -/// of a format `photocraft-codecs` reads in this build, a camera raw extension, or GIMP's gzipped -/// `.xcf.gz`, whose last extension alone says nothing. +/// of a format `photocraft-codecs` reads in this build, or GIMP's gzipped `.xcf.gz`, whose last +/// extension alone says nothing. #[cfg(not(target_arch = "wasm32"))] fn openable_name(path: &str) -> bool { let lower = file_name(path).to_ascii_lowercase(); lower.ends_with(".xcf.gz") - || lower.rsplit_once('.').is_some_and(|(_, ext)| { - OPENABLE.contains(&ext) || photocraft_io::raw::EXTENSIONS.contains(&ext) || photocraft_codecs::from_extension(ext).is_some_and(|f| f.caps().read) - }) + || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext) || photocraft_codecs::from_extension(ext).is_some_and(|f| f.caps().read)) } -/// Extensions of the document and vector formats the batch commands pick up from a folder: -/// those `photocraft_io::import` reads outside `photocraft-codecs` and the camera raw reader. +/// Extensions the batch commands pick up from a folder besides the codec formats: the document +/// and vector formats `photocraft_io::import` reads outside `photocraft-codecs`, and the camera +/// raws whose usual files `photocraft_raw::decode` develops. Not CR3, ORF, RAF, RW2, SRF or SR2: +/// CR3, compressed ORF and RAF and RW2 raw formats other than 3, 4 and 5 aren't decoded yet, and +/// import falls back to the embedded JPEG preview with only a warning, which a batch must not +/// process silently. #[cfg(not(target_arch = "wasm32"))] -const OPENABLE: &[&str] = &["pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "af", "afdesign", "afphoto", "afpub"]; +const OPENABLE: &[&str] = &[ + "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "af", "afdesign", "afphoto", "afpub", "dng", "cr2", "nef", + "nrw", "arw", "pef", +]; /// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone /// Background layer). The UI asks before such a save when the "ask before saving layered TIFF" diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs index 27a05101b7..7eb770d844 100644 --- a/crates/engine/src/file_cmds/tests.rs +++ b/crates/engine/src/file_cmds/tests.rs @@ -1835,16 +1835,16 @@ fn folder_listing_recognises_gzipped_xcf_by_its_double_extension() { assert!(!super::openable_name("notes.txt")); } -/// A folder batch picks up every extension that the codecs and the camera raw reader open: -/// Cineon, DICOM, Amiga IFF, PCX, XPM, DDS, the Netpbm family, Photoshop templates and the CR3, -/// ORF, RW2, RAF, SRF and SR2 raws. +/// A folder batch picks up every extension that the codecs open: Cineon, DICOM, Amiga IFF, PCX, +/// XPM, DDS, the Netpbm family, and Photoshop templates. Not the raws whose usual files open only +/// as the embedded JPEG preview (CR3, compressed ORF and RAF, RW2 other than raw formats 3, 4 and +/// 5): a batch would process the thumbnail without a word. #[cfg(not(target_arch = "wasm32"))] #[test] fn folder_listing_takes_every_format_photocraft_opens() { - for name in [ - "a.cin", "a.dcm", "a.dicom", "a.dc3", "a.iff", "a.lbm", "a.ilbm", "a.pcx", "a.xpm", "a.dds", "a.pbm", "a.pam", "a.pfm", "a.psdt", "a.cr3", "a.orf", - "a.rw2", "a.raf", "a.srf", "a.sr2", "A.PCX", - ] { + let codecs = ["a.cin", "a.dcm", "a.dicom", "a.dc3", "a.iff", "a.lbm", "a.ilbm", "a.pcx", "a.xpm", "a.dds", "a.pbm", "a.pam", "a.pfm", "a.psdt", "A.PCX"]; + let raws = ["a.dng", "IMG_0001.CR2", "a.nef", "a.nrw", "a.arw", "a.pef"]; + for name in codecs.into_iter().chain(raws) { assert!(super::openable_name(name), "{name}"); } for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read) { @@ -1852,8 +1852,8 @@ fn folder_listing_takes_every_format_photocraft_opens() { assert!(super::openable_name(&format!("a.{ext}")), "{f:?} .{ext}"); } } - for ext in photocraft_io::raw::EXTENSIONS { - assert!(super::openable_name(&format!("a.{ext}")), ".{ext}"); + for name in ["a.cr3", "IMG_0001.CR3", "a.orf", "a.raf", "a.rw2", "a.srf", "a.sr2"] { + assert!(!super::openable_name(name), "{name}"); } // PhotoCraft does not read AVIF. assert!(!super::openable_name("a.avif")); From 362947695da18b0dd3c5dc88c485b63de50608ce Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 13:28:32 +0100 Subject: [PATCH 64/87] Integration: a source read error in the layer records fails the open (#6583) The lazy parse took any error from read_layer_info on a Layr/Lr16/Lr32 global block as a damaged block and dropped the layers. A failed read of the source (PsdError::Read: a dropped network share, a file rewritten while it opens) then let a 16/32-bit layered file open silently from its merged image, with no damage warning, and a save replaced its layers. A read error now fails the parse, as reading the whole file would. The new test fails each read of a clean parse once, in turn, and checks the parse either fails with the read error or matches from_bytes; with the fix reverted, read 20 of the Lr16 sample drops the layers silently. Found by CodeRabbit's review of the PR. Co-authored-by: ptrinh <774083+ptrinh@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/psd/src/lazy.rs | 52 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/psd/src/lazy.rs b/crates/psd/src/lazy.rs index d22661abb5..8b6f54b533 100644 --- a/crates/psd/src/lazy.rs +++ b/crates/psd/src/lazy.rs @@ -182,11 +182,17 @@ impl PsdFile { return Ok(None); } candidate_seen = true; - let Ok(info) = read_layer_info(data, version) else { - if target_key.is_some() { - layer_info = None; + let info = match read_layer_info(data, version) { + Ok(info) => info, + // A failed read of the source is not damage: fail the parse, as + // reading the whole file would. + Err(e @ PsdError::Read(_)) => return Err(e), + Err(_) => { + if target_key.is_some() { + layer_info = None; + } + return Ok(None); } - return Ok(None); }; layer_info = Some(info); layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature, key, padding: padding.clone() }; @@ -375,4 +381,42 @@ mod tests { } } } + + /// A source whose `fail_at`-th read fails once. + struct FailOnce { + bytes: Vec, + fail_at: usize, + reads: std::sync::atomic::AtomicUsize, + } + + impl crate::source::ReadAt for FailOnce { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { + if self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == self.fail_at { + return Err(PsdError::Read("injected".into())); + } + self.bytes.read_at(offset, buf) + } + } + + #[test] + fn a_failed_read_fails_the_parse_instead_of_dropping_the_layers() { + for bytes in samples() { + let eager = PsdFile::from_bytes(&bytes).unwrap(); + let clean = std::sync::Arc::new(FailOnce { bytes: bytes.clone(), fail_at: usize::MAX, reads: 0.into() }); + PsdFile::from_source(Source::from_arc(clean.clone())).unwrap(); + let reads = clean.reads.load(std::sync::atomic::Ordering::SeqCst); + for fail_at in 0..reads { + let src = FailOnce { bytes: bytes.clone(), fail_at, reads: 0.into() }; + match PsdFile::from_source(Source::new(src)) { + Err(PsdError::Read(_)) => {} + Ok(lazy) => assert_eq!(lazy, eager, "read {fail_at} failed silently"), + Err(e) => panic!("read {fail_at}: {e:?}"), + } + } + } + } } From c65b7d93d65027e14a608f3407b9fd99f5cef5b1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 13:17:49 +0100 Subject: [PATCH 65/87] Integration: file-size bound fits DWA EXR, RLE BMP and GIF screens (#8704) The new plausibility check refused valid files that main opens: - EXR DWAA/DWAB parts: they go past 2^16:1 (a flat 8192x4320 DWAB frame with 12 alpha-scheme mattes is 29,948 bytes, 75,629:1; run-length channels zlib-packed on top reach about 132,000:1). DWA parts now get 2^18:1, so a header of a few hundred bytes can ask for about 100 MB, not gigabytes. - BMP RLE8/RLE4: end-of-line, end-of-bitmap and delta escapes leave pixels unwritten, so no ratio bounds a valid file (an EOB-only 4000x4000 RLE8 is 1,080 bytes). Skipped like HDR. - GIF: the decoder's size is the logical screen, which needs no data (a 4000x4000 screen with a 1x1 frame is 35 bytes). The first frame must be backed, and the screen only past 256 MiB, so a 35-byte GIF still can't declare a 30000x30000 screen. The declared-size products saturate: a Radiance header of 2^31 x 2^31 read without limits overflowed u64 in debug builds. Co-authored-by: FinnNk <1424666+FinnNk@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/codecs/src/codecs/exr.rs | 16 +++-- crates/codecs/src/codecs/via_image.rs | 56 ++++++++++++++--- crates/codecs/tests/it/limits.rs | 87 +++++++++++++++++++++++++++ 3 files changed, 148 insertions(+), 11 deletions(-) diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index 9640d69d5d..e179b13044 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -39,21 +39,29 @@ pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result limits.max_alloc { return Err(CodecError::LimitExceeded(format!("{total} bytes across {} parts exceed max_alloc {}", meta.headers.len(), limits.max_alloc))); } // The `exr` crate allocates a flat part's samples before reading its chunks, so the file - // must be able to hold them (#8597). Lossless EXR compression stays far below 2^16:1 even - // against this f32 budget; deep parts size their samples from the file's own counts. + // must be able to hold them (#8597). The other compressions stay far below 2^16:1 even + // against this f32 budget. DWA's run-length channels are zlib-packed on top and reach about + // 132000:1, so DWA parts get 2^18:1. Deep parts size their samples from the file's own counts. if !meta.requirements.has_deep_data { - Limits::check_plausible(total, bytes.len(), 1 << 16)?; + Limits::check_plausible(total.saturating_sub(dwa).saturating_add(dwa / 4), bytes.len(), 1 << 16)?; } Ok(meta) } diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs index 5269c94b12..0cb0bd4202 100644 --- a/crates/codecs/src/codecs/via_image.rs +++ b/crates/codecs/src/codecs/via_image.rs @@ -97,11 +97,20 @@ fn open<'a>(f: Format, bytes: &'a [u8], limits: &Limits) -> Result u64::from(fw).saturating_mul(u64::from(fh)).saturating_mul(bpp).max(declared.saturating_sub(1 << 28)), + _ => declared, + }; + if !matches!(f, Format::Avif | Format::Hdr) && !(f == Format::Bmp && bmp_is_rle(bytes)) { + Limits::check_plausible(declared, bytes.len(), 1 << 14)?; } Ok(dec) } @@ -132,9 +141,36 @@ pub(crate) fn probe(f: Format, bytes: &[u8], limits: &Limits) -> Result<(u32, u3 Ok((w, h, dec.exif_metadata().ok().flatten())) } +/// Whether a BMP's `biCompression` is RLE8 or RLE4 (only headers of 40 bytes or more have one). +fn bmp_is_rle(b: &[u8]) -> bool { + let u32_at = |at: usize| b.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + u32_at(14).is_some_and(|n| n >= 40) && matches!(u32_at(30), Some(1 | 2)) +} + +/// The width and height of a GIF's first image descriptor, if the blocks reach one. +fn gif_first_frame(b: &[u8]) -> Option<(u32, u32)> { + let mut at = None; + gif_walk(b, |i| { + at = Some(i); + false + }); + let u16_at = |at: usize| b.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + // Descriptor: separator, left, top, width, height (little-endian u16s), packed fields. + let i = at?; + Some((u32::from(u16_at(i + 5)?), u32::from(u16_at(i + 7)?))) +} + /// Counts a GIF's frames (image descriptors) by walking its blocks, without decompressing any. /// The total is unknown when the blocks end before the trailer or break off. fn gif_more_frames(b: &[u8]) -> Option { + let (frames, total) = gif_walk(b, |_| true); + (frames > 1).then_some(DecodeWarning::MoreFrames { total }) +} + +/// Walks a GIF's blocks without decompressing any, handing `frame` the offset of each image +/// descriptor until it returns false. Gives the descriptors seen, and the frame count if the +/// blocks reached the trailer. +fn gif_walk(b: &[u8], mut frame: impl FnMut(usize) -> bool) -> (u32, Option) { // Size of the colour table a packed-fields byte announces. let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 }; // Skips the data sub-blocks starting at `i` (each length-prefixed, ended by a zero length). @@ -148,7 +184,10 @@ fn gif_more_frames(b: &[u8]) -> Option { } }; // Header (6 bytes), logical screen descriptor (7) and the global colour table. - let mut i = 13 + table(*b.get(10)?); + let Some(&flags) = b.get(10) else { + return (0, None); + }; + let mut i = 13 + table(flags); let mut frames = 0u32; let total = loop { let next = match b.get(i) { @@ -156,6 +195,9 @@ fn gif_more_frames(b: &[u8]) -> Option { Some(0x21) => skip(i + 2), Some(0x2C) => { frames = frames.saturating_add(1); + if !frame(i) { + break None; + } // Descriptor (10 bytes, packed fields last), local colour table, LZW code size. b.get(i + 9).and_then(|&flags| skip(i + 11 + table(flags))) } @@ -166,7 +208,7 @@ fn gif_more_frames(b: &[u8]) -> Option { None => break None, } }; - (frames > 1).then_some(DecodeWarning::MoreFrames { total }) + (frames, total) } pub(crate) fn from_dynamic(f: Format, d: DynamicImage) -> Result { diff --git a/crates/codecs/tests/it/limits.rs b/crates/codecs/tests/it/limits.rs index 951257bb82..536e303039 100644 --- a/crates/codecs/tests/it/limits.rs +++ b/crates/codecs/tests/it/limits.rs @@ -398,6 +398,12 @@ fn pnm_header_alone_reserves_nothing_without_limits() { } } +#[test] +fn hdr_header_sizes_that_overflow_u64_are_errors_without_limits() { + let b = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 2147483648 +X 2147483648\n"; + assert!(decode_with(b, &opts(Limits::none())).is_err()); +} + #[test] fn pnm_header_sizes_that_overflow_usize_are_errors_without_limits() { let m = u32::MAX; @@ -501,6 +507,61 @@ fn image_crate_headers_declaring_gigabytes_need_a_plausible_file_size() { gif[6..8].copy_from_slice(&(side as u16).to_le_bytes()); gif[8..10].copy_from_slice(&(side as u16).to_le_bytes()); refused_as_implausible(Format::Gif, &gif); + // The frame too. Descriptor: separator, left, top, width, height. + let frame = find(&gif, &[0x2C, 0, 0, 0, 0, 64, 0, 48, 0]); + gif[frame + 5..frame + 7].copy_from_slice(&(side as u16).to_le_bytes()); + gif[frame + 7..frame + 9].copy_from_slice(&(side as u16).to_le_bytes()); + refused_as_implausible(Format::Gif, &gif); +} + +/// GIF89a with a two-colour global table and one frame at the top left holding no pixels or +/// one pixel (LZW minimum code size 2: clear, index 0, end of information). +fn tiny_gif(screen: (u16, u16), frame: (u16, u16)) -> Vec { + let mut b = b"GIF89a".to_vec(); + for v in [screen.0, screen.1] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(&[0x80, 0, 0, 0, 0, 0, 255, 255, 255, 0x2C, 0, 0, 0, 0]); + for v in [frame.0, frame.1] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(&[0, 2, 2, 0x44, 0x01, 0, 0x3B]); + b +} + +#[test] +fn a_gif_frame_much_smaller_than_its_screen_still_decodes() { + let img = decode(&tiny_gif((4000, 4000), (1, 1))).unwrap(); + assert_eq!((img.width(), img.height()), (4000, 4000)); +} + +#[test] +fn a_tiny_gif_frame_does_not_admit_a_gigabyte_screen() { + refused_as_implausible(Format::Gif, &tiny_gif((30000, 30000), (1, 1))); + // 324 MB of screen: past the 256 MiB that needs no data. + refused_as_implausible(Format::Gif, &tiny_gif((9000, 9000), (1, 1))); + refused_as_implausible(Format::Gif, &tiny_gif((30000, 30000), (0, 0))); + // A frame bigger than its screen is decoded at its own size. + refused_as_implausible(Format::Gif, &tiny_gif((100, 100), (40000, 40000))); +} + +#[test] +fn an_rle_bmp_ending_early_still_decodes() { + // 4000x4000 RLE8 whose only data is the end-of-bitmap escape: every pixel is left at index 0. + let data = 14 + 40 + 1024; + let mut b = b"BM".to_vec(); + for v in [data + 2, 0, data, 40, 4000, 4000] { + b.extend_from_slice(&(v as u32).to_le_bytes()); + } + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&8u16.to_le_bytes()); + for v in [1, 2, 0, 0, 0, 0] { + b.extend_from_slice(&(v as u32).to_le_bytes()); + } + b.resize(data, 0); + b.extend_from_slice(&[0, 1]); + let img = decode(&b).unwrap(); + assert_eq!((img.width(), img.height()), (4000, 4000)); } #[test] @@ -543,6 +604,32 @@ fn exr_header_declaring_gigabytes_needs_a_plausible_file_size() { refused_as_implausible(Format::OpenExr, &b); } +#[test] +fn a_dwab_exr_gets_a_looser_file_size_bound() { + // DWA passes 2^16:1 (a flat 8K frame with 12 alpha-scheme mattes is about 30 KB), so a DWAB + // part may declare 4 times more than a ZIP part from the same file, and no more. + let img = synth(1, 1, ChannelLayout::Rgba, SampleType::U8, 1, 0.1); + let mut b = encode(&img, Format::OpenExr, &EncodeOptions::default()).unwrap(); + let at = find(&b, b"dataWindow\0box2i\0") + b"dataWindow\0box2i\0".len() + 4; + let c = find(&b, b"compression\0compression\0") + b"compression\0compression\0".len() + 4; + // RGBA as f32: 16 bytes a pixel against a file of a few hundred bytes. + let size = |b: &mut Vec, side: i32| { + b[at + 8..at + 12].copy_from_slice(&(side - 1).to_le_bytes()); + b[at + 12..at + 16].copy_from_slice(&(side - 1).to_le_bytes()); + }; + let refused = |b: &[u8]| matches!(exr_info(b, &Limits::default()), Err(CodecError::LimitExceeded(m)) if m.contains("cannot hold")); + size(&mut b, 2048); + b[c] = 3; // ZIP + assert!(refused(&b), "{} bytes", b.len()); + for dwa in [8, 9] { + b[c] = dwa; // DWAA, DWAB + let parts = exr_info(&b, &Limits::default()).unwrap(); + assert_eq!((parts[0].width, parts[0].height), (2048, 2048)); + } + size(&mut b, 4096); + assert!(refused(&b), "{} bytes", b.len()); +} + #[test] fn highly_compressible_jpeg_and_gif_still_decode() { let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap(); From ac9b374fabe887d61cf25438dbd98211d386db57 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 13:57:20 +0100 Subject: [PATCH 66/87] Integration: Remove trail shows thin strokes on big documents (#8923) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The trail mask is at most 1024 px on its long side, so on a big document one mask pixel stands for k x k document pixels, and the Remove trail sampled only each block's centre. A thin stroke that fell between the centres (2 px on 6000x4000, k = 6; 4 px on 12000x8000, k = 12) showed no tint at all, though every pixel it touched is removed. In reach mode a mask pixel now takes the largest coverage of its whole block, clipped to the document. Blocks no coverage tile reaches are skipped (StrokeRenderer::touches), so releasing a whole stroke on a 30000x20000 document restamps in 0.22 s instead of 23 s. Also pins the waiting strokes' kept tint where a later stroke restamps its rectangle off its own path (fails with the base max removed). Co-authored-by: Hartmut Nörenberg <55043719+hnoerenberg@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/brush_tests.rs | 35 +++++++++++++ crates/paint/src/render.rs | 15 ++++++ crates/ui-egui/src/stroke_trail.rs | 82 +++++++++++++++++++++++++++--- 3 files changed, 124 insertions(+), 8 deletions(-) diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index d71e245fc5..e4193ba78e 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -1735,3 +1735,38 @@ fn resizing_with_bad_sizes_leaves_the_dual_tip_alone() { b.resize_with_dual_brush(50.0); assert_eq!(b.dual_brush.size, 20.0); } + +/// `touches` is true wherever `coverage_at` can be above 0, false only where it is 0 for sure. +#[test] +fn touches_covers_every_pixel_with_coverage() { + let b = BrushSettings { size: 6.0, ..brush() }; + let mut r = StrokeRenderer::new(&b, None, 1.0); + r.push(&line(100.0, 300.0, 200.0)); + r.finish(); + for y in (0..400).step_by(3) { + for x in (0..500).step_by(3) { + if r.coverage_at(x, y) > 0.0 { + assert!(r.touches(Rect::new(x, y, x + 1, y + 1)), "({x}, {y})"); + } + } + } + // Across the origin and tile edges (64 px): every pixel, both sides of each edge. + let mut o = StrokeRenderer::new(&b, None, 1.0); + o.push(&[StrokePoint::new(-70.0, -70.0, 1.0), StrokePoint::new(70.0, 70.0, 1.0)]); + o.finish(); + for y in -140..140 { + for x in -140..140 { + if o.coverage_at(x, y) > 0.0 { + assert!(o.touches(Rect::new(x, y, x + 1, y + 1)), "({x}, {y})"); + } + } + } + assert!(!o.touches(Rect::new(-128, 64, -64, 128)), "a tile the diagonal misses"); + assert!(!o.touches(Rect::new(-200, -200, -128, -128)), "ends exactly at a tile edge"); + assert!(o.touches(Rect::new(-200, -200, -127, -127)), "one pixel into the next tile"); + assert!(r.touches(Rect::new(150, 199, 151, 201))); + assert!(!r.touches(Rect::new(0, 0, 50, 50)), "far from the stroke"); + assert!(!r.touches(Rect::new(400, 400, 400, 400)), "empty"); + assert!(r.touches(Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX)), "huge, without a huge scan"); + assert!(!r.touches(Rect::new(1_000_000, 1_000_000, i32::MAX, i32::MAX))); +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index b68e7a3190..84856b5773 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -927,6 +927,21 @@ impl StrokeRenderer { self.ctx.stroke_mask_wet(c, self.cov.depth(x, y), self.dual.as_ref().map(|d| d.get(x, y)), x, y) } + /// Whether any coverage tile overlaps `r`: outside them [`coverage_at`](Self::coverage_at) is + /// 0, so a caller scanning a big area can skip it. + pub fn touches(&self, r: Rect) -> bool { + if r.is_empty() { + return false; + } + let (t0x, t0y) = (r.x0.div_euclid(COV_TILE), r.y0.div_euclid(COV_TILE)); + let (t1x, t1y) = ((r.x1 - 1).div_euclid(COV_TILE), (r.y1 - 1).div_euclid(COV_TILE)); + let span = (i64::from(t1x) - i64::from(t0x) + 1).saturating_mul(i64::from(t1y) - i64::from(t0y) + 1); + if span > self.cov.tiles.len() as i64 { + return self.cov.tiles.keys().any(|&(tx, ty)| (t0x..=t1x).contains(&tx) && (t0y..=t1y).contains(&ty)); + } + (t0y..=t1y).any(|ty| (t0x..=t1x).any(|tx| self.cov.tiles.contains_key(&(tx, ty)))) + } + /// Dense final coverage over the stroke bounds. pub fn dense_coverage(&self) -> (Rect, Vec) { let b = self.bounds(); diff --git a/crates/ui-egui/src/stroke_trail.rs b/crates/ui-egui/src/stroke_trail.rs index 0ea62c6a97..4a087be890 100644 --- a/crates/ui-egui/src/stroke_trail.rs +++ b/crates/ui-egui/src/stroke_trail.rs @@ -126,13 +126,19 @@ impl Trail { let tail = tail.map(|(_, t)| t); let renderer = &dabs.renderer; let full = |c: f32| if dabs.reach && c > 0.0 { 1.0 } else { c }; - self.restamp(changed, |x, y| full(renderer.coverage_at(x, y).max(tail.as_ref().map_or(0.0, |t| t.coverage_at(x, y))))); + let reach = dabs.reach; + let touches = |r| renderer.touches(r) || tail.as_ref().is_some_and(|t| t.touches(r)); + self.restamp(changed, reach, touches, |x, y| full(renderer.coverage_at(x, y).max(tail.as_ref().map_or(0.0, |t| t.coverage_at(x, y))))); self.dabs = Some(dabs); } /// Recompute the mask pixels over the document rectangle `r` from `cov` (document pixel → - /// coverage 0..=1), sampled at each mask pixel's centre. - fn restamp(&mut self, r: photocraft_geom::Rect, cov: impl Fn(i32, i32) -> f32) { + /// coverage 0..=1), sampled at each mask pixel's centre. With `block`, a mask pixel takes the + /// largest coverage of all the document pixels it stands for instead: on a big document (one + /// mask pixel per k x k) a thin Remove stroke can fall between the centres, and every pixel it + /// touches is removed. `touches` says whether `cov` can be above 0 anywhere in a document + /// rectangle, so blocks the stroke never reached aren't scanned pixel by pixel. + fn restamp(&mut self, r: photocraft_geom::Rect, block: bool, touches: impl Fn(photocraft_geom::Rect) -> bool, cov: impl Fn(i32, i32) -> f32) { if r.is_empty() { return; } @@ -144,14 +150,39 @@ impl Trail { if x1 <= x0 || y1 <= y0 { return; } + // Document pixels of mask pixel `i` along a side `n` long: its centre, or its whole span + // clipped to the document (at least one pixel). + let span = |i: usize, n: u32| -> (i32, i32) { + if block { + let lo = (i as f64 * k) as i64; + let hi = (((i + 1) as f64 * k) as i64).min(i64::from(n)).max(lo + 1); + (i32::try_from(lo).unwrap_or(i32::MAX), i32::try_from(hi).unwrap_or(i32::MAX)) + } else { + let c = ((i as f64 + 0.5) * k).floor() as i32; + (c, c.saturating_add(1)) + } + }; for y in y0..y1 { - let dy = ((y as f64 + 0.5) * k).floor() as i32; + let (dy0, dy1) = span(y, self.doc[1]); for x in x0..x1 { - let dx = ((x as f64 + 0.5) * k).floor() as i32; - let c = cov(dx, dy); - let c = if c.is_finite() { (c.clamp(0.0, 1.0) * 255.0).round() as u8 } else { 0 }; + let (dx0, dx1) = span(x, self.doc[0]); let i = y * self.w + x; - let c = c.max(self.base.get(i).copied().unwrap_or(0)); + let base = self.base.get(i).copied().unwrap_or(0); + let mut c = 0.0f32; + let skip = base == u8::MAX || !touches(photocraft_geom::Rect::new(dx0, dy0, dx1, dy1)); + 'block: for dy in if skip { 0..0 } else { dy0..dy1 } { + for dx in dx0..dx1 { + let v = cov(dx, dy); + if v > c { + c = v; + if c >= 1.0 { + break 'block; + } + } + } + } + let c = if c.is_finite() { (c.clamp(0.0, 1.0) * 255.0).round() as u8 } else { 0 }; + let c = c.max(base); if let Some(v) = self.cov.get_mut(i) { *v = c; } @@ -312,6 +343,41 @@ mod tests { assert_eq!(t.coverage(40, 40), 0); } + /// On a big document one mask pixel stands for k x k document pixels. A thin Remove stroke + /// that falls between the mask pixels' centres still removes what it touches, so it still + /// shows. + #[test] + fn a_thin_reach_stroke_on_a_big_document_still_shows() { + // A 2 px brush reaches document rows 10-14, a 4 px one rows 9-16; the mask's centres + // sample rows 9 and 15 at k = 6, rows 6 and 18 at k = 12. + for (doc, size) in [([6000, 4000], 2.0), ([12000, 8000], 4.0)] { + let brush = BrushSettings { size, hardness: 1.0, ..Default::default() }; + let pts = [[300.0, 12.5, 1.0], [3000.0, 12.5, 1.0]]; + let mut t = Trail::new(doc); + t.feed_reach(&pts, || brush.clone()); + let x = (1500.0 / t.scale()) as usize; + assert!((0..3).any(|y| t.coverage(x, y) == 255), "{size} px on {doc:?}: the stroke shows"); + assert_eq!(t.coverage(x, 3), 0, "{size} px on {doc:?}: nothing below it"); + let mut s = Trail::new(doc); + s.feed_stroke_reach(&pts, || brush.clone()); + assert!((0..3).any(|y| s.coverage(x, y) == 255), "{size} px on {doc:?}: a waiting stroke too"); + } + } + + /// A later stroke restamps its whole dirty rectangle, earlier strokes' tint included, also + /// off its own path. + #[test] + fn a_crossing_reach_stroke_keeps_the_earlier_tint_inside_its_rect() { + let mut t = Trail::new([200, 200]); + let brush = BrushSettings { size: 20.0, ..Default::default() }; + t.feed_stroke_reach(&[[20.0, 100.0, 1.0], [180.0, 100.0, 1.0]], || brush.clone()); + t.feed_stroke_reach(&[[20.0, 20.0, 1.0], [180.0, 180.0, 1.0]], || brush.clone()); + assert_eq!(t.coverage(150, 100), 255, "the first stroke, off the second, inside its rect"); + assert_eq!(t.coverage(50, 100), 255); + assert_eq!(t.coverage(150, 150), 255, "the second stroke"); + assert_eq!(t.coverage(150, 40), 0); + } + #[test] fn hostile_points_and_huge_documents_are_safe() { let mut t = Trail::new([300_000, 2]); From 0b09eb43a5bc0ac326e58dcca643371aaed74953 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 14:19:41 +0100 Subject: [PATCH 67/87] Integration: per-band AHD balancing, memory-capped fused bands (#9455) `for_bands_grouped` always split the bands into `min(workers, jobs)` static chunks, so on the default develop (jobs == workers) a worker held up on the shared pool kept a fixed share of the bands waiting, where main's `chunks_mut_limited` runs one rayon task per band. Now, when every worker may hold a scratch, each band is its own task and borrows a scratch from a pool (`par::chunks_mut_pooled`, at most one per worker, dropped as soon as no waiting band can use it); the grouping stays for memory-limited jobs. The fused bilinear/MHC, X-Trans and LinearRaw paths ran one band per worker with no memory cap: a 262144 x 455 Bayer frame with bilinear needed 2.92 GB at 15+ workers and failed with LimitExceeded under the default 2 GiB. `working_memory` now caps those bands like AHD's and the fused paths use the returned jobs. The fused LinearRaw and X-Trans band buffers are `band.min(h)` rows, as charged (CodeRabbit, develop.rs:414). Tests: a_slow_band_does_not_hold_up_the_bands_after_it and fused_bands_at_once_are_capped_by_the_memory_limit fail without the fix; for_bands_keeps_at_most_jobs_scratches_alive, chunks_mut_pooled_makes_one_state_per_worker_at_most, multi-band and short X-Trans/LinearRaw fused-vs-full cases. Co-authored-by: Valentin Klein <271991477+vangel76@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/raw/src/demosaic.rs | 156 ++++++++++++++++++++++++++++++------- crates/raw/src/develop.rs | 70 ++++++++++++----- crates/raw/src/par.rs | 66 ++++++++++++++++ 3 files changed, 244 insertions(+), 48 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 86bcee5f3c..6303931811 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -232,7 +232,7 @@ pub(crate) fn demosaic_fused( phase: [u8; 4], method: Demosaic, to_xyz: &Mat3, - ahd_jobs: usize, + jobs: usize, fill: &(impl Fn(usize, &mut [f32]) + Sync), out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync), @@ -257,7 +257,7 @@ pub(crate) fn demosaic_fused( // The rows of the tallest band, as `develop`'s memory check counts them. let rows = h.min(AHD_BAND); let init = || (AhdScratch::for_image(h, s), vec![0.0f32; rows * w * 3], vec![0.0f32; (rows + 2 * PAD) * s]); - for_bands_grouped(out, AHD_BAND * w * 3, ahd_bands(h), ahd_jobs, 1, init, |band, chunk, (sc, buf, win)| { + for_bands_grouped(out, AHD_BAND * w * 3, ahd_bands(h), jobs, 1, init, |band, chunk, (sc, buf, win)| { load(win, band * AHD_BAND, chunk.len() / (w * 3)); let buf = &mut buf[..chunk.len()]; // The window starts at a multiple of AHD_BAND (even), so it is band 0 of its own rows. @@ -269,7 +269,7 @@ pub(crate) fn demosaic_fused( let ks = kernels(phase, method, s); let rows = h.min(FUSED_ROWS); let init = || (vec![0.0f32; rows * w * 3], vec![0.0f32; (rows + 2 * PAD) * s]); - for_bands(out, FUSED_ROWS * w * 3, h.div_ceil(FUSED_ROWS), usize::MAX, init, |band, chunk, (buf, win)| { + for_bands(out, FUSED_ROWS * w * 3, h.div_ceil(FUSED_ROWS), jobs, init, |band, chunk, (buf, win)| { load(win, band * FUSED_ROWS, chunk.len() / (w * 3)); let buf = &mut buf[..chunk.len()]; linear_band(win, w, s, phase, method, &ks, band * FUSED_ROWS, band * FUSED_ROWS, buf); @@ -318,15 +318,16 @@ fn linear_band(d: &[f32], w: usize, s: usize, phase: [u8; 4], method: Demosaic, } /// Runs `f(band, chunk, scratch)` over the `unit`-sized chunks of `out` (`bands` of them), with -/// at most `jobs` scratch values alive: a few groups of consecutive bands per worker (for -/// balance), each group building its scratch once. For a scratch that is cheap to build. -pub(crate) fn for_bands( +/// at most `jobs` scratch values alive. When every worker may hold one, each band is its own +/// rayon task and borrows a scratch from a pool (one per worker at most); otherwise a few groups +/// of consecutive bands per job run, `jobs` at a time, each building its scratch once. +pub(crate) fn for_bands( out: &mut [T], unit: usize, bands: usize, jobs: usize, - init: impl Fn() -> S + Sync, - f: impl Fn(usize, &mut [T], &mut S) + Sync, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(usize, &mut [T], &mut S) + Sync + Send, ) { for_bands_grouped(out, unit, bands, jobs, 4, init, f); } @@ -337,18 +338,24 @@ fn bands_per_group(bands: usize, jobs: usize, per_worker: usize) -> usize { bands.div_ceil(groups).max(1) } -/// [`for_bands`] with `per_worker` groups of consecutive bands for each worker. A large scratch -/// (AHD: 16 planes) wants one group per worker: with more groups than workers on a many-core -/// machine every group is a single band and each band would build and zero its own scratch. -fn for_bands_grouped( +/// [`for_bands`] with `per_worker` groups of consecutive bands for each of the `jobs` workers when +/// fewer than all may hold a scratch. A large scratch (AHD: 16 planes) wants one group per job: +/// with more groups each would build and zero its own scratch for a band or two. +fn for_bands_grouped( out: &mut [T], unit: usize, bands: usize, jobs: usize, per_worker: usize, - init: impl Fn() -> S + Sync, - f: impl Fn(usize, &mut [T], &mut S) + Sync, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(usize, &mut [T], &mut S) + Sync + Send, ) { + // One task per band keeps rayon's stealing, so a busy or slow worker doesn't hold up a + // static share of the bands (as `par::chunks_mut_limited` does for the same reason). + if jobs >= par::workers() { + par::chunks_mut_pooled(out, unit, init, |sc, band, chunk| f(band, chunk, sc)); + return; + } let per_group = bands_per_group(bands, jobs, per_worker); par::chunks_mut_limited(out, per_group * unit, jobs, |group, gchunk| { let mut sc = init(); @@ -447,15 +454,15 @@ pub(crate) fn demosaic_cfa(p: &Padded, pat: &Pattern) -> Vec { } /// [`demosaic_cfa`] without the full RGB frame (the green plane stays): see [`demosaic_fused`]. -pub(crate) fn demosaic_cfa_fused(p: &Padded, pat: &Pattern, out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync)) { +pub(crate) fn demosaic_cfa_fused(p: &Padded, pat: &Pattern, jobs: usize, out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync)) { let (w, h) = (p.w, p.h); if out.len() < w * h * 3 { return; } let band = par::band_rows(w); - let init = || vec![0.0f32; band * w * 3]; + let init = || vec![0.0f32; band.min(h) * w * 3]; cfa_with(p, pat, |rows| { - for_bands(&mut out[..w * h * 3], band * w * 3, h.div_ceil(band), usize::MAX, init, |b, chunk, buf| { + for_bands(&mut out[..w * h * 3], band * w * 3, h.div_ceil(band), jobs, init, |b, chunk, buf| { let buf = &mut buf[..chunk.len()]; rows(b * band, buf); emit(buf, chunk); @@ -944,6 +951,8 @@ fn ahd_ref(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usi mod tests { use super::*; use crate::color::IDENTITY; + use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use std::time::{Duration, Instant}; #[test] fn ahd_band_concurrency_does_not_change_pixels() { @@ -1037,8 +1046,9 @@ mod tests { } } - /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over 4 scratches - /// with jobs 1 and at most 8 with jobs 2), so a stage reading a cell left over from an earlier band would show. + /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over one scratch + /// with jobs 1 and two with jobs 2 on a bigger pool), so a stage reading a cell left over from + /// an earlier band would show. #[test] fn ahd_matches_reference_with_reused_scratch() { let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; @@ -1057,9 +1067,10 @@ mod tests { } } - /// A 4-worker pool splits 35 bands into groups of 9 (the last of 8), so groups after the first - /// start at band `group * 9` and every scratch is reused for several bands: a wrong band index - /// or a stale scratch cell would change pixels. The group size does not depend on the machine. + /// On a 4-worker pool with room for 3 scratches, 35 bands go in groups of 12 (the last of 11), + /// so groups after the first start at band `group * 12` and every scratch is reused for several + /// bands; with room for 4, every band is its own task and most borrow a used scratch. A wrong band + /// index or a stale scratch cell would change pixels. The split does not depend on the machine. #[cfg(not(target_arch = "wasm32"))] #[test] fn ahd_groups_of_several_bands_match_reference() { @@ -1070,18 +1081,103 @@ mod tests { let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); pool.install(|| { assert_eq!(par::workers(), 4); - assert_eq!(bands_per_group(ahd_bands(h), 4, 1), 9); - // One worker per group, never more groups than workers, however many bands there are. - assert_eq!(bands_per_group(126, 1000, 1), 32); - for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { - let mut want = vec![0.0f32; w * h * 3]; - ahd_ref(&p, phase, &m, &mut want, 4); - let got = demosaic(&p, phase, Demosaic::Ahd, &m, 4); - assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?}"); + assert_eq!(bands_per_group(ahd_bands(h), 3, 1), 12); + // One group per job, never more groups than jobs, however many bands there are. + assert_eq!(bands_per_group(126, 3, 1), 42); + for jobs in [3, 4] { + for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?} jobs {jobs}"); + } } }); } + /// A scratch that counts how many are alive at once. + struct Live<'a>(&'a AtomicUsize); + + impl<'a> Live<'a> { + fn new(now: &'a AtomicUsize, peak: &AtomicUsize) -> Self { + peak.fetch_max(now.fetch_add(1, SeqCst) + 1, SeqCst); + Live(now) + } + } + + impl Drop for Live<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, SeqCst); + } + } + + /// Every band runs once with its own index, and no more than `jobs` scratches (what `develop`'s + /// memory check admits) or one per worker are alive at once, on either side of `jobs == workers`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn for_bands_keeps_at_most_jobs_scratches_alive() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap(); + pool.install(|| { + for jobs in [1, 2, 3, 7, 8, 9, usize::MAX] { + for per_worker in [1, 4] { + let (now, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mut out = vec![0usize; 37 * 10 - 4]; + for_bands_grouped( + &mut out, + 10, + 37, + jobs, + per_worker, + || Live::new(&now, &peak), + |band, chunk, _| { + std::thread::sleep(Duration::from_millis(1)); + chunk.iter_mut().for_each(|v| *v += band + 1); + }, + ); + assert!(out.iter().enumerate().all(|(i, &v)| v == i / 10 + 1), "jobs {jobs}"); + let peak = peak.load(SeqCst); + assert!((1..=jobs.min(8)).contains(&peak), "jobs {jobs} per_worker {per_worker}: {peak} scratches alive"); + assert_eq!(now.load(SeqCst), 0); + } + } + }); + } + + /// With room for a scratch on every worker, the bands are separate rayon tasks: a worker held up + /// on band 0 (by other work on the shared pool, or a slow core) leaves the bands after it to + /// the others. With a fixed share of 9 bands per worker, 8 of them would wait for band 0, so at + /// most 26 of the other 34 could finish meanwhile. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_slow_band_does_not_hold_up_the_bands_after_it() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + let (done, seen) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mut out = vec![0u8; 35]; + for_bands_grouped( + &mut out, + 1, + 35, + 4, + 1, + || (), + |band, _, _| { + if band > 0 { + done.fetch_add(1, SeqCst); + return; + } + let start = Instant::now(); + while done.load(SeqCst) <= 26 && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + seen.store(done.load(SeqCst), SeqCst); + }, + ); + assert_eq!(done.load(SeqCst), 34); + assert!(seen.load(SeqCst) > 26, "only {} bands ran while band 0 was held up", seen.load(SeqCst)); + }); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index ed5248b67b..aaeb390eff 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -230,7 +230,7 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result Result Result>().join("/")); if fused { let mut o = vec![0u16; w * h * 3]; - demosaic_cfa_fused(&plane, &pat, &mut o, &encode_plain); + demosaic_cfa_fused(&plane, &pat, jobs, &mut o, &encode_plain); fused_out = Some(o); } else { rgb = demosaic_cfa(&plane, &pat); @@ -410,8 +410,8 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result u64 { } /// Checks the peak of the two development phases. The CFA and non-Bayer green -/// planes are freed before the u16 output is allocated; AHD scratch is bounded -/// by reducing simultaneous bands when needed. The fused path never holds the f32 RGB frame: -/// it has the u16 output (6 bytes a pixel) next to the CFA plane, plus a band buffer and the -/// scratch per worker, and an orientation copy of the output afterwards. Sensor storage belongs +/// planes are freed before the u16 output is allocated; the AHD scratch and the fused band +/// buffers are bounded by reducing simultaneous bands when needed. The fused path never holds +/// the f32 RGB frame: it has the u16 output (6 bytes a pixel) next to the CFA plane, plus a band +/// buffer and the scratch per simultaneous band, and an orientation copy of the output afterwards. Sensor storage belongs /// to the caller and is checked separately by the decoder. fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts: &DevelopOptions, workers: usize) -> Result { let limits = &opts.limits; @@ -530,7 +530,12 @@ fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts let mut jobs = workers.max(1); // Fused: the u16 output and, per worker running a band, one band of f32 RGB. let band_of = |rows: usize, window: bool| if fused { fused_band_bytes(w, h, rows, window) } else { 0 }; - let band_jobs = |rows: usize| workers.max(1).min(h.div_ceil(rows.max(1))) as u64; + // Fewer bands at once when the bands of every worker don't fit next to `base` (at least one). + let with_bands = |jobs: &mut usize, base: u64, rows: usize, band: u64| { + let available = limits.max_alloc.saturating_sub(base) / band.max(1); + *jobs = (*jobs).min(h.div_ceil(rows.max(1))).min(usize::try_from(available).unwrap_or(usize::MAX)).max(1); + base.saturating_add(band.saturating_mul(*jobs as u64)) + }; if cfa { let plane = (w as u64).saturating_add(2 * PAD as u64).saturating_mul((h as u64).saturating_add(2 * PAD as u64)).saturating_mul(4); // Bytes a pixel next to the plane: the f32 RGB frame (and the non-Bayer green plane), or @@ -547,19 +552,17 @@ fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts if bayer && opts.demosaic == Demosaic::Ahd { mosaic = mosaic.saturating_add(crate::demosaic::AHD_TABLE_BYTES); let scratch = crate::demosaic::ahd_scratch(w as u64, h as u64).saturating_add(band_of(crate::demosaic::AHD_BAND, true)); - let available = limits.max_alloc.saturating_sub(mosaic) / scratch.max(1); - jobs = jobs.min(crate::demosaic::ahd_bands(h)).min(usize::try_from(available).unwrap_or(usize::MAX)); // At least one band must fit, even when no parallelism is available. - mosaic = mosaic.saturating_add(scratch.saturating_mul(jobs.max(1) as u64)); + mosaic = with_bands(&mut jobs, mosaic, crate::demosaic::AHD_BAND, scratch); } else { let rows = if bayer { crate::demosaic::FUSED_ROWS } else { par::band_rows(w) }; - mosaic = mosaic.saturating_add(band_of(rows, bayer).saturating_mul(band_jobs(rows))); + mosaic = with_bands(&mut jobs, mosaic, rows, band_of(rows, bayer)); } peak = peak.max(mosaic); } else if fused { // LinearRaw: the output and the bands. let rows = par::band_rows(w); - peak = peak.max(pixels.saturating_mul(6).saturating_add(band_of(rows, false).saturating_mul(band_jobs(rows)))); + peak = peak.max(with_bands(&mut jobs, pixels.saturating_mul(6), rows, band_of(rows, false))); } if peak > limits.max_alloc || usize::try_from(peak).is_err() { return Err(RawError::LimitExceeded(format!("{peak} bytes of RAW working memory exceed {}", limits.max_alloc))); @@ -836,13 +839,15 @@ mod tests { }) }) .collect(); - for (w, h) in [(6, 6), (37, 41), (80, 150)] { + // 600 samples wide: bands of 109 rows, so 350 rows are four (the last short) and 50 rows + // are less than one. + for (w, h) in [(6, 6), (37, 41), (80, 150), (600, 350), (600, 50)] { let mut s = test_sensor(w, h, Some(Cfa { width: 6, height: 6, colors: colors.clone(), origin_x: 0, origin_y: 0 }), 1); s.orientation = 8; assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("xtrans {w}x{h}")); } for samples in [1, 3] { - for (w, h) in [(1, 1), (7, 5), (90, 111)] { + for (w, h) in [(1, 1), (7, 5), (90, 111), (600, 350), (600, 50)] { let mut s = test_sensor(w, h, None, samples); s.orientation = 3; assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("linear {samples} {w}x{h}")); @@ -902,6 +907,35 @@ mod tests { assert!(working_memory(11648, 8736, true, true, FUSED, &opts, 1).is_ok()); } + /// The fused bilinear / MHC, X-Trans and LinearRaw paths run fewer bands at once when the bands + /// of every worker don't fit next to the output, as AHD does. A very wide, short Bayer frame + /// (262144 x 455: 15 bands of 32 rows, about 147 MB a band with its window) needs 2.92 GB + /// with all 15 at once against the default 2 GiB, and develops with 9. + #[test] + fn fused_bands_at_once_are_capped_by_the_memory_limit() { + let opts = DevelopOptions { demosaic: Demosaic::Bilinear, ..Default::default() }; + let table = (GAMMA_STEPS as u64 + 2) * 4; + let (w, h) = (262144usize, 455usize); + let band = 32 * 262144 * 12 + (32 + 2 * PAD as u64) * (262144 + 2 * PAD as u64) * 4; + for (workers, want) in [(1, 1), (8, 8), (9, 9), (10, 9), (16, 9), (32, 9)] { + assert_eq!(working_memory(w, h, true, true, FUSED, &opts, workers).unwrap(), want, "{workers} workers"); + } + // Never more jobs than bands, and one when only one band fits. + assert_eq!(working_memory(1000, 40, true, true, FUSED, &opts, 32).unwrap(), 2); + let mut tight = opts.clone(); + tight.limits.max_alloc = 262144 * 455 * 6 + table + band; + assert_eq!(working_memory(w, h, true, true, FUSED, &tight, 32).unwrap(), 1); + tight.limits.max_alloc -= 1; + assert!(working_memory(w, h, true, true, FUSED, &tight, 32).is_err()); + // X-Trans (bands of `band_rows(1000)` = 65 rows next to its planes) and LinearRaw likewise. + let plane = (1000 + 2 * PAD as u64) * (2000 + 2 * PAD as u64) * 4; + let mut x = opts.clone(); + x.limits.max_alloc = 1000 * 2000 * 10 + plane + table + 3 * 65 * 1000 * 12; + assert_eq!(working_memory(1000, 2000, true, false, FUSED, &x, 32).unwrap(), 3); + x.limits.max_alloc = 1000 * 2000 * 6 + 5 * 65 * 1000 * 12; + assert_eq!(working_memory(1000, 2000, false, true, FUSED, &x, 32).unwrap(), 5); + } + #[test] fn working_memory_accounts_for_padding_and_at_least_one_ahd_band() { let mut opts = DevelopOptions { demosaic: Demosaic::Ahd, ..Default::default() }; diff --git a/crates/raw/src/par.rs b/crates/raw/src/par.rs index 6d23fd70c4..d966d94f52 100644 --- a/crates/raw/src/par.rs +++ b/crates/raw/src/par.rs @@ -1,5 +1,7 @@ //! Data-parallel helpers: rayon on native targets, sequential on wasm. +use std::sync::{Mutex, PoisonError}; + /// Calls `f(index, chunk)` for each `chunk`-sized piece of `buf`. pub(crate) fn chunks_mut(buf: &mut [T], chunk: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) { let chunk = chunk.max(1); @@ -12,6 +14,36 @@ pub(crate) fn chunks_mut(buf: &mut [T], chunk: usize, f: impl Fn(usize, buf.chunks_mut(chunk).enumerate().for_each(|(i, c)| f(i, c)); } +/// Like [`chunks_mut`], with `f(state, index, chunk)` borrowing a state: a chunk takes a free one +/// or makes one with `init`, and gives it back when done, so rayon keeps its fine-grained +/// splitting and stealing while at most one state per worker is ever made (`f` must not itself +/// wait on rayon work). Rayon's `for_each_init` would make one per stolen piece, which on an idle +/// pool is often every chunk. A state no chunk still waiting can take is dropped at once, so +/// near the end they go as their workers finish rather than all at the very end. +pub(crate) fn chunks_mut_pooled( + buf: &mut [T], + chunk: usize, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(&mut S, usize, &mut [T]) + Sync + Send, +) { + let chunk = chunk.max(1); + // The free states and the number of chunks that have not taken one yet. + let pool = Mutex::new((Vec::new(), buf.len().div_ceil(chunk))); + chunks_mut(buf, chunk, |i, c| { + let taken = { + let mut pool = pool.lock().unwrap_or_else(PoisonError::into_inner); + pool.1 = pool.1.saturating_sub(1); + pool.0.pop() + }; + let mut state = taken.unwrap_or_else(&init); + f(&mut state, i, c); + let mut pool = pool.lock().unwrap_or_else(PoisonError::into_inner); + if pool.0.len() < pool.1 { + pool.0.push(state); + } + }); +} + /// Native worker count (the browser builds run sequentially). pub(crate) fn workers() -> usize { #[cfg(not(target_arch = "wasm32"))] @@ -56,3 +88,37 @@ pub(crate) fn map(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Ve pub(crate) fn band_rows(width: usize) -> usize { (65536 / width.max(1)).clamp(1, 256) } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every chunk is visited once with its own index (the last one short), and the chunks share + /// the states: a 4-worker pool makes at most 4 for 101 chunks, an empty buffer none. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn chunks_mut_pooled_makes_one_state_per_worker_at_most() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + let mut buf = vec![0usize; 1003]; + let inits = AtomicUsize::new(0); + let runs = AtomicUsize::new(0); + let init = || { + inits.fetch_add(1, Ordering::Relaxed); + 0usize + }; + chunks_mut_pooled(&mut buf, 10, init, |used, i, c| { + *used += 1; + runs.fetch_add(1, Ordering::Relaxed); + c.iter_mut().for_each(|v| *v += i + 1); + }); + assert!(buf.iter().enumerate().all(|(k, &v)| v == k / 10 + 1)); + assert_eq!(runs.load(Ordering::Relaxed), 101); + let n = inits.load(Ordering::Relaxed); + assert!((1..=4).contains(&n), "{n} states for 101 chunks on 4 workers"); + chunks_mut_pooled(&mut [0u8; 0], 4, init, |_, _, _| {}); + assert_eq!(inits.load(Ordering::Relaxed), n, "no state for an empty buffer"); + }); + } +} From 48b42979c83208c94ca4eaf3c480a96c59759862 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 14:34:21 +0100 Subject: [PATCH 68/87] Integration: Netpbm Save As row leads with .pnm, Open lists .pnm/.dib, save test (#3609) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Picking Netpbm for a bare name (Untitled) took the row's first extension, .pbm, though the codec writes P6/P7/PF from the image, never a 1-bit PBM: an RGB document saved as x.pbm holding P6 data. The row now starts with .pnm. File › Open didn't list .pnm or the new .dib alias, so a file Save As had just written was hidden in the Open dialog; both are now in All Formats and their own type. The test checks every new type and alias is offered, the Netpbm row's first extension, that Open lists every extension Save As writes, and what Save As writes to .pnm (P6) and .hdr (#?RADIANCE), as asked in review. Co-authored-by: buivanvu94 <125793064+buivanvu94@users.noreply.github.com> Co-authored-by: tanish2k09 <13985398+tanish2k09@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/services.rs | 14 +++++++------- apps/photocraft/src/services/tests.rs | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index ad50fce964..ff949863fb 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -18,10 +18,10 @@ mod recovery_tests; /// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl), swatches (.aco, .act, .ase) and keyboard shortcut sets /// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts. const OPEN_EXTS: &[&str] = &[ - "pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", - "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", "iff", "lbm", - "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act", - "ase", "kys", "af", "afdesign", "afphoto", "afpub", + "pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "dib", "tga", + "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pnm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", + "iff", "lbm", "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", + "aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; @@ -54,14 +54,14 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[ ("TIFF", &["tif", "tiff"]), ("WebP", &["webp"]), ("GIF", &["gif"]), - ("BMP", &["bmp"]), + ("BMP", &["bmp", "dib"]), ("Targa", &["tga"]), ("ICO", &["ico"]), ("QOI", &["qoi"]), ("PCX", &["pcx"]), ("DDS", &["dds"]), ("XPM", &["xpm"]), - ("Portable Bitmap", &["pbm", "pgm", "ppm", "pam", "pfm"]), + ("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]), ("OpenEXR", &["exr"]), ("Radiance HDR", &["hdr"]), ("FITS", &["fits", "fit", "fts"]), @@ -100,7 +100,7 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("GIF", &["gif"]), ("ICO", &["ico"]), ("OpenEXR", &["exr"]), - ("Netpbm", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]), + ("Netpbm", &["pnm", "pbm", "pgm", "ppm", "pam", "pfm"]), ("Radiance HDR", &["hdr"]), ("FITS", &["fits", "fit"]), ("DPX", &["dpx"]), diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index f9bce2a367..06469aa637 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -294,9 +294,21 @@ fn save_as_offers_only_writable_formats_including_ico() { assert!(format.caps().write, "{name}: .{ext} can't be written"); } } - for ext in ["ico", "gif", "bmp", "dds"] { + for ext in ["ico", "gif", "bmp", "dds", "pnm", "pfm", "hdr", "dib", "jpeg", "tiff"] { assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); } + // Picking Netpbm for a bare name takes its first extension; the codec writes P6/P7/PF from the + // image, never a 1-bit .pbm, so that one is the neutral .pnm (#3609). + let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts); + assert_eq!(netpbm.as_ref().and_then(|exts| exts.first()).map(String::as_str), Some("pnm")); + // File › Open lists every file Save As writes, also in that format's own type (PDF is written + // but not read yet). + for (name, exts) in SAVE_FILTERS { + for ext in exts.iter().filter(|e| **e != "pdf") { + assert!(OPEN_EXTS.contains(ext), "{name}: Open's All Formats lacks .{ext}"); + assert!(OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: no Open type lists .{ext}"); + } + } assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); // What Save As writes there: an icon up to 256×256, and a clear error past that. let doc = |side: u32| { @@ -307,6 +319,11 @@ fn save_as_offers_only_writable_formats_including_ico() { let opts = export_options(&photocraft_ui_egui::ExportSettings::default()); let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap(); assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header"); + // And what the Netpbm and Radiance rows write. + let pnm = photocraft_io::export(&doc(4), "x.pnm", &opts).unwrap(); + assert_eq!(pnm.bytes[..2], *b"P6", "an RGB document saves as a binary pixmap"); + let hdr = photocraft_io::export(&doc(4), "x.hdr", &opts).unwrap(); + assert!(hdr.bytes.starts_with(b"#?RADIANCE"), "a Radiance header"); let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string(); assert!(err.contains("256"), "{err}"); } From 5a6473113e4bd0c2413f11baf5a76f6651f9d6ff Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 14:32:53 +0100 Subject: [PATCH 69/87] Integration: paint.stroke fill keeps picked CMYK inks and pads to the feather's reach (#3779) fill_region called fill_cmds::blend_color_mask without the picked-inks parameter main added, so the PR no longer compiled; it now passes the brush's picked CMYK inks, as Edit > Fill and Edit > Stroke do, so a colour picked as CMYK 100/0/0/0 fills a CMYK document with those inks (where it covers fully; partial coverage blends through RGB, as there). The soft fill's working bounds were padded by ceil(sigma)+2, but the feather reaches ceil(3 sigma): a 40 px square filled with size 40, hardness 0 ended in a hard step from ~0.1 to 0 at 1 sigma + 2 px. The pad now comes from selection::feather_reach. Tests through paint.stroke: fill_soft_edge_has_no_step, fill_paints_a_cmyk_pick_with_the_picked_inks, fill_works_on_cmyk_and_16_and_32_bit. Co-authored-by: scott <1591011+dottedt@users.noreply.github.com> Co-authored-by: echelon <39263+echelon@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/brush_cmds.rs | 11 ++++-- crates/engine/src/cmd/brush_cmds/tests.rs | 43 +++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 2bce82d81e..05b2911831 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -449,13 +449,17 @@ fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pt // the brush width, the way its tip fades. let feather_px = ((1.0 - brush.hardness.clamp(0.0, 1.0)) * brush.size * 0.5).max(0.0); let (color, opacity, mode) = (brush.color, brush.opacity.clamp(0.0, 1.0), brush.mode); + // A colour picked as CMYK fills with its inks in a CMYK target where it covers fully, as + // Edit › Fill does (blend_color_mask blends partial coverage through the colour's RGB). + let picked = brush.color_cmyk.filter(|(rgb, _)| *rgb == [color[0], color[1], color[2]]).map(|(_, inks)| inks); let cmyk = doc_cmyk_space(s); let dmg = photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { s.edit(label, |doc, _| { let sel = doc.selection.clone(); let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; - // The polygon's whole-pixel bounds, grown by the feather so a soft edge is not clipped. + // The polygon's whole-pixel bounds, grown by the feather's reach (3σ) so a soft edge + // fades out instead of being clipped. let (mut bx0, mut by0, mut bx1, mut by1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); for sp in &pts { if !(sp.x.is_finite() && sp.y.is_finite()) { @@ -467,7 +471,8 @@ fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pt by1 = by1.max(sp.y); } let ix = |v: f64| v.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32; - let pad = (feather_px.ceil() as i64).clamp(0, i64::from(i32::MAX) / 4) as i32 + 2; + let reach = photocraft_algo::selection::feather_reach(feather_px); + let pad = i32::try_from(reach).unwrap_or(i32::MAX).saturating_add(2); let bounds = Rect::new( ix(bx0.floor()).saturating_sub(pad), ix(by0.floor()).saturating_sub(pad), @@ -492,7 +497,7 @@ fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pt } } let coverage = photocraft_algo::selection::mask_to_surface(&cov, bounds); - crate::fill_cmds::blend_color_mask(surf, bounds, color, &coverage, mode, opacity, lock)?; + crate::fill_cmds::blend_color_mask(surf, bounds, color, picked, &coverage, mode, opacity, lock)?; Ok(bounds) }) })?; diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 417f6a30bc..32b8efa708 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -75,6 +75,49 @@ fn fill_is_rejected_with_clear_mode() { assert!(rgba(&s, 12, 30)[3] > 0.9, "pixels the clear stroke missed remain"); } +#[test] +fn fill_soft_edge_has_no_step() { + // #3779: the feather (σ = 20 here) reaches 3σ = 60 px past the square; the fill's working + // bounds must reach as far, or the soft edge ends in a hard step where they clip it. + let mut s = session(200, 200); + s.execute( + "paint.stroke", + json!({"points": [[80, 80], [120, 80], [120, 120], [80, 120]], "fill": true, "size": 40, "color": "#ff0000", "brush": {"hardness": 0.0}}), + ) + .unwrap(); + assert!(rgba(&s, 57, 100)[3] > 0.0, "the fade continues past 1σ: {:?}", rgba(&s, 57, 100)); + for x in 0..199 { + let (a, b) = (rgba(&s, x, 100)[3], rgba(&s, x + 1, 100)[3]); + assert!((a - b).abs() < 0.03, "step between x={x} ({a}) and x={} ({b})", x + 1); + } +} + +#[test] +fn fill_paints_a_cmyk_pick_with_the_picked_inks() { + // #3779: like a plain stroke (#4344), a fill paints a colour picked as CMYK as its inks. + let cyan = [1.0f32, 0.0, 0.0, 0.0]; + let mut s = session(16, 16); + s.execute("image.mode.cmyk", json!({})).unwrap(); + let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap(); + s.execute("paint.stroke", json!({"points": [[2, 2], [14, 2], [14, 14], [2, 14]], "fill": true, "hardness": 1.0})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let got: Vec = surf.read_region(Rect::new(8, 8, 9, 9)).into_iter().take(4).collect(); + assert!(got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02), "{got:?}"); +} + +#[test] +fn fill_works_on_cmyk_and_16_and_32_bit() { + for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 30, "mode": mode, "depth": depth})).unwrap(); + s.execute("paint.stroke", json!({"points": [[10, 5], [50, 5], [50, 25], [10, 25]], "fill": true, "color": "#000000", "hardness": 1.0})).unwrap(); + assert!(rgba(&s, 30, 15)[0] < 0.2, "{mode}/{depth}: {:?}", rgba(&s, 30, 15)); + assert!(rgba(&s, 5, 15)[0] > 0.8, "{mode}/{depth} outside: {:?}", rgba(&s, 5, 15)); + } +} + #[test] fn stroke_accepts_full_points_brush_and_preset() { let mut s = session(200, 100); From 9462fa130c97ad473ebbfb840798165655a92e11 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 14:49:25 +0100 Subject: [PATCH 70/87] Integration: Artboard from Layers dialog opens at the layers' size; refuse -0.4 (#9262) The dialog remembered the last Width/Height: make a 1080x1350 board from one layer, then open it for a 20x30 layer and press OK, and that layer got a 1080x1350 board too. It also opened at 0 and an empty Name. It now starts at the selected layers' size and the next "Artboard N" every time, as in the reference application. `{"height": -0.4}` rounded to 0 and kept the bounds; negative sizes are now refused before rounding. Co-authored-by: DuBearte <130190089+DuBearte@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/artboard_cmds.rs | 22 +++++++++++++-- crates/engine/src/artboard_cmds/tests.rs | 20 ++++++++++++++ crates/ui-egui/src/filter_dialog.rs | 35 ++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs index a00c3921a8..d09687b3ce 100644 --- a/crates/engine/src/artboard_cmds.rs +++ b/crates/engine/src/artboard_cmds.rs @@ -303,6 +303,21 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// The layers' union bounds, or the canvas when they have none: the board Artboard from Layers +/// makes when no size is given. +fn union_bounds<'a>(layers: impl IntoIterator, canvas: Rect) -> Rect { + layers.into_iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas) +} + +/// What Artboard from Layers' dialog opens with, as in the reference application: the name the +/// board would get and the selected top-level layers' size (`None` without a document). +pub fn from_layers_defaults(s: &Session) -> Option<(String, [i64; 2])> { + let d = s.active()?; + let ids = crate::layer_multi_cmds::top_level(&d.doc, &crate::layer_multi_cmds::selected(s)); + let [_, _, w, h] = xywh(union_bounds(ids.iter().filter_map(|id| d.doc.layer(*id)), d.doc.bounds())); + Some((next_artboard_name(&d.doc), [w, h])) +} + fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { let sel = crate::layer_multi_cmds::selected(s); let d = s.active().ok_or(EngineError::NoDocument)?; @@ -310,6 +325,10 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string); let cmd = "layer.new.artboardFromLayers"; let background = background_param(p, cmd)?.unwrap_or_default(); + // `int` rounds, so a small negative (-0.4) would pass as 0, "keep the bounds". + if ["width", "height"].iter().any(|k| p.get(*k).and_then(Value::as_f64).is_some_and(|v| v < 0.0)) { + return Err(bad(cmd, "the artboard width and height must not be negative")); + } // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps // their bounds on that axis (#9087). let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; @@ -322,8 +341,7 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { for id in &ids { children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); } - let bounds = children.iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas); - let [x, y, w, h] = xywh(bounds); + let [x, y, w, h] = xywh(union_bounds(&children, canvas)); let rect = board_rect(cmd, [x, y, size[0].unwrap_or(w), size[1].unwrap_or(h)])?; let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), children); set_artboard(&mut g, Artboard { rect, background, preset: String::new() }); diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/artboard_cmds/tests.rs index 14b3ee4f7d..6c2afe16a4 100644 --- a/crates/engine/src/artboard_cmds/tests.rs +++ b/crates/engine/src/artboard_cmds/tests.rs @@ -679,5 +679,25 @@ fn artboard_from_layers_takes_a_custom_size() { let mut s = session(8); add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); assert!(s.execute("layer.new.artboardFromLayers", json!({"width": -5})).is_err()); + // `int` rounds -0.4 to 0, which would otherwise keep the bounds. + assert!(s.execute("layer.new.artboardFromLayers", json!({"height": -0.4})).is_err()); assert!(doc(&s).artboards().is_empty(), "a refused size changes nothing"); + assert_eq!(s.execute("layer.new.artboardFromLayers", json!({"name": ""})).unwrap()["rect"], json!([10, 10, 20, 20])); + assert_eq!(doc(&s).artboards()[0].1, "Artboard 1", "an empty name gives Artboard N"); +} + +/// The dialog's defaults (#9087): the selected layers' size and the board's name, as the command +/// makes it with no size; the canvas when the layers have no pixels. +#[test] +fn from_layers_defaults_are_the_selected_layers_size() { + let mut s = session(8); + add_square(&mut s, Rect::new(10, 10, 30, 40), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(from_layers_defaults(&s), Some(("Artboard 1".to_string(), [20, 30]))); + s.execute("layer.new.artboardFromLayers", json!({})).unwrap(); + add_square(&mut s, Rect::new(50, 5, 60, 10), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(from_layers_defaults(&s), Some(("Artboard 2".to_string(), [10, 5]))); + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(from_layers_defaults(&s), Some(("Artboard 1".to_string(), [100, 80])), "an empty layer: the canvas"); + assert_eq!(from_layers_defaults(&Session::new()), None); } diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index b8b7d758f2..57c0faa1cb 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -405,6 +405,17 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map Date: Tue, 27 Oct 2026 03:12:47 +0100 Subject: [PATCH 71/87] Integration: font menu fix-ups after merging main (#6526) - Character section: a style picked under a family's ">" with type layers selected set the layers but not the style for new type (the options bar did both). Pick "Inter > Thin" in Properties > Character: new type stayed Regular. - Faux bold: a pointed tip moved r/sin(half its angle) along its bisector, uncapped (3.9 r at 30 degrees, an A apex grew a spike), and tips sharper than about 20 degrees did not move at all. Every tip now moves at most 2r, continuously; inner corners (the crotch of a V) keep their exact miter. - Faux bold: each point searched past runs of coincident points for its neighbours, O(n^2); a contour of 50 000 copies of one point took ~8 s per glyph. Neighbours now come from one O(n) pass over the runs. - prefs.reset {"path":"type"} and Preferences > Type > Reset Section wiped the favourite fonts; they are kept now (type.favoriteFonts by name, or Reset All, still clear them). - An expanded family whose own row scrolled out of view lost its style rows, so the list below jumped up. - Show Similar Fonts re-sorted around each font an arrow step applied, so Down went back and forth between two fonts; the list now compares with the font current when the filter was turned on (or the menu opened). - Docs: an uninstalled favourite is kept but not listed; FAUX_BOLD_RADIUS and the raster budget describe the thickened outline; the unused "Recent font list" rows are gone; docs/scorecard.md regenerated (the favourite fonts are one more setting). Co-authored-by: D-monized <341904702+D-monized@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/font_library_cmds.rs | 5 +- crates/engine/src/font_library_cmds/tests.rs | 16 +++ crates/engine/src/prefs.rs | 6 + crates/text/src/embolden.rs | 144 ++++++++++++++++--- crates/text/src/render.rs | 21 +-- crates/ui-egui/src/i18n/cs.tsv | 1 - crates/ui-egui/src/i18n/de.tsv | 1 - crates/ui-egui/src/i18n/el.tsv | 1 - crates/ui-egui/src/i18n/es.tsv | 1 - crates/ui-egui/src/i18n/fr.tsv | 1 - crates/ui-egui/src/i18n/hu.tsv | 1 - crates/ui-egui/src/i18n/id.tsv | 1 - crates/ui-egui/src/i18n/it.tsv | 1 - crates/ui-egui/src/i18n/ja.tsv | 1 - crates/ui-egui/src/i18n/ko.tsv | 1 - crates/ui-egui/src/i18n/nl.tsv | 1 - crates/ui-egui/src/i18n/pl.tsv | 1 - crates/ui-egui/src/i18n/pt-br.tsv | 1 - crates/ui-egui/src/i18n/ru.tsv | 1 - crates/ui-egui/src/i18n/sr.tsv | 1 - crates/ui-egui/src/i18n/tr.tsv | 1 - crates/ui-egui/src/i18n/uk.tsv | 1 - crates/ui-egui/src/i18n/vi.tsv | 1 - crates/ui-egui/src/i18n/zh-hans.tsv | 1 - crates/ui-egui/src/i18n/zh-hant.tsv | 1 - crates/ui-egui/src/prefs_ui.rs | 33 ++++- crates/ui-egui/src/type_font_picker_tests.rs | 52 +++++++ crates/ui-egui/src/type_tool.rs | 24 +++- crates/ui-egui/src/type_tool_tests.rs | 23 +++ docs/scorecard.md | 4 +- 30 files changed, 292 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/font_library_cmds.rs b/crates/engine/src/font_library_cmds.rs index 2231a966f1..7b3fb271ae 100644 --- a/crates/engine/src/font_library_cmds.rs +++ b/crates/engine/src/font_library_cmds.rs @@ -1,7 +1,8 @@ //! The font menu's favourite font families: the star beside each font, kept until un-starred. They //! live in the preferences, so they survive a restart, and are plain family names: a favourite -//! whose font is uninstalled stays listed until removed, as in Photoshop. (The recently used -//! fonts are the shell's, `PhotocraftApp::note_recent_font`.) +//! whose font is uninstalled is kept, though the menu lists installed fonts only, and shows it +//! again once the font is back (`type.font.favorite` with `"on": false` removes it). (The +//! recently used fonts are the shell's, `PhotocraftApp::note_recent_font`.) use serde_json::{Value, json}; diff --git a/crates/engine/src/font_library_cmds/tests.rs b/crates/engine/src/font_library_cmds/tests.rs index 2c69425bb9..c31c65353a 100644 --- a/crates/engine/src/font_library_cmds/tests.rs +++ b/crates/engine/src/font_library_cmds/tests.rs @@ -21,6 +21,22 @@ fn starring_toggles_and_on_sets_a_favourite() { assert!(favorite_fonts(&s).is_empty()); } +#[test] +fn resetting_the_type_preferences_keeps_the_favourites() { + let mut s = session(); + s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap(); + s.execute("prefs.set", json!({"path": "type.smartQuotes", "value": false})).unwrap(); + s.execute("prefs.reset", json!({"path": "type"})).unwrap(); + assert!(s.prefs().type_.smart_quotes, "the Type settings are reset"); + assert_eq!(favorite_fonts(&s), ["Bebas Neue"], "the favourites are the user's library, not a setting"); + // Asked for by name, or with everything, they go. + s.execute("prefs.reset", json!({"path": "type.favoriteFonts"})).unwrap(); + assert!(favorite_fonts(&s).is_empty()); + s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap(); + s.execute("prefs.reset", json!({})).unwrap(); + assert!(favorite_fonts(&s).is_empty()); +} + #[test] fn the_library_survives_a_preferences_round_trip_and_hostile_lists_are_tidied() { let mut s = session(); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index ba3b760440..88ec457842 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1476,9 +1476,15 @@ impl Preferences { self.shortcuts.clear(); return Ok(()); } + // The favourite fonts are the user's library, not a Type setting: resetting the Type + // section keeps them (only `type.favoriteFonts` itself, or Reset All, clears them). + let favorites = (path == "type").then(|| self.type_.favorite_fonts.clone()); let mut root = self.to_json(); set_path(&mut root, path, def)?; *self = serde_json::from_value(root).map_err(|e| e.to_string())?; + if let Some(favorites) = favorites { + self.type_.favorite_fonts = favorites; + } Ok(()) } diff --git a/crates/text/src/embolden.rs b/crates/text/src/embolden.rs index 37ecad3ca0..a33711996d 100644 --- a/crates/text/src/embolden.rs +++ b/crates/text/src/embolden.rs @@ -70,7 +70,8 @@ impl Outline { /// Grow the ink by `r` on every side (the stems get `2r` heavier, counters `2r` smaller). /// Points, on and off the curve, move along the bisector of their neighbouring edges by /// `r / cos(half the turn)`, capped by the shorter neighbouring edge so short segments and - /// sharp inner corners can't spike. Nothing moves for a non-finite or non-positive `r`, or an + /// sharp inner corners can't spike; a pointed tip (an A apex) never moves further than `2r`, + /// so it grows a little instead of a long miter. Nothing moves for a non-finite or non-positive `r`, or an /// outline without area. pub(crate) fn embolden(&mut self, r: f64) { if !(r.is_finite() && r > 0.0) { @@ -118,36 +119,75 @@ impl Outline { } } -/// How far each point of one closed contour moves (see [`Outline::embolden`]). +/// How far each point of one closed contour moves (see [`Outline::embolden`]). No point moves +/// further than [`MAX_SHIFT`] times `r`: an uncapped miter puts a long spike on every pointed tip +/// (an A apex), and a tip past FreeType's spike threshold would not move at all. fn shifts(pts: &[(f64, f64)], r: f64, sign: f64) -> Vec<(f64, f64)> { let n = pts.len(); let mut out = vec![(0.0, 0.0); n]; if n < 2 { return out; } - // The nearest point in direction `step` that differs from `pts[i]`, and the edge to it. - let neighbour = |i: usize, forward: bool| -> Option<(f64, f64, f64)> { - let p = pts[i]; - (1..n).find_map(|k| { - let j = if forward { (i + k) % n } else { (i + n - k) % n }; - let (dx, dy) = if forward { (pts[j].0 - p.0, pts[j].1 - p.1) } else { (p.0 - pts[j].0, p.1 - pts[j].1) }; - let len = dx.hypot(dy); - (len > 1e-9 && len.is_finite()).then(|| (dx / len, dy / len, len)) - }) + // Runs of coincident points (or points that can't be measured) share their neighbours: the + // last point of the run before and the first of the run after. Found in one pass, so a + // contour of many repeated points (a hostile font) costs O(n), not O(n²). + let apart = |p: (f64, f64), q: (f64, f64)| { + let len = (q.0 - p.0).hypot(q.1 - p.1); + len > 1e-9 && len.is_finite() }; - for (i, shift) in out.iter_mut().enumerate() { - let (Some((ix, iy, l_in)), Some((ox, oy, l_out))) = (neighbour(i, false), neighbour(i, true)) else { continue }; - let dot = ix * ox + iy * oy; - // A near reversal (a spike) has no useful bisector: leave it. - if dot <= -0.9375 { - continue; + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut run_of = vec![0usize; n]; + for (i, &p) in pts.iter().enumerate() { + match runs.last_mut() { + Some(run) if !pts.get(run.0).is_some_and(|&a| apart(a, p)) => run.1 = i, + _ => runs.push((i, i)), } + run_of[i] = runs.len().saturating_sub(1); + } + // The contour is closed: a last run back at the start point is the first run. + if runs.len() > 1 + && let (Some(&(first, _)), Some(&(last, _))) = (runs.first(), runs.last()) + && !apart(pts[first], pts[last]) + { + runs.pop(); + for k in &mut run_of[last..] { + *k = 0; + } + runs[0].0 = last; + } + let m = runs.len(); + if m < 2 { + return out; + } + // The edge from `pts[i]` to `pts[j]` (or from `pts[j]` when `into`), as a unit vector and length. + let edge = |i: usize, j: usize, into: bool| -> Option<(f64, f64, f64)> { + let (p, q) = (pts[i], pts[j]); + let (dx, dy) = if into { (p.0 - q.0, p.1 - q.1) } else { (q.0 - p.0, q.1 - p.1) }; + let len = dx.hypot(dy); + (len > 1e-9 && len.is_finite()).then(|| (dx / len, dy / len, len)) + }; + let cap = MAX_SHIFT * r; + for (i, shift) in out.iter_mut().enumerate() { + let k = run_of[i]; + let prev = runs[(k + m - 1) % m].1; + let next = runs[(k + 1) % m].0; + let (Some((ix, iy, l_in)), Some((ox, oy, l_out))) = (edge(i, prev, true), edge(i, next, false)) else { continue }; + let dot = ix * ox + iy * oy; let d = 1.0 + dot; let (sx, sy) = (sign * (iy + oy), -sign * (ix + ox)); + let len = sx.hypot(sy); + // An exact reversal has no bisector, and no side to call outward: leave it. + if !(len > 1e-9 && len.is_finite()) { + continue; + } // How sharply the contour turns towards the ink at this point (negative: away). let q = sign * (ox * iy - oy * ix); let l = l_in.min(l_out); let scale = if r * q <= l * d { r / d } else { l / q }; + // A pointed tip (turning away from the ink) moves no more than the cap along the bisector + // (`len` is the bisector's length, √(2d)). An inner corner keeps its exact miter, already + // limited by the shorter edge above: capping it would thin the strokes meeting there. + let scale = if q < 0.0 { scale.min(cap / len) } else { scale }; if scale.is_finite() { *shift = (sx * scale, sy * scale); } @@ -155,6 +195,10 @@ fn shifts(pts: &[(f64, f64)], r: f64, sign: f64) -> Vec<(f64, f64)> { out } +/// The longest move of an emboldened point, in radii: a square corner moves √2, and a tip moves +/// `1 / sin(half its angle)`, so only tips sharper than 60° are capped. +const MAX_SHIFT: f64 = 2.0; + #[cfg(test)] mod tests { use super::*; @@ -284,4 +328,70 @@ mod tests { let b = bounds(&o); assert!(b.iter().all(|v| v.abs() < 60.0), "no runaway miter: {b:?}"); } + + /// How far the tip of an isosceles triangle with a `deg`-degree tip (long sides) moves. + fn tip_shift(deg: f64, r: f64) -> f64 { + let half = (deg / 2.0).to_radians(); + let (a, b) = ((1000.0 * half.sin()) as f32, (1000.0 * half.cos()) as f32); + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(a, b); + o.line_to(-a, b); + o.line_to(0.0, 0.0); + o.embolden(r); + let tip = o.contours[0].pts[0]; + tip.0.hypot(tip.1) + } + + #[test] + fn pointed_tips_grow_by_at_most_twice_the_radius_and_never_stop_growing() { + // 30°: an uncapped miter moves 1/sin(15°) = 3.86 r. 20.5° is just short of the spike + // threshold (5.6 r uncapped); 20° and 10° are past it, where the tip used to stay put. + for deg in [30.0, 20.5, 20.0, 10.0] { + let moved = tip_shift(deg, 1.0); + assert!(moved > 0.0 && moved <= 2.0 + 1e-9, "{deg}° tip moved {moved}"); + } + // Blunt corners keep their exact miter: a square corner √2, a 90° tip too. + assert!((tip_shift(90.0, 1.0) - std::f64::consts::SQRT_2).abs() < 1e-3); + } + + #[test] + fn inner_corners_keep_their_exact_miter() { + // A 40° notch (the crotch of a V) between long edges: its corner moves r / sin(20°), so the + // edges meeting there grow by r like the rest of the outline. The tip cap must not clip it. + let half = 20f64.to_radians(); + let (a, b) = ((1000.0 * half.sin()) as f32, (1000.0 * half.cos()) as f32); + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + o.line_to(-a, b); + o.line_to(-a - 1000.0, b); + o.line_to(-a - 1000.0, -1000.0); + o.line_to(a + 1000.0, -1000.0); + o.line_to(a + 1000.0, b); + o.line_to(a, b); + o.line_to(0.0, 0.0); + o.embolden(1.0); + let corner = o.contours[0].pts[0]; + let want = 1.0 / half.sin(); + assert!((corner.0.hypot(corner.1) - want).abs() < 1e-2, "{corner:?}, want {want}"); + } + + #[test] + fn many_repeated_points_are_thickened_in_linear_time() { + // A hostile glyph: a contour of 50 000 copies of one point, then a square. Finding each + // point's neighbours by scanning past the copies cost ~10⁹ steps. + let mut o = Outline::default(); + o.move_to(0.0, 0.0); + for _ in 0..50_000 { + o.line_to(0.0, 0.0); + } + for (x, y) in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + o.line_to(x, y); + } + let start = std::time::Instant::now(); + o.embolden(1.0); + let took = start.elapsed(); + assert!(took < std::time::Duration::from_secs(2), "took {took:?}"); + assert!(close(bounds(&o), [-1.0, -1.0, 11.0, 11.0]), "{:?}", bounds(&o)); + } } diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index 71497d3d64..dacd120dcd 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -17,24 +17,25 @@ use rayon::prelude::*; /// Faux-italic slant in degrees (Photoshop-like). pub const FAUX_ITALIC_DEG: f32 = 12.0; -/// Faux-bold ring radius as a fraction of the font size (tuned so stem weight stays close to the old summed-coverage look). +/// How far faux bold grows the outline on every side, as a fraction of the font size +/// ([`crate::embolden`]): stems get twice this heavier, close to the weight of the earlier +/// faux bold, which stamped the glyph at offsets of this radius. pub const FAUX_BOLD_RADIUS: f32 = 0.036; /// Largest raster we produce (pixels), as a guard against absurd sizes. const MAX_PIXELS: u64 = 256 * 1024 * 1024; -/// Cumulative coverage-pixel work budget across all colour and faux-bold passes of one render. +/// Cumulative coverage-pixel work budget across the colour passes of one render. const MAX_PASS_PIXELS: u64 = MAX_PIXELS * 4; /// Peak working bytes one rasterization may keep live. [`MAX_PIXELS`] does not bound them: the -/// accumulator and the output surface are both `stride` deep, and a faux-bold pass keeps one more -/// coverage buffer live, so a CMYK bold render reserves several times what a plain grey one does -/// for the same pixels. +/// accumulator and the output surface are both `stride` deep, so a CMYK render reserves several +/// times what a plain grey one does for the same pixels. const MAX_RASTER_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 }; /// Whether a `w` x `h` render's peak working bytes fit `max_bytes`: the f32 accumulator and the -/// output surface (both `stride` deep), plus the coverage buffers live at the peak. A plain pass -/// peaks inside `Coverage::finish`, which holds its accumulator and the vector it builds beside -/// it; a faux-bold pass peaks one buffer higher, since the resolved plain coverage is kept while -/// the bold pass resolves into it. `false` when the arithmetic overflows, so an absurd size is -/// refused rather than wrapping. +/// output surface (both `stride` deep), plus the coverage buffers live at the peak. A pass peaks +/// inside `Coverage::finish`, which holds its accumulator and the vector it builds beside it. +/// Faux bold draws its thickened outlines in that same pass; a `bold` render is still budgeted +/// one buffer higher, as when it was stamped into a buffer of its own, which leaves it headroom. +/// `false` when the arithmetic overflows, so an absurd size is refused rather than wrapping. fn fits_raster_budget(w: usize, h: usize, stride: usize, sample: SampleType, bold: bool, max_bytes: u64) -> bool { let f32s = size_of::() as u64; let peak = (w as u64).checked_mul(h as u64).and_then(|px| { diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f54f2c5393..dd4d2e360b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3863,7 +3863,6 @@ navigator Zoom Zvětšení Show Favorite Fonts Zobrazit oblíbená písma No favorite fonts yet: click the star beside a font to add it. Zatím žádná oblíbená písma: přidejte písmo kliknutím na hvězdičku vedle něj. Favorite fonts Oblíbená písma - Recent font list Seznam posledních písem Add to Favorites Přidat do oblíbených Remove from Favorites Odebrat z oblíbených Show All Fonts Zobrazit všechna písma diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 18de63e519..767805b654 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3267,7 +3267,6 @@ curves Smooth Glätten Show Favorite Fonts Favorisierte Schriften anzeigen No favorite fonts yet: click the star beside a font to add it. Noch keine favorisierten Schriften: Klicken Sie auf den Stern neben einer Schrift, um sie hinzuzufügen. Favorite fonts Favorisierte Schriften - Recent font list Liste zuletzt verwendeter Schriften Add to Favorites Zu Favoriten hinzufügen Remove from Favorites Aus Favoriten entfernen Show All Fonts Alle Schriften anzeigen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b60cd226de..c0a520b50c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3949,7 +3949,6 @@ curves Smooth Εξομάλυνση Show Favorite Fonts Εμφάνιση αγαπημένων γραμματοσειρών No favorite fonts yet: click the star beside a font to add it. Δεν υπάρχουν ακόμη αγαπημένες γραμματοσειρές: κάντε κλικ στο αστέρι δίπλα σε μια γραμματοσειρά για να την προσθέσετε. Favorite fonts Αγαπημένες γραμματοσειρές - Recent font list Λίστα πρόσφατων γραμματοσειρών Add to Favorites Προσθήκη στα αγαπημένα Remove from Favorites Αφαίρεση από τα αγαπημένα Show All Fonts Εμφάνιση όλων των γραμματοσειρών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c9b03faeca..fe73cf7599 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4212,7 +4212,6 @@ navigator Zoom Zoom Show Favorite Fonts Mostrar fuentes favoritas No favorite fonts yet: click the star beside a font to add it. Aún no hay fuentes favoritas: haz clic en la estrella junto a una fuente para añadirla. Favorite fonts Fuentes favoritas - Recent font list Lista de fuentes recientes Add to Favorites Añadir a favoritos Remove from Favorites Quitar de favoritos Show All Fonts Mostrar todas las fuentes diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 99dbd74b99..0718c13cc5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3259,7 +3259,6 @@ curves Smooth Lisser Show Favorite Fonts Afficher les polices favorites No favorite fonts yet: click the star beside a font to add it. Aucune police favorite pour l’instant : cliquez sur l’étoile à côté d’une police pour l’ajouter. Favorite fonts Polices favorites - Recent font list Liste des polices récentes Add to Favorites Ajouter aux favoris Remove from Favorites Retirer des favoris Show All Fonts Afficher toutes les polices diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 39e473cf77..70fbb8f15a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4157,7 +4157,6 @@ cameraRaw Yellow Sárga Show Favorite Fonts Kedvenc betűtípusok megjelenítése No favorite fonts yet: click the star beside a font to add it. Még nincsenek kedvenc betűtípusok: kattintson a betűtípus melletti csillagra a hozzáadáshoz. Favorite fonts Kedvenc betűtípusok - Recent font list Legutóbbi betűtípusok listája Add to Favorites Hozzáadás a kedvencekhez Remove from Favorites Eltávolítás a kedvencek közül Show All Fonts Összes betűtípus megjelenítése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 41b0c14e2b..0815cd08ae 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3262,7 +3262,6 @@ curves Smooth Haluskan Show Favorite Fonts Tampilkan Font Favorit No favorite fonts yet: click the star beside a font to add it. Belum ada font favorit: klik bintang di samping font untuk menambahkannya. Favorite fonts Font favorit - Recent font list Daftar font terbaru Add to Favorites Tambahkan ke Favorit Remove from Favorites Hapus dari Favorit Show All Fonts Tampilkan Semua Font diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c5127b26b5..2cafd29814 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4215,7 +4215,6 @@ navigator Zoom Zoom Show Favorite Fonts Mostra font preferiti No favorite fonts yet: click the star beside a font to add it. Ancora nessun font preferito: fai clic sulla stella accanto a un font per aggiungerlo. Favorite fonts Font preferiti - Recent font list Elenco dei font recenti Add to Favorites Aggiungi ai preferiti Remove from Favorites Rimuovi dai preferiti Show All Fonts Mostra tutti i font diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a7698416c7..b0d1f043a3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3930,7 +3930,6 @@ curves Smooth スムーズ Show Favorite Fonts お気に入りのフォントを表示 No favorite fonts yet: click the star beside a font to add it. お気に入りのフォントはまだありません。フォントの横の星をクリックして追加してください。 Favorite fonts お気に入りのフォント - Recent font list 最近使用したフォントのリスト Add to Favorites お気に入りに追加 Remove from Favorites お気に入りから削除 Show All Fonts すべてのフォントを表示 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 410dfdc293..db3206ef2d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3454,7 +3454,6 @@ curves Smooth 매끄럽게 Show Favorite Fonts 즐겨찾는 글꼴 표시 No favorite fonts yet: click the star beside a font to add it. 아직 즐겨찾는 글꼴이 없습니다. 글꼴 옆의 별을 클릭하여 추가하세요. Favorite fonts 즐겨찾는 글꼴 - Recent font list 최근 글꼴 목록 Add to Favorites 즐겨찾기에 추가 Remove from Favorites 즐겨찾기에서 제거 Show All Fonts 모든 글꼴 표시 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ba1c77a6bc..16e0538b04 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4011,7 +4011,6 @@ curves Smooth Vloeiend maken Show Favorite Fonts Favoriete lettertypen tonen No favorite fonts yet: click the star beside a font to add it. Nog geen favoriete lettertypen: klik op de ster naast een lettertype om het toe te voegen. Favorite fonts Favoriete lettertypen - Recent font list Lijst met recente lettertypen Add to Favorites Toevoegen aan favorieten Remove from Favorites Verwijderen uit favorieten Show All Fonts Alle lettertypen tonen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8178556524..c0645b1e0d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3866,7 +3866,6 @@ curves Smooth Wygładź Show Favorite Fonts Pokaż ulubione czcionki No favorite fonts yet: click the star beside a font to add it. Brak ulubionych czcionek: kliknij gwiazdkę obok czcionki, aby ją dodać. Favorite fonts Ulubione czcionki - Recent font list Lista ostatnich czcionek Add to Favorites Dodaj do ulubionych Remove from Favorites Usuń z ulubionych Show All Fonts Pokaż wszystkie czcionki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a6f9c3017b..57fd678440 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4041,7 +4041,6 @@ layerLabel No Color Sem cor Show Favorite Fonts Mostrar fontes favoritas No favorite fonts yet: click the star beside a font to add it. Ainda não há fontes favoritas: clique na estrela ao lado de uma fonte para adicioná-la. Favorite fonts Fontes favoritas - Recent font list Lista de fontes recentes Add to Favorites Adicionar aos favoritos Remove from Favorites Remover dos favoritos Show All Fonts Mostrar todas as fontes diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c6f7509b95..0058e73ffe 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3239,7 +3239,6 @@ curves Smooth Сгладить Show Favorite Fonts Показать избранные шрифты No favorite fonts yet: click the star beside a font to add it. Избранных шрифтов пока нет: нажмите на звёздочку рядом со шрифтом, чтобы добавить его. Favorite fonts Избранные шрифты - Recent font list Список последних шрифтов Add to Favorites Добавить в избранное Remove from Favorites Удалить из избранного Show All Fonts Показать все шрифты diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 38e6f98614..f1e536f8e8 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4291,7 +4291,6 @@ shape Appearance Izgled Show Favorite Fonts Прикажи омиљене фонтове No favorite fonts yet: click the star beside a font to add it. Још нема омиљених фонтова: кликните на звездицу поред фонта да бисте га додали. Favorite fonts Омиљени фонтови - Recent font list Листа недавних фонтова Add to Favorites Додај у омиљене Remove from Favorites Уклони из омиљених Show All Fonts Прикажи све фонтове diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 395395bef2..c8407e1ef3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3969,7 +3969,6 @@ cameraData Lens Lens Show Favorite Fonts Favori yazı tiplerini göster No favorite fonts yet: click the star beside a font to add it. Henüz favori yazı tipi yok: eklemek için bir yazı tipinin yanındaki yıldıza tıklayın. Favorite fonts Favori yazı tipleri - Recent font list Son kullanılan yazı tipleri listesi Add to Favorites Favorilere ekle Remove from Favorites Favorilerden kaldır Show All Fonts Tüm yazı tiplerini göster diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a0e99c11b0..c9973812a8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3951,7 +3951,6 @@ curves Smooth Згладити Show Favorite Fonts Показати вибрані шрифти No favorite fonts yet: click the star beside a font to add it. Вибраних шрифтів ще немає: натисніть зірочку біля шрифту, щоб додати його. Favorite fonts Вибрані шрифти - Recent font list Список останніх шрифтів Add to Favorites Додати до вибраного Remove from Favorites Видалити з вибраного Show All Fonts Показати всі шрифти diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f1d692c7d5..cbbe01f03f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3715,7 +3715,6 @@ curves Smooth Làm mượt Show Favorite Fonts Hiển thị phông chữ yêu thích No favorite fonts yet: click the star beside a font to add it. Chưa có phông chữ yêu thích: nhấp vào ngôi sao bên cạnh phông chữ để thêm. Favorite fonts Phông chữ yêu thích - Recent font list Danh sách phông chữ gần đây Add to Favorites Thêm vào mục yêu thích Remove from Favorites Xóa khỏi mục yêu thích Show All Fonts Hiển thị tất cả phông chữ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ba09b7ea30..df8fa52619 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2902,7 +2902,6 @@ curves Smooth 平滑 Show Favorite Fonts 显示收藏的字体 No favorite fonts yet: click the star beside a font to add it. 还没有收藏的字体:点击字体旁边的星标即可添加。 Favorite fonts 收藏的字体 - Recent font list 最近使用的字体列表 Add to Favorites 添加到收藏 Remove from Favorites 从收藏中移除 Show All Fonts 显示所有字体 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4ea8bd0b5a..cc7bdcefed 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2866,7 +2866,6 @@ curves Smooth 平滑 Show Favorite Fonts 顯示我的最愛字體 No favorite fonts yet: click the star beside a font to add it. 尚無我的最愛字體:按一下字體旁的星號即可加入。 Favorite fonts 我的最愛字體 - Recent font list 最近使用的字體清單 Add to Favorites 加入我的最愛 Remove from Favorites 從我的最愛移除 Show All Fonts 顯示所有字體 diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 1c7fbddb1e..fd7e032616 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -1472,8 +1472,16 @@ fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option = { + let mut rows: Vec<(f32, String)> = ["Family 00", "Family 01", "Family 02", "Family 03", "Family 04", "Zeta Sans"] + .iter() + .filter_map(|f| h.query_by_label(f).map(|n| (n.rect().top(), f.to_string()))) + .collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + rows.into_iter().map(|(_, f)| f).collect() + }; + assert_eq!(order[0], "Family 00", "the current font first"); + for step in 1..4 { + h.key_press(egui::Key::ArrowDown); + h.run(); + assert_eq!(h.state().current, order[step], "step {step} through {order:?}"); + } +} + #[test] fn a_style_picked_under_the_expander_picks_the_family_in_that_style() { let mut h = filter_harness(); @@ -1232,6 +1255,35 @@ fn a_style_picked_under_the_expander_picks_the_family_in_that_style() { assert!(h.query_by_label("Family 10").is_none(), "picking a style closes the menu"); } +/// An expanded family's style rows stay listed while the list scrolls its own row out of view: +/// they used to vanish then, so the rows below jumped up. +#[test] +fn an_expanded_familys_styles_stay_listed_when_its_row_scrolls_away() { + let mut h = filter_harness(); + let top = h.get_by_label("Family 00").rect().top(); + h.get_by_label("Show Styles").click(); + h.run(); + assert!(h.query_by_label("Italic").is_some(), "Family 01 lists its styles"); + let over = h.get_by_label("Family 05").rect().center(); + h.hover_at(over); + h.run(); + let mut styles_without_family_row = false; + for _ in 0..40 { + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -6.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }); + h.run_steps(3); + let family_gone = h.query_by_label("Family 01").is_none_or(|n| n.rect().bottom() <= top); + let italic = h.query_by_label("Italic").map(|n| n.rect()); + styles_without_family_row |= family_gone && italic.is_some_and(|r| r.bottom() > top); + } + assert!(styles_without_family_row, "the style rows show below the family row scrolled out of view"); +} + #[test] fn the_search_field_stays_in_place_while_the_list_scrolls() { let mut h = library_harness(&[], &[]); diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index a0eb715f10..897b915050 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -2923,7 +2923,17 @@ pub(crate) fn family_picker_in( let open_recents: Vec = ui.data_mut(|d| d.get_temp_mut_or_insert_with(recents_id, || library.recent.clone()).clone()); // No recent group while a filter is on: the filters narrow the alphabetical list alone. let (mut rows, n_recent) = font_menu_rows(families, labels, &ql, if filters.any() { &[] } else { &open_recents }); - let comparable = crate::font_filters::apply(&mut rows, &filters, &library.favorites, current, &lookup); + // Show Similar Fonts compares with the font current when it was turned on (or the menu + // opened), as the recent group stays put: each arrow step applies a font, and sorting + // around that one sent the next step back to the font before. + let similar_id = search_id.with("similar-to"); + let reference: String = if filters.similar { + ui.data_mut(|d| d.get_temp_mut_or_insert_with(similar_id, || current.clone()).clone()) + } else { + ui.data_mut(|d| d.remove::(similar_id)); + current.clone() + }; + let comparable = crate::font_filters::apply(&mut rows, &filters, &library.favorites, &reference, &lookup); // A recent family is listed twice. The current family's row is the one the last arrow // selected while it still shows that family, else its first copy: as in Photoshop, the // one in the recent group when it has one (#9160), and the arrows walk on from there. @@ -3012,11 +3022,12 @@ pub(crate) fn family_picker_in( if i == n_recent && n_recent > 0 { ui.separator(); } - // Only rows on screen read their font's format and styles. + // Only rows on screen read their font's format and styles, and an expanded + // family: its style rows stay listed when its own row scrolls out of view. let visible = ui.is_rect_visible(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(FONT_LIST_WIDTH, row_h))); let format = if visible { lookup(f).map(|t| t.format) } else { None }; - let styles = if visible { library.styles_of(f) } else { Vec::new() }; let open = !recent_row && expanded.contains(f); + let styles = if visible || open { library.styles_of(f) } else { Vec::new() }; let favorite = library.favorites.contains(f); // Highlighted by its fill alone, as Photoshop's font menu is: a hovered or selected // row's stroke grew it and pushed the rows below down (#7406). @@ -3149,6 +3160,7 @@ pub(crate) fn family_picker_in( d.remove::>(recents_id); d.remove::(row_id); d.remove::(search_id.with("reveal")); + d.remove::(search_id.with("similar-to")); }); } let hovered_font = response.inner.unwrap_or_default(); @@ -4045,7 +4057,11 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa if ready && let Some(picked) = font_picker(app, ui, &mut fam, full) { app.ui.tool_options.type_font = fam.clone(); match picked { - Some(style) => apply(app, ui.ctx(), json!({"font": fam, "fontStyle": style})), + Some(style) => { + // New type takes the style too, as from the options bar's menu. + app.ui.tool_options.type_style = style.clone(); + apply(app, ui.ctx(), json!({"font": fam, "fontStyle": style})); + } None => apply(app, ui.ctx(), json!({"font": fam})), } } diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index cf0aeb4970..59e562faa0 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -2094,6 +2094,29 @@ mod multi_layer_formatting { h.run_steps(2); } + /// A style picked under a family's ">" in the Character section's font menu, with type + /// layers selected, sets them and is kept for new type, as the options bar's menu does. + #[test] + fn a_style_picked_in_the_character_sections_font_menu_is_kept_for_new_type() { + let (app, ids) = fixture(); + // The first style row under the family (so it is in view), other than the defaults'. + let pick = super::super::styles("Inter").into_iter().find(|s| s != "Regular" && s != "Bold Italic").expect("Inter has several styles"); + assert_ne!(app.ui.tool_options.type_style, pick); + let mut h = controls(app, true); + h.get_all_by_role(Role::ComboBox).next().unwrap().click(); + h.run(); + h.get_all_by_role(Role::TextInput).find(|n| n.is_focused()).expect("the search field has the focus").type_text("Inter"); + h.run(); + h.get_all_by_label("Show Styles").next().unwrap().click(); + h.run(); + h.get_by_label(&super::super::style_label(&pick)).click(); + h.run(); + assert_eq!(h.state().ui.tool_options.type_style, pick, "new type takes the picked style"); + for id in &ids[..2] { + assert_eq!(style(h.state(), *id, 0).font_style, pick, "the selected layers are set in it"); + } + } + #[test] fn hyphenate_is_not_shown_while_layout_does_not_hyphenate() { // #6710: layout never hyphenates; the control must stay hidden until it does. diff --git a/docs/scorecard.md b/docs/scorecard.md index d025e67944..c0305f6460 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 31 | 65 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 27 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 178 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 179 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -187,7 +187,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 178** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 12 of 179** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 760b9d1cc870e3fe0b844313ab69e72237491bcd Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 14:38:52 +0100 Subject: [PATCH 72/87] Integration: distort/skew pointers only where the drag distorts or skews (#5405) Cmd armed the new Distort and Skew pointers in every transform mode, while the drag did something else: in Rotate mode a Cmd-drag on a corner or edge rotates but showed the dart or skew arrows; a Skew-mode corner with Cmd showed the dart but slides along an edge; Distort mode with Cmd drew skew arrows on edges it refuses. Cmd also hid the curved rotate arrow just outside a corner (the Alias commit pointer showed) although a Cmd-drag there still rotates. One helper, handle_indicator, now answers "what does this drag do" with the same rules as the drag (drag_mods, mode_mods, apply_mode_drag), and both the cursor and the drawn pointer use it. The pointer is drawn from the canvas's cursor branch, so a guide, pan or zoom cursor over a handle no longer gets a second pointer on top, and cursor() no longer hides the pointer while the box is being applied (the overlay draws nothing then). During a drag the rotate arrow shows only while the drag rotates (also a Rotate-mode handle drag), not when a scaling corner strays past another corner. The warp split guide reads sticky keys like the cursor does. Co-authored-by: Catur Sura <8650781+catursurapam@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 7 +- crates/ui-egui/src/tools/transform_tool.rs | 5 +- .../src/tools/transform_tool/drag_modes.rs | 29 +++++- .../ui-egui/src/tools/transform_tool/draw.rs | 64 +++++++------ .../src/tools/transform_tool/pointer.rs | 34 ++++--- .../ui-egui/src/tools/transform_tool/tests.rs | 95 ++++++++++++++++++- 6 files changed, 182 insertions(+), 52 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ad24cdc07d..6912a149e6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1361,11 +1361,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // CursorIcon::None hides the pointer; the curved arrow has to be drawn or the // rotate zone looks like a plain cursor (#4050). let d = xf.to_doc(p); - if !mods.command - && let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) - { + if let Some(k) = crate::transform_tool::rotate_cursor_dir(app, d) { let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; crate::crop_ui::draw_turn_cursor(&ctx, p, toward); + } else if c == egui::CursorIcon::None { + // Likewise the distort and skew pointers over a handle (#5405). + crate::transform_tool::draw_handle_cursor(app, &ctx, &xf, p, mods); } } else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, &xf, xf.to_doc(p))) { ui.ctx().set_cursor_icon(c); diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 1aac4e1854..f12811c781 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -35,11 +35,12 @@ pub(crate) use begin::begin_content_aware; pub use begin::{begin, begin_copy, begin_placed, begin_selection, begin_warp, enter_warp, leave_warp, warps_type}; pub(crate) use commit::{SAVE_FOR_WEB, committing, nudge}; pub use commit::{cancel, commit, end_if_left, follow_edits, intercept, is_enabled, on_job_event, track_steps}; +#[cfg(test)] +use drag_modes::{HandleIndicator, handle_indicator, keep_convex, turns}; pub(crate) use drag_modes::{apply_drag, corner_distorts, legacy_mods}; #[cfg(test)] pub(crate) use drag_modes::{apply_mode_drag, unlinked_mods}; -#[cfg(test)] -use drag_modes::{keep_convex, turns}; +pub(crate) use draw::draw_handle_cursor; #[cfg(test)] pub(crate) use draw::{Readout, live_readout, styled_frame}; pub(crate) use draw::{carries_selection_of, draw_selection}; diff --git a/crates/ui-egui/src/tools/transform_tool/drag_modes.rs b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs index 1d69a561f5..49f594e08f 100644 --- a/crates/ui-egui/src/tools/transform_tool/drag_modes.rs +++ b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs @@ -21,10 +21,37 @@ pub(crate) fn corner_distorts(app: &PhotocraftApp, index: usize, mods: egui::Mod mods.command && !(mods.alt && mods.shift) } +/// The pointer a handle shows for a drag that distorts or skews the box rather than scaling or +/// rotating it (#5405). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum HandleIndicator { + Distort, + Skew, +} + +/// What dragging handle `h` with `mods` does, worked out by the same rules as the drag itself +/// ([`drag_mods`], [`mode_mods`], [`apply_mode_drag`]): ⌘ on a corner distorts (⌘⌥⇧ adds +/// perspective) and on an edge skews, Distort and Perspective modes distort from the corners, +/// Skew mode skews from the edges. Rotate mode turns the box whatever the keys, a Skew-mode corner +/// slides along an edge, editable type refuses Distort and Content-Aware Scale only scales: `None`. +pub(super) fn handle_indicator(app: &PhotocraftApp, t: &TransformSession, h: Hit, mods: egui::Modifiers) -> Option { + if t.warp.is_some() || t.content_aware.is_some() || !mode_allows(t.mode, h) { + return None; + } + let (mode, mods) = drag_mods(app, t, h, mods); + match (mode, h) { + (TransformMode::Rotate, _) | (TransformMode::Skew, Hit::Corner(_)) => None, + (TransformMode::Skew, Hit::Edge(_)) => Some(HandleIndicator::Skew), + (_, Hit::Corner(_)) if mode_mods(mode, h, mods).command => Some(HandleIndicator::Distort), + (_, Hit::Edge(_)) if mods.command => Some(HandleIndicator::Skew), + _ => None, + } +} + /// Editable type can be scaled, rotated and skewed but not distorted (#2630): the rule that greys /// Distort and Perspective in `enable_rules::disabled`, for the box's own layer. A box on a path, /// on the selection outline or on a lone mask or channel moves no type. -pub(super) fn distort_refused(app: &PhotocraftApp, t: &TransformSession) -> bool { +fn distort_refused(app: &PhotocraftApp, t: &TransformSession) -> bool { t.path.is_none() && !t.selection && t.target.is_none() diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 241f3d53ad..68f0c5a188 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -1,18 +1,40 @@ use super::begin::warps_type; +use super::drag_modes::{HandleIndicator, handle_indicator}; use super::options_bar::{quad_scale, readout}; -use super::drag_modes::distort_refused; -use super::pointer::{Hit, hit, rotate_dir, rotation_degrees}; +use super::pointer::{Hit, handle_at, rotate_dir, rotation_degrees}; use super::warp::{on_section_edge, quick_split_kind, single_patch}; use super::*; +/// The distort or skew pointer at screen point `at`, where [`super::cursor`] hid the system +/// pointer over a handle. The canvas calls it from its cursor branch, so nothing is drawn where a +/// guide, a pan or a zoom set the cursor instead. +pub(crate) fn draw_handle_cursor(app: &PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, at: Pos2, mods: egui::Modifiers) { + let Some(t) = &app.ui.transform else { return }; + let h = handle_at(app, t, xf.to_doc(at), super::handle_tolerance(app)); + let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + match (h, handle_indicator(app, t, h, mods)) { + (Hit::Corner(i), Some(HandleIndicator::Distort)) => { + if let Some(q) = t.quad.get(i) { + draw_distort_cursor(ctx, at, scr(*q) - scr(t.pivot)); + } + } + (Hit::Edge(i), Some(HandleIndicator::Skew)) => { + if let (Some(a), Some(b)) = (t.quad.get(i), t.quad.get((i + 1) % 4)) { + draw_skew_cursor(ctx, at, scr(*b) - scr(*a)); + } + } + _ => {} + } +} + /// Draws the Free Distort cursor at `at`: a high-contrast vector pointer pointing toward /// or outward through the corner, with shadow outline for contrast on any canvas background. -pub fn draw_distort_cursor(ctx: &egui::Context, at: Pos2, toward: egui::Vec2) { +fn draw_distort_cursor(ctx: &egui::Context, at: Pos2, toward: egui::Vec2) { let len = toward.length(); let u = if len.is_finite() && len > 1e-6 { toward / len } else { vec2(-1.0, -1.0).normalized() }; let perp = vec2(-u.y, u.x); let tokens = crate::theme::Tokens::get(ctx); - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("transform-distort-cursor"))); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("transform-distort-cursor"))); // An arrowhead dart pointing along `u` with tip at `at`. let tip = at; @@ -30,12 +52,12 @@ pub fn draw_distort_cursor(ctx: &egui::Context, at: Pos2, toward: egui::Vec2) { } /// Draws the Skew cursor at `at`: opposing parallel arrows aligned with the edge tangent `tangent`. -pub fn draw_skew_cursor(ctx: &egui::Context, at: Pos2, tangent: egui::Vec2) { +fn draw_skew_cursor(ctx: &egui::Context, at: Pos2, tangent: egui::Vec2) { let len = tangent.length(); let u = if len.is_finite() && len > 1e-6 { tangent / len } else { vec2(1.0, 0.0) }; let perp = vec2(-u.y, u.x); let tokens = crate::theme::Tokens::get(ctx); - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("transform-skew-cursor"))); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("transform-skew-cursor"))); for (offset, dir) in [(4.0f32, 1.0f32), (-4.0f32, -1.0f32)] { let center = at + perp * offset; @@ -130,7 +152,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some(w) = &t.warp { let over_canvas = painter.ctx().input(|i| i.pointer.hover_pos()).filter(|p| xf.rect.contains(*p)).map(|p| xf.to_doc(p)); let at = pv.split_pointer.or(over_canvas); - let alt = painter.ctx().input(|i| i.modifiers.alt || i.modifiers.command); + // The same keys as `cursor`, sticky ones included, so the guide matches the pointer. + let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); + let alt = mods.alt || mods.command; let guide = at.filter(|_| !warps_type(app)).and_then(|p| { let tool = pv.split_tool.or_else(|| { (alt || pv.split_quick).then(|| { @@ -172,32 +196,10 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform painter.circle_stroke(c, 5.0, Stroke::new(0.5, Color32::BLACK)); painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::WHITE)); painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE)); - if let Some(at) = painter.ctx().input(|i| i.pointer.interact_pos().or(i.pointer.hover_pos())).filter(|p| xf.rect.contains(*p)) { + if let Some(at) = painter.ctx().pointer_hover_pos().filter(|p| xf.rect.contains(*p)) { let p = xf.to_doc(at); let tol = HANDLE_PX / f64::from(xf.zoom.max(0.01)); - let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); - let active_hit = pv.gesture.map(|g| g.hit); - let h = active_hit.unwrap_or_else(|| hit(t, p, tol)); - let distort_armed = (mods.command || t.mode == TransformMode::Distort) && !distort_refused(app, t) && t.content_aware.is_none(); - let skew_armed = (mods.command || t.mode == TransformMode::Skew) && t.content_aware.is_none(); - - if let Hit::Corner(i) = h - && distort_armed - { - let corner_scr = scr(t.quad[i]); - let pivot_scr = scr(t.pivot); - let toward = corner_scr - pivot_scr; - draw_distort_cursor(painter.ctx(), at, toward); - } else if let Hit::Edge(i) = h - && skew_armed - { - let a_scr = scr(t.quad[i]); - let b_scr = scr(t.quad[(i + 1) % 4]); - let tangent = b_scr - a_scr; - draw_skew_cursor(painter.ctx(), at, tangent); - } else if !mods.command - && let Some(k) = rotate_dir(t, Some(pv), p, tol) - { + if let Some(k) = rotate_dir(t, Some(pv), p, tol) { // Through the view, so the arc bends round the corner as it shows under a turned or // flipped view. let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index f22552371a..e11f0c97c9 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -1,6 +1,6 @@ use super::begin::warps_type; use super::commit::{commit, committing, moves_type}; -use super::drag_modes::{apply_drag, apply_mode_drag, distort_refused, drag_mods, mode_allows, mode_mods}; +use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, handle_indicator, mode_allows, mode_mods}; use super::warp::{quick_split_kind, split_cursor, surface_at, warp_hit, warp_pointer}; use super::*; @@ -239,9 +239,13 @@ pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: { return None; } - let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); - if !rotating && !near_rotate_corner(t, p, tol) { - return None; + // During a drag the arrow shows only while it rotates: not when a handle that scales, skews + // or distorts strays past a corner (#5405). + match pv.and_then(|pv| pv.gesture) { + Some(g) if g.hit == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(g.hit, Hit::Corner(_) | Hit::Edge(_))) => {} + Some(_) => return None, + None if !near_rotate_corner(t, p, tol) => return None, + None => {} } let dist = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); let i = (0..4).min_by(|&a, &b| dist(t.quad[a]).total_cmp(&dist(t.quad[b])))?; @@ -256,6 +260,11 @@ pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: (l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l]) } +/// The handle a drag in progress holds, else the one under document point `p`. +pub(super) fn handle_at(app: &PhotocraftApp, t: &TransformSession, p: [f64; 2], tol: f64) -> Hit { + app.transform_preview.as_ref().and_then(|pv| pv.gesture.map(|g| g.hit)).unwrap_or_else(|| hit(t, p, tol)) +} + /// Cursor for hovering a document point while transforming. `xf` is the canvas's view; /// `mods` provides modifier keys (Command for Distort on corners / Skew on edges; Alt/Command for quick split in warp). pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modifiers) -> Option { @@ -279,18 +288,18 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modi } return Some(if w.mesh.as_ref().and_then(|m| surface_at(m, p)).is_some() { CursorIcon::Grab } else { CursorIcon::Default }); } - let active_hit = app.transform_preview.as_ref().and_then(|pv| pv.gesture.map(|g| g.hit)); - let h = active_hit.unwrap_or_else(|| hit(t, p, tol)); + let h = handle_at(app, t, p, tol); if !mode_allows(t.mode, h) || (t.content_aware.is_some() && h == Hit::Outside) { return Some(CursorIcon::Default); } - if !mods.command && rotate_cursor_dir(app, p).is_some() { - // The overlay draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. + // A ⌘-drag outside the box still rotates, so ⌘ keeps the curved arrow there. + if rotate_cursor_dir(app, p).is_some() { + // The canvas draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. return Some(CursorIcon::None); } - let distort_armed = (mods.command || t.mode == TransformMode::Distort) && !distort_refused(app, t) && t.content_aware.is_none(); - let skew_armed = (mods.command || t.mode == TransformMode::Skew) && t.content_aware.is_none(); - + // The canvas draws the distort or skew pointer in place of the hidden one + // (`draw_handle_cursor`); not while the box is being applied, when it draws no handles. + let indicator = handle_indicator(app, t, h, mods).filter(|_| committing(app).is_none()); // The box's corners run clockwise from the top-left; edge k joins corners k and k + 1. let corner = |k: usize| t.quad[k % 4]; let edge_mid = |k: usize| { @@ -300,9 +309,8 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modi // A handle resizes the box away from the opposite handle. let resize = |from: [f64; 2], to: [f64; 2]| crate::tool_cursor::resize([to[0] - from[0], to[1] - from[1]], xf); Some(match h { - Hit::Corner(_) if distort_armed => CursorIcon::None, + Hit::Corner(_) | Hit::Edge(_) if indicator.is_some() => CursorIcon::None, Hit::Corner(i) => crate::tool_cursor::corner_resize(&t.quad, i, xf), - Hit::Edge(_) if skew_armed => CursorIcon::None, Hit::Edge(i) => resize(edge_mid(i + 2), edge_mid(i)), Hit::Pivot => CursorIcon::Crosshair, Hit::Inside => CursorIcon::Move, diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 9191bdf23c..5d571f4d21 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -3008,9 +3008,10 @@ fn hovering_corner_with_ctrl_shows_distort_cursor() { // With Ctrl: corner handle arms free distort, hiding OS cursor so custom pointer is drawn. assert_eq!(cursor(&app, &xf, corner, command), Some(CursorIcon::None)); - // Holding Ctrl suppresses rotation around corners. + // A Cmd-drag just outside a corner still rotates, so the curved arrow stays. let near_corner = [32.0 - tol * 1.5, 32.0 - tol * 1.5]; - assert_eq!(cursor(&app, &xf, near_corner, command), Some(CursorIcon::Alias)); + assert_eq!(cursor(&app, &xf, near_corner, command), Some(CursorIcon::None)); + assert!(rotate_cursor_dir(&app, near_corner).is_some()); assert_eq!(cursor(&app, &xf, near_corner, egui::Modifiers::NONE), Some(CursorIcon::None)); } @@ -3077,3 +3078,93 @@ fn cursor_during_drag_stays_stable() { assert_eq!(cursor(&app, &xf, [200.0, 200.0], command), Some(CursorIcon::Alias)); assert_ne!(cursor(&app, &xf, [50.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::None)); } + +fn cmd() -> egui::Modifiers { + egui::Modifiers { command: true, ..Default::default() } +} + +/// The indicator each handle shows in `mode` with `mods`: corner 0 and edge 0 (top) of a square. +fn indicators(mode: &str, mods: egui::Modifiers) -> (Option, Option) { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), mode, json!({})).unwrap(); + let t = app.ui.transform.clone().unwrap(); + (handle_indicator(&app, &t, Hit::Corner(0), mods), handle_indicator(&app, &t, Hit::Edge(0), mods)) +} + +#[test] +fn handle_pointers_follow_what_the_drag_does() { + use HandleIndicator::{Distort, Skew}; + let none = egui::Modifiers::NONE; + let persp = egui::Modifiers { command: true, alt: true, shift: true, ..Default::default() }; + assert_eq!(indicators("edit.freeTransform", none), (None, None), "plain drags scale"); + assert_eq!(indicators("edit.freeTransform", cmd()), (Some(Distort), Some(Skew))); + assert_eq!(indicators("edit.freeTransform", persp), (Some(Distort), Some(Skew))); + // Rotate mode turns the box from every handle, whatever the keys. + assert_eq!(indicators("edit.transform.rotate", cmd()), (None, None)); + // A Skew-mode corner slides along one edge, with or without Cmd; its edges skew. + assert_eq!(indicators("edit.transform.skew", cmd()), (None, Some(Skew))); + assert_eq!(indicators("edit.transform.skew", none), (None, Some(Skew))); + // Distort mode leaves the edges alone, Cmd or not. + assert_eq!(indicators("edit.transform.distort", none), (Some(Distort), None)); + assert_eq!(indicators("edit.transform.distort", cmd()), (Some(Distort), None)); + // Perspective mode: corners move in pairs; Cmd on an edge skews (`apply_drag`). + assert_eq!(indicators("edit.transform.perspective", none), (Some(Distort), None)); + assert_eq!(indicators("edit.transform.perspective", cmd()), (Some(Distort), Some(Skew))); + assert_eq!(indicators("edit.transform.scale", cmd()), (Some(Distort), Some(Skew))); +} + +#[test] +fn ctrl_in_rotate_mode_keeps_the_rotate_pointer() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.rotate", json!({})).unwrap(); + let xf = ViewXform::active(&app).unwrap(); + let corner = [32.0, 32.0]; + assert_eq!(cursor(&app, &xf, corner, cmd()), Some(CursorIcon::None)); + assert!(rotate_cursor_dir(&app, corner).is_some(), "a Rotate-mode corner drag rotates: the turn arrow stays"); + // An edge drag rotates too: Cmd draws no skew pointer there. + let edge = [96.0, 32.0]; + assert_eq!(cursor(&app, &xf, edge, cmd()), cursor(&app, &xf, edge, egui::Modifiers::NONE)); +} + +#[test] +fn rotate_mode_handle_drag_keeps_the_arrow_away_from_the_corners() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.rotate", json!({})).unwrap(); + let xf = ViewXform::active(&app).unwrap(); + let none = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, none); + // Far from every corner of the turned box, past the hover zone. + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 250.0, y: 96.0, pressure: 1.0 }, none); + let t = app.ui.transform.clone().unwrap(); + let tol = handle_tolerance(&app); + assert!(t.quad.iter().all(|q| (250.0 - q[0]).hypot(96.0 - q[1]) > tol * 4.0), "{:?}", t.quad); + assert!(rotate_cursor_dir(&app, [250.0, 96.0]).is_some(), "the corner drag rotates"); + assert_eq!(cursor(&app, &xf, [250.0, 96.0], none), Some(CursorIcon::None)); +} + +#[test] +fn scale_drag_past_a_corner_shows_no_rotate_arrow() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let none = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 160.0, y: 160.0, pressure: 1.0 }, none); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 150.0, pressure: 1.0 }, none); + let t = app.ui.transform.clone().unwrap(); + let tol = handle_tolerance(&app); + // Just outside another corner, where a hover would show the turn arrow. + let past = [t.quad[0][0] - tol * 1.5, t.quad[0][1] - tol * 1.5]; + assert_eq!(rotate_cursor_dir(&app, past), None, "the drag scales"); +} + +#[test] +fn applying_the_box_hides_no_pointer() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let xf = ViewXform::active(&app).unwrap(); + app.transform_preview.as_mut().unwrap().committing = Some(JobId(1)); + // The overlay draws no handles while the box is applied, so no drawn pointer either. + assert_eq!(cursor(&app, &xf, [32.0, 32.0], cmd()), Some(CursorIcon::ResizeNwSe)); + assert_eq!(cursor(&app, &xf, [96.0, 32.0], cmd()), Some(CursorIcon::ResizeVertical)); +} From 4add96c84b5d055a2d9e2c82a0b6570023ea42c3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 15:25:08 +0100 Subject: [PATCH 73/87] Integration: Character panel presets as in the reference app, on main's layout (#3558) Ports the size, leading and tracking preset chevrons onto main's split type tool (tools/type_tool/panel.rs, next to num_field, which now names its scrub icon) and fixes what review found: - The lists differ from the reference app: Size is 6, 8, 9, 10, 11, 12, 14, 16, 18, 24, 30, 36, 48, 60, 72, 150, 300 pt (the PR had 96, no 16/150/300); Leading is Auto plus the same list (one shared pub(crate) const); Tracking is -100..-5 | 0 | 5..200 with separators (the PR lacked -5/5 and separators). - The PR's layout test was red on CI: the chevron ended ~20 px short of the column. The numeric field now gets the column width minus the chevron's exact button width, and the test is strict again (the chevron ends at the panel edge within 0.5 px, the field's suffix slot matches Transform's). - In mm the labels read "2.1166668 mm" and a pick stored 12.000001 pt. Labels now have at most two decimals, a picked preset stores its point value directly, and "selected" uses a relative tolerance. - The chevrons have accessible names (Font size / Leading / Tracking presets, translated in every complete catalog); tests find them by name. New tests: the literal lists (fail on the PR's lists), the strict layout test, mm labels and exact 12 pt, a preset while editing a span, and presets without a type layer setting the defaults with no history step. Co-authored-by: Ni-zav <106657905+Ni-zav@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sr.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + .../ui-egui/src/panels/props_layout/tests.rs | 17 +- .../src/tools/type_tool/canvas_tests.rs | 147 +++++++++++++++--- crates/ui-egui/src/tools/type_tool/panel.rs | 103 +++++++++++- 23 files changed, 291 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 925d19568b..c4cdad6e71 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4201,3 +4201,6 @@ cameraRaw Dehaze Odstranění oparu # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Poměr stran + Font size presets Předvolby velikosti písma + Leading presets Předvolby prokladu + Tracking presets Předvolby prostrkání diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6558daa51d..05e365c3bc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3475,3 +3475,6 @@ curves Smooth Glätten Interpolation Interpolation Target Ziel Units Einheiten + Font size presets Schriftgrößen-Vorgaben + Leading presets Zeilenabstand-Vorgaben + Tracking presets Laufweiten-Vorgaben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5f1a3d3538..06ee76bb2f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4154,3 +4154,6 @@ curves Smooth Εξομάλυνση # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Στόχος + Font size presets Προεπιλογές μεγέθους γραμματοσειράς + Leading presets Προεπιλογές διάστιχου + Tracking presets Προεπιλογές διαστήματος χαρακτήρων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 879572c9f4..8d9956333e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4413,3 +4413,6 @@ navigator Zoom Zoom Tight Curl Rizo apretado Loose Curl Rizo suelto Stylized dabs from a history state Toques estilizados desde un estado del historial + Font size presets Valores predefinidos de tamaño de fuente + Leading presets Valores predefinidos de interlineado + Tracking presets Valores predefinidos de tracking diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9692437211..1631f6bbc4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4493,3 +4493,6 @@ shape Appearance Apparence Tight Curl Boucle serrée Loose Curl Boucle lâche Stylized dabs from a history state Touches stylisées depuis un état d'historique + Font size presets Tailles de police prédéfinies + Leading presets Interlignages prédéfinis + Tracking presets Approches prédéfinies diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1931aaa2b0..7077a33aa7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4366,3 +4366,6 @@ cameraRaw Yellow Sárga Tight Curl Szoros göndör Loose Curl Laza göndör Stylized dabs from a history state Stilizált pöttyök egy előzményállapotból + Font size presets Betűméret-előbeállítások + Leading presets Sorköz-előbeállítások + Tracking presets Betűköz-előbeállítások diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index eb890e9bce..046c1e3b6c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3473,3 +3473,6 @@ curves Smooth Haluskan Gamma Gamma Profile Profil Target Target + Font size presets Preset ukuran font + Leading presets Preset leading + Tracking presets Preset tracking diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 661192d7b6..622ce49888 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4568,3 +4568,6 @@ shape Appearance Aspetto Tight Curl Riccio stretto Loose Curl Riccio largo Stylized dabs from a history state Tocchi stilizzati da uno stato della storia + Font size presets Predefiniti dimensione font + Leading presets Predefiniti interlinea + Tracking presets Predefiniti spaziatura diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c5c0b02fc0..9823a7b81d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4130,3 +4130,6 @@ curves Smooth スムーズ Tight Curl タイトカール Loose Curl ルーズカール Stylized dabs from a history state 履歴状態から様式化したダブを描きます + Font size presets フォントサイズのプリセット + Leading presets 行送りのプリセット + Tracking presets トラッキングのプリセット diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2c730c1877..05ab475594 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3670,3 +3670,6 @@ curves Smooth 매끄럽게 Category 카테고리 Target 대상 Units 단위 + Font size presets 글꼴 크기 사전 설정 + Leading presets 행간 사전 설정 + Tracking presets 자간 사전 설정 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a8539cd159..783b11c2c2 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4211,3 +4211,6 @@ curves Smooth Vloeiend maken Tight Curl Strakke krul Loose Curl Losse krul Stylized dabs from a history state Gestileerde tikken uit een historiestatus + Font size presets Voorinstellingen lettergrootte + Leading presets Voorinstellingen interlinie + Tracking presets Voorinstellingen spatiëring diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6b2ad286a0..97ff292f1f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4071,3 +4071,6 @@ curves Smooth Wygładź # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Cel + Font size presets Ustawienia wstępne rozmiaru czcionki + Leading presets Ustawienia wstępne interlinii + Tracking presets Ustawienia wstępne światła diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 098ca1f8a6..4419d36362 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4381,3 +4381,6 @@ layerLabel No Color Sem cor Tight Curl Curva cerrada Loose Curl Curva solta Stylized dabs from a history state Toques estilizados a partir de um estado do histórico + Font size presets Predefinições de tamanho da fonte + Leading presets Predefinições de entrelinha + Tracking presets Predefinições de tracking diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d3e6033306..3758f226e6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4654,3 +4654,6 @@ shape Appearance Оформление Tight Curl Плотный завиток Loose Curl Свободный завиток Stylized dabs from a history state Стилизованные мазки из состояния истории + Font size presets Наборы размеров шрифта + Leading presets Наборы интерлиньяжа + Tracking presets Наборы трекинга diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 6a6dfb425f..7169441d64 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4524,3 +4524,6 @@ shape Appearance Izgled Tight Curl Usko uvijeno Loose Curl Labavo uvijeno Stylized dabs from a history state Stilizovane mrlje iz stanja istorije + Font size presets Unapred podešene veličine fonta + Leading presets Unapred podešeni proredi + Tracking presets Unapred podešeni razmaci slova diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d725b8c9ac..3a7236d22d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4180,3 +4180,6 @@ cameraData Lens Lens Tight Curl Sıkı Kıvrım Loose Curl Gevşek Kıvrım Stylized dabs from a history state Bir geçmiş durumundan stilize benekler + Font size presets Yazı tipi boyutu hazır ayarları + Leading presets Satır aralığı hazır ayarları + Tracking presets İzleme hazır ayarları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 777f03f60a..0acae08ad7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4164,3 +4164,6 @@ curves Smooth Згладити # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Target Ціль + Font size presets Набори розмірів шрифту + Leading presets Набори інтерліньяжу + Tracking presets Набори трекінгу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 397b02d38d..09019175b2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3949,3 +3949,6 @@ curves Smooth Làm mượt # Egui 0.37 migration controls (Aspect Ratio, Category, Color Table, Gamma, Interpolation, Profile, Target, Units, Demosaic) Aspect Ratio Tỷ lệ khung hình + Font size presets Cỡ chữ đặt sẵn + Leading presets Giãn dòng đặt sẵn + Tracking presets Khoảng cách chữ đặt sẵn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e6b9080ae6..587567eb0a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3134,3 +3134,6 @@ curves Smooth 平滑 Profile 配置文件 Target 目标 Units 单位 + Font size presets 字号预设 + Leading presets 行距预设 + Tracking presets 字距调整预设 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1586d47bf8..58d5a9ab92 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3090,3 +3090,6 @@ curves Smooth 平滑 Profile 描述檔 Target 目標 Units 單位 + Font size presets 字體大小預設 + Leading presets 行距預設 + Tracking presets 字距調整預設 diff --git a/crates/ui-egui/src/panels/props_layout/tests.rs b/crates/ui-egui/src/panels/props_layout/tests.rs index e5bb0a399d..88a61c518c 100644 --- a/crates/ui-egui/src/panels/props_layout/tests.rs +++ b/crates/ui-egui/src/panels/props_layout/tests.rs @@ -174,15 +174,14 @@ fn type_controls_fill_the_panel_at_every_width_and_scale() { .filter(|r| r.top() >= transform.bottom() && r.bottom() <= header.top()) .map(|r| r.right()) .fold(f32::MIN, f32::max); - // Preset-bearing fields reserve the right edge for their combo button. - // Verify the complete field (editable value plus preset) aligns with Transform. - let lead = ["Font size", "Leading (set to the font size × auto-leading when Auto)"] - .into_iter() - .map(|label| h.get_by_role_and_label(egui::accesskit::Role::SpinButton, label).rect().right()) - .fold(f32::MIN, f32::max); - let lead_combo = combos[3].right(); // Family, style, size presets, leading presets. - assert!(lead + 20.0 <= lead_combo, "{what}: the leading preset must not overlap its editable field"); - assert!((t_right - lead_combo).abs() <= 2.0, "{what}: Transform fields end at {t_right}, Character controls at {lead_combo}"); + // The size/leading row ends in the leading presets chevron at the panel's right edge, + // where Transform's field boxes end. The leading box ends where the chevron starts: + // its number stops one unit suffix ("pt", like Transform's "px") short of it. + let chevron = h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Leading presets").rect(); + let lead = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Leading (set to the font size × auto-leading when Auto)").rect(); + assert!((chevron.right() - header.right()).abs() < 0.5, "{what}: Character controls end at {}, panel {}", chevron.right(), header.right()); + let (t_suffix, lead_suffix) = (header.right() - t_right, chevron.left() - lead.right()); + assert!((t_suffix - lead_suffix).abs() < 0.5, "{what}: Transform's suffix slot {t_suffix}, the leading field's {lead_suffix} (overlap or gap)"); // Quick Actions buttons span the panel too. let qa = h.get_by_label("Rasterize Type").rect(); assert!(qa.right() >= header.right() - 2.0 && qa.right() <= header.right() + 1.0, "{what}: {qa:?}"); diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index f80008444c..5f00cf8069 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -127,6 +127,28 @@ mod panel_defaults { h } + /// Without a type target the preset chevrons set the next layer's defaults, with no + /// document edit. + #[test] + fn presets_without_a_type_layer_set_the_defaults() { + let app = new_app(); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = panels(app); + h.get_by_role_and_label(Role::ComboBox, "Font size presets").click(); + h.run(); + h.get_by_label("72 pt").scroll_to_me(); + h.run(); + h.get_by_label("72 pt").click(); + h.run(); + assert_eq!(h.state().ui.tool_options.type_size, 72.0); + h.get_by_role_and_label(Role::ComboBox, "Leading presets").click(); + h.run(); + h.get_by_label("Auto").click(); + h.run(); + assert_eq!(h.state().ui.tool_options.type_style_defaults.get("leading"), Some(&json!("auto"))); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "defaults are not a document edit"); + } + fn number(h: &mut Harness<'static, PhotocraftApp>, label: &str, value: &str) { h.get_by_role_and_label(Role::SpinButton, label).click(); h.run(); @@ -1960,6 +1982,36 @@ mod multi_layer_formatting { h.run(); } + /// Opens a preset chevron by its accessible name and picks `label`. + fn pick(h: &mut Harness<'static, PhotocraftApp>, menu: &str, label: &str) { + h.get_by_role_and_label(Role::ComboBox, menu).click(); + h.run(); + preset(h, label); + } + + /// The open preset popup's item labels, top to bottom, with "|" where a separator splits + /// them (a gap clearly larger than the row pitch). `any` is one item's label. + fn menu_items(h: &Harness<'static, PhotocraftApp>, any: &str) -> Vec { + use egui_kittest::kittest::NodeT; + let role = h.get_by_label(any).accesskit_node().role(); + let left = h.get_by_label(any).rect().left(); + let mut items: Vec<(f32, String)> = h + .query_all_by_role(role) + .filter(|n| (n.rect().left() - left).abs() < 1.0) + .filter_map(|n| Some((n.rect().top(), n.accesskit_node().label()?))) + .collect(); + items.sort_by(|a, b| a.0.total_cmp(&b.0)); + let pitch = items.windows(2).map(|w| w[1].0 - w[0].0).fold(f32::MAX, f32::min); + let mut out = Vec::new(); + for (i, (top, label)) in items.iter().enumerate() { + if i > 0 && top - items[i - 1].0 > pitch + 2.0 { + out.push("|".to_owned()); + } + out.push(label.clone()); + } + out + } + fn editing(app: &mut PhotocraftApp, id: LayerId) { app.ui.text_edit = Some(crate::state::TextEdit { layer: id.0, @@ -2031,33 +2083,53 @@ mod multi_layer_formatting { assert_eq!(text(h.state(), id).paragraph_runs()[0].style.direction, TextDirection::Rtl, "new type starts right to left"); } + /// The size, leading and tracking chevrons offer the reference application's lists: Leading + /// starts with Auto, Tracking splits tightening, 0 and loosening with separators. + #[test] + fn character_panel_preset_menus_list_the_reference_values() { + let (app, _) = fixture(); + let mut h = controls(app, true); + let sizes = [ + "6 pt", "8 pt", "9 pt", "10 pt", "11 pt", "12 pt", "14 pt", "16 pt", "18 pt", "24 pt", "30 pt", "36 pt", "48 pt", "60 pt", "72 pt", "150 pt", + "300 pt", + ]; + h.get_by_role_and_label(Role::ComboBox, "Font size presets").click(); + h.run(); + assert_eq!(menu_items(&h, "72 pt"), sizes); + h.key_press(egui::Key::Escape); + h.run(); + h.get_by_role_and_label(Role::ComboBox, "Leading presets").click(); + h.run(); + let leading: Vec<&str> = std::iter::once("Auto").chain(sizes).collect(); + assert_eq!(menu_items(&h, "72 pt"), leading); + h.key_press(egui::Key::Escape); + h.run(); + h.get_by_role_and_label(Role::ComboBox, "Tracking presets").click(); + h.run(); + let tracking = ["-100", "-75", "-50", "-25", "-10", "-5", "|", "0", "|", "5", "10", "25", "50", "75", "100", "200"]; + assert_eq!(menu_items(&h, "200"), tracking); + } + #[test] fn character_panel_preset_menus_edit_size_leading_and_tracking() { let (app, ids) = fixture(); let untouched = style(&app, ids[2], 0); + let steps = app.session.active().unwrap().history.entries().len(); let mut h = controls(app, true); - // The three chevrons are additional combo boxes after family and face. - // They use the same setStyle path as the adjacent editable fields. - h.get_all_by_role(Role::ComboBox).nth(2).expect("size presets").click(); - h.run(); - preset(&mut h, "72 pt"); - - h.get_all_by_role(Role::ComboBox).nth(3).expect("leading presets").click(); - h.run(); - preset(&mut h, "Auto"); - - h.get_all_by_role(Role::ComboBox).nth(5).expect("tracking presets").click(); - h.run(); - preset(&mut h, "50"); + // The chevrons use the same setStyle path as the editable fields beside them. + pick(&mut h, "Font size presets", "72 pt"); + pick(&mut h, "Leading presets", "Auto"); + pick(&mut h, "Tracking presets", "-5"); for id in &ids[..2] { let c = style(h.state(), *id, 0); assert_eq!(c.size_pt, 72.0); assert_eq!(c.leading_pt, None, "Auto restores font-relative line spacing"); - assert_eq!(c.tracking, 50.0); + assert_eq!(c.tracking, -5.0); } assert_eq!(style(h.state(), ids[2], 0), untouched, "unselected type layers are unchanged"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 3, "one step per pick"); // The numeric spin boxes must remain usable beside their preset chevrons. number(&mut h, "Font size", "40"); @@ -2065,6 +2137,43 @@ mod multi_layer_formatting { assert_eq!(style(h.state(), ids[1], 0).size_pt, 40.0); } + /// While typing, a preset changes only the selected characters, like a typed value. + #[test] + fn character_panel_presets_edit_only_the_selected_span() { + let (app, ids) = fixture(); + let mut h = controls(app, true); + let peer = text(h.state(), ids[1]).char_runs(); + editing(h.state_mut(), ids[0]); + h.run(); + pick(&mut h, "Font size presets", "150 pt"); + assert_eq!((size_at(h.state(), ids[0], 0), size_at(h.state(), ids[0], 1), size_at(h.state(), ids[0], 3)), (12.0, 150.0, 12.0)); + assert_eq!(text(h.state(), ids[1]).char_runs(), peer); + } + + /// Type units in millimetres: the lists show converted values with at most two decimals, + /// and a picked preset stores its exact point value (not 12.000001 from a unit round trip). + #[test] + fn character_panel_presets_in_millimetres_round_labels_and_store_exact_points() { + let mut app = new_app(); + app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "mm"})).unwrap(); + let id = LayerId(app.run("type.create", json!({"text": "AéBCD", "font": "Inter", "size": 30, "color": "#000000"})).unwrap()["layer"].as_u64().unwrap()); + selected(&mut app, &[id]); + let mut h = controls(app, true); + h.get_by_role_and_label(Role::ComboBox, "Font size presets").click(); + h.run(); + let items = menu_items(&h, "25.4 mm"); + assert_eq!(items.len(), 17, "{items:?}"); + for item in &items { + let n = item.strip_suffix(" mm").unwrap_or_else(|| panic!("{item}")); + assert!(n.split('.').nth(1).is_none_or(|d| d.len() <= 2 && !d.ends_with('0')), "{item}"); + } + assert_eq!(items[0], "2.12 mm", "6 pt"); + preset(&mut h, "4.23 mm"); + assert_eq!(style(h.state(), id, 0).size_pt, 12.0, "12 pt exactly"); + pick(&mut h, "Leading presets", "105.83 mm"); + assert_eq!(style(h.state(), id, 0).leading_pt, Some(300.0)); + } + #[test] fn options_font_family_preserves_peer_faces_and_batches_layer_flags() { let (app, ids) = fixture(); @@ -2206,14 +2315,10 @@ mod multi_layer_formatting { assert_eq!((c.size_pt, c.leading_pt, c.baseline_shift_pt), (30.0, Some(42.0), 5.0)); assert_eq!(text(h.state(), ids[0]).paragraph_runs()[0].style.start_indent_pt, 4.5); - h.get_all_by_role(Role::ComboBox).nth(2).expect("size presets").click(); - h.run(); - preset(&mut h, "144 px"); - h.get_all_by_role(Role::ComboBox).nth(3).expect("leading presets").click(); - h.run(); - preset(&mut h, "192 px"); + pick(&mut h, "Font size presets", "144 px"); + pick(&mut h, "Leading presets", "300 px"); let c = style(h.state(), ids[0], 0); - assert_eq!((c.size_pt, c.leading_pt), (72.0, Some(96.0)), "presets preserve point values in pixel display units"); + assert_eq!((c.size_pt, c.leading_pt), (72.0, Some(150.0)), "presets preserve point values in pixel display units"); } /// #5717: a layer scaled so its shown size or leading is past a field's range (2400 pt, or diff --git a/crates/ui-egui/src/tools/type_tool/panel.rs b/crates/ui-egui/src/tools/type_tool/panel.rs index 53e1ed31d1..2a36edc7c7 100644 --- a/crates/ui-egui/src/tools/type_tool/panel.rs +++ b/crates/ui-egui/src/tools/type_tool/panel.rs @@ -117,6 +117,84 @@ fn cell_width(avail: f32, n: usize) -> f32 { ((avail - (n - 1.0) * 2.0) / n).floor().max(20.0) } +/// The reference application's Character panel size list (points); Leading offers Auto, then +/// the same values. The reference app's options bar offers the same size list. +pub(crate) const SIZE_PRESETS: [f32; 17] = [6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0, 150.0, 300.0]; +/// Tracking presets (1/1000 em), in groups split by separators: tightening, none, loosening. +const TRACKING_PRESETS: [&[f32]; 3] = [&[-100.0, -75.0, -50.0, -25.0, -10.0, -5.0], &[0.0], &[5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 200.0]]; + +/// What a [`metric_field`] produced: a typed value in the display unit, a preset in the model's +/// unit (points; converting it through the display unit and back would store 12.000001), or Auto. +#[derive(Clone, Copy, Debug, PartialEq)] +enum MetricChoice { + Typed(f32), + Preset(f32), + Auto, +} + +/// A preset as the list shows it: the value in the display unit, at most two decimals. +fn preset_label(v: f32, unit: &str) -> String { + let n = format!("{v:.2}"); + let n = n.trim_end_matches('0').trim_end_matches('.'); + let n = if n == "-0" { "0" } else { n }; + if unit.is_empty() { n.to_owned() } else { format!("{n} {unit}") } +} + +/// A Character panel [`num_field`] with a preset chevron in the same cell, which still ends at +/// the column's right edge. The value stays editable: presets are shortcuts, not limits. +/// `presets` are groups of model values (split by separators), shown multiplied by `u`; `auto` +/// adds an Auto item first (`Some(true)` when Auto is current). +#[allow(clippy::too_many_arguments)] +fn metric_field( + ui: &mut egui::Ui, + (label, tip, menu): (&str, &str, &str), + value: f32, + range: std::ops::RangeInclusive, + (u, unit): (f32, &str), + width: f32, + presets: &[&[f32]], + auto: Option, +) -> Option { + let sp = ui.spacing().clone(); + let pad = sp.button_padding.x; + let combo_w = (sp.icon_spacing + sp.icon_width).max(16.0 - 2.0 * pad) + 2.0 * pad; + let mut chosen = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + if let Some(v) = num_field(ui, label, tip, value, range, unit, (width - combo_w).max(24.0)) { + chosen = Some(MetricChoice::Typed(v)); + } + let near = |p: f32| (p * u - value).abs() <= 1e-4 * value.abs().max(1.0); + let (press, close) = crate::press_menu::PressCombo::before(ui, menu); + let combo = + egui::ComboBox::from_id_salt(menu).selected_text("").width(combo_w).height(420.0).icon(crate::widgets::chevron_icon).close_behavior(close).show_ui( + ui, + |ui| { + if let Some(on) = auto { + let item = ui.selectable_label(on, tl!("Auto")); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Auto); + } + } + for (i, group) in presets.iter().enumerate() { + if i > 0 { + ui.separator(); + } + for &p in *group { + let item = ui.selectable_label(auto != Some(true) && near(p), preset_label(p * u, unit)); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Preset(p)); + } + } + } + }, + ); + press.after(&combo.response); + combo.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), tl!(menu))); + }); + chosen +} + /// Properties panel sections for a type layer: Character, Paragraph and Type Options (#155). pub fn type_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { type_sections(app, ui, true, true, false); @@ -175,13 +253,24 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa let k = shown_scale(app); // Hover tips stay English until wired through `tl!` in a multi-locale change // (`every_tl_literal_is_translated` requires every complete catalog). - if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k * u, 0.1 * u..=1296.0 * u, unit, w) { - app.ui.tool_options.type_size = v / u; - apply(app, ui.ctx(), json!({"size": v / u, "metricsAsShown": true})); + let size = + metric_field(ui, ("tT", "Font size", "Font size presets"), c.size_pt * k * u, 0.1 * u..=1296.0 * u, (u, unit), w, &[&SIZE_PRESETS], None); + if let Some(pt) = match size { + Some(MetricChoice::Typed(v)) => Some(v / u), + Some(MetricChoice::Preset(pt)) => Some(pt), + _ => None, + } { + app.ui.tool_options.type_size = pt; + apply(app, ui.ctx(), json!({"size": pt, "metricsAsShown": true})); } let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; - if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead * u, 0.1 * u..=5000.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})); + let tip = "Leading (set to the font size × auto-leading when Auto)"; + match metric_field(ui, ("A↕", tip, "Leading presets"), lead * u, 0.1 * u..=5000.0 * u, (u, unit), w, &[&SIZE_PRESETS], Some(c.leading_pt.is_none())) + { + Some(MetricChoice::Typed(v)) => apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})), + Some(MetricChoice::Preset(pt)) => apply(app, ui.ctx(), json!({"leading": pt, "metricsAsShown": true})), + Some(MetricChoice::Auto) => apply(app, ui.ctx(), json!({"leading": "auto"})), + None => {} } }); row(ui, &mut |ui| { @@ -193,7 +282,9 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa apply_kerning(app, ui.ctx(), v); } }); - if let Some(v) = num_field(ui, "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w) { + if let Some(MetricChoice::Typed(v) | MetricChoice::Preset(v)) = + metric_field(ui, ("VA", "Tracking (1/1000 em)", "Tracking presets"), c.tracking, -1000.0..=10000.0, (1.0, ""), w, &TRACKING_PRESETS, None) + { apply(app, ui.ctx(), json!({"tracking": v})); } }); From 39835939168c9635baf9a8bd62d5156d274659c4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 15:53:57 +0100 Subject: [PATCH 74/87] Integration: re-export active_type_path from vector_ui after main's tools/ move (#9321) #9321's Direct Selection change calls crate::vector_ui::active_type_path, which main's layout refactor (#9758) made a private path_ops item, so ui-egui did not build after the batch's main merge. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/vector_ui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 60ee51c676..bd501f24de 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -37,7 +37,7 @@ use overlay::{MAX_CURVE_PIECES, bezier}; pub(crate) use overlay::{curve_points, path_lines, selected_saved_path, shows_anchors}; pub(crate) use overlay::{draw_anchor, draw_handle, draw_outline}; pub use path_ops::{active_path_name, path_selection_finish, path_to_selection, pick_shape_at, selected_document_path, takes_path_mask, with_active_path}; -pub(crate) use path_ops::{active_shape_path, delete_key_deletes_work_path, free_transform_path, targeted_vector_mask}; +pub(crate) use path_ops::{active_shape_path, active_type_path, delete_key_deletes_work_path, free_transform_path, targeted_vector_mask}; #[cfg(test)] use paths_panel::path_context_actions; pub use paths_panel::{PathEntry, PathRow, path_rows, paths_footer, paths_panel}; From bb880983437582a0c5b14a9ca381507664599bdd Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 15:29:11 +0100 Subject: [PATCH 75/87] Integration: new layers go into locked open groups; Stamp Visible above an open group (#4329) A new layer with an open group active went above the group whenever the group had any lock (all, pixels, transparency or position). The reference application puts it inside, on top of the group's layers, even when the group is locked with Lock All. Locks no longer keep New Layer, New Group, adjustment and fill layers out. Layers that are edited right after they are made (Type, Shape, Place's transform box, Paste, the Gradient tool's live gradient, video layers, Render, Vanishing Point, a new frame) take Place::AutoEditable and keep the PR's rule: they go above a locked group, as before. Stamp Visible with an open group active put the stamp inside the group, where the group's opacity, mode or mask applied to the composite a second time. The reference application puts it directly above the group; with a layer inside the group active it still lands above that layer, inside the group. Co-authored-by: SckraT <70698629+SckraT@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/edit_cmds.rs | 4 +- crates/engine/src/cmd/file_cmds/open.rs | 2 +- crates/engine/src/cmd/frame_cmds.rs | 2 +- crates/engine/src/cmd/gradient_fill_cmds.rs | 2 +- crates/engine/src/cmd/layer_copy_cmds.rs | 2 +- crates/engine/src/cmd/render_cmds.rs | 2 +- crates/engine/src/cmd/stamp_cmds.rs | 2 +- crates/engine/src/cmd/type_cmds.rs | 2 +- crates/engine/src/cmd/vector_cmds/shape.rs | 2 +- crates/engine/src/cmd/video_cmds.rs | 6 +- crates/engine/src/cmd/vp_cmds.rs | 2 +- crates/engine/src/layer_place.rs | 24 ++++-- crates/engine/src/layer_place_tests.rs | 87 +++++++++++++++++---- crates/ui-egui/src/tools/gradient_ui.rs | 2 +- 14 files changed, 104 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs index 2b733e7d95..d8839950f4 100644 --- a/crates/engine/src/cmd/edit_cmds.rs +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -403,7 +403,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { let id = s.edit("Paste", |doc, active| { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = surf; - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); doc.selection = None; Ok(id) @@ -446,7 +446,7 @@ fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result< doc.patterns.extend(patterns); doc.metadata.psd_global_blocks.extend(linked); // The first pasted layer goes where a new layer would; the rest stack above it. - let mut place = crate::layer_place::Place::Auto; + let mut place = crate::layer_place::Place::AutoEditable; for l in copies.layers { *active = Some(crate::layer_place::insert_new(doc, *active, l, place)); place = crate::layer_place::Place::Above; diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 09797498ca..ff73c338e5 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -202,7 +202,7 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option Result { crate::layer_multi_cmds::check_group_depth(doc, "New Frame")?; gid } - None => crate::layer_place::insert_new(doc, *active, Layer::group(name, vec![]), crate::layer_place::Place::Auto), + None => crate::layer_place::insert_new(doc, *active, Layer::group(name, vec![]), crate::layer_place::Place::AutoEditable), }; let frame = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; frame.mask = Some(mask); diff --git a/crates/engine/src/cmd/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs index f9a8d3bfbc..41f91f8bbb 100644 --- a/crates/engine/src/cmd/gradient_fill_cmds.rs +++ b/crates/engine/src/cmd/gradient_fill_cmds.rs @@ -322,7 +322,7 @@ fn create(s: &mut Session, p: &Value) -> Result { new_layer(s, &d.doc, p)? }; let id = s.edit("New Gradient Fill Layer", |doc, active| { - let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs index 3606123e23..85eea94ad3 100644 --- a/crates/engine/src/cmd/layer_copy_cmds.rs +++ b/crates/engine/src/cmd/layer_copy_cmds.rs @@ -217,7 +217,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result { let mut above = *active; let mut new = Vec::with_capacity(copies.layers.len()); // The first copy goes where a new layer would; the rest stack above it. - let mut place = crate::layer_place::Place::Auto; + let mut place = crate::layer_place::Place::AutoEditable; for l in copies.layers { let id = crate::layer_place::insert_new(doc, above, l, place); place = crate::layer_place::Place::Above; diff --git a/crates/engine/src/cmd/render_cmds.rs b/crates/engine/src/cmd/render_cmds.rs index e45e567f46..cc27304fdc 100644 --- a/crates/engine/src/cmd/render_cmds.rs +++ b/crates/engine/src/cmd/render_cmds.rs @@ -109,7 +109,7 @@ fn draw(s: &mut Session, label: &str, p: &Value, prims: Vec, extra: Value) let raster = id.and_then(|i| doc.layer(i)).is_some_and(|l| matches!(l.content, LayerContent::Raster(_))); let (id, created) = if want_new || !raster { let l = Layer::new(label.trim_end_matches('…'), LayerContent::Raster(Surface::new(doc.pixel_format()))); - let nid = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + let nid = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(nid); (nid, true) } else { diff --git a/crates/engine/src/cmd/stamp_cmds.rs b/crates/engine/src/cmd/stamp_cmds.rs index 9c2551febd..b5c6a21120 100644 --- a/crates/engine/src/cmd/stamp_cmds.rs +++ b/crates/engine/src/cmd/stamp_cmds.rs @@ -74,7 +74,7 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result { return Ok(empty); } let layer = stamp_layer(doc, doc.next_layer_name("Layer"))?; - let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Above); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index 69503b4789..af90faf5fa 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -906,7 +906,7 @@ pub fn specs() -> Vec { let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| layer_name(&t.text)); let id = s.edit("New Type Layer", |doc, active| { refresh(doc, &mut t); - let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index a6f74c9fd6..cdd4885ae0 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -338,7 +338,7 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { let id = s.edit("New Shape Layer", |doc, active| { refresh_shape(doc, &mut sh); let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind))); - let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Shape(sh)), crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Shape(sh)), crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) })?; diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 9dd991f18a..4eee4ae799 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -127,7 +127,7 @@ fn new_blank(s: &mut Session, _p: &Value) -> Result { let name = doc.next_layer_name("Video Layer"); let mut l = Layer::raster(name, fmt); l.video = Some(VideoData::new(frames, fps)); - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); sync(doc); Ok(id) @@ -367,7 +367,7 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result { v.original_frames = Some(v.frames.clone()); v.source = photocraft_doc::VideoSource::File { path: path.clone() }; l.video = Some(v); - let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); sync(doc); Ok(id) @@ -438,7 +438,7 @@ fn frames_to_layers(s: &mut Session, p: &Value) -> Result { let n = frames.len(); s.edit("Video Frames to Layers", |doc, active| { let mut above = *active; - let mut place = crate::layer_place::Place::Auto; + let mut place = crate::layer_place::Place::AutoEditable; for (i, f) in frames.into_iter().enumerate() { let mut l = Layer::raster(format!("Frame {}", i + 1), fmt); if let LayerContent::Raster(surf) = &mut l.content { diff --git a/crates/engine/src/cmd/vp_cmds.rs b/crates/engine/src/cmd/vp_cmds.rs index 9bf2cdfc38..1a3ac8e0ca 100644 --- a/crates/engine/src/cmd/vp_cmds.rs +++ b/crates/engine/src/cmd/vp_cmds.rs @@ -252,7 +252,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { let on = layer.or(*active); let id = if new_layer { let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format()); - let nid = crate::layer_place::insert_new(doc, on, l, crate::layer_place::Place::Auto); + let nid = crate::layer_place::insert_new(doc, on, l, crate::layer_place::Place::AutoEditable); *active = Some(nid); nid } else { diff --git a/crates/engine/src/layer_place.rs b/crates/engine/src/layer_place.rs index 9b5b5cda17..3cb9c1e854 100644 --- a/crates/engine/src/layer_place.rs +++ b/crates/engine/src/layer_place.rs @@ -9,9 +9,15 @@ use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerPath, MAX_GROU #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Place { - /// New Layer, New Group, new adjustment, fill, type and shape layers, Paste…: inside the anchor - /// when it is an open, unlocked group (or an artboard the content is on), else directly above it. + /// New Layer, New Group, new adjustment and fill layers: inside the anchor when it is an open + /// group (or an artboard the content is on), else directly above it. A locked group takes the + /// layer too, as in Photoshop (checked with Lock All): the layer is locked through it. Auto, + /// [`Place::Auto`] for a layer that is edited right after it is made (Type, Shape, Place's + /// transform box, Paste, the Gradient tool's live gradient, video layers, Render and Vanishing + /// Point drawing, a new frame): never inside a group with a lock of its own (all, pixels, + /// transparency or position) that would refuse that edit; the layer goes above the group. + AutoEditable, /// Directly above the anchor, never inside it: a layer made from another layer, or the second /// and later of several new layers. Above, @@ -28,8 +34,12 @@ pub fn insertion_point(doc: &Document, anchor: Option, layer: &Layer, p // An artboard stays at the top level: beside the anchor's top-level layer. let path = if layer.artboard().is_some() { path.get(..1).map(<[usize]>::to_vec).unwrap_or_default() } else { path }; let (Some((&k, parent)), Some(target)) = (path.split_last(), doc.layer_at(&path)) else { return root_top }; + let locks = &target.locks; + let editable = !(locks.all || locks.pixels || locks.transparency || locks.position); match place { - Place::Auto if takes_new_layers(target, path.len(), layer) => (path.clone(), target.children().map_or(0, <[Layer]>::len)), + Place::Auto | Place::AutoEditable if takes_new_layers(target, path.len(), layer) && (place == Place::Auto || editable) => { + (path.clone(), target.children().map_or(0, <[Layer]>::len)) + } Place::Below if crate::background_cmds::background_id(doc) != Some(target.id) => (parent.to_vec(), k), _ => (parent.to_vec(), k + 1), } @@ -65,14 +75,12 @@ pub fn insert_new(doc: &mut Document, anchor: Option, mut layer: Layer, } /// Does the group `target` at depth `depth` (its path length) take a new `layer` as its top -/// child? An open group or an artboard does, unless it is locked (the layer would be born locked: -/// no painting, rendering or moving it) or nesting would pass [`MAX_GROUP_DEPTH`]. An artboard +/// child? An open group or an artboard does, locked or not (Photoshop puts a new layer inside a +/// group locked with Lock All), unless nesting would pass [`MAX_GROUP_DEPTH`]. An artboard /// takes a layer with content only when that content is centred on the board, as callers place /// it for the canvas (Place, Paste, a Type or Shape click): elsewhere the board would clip it. fn takes_new_layers(target: &Layer, depth: usize, layer: &Layer) -> bool { let LayerContent::Group(g) = &target.content else { return false }; - let k = &target.locks; - let locked = k.all || k.pixels || k.transparency || k.position; let on_board = |rect: photocraft_geom::Rect| { crate::layer_multi_cmds::layer_bounds(layer).is_none_or(|b| { let (cx, cy) = (b.x0 / 2 + b.x1 / 2, b.y0 / 2 + b.y1 / 2); @@ -83,7 +91,7 @@ fn takes_new_layers(target: &Layer, depth: usize, layer: &Layer) -> bool { Some(board) => on_board(board.rect), None => g.expanded, }; - open && !locked && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH + open && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH } /// Group nesting inside `layer` itself: 0 for a layer or an empty group, as diff --git a/crates/engine/src/layer_place_tests.rs b/crates/engine/src/layer_place_tests.rs index 1be02455bb..5a84035426 100644 --- a/crates/engine/src/layer_place_tests.rs +++ b/crates/engine/src/layer_place_tests.rs @@ -71,21 +71,22 @@ fn a_new_layer_goes_inside_an_open_active_group_and_above_a_closed_one() { } #[test] -fn artboards_take_new_layers_and_locked_groups_do_not() { +fn artboards_and_locked_groups_take_new_layers() { let (mut s, _, b) = session(); let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 16, 16]})).unwrap()); set_expanded(&mut s, board, false); select(&mut s, board); let l = id(s.execute("layer.new.layer", json!({})).unwrap()); assert_eq!(doc(&s).artboard_of(l), Some(board), "an artboard takes the layer even when closed"); - // A fully locked group would lock the new layer: it goes above instead. + // Photoshop puts a new layer inside an open group locked with Lock All too; the layer is + // locked through the group. select(&mut s, b); let g = id(s.execute("layer.new.group", json!({})).unwrap()); s.execute("layer.setProps", json!({"layer": g.0, "locks": {"all": true}})).unwrap(); select(&mut s, g); - let above = id(s.execute("layer.new.layer", json!({})).unwrap()); - assert!(children(&s, g).is_empty()); - assert!(doc(&s).layers.iter().any(|l| l.id == above)); + let inside = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![inside]); + assert!(doc(&s).effective_locks(inside).all); } #[test] @@ -218,21 +219,79 @@ fn a_missing_or_stale_anchor_means_the_top_of_the_stack() { assert!(matches!(d.layers.last().unwrap().content, LayerContent::Raster(_))); } -/// A partly locked group (pixels, transparency or position) would lock a layer created in it, so -/// Render and Vanishing Point could not draw into their new layer: it goes above the group. +/// Any lock on an open group still lets New Layer, New Group and new adjustment and fill layers in, +/// as in Photoshop (checked with Lock All). A layer that is edited right after it is made (Type, +/// Shape, Paste, Render…) goes above a group whose lock would refuse that edit, +/// so it never comes out locked. #[test] -fn a_partly_locked_group_keeps_new_layers_out() { - for locks in [json!({"pixels": true}), json!({"transparency": true}), json!({"position": true})] { +fn locked_groups_take_new_layers_but_not_the_ones_edited_at_once() { + for locks in [json!({"all": true}), json!({"pixels": true}), json!({"transparency": true}), json!({"position": true})] { let (mut s, _, b) = session(); select(&mut s, b); + s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); let g = id(s.execute("layer.new.group", json!({})).unwrap()); s.execute("layer.setProps", json!({"layer": g.0, "locks": locks})).unwrap(); - select(&mut s, g); - s.execute("filter.render.tree", json!({})).unwrap(); - let l = id(s.execute("layer.new.layer", json!({})).unwrap()); - assert!(children(&s, g).is_empty(), "{locks}"); - assert!(top(&s).contains(&l)); + for (cmd, p) in [ + ("layer.new.layer", json!({})), + ("layer.new.group", json!({})), + ("layer.newAdjustmentLayer.invert", json!({})), + ("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})), + ] { + select(&mut s, g); + let l = id(s.execute(cmd, p).unwrap()); + assert_eq!(children(&s, g).last(), Some(&l), "{cmd} goes inside the group locked with {locks}"); + } + for (cmd, p) in [ + ("type.create", json!({"x": 2, "y": 10, "text": "Hi"})), + ("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5]})), + ("edit.paste", json!({})), + ("filter.render.tree", json!({})), + ("gradient.fill.create", json!({"from": [0, 0], "to": [16, 16]})), + ] { + select(&mut s, g); + let l = id(s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd} with {locks}: {e}"))); + assert!(!children(&s, g).contains(&l), "{cmd} stays out of the group locked with {locks}"); + assert_eq!(top(&s).iter().position(|x| *x == l), top(&s).iter().position(|x| *x == g).map(|i| i + 1), "{cmd} directly above the group"); + assert!(!doc(&s).effective_locks(l).any(), "{cmd}: the new layer is not locked"); + if cmd == "filter.render.tree" { + assert!(doc(&s).layer(l).unwrap().surface().unwrap().tile_count() > 0, "Render drew the tree with {locks}"); + } + } } + // An open group inside a locked one still takes New Layer (the lock reaches it through the outer group). + let (mut s, _, b) = session(); + select(&mut s, b); + let outer = id(s.execute("layer.new.group", json!({})).unwrap()); + let inner = id(s.execute("layer.new.group", json!({})).unwrap()); + assert_eq!(children(&s, outer), vec![inner]); + s.execute("layer.setProps", json!({"layer": outer.0, "locks": {"pixels": true}})).unwrap(); + select(&mut s, inner); + let plain = id(s.execute("layer.new.layer", json!({})).unwrap()); + assert_eq!(children(&s, inner), vec![plain]); +} + +/// Stamp Visible goes directly above an open active group, never inside it: the stamp is the +/// composite already, and inside it the group's opacity, mode or mask would apply to it again. +/// With a layer inside a group active, it still lands above that layer, inside the group. +#[test] +fn stamp_visible_goes_above_an_open_group() { + let (mut s, a, b) = session(); + select(&mut s, a); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let g = id(s.execute("layer.groupLayers", json!({})).unwrap()); + set_expanded(&mut s, g, true); + s.execute("layer.setProps", json!({"layer": g.0, "opacity": 0.5})).unwrap(); + select(&mut s, g); + let stamp = id(s.execute("layer.stampVisible", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![a], "the stamp stays out of the group"); + assert_eq!(top(&s)[1..], [g, stamp, b]); + // A layer inside the group active: the stamp goes above it, inside the group. + select(&mut s, a); + let inside = id(s.execute("layer.stampVisible", json!({})).unwrap()); + assert_eq!(children(&s, g), vec![a, inside]); } /// An artboard takes a new layer whose content is centred on it, and a new empty layer; content diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index 4ff1e8fdfe..4ea5da8a72 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -396,7 +396,7 @@ pub fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc l.id = PREVIEW_LAYER; // Where the committed layer will go, so the preview doesn't jump on release. let active = app.session.active().and_then(|s| s.active_layer); - photocraft_engine::layer_place::insert_new(&mut shown, active, l, photocraft_engine::layer_place::Place::Auto); + photocraft_engine::layer_place::insert_new(&mut shown, active, l, photocraft_engine::layer_place::Place::AutoEditable); } else { let l = doc.layer(layer)?; let f = edited_fill(app, l, doc.bounds(), cmd, &p)?; From 4a6c0d82d703d4eba63fd2f408fa13ef0cc5ee3d Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 16:43:34 +0100 Subject: [PATCH 76/87] Integration: rustfmt the Character panel's preset menu after main's craft_ui::ComboBox switch (#3558) Main's #9849 bans egui::ComboBox; the preset menu #3558 added now uses craft_ui::ComboBox, three characters past rustfmt's 160-column limit. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/tools/type_tool/panel.rs | 42 +++++++++++---------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/panel.rs b/crates/ui-egui/src/tools/type_tool/panel.rs index 4388096863..7211b17f3d 100644 --- a/crates/ui-egui/src/tools/type_tool/panel.rs +++ b/crates/ui-egui/src/tools/type_tool/panel.rs @@ -166,29 +166,31 @@ fn metric_field( } let near = |p: f32| (p * u - value).abs() <= 1e-4 * value.abs().max(1.0); let (press, close) = crate::press_menu::PressCombo::before(ui, menu); - let combo = - craft_ui::ComboBox::from_id_salt(menu).selected_text("").width(combo_w).height(420.0).icon(crate::widgets::chevron_icon).close_behavior(close).show_ui( - ui, - |ui| { - if let Some(on) = auto { - let item = ui.selectable_label(on, tl!("Auto")); + let combo = craft_ui::ComboBox::from_id_salt(menu) + .selected_text("") + .width(combo_w) + .height(420.0) + .icon(crate::widgets::chevron_icon) + .close_behavior(close) + .show_ui(ui, |ui| { + if let Some(on) = auto { + let item = ui.selectable_label(on, tl!("Auto")); + if press.chosen(ui, &item) { + chosen = Some(MetricChoice::Auto); + } + } + for (i, group) in presets.iter().enumerate() { + if i > 0 { + ui.separator(); + } + for &p in *group { + let item = ui.selectable_label(auto != Some(true) && near(p), preset_label(p * u, unit)); if press.chosen(ui, &item) { - chosen = Some(MetricChoice::Auto); + chosen = Some(MetricChoice::Preset(p)); } } - for (i, group) in presets.iter().enumerate() { - if i > 0 { - ui.separator(); - } - for &p in *group { - let item = ui.selectable_label(auto != Some(true) && near(p), preset_label(p * u, unit)); - if press.chosen(ui, &item) { - chosen = Some(MetricChoice::Preset(p)); - } - } - } - }, - ); + } + }); press.after(&combo.response); combo.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), tl!(menu))); }); From 88c19a59d4be18b6cb79960e9a7339a494a17f4a Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 17:22:37 +0100 Subject: [PATCH 77/87] Integration: the font menu shrinks to a search with no matches, as on main (#6526) Main's #9849 lets dropdowns grow back after a short list, and its test `clearing_a_query_that_matches_nothing_grows_the_menu_back` expects a search with no matches to shrink the font menu. #6526's menu stayed at its full 534 px: its font list never shrank (auto_shrink y off), and the vertical separator between the class list and the font list took the row's whole available height. The list now shrinks, and the line is drawn over the laid-out row instead, so the menu ends with the class list. The test now checks that the menu ends with the class list (it can't drop below half with the class list beside the list), and a new test pins that the wheel past the end of the list, or over the class list, never moves the header, also in a window too short for the full menu. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/tools/type_tool/font_picker_tests.rs | 42 +++++++++++++++++-- crates/ui-egui/src/tools/type_tool/fonts.rs | 16 +++++-- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs index c04896c67f..7d24fbef42 100644 --- a/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs @@ -33,11 +33,15 @@ fn harness_with(preview: FontPreview) -> Harness<'static, State> { } fn harness_with_recents(preview: FontPreview, recents: Vec) -> Harness<'static, State> { + harness_sized(preview, recents, vec2(600.0, 900.0)) +} + +fn harness_sized(preview: FontPreview, recents: Vec, size: egui::Vec2) -> Harness<'static, State> { // Enough families that the unfiltered menu hits its maximum height and scrolls. let mut families: Vec = (0..60).map(|i| format!("Family {i:02}")).collect(); families.push("Zeta Sans".into()); let state = State { current: "Family 00".into(), families, button: egui::Id::NULL, popup: egui::Id::NULL, preview, recents }; - let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).with_max_steps(SETTLE_STEPS).build_ui_state( + let mut h = Harness::builder().with_size(size).with_max_steps(SETTLE_STEPS).build_ui_state( |ui, s: &mut State| { s.button = ui.make_persistent_id(egui::IdSalt::new("type-font")); s.popup = s.button.with("popup"); @@ -157,6 +161,33 @@ fn the_search_field_stays_put_while_the_list_scrolls() { assert!(popup.contains(after.center()), "the search field left the menu"); } +/// The wheel past the end of the list, or over the class list, leaves the preview, filters and +/// search field in place, also in a window too short for the menu's full height: the lists stay +/// within the room the menu leaves them, so the menu itself has nothing to scroll. +#[test] +fn the_wheel_past_the_end_of_the_list_leaves_the_header_in_place() { + // Over the font list, and over the class list beside it, which has no scroll area of its own. + for (size, over) in + [(vec2(600.0, 900.0), "Family 02"), (vec2(600.0, 900.0), "All Classes"), (vec2(600.0, 420.0), "Family 02"), (vec2(600.0, 420.0), "All Classes")] + { + let mut h = harness_sized(FontPreview::Medium, Vec::new(), size); + open(&mut h); + let search = h.get_by_role(Role::TextInput).rect(); + h.hover_at(h.get_by_label(over).rect().center()); + for _ in 0..40 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -10.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run(); + } + assert_eq!(search, h.get_by_role(Role::TextInput).rect(), "{size:?} over {over}: the search field moved under the wheel"); + } +} + /// #7792: the arrow keys scroll the list to the selected family without moving the search /// field: they scroll the list, not the whole menu. #[test] @@ -175,8 +206,9 @@ fn the_search_field_stays_put_while_the_arrows_scroll_the_list() { assert_eq!(search, h.get_by_role(Role::TextInput).rect(), "the search field scrolled away with the list"); } -/// A query matching no family shrinks the menu; clearing it grows the menu back to its full -/// height (egui#5225), and the search field stays where it was throughout. +/// A query matching no family shrinks the menu to its header and the class list beside the +/// list; clearing it grows the menu back to its full height (egui#5225), and the search field +/// stays where it was throughout. #[test] fn clearing_a_query_that_matches_nothing_grows_the_menu_back() { let mut h = harness(); @@ -187,7 +219,9 @@ fn clearing_a_query_that_matches_nothing_grows_the_menu_back() { h.run(); assert!(h.query_by_label("Family 00").is_none(), "the query matches no family"); let none = popup_rect(&h).expect("still open").height(); - assert!(none < full / 2.0, "no matches shrink the menu: {none} vs {full}"); + let classes = h.get_by_label("Decorative").rect(); + let menu = popup_rect(&h).expect("still open"); + assert!(none < full - 100.0 && menu.bottom() < classes.bottom() + 20.0, "no matches shrink the menu to the class list: {menu:?}, {classes:?}, full {full}"); assert_eq!(search, h.get_by_role(Role::TextInput).rect(), "the search field moved when the list emptied"); for _ in 0.."xxxx".len() { h.key_press(Key::Backspace); diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index 4bad33b1b3..e91b06f5d3 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -550,14 +550,19 @@ pub(crate) fn family_picker_in( let reveal = if stepped.is_some() { None } else { reveal }; let mut reveal_top: Option = None; ui.separator(); + // The line between the class list and the font list. A separator in the row would take + // the row's whole available height and hold the menu at its full height under a short + // search result, so the row keeps its room and the line is drawn once the row is laid out. + let mut divider: Option = None; let body = ui.horizontal_top(|ui| { if !filters.hide_classes { crate::font_filters::class_list(ui, &mut filters); - ui.separator(); + divider = Some(ui.cursor().min.x + 3.0); + ui.add_space(6.0 + ui.spacing().item_spacing.x); } - // The list scrolls under the fixed search field and filters, and keeps one height - // whatever it holds (egui never grows a popup back after a short list, #1369). - let list = egui::ScrollArea::vertical().id_salt(search_id.with("list")).max_height(FONT_LIST_HEIGHT).auto_shrink([true, false]); + // The list scrolls under the fixed search field and filters, and shrinks to a short + // search result: the menu grows back with it (craft_ui::ComboBox, #9849). + let list = egui::ScrollArea::vertical().id_salt(search_id.with("list")).max_height(FONT_LIST_HEIGHT).auto_shrink([true, true]); // Top to bottom, though the list sits beside the class list. let shown = list.show(ui, |ui| { ui.vertical(|ui| { @@ -700,6 +705,9 @@ pub(crate) fn family_picker_in( ui.data_mut(|d| d.insert_temp(list_left_id, shown.inner_rect.left() - origin)); shown.inner_rect.right() }); + if let Some(x) = divider { + ui.painter().vline(x, body.response.rect.y_range(), ui.visuals().widgets.noninteractive.bg_stroke); + } // The lists' own extent, from the class list to the font list's scroll bar: the row // itself stretches with the popup, so it can't tell when the popup is too wide. let list_right = body.inner + FONT_SCROLL_BAR_WIDTH; From 425b5efeedcad19b868d00ee7f476e4077aed8b2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 18:18:48 +0100 Subject: [PATCH 78/87] Integration: a painted fill reserves its buffers before it builds them (#3779) CodeRabbit on #9775: paint.stroke with fill:true builds the coverage, its feathered copy, the selection read and the mask over the region, up to the whole canvas (file.new allows 300000 x 300000), with infallible allocations that abort the process when memory runs out. The peak is now reserved through the fallible allocator first, and the selection is read through it; fill_survives_allocation_failure fails without this (the error came from a later blend). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/brush_cmds.rs | 9 +++++++-- crates/engine/src/cmd/brush_cmds/tests.rs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 05b2911831..05af865ddc 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -484,14 +484,19 @@ fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pt return Ok(Rect::new(0, 0, 0, 0)); } let (w, h) = (bounds.width() as usize, bounds.height() as usize); + // The coverage, its feathered copy (and the blur's scratch), the selection read and + // the mask are each a buffer over the whole region, which can be the whole canvas: + // reserve that peak first, so a region too big for memory is an error, not an abort. + const FILL: &str = "filling a painted region"; + let peak = w.checked_mul(h).and_then(|n| n.checked_mul(5)).ok_or_else(|| crate::allocation::error(FILL, "requested size overflowed"))?; + drop(crate::allocation::capacity::(peak, FILL)?); let xy: Vec<(f32, f32)> = pts.iter().map(|sp| (sp.x as f32, sp.y as f32)).collect(); let mut cov = photocraft_algo::selection::polygon(&xy, bounds, true); if feather_px > 0.01 { cov = photocraft_algo::selection::feather(&cov, w, h, feather_px); } if let Some(sel) = sel.as_ref() { - let mut sv = Vec::new(); - sel.read_region_into(bounds, &mut sv); + let sv = crate::allocation::read_region(sel, bounds, FILL)?; for (c, s) in cov.iter_mut().zip(&sv) { *c *= s.clamp(0.0, 1.0); } diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 32b8efa708..3a3041c4a6 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -580,6 +580,23 @@ fn define_brush_from_selection() { assert!(rgba(&s, 30, 32)[3] > 0.9); } +#[test] +fn fill_survives_allocation_failure() { + // CodeRabbit on #9775: a fill's buffers span the region, up to the whole canvas. Their peak is + // reserved through the fallible allocator before any of them is built, so running out of + // memory is the fill's own error, leaving the pixels and history alone, never an abort. + let mut s = session(60, 60); + let pixels_before = surface(&s); + let history_before = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "color": "#ff0000"})); + let _ = crate::allocation::capacity::(0, "reset failpoint"); + let err = result.expect_err("an allocation failure must be reported, not panic").to_string(); + assert!(err.contains("filling a painted region"), "the fill reserves its buffers first: {err}"); + assert_eq!(surface(&s), pixels_before, "no pixels changed"); + assert_eq!(s.active().unwrap().history.past_len(), history_before, "no history step was recorded"); +} + #[test] fn define_brush_from_selection_survives_allocation_failure() { // The sampled tip is one f32 buffer over the whole selection, and the selection mask is a From 3b964c0cdf9d0273d7feacd601bea28e506b60f6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 18:18:48 +0100 Subject: [PATCH 79/87] Integration: video footage off the active artboard stays out of it; one depth check for copied layers (#4329) CodeRabbit on #9775: newVideoLayerFromFile placed the layer while its content was still empty, so an active artboard always took it and clipped footage centred elsewhere; the first frame is now the content before placement, as in frames_to_layers (footage_off_the_active_artboard_stays_out_of_it fails without it). The merge also left a second check_group_depth ("Duplicate Layers") before main's "Copy Layers" one in layer.copyToDocument, so main's message could never show; it is removed. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/layer_copy_cmds.rs | 1 - crates/engine/src/cmd/video_cmds.rs | 5 +++++ crates/engine/src/cmd/video_cmds/tests.rs | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs index 85eea94ad3..631cceac65 100644 --- a/crates/engine/src/cmd/layer_copy_cmds.rs +++ b/crates/engine/src/cmd/layer_copy_cmds.rs @@ -224,7 +224,6 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result { above = Some(id); new.push(id); } - crate::layer_multi_cmds::check_group_depth(doc, "Duplicate Layers")?; *active = above; // Copied groups keep their own depth: repeated copies would otherwise nest without end. crate::layer_multi_cmds::check_group_depth(doc, "Copy Layers")?; diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 4eee4ae799..3aec55b837 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -366,6 +366,11 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result { let mut v = VideoData::new(frames, fps); v.original_frames = Some(v.frames.clone()); v.source = photocraft_doc::VideoSource::File { path: path.clone() }; + // The first frame is the layer's content before it is placed: an active artboard takes + // the layer only when its content is on the board, as `frames_to_layers` does. + if let (Some(first), LayerContent::Raster(surf)) = (v.frames.first(), &mut l.content) { + *surf = first.clone(); + } l.video = Some(v); let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable); *active = Some(id); diff --git a/crates/engine/src/cmd/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs index 3560c5f2c3..7e8c05a9b4 100644 --- a/crates/engine/src/cmd/video_cmds/tests.rs +++ b/crates/engine/src/cmd/video_cmds/tests.rs @@ -83,6 +83,21 @@ fn new_video_layer_from_image_sequence() { assert!(s.active().unwrap().doc.timeline.as_ref().unwrap().duration >= 3); } +/// CodeRabbit on #9775: footage that isn't on the active artboard stays out of it, as a placed +/// image does; the board would clip it. Before, the layer was placed while still empty. +#[test] +fn footage_off_the_active_artboard_stays_out_of_it() { + let dir = tmpdir("board"); + write_png(&format!("{dir}/f01.png"), 16, 12, "#ff0000"); + write_png(&format!("{dir}/f02.png"), 16, 12, "#00ff00"); + let mut s = session(); + let board = s.execute("layer.new.artboard", json!({"rect": [0, 0, 4, 4]})).unwrap(); + assert!(board["layer"].as_u64().is_some(), "{board}"); + let r = s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": dir})).unwrap(); + let id = LayerId(r["layer"].as_u64().unwrap()); + assert_eq!(s.active().unwrap().doc.artboard_of(id), None, "the footage is centred off the board"); +} + #[test] fn frames_to_layers_and_render_video() { let dir = tmpdir("ftl"); From 11528118e79e61fbe0f689af5b40adc00b06d0bd Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 18:18:48 +0100 Subject: [PATCH 80/87] Integration: Save As offers Netpbm as .pnm only (#3609) CodeRabbit on #9775: the encoder picks P5/P6/P7/PFM from the image, not the name, so a .pbm, .pgm or .pfm picked in Save As held other data (an RGB document as P6 in a .pbm). Only the neutral .pnm is offered; File > Open still reads every Netpbm extension. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/photocraft/src/services.rs | 4 +++- apps/photocraft/src/services/tests.rs | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index ff949863fb..c256e84d9f 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -100,7 +100,9 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("GIF", &["gif"]), ("ICO", &["ico"]), ("OpenEXR", &["exr"]), - ("Netpbm", &["pnm", "pbm", "pgm", "ppm", "pam", "pfm"]), + // The encoder picks P5, P6, P7 or PFM from the image, not from the name, so only the neutral + // .pnm is offered: a .pbm or .pgm name would hold pixmap data (CodeRabbit on #9775). + ("Netpbm", &["pnm"]), ("Radiance HDR", &["hdr"]), ("FITS", &["fits", "fit"]), ("DPX", &["dpx"]), diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index 06469aa637..0c12816707 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -294,13 +294,13 @@ fn save_as_offers_only_writable_formats_including_ico() { assert!(format.caps().write, "{name}: .{ext} can't be written"); } } - for ext in ["ico", "gif", "bmp", "dds", "pnm", "pfm", "hdr", "dib", "jpeg", "tiff"] { + for ext in ["ico", "gif", "bmp", "dds", "pnm", "hdr", "dib", "jpeg", "tiff"] { assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); } - // Picking Netpbm for a bare name takes its first extension; the codec writes P6/P7/PF from the - // image, never a 1-bit .pbm, so that one is the neutral .pnm (#3609). + // The codec writes P5/P6/P7/PF from the image, never from the name, so Netpbm offers only the + // neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data. let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts); - assert_eq!(netpbm.as_ref().and_then(|exts| exts.first()).map(String::as_str), Some("pnm")); + assert_eq!(netpbm, Some(vec!["pnm".to_string()])); // File › Open lists every file Save As writes, also in that format's own type (PDF is written // but not read yet). for (name, exts) in SAVE_FILTERS { From 199092edfdbd63803280baa8df7fe036e4920b33 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 18:18:49 +0100 Subject: [PATCH 81/87] Integration: a failed favourite toggle shows as an error; preference count from the scorecard (#6526) CodeRabbit on #9775: FontLibrary::finish wrote a failed type.font.favorite to the status bar as plain information; it now sets status_error like the other status writes. The regenerated scorecard counts 12 of 179 preferences that do nothing; ui-parity.md and gaps.md still said 178. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/tools/type_tool/fonts.rs | 1 + docs/gaps.md | 4 ++-- docs/ui-parity.md | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index e91b06f5d3..9035387c1e 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -315,6 +315,7 @@ impl FontLibrary { && let Err(e) = app.run("type.font.favorite", json!({"family": family})) { app.ui.status = e; + app.ui.status_error = true; } } } diff --git a/docs/gaps.md b/docs/gaps.md index f235d9317a..5b6d383b08 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 179 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -286,7 +286,7 @@ what an agent can't finish alone. - **Progress (2026-10-15):** the Color panel has Photoshop's panel-menu modes (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), its colour ramp and copy commands, the same in every theme (UI-217-17, #2569, #6000; `ui-egui/src/color_panel_ui.rs`). -- **Missing:** 12 of 178 preferences do nothing (scorecard prefs audit, 2026-10-25); panel groups can't +- **Missing:** 12 of 179 preferences do nothing (scorecard prefs audit, 2026-10-27); panel groups can't float or tear off into OS windows (UI-217-5, #1828, #1213, #2305); more themes (UI-217-11, #2661); a single pixel layer copies without its mask and styles (UI-217-23; fill and adjustment layers copy whole, #2344); tool-specific context menus beyond brushes, selections, Pen and Crop diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b6cae277fb..cd0d433582 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 179 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -230,7 +230,7 @@ Paragraph; the rest open as in-app floating windows. | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | | Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar | -| Every preference takes effect | partial | 12 of 178 do nothing (scorecard, 2026-10-25) | +| Every preference takes effect | partial | 12 of 179 do nothing (scorecard, 2026-10-27) | | UI scale presets | done | UI-217-9; 75–125% in 5% steps (#2492, #3222) | | History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; the snapshot History Options and History Brush sources to come (#2966) | | Themes: Photoshop's four greys | partial | five themes; #2661 | From 9426231d72f752a1c579189954f968119a1ddb66 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 19:13:57 +0100 Subject: [PATCH 82/87] Integration: Save As from a Netpbm subtype's name starts on .pnm (#3609) CodeRabbit on #9775: save_filters adds an unlisted suggested extension as its own type, so Save As on an opened .pgm offered .pgm again, though the encoder writes P6 for an RGB document. A suggested .pbm/.pgm/.ppm/.pam/.pfm now starts on the Netpbm type as .pnm; the services test checks every subtype name and fails without this. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/photocraft/src/services.rs | 3 +++ apps/photocraft/src/services/tests.rs | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index c256e84d9f..acb510c6c2 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -119,6 +119,9 @@ const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ( /// Lists the save dialog's file types with the `suggested` type first (added if unlisted), so the dialog keeps that extension instead of .psd. fn save_filters(suggested: &str) -> Vec<(String, Vec)> { let ext = Path::new(suggested).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + // A Netpbm subtype's name (an opened .pgm) starts on the Netpbm type as .pnm: the encoder picks + // the subtype from the image, so the old name could describe other data (CodeRabbit on #9775). + let ext = if ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&ext.as_str()) { "pnm".to_string() } else { ext }; if let Some((name, exts)) = OTHER_SAVE_FILTERS.iter().find(|(_, exts)| exts.contains(&ext.as_str())) { return vec![(name.to_string(), exts.iter().map(|e| e.to_string()).collect())]; } diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index 0c12816707..a2b9cfdb22 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -301,6 +301,13 @@ fn save_as_offers_only_writable_formats_including_ico() { // neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data. let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts); assert_eq!(netpbm, Some(vec!["pnm".to_string()])); + // Also when Save As starts from a subtype's name: no filter offers that subtype again. + for name in ["image.pbm", "image.pgm", "image.ppm", "image.pam", "image.pfm"] { + let filters = save_filters(name); + assert_eq!(filters[0], ("Netpbm".to_string(), vec!["pnm".to_string()]), "{name}"); + let subtype = name.rsplit('.').next().unwrap_or_default(); + assert!(!filters.iter().any(|(_, exts)| exts.iter().any(|e| e == subtype)), "{name}: .{subtype} is offered"); + } // File › Open lists every file Save As writes, also in that format's own type (PDF is written // but not read yet). for (name, exts) in SAVE_FILTERS { From c955e51b7fb062c2b4a4fadb1726b9ba719c6f3f Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 19:13:57 +0100 Subject: [PATCH 83/87] Integration: the parity docs name the locked-group exception for new layers (#4329) CodeRabbit on #9775: Place::AutoEditable puts type, shapes, pastes, placed files and frames above a group whose lock would refuse them; ui-parity.md's status line and checklist row said every new layer goes into an open active group. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index cd0d433582..33d2eb29a3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 179 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 179 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -239,7 +239,7 @@ Paragraph; the rest open as in-app floating windows. | Layers panel New Group button: click with 2+ layers selected groups them (CC 2014+), ⇧-click groups, one layer gives an empty group, ⌥-click opens the New Group dialog, ⌘-click adds the group below the active layer | done | #2561, `new_group_button_tests.rs` | | New Group dialog (Name, Color, Mode, Opacity) for Layer › New › Group… / Group from Layers…, the Layers panel menu and the row menu; ⌘G stays immediate | done | `dialogs/new_group_ui.rs`, `dialogs/new_group_ui/tests.rs` | | Groups made from layers (⌘G, New Group button, Group from Layers) start collapsed; selecting a layer inside opens the group | done | `group_options.rs` tests, `new_group_button_tests.rs` | -| New layers (New Layer/Group, adjustment, fill, type, shape, paste, place…) go in as the top layer of an open active group (or an artboard the new content is on), above a closed one; a new frame starts closed | done | `layer_place.rs`, `layer_place_tests.rs` | +| New layers (New Layer/Group, adjustment, fill, type, shape, paste, place…) go in as the top layer of an open active group (or an artboard the new content is on), above a closed one; type, shapes, pastes, placed files and frames go above a group whose lock (all, pixels, transparency or position) would refuse them; a new frame starts closed | done | `layer_place.rs`, `layer_place_tests.rs` | | A new layer or group inside a clipping mask joins it (clipped when the layer above its slot is), so the clipped layers keep their base | done | `layer_place_tests.rs` (#2203) | | Layers panel New Layer button: ⌘-click adds the layer below the active one (never under the Background) | done | `layer_place_tests.rs`, `new_group_button_tests.rs` | | Layers panel filter-type dropdown (Kind, Name, Effect, Mode, Attribute, Color, Smart Object, Selected, Artboard) | partial | Kind, Name and Mode; the other six missing. `layer_filter_ui.rs`, `ui.set {layerFilter}` (#5048) | From 6d62da9043a39c62871e1e6d2a7cff4446c217fc Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 14:19:41 +0100 Subject: [PATCH 84/87] Integration: per-band AHD balancing, memory-capped fused bands (#9455) `for_bands_grouped` always split the bands into `min(workers, jobs)` static chunks, so on the default develop (jobs == workers) a worker held up on the shared pool kept a fixed share of the bands waiting, where main's `chunks_mut_limited` runs one rayon task per band. Now, when every worker may hold a scratch, each band is its own task and borrows a scratch from a pool (`par::chunks_mut_pooled`, at most one per worker, dropped as soon as no waiting band can use it); the grouping stays for memory-limited jobs. The fused bilinear/MHC, X-Trans and LinearRaw paths ran one band per worker with no memory cap: a 262144 x 455 Bayer frame with bilinear needed 2.92 GB at 15+ workers and failed with LimitExceeded under the default 2 GiB. `working_memory` now caps those bands like AHD's and the fused paths use the returned jobs. The fused LinearRaw and X-Trans band buffers are `band.min(h)` rows, as charged (CodeRabbit, develop.rs:414). Tests: a_slow_band_does_not_hold_up_the_bands_after_it and fused_bands_at_once_are_capped_by_the_memory_limit fail without the fix; for_bands_keeps_at_most_jobs_scratches_alive, chunks_mut_pooled_makes_one_state_per_worker_at_most, multi-band and short X-Trans/LinearRaw fused-vs-full cases. Co-authored-by: Valentin Klein <271991477+vangel76@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/raw/src/demosaic.rs | 156 ++++++++++++++++++++++++++++++------- crates/raw/src/develop.rs | 70 ++++++++++++----- crates/raw/src/par.rs | 66 ++++++++++++++++ 3 files changed, 244 insertions(+), 48 deletions(-) diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 86bcee5f3c..6303931811 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -232,7 +232,7 @@ pub(crate) fn demosaic_fused( phase: [u8; 4], method: Demosaic, to_xyz: &Mat3, - ahd_jobs: usize, + jobs: usize, fill: &(impl Fn(usize, &mut [f32]) + Sync), out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync), @@ -257,7 +257,7 @@ pub(crate) fn demosaic_fused( // The rows of the tallest band, as `develop`'s memory check counts them. let rows = h.min(AHD_BAND); let init = || (AhdScratch::for_image(h, s), vec![0.0f32; rows * w * 3], vec![0.0f32; (rows + 2 * PAD) * s]); - for_bands_grouped(out, AHD_BAND * w * 3, ahd_bands(h), ahd_jobs, 1, init, |band, chunk, (sc, buf, win)| { + for_bands_grouped(out, AHD_BAND * w * 3, ahd_bands(h), jobs, 1, init, |band, chunk, (sc, buf, win)| { load(win, band * AHD_BAND, chunk.len() / (w * 3)); let buf = &mut buf[..chunk.len()]; // The window starts at a multiple of AHD_BAND (even), so it is band 0 of its own rows. @@ -269,7 +269,7 @@ pub(crate) fn demosaic_fused( let ks = kernels(phase, method, s); let rows = h.min(FUSED_ROWS); let init = || (vec![0.0f32; rows * w * 3], vec![0.0f32; (rows + 2 * PAD) * s]); - for_bands(out, FUSED_ROWS * w * 3, h.div_ceil(FUSED_ROWS), usize::MAX, init, |band, chunk, (buf, win)| { + for_bands(out, FUSED_ROWS * w * 3, h.div_ceil(FUSED_ROWS), jobs, init, |band, chunk, (buf, win)| { load(win, band * FUSED_ROWS, chunk.len() / (w * 3)); let buf = &mut buf[..chunk.len()]; linear_band(win, w, s, phase, method, &ks, band * FUSED_ROWS, band * FUSED_ROWS, buf); @@ -318,15 +318,16 @@ fn linear_band(d: &[f32], w: usize, s: usize, phase: [u8; 4], method: Demosaic, } /// Runs `f(band, chunk, scratch)` over the `unit`-sized chunks of `out` (`bands` of them), with -/// at most `jobs` scratch values alive: a few groups of consecutive bands per worker (for -/// balance), each group building its scratch once. For a scratch that is cheap to build. -pub(crate) fn for_bands( +/// at most `jobs` scratch values alive. When every worker may hold one, each band is its own +/// rayon task and borrows a scratch from a pool (one per worker at most); otherwise a few groups +/// of consecutive bands per job run, `jobs` at a time, each building its scratch once. +pub(crate) fn for_bands( out: &mut [T], unit: usize, bands: usize, jobs: usize, - init: impl Fn() -> S + Sync, - f: impl Fn(usize, &mut [T], &mut S) + Sync, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(usize, &mut [T], &mut S) + Sync + Send, ) { for_bands_grouped(out, unit, bands, jobs, 4, init, f); } @@ -337,18 +338,24 @@ fn bands_per_group(bands: usize, jobs: usize, per_worker: usize) -> usize { bands.div_ceil(groups).max(1) } -/// [`for_bands`] with `per_worker` groups of consecutive bands for each worker. A large scratch -/// (AHD: 16 planes) wants one group per worker: with more groups than workers on a many-core -/// machine every group is a single band and each band would build and zero its own scratch. -fn for_bands_grouped( +/// [`for_bands`] with `per_worker` groups of consecutive bands for each of the `jobs` workers when +/// fewer than all may hold a scratch. A large scratch (AHD: 16 planes) wants one group per job: +/// with more groups each would build and zero its own scratch for a band or two. +fn for_bands_grouped( out: &mut [T], unit: usize, bands: usize, jobs: usize, per_worker: usize, - init: impl Fn() -> S + Sync, - f: impl Fn(usize, &mut [T], &mut S) + Sync, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(usize, &mut [T], &mut S) + Sync + Send, ) { + // One task per band keeps rayon's stealing, so a busy or slow worker doesn't hold up a + // static share of the bands (as `par::chunks_mut_limited` does for the same reason). + if jobs >= par::workers() { + par::chunks_mut_pooled(out, unit, init, |sc, band, chunk| f(band, chunk, sc)); + return; + } let per_group = bands_per_group(bands, jobs, per_worker); par::chunks_mut_limited(out, per_group * unit, jobs, |group, gchunk| { let mut sc = init(); @@ -447,15 +454,15 @@ pub(crate) fn demosaic_cfa(p: &Padded, pat: &Pattern) -> Vec { } /// [`demosaic_cfa`] without the full RGB frame (the green plane stays): see [`demosaic_fused`]. -pub(crate) fn demosaic_cfa_fused(p: &Padded, pat: &Pattern, out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync)) { +pub(crate) fn demosaic_cfa_fused(p: &Padded, pat: &Pattern, jobs: usize, out: &mut [u16], emit: &(impl Fn(&[f32], &mut [u16]) + Sync)) { let (w, h) = (p.w, p.h); if out.len() < w * h * 3 { return; } let band = par::band_rows(w); - let init = || vec![0.0f32; band * w * 3]; + let init = || vec![0.0f32; band.min(h) * w * 3]; cfa_with(p, pat, |rows| { - for_bands(&mut out[..w * h * 3], band * w * 3, h.div_ceil(band), usize::MAX, init, |b, chunk, buf| { + for_bands(&mut out[..w * h * 3], band * w * 3, h.div_ceil(band), jobs, init, |b, chunk, buf| { let buf = &mut buf[..chunk.len()]; rows(b * band, buf); emit(buf, chunk); @@ -944,6 +951,8 @@ fn ahd_ref(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usi mod tests { use super::*; use crate::color::IDENTITY; + use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use std::time::{Duration, Instant}; #[test] fn ahd_band_concurrency_does_not_change_pixels() { @@ -1037,8 +1046,9 @@ mod tests { } } - /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over 4 scratches - /// with jobs 1 and at most 8 with jobs 2), so a stage reading a cell left over from an earlier band would show. + /// One scratch serves many bands (1100 rows are 35 bands, the last one short, over one scratch + /// with jobs 1 and two with jobs 2 on a bigger pool), so a stage reading a cell left over from + /// an earlier band would show. #[test] fn ahd_matches_reference_with_reused_scratch() { let m = [[0.41, 0.36, 0.18], [0.21, 0.72, 0.07], [0.02, 0.12, 0.95]]; @@ -1057,9 +1067,10 @@ mod tests { } } - /// A 4-worker pool splits 35 bands into groups of 9 (the last of 8), so groups after the first - /// start at band `group * 9` and every scratch is reused for several bands: a wrong band index - /// or a stale scratch cell would change pixels. The group size does not depend on the machine. + /// On a 4-worker pool with room for 3 scratches, 35 bands go in groups of 12 (the last of 11), + /// so groups after the first start at band `group * 12` and every scratch is reused for several + /// bands; with room for 4, every band is its own task and most borrow a used scratch. A wrong band + /// index or a stale scratch cell would change pixels. The split does not depend on the machine. #[cfg(not(target_arch = "wasm32"))] #[test] fn ahd_groups_of_several_bands_match_reference() { @@ -1070,18 +1081,103 @@ mod tests { let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); pool.install(|| { assert_eq!(par::workers(), 4); - assert_eq!(bands_per_group(ahd_bands(h), 4, 1), 9); - // One worker per group, never more groups than workers, however many bands there are. - assert_eq!(bands_per_group(126, 1000, 1), 32); - for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { - let mut want = vec![0.0f32; w * h * 3]; - ahd_ref(&p, phase, &m, &mut want, 4); - let got = demosaic(&p, phase, Demosaic::Ahd, &m, 4); - assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?}"); + assert_eq!(bands_per_group(ahd_bands(h), 3, 1), 12); + // One group per job, never more groups than jobs, however many bands there are. + assert_eq!(bands_per_group(126, 3, 1), 42); + for jobs in [3, 4] { + for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] { + let mut want = vec![0.0f32; w * h * 3]; + ahd_ref(&p, phase, &m, &mut want, jobs); + let got = demosaic(&p, phase, Demosaic::Ahd, &m, jobs); + assert!(want.iter().zip(&got).all(|(a, b)| a.to_bits() == b.to_bits()), "{phase:?} jobs {jobs}"); + } } }); } + /// A scratch that counts how many are alive at once. + struct Live<'a>(&'a AtomicUsize); + + impl<'a> Live<'a> { + fn new(now: &'a AtomicUsize, peak: &AtomicUsize) -> Self { + peak.fetch_max(now.fetch_add(1, SeqCst) + 1, SeqCst); + Live(now) + } + } + + impl Drop for Live<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, SeqCst); + } + } + + /// Every band runs once with its own index, and no more than `jobs` scratches (what `develop`'s + /// memory check admits) or one per worker are alive at once, on either side of `jobs == workers`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn for_bands_keeps_at_most_jobs_scratches_alive() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap(); + pool.install(|| { + for jobs in [1, 2, 3, 7, 8, 9, usize::MAX] { + for per_worker in [1, 4] { + let (now, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mut out = vec![0usize; 37 * 10 - 4]; + for_bands_grouped( + &mut out, + 10, + 37, + jobs, + per_worker, + || Live::new(&now, &peak), + |band, chunk, _| { + std::thread::sleep(Duration::from_millis(1)); + chunk.iter_mut().for_each(|v| *v += band + 1); + }, + ); + assert!(out.iter().enumerate().all(|(i, &v)| v == i / 10 + 1), "jobs {jobs}"); + let peak = peak.load(SeqCst); + assert!((1..=jobs.min(8)).contains(&peak), "jobs {jobs} per_worker {per_worker}: {peak} scratches alive"); + assert_eq!(now.load(SeqCst), 0); + } + } + }); + } + + /// With room for a scratch on every worker, the bands are separate rayon tasks: a worker held up + /// on band 0 (by other work on the shared pool, or a slow core) leaves the bands after it to + /// the others. With a fixed share of 9 bands per worker, 8 of them would wait for band 0, so at + /// most 26 of the other 34 could finish meanwhile. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_slow_band_does_not_hold_up_the_bands_after_it() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + let (done, seen) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let mut out = vec![0u8; 35]; + for_bands_grouped( + &mut out, + 1, + 35, + 4, + 1, + || (), + |band, _, _| { + if band > 0 { + done.fetch_add(1, SeqCst); + return; + } + let start = Instant::now(); + while done.load(SeqCst) <= 26 && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + seen.store(done.load(SeqCst), SeqCst); + }, + ); + assert_eq!(done.load(SeqCst), 34); + assert!(seen.load(SeqCst) > 26, "only {} bands ran while band 0 was held up", seen.load(SeqCst)); + }); + } + /// Mosaics an RGB image with the given phase. fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec { (0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect() diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index ed5248b67b..aaeb390eff 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -230,7 +230,7 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result Result Result>().join("/")); if fused { let mut o = vec![0u16; w * h * 3]; - demosaic_cfa_fused(&plane, &pat, &mut o, &encode_plain); + demosaic_cfa_fused(&plane, &pat, jobs, &mut o, &encode_plain); fused_out = Some(o); } else { rgb = demosaic_cfa(&plane, &pat); @@ -410,8 +410,8 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result u64 { } /// Checks the peak of the two development phases. The CFA and non-Bayer green -/// planes are freed before the u16 output is allocated; AHD scratch is bounded -/// by reducing simultaneous bands when needed. The fused path never holds the f32 RGB frame: -/// it has the u16 output (6 bytes a pixel) next to the CFA plane, plus a band buffer and the -/// scratch per worker, and an orientation copy of the output afterwards. Sensor storage belongs +/// planes are freed before the u16 output is allocated; the AHD scratch and the fused band +/// buffers are bounded by reducing simultaneous bands when needed. The fused path never holds +/// the f32 RGB frame: it has the u16 output (6 bytes a pixel) next to the CFA plane, plus a band +/// buffer and the scratch per simultaneous band, and an orientation copy of the output afterwards. Sensor storage belongs /// to the caller and is checked separately by the decoder. fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts: &DevelopOptions, workers: usize) -> Result { let limits = &opts.limits; @@ -530,7 +530,12 @@ fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts let mut jobs = workers.max(1); // Fused: the u16 output and, per worker running a band, one band of f32 RGB. let band_of = |rows: usize, window: bool| if fused { fused_band_bytes(w, h, rows, window) } else { 0 }; - let band_jobs = |rows: usize| workers.max(1).min(h.div_ceil(rows.max(1))) as u64; + // Fewer bands at once when the bands of every worker don't fit next to `base` (at least one). + let with_bands = |jobs: &mut usize, base: u64, rows: usize, band: u64| { + let available = limits.max_alloc.saturating_sub(base) / band.max(1); + *jobs = (*jobs).min(h.div_ceil(rows.max(1))).min(usize::try_from(available).unwrap_or(usize::MAX)).max(1); + base.saturating_add(band.saturating_mul(*jobs as u64)) + }; if cfa { let plane = (w as u64).saturating_add(2 * PAD as u64).saturating_mul((h as u64).saturating_add(2 * PAD as u64)).saturating_mul(4); // Bytes a pixel next to the plane: the f32 RGB frame (and the non-Bayer green plane), or @@ -547,19 +552,17 @@ fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, shape: Shape, opts if bayer && opts.demosaic == Demosaic::Ahd { mosaic = mosaic.saturating_add(crate::demosaic::AHD_TABLE_BYTES); let scratch = crate::demosaic::ahd_scratch(w as u64, h as u64).saturating_add(band_of(crate::demosaic::AHD_BAND, true)); - let available = limits.max_alloc.saturating_sub(mosaic) / scratch.max(1); - jobs = jobs.min(crate::demosaic::ahd_bands(h)).min(usize::try_from(available).unwrap_or(usize::MAX)); // At least one band must fit, even when no parallelism is available. - mosaic = mosaic.saturating_add(scratch.saturating_mul(jobs.max(1) as u64)); + mosaic = with_bands(&mut jobs, mosaic, crate::demosaic::AHD_BAND, scratch); } else { let rows = if bayer { crate::demosaic::FUSED_ROWS } else { par::band_rows(w) }; - mosaic = mosaic.saturating_add(band_of(rows, bayer).saturating_mul(band_jobs(rows))); + mosaic = with_bands(&mut jobs, mosaic, rows, band_of(rows, bayer)); } peak = peak.max(mosaic); } else if fused { // LinearRaw: the output and the bands. let rows = par::band_rows(w); - peak = peak.max(pixels.saturating_mul(6).saturating_add(band_of(rows, false).saturating_mul(band_jobs(rows)))); + peak = peak.max(with_bands(&mut jobs, pixels.saturating_mul(6), rows, band_of(rows, false))); } if peak > limits.max_alloc || usize::try_from(peak).is_err() { return Err(RawError::LimitExceeded(format!("{peak} bytes of RAW working memory exceed {}", limits.max_alloc))); @@ -836,13 +839,15 @@ mod tests { }) }) .collect(); - for (w, h) in [(6, 6), (37, 41), (80, 150)] { + // 600 samples wide: bands of 109 rows, so 350 rows are four (the last short) and 50 rows + // are less than one. + for (w, h) in [(6, 6), (37, 41), (80, 150), (600, 350), (600, 50)] { let mut s = test_sensor(w, h, Some(Cfa { width: 6, height: 6, colors: colors.clone(), origin_x: 0, origin_y: 0 }), 1); s.orientation = 8; assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("xtrans {w}x{h}")); } for samples in [1, 3] { - for (w, h) in [(1, 1), (7, 5), (90, 111)] { + for (w, h) in [(1, 1), (7, 5), (90, 111), (600, 350), (600, 50)] { let mut s = test_sensor(w, h, None, samples); s.orientation = 3; assert_fused_matches_full(&s, &DevelopOptions::default(), &format!("linear {samples} {w}x{h}")); @@ -902,6 +907,35 @@ mod tests { assert!(working_memory(11648, 8736, true, true, FUSED, &opts, 1).is_ok()); } + /// The fused bilinear / MHC, X-Trans and LinearRaw paths run fewer bands at once when the bands + /// of every worker don't fit next to the output, as AHD does. A very wide, short Bayer frame + /// (262144 x 455: 15 bands of 32 rows, about 147 MB a band with its window) needs 2.92 GB + /// with all 15 at once against the default 2 GiB, and develops with 9. + #[test] + fn fused_bands_at_once_are_capped_by_the_memory_limit() { + let opts = DevelopOptions { demosaic: Demosaic::Bilinear, ..Default::default() }; + let table = (GAMMA_STEPS as u64 + 2) * 4; + let (w, h) = (262144usize, 455usize); + let band = 32 * 262144 * 12 + (32 + 2 * PAD as u64) * (262144 + 2 * PAD as u64) * 4; + for (workers, want) in [(1, 1), (8, 8), (9, 9), (10, 9), (16, 9), (32, 9)] { + assert_eq!(working_memory(w, h, true, true, FUSED, &opts, workers).unwrap(), want, "{workers} workers"); + } + // Never more jobs than bands, and one when only one band fits. + assert_eq!(working_memory(1000, 40, true, true, FUSED, &opts, 32).unwrap(), 2); + let mut tight = opts.clone(); + tight.limits.max_alloc = 262144 * 455 * 6 + table + band; + assert_eq!(working_memory(w, h, true, true, FUSED, &tight, 32).unwrap(), 1); + tight.limits.max_alloc -= 1; + assert!(working_memory(w, h, true, true, FUSED, &tight, 32).is_err()); + // X-Trans (bands of `band_rows(1000)` = 65 rows next to its planes) and LinearRaw likewise. + let plane = (1000 + 2 * PAD as u64) * (2000 + 2 * PAD as u64) * 4; + let mut x = opts.clone(); + x.limits.max_alloc = 1000 * 2000 * 10 + plane + table + 3 * 65 * 1000 * 12; + assert_eq!(working_memory(1000, 2000, true, false, FUSED, &x, 32).unwrap(), 3); + x.limits.max_alloc = 1000 * 2000 * 6 + 5 * 65 * 1000 * 12; + assert_eq!(working_memory(1000, 2000, false, true, FUSED, &x, 32).unwrap(), 5); + } + #[test] fn working_memory_accounts_for_padding_and_at_least_one_ahd_band() { let mut opts = DevelopOptions { demosaic: Demosaic::Ahd, ..Default::default() }; diff --git a/crates/raw/src/par.rs b/crates/raw/src/par.rs index 6d23fd70c4..d966d94f52 100644 --- a/crates/raw/src/par.rs +++ b/crates/raw/src/par.rs @@ -1,5 +1,7 @@ //! Data-parallel helpers: rayon on native targets, sequential on wasm. +use std::sync::{Mutex, PoisonError}; + /// Calls `f(index, chunk)` for each `chunk`-sized piece of `buf`. pub(crate) fn chunks_mut(buf: &mut [T], chunk: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) { let chunk = chunk.max(1); @@ -12,6 +14,36 @@ pub(crate) fn chunks_mut(buf: &mut [T], chunk: usize, f: impl Fn(usize, buf.chunks_mut(chunk).enumerate().for_each(|(i, c)| f(i, c)); } +/// Like [`chunks_mut`], with `f(state, index, chunk)` borrowing a state: a chunk takes a free one +/// or makes one with `init`, and gives it back when done, so rayon keeps its fine-grained +/// splitting and stealing while at most one state per worker is ever made (`f` must not itself +/// wait on rayon work). Rayon's `for_each_init` would make one per stolen piece, which on an idle +/// pool is often every chunk. A state no chunk still waiting can take is dropped at once, so +/// near the end they go as their workers finish rather than all at the very end. +pub(crate) fn chunks_mut_pooled( + buf: &mut [T], + chunk: usize, + init: impl Fn() -> S + Sync + Send, + f: impl Fn(&mut S, usize, &mut [T]) + Sync + Send, +) { + let chunk = chunk.max(1); + // The free states and the number of chunks that have not taken one yet. + let pool = Mutex::new((Vec::new(), buf.len().div_ceil(chunk))); + chunks_mut(buf, chunk, |i, c| { + let taken = { + let mut pool = pool.lock().unwrap_or_else(PoisonError::into_inner); + pool.1 = pool.1.saturating_sub(1); + pool.0.pop() + }; + let mut state = taken.unwrap_or_else(&init); + f(&mut state, i, c); + let mut pool = pool.lock().unwrap_or_else(PoisonError::into_inner); + if pool.0.len() < pool.1 { + pool.0.push(state); + } + }); +} + /// Native worker count (the browser builds run sequentially). pub(crate) fn workers() -> usize { #[cfg(not(target_arch = "wasm32"))] @@ -56,3 +88,37 @@ pub(crate) fn map(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Ve pub(crate) fn band_rows(width: usize) -> usize { (65536 / width.max(1)).clamp(1, 256) } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every chunk is visited once with its own index (the last one short), and the chunks share + /// the states: a 4-worker pool makes at most 4 for 101 chunks, an empty buffer none. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn chunks_mut_pooled_makes_one_state_per_worker_at_most() { + let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap(); + pool.install(|| { + let mut buf = vec![0usize; 1003]; + let inits = AtomicUsize::new(0); + let runs = AtomicUsize::new(0); + let init = || { + inits.fetch_add(1, Ordering::Relaxed); + 0usize + }; + chunks_mut_pooled(&mut buf, 10, init, |used, i, c| { + *used += 1; + runs.fetch_add(1, Ordering::Relaxed); + c.iter_mut().for_each(|v| *v += i + 1); + }); + assert!(buf.iter().enumerate().all(|(k, &v)| v == k / 10 + 1)); + assert_eq!(runs.load(Ordering::Relaxed), 101); + let n = inits.load(Ordering::Relaxed); + assert!((1..=4).contains(&n), "{n} states for 101 chunks on 4 workers"); + chunks_mut_pooled(&mut [0u8; 0], 4, init, |_, _, _| {}); + assert_eq!(inits.load(Ordering::Relaxed), n, "no state for an empty buffer"); + }); + } +} From 8b0a8da8b1084633fe434eb6dada18904c668a79 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 20:21:25 +0100 Subject: [PATCH 85/87] Integration: flate2 at least 1.1.10, the first with runtime_detection (#7689) CodeRabbit on #9775 (nitpick): #7689 enables flate2's runtime_detection feature, which 1.1.9 and older don't have, under a "1" requirement; a lock-less consumer (the publishable psd crate) could resolve an older 1.x and fail. Cargo.lock already pins 1.1.10 and is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 19e7ba0943..1bf644923d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,7 +51,7 @@ clap_complete = "4.6.11" clap_mangen = { version = "0.3.3", features = ["env"] } arc-swap = "1" bytemuck = { version = "1", features = ["derive"] } -flate2 = { version = "1", default-features = false, features = ["zlib-rs", "runtime_detection"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } image = { version = "0.25", default-features = false } # Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg. zune-core = "0.5" From f56ae1952201624e79fb543475c57b5ca97fd55e Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 20:21:26 +0100 Subject: [PATCH 86/87] Integration: Save As from an opened .pgm suggests .pnm on every platform (#3609) CodeRabbit on #9775: the Linux portal swaps the extension for the picked type, but macOS and rfd keep the suggested name, so an opened image.pgm could still be saved as image.pgm holding P6 data. The suggested name itself now takes .pnm for any Netpbm subtype; the services test fails without it. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/photocraft/src/services.rs | 10 ++++++++++ apps/photocraft/src/services/tests.rs | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 18f15fe3ea..48d78aa922 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -116,6 +116,15 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ /// never swaps their extension for a document format's. const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ("Color Table", &["act"]), ("Swatch Exchange", &["ase"])]; +/// `suggested` with a Netpbm subtype's extension (an opened .pgm) as the neutral .pnm, the name +/// every save dialog starts from: the encoder picks P5, P6, P7 or PFM from the image, so the old +/// suffix could name other data, and macOS and rfd keep the suggested name as it is. +fn netpbm_as_pnm(suggested: &str) -> String { + let path = Path::new(suggested); + let subtype = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).is_some_and(|e| ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&e.as_str())); + if subtype { path.with_extension("pnm").to_string_lossy().into_owned() } else { suggested.to_string() } +} + /// Lists the save dialog's file types with the `suggested` type first (added if unlisted), so the dialog keeps that extension instead of .psd. fn save_filters(suggested: &str) -> Vec<(String, Vec)> { let ext = Path::new(suggested).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); @@ -223,6 +232,7 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>, Box::pin(async move { picked.await.map(|folder| answer_one(folder.path(), true, FileDialogAnswer::FolderTo)) }) } FileDialogRequest::Save { suggested } => { + let suggested = netpbm_as_pnm(&suggested); let filters = save_filters(&suggested); let name = dialog_file_name(&suggested, cfg!(windows)); let dir = Path::new(&suggested).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf); diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index af77bdfa9f..c71074572e 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -301,6 +301,11 @@ fn save_as_offers_only_writable_formats_including_ico() { // neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data. let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts); assert_eq!(netpbm, Some(vec!["pnm".to_string()])); + // The suggested name itself becomes .pnm, as macOS and rfd keep it (CodeRabbit on #9775). + assert_eq!(netpbm_as_pnm("scans/image.pgm"), Path::new("scans/image.pnm").to_string_lossy()); + assert_eq!(netpbm_as_pnm("image.PFM"), "image.pnm"); + assert_eq!(netpbm_as_pnm("image.png"), "image.png"); + assert_eq!(netpbm_as_pnm("Untitled-1"), "Untitled-1"); // Also when Save As starts from a subtype's name: no filter offers that subtype again. for name in ["image.pbm", "image.pgm", "image.ppm", "image.pam", "image.pfm"] { let filters = save_filters(name); From 1992cfcb9ca149e45d772e9fe665a7d494539996 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 20:21:26 +0100 Subject: [PATCH 87/87] Integration: parity docs dated 2026-10-27 with a history row for the scorecard count CodeRabbit on #9775: the 12-of-181 count changed today, so ui-parity.md and gaps.md get the date in their status lines and a revision-history row, as AGENTS.md asks. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/gaps.md | 3 ++- docs/ui-parity.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index ab694f2b0d..0c94561436 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 181 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G9: 12 of 181 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -396,6 +396,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | G9: 12 of 181 preferences do nothing, the scorecard's count with integration batch 9 (#9775) on main; no estimate changed | | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7856769dee..4490d693c2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -252,6 +252,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Every preference takes effect: 12 of 181 do nothing, the scorecard's count with integration batch 9 (#9775) on main; new layers go above a group whose lock would refuse them (#4329) | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | | 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed |