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
99 changes: 98 additions & 1 deletion crates/catalog/src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//! photo has them, or given attributes ([`KeywordInfo`]: synonyms, export options, person). The
//! tree is the keyword list together with the keywords photos carry.

use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -42,6 +42,12 @@ pub fn is_under(k: &str, parent: &str) -> bool {
k == p || k.strip_prefix(&p).is_some_and(|rest| rest.starts_with(SEP))
}

/// The upper levels of a case folded keyword path, each as a prefix of it ending before a `|`
/// (`a|b|c` gives `a`, `a|b`), the way [`is_under`] sees them.
fn upper_levels(folded: &str) -> impl Iterator<Item = &str> {
folded.match_indices(SEP).map(|(i, _)| &folded[..i])
}

/// Replace the `from` prefix of `k` (which [`is_under`] `from`) with `to`. By levels, not bytes:
/// `from` may be written in another case, which can change a letter's length (ẞ / ß).
pub fn reparent(k: &str, from: &str, to: &str) -> String {
Expand Down Expand Up @@ -466,6 +472,97 @@ impl Catalog {
Ok(Op::Batch { ops })
}

/// [`Self::delete_keyword_ops`] for several keywords at once: one batch, so one undo step.
/// Unlike one keyword (which may be absent and then changes nothing), every keyword named must
/// exist, or the whole batch is refused.
pub fn delete_keywords_ops(&self, keywords: &[String]) -> Result<Op> {
let gone: Vec<String> = keywords.iter().map(|k| clean(k)).collect();
if gone.is_empty() || gone.iter().any(String::is_empty) {
return Err(CatalogError::Invalid("empty keyword".into()));
}
// case folded once here, and each candidate once below, not once per pair
let folded: Vec<String> = gone.iter().map(|g| g.to_lowercase()).collect();
let under = |k: &str, p: &str| k == p || k.strip_prefix(p).is_some_and(|rest| rest.starts_with(SEP));
let mut found = vec![false; folded.len()];
let listed = self.keyword_list.values().map(|l| &l.path);
for k in listed.chain(self.photos().filter(|p| p.in_library()).flat_map(|p| p.meta.keywords.iter())) {
let k = k.to_lowercase();
for (hit, p) in found.iter_mut().zip(&folded) {
*hit |= under(&k, p);
}
}
if let Some(i) = found.iter().position(|hit| !hit) {
return Err(CatalogError::Invalid(format!("no keyword “{}”", gone[i])));
}
let goes = |k: &str| {
let k = k.to_lowercase();
folded.iter().any(|p| under(&k, p))
};
let mut ops = self.keyword_ops(|kws| kws.iter().filter(|x| !goes(x)).cloned().collect());
ops.extend(self.list_ops(|list| list.retain(|_, l| !goes(&l.path))));
Ok(Op::Batch { ops })
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// Move several keywords (each with the keywords below it) inside `parent`, or to the top
/// level (`None`), as one batch. Each keeps its name. Of a keyword and one below it only the
/// upper one moves (the lower goes with it). Nothing merges here: a name that is taken where
/// they go ([`CatalogError::KeywordExists`]), or two of them with one name, refuses the whole
/// move. Returns the batch and each move as `(from, to)`.
pub fn move_keywords_ops(&self, keywords: &[String], parent: Option<&str>) -> Result<(Op, Vec<(String, String)>)> {
// paths are case folded once and kept in sets: a batch of thousands stays linear
let mut from: Vec<String> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
for k in keywords {
let path = self.keyword_path(k).ok_or_else(|| CatalogError::Invalid(format!("no keyword “{}”", clean(k))))?;
if seen.insert(path.to_lowercase()) {
from.push(path);
}
}
if from.is_empty() {
return Err(CatalogError::Invalid("no keyword to move".into()));
}
// the upper ones only: a keyword goes when one of its upper levels is named too
from.retain(|f| !upper_levels(&f.to_lowercase()).any(|up| seen.contains(up)));
let upper: HashSet<String> = from.iter().map(|f| f.to_lowercase()).collect();
let parent = parent.map(clean).filter(|p| !p.is_empty()).map(|p| self.keyword_path(&p).unwrap_or(p));
if let Some(p) = &parent {
let p = p.to_lowercase();
if upper.contains(&p) || upper_levels(&p).any(|up| upper.contains(up)) {
return Err(CatalogError::Invalid("can't move a keyword inside itself".into()));
}
}
let mut moves: Vec<(String, String)> = Vec::new();
let mut names: HashSet<String> = HashSet::new();
for f in &from {
let leaf = f.rsplit(SEP).next().unwrap_or(f);
let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}{SEP}{leaf}"));
if !names.insert(to.to_lowercase()) {
return Err(CatalogError::Invalid(format!("two of them are named “{leaf}”: move them one at a time")));
}
moves.push((f.clone(), to));
}
// one that is there already stays; the others must find their name free
moves.retain(|(f, t)| !same(f, t));
if let Some((_, taken)) = moves.iter().find(|(_, t)| self.has_keyword(t)) {
return Err(CatalogError::KeywordExists(taken.clone()));
}
// case folded once here and once per photo keyword, not once per pair
let folded_from: Vec<String> = moves.iter().map(|(f, _)| f.to_lowercase()).collect();
let moved = |k: &str| {
let k_folded = k.to_lowercase();
moves.iter().zip(&folded_from).find_map(|((f, t), f_folded)| {
let under = k_folded == *f_folded || k_folded.strip_prefix(f_folded.as_str()).is_some_and(|rest| rest.starts_with(SEP));
under.then(|| reparent(k, f, t))
})
};
let mut ops = self.keyword_ops(|kws| kws.iter().map(|k| moved(k).unwrap_or_else(|| k.clone())).collect());
// (the moves touch apart parts of the list: each one's listings are its own)
for (f, t) in &moves {
ops.extend(self.list_move_ops(std::slice::from_ref(f), t));
}
Ok((Op::Batch { ops }, moves))
}

/// Merge several keywords (with their children) into `into`.
pub fn merge_keywords_ops(&self, from: &[String], into: &str) -> Result<Op> {
let into = clean(into);
Expand Down
63 changes: 56 additions & 7 deletions crates/engine/src/cmd/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,40 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo {
}
}

/// `keyword.move`'s `parent`: a keyword, or null for the top level.
fn move_parent(p: &Value) -> Result<Option<String>> {
match p.get("parent") {
Some(Value::String(k)) => Ok(Some(k.clone())),
Some(Value::Null) => Ok(None),
_ => Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")),
}
}

/// How many keywords one call may name (far more than a person chooses in a list).
const MAX_KEYWORDS: usize = 10_000;

/// The keywords a command names in `keywords`: a list of them, each once (whatever its case),
/// none empty.
fn keyword_list(p: &Value, command: &str) -> Result<Vec<String>> {
let list = p.get("keywords").and_then(Value::as_array).ok_or_else(|| bad(command, "`keywords` must be a list of keywords"))?;
if list.len() > MAX_KEYWORDS {
return Err(bad(command, format!("`keywords` names more than {MAX_KEYWORDS} keywords")));
}
let mut out: Vec<String> = Vec::new();
let mut seen = std::collections::HashSet::new();
for k in list {
let k =
k.as_str().map(clean).filter(|k| !k.is_empty()).ok_or_else(|| bad(command, format!("`keywords` must be a list of keywords, not {k}")))?;
if seen.insert(k.to_lowercase()) {
out.push(k);
}
}
if out.is_empty() {
return Err(bad(command, "`keywords` names no keyword"));
}
Ok(out)
}

/// The keyword a command names (`keyword`), as the library writes it.
fn named_keyword(s: &Session, p: &Value, command: &str) -> Result<String> {
let k = str_param(p, "keyword").ok_or_else(|| bad(command, "missing `keyword`"))?;
Expand Down Expand Up @@ -493,15 +527,23 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Keyword",
[],
None,
"{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`",
"{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`. Several at once: {keywords: [keyword], parent} as one undo step (of a keyword and one below it the upper one moves); nothing merges then: a name that is taken, or two of them with one name, refuses the whole move",
always,
|s, p| {
if p.get("keywords").is_some_and(|k| !k.is_null()) {
let parent = move_parent(p)?;
let keywords = keyword_list(p, "keyword.move")?;
let (op, moves) = s
.catalog
.move_keywords_ops(&keywords, parent.as_deref())
.map_err(|e| refused("keyword.move", e, ": moving would merge the two (move that one by itself, with merge: true)"))?;
let label = if moves.len() == 1 { "Move Keyword".to_string() } else { format!("Move {} Keywords", moves.len()) };
return commit_keywords(s, &label, op, |k| {
Some(moves.iter().find(|(f, _)| is_under(k, f)).map_or_else(|| k.to_string(), |(f, t)| reparent(k, f, t)))
});
}
let from = named_keyword(s, p, "keyword.move")?;
let parent = match p.get("parent") {
Some(Value::String(k)) => Some(k.clone()),
Some(Value::Null) => None,
_ => return Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")),
};
let parent = move_parent(p)?;
// 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()) {
Expand Down Expand Up @@ -621,9 +663,16 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Keyword",
[],
None,
"{keyword} — removes it (and the keywords below it) from every photo",
"{keyword} — removes it (and the keywords below it) from every photo. Several at once: {keywords: [keyword]}, as one undo step",
always,
|s, p| {
if p.get("keywords").is_some_and(|k| !k.is_null()) {
let keywords = keyword_list(p, "keyword.delete")?;
let op = s.catalog.delete_keywords_ops(&keywords).map_err(|e| bad("keyword.delete", e.to_string()))?;
let gone: Vec<String> = keywords.iter().map(|k| clean(k)).collect();
let label = if gone.len() == 1 { "Delete Keyword".to_string() } else { format!("Delete {} Keywords", gone.len()) };
return commit_keywords(s, &label, op, |f| (!gone.iter().any(|g| is_under(f, g))).then(|| f.to_string()));
}
let k = str_param(p, "keyword").ok_or_else(|| bad("keyword.delete", "missing `keyword`"))?.to_string();
let op = s.catalog.delete_keyword_ops(&k).map_err(|e| bad("keyword.delete", e.to_string()))?;
let c = clean(&k);
Expand Down
Loading
Loading