Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

28.5 KB
Raw Blame
//! The keyword list's commands (Lightroom Classic's Keyword List): create, edit, move and purge
//! keywords, their attributes, and the default parent for new keywords.

use serde_json::json;

use crate::Session;

/// The keyword filter follows a renamed keyword whatever the case it was typed in, also where a
/// letter's case changes its length (ẞ / ß): it used to be cut by bytes, which could land inside
/// a letter and panic.
#[test]
fn the_filter_follows_a_rename_whatever_the_case() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("photo.setMeta", &json!({"ids": [id], "keywords": ["ßßa|é"]})).unwrap();
    s.execute("library.filter", &json!({"keyword": "ßßa|é"})).unwrap();
    s.execute("keyword.rename", &json!({"from": "ẞẞA", "to": "Road"})).unwrap();
    assert_eq!(s.filter.keyword.as_deref(), Some("Road|é"));
    s.execute("keyword.merge", &json!({"from": ["ROAD"], "into": "Weg"})).unwrap();
    assert_eq!(s.filter.keyword.as_deref(), Some("Weg|é"));
}

fn temp_dir(tag: &str) -> std::path::PathBuf {
    let d = std::env::temp_dir().join(format!("lc-keyword-list-{tag}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    d
}

fn keywords_of(s: &Session, id: u64) -> Vec<String> {
    s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().meta.keywords.clone()
}

/// Create Keyword: a name inside a parent, with attributes, given to the selected photos at once,
/// in one undo step; `keyword.info` reads it back. A keyword that exists isn't created again.
#[test]
fn creating_a_keyword_with_attributes_and_the_selection() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("library.select", &json!({"ids": [id]})).unwrap();
    let undo = s.undo.len();
    let r = s
        .execute("keyword.create", &json!({"name": "Weddings", "parent": "Events", "synonyms": ["marriage"], "person": false, "addToSelected": true}))
        .unwrap();
    assert_eq!(r["keyword"], "Events|Weddings", "{r}");
    assert_eq!(s.undo.len(), undo + 1, "one undo step");
    assert!(keywords_of(&s, id).contains(&"Events|Weddings".to_string()));
    let info = s.execute("keyword.info", &json!({"keyword": "events|weddings"})).unwrap();
    assert_eq!(info["path"], "Events|Weddings");
    assert_eq!(info["synonyms"], json!(["marriage"]));
    assert_eq!((info["includeOnExport"].as_bool(), info["listed"].as_bool(), info["count"].as_u64()), (Some(true), Some(true), Some(1)));
    let err = s.execute("keyword.create", &json!({"name": "weddings", "parent": "events"})).unwrap_err().to_string();
    assert!(err.contains("already"), "{err}");
    assert!(s.execute("keyword.info", &json!({"keyword": "lisbon"})).is_err(), "no such keyword");
}

/// "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.
#[test]
fn new_keywords_go_inside_the_default_parent() {
    let dir = temp_dir("default-parent");
    let mut s = Session::new();
    s.open_library(&dir, true).unwrap();
    s.execute("keyword.create", &json!({"name": "Events"})).unwrap();
    s.execute("keyword.setDefaultParent", &json!({"keyword": "events"})).unwrap();
    assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Events"));
    assert_eq!(s.execute("keyword.create", &json!({"name": "Birthdays"})).unwrap()["keyword"], "Events|Birthdays");
    assert_eq!(s.execute("keyword.create", &json!({"name": "Travel", "parent": null})).unwrap()["keyword"], "Travel");
    s.execute("keyword.rename", &json!({"from": "Events", "to": "Occasions"})).unwrap();
    assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Occasions"), "follows the rename");
    s.execute("edit.undo", &json!({})).unwrap();
    assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Events"), "undo takes it back");
    s.execute("edit.redo", &json!({})).unwrap();
    drop(s);
    let mut s = Session::new();
    s.open_library(&dir, false).unwrap();
    assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Occasions"), "kept with the library");
    s.execute("keyword.delete", &json!({"keyword": "occasions"})).unwrap();
    assert_eq!(s.catalog.default_keyword_parent(), None, "gone with its keyword");
    assert_eq!(s.execute("keyword.create", &json!({"name": "Graduations"})).unwrap()["keyword"], "Graduations", "at the top level");
    s.execute("edit.undo", &json!({})).unwrap();
    s.execute("edit.undo", &json!({})).unwrap();
    assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Occasions"), "undoing the delete brings it back");
    s.execute("keyword.setDefaultParent", &json!({"keyword": null})).unwrap();
    assert_eq!(s.catalog.default_keyword_parent(), None);
    assert!(s.execute("keyword.setDefaultParent", &json!({"keyword": "lisbon"})).is_err(), "no such keyword");
    let _ = std::fs::remove_dir_all(&dir);
}

/// Edit Keyword: a new name and attributes in one step; attributes not given keep their values.
#[test]
fn editing_a_keyword_changes_what_it_is_given() {
    let mut s = Session::with_demo();
    s.execute("keyword.create", &json!({"name": "Weddings", "synonyms": ["marriage"]})).unwrap();
    let undo = s.undo.len();
    s.execute("keyword.edit", &json!({"keyword": "weddings", "name": "Marriages", "includeOnExport": false})).unwrap();
    assert_eq!(s.undo.len(), undo + 1);
    let info = s.execute("keyword.info", &json!({"keyword": "Marriages"})).unwrap();
    assert_eq!((info["includeOnExport"].as_bool(), info["synonyms"].clone()), (Some(false), json!(["marriage"])));
    assert!(s.execute("keyword.info", &json!({"keyword": "Weddings"})).is_err());
}

/// Move Keyword: inside another or to the top level. Onto a name that is taken it is refused with
/// a message saying it would merge, unless `merge: true`.
#[test]
fn moving_a_keyword_merges_only_when_asked() {
    let mut s = Session::with_demo();
    let ids: Vec<u64> = s.visible_cloned().iter().take(2).map(|p| p.0).collect();
    s.execute("photo.setMeta", &json!({"ids": [ids[0]], "keywords": ["Rome"]})).unwrap();
    s.execute("photo.setMeta", &json!({"ids": [ids[1]], "keywords": ["Europe|Rome"]})).unwrap();
    let err = s.execute("keyword.move", &json!({"keyword": "rome", "parent": "europe"})).unwrap_err().to_string();
    assert!(err.contains("merge"), "{err}");
    s.execute("keyword.move", &json!({"keyword": "rome", "parent": "europe", "merge": true})).unwrap();
    assert_eq!(keywords_of(&s, ids[0]), ["Europe|Rome"]);
    s.execute("keyword.move", &json!({"keyword": "europe|rome", "parent": null})).unwrap();
    assert_eq!((keywords_of(&s, ids[0]), keywords_of(&s, ids[1])), (vec!["Rome".to_string()], vec!["Rome".to_string()]));
    assert!(s.execute("keyword.move", &json!({"keyword": "rome"})).is_err(), "`parent` must be said, null for the top level");
}

/// Purge Unused Keywords takes off the list the keywords no photo has, in one undo step.
#[test]
fn purging_unused_keywords() {
    let mut s = Session::with_demo();
    s.execute("keyword.create", &json!({"name": "Weddings"})).unwrap();
    let r = s.execute("keyword.purgeUnused", &json!({})).unwrap();
    assert_eq!(r["purged"], 1, "{r}");
    assert!(s.execute("keyword.info", &json!({"keyword": "Weddings"})).is_err());
    s.execute("edit.undo", &json!({})).unwrap();
    assert!(s.execute("keyword.info", &json!({"keyword": "Weddings"})).is_ok());
}

/// Moving a keyword into a parent that doesn't exist yet makes that parent, and the keyword filter
/// follows the keyword there (the grid kept filtering by the old path, and showed nothing).
#[test]
fn the_filter_follows_a_keyword_moved_into_a_new_parent() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("photo.setMeta", &json!({"ids": [id], "keywords": ["Rome"]})).unwrap();
    s.execute("library.filter", &json!({"keyword": "Rome"})).unwrap();
    s.execute("keyword.move", &json!({"keyword": "rome", "parent": "Italy"})).unwrap();
    assert_eq!(keywords_of(&s, id), ["Italy|Rome"]);
    assert_eq!(s.filter.keyword.as_deref(), Some("Italy|Rome"));
}

