mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 09:19:25 +01:00
Merge pull request #2418 from nledford/perf-search-text
PERF-SEARCH: typing in the library search keeps up on a large library
This commit is contained in:
6 files changed
+781
-46
No files matched your search
+192
-1
@@ -1,7 +1,8 @@
|
||||
//! Lookups derived from the catalog's own data, so questions asked once per photo of a big library
|
||||
//! don't scan a list each time: which stack a photo is in, whether a regular album holds it, which
|
||||
//! photos have their file in a folder, which have a file of a given name, which photos have the same
|
||||
//! content.
|
||||
//! content, the lower-cased text the free-text search reads, and the text a smart album's Text rule
|
||||
//! reads (each made for every photo the first time it is needed for every photo).
|
||||
//!
|
||||
//! They are never saved (the on-disk format is unchanged). Each is built on first use from what
|
||||
//! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts
|
||||
@@ -13,6 +14,7 @@
|
||||
//! is kept up to date, and the photos with a photo's content touched, by the ops that change a
|
||||
//! photo's content as the library sees it, once a rule has built it or while a smart album asks
|
||||
//! about contents ([`Catalog::follows_contents`], [`Catalog::content_moved`]).
|
||||
//! The two texts follow every op that changes a photo's fields, and the photo moving to another place in memory.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::OnceLock;
|
||||
@@ -37,6 +39,10 @@ pub(crate) struct Indexes {
|
||||
/// File name, lower-cased ([`file_name_index_key`]) → the photos whose file has it (same
|
||||
/// states as `folders`).
|
||||
names: OnceLock<HashMap<String, HashSet<PhotoId>>>,
|
||||
/// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search.
|
||||
search: OnceLock<ByPhoto<PhotoText>>,
|
||||
/// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]).
|
||||
rule_text: OnceLock<ByPhoto<RuleText>>,
|
||||
}
|
||||
|
||||
/// A copy builds its own when asked (copies are made to be saved, not queried).
|
||||
@@ -93,6 +99,34 @@ impl Indexes {
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `id` is `p` now (`None`: it is gone): the text kept for it is made again.
|
||||
pub(crate) fn text_changed(&mut self, id: PhotoId, p: Option<&Photo>) {
|
||||
if let Some(m) = self.search.get_mut() {
|
||||
match p {
|
||||
Some(p) => m.insert(id, PhotoText::of(p)),
|
||||
None => m.remove(&id),
|
||||
};
|
||||
}
|
||||
if let Some(m) = self.rule_text.get_mut() {
|
||||
match p {
|
||||
Some(p) => m.insert(id, RuleText::of(p)),
|
||||
None => m.remove(&id),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `id` is about to be changed in place, at `p`: an edit of a photo that others hold
|
||||
/// (`Arc::make_mut`) puts it at another address, which its text follows.
|
||||
pub(crate) fn text_moved(&mut self, id: PhotoId, p: &Photo) {
|
||||
let at = addr(p);
|
||||
if let Some(t) = self.search.get_mut().and_then(|m| m.get_mut(&id)) {
|
||||
t.at = at;
|
||||
}
|
||||
if let Some(t) = self.rule_text.get_mut().and_then(|m| m.get_mut(&id)) {
|
||||
t.at = at;
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `id` had content `old` and has `new` now (`None`: none the library counts).
|
||||
fn content_changed(&mut self, id: PhotoId, old: Option<&str>, new: Option<String>) {
|
||||
let Some(m) = self.contents.get_mut() else { return };
|
||||
@@ -129,6 +163,135 @@ impl Indexes {
|
||||
}
|
||||
}
|
||||
|
||||
/// A map from photos, for a pass over the library that asks about each one in id order.
|
||||
type ByPhoto<T> = HashMap<PhotoId, T, std::hash::BuildHasherDefault<IdHasher>>;
|
||||
|
||||
/// Hashes a photo id as itself in the table's low bits, which is where the table looks first, so
|
||||
/// ids that follow each other sit next to each other and a pass in id order walks it in order
|
||||
/// rather than jumping about (a pass over 300 000 photos spent most of its time on that). The top
|
||||
/// bits, which tag an entry in the table, are mixed so entries still tell each other apart.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IdHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for IdHasher {
|
||||
fn finish(&self) -> u64 {
|
||||
self.0 ^ (self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) & 0xFE00_0000_0000_0000)
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = self.0.rotate_left(8) ^ u64::from(*b);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_u64(&mut self, n: u64) {
|
||||
self.0 = n;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the
|
||||
/// address it was made for. The catalog's own photos (`Arc<Photo>` contents) stay where they are
|
||||
/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]; `repair`
|
||||
/// copies them in bulk and drops every lookup instead);
|
||||
/// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy
|
||||
/// of a photo (a candidate tried with other values) is at another address, so it is read from its
|
||||
/// own fields, never from a text kept for the photo with its id. Only ids and addresses are
|
||||
/// compared; the address is never turned back into a reference. A catalog read from a snapshot
|
||||
/// (and then repaired) or cloned starts with no texts at all: they are made when asked.
|
||||
fn addr(p: &Photo) -> usize {
|
||||
std::ptr::from_ref(p).addr()
|
||||
}
|
||||
|
||||
/// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does
|
||||
/// for each field alone: file name, title, caption, camera, lens, location, format, then each
|
||||
/// keyword, then the name of each person (a named face), separated by NUL. A search word may hold
|
||||
/// white space (a quoted phrase); one that holds NUL is read from the fields one by one
|
||||
/// ([`PhotoText::field_contains`]), so no word runs over a field.
|
||||
pub(crate) struct PhotoText {
|
||||
/// The address of the photo this was made from ([`addr`]).
|
||||
at: usize,
|
||||
text: Box<str>,
|
||||
}
|
||||
|
||||
impl PhotoText {
|
||||
/// The fields of `p` that the text joins before its keywords and people.
|
||||
fn fields(p: &Photo) -> [&String; 7] {
|
||||
[&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]
|
||||
}
|
||||
|
||||
pub(crate) fn of(p: &Photo) -> PhotoText {
|
||||
let fields = Self::fields(p);
|
||||
let people = p.people();
|
||||
// (exact for ASCII, which most text is: the box takes the buffer without copying it)
|
||||
let len = fields
|
||||
.iter()
|
||||
.map(|f| f.len() + 1)
|
||||
.chain(p.meta.keywords.iter().map(|k| k.len() + 1))
|
||||
.chain(people.iter().map(|n| n.len() + 1))
|
||||
.sum::<usize>()
|
||||
.saturating_sub(1);
|
||||
let mut text = String::with_capacity(len);
|
||||
for (i, field) in fields.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
text.push('\0');
|
||||
}
|
||||
push_lowercase(&mut text, field);
|
||||
}
|
||||
for k in p.meta.keywords.iter().map(String::as_str).chain(people) {
|
||||
text.push('\0');
|
||||
push_lowercase(&mut text, k);
|
||||
}
|
||||
PhotoText { at: addr(p), text: text.into_boxed_str() }
|
||||
}
|
||||
|
||||
/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens,
|
||||
/// location, format, a keyword or the name of a person.
|
||||
pub(crate) fn contains(&self, t: &str) -> bool {
|
||||
self.text.contains(t)
|
||||
}
|
||||
|
||||
/// [`PhotoText::contains`] read from `p`'s fields one by one, for a word that holds NUL: the joined text can't tell
|
||||
/// the NUL that separates two fields from one inside a field, and a word never runs over two fields.
|
||||
pub(crate) fn field_contains(p: &Photo, t: &str) -> bool {
|
||||
Self::fields(p)
|
||||
.into_iter()
|
||||
.map(String::as_str)
|
||||
.chain(p.meta.keywords.iter().map(String::as_str))
|
||||
.chain(p.people())
|
||||
.any(|f| f.to_lowercase().contains(t))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
}
|
||||
|
||||
/// Push `s` lower-cased as `str::to_lowercase` gives it, without a temporary string for ASCII.
|
||||
fn push_lowercase(out: &mut String, s: &str) {
|
||||
if s.is_ascii() {
|
||||
let from = out.len();
|
||||
out.push_str(s);
|
||||
if let Some(added) = out.get_mut(from..) {
|
||||
added.make_ascii_lowercase();
|
||||
}
|
||||
} else {
|
||||
out.push_str(&s.to_lowercase());
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo's text for a smart album's Text rule: [`crate::rules::rule_text`].
|
||||
struct RuleText {
|
||||
at: usize,
|
||||
text: Box<str>,
|
||||
}
|
||||
|
||||
impl RuleText {
|
||||
fn of(p: &Photo) -> RuleText {
|
||||
RuleText { at: addr(p), text: crate::rules::rule_text(p).into_boxed_str() }
|
||||
}
|
||||
}
|
||||
|
||||
fn rekey(m: &mut HashMap<String, HashSet<PhotoId>>, id: PhotoId, old: Option<String>, new: Option<String>) {
|
||||
if let Some(k) = old
|
||||
&& let Some(set) = m.get_mut(&k)
|
||||
@@ -232,6 +395,34 @@ impl Catalog {
|
||||
m.get(&album).is_some_and(|s| s.contains(&photo))
|
||||
}
|
||||
|
||||
/// `p`'s lower-cased text for the free-text search, when `p` is this catalog's own photo and the
|
||||
/// text was made. `build`: make it for every photo first when it wasn't (a pass over the whole
|
||||
/// library does; testing one photo shouldn't build it for 300 000).
|
||||
pub(crate) fn search_text(&self, p: &Photo, build: bool) -> Option<&PhotoText> {
|
||||
let m = if build {
|
||||
self.index.search.get_or_init(|| self.photos.values().map(|p| (p.id, PhotoText::of(p))).collect())
|
||||
} else {
|
||||
self.index.search.get()?
|
||||
};
|
||||
m.get(&p.id).filter(|t| t.at == addr(p))
|
||||
}
|
||||
|
||||
/// [`Catalog::search_text`] for a smart album's Text rule: the lower-cased, trimmed text of
|
||||
/// [`crate::rules::rule_text`], made for every photo on first use (a smart album's count or
|
||||
/// view asks for it photo by photo).
|
||||
pub(crate) fn rule_text_of(&self, p: &Photo) -> Option<&str> {
|
||||
let m = self.index.rule_text.get_or_init(|| self.photos.values().map(|p| (p.id, RuleText::of(p))).collect());
|
||||
let t = m.get(&p.id)?;
|
||||
(t.at == addr(p)).then_some(&*t.text)
|
||||
}
|
||||
|
||||
/// Whether the Text rules' text has been made (asking for it makes it, so a test cannot look with
|
||||
/// [`Catalog::rule_text_of`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn rule_text_made(&self) -> bool {
|
||||
self.index.rule_text.get().is_some()
|
||||
}
|
||||
|
||||
/// Content → its photos, by the index (built on first use).
|
||||
fn contents(&self) -> &HashMap<String, Vec<PhotoId>> {
|
||||
self.index.contents.get_or_init(|| {
|
||||
|
||||
@@ -688,7 +688,10 @@ impl Catalog {
|
||||
|
||||
fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> {
|
||||
self.touch(id);
|
||||
self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))
|
||||
let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?;
|
||||
// (`Arc::make_mut` copies a photo others hold: the text kept for it goes with the copy)
|
||||
self.index.text_moved(id, p);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The op being applied changes photo `id` (or adds or removes it).
|
||||
@@ -917,11 +920,13 @@ impl Catalog {
|
||||
self.next_photo = self.next_photo.max(id.0.saturating_add(1));
|
||||
self.index.file_changed(id, None, file_path(&photo.source));
|
||||
self.photos.insert(id, Arc::new(*photo));
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
Op::RemovePhoto { id }
|
||||
}
|
||||
Op::RemovePhoto { id } => {
|
||||
let p = self.photos.remove(&id).ok_or(CatalogError::NoPhoto(id))?;
|
||||
self.index.file_changed(id, file_path(&p.source), None);
|
||||
self.index.text_changed(id, None);
|
||||
// album membership is restored by the batch the engine builds (see `delete_permanently`)
|
||||
Op::AddPhoto { photo: Box::new((*p).clone()) }
|
||||
}
|
||||
@@ -949,7 +954,9 @@ impl Catalog {
|
||||
}
|
||||
Op::SetMeta { id, meta } => {
|
||||
let p = self.photo_mut(id)?;
|
||||
Op::SetMeta { id, meta: Box::new(std::mem::replace(&mut p.meta, *meta)) }
|
||||
let old = std::mem::replace(&mut p.meta, *meta);
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
Op::SetMeta { id, meta: Box::new(old) }
|
||||
}
|
||||
Op::SetDeleted { id, deleted } => {
|
||||
let p = self.photo_mut(id)?;
|
||||
@@ -1137,7 +1144,9 @@ impl Catalog {
|
||||
let p = self.photo_mut(id)?;
|
||||
let old_name = std::mem::replace(&mut p.file_name, file_name);
|
||||
let old_format = format.map(|f| std::mem::replace(&mut p.format, f));
|
||||
Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }
|
||||
let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format };
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
old
|
||||
}
|
||||
Op::SetContent { id, width, height, file_size, content_hash, preview_only, preview_checked } => {
|
||||
let p = self.photo_mut(id)?;
|
||||
@@ -1171,7 +1180,9 @@ impl Catalog {
|
||||
}
|
||||
let p = self.photo_mut(id)?;
|
||||
let old_name = std::mem::replace(&mut p.file_name, file_name);
|
||||
Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) }
|
||||
let old = Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) };
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
old
|
||||
}
|
||||
Op::SetLabelName { label, name } => {
|
||||
let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
||||
@@ -1287,6 +1298,10 @@ impl Catalog {
|
||||
/// wrote).
|
||||
pub fn repair(&mut self) -> Vec<String> {
|
||||
let mut changed = Vec::new();
|
||||
// Photos others hold are copied below (`Arc::make_mut`), which moves them in memory and strands the text kept
|
||||
// for their address ([`index::Indexes`]), and stacks and albums change outside `apply`: nothing derived is
|
||||
// kept across a repair, and the lookups are built again when asked.
|
||||
self.index = index::Indexes::default();
|
||||
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
|
||||
// reference takes its grid's data, and the table is not kept — a live catalog always
|
||||
// stores the data inline, so masks render and serialize without the snapshot's table.
|
||||
@@ -1397,9 +1412,8 @@ impl Catalog {
|
||||
self.next_stack = self.next_stack.max(stack);
|
||||
}
|
||||
if !changed.is_empty() {
|
||||
// stacks and albums changed outside `apply`: the lookups are built again when asked
|
||||
self.index = index::Indexes::default();
|
||||
// (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too)
|
||||
// stacks and albums changed outside `apply`: what was worked out from the albums is made again (the guard of
|
||||
// [`Self::keeps_written_order`] too)
|
||||
self.plans = PlansMemo::default();
|
||||
}
|
||||
changed
|
||||
@@ -1622,6 +1636,8 @@ mod tests_rule_order;
|
||||
#[cfg(test)]
|
||||
mod tests_scale;
|
||||
#[cfg(test)]
|
||||
mod tests_search_text;
|
||||
#[cfg(test)]
|
||||
mod tests_tally;
|
||||
#[cfg(test)]
|
||||
mod tests_torn_append;
|
||||
+48
-17
@@ -152,6 +152,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {
|
||||
pub(crate) struct Prepared {
|
||||
root: Option<String>,
|
||||
only: Option<std::collections::HashSet<PhotoId>>,
|
||||
/// The search words ([`Filter::tokens`]).
|
||||
tokens: Vec<String>,
|
||||
/// A pass over the library, which makes the text kept for each photo when it isn't ([`Catalog::search_text`]).
|
||||
whole: bool,
|
||||
/// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]);
|
||||
/// `None` tests them as written.
|
||||
rules: Option<crate::RuleSet>,
|
||||
@@ -186,8 +190,8 @@ fn unquote(s: &str) -> &str {
|
||||
s.strip_prefix('"').map_or(s, |inner| inner.strip_suffix('"').unwrap_or(inner))
|
||||
}
|
||||
|
||||
fn token_matches(p: &Photo, tok: &str) -> bool {
|
||||
let t = tok.to_lowercase();
|
||||
/// Whether the word `t` (lower-cased) is in `p`, as a field of it or as plain text.
|
||||
fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool {
|
||||
// a token that starts with a quote is a phrase, even with a colon in it
|
||||
if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) {
|
||||
let val = unquote(quoted);
|
||||
@@ -231,20 +235,36 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
|
||||
"name" | "file" => p.file_name.to_lowercase().contains(val),
|
||||
// Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted
|
||||
// (`re:"a b"` is the text `re:a b`).
|
||||
_ if val.len() != quoted.len() => text_matches(p, &format!("{field}:{val}")),
|
||||
_ => text_matches(p, &t),
|
||||
_ if val.len() != quoted.len() => hay.contains(&format!("{field}:{val}")),
|
||||
_ => hay.contains(t),
|
||||
};
|
||||
}
|
||||
text_matches(p, unquote(&t))
|
||||
hay.contains(unquote(t))
|
||||
}
|
||||
|
||||
/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location,
|
||||
/// format, a keyword or the name of a person (a named face) of `p`.
|
||||
fn text_matches(p: &Photo, t: &str) -> bool {
|
||||
let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format];
|
||||
hay.iter().any(|h| h.to_lowercase().contains(t))
|
||||
|| p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t))
|
||||
|| p.people().iter().any(|n| n.to_lowercase().contains(t))
|
||||
/// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its
|
||||
/// own photo and a pass over the library made them ([`Prepared::whole`]), else made when first asked.
|
||||
struct Hay<'a> {
|
||||
p: &'a Photo,
|
||||
cat: &'a Catalog,
|
||||
whole: bool,
|
||||
kept: std::cell::OnceCell<Option<&'a crate::index::PhotoText>>,
|
||||
own: std::cell::OnceCell<crate::index::PhotoText>,
|
||||
}
|
||||
|
||||
impl Hay<'_> {
|
||||
fn text(&self) -> &crate::index::PhotoText {
|
||||
match self.kept.get_or_init(|| self.cat.search_text(self.p, self.whole)) {
|
||||
Some(t) => t,
|
||||
None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `t` (lower-cased) is in one field of the photo ([`crate::index::PhotoText::contains`]): a word with NUL
|
||||
/// is read from the fields themselves, for the joined text separates them with NUL.
|
||||
fn contains(&self, t: &str) -> bool {
|
||||
if t.contains('\0') { crate::index::PhotoText::field_contains(self.p, t) } else { self.text().contains(t) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` has a named face region called `name` (case-insensitive).
|
||||
@@ -356,13 +376,13 @@ impl Filter {
|
||||
|
||||
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
|
||||
// one photo: its rules are tested as written (ordering them would cost more than it saves)
|
||||
self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None })
|
||||
self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: None })
|
||||
}
|
||||
|
||||
/// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once
|
||||
/// (the `only` ids are looked through, not hashed).
|
||||
pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared {
|
||||
Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) }
|
||||
Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: self.ordered_rules(cat) }
|
||||
}
|
||||
|
||||
/// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None`
|
||||
@@ -376,16 +396,23 @@ impl Filter {
|
||||
}
|
||||
|
||||
/// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than
|
||||
/// once per photo: the library folder's identity, the `only` ids as a set and the rules in the
|
||||
/// order to test them.
|
||||
/// once per photo: the library folder's identity, the `only` ids as a set, the search words and the
|
||||
/// rules in the order to test them.
|
||||
pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared {
|
||||
Prepared {
|
||||
root: self.library_root(),
|
||||
only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()),
|
||||
tokens: self.tokens(),
|
||||
whole: true,
|
||||
rules: self.ordered_rules(cat),
|
||||
}
|
||||
}
|
||||
|
||||
/// The search words ([`search_tokens`]), lower-cased (as `str::to_lowercase` does, once per query, not once per photo).
|
||||
fn tokens(&self) -> Vec<String> {
|
||||
search_tokens(&self.text).map(str::to_lowercase).collect()
|
||||
}
|
||||
|
||||
/// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice.
|
||||
fn library_root(&self) -> Option<String> {
|
||||
// as given: a folder may be named with spaces at its edge, and trimming would make it
|
||||
@@ -510,7 +537,11 @@ impl Filter {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
search_tokens(&self.text).all(|tok| token_matches(p, tok))
|
||||
if prepared.tokens.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let hay = Hay { p, cat, whole: prepared.whole, kept: std::cell::OnceCell::new(), own: std::cell::OnceCell::new() };
|
||||
prepared.tokens.iter().all(|t| token_matches(p, t, &hay))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-21
@@ -714,8 +714,37 @@ fn lower(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a Text rule looks through for `p`: its file name, title, caption, camera, lens, location, city,
|
||||
/// state, country, alt text, format, keywords, people and copy name, trimmed and lower-cased.
|
||||
pub(crate) fn rule_text(p: &Photo) -> String {
|
||||
let m = &p.meta;
|
||||
let all = [
|
||||
p.file_name.as_str(),
|
||||
&m.title,
|
||||
&m.caption,
|
||||
&m.camera,
|
||||
&m.lens,
|
||||
&m.location,
|
||||
&m.city,
|
||||
&m.state,
|
||||
&m.country,
|
||||
&m.alt_text,
|
||||
&p.format,
|
||||
&m.keywords.join(" "),
|
||||
&p.people().join(" "),
|
||||
p.copy_name.as_deref().unwrap_or(""),
|
||||
]
|
||||
.join(" ");
|
||||
let all = all.trim();
|
||||
if all.is_ascii() { all.to_ascii_lowercase() } else { all.to_lowercase() }
|
||||
}
|
||||
|
||||
fn text_op(op: &str, have: &str, want: &str) -> bool {
|
||||
let have = have.trim().to_lowercase();
|
||||
text_op_lowered(op, &have.trim().to_lowercase(), want)
|
||||
}
|
||||
|
||||
/// [`text_op`] for a `have` that is trimmed and lower-cased already.
|
||||
fn text_op_lowered(op: &str, have: &str, want: &str) -> bool {
|
||||
match op {
|
||||
"contains" => want.split_whitespace().all(|w| have.contains(w)),
|
||||
"notContains" => !want.split_whitespace().any(|w| have.contains(w)),
|
||||
@@ -1060,26 +1089,10 @@ impl Rule {
|
||||
"keywordCount" => num_op(op, Some(p.keyword_count() as f64), value),
|
||||
"person" => names_op(op, &p.people(), &want),
|
||||
"personCount" => num_op(op, Some(p.people().len() as f64), value),
|
||||
"text" => {
|
||||
let all = [
|
||||
p.file_name.as_str(),
|
||||
&m.title,
|
||||
&m.caption,
|
||||
&m.camera,
|
||||
&m.lens,
|
||||
&m.location,
|
||||
&m.city,
|
||||
&m.state,
|
||||
&m.country,
|
||||
&m.alt_text,
|
||||
&p.format,
|
||||
&m.keywords.join(" "),
|
||||
&p.people().join(" "),
|
||||
p.copy_name.as_deref().unwrap_or(""),
|
||||
]
|
||||
.join(" ");
|
||||
text(&all)
|
||||
}
|
||||
"text" => match cat.rule_text_of(p) {
|
||||
Some(have) => text_op_lowered(op, have, &want),
|
||||
None => text_op_lowered(op, &rule_text(p), &want),
|
||||
},
|
||||
"fileName" => text(&p.file_name),
|
||||
"extension" => text_op(op, p.extension(), want.trim_start_matches('.')),
|
||||
"duration" => num_op(op, p.duration.filter(|d| d.is_finite()), value),
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
//! The free-text search and smart albums' Text rules read a photo's lower-cased text from a cache
|
||||
//! ([`crate::index`]) rather than lower-casing every field of every photo on every keystroke. The
|
||||
//! cache must give the matches the fields give, and follow every edit of a field it holds.
|
||||
|
||||
use lightcraft_meta::{Rect, Region, RegionKind};
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
use crate::index::PhotoText;
|
||||
|
||||
fn photo(id: u64, file: &str) -> Photo {
|
||||
Photo::new(PhotoId(id), Source::Demo { scene: 1 }, file, "JPEG", 60, 40, "2026-01-01T00:00:00")
|
||||
}
|
||||
|
||||
fn face(name: &str) -> Region {
|
||||
Region { rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 }, kind: RegionKind::Face, name: Some(name.into()), description: None }
|
||||
}
|
||||
|
||||
/// Photos whose text is hard on a lower-casing shortcut: Unicode that changes length or depends on
|
||||
/// its neighbours, a word that is only there across two fields, a colon in a plain word.
|
||||
fn library() -> Catalog {
|
||||
let mut photos = Vec::new();
|
||||
let mut p = photo(1, "IMG_0001.JPG");
|
||||
p.rating = 3;
|
||||
p.meta.camera = "Canon EOS R5".into();
|
||||
p.meta.lens = "RF24-70mm F2.8 L".into();
|
||||
p.meta.title = "Trip to Ōsaka".into();
|
||||
p.meta.caption = "Straße am Fluss".into();
|
||||
p.meta.location = "Kyōto".into();
|
||||
p.meta.keywords = vec!["Travel|Italy".into(), "Ὀδυσσεύς".into(), "Kyōto Japan".into()];
|
||||
photos.push(p);
|
||||
let mut p = photo(2, "İstanbul.jpg");
|
||||
p.meta.title = "ΣΊΣΥΦΟΣ".into();
|
||||
p.meta.caption = "Re: 10:30 meeting".into();
|
||||
p.meta.city = "Zürich".into();
|
||||
p.meta.regions = vec![face("Ana Lima")];
|
||||
photos.push(p);
|
||||
let mut p = photo(3, "plain.png");
|
||||
p.format = "PNG".into();
|
||||
photos.push(p);
|
||||
let mut p = photo(4, "abc");
|
||||
p.meta.camera = "def".into();
|
||||
p.meta.title = "Dž dž".into();
|
||||
photos.push(p);
|
||||
let mut p = photo(5, "name:colon.jpg");
|
||||
p.meta.lens = "title:trip".into();
|
||||
p.copy_name = Some("Black and White".into());
|
||||
photos.push(p);
|
||||
let mut c = Catalog::new();
|
||||
for p in photos {
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// How the search read a word before the cache: each field lower-cased alone, for every photo.
|
||||
fn before_text_matches(p: &Photo, t: &str) -> bool {
|
||||
let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format];
|
||||
hay.iter().any(|h| h.to_lowercase().contains(t))
|
||||
|| p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t))
|
||||
|| p.people().iter().any(|n| n.to_lowercase().contains(t))
|
||||
}
|
||||
|
||||
/// [`before_text_matches`] for the words the tests use: plain ones and the fields the cache serves.
|
||||
fn before_matches(p: &Photo, text: &str) -> bool {
|
||||
text.split_whitespace().all(|tok| {
|
||||
let t = tok.to_lowercase();
|
||||
match t.split_once(':') {
|
||||
Some(("camera", val)) => p.meta.camera.to_lowercase().contains(val),
|
||||
Some(("lens", val)) => p.meta.lens.to_lowercase().contains(val),
|
||||
Some(("name" | "file", val)) => p.file_name.to_lowercase().contains(val),
|
||||
Some(("rating", val)) => p.rating.to_string() == val,
|
||||
Some(("kw" | "keyword", val)) => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)),
|
||||
_ => before_text_matches(p, &t),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const QUERIES: &[&str] = &[
|
||||
"img",
|
||||
"IMG_0001",
|
||||
"IMG_0001.JPG",
|
||||
"canon r5",
|
||||
"CANON eos",
|
||||
"ōsaka",
|
||||
"ŌSAKA",
|
||||
"osaka",
|
||||
"straße",
|
||||
"STRASSE",
|
||||
"i̇stanbul",
|
||||
"İSTANBUL",
|
||||
"istanbul",
|
||||
"σίσυφος",
|
||||
"ΣΊΣΥΦΟΣ",
|
||||
"ς",
|
||||
"σ",
|
||||
"ὀδυσσεύς",
|
||||
"travel",
|
||||
"italy",
|
||||
"travel|italy",
|
||||
"kyōto japan",
|
||||
"kyōto",
|
||||
"10:30",
|
||||
"re:",
|
||||
"name:img",
|
||||
"NAME:IMG_0001",
|
||||
"file:plain",
|
||||
"name:",
|
||||
"camera:canon",
|
||||
"camera:r5",
|
||||
"lens:rf24",
|
||||
"lens:",
|
||||
"title:trip",
|
||||
"abcdef",
|
||||
"abc def",
|
||||
"dž",
|
||||
"rating:3 trip",
|
||||
"kw:travel ōsaka",
|
||||
"kw:travel osaka",
|
||||
"png jpeg",
|
||||
"",
|
||||
" ",
|
||||
"zzz",
|
||||
];
|
||||
|
||||
fn shown(c: &Catalog, text: &str) -> Vec<u64> {
|
||||
let f = Filter { text: text.into(), ..Default::default() };
|
||||
let mut ids: Vec<u64> = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
fn expected(c: &Catalog, text: &str) -> Vec<u64> {
|
||||
c.photos().filter(|p| !p.deleted && before_matches(p, text)).map(|p| p.id.0).collect()
|
||||
}
|
||||
|
||||
/// A search finds what the fields hold, whether it asks for one photo at a time, as a pass over the
|
||||
/// library that makes the cache, or one photo after that.
|
||||
#[test]
|
||||
fn search_matches_as_the_fields_do() {
|
||||
let c = library();
|
||||
let mut one_by_one = Vec::new();
|
||||
for q in QUERIES.iter().copied() {
|
||||
let f = Filter { text: q.into(), ..Default::default() };
|
||||
one_by_one.push(c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect::<Vec<_>>());
|
||||
}
|
||||
assert!(c.photos().all(|p| c.search_text(p, false).is_none()), "testing one photo makes no cache for the library");
|
||||
for (q, got) in QUERIES.iter().zip(&one_by_one) {
|
||||
assert_eq!(*got, expected(&c, q), "{q:?}, one photo at a time");
|
||||
}
|
||||
for q in QUERIES.iter().copied() {
|
||||
assert_eq!(shown(&c, q), expected(&c, q), "{q:?}, a pass over the library");
|
||||
}
|
||||
assert!(c.photos().all(|p| c.search_text(p, false).is_some()), "a pass made the cache");
|
||||
for q in QUERIES.iter().copied() {
|
||||
let f = Filter { text: q.into(), ..Default::default() };
|
||||
let got: Vec<u64> = c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect();
|
||||
assert_eq!(got, expected(&c, q), "{q:?}, one photo at a time, with the cache");
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo that isn't the catalog's own (an edit not made yet, a candidate being tried) is read
|
||||
/// from its own fields, not from what the catalog kept for the photo with its id.
|
||||
#[test]
|
||||
fn a_copy_of_a_photo_is_read_as_it_is() {
|
||||
let c = library();
|
||||
let f = Filter { text: "ōsaka".into(), ..Default::default() };
|
||||
assert_eq!(c.count(&f), 1);
|
||||
let mut p = (**c.photo(PhotoId(1)).unwrap()).clone();
|
||||
p.meta.title = "Trip to Nara".into();
|
||||
p.meta.keywords.clear();
|
||||
p.meta.location.clear();
|
||||
assert!(!f.matches(&p, &c), "the catalog's own text says Ōsaka, this copy doesn't");
|
||||
let nara = Filter { text: "nara".into(), ..Default::default() };
|
||||
assert!(nara.matches(&p, &c));
|
||||
assert!(!nara.matches(c.photo(PhotoId(1)).unwrap(), &c));
|
||||
let rule = Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": "contains", "value": "nara"}]}))), ..Default::default() };
|
||||
assert_eq!(c.count(&rule), 0);
|
||||
assert!(rule.matches(&p, &c));
|
||||
}
|
||||
|
||||
fn rules(v: serde_json::Value) -> RuleSet {
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
fn text_rule(op: &str, value: &str) -> Filter {
|
||||
Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": op, "value": value}]}))), ..Default::default() }
|
||||
}
|
||||
|
||||
/// What the cache holds is what a scan of the photos would give it, and every photo's is used.
|
||||
fn assert_current(c: &Catalog) {
|
||||
for p in c.photos() {
|
||||
let kept = c.search_text(p, false).unwrap_or_else(|| panic!("photo {}: no text kept, or kept for another place", p.id.0));
|
||||
let now = PhotoText::of(p);
|
||||
assert_eq!(kept.text(), now.text(), "photo {}", p.id.0);
|
||||
assert_eq!(c.rule_text_of(p), Some(crate::rules::rule_text(p).as_str()), "photo {}: the Text rule's text", p.id.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the caches, as the first search and the first smart album with a Text rule do.
|
||||
fn warm(c: &Catalog) {
|
||||
c.count(&Filter { text: "x".into(), ..Default::default() });
|
||||
c.count(&text_rule("contains", "x"));
|
||||
assert_current(c);
|
||||
}
|
||||
|
||||
fn found(c: &Catalog, text: &str) -> usize {
|
||||
c.count(&Filter { text: text.into(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn found_by_rule(c: &Catalog, text: &str) -> usize {
|
||||
c.count(&text_rule("contains", text))
|
||||
}
|
||||
|
||||
/// An edit of each field that is searched puts the new text in the cache and takes the old one out,
|
||||
/// through the op, its inverse and a batch that fails and is taken back.
|
||||
#[test]
|
||||
fn the_cache_follows_every_field_that_is_searched() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let id = PhotoId(3);
|
||||
let edit = |c: &mut Catalog, set: &dyn Fn(&mut Meta)| {
|
||||
let mut meta = c.photo(id).unwrap().meta.clone();
|
||||
set(&mut meta);
|
||||
c.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap()
|
||||
};
|
||||
type Set = fn(&mut Meta, &str);
|
||||
let fields: [(&str, Set); 6] = [
|
||||
("title", |m, v| m.title = v.into()),
|
||||
("caption", |m, v| m.caption = v.into()),
|
||||
("camera", |m, v| m.camera = v.into()),
|
||||
("lens", |m, v| m.lens = v.into()),
|
||||
("location", |m, v| m.location = v.into()),
|
||||
("keywords", |m, v| m.keywords = vec![v.into()]),
|
||||
];
|
||||
for (n, (field, set)) in fields.into_iter().enumerate() {
|
||||
let word = format!("Zq{n}x");
|
||||
let before = found(&c, &word);
|
||||
let undo = edit(&mut c, &|m| set(m, &word));
|
||||
assert_eq!((before, found(&c, &word)), (0, 1), "{field}: found after the edit");
|
||||
assert_eq!(found_by_rule(&c, &word.to_lowercase()), 1, "{field}: the Text rule");
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found(&c, &word), 0, "{field}: gone after the undo");
|
||||
assert_current(&c);
|
||||
}
|
||||
// the fields only Text rules read
|
||||
let rule_fields: [(&str, Set); 3] =
|
||||
[("city", |m, v| m.city = v.into()), ("state", |m, v| m.state = v.into()), ("country", |m, v| m.country = v.into())];
|
||||
for (n, (field, set)) in rule_fields.into_iter().enumerate() {
|
||||
let word = format!("zr{n}y");
|
||||
let undo = edit(&mut c, &|m| set(m, &word));
|
||||
assert_eq!((found_by_rule(&c, &word), found(&c, &word)), (1, 0), "{field}");
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found_by_rule(&c, &word), 0, "{field}: gone after the undo");
|
||||
}
|
||||
let undo = edit(&mut c, &|m| m.alt_text = "zalt".into());
|
||||
assert_eq!(found_by_rule(&c, "zalt"), 1);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found_by_rule(&c, "zalt"), 0);
|
||||
let undo = edit(&mut c, &|m| m.regions = vec![face("Zed Person")]);
|
||||
assert_eq!(found_by_rule(&c, "zed person"), 1, "a person named on a face");
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found_by_rule(&c, "zed person"), 0);
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_follows_a_file_name_and_a_format() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let id = PhotoId(3);
|
||||
let source = Source::Demo { scene: 1 };
|
||||
let undo = c.apply(Op::SetFile { id, file_name: "Renamed_0042.PNG".into(), source: source.clone() }).unwrap();
|
||||
assert_eq!((found(&c, "renamed_0042"), found(&c, "plain"), found(&c, "name:renamed")), (1, 0, 1));
|
||||
assert_eq!((found_by_rule(&c, "renamed_0042"), found_by_rule(&c, "plain")), (1, 0));
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1));
|
||||
assert_current(&c);
|
||||
|
||||
let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap();
|
||||
assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0));
|
||||
assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0));
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (0, 0, 1));
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// A photo that comes or goes (an import, a virtual copy, a permanent delete and its undo) does
|
||||
/// too, and a virtual copy's name is read by a Text rule.
|
||||
#[test]
|
||||
fn the_cache_follows_photos_that_come_and_go() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut copy = (**c.photo(PhotoId(1)).unwrap()).clone();
|
||||
copy.id = PhotoId(9);
|
||||
copy.copy_of = Some(PhotoId(1));
|
||||
copy.meta = Default::default();
|
||||
copy.copy_name = Some("Zcopy Name".into());
|
||||
copy.file_name = "Zfresh.jpg".into();
|
||||
let undo = c.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap();
|
||||
assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy"), found(&c, "zcopy")), (1, 1, 0));
|
||||
assert_current(&c);
|
||||
let redo = c.apply(undo).unwrap();
|
||||
assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy")), (0, 0));
|
||||
assert_current(&c);
|
||||
c.apply(redo).unwrap();
|
||||
assert_eq!(found(&c, "zfresh"), 1);
|
||||
assert_current(&c);
|
||||
let removed = c.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap();
|
||||
assert_eq!(found(&c, "ōsaka"), 0);
|
||||
assert_current(&c);
|
||||
c.apply(removed).unwrap();
|
||||
assert_eq!(found(&c, "ōsaka"), 1);
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// A batch that fails half way is taken back, and the cache with it.
|
||||
#[test]
|
||||
fn the_cache_follows_a_batch_that_fails() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone();
|
||||
meta.title = "Zbatch title".into();
|
||||
let batch = Op::Batch {
|
||||
ops: vec![
|
||||
Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) },
|
||||
Op::SetFile { id: PhotoId(3), file_name: "Zbatch.png".into(), source: Source::Demo { scene: 1 } },
|
||||
Op::SetFile { id: PhotoId(404), file_name: "gone.png".into(), source: Source::Demo { scene: 1 } },
|
||||
],
|
||||
};
|
||||
assert!(c.apply(batch).is_err());
|
||||
assert_eq!((found(&c, "zbatch"), found_by_rule(&c, "zbatch")), (0, 0));
|
||||
assert_eq!(found(&c, "plain"), 1);
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// An edit of a photo that something else holds (a thumbnail list, an undo step) puts it at another
|
||||
/// place in memory. The cache follows it, so a search isn't left reading every such photo from its fields.
|
||||
#[test]
|
||||
fn the_cache_follows_a_photo_that_others_hold() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let held: Vec<_> = c.photos().cloned().collect();
|
||||
for p in &held {
|
||||
c.apply(Op::SetRating { id: p.id, rating: 5 }).unwrap();
|
||||
}
|
||||
assert!(held.iter().all(|old| !std::ptr::eq(&**old, &**c.photo(old.id).unwrap())), "the edits copied the photos");
|
||||
assert_current(&c);
|
||||
assert_eq!(found(&c, "ōsaka"), 1);
|
||||
c.apply(Op::SetFile { id: PhotoId(2), file_name: "after.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap();
|
||||
assert_current(&c);
|
||||
assert_eq!((found(&c, "after"), found(&c, "istanbul")), (1, 0));
|
||||
}
|
||||
|
||||
/// A catalog read from a snapshot or cloned starts with no cache and builds its own.
|
||||
#[test]
|
||||
fn a_clone_builds_its_own() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut copy = c.clone();
|
||||
assert!(copy.photos().all(|p| copy.search_text(p, false).is_none()));
|
||||
assert_eq!(found(©, "ōsaka"), 1);
|
||||
warm(©);
|
||||
let mut meta = copy.photo(PhotoId(1)).unwrap().meta.clone();
|
||||
meta.title = "Elsewhere".into();
|
||||
copy.apply(Op::SetMeta { id: PhotoId(1), meta: Box::new(meta) }).unwrap();
|
||||
assert_eq!((found(©, "elsewhere"), found(&c, "elsewhere")), (1, 0));
|
||||
c.apply(Op::SetRating { id: PhotoId(1), rating: 1 }).unwrap();
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// `repair` copies the photos others hold (`Arc::make_mut`) without reporting a change, so the cache would
|
||||
/// still keep a text for the address the retained photo has. The retained photo, changed on its own, is
|
||||
/// read from its fields, never from the text kept for the photo with its id.
|
||||
#[test]
|
||||
fn repair_keeps_no_text_for_a_photo_it_copied() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut held = c.photo(PhotoId(1)).unwrap().clone();
|
||||
assert!(c.repair().is_empty(), "a sound catalog");
|
||||
assert!(!std::ptr::eq(&*held, &**c.photo(PhotoId(1)).unwrap()), "repair copied the photo");
|
||||
std::sync::Arc::make_mut(&mut held).meta.title = "Trip to Nara".into();
|
||||
let nara = Filter { text: "nara".into(), ..Default::default() };
|
||||
let osaka = Filter { text: "ōsaka".into(), ..Default::default() };
|
||||
assert!(nara.matches(&held, &c), "the retained photo's own title");
|
||||
assert!(!osaka.matches(&held, &c), "not the title it had");
|
||||
assert!(text_rule("contains", "nara").matches(&held, &c), "the Text rule reads the retained photo's own title");
|
||||
assert!(!text_rule("contains", "ōsaka").matches(&held, &c));
|
||||
warm(&c);
|
||||
assert_eq!((found(&c, "ōsaka"), found(&c, "nara")), (1, 0));
|
||||
}
|
||||
|
||||
/// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each
|
||||
/// photo is read alone (a copy of a photo is not the catalog's own, so the text kept for its id is not used), and what the
|
||||
/// kept text gives.
|
||||
#[test]
|
||||
fn text_rules_match_as_the_fields_do() {
|
||||
let c = library();
|
||||
let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"];
|
||||
let values =
|
||||
["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"];
|
||||
assert!(!c.rule_text_made(), "nothing made the text yet");
|
||||
let after: Vec<Vec<usize>> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect();
|
||||
assert!(c.rule_text_made(), "the first rule asked made the text");
|
||||
let from_the_fields: Vec<Vec<usize>> = every_op
|
||||
.iter()
|
||||
.map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(&Photo::clone(p), &c)).count()).collect())
|
||||
.collect();
|
||||
assert_eq!(from_the_fields, after);
|
||||
assert!(after.iter().flatten().any(|&n| n > 0), "the rules found something");
|
||||
let again: Vec<Vec<usize>> =
|
||||
every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect();
|
||||
assert_eq!(after, again);
|
||||
}
|
||||
|
||||
/// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the
|
||||
/// kept text: it is made there, and an edit shows in the next count.
|
||||
#[test]
|
||||
fn a_smart_album_count_reads_the_kept_text() {
|
||||
let mut c = library();
|
||||
let mut album = Album::new(AlbumId(1), "Osaka");
|
||||
album.smart = Some(Box::new(text_rule("contains", "ōsaka")));
|
||||
c.apply(Op::AddAlbum { album }).unwrap();
|
||||
let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count();
|
||||
assert!(!c.rule_text_made(), "nothing made the text yet");
|
||||
assert_eq!(one_by_one(&c), 1);
|
||||
assert!(c.rule_text_made(), "counting made the text");
|
||||
let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone();
|
||||
meta.title = "Ōsaka again".into();
|
||||
c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap();
|
||||
assert_eq!(one_by_one(&c), 2);
|
||||
}
|
||||
|
||||
/// The kept text holds the names of the people on a photo's faces, and a quoted phrase is read as
|
||||
/// one word that never runs from one field into the next.
|
||||
#[test]
|
||||
fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
assert_eq!(found(&c, "ana"), 1, "a person's name is searched");
|
||||
assert_eq!(found(&c, "\"ana lima\""), 1, "a quoted name is one phrase");
|
||||
assert_eq!(found(&c, "\"lima ana\""), 0);
|
||||
assert_eq!(found(&c, "\"ōsaka straße\""), 0, "a phrase doesn't run from the title into the caption");
|
||||
assert_eq!(found(&c, "\"trip to ōsaka\""), 1, "…but fits inside one field");
|
||||
assert_eq!(found(&c, "\"Kyōto Japan\""), 1, "…or one keyword");
|
||||
// (the photo that has Ana Lima's face)
|
||||
let mut meta = c.photo(PhotoId(2)).unwrap().meta.clone();
|
||||
meta.regions = vec![face("Zed Person")];
|
||||
c.apply(Op::SetMeta { id: PhotoId(2), meta: Box::new(meta) }).unwrap();
|
||||
assert_eq!(found(&c, "\"zed person\""), 1, "a renamed person is found at once");
|
||||
assert_eq!(found(&c, "ana"), 0, "and the old name is gone");
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// A word that holds NUL (a filter's text can) is looked for inside one field, as before the cache: it never matches across
|
||||
/// the NUL the cache puts between two fields, and still matches a field that holds NUL itself.
|
||||
#[test]
|
||||
fn a_word_holding_nul_never_runs_over_two_fields() {
|
||||
let mut c = Catalog::new();
|
||||
let mut p = photo(1, "a");
|
||||
p.meta.title = "b".into();
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
let mut p = photo(2, "c\0d");
|
||||
p.meta.title = "e".into();
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
for text in ["a\0b", "\"a\0b\"", "b\0", "\0e"] {
|
||||
assert_eq!(shown(&c, text), Vec::<u64>::new(), "{text:?}");
|
||||
}
|
||||
assert_eq!(shown(&c, "c\0d"), vec![2], "a field's own NUL is still found");
|
||||
}
|
||||
@@ -929,6 +929,16 @@
|
||||
Before, every rated photo wore the badge bar, which in a mostly rated library made it look like Always. Pick and
|
||||
reject flags and colour labels stay on every thumbnail. Always and Never work as before.
|
||||
|
||||
### Searching a big library keeps up with your typing
|
||||
- Typing in the library search stalls less on a library of hundreds of thousands of photos. The search used to
|
||||
lower-case a photo's file name, title, caption, camera, lens, location, format, every keyword and the names of the
|
||||
people on its faces again for each photo and each letter you typed. It now keeps that text, makes it the first time
|
||||
you search, and keeps it up to date as you edit titles, captions, keywords, people and file names. Smart albums with
|
||||
a Text rule keep their own text the same
|
||||
way, made the first time such an album is counted or shown. Which photos match is unchanged. On a test library of
|
||||
312 000 photos, finding the photos for a word took about 50 ms where it took 120 to 160 ms. The first search makes
|
||||
the text, which takes a fraction of a second and about 32 MB of memory at that size; a Text rule's text is another
|
||||
33 MB. Searches with `camera:`, `lens:` or `name:` gain less (about 70 ms became about 60 ms).
|
||||
### Selection rings you can see in the light themes
|
||||
- The active photo's white outline vanished on Silver and Paper's light grid, and told the active photo from the other
|
||||
selected ones by lightness alone. Now the active photo has a heavier ring (3 pt, with a thin line against the photo so
|
||||
|
||||
Reference in new issue
Block a user