//! THE PICTURES SWEEP: the 256 px thumbnails a phone on the personal object//! fetches ahead of its screens.//!//! A grid never fetches (`read.mediaPath`), so a picture is drawn from what//! this phone already holds. On the relay a pack of thumbnails came down on//! the drain's tick (`cotton_client::media::thumbs`); the personal object has//! no packs — it draws any picture at the width it is asked for — so without//! this the Photos grid and the Messages deck filled only as cards came into//! hand, glyphs first.//!//! **What is asked for**: the thumbnail of every photo and every film's poster//! in this phone's copy, and of every picture a message in the copy carries//! (the copy holds only the kept window of messages), newest first, and only//! where the thumbnail is not on this phone. Never an original and never a//! 1600 px rendition: every key asked is a thumbnail key//! (`cotton_core::media::keys`), and the object draws it from the original.//!//! **How**: through `media.ensure`'s own door ([`super::media::land`]), so//! one fetch path, one ledger write and one turn per key; at most//! [`SWEEP_IN_FLIGHT`] at a time and [`SWEEP_FETCHES`] a sweep, the rest the//! next sweep. A fetch that fails is left for the next sweep, which asks the//! same question again: there is no cursor, an arrived thumbnail drops out of//! the list. A key the object answered 404 for is the exception: it waits//! (`cotton_client::media::absent`, held by the client) and `land` refuses it//! with no request until its wait is over, so a picture whose bytes never//! reached the object is not asked after every pass. The sweep stops between fetches when the app's background time//! is running out (`ClientController::slice_has_room`, the box a pass stops//! by), so nothing is left in the air past it.//!//! **When**: after every pass of the sync loop that ended idle, and once when//! `personal.connect` connects the copy (a launch). One sweep at a time; a//! pass that ends while one runs asks for another straight after it.use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Weak};use rusqlite::types::ValueasSqlValue;usecrate::events::{EventBus, EventKind};usecrate::shell::client::ClientController;usesuper::media::{land, media_moved_event, Asker, Landed, Tier};/// How many thumbnails are fetched at once.pubconst SWEEP_IN_FLIGHT: usize = 4;/// How many thumbnails one sweep asks for, newest first; the rest wait for/// the next.pubconst SWEEP_FETCHES: usize = 2_000;/// How many arrivals one `_media` data event says: screens redraw on the/// event, so one per thumbnail would be two thousand redraws a sweep.const TELL_EVERY: usize = 50;/// What one sweep may do.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructCaps {pub fetches: usize,pub in_flight: usize,}implCaps {pubconst SHIPPED: Caps = Caps { fetches: SWEEP_FETCHES, in_flight: SWEEP_IN_FLIGHT };}/// What one sweep did.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructSweepPass {/// Thumbnails the work list named.pub wanted: usize,/// Fetched and now on this phone.pub landed: usize,/// Refused or not answered: asked again next sweep.pub failed: usize,}/// The sweep a phone on the personal object holds (`personal.connect`/// installs it): where it says what arrived, and whether one is running.pubstructPicturesSweep { events: Arc<EventBus>, busy: AtomicBool, again: AtomicBool,}implPicturesSweep {pubfn new(events: Arc<EventBus>) -> Arc<PicturesSweep> {Arc::new(PicturesSweep { events, busy: AtomicBool::new(false), again: AtomicBool::new(false) }) }}/// Start a sweep on its own thread, if this phone holds one; one already/// running is asked to go again when it ends. Never on the caller's stack:/// the after-pass hook is called from the loop's status listener.pubfn kick(client: &Arc<ClientController>) {letSome(sweep) = client.pictures_sweep() else { return };if sweep.busy.swap(true, Ordering::SeqCst) { sweep.again.store(true, Ordering::SeqCst);return; }let held: Weak<ClientController> = Arc::downgrade(client);let running = Arc::clone(&sweep);let spawned = std::thread::Builder::new().name("cotton-pictures-sweep".to_string()).spawn(move || loop { running.again.store(false, Ordering::SeqCst);ifletSome(client) = held.upgrade() {match run(&client, &running.events, Caps::SHIPPED) {Ok(pass) if pass.wanted > 0 => tracing::info!("pictures: {} of {} thumbnails landed, {} asked again next sweep", pass.landed, pass.wanted, pass.failed ),Ok(_) => {}Err(reason) => tracing::warn!("pictures: the sweep could not read this copy — {reason}. The next pass asks again."), } } running.busy.store(false, Ordering::SeqCst);if !running.again.load(Ordering::SeqCst) || running.busy.swap(true, Ordering::SeqCst) {break; } });if spawned.is_err() { sweep.busy.store(false, Ordering::SeqCst); }}/// One sweep, on the caller's thread: the work list, then its fetches,/// [`Caps::in_flight`] at a time.pubfn run(client: &ClientController, events: &EventBus, caps: Caps) -> Result<SweepPass, String> {let wanted = wanted(client, caps.fetches)?;let (landed, failed) = fetch_all(client, events, &wanted, caps.in_flight);Ok(SweepPass { wanted: wanted.len(), landed, failed })}/// Each of `wanted` landed, `in_flight` at a time, the screens told in batches; how many came and how many did not.fn fetch_all(client: &ClientController, events: &EventBus, wanted: &[String], in_flight: usize) -> (usize, usize) {let next = AtomicUsize::new(0);let landed = AtomicUsize::new(0);let failed = AtomicUsize::new(0);let told = AtomicUsize::new(0);let tell = |workspace_id: &str, count: usize| {if count > 0 { events.emit(EventKind::Data, media_moved_event(workspace_id, cotton_client::media::MediaMoved { landed: count, evicted: 0 }), ); } };let workspace = std::sync::Mutex::new(None::<String>); std::thread::scope(|scope| {for _ in0..in_flight.max(1).min(wanted.len()) { scope.spawn(|| loop {// The app's background time running out stops the sweep// between fetches, the way it stops a pass between pages.if !client.slice_has_room() {break; }letSome(key) = wanted.get(next.fetch_add(1, Ordering::SeqCst)) else { break };match land(client, key.clone(), Tier::Best, Asker::Sweep) {Ok(Landed { fetched_into: Some(workspace_id), .. }) => {let count = landed.fetch_add(1, Ordering::SeqCst) + 1;if count.is_multiple_of(TELL_EVERY) { told.fetch_add(TELL_EVERY, Ordering::SeqCst); tell(&workspace_id, TELL_EVERY); } *workspace.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(workspace_id); }Ok(_) => {}Err(refusal) => { failed.fetch_add(1, Ordering::SeqCst); tracing::debug!("pictures: {key} did not come — {} ({})", refusal.message, refusal.code); } } }); } });let landed = landed.into_inner();ifletSome(workspace_id) = workspace.into_inner().unwrap_or_else(|poisoned| poisoned.into_inner()) { tell(&workspace_id, landed - told.into_inner()); } (landed, failed.into_inner())}/// FIRST FILL's pictures (CONTRACT-2, FIRST FILL): at most this many keys a first screen drew, asked before anything/// else.pubconst FIRST_KEYS: usize = 60;/// The keys a first screen handed last, per account (the copy's folder and its credential: another account on this/// phone asks its own), and the accounts whose first run is on.static FIRST_ASKED: std::sync::Mutex<std::collections::BTreeMap<String, Vec<String>>> = std::sync::Mutex::new(std::collections::BTreeMap::new());static FIRST_BUSY: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());/// The keys to ask, in the screen's order: each the 256 px thumbnail a tile draws (`thumb_key_for`), else the key/// itself (a picture with no thumbnail tier, which the tile draws as it is); each once, at most [`FIRST_KEYS`].pub(crate) fn first_chosen(keys: implIntoIterator<Item = String>) -> Vec<String> {letmut seen = std::collections::BTreeSet::new(); keys.into_iter() .map(|key| key.trim().to_string()) .filter(|key| !key.is_empty()) .map(|key| cotton_core::media::keys::thumb_key_for(&key).unwrap_or(key)) .filter(|key| seen.insert(key.clone())) .take(FIRST_KEYS) .collect()}/// Whether a first screen's pictures may be fetched ahead now (HIDDEN 10, L1): only when the shell says which network/// it is on and that it is not in Low Data Mode (`constrained: false`, said, not left out); on Wi-Fi, or on mobile data/// when this phone's films may use it (`films.keeping` `cellular`). A shell that says nothing fetches nothing ahead.pub(crate) fn first_allowed(client: &ClientController, network: Option<&str>, constrained: Option<bool>) -> bool {if constrained != Some(false) {returnfalse; }match network {Some("wifi") => true,Some("cellular") => crate::phone::films::call_keeping(client).is_ok_and(|keeping| keeping["cellular"] == serde_json::Value::Bool(true)), _ => false, }}/// A first screen's pictures, fetched now and before anything else (CONTRACT-2, FIRST FILL: Home's featured backdrop,/// then Carry on's and Recently added's posters, then the other rows'): their 256 px thumbnails, on their own thread,/// [`SWEEP_IN_FLIGHT`] at a time, through the sweep's own door ([`land`], at a tile's tier). Not after an idle pass as/// the sweep is: a first sync's passes are not idle until it is done, and the first screen is drawn long before. A/// key already here costs no request; the same list handed again for the same account, while it runs or after it ran,/// asks nothing. `account` keys the list ([`FIRST_ASKED`]); the caller has checked [`first_allowed`].pubfn first(client: &Arc<ClientController>, account: &str, keys: Vec<String>) {let keys = first_chosen(keys);letSome(sweep) = client.pictures_sweep() else { return }; {letmut asked = FIRST_ASKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner());if keys.is_empty() || asked.get(account) == Some(&keys) {return; }if !FIRST_BUSY.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(account.to_string()) {return; } asked.insert(account.to_string(), keys.clone()); }let held: Weak<ClientController> = Arc::downgrade(client);let account = account.to_string();let done = account.clone();let after = account.clone();let spawned = std::thread::Builder::new().name("cotton-first-pictures".to_string()).spawn(move || {ifletSome(client) = held.upgrade() {let (landed, failed) = fetch_all(&client, &sweep.events, &keys, SWEEP_IN_FLIGHT); tracing::info!("pictures: the first screen's {} pictures, {landed} fetched, {failed} not yet", keys.len());if failed > 0 {// Asked again the next time the screen hands them. FIRST_ASKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&account); } } FIRST_BUSY.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&done); });if spawned.is_err() { FIRST_ASKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&after); FIRST_BUSY.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&after); }}/// The thumbnails this phone's copy names and this phone lacks, newest/// first, at most `limit`: its photos' and films' (the store's own work list,/// `cotton_store::media_thumbs::thumbs_wanted`) and its messages' pictures./// A status's never, on a phone (`cotton_store::keep`).pubfn wanted(client: &ClientController, limit: usize) -> Result<Vec<String>, String> {let device = client.self_device_id(); client.with_file(|file| {let id = file.identity.id();let phone = match &device {Some(device) => cotton_store::keep::is_phone(file.driver, device).map_err(|error| error.to_string())?,None => false, };let statuses = phone.then(|| cotton_core::media::keys::message_media_prefix(id, cotton_store::keep::STATUS_MEDIA_FOLDER));let (photo, video) = cotton_client::media::thumb_key_shapes(id);let page = i64::try_from(limit).unwrap_or(i64::MAX);let pictures = cotton_store::media_thumbs::thumbs_wanted(file.driver, file.workspace_id, &photo, &video, statuses.as_deref(), None, page) .map_err(|error| error.to_string())? .into_iter() .map(|wanted| (wanted.taken_at, wanted.key));letmut messages = Vec::new();for (at, thumb) in message_thumbs_wanted(file.driver, file.workspace_id, page)? {let never = match &device {Some(device) => cotton_store::keep::status_bytes_never(file.driver, device, &thumb).map_err(|error| error.to_string())?,None => false, };if !never { messages.push((at, thumb)); } }let declared = declared_pictures(file.driver, file.workspace_id)?;letmut all: Vec<(String, String)> = pictures.chain(messages).collect();for (at, original) in declared {letSome(thumb) = cotton_core::media::keys::thumb_key_for(&original) else { continue };let held = cotton_store::media_ledger::media_by_key(file.driver, &thumb).map_err(|error| error.to_string())?;if !held.is_some_and(|row| row.local_path.is_some()) { all.push((at, thumb)); } } all.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));letmut seen = std::collections::HashSet::new();Ok(all.into_iter().filter(|(_, key)| seen.insert(key.clone())).take(limit).map(|(_, key)| key).collect()) })}/// The pictures messages in this copy carry whose thumbnail is not here,/// newest message first: `(sent_at, thumbnail key)`. A picture is what the/// one judge of a message file's kind says it is/// (`cotton_core::messages::preview::media_kind_of`); an SVG is not drawn at/// a size by the object, so it is left as it is.fn message_thumbs_wanted(db: &cotton_store::driver::Driver, workspace_id: &str, limit: i64) -> Result<Vec<(String, String)>, String> {use cotton_core::constants::MessageMediaKind;use cotton_core::media::keys::message_thumb_key_for;// The thumbnail's key is the picture's plus what the ONE builder adds,// split off a built key so the SQL never spells it.let probe = "probe/messages/thread/picture.jpg";let suffix = message_thumb_key_for(probe).and_then(|thumb| thumb.strip_prefix(probe).map(str::to_string)).unwrap_or_default();let rows = db .all("SELECT m.sent_at AS at, json_extract(entry.value, '$.key') AS key, json_extract(entry.value, '$.contentType') AS content_type, json_extract(entry.value, '$.kind') AS kind FROM cotton_msg_messages m, json_each(m.media) entry WHERE m.workspace_id = ?1 AND m.deleted_at IS NULL AND m.trashed_at IS NULL AND json_type(entry.value) = 'object' AND json_extract(entry.value, '$.key') IS NOT NULL AND NOT EXISTS (SELECT 1 FROM _media held WHERE held.key = json_extract(entry.value, '$.key') || ?2 AND held.local_path IS NOT NULL) ORDER BY m.sent_at DESC, m.id DESC, entry.key", &[SqlValue::Text(workspace_id.to_string()), SqlValue::Text(suffix)], ) .map_err(|error| error.to_string())?;letmut wanted = Vec::new();for row in &rows {if i64::try_from(wanted.len()).unwrap_or(i64::MAX) >= limit {break; }let content_type = row.text("content_type").unwrap_or_default().to_string();letmut entry = cotton_core::messages::MessageMedia::new(row.text("key").unwrap_or_default(), &content_type); entry.kind = row.text("kind").and_then(|kind| serde_json::from_value::<MessageMediaKind>(serde_json::Value::from(kind)).ok());if cotton_core::messages::preview::media_kind_of(&entry) != MessageMediaKind::Image || content_type.eq_ignore_ascii_case("image/svg+xml") {continue; }ifletSome(thumb) = message_thumb_key_for(&entry.key) { wanted.push((row.text("at").unwrap_or_default().to_string(), thumb)); } }Ok(wanted)}/// Photo columns of data-defined tables are pictures too: a film's poster,/// a book's cover, a list's own picture, or a picture in an installed tool./// Read definitions rather than maintaining a second list of tool ids and/// column names. A table this build compiles (a list, `record_group`, kept/// in `cotton_groups`) is read where the storage map keeps it.pub(super) fn declared_pictures(db: &cotton_store::driver::Driver, workspace: &str) -> Result<Vec<(String, String)>, String> {use cotton_core::definitions::ColumnType;let definitions = cotton_tools::definitions::shared_table_definitions_from_driver(db, workspace).map_err(|error| error.to_string())?;let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));let compiled = cotton_client::transport::object::ObjectTables::personal();letmut pictures = Vec::new();for definition in definitions.definitions.iter().filter(|definition| !definition.has_engine() && definition.source.is_none()) {let mapped = compiled.object(&definition.id);let table = match mapped {Some(stored) => stored.store.clone(),None => cotton_core::rules::search_everything::defined_storage(&definition.id), };// A column of the definition, as the table here names it.let ours = |key: &str| -> String { mapped.and_then(|stored| stored.columns.iter().find(|(object, _, _)| object == key)).map_or_else(|| key.to_string(), |(_, ours, _)| ours.clone()) };let columns = db.all(&format!("PRAGMA table_info({})", quote(&table)), &[]).map_err(|error| error.to_string())?;let held = |name: &str| columns.iter().any(|column| column.text("name") == Some(name));if columns.is_empty() || !held("workspace_id") || !held("updated_at") { continue; }letmut conditions = vec!["workspace_id = ?1".to_string()];for column in ["deleted_at", "trashed_at", "archived_at"] {if held(column) { conditions.push(format!("{} IS NULL", quote(column))); } }for column in definition.columns.iter().filter(|column| column.column_type == ColumnType::Photo && held(&ours(&column.key))) {let column = quote(&ours(&column.key));let sql = format!("SELECT updated_at AS at, {column} AS key FROM {} WHERE {} AND {column} IS NOT NULL AND {column} <> ''", quote(&table), conditions.join(" AND "));for row in db.all(&sql, &[SqlValue::Text(workspace.to_string())]).map_err(|error| error.to_string())? {ifletSome(key) = row.text("key") { pictures.push((row.text("at").unwrap_or_default().to_string(), key.to_string())); } } } }Ok(pictures)}