/// Keywords given to photos are stored cleaned (" beach " is "beach", "Travel | Italy" is
/// "Travel|Italy"), so the list's actions find them; one a photo has already, whatever the case of
/// any letter, isn't added twice.
#[test]
fn keywords_given_to_photos_are_stored_cleaned() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("photo.setMeta", &json!({"ids": [id], "keywords": [" beach ", "Travel | Italy", "Ärzte"]})).unwrap();
    s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": [" sea ", "ÄRZTE", " "]})).unwrap();
    assert_eq!(keywords_of(&s, id), ["beach", "Travel|Italy", "Ärzte", "sea"]);
    s.execute("photo.setMeta", &json!({"ids": [id], "removeKeywords": ["travel | italy"]})).unwrap();
    assert_eq!(keywords_of(&s, id), ["beach", "Ärzte", "sea"]);
    assert!(s.execute("keyword.info", &json!({"keyword": "beach"})).is_ok());
}

/// Rename, merge and delete say how many photos they changed, as before the keyword list: the
/// list's own changes aren't photos.
#[test]
fn keyword_actions_count_the_photos_they_change() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("keyword.create", &json!({"name": "Weddings", "synonyms": ["marriage"]})).unwrap();
    assert_eq!(s.execute("keyword.rename", &json!({"from": "Weddings", "to": "Marriages"})).unwrap()["changed"], 0);
    s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": ["Marriages"]})).unwrap();
    assert_eq!(s.execute("keyword.rename", &json!({"from": "Marriages", "to": "Weddings"})).unwrap()["changed"], 1);
    assert_eq!(s.execute("keyword.delete", &json!({"keyword": "weddings"})).unwrap()["changed"], 1);
}

