diff --git a/Cargo.lock b/Cargo.lock index b087f5b..acf54ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2232,6 +2232,26 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "input" version = "0.10.0" @@ -2372,6 +2392,26 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.2", + "libc", +] + [[package]] name = "ksni" version = "0.3.7" @@ -2601,6 +2641,22 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2627,6 +2683,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -2751,6 +2819,46 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "notify" +version = "8.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab" +dependencies = [ + "bitflags 2.13.2", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "objc2-core-foundation", + "objc2-core-services", + "walkdir", + "windows-sys 0.61.2", +] + +[[package]] +name = "notify-debouncer-mini" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17849edfaabd9a5fef1c606d99cfc615a8e99f7ac4366406d86c7942a3184cf2" +dependencies = [ + "log", + "notify", + "notify-types", + "tempfile", +] + +[[package]] +name = "notify-types" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2922,6 +3030,16 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-services" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-core-text" version = "0.3.2" @@ -4562,6 +4680,10 @@ dependencies = [ [[package]] name = "tunal-core" version = "0.1.0" +dependencies = [ + "mime_guess", + "notify-debouncer-mini", +] [[package]] name = "tunal-devices" @@ -4797,6 +4919,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" diff --git a/Cargo.toml b/Cargo.toml index 4006779..3deada7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,3 +14,5 @@ slint-build = "1.19" zbus = { version = "5.19", default-features = false, features = ["async-io", "blocking-api"] } material-colors = "0.5" png = "0.18" +notify-debouncer-mini = { version = "0.7", default-features = false } +mime_guess = "2.0" diff --git a/Plans/03 File browsing/S006-location-layer.md b/Plans/03 File browsing/S006-location-layer.md index 8d43031..98ef3bb 100644 --- a/Plans/03 File browsing/S006-location-layer.md +++ b/Plans/03 File browsing/S006-location-layer.md @@ -10,13 +10,13 @@ The protocol-neutral location layer every view talks to, plus the local backend: CLAUDE.md §3 (location layer rule), §4; PROMPT.md §Network connections (last bullet). ## Steps -- [ ] Types: `Uri` (scheme, authority, path as bytes; `file://` paths keep `OsString`), `Entry` (raw name + lossy display name, kind incl. symlink target and target kind, size, mtime, mode, uid/gid, hidden), `Error` (NotFound, PermissionDenied, Exists, NotEmpty, Unsupported, Cancelled, Io, Remote) with `needs_elevation()`. -- [ ] `Location` trait (`Send + Sync`): chunked `list`, `stat`, `open_read`, `open_write`, `mkdir`, `rename`, `delete`, `trash`, `symlink`, `capabilities()`, `watch()`; unsupported operations default to `Unsupported`. -- [ ] `Locations` registry: scheme → backend; resolve a `Uri` to its backend. -- [ ] Local backend: `lstat`-based listing (symlinks not followed, target kind resolved), permission-denied folders return an error, non-UTF-8 names intact; watching with `notify` (inotify), debounced. -- [ ] Mime guess by extension (`mime_guess`); folders/symlinks typed. -- [ ] Example `cargo run -p tunal-core --example ls -- ` prints entries and timing. -- [ ] PROGRESS entry, INDEX line, commit `S006: …` +- [x] Types: `Uri` (scheme, authority, path as bytes; `file://` paths keep `OsString`), `Entry` (raw name + lossy display name, kind incl. symlink target and target kind, size, mtime, mode, uid/gid, hidden), `Error` (NotFound, PermissionDenied, Exists, NotEmpty, Unsupported, Cancelled, Io, Remote) with `needs_elevation()`. +- [x] `Location` trait (`Send + Sync`): chunked `list`, `stat`, `open_read`, `open_write`, `mkdir`, `rename`, `delete`, `trash`, `symlink`, `capabilities()`, `watch()`; unsupported operations default to `Unsupported`. +- [x] `Locations` registry: scheme → backend; resolve a `Uri` to its backend. +- [x] Local backend: `lstat`-based listing (symlinks not followed, target kind resolved), permission-denied folders return an error, non-UTF-8 names intact; watching with `notify` (inotify), debounced. +- [x] Mime guess by extension (`mime_guess`); folders/symlinks typed. +- [x] Example `cargo run -p tunal-core --example ls -- ` prints entries and timing. +- [x] PROGRESS entry, INDEX line, commit `S006: …` ## 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 91b35bf..e84eac0 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -17,7 +17,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 03 File browsing -- [ ] [S006 — Location layer and local backend](03%20File%20browsing/S006-location-layer.md) · Opus medium +- [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 - [ ] [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 diff --git a/crates/tunal-core/Cargo.toml b/crates/tunal-core/Cargo.toml index e2c99ba..b303885 100644 --- a/crates/tunal-core/Cargo.toml +++ b/crates/tunal-core/Cargo.toml @@ -4,3 +4,7 @@ version.workspace = true edition.workspace = true license.workspace = true publish.workspace = true + +[dependencies] +notify-debouncer-mini.workspace = true +mime_guess.workspace = true diff --git a/crates/tunal-core/examples/ls.rs b/crates/tunal-core/examples/ls.rs new file mode 100644 index 0000000..b898205 --- /dev/null +++ b/crates/tunal-core/examples/ls.rs @@ -0,0 +1,98 @@ +//! Lists folders through the location layer and prints timing. +//! `cargo run -p tunal-core --example ls -- [--watch] ...` + +use std::io::{BufWriter, Write}; +use std::ops::ControlFlow; +use std::path::Path; +use std::time::Instant; + +use tunal_core::{Kind, Locations, Uri, WatchEvent, display_name}; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let watch = args.iter().any(|a| a == "--watch"); + let dirs: Vec<&String> = args.iter().filter(|a| *a != "--watch").collect(); + if dirs.is_empty() { + eprintln!("usage: ls [--watch] ..."); + std::process::exit(2); + } + + let locations = Locations::with_local(); + let mut failed = false; + for dir in &dirs { + let uri = Uri::from_path(Path::new(dir)); + let backend = locations.resolve(&uri).expect("file backend registered"); + let start = Instant::now(); + let mut out = BufWriter::new(std::io::stdout().lock()); + let (mut count, mut chunks) = (0, 0); + let result = backend.list(&uri, &mut |entries| { + chunks += 1; + for e in entries { + count += 1; + let kind = match &e.kind { + Kind::File => "file".to_owned(), + Kind::Dir => "dir".to_owned(), + Kind::Special => "special".to_owned(), + Kind::Symlink { + target, + target_type, + } => format!("link -> {} ({target_type:?})", display_name(target)), + }; + let _ = writeln!( + out, + "{:04o} {:>5}:{:<5} {:>10} {:<28} {}{} [{kind}]", + e.mode, + e.uid, + e.gid, + e.size, + e.mime, + e.display_name, + if e.hidden { " (hidden)" } else { "" }, + ); + if e.display_name.as_bytes() != e.name { + let _ = writeln!(out, " raw: {}", uri.join(&e.name)); + } + } + ControlFlow::Continue(()) + }); + drop(out); + let elapsed = start.elapsed(); + match result { + Ok(()) => eprintln!("{uri}: {count} entries in {chunks} chunks, {elapsed:.2?}"), + Err(e) => { + failed = true; + eprintln!( + "{uri}: error: {e:?} ({e}), needs elevation: {}", + e.needs_elevation() + ); + } + } + } + + if watch { + let uri = Uri::from_path(Path::new(dirs[0])); + let backend = locations.resolve(&uri).expect("file backend registered"); + let _watch = backend + .watch( + &uri, + Box::new(|event| match event { + WatchEvent::Changed(uris) => { + let names: Vec = uris + .iter() + .map(|u| display_name(u.file_name().unwrap_or(b"/"))) + .collect(); + eprintln!("changed ({}): {}", names.len(), names.join(", ")); + } + WatchEvent::Error(e) => eprintln!("watch error: {e}"), + }), + ) + .unwrap_or_else(|e| panic!("watch {uri}: {e}")); + eprintln!("watching {uri}; Ctrl+C to stop"); + loop { + std::thread::park(); + } + } + if failed { + std::process::exit(1); + } +} diff --git a/crates/tunal-core/src/entry.rs b/crates/tunal-core/src/entry.rs new file mode 100644 index 0000000..334a77b --- /dev/null +++ b/crates/tunal-core/src/entry.rs @@ -0,0 +1,57 @@ +//! One item of a folder listing. + +use std::time::SystemTime; + +/// What an entry (or a symlink target) is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileType { + File, + Dir, + /// Device, fifo, socket. + Special, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Kind { + File, + Dir, + Special, + /// The link itself; `target_type` is `None` when the target is missing (broken link). + Symlink { + target: Vec, + target_type: Option, + }, +} + +impl Kind { + /// True for folders and links to folders. + pub fn is_dir(&self) -> bool { + matches!( + self, + Self::Dir + | Self::Symlink { + target_type: Some(FileType::Dir), + .. + } + ) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// Raw name bytes, exactly as the backend returned them. + pub name: Vec, + /// `name` decoded lossily, for display only. + pub display_name: String, + pub kind: Kind, + /// Bytes (of the link itself for symlinks). + pub size: u64, + pub mtime: Option, + /// Permission bits (`0o7777`), 0 when the backend has none. + pub mode: u32, + pub uid: u32, + pub gid: u32, + pub hidden: bool, + /// MIME type: guessed by extension for files, `inode/*` for the rest. + pub mime: &'static str, +} diff --git a/crates/tunal-core/src/error.rs b/crates/tunal-core/src/error.rs new file mode 100644 index 0000000..3e11f57 --- /dev/null +++ b/crates/tunal-core/src/error.rs @@ -0,0 +1,56 @@ +//! Errors shared by every location backend. + +use std::fmt; +use std::io; + +pub type Result = std::result::Result; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + NotFound, + PermissionDenied, + Exists, + NotEmpty, + Unsupported, + Cancelled, + /// Any other local I/O failure, with the OS message. + Io(String), + /// A failure reported by a remote peer (device, server), with its message. + Remote(String), +} + +impl Error { + /// True when retrying the operation as root could succeed. + pub fn needs_elevation(&self) -> bool { + matches!(self, Self::PermissionDenied) + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + match e.kind() { + io::ErrorKind::NotFound => Self::NotFound, + io::ErrorKind::PermissionDenied => Self::PermissionDenied, + io::ErrorKind::AlreadyExists => Self::Exists, + io::ErrorKind::DirectoryNotEmpty => Self::NotEmpty, + io::ErrorKind::Unsupported => Self::Unsupported, + _ => Self::Io(e.to_string()), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotFound => f.write_str("not found"), + Self::PermissionDenied => f.write_str("permission denied"), + Self::Exists => f.write_str("already exists"), + Self::NotEmpty => f.write_str("folder is not empty"), + Self::Unsupported => f.write_str("not supported here"), + Self::Cancelled => f.write_str("cancelled"), + Self::Io(msg) | Self::Remote(msg) => f.write_str(msg), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/tunal-core/src/lib.rs b/crates/tunal-core/src/lib.rs index ce99a9a..a1865d8 100644 --- a/crates/tunal-core/src/lib.rs +++ b/crates/tunal-core/src/lib.rs @@ -1 +1,16 @@ //! Filesystem model, file operations and the location layer. + +mod entry; +mod error; +mod local; +mod location; +pub mod mime; +mod registry; +mod uri; + +pub use entry::{Entry, FileType, Kind}; +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 uri::{FILE, Uri, display_name}; diff --git a/crates/tunal-core/src/local.rs b/crates/tunal-core/src/local.rs new file mode 100644 index 0000000..f0148a3 --- /dev/null +++ b/crates/tunal-core/src/local.rs @@ -0,0 +1,200 @@ +//! `file://` backend on the local filesystem. + +use std::ffi::OsString; +use std::fs::{self, Metadata, OpenOptions}; +use std::io::{Read, Write}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::os::unix::fs::{FileTypeExt, MetadataExt}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use notify_debouncer_mini::{new_debouncer, notify}; + +use crate::mime::mime_type; +use crate::{ + Capabilities, Entry, Error, FILE, FileType, Kind, ListSink, Location, Result, Uri, Watch, + WatchCallback, WatchEvent, WriteMode, display_name, +}; + +/// Entries handed to the list sink at once. +const CHUNK: usize = 256; +/// Quiet time before a burst of changes is reported. +const DEBOUNCE: Duration = Duration::from_millis(200); + +#[derive(Clone, Copy, Debug, Default)] +pub struct LocalLocation; + +impl Location for LocalLocation { + fn scheme(&self) -> &str { + FILE + } + + fn capabilities(&self) -> Capabilities { + Capabilities { + write: true, + trash: false, + symlink: true, + watch: true, + permissions: true, + } + } + + fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> { + let dir = local_path(dir)?; + let mut chunk = Vec::with_capacity(CHUNK); + for item in fs::read_dir(&dir)? { + let Ok(item) = item else { continue }; + // DirEntry::metadata does not follow symlinks; entries that vanish are skipped. + let Ok(meta) = item.metadata() else { continue }; + let name = item.file_name().into_vec(); + chunk.push(entry(name, &item.path(), &meta)); + if chunk.len() == CHUNK { + let full = std::mem::replace(&mut chunk, Vec::with_capacity(CHUNK)); + if sink(full).is_break() { + return Err(Error::Cancelled); + } + } + } + if !chunk.is_empty() && sink(chunk).is_break() { + return Err(Error::Cancelled); + } + Ok(()) + } + + fn stat(&self, uri: &Uri) -> Result { + let path = local_path(uri)?; + let meta = fs::symlink_metadata(&path)?; + let name = uri.file_name().unwrap_or(b"/").to_vec(); + Ok(entry(name, &path, &meta)) + } + + fn open_read(&self, uri: &Uri) -> Result> { + Ok(Box::new(fs::File::open(local_path(uri)?)?)) + } + + fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result> { + let mut options = OpenOptions::new(); + options.write(true); + match mode { + WriteMode::CreateNew => options.create_new(true), + WriteMode::Overwrite => options.create(true).truncate(true), + }; + Ok(Box::new(options.open(local_path(uri)?)?)) + } + + fn mkdir(&self, uri: &Uri) -> Result<()> { + Ok(fs::create_dir(local_path(uri)?)?) + } + + fn rename(&self, from: &Uri, to: &Uri) -> Result<()> { + let (from, to) = (local_path(from)?, local_path(to)?); + // fs::rename replaces silently; refuse instead (a racing creator can still win). + if fs::symlink_metadata(&to).is_ok() { + return Err(Error::Exists); + } + Ok(fs::rename(from, to)?) + } + + fn delete(&self, uri: &Uri) -> Result<()> { + let path = local_path(uri)?; + if fs::symlink_metadata(&path)?.is_dir() { + Ok(fs::remove_dir(path)?) + } else { + Ok(fs::remove_file(path)?) + } + } + + 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)?)?) + } + + fn watch(&self, dir: &Uri, callback: WatchCallback) -> Result { + let path = local_path(dir)?; + let mut debouncer = new_debouncer( + DEBOUNCE, + move |res: notify_debouncer_mini::DebounceEventResult| { + callback(match res { + Ok(events) => { + let mut uris: Vec = + events.iter().map(|e| Uri::from_path(&e.path)).collect(); + uris.sort_by(|a, b| a.path().cmp(b.path())); + uris.dedup(); + WatchEvent::Changed(uris) + } + Err(e) => WatchEvent::Error(notify_error(e)), + }) + }, + ) + .map_err(notify_error)?; + debouncer + .watcher() + .watch(&path, notify::RecursiveMode::NonRecursive) + .map_err(notify_error)?; + Ok(Watch::new(debouncer)) + } +} + +fn local_path(uri: &Uri) -> Result { + uri.to_path().ok_or(Error::Unsupported) +} + +/// Builds an entry from `lstat` data; for symlinks also reads the target and its type. +fn entry(name: Vec, path: &Path, meta: &Metadata) -> Entry { + let ft = meta.file_type(); + let kind = if ft.is_symlink() { + Kind::Symlink { + target: fs::read_link(path) + .map(|t| t.as_os_str().as_bytes().to_vec()) + .unwrap_or_default(), + target_type: fs::metadata(path).ok().map(|m| file_type(&m)), + } + } else { + match file_type(meta) { + FileType::File => Kind::File, + FileType::Dir => Kind::Dir, + FileType::Special => Kind::Special, + } + }; + let mime = if ft.is_fifo() { + "inode/fifo" + } else if ft.is_socket() { + "inode/socket" + } else if ft.is_block_device() { + "inode/blockdevice" + } else if ft.is_char_device() { + "inode/chardevice" + } else { + mime_type(&name, &kind) + }; + Entry { + display_name: display_name(&name), + hidden: name.first() == Some(&b'.'), + kind, + size: meta.len(), + mtime: meta.modified().ok(), + mode: meta.mode() & 0o7777, + uid: meta.uid(), + gid: meta.gid(), + mime, + name, + } +} + +fn file_type(meta: &Metadata) -> FileType { + if meta.is_dir() { + FileType::Dir + } else if meta.is_file() { + FileType::File + } else { + FileType::Special + } +} + +fn notify_error(e: notify::Error) -> Error { + match e.kind { + notify::ErrorKind::Io(io) => io.into(), + notify::ErrorKind::PathNotFound => Error::NotFound, + _ => Error::Io(e.to_string()), + } +} diff --git a/crates/tunal-core/src/location.rs b/crates/tunal-core/src/location.rs new file mode 100644 index 0000000..7547ab4 --- /dev/null +++ b/crates/tunal-core/src/location.rs @@ -0,0 +1,103 @@ +//! The protocol-neutral `Location` trait every view talks to. + +use std::io::{Read, Write}; +use std::ops::ControlFlow; + +use crate::{Entry, Error, Result, Uri}; + +/// What a backend can do, so views can hide actions up front. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Capabilities { + pub write: bool, + pub trash: bool, + pub symlink: bool, + pub watch: bool, + /// Entries carry real `mode`/`uid`/`gid`. + pub permissions: bool, +} + +/// How `open_write` treats an existing file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WriteMode { + /// Fail with `Exists` if the file is there. + CreateNew, + /// Create or truncate. + Overwrite, +} + +/// A debounced change notification for a watched folder. +#[derive(Clone, Debug)] +pub enum WatchEvent { + /// These entries (or the folder itself) were created, changed or removed. + Changed(Vec), + /// Watching failed; the view should fall back to manual refresh. + Error(Error), +} + +/// Keeps a watch alive; dropping it stops watching. +pub struct Watch(#[allow(dead_code)] Box); + +impl Watch { + pub fn new(guard: impl Send + 'static) -> Self { + Self(Box::new(guard)) + } +} + +/// Receives listing chunks; `ControlFlow::Break` stops the listing with `Cancelled`. +pub type ListSink<'a> = dyn FnMut(Vec) -> ControlFlow<()> + 'a; + +/// Called from a backend thread for each watch event. +pub type WatchCallback = Box; + +/// One storage protocol (local, trash, device, SFTP). Object-safe; all calls block, +/// so callers run them off the UI thread. +pub trait Location: Send + Sync { + /// URI scheme this backend serves, e.g. `file`. + fn scheme(&self) -> &str; + + fn capabilities(&self) -> Capabilities { + Capabilities::default() + } + + /// Lists a folder, handing entries to `sink` in chunks as they are read. + fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()>; + + /// Entry for one item (symlinks not followed). + fn stat(&self, uri: &Uri) -> Result; + + fn open_read(&self, _uri: &Uri) -> Result> { + Err(Error::Unsupported) + } + + fn open_write(&self, _uri: &Uri, _mode: WriteMode) -> Result> { + Err(Error::Unsupported) + } + + fn mkdir(&self, _uri: &Uri) -> Result<()> { + Err(Error::Unsupported) + } + + /// Renames or moves within this backend; `Exists` if `to` is taken. + fn rename(&self, _from: &Uri, _to: &Uri) -> Result<()> { + Err(Error::Unsupported) + } + + /// Deletes a file, link or empty folder permanently. + fn delete(&self, _uri: &Uri) -> Result<()> { + Err(Error::Unsupported) + } + + fn trash(&self, _uri: &Uri) -> Result<()> { + Err(Error::Unsupported) + } + + /// Creates `link` pointing at the raw `target` path. + fn symlink(&self, _link: &Uri, _target: &[u8]) -> Result<()> { + Err(Error::Unsupported) + } + + /// Watches a folder's direct children until the returned `Watch` is dropped. + fn watch(&self, _dir: &Uri, _callback: WatchCallback) -> Result { + Err(Error::Unsupported) + } +} diff --git a/crates/tunal-core/src/mime.rs b/crates/tunal-core/src/mime.rs new file mode 100644 index 0000000..031195c --- /dev/null +++ b/crates/tunal-core/src/mime.rs @@ -0,0 +1,39 @@ +//! MIME type of an entry, guessed from its name. + +use std::ffi::OsStr; +use std::os::unix::ffi::OsStrExt; +use std::path::Path; + +use crate::{FileType, Kind}; + +pub const DIRECTORY: &str = "inode/directory"; +pub const SYMLINK: &str = "inode/symlink"; +pub const UNKNOWN: &str = "application/octet-stream"; + +/// Folders (and links to them) are `inode/directory`, broken links `inode/symlink`, +/// files are guessed by extension, links to files by their own name, then the target's. +pub fn mime_type(name: &[u8], kind: &Kind) -> &'static str { + match kind { + Kind::Dir => DIRECTORY, + Kind::Special => UNKNOWN, + Kind::Symlink { + target, + target_type, + } => match target_type { + None => SYMLINK, + Some(FileType::Dir) => DIRECTORY, + Some(FileType::Special) => UNKNOWN, + Some(FileType::File) => match by_extension(name) { + UNKNOWN => by_extension(target), + mime => mime, + }, + }, + Kind::File => by_extension(name), + } +} + +fn by_extension(name: &[u8]) -> &'static str { + mime_guess::from_path(Path::new(OsStr::from_bytes(name))) + .first_raw() + .unwrap_or(UNKNOWN) +} diff --git a/crates/tunal-core/src/registry.rs b/crates/tunal-core/src/registry.rs new file mode 100644 index 0000000..d2aa3f3 --- /dev/null +++ b/crates/tunal-core/src/registry.rs @@ -0,0 +1,41 @@ +//! Scheme → backend registry. + +use std::collections::HashMap; +use std::sync::Arc; + +use crate::{Error, LocalLocation, Location, Result, Uri}; + +/// All registered backends, looked up by URI scheme. Cheap to clone. +#[derive(Clone, Default)] +pub struct Locations { + backends: HashMap>, +} + +impl Locations { + /// Empty registry. + pub fn new() -> Self { + Self::default() + } + + /// Registry with the local `file://` backend. + pub fn with_local() -> Self { + let mut locations = Self::new(); + locations.register(Arc::new(LocalLocation)); + locations + } + + /// Adds (or replaces) the backend for its scheme. + pub fn register(&mut self, backend: Arc) { + self.backends + .insert(backend.scheme().to_ascii_lowercase(), backend); + } + + pub fn get(&self, scheme: &str) -> Option<&Arc> { + self.backends.get(&scheme.to_ascii_lowercase()) + } + + /// Backend serving `uri`, `Unsupported` for unknown schemes. + pub fn resolve(&self, uri: &Uri) -> Result> { + self.get(uri.scheme()).cloned().ok_or(Error::Unsupported) + } +} diff --git a/crates/tunal-core/src/uri.rs b/crates/tunal-core/src/uri.rs new file mode 100644 index 0000000..39998b5 --- /dev/null +++ b/crates/tunal-core/src/uri.rs @@ -0,0 +1,147 @@ +//! Location URIs: `scheme://authority/path`, path kept as raw bytes. + +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::path::{Path, PathBuf}; + +/// Scheme of local files. +pub const FILE: &str = "file"; + +/// A location address. The path is raw bytes, so non-UTF-8 names survive; +/// for `file://` it maps 1:1 to an `OsString`. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Uri { + scheme: String, + authority: String, + path: Vec, +} + +impl Uri { + /// Builds a URI; an empty path becomes `/`. + pub fn new(scheme: &str, authority: &str, path: impl Into>) -> Self { + let mut path = path.into(); + if path.first() != Some(&b'/') { + path.insert(0, b'/'); + } + Self { + scheme: scheme.to_ascii_lowercase(), + authority: authority.to_owned(), + path, + } + } + + /// `file://` URI for a local path (made absolute against the current dir if relative). + pub fn from_path(path: &Path) -> Self { + let path = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); + Self::new(FILE, "", path.into_os_string().into_vec()) + } + + /// Parses `scheme://authority/path` with `%XX` escapes in the path. + pub fn parse(s: &str) -> Option { + let (scheme, rest) = s.split_once("://")?; + let valid = scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); + if !valid { + return None; + } + let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + Some(Self::new(scheme, authority, percent_decode(path)?)) + } + + pub fn scheme(&self) -> &str { + &self.scheme + } + + pub fn authority(&self) -> &str { + &self.authority + } + + /// Raw path bytes, always starting with `/`. + pub fn path(&self) -> &[u8] { + &self.path + } + + /// Local path for `file://` URIs. + pub fn to_path(&self) -> Option { + (self.scheme == FILE).then(|| PathBuf::from(OsString::from_vec(self.path.clone()))) + } + + /// Last path component, `None` at the root. + pub fn file_name(&self) -> Option<&[u8]> { + let trimmed = self.trimmed(); + let name = &trimmed[trimmed.iter().rposition(|&b| b == b'/')? + 1..]; + (!name.is_empty()).then_some(name) + } + + /// Parent folder, `None` at the root. + pub fn parent(&self) -> Option { + let trimmed = self.trimmed(); + let cut = trimmed.iter().rposition(|&b| b == b'/')?; + (trimmed.len() > 1).then(|| Self::new(&self.scheme, &self.authority, &trimmed[..cut])) + } + + /// Child `name` (a single component) inside this folder. + pub fn join(&self, name: &[u8]) -> Self { + let mut path = self.trimmed().to_vec(); + if path.last() != Some(&b'/') { + path.push(b'/'); + } + path.extend_from_slice(name); + Self::new(&self.scheme, &self.authority, path) + } + + /// Path without trailing slashes (but `/` stays `/`). + fn trimmed(&self) -> &[u8] { + let end = self + .path + .iter() + .rposition(|&b| b != b'/') + .map_or(1, |i| i + 1); + &self.path[..end] + } +} + +impl From<&Path> for Uri { + fn from(path: &Path) -> Self { + Self::from_path(path) + } +} + +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(()) + } +} + +/// 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> { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?; + out.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + Some(out) +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 175e3b6..ccb57af 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -25,3 +25,4 @@ D-020 — 2026-11-18 — Accepted SSH host keys go to `$XDG_CONFIG_HOME/tunal/kn D-021 — 2026-11-18 — Playlist sort: a sort option "Playlist sort" offered only in folders under XDG_MUSIC_DIR that contain a playlist file (.m3u, .m3u8, .pls, .xspf); listed files first in playlist order, unlisted entries after in natural name order; several playlists → one option each; desc reverses; re-sorts when the playlist changes; stored as the folder's sort in `.directory` like other sorts — user request (details chosen by orchestrator, user may revise) — S008, S015. D-022 — 2026-11-18 — Fallback theme seed `#3F6FB5` (muted blue) when the portal gives no accent; palettes are `material-colors` 0.5 `ThemeBuilder` defaults (tonal spot, spec 2021) exported as ARGB `Palette` structs; library warnings go to stderr as one `tunal-theme: …` line (no logging crate yet) — S002 — S002, S003. D-023 — 2026-11-18 — Window minimum size 720×480 px (preferred 960×640): fits a 240 px sidebar plus a usable content column; Slint 1.19 can't drive the icon font's variation axes (font-weight doesn't reach `wght`), so `Icon` has size only and draws the default instance (wght 400, FILL 0); easing tokens live in an internal `Motion` global and Rust sets the reduced flag through `MotionPrefs` (easing properties can't be exported) — S003 — S003 and every UI plan. +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. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 43461be..0f3784f 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -20,5 +20,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: live re-theme not observed end to end (no D-Bus Python bindings for a fake portal); the path is `watch` (verified in S002) → `apply` (verified by screenshots). Icon weight/fill: not settable in Slint 1.19 (D-023). - Later: icon weight/fill if Slint gains font variations; screenshot hover/press states need a controlled clock (phase 12). +## S006 — Location layer and local backend +- Done: `tunal-core` types `Uri` (scheme, authority, path as raw bytes; `Uri::from_path/parse/to_path/join/parent/file_name`, Display percent-encodes the path, e.g. `file:///a/b%FFc`), `Entry { name: Vec, display_name, kind: Kind, size, mtime: Option, mode (0o7777), uid, gid, hidden, mime: &'static str }`, `Kind::{File, Dir, Special, Symlink { target: Vec, target_type: Option }}` (`None` = broken), `Error::{NotFound, PermissionDenied, Exists, NotEmpty, Unsupported, Cancelled, Io(String), Remote(String)}` + `needs_elevation()`, `From`. +- Trait `Location: Send + Sync` (object-safe, blocking): `scheme()`, `capabilities() -> Capabilities { write, trash, symlink, watch, permissions }`, `list(&Uri, &mut dyn FnMut(Vec) -> ControlFlow<()>)` (Break → `Cancelled`), `stat` (lstat), `open_read -> Box`, `open_write(&Uri, WriteMode::{CreateNew, Overwrite})`, `mkdir`, `rename` (`Exists` if target taken), `delete` (file/link/empty dir), `trash`, `symlink(link, target: &[u8])`, `watch(&Uri, Box) -> Watch` (drop stops; `WatchEvent::{Changed(Vec), Error}`); defaults → `Unsupported`. `Locations` registry (`with_local()`, `register`, `get`, `resolve`). `LocalLocation` (`file`): 256-entry chunks, `notify-debouncer-mini` 0.7 (200 ms, non-recursive); trash Unsupported until S007. `mime::mime_type(name, kind)` (`mime_guess`; dirs `inode/directory`, broken links `inode/symlink`, links by own name then target; local fifo/socket/devices `inode/*`). Example `ls [--watch] ...`. +- Verified: workspace build, clippy -D warnings, fmt --check; scratch dir (non-UTF-8 name shown raw as `%FF`, broken/dir/file links, fifo, hidden, `chmod 000` folder → PermissionDenied, 10 000 files in 36 ms debug / 15 ms release); `--watch` reported create/modify/delete/mkdir once per path. +- Not done: nothing. URI schemes `trash:///`, `ios://`, `mtp://`, `sftp://user@host:port/path` come with their plans. +- Later: local `rename` uses a check-then-rename (race); `renameat2(RENAME_NOREPLACE)` would need `libc`/`rustix`. + ## Later -