From c51e63a4a9eb741e42ab3d845314ce178173201f Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 10:04:31 -0600 Subject: [PATCH] S007: file operations engine, freedesktop trash and trash:/// backend Jobs with progress, cancel, conflict and error requests; scan pass, copy_file_range and stream copies, rename moves; per-filesystem trash with .trashinfo, restore and empty; ops smoke example. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + Cargo.lock | 53 ++ Cargo.toml | 1 + .../03 File browsing/S007-file-ops-engine.md | 14 +- Plans/INDEX.md | 2 +- crates/tunal-core/Cargo.toml | 1 + crates/tunal-core/examples/ops.rs | 359 +++++++++ crates/tunal-core/src/lib.rs | 3 + crates/tunal-core/src/local.rs | 6 +- crates/tunal-core/src/ops/mod.rs | 256 ++++++ crates/tunal-core/src/ops/naming.rs | 73 ++ crates/tunal-core/src/ops/run.rs | 745 ++++++++++++++++++ crates/tunal-core/src/registry.rs | 5 +- crates/tunal-core/src/trash.rs | 495 ++++++++++++ crates/tunal-core/src/uri.rs | 31 +- docs/DECISIONS.md | 1 + docs/PROGRESS.md | 7 + 17 files changed, 2032 insertions(+), 21 deletions(-) create mode 100644 crates/tunal-core/examples/ops.rs create mode 100644 crates/tunal-core/src/ops/mod.rs create mode 100644 crates/tunal-core/src/ops/naming.rs create mode 100644 crates/tunal-core/src/ops/run.rs create mode 100644 crates/tunal-core/src/trash.rs diff --git a/CLAUDE.md b/CLAUDE.md index 37d5ec5..1dc3e5c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,6 +84,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~ | `busctl --user call org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop org.freedesktop.portal.Settings ReadOne ss org.freedesktop.appearance accent-color` | inspect portal values | now | | `fc-list` | check bundled/system fonts | now | | `cargo run -p tunal -- --screenshot [--dark] [--size WxH]` (software renderer, offscreen, default 960x640; env `TUNAL_SEED=#rrggbb`, `TUNAL_REDUCED_MOTION=1`) | single-PNG visual check; full state matrix in phase 12 | S003 | +| `XDG_DATA_HOME=/data cargo run -p tunal-core --example ops -- ` (refuses unless XDG_DATA_HOME is inside ``) | job engine + trash smoke run: conflicts, cancel, trash/restore/empty | S007 | | `cargo run -p tunal -- --gallery --screenshot [--dark] --size 1200x1000` (`--gallery` alone opens it in a window) | every control in rest/hover/pressed/focused/disabled; press squeeze not drawn by the software renderer | S004 | Don't assume a tool exists: check first. When your plan creates a tool, add its row here. diff --git a/Cargo.lock b/Cargo.lock index acf54ce..d8b296b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2297,6 +2297,58 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.22.4" @@ -4681,6 +4733,7 @@ dependencies = [ name = "tunal-core" version = "0.1.0" dependencies = [ + "jiff", "mime_guess", "notify-debouncer-mini", ] diff --git a/Cargo.toml b/Cargo.toml index 3deada7..f94d33e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,3 +16,4 @@ material-colors = "0.5" png = "0.18" notify-debouncer-mini = { version = "0.7", default-features = false } mime_guess = "2.0" +jiff = "0.2" diff --git a/Plans/03 File browsing/S007-file-ops-engine.md b/Plans/03 File browsing/S007-file-ops-engine.md index 09ac426..19a335f 100644 --- a/Plans/03 File browsing/S007-file-ops-engine.md +++ b/Plans/03 File browsing/S007-file-ops-engine.md @@ -10,13 +10,13 @@ Background jobs for copy, move, delete, trash, restore, empty trash, mkdir, rena CLAUDE.md §4 (file ops, trash); crates/tunal-core/src/lib.rs and the trait from S006. ## Steps -- [ ] Job model: kinds, `JobHandle` with progress (bytes/files/current name), cancel flag, conflict requests (Skip/Overwrite/Rename/auto-rename + apply to all), error requests (Retry/Skip/Abort; PermissionDenied flagged for elevation). -- [ ] Scan pass for totals; worker queue; copy through `open_read`/`open_write` streams (cross-backend), local fast paths (rename for same-filesystem move, `copy_file_range`); move across devices = copy + delete; keep mtime/mode where supported. -- [ ] Auto-rename naming `name (2).ext`; never copy a folder into itself. -- [ ] Trash per the freedesktop spec: `$XDG_DATA_HOME/Trash` and `$topdir/.Trash-$uid` (mounts from `/proc/self/mountinfo`), `.trashinfo` with encoded path and DeletionDate, collision-free names. -- [ ] `trash:///` backend: list (original path, date), restore (with conflict), delete permanently, empty. -- [ ] Example `--example ops` runs a copy with a conflict and a trash/restore round trip in the scratchpad (with `XDG_DATA_HOME` pointed there). -- [ ] PROGRESS entry, INDEX line, commit `S007: …` +- [x] Job model: kinds, `JobHandle` with progress (bytes/files/current name), cancel flag, conflict requests (Skip/Overwrite/Rename/auto-rename + apply to all), error requests (Retry/Skip/Abort; PermissionDenied flagged for elevation). +- [x] Scan pass for totals; worker queue; copy through `open_read`/`open_write` streams (cross-backend), local fast paths (rename for same-filesystem move, `copy_file_range`); move across devices = copy + delete; keep mtime/mode where supported. +- [x] Auto-rename naming `name (2).ext`; never copy a folder into itself. +- [x] Trash per the freedesktop spec: `$XDG_DATA_HOME/Trash` and `$topdir/.Trash-$uid` (mounts from `/proc/self/mountinfo`), `.trashinfo` with encoded path and DeletionDate, collision-free names. +- [x] `trash:///` backend: list (original path, date), restore (with conflict), delete permanently, empty. +- [x] Example `--example ops` runs a copy with a conflict and a trash/restore round trip in the scratchpad (with `XDG_DATA_HOME` pointed there). +- [x] PROGRESS entry, INDEX line, commit `S007: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 5a14517..a12e833 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -18,7 +18,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 03 File browsing - [x] [S006 — Location layer and local backend](03%20File%20browsing/S006-location-layer.md) · Opus medium -- [ ] [S007 — File operations engine and trash](03%20File%20browsing/S007-file-ops-engine.md) · Opus medium +- [x] [S007 — File operations engine and trash](03%20File%20browsing/S007-file-ops-engine.md) · Opus medium - [ ] [S008 — Folder model and details view](03%20File%20browsing/S008-folder-model-details.md) · Opus medium - [ ] [S009 — Icon grid view and list motion](03%20File%20browsing/S009-grid-and-list-motion.md) · Opus high - [ ] [S010 — Tabs, split view, breadcrumbs, history and places](03%20File%20browsing/S010-navigation-shell.md) · Opus medium diff --git a/crates/tunal-core/Cargo.toml b/crates/tunal-core/Cargo.toml index b303885..6594470 100644 --- a/crates/tunal-core/Cargo.toml +++ b/crates/tunal-core/Cargo.toml @@ -8,3 +8,4 @@ publish.workspace = true [dependencies] notify-debouncer-mini.workspace = true mime_guess.workspace = true +jiff.workspace = true diff --git a/crates/tunal-core/examples/ops.rs b/crates/tunal-core/examples/ops.rs new file mode 100644 index 0000000..1b5f28b --- /dev/null +++ b/crates/tunal-core/examples/ops.rs @@ -0,0 +1,359 @@ +//! Smoke run of the job engine and the trash inside a scratch folder. +//! `XDG_DATA_HOME=/data cargo run -p tunal-core --example ops -- ` +//! (refuses to run unless `XDG_DATA_HOME` is inside ``, so the real trash is never touched). + +use std::ffi::OsStr; +use std::fs; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use tunal_core::ops::{ + ConflictAction, ConflictChoice, ErrorAction, JobEvent, JobId, JobKind, Jobs, Report, +}; +use tunal_core::{Locations, Uri, display_name, trash}; + +/// Makes the event sink slow (like a busy UI) so a cancel lands in the middle of a file. +static SLOW: AtomicBool = AtomicBool::new(false); + +fn main() { + let Some(dir) = std::env::args().nth(1).map(PathBuf::from) else { + eprintln!("usage: XDG_DATA_HOME=/data ops "); + std::process::exit(2); + }; + let dir = std::path::absolute(&dir).expect("absolute dir"); + let data = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from); + let Some(data) = data.filter(|d| d.starts_with(&dir)) else { + eprintln!("ops: XDG_DATA_HOME must point inside {}", dir.display()); + std::process::exit(2); + }; + + let src = dir.join("src"); + let dst = dir.join("dst"); + let _ = fs::remove_dir_all(&src); + let _ = fs::remove_dir_all(&dst); + fs::create_dir_all(src.join("sub")).unwrap(); + fs::create_dir_all(&dst).unwrap(); + fs::write(src.join("a.txt"), "new a\n").unwrap(); + fs::write(src.join("big.bin"), vec![7u8; 24 << 20]).unwrap(); + fs::write(src.join("sub/b.txt"), "b\n").unwrap(); + std::os::unix::fs::symlink("b.txt", src.join("sub/link")).unwrap(); + fs::write(dst.join("a.txt"), "old a\n").unwrap(); + + let (tx, events) = mpsc::channel(); + let jobs = Jobs::new(Locations::with_local(), move |id, event| { + let progress = matches!(event, JobEvent::Progress(_)); + let _ = tx.send((id, event)); + if progress && SLOW.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(150)); + } + }); + let uri = |p: &Path| Uri::from_path(p); + let children = |p: &Path| -> Vec { + let mut v: Vec = fs::read_dir(p) + .unwrap() + .map(|e| Uri::from_path(&e.unwrap().path())) + .collect(); + v.sort_by(|a, b| a.path().cmp(b.path())); + v + }; + + println!("== copy src/* -> dst (a.txt exists: auto-rename)"); + let job = JobKind::Copy { + sources: children(&src), + dest: uri(&dst), + }; + report(run(&jobs, &events, job, ConflictAction::AutoRename)); + + println!("== copy dst/a.txt into dst (same folder: numbered copy)"); + let job = JobKind::Copy { + sources: vec![uri(&dst.join("a.txt"))], + dest: uri(&dst), + }; + report(run(&jobs, &events, job, ConflictAction::Skip)); + + println!("== copy src into src/sub (folder into itself: refused)"); + let job = JobKind::Copy { + sources: vec![uri(&src)], + dest: uri(&src.join("sub")), + }; + report(run(&jobs, &events, job, ConflictAction::Skip)); + + println!("== move src/sub -> dst (dst/sub exists: overwrite merges)"); + let job = JobKind::Move { + sources: vec![uri(&src.join("sub"))], + dest: uri(&dst), + }; + report(run(&jobs, &events, job, ConflictAction::Overwrite)); + + println!("== trash dst/a.txt and dst/big.bin"); + let job = JobKind::Trash(vec![uri(&dst.join("a.txt")), uri(&dst.join("big.bin"))]); + report(run(&jobs, &events, job, ConflictAction::Skip)); + list_trash(); + let info = data.join("Trash/info/a.txt.trashinfo"); + println!( + " {}:\n{}", + info.display(), + fs::read_to_string(&info).unwrap_or_default() + ); + + println!("== restore both (dst/a.txt recreated first: rename on conflict)"); + fs::write(dst.join("a.txt"), "a made after trashing\n").unwrap(); + let items = trash::items().into_iter().map(|i| i.uri).collect(); + report(run( + &jobs, + &events, + JobKind::Restore(items), + ConflictAction::Rename(b"a restored.txt".to_vec()), + )); + list_trash(); + + println!("== trash dst/sub and two files both named dup.txt, then empty the trash"); + let job = JobKind::Trash(vec![uri(&dst.join("sub"))]); + report(run(&jobs, &events, job, ConflictAction::Skip)); + let backend = Locations::with_local().resolve(&trash::root()).unwrap(); + for folder in [trash::root(), trash::root().join(b"home:sub")] { + let mut names = Vec::new(); + backend + .list(&folder, &mut |chunk| { + names.extend(chunk.into_iter().map(|e| e.display_name)); + std::ops::ControlFlow::Continue(()) + }) + .unwrap(); + names.sort(); + println!(" list {folder}: {names:?}"); + } + for text in ["first dup\n", "second dup\n"] { + fs::write(dst.join("dup.txt"), text).unwrap(); + let job = JobKind::Trash(vec![uri(&dst.join("dup.txt"))]); + report(run(&jobs, &events, job, ConflictAction::Skip)); + } + list_trash(); + report(run( + &jobs, + &events, + JobKind::EmptyTrash, + ConflictAction::Skip, + )); + list_trash(); + + println!("== cancel a copy of dst/big.bin into dst/cancel"); + report(run( + &jobs, + &events, + JobKind::Mkdir(uri(&dst.join("cancel"))), + ConflictAction::Skip, + )); + let job = JobKind::Copy { + sources: vec![uri(&dst.join("big.bin"))], + dest: uri(&dst.join("cancel")), + }; + SLOW.store(true, Ordering::Relaxed); + report(run_with(&jobs, &events, job, ConflictAction::Skip, true)); + SLOW.store(false, Ordering::Relaxed); + println!( + " partial file left: {}", + dst.join("cancel/big.bin").exists() + ); + + println!( + "== move (rename) dst/a (3).txt into dst/cancel, rename it, link it, delete dst/cancel" + ); + let job = JobKind::Move { + sources: vec![uri(&dst.join("a (3).txt"))], + dest: uri(&dst.join("cancel")), + }; + report(run(&jobs, &events, job, ConflictAction::Skip)); + let job = JobKind::Rename { + from: uri(&dst.join("cancel/a (3).txt")), + to: uri(&dst.join("cancel/old.txt")), + }; + report(run(&jobs, &events, job, ConflictAction::Skip)); + let job = JobKind::Link { + sources: vec![uri(&dst.join("cancel/old.txt"))], + dest: uri(&dst), + }; + report(run(&jobs, &events, job, ConflictAction::Skip)); + println!(" link: {:?}", fs::read_link(dst.join("old.txt")).ok()); + let _ = fs::remove_file(dst.join("old.txt")); + report(run( + &jobs, + &events, + JobKind::Delete(vec![uri(&dst.join("cancel"))]), + ConflictAction::Skip, + )); + println!(" src/sub after move: exists {}", src.join("sub").exists()); + + println!("== copy an unreadable file next to a readable one (partial failure)"); + fs::write(src.join("locked.txt"), "secret\n").unwrap(); + fs::set_permissions(src.join("locked.txt"), fs::Permissions::from_mode(0o000)).unwrap(); + let job = JobKind::Copy { + sources: vec![uri(&src.join("locked.txt")), uri(&src.join("a.txt"))], + dest: uri(&dst.join("partial")), + }; + report(run( + &jobs, + &events, + JobKind::Mkdir(uri(&dst.join("partial"))), + ConflictAction::Skip, + )); + report(run(&jobs, &events, job, ConflictAction::Skip)); + fs::set_permissions(src.join("locked.txt"), fs::Permissions::from_mode(0o644)).unwrap(); + + println!("== trash and restore a non-UTF-8 name with a space"); + let odd = dst.join(OsStr::from_bytes(b"odd \xff name.txt")); + fs::write(&odd, "odd\n").unwrap(); + report(run( + &jobs, + &events, + JobKind::Trash(vec![uri(&odd)]), + ConflictAction::Skip, + )); + list_trash(); + let info = data + .join("Trash/info") + .join(OsStr::from_bytes(b"odd \xff name.txt.trashinfo")); + println!( + " {}", + fs::read_to_string(&info) + .unwrap_or_default() + .replace('\n', " | ") + ); + let items: Vec = trash::items().into_iter().map(|i| i.uri).collect(); + println!(" copy it out of trash:/// into dst/partial (stream path)"); + let job = JobKind::Copy { + sources: items.clone(), + dest: uri(&dst.join("partial")), + }; + report(run(&jobs, &events, job, ConflictAction::Skip)); + report(run( + &jobs, + &events, + JobKind::Restore(items), + ConflictAction::Skip, + )); + println!(" restored: {}", odd.exists()); + + println!("== final dst"); + let mut names: Vec<_> = fs::read_dir(&dst) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + names.sort(); + for raw in names { + let path = dst.join(&raw); + let name = raw.to_string_lossy(); + if path.is_dir() { + println!( + " {name}/: {} item(s)", + fs::read_dir(&path).unwrap().count() + ); + continue; + } + let content = fs::read(path).unwrap_or_default(); + let shown = if content.len() < 64 { + String::from_utf8_lossy(&content).trim().to_owned() + } else { + format!("{} bytes", content.len()) + }; + println!(" {name}: {shown}"); + } +} + +/// Submits a job, prints its events and answers requests until it finishes. +fn run( + jobs: &Jobs, + events: &mpsc::Receiver<(JobId, JobEvent)>, + kind: JobKind, + on_conflict: ConflictAction, +) -> Report { + run_with(jobs, events, kind, on_conflict, false) +} + +/// Like `run`; with `cancel`, cancels once the first bytes were copied. +fn run_with( + jobs: &Jobs, + events: &mpsc::Receiver<(JobId, JobEvent)>, + kind: JobKind, + on_conflict: ConflictAction, + cancel: bool, +) -> Report { + let handle = jobs.submit(kind); + for (id, event) in events { + if id != handle.id() { + continue; + } + match event { + JobEvent::Progress(p) if cancel && p.done_bytes > 0 => { + println!( + " progress {}/{} bytes -> cancel", + p.done_bytes, p.total_bytes + ); + handle.cancel(); + } + JobEvent::Progress(p) => println!( + " progress {:?}: {}/{} files, {}/{} bytes{}", + p.phase, + p.done_files, + p.total_files, + p.done_bytes, + p.total_bytes, + p.current + .map(|c| format!(", at {}", display_name(c.file_name().unwrap_or(b"/")))) + .unwrap_or_default() + ), + JobEvent::Conflict(request) => { + println!(" conflict: {} exists -> {:?}", request.target, on_conflict); + request.reply.send(ConflictChoice { + action: on_conflict.clone(), + apply_to_all: false, + }); + } + JobEvent::Error(request) => { + println!( + " error at {}: {} (elevation: {}) -> Skip", + request.uri, + request.error, + request.needs_elevation() + ); + request.reply.send(ErrorAction::Skip); + } + JobEvent::Finished(report) => return report, + } + } + panic!("job worker stopped"); +} + +fn report(report: Report) { + let failures: Vec = report + .failures + .iter() + .map(|(uri, e)| format!("{} ({e})", display_name(uri.file_name().unwrap_or(b"/")))) + .collect(); + println!( + " finished: {} files, {} bytes, cancelled {}, failures {failures:?}", + report.done_files, report.done_bytes, report.cancelled + ); +} + +fn list_trash() { + let items = trash::items(); + println!(" trash: {} item(s)", items.len()); + for item in items { + let date = item.deleted.map(age).unwrap_or_else(|| "no date".into()); + println!( + " {} ({}) from {}, deleted {date}", + item.uri, item.entry.display_name, item.original + ); + } +} + +fn age(t: std::time::SystemTime) -> String { + match t.elapsed() { + Ok(age) => format!("{} s ago", age.as_secs()), + Err(_) => "in the future".into(), + } +} diff --git a/crates/tunal-core/src/lib.rs b/crates/tunal-core/src/lib.rs index a1865d8..f1c695e 100644 --- a/crates/tunal-core/src/lib.rs +++ b/crates/tunal-core/src/lib.rs @@ -5,7 +5,9 @@ mod error; mod local; mod location; pub mod mime; +pub mod ops; mod registry; +pub mod trash; mod uri; pub use entry::{Entry, FileType, Kind}; @@ -13,4 +15,5 @@ pub use error::{Error, Result}; pub use local::LocalLocation; pub use location::{Capabilities, ListSink, Location, Watch, WatchCallback, WatchEvent, WriteMode}; pub use registry::Locations; +pub use trash::{TRASH, TrashLocation}; pub use uri::{FILE, Uri, display_name}; diff --git a/crates/tunal-core/src/local.rs b/crates/tunal-core/src/local.rs index f0148a3..9f73b30 100644 --- a/crates/tunal-core/src/local.rs +++ b/crates/tunal-core/src/local.rs @@ -32,7 +32,7 @@ impl Location for LocalLocation { fn capabilities(&self) -> Capabilities { Capabilities { write: true, - trash: false, + trash: true, symlink: true, watch: true, permissions: true, @@ -104,6 +104,10 @@ impl Location for LocalLocation { } } + fn trash(&self, uri: &Uri) -> Result<()> { + crate::trash::trash_path(&local_path(uri)?) + } + fn symlink(&self, link: &Uri, target: &[u8]) -> Result<()> { let target = PathBuf::from(OsString::from_vec(target.to_vec())); Ok(std::os::unix::fs::symlink(target, local_path(link)?)?) diff --git a/crates/tunal-core/src/ops/mod.rs b/crates/tunal-core/src/ops/mod.rs new file mode 100644 index 0000000..72eb509 --- /dev/null +++ b/crates/tunal-core/src/ops/mod.rs @@ -0,0 +1,256 @@ +//! Background file operations across any backends: copy, move, delete, trash, +//! restore, empty trash, mkdir, rename and link, with progress, cancel, +//! conflict and error requests. + +mod naming; +mod run; + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; + +use crate::{Entry, Error, Locations, Uri}; + +pub use naming::{auto_rename, is_inside, numbered}; + +pub type JobId = u64; + +/// What a job does. Sources and targets may live on any registered backend. +#[derive(Clone, Debug)] +pub enum JobKind { + /// Copies each source into the folder `dest`. + Copy { + sources: Vec, + dest: Uri, + }, + /// Moves each source into the folder `dest` (rename when possible, else copy + delete). + Move { + sources: Vec, + dest: Uri, + }, + /// Deletes permanently, folders recursively. + Delete(Vec), + Trash(Vec), + /// Puts `trash:///` items back at their original paths. + Restore(Vec), + EmptyTrash, + Mkdir(Uri), + Rename { + from: Uri, + to: Uri, + }, + /// Creates a symlink in `dest` pointing at each (local) source. + Link { + sources: Vec, + dest: Uri, + }, +} + +impl JobKind { + /// Single quick calls that should not wait behind a long copy. + fn is_quick(&self) -> bool { + matches!(self, Self::Mkdir(_) | Self::Rename { .. }) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Phase { + #[default] + Queued, + /// Counting files and bytes. + Scanning, + Running, + Finished, +} + +/// Snapshot of a job's progress. +#[derive(Clone, Debug, Default)] +pub struct Progress { + pub phase: Phase, + pub total_files: u64, + pub total_bytes: u64, + pub done_files: u64, + pub done_bytes: u64, + /// Item being worked on. + pub current: Option, +} + +/// Sent from the job thread; requests block the job until answered, +/// dropped or the job is cancelled. +#[derive(Debug)] +pub enum JobEvent { + /// At most every 100 ms, and on phase changes. + Progress(Progress), + Conflict(Box), + Error(ErrorRequest), + Finished(Report), +} + +/// Answer slot of a request. Dropping it unanswered means `Skip`. +#[derive(Debug)] +pub struct Reply(mpsc::SyncSender); + +impl Reply { + pub fn send(self, answer: T) { + let _ = self.0.send(answer); + } +} + +/// The target of a copy, move, link or restore already exists. +#[derive(Debug)] +pub struct ConflictRequest { + pub source: Uri, + pub source_entry: Entry, + pub target: Uri, + pub target_entry: Entry, + pub reply: Reply, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ConflictAction { + Skip, + /// Replace the target; a folder onto a folder merges their contents. + Overwrite, + /// Use this new name (one component) in the same folder. + Rename(Vec), + /// Pick `name (2).ext`, `name (3).ext`, … + AutoRename, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConflictChoice { + pub action: ConflictAction, + /// Reuse the action for later conflicts of this job (ignored for `Rename`). + pub apply_to_all: bool, +} + +/// One item failed; the job waits for a decision. +#[derive(Debug)] +pub struct ErrorRequest { + pub uri: Uri, + pub error: Error, + pub reply: Reply, +} + +impl ErrorRequest { + /// True when retrying as root could succeed (offer elevation). + pub fn needs_elevation(&self) -> bool { + self.error.needs_elevation() + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ErrorAction { + Retry, + Skip, + /// Skip this and every later failing item without asking. + SkipAll, + /// Stop the job. + Abort, +} + +/// Outcome of a finished job. +#[derive(Clone, Debug, Default)] +pub struct Report { + pub done_files: u64, + pub done_bytes: u64, + /// Items that failed and were skipped (or aborted on), for the UI to list. + pub failures: Vec<(Uri, Error)>, + /// Cancelled or aborted before the end. + pub cancelled: bool, +} + +/// Receives every job's events, on the job's thread. +pub type EventSink = Arc; + +struct Shared { + cancel: AtomicBool, + progress: Mutex, +} + +/// Lets the UI watch and cancel one job. Cheap to clone. +#[derive(Clone)] +pub struct JobHandle { + id: JobId, + shared: Arc, +} + +impl JobHandle { + pub fn id(&self) -> JobId { + self.id + } + + /// Asks the job to stop; it finishes with `Report::cancelled`. + pub fn cancel(&self) { + self.shared.cancel.store(true, Ordering::Relaxed); + } + + pub fn progress(&self) -> Progress { + self.shared.progress.lock().unwrap().clone() + } +} + +struct Job { + id: JobId, + kind: JobKind, + shared: Arc, +} + +/// Job queue: long jobs run one after another on a worker thread, +/// quick ones (mkdir, rename) on a thread of their own. +pub struct Jobs { + locations: Locations, + events: EventSink, + queue: mpsc::Sender, + next_id: AtomicU64, +} + +impl Jobs { + pub fn new( + locations: Locations, + events: impl Fn(JobId, JobEvent) + Send + Sync + 'static, + ) -> Self { + let events: EventSink = Arc::new(events); + let (queue, jobs) = mpsc::channel::(); + let (worker_locations, worker_events) = (locations.clone(), events.clone()); + std::thread::Builder::new() + .name("tunal-jobs".into()) + .spawn(move || { + for job in jobs { + run::run(&worker_locations, &worker_events, job); + } + }) + .expect("spawn job worker"); + Self { + locations, + events, + queue, + next_id: AtomicU64::new(1), + } + } + + /// Queues a job and returns its handle at once. + pub fn submit(&self, kind: JobKind) -> JobHandle { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let shared = Arc::new(Shared { + cancel: AtomicBool::new(false), + progress: Mutex::new(Progress::default()), + }); + let handle = JobHandle { + id, + shared: shared.clone(), + }; + let job = Job { id, kind, shared }; + let job = if job.kind.is_quick() { + job + } else { + match self.queue.send(job) { + Ok(()) => return handle, + // Worker gone (it panicked): run on a thread of its own rather than lose the job. + Err(mpsc::SendError(job)) => job, + } + }; + let (locations, events) = (self.locations.clone(), self.events.clone()); + std::thread::spawn(move || run::run(&locations, &events, job)); + handle + } +} diff --git a/crates/tunal-core/src/ops/naming.rs b/crates/tunal-core/src/ops/naming.rs new file mode 100644 index 0000000..b1d42b1 --- /dev/null +++ b/crates/tunal-core/src/ops/naming.rs @@ -0,0 +1,73 @@ +//! Collision-free names and folder nesting checks. + +use crate::{Error, Location, Result, Uri}; + +/// Double extensions kept whole when numbering (`backup (2).tar.gz`). +const DOUBLE_EXT: [&[u8]; 4] = [b".tar.gz", b".tar.xz", b".tar.bz2", b".tar.zst"]; + +/// `name` with copy number `n`: `report (2).pdf`, `photos (3)`, `.bashrc (2)`. +/// An existing ` (N)` suffix is replaced, so `report (2).pdf` → `report (3).pdf`. +pub fn numbered(name: &[u8], n: u32) -> Vec { + let (stem, ext) = split_ext(name); + let mut out = strip_number(stem).to_vec(); + out.extend_from_slice(format!(" ({n})").as_bytes()); + out.extend_from_slice(ext); + out +} + +/// First free `name (N).ext` next to `uri` on `location`. +pub fn auto_rename(location: &dyn Location, uri: &Uri) -> Result { + let (Some(name), Some(parent)) = (uri.file_name(), uri.parent()) else { + return Err(Error::NotFound); + }; + for n in 2..u32::MAX { + let candidate = parent.join(&numbered(name, n)); + match location.stat(&candidate) { + Err(Error::NotFound) => return Ok(candidate), + Ok(_) => {} + Err(e) => return Err(e), + } + } + Err(Error::Exists) +} + +/// True when `uri` is `folder` itself or somewhere below it. +pub fn is_inside(uri: &Uri, folder: &Uri) -> bool { + if uri.scheme() != folder.scheme() || uri.authority() != folder.authority() { + return false; + } + let trim = |p: &[u8]| { + let end = p.iter().rposition(|&b| b != b'/').map_or(0, |i| i + 1); + p[..end].to_vec() + }; + let (path, folder) = (trim(uri.path()), trim(folder.path())); + path.starts_with(&folder) && (path.len() == folder.len() || path[folder.len()] == b'/') +} + +fn split_ext(name: &[u8]) -> (&[u8], &[u8]) { + let lower = name.to_ascii_lowercase(); + if let Some(ext) = DOUBLE_EXT + .iter() + .find(|ext| lower.len() > ext.len() && lower.ends_with(ext)) + { + return name.split_at(name.len() - ext.len()); + } + match name.iter().rposition(|&b| b == b'.') { + Some(dot) if dot > 0 => name.split_at(dot), + _ => (name, &[]), + } +} + +/// `report (2)` → `report`. +fn strip_number(stem: &[u8]) -> &[u8] { + let Some(body) = stem.strip_suffix(b")") else { + return stem; + }; + let digits = body.iter().rev().take_while(|b| b.is_ascii_digit()).count(); + let cut = body.len() - digits; + if digits > 0 && body[..cut].ends_with(b" (") && cut > 2 { + &stem[..cut - 2] + } else { + stem + } +} diff --git a/crates/tunal-core/src/ops/run.rs b/crates/tunal-core/src/ops/run.rs new file mode 100644 index 0000000..218dbaa --- /dev/null +++ b/crates/tunal-core/src/ops/run.rs @@ -0,0 +1,745 @@ +//! Runs one job on the current thread. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::sync::atomic::Ordering; +use std::sync::{Arc, mpsc}; +use std::time::{Duration, Instant}; + +use super::{ + ConflictAction, ConflictChoice, ConflictRequest, ErrorAction, ErrorRequest, EventSink, Job, + JobEvent, JobId, JobKind, Phase, Progress, Reply, Report, Shared, auto_rename, is_inside, +}; +use crate::{Entry, Error, Kind, Location, Locations, Result, Uri, WriteMode, trash}; + +/// Bytes per progress step when copying. +const CHUNK: u64 = 4 << 20; +/// Buffer for cross-backend streams. +const BUFFER: usize = 256 << 10; +/// Minimum time between progress events. +const PROGRESS_EVERY: Duration = Duration::from_millis(100); +/// How often a job waiting for an answer checks its cancel flag. +const POLL: Duration = Duration::from_millis(100); + +pub(super) fn run(locations: &Locations, events: &EventSink, job: Job) { + let mut runner = Runner { + locations, + events, + id: job.id, + shared: &job.shared, + progress: Progress::default(), + last_emit: Instant::now(), + conflict_all: None, + skip_all: false, + failures: Vec::new(), + }; + let cancelled = runner.job(&job.kind).is_err(); + runner.progress.phase = Phase::Finished; + runner.progress.current = None; + runner.publish(true); + let report = Report { + done_files: runner.progress.done_files, + done_bytes: runner.progress.done_bytes, + failures: runner.failures, + cancelled, + }; + (events)(job.id, JobEvent::Finished(report)); +} + +/// Where a source goes and whether an existing target is replaced (or merged into). +struct Target { + uri: Uri, + overwrite: bool, +} + +struct Runner<'a> { + locations: &'a Locations, + events: &'a EventSink, + id: JobId, + shared: &'a Arc, + progress: Progress, + last_emit: Instant, + conflict_all: Option, + skip_all: bool, + failures: Vec<(Uri, Error)>, +} + +/// `Err(Cancelled)` from any step stops the whole job (cancel or abort); +/// a skipped item is `Ok(None)`. +impl Runner<'_> { + fn job(&mut self, kind: &JobKind) -> Result<()> { + self.set_phase(Phase::Scanning); + match kind { + JobKind::Copy { sources, dest } | JobKind::Move { sources, dest } => { + let mv = matches!(kind, JobKind::Move { .. }); + let mut sizes = Vec::with_capacity(sources.len()); + for src in sources { + let size = self.tree_size(src)?; + self.progress.total_files += size.0; + self.progress.total_bytes += size.1; + sizes.push(size); + } + self.set_phase(Phase::Running); + for (src, size) in sources.iter().zip(sizes) { + self.transfer(src, dest, mv, size)?; + } + } + JobKind::Delete(uris) => { + for uri in uris { + self.progress.total_files += self.tree_size(uri)?.0; + } + self.set_phase(Phase::Running); + for uri in uris { + if let Some(backend) = self.backend(uri)? { + self.delete_tree(&*backend, uri, true)?; + } + } + } + JobKind::EmptyTrash => { + let items: Vec = trash::items().into_iter().map(|i| i.uri).collect(); + for uri in &items { + self.progress.total_files += self.tree_size(uri)?.0; + } + self.set_phase(Phase::Running); + let backend = self.locations.resolve(&trash::root())?; + for uri in &items { + self.delete_tree(&*backend, uri, true)?; + } + } + JobKind::Trash(uris) => { + self.progress.total_files = uris.len() as u64; + self.set_phase(Phase::Running); + for uri in uris { + self.step(uri); + if let Some(backend) = self.backend(uri)? { + self.attempt(uri, |_| backend.trash(uri))?; + } + self.file_done(); + } + } + JobKind::Restore(uris) => { + self.progress.total_files = uris.len() as u64; + self.set_phase(Phase::Running); + for uri in uris { + self.restore(uri)?; + self.file_done(); + } + } + JobKind::Mkdir(uri) => { + self.progress.total_files = 1; + self.set_phase(Phase::Running); + self.step(uri); + if let Some(backend) = self.backend(uri)? { + self.attempt(uri, |_| backend.mkdir(uri))?; + } + self.file_done(); + } + JobKind::Rename { from, to } => { + self.progress.total_files = 1; + self.set_phase(Phase::Running); + self.step(from); + if let Some(backend) = self.backend(from)? { + self.attempt(from, |_| backend.rename(from, to))?; + } + self.file_done(); + } + JobKind::Link { sources, dest } => { + self.progress.total_files = sources.len() as u64; + self.set_phase(Phase::Running); + for src in sources { + self.link(src, dest)?; + self.file_done(); + } + } + } + Ok(()) + } + + // ---- copy / move ---- + + fn transfer(&mut self, src: &Uri, dest: &Uri, mv: bool, size: (u64, u64)) -> Result<()> { + self.step(src); + let (Some(sb), Some(db)) = (self.backend(src)?, self.backend(dest)?) else { + return Ok(()); + }; + let Some(entry) = self.attempt(src, |_| sb.stat(src))? else { + return Ok(()); + }; + // A trashed item keeps its original name, not its trash key. + let original = trash::original(src).ok(); + let Some(name) = original + .as_ref() + .and_then(Uri::file_name) + .or(src.file_name()) + else { + return self.fail(src, Error::Unsupported); + }; + let target = dest.join(name); + if mv && target == *src { + self.add_done(size); + return Ok(()); + } + if entry.kind == Kind::Dir && is_inside(dest, src) { + return self.fail(src, Error::Io("cannot copy a folder into itself".into())); + } + let Some(target) = self.target(&*db, src, &entry, target)? else { + self.add_done(size); + return Ok(()); + }; + if mv && self.try_rename(&*sb, &*db, src, &entry, &target)? { + self.add_done(size); + return Ok(()); + } + self.place(&*sb, &*db, src, &entry, &target, mv) + } + + /// Same-backend move by rename. `Ok(false)` means "copy and delete instead". + fn try_rename( + &mut self, + sb: &dyn Location, + db: &dyn Location, + src: &Uri, + entry: &Entry, + target: &Target, + ) -> Result { + let same_backend = + src.scheme() == target.uri.scheme() && src.authority() == target.uri.authority(); + if !same_backend || !same_device(src, &target.uri) { + return Ok(false); + } + if target.overwrite { + match db.stat(&target.uri) { + // Folder onto folder merges item by item. + Ok(existing) if existing.kind == Kind::Dir && entry.kind == Kind::Dir => { + return Ok(false); + } + Ok(_) => { + self.delete_tree(db, &target.uri, false)?; + } + Err(_) => {} + } + } + loop { + match sb.rename(src, &target.uri) { + Ok(()) => return Ok(true), + Err(Error::Unsupported) => return Ok(false), + Err(e) => match self.ask_error(src, e)? { + ErrorAction::Retry => continue, + // ask_error already recorded the failure. + _ => return Ok(true), + }, + } + } + } + + /// Copies `src` to `target` (recursively), deleting the source afterwards when moving. + fn place( + &mut self, + sb: &dyn Location, + db: &dyn Location, + src: &Uri, + entry: &Entry, + target: &Target, + mv: bool, + ) -> Result<()> { + self.step(src); + let copied = match &entry.kind { + Kind::Dir => return self.place_dir(sb, db, src, entry, target, mv), + Kind::File => self + .attempt(src, |r| r.copy_file(sb, db, src, entry, target))? + .is_some(), + Kind::Symlink { target: link, .. } => { + if target.overwrite { + self.delete_tree(db, &target.uri, false)?; + } + self.attempt(src, |_| db.symlink(&target.uri, link))? + .is_some() + } + Kind::Special => { + self.fail(src, Error::Unsupported)?; + false + } + }; + self.file_done(); + if copied && mv { + self.attempt(src, |_| sb.delete(src))?; + } + Ok(()) + } + + fn place_dir( + &mut self, + sb: &dyn Location, + db: &dyn Location, + src: &Uri, + entry: &Entry, + target: &Target, + mv: bool, + ) -> Result<()> { + let merge = target.overwrite + && match db.stat(&target.uri) { + Ok(existing) if existing.kind == Kind::Dir => true, + Ok(_) => { + self.delete_tree(db, &target.uri, false)?; + false + } + Err(_) => false, + }; + if !merge && self.attempt(src, |_| db.mkdir(&target.uri))?.is_none() { + return Ok(()); + } + self.file_done(); + let Some(children) = self.attempt(src, |r| r.list(sb, src))? else { + return Ok(()); + }; + for child in children { + let child_src = src.join(&child.name); + let child_target = target.uri.join(&child.name); + let child_target = if merge { + match self.target(db, &child_src, &child, child_target)? { + Some(t) => t, + None => continue, + } + } else { + Target { + uri: child_target, + overwrite: false, + } + }; + self.place(sb, db, &child_src, &child, &child_target, mv)?; + } + if let (Some(path), Some(mtime)) = (target.uri.to_path(), entry.mtime) { + let _ = File::open(&path).and_then(|f| f.set_modified(mtime)); + let _ = fs::set_permissions(&path, fs::Permissions::from_mode(entry.mode)); + } + if mv { + // Skipped children keep the folder; that is not another failure. + match sb.delete(src) { + Ok(()) | Err(Error::NotEmpty) => {} + Err(e) => self.fail(src, e)?, + } + } + Ok(()) + } + + fn copy_file( + &mut self, + sb: &dyn Location, + db: &dyn Location, + src: &Uri, + entry: &Entry, + target: &Target, + ) -> Result<()> { + let start = self.progress.done_bytes; + let result = match (src.to_path(), target.uri.to_path()) { + (Some(from), Some(to)) => self.copy_local(&from, &to, target.overwrite), + _ => self.copy_stream(sb, db, src, target), + }; + if result.is_err() { + self.progress.done_bytes = start; + return result; + } + if let Some(path) = target.uri.to_path() { + if let Some(mtime) = entry.mtime { + let _ = File::options() + .write(true) + .open(&path) + .and_then(|f| f.set_modified(mtime)); + } + if entry.mode != 0 { + let _ = fs::set_permissions(&path, fs::Permissions::from_mode(entry.mode)); + } + } + Ok(()) + } + + /// Local to local: `io::copy` between files uses `copy_file_range` on Linux. + fn copy_local( + &mut self, + from: &std::path::Path, + to: &std::path::Path, + overwrite: bool, + ) -> Result<()> { + let source = File::open(from)?; + let mut options = OpenOptions::new(); + options.write(true); + if overwrite { + options.create(true).truncate(true); + } else { + options.create_new(true); + } + let mut dest = options.open(to)?; + let result = (|| { + loop { + let n = io::copy(&mut (&source).take(CHUNK), &mut dest)?; + if n == 0 { + return Ok(()); + } + self.add_bytes(n); + self.check_cancel()?; + } + })(); + if result.is_err() { + drop(dest); + let _ = fs::remove_file(to); + } + result + } + + /// Any backend to any backend through `open_read` / `open_write`. + fn copy_stream( + &mut self, + sb: &dyn Location, + db: &dyn Location, + src: &Uri, + target: &Target, + ) -> Result<()> { + let mut reader = sb.open_read(src)?; + let mode = if target.overwrite { + WriteMode::Overwrite + } else { + WriteMode::CreateNew + }; + let mut writer = db.open_write(&target.uri, mode)?; + let result = (|| { + let mut buf = vec![0; BUFFER]; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + return Ok(writer.flush()?); + } + writer.write_all(&buf[..n])?; + self.add_bytes(n as u64); + self.check_cancel()?; + } + })(); + if result.is_err() { + drop(writer); + let _ = db.delete(&target.uri); + } + result + } + + // ---- conflicts ---- + + /// Resolves an existing target; `None` means skip this item. + fn target( + &mut self, + db: &dyn Location, + src: &Uri, + entry: &Entry, + mut uri: Uri, + ) -> Result> { + loop { + let Ok(existing) = db.stat(&uri) else { + return Ok(Some(Target { + uri, + overwrite: false, + })); + }; + let action = if uri == *src { + // Pasting into the item's own folder makes a numbered copy. + ConflictAction::AutoRename + } else { + self.ask_conflict(src, entry, &uri, existing)? + }; + match action { + ConflictAction::Skip => return Ok(None), + ConflictAction::Overwrite => { + return Ok(Some(Target { + uri, + overwrite: true, + })); + } + ConflictAction::Rename(name) => match uri.parent() { + Some(parent) => uri = parent.join(&name), + None => return Ok(None), + }, + ConflictAction::AutoRename => { + return Ok(self + .attempt(&uri, |_| auto_rename(db, &uri))? + .map(|uri| Target { + uri, + overwrite: false, + })); + } + } + } + } + + fn ask_conflict( + &mut self, + src: &Uri, + entry: &Entry, + target: &Uri, + existing: Entry, + ) -> Result { + if let Some(action) = &self.conflict_all { + return Ok(action.clone()); + } + let (reply, answer) = mpsc::sync_channel(1); + self.send(JobEvent::Conflict(Box::new(ConflictRequest { + source: src.clone(), + source_entry: entry.clone(), + target: target.clone(), + target_entry: existing, + reply: Reply(reply), + }))); + let choice = self.wait(answer)?.unwrap_or(ConflictChoice { + action: ConflictAction::Skip, + apply_to_all: false, + }); + if choice.apply_to_all && !matches!(choice.action, ConflictAction::Rename(_)) { + self.conflict_all = Some(choice.action.clone()); + } + Ok(choice.action) + } + + // ---- errors ---- + + /// Runs `op` until it succeeds or the user skips (`None`) or aborts (`Err(Cancelled)`). + fn attempt( + &mut self, + uri: &Uri, + mut op: impl FnMut(&mut Self) -> Result, + ) -> Result> { + loop { + self.check_cancel()?; + match op(self) { + Ok(value) => return Ok(Some(value)), + Err(Error::Cancelled) => return Err(Error::Cancelled), + Err(e) => match self.ask_error(uri, e)? { + ErrorAction::Retry => continue, + _ => return Ok(None), + }, + } + } + } + + /// Asks what to do about a failed item; records it unless retried. + fn ask_error(&mut self, uri: &Uri, error: Error) -> Result { + let action = if self.skip_all { + ErrorAction::Skip + } else { + let (reply, answer) = mpsc::sync_channel(1); + self.send(JobEvent::Error(ErrorRequest { + uri: uri.clone(), + error: error.clone(), + reply: Reply(reply), + })); + self.wait(answer)?.unwrap_or(ErrorAction::Skip) + }; + if action != ErrorAction::Retry { + self.failures.push((uri.clone(), error)); + } + match action { + ErrorAction::SkipAll => self.skip_all = true, + ErrorAction::Abort => return Err(Error::Cancelled), + _ => {} + } + Ok(action) + } + + /// A failure that retrying cannot fix: record and go on (still honours SkipAll/Abort). + fn fail(&mut self, uri: &Uri, error: Error) -> Result<()> { + loop { + if self.ask_error(uri, error.clone())? != ErrorAction::Retry { + return Ok(()); + } + } + } + + /// Waits for an answer; `None` if the request was dropped unanswered. + fn wait(&self, answer: mpsc::Receiver) -> Result> { + loop { + match answer.recv_timeout(POLL) { + Ok(value) => return Ok(Some(value)), + Err(mpsc::RecvTimeoutError::Timeout) => self.check_cancel()?, + Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(None), + } + } + } + + // ---- other kinds ---- + + fn restore(&mut self, uri: &Uri) -> Result<()> { + self.step(uri); + let Some(original) = self.attempt(uri, |_| trash::original(uri))? else { + return Ok(()); + }; + let local = self.locations.resolve(&original)?; + let tb = self.locations.resolve(uri)?; + let Some(entry) = self.attempt(uri, |_| tb.stat(uri))? else { + return Ok(()); + }; + let Some(target) = self.target(&*local, uri, &entry, original)? else { + return Ok(()); + }; + if target.overwrite { + self.delete_tree(&*local, &target.uri, false)?; + } + let path = target.uri.to_path().ok_or(Error::Unsupported)?; + self.attempt(uri, |_| trash::restore(uri, &path))?; + Ok(()) + } + + fn link(&mut self, src: &Uri, dest: &Uri) -> Result<()> { + self.step(src); + let Some(db) = self.backend(dest)? else { + return Ok(()); + }; + let (Some(name), Some(path)) = (src.file_name(), src.to_path()) else { + return self.fail(src, Error::Unsupported); + }; + let Ok(entry) = self.locations.resolve(src).and_then(|b| b.stat(src)) else { + return self.fail(src, Error::NotFound); + }; + let Some(target) = self.target(&*db, src, &entry, dest.join(name))? else { + return Ok(()); + }; + if target.overwrite { + self.delete_tree(&*db, &target.uri, false)?; + } + let path = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str()).to_vec(); + self.attempt(src, |_| db.symlink(&target.uri, &path))?; + Ok(()) + } + + /// Deletes `uri` and everything below it, children first. `Ok(false)` when + /// something was skipped (so the parent folder stays). + fn delete_tree(&mut self, backend: &dyn Location, uri: &Uri, count: bool) -> Result { + self.step(uri); + let Some(entry) = self.attempt(uri, |_| backend.stat(uri))? else { + return Ok(false); + }; + if entry.kind == Kind::Dir { + let Some(children) = self.attempt(uri, |r| r.list(backend, uri))? else { + return Ok(false); + }; + let mut all = true; + for child in children { + all &= self.delete_tree(backend, &uri.join(&child.name), count)?; + } + // A skipped child is the failure; its folder staying is not another one. + if !all { + return Ok(false); + } + } + let deleted = self.attempt(uri, |_| backend.delete(uri))?.is_some(); + if count { + self.file_done(); + } + Ok(deleted) + } + + // ---- helpers ---- + + /// Files (folders included) and bytes below `uri`; unreadable parts count as nothing. + fn tree_size(&mut self, uri: &Uri) -> Result<(u64, u64)> { + self.check_cancel()?; + let Ok(backend) = self.locations.resolve(uri) else { + return Ok((0, 0)); + }; + let Ok(entry) = backend.stat(uri) else { + return Ok((0, 0)); + }; + let mut size = ( + 1, + if entry.kind == Kind::File { + entry.size + } else { + 0 + }, + ); + if entry.kind == Kind::Dir { + let children = self.list(&*backend, uri).unwrap_or_default(); + for child in children { + let sub = self.tree_size(&uri.join(&child.name))?; + size = (size.0 + sub.0, size.1 + sub.1); + } + } + Ok(size) + } + + fn list(&self, backend: &dyn Location, dir: &Uri) -> Result> { + let mut all = Vec::new(); + backend.list(dir, &mut |chunk| { + all.extend(chunk); + if self.shared.cancel.load(Ordering::Relaxed) { + std::ops::ControlFlow::Break(()) + } else { + std::ops::ControlFlow::Continue(()) + } + })?; + Ok(all) + } + + /// Backend for `uri`; an unknown scheme is recorded as a failure (`None`). + fn backend(&mut self, uri: &Uri) -> Result>> { + match self.locations.resolve(uri) { + Ok(backend) => Ok(Some(backend)), + Err(e) => self.fail(uri, e).map(|()| None), + } + } + + fn check_cancel(&self) -> Result<()> { + if self.shared.cancel.load(Ordering::Relaxed) { + Err(Error::Cancelled) + } else { + Ok(()) + } + } + + fn set_phase(&mut self, phase: Phase) { + self.progress.phase = phase; + self.publish(true); + } + + fn step(&mut self, uri: &Uri) { + self.progress.current = Some(uri.clone()); + self.publish(false); + } + + fn file_done(&mut self) { + self.progress.done_files += 1; + self.publish(false); + } + + fn add_bytes(&mut self, n: u64) { + self.progress.done_bytes += n; + self.publish(false); + } + + fn add_done(&mut self, (files, bytes): (u64, u64)) { + self.progress.done_files += files; + self.progress.done_bytes += bytes; + self.publish(false); + } + + /// Updates the shared snapshot; sends an event when `force` or throttling allows. + fn publish(&mut self, force: bool) { + *self.shared.progress.lock().unwrap() = self.progress.clone(); + if force || self.last_emit.elapsed() >= PROGRESS_EVERY { + self.last_emit = Instant::now(); + self.send(JobEvent::Progress(self.progress.clone())); + } + } + + fn send(&self, event: JobEvent) { + (self.events)(self.id, event); + } +} + +/// Local items on the same filesystem (rename works); non-local: let the backend decide. +fn same_device(a: &Uri, b: &Uri) -> bool { + let (Some(a), Some(b)) = (a.to_path(), b.to_path()) else { + return true; + }; + let dev = |p: &std::path::Path| { + p.parent() + .and_then(|p| fs::metadata(p).ok()) + .map(|m| m.dev()) + }; + matches!((fs::symlink_metadata(&a).map(|m| m.dev()).ok(), dev(&b)), (Some(x), Some(y)) if x == y) +} diff --git a/crates/tunal-core/src/registry.rs b/crates/tunal-core/src/registry.rs index d2aa3f3..2e5c6ea 100644 --- a/crates/tunal-core/src/registry.rs +++ b/crates/tunal-core/src/registry.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::sync::Arc; -use crate::{Error, LocalLocation, Location, Result, Uri}; +use crate::{Error, LocalLocation, Location, Result, TrashLocation, Uri}; /// All registered backends, looked up by URI scheme. Cheap to clone. #[derive(Clone, Default)] @@ -17,10 +17,11 @@ impl Locations { Self::default() } - /// Registry with the local `file://` backend. + /// Registry with the local `file://` and `trash://` backends. pub fn with_local() -> Self { let mut locations = Self::new(); locations.register(Arc::new(LocalLocation)); + locations.register(Arc::new(TrashLocation)); locations } diff --git a/crates/tunal-core/src/trash.rs b/crates/tunal-core/src/trash.rs new file mode 100644 index 0000000..5d46c5f --- /dev/null +++ b/crates/tunal-core/src/trash.rs @@ -0,0 +1,495 @@ +//! Freedesktop trash (`$XDG_DATA_HOME/Trash`, `$topdir/.Trash/$uid`, `$topdir/.Trash-$uid`) +//! and the `trash:///` backend. +//! +//! Item URIs are `trash:///:[/]`, where `` is +//! `home` for the home trash or the hex-encoded path of another trash directory, and +//! `` is the item's name in that trash's `files/` folder. + +use std::ffi::{OsStr, OsString}; +use std::fs::{self, DirBuilder, OpenOptions}; +use std::io::{Read, Write}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::os::unix::fs::{DirBuilderExt, MetadataExt}; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use crate::ops::numbered; +use crate::uri::{percent_decode, percent_encode}; +use crate::{ + Capabilities, Entry, Error, ListSink, LocalLocation, Location, Result, Uri, display_name, +}; + +/// Scheme of the trash backend. +pub const TRASH: &str = "trash"; + +/// Id of the home trash in item URIs. +const HOME_ID: &[u8] = b"home"; +/// Entries handed to the list sink at once. +const CHUNK: usize = 256; +/// Mounts never searched for a trash folder (virtual or slow to stat). +const SKIP_FS: [&str; 14] = [ + "proc", + "sysfs", + "devtmpfs", + "devpts", + "cgroup", + "cgroup2", + "securityfs", + "debugfs", + "tracefs", + "pstore", + "bpf", + "mqueue", + "autofs", + "fuse.sshfs", +]; + +/// `trash:///`, the folder listing every trashed item. +pub fn root() -> Uri { + Uri::new(TRASH, "", "/") +} + +/// One trashed item with its `.trashinfo` data. +#[derive(Clone, Debug)] +pub struct TrashItem { + pub uri: Uri, + /// Where it was before it was trashed (restore target). + pub original: Uri, + pub deleted: Option, + /// `name` is the URI key, `display_name` the original file name. + pub entry: Entry, +} + +/// A trash directory holding `files/` and `info/`. +#[derive(Clone, Debug, PartialEq, Eq)] +struct TrashDir { + id: Vec, + root: PathBuf, + /// Base for relative `Path=` values; `None` for the home trash (absolute paths). + topdir: Option, +} + +impl TrashDir { + fn files(&self) -> PathBuf { + self.root.join("files") + } + + fn info(&self, name: &[u8]) -> PathBuf { + let mut file = name.to_vec(); + file.extend_from_slice(b".trashinfo"); + self.root.join("info").join(OsStr::from_bytes(&file)) + } + + fn item_uri(&self, name: &[u8]) -> Uri { + root().join(&key(&self.id, name)) + } +} + +/// Moves a local file, link or folder to the trash of its filesystem. +pub fn trash_path(path: &Path) -> Result<()> { + let meta = fs::symlink_metadata(path)?; + let name = path.file_name().ok_or(Error::Unsupported)?; + // The item itself may be a link; resolve only its folder. + let path = path + .parent() + .ok_or(Error::Unsupported)? + .canonicalize()? + .join(name); + if let Some(home) = home_trash() + && device_of(&home.root) == Some(meta.dev()) + { + let original = path.as_os_str().as_bytes().to_vec(); + return put(&home, &path, &original); + } + let top = topdir(&path).ok_or(Error::Unsupported)?; + let trash = topdir_trash(&top, true).ok_or(Error::Unsupported)?; + if device_of(&trash.root) != Some(meta.dev()) { + return Err(Error::Unsupported); + } + let relative = path.strip_prefix(&top).map_err(|_| Error::Unsupported)?; + put(&trash, &path, relative.as_os_str().as_bytes()) +} + +/// Every item in every trash directory that is reachable now. +pub fn items() -> Vec { + let mut items = Vec::new(); + for dir in trash_dirs() { + let Ok(files) = fs::read_dir(dir.files()) else { + continue; + }; + for file in files.flatten() { + if let Ok(item) = item(&dir, &file.file_name().into_vec()) { + items.push(item); + } + } + } + items +} + +/// Original location of a top-level trash item (`NotFound` for paths inside one). +pub fn original(uri: &Uri) -> Result { + let (dir, name, sub) = resolve(uri)?; + if !sub.is_empty() { + return Err(Error::NotFound); + } + Ok(read_info(&dir, &name)?.0) +} + +/// Moves a top-level trash item to `target` (recreating its folder) and drops its info file. +pub fn restore(uri: &Uri, target: &Path) -> Result<()> { + let (dir, name, sub) = resolve(uri)?; + if !sub.is_empty() { + return Err(Error::Unsupported); + } + if fs::symlink_metadata(target).is_ok() { + return Err(Error::Exists); + } + if let Some(parent) = target.parent() { + fs::create_dir_all(parent)?; + } + fs::rename(dir.files().join(OsStr::from_bytes(&name)), target)?; + let _ = fs::remove_file(dir.info(&name)); + Ok(()) +} + +/// The `trash:///` backend: browse, read and permanently delete trashed items. +/// Restoring and trashing go through `restore` and `trash_path`. +#[derive(Clone, Copy, Debug, Default)] +pub struct TrashLocation; + +impl Location for TrashLocation { + fn scheme(&self) -> &str { + TRASH + } + + fn capabilities(&self) -> Capabilities { + Capabilities { + permissions: true, + ..Capabilities::default() + } + } + + fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> { + if is_root(dir) { + let entries: Vec = items().into_iter().map(|i| i.entry).collect(); + for chunk in entries.chunks(CHUNK) { + if sink(chunk.to_vec()).is_break() { + return Err(Error::Cancelled); + } + } + return Ok(()); + } + let local = Uri::from_path(&local_path(dir)?); + LocalLocation.list(&local, sink) + } + + fn stat(&self, uri: &Uri) -> Result { + if is_root(uri) { + let mut entry = LocalLocation.stat(&Uri::from_path(Path::new("/")))?; + entry.name = b"/".to_vec(); + entry.display_name = "Trash".into(); + return Ok(entry); + } + let (dir, name, sub) = resolve(uri)?; + if sub.is_empty() { + return Ok(item(&dir, &name)?.entry); + } + LocalLocation.stat(&Uri::from_path(&local_path(uri)?)) + } + + fn open_read(&self, uri: &Uri) -> Result> { + LocalLocation.open_read(&Uri::from_path(&local_path(uri)?)) + } + + fn delete(&self, uri: &Uri) -> Result<()> { + let (dir, name, sub) = resolve(uri)?; + LocalLocation.delete(&Uri::from_path(&local_path(uri)?))?; + if sub.is_empty() { + let _ = fs::remove_file(dir.info(&name)); + } + Ok(()) + } +} + +// ---- trash directories ---- + +fn home_trash() -> Option { + let data = std::env::var_os("XDG_DATA_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))?; + Some(TrashDir { + id: HOME_ID.to_vec(), + root: data.join("Trash"), + topdir: None, + }) +} + +/// Home trash plus every existing per-mount trash of this user. +fn trash_dirs() -> Vec { + let mut dirs: Vec = home_trash().into_iter().collect(); + for (mount, fstype) in mounts() { + if SKIP_FS.contains(&fstype.as_str()) { + continue; + } + if let Some(dir) = topdir_trash(&mount, false) + && !dirs.iter().any(|d| d.root == dir.root) + { + dirs.push(dir); + } + } + dirs +} + +/// `$topdir/.Trash/$uid` when the admin made a valid `.Trash` (sticky, not a link), +/// else `$topdir/.Trash-$uid`. With `create`, makes the per-user folder (0700). +fn topdir_trash(top: &Path, create: bool) -> Option { + let uid = uid()?.to_string(); + let shared = top.join(".Trash"); + let shared_ok = + fs::symlink_metadata(&shared).is_ok_and(|m| m.is_dir() && m.mode() & 0o1000 != 0); + let mut candidates = Vec::new(); + if shared_ok { + candidates.push(shared.join(&uid)); + } + candidates.push(top.join(format!(".Trash-{uid}"))); + let root = candidates.into_iter().find(|c| { + fs::symlink_metadata(c).is_ok_and(|m| m.is_dir()) + || (create && DirBuilder::new().mode(0o700).create(c).is_ok()) + })?; + let id = hex(root.as_os_str().as_bytes()); + Some(TrashDir { + id, + root, + topdir: Some(top.to_path_buf()), + }) +} + +/// Mount point of the filesystem holding `path` (longest matching mount). +fn topdir(path: &Path) -> Option { + mounts() + .into_iter() + .map(|(mount, _)| mount) + .filter(|mount| path.starts_with(mount)) + .max_by_key(|mount| mount.as_os_str().len()) +} + +/// `(mount point, fs type)` from `/proc/self/mountinfo`. +fn mounts() -> Vec<(PathBuf, String)> { + let Ok(text) = fs::read("/proc/self/mountinfo") else { + return Vec::new(); + }; + text.split(|&b| b == b'\n') + .filter_map(|line| { + let fields: Vec<&[u8]> = line.split(|&b| b == b' ').collect(); + let mount = fields.get(4)?; + let sep = fields.iter().position(|f| *f == b"-")?; + let fstype = String::from_utf8_lossy(fields.get(sep + 1)?).into_owned(); + Some(( + PathBuf::from(OsString::from_vec(unescape_octal(mount))), + fstype, + )) + }) + .collect() +} + +/// mountinfo escapes space, tab, newline and backslash as `\ooo`. +fn unescape_octal(field: &[u8]) -> Vec { + let mut out = Vec::with_capacity(field.len()); + let mut i = 0; + while i < field.len() { + let code = field + .get(i + 1..i + 4) + .filter(|_| field[i] == b'\\') + .and_then(|d| std::str::from_utf8(d).ok()) + .and_then(|d| u8::from_str_radix(d, 8).ok()); + match code { + Some(b) => { + out.push(b); + i += 4; + } + None => { + out.push(field[i]); + i += 1; + } + } + } + out +} + +/// Real uid of this process (owner of `/proc/self`). +fn uid() -> Option { + fs::metadata("/proc/self").ok().map(|m| m.uid()) +} + +/// Device of `path`, or of its nearest existing ancestor. +fn device_of(path: &Path) -> Option { + path.ancestors() + .find_map(|p| fs::metadata(p).ok()) + .map(|m| m.dev()) +} + +// ---- trashing ---- + +/// Reserves a free name with an exclusive `.trashinfo`, then moves the item in. +fn put(dir: &TrashDir, path: &Path, original: &[u8]) -> Result<()> { + for sub in ["files", "info"] { + DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir.root.join(sub))?; + } + let name = path.file_name().ok_or(Error::Unsupported)?.as_bytes(); + let date = jiff::Zoned::now().strftime("%Y-%m-%dT%H:%M:%S").to_string(); + let body = format!( + "[Trash Info]\nPath={}\nDeletionDate={date}\n", + percent_encode(original) + ); + for n in 1..u32::MAX { + let candidate = if n == 1 { + name.to_vec() + } else { + numbered(name, n) + }; + let info = dir.info(&candidate); + let mut file = match OpenOptions::new().write(true).create_new(true).open(&info) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.into()), + }; + let target = dir.files().join(OsStr::from_bytes(&candidate)); + // A leftover file without info: keep its info slot taken, try the next name. + if fs::symlink_metadata(&target).is_ok() { + continue; + } + let result = file + .write_all(body.as_bytes()) + .and_then(|()| file.sync_all()) + .and_then(|()| fs::rename(path, &target)); + if let Err(e) = result { + let _ = fs::remove_file(&info); + return Err(e.into()); + } + return Ok(()); + } + Err(Error::Exists) +} + +// ---- reading ---- + +fn item(dir: &TrashDir, name: &[u8]) -> Result { + let (original, deleted) = read_info(dir, name)?; + let file = Uri::from_path(&dir.files().join(OsStr::from_bytes(name))); + let mut entry = LocalLocation.stat(&file)?; + entry.name = key(&dir.id, name); + entry.display_name = display_name(original.file_name().unwrap_or(name)); + entry.hidden = false; + Ok(TrashItem { + uri: dir.item_uri(name), + original, + deleted, + entry, + }) +} + +/// `Path=` (decoded, made absolute) and `DeletionDate=` of an item. +fn read_info(dir: &TrashDir, name: &[u8]) -> Result<(Uri, Option)> { + let text = fs::read(dir.info(name))?; + let (mut path, mut date) = (None, None); + let mut in_group = false; + for line in text.split(|&b| b == b'\n') { + let line = line.strip_suffix(b"\r").unwrap_or(line); + if line.starts_with(b"[") { + in_group = line == b"[Trash Info]"; + } else if !in_group { + } else if let Some(value) = line.strip_prefix(b"Path=") { + path = std::str::from_utf8(value).ok().and_then(percent_decode); + } else if let Some(value) = line.strip_prefix(b"DeletionDate=") { + date = std::str::from_utf8(value).ok().and_then(parse_date); + } + } + let path = PathBuf::from(OsString::from_vec(path.ok_or(Error::NotFound)?)); + let path = match &dir.topdir { + Some(top) if path.is_relative() => top.join(path), + _ => path, + }; + Ok((Uri::from_path(&path), date)) +} + +fn parse_date(s: &str) -> Option { + let local = jiff::civil::DateTime::strptime("%Y-%m-%dT%H:%M:%S", s.trim()).ok()?; + let zoned = local.to_zoned(jiff::tz::TimeZone::system()).ok()?; + Some(zoned.timestamp().into()) +} + +// ---- URIs ---- + +fn is_root(uri: &Uri) -> bool { + uri.scheme() == TRASH && uri.path().iter().all(|&b| b == b'/') +} + +/// `id:name`, the first path component of an item URI. +fn key(id: &[u8], name: &[u8]) -> Vec { + let mut key = id.to_vec(); + key.push(b':'); + key.extend_from_slice(name); + key +} + +/// Splits an item URI into its trash directory, item name and the path below it. +fn resolve(uri: &Uri) -> Result<(TrashDir, Vec, Vec)> { + if uri.scheme() != TRASH || is_root(uri) { + return Err(Error::NotFound); + } + let path = uri.path().strip_prefix(b"/").unwrap_or(uri.path()); + let (first, sub) = match path.iter().position(|&b| b == b'/') { + Some(slash) => (&path[..slash], &path[slash + 1..]), + None => (path, &[][..]), + }; + let colon = first + .iter() + .position(|&b| b == b':') + .ok_or(Error::NotFound)?; + let (id, name) = (&first[..colon], &first[colon + 1..]); + if name.is_empty() || name == b"." || name == b".." { + return Err(Error::NotFound); + } + if sub.split(|&b| b == b'/').any(|c| c == b"..") { + return Err(Error::PermissionDenied); + } + // Only trash directories that exist now: an id can't point anywhere else. + let dir = if id == HOME_ID { + home_trash() + } else { + let root = PathBuf::from(OsString::from_vec(unhex(id).ok_or(Error::NotFound)?)); + trash_dirs().into_iter().find(|d| d.root == root) + } + .ok_or(Error::NotFound)?; + let sub = sub.strip_suffix(b"/").unwrap_or(sub).to_vec(); + Ok((dir, name.to_vec(), sub)) +} + +/// Local path behind an item URI. +fn local_path(uri: &Uri) -> Result { + let (dir, name, sub) = resolve(uri)?; + let mut path = dir.files().join(OsStr::from_bytes(&name)); + if !sub.is_empty() { + path.push(OsStr::from_bytes(&sub)); + } + Ok(path) +} + +fn hex(bytes: &[u8]) -> Vec { + bytes + .iter() + .flat_map(|b| format!("{b:02x}").into_bytes()) + .collect() +} + +fn unhex(s: &[u8]) -> Option> { + let s = std::str::from_utf8(s).ok()?; + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()) + .collect() +} diff --git a/crates/tunal-core/src/uri.rs b/crates/tunal-core/src/uri.rs index 39998b5..2e7d515 100644 --- a/crates/tunal-core/src/uri.rs +++ b/crates/tunal-core/src/uri.rs @@ -112,24 +112,35 @@ impl From<&Path> for Uri { impl fmt::Display for Uri { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}://{}", self.scheme, self.authority)?; - for &b in &self.path { - if b.is_ascii_alphanumeric() || b"/-._~!$&'()*+,;=:@".contains(&b) { - write!(f, "{}", b as char)?; - } else { - write!(f, "%{b:02X}")?; - } - } - Ok(()) + write!( + f, + "{}://{}{}", + self.scheme, + self.authority, + percent_encode(&self.path) + ) } } +/// Escapes a raw path as `%XX`, keeping `/` and the URI path characters. +pub(crate) fn percent_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len()); + for &b in bytes { + if b.is_ascii_alphanumeric() || b"/-._~!$&'()*+,;=:@".contains(&b) { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + /// Lossy display form of a raw name or path. pub fn display_name(bytes: &[u8]) -> String { OsStr::from_bytes(bytes).to_string_lossy().into_owned() } -fn percent_decode(s: &str) -> Option> { +pub(crate) fn percent_decode(s: &str) -> Option> { let bytes = s.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index e6b87bc..d4a5066 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -28,3 +28,4 @@ D-023 — 2026-11-18 — Window minimum size 720×480 px (preferred 960×640): f D-024 — 2026-11-18 — Location URIs are `scheme://authority/path` with the path as raw bytes (percent-encoded only in Display); every backend implements the object-safe blocking `Location` trait in `tunal-core` (chunked `list` with a `ControlFlow` sink, `watch` returning a drop guard), unsupported ops return `Error::Unsupported`, and views gate actions on `capabilities()` — S006 — S007–S014, S024–S029. D-025 — 2026-11-18 — Controls: every control inherits `StateLayer` (tint drawn above content, `clicked` for users and `activated` for the control's own toggling; inherited properties must be written `root.x`); `TextField` is built on the builtin `TextInput` because std `LineEdit` (material) takes its colours from the fixed `MaterialPalette` and can't use our tokens; the software renderer ignores `transform-scale`, so press squeeze shows only in a real window — S004 — every UI plan, S035. D-023 — 2026-11-18 — UI sessions look at the user's other Material You apps (Damson, Mulberry, Nacre; egui) as design references for colour roles, state layers, shape, spacing and motion, porting ideas to our Slint Theme/Motion tokens; the stack (Slint 1.19) stays; library defaults that don't match are replaced by own components — user — all UI plans (S004–S031, S034, S035). +D-026 — 2026-11-18 — File operations run as jobs in `tunal-core::ops`: `Jobs::new(locations, sink)` (one worker thread runs long jobs in order; mkdir/rename get their own thread), `submit(JobKind) -> JobHandle` (`progress()`, `cancel()`); the sink gets `JobEvent::{Progress, Conflict(Box), Error(ErrorRequest), Finished(Report)}` on the job thread, requests block the job until answered through `Reply::send` (dropped = Skip). Folder onto folder with Overwrite merges. Trash item URIs are `trash:///:[/sub]` with `` = `home` or the hex path of a per-mount trash dir; entries' `name` is that key, `display_name` the original name; jiff 0.2 for local DeletionDate — S007 — S010, S011, S012, S013 and every plan that changes files. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index cf55f44..140788b 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -35,5 +35,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: press squeeze is invisible in PNGs (software renderer ignores `transform-scale`, D-025); live hover/tooltip/animation not watched (no hidden session); `TextField` uses `TextInput`, not `LineEdit` (D-025). - Later: focus ring on `TextField` is its 2 px border only; long tab bars (more tabs than fit) need scrolling. +## S007 — File operations engine and trash +- Done: `tunal-core::ops` — `Jobs`/`JobHandle`/`JobKind::{Copy, Move, Delete, Trash, Restore, EmptyTrash, Mkdir, Rename, Link}`, `Progress { phase: Queued/Scanning/Running/Finished, total/done files+bytes, current }` (event ≤ every 100 ms), `ConflictRequest { source, source_entry, target, target_entry, reply }` → `ConflictChoice { action: Skip/Overwrite/Rename(name)/AutoRename, apply_to_all }`, `ErrorRequest { uri, error, reply, needs_elevation() }` → `ErrorAction::{Retry, Skip, SkipAll, Abort}`, `Report { done_files, done_bytes, failures, cancelled }`; `numbered`/`auto_rename` (`name (2).ext`, `.tar.*` kept), `is_inside`. Scan pass, local `io::copy` chunks (copy_file_range), stream copy for other backends, same-fs move = rename, else copy + delete; mtime/mode kept on local targets; partial files removed on cancel/error. +- `tunal-core::trash`: home trash + `$topdir/.Trash/$uid` (sticky check) / `.Trash-$uid` from mountinfo; exclusive `.trashinfo` reservation, percent-encoded Path, local DeletionDate (jiff 0.2); `items()`, `original()`, `restore()`, `TrashLocation` (`trash:///:`, list/stat/open_read/delete), registered by `Locations::with_local()`; `LocalLocation::trash` now works. Example `ops` (refuses unless `XDG_DATA_HOME` is inside its dir). URI format and job API: D-026. +- Verified: workspace build, clippy -D warnings, `cargo fmt --check -p tunal-core`; `XDG_DATA_HOME=/data cargo run -p tunal-core --example ops -- `: progress, auto-rename conflict, same-folder copy → `a (3).txt`, folder-into-itself refused, merge move, trash/list/restore with rename conflict, duplicate names `dup (2).txt`, non-UTF-8 name encoded `%FF`, copy out of trash by original name (stream path), cancel mid-file (partial removed), chmod 000 → PermissionDenied flagged, rest copied; empty trash; real `~/.local/share/Trash` untouched. +- Not verified: per-mount `.Trash-$uid` trash and cross-device move (no second filesystem inside the scratchpad). Workspace `cargo fmt --check` fails only on S005's in-progress `crates/tunal/src/main.rs`. +- Later: trash `directorysizes` cache; orphan `.trashinfo` cleanup on empty; trash watch for live trash view; checking free space before copy. + ## Later -