Merge queue batch: 8 PRs (#15091, #17575, #17524, #17805, #17529, #17675, #16678, #17854)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-29 15:31:29 +01:00
commit 5ade830905
29 files changed
+1386 -43

No files matched your search

@@ -1058,6 +1058,27 @@ fn feature_values(m: &mut Map<String, Value>, f: &Feature, count: usize, factor:
m.insert("histogram".into(), json!(f.histogram));
}
/// The start of Record Measurements' error when no data point is enabled for the source it records; the source's
/// name and a full stop follow (#17407).
pub const NO_DATA_POINTS: &str = "There are no measurement data points currently enabled for the ";
/// The second line of that alert.
pub const NO_DATA_POINTS_DETAIL: &str = "Data points must be set before measurements can be recorded.";
/// The name the alert gives source `source` (`selection`, `ruler` or `count`).
pub fn data_points_source_name(source: &str) -> &'static str {
match source {
"ruler" => "Ruler Tool",
"count" => "Count Tool",
_ => "Selection",
}
}
/// Record Measurements' error for `source` with no data point enabled: the alert's two lines.
fn no_data_points(source: &str) -> String {
format!("{NO_DATA_POINTS}{}.\n{NO_DATA_POINTS_DETAIL}", data_points_source_name(source))
}
fn record(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.analysis.recordMeasurements";
let d = doc(s)?;
@@ -1117,6 +1138,11 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
rows.push(m);
}
}
// No data point enabled for the source: the reference application's alert, and nothing is recorded (no
// empty row, no label number used up, #17407).
if s.analysis.data_points.of(source).is_empty() {
return Err(EngineError::Other(no_data_points(source)));
}
s.analysis.next_measurement += 1;
let keep = s.analysis.data_points.of(source).to_vec();
let mut ids = Vec::new();
@@ -1414,4 +1440,6 @@ mod analysis_straighten_selection_tests;
#[cfg(test)]
mod data_points_empty_set_tests;
#[cfg(test)]
mod record_no_data_points_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,72 @@
//! #17407: Record Measurements with no data point enabled for the source it records refuses with the reference
//! application's alert text, records nothing and does not use up a label number. Ruler and Count get the same check,
//! naming their tool.
use super::*;
const RECORD: &str = "image.analysis.recordMeasurements";
const POINTS: &str = "image.analysis.selectDataPoints";
fn session() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 120, "background": "white"})).unwrap();
s
}
fn log_len(s: &mut Session) -> usize {
s.execute("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len)
}
fn message(e: &EngineError) -> String {
e.to_string()
}
#[test]
fn a_selection_with_only_ruler_points_on_warns_and_records_nothing() {
let mut s = session();
s.execute(POINTS, json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let e = s.execute(RECORD, json!({})).unwrap_err();
assert_eq!(
message(&e),
"There are no measurement data points currently enabled for the Selection.\nData points must be set before measurements can be recorded."
);
assert!(message(&e).starts_with(NO_DATA_POINTS));
assert_eq!(log_len(&mut s), 0, "no empty row");
// The label number was not used up: after setting a point, the first row is "Measurement 1".
s.execute(POINTS, json!({"selection": ["label", "area"]})).unwrap();
let r = s.execute(RECORD, json!({})).unwrap();
assert_eq!(r["rows"][0]["values"]["label"], json!("Measurement 1"), "{r}");
assert_eq!(log_len(&mut s), 1);
}
#[test]
fn ruler_and_count_get_the_same_check_with_their_tool_name() {
let mut s = session();
s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [10, 50], "end": [40, 10]})).unwrap();
let e = s.execute(RECORD, json!({"source": "ruler"})).unwrap_err();
assert_eq!(message(&e), format!("{NO_DATA_POINTS}Ruler Tool.\n{NO_DATA_POINTS_DETAIL}"));
s.execute("count.add", json!({"x": 20, "y": 20})).unwrap();
let e = s.execute(RECORD, json!({"source": "count"})).unwrap_err();
assert_eq!(message(&e), format!("{NO_DATA_POINTS}Count Tool.\n{NO_DATA_POINTS_DETAIL}"));
assert_eq!(log_len(&mut s), 0);
// With a point on, each source records as before.
s.execute(POINTS, json!({"ruler": ["length"], "count": ["count"]})).unwrap();
assert!(s.execute(RECORD, json!({"source": "ruler"})).is_ok());
assert!(s.execute(RECORD, json!({"source": "count"})).is_ok());
assert_eq!(log_len(&mut s), 2);
}
#[test]
fn a_source_that_has_points_records_whatever_the_other_sources_hold() {
let mut s = session();
s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let r = s.execute(RECORD, json!({})).unwrap();
assert_eq!(r["rows"][0]["values"]["area"], json!(5000.0), "{r}");
}
@@ -0,0 +1,106 @@
use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem};
use craft_psd::descriptor::{UnicodeString, Value as D};
use photocraft_doc::{LayerContent, LayerId, Size, SmartObject};
use photocraft_geom::{Point, Rect};
use photocraft_paint::tile::{b64_decode, b64_encode};
use serde_json::json;
use super::{ang, desc, get_num, px};
use crate::Session;
fn document() -> (Session, LayerId, LayerId) {
let mut s = crate::session();
s.execute("prefs.set", json!({"path": "actions.createSingleHistoryState", "value": false})).unwrap();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({"name": "Embedded square"})).unwrap();
s.edit("Paint square", |doc, active| {
let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
surface.fill_rect(Rect::new(150, 100, 250, 200), &[0.2, 0.4, 0.8, 1.0]);
Ok(())
})
.unwrap();
let converted = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [250, 20, 140, 70], "fill": "#ff6600"})).unwrap();
(s, LayerId(converted["layer"].as_u64().unwrap()), LayerId(shape["layer"].as_u64().unwrap()))
}
fn smart_object(s: &Session, id: LayerId) -> &SmartObject {
let LayerContent::Smart(smart) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected a Smart Object") };
smart
}
fn shape_corners(s: &Session, id: LayerId) -> Vec<Point> {
let LayerContent::Shape(shape) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected a shape") };
shape.path.subpaths[0].knots.iter().map(|knot| knot.anchor).collect()
}
fn play_atn(s: &mut Session, data: &str) {
let loaded = s.execute("actions.load", json!({"data": data})).unwrap();
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
let before = s.active().unwrap().history.past_len();
let played = s.execute("actions.play", json!({"action": loaded["actions"][0]})).unwrap();
assert_eq!(played["ran"], 1, "{played}");
assert!(played.get("failed").is_none(), "{played}");
let state = s.active().unwrap();
assert_eq!(state.history.past_len(), before + 1);
assert_eq!(state.history.undo_label(), Some("Crop"));
assert_eq!(state.doc.size, Size::new(300, 200));
}
#[test]
fn imported_crop_turns_shape_and_smart_object_clockwise() {
let frame = desc("Rctn").with("Top ", px(50.0)).with("Left", px(50.0)).with("Btom", px(250.0)).with("Rght", px(350.0));
let crop = desc("null").with("To ", D::Descriptor(frame)).with("Angl", ang(10.0)).with("Dlt ", D::Boolean(false));
let file = AtnFile {
name: UnicodeString::new_nul("Crops"),
actions: vec![AtnAction {
name: UnicodeString::new_nul("Turn and crop"),
items: vec![AtnItem { event: AtnEvent::Code(*b"Crop"), dictionary: b"Crop".to_vec(), descriptor: Some(crop), ..Default::default() }],
..Default::default()
}],
..Default::default()
};
let (mut s, smart, shape) = document();
let origin = smart_object(&s, smart).source.clone();
play_atn(&mut s, &b64_encode(&atn::write(&file).unwrap()));
let placed = smart_object(&s, smart);
assert_eq!(placed.source, origin);
let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| placed.transform.apply(Point::new(x, y)));
for (point, (x, y)) in corners.into_iter().zip([(109.4, 42.1), (207.9, 59.4), (190.6, 157.9), (92.1, 140.6)]) {
assert!((point.x - x).abs() <= 1.0 && (point.y - y).abs() <= 1.0, "{point:?} expected ({x}, {y})");
}
let corners = shape_corners(&s, shape);
let bounds = [
corners.iter().map(|p| p.x).fold(f64::INFINITY, f64::min),
corners.iter().map(|p| p.y).fold(f64::INFINITY, f64::min),
corners.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max),
corners.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max),
];
for (edge, expected) in bounds.into_iter().zip([209.0, -20.0, 360.0, 74.0]) {
assert!((edge - expected).abs() <= 1.0, "{bounds:?}");
}
}
#[test]
fn recorded_crop_exports_a_canvas_angle_and_replays_the_same_geometry() {
for angle in [-10.0, 6.5] {
let (mut recorded, smart, shape) = document();
recorded.execute("actions.record", json!({"name": "Turn and crop"})).unwrap();
recorded.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200, "angle": angle, "deleteCroppedPixels": false})).unwrap();
recorded.execute("actions.stop", json!({})).unwrap();
let saved = recorded.execute("actions.save", json!({"action": "Turn and crop"})).unwrap();
assert_eq!(saved["skipped"], json!([]));
let data = saved["data"].as_str().unwrap();
let file = atn::parse(&b64_decode(data).unwrap()).unwrap();
let [step] = file.actions[0].items.as_slice() else { panic!("expected a single Crop step") };
assert_eq!(step.event.id(), "Crop");
assert_eq!(get_num(step.descriptor.as_ref().unwrap(), "Angl"), Some(-angle));
let (mut replayed, replayed_smart, replayed_shape) = document();
play_atn(&mut replayed, data);
assert_eq!(smart_object(&replayed, replayed_smart).transform, smart_object(&recorded, smart).transform);
assert_eq!(shape_corners(&replayed, replayed_shape), shape_corners(&recorded, shape));
}
}
@@ -7,6 +7,10 @@ use super::fields::{Mapped, none, step, steps};
use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back};
use super::{D, Descriptor, Id, Map, ReferenceItem, STOP_MESSAGE, UnicodeString, Value, json};
#[cfg(test)]
#[path = "crop_angle_sign_tests.rs"]
mod crop_angle_sign_tests;
/// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale.
pub(super) fn place_from(d: &Descriptor) -> Mapped {
let Some(path) = d.get("null").and_then(path_text) else { return Mapped::Unsupported { harmless: false } };
@@ -631,7 +635,8 @@ pub(super) fn crop_from(d: &Descriptor) -> Mapped {
p.insert("height".into(), (bottom - top).round().into());
}
if let Some(a) = get_num(d, "Angl") {
p.insert("angle".into(), a.into());
// ATN records the canvas turn. PhotoCraft's Crop angle describes the frame's turn.
p.insert("angle".into(), (-a).into());
}
if let Some(del) = get_bool(d, "Dlt ") {
p.insert("deleteCroppedPixels".into(), del.into());
@@ -650,7 +655,7 @@ pub(super) fn crop_to(_: &str, p: &Value) -> Option<Descriptor> {
d = d.with("To ", D::Descriptor(desc("Rctn").with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w))));
}
if let Some(a) = jnum(p, "angle") {
d = d.with("Angl", ang(a));
d = d.with("Angl", ang(-a));
}
if let Some(del) = jbool(p, "deleteCroppedPixels") {
d = d.with("Dlt ", D::Boolean(del));
+23 -2
View File
@@ -12,7 +12,10 @@ use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
const CMD: &str = "layer.new.backgroundFromLayer";
pub(crate) const CMD: &str = "layer.new.backgroundFromLayer";
/// Why Background from Layer is greyed with two or more layers selected (#17306).
const SEVERAL_SELECTED: &str = "several layers selected; select one layer to make it the Background";
/// The document's Background layer, if it has one (always the bottom layer).
pub(crate) fn background_id(doc: &Document) -> Option<LayerId> {
@@ -41,7 +44,19 @@ fn convertible(l: &Layer) -> std::result::Result<(), String> {
}
}
/// The menu's precondition: greyed, as in the reference, with two or more layers selected
/// (#17306); otherwise [`can_convert_active`].
fn can_convert(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
if d.selected_layers().len() > 1 {
return Err(SEVERAL_SELECTED.into());
}
can_convert_active(s)
}
/// Can the active layer become the Background? A call that names its `"layer"` (scripts,
/// actions) is checked with this alone: it converts that layer whatever else is selected.
pub(crate) fn can_convert_active(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
if background_id(&d.doc).is_some() {
return Err("the document already has a Background layer".into());
@@ -52,7 +67,13 @@ fn can_convert(s: &Session) -> std::result::Result<(), String> {
fn background_from_layer(s: &mut Session, p: &Value) -> Result<Value> {
let id = match p.get("layer") {
None | Some(Value::Null) => crate::commands::layer_param(s, p)?,
None | Some(Value::Null) => {
// Without a named layer the selection is the target, and it must be one layer.
if s.active().is_some_and(|d| d.selected_layers().len() > 1) {
return Err(EngineError::Disabled(CMD.into(), SEVERAL_SELECTED.into()));
}
crate::commands::layer_param(s, p)?
}
Some(v) => LayerId(v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "`layer` must be a layer id".into() })?),
};
let bg = s.tools.background;
@@ -24,6 +24,16 @@ use crate::{EngineError, Result, Session};
pub use crate::state::{CustomShape, EditState, FadeSource, FadeTarget, FindCursor};
/// Edit › Fade's menu label, as the reference application shows it (#13803): `Fade <history name
/// of the step it fades>…` (`Fade Invert…`, `Fade Gaussian Blur…`) while Fade can run, plain
/// `Fade…` when it can't.
pub fn fade_menu_label(s: &Session) -> String {
match s.edit_state.fade.as_ref().filter(|_| can_fade(s).is_ok()) {
Some(f) => format!("Fade {}…", f.label),
None => "Fade…".into(),
}
}
/// Commands whose result Edit › Fade can blend back against the previous state.
fn fadeable(id: &str) -> bool {
id.starts_with("filter.")
+6 -1
View File
@@ -254,7 +254,10 @@ fn convert(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => v.as_f64().filter(|v| v.is_finite() && (1.0..=300_000.0).contains(v)).ok_or_else(|| bad(format!("{k} must be 1..=300000"))),
}
};
f.transform.m = [n("width", a)?, b, c, n("height", d)?, x, y];
// The frame keeps the layer's centre, as in the reference (#17325): a new width or height moves the
// origin by half the change. `normalized` gives an axis-aligned transform, so `b` and `c` are 0.
let (w, h) = (n("width", a)?, n("height", d)?);
f.transform.m = [w, b, c, h, x + (a - w) / 2.0, y + (d - h) / 2.0];
}
if !f.valid() {
return Err(bad("invalid converted frame"));
@@ -415,6 +418,8 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod content_name_tests;
#[cfg(test)]
mod convert_resize_tests;
#[cfg(test)]
mod from_layers_hidden_tests;
#[cfg(test)]
mod mode_tests;
@@ -0,0 +1,55 @@
//! #17325: Convert to Frame with a new width or height resizes the frame around the layer's centre, as the reference
//! application does; without either the frame keeps the layer's bounds.
use super::*;
/// A 400 × 200 document with a shape layer "Rect" covering 200..280 × 60..120.
fn rect_layer() -> (Session, u64) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 200})).unwrap();
let r = s.execute("shape.create", json!({"kind": "rect", "rect": [200, 60, 80, 60], "fill": "#e07020"})).unwrap();
let id = r["layer"].as_u64().unwrap();
s.execute("layer.setProps", json!({"layer": id, "name": "Rect"})).unwrap();
(s, id)
}
/// The frame's rect as (x0, x1, y0, y1).
fn frame_rect(s: &Session, id: u64) -> (f64, f64, f64, f64) {
let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap();
let [w, _, _, h, x, y] = l.frame.as_ref().expect("a frame").transform.m;
(x, x + w, y, y + h)
}
#[test]
fn the_layer_has_the_measured_bounds() {
let (mut s, id) = rect_layer();
s.execute("layer.frame.convert", json!({"layer": id})).unwrap();
assert_eq!(frame_rect(&s, id), (200.0, 280.0, 60.0, 120.0), "without width or height the frame keeps the layer bounds");
}
#[test]
fn a_new_width_grows_around_the_centre() {
let (mut s, id) = rect_layer();
let r = s.execute("layer.frame.convert", json!({"layer": id, "name": "MyFrame", "width": 160})).unwrap();
assert_eq!(r["name"], "MyFrame");
assert_eq!(frame_rect(&s, id), (160.0, 320.0, 60.0, 120.0));
}
#[test]
fn a_new_height_grows_around_the_centre() {
let (mut s, id) = rect_layer();
s.execute("layer.frame.convert", json!({"layer": id, "height": 100})).unwrap();
assert_eq!(frame_rect(&s, id), (200.0, 280.0, 40.0, 140.0));
}
#[test]
fn both_shrink_around_the_centre_and_the_mask_follows() {
let (mut s, id) = rect_layer();
s.execute("layer.frame.convert", json!({"layer": id, "width": 40, "height": 20})).unwrap();
assert_eq!(frame_rect(&s, id), (220.0, 260.0, 80.0, 100.0));
let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap();
let path = &l.vector_mask.as_ref().unwrap().path;
let coverage = |x: i32, y: i32| photocraft_vector::path_coverage(path, photocraft_geom::Rect::new(x, y, x + 1, y + 1))[0];
assert_eq!(coverage(240, 90), 1.0, "the centre is inside");
assert_eq!(coverage(210, 90), 0.0, "the old left edge is outside");
}
@@ -247,7 +247,8 @@ fn converting_a_shape_uses_its_outline_and_leaves_an_empty_frame() {
let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap();
assert_eq!(l.name, "Portrait");
assert!(l.children().unwrap().is_empty());
assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 10., 15.]);
// The ellipse's 40 × 30 box at (10, 15) resized to 20 × 25 around its centre (30, 30) (#17325).
assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 20., 17.5]);
assert_eq!(TestMask(l.vector_mask.as_ref().unwrap().path.clone()).value(10, 15), 0.0);
assert!(s.undo());
assert!(matches!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().content, LayerContent::Shape(_)));
+183 -10
View File
@@ -627,22 +627,14 @@ fn apply_photometric(rois: &mut [RoiImage], fmt: PixelFormat, geometry: Option<B
for y in 0..roi.h {
for x in 0..roi.w {
let r2 = if vig && let Some((pl, sizes)) = geo {
pl[i].inverse((roi.x0 + x as i32) as f64 + 0.5, (roi.y0 + y as i32) as f64 + 0.5).map_or(0.0, |(sx, sy)| {
let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64);
let (dx, dy) = (sx - w / 2.0, sy - h / 2.0);
(dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)
})
source_r2(&pl[i], sizes[i], (roi.x0 + x as i32) as f64 + 0.5, (roi.y0 + y as i32) as f64 + 0.5)
} else {
0.0
};
let k = y * roi.w + x;
for c in 0..ch {
let f = photo.factor(i, c, r2);
let v = &mut roi.px[k * ch + c];
*v = if fmt.mode == ColorMode::Cmyk { 1.0 - (1.0 - *v) * f } else { *v * f };
if fmt.sample != SampleType::F32 {
*v = v.clamp(0.0, 1.0);
}
*v = scale_sample(*v, photo.factor(i, c, r2), fmt);
}
}
}
@@ -650,6 +642,187 @@ fn apply_photometric(rois: &mut [RoiImage], fmt: PixelFormat, geometry: Option<B
(photo.gains, photo.vignette)
}
/// The squared distance of panorama point (`u`, `v`) from the centre of the `size` source that `pl` placed there, over
/// the squared half diagonal (the vignetting radius of [`panorama::Photometric`]); 0 where no source point maps there.
fn source_r2(pl: &Placement, size: (usize, usize), u: f64, v: f64) -> f64 {
pl.inverse(u, v).map_or(0.0, |(sx, sy)| {
let (w, h) = (size.0 as f64, size.1 as f64);
let (dx, dy) = (sx - w / 2.0, sy - h / 2.0);
(dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)
})
}
/// A colour sample brightened by the factor `f` (CMYK scales the light, not the ink), within range unless float.
fn scale_sample(v: f32, f: f32, fmt: PixelFormat) -> f32 {
let v = if fmt.mode == ColorMode::Cmyk { 1.0 - (1.0 - v) * f } else { v * f };
if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) }
}
/// Vignette estimates read the layers box-averaged to at most this many pixels across: the falloff is smooth, and
/// [`panorama::photometric`] samples about 40 000 points of the overlaps anyway.
const VIGNETTE_SIDE: usize = 1024;
/// The light in `surf`'s colour channels and its coverage, box-averaged over `k × k` pixels on a grid aligned to the
/// origin. The estimate fits light: CMYK reads as the red, green and blue light its inks let through, Lab as one
/// channel, its lightness as encoded luminance ([`lab_light`]).
fn roi_downsampled(surf: &Surface, k: usize) -> Result<RoiImage> {
let fmt = surf.format();
let cmyk = fmt.mode == ColorMode::Cmyk;
let lab = fmt.mode == ColorMode::Lab;
let n = fmt.channels();
let cc = match fmt.mode {
ColorMode::Cmyk => 3,
ColorMode::Lab => 1,
mode => mode.color_channels(),
};
let b = surf.content_bounds();
if b.is_empty() {
return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() });
}
let ki = k as i32;
let (gx0, gy0) = (b.x0.div_euclid(ki), b.y0.div_euclid(ki));
let (w, h) = (((b.x1 - gx0 * ki) as usize).div_ceil(k), ((b.y1 - gy0 * ki) as usize).div_ceil(k));
let overflow = || crate::allocation::error("Auto-Align", "vignette estimate size overflowed");
let cells = w.checked_mul(h).ok_or_else(overflow)?;
let samples = cells.checked_mul(cc).ok_or_else(overflow)?;
let mut px = crate::allocation::capacity(samples, "Auto-Align vignette estimate")?;
px.resize(samples, 0.0f32);
let mut alpha = crate::allocation::capacity(cells, "Auto-Align vignette estimate")?;
alpha.resize(cells, 0.0f32);
let mut row = vec![0.0f32; w * k * n];
for y in gy0 * ki..(gy0 + h as i32) * ki {
surf.read_region_into(Rect::new(gx0 * ki, y, (gx0 + w as i32) * ki, y + 1), &mut row);
let line = ((y - gy0 * ki) as usize / k) * w;
for (x, q) in row.chunks_exact(n).enumerate() {
let cell = line + x / k;
let a = if fmt.alpha { q[n - 1] } else { 1.0 };
alpha[cell] += a;
for c in 0..cc {
let light = if cmyk {
(1.0 - q[c]) * (1.0 - q[3])
} else if lab {
lab_light(q[0])
} else {
q[c]
};
px[cell * cc + c] += light * a;
}
}
}
let area = (k * k) as f32;
for (cell, a) in alpha.iter_mut().enumerate() {
for v in &mut px[cell * cc..(cell + 1) * cc] {
*v = if *a > 0.0 { *v / *a } else { 0.0 };
}
*a /= area;
}
Ok(RoiImage { x0: gx0, y0: gy0, w, h, ch: cc, px, alpha })
}
/// The vignetting falloff shared by `layers`, each warped into canvas coordinates by its placement from a `size` frame
/// (Auto-Align's Vignette Removal, #14197): Photomerge's estimate from the layers' overlaps, read at most
/// [`VIGNETTE_SIDE`] pixels across. Exposure gains are estimated beside it, so a brighter layer isn't taken for
/// vignetting, and then dropped. `[0, 0]` when the overlaps show none: too few, or every scene point at about the same
/// radius in each layer (a bracket whose layers nearly coincide).
pub fn estimate_vignette(layers: &[(&Surface, &Placement)], size: (usize, usize)) -> Result<[f64; 2]> {
let area = layers.iter().fold(Rect::EMPTY, |a, (s, _)| a.union(&s.content_bounds()));
if area.is_empty() {
return Ok([0.0, 0.0]);
}
let k = (area.width().max(area.height()) as usize).div_ceil(VIGNETTE_SIDE).max(1);
let rois = layers.iter().map(|(s, _)| roi_downsampled(s, k)).collect::<Result<Vec<_>>>()?;
// The same source points, landing on the `k`× smaller grid: a cell's centre is the centre of its `k × k` pixels.
let shrink = Homography([1.0 / k as f64, 0.0, 0.0, 0.0, 1.0 / k as f64, 0.0, 0.0, 0.0, 1.0]);
let placements: Vec<Placement> = layers.iter().map(|(_, pl)| Placement { h: shrink.mul(&pl.h), ..(*pl).clone() }).collect();
let sizes = vec![size; layers.len()];
Ok(panorama::photometric(&rois, Some((&placements, &sizes)), true, true).vignette)
}
/// `surf`, warped into canvas coordinates by `pl` from a `size` frame, with the falloff `vignette`
/// ([`estimate_vignette`]) divided out of its colour channels: of the light that CMYK's inks let through
/// ([`brighten_cmyk`]) and of Lab's lightness ([`brighten_lab`]).
pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vignette: [f64; 2]) -> Surface {
let fmt = surf.format();
let (n, cc) = (fmt.channels(), fmt.mode.color_channels());
let photo = panorama::Photometric { gains: vec![vec![1.0; cc]], vignette };
let b = surf.content_bounds();
let mut out = surf.clone();
let mut row = vec![0.0f32; b.width() as usize * n];
for y in b.y0..b.y1 {
let line = Rect::new(b.x0, y, b.x1, y + 1);
surf.read_region_into(line, &mut row);
for (x, q) in (b.x0..).zip(row.chunks_exact_mut(n)) {
let f = photo.factor(0, 0, source_r2(pl, size, x as f64 + 0.5, y as f64 + 0.5));
match fmt.mode {
ColorMode::Cmyk => brighten_cmyk(q, f, fmt),
ColorMode::Lab => brighten_lab(q, f, fmt),
_ => {
for v in &mut q[..cc] {
*v = scale_sample(*v, f, fmt);
}
}
}
}
out.write_region(line, &row);
}
out
}
/// CMYK pixel `q` with the red, green and blue light its inks let through brightened by the factor `f`, within range
/// unless float. Only C, M and Y thin out while they can carry it; K thins out as far as the brightest light needs, so a
/// grey printed in K alone still brightens.
fn brighten_cmyk(q: &mut [f32], f: f32, fmt: PixelFormat) {
let float = fmt.sample == SampleType::F32;
let light: [f32; 3] = std::array::from_fn(|c| {
let l = (1.0 - q[c]) * (1.0 - q[3]) * f;
if float { l } else { l.clamp(0.0, 1.0) }
});
let k = q[3].min(1.0 - light.iter().fold(0.0f32, |a, l| a.max(*l))).max(0.0);
if k >= 1.0 {
return;
}
for c in 0..3 {
let v = 1.0 - light[c] / (1.0 - k);
q[c] = if float { v } else { v.clamp(0.0, 1.0) };
}
q[3] = k;
}
/// CIE L*a*b*'s companding: a tristimulus value relative to white → its `f`, a cube root above a linear toe.
fn lab_f(t: f32) -> f32 {
if t > (6.0f32 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 }
}
/// The inverse of [`lab_f`].
fn lab_f_inv(f: f32) -> f32 {
if f > 6.0 / 29.0 { f * f * f } else { 3.0 * (6.0f32 / 29.0).powi(2) * (f - 4.0 / 29.0) }
}
/// Lab's encoded L (0..1 for L* 0..100) as the sRGB-encoded luminance the vignette is fitted to and divided out of, as
/// RGB's encoded values are.
fn lab_light(l: f32) -> f32 {
photocraft_color::convert::linear_to_srgb(lab_f_inv((l * 100.0 + 16.0) / 116.0).max(0.0))
}
/// Lab pixel `q` with its light ([`lab_light`]) brightened by the factor `f`: X, Y and Z grow by the same ratio, as they
/// do when the light itself is brighter, so a neutral pixel stays neutral and a colour keeps its hue and saturation.
fn brighten_lab(q: &mut [f32], f: f32, fmt: PixelFormat) {
let float = fmt.sample == SampleType::F32;
let fy = (q[0] * 100.0 + 16.0) / 116.0;
let (a, b) = (q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0);
let xyz = [lab_f_inv(fy + a / 500.0), lab_f_inv(fy), lab_f_inv(fy - b / 200.0)];
if xyz[1] <= 0.0 {
return;
}
let light = scale_sample(photocraft_color::convert::linear_to_srgb(xyz[1]), f, fmt);
let grow = photocraft_color::convert::srgb_to_linear(light) / xyz[1];
let [fx, fy, fz] = xyz.map(|t| lab_f(t * grow));
let lab = [(116.0 * fy - 16.0) / 100.0, (500.0 * (fx - fy) + 128.0) / 255.0, (200.0 * (fy - fz) + 128.0) / 255.0];
for (v, n) in q.iter_mut().zip(lab) {
*v = if float { n } else { n.clamp(0.0, 1.0) };
}
}
/// Per-image seam weights (1 inside an image's seam region, else 0) over each ROI.
fn compute_seam_weights(rois: &[RoiImage], canvas: Rect, order: &[usize]) -> Vec<Vec<f32>> {
let n = rois.len();
@@ -654,3 +654,21 @@ fn photomerge_open_documents_ignores_the_folder() {
let _ = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "paths": paths}));
}
}
/// Vignette Removal brightens a Lab colour as brighter light would, in the linear toe of L* too: its linear red, green
/// and blue grow by one ratio, so the colour keeps its hue and saturation (#14197).
#[test]
fn a_brightened_lab_shadow_keeps_its_colour() {
use photocraft_color::convert::{lab_to_srgb, srgb_to_linear};
let linear = |q: &[f32]| lab_to_srgb([q[0] * 100.0, q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0]).map(srgb_to_linear);
let fmt = PixelFormat::new(ColorMode::Lab, SampleType::F32, true);
for lab in [[4.0f32, 3.0, -2.0], [40.0, 20.0, -15.0]] {
let mut q = [lab[0] / 100.0, (lab[1] + 128.0) / 255.0, (lab[2] + 128.0) / 255.0, 1.0];
let before = linear(&q);
brighten_lab(&mut q, 1.3, fmt);
let after = linear(&q);
let grow = after.iter().zip(&before).map(|(a, b)| a / b).collect::<Vec<_>>();
assert!(grow[0] > 1.0, "{lab:?} brightens: {grow:?}");
assert!(grow.iter().all(|g| (g / grow[0] - 1.0).abs() < 0.01), "{lab:?}: every channel grows alike: {before:?} → {after:?}");
}
}
@@ -167,6 +167,11 @@ impl Session {
if let Some(why) = bitmap_mode_refusal(self, spec.id, params) {
return Err(why.into());
}
// A named layer is converted whatever else is selected; the menu (no params) is greyed
// with several layers selected (#17306).
if spec.id == crate::background_cmds::CMD && params.get("layer").is_some_and(|l| !l.is_null()) {
return crate::background_cmds::can_convert_active(self);
}
channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self))
}
+74 -6
View File
@@ -8,7 +8,8 @@
//! ([`photocraft_algo::direct`], `registration`: auto falls back to it, or ask for it). Projections: Auto, Perspective
//! (homography), Cylindrical and Spherical (rigid motion on the cylinder / sphere, focal length
//! from the homographies or EXIF), Collage (similarity) and Reposition (translation). The
//! reference stays put in the planar projections.
//! reference stays put in the planar projections. Vignette Removal estimates one radial falloff
//! from the layers' overlaps, as Photomerge does, and divides it out of every aligned layer.
//!
//! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest
//! layer (Stack Images, for focus stacking) or one layer per region with seams routed where the
@@ -21,7 +22,7 @@
//! from focus ([`photocraft_algo::dff`]): black = the bottom layer, white = the top, so that once
//! on a layer mask it drives Lens Blur's depth map.
use photocraft_algo::panorama::Layout;
use photocraft_algo::panorama::{Layout, Placement};
use photocraft_algo::pyramid;
use photocraft_algo::transform::Interp;
use photocraft_algo::warp::warp_mesh_gray;
@@ -31,7 +32,9 @@ use photocraft_raster::{Surface, to_rgba};
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::photo_cmds::{BlendOptions, NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed};
use crate::photo_cmds::{
BlendOptions, NO_DETAIL, estimate_vignette, plane_matrix, register, register_direct, remove_vignette, seam_blend, seam_order, warp_placed,
};
use crate::{EngineError, Result, Session};
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
@@ -84,6 +87,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto");
let layout = Layout::parse(projection)
.ok_or_else(|| bad(cmd, format!("unknown projection `{projection}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?;
let vignette = match p.get("vignetteRemoval") {
None | Some(Value::Null) => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`vignetteRemoval` must be true or false"))?,
};
// The dialog greys and clears Vignette Removal under Collage and Reposition; a script's request is ignored there too.
let vignette = vignette && !matches!(layout, Layout::Collage | Layout::Reposition);
let st = s.active().ok_or(EngineError::NoDocument)?;
let doc = st.doc.clone();
let reference = match p.get("reference").and_then(Value::as_u64) {
@@ -130,7 +139,7 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(l) = moves.iter().find(|&&i| pinned(&doc, ids[i])).and_then(|&i| doc.layer(ids[i])) {
return Err(EngineError::Other(format!("Auto-Align can't move the locked layer \"{}\"", l.name)));
}
let warped: Vec<(LayerId, Surface, Option<Surface>)> = moves
let mut warped: Vec<(LayerId, Surface, Option<Surface>)> = moves
.iter()
.map(|&i| {
let pl = al.placements[i].as_ref().ok_or_else(|| EngineError::Other("Auto-Align lost a layer's placement".into()))?;
@@ -150,6 +159,47 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
Ok((ids[i], px, mask))
})
.collect::<Result<_>>()?;
// Vignette Removal (#14197): one falloff for all the aligned layers, from their overlaps, divided out of each. The
// reference of a planar layout stays put but is brightened too, unless a lock keeps its pixels.
let size = (area.width() as usize, area.height() as usize);
let still = (!moves.contains(&ref_idx)).then_some(ref_idx).and_then(|i| Some((i, al.placements[i].as_ref()?)));
let mut falloff = None;
let mut reference_px = None;
let mut warnings: Vec<String> = Vec::new();
if vignette {
// The reference keeps its own pixels, but its placement carries the lens distortion `k1` that Geometric
// Distortion may fit: the estimate reads it warped by that placement, as it reads the layers that moved, and its
// correction measures radii in its own pixels, with no distortion.
let still_warped = match still {
Some((i, pl)) if pl.k1 != 0.0 => {
let b = surfs[i].content_bounds();
Some(if b.is_empty() { surfs[i].clone() } else { warp_placed(surfs[i], b, (0.0, 0.0), pl, (0.0, 0.0), interp)? })
}
_ => None,
};
let mut layers: Vec<(&Surface, &Placement)> = warped.iter().zip(&moves).filter_map(|((_, px, _), &i)| Some((px, al.placements[i].as_ref()?))).collect();
layers.extend(still.map(|(i, pl)| (still_warped.as_ref().unwrap_or(surfs[i]), pl)));
let v = estimate_vignette(&layers, size)?;
if negligible(v) {
warnings.push(NO_VIGNETTE.to_owned());
} else {
for ((_, px, _), &i) in warped.iter_mut().zip(&moves) {
if let Some(pl) = al.placements[i].as_ref() {
*px = remove_vignette(px, pl, size, v);
}
}
if let Some((i, pl)) = still {
let locks = doc.effective_locks(ids[i]);
if locks.all || locks.pixels {
warnings
.push(format!("Vignette Removal left the locked reference layer \"{}\" as it was", doc.layer(ids[i]).map_or("", |l| l.name.as_str())));
} else {
reference_px = Some((ids[i], remove_vignette(surfs[i], &Placement { k1: 0.0, ..pl.clone() }, size, v)));
}
}
}
falloff = Some(v);
}
s.edit("Auto-Align Layers", |doc, _| {
for (id, px, mask) in &warped {
// Photoshop turns the Background into a normal layer before moving it.
@@ -162,6 +212,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
m.surface = ms.clone();
}
}
// The reference doesn't move, so a Background stays the Background.
if let Some((id, px)) = &reference_px
&& let Some(surf) = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.surface_mut()
{
*surf = px.clone();
}
Ok(())
})?;
let model = match al.layout {
@@ -179,10 +235,19 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
})
.collect();
Ok(
json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed}),
json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed, "vignette": falloff, "warnings": warnings}),
)
}
/// Auto-Align's warning when Vignette Removal was asked for but the layers' overlaps show no falloff to remove.
const NO_VIGNETTE: &str = "Vignette Removal found no vignetting to remove: the layers' overlaps don't show any (layers that nearly coincide, as in a focus or exposure bracket, can't show it)";
/// Whether the falloff `log V = a·r² + b·r⁴` changes no pixel by as much as 1% out to the corners (r² = 1): what the
/// overlaps of layers that nearly coincide leave, where the estimate stays at its prior.
fn negligible([a, b]: [f64; 2]) -> bool {
(0..=10).map(|i| f64::from(i) / 10.0).all(|r2| (a * r2 + b * r2 * r2).abs() < 0.01)
}
/// The most memory Auto-Blend's working buffers may take past the canvas: a bound independent
/// of the layers' own bounding boxes, which a sparse layer (a dot at each far corner) can make
/// arbitrarily large, and of how many layers are blended.
@@ -456,7 +521,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"edit.autoAlignLayers",
"Auto-Align Layers…",
r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##,
r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"vignetteRemoval":bool=false (ignored with collage and reposition),"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##,
two_layers,
auto_align
),
@@ -478,3 +543,6 @@ mod auto_blend_background_tests;
#[cfg(test)]
mod auto_blend_stack_bottom_mask_tests;
#[cfg(test)]
mod auto_align_vignette_tests;
@@ -0,0 +1,261 @@
//! Auto-Align's Vignette Removal (#14197): one falloff estimated from the layers' overlaps, as Photomerge does, and
//! divided out of every aligned layer; off, and under Collage or Reposition, the layers come out as before.
use photocraft_color::convert::{lab_to_srgb, srgb_to_lab};
use photocraft_color::{ColorMode, PixelFormat};
use super::*;
const W: i32 = 400;
const H: i32 = 300;
/// A scene larger than the canvas: soft mid-tone patches on a gentle gradient, every value well inside 0..1.
fn scene() -> Vec<[f32; 3]> {
let (sw, sh) = (W + 120, H + 100);
let mut px: Vec<[f32; 3]> =
(0..sw * sh).map(|i| 0.45 + 0.1 * (i % sw) as f32 / sw as f32 + 0.05 * (i / sw) as f32 / sh as f32).map(|v| [v, v, v]).collect();
let mut seed = 7u64;
let mut rnd = || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as f32 / (1u64 << 31) as f32
};
for _ in 0..400 {
let (x, y) = ((rnd() * (sw - 20) as f32) as i32, (rnd() * (sh - 16) as f32) as i32);
let (rw, rh) = (4 + (rnd() * 16.0) as i32, 4 + (rnd() * 12.0) as i32);
let c = [0.3 + 0.5 * rnd(), 0.3 + 0.5 * rnd(), 0.3 + 0.5 * rnd()];
for yy in y..y + rh {
for xx in x..x + rw {
px[(yy * sw + xx) as usize] = c;
}
}
}
px
}
/// The CMYK test layers' black ink, everywhere.
const BLACK_INK: f32 = 0.1;
/// A canvas-sized layer: the scene seen from (`ox`, `oy`), darkened towards the corners by `exp(falloff · r²)`
/// (r = 1 at a corner), as a lens does. `look` is the document's mode, or `cmyk-k` for the scene in grey in K alone; in
/// `cmyk` the scene's light is printed in C, M and Y over [`BLACK_INK`].
fn photo_layer(s: &mut Session, look: &str, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId {
let px = scene();
s.execute("layer.new.layer", json!({"name": name})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
s.edit("photo", |doc, _| {
let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap();
let fmt = surf.format();
let n = fmt.channels();
let mut row = vec![0.0f32; W as usize * n];
for y in 0..H {
for x in 0..W {
let (dx, dy) = (x as f32 + 0.5 - W as f32 / 2.0, y as f32 + 0.5 - H as f32 / 2.0);
let v = (falloff * (dx * dx + dy * dy) / ((W * W + H * H) as f32 / 4.0)).exp();
let c = px[((y + oy) * (W + 120) + x + ox) as usize];
let q = &mut row[x as usize * n..(x as usize + 1) * n];
let c = c.map(|c| c * v);
match look {
"cmyk" => q.copy_from_slice(&[1.0 - c[0], 1.0 - c[1], 1.0 - c[2], BLACK_INK, 1.0]),
"cmyk-k" => q.copy_from_slice(&[0.0, 0.0, 0.0, 1.0 - (c[0] + c[1] + c[2]) / 3.0, 1.0]),
"lab" => {
let [l, a, b] = srgb_to_lab(c);
q.copy_from_slice(&[l / 100.0, (a + 128.0) / 255.0, (b + 128.0) / 255.0, 1.0]);
}
_ => q.copy_from_slice(&[c[0], c[1], c[2], 1.0]),
}
}
surf.write_region(Rect::new(0, y, W, y + 1), &row);
}
Ok(())
})
.unwrap();
id
}
/// Two vignetted photos of one scene, `shift` apart, both selected.
fn pair(falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) {
pair_in("rgb", falloff, shift)
}
/// [`pair`] drawn as [`photo_layer`]'s `look`.
fn pair_in(look: &str, falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) {
let mut s = crate::session();
let mode = look.split('-').next().unwrap_or(look);
s.execute("file.new", json!({"width": W, "height": H, "mode": mode, "background": "transparent"})).unwrap();
let a = photo_layer(&mut s, look, "A", 0, 0, falloff);
let b = photo_layer(&mut s, look, "B", shift.0, shift.1, falloff);
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
(s, [a, b])
}
fn pixels(s: &Session, id: LayerId) -> Vec<f32> {
s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(Rect::new(-200, -200, W + 200, H + 200))
}
/// The red, green and blue light of pixel `q` summed: what CMYK's inks let through, and Lab's colour in sRGB.
fn light(mode: ColorMode, q: &[f32]) -> f32 {
match mode {
ColorMode::Cmyk => q[..3].iter().map(|c| (1.0 - c) * (1.0 - q[3])).sum(),
ColorMode::Lab => lab_to_srgb([q[0] * 100.0, q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0]).iter().sum(),
_ => q[..3].iter().sum(),
}
}
fn format(s: &Session) -> PixelFormat {
s.active().unwrap().doc.pixel_format()
}
/// How far apart the two aligned layers are where both are opaque: the mean |log| of their luminance ratio. The scene is
/// the same in both, so what's left is each one's vignetting at a different place in the frame.
fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 {
let (pa, pb) = (pixels(s, a), pixels(s, b));
let (mode, ch) = (format(s).mode, format(s).channels());
let (mut sum, mut n) = (0.0, 0usize);
for (qa, qb) in pa.chunks_exact(ch).zip(pb.chunks_exact(ch)) {
if qa[ch - 1] > 0.999 && qb[ch - 1] > 0.999 {
let (la, lb) = (light(mode, qa), light(mode, qb));
sum += f64::from((la / lb).ln().abs());
n += 1;
}
}
assert!(n > 10_000, "the layers overlap");
sum / n as f64
}
/// The mean luminance of layer `id` in the four corner squares of its own frame, a few pixels in from its warped edge.
fn corners(s: &Session, id: LayerId) -> f32 {
let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap();
let b = surf.content_bounds();
let (mode, ch) = (format(s).mode, format(s).channels());
let mut sum = 0.0;
for (x, y) in [(b.x0 + 4, b.y0 + 4), (b.x1 - 34, b.y0 + 4), (b.x0 + 4, b.y1 - 34), (b.x1 - 34, b.y1 - 34)] {
sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).chunks_exact(ch).map(|q| light(mode, q)).sum::<f32>();
}
sum / (4.0 * 900.0 * 3.0)
}
fn align(s: &mut Session, params: Value) -> Value {
let r = s.execute("edit.autoAlignLayers", params).unwrap();
assert_eq!(r["failed"], json!([]), "{r}");
r
}
#[test]
fn shifted_vignetted_layers_come_out_flatter_with_their_corners_brightened() {
shifted_layers_come_out_flatter("rgb");
}
/// CMYK samples are ink, which grows towards darkened corners: the falloff is fitted to their light, and the light of
/// C, M and Y is brightened once, not again through K's.
#[test]
fn shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened() {
shifted_layers_come_out_flatter("cmyk");
}
/// A grey printed in K alone can only brighten if K thins out.
#[test]
fn shifted_vignetted_cmyk_layers_in_black_ink_alone_come_out_flatter_with_their_corners_brightened() {
shifted_layers_come_out_flatter("cmyk-k");
}
/// Lab's lightness is brightened, and its a and b only as far as a brighter light would take them: no colour cast.
#[test]
fn shifted_vignetted_lab_layers_come_out_flatter_without_a_colour_cast() {
let ab = |s: &Session, id: LayerId| {
let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap();
let b = surf.content_bounds();
let px = surf.read_region(Rect::new(b.x0 + 4, b.y0 + 4, b.x0 + 34, b.y0 + 34));
let mean = |c: usize| px.as_chunks::<4>().0.iter().map(|q| q[c] * 255.0 - 128.0).sum::<f32>() / 900.0;
[mean(1), mean(2)]
};
let (mut s, ids) = pair_in("lab", -0.5, (60, 40));
align(&mut s, json!({"projection": "auto"}));
let before = ids.map(|id| ab(&s, id));
let (s, ids) = shifted_layers_come_out_flatter("lab");
for (i, id) in ids.into_iter().enumerate() {
let after = ab(&s, id);
assert!((0..2).all(|c| (after[c] - before[i][c]).abs() < 5.0), "layer {i}'s corner a and b stay put: {after:?} vs {:?}", before[i]);
}
}
/// Aligns a shifted vignetted pair drawn as `look` without and with Vignette Removal, checks the second is flatter with
/// brighter corners, and returns it.
fn shifted_layers_come_out_flatter(look: &str) -> (Session, [LayerId; 2]) {
let (mut s, ids) = pair_in(look, -0.5, (60, 40));
let r = align(&mut s, json!({"projection": "auto"}));
assert_eq!(r["vignette"], Value::Null, "off by default: {r}");
let (before, plain) = (mismatch(&s, ids), ids.map(|id| pixels(&s, id)));
let dark = ids.map(|id| corners(&s, id));
s.undo();
let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": false}));
assert!(ids.map(|id| pixels(&s, id)) == plain, "false is today's result: {r}");
s.undo();
let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": true}));
let v = r["vignette"].as_array().unwrap_or_else(|| panic!("{r}"));
assert!(v[0].as_f64().unwrap() + v[1].as_f64().unwrap() < -0.1, "a darkening falloff is found: {r}");
assert_eq!(r["warnings"], json!([]), "{r}");
let after = mismatch(&s, ids);
assert!(after < before * 0.6, "the overlap agrees better: {after} vs {before}");
for (i, id) in ids.into_iter().enumerate() {
assert!(corners(&s, id) > dark[i] * 1.1, "layer {i}'s corners are brighter, the reference's too: {r}");
}
(s, ids)
}
#[test]
fn collage_and_reposition_ignore_vignette_removal() {
for projection in ["collage", "reposition"] {
let (mut s, ids) = pair(-0.5, (60, 40));
align(&mut s, json!({"projection": projection}));
let plain = ids.map(|id| pixels(&s, id));
s.undo();
let r = align(&mut s, json!({"projection": projection, "vignetteRemoval": true}));
assert!(ids.map(|id| pixels(&s, id)) == plain, "{projection}: {r}");
assert_eq!(r["vignette"], Value::Null, "{projection}: {r}");
}
}
/// Layers that coincide see every scene point at the same radius, so the overlaps can't show a falloff: the layers are
/// left as they are and the result says so, rather than claiming a correction.
#[test]
fn coinciding_layers_report_that_no_vignetting_was_found() {
let (mut s, ids) = pair(-0.5, (0, 0));
align(&mut s, json!({"projection": "auto", "registration": "intensity"}));
let plain = ids.map(|id| pixels(&s, id));
s.undo();
let r = align(&mut s, json!({"projection": "auto", "registration": "intensity", "vignetteRemoval": true}));
assert_eq!(r["warnings"], json!([NO_VIGNETTE]), "{r}");
assert!(ids.map(|id| pixels(&s, id)) == plain, "{r}");
}
#[test]
fn a_wrong_typed_vignette_removal_is_an_error() {
let (mut s, ids) = pair(-0.5, (60, 40));
for bad in [json!("yes"), json!(1), json!(1e308), json!([true]), json!({"on": true})] {
let e = s.execute("edit.autoAlignLayers", json!({"vignetteRemoval": bad})).unwrap_err();
assert!(e.to_string().contains("vignetteRemoval"), "{bad}: {e}");
}
assert_eq!(s.active().unwrap().doc.layer(ids[1]).unwrap().surface().unwrap().content_bounds(), Rect::new(0, 0, W, H), "nothing moved");
}
/// A reference whose pixels are locked stays as it was, and the result says so; the layers aligned onto it are still
/// brightened.
#[test]
fn a_pixel_locked_reference_keeps_its_pixels() {
let (mut s, [a, b]) = pair(-0.5, (60, 40));
s.edit("lock", |doc, _| {
doc.layer_mut(a).unwrap().locks.set("pixels", true);
Ok(())
})
.unwrap();
align(&mut s, json!({"projection": "auto"}));
let dark = corners(&s, b);
s.undo();
let kept = pixels(&s, a);
let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": true}));
assert_eq!(r["reference"], a.0, "{r}");
assert!(pixels(&s, a) == kept, "{r}");
assert!(r["warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|m| m.contains("\"A\""))), "{r}");
assert!(corners(&s, b) > dark * 1.1, "{r}");
}
@@ -0,0 +1,133 @@
//! Layer › New › Background from Layer with several layers selected (#17306).
//!
//! Measured in the reference: with two layers selected the menu item is greyed. With one layer it
//! is live for pixel, type, smart object, fill and shape layers and greyed for groups and
//! adjustment layers. A script or action that names the layer (`"layer": id`) converts that
//! layer, whatever is selected.
use photocraft_doc::LayerId;
use photocraft_engine::Session;
use serde_json::{Value, json};
const CMD: &str = "layer.new.backgroundFromLayer";
/// A document without a Background: a transparent "Layer 1" plus A and B on top.
fn no_background() -> (Session, [LayerId; 3]) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 12, "background": "transparent"})).unwrap();
let base = s.active().unwrap().active_layer.unwrap();
let a = new_layer(&mut s, "A");
let b = new_layer(&mut s, "B");
(s, [base, a, b])
}
fn new_layer(s: &mut Session, name: &str) -> LayerId {
LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap())
}
fn ids(r: &Value) -> LayerId {
LayerId(r["layer"].as_u64().unwrap())
}
fn order(s: &Session) -> Vec<LayerId> {
s.active().unwrap().doc.layers.iter().map(|l| l.id).collect()
}
fn background(s: &Session) -> Option<LayerId> {
s.active().unwrap().doc.background().map(|l| l.id)
}
#[test]
fn two_selected_layers_grey_the_command_and_a_call_without_layer_is_refused() {
let (mut s, [_, a, b]) = no_background();
s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap();
assert_eq!(s.active().unwrap().selected_layers().len(), 2);
assert!(!s.is_enabled(CMD), "greyed with two layers selected");
let why = s.disabled_reason(CMD).unwrap();
assert!(why.contains("layers selected"), "the reason names the multi-selection: {why}");
let before = order(&s);
let revision = s.active().unwrap().revision;
let err = s.execute(CMD, json!({})).unwrap_err().to_string();
assert!(err.contains("layers selected"), "the error names the reason: {err}");
assert_eq!(order(&s), before, "no layer moved");
assert_eq!(background(&s), None, "no Background made");
assert_eq!(s.active().unwrap().revision, revision, "the document did not change");
// Three layers selected: greyed too.
let (mut s, [base, a, b]) = no_background();
s.execute("layer.select", json!({"layers": [base.0, a.0, b.0]})).unwrap();
assert!(!s.is_enabled(CMD));
assert!(s.execute(CMD, json!({"layer": null})).is_err(), "a null layer is the selection too");
}
#[test]
fn an_explicit_layer_converts_that_layer_with_several_selected() {
// The named layer is one of the selected ones.
let (mut s, [_, a, b]) = no_background();
s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap();
let r = s.execute(CMD, json!({"layer": a.0})).unwrap();
assert_eq!(ids(&r), a);
assert_eq!(background(&s), Some(a), "A is the Background");
assert_eq!(order(&s)[0], a, "at the bottom");
// The named layer is outside the selection.
let (mut s, [base, a, b]) = no_background();
s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap();
s.execute(CMD, json!({"layer": base.0})).unwrap();
assert_eq!(background(&s), Some(base));
}
#[test]
fn one_selected_layer_keeps_todays_rules() {
let live = |make: &dyn Fn(&mut Session)| {
let (mut s, _) = no_background();
make(&mut s);
assert_eq!(s.active().unwrap().selected_layers().len(), 1);
s.is_enabled(CMD)
};
assert!(live(&|_| {}), "pixel layer");
assert!(
live(&|s| {
s.execute("type.create", json!({"x": 2, "y": 10, "text": "I", "size": 8})).unwrap();
}),
"type layer"
);
assert!(
live(&|s| {
s.execute("edit.fill", json!({"contents": "black"})).unwrap();
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
}),
"smart object"
);
assert!(
live(&|s| {
s.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap();
}),
"solid colour fill layer"
);
assert!(
live(&|s| {
s.execute("shape.create", json!({"kind": "rect", "rect": [2, 2, 6, 6]})).unwrap();
}),
"shape layer"
);
assert!(
!live(&|s| {
s.execute("layer.new.group", json!({})).unwrap();
}),
"group"
);
assert!(
!live(&|s| {
s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
}),
"adjustment layer"
);
// And one selected pixel layer converts as before.
let (mut s, [_, a, _]) = no_background();
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute(CMD, json!({})).unwrap();
assert_eq!(background(&s), Some(a));
}
+1
View File
@@ -38,6 +38,7 @@ mod auto_blend_layer_kinds;
mod average_smart;
mod background_and_mask_depth;
mod background_from_layer_history_name;
mod background_from_layer_multi_select;
mod background_job_target;
mod background_layer_consistency;
mod brush_smoothing;
+25 -18
View File
@@ -1984,25 +1984,32 @@ pub fn entries(app: &PhotocraftApp, menu: &CanvasToolMenu) -> Vec<Entry<String>>
out.push(Entry::separator());
continue;
};
let text = match row_label(app, menu, label, command) {
// Spelled out so `cargo xtask i18n-coverage` lists the new label.
"Free Transform Points" => tl!("Free Transform Points"),
"Fill Subpath…" => tl!("Fill Subpath…"),
"Fill Subpaths…" => tl!("Fill Subpaths…"),
"Stroke Subpath…" => tl!("Stroke Subpath…"),
"Stroke Subpaths…" => tl!("Stroke Subpaths…"),
"Rasterize Vector Mask" => tl!("Rasterize Vector Mask"),
// `layer_menu_ui::layer_count_label`'s labels, likewise (#12358).
"Duplicate Layer…" => tl!("Duplicate Layer…"),
"Delete Layer" => tl!("Delete Layer"),
"Duplicate Layers…" => tl!("Duplicate Layers…"),
"Delete Layers" => tl!("Delete Layers"),
"Rasterize Layers" => tl!("Rasterize Layers"),
"Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"),
"Show Contextual Task Bar" => tl!("Show Contextual Task Bar"),
key => tl!(key),
let shown = row_label(app, menu, label, command);
// The same label as Edit › Fade (#13803).
let text = if shown == "Fade…" {
crate::menus::fade_label(app)
} else {
match shown {
// Spelled out so `cargo xtask i18n-coverage` lists the new label.
"Free Transform Points" => tl!("Free Transform Points"),
"Fill Subpath…" => tl!("Fill Subpath…"),
"Fill Subpaths…" => tl!("Fill Subpaths…"),
"Stroke Subpath…" => tl!("Stroke Subpath…"),
"Stroke Subpaths…" => tl!("Stroke Subpaths…"),
"Rasterize Vector Mask" => tl!("Rasterize Vector Mask"),
// `layer_menu_ui::layer_count_label`'s labels, likewise (#12358).
"Duplicate Layer…" => tl!("Duplicate Layer…"),
"Delete Layer" => tl!("Delete Layer"),
"Duplicate Layers…" => tl!("Duplicate Layers…"),
"Delete Layers" => tl!("Delete Layers"),
"Rasterize Layers" => tl!("Rasterize Layers"),
"Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"),
"Show Contextual Task Bar" => tl!("Show Contextual Task Bar"),
key => tl!(key),
}
.to_string()
};
out.push(Entry::new(command.to_string(), text.to_string()).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command)));
out.push(Entry::new(command.to_string(), text).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command)));
}
out
}
@@ -325,6 +325,21 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View,
let mut overlay_context = None;
let shown = canvas.show_at(ui, rect, |ui, body| {
let Some(space) = canvas_space(&body.env) else { return };
if !measuring && app.session.active_index() == Some(idx) {
let hovered = ui
.input(|i| i.pointer.hover_pos())
.filter(|pos| space.view.rect.contains(*pos) && ui.ctx().layer_id_at(*pos).is_none_or(|layer| layer == ui.layer_id()))
.map(|pos| {
let at = space.view.to_doc(pos);
[at.x, at.y]
});
let next = if primary { hovered } else { hovered.or(app.hover_doc) };
if app.hover_doc != next {
app.hover_doc = next;
// The Info panel may have already drawn earlier in this frame.
ctx.request_repaint();
}
}
pasteboards(app, ui, body.rect, idx, border, label.clone());
guides = super::rulers::show(app, ui, host, ruler_guide(&body.env));
selection_controls(app, ui, body.rect, idx, &label);
+1
View File
@@ -446,6 +446,7 @@ pub(crate) type PromptRow = fn(&mut PhotocraftApp, &egui::Context, &mut PromptAn
pub(crate) const PROMPTS: &[PromptRow] = &[
crate::tools::tool_reset::answer,
crate::analysis::note_alerts::answer,
crate::analysis::no_data_points_answer,
delete_layer_prompt::answer,
mask_trash_prompt::answer,
disk_change_prompt::answer,
+2
View File
@@ -80,6 +80,8 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Edit"], "Undo", None, "edit.undo"),
(&["Edit"], "Redo", None, "edit.redo"),
(&["Edit"], "Toggle Last State", Some("Cmd+Alt+Z"), "edit.toggleLastState"),
// Fade sits in its own group, between separators (#13803).
(&["Edit"], "---", None, "---"),
(&["Edit"], "Fade…", Some("Cmd+Shift+F"), "edit.fade"),
(&["Edit"], "---", None, "---"),
(&["Edit"], "Cut", None, "edit.cut"),
+3 -1
View File
@@ -13,6 +13,8 @@ use crate::PhotocraftApp;
mod bar;
pub mod enable_rules;
pub(crate) mod facts;
#[cfg(test)]
mod fade_label_tests;
mod invoke;
mod items;
pub mod native_menu;
@@ -29,10 +31,10 @@ pub(crate) use invoke::{invoke_unguarded, panel_alias};
pub use items::{MenuModel, base_rows, is_live, menu_rows, model, row};
#[cfg(test)]
pub(crate) use items::{fresh_bar, model_id};
pub use state::is_enabled;
pub(crate) use state::reveal_label;
#[cfg(test)]
use state::translated_menu_label;
pub use state::{fade_label, is_enabled};
/// What may run from the menus now: the gate (a dialog, the shortcut recorder) and the per-command
/// rules (a full-window workspace, a pending crop). Both bars, the runtime's command gate and
@@ -0,0 +1,61 @@
//! #13803: Edit › Fade names the step it fades (`Fade Invert…`), reads plain `Fade…` and is
//! greyed when nothing can be faded, sits in its own group between separators, and the selection
//! right-click menu and `ui.menu.list` show the same label.
use super::*;
use serde_json::json;
fn app() -> Box<crate::PhotocraftApp> {
let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
app
}
/// Edit › Fade's (label, enabled) as the menus and `ui.menu.list` report it.
fn fade(app: &crate::PhotocraftApp) -> (String, bool) {
let row = menu_rows(app).into_iter().find(|r| r.command.id == "edit.fade").expect("Edit › Fade");
(row.label, row.enabled)
}
#[test]
fn the_label_names_the_step_it_fades() {
let mut app = app();
app.run("image.adjustments.invert", json!({})).unwrap();
assert_eq!(fade(&app), ("Fade Invert…".into(), true));
app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
assert_eq!(fade(&app).0, "Fade Gaussian Blur…");
app.run("paint.stroke", json!({"points": [[8, 20], [56, 20]], "size": 6})).unwrap();
assert_eq!(fade(&app).0, "Fade Brush Tool…");
assert_eq!(fade_label(&app), "Fade Brush Tool…", "the right-click menu's row shows the same");
}
#[test]
fn nothing_to_fade_reads_plain_fade_and_is_greyed() {
let mut app = app();
assert_eq!(fade(&app), ("Fade…".into(), false), "a fresh document");
app.run("image.adjustments.invert", json!({})).unwrap();
app.run("select.all", json!({})).unwrap();
app.run("select.deselect", json!({})).unwrap();
assert_eq!(fade(&app), ("Fade…".into(), false), "after Deselect");
assert_eq!(fade_label(&app), "Fade…");
let empty = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
assert_eq!(fade(&empty), ("Fade…".into(), false), "no document");
}
#[test]
fn fade_sits_in_its_own_group() {
let rows = menu_rows(&app());
let edit: Vec<&str> = rows.iter().filter(|r| r.path == ["Edit"]).map(|r| r.label.as_str()).take(7).collect();
assert_eq!(edit, ["Undo", "Redo", "Toggle Last State", "---", "Fade…", "---", "Cut"], "{edit:?}");
}
/// CodeRabbit on #15091: the label comes from the engine, so hiding Fade in Edit › Menus (which drops its row
/// from the menu list) does not turn the right-click menu's Fade back into plain `Fade…`.
#[test]
fn a_hidden_menu_row_does_not_change_the_right_click_label() {
let mut app = app();
app.run("image.adjustments.invert", json!({})).unwrap();
app.session.prefs.edit(|p| p.menus.hidden.push("edit.fade".into()));
assert!(menu_rows(&app).iter().all(|r| r.command.id != "edit.fade"), "the row is hidden from the menu list");
assert_eq!(fade_label(&app), "Fade Invert…");
}
+4
View File
@@ -236,6 +236,10 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec<Row> {
{
item.label = "Merge Group".into();
}
// Edit › Fade names the step it fades (#13803).
if let Some(item) = find(&mut rows, "edit.fade") {
item.label = photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session);
}
// The File quick-export command uses the format selected in Export Preferences.
// On the web it intentionally downloads PNG until the quick-export service supports
// the other formats; the Layer quick-export command also always produces PNG.
+19
View File
@@ -244,5 +244,24 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, id: &str, label: &s
{
return crate::i18n::fmt(crate::i18n::tr(lang, "New Window for {name}"), &[("name", name)]);
}
if id == "edit.fade" {
return translated_fade_label(lang, label);
}
crate::i18n::tr_id(lang, id, label).to_string()
}
/// Edit › Fade's `label` translated: `Fade Invert…` is the translated "Fade…" around the step's own
/// history name (#13803), plain `Fade…` just the translation.
pub(super) fn translated_fade_label(lang: crate::i18n::Lang, label: &str) -> String {
match label.strip_prefix("Fade ").and_then(|l| l.strip_suffix('…')) {
Some(step) => crate::i18n::tr_id(lang, "edit.fade", "Fade…").replace('…', &format!(" {step}…")),
None => crate::i18n::tr_id(lang, "edit.fade", label).to_string(),
}
}
/// Edit › Fade's label as the menus show it, translated (#13803): `Fade Invert…` while Fade can
/// run, `Fade…` when it can't. The selection right-click menu shows the same. Read from the engine,
/// not from the menu rows, so hiding Fade in Edit › Menus does not change the right-click menu.
pub fn fade_label(app: &crate::PhotocraftApp) -> String {
translated_fade_label(crate::i18n::current(), &photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session))
}
@@ -0,0 +1,84 @@
use std::sync::Arc;
use craft::settings::testing::MemoryFiles;
use craft::settings::{Location, OpenOptions, SettingsStore};
use photocraft_engine::Session;
use photocraft_engine::prefs::SavedPrefs;
use serde_json::{Value, json};
use crate::{PhotocraftApp, Services, menus};
fn invoke(app: &mut PhotocraftApp, id: &str, params: Value) {
let ctx = app.ctx().clone();
menus::invoke(app, &ctx, id, params).unwrap();
}
fn customizations(app: &mut PhotocraftApp) -> [Value; 3] {
["toolbar", "shortcuts", "menus"].map(|path| app.run("prefs.get", json!({"path": path})).unwrap())
}
fn set_customizations(app: &mut PhotocraftApp, extra_tool: &str, brush_key: &str, fill_color: &str) {
app.run("edit.toolbar", json!({"reset": true, "extras": [[extra_tool]]})).unwrap();
app.run("prefs.set", json!({"values": {"shortcuts.tools.select.brush": brush_key, "menus.colors.edit.fill": fill_color}})).unwrap();
}
#[test]
fn reset_restores_and_saves_all_captured_customizations() {
let files = Arc::new(MemoryFiles::new());
let open_app = || {
let options = OpenOptions::new(Location::Dir("/memory/photocraft".into())).files(files.clone());
let services = Services { settings: Some(SettingsStore::<SavedPrefs>::open_with(options)), ..Default::default() };
PhotocraftApp::new(Session::new(), services)
};
let mut app = open_app();
set_customizations(&mut app, "Frame", "F8", "red");
let captured = customizations(&mut app);
invoke(&mut app, "workspace.new", json!({"name": "Retouch", "toolbar": true, "keyboardShortcuts": true, "menus": true}));
set_customizations(&mut app, "Crop", "F9", "blue");
let changed = customizations(&mut app);
for (before, after) in captured.iter().zip(&changed) {
assert_ne!(before, after);
}
invoke(&mut app, "workspace.reset", json!({}));
assert_eq!(customizations(&mut app), captured);
crate::prefs_ui::save_preferences(&mut app).unwrap();
drop(app);
let mut restarted = open_app();
assert_eq!(customizations(&mut restarted), captured);
}
#[test]
fn reset_applies_each_capture_independently() {
for toolbar in [true, false] {
let mut app = PhotocraftApp::new(Session::new(), Services::default());
set_customizations(&mut app, "Frame", "F8", "red");
let captured = customizations(&mut app);
invoke(&mut app, "workspace.new", json!({"name": "Retouch", "toolbar": toolbar, "keyboardShortcuts": !toolbar, "menus": !toolbar}));
set_customizations(&mut app, "Crop", "F9", "blue");
let changed = customizations(&mut app);
invoke(&mut app, "workspace.reset", json!({}));
let restored = customizations(&mut app);
for (index, captured_by_workspace) in [toolbar, !toolbar, !toolbar].into_iter().enumerate() {
let expected = if captured_by_workspace { &captured[index] } else { &changed[index] };
assert_eq!(&restored[index], expected);
}
}
}
#[test]
fn reset_keeps_live_customizations_without_captures() {
let mut app = PhotocraftApp::new(Session::new(), Services::default());
set_customizations(&mut app, "Frame", "F8", "red");
let live = customizations(&mut app);
invoke(&mut app, "workspace.reset", json!({}));
assert_eq!(customizations(&mut app), live, "built-in workspace");
invoke(&mut app, "workspace.new", json!({"name": "Panels Only"}));
set_customizations(&mut app, "Crop", "F9", "blue");
let live = customizations(&mut app);
invoke(&mut app, "workspace.reset", json!({}));
assert_eq!(customizations(&mut app), live, "saved workspace without captures");
}
+6
View File
@@ -270,6 +270,8 @@ pub fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, command: WorkspaceComm
Some(_) | None => {}
}
if command == WorkspaceCommands::Reset {
let current = app.workspaces.set.current.clone();
restore_extras(app, &current);
crate::dock::persist(app);
}
store(app);
@@ -560,6 +562,10 @@ fn extras_options() -> [(&'static str, &'static str); 13] {
]
}
#[cfg(test)]
#[path = "workspace_reset_captured_toolbar_tests.rs"]
mod workspace_reset_captured_toolbar_tests;
#[cfg(test)]
mod tests {
use super::*;
+57
View File
@@ -229,6 +229,63 @@ mod tests {
app.run("view.colorSamplers.add", json!({"x": 8, "y": 8})).unwrap();
assert_eq!(sampler_readouts(&mut app).len(), 2, "so does a new sampler");
}
/// Hovering the canvas or dragging the Eyedropper updates `hover_doc` and the Info panel's
/// colour and position readouts; leaving the canvas clears them (#16654).
#[test]
fn canvas_hover_and_eyedropper_drag_update_info_readings() {
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
use crate::canvas::document_display::CanvasHost;
use crate::state::{Tool, View};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let ctx = app.ctx().clone();
app.run("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap();
app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
app.session
.edit("blue half", |doc, active| {
let id = active.unwrap();
let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap();
surf.fill_rect(photocraft_geom::Rect::new(50, 0, 100, 100), &[0.0, 0.0, 1.0, 1.0]);
Ok(())
})
.unwrap();
let mut view = View { zoom: 1.0, center: [50.0, 50.0], doc_size: [100, 100], ..Default::default() };
view.clear_pending();
let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0));
let step = |app: &mut PhotocraftApp, events: Vec<Event>| {
let input = RawInput { screen_rect: Some(rect), events, ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
crate::canvas::canvas_view(app, ui, CanvasHost::main(0), rect, view.clone(), true);
});
out.textures_delta.clear();
};
// Hover over the red half: Info reports red and (20, 30).
step(&mut app, vec![Event::PointerMoved(pos2(20.5, 30.5))]);
let r = readings(&mut app, &[]);
assert_eq!(r.color.map(|c| c.rgb), Some([255, 0, 0]), "hovered red pixel");
let pos = r.position.expect("hovered position");
assert!(pos[0].as_str().starts_with("20") && pos[1].as_str().starts_with("30"), "got {pos:?}");
// Dragging the Eyedropper into the blue half keeps updating the Info readout.
app.ui.tool = Tool::Eyedropper;
step(&mut app, vec![Event::PointerButton { pos: pos2(20.5, 30.5), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
step(&mut app, vec![Event::PointerMoved(pos2(75.5, 40.5))]);
let r = readings(&mut app, &[]);
assert_eq!(r.color.map(|c| c.rgb), Some([0, 0, 255]), "dragged blue pixel");
let pos = r.position.expect("dragged position");
assert!(pos[0].as_str().starts_with("75") && pos[1].as_str().starts_with("40"), "got {pos:?}");
// Releasing and leaving the canvas clears the readings.
step(&mut app, vec![Event::PointerButton { pos: pos2(75.5, 40.5), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
step(&mut app, vec![Event::PointerGone]);
let r = readings(&mut app, &[]);
assert_eq!(r.color, None, "cleared after leaving canvas");
assert_eq!(r.position, None, "position cleared after leaving canvas");
}
}
#[cfg(test)]
+49 -2
View File
@@ -8,6 +8,8 @@
//! [`note_alerts`].
use craft::behavior::Selection;
use craft::ui::dialog::{PromptAnswer, PromptChoice, StandardPrompt};
use photocraft_engine::analysis_cmds;
use photocraft_engine::color_cmds::ColorExt;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -172,8 +174,12 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<
_ => "auto",
};
let r = app.run(id, json!({"source": source}));
if r.is_ok() {
let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true));
match &r {
Ok(_) => {
let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true));
}
Err(e) if e.starts_with(analysis_cmds::NO_DATA_POINTS) => no_data_points_alert(app, e),
Err(_) => {}
}
r
}
@@ -199,6 +205,43 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<
})
}
/// The tag of the alert Record Measurements shows when no data point is enabled for the source (#17407).
pub(crate) struct NoDataPoints;
/// The reference's warning when Record Measurements has no data point to record for the source named in `error`:
/// OK, or Set Data Points… to open Select Data Points with the current set. Nothing was recorded.
fn no_data_points_alert(app: &mut PhotocraftApp, error: &str) {
let source = error.strip_prefix(analysis_cmds::NO_DATA_POINTS).and_then(|rest| rest.split_once('.')).map_or("", |(name, _)| name);
let name = match source {
"Ruler Tool" => tl!("Ruler Tool"),
"Count Tool" => tl!("Count Tool"),
_ => tl!("Selection"),
};
let message = crate::i18n::fmt(tl!("There are no measurement data points currently enabled for the {source}."), &[("source", name)]);
let prompt = StandardPrompt::custom(message)
.title(tl!("PhotoCraft"))
.paragraph(tl!("Data points must be set before measurements can be recorded."))
.icon(craft::behavior::IconId::new("warning"))
.button(PromptChoice::Proceed, tl!("OK"))
.button(PromptChoice::Alternate, tl!("Set Data Points…"))
.escape(PromptChoice::Proceed)
.tag(NoDataPoints);
let _ = crate::dialogs::alerts::open_prompt(app, prompt);
}
/// The `PROMPTS` entry of that alert: Set Data Points… opens Select Data Points, whose OK only stores the set.
pub(crate) fn no_data_points_answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut PromptAnswer) -> bool {
if answer.take_tag::<NoDataPoints>().is_none() {
return false;
}
if answer.choice == PromptChoice::Alternate
&& let Err(error) = dialogs::open(app, dialogs::Kind::DataPoints)
{
crate::dialogs::alerts::report_error(app, error);
}
true
}
/// Export the Measurement Log (or the given rows) as CSV through the save picker.
pub(crate) fn export_log(app: &mut PhotocraftApp, rows: Option<Vec<u64>>) -> Result<Value, String> {
let p = rows.map_or(json!({}), |r| json!({"rows": r}));
@@ -251,3 +294,7 @@ pub(super) fn status_on_err(app: &mut PhotocraftApp, r: Result<Value, String>) {
app.ui.status_error = false;
}
}
#[cfg(test)]
#[path = "record_no_data_points_alert_tests.rs"]
mod record_no_data_points_alert_tests;
@@ -0,0 +1,76 @@
//! #17407: Image › Analysis › Record Measurements with no data point enabled for the source shows the warning with
//! OK and Set Data Points…; the latter opens Select Data Points with the current set, whose OK only stores the set.
use craft::ui::dialog::{DialogId, StandardPrompt};
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use serde_json::json;
use super::NoDataPoints;
use crate::PhotocraftApp;
const RECORD: &str = "image.analysis.recordMeasurements";
fn app() -> (Box<PhotocraftApp>, egui::Context) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 120})).unwrap();
app.run("image.analysis.selectDataPoints", json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let ctx = app.ctx().clone();
(app, ctx)
}
fn rows(app: &mut PhotocraftApp) -> usize {
app.run("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len)
}
/// The open alert: its id, and its message, paragraphs and buttons as shown.
fn alert(app: &PhotocraftApp) -> Option<(DialogId, String, Vec<String>, Vec<String>)> {
let id = crate::dialogs::alerts::prompt_tagged::<NoDataPoints>(app)?;
let prompt = app.framework.dialogs.get::<StandardPrompt>()?;
let host = app.framework.host();
let buttons = prompt.shown_buttons(host).into_iter().map(|(_, label)| label).collect();
Some((id, prompt.shown_message(host), prompt.shown_paragraphs(host), buttons))
}
#[test]
fn record_measurements_shows_the_warning_with_ok_and_set_data_points() {
let (mut app, ctx) = app();
assert!(crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).is_err());
let (id, message, paragraphs, buttons) = alert(&app).expect("the warning is open");
assert_eq!(message, "There are no measurement data points currently enabled for the Selection.");
assert_eq!(paragraphs, ["Data points must be set before measurements can be recorded."]);
assert_eq!(buttons, ["OK", "Set Data Points…"]);
assert_eq!(rows(&mut app), 0, "nothing is recorded");
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert!(alert(&app).is_none(), "OK closes it");
assert!(app.framework.dialogs.get::<HostedParamDialog>().is_none(), "OK opens nothing");
}
#[test]
fn set_data_points_opens_select_data_points_whose_ok_only_stores_the_set() {
let (mut app, ctx) = app();
let _ = crate::menus::invoke(&mut app, &ctx, RECORD, json!({}));
let (id, ..) = alert(&app).unwrap();
app.framework.dialogs.set_json_field(&ctx, id, "choice", json!("alternate")).unwrap();
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert!(alert(&app).is_none());
let dialog = app.framework.dialogs.get::<HostedParamDialog>().map(craft::ui::dialog::StackDialog::id).expect("Select Data Points is open");
// The current set: Ruler Length is ticked, Selection Area is not.
let fields = serde_json::to_value(app.framework.dialogs.get_by_id::<HostedParamDialog>(dialog).unwrap().fields()).unwrap();
assert_eq!(fields["ruler:length"], json!(true), "{fields}");
assert_ne!(fields["selection:area"], json!(true), "{fields}");
crate::dialogs::confirm(&mut app, &ctx, dialog).unwrap();
assert_eq!(rows(&mut app), 0, "its OK records nothing");
assert!(alert(&app).is_none(), "its OK does not record, so it does not warn again");
let points = app.run("image.analysis.selectDataPoints", json!({})).unwrap();
assert_eq!(points["dataPoints"]["ruler"], json!(["length", "angle"]), "its OK stores the set it shows: {points}");
app.run("image.analysis.selectDataPoints", json!({"selection": ["area"], "ruler": [], "count": []})).unwrap();
// Now Record Measurements records, as "Measurement 1".
crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).unwrap();
assert_eq!(rows(&mut app), 1);
assert!(alert(&app).is_none());
}