/// ⌥1–⌥9 take a set's keyword off the selected photos when they all have it, whatever the case of
/// any of its letters (the set has "ärzte", the photos "ÄRZTE" and "ärzte").
#[test]
fn a_set_keyword_toggles_whatever_its_case() {
    let mut s = Session::with_demo();
    let ids: Vec<u64> = s.visible_cloned().iter().take(2).map(|p| p.0).collect();
    s.execute("photo.setMeta", &json!({"ids": [ids[0]], "keywords": ["ÄRZTE"]})).unwrap();
    s.execute("photo.setMeta", &json!({"ids": [ids[1]], "keywords": ["ärzte"]})).unwrap();
    s.execute("keyword.saveSet", &json!({"name": "Clinic", "keywords": ["ärzte"]})).unwrap();
    s.execute("keyword.toggleFromSet", &json!({"index": 1, "ids": ids})).unwrap();
    assert!(ids.iter().all(|id| keywords_of(&s, *id).is_empty()), "taken off both");
}

/// The keyword shortcut (Set Keyword Shortcut, ⌘⌥⇧K) holds the keywords typed with commas
/// between them, each once whatever its case and spelled as the library spells it; ⇧K adds them to
/// the target photos unless every one has them all, and then takes them off. With no keyword
/// shortcut set, ⇧K leaves the photos' keywords as they were.
#[test]
fn the_keyword_shortcut_adds_and_removes_its_keywords() {
    let mut s = Session::with_demo();
    let ids: Vec<u64> = s.visible_cloned().iter().take(2).map(|p| p.0).collect();
    s.execute("photo.setMeta", &json!({"ids": [ids[0]], "keywords": ["beach"]})).unwrap();
    s.execute("photo.setMeta", &json!({"ids": [ids[1]], "keywords": []})).unwrap();
    let r = s.execute("keyword.setShortcut", &json!({"keywords": " Beach , sunset,, BEACH"})).unwrap();
    assert_eq!(r["keywords"], json!(["beach", "sunset"]));
    assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["beach", "sunset"]));
    let r = s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap();
    assert_eq!(r["added"], true, "{r}");
    assert_eq!(keywords_of(&s, ids[0]), ["beach", "sunset"], "a keyword it has isn't added again");
    assert_eq!(keywords_of(&s, ids[1]), ["beach", "sunset"]);
    let r = s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap();
    assert_eq!(r["added"], false, "{r}");
    assert!(ids.iter().all(|id| keywords_of(&s, *id).is_empty()), "every photo had both: taken off");
    // both photos have one of the two keywords: both keywords are added to both photos
    s.execute("photo.setMeta", &json!({"ids": ids, "keywords": ["sunset"]})).unwrap();
    assert_eq!(s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap()["added"], true);
    assert!(ids.iter().all(|id| keywords_of(&s, *id).len() == 2));
    // with nothing typed the keyword shortcut is cleared, and ⇧K leaves the photos' keywords as they were
    assert_eq!(s.execute("keyword.setShortcut", &json!({"keywords": " , "})).unwrap()["keywords"], json!([]));
    let r = s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap();
    assert_eq!(r["changed"], 0, "{r}");
    assert!(ids.iter().all(|id| keywords_of(&s, *id).len() == 2));
}

