Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions crates/develop/src/recipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,34 @@ pub fn generic_name(name: &str) -> bool {
n.is_empty() || n == "Mask" || n.strip_prefix("Mask ").is_some_and(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit()))
}

/// Whether `name` is `base` or `base` numbered ("Brush", "Brush 2"): an automatic name that
/// [`unique_name`] may have numbered.
pub fn numbered_name(name: &str, base: &str) -> bool {
name == base || name.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit()))
}

/// `base`, or `base` with the lowest number from 2 up that none of `taken` has ("Brush 2"), so
/// two masks of a photo never share an automatic name.
pub fn unique_name(base: &str, taken: &[&str]) -> String {
if !taken.contains(&base) {
return base.to_string();
}
(2..=taken.len().saturating_add(2)).map(|n| format!("{base} {n}")).find(|c| !taken.contains(&c.as_str())).unwrap_or_else(|| base.to_string())
}

/// What a mask is made of: the kinds of its components in order, each once ("Radial Gradient,
/// Brush", "People - Eyes"); Copy Settings shows it next to each mask's name.
pub fn composition(m: &Mask) -> String {
let mut kinds: Vec<String> = Vec::new();
for c in &m.components {
let n = shape_name(&c.shape);
if !kinds.contains(&n) {
kinds.push(n);
}
}
kinds.join(", ")
}

