Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

IX7: a file kept only in iCloud goes into the Index from Quick Look's thumbnail, never downloaded. cloud.rs asks QLThumbnailGenerator for the 256 px thumbnail iCloud keeps (objc2-quick-look-thumbnailing), after a folder's local files and eight at a time, since iCloud hands them over about one by one; the fast pass writes a waiting batch after a second, so a slow source still lands each picture as it comes. walk.rs lists iCloud's cloud-only files again (937387c3d left them out) and still leaves out and counts other providers' (Google Drive, Dropbox), which aren't shown to answer Quick Look without a download. Measured: 40 fresh cloud-only pictures and videos searchable in 17.9 s (2 a second), all 40 still dataless after; a mixed folder searchable whole, words finding an iCloud picture

shinyobjectz8e86f0a3baa8
diff --git a/Cargo.lock b/Cargo.lock
index cb1a8901..63b5cb0a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11592,6 +11592,20 @@ dependencies = [
"objc2-metal 0.3.2",
]
+[[package]]
+name = "objc2-quick-look-thumbnailing"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac8e00da1ca87ffe3ea8d20981026f013df91072a140432f0f88da9a356d9b3c"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+]
+
[[package]]
name = "objc2-symbols"
version = "0.2.2"
@@ -15826,6 +15840,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"objc2-image-io",
"objc2-photos",
+ "objc2-quick-look-thumbnailing",
"ort",
"raea-io-home",
"raea-sys-ml",
diff --git a/docs/index.feature b/docs/index.feature
index 9b74ce2d..95ff6665 100644
--- a/docs/index.feature
+++ b/docs/index.feature
@@ -93,6 +93,13 @@ Feature: Index: every picture and video you have, searchable in minutes (0.1.5)
and every file was still dataless after; the same 40 again took 0.02 s (Quick Look's cache). So cloud-only
files can go in as a slow second stage after the local ones, about 20 minutes for this Mac's 2,245, with no
download
+ Built 11-15 (cloud.rs): a folder's cloud-only files in iCloud Drive are listed and go in after its local files,
+ from Quick Look's thumbnail, eight asked for at once; a batch waiting on them is written after a second, so
+ each lands as it comes. Measured: 40 fresh cloud-only pictures and videos searchable in 17.9 s (2 a second),
+ all 40 still dataless after; a mixed folder (3 in iCloud, 2 local) searchable whole, and words found one of the
+ iCloud ones. Cloud-only files of other providers (Google Drive, Dropbox under ~/Library/CloudStorage) stay out
+ and counted until each is shown to answer Quick Look without a download. Not yet: marked "in iCloud" on the
+ page, and downloaded only when opened (the original isn't opened from the Index yet)
Scenario: IX8. Google Drive
Then through the Drive connection (raea-api src/connect; Drive is live since 11-11), raea-api lists the Drive's
diff --git a/systems/index/Cargo.toml b/systems/index/Cargo.toml
index a0d6df79..bf881b26 100644
--- a/systems/index/Cargo.toml
+++ b/systems/index/Cargo.toml
@@ -36,3 +36,5 @@ objc2-core-media = "0.3"
objc2-photos = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-app-kit", "PHAsset", "PHFetchResult", "PHFetchOptions", "PHImageManager", "PHPhotoLibrary", "PHAssetResource", "PhotosTypes", "PHObject"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSImage", "NSImageRep", "NSGraphicsContext", "objc2-core-graphics"] }
block2 = "0.6"
+# a file kept only in iCloud (cloud.rs): its picture from Quick Look, without downloading the original
+objc2-quick-look-thumbnailing = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-core-graphics", "QLThumbnailGenerator", "QLThumbnailGenerationRequest", "QLThumbnailRepresentation"] }
diff --git a/systems/index/src/cli.rs b/systems/index/src/cli.rs
index 8878004f..0a4469af 100644
--- a/systems/index/src/cli.rs
+++ b/systems/index/src/cli.rs
@@ -98,7 +98,7 @@ fn add(f: &Flags, home: &std::path::Path) -> Result<()> {
if !f.json {
println!("{}: {} found ({} new), {} searchable, {} failed; {:.0} a second over {:.1} s", root.display(), l.found, l.added, p.done, p.failed, p.per_sec, p.seconds);
if l.cloud > 0 {
- println!(" {} only in iCloud, left out: reading them would download each original", l.cloud);
+ println!(" {} only in the cloud (not iCloud), left out: reading them would download each original", l.cloud);
}
}
}
diff --git a/systems/index/src/cloud.rs b/systems/index/src/cloud.rs
new file mode 100644
index 00000000..05665578
--- /dev/null
+++ b/systems/index/src/cloud.rs
@@ -0,0 +1,47 @@
+//! Files kept only in iCloud (docs/index.feature IX7). A file whose bytes are only in the cloud (SF_DATALESS) lists at
+//! its full size, but reading it downloads the original, so the fast pass takes its picture from Quick Look instead:
+//! the thumbnail iCloud keeps of it, at 256 px, which leaves the file in the cloud (measured 11-15: 40 of 40 still
+//! dataless after). iCloud hands them over about one at a time (1.7 a second the first time, then from Quick Look's
+//! cache), so they go in after the local files. Other providers (Google Drive, Dropbox under ~/Library/CloudStorage)
+//! aren't known to answer Quick Look without a download, so their cloud-only files stay out and are counted.
+
+use crate::apple::{SIDE, squash, write_jpeg};
+use crate::walk::{cloud_only, in_icloud};
+use block2::RcBlock;
+use objc2::AllocAnyThread;
+use objc2_core_foundation::{CFRetained, CGSize};
+use objc2_core_video::CVPixelBuffer;
+use objc2_foundation::{NSError, NSString, NSURL};
+use objc2_quick_look_thumbnailing::{QLThumbnailGenerationRequest, QLThumbnailGenerationRequestRepresentationTypes, QLThumbnailGenerator, QLThumbnailRepresentation};
+use std::path::Path;
+use std::time::Duration;
+
+/// Whether the fast pass takes this file's picture from Quick Look: only in the cloud, and in iCloud
+pub fn wants(path: &Path) -> bool {
+ std::fs::metadata(path).is_ok_and(|m| cloud_only(&m)) && in_icloud(path)
+}
+
+/// A cloud-only file's picture from Quick Look at `SIDE`, its thumbnail written to `thumb`; waits for iCloud's answer
+/// up to a minute
+pub fn picture(path: &Path, thumb: Option<&Path>) -> Result<(CFRetained<CVPixelBuffer>, u32, u32), String> {
+ objc2::rc::autoreleasepool(|_| {
+ let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()));
+ let side = CGSize::new(SIDE as f64, SIDE as f64);
+ let req = unsafe { QLThumbnailGenerationRequest::initWithFileAtURL_size_scale_representationTypes(QLThumbnailGenerationRequest::alloc(), &url, side, 1.0, QLThumbnailGenerationRequestRepresentationTypes::Thumbnail) };
+ let (tx, rx) = std::sync::mpsc::sync_channel(1);
+ let answer = RcBlock::new(move |rep: *mut QLThumbnailRepresentation, err: *mut NSError| {
+ let got = match unsafe { rep.as_ref() } {
+ Some(rep) => Ok(unsafe { rep.CGImage() }),
+ None => Err(unsafe { err.as_ref() }.map(|e| e.localizedDescription().to_string()).unwrap_or_else(|| "no thumbnail".into())),
+ };
+ let _ = tx.send(got);
+ });
+ unsafe { QLThumbnailGenerator::sharedGenerator().generateBestRepresentationForRequest_completionHandler(&req, &answer) };
+ let cg = rx.recv_timeout(Duration::from_secs(60)).map_err(|_| "iCloud didn't answer for its thumbnail".to_string())?.map_err(|e| format!("in iCloud, and Quick Look has no thumbnail of it: {e}"))?;
+ let (w, h) = (objc2_core_graphics::CGImage::width(Some(&cg)) as u32, objc2_core_graphics::CGImage::height(Some(&cg)) as u32);
+ if let Some(t) = thumb {
+ let _ = write_jpeg(&cg, t);
+ }
+ Ok((squash(&cg)?, w, h))
+ })
+}
diff --git a/systems/index/src/lib.rs b/systems/index/src/lib.rs
index 012bb114..48cfa6ed 100644
--- a/systems/index/src/lib.rs
+++ b/systems/index/src/lib.rs
@@ -8,6 +8,8 @@
pub mod apple;
pub mod cli;
#[cfg(target_vendor = "apple")]
+pub mod cloud;
+#[cfg(target_vendor = "apple")]
pub mod frames;
#[cfg(target_vendor = "apple")]
pub mod photos;
@@ -51,8 +53,9 @@ pub struct Progress {
pub seconds: f64,
/// the items finished since the last report, newest last, for the wall of thumbnails
pub newest: Vec<i64>,
- /// pictures and videos the listing left out because their bytes are only in iCloud (walk.rs cloud_only): reading
- /// one would download its original
+ /// pictures and videos the listing left out because their bytes are only in a cloud other than iCloud (walk.rs
+ /// cloud_only; Google Drive's or Dropbox's online-only files): reading one would download its original. iCloud's go
+ /// in from Quick Look (cloud.rs)
pub cloud: u64,
pub stage: &'static str,
}
@@ -102,7 +105,7 @@ pub struct Listed {
pub added: u64,
/// items whose file changed since the last listing: their old rows are gone
pub changed: u64,
- /// items left out as only in iCloud (Progress::cloud)
+ /// items left out as only in a cloud other than iCloud (Progress::cloud)
pub cloud: u64,
}
@@ -120,7 +123,7 @@ pub fn list_photos(store: &mut Store, on: &mut dyn FnMut(&Progress)) -> Result<L
}
/// Lists a source (its kind, root and label) as `each` hands its items over a batch at a time and then says how many
-/// it left out as only in iCloud
+/// it left out as only in the cloud
fn list_source(store: &mut Store, (kind, root, label): (&str, &str, &str), each: impl FnOnce(&mut dyn FnMut(Vec<Found>)) -> Result<u64>, on: &mut dyn FnMut(&Progress)) -> Result<Listed> {
let source = store.source(kind, root, label)?;
let started = Instant::now();
@@ -148,42 +151,60 @@ fn list_source(store: &mut Store, (kind, root, label): (&str, &str, &str), each:
Ok(l)
}
+/// An item's frames read for the fast pass, or the item and why it couldn't be read
+#[cfg(target_vendor = "apple")]
+type Decoded = Result<Vec<apple::Ready>, (i64, String)>;
+
+/// One item's frames: a Photos asset, a picture or a file kept only in iCloud gives one small copy (photos.rs,
+/// apple.rs, cloud.rs), a video file its keyframes (frames.rs)
+#[cfg(target_vendor = "apple")]
+fn frames_of(p: &store::Pending, thumb: &Path) -> Decoded {
+ let file = Path::new(&p.locator);
+ let one = match p.locator.strip_prefix(PHOTOS) {
+ Some(id) => Some(photos::picture(id, Some(thumb))),
+ None if cloud::wants(file) => Some(cloud::picture(file, Some(thumb))),
+ None if p.kind == "video" => None,
+ None => Some(apple::picture(file, Some(thumb))),
+ };
+ let r = match one {
+ Some(r) => r.map(|(px, w, h)| vec![apple::Ready { item: p.id, t: 0.0, px, w, h }]),
+ None => frames::video(file, Some(thumb)).map(|f| f.px.into_iter().map(|(px, t)| apple::Ready { item: p.id, t, px, w: f.w, h: f.h }).collect()),
+ };
+ r.map_err(|e| (p.id, e))
+}
+
/// The fast pass over a source's pictures and videos that wait for it: decoded on every core but two (a video as a few
/// keyframes, frames.rs), embedded about 32 frames at a time on the Neural Engine, each batch's rows written as it
-/// finishes. An item's frames go in one batch, so an item counts as searchable once all of its rows are written.
+/// finishes. An item's frames go in one batch, so an item counts as searchable once all of its rows are written. Files
+/// kept only in iCloud follow the local ones, from Quick Look's thumbnail (cloud.rs), a few asked for at once.
#[cfg(target_vendor = "apple")]
pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, stop: &std::sync::Arc<std::sync::atomic::AtomicBool>, on: &mut dyn FnMut(&Progress)) -> Result<Progress> {
use std::sync::atomic::Ordering;
+ use std::sync::mpsc::RecvTimeoutError;
+ use std::time::Duration;
use rayon::prelude::*;
const BATCH: usize = 32;
- let all: Vec<store::Pending> = store.pending(source, usize::MAX)?;
+ // how many of iCloud's thumbnails are asked for at once
+ const ICLOUD: usize = 8;
+ let (in_cloud, all): (Vec<store::Pending>, Vec<store::Pending>) = store.pending(source, usize::MAX)?.into_iter().partition(|p| !p.locator.starts_with(PHOTOS) && cloud::wants(Path::new(&p.locator)));
let base = store.counts(Some(source))?;
- let (tx, rx) = std::sync::mpsc::sync_channel::<Result<Vec<apple::Ready>, (i64, String)>>(BATCH * 8);
+ let (tx, rx) = std::sync::mpsc::sync_channel::<Decoded>(BATCH * 8);
let thumbs: Vec<PathBuf> = all.iter().map(|p| store.thumb(p.id)).collect();
+ let cloud_thumbs: Vec<PathBuf> = in_cloud.iter().map(|p| store.thumb(p.id)).collect();
let threads = std::thread::available_parallelism().map(|n| n.get().saturating_sub(2).max(2)).unwrap_or(4);
let halt = stop.clone();
let decoder = std::thread::spawn(move || {
- let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().expect("a decoding pool");
- pool.install(|| {
- all.par_iter().zip(thumbs.par_iter()).for_each_with(tx, |tx, (p, thumb)| {
- if halt.load(Ordering::Relaxed) {
- return;
- }
- let file = Path::new(&p.locator);
- // a Photos asset or a picture file gives one small copy; a video file its keyframes
- let one = match p.locator.strip_prefix(PHOTOS) {
- Some(id) => Some(photos::picture(id, Some(thumb))),
- None if p.kind == "video" => None,
- None => Some(apple::picture(file, Some(thumb))),
- };
- let r = match one {
- Some(r) => r.map(|(px, w, h)| vec![apple::Ready { item: p.id, t: 0.0, px, w, h }]),
- None => frames::video(file, Some(thumb)).map(|f| f.px.into_iter().map(|(px, t)| apple::Ready { item: p.id, t, px, w: f.w, h: f.h }).collect()),
- };
- let r = r.map_err(|e| (p.id, e));
- let _ = tx.send(r);
- })
- })
+ let each = |tx: &mut std::sync::mpsc::SyncSender<Decoded>, (p, thumb): (&store::Pending, &PathBuf)| {
+ if !halt.load(Ordering::Relaxed) {
+ let _ = tx.send(frames_of(p, thumb));
+ }
+ };
+ // the local files on every core but two, then iCloud's: each of those waits on the network, so a few at a time
+ let stages = [(threads, all, thumbs, tx.clone()), (ICLOUD, in_cloud, cloud_thumbs, tx)];
+ for (n, items, thumbs, tx) in stages {
+ let pool = rayon::ThreadPoolBuilder::new().num_threads(n).build().expect("a decoding pool");
+ pool.install(|| items.par_iter().zip(thumbs.par_iter()).for_each_with(tx, each));
+ }
});
let started = Instant::now();
let mut last = Instant::now();
@@ -206,22 +227,36 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, sto
batch.clear();
Ok(())
};
- for r in rx {
+ // when the batch's first frame came: a slow source (iCloud's thumbnails) still lands its pictures within a second
+ let mut waiting = Instant::now();
+ loop {
+ let r = match rx.recv_timeout(Duration::from_millis(250)) {
+ Ok(r) => Some(r),
+ Err(RecvTimeoutError::Timeout) => None,
+ Err(RecvTimeoutError::Disconnected) => break,
+ };
if stop.load(Ordering::Relaxed) {
prog.stage = "stopped";
break;
}
match r {
- Ok(item) => {
+ Some(Ok(item)) => {
+ if batch.is_empty() {
+ waiting = Instant::now();
+ }
batch.extend(item);
if batch.len() >= BATCH {
flush(&mut batch, &mut prog, store)?;
}
}
- Err((item, why)) => {
+ Some(Err((item, why))) => {
store.fail(item, &why)?;
prog.failed += 1;
}
+ None => {}
+ }
+ if !batch.is_empty() && waiting.elapsed() >= Duration::from_secs(1) {
+ flush(&mut batch, &mut prog, store)?;
}
if last.elapsed().as_millis() >= 250 {
prog.seconds = started.elapsed().as_secs_f64();
diff --git a/systems/index/src/walk.rs b/systems/index/src/walk.rs
index d0288a45..04dc9e54 100644
--- a/systems/index/src/walk.rs
+++ b/systems/index/src/walk.rs
@@ -38,21 +38,27 @@ fn skipped(name: &str, depth: usize) -> bool {
}
/// Whether a file's bytes are only in the cloud (iCloud Drive with Optimise Mac Storage, or another File Provider):
-/// it lists at its full size, but reading it downloads the original, so the fast pass leaves it until it's on this Mac
+/// it lists at its full size, but reading it downloads the original
#[cfg(target_os = "macos")]
-fn cloud_only(m: &std::fs::Metadata) -> bool {
+pub fn cloud_only(m: &std::fs::Metadata) -> bool {
use std::os::macos::fs::MetadataExt;
const SF_DATALESS: u32 = 0x4000_0000;
m.st_flags() & SF_DATALESS != 0
}
#[cfg(not(target_os = "macos"))]
-fn cloud_only(_: &std::fs::Metadata) -> bool {
+pub fn cloud_only(_: &std::fs::Metadata) -> bool {
false
}
+/// Whether a file lives in iCloud Drive (a link is followed to where it lives): its cloud-only files go in from Quick
+/// Look's thumbnail (cloud.rs) without a download
+pub fn in_icloud(path: &Path) -> bool {
+ cfg!(target_os = "macos") && std::fs::canonicalize(path).is_ok_and(|p| p.to_string_lossy().contains("/Library/Mobile Documents/"))
+}
+
/// Every picture and video under `root`, `on` called with each batch of `every` as they're found; says how many it
-/// found and how many it left out as only in the cloud (cloud_only)
+/// found and how many it left out as only in a cloud other than iCloud (cloud_only: reading one downloads it)
pub fn walk(root: &Path, every: usize, on: &mut dyn FnMut(Vec<Found>)) -> (u64, u64) {
let mut batch = Vec::with_capacity(every);
let (mut n, mut cloud) = (0u64, 0u64);
@@ -71,7 +77,7 @@ pub fn walk(root: &Path, every: usize, on: &mut dyn FnMut(Vec<Found>)) -> (u64,
if m.len() < 1024 {
continue;
}
- if cloud_only(&m) {
+ if cloud_only(&m) && !in_icloud(e.path()) {
cloud += 1;
continue;
}