/// A keyword with a comma in its name stays one keyword when Set Keyword Shortcut… is confirmed
/// with the text it showed; other text is split at its commas.
#[test]
fn the_keyword_shortcut_keeps_a_name_with_a_comma() {
    let mut s = Session::with_demo();
    s.execute("keyword.create", &json!({"name": "Paris, France"})).unwrap();
    s.execute("keyword.create", &json!({"name": "Trips"})).unwrap();
    s.execute("keyword.setShortcut", &json!({"keywords": ["Paris, France", "Trips"]})).unwrap();
    let r = s.execute("keyword.setShortcut", &json!({"keywords": "Paris, France, Trips"})).unwrap();
    assert_eq!(r["keywords"], json!(["Paris, France", "Trips"]), "the text it showed, confirmed as it was");
    let r = s.execute("keyword.setShortcut", &json!({"keywords": "Paris, France"})).unwrap();
    assert_eq!(r["keywords"], json!(["France", "Paris"]), "changed text is split at its commas");
}

/// A `keywords` value that is neither text nor a list of text is an error, and the keyword
/// shortcut keeps its keywords.
#[test]
fn the_keyword_shortcut_refuses_keywords_that_are_not_text() {
    let mut s = Session::with_demo();
    s.execute("keyword.setShortcut", &json!({"keywords": ["beach", "sunset"]})).unwrap();
    for keywords in [json!(7), json!(["beach", 7]), json!({"name": "beach"})] {
        let e = s.execute("keyword.setShortcut", &json!({"keywords": keywords})).unwrap_err().to_string();
        assert!(e.contains("`keywords` must be a string or an array of strings"), "{keywords}: {e}");
        assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["beach", "sunset"]), "{keywords}");
    }
    // parameters that are not an object are an error too, not a request to clear it
    for params in [json!(7), json!("beach"), json!(["beach"])] {
        let e = s.execute("keyword.setShortcut", &params).unwrap_err().to_string();
        assert!(e.contains("parameters must be an object"), "{params}: {e}");
        assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["beach", "sunset"]), "{params}");
    }
}

