//! The Tidy lists, biggest win first, each with its size (DECISIONS.md//! "Tidy"). **Each photo is in one list only**, so the totals add up and//! "You could free about 52 GB more" is true://!//! 1. **Sets:** the shots a set does not pick.//! 2. **Large videos:** a video of [`LARGE_VIDEO_BYTES`] or more.//! 3. **WhatsApp copies:** saved from WhatsApp; those whose camera original is//! in the library come first ([`copy_of`]).//! 4. **Screenshots:** screenshots and screen recordings.//! 5. **Receipts and documents:** a document found, or Vision's "utility"//! with text.//! 6. **Blurry and dark:** only when seen at `Full` (a small picture hides blur).//! 7. **Exact copies:** the same picture twice (same hash, size and bytes),//! the earliest kept; listed only when there are any.//!//! Never offered: favourites, hidden photos, shared-album photos, the phone's//! trash, a part of another item (RAW+JPEG, an edit), anything he chose to//! keep, anything in the Bin.//!//! **A copy is a copy only while its original is here** (coordinator's rule E)://! present in the library, not in the Bin and not part of the same act. The//! caller passes only such originals to [`copy_of`] and [`exact_copies`], and//! checks again at the moment of an act.use std::collections::HashMap;use serde::Serialize;usesuper::bin::Mark;usesuper::look::{hamming, print_distance, Level, Look};usesuper::size::{self, Size};usesuper::{Item, Kind};pubconst LARGE_VIDEO_BYTES: u64 = 100_000_000;/// Blurred: sharpness under this (variance of the Laplacian, 128 px reduction).pubconst BLUR_MAX: f32 = 0.0008;pubconst DARK_BRIGHTNESS: f32 = 0.10;pubconst DARK_SHARE: f32 = 0.75;/// A WhatsApp copy's original: taken up to 30 days before the copy was saved.pubconst COPY_WINDOW_MS: i64 = 30 * 86_400_000;/// A copy is the same picture re-encoded (WhatsApp shrinks to 1600 px and/// recompresses), which barely moves an 8x8 reduction: so it must match far/// more closely than two shots of one moment do (a set allows 0.55 and 20).pubconst COPY_PRINT_MAX: f32 = 0.25;pubconst COPY_HAMMING_MAX: u32 = 10;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]#[serde(rename_all = "snake_case")]pubenumList {Sets,LargeVideos,WhatsappCopies,Screenshots,Documents,BlurryDark,ExactCopies,}implList {pubconst ALL: [List; 7] = [List::Sets, List::LargeVideos, List::WhatsappCopies, List::Screenshots, List::Documents, List::BlurryDark, List::ExactCopies];pubfn key(self) -> &'static str {matchself {List::Sets => "sets",List::LargeVideos => "large_videos",List::WhatsappCopies => "whatsapp_copies",List::Screenshots => "screenshots",List::Documents => "documents",List::BlurryDark => "blurry_dark",List::ExactCopies => "exact_copies", } }pubfn from_key(key: &str) -> Option<List> {List::ALL.into_iter().find(|l| l.key() == key) }}/// One library item as Tidy sees it.pubstructEntry<'a> {pub item: &'a Item,pub look: Option<&'a Look>,pub mark: Mark,/// In a set and not picked.pub set_offer: bool,/// In a set and picked (never offered by another list).pub set_pick: bool,/// The first of a group of exact copies is kept; the rest are offered.pub exact_copy: bool,}pubfn offerable(item: &Item, mark: &Mark) -> bool { mark.offered() && !item.has("favourite") && !item.has("hidden") && !item.has("cloud_shared") && !item.has("trashed")}/// Saved from WhatsApp. Android: WhatsApp's folders. iPhone: WhatsApp's file/// names, when iOS 27 gives `originalFilename` (unconfirmed until measured on/// a phone, RESEARCH.md §5).pubfn whatsapp(item: &Item) -> bool {letSome(p) = item.path.as_deref() else { returnfalse };let lower = p.to_ascii_lowercase();if lower.contains("whatsapp") {returntrue; }// IMG-20231201-WA0003.jpg / VID-20231201-WA0003.mp4let name = lower.rsplit('/').next().unwrap_or(&lower);let b = name.as_bytes(); b.len() >= 19 && (name.starts_with("img-") || name.starts_with("vid-")) && b[4..12].iter().all(u8::is_ascii_digit) && &name[12..15] == "-wa" && b[15..19].iter().all(u8::is_ascii_digit)}fn document(look: Option<&Look>) -> bool { look.is_some_and(|l| l.platform.document == Some(true) || (l.platform.utility == Some(true) && l.platform.text_chars.unwrap_or(0) >= 40))}fn blurry_or_dark(look: Option<&Look>) -> bool { look.is_some_and(|l| l.level == Level::Full && (l.sharp.is_some_and(|s| s < BLUR_MAX) || (l.brightness < DARK_BRIGHTNESS && l.dark_share > DARK_SHARE)))}/// Which list offers this entry, if any.pubfn list_of(e: &Entry<'_>) -> Option<List> {if !offerable(e.item, &e.mark) || e.set_pick {returnNone; }if e.set_offer {returnSome(List::Sets); }if e.item.kind == Kind::Video && size::of(e.item).bytes >= LARGE_VIDEO_BYTES {returnSome(List::LargeVideos); }if whatsapp(e.item) {returnSome(List::WhatsappCopies); }if e.item.has("screenshot") || e.item.has("screen_recording") {returnSome(List::Screenshots); }if e.item.kind == Kind::Photo && document(e.look) {returnSome(List::Documents); }if e.item.kind == Kind::Photo && blurry_or_dark(e.look) {returnSome(List::BlurryDark); }if e.exact_copy {returnSome(List::ExactCopies); }None}#[derive(Debug, Clone, PartialEq, Serialize)]pubstructSummary {pub list: List,pub count: usize,pub bytes: u64,pub exact: bool,}/// The lists with something in them, biggest first (ties in the fixed order).pubfn summarise(entries: &[Entry<'_>]) -> Vec<Summary> {letmut by: HashMap<List, (usize, Size)> = HashMap::new();for e in entries {ifletSome(l) = list_of(e) {let s = by.entry(l).or_insert((0, Size::ZERO)); s.0 += 1; s.1 = s.1.add(size::of(e.item)); } }letmut out: Vec<Summary> = by.into_iter().map(|(list, (count, s))| Summary { list, count, bytes: s.bytes, exact: s.exact }).collect(); out.sort_by(|a, b| b.bytes.cmp(&a.bytes).then(a.list.cmp(&b.list))); out}/// Groups of exact copies (same difference hash, pixel size and exact bytes),/// each earliest first; the first is the one kept.pubfn exact_copies(items: &[(&Item, Option<&Look>)]) -> Vec<Vec<usize>> {letmut by: HashMap<(u64, u32, u32, u64), Vec<usize>> = HashMap::new();for (i, (item, look)) in items.iter().enumerate() {let (Some(l), Some(b)) = (look, item.bytes) else { continue };if l.level == Level::None {continue; } by.entry((l.dhash, item.width, item.height, b)).or_default().push(i); }letmut out: Vec<Vec<usize>> = by.into_values().filter(|g| g.len() >= 2).collect();for g in out.iter_mut() { g.sort_by_key(|&i| (items[i].0.taken_at_ms, i)); } out.sort(); out}/// The camera original of a WhatsApp copy among `candidates` (not WhatsApp/// items themselves), taken before the copy was saved and within 30 days; the/// closest by print. Answers the candidate's index.pubfn copy_of(copy: (&Item, &Look), candidates: &[(&Item, &Look)]) -> Option<usize> {let (ci, cl) = copy;if cl.level == Level::None {returnNone; } candidates .iter() .enumerate() .filter(|(_, (i, l))| !whatsapp(i) && l.level != Level::None && i.taken_at_ms <= ci.taken_at_ms && ci.taken_at_ms - i.taken_at_ms <= COPY_WINDOW_MS) .filter(|(_, (_, l))| hamming(l.dhash, cl.dhash) <= COPY_HAMMING_MAX) .map(|(k, (_, l))| (k, print_distance(&l.print, &cl.print))) .filter(|(_, d)| *d <= COPY_PRINT_MAX) .min_by(|a, b| a.1.total_cmp(&b.1)) .map(|(k, _)| k)}