Merge queue batch: 7 PRs (#17266, #17334, #17822, #17823, #17836, #17843, #17574)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-29 14:14:29 +01:00
commit d056dc4e99
28 files changed
+1821 -96

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
//! craft-metadata; the raw-date and numeric selection semantics are preserved there.
pub use craft_metadata::camera_fields::{CameraInfo, read, try_build};
// The existing shared reader supplies additional camera tags without another TIFF parser.
pub use craft_metadata::{TagRow, file_tag_rows};
/// Build a TIFF-structured EXIF payload, preserving the existing infallible API.
/// Returns an empty payload when the shared writer refuses an oversized value. New callers
@@ -0,0 +1,93 @@
//! #17544: the Gradient tool's dither adds no noise in 16-bit RGB and Grayscale documents, where
//! the reference's dither on and dither off give the same smooth ramp. 8 bit keeps its one-step
//! noise, and 32 bit and 16-bit CMYK and Lab keep today's behaviour (not measured).
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_raster::Surface;
use super::{BlendMode, GradientShape, Rect, paint_gradient};
/// A black → white Linear gradient over 800 × 600, from (100, 300) to (700, 300), in `fmt`.
fn painted(fmt: PixelFormat, dither: bool) -> Surface {
let mut s = Surface::new(fmt);
let stops = [(0.0, [0.0, 0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 1.0, 1.0])];
paint_gradient(
&mut s,
Rect::new(0, 0, 800, 600),
(100.0, 300.0),
(700.0, 300.0),
GradientShape::Linear,
&stops,
false,
1.0,
BlendMode::Normal,
dither,
None,
false,
);
s
}
/// The pixels of a 32 × 32 patch around the ramp's middle, all channels.
fn patch(s: &Surface) -> Vec<f32> {
(290..322).flat_map(|y| (384..416).flat_map(move |x| s.pixel(x, y))).collect()
}
const RGB16: PixelFormat = PixelFormat::RGBA16;
const GRAY16: PixelFormat = PixelFormat { mode: ColorMode::Grayscale, sample: SampleType::U16, alpha: true };
const GRAY32: PixelFormat = PixelFormat { mode: ColorMode::Grayscale, sample: SampleType::F32, alpha: true };
const CMYK16: PixelFormat = PixelFormat { mode: ColorMode::Cmyk, sample: SampleType::U16, alpha: true };
const LAB16: PixelFormat = PixelFormat { mode: ColorMode::Lab, sample: SampleType::U16, alpha: true };
#[test]
fn rgb_16_bit_dither_on_paints_what_dither_off_paints() {
assert_eq!(patch(&painted(RGB16, true)), patch(&painted(RGB16, false)));
}
#[test]
fn rgb_16_bit_dithered_ramp_is_smooth() {
// Along the ramp every step is the same small rise; down a column nothing changes.
let s = painted(RGB16, true);
let row: Vec<f32> = (400..406).map(|x| s.pixel(x, 300)[0] * 255.0).collect();
for w in row.windows(2) {
let step = w[1] - w[0];
assert!((0.3..0.55).contains(&step), "x row {row:?}");
}
let col: Vec<f32> = (300..306).map(|y| s.pixel(400, y)[0]).collect();
assert!(col.iter().all(|v| *v == col[0]), "column {col:?}");
}
#[test]
fn gray_16_bit_follows_rgb_16_bit() {
assert_eq!(patch(&painted(GRAY16, true)), patch(&painted(GRAY16, false)));
}
#[test]
fn eight_bit_still_dithers() {
for fmt in [PixelFormat::RGBA8, PixelFormat::GRAYA8] {
assert_ne!(patch(&painted(fmt, true)), patch(&painted(fmt, false)), "{fmt:?}");
}
}
#[test]
fn thirty_two_bit_keeps_its_noise() {
for fmt in [PixelFormat::RGBA32F, GRAY32] {
let (on, off) = (patch(&painted(fmt, true)), patch(&painted(fmt, false)));
assert_ne!(on, off, "{fmt:?}");
// Today's amplitude: at most half an 8-bit step either way.
let most = on.iter().zip(&off).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(most <= 0.5 / 255.0 + 1e-6, "{fmt:?}: {most}");
}
}
#[test]
fn cmyk_and_lab_16_bit_keep_their_noise() {
// Not measured in the issue, so these keep today's dither. The noise is added to the RGB
// colour before the conversion, so a channel moves by less than one 8-bit step.
for fmt in [CMYK16, LAB16] {
let (on, off) = (patch(&painted(fmt, true)), patch(&painted(fmt, false)));
assert_ne!(on, off, "{fmt:?}");
let most = on.iter().zip(&off).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(most < 1.0 / 255.0, "{fmt:?}: {most}");
}
}
+11
View File
@@ -186,6 +186,13 @@ pub fn paint_gradient(
selection: Option<&Surface>,
lock_transparency: bool,
) {
// 16-bit RGB and Grayscale get no dither noise: the reference's dither on and off give the
// same smooth ramp there (#17544). Other 16-bit models (CMYK, Lab) weren't measured and keep
// the noise, as do 8 and 32 bit.
let fmt = s.format();
let smooth_16 =
fmt.sample == photocraft_color::SampleType::U16 && matches!(fmt.mode, photocraft_color::ColorMode::Rgb | photocraft_color::ColorMode::Grayscale);
let dither = dither && !smooth_16;
composite_area(
s,
area,
@@ -362,6 +369,10 @@ fn rim_ring(region: &crate::selection::Region) -> Vec<bool> {
.collect()
}
#[cfg(test)]
#[path = "gradient_dither_16bit_tests.rs"]
mod gradient_dither_16bit_tests;
#[cfg(test)]
#[path = "paint_gradient_sample_tests.rs"]
mod paint_gradient_sample_tests;
+56 -19
View File
@@ -90,13 +90,9 @@ fn li_values(inner: &str) -> Vec<String> {
out
}
/// Attribute form `prop="value"` on an `rdf:Description`.
/// Basic attributes share the Copyright matcher's accepted forms and rewrite span.
fn find_attr<'a>(xmp: &'a str, prop: &str) -> Option<(usize, usize, &'a str)> {
let key = format!(" {prop}=\"");
let i = xmp.find(&key)?;
let v0 = i + key.len();
let v1 = xmp[v0..].find('"')? + v0;
Some((i, v1 + 1, &xmp[v0..v1]))
tag_attr(xmp, prop, false)
}
/// The packet's `xmpRights:Marked` value, as an element or an attribute.
@@ -104,14 +100,17 @@ fn rights_marked(xmp: &str) -> Option<&str> {
find_element(xmp, "xmpRights:Marked").map(|(_, _, v)| v.trim()).or_else(|| marked_attr(xmp).map(|(_, _, v)| v))
}
/// Attribute form `xmpRights:Marked="…"` with either quote, any XML whitespace before the name
/// and around the `=`, as XMP writers lay attributes out on their own lines. Only names inside a
/// tag count, not text in another attribute's value, element text, a comment or CDATA. Returns
/// (start, end, value) with the whitespace before the name in the span, as [`find_attr`] does, so
/// a rewrite removes every form it reads.
// The existing Marked path retains its quote/whitespace and rewrite-span behavior.
fn marked_attr(xmp: &str) -> Option<(usize, usize, &str)> {
tag_attr(xmp, "xmpRights:Marked", false)
}
/// Attribute form `prop="…"` with either quote and XML whitespace before the name and around `=`.
/// Only names inside a tag count, not text in another attribute's value, element text, a comment
/// or CDATA. The span includes the whitespace before the name, so rewriting removes what is read.
fn tag_attr<'a>(xmp: &'a str, prop: &str, camera_only: bool) -> Option<(usize, usize, &'a str)> {
// The tab title asks every frame, and packets can be megabytes: walk only when the name is there.
if !xmp.contains("xmpRights:Marked") {
if !xmp.contains(prop) {
return None;
}
let b = xmp.as_bytes();
@@ -121,7 +120,9 @@ fn marked_attr(xmp: &str) -> Option<(usize, usize, &str)> {
(_, Some(q)) => quote = (c != q).then_some(q),
(false, None) if c == b'<' => {
let rest = &xmp[i..];
let skip = [("<!--", "-->"), ("<![CDATA[", "]]>")].into_iter().find(|(open, _)| rest.starts_with(open));
let skip = [("<!--", "-->"), ("<![CDATA[", "]]>"), ("<?", "?>")]
.into_iter()
.find(|(open, _)| rest.starts_with(open) && (camera_only || *open != "<?"));
match skip {
Some((_, close)) => i += rest.find(close).map_or(rest.len(), |e| e + close.len()) - 1,
None => in_tag = true,
@@ -132,7 +133,7 @@ fn marked_attr(xmp: &str) -> Option<(usize, usize, &str)> {
b'>' => in_tag = false,
b'"' | b'\'' => quote = Some(c),
_ if c.is_ascii_whitespace() => {
if let Some((end, v)) = marked_value(xmp, i + 1) {
if let Some((end, v)) = attr_value(xmp, i + 1, prop) {
return Some((i, end, v));
}
}
@@ -144,9 +145,9 @@ fn marked_attr(xmp: &str) -> Option<(usize, usize, &str)> {
None
}
/// `xmpRights:Marked = "value"` starting at byte `at`: (end after the closing quote, value).
fn marked_value(xmp: &str, at: usize) -> Option<(usize, &str)> {
let rest = xmp.get(at..)?.strip_prefix("xmpRights:Marked")?.trim_start().strip_prefix('=')?.trim_start();
/// `prop = "value"` starting at byte `at`: (end after the closing quote, value).
fn attr_value<'a>(xmp: &'a str, at: usize, prop: &str) -> Option<(usize, &'a str)> {
let rest = xmp.get(at..)?.strip_prefix(prop)?.trim_start().strip_prefix('=')?.trim_start();
let quote = rest.chars().next().filter(|&c| c == '"' || c == '\'')?;
let v0 = xmp.len() - rest.len() + 1;
let v1 = xmp[v0..].find(quote)? + v0;
@@ -193,7 +194,7 @@ pub fn read_file_info(xmp: Option<&str>) -> Value {
}
/// File Info's read-only Camera Data, as (result key, English label) in display order.
pub const CAMERA_FIELDS: [(&str, &str); 9] = [
pub const CAMERA_FIELDS: [(&str, &str); 14] = [
("make", "Make"),
("model", "Model"),
("dateTaken", "Date Taken"),
@@ -203,6 +204,11 @@ pub const CAMERA_FIELDS: [(&str, &str); 9] = [
("focalLength", "Focal Length"),
("focalLength35mm", "Focal Length (35 mm)"),
("lens", "Lens"),
("owner", "Owner"),
("imageSize", "Image Size"),
("orientation", "Orientation"),
("resolution", "Resolution"),
("flash", "Flash"),
];
/// `v` with at most `decimals` decimals and no trailing zeros (33.10 → "33.1", 8.0 → "8").
@@ -263,7 +269,7 @@ fn date_text(s: &str) -> String {
fn xmp_value(x: &str, prop: &str) -> Option<String> {
let v = match find_element(x, prop) {
Some((_, _, inner)) => li_values(inner).into_iter().next(),
None => find_attr(x, prop).map(|(_, _, v)| xml_unescape(v)),
None => tag_attr(x, prop, true).map(|(_, _, v)| xml_unescape(v)),
}?;
let v = v.trim().to_string();
(!v.is_empty()).then_some(v)
@@ -309,6 +315,37 @@ pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value {
m.insert(key.into(), json!(v));
}
}
// Reuse the shared tag reader for the five fields the nine-field compatibility facade lacks.
let rows = exif.map(|bytes| photocraft_algo::exif::file_tag_rows(bytes.strip_prefix(b"Exif\0\0").unwrap_or(bytes))).unwrap_or_default();
let tag = |tags: &[(&str, u16)]| {
tags.iter().find_map(|(group, tag)| {
rows.iter().find(|row| row.group == *group && row.tag == *tag).map(|row| row.value.trim().to_string()).filter(|value| !value.is_empty())
})
};
let extra = |tags: &[(&str, u16)], properties: &[&str]| tag(tags).or_else(|| properties.iter().find_map(|property| xmp_value(x, property)));
let owner = extra(&[("EXIF", 0xa430)], &["exifEX:CameraOwnerName", "aux:OwnerName"]);
let width = extra(&[("EXIF", 0xa002), ("TIFF", 0x0100)], &["exif:PixelXDimension", "tiff:ImageWidth"]);
let height = extra(&[("EXIF", 0xa003), ("TIFF", 0x0101)], &["exif:PixelYDimension", "tiff:ImageLength"]);
let image_size = width.zip(height).map(|(width, height)| format!("{width} x {height}"));
let orientation = extra(&[("TIFF", 0x0112)], &["tiff:Orientation"]);
let x_resolution = extra(&[("TIFF", 0x011a)], &["tiff:XResolution"]);
let y_resolution = extra(&[("TIFF", 0x011b)], &["tiff:YResolution"]);
let unit = extra(&[("TIFF", 0x0128)], &["tiff:ResolutionUnit"]);
let resolution = match (x_resolution, y_resolution) {
(Some(x), Some(y)) => Some(format!("{x} x {y}")),
(Some(value), None) | (None, Some(value)) => Some(value),
(None, None) => None,
}
.map(|value| match unit {
Some(unit) => format!("{value} / {unit}"),
None => value,
});
let flash = extra(&[("EXIF", 0x9209)], &["exif:Flash", "exif:Fired"]);
for (key, value) in [("owner", owner), ("imageSize", image_size), ("orientation", orientation), ("resolution", resolution), ("flash", flash)] {
if let Some(value) = value.map(|value| value.chars().take(200).collect::<String>()).filter(|value| !value.is_empty()) {
m.insert(key.into(), json!(value));
}
}
Value::Object(m)
}
+21 -5
View File
@@ -427,13 +427,13 @@ fn type_warp(cmd: &str, w: &Warp) -> Result<Option<photocraft_doc::text::TextWar
}
/// Warp on a type layer sets its Warp Text style: one history step, and the type stays editable.
fn warp_type_layer(s: &mut Session, cmd: &str, id: LayerId, w: &Warp) -> Result<Value> {
fn warp_type_layer(s: &mut Session, cmd: &str, id: LayerId, w: &Warp, label: &str) -> Result<Value> {
let tw = type_warp(cmd, w)?;
let unchanged = s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(&l.content, LayerContent::Text(t) if t.warp == tw));
if unchanged {
return Ok(json!({"layer": id.0, "changed": false}));
}
s.edit("Warp", |doc, _| {
s.edit(label, |doc, _| {
let group = crate::transform_cmds::group_locks(doc, id);
let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
@@ -449,11 +449,23 @@ fn warp_type_layer(s: &mut Session, cmd: &str, id: LayerId, w: &Warp) -> Result<
Ok(json!({"layer": id.0, "changed": true, "warp": tw}))
}
/// The History step a warp makes: "Warp" (Edit › Transform › Warp), or "Free Transform" for a
/// warp committed from a Free Transform session's warp toggle (#17579). Any other name is refused.
fn step_name(cmd: &str, p: &Value) -> Result<&'static str> {
match p.get("stepName") {
None | Some(Value::Null) => Ok("Warp"),
Some(Value::String(n)) if n == "Warp" => Ok("Warp"),
Some(Value::String(n)) if n == "Free Transform" => Ok("Free Transform"),
Some(_) => Err(bad(cmd, "`stepName` must be \"Warp\" or \"Free Transform\"")),
}
}
fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let label = step_name(cmd, p)?;
let (id, rect) = target(s, cmd, p)?;
let w = warp_from_params(cmd, p, rect_f(rect))?;
if matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Text(_))) {
return warp_type_layer(s, cmd, id, &w);
return warp_type_layer(s, cmd, id, &w, label);
}
let is_smart = matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_)));
if w.is_identity() && !is_smart {
@@ -469,7 +481,7 @@ fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
// a large layer runs on a worker with progress, and can be cancelled.
crate::jobs::edit_job(
s,
"Warp",
label,
move |doc, _, ctx| ctx.stage(0.0, 1.0, "Warping", |ctl| warp_doc(doc, id, &w, rect, interp, content_knots, ctl)),
move |()| json!({"layer": id.0, "changed": true, "rect": [rect.x0, rect.y0, rect.x1, rect.y1]}),
)
@@ -741,7 +753,7 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
}
pub fn specs() -> Vec<CommandSpec> {
const P: &str = r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist|cylinder","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"values":[left,bottom,right,top,topDepth,bottomDepth,wrap]? (cylinder: silhouettes and edges in document px, the ellipses' depths in half-axis units, wrap 0..1; horizontal only),"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px; on a smart object `us`/`vs` span the source contents, so points equal to the placement are an identity warp even when it is skewed),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest"} — on a type layer a style (or none) sets its Warp Text and the type stays editable"##;
const P: &str = r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist|cylinder","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"values":[left,bottom,right,top,topDepth,bottomDepth,wrap]? (cylinder: silhouettes and edges in document px, the ellipses' depths in half-axis units, wrap 0..1; horizontal only),"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px; on a smart object `us`/`vs` span the source contents, so points equal to the placement are an identity warp even when it is skewed),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest","stepName":"Warp|Free Transform"="Warp" (History step name; Free Transform's warp toggle sends "Free Transform"; any other value is refused)} — on a type layer a style (or none) sets its Warp Text and the type stays editable"##;
const S: &str = r##"{"warp":{…}? (the warp being edited; returned split),"rect":[x0,y0,x1,y1]?,"at":[x,y]? (document point; default = middle of the patch)} — without `warp`, edits the active smart object's warp. A 1×1 custom mesh is divided at the thirds first (the guides drawn on the default grid), so splitWarpCrosswise on an identity custom warp returns a 4×4 mesh (knots at 0, 1/3, 1/2, 2/3 and 1), not a 2×2. A preset is fitted as one patch and split without that step."##;
const G: &str = r##"{"warp":{…}? (the warp being edited; returned with the new mesh),"rect":[x0,y0,x1,y1]?,"size":n|"default"|"3"|"4"|"5" (square patches, 1..=64; 1 and "default" are the single-patch grid)} — without `warp`/`style`/`mesh`, edits the active smart object's warp. The surface is kept and the new lines are real splits at i/n."##;
vec![
@@ -821,6 +833,10 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "warp_history_name_tests.rs"]
mod warp_history_name_tests;
#[cfg(test)]
#[path = "warp_split_default_grid_tests.rs"]
mod warp_split_default_grid_tests;
@@ -0,0 +1,91 @@
//! #17579: a warp committed from a Free Transform session (its warp toggle) is one History step
//! named "Free Transform"; Edit › Transform › Warp stays "Warp". `edit.transform.warp` takes the
//! name as `stepName`, which accepts only those two names.
use super::*;
/// A pixel layer with a filled square, as the warp's content.
fn session() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 160})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.edit("fill", |doc, active| {
let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let px = photocraft_raster::from_rgba(&surface.format(), [1.0, 0.0, 0.0, 1.0]);
surface.fill_rect(Rect::new(40, 40, 120, 120), &px);
Ok(())
})
.unwrap();
s
}
fn history(s: &Session) -> Vec<String> {
s.active().unwrap().history.entries()
}
fn pixels(s: &Session) -> Vec<f32> {
let st = s.active().unwrap();
let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
(0..160).flat_map(|y| (0..200).flat_map(move |x| surface.pixel(x, y))).collect()
}
/// A mesh drag: the 1×1 grid over the square with its top-right corner pulled out.
fn dragged_warp() -> Value {
let rect = [40.0, 40.0, 120.0, 120.0];
let mut mesh = BezierMesh::identity(rect, 1, 1);
// Row-major: the top row's last point is the top-right corner.
let i = mesh.nx() - 1;
mesh.points[i] = [mesh.points[i][0] + 20.0, mesh.points[i][1] - 15.0];
serde_json::to_value(Warp::custom(mesh, rect)).unwrap()
}
/// Runs a warp with `extra` params and returns the name of the one History step it added.
fn step(s: &mut Session, extra: Value) -> String {
let before = history(s);
let mut p = json!({"rect": [40, 40, 120, 120], "warp": dragged_warp()});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("edit.transform.warp", p).unwrap();
let after = history(s);
assert_eq!(after.len(), before.len() + 1, "one History step: {after:?}");
after.last().cloned().unwrap()
}
#[test]
fn free_transform_warp_is_a_free_transform_step() {
let mut s = session();
assert_eq!(step(&mut s, json!({"stepName": "Free Transform"})), "Free Transform");
}
#[test]
fn menu_warp_stays_warp() {
let mut s = session();
assert_eq!(step(&mut s, json!({})), "Warp");
let mut s = session();
assert_eq!(step(&mut s, json!({"stepName": "Warp"})), "Warp");
let mut s = session();
assert_eq!(step(&mut s, json!({"stepName": null})), "Warp");
}
/// The name is the only difference: both warps paint the same pixels.
#[test]
fn the_step_name_does_not_change_the_pixels() {
let mut a = session();
step(&mut a, json!({}));
let mut b = session();
step(&mut b, json!({"stepName": "Free Transform"}));
assert_eq!(pixels(&a), pixels(&b));
}
#[test]
fn other_step_names_are_refused_and_change_nothing() {
let mut s = session();
let (before, px) = (history(&s), pixels(&s));
for name in [json!("Transform Path"), json!("free transform"), json!(""), json!(3), json!(true), json!(["Warp"])] {
let r = s.execute("edit.transform.warp", json!({"rect": [40, 40, 120, 120], "warp": dragged_warp(), "stepName": name}));
assert!(r.is_err(), "{name} is refused");
}
assert_eq!(history(&s), before);
assert_eq!(pixels(&s), px);
}
+34 -1
View File
@@ -382,7 +382,40 @@ fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&St
/// The Pencil's brush: the session brush made aliased (every pixel fully painted or untouched,
/// dabs on the pixel grid), hard and at full flow, with the options-bar mode.
fn pencil_brush(s: &Session, p: &Value) -> Result<BrushSettings> {
pencil_shape(with_blend_mode(resolve_brush(s, p, "paint.pencil")?, p), p)
let mut brush = pencil_shape(with_blend_mode(resolve_brush(s, p, "paint.pencil")?, p), p)?;
// A mask, an alpha channel or a single colour channel takes the colour as before.
let layer_pixels = !is_mask_target(p) && !crate::channel_cmds::is_channel_target(p) && crate::color_channels::target(s, p)?.is_none();
if layer_pixels {
brush.color = pencil_gray_in_doc(s, brush.color);
}
Ok(brush)
}
/// The Pencil's colour (straight RGB in the RGB working space) as a Grayscale document takes it
/// (#17559): converted through `craft-cms` (relative colorimetric, black point compensation) into
/// the document's gray, not the Rec. 601 luma sum. In 8 and 16 bit that is the document's own
/// gray profile (RGB 30,120,200 becomes 63.5 % ink, as the reference paints it); in 32 bit the
/// linear version of it, as the 32-bit document stores linear light (82.7 % ink). It is returned
/// as equal R, G and B, so the pixel conversion keeps it. Other modes, a failed conversion, and
/// Grayscale documents outside the default gray working space (not measured) keep the colour.
fn pencil_gray_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] {
use crate::color_cmds::ColorExt;
use photocraft_color::{ColorMode, SampleType};
let Some(st) = s.active().filter(|st| st.doc.mode == ColorMode::Grayscale) else { return c };
let default_gray = craft_cms::Builtin::DotGain20Compat;
let doc_profile = crate::color_cmds::document_profile(&st.doc);
if s.color().settings.working_gray != default_gray.id() || doc_profile.content_hash() != default_gray.profile().content_hash() {
return c;
}
let dst = if st.doc.depth == SampleType::F32 { std::sync::Arc::new(craft_cms::builtin::linear_gray().clone()) } else { doc_profile };
let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() };
let Ok(t) = craft_cms::cached(&s.color().working(ColorMode::Rgb), &dst, opts) else { return c };
let mut out = [0.0f32; 16];
if t.eval(&[c[0], c[1], c[2]], &mut out).is_err() || !out[0].is_finite() {
return c;
}
let g = out[0].clamp(0.0, 1.0);
[g, g, g, c[3]]
}
/// `brush` with the Pencil's hard, aliased tip, or the Eraser's Block (`"block": true`).
+1
View File
@@ -171,6 +171,7 @@ mod path_blur_speed_clamp;
mod path_transform_target;
mod pdn;
mod pen_path_append;
mod pencil_grayscale_foreground;
mod photoshop_oracles;
mod pixel_lock_edits;
mod place_steps_measure;
@@ -0,0 +1,111 @@
//! #17559: the Pencil in a Grayscale document paints the foreground's gray through the colour
//! managed conversion (relative colorimetric into the document's gray, linear in 32 bit), not the
//! Rec. 601 luma sum. Reference values are ink % at the dab centre.
use photocraft_engine::Session;
use serde_json::{Value, json};
fn gray_doc(depth: u32, fg: &str) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 30, "mode": "gray", "depth": depth})).unwrap();
s.execute("tools.setColors", json!({"foreground": fg, "background": "#ffffff"})).unwrap();
s
}
fn click(s: &mut Session, extra: Value) {
let mut p = json!({"points": [[20, 15]], "size": 9});
if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {
o.extend(e.clone());
}
s.execute("paint.pencil", p).unwrap();
}
/// Ink % (100 − gray) of the active layer at the dab centre.
fn ink(s: &Session) -> f32 {
let st = s.active().unwrap();
let l = st.active_layer.and_then(|id| st.doc.layer(id)).unwrap();
let v = l.surface().unwrap().rgba(20, 15);
assert_eq!(v[3], 1.0, "painted");
(1.0 - v[0]) * 100.0
}
fn assert_ink(got: f32, want: f32, what: &str) {
assert!((got - want).abs() <= 0.5, "{what}: {got:.2} % ink, want {want} ± 0.5");
}
#[test]
fn foreground_30_120_200_paints_the_reference_gray() {
for (depth, want) in [(8, 63.5), (16, 63.6), (32, 82.7)] {
let mut s = gray_doc(depth, "#1e78c8");
click(&mut s, json!({}));
assert_ink(ink(&s), want, &format!("Gray {depth}"));
}
}
#[test]
fn foreground_pure_blue_paints_the_reference_gray() {
for (depth, want) in [(8, 80.0), (16, 80.1), (32, 93.9)] {
let mut s = gray_doc(depth, "#0000ff");
click(&mut s, json!({}));
assert_ink(ink(&s), want, &format!("Gray {depth}"));
}
}
#[test]
fn auto_erase_toggles_foreground_white_foreground() {
for (depth, want) in [(8, 63.5), (16, 63.6), (32, 82.7)] {
let mut s = gray_doc(depth, "#1e78c8");
let mut seen = Vec::new();
for _ in 0..3 {
click(&mut s, json!({"autoErase": true}));
seen.push(ink(&s));
}
assert_ink(seen[0], want, &format!("Gray {depth}, first click"));
assert_ink(seen[1], 0.0, &format!("Gray {depth}, second click"));
assert_ink(seen[2], want, &format!("Gray {depth}, third click"));
}
}
#[test]
fn black_and_white_stay_exact() {
for depth in [8, 16, 32] {
for (fg, want) in [("#000000", 100.0), ("#ffffff", 0.0)] {
let mut s = gray_doc(depth, fg);
click(&mut s, json!({}));
assert!((ink(&s) - want).abs() < 0.01, "Gray {depth} {fg}: {} % ink", ink(&s));
}
}
}
/// Not measured, so as before: a Grayscale document with a profile other than the default gray,
/// and RGB documents.
#[test]
fn other_profiles_and_modes_keep_todays_colour() {
let mut s = gray_doc(8, "#1e78c8");
s.execute("edit.assignProfile", json!({"profile": "gray-gamma-2.2"})).unwrap();
click(&mut s, json!({}));
assert_ink(ink(&s), 60.0, "Gray 8 tagged Gray Gamma 2.2: the luma sum");
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 30, "mode": "rgb", "depth": 8})).unwrap();
s.execute("tools.setColors", json!({"foreground": "#1e78c8"})).unwrap();
click(&mut s, json!({}));
let st = s.active().unwrap();
let v = st.active_layer.and_then(|id| st.doc.layer(id)).unwrap().surface().unwrap().rgba(20, 15);
let want = [30.0 / 255.0, 120.0 / 255.0, 200.0 / 255.0];
assert!((0..3).all(|i| (v[i] - want[i]).abs() < 1e-4), "RGB 8: {v:?}");
}
/// The foreground is RGB in the session's working RGB space, so another working RGB reads the same
/// numbers as another colour: pure green in Adobe RGB (1998) is darker than in sRGB.
#[test]
fn the_foreground_is_read_in_the_working_rgb() {
let mut s = gray_doc(8, "#00ff00");
click(&mut s, json!({}));
let srgb = ink(&s);
let mut s = gray_doc(8, "#00ff00");
s.execute("edit.colorSettings", json!({"workingRgb": "adobe-rgb-compat"})).unwrap();
click(&mut s, json!({}));
let adobe = ink(&s);
assert!(adobe > srgb + 3.0, "green: {srgb:.2} % ink in sRGB, {adobe:.2} % in Adobe RGB");
}
@@ -0,0 +1,77 @@
//! #17310: own synthetic strokes exercise the measured short-axis spacing law.
use photocraft_color::PixelFormat;
use photocraft_raster::Surface;
use crate::{BrushSettings, Stroke, StrokePoint, dabs, render_stroke};
#[test]
fn flattened_tip_spacing_uses_the_short_axis_at_both_angles_and_directions() {
for angle in [0.0, 90.0] {
for vertical in [false, true] {
let brush = BrushSettings { size: 40.0, roundness: 0.2, angle, spacing: 1.5, seed: 17310, ..BrushSettings::default() };
let points = if vertical {
vec![StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(100.0, 400.0, 1.0)]
} else {
vec![StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(400.0, 100.0, 1.0)]
};
let steps = dabs(&Stroke { brush, points });
assert_eq!(steps.len(), 26, "{angle} degrees, vertical={vertical}");
for (index, dab) in steps.iter().enumerate() {
let coordinate = if vertical { dab.center.y } else { dab.center.x };
assert!((coordinate - (100.0 + 12.0 * index as f64)).abs() < 1e-4);
}
}
}
}
#[test]
fn half_roundness_stays_continuous_and_round_tips_keep_their_last_dab() {
let points = [StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(400.0, 100.0, 1.0)];
let brush = BrushSettings { size: 40.0, roundness: 0.5, spacing: 1.5, seed: 17310, ..BrushSettings::default() };
let mut surface = Surface::new(PixelFormat::RGBA32F);
render_stroke(&mut surface, &brush, &points, None, false, 1.0);
for x in 100..=400 {
assert!(surface.rgba(x, 100)[3] > 0.5, "gap at {x}");
}
let round = BrushSettings { size: 20.0, roundness: 1.0, spacing: 2.0, ..brush };
let steps = dabs(&Stroke { brush: round, points: points.to_vec() });
assert_eq!(steps.len(), 8);
assert!((steps.last().unwrap().center.x - 380.0).abs() < 1e-4);
}
#[test]
fn square_block_spacing_ignores_roundness_like_its_rendered_tip() {
let points = vec![StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(400.0, 100.0, 1.0)];
let centres = |brush| dabs(&Stroke { brush, points: points.clone() }).iter().map(|dab| dab.center.x).collect::<Vec<_>>();
let brush = BrushSettings { size: 40.0, roundness: 0.2, spacing: 1.5, seed: 17310, ..BrushSettings::default() };
let elliptic = centres(brush.clone());
let square = centres(BrushSettings { aliased: true, square: true, ..brush.clone() });
let round = centres(BrushSettings { roundness: 1.0, ..brush });
assert!(elliptic.len() > 2 && square.len() > 2);
assert!(elliptic.windows(2).all(|pair| ((pair[1] - pair[0]) - 12.0).abs() < 1e-4));
assert!(square.windows(2).all(|pair| ((pair[1] - pair[0]) - 60.0).abs() < 1e-4));
assert_eq!(square, round, "Block's full square has the same pitch as a full-diameter round tip");
assert_ne!(square, elliptic, "only the genuinely elliptic tip uses its short axis");
}
#[test]
fn spacing_unchecked_keeps_legacy_distance_fallback_and_timestamped_speed() {
let centres =
|brush: BrushSettings, points: &[StrokePoint]| dabs(&Stroke { brush, points: points.to_vec() }).iter().map(|dab| dab.center.x).collect::<Vec<_>>();
let brush = BrushSettings { size: 40.0, roundness: 0.2, spacing: 1.5, spacing_enabled: false, seed: 17310, ..BrushSettings::default() };
let round = BrushSettings { roundness: 1.0, ..brush.clone() };
let points = [StrokePoint::new(100.0, 100.0, 1.0), StrokePoint::new(400.0, 100.0, 1.0)];
let unchecked = centres(brush.clone(), &points);
assert_eq!(unchecked, vec![100.0, 160.0, 220.0, 280.0, 340.0, 400.0], "unchecked distance fallback keeps the legacy full diameter");
assert_eq!(unchecked, centres(round.clone(), &points));
assert_ne!(unchecked, centres(BrushSettings { spacing_enabled: true, ..brush.clone() }, &points));
// Timestamped unchecked strokes still use the existing pointer-speed interval.
for (ms, count) in [(400.0, 51), (40.0, 6)] {
let timed = [points[0], StrokePoint { time: ms, ..points[1] }];
let flat = centres(brush.clone(), &timed);
assert_eq!(flat.len(), count, "{ms} ms");
assert_eq!(flat, centres(round.clone(), &timed), "roundness does not change timed unchecked spacing");
}
}
+4 -2
View File
@@ -606,13 +606,15 @@ pub fn base_diameter(b: &BrushSettings, s: &StepInput) -> f32 {
b.size * f
}
/// Distance after this dab: its current pre-jitter diameter times the spacing.
/// Distance after this dab: checked spacing uses its current pre-jitter short axis.
/// Unchecked spacing falls back to the full diameter when a segment has no usable timestamps.
fn step_len_for(brush: &BrushSettings, p: &StrokePoint, step: u64) -> f64 {
// The two initial Airbrush dabs share Fade step zero, as in DabBuilder::build_step.
let step = if brush.build_up { step.saturating_sub(1) } else { step };
let s = StepInput { point: *p, direction: 0.0, initial_direction: 0.0, step };
let d = base_diameter(brush, &s).max(1.0);
f64::from(d * brush.spacing.max(0.01)).max(0.5)
let short_axis = if !brush.spacing_enabled || (brush.aliased && brush.square) { d } else { d * brush.roundness.clamp(0.01, 1.0) };
f64::from(short_axis * brush.spacing.max(0.01)).max(0.5)
}
/// Builds the primary dabs of a step (Shape Dynamics, Scattering, Transfer, Color, Texture depth).
+3
View File
@@ -489,6 +489,9 @@ mod mixer_load_supply_tests;
#[cfg(test)]
mod smoothing_catch_up_default_tests;
#[cfg(test)]
mod brush_spacing_elliptic_tip_tests;
#[cfg(test)]
mod brush_pose_no_pen_tests;
+4
View File
@@ -486,6 +486,7 @@ pub(crate) const TAKERS: &[fn(&mut PhotocraftApp, &egui::Context)] = &[
discard_ui::take,
open_prompt::take,
credits::take,
crate::file_info_ui::take,
adjust_dialog::take,
layer_style::take,
color_picker_ui::take,
@@ -637,6 +638,9 @@ pub(crate) fn cancel_for_closed(app: &mut PhotocraftApp, ctx: &egui::Context, cl
/// Slice options and Divide, the adjustment editor for `image.adjustments.*`, the schema dialog for filters, otherwise a
/// bare command form. The error is an opener's refusal text.
pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) -> Result<DialogId, String> {
if command == crate::file_info_ui::COMMAND {
return crate::file_info_ui::open(app);
}
if command == "view.newGuideLayout" {
return guide_layout_ui::open(app).ok_or_else(|| "no document".to_string());
}
+10 -3
View File
@@ -80,10 +80,17 @@ fn file_info_keeps_multiline_metadata_on_confirm_and_reopen() {
}
confirm(&mut app, &ctx, id).unwrap();
crate::menus::invoke(&mut app, &ctx, "file.fileInfo", json!({})).unwrap();
let id = app.framework.dialogs.stack().top().expect("File Info reopens");
let dialog = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).expect("a parameter dialog");
assert!(app.framework.dialogs.stack().top().is_some(), "File Info reopens");
let (request, _rx) = crate::control::ControlRequest::new("ui.inspect", json!({}));
let report = match crate::control::handle(&mut app, &ctx, &request) {
crate::control::Reply::Done(report) => report,
_ => panic!("File Info inspection completes immediately"),
};
assert_eq!(report["ok"], true);
let dialogs = report["result"]["dialogs"].as_array().expect("reported dialogs");
let dialog = dialogs.iter().find(|dialog| dialog["key"] == "file.fileInfo").expect("File Info reports its fields");
for key in ["description", "copyright"] {
assert_eq!(dialog.fields().get(key), Some(&FieldValue::Text("First line\nSecond line".into())), "{key} comes back with its line break");
assert_eq!(dialog["fields"][key], json!("First line\nSecond line"), "{key} comes back with its line break");
}
}
@@ -0,0 +1,510 @@
//! File Info categories through the actual menu, dialog host, widgets and control channel.
use std::sync::Arc;
use egui::accesskit::Role;
use egui::{Modifiers, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::app::framework::BuildApp as _;
type H = Harness<'static, Box<PhotocraftApp>>;
const CATEGORIES: [(&str, &str); 12] = [
("basic", "Basic"),
("cameraData", "Camera Data"),
("origin", "Origin"),
("iptc", "IPTC"),
("iptcExtension", "IPTC Extension"),
("gpsData", "GPS Data"),
("audioData", "Audio Data"),
("videoData", "Video Data"),
("history", "History"),
("dicom", "DICOM"),
("assetTags", "Asset Tags"),
("rawData", "Raw Data"),
];
const CAMERA: [(&str, &str); 10] = [
("make", "Make"),
("model", "Model"),
("owner", "Owner"),
("lens", "Lens"),
("focalLength", "Focal Length"),
("exposure", "Exposure"),
("imageSize", "Image Size"),
("orientation", "Orientation"),
("resolution", "Resolution"),
("flash", "Flash"),
];
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:xmp="http://ns.adobe.com/xap/1.0/" xmlns:aux="http://ns.adobe.com/exif/1.0/aux/" xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" xmlns:fixture="https://example.invalid/metadata-fixture/" xmp:CreateDate="2024-02-17T12:40:19+01:00" xmp:ModifyDate="2024-02-17T12:41:20+01:00" xmp:MetadataDate="2024-02-17T12:42:21+01:00" fixture:opaque="preserve-me" aux:OwnerName="Fixture owner" exif:PixelXDimension="6016" exif:PixelYDimension="4000" tiff:Orientation="1" tiff:XResolution="300" tiff:YResolution="300" tiff:ResolutionUnit="2" exif:Flash="1"/></rdf:RDF></x:xmpmeta>"#;
/// Five camera rows the old nine-field CameraInfo writer does not carry. This is a
/// classic little-endian TIFF EXIF payload, using the same test-writer pattern as
/// engine web_cmds::tests::camera_exif; no parser or production helper is added.
fn extra_camera_exif() -> Vec<u8> {
let entry = |bytes: &mut Vec<u8>, tag: u16, kind: u16, count: u32, value: u32| {
bytes.extend_from_slice(&tag.to_le_bytes());
bytes.extend_from_slice(&kind.to_le_bytes());
bytes.extend_from_slice(&count.to_le_bytes());
bytes.extend_from_slice(&value.to_le_bytes());
};
const IFD0: u32 = 8;
const EXIF: u32 = IFD0 + 2 + 5 * 12 + 4;
const OWNER: u32 = EXIF + 2 + 4 * 12 + 4;
const X_RESOLUTION: u32 = OWNER + 12;
const Y_RESOLUTION: u32 = X_RESOLUTION + 8;
let mut bytes = b"II*\0".to_vec();
bytes.extend_from_slice(&IFD0.to_le_bytes());
bytes.extend_from_slice(&5u16.to_le_bytes());
entry(&mut bytes, 0x0112, 3, 1, 6); // Orientation: rotated 90 degrees clockwise.
entry(&mut bytes, 0x011a, 5, 1, X_RESOLUTION);
entry(&mut bytes, 0x011b, 5, 1, Y_RESOLUTION);
entry(&mut bytes, 0x0128, 3, 1, 3); // ResolutionUnit: centimetres.
entry(&mut bytes, 0x8769, 4, 1, EXIF);
bytes.extend_from_slice(&0u32.to_le_bytes());
assert_eq!(bytes.len(), EXIF as usize);
bytes.extend_from_slice(&4u16.to_le_bytes());
entry(&mut bytes, 0x9209, 3, 1, 0); // Flash: zero is a present value, not a missing row.
entry(&mut bytes, 0xa002, 4, 1, 4032);
entry(&mut bytes, 0xa003, 4, 1, 3024);
entry(&mut bytes, 0xa430, 2, 11, OWNER);
bytes.extend_from_slice(&0u32.to_le_bytes());
assert_eq!(bytes.len(), OWNER as usize);
bytes.extend_from_slice(b"EXIF owner\0\0"); // Eleven ASCII bytes, then one alignment byte.
assert_eq!(bytes.len(), X_RESOLUTION as usize);
for numerator in [240u32, 180] {
bytes.extend_from_slice(&numerator.to_le_bytes());
bytes.extend_from_slice(&1u32.to_le_bytes());
}
assert_eq!(bytes.len(), Y_RESOLUTION as usize + 8);
bytes
}
fn harness(size: egui::Vec2, camera: bool) -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 48, "name": "first.psd"})).unwrap();
if camera {
app.session
.edit("Metadata fixture", |doc, _| {
doc.metadata.xmp = Some(PACKET.into());
doc.metadata.exif = Some(Arc::new(photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo {
make: Some("Fixture make".into()),
model: Some("Fixture model".into()),
lens: Some("Fixture lens".into()),
exposure_time: Some(1.0 / 250.0),
f_number: Some(5.6),
iso: Some(200.0),
focal_length: Some(35.0),
focal_length_35mm: Some(52.0),
date_taken: Some("2024:02:17 12:40:19".into()),
})));
Ok(())
})
.unwrap();
}
app.sync_views();
let mut h = Harness::builder()
.with_context(app.ctx().clone())
.with_size(size)
.with_step_dt(1.0 / 30.0)
.with_max_steps(64)
.build_app(|ui, app| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro());
h.run_steps(4);
h
}
fn call(h: &mut H, method: &str, params: Value) -> Value {
let ctx = h.ctx.clone();
let (request, _rx) = crate::control::ControlRequest::new(method, params);
match crate::control::handle(h.state_mut(), &ctx, &request) {
crate::control::Reply::Done(reply) => reply,
_ => panic!("{method} should complete immediately"),
}
}
fn dialog(h: &mut H) -> Value {
let inspection = call(h, "ui.inspect", json!({}));
let dialogs = inspection["result"]["dialogs"].as_array().unwrap();
let matching: Vec<_> = dialogs.iter().filter(|dialog| dialog["key"] == "file.fileInfo").cloned().collect();
assert_eq!(matching.len(), 1, "{inspection}");
matching[0].clone()
}
fn open(h: &mut H) {
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "file.fileInfo", json!({})).unwrap();
h.run_steps(5);
assert_eq!(dialog(h)["key"], "file.fileInfo");
}
fn set(h: &mut H, field: &str, value: Value) {
let reply = call(h, "ui.dialog.set", json!({"dialog": "top", "field": field, "value": value}));
assert_eq!(reply["ok"], true, "{reply}");
h.run_steps(3);
}
fn camera_value_node(node: &egui_kittest::kittest::AccessKitNode<'_>, label: &str) -> bool {
use egui::accesskit::Role;
fn value_input(node: egui_kittest::kittest::AccessKitNode<'_>) -> bool {
(node.role() == Role::MultilineTextInput && node.is_hidden()) || node.children().any(value_input)
}
// The selectable value part owns both this label and its folded text input.
// A side caption has only its label; stay inside the immediate part container.
node.role() == Role::Label
&& node.label().as_deref() == Some(label)
&& node.value().is_some()
&& node.parent().is_some_and(|part| part.role() == Role::GenericContainer && part.children().any(value_input))
}
fn camera_value(h: &H, label: &str) -> String {
h.get_by(|node| camera_value_node(node, label)).accesskit_node().value().unwrap().to_owned()
}
#[test]
fn file_info_lists_twelve_categories_in_order_with_only_measured_tooltips() {
let mut h = harness(vec2(1200.0, 900.0), false);
open(&mut h);
h.get_by_role_and_label(Role::Dialog, "first");
assert_eq!(dialog(&mut h)["fields"]["category"], "basic");
let mut rows: Vec<_> = h
.query_all_by_role(Role::ListItem)
.filter_map(|row| {
row.accesskit_node().label().filter(|name| CATEGORIES.iter().any(|(_, label)| *label == name.as_str())).map(|label| (row.rect().top(), label))
})
.collect();
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
assert_eq!(rows.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>(), CATEGORIES.map(|(_, label)| label));
for (label, expected) in [
("Camera Data", "Camera Data :: Contains the most important TIFF and Exif properties."),
("Origin", "Origin :: Displays information about the origin of the asset"),
("IPTC", "IPTC :: International Press Telecommunications Council Core schema properties"),
("Raw Data", "Raw Data :: Displays the XMP packet in raw RDF/XML form."),
] {
assert_eq!(h.get_by_role_and_label(Role::ListItem, label).accesskit_node().description().as_deref(), Some(expected));
}
for label in ["Basic", "IPTC Extension", "GPS Data", "Audio Data", "Video Data", "History", "DICOM", "Asset Tags"] {
assert_eq!(h.get_by_role_and_label(Role::ListItem, label).accesskit_node().description(), None, "unmeasured {label}");
}
h.get_by_role_and_label(Role::TextInput, "Document Title");
assert!(h.query_by_role_and_label(Role::Heading, "Camera Information").is_none(), "Camera Data isn't appended to Basic");
h.get_by_role_and_label(Role::Button, "Preferences");
h.get_by_role_and_label(Role::Button, "Template Folder");
}
#[test]
fn category_click_and_control_switch_are_inspectable_and_reopen_on_the_last_page() {
let mut h = harness(vec2(1200.0, 900.0), false);
open(&mut h);
let before = h.state().session.active().unwrap().doc.clone();
h.get_by_role_and_label(Role::ListItem, "Camera Data").click();
h.run_steps(4);
assert_eq!(dialog(&mut h)["fields"]["category"], "cameraData");
for (key, label) in CATEGORIES {
set(&mut h, "category", json!(key));
assert_eq!(dialog(&mut h)["fields"]["category"], key);
assert_eq!(h.get_by_role_and_label(Role::ListItem, label).accesskit_node().is_selected(), Some(true));
}
let rejected = call(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "category", "value": "invented"}));
assert_eq!(rejected["ok"], false);
assert_eq!(dialog(&mut h)["fields"]["category"], "rawData");
h.get_by_role_and_label(Role::Button, "Cancel").click();
h.run_steps(3);
assert!(h.state().framework.dialogs.is_empty());
assert!(Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc));
open(&mut h);
assert_eq!(dialog(&mut h)["fields"]["category"], "rawData");
assert!(h.query_by_role_and_label(Role::TextInput, "Document Title").is_none());
}
#[test]
fn camera_page_shows_ten_empty_rows_and_keeps_existing_camera_formatting() {
for populated in [false, true] {
let mut h = harness(vec2(1200.0, 1000.0), populated);
let info = h.state_mut().session.execute("file.fileInfo", json!({})).unwrap();
open(&mut h);
h.get_by_role_and_label(Role::ListItem, "Camera Data").click();
h.run_steps(4);
let mut last = f32::NEG_INFINITY;
for (key, label) in CAMERA {
let node = h.get_by(|node| camera_value_node(node, label));
assert!(node.rect().top() >= last, "camera order {label}");
last = node.rect().top();
assert_eq!(camera_value(&h, label), info["camera"][key].as_str().unwrap_or_default(), "{label}");
}
h.get_by_role_and_label(Role::Heading, "Camera Information");
h.get_by_role_and_label(Role::Heading, "Shot Information");
assert_eq!(call(&mut h, "ui.dialog.set", json!({"dialog":"top", "field":"camera/owner", "value":"changed"}))["ok"], false);
if populated {
for (label, value) in [
("Make", "Fixture make"),
("Model", "Fixture model"),
("Lens", "Fixture lens"),
("Focal Length", "35 mm"),
("Exposure", "1/250 s"),
("Date Taken", "2024-02-17 12:40:19"),
("F-Stop", "f/5.6"),
("ISO Speed", "ISO 200"),
("Focal Length (35 mm)", "52 mm"),
] {
assert_eq!(camera_value(&h, label), value);
}
for key in ["owner", "imageSize", "orientation", "resolution", "flash"] {
assert!(info["camera"][key].as_str().is_some_and(|value| !value.is_empty()), "fixture supplies {key}: {info}");
}
}
}
// EXIF-only and conflicting XMP both use EXIF, including the present Flash=0.
for conflicting_xmp in [false, true] {
let mut h = harness(vec2(1200.0, 1000.0), false);
h.state_mut()
.session
.edit("Five EXIF camera fields", |doc, _| {
doc.metadata.exif = Some(Arc::new(extra_camera_exif()));
// PACKET disagrees with EXIF on all five rows; EXIF must win, including Flash=0.
doc.metadata.xmp = conflicting_xmp.then(|| PACKET.into());
Ok(())
})
.unwrap();
let info = h.state_mut().session.execute("file.fileInfo", json!({})).unwrap();
let expected = [
("owner", "Owner", "EXIF owner"),
("imageSize", "Image Size", "4032 x 3024"),
("orientation", "Orientation", "Rotated 90° CW"),
("resolution", "Resolution", "240 x 180 / centimetres"),
("flash", "Flash", "No flash"),
];
for (key, _, value) in expected {
assert_eq!(info["camera"][key], value, "EXIF row {key}, conflicting XMP {conflicting_xmp}");
}
open(&mut h);
h.get_by_role_and_label(Role::ListItem, "Camera Data").click();
h.run_steps(4);
for (_, label, value) in expected {
assert_eq!(camera_value(&h, label), value, "shown EXIF row {label}, conflicting XMP {conflicting_xmp}");
}
}
}
#[test]
fn switching_category_resets_only_the_page_scroll_and_keeps_the_footer_fixed() {
let mut h = harness(vec2(1100.0, 430.0), true);
open(&mut h);
h.get_by_role_and_label(Role::ListItem, "Camera Data").click();
h.run_steps(8);
let make_y = h.get_by(|node| camera_value_node(node, "Make")).rect().top();
let footer = h.get_by_role_and_label(Role::Button, "OK").rect();
let categories = h.get_by_role_and_label(Role::ListItem, "Basic").rect();
h.hover_at(h.get_by(|node| camera_value_node(node, "Lens")).rect().center());
for _ in 0..12 {
h.event(egui::Event::MouseWheel {
source: egui::MouseWheelSource::Unknown,
unit: egui::MouseWheelUnit::Line,
delta: vec2(0.0, -1.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
});
h.run_steps(1);
}
let moved_y = h.query_by(|node| camera_value_node(node, "Make")).map(|node| node.rect().top());
assert_ne!(moved_y, Some(make_y), "the page really scrolled");
assert_eq!(h.get_by_role_and_label(Role::Button, "OK").rect(), footer);
assert_eq!(h.get_by_role_and_label(Role::ListItem, "Basic").rect(), categories);
h.get_by_role_and_label(Role::ListItem, "Basic").click();
h.run_steps(4);
h.get_by_role_and_label(Role::ListItem, "Camera Data").click();
h.run_steps(32);
let reset = h.get_by(|node| camera_value_node(node, "Make")).rect().top();
assert!((reset - make_y).abs() < 1.0, "returned to page top: {make_y} -> {reset}");
assert_eq!(h.get_by_role_and_label(Role::Button, "OK").rect(), footer);
}
#[test]
fn basic_widget_edits_cancel_without_mutation_then_ok_applies_once() {
let mut h = harness(vec2(1200.0, 900.0), true);
for commit in [false, true] {
open(&mut h);
let before = h.state().session.active().unwrap().doc.clone();
let history = h.state().session.active().unwrap().history.entries();
h.get_by_role_and_label(Role::TextInput, "Document Title").click();
h.run_steps(1);
h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("Typed title".into()));
h.run_steps(2);
h.key_press(egui::Key::Tab);
h.run_steps(2);
assert_eq!(dialog(&mut h)["fields"]["title"], "Typed title");
h.get_by_role_and_label(Role::Button, if commit { "OK" } else { "Cancel" }).click();
h.run_steps(5);
assert!(h.state().framework.dialogs.is_empty());
let state = h.state().session.active().unwrap();
if commit {
assert_eq!(state.history.entries().len(), history.len() + 1);
let info = h.state_mut().session.execute("file.fileInfo", json!({})).unwrap();
assert_eq!(info["title"], "Typed title");
} else {
assert!(Arc::ptr_eq(&before, &state.doc));
assert_eq!(state.history.entries(), history);
}
}
}
#[test]
fn command_control_held_ok_keeps_captured_document_and_retries_after_both_authorization_failures() {
let mut h = harness(vec2(1200.0, 900.0), true);
let first = h.state().session.active().unwrap().doc.id;
let opened = call(&mut h, "ui.dialog.open", json!({"kind":"command", "command":"file.fileInfo"}));
assert_eq!(opened["ok"], true, "{opened}");
h.run_steps(4);
set(&mut h, "title", json!("Captured title"));
set(&mut h, "author", json!("A; B"));
set(&mut h, "keywords", json!("A; B, C"));
set(&mut h, "copyrightStatus", json!("copyrighted"));
assert_eq!(call(&mut h, "ui.dialog.set", json!({"dialog":"top", "field":"copyrightStatus", "value":"invented"}))["ok"], false);
assert_eq!(dialog(&mut h)["fields"]["copyrightStatus"], "copyrighted");
h.state_mut().run("file.new", json!({"width": 32, "height": 24, "name":"second.psd"})).unwrap();
let second = h.state().session.active().unwrap().doc.id;
h.run_steps(4);
h.get_by_role_and_label(Role::Dialog, "first");
let before: Vec<_> = h.state().session.documents().iter().map(|state| (state.doc.clone(), state.revision, state.history.entries())).collect();
h.state_mut().services.automation_command = Some(Box::new(|id, _| if id == "file.fileInfo" { Err("command denied".into()) } else { Ok(()) }));
let denied = call(&mut h, "ui.dialog.confirm", json!({"dialog":"top"}));
assert_eq!(denied["ok"], false, "{denied}");
assert_eq!(dialog(&mut h)["fields"]["title"], "Captured title");
h.state_mut().services.automation_command = None;
h.state_mut().services.automation_authorize =
Some(|id, _| if id == "file.fileInfo" { Err(photocraft_engine::EngineError::Other("engine denied".into())) } else { Ok(()) });
let failed = call(&mut h, "ui.dialog.confirm", json!({"dialog":"top"}));
assert_eq!(failed["ok"], false, "{failed}");
assert_eq!(dialog(&mut h)["fields"]["title"], "Captured title");
for (state, (doc, revision, history)) in h.state().session.documents().iter().zip(&before) {
assert!(Arc::ptr_eq(doc, &state.doc));
assert_eq!(state.revision, *revision);
assert_eq!(&state.history.entries(), history);
}
h.state_mut().services.automation_authorize = None;
let from = h.state().session.journal.len();
assert_eq!(call(&mut h, "ui.dialog.confirm", json!({"dialog":"top"}))["ok"], true);
h.run_steps(4);
assert!(h.state().framework.dialogs.is_empty());
assert_eq!(h.state().session.active().unwrap().doc.id, second, "active tab restored");
assert!(Arc::ptr_eq(&before[1].0, &h.state().session.active().unwrap().doc));
let captured = h.state().session.documents().iter().find(|state| state.doc.id == first).unwrap();
assert_eq!(captured.history.entries().len(), before[0].2.len() + 1);
assert_eq!(h.state().session.journal[from..].iter().filter(|(id, _)| id == "file.fileInfo").count(), 1);
let info = photocraft_engine::file_cmds::read_file_info(captured.doc.metadata.xmp.as_deref());
assert_eq!(info["title"], "Captured title");
assert_eq!(info["author"], "A; B");
assert_eq!(info["keywords"], json!(["A", "B", "C"]));
assert_eq!(info["copyrightStatus"], "copyrighted");
assert_eq!(call(&mut h, "ui.dialog.confirm", json!({"dialog":"top"}))["ok"], false, "cannot apply twice");
}
#[test]
fn no_op_basic_confirmation_preserves_dates_and_matches_the_current_command_history_contract() {
let mut ui = harness(vec2(1200.0, 900.0), true);
let mut direct = harness(vec2(1200.0, 900.0), true);
open(&mut ui);
let fields = dialog(&mut ui)["fields"].clone();
let mut params = serde_json::Map::new();
for key in ["title", "author", "authorTitle", "description", "keywords", "copyrightStatus", "copyright", "copyrightUrl"] {
params.insert(key.to_owned(), fields[key].clone());
}
let before = ui.state().session.active().unwrap().history.entries().len();
let direct_before = direct.state().session.active().unwrap().history.entries().len();
direct.state_mut().run("file.fileInfo", Value::Object(params)).unwrap();
assert_eq!(call(&mut ui, "ui.dialog.confirm", json!({"dialog":"top"}))["ok"], true);
ui.run_steps(4);
let actual = ui.state().session.active().unwrap();
let expected = direct.state().session.active().unwrap();
assert_eq!(actual.doc.metadata.xmp, expected.doc.metadata.xmp);
assert_eq!(actual.history.entries().len() - before, expected.history.entries().len() - direct_before);
let xmp = actual.doc.metadata.xmp.as_deref().unwrap();
for unchanged in ["2024-02-17T12:40:19+01:00", "2024-02-17T12:41:20+01:00", "2024-02-17T12:42:21+01:00", "preserve-me"] {
assert!(xmp.contains(unchanged), "kept {unchanged}: {xmp}");
}
}
#[test]
fn xmp_attribute_forms_supply_camera_and_basic_values_and_preserve_unrelated_content() {
// Our own synthetic XML: ordinary double quotes, single quotes, and XML whitespace variants.
for (before, around, quote) in [(" ", "", '"'), (" ", "", '\''), ("\t", " \t ", '"'), ("\n", "\r\n", '\''), ("\r", " ", '"')] {
let other = if quote == '"' { '\'' } else { '"' };
let note = format!("fixture:note={other} aux:OwnerName={quote}quoted-decoy{quote}{other}");
let packet = format!(
r#"<?fixture aux:OwnerName='pi-owner' tiff:Make='pi-make'?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><!-- aux:OwnerName={quote}comment-decoy{quote} --><rdf:Description rdf:about="" xmlns:aux="http://ns.adobe.com/exif/1.0/aux/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:xmpRights="http://ns.adobe.com/xap/1.0/rights/" xmlns:fixture="https://example.invalid/metadata-fixture/" {note}{before}aux:OwnerName{around}={around}{quote}Ada &amp; Co{quote}{before}tiff:Make{around}={around}{quote}Fixture make{quote}{before}photoshop:AuthorsPosition{around}={around}{quote}Old role{quote}{before}xmpRights:Marked{around}={around}{quote}True{quote} fixture:opaque="preserve-me"/></rdf:RDF></x:xmpmeta>"#
);
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
session
.edit("XMP attribute fixture", |doc, _| {
doc.metadata.xmp = Some(packet.clone().into());
Ok(())
})
.unwrap();
let original = session.active().unwrap().doc.metadata.xmp.clone();
let read = session.execute("file.fileInfo", json!({})).unwrap();
assert_eq!(read["camera"]["owner"], "Ada & Co", "{before:?} {around:?} {quote}");
assert_eq!(read["camera"]["make"], "Fixture make");
assert_eq!(read["authorTitle"], "Old role", "Basic shares the approved attribute forms");
assert_eq!(read["copyrightStatus"], "copyrighted", "existing Marked behavior");
assert_eq!(session.active().unwrap().doc.metadata.xmp, original, "reading must not edit metadata");
let changed = session.execute("file.fileInfo", json!({"authorTitle": "New role"})).unwrap();
assert_eq!(changed["authorTitle"], "New role");
assert_eq!(changed["camera"], read["camera"], "a Basic edit keeps Camera Data");
assert_eq!(changed["copyrightStatus"], "copyrighted");
let xmp = session.active().unwrap().doc.metadata.xmp.as_deref().unwrap();
assert!(!xmp.contains("Old role"), "a Basic edit removes every attribute form it reads");
assert!(xmp.contains(&note), "unrelated quoted attribute content survives");
assert!(xmp.contains("fixture:opaque=\"preserve-me\""));
assert!(xmp.contains(&format!("<!-- aux:OwnerName={quote}comment-decoy{quote} -->")));
}
// The pre-existing Marked scanner also reads PI pseudo-attributes. Basic reuse keeps
// that policy; Camera fallbacks still exclude the processing-instruction decoys above.
let marked = photocraft_engine::file_cmds::read_file_info(Some(
r#"<?fixture xmpRights:Marked='False'?><rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xmpRights="http://ns.adobe.com/xap/1.0/rights/" xmpRights:Marked="True"/>"#,
));
assert_eq!(marked["copyrightStatus"], "publicDomain", "keep pre-PR Marked behavior");
}
#[test]
fn a_single_quoted_basic_attribute_reads_edits_and_reopens_without_leaving_the_old_value() {
let mut h = harness(vec2(1200.0, 900.0), false);
let packet = 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:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:fixture="https://example.invalid/metadata-fixture/" photoshop:AuthorsPosition = 'Old &amp; role' fixture:opaque='keep-me'/></rdf:RDF></x:xmpmeta>"#;
h.state_mut()
.session
.edit("Single-quoted Basic fixture", |doc, _| {
doc.metadata.xmp = Some(packet.into());
Ok(())
})
.unwrap();
h.run_steps(3);
let original = h.state().session.active().unwrap().doc.metadata.xmp.clone();
open(&mut h);
assert_eq!(dialog(&mut h)["fields"]["category"], "basic");
assert_eq!(dialog(&mut h)["fields"]["authorTitle"], "Old & role");
assert_eq!(h.state().session.active().unwrap().doc.metadata.xmp, original, "opening does not rewrite XMP");
set(&mut h, "authorTitle", json!("Revised & role"));
assert_eq!(h.state().session.active().unwrap().doc.metadata.xmp, original, "the edit stays a draft until OK");
h.get_by_role_and_label(Role::Button, "OK").click();
h.run_steps(5);
assert!(h.state().framework.dialogs.is_empty());
let info = h.state_mut().session.execute("file.fileInfo", json!({})).unwrap();
assert_eq!(info["authorTitle"], "Revised & role");
let xmp = h.state().session.active().unwrap().doc.metadata.xmp.as_deref().unwrap();
assert!(!xmp.contains("Old &amp; role"), "the old attribute is removed, not hidden by the new element");
assert!(xmp.contains("fixture:opaque='keep-me'"), "unrelated attributes survive");
open(&mut h);
assert_eq!(dialog(&mut h)["fields"]["authorTitle"], "Revised & role");
h.get_by_role_and_label(Role::Button, "Cancel").click();
h.run_steps(3);
assert!(h.state().framework.dialogs.is_empty());
}
+396
View File
@@ -0,0 +1,396 @@
//! File Info's app-owned pages. The framework owns the dialog, input and field controls; this
//! module keeps the metadata draft and applies it to the document the dialog opened on.
use std::borrow::Cow;
use craft::behavior::{DisplayOrder, ItemSource, Selection, SelectionChange};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{
ActivateOn, Bind, CollectionEvent, Lazy, Props as _, SaveKey, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::display::Divider;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow};
use craft::ui::notices::{Notice, NoticeLayout};
use craft::ui::patterns::form_dialogs::{DialogFields, FormDialog, Param, ParamKind, ParamRows, set_param_field};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::memory::{saved_value, set_saved_value};
use photocraft_doc::DocId;
use serde_json::{Value, json};
use crate::PhotocraftApp;
pub(crate) const COMMAND: &str = "file.fileInfo";
const LAST_CATEGORY: SaveKey = SaveKey::new("photocraft.fileInfo.category");
const BASIC_KEYS: [&str; 8] = ["title", "author", "authorTitle", "description", "keywords", "copyrightStatus", "copyright", "copyrightUrl"];
struct Category {
key: &'static str,
label: &'static str,
tooltip: Option<&'static str>,
}
const CATEGORIES: [Category; 12] = [
Category { key: "basic", label: "Basic", tooltip: None },
Category { key: "cameraData", label: "Camera Data", tooltip: Some("Camera Data :: Contains the most important TIFF and Exif properties.") },
Category { key: "origin", label: "Origin", tooltip: Some("Origin :: Displays information about the origin of the asset") },
Category { key: "iptc", label: "IPTC", tooltip: Some("IPTC :: International Press Telecommunications Council Core schema properties") },
Category { key: "iptcExtension", label: "IPTC Extension", tooltip: None },
Category { key: "gpsData", label: "GPS Data", tooltip: None },
Category { key: "audioData", label: "Audio Data", tooltip: None },
Category { key: "videoData", label: "Video Data", tooltip: None },
Category { key: "history", label: "History", tooltip: None },
Category { key: "dicom", label: "DICOM", tooltip: None },
Category { key: "assetTags", label: "Asset Tags", tooltip: None },
Category { key: "rawData", label: "Raw Data", tooltip: Some("Raw Data :: Displays the XMP packet in raw RDF/XML form.") },
];
struct Categories;
impl DisplayOrder<String> for Categories {
fn len(&self) -> usize {
CATEGORIES.len()
}
fn key(&self, at: usize) -> String {
CATEGORIES.get(at).map_or_else(String::new, |category| category.key.to_owned())
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
CATEGORIES.get(at).map(|category| Cow::Borrowed(category.label))
}
}
impl ItemSource<String> for Categories {}
/// The Basic page schema, shared with its title/label contract tests.
pub(crate) fn basic_rows() -> Vec<Param> {
vec![
Param::new("title", tl!("Document Title"), ParamKind::text("")),
Param::new("author", tl!("Author"), ParamKind::text("")),
Param::new("authorTitle", tl!("Author Title"), ParamKind::text("")),
Param::new("description", tl!("Description"), ParamKind::text("")).multiline(3),
Param::new("keywords", tl!("Keywords"), ParamKind::text("")).multiline(3),
Param::new(
"copyrightStatus",
tl!("Copyright Status"),
ParamKind::choice(
vec![
("unknown".to_owned(), Label::from(tl!("Unknown"))),
("copyrighted".to_owned(), Label::from(tl!("Copyrighted"))),
("publicDomain".to_owned(), Label::from(tl!("Public Domain"))),
],
Some("unknown".to_owned()),
),
),
Param::new("copyright", tl!("Copyright Notice"), ParamKind::text("")).multiline(3),
Param::new("copyrightUrl", tl!("Copyright Info URL"), ParamKind::text("")),
]
}
/// The reference's ten rows are always present; the four older extra rows keep their values
/// and stay below them when present. The engine alone formats camera values.
fn camera_rows(camera: &Value) -> (Vec<Param>, DialogFields) {
let lang = crate::i18n::current();
let mut rows = Vec::new();
let mut fields = DialogFields::new();
for (heading, entries) in [
("Camera Information", &[("make", "Make"), ("model", "Model"), ("owner", "Owner"), ("lens", "Lens")][..]),
(
"Shot Information",
&[
("focalLength", "Focal Length"),
("exposure", "Exposure"),
("imageSize", "Image Size"),
("orientation", "Orientation"),
("resolution", "Resolution"),
("flash", "Flash"),
][..],
),
] {
rows.push(Param::section(tl!(heading)));
for (key, label) in entries {
let value = camera.get(*key).and_then(Value::as_str).unwrap_or_default();
let field = format!("camera/{key}");
fields.set(field.clone(), value);
rows.push(Param::read_only_text(field, crate::i18n::tr_ctx(lang, "cameraData", label), value.to_owned()));
}
}
for (key, label) in [("dateTaken", "Date Taken"), ("fNumber", "F-Stop"), ("iso", "ISO Speed"), ("focalLength35mm", "Focal Length (35 mm)")] {
if let Some(value) = camera.get(key).and_then(Value::as_str).filter(|value| !value.is_empty()) {
let field = format!("camera/{key}");
fields.set(field.clone(), value);
rows.push(Param::read_only_text(field, crate::i18n::tr_ctx(lang, "cameraData", label), value.to_owned()));
}
}
(rows, fields)
}
fn initial_fields(info: &Value) -> DialogFields {
let mut fields = DialogFields::new();
for key in BASIC_KEYS {
let text = if key == "keywords" {
info[key].as_array().map(|values| values.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default()
} else if key == "copyrightStatus" {
info[key].as_str().unwrap_or("unknown").to_owned()
} else {
info[key].as_str().unwrap_or_default().to_owned()
};
fields.set(key, text);
}
fields.snapshot();
fields
}
fn command_params(fields: &DialogFields) -> Value {
Value::Object(BASIC_KEYS.into_iter().map(|key| (key.to_owned(), json!(fields.text(key).unwrap_or_default()))).collect())
}
/// Opens on the last page shown, keeping Basic's values from this document, not a previous form.
pub(crate) fn open(app: &mut PhotocraftApp) -> Result<DialogId, String> {
let document = app.active_doc_id()?;
let title = Label::from(crate::dialogs::file_info_title(app));
let info = app.session.execute(COMMAND, json!({})).map_err(|error| error.to_string())?;
let selected = saved_value::<String>(app.ctx(), &LAST_CATEGORY);
let category = CATEGORIES.iter().find(|category| category.key == selected).map_or("basic", |category| category.key);
let fields = initial_fields(&info);
let (camera_params, camera_fields) = camera_rows(&info["camera"]);
Ok(app.framework.dialogs.open(FileInfoDialog {
document,
title,
opening: fields.clone(),
fields,
camera: info["camera"].clone(),
camera_params,
camera_fields,
category,
reset_scroll: true,
held: HeldAnswer::new(),
}))
}
struct FileInfoDialog {
document: DocId,
title: Label,
fields: DialogFields,
opening: DialogFields,
camera: Value,
camera_params: Vec<Param>,
camera_fields: DialogFields,
category: &'static str,
reset_scroll: bool,
held: HeldAnswer<Answer>,
}
#[derive(Clone)]
struct Answer {
fields: DialogFields,
programmatic: bool,
}
impl FileInfoDialog {
fn file_ok(&mut self, programmatic: bool) {
if !self.held.is_waiting() && !self.held.is_accepted() {
self.held.file(Answer { fields: self.fields.clone(), programmatic });
}
}
}
impl StackDialog for FileInfoDialog {
type Result = ();
fn id(&self) -> DialogId {
dialog_id(COMMAND)
}
fn key(&self) -> Option<&str> {
Some(COMMAND)
}
fn held_state(&self) -> Option<HeldOk> {
self.held.state()
}
fn confirm(&mut self, _: &egui::Context) -> Option<()> {
if self.held.finish().is_some() {
Some(())
} else {
self.file_ok(true);
None
}
}
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let measuring = craft::ui::runtime::measure::active(ui.ctx());
if !measuring && self.held.finish().is_some() {
return Some(DialogResult::Ok(()));
}
let before = self.fields.clone();
let old_category = self.category;
let mut selected = self.category;
let mut reset_scroll = self.reset_scroll;
let waiting = self.held.is_waiting();
let error = self.held.refusal().map(|(error, _)| error.clone());
let rows = basic_rows();
let shown = FormDialog::new(self.title.clone(), Bind::bound(&mut self.fields))
.opening(self.opening.clone())
.history(true)
.collection_body(true)
.accept_stays_open(true)
.ok_enabled(!waiting)
.footer_extra(|ui| {
// These future File Info subdialogs are outside #13828; don't invent their behaviour.
Row::new().show(ui, |ui, _| {
Button::new(tl!("Preferences")).enabled(false).show(ui);
Button::new(tl!("Template Folder")).enabled(false).show(ui);
});
})
.shaped(|dialog| {
dialog.id(dialog_id(COMMAND)).resizable(true).overlay(|overlay| {
// design: allow[literal-size/vec2](File Info's resizable opening and minimum sizes in points)
overlay.size(egui::vec2(900.0, 640.0)).min_size(egui::vec2(560.0, 360.0))
})
})
.show(ui, |ui, _, fields| {
Row::new().fill().enabled(!waiting).show(ui, |ui, _| {
let list = List::<String>::new(tl!("File Info Categories"))
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.allow_empty(false)
.header(false)
.sizing(Sizing::Content)
.selection(Bind::given(Selection::single(selected.to_owned())))
.show_items(ui, &Categories, &mut |key, _| {
let category = CATEGORIES.iter().find(|category| category.key == key.as_str());
let row = ListRow::new(category.map_or_else(Label::default, |category| Label::from(tl!(category.label))));
match category.and_then(|category| category.tooltip) {
Some(tooltip) => row.tooltip(tl!(tooltip)),
None => row,
}
});
for event in list.events {
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(category) = keys.iter().find_map(|key| CATEGORIES.iter().find(|category| category.key == key.as_str()))
&& category.key != selected
{
selected = category.key;
reset_scroll = true;
}
}
Divider::vertical().show(ui);
Stack::new().fill().scroll(Scroll::vertical()).label(tl!("File Info Page")).show(ui, |ui, _| {
// One stable scroll owner; reveal its first child on a switch instead of leaking
// one new scroll identity for every visit. Wheel input can interrupt the glide.
Lazy::new("file-info-page", 0.0).reveal(reset_scroll).show(ui, |ui| match selected {
"basic" => {
ParamRows::new(tl!("Basic"), &rows, Bind::bound(fields)).show(ui);
}
"cameraData" => {
ParamRows::new(tl!("Camera Data"), &self.camera_params, Bind::bound(&mut self.camera_fields)).read_only(true).show(ui);
}
_ => {}
});
});
});
if let Some(error) = &error {
Notice::new(Tone::Bad, error.clone()).layout(NoticeLayout::Inline).show(ui);
}
true
});
if measuring {
return None;
}
self.reset_scroll = false;
self.category = selected;
if selected != old_category {
set_saved_value(ui.ctx(), &LAST_CATEGORY, selected.to_owned());
}
if self.fields != before || selected != old_category {
self.held.clear_refusal();
}
if shown.picked == Some(0) || shown.accepted.is_some() {
self.file_ok(false);
}
if shown.closed.is_some() && !self.held.is_waiting() { Some(DialogResult::Cancel) } else { None }
}
fn json_fields(&self) -> Option<Value> {
let Value::Object(mut fields) = serde_json::to_value(&self.fields).ok()? else { return None };
fields.insert("category".into(), json!(self.category));
fields.insert("camera".into(), self.camera.clone());
fields.insert("document".into(), json!(self.document.0));
Some(Value::Object(fields))
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> {
if self.held.is_waiting() || self.held.is_accepted() {
return Err(FieldRefusal::Inactive.message(field));
}
if field == "category" {
let category = value
.as_str()
.and_then(|key| CATEGORIES.iter().find(|category| category.key == key))
.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
if self.category != category.key {
self.category = category.key;
self.reset_scroll = true;
set_saved_value(ctx, &LAST_CATEGORY, category.key.to_owned());
}
} else if field == "camera" || field == "document" || field.starts_with("camera/") {
return Err(FieldRefusal::ReadOnly.message(field));
} else {
if self.category != "basic" {
return Err(FieldRefusal::Inactive.message(field));
}
set_param_field(&basic_rows(), &mut self.fields, field, value)?;
}
self.held.clear_refusal();
Ok(())
}
}
/// The held OK applies through the normal command path before the host closes the dialog.
/// A refused command keeps the draft and captured document; a successful one runs only once.
pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
let closed = app
.framework
.dialogs
.get_by_id::<FileInfoDialog>(dialog_id(COMMAND))
.filter(|dialog| !app.session.documents().iter().any(|state| state.doc.id == dialog.document))
.map(StackDialog::id);
if let Some(id) = closed {
app.framework.dialogs.cancel_by_id(ctx, id);
}
let owner = app
.framework
.dialogs
.get_by_id::<FileInfoDialog>(dialog_id(COMMAND))
.and_then(|dialog| app.framework.dialogs.open_serial(dialog.id()).map(|serial| (dialog.id(), serial, dialog.document)));
let pending = owner.and_then(|(id, serial, document)| {
app.framework.dialogs.get_mut_by_id::<FileInfoDialog>(id).and_then(|dialog| dialog.held.take().map(|answer| (id, serial, document, answer)))
});
if let Some((id, serial, document, answer)) = pending {
let params = command_params(&answer.fields);
let result = app.with_document(document, |app| {
// ui.dialog.confirm judges command dialogs even without an injected input pass. The
// generic control adapter recognizes HostedParamDialog; this app-owned family keeps
// that same gate here while OK is still held. Injected input is already gated by run.
if answer.programmatic
&& !app.automation_input
&& let Some(authorize) = app.services.automation_command.as_ref()
{
authorize(COMMAND, &params)?;
}
app.run(COMMAND, params)
});
// A command may open/replace a dialog through a script event. Its answer belongs only
// to this opening, never a replacement with the same family/id.
if app.framework.dialogs.open_serial(id) == Some(serial)
&& let Some(dialog) = app.framework.dialogs.get_mut_by_id::<FileInfoDialog>(id)
{
dialog.held.answer(result.map(|_| ()).map_err(Label::from));
}
}
// The result is only a completion notification: the command already succeeded while held.
while app.framework.dialogs.take::<FileInfoDialog>().is_some() {}
}
@@ -0,0 +1,72 @@
//! #17609: with the Brush tool and no stroke, Escape leaves the selection alone and adds no
//! History state. It still resets a rotated view and leaves a full screen mode first; other tools
//! keep the idle Escape deselect (#2674).
use egui::{Key, vec2};
use egui_kittest::Harness;
use serde_json::json;
use crate::PhotocraftApp;
use crate::state::Tool;
/// A 600x500 document with a selection of 100,100 - 500,400 and `tool` active.
fn harness(tool: Tool) -> Harness<'static, Box<PhotocraftApp>> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 600, "height": 500})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 100, "width": 400, "height": 300})).unwrap();
app.ui.tool = tool;
app.sync_views();
let ctx = app.ctx().clone();
let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_context(ctx).with_max_steps(64).build_eframe(move |_cc| app);
h.run_steps(4);
h
}
fn selection_bounds(h: &Harness<'static, Box<PhotocraftApp>>) -> Option<photocraft_geom::Rect> {
h.state().session.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds())
}
fn history(h: &Harness<'static, Box<PhotocraftApp>>) -> usize {
h.state().session.active().unwrap().history.entries().len()
}
fn escape(h: &mut Harness<'static, Box<PhotocraftApp>>) {
h.key_press(Key::Escape);
h.run_steps(2);
}
const SELECTED: photocraft_geom::Rect = photocraft_geom::Rect { x0: 100, y0: 100, x1: 500, y1: 400 };
#[test]
fn brush_escape_keeps_the_selection_and_adds_no_history_state() {
let mut h = harness(Tool::Brush);
let steps = history(&h);
escape(&mut h);
assert_eq!(selection_bounds(&h), Some(SELECTED), "the selection stays");
assert_eq!(history(&h), steps, "no Deselect state");
escape(&mut h);
assert_eq!(selection_bounds(&h), Some(SELECTED), "a second Escape changes nothing either");
assert!(!h.state().ui.status_error, "no error: {}", h.state().ui.status);
}
#[test]
fn brush_escape_still_resets_a_rotated_view_and_leaves_full_screen() {
let mut h = harness(Tool::Brush);
h.state_mut().ui.views[0].rotation = 40.0;
escape(&mut h);
assert_eq!(h.state().ui.views[0].rotation, 0.0, "the rotated view is reset");
h.state_mut().ui.view.screen_mode = craft::ui::shell::ScreenMode::FullScreen;
h.run_steps(2);
escape(&mut h);
assert_eq!(h.state().ui.view.screen_mode, craft::ui::shell::ScreenMode::Standard, "full screen is left");
assert_eq!(selection_bounds(&h), Some(SELECTED), "the selection stays");
}
#[test]
fn other_tools_still_deselect_on_escape() {
for tool in [Tool::Pencil, Tool::Move, Tool::RectMarquee] {
let mut h = harness(tool);
escape(&mut h);
assert_eq!(selection_bounds(&h), None, "{tool:?}: Escape deselects as before");
}
}
+6 -1
View File
@@ -359,7 +359,8 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
app.ui.view.screen_mode = craft::ui::shell::ScreenMode::Standard;
return;
}
if !esc_taken && app.session.active().is_some_and(|st| st.doc.selection.is_some()) && crate::window_keys::take_escape(ctx) {
// The Brush leaves the selection alone on an idle Esc, as the reference application does (#17609).
if !esc_taken && app.ui.tool != Tool::Brush && app.session.active().is_some_and(|st| st.doc.selection.is_some()) && crate::window_keys::take_escape(ctx) {
if let Err(e) = app.run("select.deselect", json!({})) {
app.ui.status = e;
app.ui.status_error = true;
@@ -416,3 +417,7 @@ mod tests;
#[cfg(test)]
#[path = "tool_key_default_tests.rs"]
mod tool_key_default_tests;
#[cfg(test)]
#[path = "brush_escape_keeps_selection_tests.rs"]
mod brush_escape_keeps_selection_tests;
+3 -1
View File
@@ -680,7 +680,9 @@ fn escape_resets_rotation_before_idle_deselection_for_paint_tools() {
assert_eq!(h.state().session.active().unwrap().history.entries().len(), history, "view reset is not an edit");
h.key_press(Key::Escape);
h.run_steps(2);
assert!(h.state().session.active().unwrap().doc.selection.is_none(), "second Esc deselects normally");
// The Brush keeps the selection on an idle Esc (#17609); the Pencil deselects.
let kept = h.state().session.active().unwrap().doc.selection.is_some();
assert_eq!(kept, tool == crate::state::Tool::Brush, "{tool:?}: second Esc");
}
}
+4
View File
@@ -33,6 +33,7 @@ pub mod dialogs;
pub mod dock;
pub(crate) mod edit_session;
pub mod file_dialog;
mod file_info_ui;
pub mod file_open;
pub mod frame_stages;
pub mod gpu_memo;
@@ -1128,3 +1129,6 @@ mod clone_stamp_indexed_bar_tests;
#[cfg(test)]
mod place_visible_centre_tests;
#[cfg(test)]
mod file_info_categories_tests;
+2 -48
View File
@@ -19,10 +19,9 @@ pub(crate) use artboard_name_options::strip as strip_artboard_name_options;
/// The command ids whose dialog is a hosted parameter form built by [`params_for`] (Open EXR Parts included).
/// The dialogs area's `PARAM_FAMILIES` row owns exactly these.
const FORM_COMMANDS: [&str; 21] = [
const FORM_COMMANDS: [&str; 20] = [
"file.openExrParts",
"layer.videoLayers.interpretFootage",
"file.fileInfo",
"file.automate.fitImage",
"file.automate.conditionalModeChange",
"file.export.layersToFiles",
@@ -290,7 +289,6 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
let fps = st.doc.layer(layer).and_then(|l| l.video.as_ref()).map_or(30.0, |v| f64::from(v.fps));
plain(vec![Param::new("fps", tl!("Frame Rate"), ParamKind::number(Some(0.01), Some(1000.0), fps, 1.0, 2))])
}
"file.fileInfo" => file_info_form(app),
"file.automate.fitImage" => {
let (w, h, _) = doc?;
// The values Fit Image last ran with, else the document's size (#13853). A stored value that isn't a
@@ -519,51 +517,6 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
}
}
/// File › File Info…: the document's metadata in Photoshop's order and labels, then its read-only Camera Data.
pub(super) fn file_info_form(app: &mut PhotocraftApp) -> Option<(Vec<Param>, DialogFields)> {
let info = app.session.execute("file.fileInfo", json!({})).ok()?;
let text = |key: &str| info[key].as_str().unwrap_or_default().to_owned();
let keywords = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default();
let mut rows = vec![
Param::new("title", tl!("Document Title"), ParamKind::text("")),
Param::new("author", tl!("Author"), ParamKind::text("")),
Param::new("authorTitle", tl!("Author Title"), ParamKind::text("")),
Param::new("description", tl!("Description"), ParamKind::text("")).multiline(3),
Param::new("keywords", tl!("Keywords"), ParamKind::text("")).multiline(3),
choice(
"copyrightStatus",
tl!("Copyright Status"),
opts(&[("unknown", tl!("Unknown")), ("copyrighted", tl!("Copyrighted")), ("publicDomain", tl!("Public Domain"))]),
"unknown",
),
Param::new("copyright", tl!("Copyright Notice"), ParamKind::text("")).multiline(3),
Param::new("copyrightUrl", tl!("Copyright Info URL"), ParamKind::text("")),
];
let camera: Vec<(&'static str, String)> = photocraft_engine::file_cmds::CAMERA_FIELDS
.iter()
.filter_map(|(key, label)| info["camera"].get(*key).and_then(Value::as_str).map(|v| (*label, v.to_owned())))
.collect();
if !camera.is_empty() {
rows.push(Param::section(tl!("Camera Data")));
let lang = crate::i18n::current();
for (label, value) in camera {
rows.push(Param::read_only_text(format!("camera/{label}"), crate::i18n::tr_ctx(lang, "cameraData", label), value));
}
}
let status = info["copyrightStatus"].as_str().unwrap_or("unknown").to_owned();
let fields = DialogFields::from_pairs([
("title", text("title")),
("author", text("author")),
("authorTitle", text("authorTitle")),
("description", text("description")),
("keywords", keywords),
("copyrightStatus", status),
("copyright", text("copyright")),
("copyrightUrl", text("copyrightUrl")),
]);
Some((rows, fields))
}
/// File › Automate › Batch…: the selected action and its set, and where the files come from and go.
fn batch_form(app: &PhotocraftApp, dir: &str) -> Option<(Vec<Param>, DialogFields)> {
let action = crate::actions::selected_action(app)?;
@@ -1129,6 +1082,7 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para
}
let label = photocraft_engine::commands::find(id).map_or(id, |c| c.label);
match id {
"file.fileInfo" => Some(crate::file_info_ui::open(app).map(opened)),
"file.openAs" => Some(app.open_as_dialog_file()),
"file.openAsSmartObject" => Some(app.open_dialog_as_smart_object()),
"file.saveACopy" => Some(save_a_copy(app)),
@@ -29,8 +29,7 @@ fn the_title_is_the_document_name_without_its_extension() {
#[test]
fn the_author_title_and_copyright_status_labels_are_title_case() {
let mut app = app_with_document("oracle.psd");
let (rows, _) = super::dialogs::file_info_form(&mut app).expect("File Info form");
let rows = crate::file_info_ui::basic_rows();
let label = |key: &str| rows.iter().find(|p| p.key == key).map(|p| p.label.as_str()).unwrap_or_default();
assert_eq!(label("authorTitle"), "Author Title");
assert_eq!(label("copyrightStatus"), "Copyright Status");
+4
View File
@@ -101,6 +101,10 @@ pub struct FreeTransform {
/// Edit › Content-Aware Scale (#3096): the box only scales and moves, and OK runs
/// `edit.contentAwareScale` with these options instead of `edit.transform`.
pub content_aware: Option<ContentAwareOptions>,
/// Warp mode was entered with the warp toggle of an untouched Free Transform box, not with
/// Edit › Transform › Warp: on a pixel layer the commit is one "Free Transform" History step,
/// as in the reference (#17579).
pub free_transform_warp: bool,
}
impl FreeTransform {
+28 -13
View File
@@ -4,10 +4,10 @@
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::DialogId;
use craft::ui::display::Text;
use craft::ui::display::{Elide, Text};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::{Label, UnitKind};
use craft::ui::runtime::env::{Env, Label, UnitKind};
use photocraft_doc::Document;
use photocraft_engine::analysis_cmds;
use serde_json::{Value, json};
@@ -134,6 +134,21 @@ pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamRe
}
}
/// The most characters of the scale readout that set its width: about the width of the dialog's fields.
const READOUT_CHARS: usize = 46;
/// The Measurement Scale readout: `<px> pixel(s) = <length, 4 decimals> <units>`, with `decimal` as the decimal mark,
/// as the reference shows it while the values are typed (#17414). The Default preset reads 1 pixel(s) = 1 pixels.
pub(crate) fn scale_readout(f: &DialogFields, decimal: char) -> String {
let (pixels, length, units) = if f.text("preset") == Some("default") {
(1.0, 1.0, "pixels")
} else {
(f.number("pixelLength").unwrap_or(1.0), f.number("logicalLength").unwrap_or(1.0), f.text("units").unwrap_or("pixels"))
};
let mark = |n: String| if decimal == '.' { n } else { n.replace('.', &decimal.to_string()) };
format!("{} pixel(s) = {} {units}", mark(pixels.to_string()), mark(format!("{length:.4}")))
}
fn options(pairs: &[(&str, &str)]) -> Vec<(String, Label)> {
pairs.iter().map(|(key, name)| ((*key).to_owned(), Label::from((*name).to_owned()))).collect()
}
@@ -156,17 +171,13 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> {
custom(Param::new("units", tl!("Logical Units:"), ParamKind::text("pixels"))),
];
ParamDialog::command(key, tl!("Measurement Scale"), rows).below(|ui, f| {
let text = if f.text("preset") == Some("default") {
"1 pixels = 1.0000 pixels".to_owned()
} else {
format!(
"{} pixels = {:.4} {}",
f.number("pixelLength").unwrap_or(1.0),
f.number("logicalLength").unwrap_or(1.0),
f.text("units").unwrap_or("pixels")
)
};
Text::new(Label::from(text)).show(ui);
// One line: units too long for it are cut with "…", so the dialog keeps its width (#17414). The decimal
// mark is the one the fields above write: the system's (any mark, not only `.` or `,`) or the host's.
let text = scale_readout(f, Env::of(ui).format().separators().0);
// The readout asks for the width of its text up to READOUT_CHARS characters, so a short one shows whole
// and long units are cut with "…" instead of widening the dialog.
let sample: String = text.chars().take(READOUT_CHARS).collect();
Text::new(Label::from(text)).elide(Elide::End).sample(Label::from(sample)).show(ui);
})
}
Kind::DataPoints => {
@@ -224,3 +235,7 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> {
#[cfg(test)]
#[path = "data_points_labels_tests.rs"]
mod data_points_labels_tests;
#[cfg(test)]
#[path = "scale_readout_tests.rs"]
mod scale_readout_tests;
@@ -0,0 +1,126 @@
//! #17414: the Measurement Scale dialog's readout reads `<px> pixel(s) = <length, 4 decimals> <units>`, live while
//! the values are typed, on one line: units too long for it are cut with "…" and the dialog keeps its width. The title
//! "Measurement Scale" shows once, in the dialog's frame.
use std::cell::Cell;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog};
use craft::ui::runtime::env::Env;
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::scale_readout;
use crate::PhotocraftApp;
type H = Harness<'static, Box<PhotocraftApp>>;
const COMMAND: &str = "image.analysis.setMeasurementScale";
thread_local! {
/// The decimal mark the dialog's fields write, from the env they are drawn in: the system region's unless the
/// host sets one.
static MARK: Cell<char> = const { Cell::new('.') };
}
/// `text` with `.` replaced by the fields' decimal mark.
fn localized(text: &str) -> String {
text.replace('.', &MARK.get().to_string())
}
fn fields(preset: &str, pixels: f64, length: f64, units: &str) -> DialogFields {
let mut f = DialogFields::new();
f.set("preset", preset);
f.set("pixelLength", pixels);
f.set("logicalLength", length);
f.set("units", units);
f
}
#[test]
fn the_readout_reads_pixel_s_and_four_decimals_in_the_decimal_mark() {
assert_eq!(scale_readout(&fields("default", 1.0, 1.0, "pixels"), '.'), "1 pixel(s) = 1.0000 pixels");
assert_eq!(scale_readout(&fields("custom", 1.0, 1.0, "pixels"), '.'), "1 pixel(s) = 1.0000 pixels");
assert_eq!(scale_readout(&fields("custom", 200.0, 25.0, "Mikrometer"), '.'), "200 pixel(s) = 25.0000 Mikrometer");
assert_eq!(scale_readout(&fields("custom", 200.0, 25.0, "Mikrometer"), ','), "200 pixel(s) = 25,0000 Mikrometer");
assert_eq!(scale_readout(&fields("custom", 2.5, 0.12345, "mm"), ','), "2,5 pixel(s) = 0,1235 mm");
// The Default preset shows the default scale whatever the custom rows hold.
assert_eq!(scale_readout(&fields("default", 200.0, 25.0, "mm"), '.'), "1 pixel(s) = 1.0000 pixels");
}
fn open() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).with_context(app.ctx().clone()).build_ui_state(
|ui, app: &mut Box<PhotocraftApp>| {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
MARK.set(Env::of(ui).format().separators().0);
crate::dialogs::run(app, ui);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap();
h.run_steps(6);
h
}
/// Types `value` into field `key` of the open dialog, as the user would, and lets it draw.
fn set(h: &mut H, key: &str, value: serde_json::Value) {
let ctx = h.ctx.clone();
let id = h.state().framework.dialogs.get::<HostedParamDialog>().map(craft::ui::dialog::StackDialog::id).expect("the dialog is open");
h.state_mut().framework.dialogs.set_json_field(&ctx, id, key, value).unwrap();
h.run_steps(6);
}
/// The readout's text node: the label that starts with a pixel count.
fn readout(h: &H) -> (String, egui::Rect) {
let node = h
.query_all_by_role(Role::Label)
.find(|n| n.accesskit_node().value().or_else(|| n.accesskit_node().label()).is_some_and(|v| v.contains(" pixel(s) = ")))
.expect("the readout is drawn");
let text = node.accesskit_node().value().or_else(|| node.accesskit_node().label()).unwrap_or_default();
(text, node.rect())
}
/// The dialog's window: the widest window-like node around the readout.
fn dialog_width(h: &H) -> f32 {
h.query_all_by_role(Role::Window).chain(h.query_all_by_role(Role::Dialog)).map(|n| n.rect().width()).fold(0.0, f32::max)
}
#[test]
fn the_readout_follows_typing_and_long_units_stay_on_one_line_without_growing_the_dialog() {
let mut h = open();
let (default_text, default_rect) = readout(&h);
assert_eq!(default_text, localized("1 pixel(s) = 1.0000 pixels"));
set(&mut h, "preset", json!("custom"));
set(&mut h, "pixelLength", json!(200.0));
set(&mut h, "logicalLength", json!(25.0));
set(&mut h, "units", json!("Mikrometer"));
let (text, short) = readout(&h);
assert_eq!(text, localized("200 pixel(s) = 25.0000 Mikrometer"), "live while typing");
assert!(short.width() > default_rect.width() + 20.0, "a readout that fits shows whole: {default_rect:?} vs {short:?}");
let width = dialog_width(&h);
assert!(width > 0.0, "the dialog has a frame");
set(&mut h, "units", json!("Mikrometer ".repeat(30).trim_end()));
let (_, long) = readout(&h);
assert!((long.height() - short.height()).abs() < 1.0, "one line: {short:?} vs {long:?}");
assert!((dialog_width(&h) - width).abs() < 1.0, "the dialog keeps its width");
}
#[test]
fn the_title_shows_once() {
let h = open();
// The frame draws its title as a heading; a second copy in the body would be a label.
let shown = h
.query_all_by_role(Role::Heading)
.chain(h.query_all_by_role(Role::Label))
.filter(|n| n.accesskit_node().value().or_else(|| n.accesskit_node().label()).as_deref() == Some("Measurement Scale"))
.count();
assert_eq!(shown, 1, "\"Measurement Scale\" is drawn {shown} times");
}
@@ -172,6 +172,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>
path: None,
made: None,
content_aware: None,
free_transform_warp: false,
});
Ok(())
};
@@ -340,6 +341,7 @@ fn begin_several(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc<Document
path: None,
made: None,
content_aware: None,
free_transform_warp: false,
});
Ok(())
}
@@ -508,6 +510,7 @@ pub(crate) fn begin_content_aware(
path: None,
made: None,
content_aware: Some(Default::default()),
free_transform_warp: false,
});
Ok(())
}
@@ -609,6 +612,7 @@ fn begin_lone(
path: None,
made: None,
content_aware: None,
free_transform_warp: false,
});
Ok(())
}
@@ -640,6 +644,7 @@ fn begin_path(app: &mut PhotocraftApp, params: serde_json::Value, path: photocra
path: Some(params),
made: None,
content_aware: None,
free_transform_warp: false,
});
Ok(())
}
@@ -700,6 +705,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, _ctx: &egui::Context) -> Result<
path: None,
made: None,
content_aware: None,
free_transform_warp: false,
});
Ok(())
}
@@ -733,6 +739,10 @@ pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), St
}
}
enter_warp(app, ctx);
// Edit › Transform › Warp commits as "Warp", also when it switches an open box into Warp mode.
if let Some(t) = app.ui.transform.as_mut() {
t.free_transform_warp = false;
}
Ok(())
}
@@ -780,6 +790,11 @@ pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) {
[x, y]
});
report_warp(app, Warp::custom(mesh, rect), false, false);
// The warp toggle of an untouched Free Transform box: the commit is a Free Transform step
// (#17579). Edit › Transform › Warp clears it again ([`begin_warp`]).
if let Some(t) = app.ui.transform.as_mut() {
t.free_transform_warp = untouched;
}
}
/// Whether the active layer is warped: a Warp box is open on it, or it is a smart object with a
@@ -81,7 +81,13 @@ pub fn commit(app: &mut PhotocraftApp) {
let made = t.made;
let r = if let Some(w) = &warp {
// The warp's bounds are the frame it was built over (a stored smart warp's, or Warp Text's).
app.run("edit.transform.warp", json!({"layer": t.layer, "rect": w.bounds, "warp": w, "interpolation": interpolation}))
let mut p = json!({"layer": t.layer, "rect": w.bounds, "warp": w, "interpolation": interpolation});
// Free Transform's warp toggle on a pixel layer is a Free Transform step (#17579).
let pixels = app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Raster(_)));
if t.free_transform_warp && pixels {
p["stepName"] = json!("Free Transform");
}
app.run("edit.transform.warp", p)
} else {
let mut p = json!({"rect": rect, "quad": quad, "interpolation": interpolation});
if t.layers.is_empty() {
@@ -493,3 +499,7 @@ fn step(app: &mut PhotocraftApp, redo: bool) -> serde_json::Value {
}
json!({"transform": app.ui.transform})
}
#[cfg(test)]
#[path = "warp_history_name_tests.rs"]
mod warp_history_name_tests;
@@ -0,0 +1,125 @@
//! #17579: a warp committed from a Free Transform session's warp toggle on a pixel layer is one
//! History step named "Free Transform"; Edit › Transform › Warp stays "Warp". The cases the issue
//! did not measure (Edit › Transform › Warp on an open box, a box scaled before the toggle) keep
//! today's "Warp".
use craft::behavior::geometry::quad::BoxState;
use craft::behavior::kurbo::{Point, Vec2};
use craft::behavior::{EditEvent, EditEvents, GestureId, Mixed};
use craft::draw::ui::transform::{TransformEdit, TransformRequest};
use craft::imaging::ui::warp::WarpMesh;
use serde_json::json;
use super::super::warp::grid_edit;
use crate::PhotocraftApp;
use crate::transform_tool::{begin, begin_warp, commit, enter_warp};
/// A 64 px document with a pixel layer holding a red square over 8..32.
fn app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
app.sync_views();
app.session.execute("layer.new.layer", json!({})).unwrap();
app.session
.edit("paint", |doc, a| {
doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
app
}
/// Ctrl+T, then the options bar's warp toggle: the session asks for a warp and gets one.
fn free_transform_then_toggle(app: &mut PhotocraftApp) {
let ctx = app.ctx().clone();
begin(app, &ctx).unwrap();
toggle(app);
}
/// The warp toggle of the open box, as the options bar sends it.
fn toggle(app: &mut PhotocraftApp) {
let ctx = app.ctx().clone();
let request = app.ui.transform.as_mut().unwrap().session.apply(TransformEdit::WarpRequested, 0.0);
assert!(matches!(request, Some(TransformRequest::NeedWarp { .. })), "the toggle asks for a warp");
enter_warp(app, &ctx);
assert!(app.ui.transform.as_ref().unwrap().session.warp().is_some(), "Warp mode");
}
/// A mesh drag: the bottom-right anchor (point 15) and its two handles by (+10, +6), then Enter.
/// Returns the History step names it added.
fn drag_and_commit(app: &mut PhotocraftApp) -> Vec<String> {
let before = app.session.active().unwrap().history.entries();
let mesh: WarpMesh = app.ui.transform.as_ref().unwrap().session.warp().unwrap().mesh.clone();
let mut to = mesh.clone();
for k in [15, 14, 11] {
to.points[k] += Vec2::new(10.0, 6.0);
}
let gesture = GestureId::new(1);
let mut events = EditEvents::new();
events.push(EditEvent::begin(gesture, Mixed::Same(mesh.clone()), "Warp".into(), None));
events.push(EditEvent::update(gesture, to.clone()));
events.push(EditEvent::commit(gesture, Mixed::Same(mesh), to));
grid_edit(app, &events, false);
commit(app);
assert!(app.ui.transform.is_none(), "committed: {}", app.ui.status);
let after = app.session.active().unwrap().history.entries();
after[before.len()..].to_vec()
}
fn pixels(app: &PhotocraftApp) -> Vec<f32> {
let st = app.session.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64))
}
#[test]
fn free_transform_warp_toggle_is_one_free_transform_step() {
let mut app = app();
free_transform_then_toggle(&mut app);
assert_eq!(drag_and_commit(&mut app), ["Free Transform"]);
}
#[test]
fn edit_transform_warp_stays_warp() {
let mut app = app();
let ctx = app.ctx().clone();
begin_warp(&mut app, &ctx).unwrap();
assert_eq!(drag_and_commit(&mut app), ["Warp"]);
}
/// Both ways paint the same pixels: only the step's name differs.
#[test]
fn both_warps_paint_the_same_pixels() {
let mut toggled = app();
free_transform_then_toggle(&mut toggled);
drag_and_commit(&mut toggled);
let mut menu = app();
let ctx = menu.ctx().clone();
begin_warp(&mut menu, &ctx).unwrap();
drag_and_commit(&mut menu);
assert_eq!(pixels(&toggled), pixels(&menu));
}
/// Not measured, so today's "Warp": Edit › Transform › Warp while a Free Transform box is open.
#[test]
fn edit_transform_warp_on_an_open_box_stays_warp() {
let mut app = app();
let ctx = app.ctx().clone();
begin(&mut app, &ctx).unwrap();
begin_warp(&mut app, &ctx).unwrap();
assert_eq!(drag_and_commit(&mut app), ["Warp"]);
}
/// Not measured, so today's "Warp": a box scaled before the toggle.
#[test]
fn a_box_scaled_before_the_toggle_stays_warp() {
let mut app = app();
let ctx = app.ctx().clone();
begin(&mut app, &ctx).unwrap();
let t = app.ui.transform.as_mut().unwrap();
t.edit_box(|b| {
let q = b.quad;
*b = BoxState::new([q[0], Point::new(q[1].x + 8.0, q[1].y), Point::new(q[2].x + 8.0, q[2].y), q[3]], b.pivot);
});
toggle(&mut app);
assert_eq!(drag_and_commit(&mut app), ["Warp"]);
}