/// ⇧K with an `ids` or `id` that is not photo ids is an error, with or without a keyword shortcut set.
#[test]
fn the_keyword_shortcut_refuses_targets_that_are_not_photo_ids() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("library.select", &json!({"ids": [id]})).unwrap();
    for shortcut in [json!([]), json!(["beach"])] {
        s.execute("keyword.setShortcut", &json!({"keywords": shortcut})).unwrap();
        for params in [json!({"ids": "x"}), json!({"ids": ["x"]}), json!({"id": "x"})] {
            let e = s.execute("keyword.toggleShortcut", &params).unwrap_err().to_string();
            assert!(e.contains("must be photo ids"), "{shortcut} {params}: {e}");
        }
    }
}

/// The keyword shortcut follows its keywords when they are moved, renamed or merged, and loses one
/// that is deleted; setting it is one undo step, and undo brings a deleted one back.
#[test]
fn the_keyword_shortcut_follows_its_keywords() {
    let mut s = Session::with_demo();
    for name in ["Weddings", "Events", "Trips"] {
        s.execute("keyword.create", &json!({"name": name})).unwrap();
    }
    let undo = s.undo.len();
    s.execute("keyword.setShortcut", &json!({"keywords": ["Weddings", "Trips"]})).unwrap();
    assert_eq!(s.undo.len(), undo + 1, "one undo step");
    let shortcut = |s: &mut Session| s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"].clone();
    s.execute("keyword.move", &json!({"keyword": "Weddings", "parent": "Events"})).unwrap();
    assert_eq!(shortcut(&mut s), json!(["Events|Weddings", "Trips"]), "moved");
    s.execute("keyword.edit", &json!({"keyword": "Events|Weddings", "name": "Marriages"})).unwrap();
    assert_eq!(shortcut(&mut s), json!(["Events|Marriages", "Trips"]), "renamed");
    s.execute("keyword.merge", &json!({"from": ["Trips"], "into": "Events|Marriages"})).unwrap();
    assert_eq!(shortcut(&mut s), json!(["Events|Marriages"]), "merged, and kept once");
    s.execute("keyword.delete", &json!({"keyword": "Events"})).unwrap();
    assert_eq!(shortcut(&mut s), json!([]), "deleted with the keyword it was inside");
    s.execute("edit.undo", &json!({})).unwrap();
    assert_eq!(shortcut(&mut s), json!(["Events|Marriages"]), "undo brings it back");
}

/// A new name in the keyword shortcut goes inside the default parent, as the Keywording box puts
/// it; a keyword the library has stays where it is. The keyword shortcut is kept with the library.
#[test]
fn the_keyword_shortcut_is_kept_with_the_library() {
    let dir = temp_dir("keyword-shortcut");
    let mut s = Session::new();
    s.open_library(&dir, true).unwrap();
    s.execute("keyword.create", &json!({"name": "Travel"})).unwrap();
    s.execute("keyword.create", &json!({"name": "Events"})).unwrap();
    s.execute("keyword.setDefaultParent", &json!({"keyword": "events"})).unwrap();
    let r = s.execute("keyword.setShortcut", &json!({"keywords": ["Travel", "Birthdays"]})).unwrap();
    assert_eq!(r["keywords"], json!(["Events|Birthdays", "Travel"]));
    drop(s);
    let mut s = Session::new();
    s.open_library(&dir, false).unwrap();
    assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["Events|Birthdays", "Travel"]));
    let _ = std::fs::remove_dir_all(&dir);
}

fn set_named(s: &mut Session, name: &str) -> serde_json::Value {
    let sets = s.execute("keyword.sets", &json!({})).unwrap();
    sets["sets"].as_array().unwrap().iter().find(|x| x["name"] == name).cloned().unwrap_or(serde_json::Value::Null)
}

