Merge pull request #3482 from dotCooCoo/fix/keyword-names-no-trailing-asterisk

LRC-LIB-KEYWORDS: a new keyword name cannot end in an asterisk
This commit is contained in:
FredApps authored and GitHub committed 2026-11-20 21:04:02 +07:00
commit 041c8db2f7
11 files changed
+226 -13

No files matched your search

+22
View File
@@ -24,6 +24,13 @@ pub fn clean(k: &str) -> String {
k.split(SEP).map(str::trim).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("|")
}
/// No level of `k` ends in `*` (after trimming): a name a user gives can't end in an asterisk,
/// which marks a keyword only some of the selected photos have. An asterisk inside a name (`a*b`)
/// is allowed.
pub fn valid_name(k: &str) -> bool {
!k.split(SEP).any(|level| level.trim().ends_with('*'))
}
/// The same name, whatever the case of any of its letters (not only ASCII ones).
pub fn same(a: &str, b: &str) -> bool {
a == b || a.to_lowercase() == b.to_lowercase()
@@ -691,6 +698,19 @@ impl Catalog {
self.keyword_path(path).is_some()
}
/// Refuse a keyword a user gives (a new keyword, a new name, a keyword typed for photos) when a
/// level the library doesn't have yet ends in `*` ([`valid_name`]). Levels the library has,
/// such as those read from sidecars and catalogs, are accepted as they are.
pub fn check_keyword_name(&self, path: &str) -> Result<()> {
let levels: Vec<&str> = path.split(SEP).map(str::trim).filter(|s| !s.is_empty()).collect();
for (i, level) in levels.iter().enumerate() {
if !valid_name(level) && !self.has_keyword(&levels.get(..=i).map(|l| l.join("|")).unwrap_or_default()) {
return Err(CatalogError::Invalid(format!("keyword names can't end in “*”: “{level}”")));
}
}
Ok(())
}
/// Where a keyword typed for a photo goes: inside the default parent when it is a new name (Put
/// New Keywords Inside This Keyword); a keyword the library has, or a path typed whole, as
/// typed (cleaned).
@@ -795,6 +815,7 @@ impl Catalog {
if self.has_keyword(&path) {
return Err(CatalogError::KeywordExists(path));
}
self.check_keyword_name(&path)?;
let path = self.spelled(&path);
let mut ops = vec![Op::SetKeyword { path: path.clone(), info: Some(info) }];
for id in photos {
@@ -849,6 +870,7 @@ impl Catalog {
if !same(&to, &from) && self.has_keyword(&to) {
return Err(CatalogError::KeywordExists(to));
}
self.check_keyword_name(&to)?;
if let Op::Batch { ops: renamed } = self.rename_keyword_ops(&from, &to)? {
ops = renamed;
}
+30
View File
@@ -209,6 +209,36 @@ fn creating_a_keyword_lists_it_and_can_tag_photos() {
assert!(c.create_keyword_ops(" | ", KeywordInfo::default(), &[]).is_err());
}
/// A new keyword's name can't end in `*` at any level, which marks a keyword only some of the
/// selected photos have; an asterisk inside a name is allowed. Levels the library already has,
/// as a sidecar or catalog wrote them, are accepted as they are.
#[test]
fn a_new_keyword_name_cannot_end_in_an_asterisk() {
assert!(!valid_name("travel*") && !valid_name("places | rome* ") && valid_name("a*b"));
for name in ["a*", "a | b*", "*", "a *"] {
assert!(!valid_name(name), "{name}");
}
let (mut c, ids) = lib(&[&["places|italy"], &[]]);
for name in ["travel*", "places|rome*", "travel *|rome", "a*", "a | b*", "*", "a *"] {
let err = c.create_keyword_ops(name, KeywordInfo::default(), &[ids[1]]).unwrap_err();
assert!(err.to_string().contains("can't end in “*”"), "{name}: {err}");
}
assert!(c.edit_keyword_ops("places|italy", "Italy*", KeywordInfo::default()).is_err());
let op = c.create_keyword_ops("a*b", KeywordInfo::default(), &[]).unwrap();
c.apply(op).unwrap();
assert!(c.has_keyword("a*b"));
// read from a file: kept, and it can be named again
assert_eq!(from_file(&["travel*".to_string()], &["old*|rome".to_string()]), ["old*|rome", "travel*"]);
let (mut c, ids) = lib(&[&["travel*", "old*|rome"], &[]]);
assert!(c.check_keyword_name("travel*").is_ok() && c.check_keyword_name("old*|rome").is_ok());
let op = c.create_keyword_ops("old*|milan", KeywordInfo::default(), &[ids[1]]).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[1]), ["old*|milan"]);
let op = c.edit_keyword_ops("travel*", "TRAVEL*", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["TRAVEL*", "old*|rome"]);
}
/// Moving a keyword nests it inside another (or takes it to the top level), with its children,
/// on photos and in the list. It can't go inside itself or one of its children, and moving it
/// where it already is changes nothing.
+14 -4
View File
@@ -170,6 +170,7 @@ fn shortcut_keywords(s: &Session, p: &Value) -> Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
for k in typed {
let k = s.catalog.typed_keyword(&k);
s.catalog.check_keyword_name(&k).map_err(|e| bad("keyword.setShortcut", e.to_string()))?;
if !k.is_empty() && !out.iter().any(|x| lightcraft_catalog::keywords::same(x, &k)) {
out.push(k);
}
@@ -266,7 +267,11 @@ pub fn specs() -> Vec<CommandSpec> {
};
// keywords not given: the renamed set's own, else the current nine
let keywords = if p.get("keywords").is_some() {
slots(&strs(p, "keywords"))
let keywords = slots(&strs(p, "keywords"));
for k in &keywords {
s.catalog.check_keyword_name(k).map_err(|e| bad("keyword.saveSet", e.to_string()))?;
}
keywords
} else {
match renames.and_then(|at| s.keyword_sets.get(at)) {
Some(x) => x.keywords.clone(),
@@ -437,7 +442,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Keyword",
[],
None,
"{name, parent?: keyword | null (default: the default parent; null = the top level), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?, addToSelected?: bool, ids?} → {keyword}",
"{name (a new level can't end in `*`), parent?: keyword | null (default: the default parent; null = the top level), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?, addToSelected?: bool, ids?} → {keyword}",
always,
|s, p| {
let name = str_param(p, "name").map(clean).filter(|n| !n.is_empty()).ok_or_else(|| bad("keyword.create", "missing `name`"))?;
@@ -467,7 +472,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Keyword",
[],
None,
"{keyword, name?: its new name (one level), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?} — what isn't given keeps its value",
"{keyword, name?: its new name (one level, not ending in `*`), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?} — what isn't given keeps its value",
always,
|s, p| {
let from = named_keyword(s, p, "keyword.edit")?;
@@ -500,7 +505,10 @@ pub fn specs() -> Vec<CommandSpec> {
// where it lands, as the catalog spells it: a parent that doesn't exist yet is made
let leaf = from.rsplit('|').next().unwrap_or(&from).to_string();
let to = match parent.as_deref().map(|k| s.catalog.keyword_path(k).unwrap_or_else(|| clean(k))).filter(|k| !k.is_empty()) {
Some(parent) => format!("{parent}|{leaf}"),
Some(parent) => {
s.catalog.check_keyword_name(&parent).map_err(|e| bad("keyword.move", e.to_string()))?;
format!("{parent}|{leaf}")
}
None => leaf,
};
let op = s
@@ -602,6 +610,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
let from = str_param(p, "from").ok_or_else(|| bad("keyword.rename", "missing `from`"))?.to_string();
let to = str_param(p, "to").ok_or_else(|| bad("keyword.rename", "missing `to`"))?.to_string();
s.catalog.check_keyword_name(&to).map_err(|e| bad("keyword.rename", e.to_string()))?;
let op = s.catalog.rename_keyword_ops(&from, &to).map_err(|e| bad("keyword.rename", e.to_string()))?;
let (f, t) = (clean(&from), clean(&to));
commit_keywords(s, "Rename Keyword", op, |k| Some(if is_under(k, &f) { reparent(k, &f, &t) } else { k.to_string() }))
@@ -631,6 +640,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
let from = strs(p, "from");
let into = str_param(p, "into").ok_or_else(|| bad("keyword.merge", "missing `into`"))?.to_string();
s.catalog.check_keyword_name(&into).map_err(|e| bad("keyword.merge", e.to_string()))?;
let op = s.catalog.merge_keywords_ops(&from, &into).map_err(|e| bad("keyword.merge", e.to_string()))?;
let (from, into) = (from.iter().map(|f| clean(f)).collect::<Vec<_>>(), clean(&into));
commit_keywords(s, "Merge Keywords", op, |k| {
+11 -1
View File
@@ -60,6 +60,12 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
{
return Err(bad("library.import", format!("unknown metadata preset `{n}`")));
}
// the chosen preset and the import defaults' preset (presets saved earlier are kept in prefs)
for n in metadata_preset.iter().chain(s.import_defaults.metadata_preset.iter()) {
if let Some(mp) = s.metadata_presets.iter().find(|m| m.name.eq_ignore_ascii_case(n)) {
crate::cmd::metadata::check_keywords(s, &mp.fields, "library.import")?;
}
}
let on_deleted = match str_param(p, "onDeleted") {
Some(v) => {
crate::import::OnDeleted::parse(v).ok_or_else(|| bad("library.import", format!("unknown onDeleted `{v}` (restore|skip|fresh)")))?
@@ -70,11 +76,15 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
Some(n) => usize::try_from(n).map_err(|_| bad("library.import", "renameStart is too large for this platform"))?,
None => 1,
};
let keywords = strs(p, "keywords");
for k in &keywords {
s.catalog.check_keyword_name(k).map_err(|e| bad("library.import", e.to_string()))?;
}
let opts = crate::import::ImportOptions {
on_deleted,
mode,
preset,
keywords: strs(p, "keywords"),
keywords,
destination: str_param(p, "destination").map(str::to_string),
organize,
rename: str_param(p, "rename").map(str::to_string),
+13 -1
View File
@@ -728,6 +728,14 @@ pub fn specs() -> Vec<CommandSpec> {
),
None => None,
};
// the keywords given that the library refuses as new names, each checked once
let refused: Vec<(String, String)> = strs("keywords")
.into_iter()
.flatten()
.chain(strs("addKeywords").unwrap_or_default())
.map(|k| lightcraft_catalog::keywords::clean(&k))
.filter_map(|k| s.catalog.check_keyword_name(&k).err().map(|e| (k, e.to_string())))
.collect();
let mut ops = Vec::new();
for id in targets {
let Some(ph) = s.catalog.photo(id) else { continue };
@@ -757,7 +765,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
}
// keywords are stored cleaned (`a | b ` is `a|b`), each once whatever its case
use lightcraft_catalog::keywords::clean;
use lightcraft_catalog::keywords::{clean, same};
// (a set of the lower-cased keywords keeps this linear however many are supplied)
let mut seen: std::collections::HashSet<String> = m.keywords.iter().map(|x| x.to_lowercase()).collect();
let add = |m: &mut lightcraft_catalog::Meta, seen: &mut std::collections::HashSet<String>, k: &str| {
@@ -766,6 +774,10 @@ pub fn specs() -> Vec<CommandSpec> {
m.keywords.push(k);
}
};
// a keyword the photo or the library doesn't have yet can't end in `*`
if let Some((_, e)) = refused.iter().find(|(k, _)| !m.keywords.iter().any(|x| same(&clean(x), k))) {
return Err(bad("photo.setMeta", e.clone()));
}
if let Some(k) = strs("keywords") {
m.keywords.clear();
seen.clear();
+10
View File
@@ -66,6 +66,15 @@ pub fn apply_to(m: &mut Meta, fields: &Value) {
}
}
/// Refuses preset `fields` whose keywords hold a new name the library cannot take
/// (`Catalog::check_keyword_name`).
pub fn check_keywords(s: &Session, fields: &Value, command: &str) -> Result<()> {
for kw in fields.get("keywords").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
s.catalog.check_keyword_name(kw).map_err(|e| bad(command, e.to_string()))?;
}
Ok(())
}
fn list(s: &Session) -> Value {
json!(s.metadata_presets)
}
@@ -113,6 +122,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Value::Object(o)
}
};
check_keywords(s, &fields, C)?;
let preset = MetadataPreset { name: name.clone(), fields };
match s.metadata_presets.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&name)) {
Some(m) => *m = preset,
+53
View File
@@ -54,6 +54,59 @@ fn creating_a_keyword_with_attributes_and_the_selection() {
assert!(s.execute("keyword.info", &json!({"keyword": "lisbon"})).is_err(), "no such keyword");
}
/// Every command that names a keyword refuses a new name ending in `*` at any level, and changes
/// nothing; a name with `*` inside is allowed. A keyword the library has from a file keeps its name
/// and can still be given to photos.
#[test]
fn commands_refuse_a_new_keyword_name_ending_in_an_asterisk() {
let mut s = Session::with_demo();
let ids: Vec<u64> = s.visible_cloned().iter().take(2).map(|p| p.0).collect();
s.execute("library.select", &json!({"ids": ids})).unwrap();
s.execute("keyword.create", &json!({"name": "Lagoon", "parent": null})).unwrap();
s.execute("keyword.saveSet", &json!({"name": "Mine", "keywords": ["Lagoon"]})).unwrap();
for name in ["travel*", "places|rome*"] {
// a metadata preset in prefs that holds the name
s.metadata_presets = vec![crate::cmd::metadata::MetadataPreset { name: "Old".into(), fields: json!({"keywords": [name]}) }];
let before = s.catalog.to_snapshot();
let sets = s.keyword_sets.clone();
let presets = s.metadata_presets.clone();
for (command, params) in [
("keyword.create", json!({"name": name, "parent": null})),
("keyword.edit", json!({"keyword": "Lagoon", "name": name.rsplit('|').next()})),
("keyword.rename", json!({"from": "Lagoon", "to": name})),
("keyword.merge", json!({"from": ["Lagoon"], "into": name})),
("keyword.move", json!({"keyword": "Lagoon", "parent": name})),
("photo.setMeta", json!({"addKeywords": [name]})),
("photo.setMeta", json!({"keywords": ["Lagoon", name]})),
("keyword.setShortcut", json!({"keywords": [name]})),
("keyword.saveSet", json!({"name": "Mine", "keywords": [name]})),
("library.import", json!({"paths": ["missing.jpg"], "keywords": [name]})),
("metadata.savePreset", json!({"name": "Trip", "fields": {"keywords": ["Lagoon", name]}})),
("library.import", json!({"paths": ["missing.jpg"], "metadataPreset": "Old"})),
] {
let err = s.execute(command, &params).unwrap_err().to_string();
assert!(err.contains("can't end in “*”"), "{command} {params}: {err}");
}
// the import defaults' metadata preset
s.import_defaults.metadata_preset = Some("Old".into());
let err = s.execute("library.import", &json!({"paths": ["missing.jpg"]})).unwrap_err().to_string();
assert!(err.contains("can't end in “*”"), "import defaults: {err}");
s.import_defaults.metadata_preset = None;
assert!(s.catalog.to_snapshot() == before && s.keyword_sets == sets && s.metadata_presets == presets, "{name}: nothing changed");
}
s.execute("photo.setMeta", &json!({"addKeywords": ["a*b"]})).unwrap();
assert!(ids.iter().all(|id| keywords_of(&s, *id).contains(&"a*b".to_string())));
// a keyword read from a file (here put on the photo as a sidecar read puts it)
let id = lightcraft_catalog::PhotoId(ids[0]);
let mut meta = s.catalog.photo(id).unwrap().meta.clone();
meta.keywords.push("travel*".into());
s.commit("Read Metadata", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap();
s.execute("photo.setMeta", &json!({"ids": [ids[1]], "addKeywords": ["TRAVEL*"]})).unwrap();
assert!(keywords_of(&s, ids[1]).contains(&"TRAVEL*".to_string()), "{:?}", keywords_of(&s, ids[1]));
s.execute("keyword.edit", &json!({"keyword": "travel*", "synonyms": ["trip"]})).unwrap();
assert!(keywords_of(&s, ids[0]).contains(&"travel*".to_string()), "its name is kept");
}
/// "Put new keywords inside this keyword": new keywords go inside the default parent unless the
/// command says otherwise (`parent: null` = the top level). It belongs to its keyword in the
/// library: it follows a rename, goes with a delete, and undo and redo bring it back with them.
+14
View File
@@ -280,6 +280,20 @@ mod tests {
ImportDialog::new(candidates)
}
/// An import the engine refuses creates no new album: its params are checked first.
#[test]
fn a_refused_import_creates_no_new_album() {
let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default());
let mut d = dialog();
d.new_album = "Card 1".into();
d.keywords = "travel*".into();
let albums = app.session.catalog.albums().count();
let err = start(&mut app, &d).unwrap_err();
assert!(err.contains("can't end in “*”"), "{err}");
assert_eq!(app.session.catalog.albums().count(), albums, "no album was created");
assert!(app.import.is_none());
}
/// Identical copies inside the source folder are not "already in the library" (a fresh library
/// said "8 already in the library").
#[test]
+11 -6
View File
@@ -214,11 +214,6 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String>
return Err("no photos selected".into());
}
let undo0 = app.session.undo.len();
let mut album = d.album;
if album.is_none() && !d.new_album.trim().is_empty() {
let r = app.session.execute("album.create", &json!({"name": d.new_album.trim()})).map_err(|e| e.to_string())?;
album = r["id"].as_u64();
}
let mode = match (d.copy, d.move_files) {
(false, _) => "add",
(true, false) => "copy",
@@ -231,7 +226,7 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String>
if !d.on_deleted.is_empty() {
params["onDeleted"] = json!(d.on_deleted);
}
if let Some(a) = album {
if let Some(a) = d.album {
params["album"] = json!(a);
}
if !d.preset.is_empty() {
@@ -255,6 +250,16 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String>
params["dng"] = json!(true);
}
}
// the params are checked before a new album is created, so a refused import leaves no album
let mut check = params.clone();
check["paths"] = json!(queue);
lightcraft_engine::cmd::library::import_params(&app.session, &check).map_err(|e| e.to_string())?;
if d.album.is_none() && !d.new_album.trim().is_empty() {
let r = app.session.execute("album.create", &json!({"name": d.new_album.trim()})).map_err(|e| e.to_string())?;
if let Some(a) = r["id"].as_u64() {
params["album"] = json!(a);
}
}
let total = queue.len();
app.import = Some(ImportTask::new(queue, params, undo0, false));
app.renderer.forget_imports();
+8 -1
View File
@@ -224,7 +224,14 @@ fn ui_commands_1(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val
}
"tool.keywordPainter" => {
// {keyword?}: paint that keyword onto photos in the grid by clicking them; no keyword stops
app.ui.keyword_painter = p.get("keyword").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).map(str::to_string);
let keyword = p.get("keyword").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).map(str::to_string);
// a new keyword ending in `*` is refused before painting starts, so no click fails unseen
if let Some(Err(e)) = keyword.as_deref().map(|k| app.session.catalog.check_keyword_name(k)) {
let e = format!("tool.keywordPainter: {e}");
app.toast_error(ctx, e.clone());
return Some(Err(e));
}
app.ui.keyword_painter = keyword;
if app.ui.keyword_painter.is_some() && !matches!(app.ui.view, ViewMode::PhotoGrid | ViewMode::SquareGrid) {
app.ui.view = ViewMode::PhotoGrid;
}
+40
View File
@@ -249,6 +249,46 @@ fn creating_a_keyword_that_exists_keeps_the_dialog() {
assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("already")), "{:?}", h.app.ui.toast);
}
/// Create Keyword Tag and Edit Keyword Tag refuse a name ending in `*` (at any level) and stay
/// open with what was typed; nothing is created or renamed.
#[test]
fn keyword_tag_dialogs_refuse_a_name_ending_in_an_asterisk() {
let (mut h, _) = keywords_panel();
for typed in ["travel*", "places|rome*"] {
ask(&mut h, "ui.clickWidget", json!({"id": "keywordList:create"}));
ask(&mut h, "ui.text", json!({"text": typed}));
ask(&mut h, "ui.key", json!({"key": "Enter"}));
assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::KeywordTag { name, .. }) if name == typed), "{typed}: {:?}", h.app.ui.dialog);
assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("can't end in “*”")), "{typed}: {:?}", h.app.ui.toast);
assert!(!h.app.session.catalog.has_keyword(typed), "{typed}");
ask(&mut h, "ui.dialog.cancel", json!({}));
}
find(&mut h, "mountains");
ask(&mut h, "ui.clickWidget", json!({"id": "keywordRow:mountains", "count": 2}));
assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::KeywordTag { editing: Some(_), .. })), "{:?}", h.app.ui.dialog);
ask(&mut h, "ui.text", json!({"text": "mountains*"}));
ask(&mut h, "ui.key", json!({"key": "Enter"}));
assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("“mountains*”")), "{:?}", h.app.ui.toast);
assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::KeywordTag { editing: Some(_), .. })), "still open: {:?}", h.app.ui.dialog);
assert!(h.app.session.catalog.has_keyword("mountains") && !h.app.session.catalog.has_keyword("mountains*"));
}
/// The keyword painter refuses a new keyword ending in `*` and says why, without starting to paint;
/// a keyword the library has paints as before.
#[test]
fn the_keyword_painter_refuses_a_name_ending_in_an_asterisk() {
let (mut h, _) = keywords_panel();
for typed in ["travel*", "places|rome*"] {
let r = h.request("engine.execute", json!({"command": "tool.keywordPainter", "params": {"keyword": typed}}), T);
h.settle(SETTLE);
assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("can't end in “*”")), "{typed}: {r}");
assert_eq!(h.app.ui.keyword_painter, None, "{typed}: not painting");
assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("can't end in “*”")), "{typed}: {:?}", h.app.ui.toast);
}
run(&mut h, "tool.keywordPainter", json!({"keyword": "mountains"}));
assert_eq!(h.app.ui.keyword_painter.as_deref(), Some("mountains"));
}
/// A keyword's context menu: create a keyword inside it, edit it, make it where new keywords go
/// (marked in the list), and purge the keywords no photo has.
#[test]