mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Integration: track t12
# Conflicts: # contributors/people.toml # crates/compose/src/lib.rs # crates/compose/src/tests.rs # crates/engine/src/print_cmds.rs # crates/engine/src/print_cmds/tests.rs # docs/target-app-parity.md
This commit is contained in:
commit
576ba0e02b
48 files changed
+2238
-219
No files matched your search
Generated
-4
@@ -4716,7 +4716,6 @@ dependencies = [
|
||||
"photocraft-doc",
|
||||
"photocraft-engine",
|
||||
"photocraft-format",
|
||||
"photocraft-geom",
|
||||
"photocraft-io",
|
||||
"rmcp",
|
||||
"rustix 1.1.5",
|
||||
@@ -5018,9 +5017,6 @@ name = "photocraft-testkit"
|
||||
version = "0.12.0"
|
||||
dependencies = [
|
||||
"memory-stats",
|
||||
"photocraft-color",
|
||||
"photocraft-geom",
|
||||
"photocraft-raster",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
|
||||
@@ -524,6 +524,13 @@ fn main() -> eframe::Result {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let single_instance = {
|
||||
let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok();
|
||||
// A variable documented as the equivalent of a per-launch flag counts as that flag: a
|
||||
// launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it
|
||||
// keeps its own process instead of handing its files over and being ignored.
|
||||
// Folded in here, inside the block that only non-macOS builds compile, so the binding
|
||||
// above keeps its `mut` off macOS, where nothing is folded in.
|
||||
let mut launch_options = launch_options;
|
||||
launch_options.extend_from_slice(&single_instance::env_launch_options());
|
||||
let context = single_instance::LaunchContext {
|
||||
per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform,
|
||||
new_instance_flag: new_instance,
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Native platform services: file dialogs (rfd), filesystem, codecs.
|
||||
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image, SampleType as CS};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Layer, Size};
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_format::RecoveryStore;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, Recoverable, Services};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::future::Future;
|
||||
@@ -471,6 +469,17 @@ fn recovery_services(dir: Option<PathBuf>) -> Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// The OS clipboard read and write run under the crash guard, like Open and Export (#7582): a
|
||||
/// panic in arboard, or in decoding a copied file, becomes the paste's (or copy's) error and the
|
||||
/// app keeps its documents.
|
||||
fn guarded_clipboard_get(mut read: impl FnMut() -> Result<Option<(u32, u32, Vec<u8>)>, String> + 'static) -> photocraft_ui_egui::ClipboardGetFn {
|
||||
Box::new(move || crate::crash_guard::guard("Paste", &mut read))
|
||||
}
|
||||
|
||||
fn guarded_clipboard_set(mut write: impl FnMut(u32, u32, &[u8]) -> Result<(), String> + 'static) -> photocraft_ui_egui::ClipboardSetFn {
|
||||
Box::new(move |w: u32, h: u32, px: &[u8]| crate::crash_guard::guard("Copy", || write(w, h, px)))
|
||||
}
|
||||
|
||||
/// The pixels to paste when the clipboard holds copied files rather than an image (Copy in
|
||||
/// Files, Finder or Explorer puts paths on the clipboard, #338): the first file that decodes,
|
||||
/// upright, as RGBA8. Files that aren't images are skipped after reading only their header.
|
||||
@@ -616,7 +625,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
|
||||
beep: Some(platform_beep),
|
||||
clipboard_set_image: Some({
|
||||
let clip = clip.clone();
|
||||
Box::new(move |w: u32, h: u32, px: &[u8]| {
|
||||
guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| {
|
||||
let mut slot = clip.try_borrow_mut().map_err(|_| "clipboard is busy".to_string())?;
|
||||
let cb = match slot.as_mut() {
|
||||
Some(c) => c,
|
||||
@@ -628,7 +637,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
|
||||
clipboard_get_image: Some({
|
||||
let clip = clip.clone();
|
||||
let unreadable = clip_unreadable.clone();
|
||||
Box::new(move || {
|
||||
guarded_clipboard_get(move || {
|
||||
let mut slot = clip.try_borrow_mut().map_err(|_| "clipboard is busy".to_string())?;
|
||||
let cb = match slot.as_mut() {
|
||||
Some(c) => c,
|
||||
@@ -705,68 +714,6 @@ fn platform_beep() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Flat-image import via photocraft-codecs (kept for reference/tests; the app uses photocraft-io).
|
||||
#[allow(dead_code)]
|
||||
pub fn import_flat(name: &str, bytes: &[u8]) -> Result<Document, String> {
|
||||
let img = photocraft_codecs::decode(bytes).map_err(|e| e.to_string())?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
let depth = match img.sample_type() {
|
||||
CS::U8 => SampleType::U8,
|
||||
CS::U16 => SampleType::U16,
|
||||
_ => SampleType::F32,
|
||||
};
|
||||
let gray = matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA);
|
||||
let cmyk = matches!(img.layout(), ChannelLayout::Cmyk | ChannelLayout::CmykA);
|
||||
let mode = if gray {
|
||||
ColorMode::Grayscale
|
||||
} else if cmyk {
|
||||
ColorMode::Cmyk
|
||||
} else {
|
||||
ColorMode::Rgb
|
||||
};
|
||||
let target = match mode {
|
||||
ColorMode::Grayscale => ChannelLayout::GrayA,
|
||||
ColorMode::Cmyk => ChannelLayout::CmykA,
|
||||
_ => ChannelLayout::Rgba,
|
||||
};
|
||||
let sample = match depth {
|
||||
SampleType::U8 => CS::U8,
|
||||
SampleType::U16 => CS::U16,
|
||||
SampleType::F32 => CS::F32,
|
||||
};
|
||||
let conv = img.convert(target, sample);
|
||||
let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or(name.to_string());
|
||||
let mut doc = Document::new(stem, Size::new(w, h), mode, depth);
|
||||
doc.icc_profile = img.icc.clone().map(std::sync::Arc::new);
|
||||
if let Some((x, _)) = img.meta.dpi {
|
||||
doc.resolution_dpi = x;
|
||||
}
|
||||
let mut layer = Layer::raster("Background", doc.pixel_format());
|
||||
let data = conv.to_normalized();
|
||||
layer.surface_mut().ok_or("new raster layer has no pixels")?.write_region(Rect::from_xywh(0, 0, w, h), &data);
|
||||
doc.layers.push(layer);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn export_flat(doc: &Document, path: &str) -> Result<Vec<u8>, String> {
|
||||
let format = photocraft_codecs::from_extension(path).ok_or_else(|| format!("unknown file type for {path}"))?;
|
||||
let buf = photocraft_compose::flatten(doc);
|
||||
let (w, h) = (buf.rect.width(), buf.rect.height());
|
||||
let data: Vec<f32> = buf.px.iter().flat_map(|p| *p).collect();
|
||||
let img = match doc.depth {
|
||||
SampleType::U8 => Image::from_u8(w, h, ChannelLayout::Rgba, buf.to_rgba8().pixels),
|
||||
SampleType::U16 => Image::from_u16(w, h, ChannelLayout::Rgba, &data.iter().map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).collect::<Vec<_>>()),
|
||||
SampleType::F32 => Image::from_f32(w, h, ChannelLayout::Rgba, &data),
|
||||
}
|
||||
.map_err(|e| e.to_string())?;
|
||||
let img = match &doc.icc_profile {
|
||||
Some(icc) if doc.mode == ColorMode::Rgb => img.with_icc(Some((**icc).clone())),
|
||||
_ => img,
|
||||
};
|
||||
photocraft_codecs::encode(&img, format, &EncodeOptions::default()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1427,4 +1374,29 @@ mod tests {
|
||||
assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255])));
|
||||
assert!(image_from_files(&[bin]).is_none());
|
||||
}
|
||||
|
||||
/// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is
|
||||
/// the paste's error in the status bar, not a crash: the document stays and the next paste
|
||||
/// works. The same for a panic while writing it.
|
||||
#[test]
|
||||
fn a_panicking_clipboard_read_is_reported_not_a_crash() {
|
||||
let panics = Rc::new(Cell::new(true));
|
||||
let p = panics.clone();
|
||||
let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) });
|
||||
let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() });
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
let layers = app.session.active().unwrap().doc.layers.len();
|
||||
|
||||
let error = app.run("edit.paste", json!({})).unwrap_err();
|
||||
assert!(error.contains("Paste failed"), "{error}");
|
||||
assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status);
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged");
|
||||
|
||||
panics.set(false);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works");
|
||||
|
||||
let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug"));
|
||||
assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
use photocraft_color::Color;
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::Size;
|
||||
use photocraft_format::{Autosaver, RecoveryEntry, SaveOptions, list_recovery};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
|
||||
@@ -129,10 +129,71 @@ pub struct LaunchContext<'a> {
|
||||
pub control: bool,
|
||||
/// Paths that aren't valid Unicode: this launch reports them.
|
||||
pub unreadable_paths: bool,
|
||||
/// Options that only apply to the process they're given to (`--safe-gpu`, …).
|
||||
/// Options that only apply to the process they're given to (`--safe-gpu`, …), including the
|
||||
/// ones this launch's environment sets (see [`env_launch_options`]).
|
||||
pub launch_options: &'a [&'static str],
|
||||
}
|
||||
|
||||
/// Variables documented as the equivalent of a per-launch flag, each with the flag it stands for
|
||||
/// (`PHOTOCRAFT_PRESENT_MODE` is `--present-mode`) and the rule that says whether its value asks for
|
||||
/// that option at all. Setting one asks for the same thing as giving the flag, so it belongs to this
|
||||
/// process alone.
|
||||
const ENV_LAUNCH_OPTIONS: [(&str, &str, ValueRule); 6] = [
|
||||
("PHOTOCRAFT_PRESENT_MODE", "--present-mode", present_mode_is_on),
|
||||
("PHOTOCRAFT_FRAME_LATENCY", "--frame-latency", frame_latency_is_on),
|
||||
("PHOTOCRAFT_STROKE_TRACE", "--stroke-trace", stroke_trace_is_on),
|
||||
("PHOTOCRAFT_IN_WINDOW_MENUS", "--in-window-menus", flag_is_on),
|
||||
("PHOTOCRAFT_AUTOMATION_READ_ROOT", "--automation-read-root", path_is_set),
|
||||
("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "--automation-write-root", path_is_set),
|
||||
];
|
||||
|
||||
/// Whether a variable's value asks this launch for its own option. Each rule matches how that
|
||||
/// variable is read where it takes effect, so a value ignored there keeps no process here either.
|
||||
type ValueRule = fn(&str) -> bool;
|
||||
|
||||
/// A value `presentation::parse` accepts, handed over as written: it trims, treats empty as unset and
|
||||
/// warns and ignores anything it does not recognise, so an unrecognised `PHOTOCRAFT_PRESENT_MODE`
|
||||
/// changes nothing there and so needs no process of its own here.
|
||||
fn present_mode_is_on(value: &str) -> bool {
|
||||
crate::presentation::parse(Some(value), None).0.mode.is_some()
|
||||
}
|
||||
|
||||
/// [`present_mode_is_on`] for `PHOTOCRAFT_FRAME_LATENCY`, which takes `1` to `3`.
|
||||
fn frame_latency_is_on(value: &str) -> bool {
|
||||
crate::presentation::parse(None, Some(value)).0.latency.is_some()
|
||||
}
|
||||
|
||||
/// Anything except `""`, `0`, `off` and `false`, which is how `StrokeTrace::from_value` reads it: the
|
||||
/// rest is a stderr summary or a CSV path. It trims, so `" 0 "` is off there and off here.
|
||||
fn stroke_trace_is_on(value: &str) -> bool {
|
||||
!matches!(value.trim(), "" | "0" | "off" | "false")
|
||||
}
|
||||
|
||||
/// Any value except empty and exactly `0`, as `main.rs` reads `PHOTOCRAFT_IN_WINDOW_MENUS` - which is
|
||||
/// why `off` means on there, why this rule is not shared with the stroke trace above, and why it does
|
||||
/// not trim: a padded `" 0 "` enables the menus there, so it keeps a process here too.
|
||||
fn flag_is_on(value: &str) -> bool {
|
||||
!value.is_empty() && value != "0"
|
||||
}
|
||||
|
||||
/// A path is an option; an empty value is no path. Not trimmed: a path may end in a space. An empty
|
||||
/// root is read as no root unless `--control` is given, and that flag keeps its own process already.
|
||||
fn path_is_set(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
}
|
||||
|
||||
/// The per-process options this launch's environment sets, named as the flags they stand for. A
|
||||
/// launch that sets only variables would otherwise hand its files to the running instance, which
|
||||
/// never sees the override, and exit.
|
||||
pub fn env_launch_options() -> Vec<&'static str> {
|
||||
env_launch_options_from(|name| std::env::var_os(name))
|
||||
}
|
||||
|
||||
/// [`env_launch_options`] with the reader given, so the rule is testable without the environment.
|
||||
fn env_launch_options_from(get: impl Fn(&str) -> Option<std::ffi::OsString>) -> Vec<&'static str> {
|
||||
ENV_LAUNCH_OPTIONS.iter().filter(|(name, _, is_on)| get(name).is_some_and(|v| is_on(&v.to_string_lossy()))).map(|(_, flag, _)| *flag).collect()
|
||||
}
|
||||
|
||||
/// Why this launch runs as its own instance, or `None` to take part in single-instance.
|
||||
pub fn skip_reason(c: &LaunchContext) -> Option<String> {
|
||||
if !c.per_user_settings {
|
||||
@@ -915,4 +976,46 @@ mod tests {
|
||||
assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None);
|
||||
assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None);
|
||||
}
|
||||
|
||||
/// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch
|
||||
/// that sets only variables has per-process options, so it keeps its own process rather than
|
||||
/// handing its files to the running instance, which never sees the override.
|
||||
#[test]
|
||||
fn an_environment_override_counts_as_a_process_option() {
|
||||
let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into()));
|
||||
assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec!["--present-mode"]);
|
||||
assert_eq!(
|
||||
with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]),
|
||||
vec!["--stroke-trace", "--automation-write-root"]
|
||||
);
|
||||
// Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way
|
||||
// it is read where it takes effect, not by one rule shared across all six.
|
||||
assert!(with(&[]).is_empty());
|
||||
assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "0"), ("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty());
|
||||
// The trace is off at `off` and `false` as well, and a value the presentation parser rejects
|
||||
// is ignored there, so neither keeps a process of its own here.
|
||||
assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty());
|
||||
assert!(with(&[("PHOTOCRAFT_AUTOMATION_READ_ROOT", "")]).is_empty());
|
||||
// Spaces are part of the value only where the reader keeps them: the trace and the two
|
||||
// presentation values are trimmed where they take effect, the menu flag and a path are not.
|
||||
assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), vec!["--present-mode", "--stroke-trace"]);
|
||||
assert_eq!(
|
||||
with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", " 0 "), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", " /tmp/out ")]),
|
||||
vec!["--in-window-menus", "--automation-write-root"]
|
||||
);
|
||||
// A whitespace-only menu value is not empty, so it enables the menus there and here too.
|
||||
assert_eq!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", " ")]), vec!["--in-window-menus"]);
|
||||
// `PHOTOCRAFT_IN_WINDOW_MENUS=off` means menus in the window there, so it means it here too.
|
||||
assert_eq!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "off")]), vec!["--in-window-menus"]);
|
||||
let base = LaunchContext {
|
||||
per_user_settings: true,
|
||||
new_instance_flag: false,
|
||||
new_instance_env: None,
|
||||
control: false,
|
||||
unreadable_paths: false,
|
||||
launch_options: &[],
|
||||
};
|
||||
let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base });
|
||||
assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}");
|
||||
}
|
||||
}
|
||||
@@ -226,3 +226,7 @@ sync_github_name = true
|
||||
|
||||
[people.giang17]
|
||||
real_name = "Giang Nguyen"
|
||||
sync_github_name = true
|
||||
|
||||
[people.aqibmohd271]
|
||||
sync_github_name = true
|
||||
@@ -10,7 +10,6 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
photocraft-geom = { workspace = true }
|
||||
photocraft-doc = { workspace = true }
|
||||
photocraft-compose = { workspace = true }
|
||||
photocraft-codecs = { workspace = true }
|
||||
|
||||
@@ -120,6 +120,29 @@ pub fn read_sample(bytes: &[u8], sample: SampleType, index: usize) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`read_sample`] for the `out.len()` samples from sample index `start` on, matching the sample
|
||||
/// type once instead of per sample.
|
||||
pub fn read_samples(bytes: &[u8], sample: SampleType, start: usize, out: &mut [f32]) {
|
||||
let end = start + out.len();
|
||||
match sample {
|
||||
SampleType::U8 => {
|
||||
for (o, b) in out.iter_mut().zip(&bytes[start..end]) {
|
||||
*o = *b as f32 / 255.0;
|
||||
}
|
||||
}
|
||||
SampleType::U16 => {
|
||||
for (o, b) in out.iter_mut().zip(bytes[start * 2..end * 2].as_chunks::<2>().0) {
|
||||
*o = u16::from_ne_bytes(*b) as f32 / 65535.0;
|
||||
}
|
||||
}
|
||||
SampleType::F32 => {
|
||||
for (o, b) in out.iter_mut().zip(bytes[start * 4..end * 4].as_chunks::<4>().0) {
|
||||
*o = f32::from_ne_bytes(*b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a normalised f32 sample; integer types are clamped and rounded.
|
||||
#[inline]
|
||||
pub fn write_sample(bytes: &mut [u8], sample: SampleType, index: usize, v: f32) {
|
||||
|
||||
+141
-37
@@ -233,7 +233,8 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth
|
||||
}
|
||||
}
|
||||
Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => {
|
||||
map_rgb(buf, |c| std::array::from_fn(|ch| color_balance_channel([*shadows, *midtones, *highlights], *preserve_luminosity, ch, c[ch])))
|
||||
let curves = BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity);
|
||||
map_rgb(buf, |c| std::array::from_fn(|ch| curves[ch].eval(c[ch])))
|
||||
}
|
||||
Adjustment::SelectiveColor { relative, adjustments } => map_rgb(buf, |c| selective_color(c, *relative, adjustments)),
|
||||
Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => {
|
||||
@@ -812,48 +813,89 @@ pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f
|
||||
/// - Preserve Luminosity on: each channel's black point is (max − own) shadows levels, its white
|
||||
/// point 255 − (own − min) highlights levels, and m = own − (max + min) / 2 midtones.
|
||||
///
|
||||
/// A gamma > 1 starts with slope 2^gamma at black ([`balance_gamma`]: up to 18 of 255 brighter
|
||||
/// A gamma > 1 starts with slope 2^gamma at black (up to 18 of 255 brighter
|
||||
/// near black without it). When the black point reaches the white point, input
|
||||
/// at or above the white point is white and the rest black.
|
||||
pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 {
|
||||
let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 }));
|
||||
let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0);
|
||||
let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]);
|
||||
let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]);
|
||||
let (black, white, m) = if preserve_luminosity {
|
||||
(max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0)
|
||||
} else {
|
||||
((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0)
|
||||
};
|
||||
let (b, w) = (black / 255.0, 1.0 - white / 255.0);
|
||||
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
if v >= w {
|
||||
return 1.0;
|
||||
}
|
||||
if v <= b {
|
||||
return 0.0;
|
||||
}
|
||||
balance_gamma((v - b) / (w - b), 2f32.powf(m / 100.0))
|
||||
BalanceCurve::new(tones, preserve_luminosity, ch).eval(v)
|
||||
}
|
||||
|
||||
/// The midtone gamma of Color Balance's per-channel Levels (`u` in 0..1): `u^(1/gamma)`, except
|
||||
/// that a gamma > 1 (which would start with infinite slope) starts at slope 2^gamma and joins the
|
||||
/// power curve in a cubic Hermite at twice the input where that line meets it (Photoshop,
|
||||
/// measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255).
|
||||
fn balance_gamma(u: f32, gamma: f32) -> f32 {
|
||||
let e = 1.0 / gamma.max(0.01);
|
||||
let power = u.powf(e);
|
||||
if gamma <= 1.0 {
|
||||
return power;
|
||||
/// One channel's Color Balance curve (see [`color_balance_channel`]), with the terms that don't
|
||||
/// depend on the sample worked out once rather than per pixel.
|
||||
pub struct BalanceCurve {
|
||||
/// Input black and white points.
|
||||
b: f32,
|
||||
w: f32,
|
||||
/// The power curve's exponent, 1 / gamma.
|
||||
e: f32,
|
||||
/// The Hermite join of a gamma > 1.
|
||||
knee: Option<Knee>,
|
||||
}
|
||||
|
||||
/// Where a gamma > 1 curve's Hermite join ends (`u0`), its starting slope 2^gamma (`s0`), and the
|
||||
/// power curve's value (`p`) and slope (`d`) at `u0`.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Knee {
|
||||
u0: f32,
|
||||
s0: f32,
|
||||
p: f32,
|
||||
d: f32,
|
||||
}
|
||||
|
||||
impl BalanceCurve {
|
||||
/// The red, green and blue curves.
|
||||
pub fn rgb(tones: [[f32; 3]; 3], preserve_luminosity: bool) -> [Self; 3] {
|
||||
std::array::from_fn(|ch| Self::new(tones, preserve_luminosity, ch))
|
||||
}
|
||||
let s0 = 2f32.powf(gamma);
|
||||
let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0);
|
||||
if u0.is_nan() || u0 <= 0.0 || u >= u0 {
|
||||
return power;
|
||||
|
||||
/// The curve of channel `ch` (0 red, 1 green, 2 blue) for the shadows, midtones and
|
||||
/// highlights slider triples `tones`.
|
||||
pub fn new(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize) -> Self {
|
||||
let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 }));
|
||||
let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0);
|
||||
let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]);
|
||||
let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]);
|
||||
let (black, white, m) = if preserve_luminosity {
|
||||
(max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0)
|
||||
} else {
|
||||
((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0)
|
||||
};
|
||||
// The midtone gamma of the channel's Levels: `u^(1/gamma)`, except that a gamma > 1
|
||||
// (which would start with infinite slope) starts at slope 2^gamma and joins the power
|
||||
// curve in a cubic Hermite at twice the input where that line meets it (Photoshop,
|
||||
// measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255).
|
||||
let gamma = 2f32.powf(m / 100.0);
|
||||
let e = 1.0 / gamma.max(0.01);
|
||||
let knee = if gamma > 1.0 {
|
||||
let s0 = 2f32.powf(gamma);
|
||||
let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0);
|
||||
(!u0.is_nan() && u0 > 0.0).then(|| Knee { u0, s0, p: u0.powf(e), d: e * u0.powf(e - 1.0) })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Self { b: black / 255.0, w: 1.0 - white / 255.0, e, knee }
|
||||
}
|
||||
|
||||
/// The curve at `v` (0..1).
|
||||
pub fn eval(&self, v: f32) -> f32 {
|
||||
let (b, w) = (self.b, self.w);
|
||||
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
if v >= w {
|
||||
return 1.0;
|
||||
}
|
||||
if v <= b {
|
||||
return 0.0;
|
||||
}
|
||||
let u = (v - b) / (w - b);
|
||||
match self.knee {
|
||||
Some(Knee { u0, s0, p, d }) if u < u0 => {
|
||||
let t = u / u0;
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0)
|
||||
}
|
||||
_ => u.powf(self.e),
|
||||
}
|
||||
}
|
||||
let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0);
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans,
|
||||
@@ -924,7 +966,9 @@ fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) {
|
||||
#[inline]
|
||||
fn lut(table: &[f32], v: f32) -> f32 {
|
||||
let x = v.clamp(0.0, 1.0) * (table.len() - 1) as f32;
|
||||
let i = x.floor() as usize;
|
||||
// Never negative (NaN casts to 0, as its floor did), so truncating is `floor`, without the
|
||||
// libm call baseline x86-64 (no SSE4.1) makes for it.
|
||||
let i = x as usize;
|
||||
let j = (i + 1).min(table.len() - 1);
|
||||
let f = x - i as f32;
|
||||
table[i] * (1.0 - f) + table[j] * f
|
||||
@@ -1793,6 +1837,66 @@ mod tone_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_balance_curve_matches_the_per_sample_formula_bitwise() {
|
||||
// The curve works out its sample-independent terms once; this is the formula it replaced,
|
||||
// evaluated whole for every sample.
|
||||
fn per_sample(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 {
|
||||
let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 }));
|
||||
let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0);
|
||||
let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]);
|
||||
let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]);
|
||||
let (black, white, m) = if preserve_luminosity {
|
||||
(max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0)
|
||||
} else {
|
||||
((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0)
|
||||
};
|
||||
let (b, w) = (black / 255.0, 1.0 - white / 255.0);
|
||||
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
if v >= w {
|
||||
return 1.0;
|
||||
}
|
||||
if v <= b {
|
||||
return 0.0;
|
||||
}
|
||||
let (u, gamma) = ((v - b) / (w - b), 2f32.powf(m / 100.0));
|
||||
let e = 1.0 / gamma.max(0.01);
|
||||
let power = u.powf(e);
|
||||
if gamma <= 1.0 {
|
||||
return power;
|
||||
}
|
||||
let s0 = 2f32.powf(gamma);
|
||||
let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0);
|
||||
if u0.is_nan() || u0 <= 0.0 || u >= u0 {
|
||||
return power;
|
||||
}
|
||||
let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0);
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0)
|
||||
}
|
||||
let mut seed = 0x9e37_79b9_u32;
|
||||
let mut slider = || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
(seed % 241) as f32 - 120.0
|
||||
};
|
||||
let mut settings = vec![[[0.0; 3]; 3], [[f32::NAN, 1e9, -1e9]; 3], [[-100.0; 3], [100.0; 3], [100.0; 3]]];
|
||||
settings.extend((0..120).map(|_| std::array::from_fn(|_| std::array::from_fn(|_| slider()))));
|
||||
let samples: Vec<f32> = (0..=1024).map(|i| i as f32 / 1024.0).chain([-0.5, 1.5, f32::NAN, f32::INFINITY]).collect();
|
||||
for tones in settings {
|
||||
for preserve in [false, true] {
|
||||
for ch in [0, 1, 2, 7] {
|
||||
let curve = BalanceCurve::new(tones, preserve, ch);
|
||||
for &v in &samples {
|
||||
let (got, want) = (curve.eval(v), per_sample(tones, preserve, ch, v));
|
||||
assert_eq!(got.to_bits(), want.to_bits(), "{tones:?} {preserve} ch {ch} v {v}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_and_curves_apply_each_channel_before_the_master() {
|
||||
// These two affine tone adjustments describe the same mapping:
|
||||
|
||||
+87
-21
@@ -399,6 +399,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
|
||||
vector_masks: RenderVectorMasks::default(),
|
||||
fx_maps: Default::default(),
|
||||
fx_clip: Default::default(),
|
||||
fx_over_budget: false,
|
||||
tone_luts: prepare_tones(std::slice::from_ref(layer), 0),
|
||||
doc: None,
|
||||
layer_keys: Default::default(),
|
||||
@@ -771,6 +772,9 @@ struct Ctx<'a> {
|
||||
fx_maps: std::sync::Mutex<std::collections::HashMap<u64, (std::sync::Arc<effects::FxMaps>, bool)>>,
|
||||
/// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`].
|
||||
fx_clip: std::sync::Mutex<Option<Rect>>,
|
||||
/// The whole-region effect maps of this render's layers wouldn't fit in the effect cache
|
||||
/// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330).
|
||||
fx_over_budget: bool,
|
||||
/// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer.
|
||||
doc: Option<&'a Document>,
|
||||
/// Effect-map identities of this render's document layers (see [`LayerKeys`]).
|
||||
@@ -842,6 +846,7 @@ impl<'a> Ctx<'a> {
|
||||
vector_masks: RenderVectorMasks::default(),
|
||||
fx_maps: Default::default(),
|
||||
fx_clip: Default::default(),
|
||||
fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()),
|
||||
layer_keys: Default::default(),
|
||||
tone_luts: prepare_tones(&doc.layers, 0),
|
||||
}
|
||||
@@ -984,11 +989,41 @@ pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option<f32> {
|
||||
fn quantize(b: &mut Buffer, q: f32) {
|
||||
for p in &mut b.px {
|
||||
for v in p.iter_mut() {
|
||||
*v = (*v * q + 0.5).floor() / q;
|
||||
*v = branchless_floor(*v * q + 0.5) / q;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline
|
||||
/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample
|
||||
/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the
|
||||
/// loop vectorizes.
|
||||
#[inline]
|
||||
fn branchless_floor(x: f32) -> f32 {
|
||||
// From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the
|
||||
// nearest whole number; where that went up, step down.
|
||||
const WHOLE: f32 = 8_388_608.0;
|
||||
let a = x.abs();
|
||||
let r = ((a + WHOLE) - WHOLE).copysign(x);
|
||||
let r = if r > x { r - 1.0 } else { r };
|
||||
if a < WHOLE { r } else { x }
|
||||
}
|
||||
|
||||
/// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each
|
||||
/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`.
|
||||
fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator<Item = f32>, mode: BlendMode) {
|
||||
for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) {
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let s = [a[0], a[1], a[2]];
|
||||
// Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment
|
||||
// layers are Normal: no per-pixel mode dispatch for them.
|
||||
let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) };
|
||||
*b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]];
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic hash for Dissolve (document-coordinate based, so it is stable under tiling).
|
||||
#[inline]
|
||||
fn dissolve_noise(x: i32, y: i32) -> f32 {
|
||||
@@ -1890,26 +1925,23 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
|
||||
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]];
|
||||
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);
|
||||
@@ -2144,7 +2176,9 @@ fn fx_cache() -> &'static std::sync::Mutex<FxCache> {
|
||||
/// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for
|
||||
/// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local
|
||||
/// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded
|
||||
/// by twice the effect reach instead, which gives the same pixels there. Only when `rect`, what
|
||||
/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local
|
||||
/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]).
|
||||
/// Only when `rect`, what
|
||||
/// the caller composites the layer over, lies within the render rectangle: a group's effect shape
|
||||
/// (or anything else rendering children over a wider area) gets the whole region.
|
||||
fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) {
|
||||
@@ -2152,7 +2186,7 @@ fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) {
|
||||
let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m));
|
||||
let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match clip {
|
||||
Some(c) if c.contains_rect(&rect) && advanced::shapeless(layer) && effects::maps_are_local(layer) => {
|
||||
Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => {
|
||||
let part = region.intersect(&c.inflate(m.saturating_mul(2)));
|
||||
(part, part != region)
|
||||
}
|
||||
@@ -2160,6 +2194,38 @@ fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the effect maps of the visible layers of `layers` (groups included), each over its
|
||||
/// whole region, would take more than the effect cache budget together. A render needs all of
|
||||
/// them, so when they don't fit, building one evicts the next one needed and every render builds
|
||||
/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`]
|
||||
/// counts them, with only the shape and one map per enabled effect: a lower bound.
|
||||
fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool {
|
||||
fx_region_bytes(layers, canvas) > effect_cache_budget() as u64
|
||||
}
|
||||
|
||||
/// The lower bound [`fx_over_budget`] compares with the budget.
|
||||
fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 {
|
||||
fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 {
|
||||
let mut total = 0u64;
|
||||
for l in layers.iter().filter(|l| l.visible) {
|
||||
if effects::has_effects(l) {
|
||||
let m = effects::margin(l);
|
||||
let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m));
|
||||
let maps = 1 + l.effects.items.iter().filter(|e| e.enabled()).count() as u64;
|
||||
let px = u64::from(region.width()) * u64::from(region.height());
|
||||
total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4));
|
||||
}
|
||||
if let LayerContent::Group(g) = &l.content
|
||||
&& depth < PREPARE_DEPTH
|
||||
{
|
||||
total = total.saturating_add(bytes(&g.children, canvas, depth + 1));
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
bytes(layers, canvas, 0)
|
||||
}
|
||||
|
||||
/// The layer's effect maps over its region (layer bounds grown by the effect reach, within the
|
||||
/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every
|
||||
/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]).
|
||||
|
||||
@@ -1942,6 +1942,105 @@ fn shapeless_effect_maps_cover_only_the_band_being_rendered() {
|
||||
);
|
||||
}
|
||||
|
||||
/// [`shapeless_fx_doc`] with Transparency Shapes Layer back on everywhere: ordinary layers, whose
|
||||
/// effect regions are their own bounds grown by the effects' reach.
|
||||
fn ordinary_fx_doc(depth: SampleType) -> Document {
|
||||
fn shaped(layers: &mut [Layer]) {
|
||||
for l in layers {
|
||||
l.advanced.transparency_shapes = true;
|
||||
if let LayerContent::Group(g) = &mut l.content {
|
||||
shaped(&mut g.children);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut d = shapeless_fx_doc(depth);
|
||||
shaped(&mut d.layers);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_maps_over_the_cache_budget_are_built_over_the_render_rect() {
|
||||
// #8330: an ordinary layer's maps cover its whole region, so on a large document a render's
|
||||
// layers can need more than the effect cache holds; building one then evicts the next one
|
||||
// needed, and every render, however small, builds them all again. Over the budget, local maps
|
||||
// are built over the render rect (plus twice the reach), as a shapeless layer's are (#1909).
|
||||
let d = ordinary_fx_doc(SampleType::U8);
|
||||
let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES);
|
||||
// A row through fx8 (pixels at y 552..570, an outside stroke and an inner glow).
|
||||
let band = Rect::new(0, 561, 48, 562);
|
||||
let mut cx = Ctx::for_doc(&d, &patterns);
|
||||
assert!(!cx.fx_over_budget, "a small document fits");
|
||||
let l = &d.layers[9];
|
||||
let whole = effect_region(l, band, &cx);
|
||||
cx.set_fx_clip(band);
|
||||
assert_eq!(effect_region(l, band, &cx), whole, "under the budget: the whole region");
|
||||
cx.fx_over_budget = true;
|
||||
let (part, clipped) = effect_region(l, band, &cx);
|
||||
assert_eq!(part, whole.0.intersect(&band.inflate(2 * effects::margin(l))));
|
||||
assert!(clipped && part.height() < whole.0.height(), "{part:?} vs {:?}", whole.0);
|
||||
let built = effect_maps(l, band, &cx).bytes();
|
||||
cx.fx_over_budget = false;
|
||||
cx.set_fx_clip(Rect::new(0, 0, 1, 1));
|
||||
cx.set_fx_clip(band);
|
||||
assert!(built < effect_maps(l, band, &cx).bytes());
|
||||
cx.fx_over_budget = true;
|
||||
// Composited over more than the band, and maps that aren't local: the whole region.
|
||||
assert_eq!(effect_region(l, Rect::new(0, 500, 48, 600), &cx), whole);
|
||||
let noisy = &d.layers[2];
|
||||
assert!(!effects::maps_are_local(noisy));
|
||||
cx.set_fx_clip(Rect::new(0, 100, 48, 140));
|
||||
assert!(!effect_region(noisy, Rect::new(0, 100, 48, 140), &cx).1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_with_maps_clipped_over_the_budget_match_the_whole_maps() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let d = ordinary_fx_doc(depth);
|
||||
let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES);
|
||||
purge_effect_cache();
|
||||
let whole = render(&d, d.bounds());
|
||||
let mut cx = Ctx::for_doc(&d, &patterns);
|
||||
cx.fx_over_budget = true;
|
||||
// Bands, edit-sized parts and single tiles, each from maps built over it alone.
|
||||
purge_effect_cache();
|
||||
let bands = (0..10).map(|i| Rect::new(0, i * 64, 48, (i + 1) * 64));
|
||||
let parts = [Rect::new(3, 290, 41, 333), Rect::new(0, 0, 48, 20), Rect::new(20, 600, 48, 640), Rect::new(0, 296, 20, 312), Rect::new(10, 425, 40, 445)];
|
||||
for r in bands.chain(parts) {
|
||||
let p = render_tiled_with(&d, r, RENDER_TILE, &cx);
|
||||
for y in r.y0..r.y1 {
|
||||
for x in r.x0..r.x1 {
|
||||
assert_eq!(p.get(x, y), whole.get(x, y), "{depth:?}: {r:?} differs at ({x},{y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(render_tiled_with(&d, d.bounds(), 16, &cx).px == whole.px, "{depth:?}: tiled render differs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_effect_map_estimate_is_a_lower_bound() {
|
||||
// fx_over_budget compares a lower bound of the maps' bytes with the budget: it must not
|
||||
// exceed what building them takes, or a document that fits would lose its shared maps.
|
||||
let d = ordinary_fx_doc(SampleType::U8);
|
||||
let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES);
|
||||
let cx = Ctx::for_doc(&d, &patterns);
|
||||
let mut todo = Vec::new();
|
||||
effect_layers(&d.layers, d.bounds(), 0, &mut todo);
|
||||
let built: usize = todo.iter().map(|l| effect_maps(l, d.bounds(), &cx).bytes()).sum();
|
||||
let estimate = fx_region_bytes(&d.layers, d.bounds());
|
||||
assert!(estimate > 0 && estimate <= built as u64, "estimate {estimate} B, built {built} B");
|
||||
// A 9000 x 6000 document with three full layers, each with a drop shadow (#8330's case):
|
||||
// about 1.3 GB, over the default 768 MB. One such layer fits.
|
||||
let mut big = Document::with_background("big", Size::new(9000, 6000), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut l = Layer::raster("fill", big.pixel_format());
|
||||
l.surface_mut().unwrap().fill_rect(big.bounds(), &photocraft_raster::from_rgba(&big.pixel_format(), [0.8, 0.5, 0.3, 1.0]));
|
||||
l.effects.items = vec![Effect::DropShadow(Shadow { size: 40.0, ..shadow(20.0, 120.0) })];
|
||||
big.layers.push(l.clone());
|
||||
assert!(fx_region_bytes(&big.layers, big.bounds()) < DEFAULT_FX_CACHE_BUDGET as u64);
|
||||
big.layers.extend([l.clone(), l]);
|
||||
assert!(fx_region_bytes(&big.layers, big.bounds()) > DEFAULT_FX_CACHE_BUDGET as u64);
|
||||
}
|
||||
|
||||
// ---------- PSD-fidelity effect semantics (fitted on Photoshop composites) ----------
|
||||
|
||||
#[test]
|
||||
@@ -4033,3 +4132,19 @@ fn clipped_dissolve_adjustment_preserves_alpha_and_document_coverage() {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -659,6 +659,10 @@ pub struct Layer {
|
||||
pub advanced: AdvancedBlending,
|
||||
/// Layer › Video Layers frame stack (None for a normal layer).
|
||||
pub video: Option<VideoData>,
|
||||
/// The layer's own XMP packet (Photoshop's `layer.xmpMetadata.rawData`), where scripts and
|
||||
/// embedding apps keep data about the layer under their own namespaces. Copied by
|
||||
/// [`Layer::duplicate`], as in Photoshop. PSD `shmd` › `cust` › `layerXMP`.
|
||||
pub xmp: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
@@ -692,6 +696,7 @@ impl Layer {
|
||||
blend_if: BlendIf::default(),
|
||||
advanced: AdvancedBlending::default(),
|
||||
video: None,
|
||||
xmp: None,
|
||||
}
|
||||
}
|
||||
pub fn raster(name: impl Into<String>, format: PixelFormat) -> Self {
|
||||
|
||||
@@ -1546,6 +1546,7 @@ fn build() -> Vec<CommandSpec> {
|
||||
v.extend(crate::adjust_cmds::specs());
|
||||
v.extend(crate::layer_menu_cmds::specs());
|
||||
v.extend(crate::layer_label_cmds::specs());
|
||||
v.extend(crate::layer_xmp_cmds::specs());
|
||||
v.extend(crate::mode_cmds::specs());
|
||||
v.extend(crate::multichannel_cmds::specs());
|
||||
v.extend(crate::pattern_cmds::specs());
|
||||
|
||||
@@ -346,7 +346,7 @@ pub(crate) fn before_command(s: &mut Session, id: &str) -> Result<Option<Value>>
|
||||
}
|
||||
match id {
|
||||
// Edit › Undo and the History panel's Step Backward step back over the move itself.
|
||||
"edit.undo" | "edit.stepBackward" | "history.stepBackward" => {
|
||||
"edit.undo" | "history.stepBackward" => {
|
||||
st.floating = None;
|
||||
Ok(Some(json!({"floating": "returned"})))
|
||||
}
|
||||
|
||||
@@ -106,6 +106,7 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMa
|
||||
"bounds": bounds,
|
||||
"selected": selected.contains(&l.id),
|
||||
"linkGroup": l.link_group,
|
||||
"hasXmp": l.xmp.is_some(),
|
||||
});
|
||||
match &l.content {
|
||||
LayerContent::Group(g) => {
|
||||
|
||||
@@ -637,7 +637,7 @@ fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::Al
|
||||
/// compared here: the caller walks into them, so an edit inside a group damages only the
|
||||
/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new
|
||||
/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored
|
||||
/// (name, locks, label, `psd_blocks`, `psd_id`, link group — none of them composite; video
|
||||
/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video
|
||||
/// bails out earlier in the walk).
|
||||
fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool {
|
||||
let Layer {
|
||||
@@ -662,6 +662,7 @@ fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool {
|
||||
blend_if,
|
||||
advanced,
|
||||
video: _,
|
||||
xmp: _,
|
||||
} = a;
|
||||
*id == b.id
|
||||
&& *visible == b.visible
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! A layer's own XMP packet, as Photoshop scripts reach it through `layer.xmpMetadata.rawData`:
|
||||
//! scripts and embedding apps keep data about a layer there under their own namespaces. It is
|
||||
//! saved in PSD, PSB, layered TIFF and `.pcraft`, and copied when the layer is duplicated.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_doc::LayerId;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const ID: &str = "layer.xmpMetadata";
|
||||
|
||||
/// Largest packet accepted, in UTF-8 bytes. Every history state shares the packet, but a PSD
|
||||
/// stores it as UTF-16 in each layer's record.
|
||||
pub const MAX_LAYER_XMP: usize = 4 << 20;
|
||||
|
||||
fn bad(message: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: ID.into(), msg: message.into() }
|
||||
}
|
||||
|
||||
fn enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
crate::active_layer_of(s).map(|_| ())
|
||||
}
|
||||
|
||||
/// `raw` if it is an XMP packet: well-formed XML (no DTD) whose root is `x:xmpmeta` or
|
||||
/// `rdf:RDF`, without NUL characters (Photoshop stores the packet NUL-terminated).
|
||||
fn check_packet(raw: &str) -> Result<()> {
|
||||
if raw.len() > MAX_LAYER_XMP {
|
||||
return Err(bad(format!("`rawData` is {} bytes; the most a layer holds is {MAX_LAYER_XMP}", raw.len())));
|
||||
}
|
||||
if raw.contains('\0') {
|
||||
return Err(bad("`rawData` can't contain NUL characters"));
|
||||
}
|
||||
let xml = roxmltree::Document::parse(raw).map_err(|e| bad(format!("`rawData` isn't well-formed XML: {e}")))?;
|
||||
let root = xml.root_element().tag_name();
|
||||
let xmp = matches!((root.namespace(), root.name()), (Some("adobe:ns:meta/"), "xmpmeta") | (Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "RDF"));
|
||||
if !xmp {
|
||||
return Err(bad("`rawData` must be an XMP packet: its root element is x:xmpmeta or rdf:RDF"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn xmp_metadata(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let empty = Map::new();
|
||||
let p = match p {
|
||||
Value::Null => &empty,
|
||||
Value::Object(m) => m,
|
||||
_ => return Err(bad("expected an object")),
|
||||
};
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let id = match p.get("layer") {
|
||||
Some(v) => LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?),
|
||||
None => st.active_layer.ok_or_else(|| bad("no active layer"))?,
|
||||
};
|
||||
let current = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?.xmp.clone();
|
||||
let new = match p.get("rawData") {
|
||||
None => return Ok(json!({"layer": id.0, "rawData": current.as_deref(), "changed": false})),
|
||||
Some(Value::Null) => None,
|
||||
Some(Value::String(raw)) => {
|
||||
check_packet(raw)?;
|
||||
Some(raw.as_str())
|
||||
}
|
||||
Some(_) => return Err(bad("`rawData` must be a string (an XMP packet) or null (remove it)")),
|
||||
};
|
||||
let changed = current.as_deref() != new;
|
||||
if changed {
|
||||
let stored: Option<Arc<str>> = new.map(Into::into);
|
||||
s.edit("Layer Metadata", move |doc, _| {
|
||||
doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.xmp = stored;
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(st) = s.active_mut() {
|
||||
// Saved metadata only; no canvas pixels need recompositing.
|
||||
st.last_damage = Some(photocraft_geom::Rect::EMPTY);
|
||||
}
|
||||
}
|
||||
Ok(json!({"layer": id.0, "rawData": new, "changed": changed}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
id: ID,
|
||||
label: "Layer XMP Metadata",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r#"{"layer":id?,"rawData":string|null?} → {"layer","rawData","changed"} (no layer: the active layer; no rawData: read it; a string sets the layer's XMP packet, null removes it; as Photoshop's layer.xmpMetadata.rawData)"#,
|
||||
enabled,
|
||||
run: xmp_metadata,
|
||||
journal: true,
|
||||
}]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,106 @@
|
||||
use super::*;
|
||||
use photocraft_doc::Layer;
|
||||
|
||||
const PACKET: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:app="http://example.com/app/1.0/"><app:arc>120</app:arc></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
fn fixture(depth: u8) -> (Session, LayerId, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 4, "height": 4, "depth": depth})).unwrap();
|
||||
let (a, b) = s
|
||||
.edit("Fixture", |doc, _| {
|
||||
let a = Layer::raster("A", doc.pixel_format());
|
||||
let b = Layer::group("B", vec![Layer::raster("Child", doc.pixel_format())]);
|
||||
let ids = (a.id, b.id);
|
||||
doc.layers = vec![a, b];
|
||||
Ok(ids)
|
||||
})
|
||||
.unwrap();
|
||||
s.select_layer(a).unwrap();
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
fn xmp(s: &Session, id: LayerId) -> Option<String> {
|
||||
s.active().unwrap().doc.layer(id).unwrap().xmp.as_deref().map(str::to_string)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_reads_and_removes_as_one_undo_step_each() {
|
||||
for depth in [8, 16, 32] {
|
||||
let (mut s, a, b) = fixture(depth);
|
||||
assert_eq!(s.execute(ID, json!({})).unwrap(), json!({"layer": a.0, "rawData": null, "changed": false}));
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
|
||||
// The active layer by default; a group by id.
|
||||
assert_eq!(s.execute(ID, json!({"rawData": PACKET})).unwrap(), json!({"layer": a.0, "rawData": PACKET, "changed": true}));
|
||||
assert_eq!(s.execute(ID, json!({"layer": b.0, "rawData": PACKET})).unwrap()["changed"], true);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 2);
|
||||
assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY));
|
||||
assert_eq!(s.execute(ID, Value::Null).unwrap()["rawData"], PACKET);
|
||||
assert_eq!(crate::inspect::layer(s.active().unwrap().doc.layer(b).unwrap())["hasXmp"], true);
|
||||
|
||||
// Only the packets changed.
|
||||
let mut expected = (*before).clone();
|
||||
for id in [a, b] {
|
||||
expected.layer_mut(id).unwrap().xmp = Some(PACKET.into());
|
||||
}
|
||||
assert_eq!(*s.active().unwrap().doc, expected, "depth {depth}");
|
||||
|
||||
// The same packet again is not an edit.
|
||||
assert_eq!(s.execute(ID, json!({"rawData": PACKET})).unwrap()["changed"], false);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 2);
|
||||
|
||||
assert_eq!(s.execute(ID, json!({"rawData": null})).unwrap(), json!({"layer": a.0, "rawData": null, "changed": true}));
|
||||
assert_eq!(xmp(&s, a), None);
|
||||
assert!(s.undo());
|
||||
assert_eq!(xmp(&s, a).as_deref(), Some(PACKET));
|
||||
assert!(s.undo() && s.undo());
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert!(s.redo());
|
||||
assert_eq!(xmp(&s, a).as_deref(), Some(PACKET));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_a_layer_copies_its_packet() {
|
||||
let (mut s, a, _) = fixture(8);
|
||||
s.execute(ID, json!({"rawData": PACKET})).unwrap();
|
||||
s.execute("layer.duplicate", json!({})).unwrap();
|
||||
let copy = s.active().unwrap().active_layer.unwrap();
|
||||
assert_ne!(copy, a);
|
||||
assert_eq!(xmp(&s, copy).as_deref(), Some(PACKET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_what_is_not_an_xmp_packet() {
|
||||
let (mut s, a, _) = fixture(8);
|
||||
let refused = |s: &mut Session, p: Value| matches!(s.execute(ID, p), Err(EngineError::BadParams { .. }));
|
||||
for p in [
|
||||
json!([]),
|
||||
json!({"layer": "A"}),
|
||||
json!({"rawData": 7}),
|
||||
json!({"rawData": ""}),
|
||||
json!({"rawData": "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">"}),
|
||||
json!({"rawData": "<html/>"}),
|
||||
json!({"rawData": "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\u{0}</x:xmpmeta>"}),
|
||||
json!({"rawData": "<!DOCTYPE x [<!ENTITY a \"aaaa\">]><x:xmpmeta xmlns:x=\"adobe:ns:meta/\">&a;</x:xmpmeta>"}),
|
||||
json!({"rawData": format!("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">{}</x:xmpmeta>", "a".repeat(MAX_LAYER_XMP))}),
|
||||
] {
|
||||
assert!(refused(&mut s, p.clone()), "{p:.80}");
|
||||
}
|
||||
let r = s.execute(ID, json!({"layer": 999_999_999}));
|
||||
assert!(matches!(r, Err(EngineError::UnknownLayer { .. })), "{r:?}");
|
||||
assert_eq!(xmp(&s, a), None);
|
||||
// A bare RDF root and a packet wrapper are packets.
|
||||
let rdf = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"/>"#;
|
||||
assert_eq!(s.execute(ID, json!({"rawData": rdf})).unwrap()["changed"], true);
|
||||
let wrapped = format!("<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>{PACKET}<?xpacket end=\"w\"?>");
|
||||
assert_eq!(s.execute(ID, json!({"rawData": wrapped})).unwrap()["changed"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_document_and_a_layer() {
|
||||
let mut s = Session::new();
|
||||
assert!(matches!(s.execute(ID, json!({})), Err(EngineError::Disabled(..))));
|
||||
assert!(enabled(&s).is_err());
|
||||
}
|
||||
@@ -75,6 +75,7 @@ pub mod layer_menu_cmds;
|
||||
pub mod layer_multi_cmds;
|
||||
pub mod layer_nav_cmds;
|
||||
pub mod layer_style;
|
||||
pub mod layer_xmp_cmds;
|
||||
pub mod lens_cmds;
|
||||
pub mod link_watch;
|
||||
pub mod magnetic_cmds;
|
||||
|
||||
+112
-16
@@ -253,6 +253,27 @@ pub struct Marks {
|
||||
pub corner_crop: bool,
|
||||
pub center_crop: bool,
|
||||
pub registration: bool,
|
||||
/// Photoshop's Functions › Bleed, in points: corner crop marks sit this far inside the image
|
||||
/// edge, so the trim cuts through the image and leaves no paper-white sliver. 0 = on the edge.
|
||||
pub bleed: f64,
|
||||
}
|
||||
|
||||
/// Gap between the image edge and a crop mark, and the mark's length (pt).
|
||||
const MARK_GAP: f64 = 6.0;
|
||||
const MARK_LEN: f64 = 18.0;
|
||||
|
||||
/// Corner crop marks around `(x, y, w, h)` as eight `(from, to)` segments, a horizontal then a
|
||||
/// vertical one per corner. Each starts `MARK_GAP` outside the image (so it never prints on it)
|
||||
/// and lies on the trim line, `bleed` inside the edge. The inset is symmetric, so this holds for
|
||||
/// both bottom-up (PDF) and top-down (Windows) coordinates.
|
||||
fn corner_crop_segments(bleed: f64, (x, y, w, h): (f64, f64, f64, f64)) -> [((f64, f64), (f64, f64)); 8] {
|
||||
let mut out = [((0.0, 0.0), (0.0, 0.0)); 8];
|
||||
for (i, (cx, cy, dx, dy)) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)].into_iter().enumerate() {
|
||||
let (tx, ty) = (cx - dx * bleed, cy - dy * bleed);
|
||||
out[2 * i] = ((cx + dx * MARK_GAP, ty), (cx + dx * (MARK_GAP + MARK_LEN), ty));
|
||||
out[2 * i + 1] = ((tx, cy + dy * MARK_GAP), (tx, cy + dy * (MARK_GAP + MARK_LEN)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One page: paper (pt), image box (pt, origin bottom-left), marks and texts.
|
||||
@@ -268,16 +289,51 @@ pub struct PrintPage {
|
||||
pub emulsion_down: bool,
|
||||
}
|
||||
|
||||
// ISO 32000-1, Annex D.2: the standard Helvetica font below uses WinAnsiEncoding,
|
||||
// not UTF-8. Escape non-ASCII bytes as three octal digits so the content stays ASCII
|
||||
// and a following digit cannot become part of the escape. Other scripts still need
|
||||
// an embedded font; retain the existing '?' fallback for unsupported characters.
|
||||
fn pdf_string(s: &str) -> String {
|
||||
let mut o = String::from("(");
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'(' | ')' | '\\' => {
|
||||
let byte = match c {
|
||||
'\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' => c as u8,
|
||||
'€' => 0x80,
|
||||
'‚' => 0x82,
|
||||
'ƒ' => 0x83,
|
||||
'„' => 0x84,
|
||||
'…' => 0x85,
|
||||
'†' => 0x86,
|
||||
'‡' => 0x87,
|
||||
'ˆ' => 0x88,
|
||||
'‰' => 0x89,
|
||||
'Š' => 0x8a,
|
||||
'‹' => 0x8b,
|
||||
'Œ' => 0x8c,
|
||||
'Ž' => 0x8e,
|
||||
'‘' => 0x91,
|
||||
'’' => 0x92,
|
||||
'“' => 0x93,
|
||||
'”' => 0x94,
|
||||
'•' => 0x95,
|
||||
'–' => 0x96,
|
||||
'—' => 0x97,
|
||||
'˜' => 0x98,
|
||||
'™' => 0x99,
|
||||
'š' => 0x9a,
|
||||
'›' => 0x9b,
|
||||
'œ' => 0x9c,
|
||||
'ž' => 0x9e,
|
||||
'Ÿ' => 0x9f,
|
||||
_ => b'?',
|
||||
};
|
||||
match byte {
|
||||
b'(' | b')' | b'\\' => {
|
||||
o.push('\\');
|
||||
o.push(c);
|
||||
o.push(char::from(byte));
|
||||
}
|
||||
c if c.is_ascii() && !c.is_ascii_control() => o.push(c),
|
||||
_ => o.push('?'),
|
||||
0x80..=0xff => o.push_str(&format!("\\{byte:03o}")),
|
||||
_ => o.push(char::from(byte)),
|
||||
}
|
||||
}
|
||||
o.push(')');
|
||||
@@ -294,12 +350,11 @@ fn deflate(data: &[u8]) -> Vec<u8> {
|
||||
/// Vector marks around `(x, y, w, h)`.
|
||||
fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String {
|
||||
let mut s = String::from("q 0 G 0.3 w\n");
|
||||
let (gap, len) = (6.0, 18.0);
|
||||
let (gap, len) = (MARK_GAP, MARK_LEN);
|
||||
let line = |s: &mut String, x0: f64, y0: f64, x1: f64, y1: f64| s.push_str(&format!("{x0:.2} {y0:.2} m {x1:.2} {y1:.2} l S\n"));
|
||||
if m.corner_crop {
|
||||
for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] {
|
||||
line(&mut s, cx + dx * gap, cy, cx + dx * (gap + len), cy);
|
||||
line(&mut s, cx, cy + dy * gap, cx, cy + dy * (gap + len));
|
||||
for ((x0, y0), (x1, y1)) in corner_crop_segments(m.bleed, (x, y, w, h)) {
|
||||
line(&mut s, x0, y0, x1, y1);
|
||||
}
|
||||
}
|
||||
if m.center_crop {
|
||||
@@ -512,15 +567,33 @@ pub struct PrintLayout {
|
||||
pub emulsion_down: bool,
|
||||
}
|
||||
|
||||
/// The print layout for `doc` with Print parameters `p` (used by the dialog's preview too).
|
||||
/// Symmetric safety bound for manual Top/Left offsets, shared with the dialog (inches).
|
||||
pub const MAX_POSITION_INCHES: f64 = 10000.0;
|
||||
|
||||
/// Resolves the shared preview/PDF layout without changing `doc`.
|
||||
///
|
||||
/// Paper and image bounds use points (72 per inch), with the image origin at bottom-left.
|
||||
/// Manual `top`/`left` are inches from the paper's top-left; negative values place artwork
|
||||
/// off-page. Center ignores these offsets. Scale to Fit preserves the aspect ratio and uses
|
||||
/// the available paper area after the existing mark margins, overriding percentage scale.
|
||||
/// Emulsion Down is recorded for rendering; the returned rectangle is not yet mirrored.
|
||||
///
|
||||
/// Returns an error for malformed manual offsets or offsets beyond [`MAX_POSITION_INCHES`],
|
||||
/// nonfinite geometry, geometry magnitudes above 1e9, or nonpositive image dimensions.
|
||||
pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result<PrintLayout> {
|
||||
let (pw, ph) = paper(p, cmd)?;
|
||||
let dpi = f64::from(doc.resolution_dpi.max(1.0));
|
||||
let (iw, ih) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi);
|
||||
let marks = Marks {
|
||||
// Bleed in inches, like Photoshop's Position fields; the marks need it in points.
|
||||
let bleed = match p.get("bleed") {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
Some(v) => v.as_f64().filter(|b| b.is_finite() && *b >= 0.0).ok_or_else(|| bad(cmd, "bleed is a width in inches, 0 or more"))? * 72.0,
|
||||
};
|
||||
let mut marks = Marks {
|
||||
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 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
|
||||
@@ -549,6 +622,14 @@ pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result<PrintLayout> {
|
||||
};
|
||||
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 && fit {
|
||||
(fit_box.0 + (fit_box.2 - w) / 2.0, fit_box.1 + (fit_box.3 - h) / 2.0)
|
||||
@@ -556,10 +637,25 @@ pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result<PrintLayout> {
|
||||
((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"));
|
||||
}
|
||||
Ok(PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down })
|
||||
}
|
||||
|
||||
@@ -676,7 +772,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spool
|
||||
require_printing_enabled()?;
|
||||
let printed = print_windows(&page, p, &doc.name, copies)?;
|
||||
return Ok(json!({
|
||||
"pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0,
|
||||
"pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "bleed": marks.bleed / 72.0, "scale": scale * 100.0,
|
||||
"copies": copies, "command": Value::Null, "sent": true, "spooler": printed, "color": color,
|
||||
}));
|
||||
}
|
||||
@@ -722,7 +818,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spool
|
||||
sent = true;
|
||||
}
|
||||
Ok(
|
||||
json!({"pdf": pdf_path, "bytes": pdf_len, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": command, "sent": sent, "spooler": spool, "backend": backend, "color": color}),
|
||||
json!({"pdf": pdf_path, "bytes": pdf_len, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "bleed": marks.bleed / 72.0, "scale": scale * 100.0, "copies": copies, "command": command, "sent": sent, "spooler": spool, "backend": backend, "color": color}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1181,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,"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),
|
||||
|
||||
@@ -1,6 +1,68 @@
|
||||
use super::*;
|
||||
use photocraft_doc::{Knot, NamedPath, Path, Subpath};
|
||||
|
||||
/// Compares signed-offset layout with actual PDF image operators and whole-page mirroring
|
||||
/// across scale/fit/orientation cases, while checking the source document stays unchanged.
|
||||
#[test]
|
||||
fn negative_print_positions_match_pdf_without_changing_the_document() {
|
||||
let dir = tmp("negative-position");
|
||||
for (scale, fit, landscape, mirrored) in
|
||||
[(100.0, false, false, false), (175.0, false, true, false), (50.0, true, false, false), (100.0, false, false, true)]
|
||||
{
|
||||
let mut s = session("rgb", 8);
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let revision = s.active().unwrap().revision;
|
||||
let path = format!("{dir}/{scale}-{fit}-{landscape}-{mirrored}.pdf");
|
||||
let p = json!({"paper": "a4", "center": false, "left": -0.5, "top": -0.25,
|
||||
"scale": scale, "scaleToFit": fit, "orientation": if landscape {"landscape"} else {"portrait"},
|
||||
"emulsionDown": mirrored, "output": path, "send": false, "dryRun": true});
|
||||
let preview = layout(&before, &p, "file.print").unwrap();
|
||||
let (x, y, w, h) = preview.rect;
|
||||
assert_eq!(x, -36.0);
|
||||
assert!((preview.paper.1 - y - h + 18.0).abs() < 1e-9);
|
||||
assert!((w / h - 2.0).abs() < 1e-9);
|
||||
if !fit {
|
||||
assert!((w - 300.0 * scale / 100.0).abs() < 1e-9);
|
||||
} else {
|
||||
assert!((w - (preview.paper.0 - 36.0)).abs() < 1e-9);
|
||||
}
|
||||
let result = s.execute("file.print", p).unwrap();
|
||||
assert_eq!(result["sent"], false);
|
||||
assert_eq!(result["imageRect"], json!([x, y, w, h]));
|
||||
let pdf = std::fs::read(path).unwrap();
|
||||
let content = pdf_content(&pdf);
|
||||
assert!(content.contains(&format!("q {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q")));
|
||||
assert_eq!(content.contains(&format!("q -1 0 0 1 {:.2} 0 cm", preview.paper.0)), mirrored);
|
||||
let after = s.active().unwrap();
|
||||
assert_eq!(after.revision, revision);
|
||||
assert_eq!(after.doc.size, before.size);
|
||||
assert_eq!(after.doc.resolution_dpi, before.resolution_dpi);
|
||||
assert_eq!(photocraft_compose::thumbnail(&before, 32).pixels, photocraft_compose::thumbnail(&after.doc, 32).pixels);
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks inclusive signed inch limits, malformed manual offsets and overflow-prone scale
|
||||
/// or paper inputs at the shared layout boundary, without invoking a printer.
|
||||
#[test]
|
||||
fn print_position_and_geometry_bounds_reject_malformed_inputs() {
|
||||
let s = session("rgb", 8);
|
||||
let doc = &s.active().unwrap().doc;
|
||||
for key in ["top", "left"] {
|
||||
for value in [json!(-10000.0), json!(10000.0), json!(-0.125)] {
|
||||
let mut p = json!({"center": false});
|
||||
p[key] = value;
|
||||
assert!(layout(doc, &p, "file.print").is_ok());
|
||||
}
|
||||
for value in [json!(1e308), json!(-10001.0), json!("NaN"), Value::Null] {
|
||||
let mut p = json!({"center": false});
|
||||
p[key] = value;
|
||||
assert!(layout(doc, &p, "file.print").is_err());
|
||||
}
|
||||
}
|
||||
assert!(layout(doc, &json!({"scale": 1e308}), "file.print").is_err());
|
||||
assert!(layout(doc, &json!({"paper": [1e308, 792]}), "file.print").is_err());
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-print-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
@@ -1000,3 +1062,101 @@ fn package_of_a_document_named_after_a_windows_device_is_written() {
|
||||
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");
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! App-owned print-mark composition in points from the sheet's top-left.
|
||||
use super::Marks;
|
||||
use super::{MARK_GAP, MARK_LEN, Marks, corner_crop_segments};
|
||||
use craft_print::rgb::{Primitive, Shape};
|
||||
|
||||
pub(super) fn primitives(marks: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> Vec<Primitive> {
|
||||
@@ -7,11 +7,10 @@ pub(super) fn primitives(marks: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> Ve
|
||||
let line = |out: &mut Vec<Primitive>, x0, y0, x1, y1| {
|
||||
out.push(Primitive { shape: Shape::Line { from: (x0, y0), to: (x1, y1) }, width: 0.3, color: [0; 3] });
|
||||
};
|
||||
let (gap, len) = (6.0, 18.0);
|
||||
let (gap, len) = (MARK_GAP, MARK_LEN);
|
||||
if marks.corner_crop {
|
||||
for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] {
|
||||
line(&mut out, cx + dx * gap, cy, cx + dx * (gap + len), cy);
|
||||
line(&mut out, cx, cy + dy * gap, cx, cy + dy * (gap + len));
|
||||
for ((x0, y0), (x1, y1)) in corner_crop_segments(marks.bleed, (x, y, w, h)) {
|
||||
line(&mut out, x0, y0, x1, y1);
|
||||
}
|
||||
}
|
||||
if marks.center_crop {
|
||||
@@ -37,11 +36,24 @@ mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn marks_surround_the_final_image_box_in_physical_points() {
|
||||
let out = primitives(Marks { corner_crop: true, center_crop: true, registration: true }, (100.0, 200.0, 144.0, 72.0));
|
||||
let out = primitives(Marks { corner_crop: true, center_crop: true, registration: true, bleed: 0.0 }, (100.0, 200.0, 144.0, 72.0));
|
||||
assert_eq!(out.len(), 24);
|
||||
assert_eq!(out[0].shape, Shape::Line { from: (94.0, 200.0), to: (76.0, 200.0) });
|
||||
assert_eq!(out[12].shape, Shape::Ellipse { bounds: (167.0, 180.0, 10.0, 10.0) });
|
||||
assert!(out.iter().all(|p| p.width == 0.3 && p.color == [0; 3]));
|
||||
assert!(primitives(Marks::default(), (0.0, 0.0, 10.0, 10.0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bleed_moves_corner_crop_marks_onto_the_trim_line_in_top_down_coordinates() {
|
||||
let rect = (100.0, 200.0, 144.0, 72.0);
|
||||
let out = primitives(Marks { corner_crop: true, bleed: 9.0, ..Marks::default() }, rect);
|
||||
assert_eq!(out.len(), 8);
|
||||
// Top-left corner: still outside the image, but on the trim line 9 pt in (y down here).
|
||||
assert_eq!(out[0].shape, Shape::Line { from: (94.0, 209.0), to: (76.0, 209.0) });
|
||||
assert_eq!(out[1].shape, Shape::Line { from: (109.0, 194.0), to: (109.0, 176.0) });
|
||||
// Bottom-right corner, mirrored.
|
||||
assert_eq!(out[6].shape, Shape::Line { from: (250.0, 263.0), to: (268.0, 263.0) });
|
||||
assert_eq!(out[7].shape, Shape::Line { from: (235.0, 278.0), to: (235.0, 296.0) });
|
||||
}
|
||||
}
|
||||
@@ -211,6 +211,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
|
||||
blend_if: l.blend_if.clone(),
|
||||
advanced: l.advanced,
|
||||
video: l.video.as_ref().map(|v| video_m(v, sink)),
|
||||
xmp: l.xmp.as_deref().map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,6 +548,7 @@ impl Loader<'_> {
|
||||
blend_if: m.blend_if.clone(),
|
||||
advanced: m.advanced,
|
||||
video: m.video.as_ref().map(|v| self.video(v)).transpose()?,
|
||||
xmp: m.xmp.as_deref().map(Arc::from),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,9 @@ pub struct LayerM {
|
||||
pub advanced: photocraft_doc::AdvancedBlending,
|
||||
#[serde(default)]
|
||||
pub video: Option<VideoDataM>,
|
||||
/// The layer's own XMP packet (missing in older files = none).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub xmp: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -1760,9 +1760,9 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf
|
||||
(13, p, Some(rows))
|
||||
}
|
||||
Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => {
|
||||
// Per-channel curves (compose::adjust::color_balance_channel), through the Levels kernel.
|
||||
let tones = [*shadows, *midtones, *highlights];
|
||||
(7, p, Some(lut_rows(|ch, v| adjust::color_balance_channel(tones, *preserve_luminosity, ch, v), 3)))
|
||||
// Per-channel curves (compose::adjust::BalanceCurve), through the Levels kernel.
|
||||
let curves = adjust::BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity);
|
||||
(7, p, Some(lut_rows(|ch, v| curves[ch].eval(v), 3)))
|
||||
}
|
||||
Adjustment::SelectiveColor { relative, adjustments } => {
|
||||
// 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact).
|
||||
|
||||
@@ -146,3 +146,144 @@ fn bits(doc: &Document) -> Vec<u8> {
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_color::{Color, SampleType};
|
||||
use photocraft_doc::Size;
|
||||
|
||||
fn document(width: u32, height: u32, depth: SampleType, mode: ColorMode, pixels: &[f32]) -> Document {
|
||||
let mut doc = Document::with_background("palette test", Size::new(width, height), ColorMode::Rgb, depth, Color::rgba(0.0, 0.0, 0.0, 1.0));
|
||||
let bounds = doc.bounds();
|
||||
doc.layers[0].surface_mut().unwrap().write_region(bounds, pixels);
|
||||
doc.mode = mode;
|
||||
doc
|
||||
}
|
||||
|
||||
fn round_trip(doc: &Document) -> (PsdFile, Document) {
|
||||
let (file, _) = document_to_psd(doc, false).unwrap();
|
||||
let bytes = file.to_bytes().unwrap();
|
||||
let file = PsdFile::from_bytes(&bytes).unwrap();
|
||||
let back = crate::import("test.psd", &bytes).unwrap().document;
|
||||
(file, back)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_palette_endpoints_round_trip_with_either_transparent_endpoint() {
|
||||
let colors: Vec<_> = (0..=255).map(|v| [v, 255 - v, v / 2]).collect();
|
||||
for transparent in [0, 255] {
|
||||
let opaque = 255 - transparent;
|
||||
let rgb = colors[usize::from(opaque)].map(|v| f32::from(v) / 255.0);
|
||||
let mut doc = document(2, 1, SampleType::U8, ColorMode::Indexed, &[rgb[0], rgb[1], rgb[2], 1.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
doc.color_table = Some(ColorTable { colors: colors.clone(), transparent: Some(transparent) });
|
||||
let (file, back) = round_trip(&doc);
|
||||
assert_eq!((file.header.color_mode, file.header.depth, file.header.channels), (PsdMode::Indexed, 8, 1));
|
||||
assert_eq!(file.decode_merged().unwrap(), [opaque, transparent]);
|
||||
assert_eq!(file.resource(COLOR_TABLE_COUNT).unwrap().data, [1, 0]);
|
||||
assert_eq!(file.color_mode_data.len(), 768);
|
||||
for (i, c) in colors.iter().enumerate() {
|
||||
assert_eq!([file.color_mode_data[i], file.color_mode_data[256 + i], file.color_mode_data[512 + i]], *c);
|
||||
}
|
||||
assert_eq!(back.color_table, doc.color_table);
|
||||
let surface = back.layers[0].surface().unwrap();
|
||||
assert_eq!(surface.pixel(0, 0), vec![rgb[0], rgb[1], rgb[2], 1.0]);
|
||||
assert_eq!(surface.pixel(1, 0)[3], 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_alpha_threshold_uses_stored_samples_at_all_depths() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut doc = document(3, 1, depth, ColorMode::Indexed, &[0.0, 0.0, 0.0, 0.49, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.51]);
|
||||
doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 255, 255]], transparent: Some(1) });
|
||||
let (file, back) = round_trip(&doc);
|
||||
assert_eq!(file.decode_merged().unwrap(), [1, 0, 0], "{depth:?}");
|
||||
let surface = back.layers[0].surface().unwrap();
|
||||
assert_eq!((0..3).map(|x| surface.pixel(x, 0)[3]).collect::<Vec<_>>(), [0.0, 1.0, 1.0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_palette_zero_pads_unused_entries_and_rejects_invalid_lengths() {
|
||||
let mut doc = document(1, 1, SampleType::U8, ColorMode::Indexed, &[1.0, 0.0, 0.0, 1.0]);
|
||||
doc.color_table = Some(ColorTable { colors: vec![[255, 0, 0]], transparent: None });
|
||||
let (file, back) = round_trip(&doc);
|
||||
assert_eq!(file.color_mode_data[0], 255);
|
||||
assert!(file.color_mode_data[1..].iter().all(|&v| v == 0));
|
||||
assert_eq!(back.color_table, doc.color_table);
|
||||
for count in [0, 257] {
|
||||
doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0]; count], transparent: None });
|
||||
assert!(document_to_psd(&doc, false).is_none(), "{count}");
|
||||
}
|
||||
doc.color_table = None;
|
||||
assert!(document_to_psd(&doc, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_import_bounds_malformed_count_and_transparency_resources() {
|
||||
let mut doc = document(1, 1, SampleType::U8, ColorMode::Indexed, &[0.0, 0.0, 0.0, 1.0]);
|
||||
doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 255, 255]], transparent: None });
|
||||
let (original, _) = document_to_psd(&doc, false).unwrap();
|
||||
for (count, expected) in [(vec![0, 0], 1), (vec![1, 1], 256), (vec![255, 255], 256), (vec![0], 256)] {
|
||||
let mut file = original.clone();
|
||||
file.resources.retain(|r| r.id != COLOR_TABLE_COUNT);
|
||||
file.resources.push(ImageResource::new(COLOR_TABLE_COUNT, count));
|
||||
file.resources.push(ImageResource::new(TRANSPARENCY_INDEX, vec![255, 255]));
|
||||
let bytes = file.to_bytes().unwrap();
|
||||
let back = crate::import("malformed.psd", &bytes).unwrap().document;
|
||||
let table = back.color_table.unwrap();
|
||||
assert_eq!(table.colors.len(), expected);
|
||||
assert_eq!(table.transparent, None);
|
||||
assert_eq!(back.layers[0].surface().unwrap().pixel(0, 0)[3], 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_rows_are_msb_first_and_independently_byte_padded() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
for width in [1u32, 7, 8, 9, 15, 17] {
|
||||
// Opposite rows expose padding carried into the next row or reversed bit order.
|
||||
let pixels: Vec<_> = (0..2)
|
||||
.flat_map(|y| {
|
||||
(0..width).flat_map(move |x| {
|
||||
let v = if (x + y) % 2 == 0 { 0.0 } else { 1.0 };
|
||||
[v, v, v, 1.0]
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let doc = document(width, 2, depth, ColorMode::Bitmap, &pixels);
|
||||
let (file, back) = round_trip(&doc);
|
||||
assert_eq!((file.header.color_mode, file.header.depth, file.header.channels), (PsdMode::Bitmap, 1, 1));
|
||||
let mut expected = Vec::new();
|
||||
for y in 0..2 {
|
||||
for byte in 0..width.div_ceil(8) {
|
||||
let mut packed = 0;
|
||||
for bit in 0..8 {
|
||||
let x = byte * 8 + bit;
|
||||
if x < width && (x + y) % 2 == 0 {
|
||||
packed |= 0x80 >> bit;
|
||||
}
|
||||
}
|
||||
expected.push(packed);
|
||||
}
|
||||
}
|
||||
assert_eq!(file.decode_merged().unwrap(), expected, "{depth:?}, width={width}");
|
||||
assert!(file.color_mode_data.is_empty());
|
||||
assert_eq!(back.mode, ColorMode::Bitmap);
|
||||
let gray_alpha: Vec<_> = pixels.as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[3]]).collect();
|
||||
assert_eq!(back.layers[0].surface().unwrap().read_region(back.bounds()), gray_alpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_alpha_is_flattened_over_white_before_thresholding() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let doc = document(3, 1, depth, ColorMode::Bitmap, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.49, 0.0, 0.0, 0.0, 0.51]);
|
||||
let (file, back) = round_trip(&doc);
|
||||
assert_eq!(file.decode_merged().unwrap(), [0x20], "{depth:?}");
|
||||
assert_eq!(back.layers[0].surface().unwrap().read_region(back.bounds()), [1.0, 1.0, 1.0, 1.0, 0.0, 1.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -731,9 +731,24 @@ impl Ex {
|
||||
let id = self.layer_ids.get(&l.id).copied().unwrap_or(0);
|
||||
crate::comps_map::set_cmls(&mut raw, crate::comps_map::write_cmls(comps, last.as_ref(), l, id));
|
||||
}
|
||||
self.layer_xmp_block(l, &mut raw);
|
||||
regenerated.into_iter().chain(raw).map(|(k, d)| TaggedBlock::new(k, d)).collect()
|
||||
}
|
||||
|
||||
/// Writes the layer's XMP packet into its `shmd` block (created when it has none). Import
|
||||
/// takes the packet out of `shmd`, so a layer without one keeps the block as it was.
|
||||
fn layer_xmp_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec<u8>)>) {
|
||||
let Some(xmp) = l.xmp.as_deref() else { return };
|
||||
let pos = raw.iter().position(|(k, _)| k == b"shmd");
|
||||
match photocraft_psd::metadata::put_layer_xmp(pos.map(|i| raw[i].1.as_slice()), xmp) {
|
||||
Ok(data) => match pos {
|
||||
Some(i) => raw[i].1 = data,
|
||||
None => raw.push((*b"shmd", data)),
|
||||
},
|
||||
Err(e) => self.warnings.push(format!("layer \"{}\": its XMP metadata was not saved (its metadata block can't be read: {e})", l.name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps, regenerates or removes the `vmsk`/`vsms` block of a non-shape layer.
|
||||
fn vector_mask_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec<u8>)>) {
|
||||
let (w, h) = (self.canvas.width(), self.canvas.height());
|
||||
|
||||
@@ -330,6 +330,19 @@ impl Ctx<'_> {
|
||||
// Blend If lives in the layer record's blending ranges.
|
||||
l.blend_if = crate::blocks::blend_if_from_ranges(&rec.blending_ranges);
|
||||
l.psd_id = rec.layer_id();
|
||||
// The layer's XMP packet (`shmd` › `cust` › `layerXMP`) becomes the field; the rest of
|
||||
// `shmd` stays in `psd_blocks`, where export puts the packet back.
|
||||
if let Some(i) = l.psd_blocks.iter().position(|(k, _)| k == b"shmd")
|
||||
&& let Some((xmp, rest)) = photocraft_psd::metadata::take_layer_xmp(&l.psd_blocks[i].1)
|
||||
{
|
||||
l.xmp = Some(Arc::from(xmp));
|
||||
match rest {
|
||||
Some(data) => l.psd_blocks[i].1 = Arc::new(data),
|
||||
None => {
|
||||
l.psd_blocks.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
let name = l.name.clone();
|
||||
l.mask = self.record_mask(rec, &name);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! A layer's own XMP packet (`Layer::xmp`, PSD `shmd` › `cust` › `layerXMP`) survives every
|
||||
//! layered format and keeps the rest of a Photoshop `shmd` block as it was.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Layer, Size};
|
||||
use photocraft_io::{ExportOptions, export, import};
|
||||
use photocraft_psd::PsdFile;
|
||||
use photocraft_psd::metadata::{layer_xmp, put_layer_xmp};
|
||||
|
||||
const A: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:app="http://example.com/app/1.0/"><app:arc>120</app:arc></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
const G: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:app="http://example.com/app/1.0/"><app:name>Café 🎨</app:name></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
/// `shmd` of a Photoshop 2026 layer without XMP: a `cust` item holding only `layerTime`.
|
||||
const PS_WITHOUT_XMP: &str =
|
||||
"000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00";
|
||||
|
||||
fn unhex(h: &str) -> Vec<u8> {
|
||||
(0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect()
|
||||
}
|
||||
|
||||
fn xmps(d: &Document) -> Vec<(String, Option<String>)> {
|
||||
d.walk().into_iter().map(|(_, _, l)| (l.name.clone(), l.xmp.as_deref().map(str::to_string))).collect()
|
||||
}
|
||||
|
||||
fn layer_shmd<'a>(f: &'a PsdFile, name: &str) -> Option<&'a [u8]> {
|
||||
f.layers().iter().find(|r| r.name() == name).and_then(|r| r.block(b"shmd")).map(|b| b.data.as_slice())
|
||||
}
|
||||
|
||||
fn sample(depth: SampleType) -> Document {
|
||||
let mut doc = Document::new("Layer XMP", Size::new(4, 4), ColorMode::Rgb, depth);
|
||||
let mut a = Layer::raster("A", doc.pixel_format());
|
||||
a.xmp = Some(Arc::from(A));
|
||||
let plain = Layer::raster("Plain", doc.pixel_format());
|
||||
let mut g = Layer::group("G", vec![plain]);
|
||||
g.xmp = Some(Arc::from(G));
|
||||
doc.layers.extend([a, g]);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_xmp_round_trips_through_every_layered_format_and_depth() {
|
||||
let psb = ExportOptions { force_psb: true, ..Default::default() };
|
||||
let tiff = ExportOptions { tiff_layers: true, ..Default::default() };
|
||||
for depth in SampleType::ALL {
|
||||
let doc = sample(depth);
|
||||
for (path, opts) in [("x.psd", &ExportOptions::default()), ("x.psb", &psb), ("x.tif", &tiff), ("x.pcraft", &ExportOptions::default())] {
|
||||
let bytes = export(&doc, path, opts).unwrap().bytes;
|
||||
let back = import(path, &bytes).unwrap().document;
|
||||
assert_eq!(xmps(&back), xmps(&doc), "{path} {depth:?}");
|
||||
}
|
||||
// Stored as Photoshop stores it; a layer without XMP gets no block.
|
||||
let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
let f = PsdFile::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(layer_shmd(&f, "A").and_then(layer_xmp).as_deref(), Some(A));
|
||||
assert_eq!(layer_shmd(&f, "G").and_then(layer_xmp).as_deref(), Some(G));
|
||||
assert!(layer_shmd(&f, "Plain").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photoshop_shmd_keeps_its_other_data() {
|
||||
let without = unhex(PS_WITHOUT_XMP);
|
||||
let with = put_layer_xmp(Some(&without), A).unwrap();
|
||||
// A layer as an older PhotoCraft kept it: Photoshop's block verbatim, no field.
|
||||
let mut doc = Document::new("PS", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);
|
||||
let mut l = Layer::raster("L", doc.pixel_format());
|
||||
l.psd_blocks.push((*b"shmd", Arc::new(with.clone())));
|
||||
doc.layers.push(l);
|
||||
let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
|
||||
// Opening it gives the packet to the field and keeps the rest of the block.
|
||||
let mut back = import("x.psd", &bytes).unwrap().document;
|
||||
let l = &back.layers[0];
|
||||
assert_eq!(l.xmp.as_deref(), Some(A));
|
||||
assert_eq!(l.psd_blocks.iter().find(|(k, _)| k == b"shmd").map(|(_, d)| d.as_slice()), Some(without.as_slice()));
|
||||
|
||||
// Unchanged, the block is written back byte for byte.
|
||||
let again = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&again).unwrap(), "L"), Some(with.as_slice()));
|
||||
|
||||
// Edited, `layerTime` stays; removed, the block is Photoshop's block without XMP.
|
||||
back.layers[0].xmp = Some(Arc::from(G));
|
||||
let edited = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&edited).unwrap(), "L"), Some(put_layer_xmp(Some(&without), G).unwrap().as_slice()));
|
||||
back.layers[0].xmp = None;
|
||||
let removed = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&removed).unwrap(), "L"), Some(without.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_shmd_is_kept_and_reported() {
|
||||
let mut doc = Document::new("Bad", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);
|
||||
let mut l = Layer::raster("L", doc.pixel_format());
|
||||
l.psd_blocks.push((*b"shmd", Arc::new(vec![0, 0, 0, 9])));
|
||||
l.xmp = Some(Arc::from(A));
|
||||
doc.layers.push(l);
|
||||
let out = export(&doc, "x.psd", &ExportOptions::default()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w.contains("XMP metadata was not saved")), "{:?}", out.warnings);
|
||||
assert_eq!(layer_shmd(&PsdFile::from_bytes(&out.bytes).unwrap(), "L"), Some([0, 0, 0, 9].as_slice()));
|
||||
}
|
||||
+48
-7
@@ -12,7 +12,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -111,12 +111,36 @@ impl Endpoint {
|
||||
.find(Endpoint::reachable)
|
||||
}
|
||||
|
||||
/// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default).
|
||||
/// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default). An IPv6
|
||||
/// server is `[address]` or `[address]:port`; written bare (more than one `:`) it keeps the
|
||||
/// default port, because its last `:` cannot be told apart from a port separator. Anything else
|
||||
/// after the bracket (`[::1]:abc`) stays the host, so a mistyped endpoint cannot resolve rather
|
||||
/// than quietly becoming the default one.
|
||||
pub fn parse(server: &str) -> Endpoint {
|
||||
if server.starts_with('/') {
|
||||
return Endpoint::Unix(PathBuf::from(server));
|
||||
}
|
||||
let (host, port) = server.rsplit_once(':').and_then(|(h, p)| p.parse().ok().map(|p| (h.to_string(), p))).unwrap_or((server.to_string(), 631));
|
||||
// `[IPv6]:port` - the brackets tell the address from the port, and are not part of the host.
|
||||
if let Some(rest) = server.strip_prefix('[')
|
||||
&& let Some((host, tail)) = rest.split_once(']')
|
||||
{
|
||||
// Nothing after the bracket, or a real `:port`, is understood. Anything else (`[::1]:abc`,
|
||||
// `[::1]:70000`, `[::1]junk`) keeps the whole string as the host, so the mistyped endpoint
|
||||
// stays unresolvable instead of quietly becoming the default one.
|
||||
let port = if tail.is_empty() {
|
||||
631
|
||||
} else if let Some(port) = tail.strip_prefix(':').and_then(|p| p.parse().ok()) {
|
||||
port
|
||||
} else {
|
||||
return Endpoint::Tcp(server.to_string(), 631);
|
||||
};
|
||||
return Endpoint::Tcp(host.to_string(), port);
|
||||
}
|
||||
// A bare IPv6 literal has more than one ':', so splitting on the last one would cut the
|
||||
// address in half: it is the host, and the port stays the default. A zone id (`fe80::1%eth0`)
|
||||
// carries no ':', so there a port can still follow the address.
|
||||
let host_port = if server.matches(':').count() > 1 && !server.contains('%') { None } else { server.rsplit_once(':') };
|
||||
let (host, port) = host_port.and_then(|(h, p)| p.parse().ok().map(|p| (h.to_string(), p))).unwrap_or((server.to_string(), 631));
|
||||
Endpoint::Tcp(host, port)
|
||||
}
|
||||
|
||||
@@ -142,17 +166,23 @@ impl Endpoint {
|
||||
Endpoint::Tcp(host, port) => {
|
||||
let addr = (host.as_str(), *port).to_socket_addrs().map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?.next();
|
||||
let addr = addr.ok_or_else(|| Error::Unreachable(format!("{host}:{port}: no address")))?;
|
||||
let s = TcpStream::connect_timeout(&addr, CONNECT).map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?;
|
||||
let _ = s.set_read_timeout(Some(REQUEST));
|
||||
let _ = s.set_write_timeout(Some(REQUEST));
|
||||
Ok(Stream::Tcp(s))
|
||||
open_tcp(host, *port, addr, |addr| TcpStream::connect_timeout(&addr, CONNECT))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The endpoint as an HTTP authority: an IPv6 host is bracketed, or its last colon reads as the
|
||||
/// port separator and the request carries a host CUPS has never heard of. A scoped address keeps
|
||||
/// its zone id and writes it escaped as "%25": "%" is not valid inside an authority (RFC 3986
|
||||
/// section 3.2.2 reserves it for escaping), and the escaped form is what CUPS, curl and the
|
||||
/// ipp:// URIs CUPS writes use for a zone. RFC 9844 (Aug 2025) obsoleted RFC 6874, which had made
|
||||
/// that form URI syntax, so this is interop rather than a standard; dropping the zone instead
|
||||
/// would name a different host on the wire than the socket was opened to. The socket still gets
|
||||
/// the raw address%zone, which is the form a resolver understands.
|
||||
fn host(&self) -> String {
|
||||
match self {
|
||||
Endpoint::Unix(_) => "localhost".into(),
|
||||
Endpoint::Tcp(host, port) if host.contains(':') => format!("[{}]:{port}", host.replace('%', "%25")),
|
||||
Endpoint::Tcp(host, port) => format!("{host}:{port}"),
|
||||
}
|
||||
}
|
||||
@@ -162,11 +192,22 @@ impl std::fmt::Display for Endpoint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Endpoint::Unix(p) => write!(f, "{}", p.display()),
|
||||
Endpoint::Tcp(h, p) if h.contains(':') => write!(f, "[{h}]:{p}"),
|
||||
Endpoint::Tcp(h, p) => write!(f, "{h}:{p}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open one address and put the request timeouts on it. The connect call is a parameter so the
|
||||
/// refusal path can be tested at all: no port is guaranteed to stay free between picking one and
|
||||
/// using it, and what a refused connect reported is what the caller is supposed to hear.
|
||||
fn open_tcp(host: &str, port: u16, addr: SocketAddr, open: impl FnOnce(SocketAddr) -> std::io::Result<TcpStream>) -> Result<Stream> {
|
||||
let s = open(addr).map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?;
|
||||
let _ = s.set_read_timeout(Some(REQUEST));
|
||||
let _ = s.set_write_timeout(Some(REQUEST));
|
||||
Ok(Stream::Tcp(s))
|
||||
}
|
||||
|
||||
enum Stream {
|
||||
#[cfg(unix)]
|
||||
Unix(std::os::unix::net::UnixStream),
|
||||
|
||||
+81
-3
@@ -158,7 +158,10 @@ fn a_print_job_carries_the_document_and_returns_its_id() {
|
||||
assert_eq!(op, OP_PRINT_JOB);
|
||||
assert_eq!(doc, pdf);
|
||||
let get = |n: &str| attrs.iter().find(|a| a.name == n).cloned().unwrap_or_else(|| panic!("{n}"));
|
||||
assert_eq!(get("printer-uri").values[0], format!("ipp://{}/printers/Office", ep.host()).as_bytes());
|
||||
let uri = String::from_utf8(get("printer-uri").values[0].clone()).unwrap();
|
||||
// Spelled out here rather than echoed back from host(), so the printer-uri the server receives is
|
||||
// pinned down even when the authority is an IP literal.
|
||||
assert!(uri.starts_with("ipp://127.0.0.1:") && uri.ends_with("/printers/Office"), "{uri}");
|
||||
assert_eq!(get("job-name").values[0], b"photo.psd");
|
||||
assert_eq!(get("requesting-user-name").values[0], b"diego");
|
||||
assert_eq!(get("document-format").values[0], b"application/pdf");
|
||||
@@ -186,9 +189,36 @@ fn error_statuses_and_broken_replies_are_errors() {
|
||||
assert!(matches!(printers(&ep), Err(Error::Protocol(_))));
|
||||
let (ep, _rx) = fake(b"not ipp at all".to_vec(), false, 200);
|
||||
assert!(matches!(printers(&ep), Err(Error::Protocol(_))));
|
||||
// Nobody listening.
|
||||
let e = printers(&Endpoint::Tcp("127.0.0.1".into(), 1)).unwrap_err();
|
||||
// Nobody reachable. A port is never guaranteed to be free, let alone to stay free: that is what
|
||||
// made the old port-1 case fail on a FreeBSD CI VM. A name that can never resolve (RFC 2606)
|
||||
// reaches the same exit without owning or releasing anything.
|
||||
let e = printers(&Endpoint::Tcp("printer.invalid".into(), 631)).unwrap_err();
|
||||
assert!(matches!(e, Error::Unreachable(_)), "{e}");
|
||||
assert!(e.to_string().contains("printer.invalid"), "{e} does not name the server it tried");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_connection_is_unreachable_and_keeps_why() {
|
||||
// The refused-connect path, with the machine no longer deciding what is closed: the connect call
|
||||
// is a parameter, so this test cannot race for an ephemeral port with anything.
|
||||
let addr: SocketAddr = "192.0.2.9:631".parse().unwrap();
|
||||
let asked_for = std::cell::RefCell::new(None);
|
||||
let open = |seen: SocketAddr| -> std::io::Result<TcpStream> {
|
||||
*asked_for.borrow_mut() = Some(seen);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "nobody is listening on this port"))
|
||||
};
|
||||
let e = match open_tcp("printserver", 631, addr, open) {
|
||||
Ok(_) => panic!("nothing opens {addr}"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(*asked_for.borrow(), Some(addr), "the connector is handed the resolved address");
|
||||
match &e {
|
||||
Error::Unreachable(m) => {
|
||||
assert!(m.contains("printserver:631"), "{e} does not name the endpoint");
|
||||
assert!(m.contains("nobody is listening on this port"), "{e} loses why the connect failed");
|
||||
}
|
||||
other => panic!("expected Unreachable, got {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -232,6 +262,54 @@ fn the_unix_socket_endpoint_works_and_detect_honours_cups_server() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An IPv6 print server is not a `host:port` split: a bare address has more than one ':', and the
|
||||
/// brackets of `[address]:port` must not end up inside the host, where no resolver can read them.
|
||||
#[test]
|
||||
fn an_ipv6_print_server_is_parsed_as_a_host_not_as_host_port() {
|
||||
assert_eq!(Endpoint::parse("::1"), Endpoint::Tcp("::1".into(), 631));
|
||||
assert_eq!(Endpoint::parse("fe80::1"), Endpoint::Tcp("fe80::1".into(), 631));
|
||||
assert_eq!(Endpoint::parse("2001:db8::1"), Endpoint::Tcp("2001:db8::1".into(), 631));
|
||||
assert_eq!(Endpoint::parse("[::1]"), Endpoint::Tcp("::1".into(), 631));
|
||||
assert_eq!(Endpoint::parse("[::1]:631"), Endpoint::Tcp("::1".into(), 631));
|
||||
assert_eq!(Endpoint::parse("[fe80::1]:6310"), Endpoint::Tcp("fe80::1".into(), 6310));
|
||||
// A zone id carries no ':', so a port can still follow it without brackets.
|
||||
assert_eq!(Endpoint::parse("fe80::1%eth0:631"), Endpoint::Tcp("fe80::1%eth0".into(), 631));
|
||||
// What already worked is unchanged.
|
||||
assert_eq!(Endpoint::parse("cups.example"), Endpoint::Tcp("cups.example".into(), 631));
|
||||
assert_eq!(Endpoint::parse("cups.example:6310"), Endpoint::Tcp("cups.example".into(), 6310));
|
||||
assert_eq!(Endpoint::parse("127.0.0.1:6310"), Endpoint::Tcp("127.0.0.1".into(), 6310));
|
||||
assert_eq!(Endpoint::parse("/var/run/cups/cups.sock"), Endpoint::Unix("/var/run/cups/cups.sock".into()));
|
||||
// A mistyped bracketed endpoint is not quietly the default one: the whole string stays the host,
|
||||
// so nothing can resolve it and detect() reports the endpoint unreachable.
|
||||
assert_eq!(Endpoint::parse("[::1]:abc"), Endpoint::Tcp("[::1]:abc".into(), 631));
|
||||
assert_eq!(Endpoint::parse("[::1]:70000"), Endpoint::Tcp("[::1]:70000".into(), 631));
|
||||
assert_eq!(Endpoint::parse("[::1]junk"), Endpoint::Tcp("[::1]junk".into(), 631));
|
||||
assert!(!Endpoint::parse("[::1]:abc").reachable());
|
||||
}
|
||||
|
||||
/// The authority a request carries (the `Host:` header and the `ipp://` printer-uri) has to bracket an
|
||||
/// IPv6 host, or its last colon reads as the port separator and CUPS sees a nonsense host.
|
||||
#[test]
|
||||
fn an_ipv6_endpoint_writes_its_authority_in_brackets() {
|
||||
assert_eq!(Endpoint::parse("::1").host(), "[::1]:631");
|
||||
assert_eq!(Endpoint::parse("[::1]:631").host(), "[::1]:631");
|
||||
assert_eq!(Endpoint::parse("[fe80::1]:6310").host(), "[fe80::1]:6310");
|
||||
assert_eq!(Endpoint::parse("cups.example").host(), "cups.example:631");
|
||||
assert_eq!(Endpoint::parse("cups.example:6310").host(), "cups.example:6310");
|
||||
assert_eq!(Endpoint::parse("127.0.0.1:6310").host(), "127.0.0.1:6310");
|
||||
// A scoped address keeps its zone id, but the authority writes it "%25"-escaped: a bare "%" is
|
||||
// not valid inside an authority, and the escaped form is what CUPS and curl-style ipp:// URIs
|
||||
// use. The host itself stays raw, because that is what the resolver gets.
|
||||
assert_eq!(Endpoint::parse("fe80::1%3:631").host(), "[fe80::1%253]:631");
|
||||
assert_eq!(Endpoint::parse("[fe80::1%3]:6310").host(), "[fe80::1%253]:6310");
|
||||
assert_eq!(Endpoint::parse("fe80::1%eth0:631").host(), "[fe80::1%25eth0]:631");
|
||||
assert_eq!(Endpoint::parse("fe80::1%3:631"), Endpoint::Tcp("fe80::1%3".into(), 631));
|
||||
// What the user is shown is written the same way, with the zone exactly as it was typed.
|
||||
assert_eq!(Endpoint::parse("::1").to_string(), "[::1]:631");
|
||||
assert_eq!(Endpoint::parse("cups.example:6310").to_string(), "cups.example:6310");
|
||||
assert_eq!(Endpoint::parse("fe80::1%3:631").to_string(), "[fe80::1%3]:631");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_start_with_the_mandatory_attributes() {
|
||||
let r = Request::new(OP_PRINT_JOB, 9).end();
|
||||
|
||||
@@ -106,6 +106,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla
|
||||
| PSB 8-byte-length keys | ✓ | ✓ | – | LMsk Lr16 Lr32 Layr Mt16 Mt32 Mtrn Alph FMsk lnk2 FEid FXid PxSD |
|
||||
| Lr16 / Lr32 / Layr layer info | ✓ | ✓ | ✓ | lifted into `layer_info`; re-inserted at its original position |
|
||||
| luni lsct lsdk lyid lnsr clbl infx knko lspf lclr iOpa shmd | ✓ | ✓ | ✓ | `TaggedBlock::parsed()` |
|
||||
| Layer XMP (`shmd` › `cust` › `layerXMP`) | ✓ | ✓ | ✓ | `metadata::layer_xmp` / `take_layer_xmp` / `put_layer_xmp`, laid out as Photoshop 2026 writes it |
|
||||
| ActionDescriptor (all OSTypes) | ✓ | ✓ | ✓ | including references, `ObAr` (best effort), `UnFl`, `Pth `, version-16 wrapper |
|
||||
| Layer tree (groups) | ✓ | ✓ | ✓ | open/closed folders plus bounding dividers; tolerant of malformed nesting |
|
||||
| RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone |
|
||||
|
||||
+158
-1
@@ -1,11 +1,12 @@
|
||||
//! `shmd` (metadata setting) layer block: a list of keyed sub-blocks, such as `cmls` (layer comp
|
||||
//! state, a versioned descriptor), `cust` and `mlst`.
|
||||
//! state, a versioned descriptor), `cust` (the layer's modify time and XMP packet) and `mlst`.
|
||||
//!
|
||||
//! Layout (Adobe PSD spec, "Metadata setting"): u32 count, then per item the signature `8BIM`,
|
||||
//! a 4-byte key, a copy-on-sheet-duplication byte, 3 padding bytes, a u32 length and the data.
|
||||
//! Photoshop pads item data to an even length (the padding is part of the stored length), so
|
||||
//! parsing and writing are exact: `write(parse(b)) == b`.
|
||||
|
||||
use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor};
|
||||
use crate::error::{PsdError, Result};
|
||||
use crate::io::{Reader, WriteExt};
|
||||
|
||||
@@ -71,10 +72,166 @@ pub fn write_shmd(items: &[MetadataItem]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The `shmd` item that holds a layer's own metadata (its modify time and XMP).
|
||||
const CUST: [u8; 4] = *b"cust";
|
||||
/// Key of a layer's XMP packet in the `cust` descriptor.
|
||||
const LAYER_XMP: &str = "layerXMP";
|
||||
|
||||
// A layer's XMP packet (Photoshop's `layer.xmpMetadata.rawData`), as observed in files Photoshop
|
||||
// 2026 saves: a `TEXT` item `layerXMP` (UTF-16 with a terminating NUL) in the `metadata`
|
||||
// descriptor (version 16, class name a lone NUL) of the `shmd` item `cust`, after the
|
||||
// `layerTime` double that every Photoshop layer has. A layer without XMP has no `layerXMP` item.
|
||||
|
||||
fn pad_even(mut v: Vec<u8>) -> Vec<u8> {
|
||||
if v.len() % 2 == 1 {
|
||||
v.push(0);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The `cust` descriptor of `item`, or `None` when it isn't one.
|
||||
fn cust_descriptor(item: &MetadataItem) -> Option<VersionedDescriptor> {
|
||||
(item.key == CUST).then(|| VersionedDescriptor::parse_prefix(&item.data).ok().map(|(d, _)| d)).flatten()
|
||||
}
|
||||
|
||||
/// The XMP packet stored on a layer whose `shmd` block data is `shmd`, or `None` when it has
|
||||
/// none (or the block can't be read).
|
||||
pub fn layer_xmp(shmd: &[u8]) -> Option<String> {
|
||||
let items = parse_shmd(shmd).ok()?;
|
||||
items.iter().filter_map(cust_descriptor).find_map(|d| match d.descriptor.get(LAYER_XMP) {
|
||||
Some(Value::Text(t)) => Some(t.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Splits a layer's XMP packet out of its `shmd` block data: the packet, and the block without
|
||||
/// it (`None` when nothing is left). `None` when the block holds no packet, so the caller keeps
|
||||
/// the original bytes. A `cust` item left empty is dropped, the other items are kept as stored.
|
||||
pub fn take_layer_xmp(shmd: &[u8]) -> Option<(String, Option<Vec<u8>>)> {
|
||||
let mut items = parse_shmd(shmd).ok()?;
|
||||
let (i, mut vd) = items.iter().enumerate().find_map(|(i, it)| cust_descriptor(it).filter(|d| d.descriptor.get(LAYER_XMP).is_some()).map(|d| (i, d)))?;
|
||||
let at = vd.descriptor.items.iter().position(|(k, _)| k.is(LAYER_XMP))?;
|
||||
let xmp = match vd.descriptor.items.remove(at).1 {
|
||||
Value::Text(t) => t.to_string_lossy(),
|
||||
_ => return None,
|
||||
};
|
||||
if vd.descriptor.items.is_empty() {
|
||||
items.remove(i);
|
||||
} else {
|
||||
items[i].data = pad_even(vd.to_bytes());
|
||||
}
|
||||
Some((xmp, (!items.is_empty()).then(|| write_shmd(&items))))
|
||||
}
|
||||
|
||||
/// `shmd` block data (`shmd`, or a new block when `None`) with `xmp` as the layer's XMP packet,
|
||||
/// written as Photoshop writes it: it replaces an existing packet in place, or is appended to
|
||||
/// the `cust` descriptor (a new `cust` item when there is none). An unreadable block is an
|
||||
/// error, so the caller never replaces data it couldn't read.
|
||||
pub fn put_layer_xmp(shmd: Option<&[u8]>, xmp: &str) -> Result<Vec<u8>> {
|
||||
let mut items = match shmd {
|
||||
Some(b) => parse_shmd(b)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let value = Value::Text(UnicodeString::new_nul(xmp));
|
||||
match items.iter().position(|it| it.key == CUST) {
|
||||
Some(i) => {
|
||||
let (mut vd, _) = VersionedDescriptor::parse_prefix(&items[i].data)?;
|
||||
match vd.descriptor.items.iter_mut().find(|(k, _)| k.is(LAYER_XMP)) {
|
||||
Some(entry) => entry.1 = value,
|
||||
None => vd.descriptor.items.push((Id::new(LAYER_XMP), value)),
|
||||
}
|
||||
items[i].data = pad_even(vd.to_bytes());
|
||||
}
|
||||
None => {
|
||||
let d = Descriptor { name: UnicodeString::new_nul(""), class_id: Id::new("metadata"), items: vec![(Id::new(LAYER_XMP), value)] };
|
||||
items.push(MetadataItem::new(CUST, VersionedDescriptor::new(d).to_bytes()));
|
||||
}
|
||||
}
|
||||
Ok(write_shmd(&items))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unhex(lines: &[&str]) -> Vec<u8> {
|
||||
let h: String = lines.concat();
|
||||
(0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect()
|
||||
}
|
||||
|
||||
/// `shmd` of a layer saved by Photoshop 2026 after a script set its XMP to [`PS_PACKET`].
|
||||
const PS_WITH_XMP: &[&str] = &[
|
||||
"000000013842494d63757374000000000000024800000010000000010000000000086d65746164617461000000020000",
|
||||
"00096c6179657254696d65646f756241dab643ffd54363000000086c61796572584d505445585400000100003c007800",
|
||||
"3a0078006d0070006d00650074006100200078006d006c006e0073003a0078003d002200610064006f00620065003a00",
|
||||
"6e0073003a006d006500740061002f0022003e003c007200640066003a00520044004600200078006d006c006e007300",
|
||||
"3a007200640066003d00220068007400740070003a002f002f007700770077002e00770033002e006f00720067002f00",
|
||||
"31003900390039002f00300032002f00320032002d007200640066002d00730079006e007400610078002d006e007300",
|
||||
"230022003e003c007200640066003a004400650073006300720069007000740069006f006e0020007200640066003a00",
|
||||
"610062006f00750074003d0022002200200078006d006c006e0073003a00730061006d0070006c0065003d0022006800",
|
||||
"7400740070003a002f002f006500780061006d0070006c0065002e0063006f006d002f00730061006d0070006c006500",
|
||||
"2f0031002e0030002f0022003e003c00730061006d0070006c0065003a00760061006c00750065003e0061006c007000",
|
||||
"680061002d003100320033003c002f00730061006d0070006c0065003a00760061006c00750065003e003c002f007200",
|
||||
"640066003a004400650073006300720069007000740069006f006e003e003c002f007200640066003a00520044004600",
|
||||
"3e003c002f0078003a0078006d0070006d006500740061003e000000",
|
||||
];
|
||||
/// `shmd` of a layer without XMP in the same file (its own `layerTime` only).
|
||||
const PS_WITHOUT_XMP: &[&str] =
|
||||
&["000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00"];
|
||||
const PS_PACKET: &str = concat!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">"#,
|
||||
r#"<rdf:Description rdf:about="" xmlns:sample="http://example.com/sample/1.0/"><sample:value>alpha-123</sample:value>"#,
|
||||
r#"</rdf:Description></rdf:RDF></x:xmpmeta>"#
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn reads_photoshop_layer_xmp() {
|
||||
assert_eq!(layer_xmp(&unhex(PS_WITH_XMP)).as_deref(), Some(PS_PACKET));
|
||||
assert_eq!(layer_xmp(&unhex(PS_WITHOUT_XMP)), None);
|
||||
assert!(take_layer_xmp(&unhex(PS_WITHOUT_XMP)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_then_put_is_exact() {
|
||||
let ps = unhex(PS_WITH_XMP);
|
||||
let (xmp, rest) = take_layer_xmp(&ps).unwrap();
|
||||
assert_eq!(xmp, PS_PACKET);
|
||||
let rest = rest.unwrap();
|
||||
// What's left is a layer without XMP, shaped as Photoshop writes one.
|
||||
assert_eq!(rest.len(), unhex(PS_WITHOUT_XMP).len());
|
||||
assert_eq!(layer_xmp(&rest), None);
|
||||
assert_eq!(put_layer_xmp(Some(&rest), &xmp).unwrap(), ps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_replaces_in_place_and_creates_a_block() {
|
||||
let ps = unhex(PS_WITH_XMP);
|
||||
let edited = put_layer_xmp(Some(&ps), "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>").unwrap();
|
||||
assert_eq!(layer_xmp(&edited).as_deref(), Some("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>"));
|
||||
// `layerTime` is kept, still first.
|
||||
let items = parse_shmd(&edited).unwrap();
|
||||
let d = cust_descriptor(&items[0]).unwrap().descriptor;
|
||||
assert!(d.items[0].0.is("layerTime") && d.items[1].0.is(LAYER_XMP) && d.items.len() == 2);
|
||||
|
||||
let fresh = put_layer_xmp(None, PS_PACKET).unwrap();
|
||||
assert_eq!(layer_xmp(&fresh).as_deref(), Some(PS_PACKET));
|
||||
assert_eq!(take_layer_xmp(&fresh), Some((PS_PACKET.to_string(), None)));
|
||||
// Other items (here a layer comp state) stay as they were.
|
||||
let comps = write_shmd(&[MetadataItem::new(*b"cmls", vec![1, 2])]);
|
||||
let both = put_layer_xmp(Some(&comps), PS_PACKET).unwrap();
|
||||
assert_eq!(parse_shmd(&both).unwrap()[0], parse_shmd(&comps).unwrap()[0]);
|
||||
assert_eq!(take_layer_xmp(&both).unwrap().1.unwrap(), comps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_refuses_an_unreadable_block() {
|
||||
assert!(put_layer_xmp(Some(&[0, 0, 0, 9]), PS_PACKET).is_err());
|
||||
let bad_cust = write_shmd(&[MetadataItem::new(CUST, vec![0, 0, 0, 16, 1])]);
|
||||
assert!(put_layer_xmp(Some(&bad_cust), PS_PACKET).is_err());
|
||||
assert_eq!(layer_xmp(&bad_cust), None);
|
||||
assert!(take_layer_xmp(&bad_cust).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_exact() {
|
||||
let items = vec![MetadataItem::new(*b"cmls", vec![1, 2, 3]), MetadataItem { copy: true, ..MetadataItem::new(*b"cust", vec![9; 4]) }];
|
||||
|
||||
+40
-11
@@ -14,7 +14,7 @@ use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, write_sample};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, read_samples, write_sample};
|
||||
use photocraft_geom::{Rect, TILE_SIZE, TileCoord};
|
||||
|
||||
/// A checked surface allocation could not be represented or reserved.
|
||||
@@ -533,9 +533,7 @@ impl Surface {
|
||||
match tile {
|
||||
Some(t) => {
|
||||
let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n;
|
||||
for (i, d) in dst.iter_mut().enumerate() {
|
||||
*d = read_sample(&t.data, self.format.sample, base + i);
|
||||
}
|
||||
read_samples(&t.data, self.format.sample, base, dst);
|
||||
}
|
||||
None if n == 1 => dst.fill(dp[0]),
|
||||
None => {
|
||||
@@ -559,8 +557,8 @@ impl Surface {
|
||||
let n = fmt.channels();
|
||||
let mut stack = [0.0; 8];
|
||||
let mut heap = Vec::new();
|
||||
let px = self.default_samples(&mut stack, &mut heap);
|
||||
let dp = to_rgba(&fmt, px);
|
||||
let dp = to_rgba(&fmt, self.default_samples(&mut stack, &mut heap));
|
||||
let mut row = Vec::new();
|
||||
for tc in r.tiles() {
|
||||
let tr = tc.rect().intersect(&r);
|
||||
let tile = self.tiles.get(&tc);
|
||||
@@ -604,11 +602,17 @@ impl Surface {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
for (i, d) in dst.iter_mut().enumerate() {
|
||||
for (c, v) in px.iter_mut().enumerate() {
|
||||
*v = read_sample(&t.data, fmt.sample, base + i * n + c);
|
||||
}
|
||||
*d = to_rgba(&fmt, px);
|
||||
// The row's samples in one pass, then its colour model resolved once:
|
||||
// RGB and grey take their channels as `to_rgba` does, other models go
|
||||
// through it.
|
||||
row.resize(dst.len() * n, 0.0);
|
||||
read_samples(&t.data, fmt.sample, base, &mut row);
|
||||
let a = |s: &[f32], i: usize| if fmt.alpha { s[i] } else { 1.0 };
|
||||
let pixels = dst.iter_mut().zip(row.chunks_exact(n));
|
||||
match fmt.mode {
|
||||
ColorMode::Rgb => pixels.for_each(|(d, s)| *d = [s[0], s[1], s[2], a(s, 3)]),
|
||||
ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => pixels.for_each(|(d, s)| *d = [s[0], s[0], s[0], a(s, 1)]),
|
||||
_ => pixels.for_each(|(d, s)| *d = to_rgba(&fmt, s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1657,6 +1661,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgba_reads_match_individual_pixels_bitwise_in_every_model_and_depth() {
|
||||
// Across tile edges and a missing tile; float samples include -0, out-of-range and NaN.
|
||||
let rect = Rect::new(-3, -1, 300, 2);
|
||||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] {
|
||||
for depth in SampleType::ALL {
|
||||
for alpha in [false, true] {
|
||||
let fmt = PixelFormat::new(mode, depth, alpha);
|
||||
let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]);
|
||||
let values = [-0.0, 0.1, 0.5, 1.0, 1.5, -0.25, f32::NAN, 0.75];
|
||||
for (i, x) in (-2..260).enumerate() {
|
||||
let px: Vec<f32> = (0..fmt.channels()).map(|c| values[(i + c * 3) % values.len()]).collect();
|
||||
s.write_pixel(x, 0, &px);
|
||||
}
|
||||
let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize];
|
||||
s.read_rgba_into(rect, &mut out);
|
||||
for (i, actual) in out.iter().enumerate() {
|
||||
let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32);
|
||||
assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{fmt:?}, pixel={i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_content_bounds_scans_against_the_given_pixel() {
|
||||
let mut s = Surface::new(PixelFormat::GRAY8);
|
||||
|
||||
@@ -8,9 +8,6 @@ license.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
photocraft-geom = { workspace = true }
|
||||
photocraft-color = { workspace = true }
|
||||
photocraft-raster = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
|
||||
+91
-12
@@ -1113,6 +1113,14 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
|
||||
let prev = previous.and_then(parse_txt2);
|
||||
let prev_objects: &[E] = prev.as_ref().and_then(|p| p.path(&["1", "1"]).and_then(E::as_array)).unwrap_or(&[]);
|
||||
let mut slots: Vec<E> = prev_objects.to_vec();
|
||||
// The older Photoshop's objects (#6971): named keys at `/DocumentObjects /TextObjects`
|
||||
// instead of the numbered `/1 /1`, one entry per layer by `TextIndex` position (the same
|
||||
// numbering the slots take), its text under `Model /Text` and its run lengths under `/Length`.
|
||||
// Photoshop re-renders a type layer from this copy when the file has one, so an edit that
|
||||
// left the old text here showed the old text back on reopen. The entries are only ever edited
|
||||
// in place, never grown: a layer the block has no entry for has no stale copy to fix.
|
||||
let mut td: Option<Vec<E>> = prev.as_ref().and_then(|p| p.path(&["DocumentObjects", "TextObjects"])).and_then(E::as_array).map(<[E]>::to_vec);
|
||||
let mut td_changed = false;
|
||||
let mut fonts: Vec<E> = prev.as_ref().and_then(|p| p.path(&["0", "1", "0"]).and_then(E::as_array)).map(<[E]>::to_vec).unwrap_or_default();
|
||||
let fonts_before = fonts.len();
|
||||
// Looked up once per save, not per layer: a crafted block with many objects must not cost
|
||||
@@ -1127,6 +1135,21 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
|
||||
let text = format!("{}\r", layer.text.replace('\n', "\r"));
|
||||
let modes = txt2_mode_runs(layer);
|
||||
let at = *index as usize;
|
||||
// The older Photoshop's copy of this object (#6971), refitted like the numbered one
|
||||
// below. The entry's own text is the check, so a file a previous save left with a stale
|
||||
// copy beside a current `/1 /1` object is repaired here too.
|
||||
if let Some(entries) = td.as_mut() {
|
||||
let fixed = match entries.get(at) {
|
||||
Some(entry) if entry.path(&["Model", "Text"]).and_then(E::as_str) != Some(text.as_str()) => td_edited_object(entry, &text),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(fixed) = fixed
|
||||
&& let Some(slot) = entries.get_mut(at)
|
||||
{
|
||||
*slot = fixed;
|
||||
td_changed = true;
|
||||
}
|
||||
}
|
||||
// A stub an earlier save wrote beside Photoshop's objects counts as no object at all, so
|
||||
// it is replaced like a missing one (below) and re-saving such a file repairs it, whether
|
||||
// or not the layer's text changed.
|
||||
@@ -1191,6 +1214,14 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
|
||||
Some(objs @ E::Dict(_)) => objs.set("1", E::Array(slots)),
|
||||
_ => outer.set("1", E::Dict(vec![("1".into(), E::Array(slots))])),
|
||||
}
|
||||
// The older Photoshop's objects, whatever the loop fixed in them (an untouched list is left
|
||||
// exactly as the file has it, so the byte-for-byte return below still holds).
|
||||
if td_changed
|
||||
&& let Some(entries) = td
|
||||
&& let Some(objects @ E::Dict(_)) = outer.get_mut("DocumentObjects")
|
||||
{
|
||||
objects.set("TextObjects", E::Array(entries));
|
||||
}
|
||||
// Nothing changed: the file's own bytes (writing them back would re-encode strings and numbers).
|
||||
if let (Some(bytes), Some(p)) = (previous, &prev)
|
||||
&& *p == outer
|
||||
@@ -1246,7 +1277,7 @@ fn new_object(template: &E, at: usize, text: &str) -> Option<E> {
|
||||
}
|
||||
}
|
||||
if let Some(runs) = view.path(&["1", "0"]).and_then(E::as_array) {
|
||||
let fitted = runs_per(runs, ¶graphs)?;
|
||||
let fitted = runs_per(runs, ¶graphs, "1")?;
|
||||
view.get_mut("1")?.set("0", E::Array(fitted));
|
||||
}
|
||||
Some(object)
|
||||
@@ -1299,34 +1330,82 @@ fn edited_object(object: &E, text: &str) -> Option<E> {
|
||||
let Some(runs) = value.get("0").and_then(E::as_array).filter(|r| r.iter().all(|x| matches!(x, E::Dict(_)) && x.get("1").is_some())) else {
|
||||
continue;
|
||||
};
|
||||
let fitted = if key.as_str() == "5" { runs_per(runs, ¶graphs)? } else { runs_to_length(runs, total)? };
|
||||
let fitted = if key.as_str() == "5" { runs_per(runs, ¶graphs, "1")? } else { runs_to_length(runs, total, "1")? };
|
||||
value.set("0", E::Array(fitted));
|
||||
}
|
||||
Some(object)
|
||||
}
|
||||
|
||||
/// `runs` (`<< … /1 length >>`) remade with the lengths `lens`: run i keeps the content of the
|
||||
/// file's run i, else of its last one. `None` for an empty `runs`.
|
||||
fn runs_per(runs: &[E], lens: &[usize]) -> Option<Vec<E>> {
|
||||
/// The older Photoshop's `Txt2` text object `object` (`<< /Model << /Text … /ParagraphRun … >>
|
||||
/// /View … >>`) for the changed engine text `text` (`\r` breaks, trailing `\r`): the model's text
|
||||
/// replaced and every run array of the model refitted the way [`edited_object`] refits the
|
||||
/// numbered objects' — the paragraph runs (`/ParagraphRun`) one per paragraph of the new text, the
|
||||
/// others (`/StyleRun`, `/KernRun`, …) cut or extended to the new total. The model's other keys,
|
||||
/// the view and the rest are kept: these blocks (the objects at `/DocumentObjects /TextObjects`
|
||||
/// that older Photoshop versions write and re-render from, #6971) name their keys and number
|
||||
/// their runs with `/Length` in UTF-16 units instead of `/1`. `None` when the object or one of
|
||||
/// its run arrays isn't shaped as Photoshop writes it: the caller then leaves the entry as the
|
||||
/// file has it, rather than write text its runs don't cover (#6968).
|
||||
fn td_edited_object(object: &E, text: &str) -> Option<E> {
|
||||
let mut object = object.clone();
|
||||
let model = object.get_mut("Model").filter(|m| matches!(m, E::Dict(_)))?;
|
||||
let E::Dict(entries) = model else { return None };
|
||||
// The text must be there to replace: refitted runs over a text the model doesn't hold would
|
||||
// be a half-edited object.
|
||||
if !entries.iter().any(|(k, v)| k == "Text" && matches!(v, E::String(_))) {
|
||||
return None;
|
||||
}
|
||||
let total = utf16_len(text) as usize;
|
||||
let paragraphs: Vec<usize> = text.split_inclusive('\r').map(|p| p.encode_utf16().count()).collect();
|
||||
for (key, value) in entries.iter_mut() {
|
||||
if key.as_str() == "Text" {
|
||||
*value = E::String(text.to_string());
|
||||
continue;
|
||||
}
|
||||
if !matches!(value, E::Dict(_)) {
|
||||
continue;
|
||||
}
|
||||
// A model dict without `RunArray` isn't a run array (the view's keys live elsewhere), so
|
||||
// it is skipped; a named `RunArray` is unambiguous — malformed, the whole entry is left to
|
||||
// the file rather than half-updated.
|
||||
let Some(runs) = value.get("RunArray") else { continue };
|
||||
let fitted = match runs {
|
||||
E::Array(runs) if runs.iter().all(|x| matches!(x, E::Dict(_)) && x.get("Length").is_some()) => {
|
||||
if key.as_str() == "ParagraphRun" {
|
||||
runs_per(runs, ¶graphs, "Length")?
|
||||
} else {
|
||||
runs_to_length(runs, total, "Length")?
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
value.set("RunArray", E::Array(fitted));
|
||||
}
|
||||
Some(object)
|
||||
}
|
||||
|
||||
/// `runs` (`<< … /1 length >>`, the length key named `len_key`) remade with the lengths `lens`:
|
||||
/// run i keeps the content of the file's run i, else of its last one. `None` for an empty `runs`.
|
||||
fn runs_per(runs: &[E], lens: &[usize], len_key: &str) -> Option<Vec<E>> {
|
||||
let last = runs.last()?;
|
||||
lens.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &len)| {
|
||||
let mut r = runs.get(i).unwrap_or(last).clone();
|
||||
r.set("1", E::Int(i64::try_from(len).ok()?));
|
||||
r.set(len_key, E::Int(i64::try_from(len).ok()?));
|
||||
Some(r)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `runs` (`<< … /1 length >>`) covering `total` UTF-16 units: the leading runs as they were, cut
|
||||
/// where `total` ends, the last kept run extended when `total` is longer. Empty runs are dropped.
|
||||
/// `None` when `runs` is empty or a length isn't a count.
|
||||
fn runs_to_length(runs: &[E], total: usize) -> Option<Vec<E>> {
|
||||
/// `runs` (`<< … /1 length >>`, the length key named `len_key`) covering `total` UTF-16 units:
|
||||
/// the leading runs as they were, cut where `total` ends, the last kept run extended when `total`
|
||||
/// is longer. Empty runs are dropped. `None` when `runs` is empty or a length isn't a count.
|
||||
fn runs_to_length(runs: &[E], total: usize, len_key: &str) -> Option<Vec<E>> {
|
||||
let mut out: Vec<(E, usize)> = Vec::new();
|
||||
let mut left = total;
|
||||
for r in runs {
|
||||
let len = r.get("1").and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())?;
|
||||
let len = r.get(len_key).and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())?;
|
||||
let take = len.min(left);
|
||||
if take > 0 {
|
||||
out.push((r.clone(), take));
|
||||
@@ -1341,7 +1420,7 @@ fn runs_to_length(runs: &[E], total: usize) -> Option<Vec<E>> {
|
||||
}
|
||||
out.into_iter()
|
||||
.map(|(mut r, len)| {
|
||||
r.set("1", E::Int(i64::try_from(len).ok()?));
|
||||
r.set(len_key, E::Int(i64::try_from(len).ok()?));
|
||||
Some(r)
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -1085,6 +1085,202 @@ fn txt2_keeps_a_kept_objects_extras_and_drops_them_with_its_text() {
|
||||
assert!(object.path(&["0", "keep"]).is_none(), "model extras of another text are dropped");
|
||||
}
|
||||
|
||||
/// The `DocumentObjects` value older Photoshop writes beside the numbered objects
|
||||
/// (`/DocumentObjects /TextObjects`, named keys, run lengths under `/Length` in UTF-16 units,
|
||||
/// #6971): one entry per layer, its `\r`-terminated text in `Model /Text`, one paragraph run per
|
||||
/// paragraph, one style and kern run covering the whole text.
|
||||
fn photoshop_era_objects(texts: &[&str]) -> crate::engine_data::Value {
|
||||
use crate::engine_data::Value as E;
|
||||
let run = |len: i64| E::Dict(vec![("RunData".into(), E::Dict(vec![("0".into(), E::String(String::new()))])), ("Length".into(), E::Int(len))]);
|
||||
let entries = texts
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let text = format!("{t}\r");
|
||||
let paragraphs: Vec<i64> = text.split_inclusive('\r').map(|p| p.encode_utf16().count() as i64).collect();
|
||||
let total = text.encode_utf16().count() as i64;
|
||||
E::Dict(vec![
|
||||
(
|
||||
"Model".into(),
|
||||
E::Dict(vec![
|
||||
("Text".into(), E::String(text)),
|
||||
("ParagraphRun".into(), E::Dict(vec![("RunArray".into(), E::Array(paragraphs.iter().map(|&n| run(n)).collect()))])),
|
||||
("StyleRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run(total)]))])),
|
||||
("KernRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run(total)]))])),
|
||||
]),
|
||||
),
|
||||
("View".into(), E::Dict(vec![("0".into(), E::Array(vec![E::Dict(vec![("0".into(), E::Int(0))])]))])),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
E::Dict(vec![("TextObjects".into(), E::Array(entries))])
|
||||
}
|
||||
|
||||
/// A whole `Txt2` block shaped like the older Photoshop's: document resources and the objects at
|
||||
/// `/DocumentObjects /TextObjects`, no numbered `/1 /1` list at all.
|
||||
fn photoshop_era_txt2(texts: &[&str]) -> Vec<u8> {
|
||||
use crate::engine_data::Value as E;
|
||||
crate::engine_data::write_bare(&[
|
||||
("98".into(), E::Dict(vec![("0".into(), E::Int(14))])),
|
||||
("0".into(), E::dict()),
|
||||
("DocumentObjects".into(), photoshop_era_objects(texts)),
|
||||
])
|
||||
}
|
||||
|
||||
/// #6971: Photoshop re-renders a type layer from the objects older Photoshop keeps at
|
||||
/// `/DocumentObjects /TextObjects` when the file has them, so an edit that left the old text
|
||||
/// there showed the old text back on reopen. The save refits that copy the way it refits the
|
||||
/// numbered ones — the new text, one paragraph run per paragraph of it, the other runs to its
|
||||
/// total — and keeps the entries' view and the rest.
|
||||
#[test]
|
||||
fn edited_text_updates_the_photoshop_era_objects() {
|
||||
use crate::engine_data::Value as E;
|
||||
use photocraft_doc::text::Kerning;
|
||||
let prev = photoshop_era_txt2(&["Line 1\rLine 2"]);
|
||||
let before = crate::psd::parse_txt2(&prev).unwrap();
|
||||
let t = styled("Hi\nBye", CharStyle { kerning: Kerning::Optical, ..Default::default() });
|
||||
let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();
|
||||
let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");
|
||||
assert_eq!(entries.len(), 1, "no entry is added");
|
||||
let entry = entries.first().expect("the entry");
|
||||
let model = entry.get("Model").expect("the model");
|
||||
assert_eq!(model.get("Text").and_then(E::as_str), Some("Hi\rBye\r"), "the stale text is replaced");
|
||||
let lens = |key: &str| -> Vec<i64> {
|
||||
model
|
||||
.path(&[key, "RunArray"])
|
||||
.and_then(E::as_array)
|
||||
.map(|rs| rs.iter().map(|r| r.get("Length").and_then(E::as_i64).unwrap_or(-1)).collect())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
assert_eq!(lens("ParagraphRun"), vec![3, 4], "one paragraph run per paragraph of the new text");
|
||||
assert_eq!(lens("StyleRun"), vec![7], "the style runs cover the new text's UTF-16 units");
|
||||
assert_eq!(lens("KernRun"), vec![7]);
|
||||
assert_eq!(
|
||||
entry.get("View"),
|
||||
before.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()).and_then(|e| e.get("View")),
|
||||
"the view is kept"
|
||||
);
|
||||
// The numbered list is written alongside, as it was before this fix.
|
||||
let slots = out.path(&["1", "1"]).and_then(E::as_array).expect("the numbered objects");
|
||||
assert_eq!(slots.len(), 1);
|
||||
assert_eq!(slots.first().and_then(|o| o.path(&["0", "0"])).and_then(E::as_str), Some("Hi\rBye\r"));
|
||||
}
|
||||
|
||||
/// Only the entries of layers the save holds change: another layer's object — one no layer names
|
||||
/// — is written back as the file has it.
|
||||
#[test]
|
||||
fn only_the_edited_photoshop_era_object_changes() {
|
||||
use crate::engine_data::Value as E;
|
||||
use photocraft_doc::text::Kerning;
|
||||
let prev = photoshop_era_txt2(&["One", "Two"]);
|
||||
let before = crate::psd::parse_txt2(&prev).unwrap();
|
||||
let style = |kerning: Kerning| CharStyle { kerning, ..Default::default() };
|
||||
let t0 = runs_of("One", &[(3, style(Kerning::Metrics))]);
|
||||
let t1 = runs_of("Changed", &[(7, style(Kerning::Optical))]);
|
||||
let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t0), (1, &t1)], Some(&prev))).unwrap();
|
||||
let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");
|
||||
let was = before.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects before");
|
||||
assert_eq!(entries.len(), 2, "no entry is added");
|
||||
assert_eq!(entries.first(), was.first(), "the unchanged entry is written back as it was");
|
||||
assert_eq!(entries.get(1).and_then(|e| e.path(&["Model", "Text"])).and_then(E::as_str), Some("Changed\r"), "the edited entry takes the new text");
|
||||
}
|
||||
|
||||
/// Files saved by the old code have both lists: the numbered object current, the older copy still
|
||||
/// holding the text of an earlier edit. Re-saving repairs the stale copy even when the numbered
|
||||
/// object's text matches the layer (nothing else about the file changes).
|
||||
#[test]
|
||||
fn legacy_file_with_both_object_lists_repairs_the_stale_one() {
|
||||
use crate::engine_data::Value as E;
|
||||
use photocraft_doc::text::Kerning;
|
||||
let mut prev = photoshop_txt2(&[(4, 1)]);
|
||||
prev.extend_from_slice(&crate::engine_data::write_bare(&[("DocumentObjects".into(), photoshop_era_objects(&["Old stuff"]))]));
|
||||
let before = crate::psd::parse_txt2(&prev).unwrap();
|
||||
let t = styled("AVA", CharStyle { kerning: Kerning::Metrics, ..Default::default() });
|
||||
let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();
|
||||
let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");
|
||||
assert_eq!(entries.len(), 1);
|
||||
let model = entries.first().expect("the entry").get("Model").expect("the model");
|
||||
assert_eq!(model.get("Text").and_then(E::as_str), Some("AVA\r"), "the stale copy is repaired");
|
||||
let lens = model
|
||||
.path(&["StyleRun", "RunArray"])
|
||||
.and_then(E::as_array)
|
||||
.map(|rs| rs.iter().map(|r| r.get("Length").and_then(E::as_i64).unwrap_or(-1)).collect::<Vec<_>>());
|
||||
assert_eq!(lens, Some(vec![4]), "its runs cover the layer's text");
|
||||
let slots = out.path(&["1", "1"]).and_then(E::as_array).expect("the numbered objects");
|
||||
assert_eq!(slots.first().and_then(|o| o.path(&["0", "0"])).and_then(E::as_str), Some("AVA\r"), "the numbered object is kept as it was");
|
||||
assert_eq!(before.path(&["1", "1"]).and_then(E::as_array).and_then(|s| s.first()), slots.first(), "the numbered object changes not at all");
|
||||
}
|
||||
|
||||
/// When both lists hold the layer's text, the block is written back byte for byte — #2374 holds
|
||||
/// for the older objects too: re-encoding them would only risk Photoshop refusing the file.
|
||||
#[test]
|
||||
fn unchanged_block_with_both_object_lists_is_byte_identical() {
|
||||
use photocraft_doc::text::Kerning;
|
||||
let mut prev = photoshop_txt2(&[(4, 1)]);
|
||||
prev.extend_from_slice(&crate::engine_data::write_bare(&[("DocumentObjects".into(), photoshop_era_objects(&["AVA"]))]));
|
||||
let t = styled("AVA", CharStyle { kerning: Kerning::Metrics, ..Default::default() });
|
||||
assert_eq!(crate::psd::build_txt2(&[(0, &t)], Some(&prev)), prev);
|
||||
}
|
||||
|
||||
/// An entry shaped unlike Photoshop writes it — a run without its `/Length`, a `RunArray` that
|
||||
/// isn't an array, an empty one, an object with no text to replace — is left exactly as the file
|
||||
/// has it: a half-refitted object (new text over old runs) is what made Photoshop quit (#6968),
|
||||
/// so the save never writes one.
|
||||
#[test]
|
||||
fn odd_photoshop_era_entries_are_left_as_the_file_has_them() {
|
||||
use crate::engine_data::Value as E;
|
||||
use photocraft_doc::text::Kerning;
|
||||
let run = |len: i64| E::Dict(vec![("RunData".into(), E::dict()), ("Length".into(), E::Int(len))]);
|
||||
let entry = |model: Vec<(&str, E)>| {
|
||||
E::Dict(vec![("Model".into(), E::Dict(model.into_iter().map(|(k, v)| (k.to_string(), v)).collect())), ("View".into(), E::dict())])
|
||||
};
|
||||
let with_text = |text: E, style: E| {
|
||||
entry(vec![
|
||||
("Text", text),
|
||||
("ParagraphRun", E::Dict(vec![("RunArray".into(), E::Array(vec![run(4)]))])),
|
||||
("StyleRun", E::Dict(vec![("RunArray".into(), style)])),
|
||||
])
|
||||
};
|
||||
let odd = [
|
||||
with_text(E::String("Old\r".into()), E::Array(vec![E::Dict(vec![("RunData".into(), E::dict())])])),
|
||||
with_text(E::String("Old\r".into()), E::Int(3)),
|
||||
with_text(E::String("Old\r".into()), E::Array(vec![])),
|
||||
E::Int(3),
|
||||
entry(vec![("ParagraphRun", E::Dict(vec![("RunArray".into(), E::Array(vec![run(4)]))]))]),
|
||||
with_text(E::Int(9), E::Array(vec![run(4)])),
|
||||
];
|
||||
for (i, object) in odd.iter().enumerate() {
|
||||
let prev = crate::engine_data::write_bare(&[
|
||||
("98".into(), E::Dict(vec![("0".into(), E::Int(14))])),
|
||||
("0".into(), E::dict()),
|
||||
("DocumentObjects".into(), E::Dict(vec![("TextObjects".into(), E::Array(vec![object.clone()]))])),
|
||||
]);
|
||||
let was = crate::psd::parse_txt2(&prev).unwrap();
|
||||
let t = styled("New", CharStyle { kerning: Kerning::Optical, ..Default::default() });
|
||||
let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap();
|
||||
let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");
|
||||
assert_eq!(
|
||||
entries.first(),
|
||||
was.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()),
|
||||
"entry {i} is left as the file has it"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `TextIndex` past the entries the block holds has no stale copy to fix: nothing is grown to
|
||||
/// the layer's number (the slot list grows as it always did), and the entries stay the file's.
|
||||
#[test]
|
||||
fn a_text_index_beyond_the_photoshop_era_entries_grows_nothing() {
|
||||
use crate::engine_data::Value as E;
|
||||
use photocraft_doc::text::Kerning;
|
||||
let prev = photoshop_era_txt2(&["Only one"]);
|
||||
let was = crate::psd::parse_txt2(&prev).unwrap();
|
||||
let t = styled("Whatever", CharStyle { kerning: Kerning::Optical, ..Default::default() });
|
||||
let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(crate::psd::MAX_TEXT_INDEX, &t)], Some(&prev))).unwrap();
|
||||
let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects");
|
||||
assert_eq!(entries.len(), 1, "no entry is grown to the layer's number");
|
||||
assert_eq!(entries.first(), was.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()));
|
||||
}
|
||||
|
||||
/// A `Txt2` shaped like Photoshop's: document resources and settings beside the text objects
|
||||
/// (`/0`, `/1 /0`, `/1 /2`), style runs carrying a full style (font, size, leading) besides the
|
||||
/// auto-kern mode, a Latin-1 string without a byte-order mark, reals, and a second object no
|
||||
|
||||
+147
-15
@@ -918,7 +918,15 @@ fn length_field(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str) -> bo
|
||||
length_field_prec(ui, label, pt, units, 0)
|
||||
}
|
||||
|
||||
/// Edits a point-valued length in the selected units, with the requested decimal precision.
|
||||
/// Retains the nonnegative 0..=10000 display-unit range used by existing size fields.
|
||||
fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32) -> bool {
|
||||
length_field_range(ui, label, pt, units, decimals, 0.0..=10000.0)
|
||||
}
|
||||
|
||||
/// Edits a length stored in print points (72 per inch), returning true for a finite edit.
|
||||
/// `range` is in the displayed `units`; a signed range permits negative Top/Left offsets.
|
||||
fn length_field_range(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32, range: std::ops::RangeInclusive<f32>) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let k = unit_pt(units);
|
||||
let mut v = (*pt / k) as f32;
|
||||
@@ -926,7 +934,7 @@ fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str,
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(label).color(t.text_dim));
|
||||
let before = v;
|
||||
crate::widgets::value_field_prec(ui, &mut v, 0.0..=10000.0, units, 70.0, decimals);
|
||||
crate::widgets::value_field_prec(ui, &mut v, range, units, 70.0, decimals);
|
||||
if (v - before).abs() > 1e-4 && v.is_finite() {
|
||||
*pt = f64::from(v) * k;
|
||||
changed = true;
|
||||
@@ -997,6 +1005,44 @@ fn browse_pdf(app: &mut PhotocraftApp, id: u64, suggested: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts total displacement from a fixed drag-start layout into manual inch offsets.
|
||||
/// Resolving Center before the drag avoids a jump; each update replaces the offsets rather
|
||||
/// than accumulating movement. Emulsion Down reverses horizontal layout-space movement.
|
||||
///
|
||||
/// `delta` and the painter use egui points, including on Retina displays; the scale is egui
|
||||
/// points per print point (1/72 inch). Applying pixels_per_point would count HiDPI twice.
|
||||
/// Invalid scales or nonfinite displacement/offsets return false without changing fields.
|
||||
/// Accepted offsets are clamped to the engine's safety bound and Center is disabled.
|
||||
fn drag_print_position(f: &mut Map<String, Value>, start: photocraft_engine::print_cmds::PrintLayout, delta: egui::Vec2, points_per_print_point: f32) -> bool {
|
||||
if !points_per_print_point.is_finite() || points_per_print_point <= 0.0 || !delta.is_finite() {
|
||||
return false;
|
||||
}
|
||||
let (x, y, _, h) = start.rect;
|
||||
let direction = if start.emulsion_down { -1.0 } else { 1.0 };
|
||||
let left = (x + direction * f64::from(delta.x) / f64::from(points_per_print_point)) / 72.0;
|
||||
let top = (start.paper.1 - y - h + f64::from(delta.y) / f64::from(points_per_print_point)) / 72.0;
|
||||
if !left.is_finite() || !top.is_finite() {
|
||||
return false;
|
||||
}
|
||||
let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES;
|
||||
f.insert("center".into(), json!(false));
|
||||
f.insert("left".into(), json!(left.clamp(-limit, limit)));
|
||||
f.insert("top".into(), json!(top.clamp(-limit, limit)));
|
||||
true
|
||||
}
|
||||
|
||||
/// Maps the engine's bottom-left print-point rectangle into top-left egui coordinates.
|
||||
/// `k` is egui points per print point; Emulsion Down mirrors placement across the page,
|
||||
/// matching the PDF page transform. Returns the full image bounds for the caller to clip.
|
||||
fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout, page: egui::Rect, k: f32) -> egui::Rect {
|
||||
let (x, y, w, h) = l.rect;
|
||||
let x = if l.emulsion_down { l.paper.0 - x - w } else { x };
|
||||
egui::Rect::from_min_size(egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), egui::vec2(w as f32 * k, h as f32 * k))
|
||||
}
|
||||
|
||||
/// Draws the print controls and paper-clipped preview using the engine's shared layout.
|
||||
/// Dragging the visible image updates dialog offsets live from a fixed gesture origin;
|
||||
/// the position row stays present while centered so switching to manual cannot move the page.
|
||||
fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>, id: u64) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
|
||||
@@ -1026,19 +1072,39 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
let (area, _) = ui.allocate_exact_size(egui::vec2(330.0, 400.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(area, 0.0, t.canvas);
|
||||
match photocraft_engine::print_cmds::layout(&doc, &p, "file.print") {
|
||||
Ok(l) => {
|
||||
Ok(mut l) => {
|
||||
let (pw, ph) = l.paper;
|
||||
let k = ((area.width() - 20.0) / pw as f32).min((area.height() - 20.0) / ph as f32);
|
||||
let page = egui::Rect::from_center_size(area.center(), egui::vec2(pw as f32 * k, ph as f32 * k));
|
||||
ui.painter().rect_filled(page, 0.0, egui::Color32::WHITE);
|
||||
ui.painter().rect_stroke(page, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
|
||||
let mut img = print_preview_image(l, page, k);
|
||||
let drag_id = ui.id().with(("print-position", id));
|
||||
let visible = img.intersect(page).intersect(ui.clip_rect());
|
||||
let response = ui.interact(visible, drag_id, egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Image, true, tl!("Print preview image")));
|
||||
// Keep a fixed layout and press origin for the whole gesture: rounding and
|
||||
// the transition from Center must never accumulate or move the grab point.
|
||||
if response.drag_started_by(egui::PointerButton::Primary)
|
||||
&& let Some(origin) = ui.input(|i| i.pointer.press_origin())
|
||||
{
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, (l, origin, k)));
|
||||
}
|
||||
if (response.dragged_by(egui::PointerButton::Primary) || response.drag_stopped_by(egui::PointerButton::Primary))
|
||||
&& let Some((start, origin, scale)) = ui.data(|d| d.get_temp::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id))
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
&& drag_print_position(f, start, pointer - origin, scale)
|
||||
{
|
||||
if let Ok(updated) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") {
|
||||
l = updated;
|
||||
img = print_preview_image(l, page, k);
|
||||
}
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
if !ui.input(|i| i.pointer.primary_down()) {
|
||||
ui.data_mut(|d| d.remove::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id));
|
||||
}
|
||||
let (x, y, w, h) = l.rect;
|
||||
// Emulsion Down shows the page as it prints: mirrored.
|
||||
let x = if l.emulsion_down { pw - x - w } else { x };
|
||||
let img = egui::Rect::from_min_size(
|
||||
egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k),
|
||||
egui::vec2(w as f32 * k, h as f32 * k),
|
||||
);
|
||||
let key = egui::Id::new(("print-thumb", doc.id.0, app.session.active().map_or(0, |d| d.revision)));
|
||||
let tex: Option<Arc<egui::TextureHandle>> = ui.data(|d| d.get_temp(key));
|
||||
let tex = tex.unwrap_or_else(|| {
|
||||
@@ -1057,11 +1123,13 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
clip.image(tex.id(), img, uv, egui::Color32::WHITE);
|
||||
let mark = egui::Stroke::new(1.0, egui::Color32::BLACK);
|
||||
if l.marks.corner_crop {
|
||||
// Bleed puts the marks on the trim line, inside the image edge.
|
||||
let b = l.marks.bleed as f32 * k;
|
||||
for (c, dx, dy) in
|
||||
[(img.left_top(), -1.0, -1.0), (img.right_top(), 1.0, -1.0), (img.left_bottom(), -1.0, 1.0), (img.right_bottom(), 1.0, 1.0)]
|
||||
{
|
||||
clip.line_segment([c + egui::vec2(dx * 3.0, 0.0), c + egui::vec2(dx * 12.0, 0.0)], mark);
|
||||
clip.line_segment([c + egui::vec2(0.0, dy * 3.0), c + egui::vec2(0.0, dy * 12.0)], mark);
|
||||
clip.line_segment([c + egui::vec2(dx * 3.0, -dy * b), c + egui::vec2(dx * 12.0, -dy * b)], mark);
|
||||
clip.line_segment([c + egui::vec2(-dx * b, dy * 3.0), c + egui::vec2(-dx * b, dy * 12.0)], mark);
|
||||
}
|
||||
}
|
||||
if l.marks.registration {
|
||||
@@ -1218,17 +1286,24 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
dropdown_str(ui, "print-units", f, "units", &[("cm", tl!("Centimeters")), ("mm", tl!("Millimeters")), ("in", tl!("Inches"))], 130.0);
|
||||
let units = s(f, "units", "cm");
|
||||
check(ui, f, "center", tl!("Center"), true);
|
||||
if !b(f, "center", true) {
|
||||
let centered = b(f, "center", true);
|
||||
let centered_layout = centered.then(|| photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print").ok()).flatten();
|
||||
// Revealing this row during a drag resizes the centered modal and moves the paper.
|
||||
// Keep it present, showing the resolved position while Center owns the offsets.
|
||||
ui.add_enabled_ui(!centered, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
// Kept in inches (Photoshop's Position fields), shown in the chosen units.
|
||||
for (key, label) in [("top", tl!("Top")), ("left", tl!("Left"))] {
|
||||
let mut pt = n(f, key, 0.0) * 72.0;
|
||||
if length_field(ui, label, &mut pt, &units) {
|
||||
f.insert(key.into(), json!(pt / 72.0));
|
||||
let mut pt =
|
||||
centered_layout.map_or_else(|| n(f, key, 0.0) * 72.0, |l| if key == "top" { l.paper.1 - l.rect.1 - l.rect.3 } else { l.rect.0 });
|
||||
let limit = (photocraft_engine::print_cmds::MAX_POSITION_INCHES * 72.0 / unit_pt(&units)) as f32;
|
||||
if length_field_range(ui, label, &mut pt, &units, 2, -limit..=limit) {
|
||||
let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES;
|
||||
f.insert(key.into(), json!((pt / 72.0).clamp(-limit, limit)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
check(ui, f, "scaleToFit", tl!("Scale to Fit Media"), false);
|
||||
// Scaled Print Size: Scale, Height and Width move together; Print Resolution follows.
|
||||
if let Ok(l) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") {
|
||||
@@ -1333,6 +1408,63 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Checks no-jump centering and nonaccumulating screen displacement against shared layout
|
||||
/// across fit, percentage scaling, orientation and mirroring combinations.
|
||||
#[test]
|
||||
fn print_drag_uses_the_resolved_layout_and_screen_points_without_accumulation() {
|
||||
let (app, _) = app();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
for fit in [false, true] {
|
||||
for mirror in [false, true] {
|
||||
for orientation in ["portrait", "landscape"] {
|
||||
let mut f = json!({"center": true, "scale": 175, "scaleToFit": fit,
|
||||
"emulsionDown": mirror, "orientation": orientation})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
let start = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap();
|
||||
let page = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(start.paper.0 as f32, start.paper.1 as f32));
|
||||
assert!(drag_print_position(&mut f, start, egui::Vec2::ZERO, 1.0));
|
||||
let manual = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap();
|
||||
assert!((manual.rect.0 - start.rect.0).abs() < 1e-9);
|
||||
assert!((manual.rect.1 - start.rect.1).abs() < 1e-9);
|
||||
assert_eq!(manual.scale, start.scale);
|
||||
for k in [0.25, 0.5, 1.0, 2.0] {
|
||||
let delta = egui::vec2(-90.0, 45.0) * k;
|
||||
assert!(drag_print_position(&mut f, start, delta, k));
|
||||
let moved = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap();
|
||||
let old_img = print_preview_image(start, page, k);
|
||||
let new_img = print_preview_image(moved, page, k);
|
||||
assert!((new_img.min - old_img.min - delta).length() < 0.001);
|
||||
assert_eq!((moved.rect.2, moved.rect.3, moved.scale), (start.rect.2, start.rect.3, start.scale));
|
||||
let once = f.clone();
|
||||
assert!(drag_print_position(&mut f, start, delta, k));
|
||||
assert_eq!(f, once, "total drag displacement must not accumulate");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks rejected pointer geometry leaves fields untouched and extreme finite drags
|
||||
/// clamp both inch offsets to the same safety limits as numeric positioning.
|
||||
#[test]
|
||||
fn print_drag_rejects_nonfinite_input_and_bounds_offsets() {
|
||||
let (app, _) = app();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let start = photocraft_engine::print_cmds::layout(doc, &json!({}), "file.print").unwrap();
|
||||
let mut f = Map::new();
|
||||
for k in [0.0, -1.0, f32::NAN, f32::INFINITY] {
|
||||
assert!(!drag_print_position(&mut f, start, egui::vec2(10.0, 10.0), k));
|
||||
assert!(f.is_empty());
|
||||
}
|
||||
assert!(!drag_print_position(&mut f, start, egui::vec2(f32::NAN, 0.0), 1.0));
|
||||
assert!(f.is_empty());
|
||||
assert!(drag_print_position(&mut f, start, egui::vec2(-f32::MAX, f32::MAX), 1.0));
|
||||
assert_eq!(f["left"], -photocraft_engine::print_cmds::MAX_POSITION_INCHES);
|
||||
assert_eq!(f["top"], photocraft_engine::print_cmds::MAX_POSITION_INCHES);
|
||||
}
|
||||
|
||||
fn app() -> (PhotocraftApp, egui::Context) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap();
|
||||
|
||||
@@ -263,3 +263,50 @@ fn nulls(v: &Value) -> usize {
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn selected_tool_and_non_default_options_roundtrip() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.ui.tool = Tool::Move;
|
||||
app.ui.tool_options.tolerance = 42.5;
|
||||
persist(&mut app, &egui::Context::default());
|
||||
|
||||
let saved = app.session.prefs();
|
||||
assert_eq!(saved.selected_tool, serde_json::to_value(Tool::Move).unwrap());
|
||||
assert_eq!(saved.tool_options["tolerance"], Value::from(42.5));
|
||||
assert!(saved.tool_options.get("contiguous").is_none(), "unchanged defaults are not written");
|
||||
|
||||
let mut restored = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
restored.session.prefs.edit(|p| {
|
||||
p.selected_tool = saved.selected_tool.clone();
|
||||
p.tool_options = saved.tool_options.clone();
|
||||
});
|
||||
restore(&mut restored);
|
||||
assert_eq!(restored.ui.tool, Tool::Move);
|
||||
assert_eq!(restored.ui.tool_options.tolerance, 42.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_ignores_unknown_and_malformed_tool_options() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let original_tool = app.ui.tool;
|
||||
let default_contiguous = ToolOptions::default().contiguous;
|
||||
app.session.prefs.edit(|p| {
|
||||
p.selected_tool = Value::from("not-a-tool");
|
||||
p.tool_options = serde_json::json!({
|
||||
"tolerance": 42.5,
|
||||
"contiguous": "not a boolean",
|
||||
"future_option": true
|
||||
});
|
||||
});
|
||||
|
||||
restore(&mut app);
|
||||
assert_eq!(app.ui.tool, original_tool, "an invalid selected tool leaves the current tool intact");
|
||||
assert_eq!(app.ui.tool_options.tolerance, 42.5, "valid fields still restore");
|
||||
assert_eq!(app.ui.tool_options.contiguous, default_contiguous, "a malformed field falls back to its default");
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,7 @@ fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]], skip: usize) -> f32 {
|
||||
|
||||
#[test]
|
||||
fn preview_layer_composites_on_the_gpu_like_the_command() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some((device, queue, mut comp)) = gpu() else { return };
|
||||
// GPU vs CPU of the same document (as the compositor parity tests), and GPU preview vs the
|
||||
// command's CPU result (adds the command's rounding to the layer depth).
|
||||
@@ -170,6 +171,7 @@ fn preview_layer_composites_on_the_gpu_like_the_command() {
|
||||
/// The zoomed-out proxy preview (own document and layer ids) composites on the GPU like the CPU.
|
||||
#[test]
|
||||
fn proxy_preview_composites_on_the_gpu() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
use photocraft_ui_egui::adjust_preview::{base_document, proxy_base, proxy_with_settings};
|
||||
let Some((device, queue, mut comp)) = gpu() else { return };
|
||||
for selection in [false, true] {
|
||||
|
||||
@@ -278,6 +278,7 @@ fn grid_line_contrast_over_grey(h: &mut Harness, grey: u8) -> i32 {
|
||||
|
||||
#[test]
|
||||
fn pixel_grid_does_not_flip_colour_across_mid_tones() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
h.run_steps(4);
|
||||
// 0x87 and 0x90 sit either side of luma 0.55, where the line used to switch from a full white
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! #3820: edit custom paper through the real Print dialog, preview it, and print safely to PDF.
|
||||
use egui::{Event, Key, Modifiers, PointerButton, vec2};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{NodeT, Queryable},
|
||||
};
|
||||
use photocraft_ui_egui::{PhotocraftApp, file_ui::open_print};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
@@ -22,7 +25,13 @@ fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp) {
|
||||
}
|
||||
|
||||
fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {
|
||||
let mut h = Harness::builder().with_size(vec2(1000.0, 900.0)).with_max_steps(64).build_ui_state(show, app);
|
||||
harness_at_scale(app, 1.0)
|
||||
}
|
||||
|
||||
/// Builds the real dialog at an explicit physical-pixels-per-egui-point ratio so pointer
|
||||
/// events remain in egui points while exercising both standard and Retina display scales.
|
||||
fn harness_at_scale(app: PhotocraftApp, pixels_per_point: f32) -> Harness<'static, PhotocraftApp> {
|
||||
let mut h = Harness::builder().with_size(vec2(1000.0, 900.0)).with_pixels_per_point(pixels_per_point).with_max_steps(64).build_ui_state(show, app);
|
||||
PhotocraftApp::setup_context(&h.ctx, Default::default());
|
||||
h.run_steps(4);
|
||||
h
|
||||
@@ -42,8 +51,8 @@ fn shown(h: &Harness<'_, PhotocraftApp>, text: &str) -> bool {
|
||||
}
|
||||
|
||||
fn enter_length(h: &mut Harness<'_, PhotocraftApp>, label: &str, value: &str) {
|
||||
// Anchor the pointer to the real label; the existing length widget immediately follows it.
|
||||
let pos = h.get_by_label(label).rect().right_center() + vec2(35.0, 0.0);
|
||||
// Use the editor's actual accessibility bounds rather than a fixed offset from its label.
|
||||
let pos = h.get_by_label(label).parent().unwrap().get_by_role(egui::accesskit::Role::SpinButton).rect().center();
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
@@ -60,6 +69,89 @@ fn fields(h: &Harness<'_, PhotocraftApp>, id: u64) -> Map<String, Value> {
|
||||
h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone()
|
||||
}
|
||||
|
||||
/// Finds the thumbnail's painted mesh bounds, rather than the earlier interaction bounds,
|
||||
/// so drag assertions detect visible lag in the same frame as a Center transition.
|
||||
fn painted_image(h: &Harness<'_, PhotocraftApp>) -> egui::Rect {
|
||||
let active = h.state().session.active().unwrap();
|
||||
let key = egui::Id::new(("print-thumb", active.doc.id.0, active.revision));
|
||||
let tex = h.ctx.data(|d| d.get_temp::<std::sync::Arc<egui::TextureHandle>>(key)).unwrap();
|
||||
h.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Mesh(mesh) if mesh.texture_id == tex.id() => Some(mesh.calc_bounds()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the print image must be painted")
|
||||
}
|
||||
|
||||
/// Exercises live painted movement at 1x/2x display scale, signed numeric entry and pointer
|
||||
/// capture off-page and back, then verifies Center restores the shared layout's placement.
|
||||
#[test]
|
||||
fn preview_drag_and_negative_fields_work_at_standard_and_retina_scale() {
|
||||
for pixels_per_point in [1.0, 2.0] {
|
||||
let (mut app, id) = app();
|
||||
app.ui
|
||||
.dialog_mut(id)
|
||||
.unwrap()
|
||||
.fields
|
||||
.extend(json!({"paper": "a4", "center": true, "scale": 100, "scaleToFit": false, "units": "cm"}).as_object().unwrap().clone());
|
||||
let mut h = harness_at_scale(app, pixels_per_point);
|
||||
let start = photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(fields(&h, id)), "file.print").unwrap();
|
||||
let start_image = painted_image(&h);
|
||||
let from = start_image.center();
|
||||
let delta = vec2(-24.0, 18.0);
|
||||
h.event(Event::PointerMoved(from));
|
||||
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
for step in 1..=3 {
|
||||
h.event(Event::PointerMoved(from + delta * (step as f32 / 3.0)));
|
||||
h.run_steps(1);
|
||||
}
|
||||
let during = fields(&h, id);
|
||||
assert_eq!(during["center"], false, "Center must switch off during the drag");
|
||||
// The hit target was registered before this frame's pointer handling. Inspect the
|
||||
// actual painted mesh to verify the image moves immediately, without a frame of lag.
|
||||
let moved_image = painted_image(&h);
|
||||
assert!(
|
||||
(moved_image.min - start_image.min - delta).length() < 0.1,
|
||||
"the visible image must stay under the pointer when Center turns off: {start_image:?} -> {moved_image:?}, delta {delta:?}"
|
||||
);
|
||||
let k = (310.0 / start.paper.0).min(380.0 / start.paper.1);
|
||||
assert!((during["left"].as_f64().unwrap() * 72.0 - start.rect.0 - f64::from(delta.x) / k).abs() < 0.001);
|
||||
assert!((during["top"].as_f64().unwrap() * 72.0 - (start.paper.1 - start.rect.1 - start.rect.3) - f64::from(delta.y) / k).abs() < 0.001);
|
||||
h.event(Event::PointerButton { pos: from + delta, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Centimeters");
|
||||
click(&mut h, "Inches");
|
||||
enter_length(&mut h, "Top", "-0.25");
|
||||
enter_length(&mut h, "Left", "-0.5");
|
||||
let negative = fields(&h, id);
|
||||
assert_eq!(negative["top"], -0.25);
|
||||
assert_eq!(negative["left"], -0.5);
|
||||
let visible = h.get_by_label("Print preview image").rect();
|
||||
assert!(visible.is_positive(), "a partly off-page image must retain a visible drag target");
|
||||
let from = visible.center();
|
||||
h.event(Event::PointerMoved(from));
|
||||
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
// Keep capture even when both the pointer and image leave the sheet entirely.
|
||||
h.event(Event::PointerMoved(from - vec2(400.0, 0.0)));
|
||||
h.run_steps(2);
|
||||
assert!(fields(&h, id)["left"].as_f64().unwrap() < -1.0);
|
||||
h.event(Event::PointerMoved(from + vec2(12.0, 12.0)));
|
||||
h.run_steps(2);
|
||||
assert!(fields(&h, id)["left"].as_f64().unwrap() > -0.5);
|
||||
h.event(Event::PointerButton { pos: from + vec2(12.0, 12.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
click(&mut h, "Center");
|
||||
let centered = photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(fields(&h, id)), "file.print").unwrap();
|
||||
assert_eq!(fields(&h, id)["center"], true);
|
||||
assert!((centered.rect.0 - (centered.paper.0 - centered.rect.2) / 2.0).abs() < 1e-9);
|
||||
assert!((centered.rect.1 - (centered.paper.1 - centered.rect.3) / 2.0).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() {
|
||||
let (mut app, id) = app();
|
||||
|
||||
@@ -220,6 +220,7 @@ fn the_move_preview_is_what_the_move_commits() {
|
||||
|
||||
#[test]
|
||||
fn layout_document_composites_on_the_gpu_like_the_cpu() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
use eframe::wgpu;
|
||||
fn block_on<F: std::future::Future>(f: F) -> F::Output {
|
||||
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
|
||||
@@ -82,6 +82,7 @@ fn selection(h: &Harness) -> Option<[i32; 4]> {
|
||||
|
||||
#[test]
|
||||
fn marquee_dragged_past_the_right_edge_scrolls_and_selects_beyond_the_view() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
setup(&mut h, "rectMarquee");
|
||||
let start = xf(&h);
|
||||
@@ -121,6 +122,7 @@ fn marquee_dragged_past_the_right_edge_scrolls_and_selects_beyond_the_view() {
|
||||
|
||||
#[test]
|
||||
fn a_drag_inside_the_canvas_does_not_scroll() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
setup(&mut h, "rectMarquee");
|
||||
let start = xf(&h);
|
||||
@@ -139,6 +141,7 @@ fn a_drag_inside_the_canvas_does_not_scroll() {
|
||||
|
||||
#[test]
|
||||
fn rotated_marquee_scrolls_on_the_axis_that_is_visibly_clipped() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness_with_size(egui::vec2(1200.0, 640.0)) else { return };
|
||||
setup(&mut h, "rectMarquee");
|
||||
let rect = xf(&h).rect;
|
||||
|
||||
@@ -52,6 +52,7 @@ fn near(a: [u8; 3], b: [u8; 3]) -> bool {
|
||||
|
||||
#[test]
|
||||
fn pattern_preview_repeats_the_document_on_gpu_and_cpu_canvases() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
let app = h.state_mut();
|
||||
app.run("file.new", json!({"width": 200, "height": 100, "mode": "rgb", "depth": 8})).expect("new");
|
||||
|
||||
@@ -21,7 +21,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.
|
||||
|
||||
| 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); LZW/ZIP for scripted saves by `tiffCompression`; undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) |
|
||||
|
||||
@@ -5,6 +5,22 @@ position and scale, crop and registration marks, labels, colour handling) and ha
|
||||
to a printer. The rendering is `print_cmds.rs` in `photocraft-engine`, shared by the dialog, the
|
||||
batch commands and automation (`file.print`, `file.printOneCopy`); this page is about the hand-off.
|
||||
|
||||
## Positioning the preview
|
||||
|
||||
Drag the visible image on the paper to change Top and Left. Starting a drag switches Center
|
||||
off using the currently resolved layout, including Scale to Fit Media, so the image stays at
|
||||
the grab point. Top/Left stay visible but disabled while Center is on, keeping the dialog and
|
||||
paper stationary when a drag enables them. Position fields accept negative values in inches, centimetres or millimetres;
|
||||
the stored command parameters are inches from the sheet's top-left. Manual positions are
|
||||
bounded to ±10000 inches. Height, width and paper dimensions retain their positive fields.
|
||||
|
||||
The preview converts egui point displacement to PDF points using its paper display scale.
|
||||
No extra Retina pixel factor is needed: painting and pointer input both use egui points.
|
||||
Emulsion Down reverses the horizontal position change to match the mirrored output. The image
|
||||
is clipped to the paper; any visible portion remains a drag target. A completely off-page image
|
||||
can be recovered with Top/Left or Center. These controls affect print parameters only, and
|
||||
the preview and generated PDF continue to share `print_cmds::layout`.
|
||||
|
||||
## Routes to the printer
|
||||
|
||||
| Route | When | What the user sees |
|
||||
|
||||
@@ -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-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);
|
||||
@@ -286,7 +286,7 @@ just presence.
|
||||
| Transform, warp, puppet, perspective, liquify | ~88% | No Face-Aware Liquify (needs a landmark model) |
|
||||
| Automation: CLI, MCP, headless server, control channel | ~95% | Ahead of Photoshop here (see below) |
|
||||
| Image modes (RGB/Gray/CMYK/Lab/Indexed/Duotone/Multichannel) | ~85% | Multichannel display-only; no ink-plate model |
|
||||
| Print / export / Save for Web / slices / Generator | ~85% | No Separations/bleed; droplets basic |
|
||||
| Print / export / Save for Web / slices / Generator | ~85% | No Separations; Bleed only through `file.print` (no Print dialog field yet); droplets basic |
|
||||
| Computational photo (Photomerge, HDR, Lens, Camera Raw, Wide Angle) | ~70% | Classical implementations; generic lens profiles only |
|
||||
| Data-driven graphics (Variables, Data Sets) | ~0% | Not started (5 menu items) |
|
||||
| Video / Timeline / animation | ~0% | Not started (13 menu items) — a whole subsystem |
|
||||
@@ -570,6 +570,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md).
|
||||
| 2026-10-18 | minor | Layers: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial; percentages unchanged |
|
||||
| 2026-10-16 | minor | Content-Aware Move: live result preview for every selection the command takes (TOOL-213-4 done, #6680); percentages unchanged |
|
||||
| 2026-10-15 | minor | Vector shapes: shape layers take Density and Feather (Properties › Masks), PSD and .pcraft round trip; TOOL-214-12 done (#5846); estimates unchanged |
|
||||
| 2026-10-15 | minor | Print: Functions › Bleed (`file.print` / `file.printOneCopy` `bleed`, corner crop marks on the trim line, PDF and Windows paths); the Print dialog field is still missing; percentages unchanged |
|
||||
| 2026-10-13 | minor | Vector shapes: on-canvas corner radius widgets on live rectangles (TOOL-214-12); estimates unchanged |
|
||||
| 2026-10-13 | minor | Stale "missing tool" rows corrected against main: Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (the Pen flyout) are live toolbar tools and Frame landed, so Art History Brush is the only tool still missing; percentages unchanged |
|
||||
| 2026-10-12 | minor | Free Transform options bar H/V skew fields; percentages unchanged |
|
||||
|
||||
Reference in new issue
Block a user