/// Edit Keyword Set: a set's nine slots keep their places, so each keyword stays on its ⌥ key; an
/// empty slot is allowed and does nothing.
#[test]
fn a_keyword_sets_slots_keep_their_places() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("keyword.saveSet", &json!({"name": "Weddings", "keywords": [" ceremony ", "", "reception", ""]})).unwrap();
    assert_eq!(set_named(&mut s, "Weddings")["keywords"], json!(["ceremony", "", "reception"]), "trailing empty slots go");
    let before = keywords_of(&s, id);
    let r = s.execute("keyword.toggleFromSet", &json!({"index": 2, "ids": [id]})).unwrap();
    assert_eq!((r["changed"].as_u64(), keywords_of(&s, id)), (Some(0), before), "⌥2 is empty: nothing");
    s.execute("keyword.toggleFromSet", &json!({"index": 3, "ids": [id]})).unwrap();
    assert!(keywords_of(&s, id).contains(&"reception".to_string()), "⌥3 is reception");
}

/// A set holds each keyword once, whatever its case: a second one leaves its slot empty.
#[test]
fn a_keyword_set_holds_each_keyword_once() {
    let mut s = Session::with_demo();
    s.execute("keyword.saveSet", &json!({"name": "Travel", "keywords": ["Lisbon", "harbour", "LISBON"]})).unwrap();
    assert_eq!(set_named(&mut s, "Travel")["keywords"], json!(["Lisbon", "harbour"]));
}

/// Renaming a set keeps its place among the sets and keeps it current; a name another set has is
/// refused.
#[test]
fn renaming_a_keyword_set_keeps_its_place() {
    let mut s = Session::with_demo();
    s.execute("keyword.saveSet", &json!({"name": "Weddings", "keywords": ["ceremony"]})).unwrap();
    s.execute("keyword.saveSet", &json!({"name": "Travel", "keywords": ["harbour"]})).unwrap();
    s.execute("keyword.useSet", &json!({"name": "Weddings"})).unwrap();
    let r = s.execute("keyword.saveSet", &json!({"name": "Ceremonies", "replace": "weddings", "keywords": ["ceremony", "rings"]})).unwrap();
    let names: Vec<String> = r["sets"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap().to_string()).collect();
    assert_eq!(names, ["Recent Keywords", "Ceremonies", "Travel"]);
    assert_eq!(r["current"], "Ceremonies");
    assert_eq!(r["keywords"], json!(["ceremony", "rings"]));
    let err = s.execute("keyword.saveSet", &json!({"name": "travel", "replace": "Ceremonies", "keywords": []})).unwrap_err().to_string();
    assert!(err.contains("already"), "{err}");
    assert!(s.execute("keyword.saveSet", &json!({"name": "Rings", "replace": "Lisbon", "keywords": []})).is_err(), "no such set");
}

/// Renaming a set without giving its keywords keeps its keywords (not the current set's).
#[test]
fn renaming_a_set_alone_keeps_its_keywords() {
    let mut s = Session::with_demo();
    s.execute("keyword.saveSet", &json!({"name": "Weddings", "keywords": ["ceremony"]})).unwrap();
    s.execute("keyword.saveSet", &json!({"name": "Travel", "keywords": ["harbour"]})).unwrap();
    s.execute("keyword.saveSet", &json!({"name": "Ceremonies", "replace": "Weddings"})).unwrap();
    assert_eq!(set_named(&mut s, "Ceremonies")["keywords"], json!(["ceremony"]));
}

/// A new set (`new: true`, what Edit Set… on Recent Keywords saves) never takes another set's
/// name: saving over it silently is refused.
#[test]
fn a_new_set_doesnt_take_a_sets_name() {
    let mut s = Session::with_demo();
    s.execute("keyword.saveSet", &json!({"name": "Travel", "keywords": ["harbour", "lisbon"]})).unwrap();
    let err = s.execute("keyword.saveSet", &json!({"name": "travel", "new": true, "keywords": ["x"]})).unwrap_err().to_string();
    assert!(err.contains("already"), "{err}");
    assert_eq!(set_named(&mut s, "Travel")["keywords"], json!(["harbour", "lisbon"]), "left as it was");
}