/// A preset's name without a leading catalogue code and trailing filler ("P10 Sun Kissed" → "Sun
/// Kissed", "P5 Enhance Portrait......" → "Enhance Portrait").
pub fn short_preset_name(name: &str) -> String {
Expand Down Expand Up @@ -655,6 +683,34 @@ mod tests {
assert_eq!(short_preset_name("2026"), "2026");
}

#[test]
fn automatic_names_are_numbered_only_where_they_would_repeat() {
assert_eq!(unique_name("Brush", &["Sky", "Subject"]), "Brush");
assert_eq!(unique_name("Brush", &["Brush"]), "Brush 2");
assert_eq!(unique_name("Brush", &["Brush", "Brush 2", "Brush 4"]), "Brush 3");
assert_eq!(unique_name("", &[""]), " 2");
assert!(numbered_name("Brush", "Brush") && numbered_name("Brush 12", "Brush"));
assert!(!numbered_name("Brush two", "Brush") && !numbered_name("Brush ", "Brush") && !numbered_name("Brushes", "Brush"));
assert!(!numbered_name("Sky", "Brush"));
let comp = |op, shape| MaskComponent { anchor: None, name: None, op, invert: false, shape };
let radial = MaskShape::Radial { center: Point::new(0.5, 0.5), rx: 0.2, ry: 0.2, angle: 0.0, feather: 50.0, invert: false };
let m = Mask {
components: vec![
comp(MaskOp::Add, radial.clone()),
comp(MaskOp::Add, MaskShape::Brush { strokes: vec![] }),
comp(MaskOp::Subtract, radial),
],
..Default::default()
};
assert_eq!(composition(&m), "Radial Gradient, Brush");
let eyes = Mask {
components: vec![comp(MaskOp::Add, MaskShape::People { person: 0, parts: vec!["Eyes".into()], who: None, seg: None })],
..Default::default()
};
assert_eq!(composition(&eyes), "People - Eyes");
assert_eq!(composition(&Mask::default()), "");
}

#[test]
fn who_and_anchor_serialize_plainly() {
let w: Who = serde_json::from_value(serde_json::json!({"role": "Bride"})).unwrap();
Expand Down
49 changes: 43 additions & 6 deletions crates/engine/src/cmd/develop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,19 @@ fn pick_param(p: &Value, c: &str) -> Result<Option<SettingsPick>> {
Ok(Some(SettingsPick { groups: groups.unwrap_or_default(), settings }.normalized()))
}

/// `masks` (Copy: which of the photo's masks, by id); `None` when not given.
fn mask_ids_param(p: &Value, c: &str) -> Result<Option<Vec<u32>>> {
match p.get("masks") {
None | Some(Value::Null) => Ok(None),
Some(Value::Array(a)) => a
.iter()
.map(|v| v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(c, format!("invalid mask id `{v}` (develop.get: masks[].id)"))))
.collect::<Result<Vec<u32>>>()
.map(Some),
Some(_) => Err(bad(c, "`masks` must be a list of mask ids (develop.get: masks[].id)")),
}
}

/// A preset group named like `name` (trimmed, any case) that exists already, else `name` trimmed:
/// typing "wedding " never makes a second "Wedding" group.
pub(crate) fn existing_preset_group(s: &Session, name: &str) -> String {
Expand Down Expand Up @@ -1416,23 +1429,46 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy Edit Settings",
["Photo", "Develop Settings"],
Some("Cmd+C"),
"{groups?: [settingsGroup], settings?: [settingItem] (single settings of a group, develop.settingItems)} (default: what was ticked last; at first all but crop, masks, remove): the choice is remembered → {groups, settings}",
"{groups?: [settingsGroup], settings?: [settingItem] (single settings of a group, develop.settingItems), masks?: [maskId] (with the masks group: only these of the photo's masks, by id (develop.get); default all)} (default: what was ticked last; at first all but crop, masks, remove): the group choice is remembered, the masks one is for this copy only → {groups, settings, masks? (the mask ids copied, when `masks` was given)}",
has_active,
|s, p| {
let c = "develop.copy";
let id = active(s, c)?;
if let Some(pick) = pick_param(p, c)?
let pick = pick_param(p, c)?;
let only_masks = mask_ids_param(p, c)?;
let d = s.develop_of(id).unwrap_or_default();
if let Some(only) = &only_masks {
if !pick.as_ref().unwrap_or(&s.dialogs.copy).has(SettingsGroup::Masks.id()) {
return Err(bad(c, "`masks` picks which masks to copy: add \"masks\" to `groups`"));
}
if let Some(unknown) = only.iter().find(|m| !d.masks.iter().any(|x| x.id == **m)) {
return Err(bad(c, format!("this photo has no mask {unknown} (develop.get: masks[].id)")));
}
}
if let Some(pick) = pick
&& pick != s.dialogs.copy
{
s.dialogs.copy = pick;
remember_dialogs(s);
}
let d = s.develop_of(id).unwrap_or_default();
let mut copied = s.dialogs.copy.extract(&d);
if let Some(only) = &only_masks
&& let Some(masks) = copied.get_mut("masks").and_then(Value::as_array_mut)
{
// (in the photo's own order, whatever order they were named in)
masks.retain(|m| m.get("id").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).is_some_and(|mid| only.contains(&mid)));
}
// portable: pasted in another catalog, a flat-field map still applies
let copied = s.dialogs.copy.extract(&d);
s.clipboard = Some(s.portable(&copied));
s.clipboard_from = Some(id);
Ok(json!({"groups": s.dialogs.copy.groups, "settings": s.dialogs.copy.settings}))
let mut out = json!({"groups": s.dialogs.copy.groups, "settings": s.dialogs.copy.settings});
if let Some(only) = only_masks
&& let Some(o) = out.as_object_mut()
{
let ids: Vec<u32> = d.masks.iter().map(|m| m.id).filter(|mid| only.contains(mid)).collect();
o.insert("masks".into(), json!(ids));
}
Ok(out)
}
),
cmd!(
Expand Down Expand Up @@ -1765,7 +1801,8 @@ pub fn specs() -> Vec<CommandSpec> {
// photographer gave it ("Warmth") is kept
for k in 0..d.masks.len() {
let Some(m) = d.masks.get(k).cloned() else { continue };
if s.auto_mask_name(id, &m) == m.name
// (numbered too: "Brush 2" next to another Brush)
if lcc_develop::recipe::numbered_name(&m.name, &s.auto_mask_name(id, &m))
&& let Some(m) = d.masks.get_mut(k)
{
m.name.clear();
Expand Down
27 changes: 22 additions & 5 deletions crates/engine/src/people_smart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,30 @@ impl Session {
}

/// Give the masks of `after` that still carry an automatic name (a placeholder such as
/// "Mask 3", or the name they had automatically in `before`) the name of what they select now;
/// a name the photographer gave is kept.
/// "Mask 3", or the name they had automatically in `before`, numbered or not) the name of what
/// they select now; a name the photographer gave is kept. A name another mask of the photo
/// has already gets a number ("Brush 2", issue #1268); a mask whose name doesn't change keeps
/// it, so masks that shared a name before (imported ones too) keep theirs.
pub(crate) fn refresh_mask_names(&mut self, id: PhotoId, before: &[lcc_develop::Mask], after: &mut [lcc_develop::Mask]) {
for m in after.iter_mut().filter(|m| !m.components.is_empty()) {
use lcc_develop::recipe::{generic_name, numbered_name, unique_name};
for i in 0..after.len() {
let Some(m) = after.get(i).filter(|m| !m.components.is_empty()).cloned() else { continue };
let was = before.iter().find(|b| b.id == m.id).filter(|b| !b.components.is_empty()).map(|b| self.auto_mask_name(id, b));
if lcc_develop::recipe::generic_name(&m.name) || was.as_deref() == Some(m.name.as_str()) {
m.name = self.auto_mask_name(id, m);
let placeholder = generic_name(&m.name);
if !placeholder && !was.as_deref().is_some_and(|w| numbered_name(&m.name, w)) {
continue;
}
let base = self.auto_mask_name(id, &m);
if !placeholder && was.as_deref() == Some(base.as_str()) {
// selects what it selected: its name (and number) stays
continue;
}
let name = {
let taken: Vec<&str> = after.iter().enumerate().filter(|(k, _)| *k != i).map(|(_, x)| x.name.as_str()).collect();
unique_name(&base, &taken)
};
if let Some(m) = after.get_mut(i) {
m.name = name;
}
}
}
Expand Down
93 changes: 93 additions & 0 deletions crates/engine/src/tests_mask_links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,3 +391,96 @@ fn the_selected_mask_follows_the_active_photo_to_its_linked_copy() {
s.execute("library.select", &json!({"ids": [c.0]})).unwrap();
assert_eq!(s.active_mask, None, "a photo without it: none");
}

/// Issue #1268: Copy can take some of the photo's masks (`masks`: their ids); Paste puts just
/// those on, in the photo's order and linked to their originals. Without `masks` every mask goes,
/// as before. A mask id the photo doesn't have, or a malformed list, is an error.
#[test]
fn copy_takes_a_subset_of_the_masks_and_paste_links_just_those() {
let (mut s, [a, b, c]) = photos::<3>();
s.execute("library.select", &json!({"ids": [a.0]})).unwrap();
s.execute("mask.add", &json!({"kind": "radial"})).unwrap();
s.execute("mask.add", &json!({"kind": "linear", "start": [0.5, 0.0], "end": [0.5, 0.5]})).unwrap();
s.execute("mask.add", &json!({"kind": "radial", "center": [0.2, 0.2]})).unwrap();
let mine = masks(&s, a);
assert_eq!(mine.len(), 3);
let names: Vec<&str> = mine.iter().map(|m| m.name.as_str()).collect();
assert_eq!(names, ["Radial Gradient", "Linear Gradient", "Radial Gradient 2"], "two radials don't share a name");
let (first, third) = (mine[0].id, mine[2].id);

// asked in reverse order: copied in the photo's order
let out = s.execute("develop.copy", &json!({"groups": ["masks"], "masks": [third, first]})).unwrap();
assert_eq!(out["masks"], json!([first, third]));
select(&mut s, &[b, c], b);
s.execute("develop.paste", &json!({})).unwrap();
for id in [b, c] {
let got = masks(&s, id);
let names: Vec<&str> = got.iter().map(|m| m.name.as_str()).collect();
assert_eq!(names, ["Radial Gradient", "Radial Gradient 2"], "only the two picked, in order");
}
let orig = masks(&s, a);
assert!(orig[1].link.is_empty(), "the mask left behind isn't linked");
for (k, o) in [(0, &orig[0]), (1, &orig[2])] {
assert!(!o.link.is_empty());
assert!([b, c].iter().all(|id| masks(&s, *id)[k].link == o.link), "each copy joins its own original");
}

// no `masks`: all of them, as before
s.execute("library.select", &json!({"ids": [a.0]})).unwrap();
let out = s.execute("develop.copy", &json!({"groups": ["masks"]})).unwrap();
assert!(out.get("masks").is_none());
s.execute("library.select", &json!({"ids": [c.0]})).unwrap();
s.execute("develop.paste", &json!({})).unwrap();
assert_eq!(masks(&s, c).len(), 3);

// an empty pick copies no mask
s.execute("library.select", &json!({"ids": [a.0]})).unwrap();
s.execute("develop.copy", &json!({"groups": ["masks"], "masks": []})).unwrap();
assert_eq!(s.clipboard.as_ref().and_then(|c| c.get("masks")).and_then(|m| m.as_array()).map(Vec::len), Some(0));

// hostile: errors, and the clipboard and the remembered choice stay as they were
let clip = s.clipboard.clone();
let remembered = s.dialogs.copy.clone();
for bad in [
json!({"groups": ["masks"], "masks": [9999]}),
json!({"groups": ["masks"], "masks": [-1]}),
json!({"groups": ["masks"], "masks": ["one"]}),
json!({"groups": ["masks"], "masks": [u64::MAX]}),
json!({"groups": ["masks"], "masks": 3}),
json!({"groups": ["light"], "masks": [first]}),
] {
assert!(s.execute("develop.copy", &bad).is_err(), "{bad}");
}
assert_eq!(s.clipboard, clip);
assert_eq!(s.dialogs.copy, remembered);
}

/// Issue #1268: a placeholder name the photographer gave ("Warmth") stays; an automatic name
/// that would repeat gets a number, and a numbered name keeps its number while the mask selects
/// the same; masks that already share a name keep it.
#[test]
fn automatic_mask_names_get_a_number_only_where_they_would_repeat() {
let (mut s, [a]) = photos::<1>();
s.execute("library.select", &json!({"ids": [a.0]})).unwrap();
s.execute("mask.add", &json!({"kind": "radial"})).unwrap();
s.execute("mask.add", &json!({"kind": "radial", "name": "Warmth"})).unwrap();
s.execute("mask.add", &json!({"kind": "radial"})).unwrap();
let names = |s: &Session| masks(s, a).iter().map(|m| m.name.clone()).collect::<Vec<_>>();
assert_eq!(names(&s), ["Radial Gradient", "Warmth", "Radial Gradient 2"]);
// an edit that doesn't change what it selects keeps the number
let third = masks(&s, a)[2].id;
s.execute("mask.adjust", &json!({"id": third, "values": {"exposure": 0.5}})).unwrap();
assert_eq!(names(&s)[2], "Radial Gradient 2");
// a component of another kind: its new name, unique
s.execute("mask.addComponent", &json!({"id": third, "op": "add", "kind": "linear"})).unwrap();
assert_eq!(names(&s)[2], "Radial Gradient + Linear Gradient");
// masks that already shared a name (imported, or from before) keep it
let mut d = (*s.develop_of(a).unwrap()).clone();
for m in &mut d.masks {
m.name = "Radial Gradient".into();
}
s.set_develop(a, d, "test").unwrap();
let first = masks(&s, a)[0].id;
s.execute("mask.adjust", &json!({"id": first, "values": {"exposure": 0.2}})).unwrap();
assert!(names(&s).iter().all(|n| n == "Radial Gradient"), "{:?}", names(&s));
}
2 changes: 1 addition & 1 deletion crates/ui-egui/src/menus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2399,7 +2399,7 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option<Result<Va
}
"dialog.copySettings" => {
let groups = app.session.dialogs.copy.to_ids();
app.ui.dialog = Some(Dialog::CopySettings { groups });
app.ui.dialog = Some(Dialog::CopySettings { groups, masks_off: Vec::new() });
Ok(Value::Null)
}
"dialog.slideshowExport" => {
Expand Down
Loading