Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Integration: track t12

aiongg576ba0e02b8f
diff --cc contributors/people.toml
index 474ea4f13,a627aa8ac..c5b0f2c0a
--- a/contributors/people.toml
+++ b/contributors/people.toml
@@@ -201,28 -192,5 +201,32 @@@ sync_github_name = tru
[people.ha1des]
sync_github_name = true
+[people.webdevtodayjason]
+display_name = "Jason Brashear"
+
+[people.AndreeSalazar]
+real_name = "Andreé Salazar"
+sync_github_name = true
+
+[people.LorenzoFasolino]
+real_name = "Lorenzo Fasolino"
+display_name = "Lorenzo Fasolino"
+sync_github_name = false
+
+[people.zolyy]
+real_name = "Gall Zoltan"
+sync_github_name = false
+
+[people.theshubh77]
+real_name = "Shubham Bhamare"
+sync_github_name = true
+
+[people.ksaxena149]
+sync_github_name = true
+
+[people.giang17]
+real_name = "Giang Nguyen"
++sync_github_name = true
++
+ [people.aqibmohd271]
+ sync_github_name = true
diff --cc crates/compose/src/lib.rs
index 1e233e1c7,e24902df6..dadeb2e72
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -1890,27 -1925,9 +1925,24 @@@ fn composite_layer_plain(layer: &Layer
cx.apply_adjustment(adj, &mut adjusted);
// Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result.
advanced::composite_clipped(clipped, &mut adjusted, cx);
- for y in rect.y0..rect.y1 {
- for x in rect.x0..rect.x1 {
- let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;
- let k = opacity * mask_k(&mv, i);
- if k <= 0.0 {
- continue;
- }
- // Only `adjusted` has changed; this pixel's original backdrop is still in place.
- let b = backdrop.px[i];
- let a = adjusted.px[i];
- if layer.blend == BlendMode::Dissolve {
- // An adjustment has no standalone source alpha. Its effective coverage
- // comes from its own opacity and mask, not a continuous RGB mix (#3050).
- if dissolve_noise(x, y) < k {
- backdrop.px[i] = [a[0], a[1], a[2], b[3]];
- match &mv {
- Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend),
- None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend),
++ if layer.blend == BlendMode::Dissolve {
++ // An adjustment has no standalone source alpha. Its effective coverage comes from its
++ // own opacity and mask, not a continuous RGB mix (#3050).
++ for y in rect.y0..rect.y1 {
++ for x in rect.x0..rect.x1 {
++ let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;
++ let k = opacity * mask_k(&mv, i);
++ if k > 0.0 && dissolve_noise(x, y) < k {
++ let a = adjusted.px[i];
++ backdrop.px[i] = [a[0], a[1], a[2], backdrop.px[i][3]];
+ }
- continue;
+ }
- let blended = blend::blend_rgb(layer.blend, [b[0], b[1], b[2]], [a[0], a[1], a[2]]);
- backdrop.px[i] = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]];
++ }
++ } else {
++ match &mv {
++ Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend),
++ None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend),
+ }
}
recycle_buffer(adjusted);
return;
diff --cc crates/compose/src/tests.rs
index 02878d080,f31a53049..84fa7e6df
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -3932,104 -3840,18 +4031,120 @@@ fn fully_masked_adjustment_tiles_preser
}
}
+#[test]
+fn dissolve_adjustment_resolves_opacity_to_binary_coverage() {
+ let mut d = doc_white(16, 16);
+ let mut layer = Layer::new("Invert", LayerContent::Adjustment(Adjustment::Invert));
+ layer.blend = BlendMode::Dissolve;
+ layer.opacity = 0.5;
+ d.layers.push(layer);
+ let pixels = render(&d, d.bounds()).px;
+ let black = pixels.iter().filter(|p| p[0] < 0.01).count();
+ let white = pixels.iter().filter(|p| p[0] > 0.99).count();
+ assert!(black > 0 && white > 0, "Dissolve must select both original and adjusted pixels");
+ assert_eq!(black + white, pixels.len(), "no intermediate gray pixels");
+ d.layers.last_mut().unwrap().blend = BlendMode::Normal;
+ let continuous = render(&d, d.bounds()).px;
+ assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E), "Normal remains continuously interpolated");
+}
+
+#[test]
+fn clipped_dissolve_fill_matches_opaque_unclipped_coverage() {
+ let mut d = doc_white(16, 16);
+ let mut fill = Layer::new("Black", LayerContent::Fill(Fill::Solid(Color::BLACK)));
+ fill.blend = BlendMode::Dissolve;
+ fill.opacity = 0.5;
+ d.layers.push(fill);
+ let control = render(&d, d.bounds()).px;
+ d.layers.last_mut().unwrap().clipped = true;
+ let clipped = render(&d, d.bounds()).px;
+ assert_eq!(clipped, control, "clipping over a fully opaque base must preserve dissolve pixels");
+ let black = clipped.iter().filter(|p| p[0] < 0.01).count();
+ assert!(black > 0 && black < clipped.len());
+ d.layers.last_mut().unwrap().blend = BlendMode::Normal;
+ let continuous = render(&d, d.bounds()).px;
+ assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E));
+}
+
+#[test]
+fn dissolve_color_overlay_preserves_binary_layer_coverage() {
+ let mut d = doc_white(16, 16);
+ let mut layer = Layer::new("Black", LayerContent::Fill(Fill::Solid(Color::BLACK)));
+ layer.blend = BlendMode::Dissolve;
+ layer.opacity = 0.5;
+ d.layers.push(layer);
+ let control = render(&d, d.bounds()).px;
+ d.layers
+ .last_mut()
+ .unwrap()
+ .effects
+ .items
+ .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::BLACK });
+ let styled = render(&d, d.bounds()).px;
+ assert_eq!(styled, control, "an identity overlay should not turn dissolve pixels gray");
+ d.layers.last_mut().unwrap().blend = BlendMode::Normal;
+ let continuous = render(&d, d.bounds()).px;
+ assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E));
+}
+
+#[test]
+fn clipped_dissolve_adjustment_preserves_alpha_and_document_coverage() {
+ for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
+ let mut d = Document::new("clipped adjustment", Size::new(272, 12), ColorMode::Rgb, fmt.sample);
+ let bounds = Rect::new(-3, -2, 272, 12);
+ let mut base = Layer::raster("base", fmt);
+ base.surface_mut().unwrap().fill_rect(bounds, &[1.0, 1.0, 1.0, 0.5]);
+ d.layers.push(base);
+ let original = render(&d, bounds);
+ let mut adjustment = Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert));
+ adjustment.clipped = true;
+ adjustment.blend = BlendMode::Dissolve;
+ adjustment.opacity = 0.6;
+ adjustment.fill_opacity = 0.5;
+ let mut mask = photocraft_raster::Surface::new(PixelFormat::GRAY8);
+ mask.fill_rect(Rect::new(-3, -2, 260, 12), &[1.0]);
+ adjustment.mask = Some(LayerMask { surface: mask, enabled: true, linked: true, density: 1.0, feather: 0.0 });
+ d.layers.push(adjustment);
+ let whole = render(&d, bounds);
+ let mut changed = 0;
+ for y in bounds.y0..bounds.y1 {
+ for x in bounds.x0..bounds.x1 {
+ let p = whole.get(x, y);
+ let value = if x < 260 && dissolve_noise(x, y) < 0.3 {
+ changed += 1;
+ 0.0
+ } else {
+ 1.0
+ };
+ assert!(close4(p, [value, value, value, original.get(x, y)[3]]), "{fmt:?} at ({x}, {y}): {p:?}");
+ }
+ }
+ assert!(changed > 0 && changed < whole.px.len());
+ let region = Rect::new(250, 1, 270, 10);
+ let part = render(&d, region);
+ for y in region.y0..region.y1 {
+ for x in region.x0..region.x1 {
+ assert!(close4(part.get(x, y), whole.get(x, y)), "{fmt:?} region at ({x}, {y})");
+ }
+ }
+ d.layers.last_mut().unwrap().blend = BlendMode::Normal;
+ let normal = render(&d, bounds);
+ assert!(normal.px.iter().any(|p| p[0] > 0.01 && p[0] < 0.99), "Normal keeps continuous mixing");
+ }
+}
++
+ #[test]
+ fn branchless_floor_matches_floor_bitwise() {
+ // Every 4099th bit pattern (all exponents, both signs, NaNs and infinities among them), plus
+ // the values either side of the whole numbers and of 2^23 where the rounding steps.
+ let mut xs: Vec<f32> = (0..=u32::MAX).step_by(4099).map(f32::from_bits).collect();
+ for w in [0.0f32, 1.0, 2.0, 254.0, 255.0, 32768.0, 4_194_303.0, 4_194_304.0, 8_388_607.0, 8_388_608.0, 16_777_216.0] {
+ for v in [w, -w] {
+ xs.extend([v, v.next_up(), v.next_down(), v + 0.5, v - 0.5]);
+ }
+ }
+ xs.extend([f32::INFINITY, f32::NEG_INFINITY, f32::NAN, -f32::NAN, f32::MIN_POSITIVE, -f32::MIN_POSITIVE, f32::MAX, f32::MIN]);
+ for x in xs {
+ assert_eq!(branchless_floor(x).to_bits(), x.floor().to_bits(), "{x:e} ({:#010x})", x.to_bits());
+ }
+ }
diff --cc crates/engine/src/print_cmds.rs
index c06cd4e1b,f5a110eea..a0395ff52
--- a/crates/engine/src/print_cmds.rs
+++ b/crates/engine/src/print_cmds.rs
@@@ -521,45 -571,49 +593,69 @@@ pub fn layout(doc: &Document, p: &Value
corner_crop: p.get("cornerCropMarks").and_then(Value::as_bool).unwrap_or(false),
center_crop: p.get("centerCropMarks").and_then(Value::as_bool).unwrap_or(false),
registration: p.get("registrationMarks").and_then(Value::as_bool).unwrap_or(false),
+ bleed,
};
- let margin = if marks.corner_crop || marks.center_crop || marks.registration { 36.0 } else { 18.0 };
+ let has_marks = marks.corner_crop || marks.center_crop || marks.registration;
+ // Scale to Fit Media fits the driver's printable area when it is known (the whole sheet for
+ // borderless paper); marks keep their inset inside it. Without one (CUPS, PDF), the paper
+ // minus a fixed margin.
+ let emulsion_down = p.get("emulsionDown").and_then(Value::as_bool).unwrap_or(false);
let fit = p.get("scaleToFit").and_then(Value::as_bool).unwrap_or(false);
- let scale = if fit {
- ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih)
- } else {
- p.get("scale").and_then(Value::as_f64).filter(|v| *v > 0.0).unwrap_or(100.0) / 100.0
+ // Only a fitted print reads the area, so a stale one (a replayed action, another paper) can't
+ // fail a print at a manual scale.
+ let area = if fit { printable(p, (pw, ph), cmd)? } else { None };
+ let fit_box = match area {
+ Some((x, y, w, h)) => {
+ // Emulsion Down mirrors the page as it prints: fit the mirror of the printable area,
+ // so the printed image lands inside the real one.
+ let x = if emulsion_down { pw - x - w } else { x };
+ let inset = if has_marks { 36.0 } else { 0.0 };
+ if !(w > 2.0 * inset && h > 2.0 * inset) {
+ return Err(bad(cmd, "the printable area is too small for crop and registration marks"));
+ }
+ (x + inset, y + inset, w - 2.0 * inset, h - 2.0 * inset)
+ }
+ None => {
+ let margin = if has_marks { 36.0 } else { 18.0 };
+ (margin, margin, pw - 2.0 * margin, ph - 2.0 * margin)
+ }
};
+ let scale = if fit { (fit_box.2 / iw).min(fit_box.3 / ih) } else { p.get("scale").and_then(Value::as_f64).filter(|v| *v > 0.0).unwrap_or(100.0) / 100.0 };
let (w, h) = (iw * scale, ih * scale);
+ // The trim box must keep some area, or the marks of opposite corners would cross.
+ if 2.0 * marks.bleed >= w.min(h) {
+ return Err(bad(cmd, format!("bleed {:.3} in leaves no image inside the trim ({:.2} × {:.2} in printed)", marks.bleed / 72.0, w / 72.0, h / 72.0)));
+ }
+ // Bleed only moves crop marks; without them it has nothing to change.
+ if !marks.corner_crop {
+ marks.bleed = 0.0;
+ }
let center = p.get("center").and_then(Value::as_bool).unwrap_or(true);
- let (x, y) = if center {
+ let (x, y) = if center && fit {
+ (fit_box.0 + (fit_box.2 - w) / 2.0, fit_box.1 + (fit_box.3 - h) / 2.0)
+ } else if center {
((pw - w) / 2.0, (ph - h) / 2.0)
} else {
// Top / left in inches from the paper's top-left corner (Photoshop's Position fields).
- let top = p.get("top").and_then(Value::as_f64).unwrap_or(0.0) * 72.0;
- let left = p.get("left").and_then(Value::as_f64).unwrap_or(0.0) * 72.0;
+ let position = |key: &str| -> Result<f64> {
+ let value = match p.get(key) {
+ None => 0.0,
+ Some(v) => v.as_f64().ok_or_else(|| bad(cmd, "print positions must be finite numbers in inches"))?,
+ };
+ if !value.is_finite() || value.abs() > MAX_POSITION_INCHES {
+ return Err(bad(cmd, "print positions must be within -10000 to 10000 inches"));
+ }
+ Ok(value * 72.0)
+ };
+ let top = position("top")?;
+ let left = position("left")?;
(left, ph - top - h)
};
+ // Guard geometry before converting to screen points or writing PDF operators. Even a
+ // finite JSON scale can overflow when multiplied by document dimensions.
+ if ![pw, ph, x, y, w, h, scale].into_iter().all(|v| v.is_finite() && v.abs() <= 1.0e9) || w <= 0.0 || h <= 0.0 {
+ return Err(bad(cmd, "print layout must have finite geometry within 1000000000 points and positive image dimensions"));
+ }
- let emulsion_down = p.get("emulsionDown").and_then(Value::as_bool).unwrap_or(false);
Ok(PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down })
}
@@@ -1181,7 -1194,7 +1277,7 @@@ pub fn specs() -> Vec<CommandSpec>
CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }
};
}
- const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"printable":[x,y,w,h] pt? (the driver's printable area from the paper's top-left, as file.print.page reports it; Scale to Fit Media fits it, else the paper minus 18 pt; a native Windows print reads the driver's own instead),"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"printServer":"host[:port]|socket path"? (default: the system's CUPS; a named server is always printed to over IPP),"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent, spooler:where the job went|null, backend:"lp|windows|ipp|portal"|null}"##;
- const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"bleed":in=0 (Functions › Bleed: corner crop marks this far inside the image edge, on the trim line),"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"printServer":"host[:port]|socket path"? (default: the system's CUPS; a named server is always printed to over IPP),"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent, spooler:where the job went|null, backend:"lp|windows|ipp|portal"|null}"##;
++ const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"printable":[x,y,w,h] pt? (the driver's printable area from the paper's top-left, as file.print.page reports it; Scale to Fit Media fits it, else the paper minus 18 pt; a native Windows print reads the driver's own instead),"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"bleed":in=0 (Functions › Bleed: corner crop marks this far inside the image edge, on the trim line),"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"printServer":"host[:port]|socket path"? (default: the system's CUPS; a named server is always printed to over IPP),"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent, spooler:where the job went|null, backend:"lp|windows|ipp|portal"|null}"##;
vec![
spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print),
diff --cc crates/engine/src/print_cmds/tests.rs
index de9e14579,2f7809fd8..43f49101a
--- a/crates/engine/src/print_cmds/tests.rs
+++ b/crates/engine/src/print_cmds/tests.rs
@@@ -870,133 -932,100 +932,231 @@@ fn the_windows_pdf_check_is_a_no_op_els
assert!(require_windows_pdf().is_ok());
}
+/// A 500 × 1000 pt document (72 ppi) on A3 (841.89 × 1190.55 pt): its height sets the fit.
+fn a3_layout(extra: Value) -> Result<PrintLayout> {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 500, "height": 1000, "resolution": 72})).unwrap();
+ let mut p = json!({"paper": "a3", "scaleToFit": true});
+ if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
+ p.extend(extra.clone());
+ }
+ layout(&s.active().unwrap().doc, &p, "file.print")
+}
+
+#[test]
+fn scale_to_fit_fills_a_borderless_printable_area() {
+ let (pw, ph) = (841.89, 1190.55);
+ // Without a printable area, the fixed 18 pt margin stays (CUPS, PDF).
+ let l = a3_layout(json!({})).unwrap();
+ assert!((l.scale - (ph - 36.0) / 1000.0).abs() < 1e-9, "{l:?}");
+ // Borderless: the driver reports the whole sheet (#7782: a Canon PRO-1000 reports its A3 as
+ // 842.29 × 1191.14 pt), and the image reaches the paper's edges.
+ let l = a3_layout(json!({"printable": [0.0, 0.0, 842.29, 1191.14]})).unwrap();
+ assert!((l.scale - ph / 1000.0).abs() < 1e-9, "{l:?}");
+ let (x, y, w, h) = l.rect;
+ assert!(y.abs() < 1e-9 && (h - ph).abs() < 1e-9 && (x - (pw - w) / 2.0).abs() < 1e-9, "{l:?}");
+}
+
+#[test]
+fn scale_to_fit_stays_inside_an_uneven_printable_area() {
+ let (pw, ph) = (841.89, 1190.55);
+ // 17 pt left and right, 14 pt at the top, 48 pt at the bottom (from the top-left, as
+ // `file.print.page` reports it). The layout's rect has its origin at the bottom-left.
+ let l = a3_layout(json!({"printable": [17.0, 14.0, pw - 34.0, ph - 62.0]})).unwrap();
+ assert!((l.scale - (ph - 62.0) / 1000.0).abs() < 1e-9, "{l:?}");
+ let (x, y, w, h) = l.rect;
+ assert!((y - 48.0).abs() < 1e-9 && (y + h - (ph - 14.0)).abs() < 1e-9, "fills the printable height: {l:?}");
+ assert!((x - (pw - w) / 2.0).abs() < 1e-9, "centred between equal side margins: {l:?}");
+ // Crop and registration marks keep their 36 pt inset, inside the printable area.
+ let l = a3_layout(json!({"printable": [17.0, 14.0, pw - 34.0, ph - 62.0], "cornerCropMarks": true})).unwrap();
+ assert!((l.scale - (ph - 62.0 - 72.0) / 1000.0).abs() < 1e-9, "{l:?}");
+ assert!((l.rect.1 - 84.0).abs() < 1e-9, "{l:?}");
+ // Scale to fit off: the printable area changes nothing.
+ let l = a3_layout(json!({"printable": [17.0, 14.0, pw - 34.0, ph - 62.0], "scaleToFit": false})).unwrap();
+ assert_eq!(l, a3_layout(json!({"scaleToFit": false})).unwrap());
+}
+
+#[test]
+fn a_bad_printable_area_is_refused() {
+ let portrait = json!([0.0, 0.0, 842.29, 1191.14]);
+ for bad in [
+ json!([0, 0, 100]),
+ json!([0, 0, 0, 100]),
+ json!([0, 0, 100, -5]),
+ json!("whole"),
+ json!([2000, 0, 100, 100]),
+ json!([0, "oops", 0, 842.29, 1191.14]),
+ json!([0, 0, 842.29, null]),
+ ] {
+ assert!(a3_layout(json!({ "printable": bad })).is_err(), "{bad}");
+ }
+ // A portrait sheet's area on a landscape layout is another paper, not a rounding error.
+ assert!(a3_layout(json!({"printable": portrait, "orientation": "landscape"})).is_err());
+}
+
+#[test]
+fn emulsion_down_fits_the_mirrored_printable_area() {
+ let (pw, ph) = (841.89, 1190.55);
+ // 10 pt on the left, 40 pt on the right of the sheet as the driver sees it. The page is
+ // mirrored as it prints, so the image box (before mirroring) must fit the mirror image.
+ // A wide image, so the printable width sets the fit.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 1000, "height": 500, "resolution": 72})).unwrap();
+ let p = json!({"paper": "a3", "scaleToFit": true, "printable": [10.0, 0.0, pw - 50.0, ph], "emulsionDown": true});
+ let l = layout(&s.active().unwrap().doc, &p, "file.print").unwrap();
+ let (x, _, w, _) = l.rect;
+ let printed = (pw - x - w, pw - x);
+ assert!(printed.0 >= 10.0 - 1e-9 && printed.1 <= pw - 40.0 + 1e-9, "printed at {printed:?}: {l:?}");
+}
+
+/// A native print fits only the driver's area: one the caller passed is dropped when the
+/// driver can't give one for this paper (no such paper here, or no driver at all).
+#[test]
+fn a_native_print_drops_a_printable_area_the_driver_did_not_give() {
+ let p = with_driver_printable(&json!({"paper": [500.0, 500.0], "printable": [0.0, 0.0, 100.0, 100.0], "scaleToFit": true}));
+ assert!(p.get("printable").is_none(), "{p}");
+ assert_eq!(p["paper"], json!([500.0, 500.0]));
+}
+
+#[test]
+fn a_print_uses_the_printable_area_but_does_not_remember_it() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 500, "height": 1000, "resolution": 72})).unwrap();
+ let r = s.execute("file.print", json!({"paper": "a3", "scaleToFit": true, "printable": [0.0, 0.0, 842.29, 1191.14], "dryRun": true})).unwrap();
+ assert!((r["scale"].as_f64().unwrap() - 119.055).abs() < 1e-6, "{r}");
+ // The next print (Print One Copy, or the dialog on another printer or to PDF) reads its own.
+ let last = last_print(&s).unwrap();
+ assert!(last.get("printable").is_none() && last["scaleToFit"] == true, "{last}");
+}
+
+#[test]
+fn a_rejected_printable_area_fails_the_print_and_changes_nothing() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 500, "height": 1000, "resolution": 72})).unwrap();
+ s.execute("file.print", json!({"paper": "a3", "scale": 50, "dryRun": true})).unwrap();
+ let before = (last_print(&s), s.prefs.get().dialogs.get(REMEMBERED).cloned(), s.active().unwrap().doc.clone());
+ for printable in [json!([2000, 0, 100, 100]), json!([0, "oops", 0, 842.29, 1191.14])] {
+ let r = s.execute("file.print", json!({"paper": "a3", "scaleToFit": true, "printable": printable, "dryRun": true}));
+ assert!(r.is_err(), "{printable}: {r:?}");
+ }
+ assert!(before == (last_print(&s), s.prefs.get().dialogs.get(REMEMBERED).cloned(), s.active().unwrap().doc.clone()));
+ // A print at a manual scale doesn't read the area, so a stale one doesn't fail it.
+ let r = s.execute("file.print", json!({"paper": "a3", "scale": 50, "printable": [0.0, 0.0, 842.29, 1191.14], "orientation": "landscape", "dryRun": true}));
+ assert!(r.is_ok(), "{r:?}");
+ // Marks need room only to fit: a small manual scale in a 60 pt-wide area prints.
+ let r = s.execute("file.print", json!({"paper": "a3", "scale": 5, "printable": [0, 0, 60, 1191.14], "cornerCropMarks": true, "dryRun": true}));
+ assert!(r.is_ok(), "{r:?}");
+ let r = s.execute("file.print", json!({"paper": "a3", "scaleToFit": true, "printable": [0, 0, 60, 1191.14], "cornerCropMarks": true, "dryRun": true}));
+ assert!(r.is_err(), "{r:?}");
+}
+
+#[test]
+fn package_of_a_document_named_after_a_windows_device_is_written() {
+ // On Windows a folder named `nul` is the NUL device: the save failed with "path not found".
+ let dir = tmp("package-device-name");
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8, "name": "nul.psd"})).unwrap();
+ let r = s.execute("file.package", json!({"dir": format!("{dir}/pkg")})).unwrap();
+ assert_eq!(r["folder"].as_str().unwrap(), format!("{dir}/pkg/nul_"));
+ let document = r["document"].as_str().unwrap();
+ assert!(document.ends_with("pkg/nul_/nul_.pcraft"), "{document}");
+ assert!(std::path::Path::new(document).is_file());
+}
++
+ /// A dry-run print to `name`.pdf with `extra` params; returns the result and the PDF content stream.
+ fn print_with(s: &mut Session, dir: &str, name: &str, extra: Value) -> (Value, Vec<u8>) {
+ let mut p = json!({"output": format!("{dir}/{name}.pdf"), "dryRun": true, "paper": "a4", "center": false, "left": 1.0, "top": 1.0});
+ for (k, v) in extra.as_object().unwrap() {
+ p[k] = v.clone();
+ }
+ let r = s.execute("file.print", p).unwrap();
+ let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap();
+ (r, pdf)
+ }
+
+ #[test]
+ fn zero_bleed_prints_exactly_as_before() {
+ let mut s = session("rgb", 8);
+ let dir = tmp("bleed-zero");
+ let (plain, a) = print_with(&mut s, &dir, "plain", json!({"cornerCropMarks": true}));
+ let (zero, b) = print_with(&mut s, &dir, "zero", json!({"cornerCropMarks": true, "bleed": 0.0}));
+ assert_eq!(a, b, "bleed 0 must not change a single byte");
+ assert_eq!(plain["bleed"], 0.0);
+ assert_eq!(zero["bleed"], 0.0);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn bleed_puts_corner_crop_marks_on_the_trim_line_outside_the_image() {
+ let mut s = session("rgb", 8);
+ let dir = tmp("bleed");
+ let (r, pdf) = print_with(&mut s, &dir, "bleed", json!({"cornerCropMarks": true, "centerCropMarks": true, "bleed": 0.125}));
+ assert_eq!(r["bleed"], 0.125);
+ let rect: Vec<f64> = r["imageRect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
+ let c = pdf_content(&pdf);
+ // Bottom-left corner (PDF is bottom-up): the horizontal mark runs left from 6 pt outside the
+ // image, 9 pt (0.125 in) above the image's bottom edge; the vertical one 9 pt right of its left edge.
+ assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x - 6.0, y + 9.0, x - 24.0, y + 9.0)), "{c}");
+ assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + 9.0, y - 6.0, x + 9.0, y - 24.0)), "{c}");
+ // Top-right corner, mirrored.
+ assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + w + 6.0, y + h - 9.0, x + w + 24.0, y + h - 9.0)), "{c}");
+ assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + w - 9.0, y + h + 6.0, x + w - 9.0, y + h + 24.0)), "{c}");
+ // Centre crop marks are on the midlines, which a symmetric bleed does not move.
+ assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + w / 2.0, y - 6.0, x + w / 2.0, y - 24.0)), "{c}");
+ // Print One Copy repeats the last print, bleed included.
+ let again = s.execute("file.printOneCopy", json!({"output": format!("{dir}/again.pdf"), "dryRun": true})).unwrap();
+ assert_eq!(again["bleed"], 0.125);
+ // The image box itself is unchanged: bleed moves marks, not pixels.
+ let (plain, _) = print_with(&mut s, &dir, "plain", json!({"cornerCropMarks": true}));
+ assert_eq!(plain["imageRect"], r["imageRect"]);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn bleed_without_corner_crop_marks_changes_nothing() {
+ let mut s = session("rgb", 8);
+ let dir = tmp("bleed-nomarks");
+ let (_, a) = print_with(&mut s, &dir, "plain", json!({"registrationMarks": true}));
+ let (r, b) = print_with(&mut s, &dir, "bleed", json!({"registrationMarks": true, "bleed": 0.1}));
+ assert_eq!(a, b);
+ assert_eq!(r["bleed"], 0.0);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn bad_bleed_is_an_error_not_a_panic() {
+ let mut s = session("rgb", 8);
+ // The test document prints 300 × 150 pt, so 1.05 in (75.6 pt) leaves no trim box.
+ for bleed in [json!(-0.1), json!("0.1"), json!(true), json!([0.1]), json!(1.05), json!(1e308)] {
+ let r = s.execute("file.print", json!({"dryRun": true, "send": false, "output": "", "cornerCropMarks": true, "bleed": bleed}));
+ assert!(matches!(r, Err(EngineError::BadParams { .. })), "bleed {bleed}: {r:?}");
+ }
+ }
+
+ #[test]
+ fn print_strings_keep_winansi_accents_and_punctuation() {
+ assert_eq!(pdf_string("Café – résumé"), r"(Caf\351 \226 r\351sum\351)");
+ assert_eq!(pdf_string("€ ‘quote’ “double” • Œœ Šš Žž Ÿ"), r"(\200 \221quote\222 \223double\224 \225 \214\234 \212\232 \216\236 \237)");
+ assert_eq!(pdf_string("é7"), r"(\3517)", "octal escapes must have three digits before a digit");
+ }
+
+ #[test]
+ fn print_strings_keep_pdf_delimiters_safe_and_fallback_bounded() {
+ assert_eq!(pdf_string(r"a(b)\c"), r"(a\(b\)\\c)");
+ assert_eq!(pdf_string("\n\r\t\0\u{7f}\u{81}中😀"), "(????????)");
+ assert_eq!(pdf_string(""), "()");
+ }
+
+ #[test]
+ fn printed_pdf_uses_winansi_for_labels_and_descriptions() {
+ let mut page = page_of(3, vec![255; 6], false);
+ page.label = Some("Café – résumé.psd".into());
+ page.description = Some("Price: €20 (proof)".into());
+ let pdf = print_pdf(&page);
+ assert!(String::from_utf8_lossy(&pdf).contains("/Encoding /WinAnsiEncoding"));
+ let content = pdf_content(&pdf);
+ assert!(content.contains(r"(Caf\351 \226 r\351sum\351.psd) Tj"), "{content}");
+ assert!(content.contains(r"(Price: \20020 \(proof\)) Tj"), "{content}");
+ assert!(content.is_ascii(), "encoded bytes are escaped, never UTF-8 text operands");
+ }
diff --cc docs/file-format-parity.md
index 6e71889dd,db18c205a..6de0d0319
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@@ -21,11 -21,11 +21,11 @@@ XL are missing (gap G10). Remaining: 30
| Format | Photoshop | PhotoCraft read | PhotoCraft write | Fidelity and tests |
|---|---|---|---|---|
- | PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (45 mapped, among them Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
+ | PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (45 mapped, among them Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending, each layer's XMP packet (`layer.xmpMetadata`). Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 |
| Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) |
-| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders, including Photoshop mixed-order type blocks (#4758); undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) |
-| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) |
+| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders, including Photoshop mixed-order type blocks (#4758); LZW/ZIP for scripted saves by `tiffCompression`; undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) |
+| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); Save As and Save a Copy ask JPEG Options: Quality 0–12, starting at the opened file's quality or else the Export preference, and Baseline ("Standard") / Baseline Optimized / Progressive; scripts pass `quality`/`jpegFormat`, the CLI `--jpeg-format` (FILE-215-19). Baseline Optimized fits the Huffman tables only at 4:4:4 (Gray, CMYK) or progressive: RGB is written 4:2:0, which zune-jpeg 0.5.15 decodes wrongly with fitted tables, as in Save for Web. No Matte or size preview |
| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) |
| GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done |
| BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode and Indexed Color documents save as palette BMPs (no transparency) |
diff --cc docs/target-app-parity.md
index 1e6cd36bb,4c06ff651..62fae2389
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# PhotoCraft vs Adobe Photoshop: target-app parity
- > **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-21 · **Change:** minor (compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026
-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-18 · **Change:** minor (Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; Print › Functions › Bleed through `file.print`; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026
++> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-21 · **Change:** minor (compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026
The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The
one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md);