/// Set names match whatever the case of any of their letters, for every set command alike.
#[test]
fn set_names_match_whatever_their_case() {
    let mut s = Session::with_demo();
    s.execute("keyword.saveSet", &json!({"name": "ÉTÉ", "keywords": ["sunset"]})).unwrap();
    s.execute("keyword.useSet", &json!({"name": "Recent Keywords"})).unwrap();
    s.execute("keyword.useSet", &json!({"name": "été"})).unwrap();
    assert_eq!(s.execute("keyword.sets", &json!({})).unwrap()["current"], "ÉTÉ");
    s.execute("keyword.deleteSet", &json!({"name": "été"})).unwrap();
    assert!(set_named(&mut s, "ÉTÉ").is_null(), "deleted");
}

/// Next / Previous Keyword Set (⌥0 / ⌥⇧0) step through the sets in the Keyword Set menu's order,
/// Recent Keywords first, and wrap around at either end; with no saved sets they stay on Recent
/// Keywords.
#[test]
fn next_and_previous_keyword_set_wrap_around_the_sets() {
    let mut s = Session::with_demo();
    let current = |r: serde_json::Value| r["current"].as_str().unwrap_or_default().to_string();
    assert_eq!(current(s.execute("keyword.nextSet", &json!({})).unwrap()), "Recent Keywords", "no sets: nothing to go to");
    assert_eq!(current(s.execute("keyword.previousSet", &json!({})).unwrap()), "Recent Keywords");
    s.execute("keyword.saveSet", &json!({"name": "Weddings", "keywords": ["ceremony"]})).unwrap();
    s.execute("keyword.saveSet", &json!({"name": "Travel", "keywords": ["harbor"]})).unwrap();
    s.execute("keyword.useSet", &json!({"name": "Recent Keywords"})).unwrap();
    let forward: Vec<String> = (0..3).map(|_| current(s.execute("keyword.nextSet", &json!({})).unwrap())).collect();
    assert_eq!(forward, ["Weddings", "Travel", "Recent Keywords"]);
    let back: Vec<String> = (0..3).map(|_| current(s.execute("keyword.previousSet", &json!({})).unwrap())).collect();
    assert_eq!(back, ["Travel", "Weddings", "Recent Keywords"]);
    let r = s.execute("keyword.nextSet", &json!({})).unwrap();
    assert_eq!(r["keywords"], json!(["ceremony"]), "⌥1–⌥9 now apply the set's keywords");
    // a current set that is no longer there counts as Recent Keywords
    s.keyword_set = Some("Gone".into());
    assert_eq!(current(s.execute("keyword.nextSet", &json!({})).unwrap()), "Weddings");
}

/// Export Keywords writes the keyword list file, and names the keywords Capture One's importer
/// refuses (it allows none of ; , < > in a list); without a path it gives the text.
#[test]
fn exporting_keywords_writes_the_list() {
    let dir = temp_dir("export-keywords");
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("photo.setMeta", &json!({"ids": [id], "keywords": ["Places|Lisbon", "fish, chips"]})).unwrap();
    let path = dir.join("keywords.txt");
    let r = s.execute("keyword.export", &json!({"path": path.to_string_lossy()})).unwrap();
    let text = std::fs::read_to_string(&path).unwrap();
    assert!(text.contains("Places\n\tLisbon\n"), "{text}");
    assert!(r["keywords"].as_u64().unwrap() >= 3, "{r}");
    assert_eq!(r["captureOneRefuses"], json!(["fish, chips"]), "{r}");
    assert_eq!(r["unwritable"], json!([]), "{r}");
    let r = s.execute("keyword.export", &json!({})).unwrap();
    assert_eq!(r["text"].as_str(), Some(text.as_str()));
    let _ = std::fs::remove_dir_all(&dir);
}

/// A keyword the format can't hold is left out of the file and named, so the file reads back.
#[test]
fn exporting_keywords_names_what_the_list_cant_hold() {
    let mut s = Session::with_demo();
    let id = s.visible_cloned()[0].0;
    s.execute("photo.setMeta", &json!({"ids": [id], "keywords": ["Travel|[draft]", "Travel|Lisbon"]})).unwrap();
    let before = s.execute("keyword.export", &json!({})).unwrap()["keywords"].as_u64().unwrap();
    // a name starting with a brace is written, counted and checked for Capture One like any other
    s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": ["{draft, notes"]})).unwrap();
    let r = s.execute("keyword.export", &json!({})).unwrap();
    assert_eq!(r["keywords"].as_u64(), Some(before + 1), "{r}");
    assert_eq!(r["captureOneRefuses"], json!(["{draft, notes"]), "{r}");
    assert_eq!(r["unwritable"], json!(["Travel|[draft]"]), "{r}");
    let text = r["text"].as_str().unwrap();
    assert!(text.contains("Travel\n\tLisbon\n") && !text.contains("[draft]"), "{text}");
    s.execute("keyword.import", &json!({"text": text})).unwrap();
}

/// A list saved as UTF-16 (as Windows' Notepad can) says to save it as UTF-8, and text too big to
/// be a keyword list is refused, as a file that big is.
#[test]
fn importing_keywords_refuses_what_it_cant_read() {
    let dir = temp_dir("import-keywords-refused");
    let mut s = Session::with_demo();
    let utf16: Vec<u8> = [0xff, 0xfe].into_iter().chain("Travel\r\n".encode_utf16().flat_map(u16::to_le_bytes)).collect();
    std::fs::write(dir.join("travel.txt"), utf16).unwrap();
    let err = s.execute("keyword.import", &json!({"path": dir.join("travel.txt").to_string_lossy()})).unwrap_err().to_string();
    assert!(err.contains("UTF-16") && err.contains("UTF-8"), "{err}");
    let big = "Travel\n".repeat((17 << 20) / 7);
    let err = s.execute("keyword.import", &json!({"text": big})).unwrap_err().to_string();
    assert!(err.contains("16 MB"), "{err}");
    let _ = std::fs::remove_dir_all(&dir);
}

/// Import Keywords reads a keyword list file (or text) as one undo step and says what it added;
/// a file it can't read says which line, and nothing is taken.
#[test]
fn importing_keywords_reads_a_list() {
    let dir = temp_dir("import-keywords");
    let mut s = Session::with_demo();
    let path = dir.join("vocabulary.utf8");
    std::fs::write(&path, "[Places]\r\n\tPortugal\r\n\t\tLisbon\r\n").unwrap();
    let undo = s.undo.len();
    let r = s.execute("keyword.import", &json!({"path": path.to_string_lossy()})).unwrap();
    assert_eq!((r["added"].as_u64(), r["updated"].as_u64()), (Some(3), Some(0)), "{r}");
    assert_eq!(s.undo.len(), undo + 1);
    assert!(s.catalog.has_keyword("Places|Portugal|Lisbon"));
    let r = s.execute("keyword.import", &json!({"text": "Events\n\t{celebrations}\n"})).unwrap();
    assert_eq!(r["added"], 1);
    let err = s.execute("keyword.import", &json!({"text": "Events\n\t\tWeddings\n"})).unwrap_err().to_string();
    assert!(err.contains("line 2"), "{err}");
    std::fs::write(dir.join("bad.txt"), [0xff, 0xfe, 0x00, 0x41]).unwrap();
    assert!(s.execute("keyword.import", &json!({"path": dir.join("bad.txt").to_string_lossy()})).is_err(), "not UTF-8: refused");
    assert!(s.execute("keyword.import", &json!({})).is_err(), "a path or text");
    let _ = std::fs::remove_dir_all(&dir);
}