From ef04575f35cb175bd322888b136736db3b28b806 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 14:30:02 -0600 Subject: [PATCH] devices: USB drives and other disks in the sidebar, with mount and unmount Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + FEATURES.md | 2 +- README.md | 3 +- crates/tunal-devices/Cargo.toml | 1 + crates/tunal-devices/src/drives.rs | 240 +++++++++++++++++++++ crates/tunal-devices/src/lib.rs | 3 +- crates/tunal/src/devices_bridge.rs | 295 +++++++++++++++++++++++--- crates/tunal/src/shell/mod.rs | 62 ++++-- crates/tunal/src/shell/places.rs | 5 +- crates/tunal/ui/app.slint | 4 + crates/tunal/ui/components/icon.slint | 1 + crates/tunal/ui/shell/sidebar.slint | 19 ++ docs/PROGRESS.md | 5 + packaging/arch/PKGBUILD | 1 + 14 files changed, 591 insertions(+), 51 deletions(-) create mode 100644 crates/tunal-devices/src/drives.rs diff --git a/Cargo.lock b/Cargo.lock index 3852279..4a19ac2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7107,6 +7107,7 @@ dependencies = [ "tempfile", "tokio", "tunal-core", + "zbus", ] [[package]] diff --git a/FEATURES.md b/FEATURES.md index 249e8c2..2ed28ab 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -48,6 +48,7 @@ Status: done = built and checked here; built, awaiting real-world check = built |---|---|---|---| | iOS browsing and transfer over AFC | built, awaiting real-world check | S024 | tunal-devices | | Android browsing and transfer over MTP | built, awaiting real-world check | S025, S026 | tunal-devices | +| USB drives and other disks through UDisks: mount, open, unmount, safely remove | done | user request | tunal-devices | ## Network @@ -69,7 +70,6 @@ Status: done = built and checked here; built, awaiting real-world check = built | Feature | Status | |---|---| -| Removable drives through UDisks (mount, eject) | Later | | Recursive file search and content indexing | Later | | Plugins and service menus | Out of scope | | Embedded terminal panel | Out of scope | diff --git a/README.md b/README.md index 014e5d8..56c16b4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Tunal is a desktop file manager for Linux (Wayland and X11), written in Rust with [Slint](https://slint.dev) and Material You styling. It follows the system accent colour and light/dark mode, and animates navigation, lists, menus and dialogs. -Features: tabs, split view, places, file operations with trash, `.directory` folder metadata, sudo elevation, thumbnails, a music tag editor, a quick audio player, iOS/Android device browsing and SFTP locations. See [FEATURES.md](FEATURES.md) for every feature and its status and [PLAN.md](PLAN.md) for the roadmap. +Features: tabs, split view, places, file operations with trash, `.directory` folder metadata, sudo elevation, thumbnails, a music tag editor, a quick audio player, USB drives, iOS/Android device browsing and SFTP locations. See [FEATURES.md](FEATURES.md) for every feature and its status and [PLAN.md](PLAN.md) for the roadmap. ## Build and run @@ -76,6 +76,7 @@ Everything compiles into the `tunal` binary. Optional tools only switch their fe - `ffmpeg` / `ffprobe`: video frame thumbnails - `usbmuxd`: iOS devices +- `udisks2`: USB drives, memory cards, discs and other disks in the sidebar - a polkit agent with `pkexec`: root operations - `xdg-desktop-portal`: accent colour and dark mode (a fixed fallback colour is used without it) diff --git a/crates/tunal-devices/Cargo.toml b/crates/tunal-devices/Cargo.toml index 6a9a331..0a799c4 100644 --- a/crates/tunal-devices/Cargo.toml +++ b/crates/tunal-devices/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true publish.workspace = true [dependencies] +zbus.workspace = true nusb.workspace = true jiff.workspace = true tunal-core = { path = "../tunal-core" } diff --git a/crates/tunal-devices/src/drives.rs b/crates/tunal-devices/src/drives.rs new file mode 100644 index 0000000..21120d1 --- /dev/null +++ b/crates/tunal-devices/src/drives.rs @@ -0,0 +1,240 @@ +//! Drives (USB sticks and disks, memory cards, discs, other inner disks) through UDisks2 on the +//! system bus: listing, hotplug, mount, unmount and safe removal. Their files are plain local +//! folders, so there is no backend here. + +use std::collections::HashMap; +use std::ffi::OsString; +use std::os::unix::ffi::OsStringExt; +use std::path::{Path, PathBuf}; +use std::thread; + +use zbus::blocking::{Connection, MessageIterator, Proxy}; +use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; +use zbus::{MatchRule, message::Type}; + +const SERVICE: &str = "org.freedesktop.UDisks2"; +const ROOT: &str = "/org/freedesktop/UDisks2"; +const BLOCK: &str = "org.freedesktop.UDisks2.Block"; +const DRIVE: &str = "org.freedesktop.UDisks2.Drive"; +const PARTITION: &str = "org.freedesktop.UDisks2.Partition"; +/// GPT types of the partitions a computer starts from, and a disk's recovery and reserved ones. +const HIDDEN_TYPES: [&str; 4] = [ + "c12a7328-f81f-11d2-ba4b-00a0c93ec93b", + "bc13c2ff-59e6-4262-a352-b275fd6f7172", + "de94bba4-06d1-4d40-a16a-bfd50179d6ac", + "e3c9e316-0b5c-4db8-817d-f92df00215ae", +]; +const FILESYSTEM: &str = "org.freedesktop.UDisks2.Filesystem"; + +type Interfaces = HashMap>; +type Objects = HashMap; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Usb, + Card, + Disc, + Other, +} + +/// How the whole drive is made safe to take out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Removal { + PowerOff, + Eject, +} + +/// A file system on a drive. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Volume { + /// UDisks object path of the block device: the volume's id here. + pub block: String, + /// Object path of the drive it is on, if UDisks knows it. + pub drive: Option, + /// Its label, empty for none. + pub label: String, + pub kind: Kind, + pub size: u64, + pub mount: Option, + pub removal: Option, +} + +#[derive(Debug)] +pub enum Error { + /// The user closed the password prompt. + Dismissed, + /// A message to show. + Failed(String), +} + +impl From for Error { + fn from(err: zbus::Error) -> Self { + let zbus::Error::MethodError(name, detail, _) = &err else { + return Self::Failed(err.to_string()); + }; + match name.rsplit('.').next().unwrap_or_default() { + "NotAuthorizedDismissed" => Self::Dismissed, + "NotAuthorized" | "NotAuthorizedCanObtain" => Self::Failed("not allowed".into()), + "DeviceBusy" => Self::Failed("a program still uses it".into()), + _ => Self::Failed(detail.clone().unwrap_or_else(|| name.to_string())), + } + } +} + +/// Calls `on_change` on a background thread with the volumes now and after every change. The +/// thread ends (after one stderr line) when UDisks is not there. +pub fn watch(on_change: impl Fn(Vec) + Send + 'static) { + thread::spawn(move || { + if let Err(err) = watch_loop(on_change) { + eprintln!("tunal: removable drives: {err}"); + } + }); +} + +fn watch_loop(on_change: impl Fn(Vec)) -> zbus::Result<()> { + // Calls have their own connection: a full signal queue must not hold up their replies. + let calls = Connection::system()?; + let rule = MatchRule::builder() + .msg_type(Type::Signal) + .sender(SERVICE)? + .path_namespace(ROOT)? + .build(); + // Subscribe before listing so a change in between is not lost. + let signals = MessageIterator::for_match_rule(rule, &Connection::system()?, Some(64))?; + let mut current = volumes(&calls)?; + on_change(current.clone()); + for message in signals { + message?; + let next = volumes(&calls)?; + if next != current { + current = next; + on_change(current.clone()); + } + } + Ok(()) +} + +fn volumes(conn: &Connection) -> zbus::Result> { + let manager = Proxy::new(conn, SERVICE, ROOT, "org.freedesktop.DBus.ObjectManager")?; + let objects: Objects = manager.call("GetManagedObjects", &())?; + let mut found: Vec = objects + .iter() + .filter_map(|(path, interfaces)| volume(path.as_str(), interfaces, &objects)) + .collect(); + found.sort_by(|a, b| a.block.cmp(&b.block)); + Ok(found) +} + +/// The volume at `path`, unless it has no file system or is part of the running system. +fn volume(path: &str, interfaces: &Interfaces, objects: &Objects) -> Option { + let block = interfaces.get(BLOCK)?; + let filesystem = interfaces.get(FILESYSTEM)?; + // An inner disk. + let system = flag(block, "HintSystem"); + let mounts: Vec = value::>>(filesystem, "MountPoints") + .unwrap_or_default() + .into_iter() + .map(|mut bytes| { + // Paths come with their NUL. + bytes.retain(|b| *b != 0); + PathBuf::from(OsString::from_vec(bytes)) + }) + .collect(); + let hidden_type = interfaces + .get(PARTITION) + .and_then(|p| value::(p, "Type")) + .is_some_and(|t| HIDDEN_TYPES.contains(&t.as_str())); + if flag(block, "HintIgnore") + || (system && (hidden_type || mounts.iter().any(|m| !is_storage(m)))) + { + return None; + } + let mount = mounts.into_iter().next(); + // "/" stands for no drive (an unlocked encrypted volume). + let drive = value::(block, "Drive").filter(|d| d.as_str() != "/"); + let about = drive + .as_ref() + .and_then(|d| objects.get(d)) + .and_then(|i| i.get(DRIVE)); + let kind = about.map_or(Kind::Other, kind); + Some(Volume { + block: path.to_owned(), + drive: drive.map(|d| d.as_str().to_owned()), + label: value(block, "IdLabel").unwrap_or_default(), + kind, + size: value(block, "Size").unwrap_or_default(), + mount, + removal: about.filter(|_| !system).and_then(|d| match kind { + // Powering off would take the whole card reader or disc drive away. + Kind::Card | Kind::Disc => flag(d, "Ejectable").then_some(Removal::Eject), + _ if flag(d, "CanPowerOff") => Some(Removal::PowerOff), + _ => flag(d, "Ejectable").then_some(Removal::Eject), + }), + }) +} + +/// True for a folder disks are mounted under for their files, not for the system to run on. +fn is_storage(mount: &Path) -> bool { + ["/run/media", "/media", "/mnt"] + .iter() + .any(|dir| mount.starts_with(dir)) +} + +fn kind(drive: &HashMap) -> Kind { + let text = |key| value::(drive, key).unwrap_or_default(); + let (bus, media) = (text("ConnectionBus"), text("Media")); + if media.starts_with("optical") || flag(drive, "Optical") { + Kind::Disc + } else if bus == "sdio" || media.starts_with("flash") { + Kind::Card + } else if bus == "usb" { + Kind::Usb + } else { + Kind::Other + } +} + +fn value>(map: &HashMap, key: &str) -> Option { + T::try_from(map.get(key)?.try_clone().ok()?).ok() +} + +fn flag(map: &HashMap, key: &str) -> bool { + value(map, key).unwrap_or_default() +} + +/// Calls `method` of `interface` with no options: polkit may ask the user. +fn call(path: &str, interface: &str, method: &str) -> Result +where + R: for<'d> zbus::zvariant::DynamicDeserialize<'d>, +{ + let conn = Connection::system()?; + let proxy = Proxy::new(&conn, SERVICE, path, interface)?; + Ok(proxy.call(method, &(HashMap::<&str, Value>::new(),))?) +} + +/// Mounts `volume` and returns its folder. Blocks; call it off the UI thread. +pub fn mount(volume: &Volume) -> Result { + call::(&volume.block, FILESYSTEM, "Mount").map(PathBuf::from) +} + +/// Writes what is pending and unmounts `volume`. Blocks, for minutes after a large copy. +pub fn unmount(volume: &Volume) -> Result<(), Error> { + call(&volume.block, FILESYSTEM, "Unmount") +} + +/// Unmounts every volume of `volume`'s drive and makes the drive safe to take out. Blocks. +pub fn remove(volume: &Volume) -> Result<(), Error> { + let (Some(drive), Some(removal)) = (&volume.drive, volume.removal) else { + return unmount(volume); + }; + for v in volumes(&Connection::system()?)? { + if v.drive.as_ref() == Some(drive) && v.mount.is_some() { + unmount(&v)?; + } + } + let method = match removal { + Removal::PowerOff => "PowerOff", + Removal::Eject => "Eject", + }; + call(drive, DRIVE, method) +} diff --git a/crates/tunal-devices/src/lib.rs b/crates/tunal-devices/src/lib.rs index bcd3ceb..e4b14f9 100644 --- a/crates/tunal-devices/src/lib.rs +++ b/crates/tunal-devices/src/lib.rs @@ -1,5 +1,6 @@ -//! iOS and Android device locations. +//! iOS and Android device locations, and removable drives. +pub mod drives; pub mod ios; pub mod mtp; diff --git a/crates/tunal/src/devices_bridge.rs b/crates/tunal/src/devices_bridge.rs index 7866539..d3e9eda 100644 --- a/crates/tunal/src/devices_bridge.rs +++ b/crates/tunal/src/devices_bridge.rs @@ -1,15 +1,18 @@ -//! Phones in the sidebar: the `mtp://` and `ios://` backends and their hotplug watches, -//! adapted to the shell. +//! Phones and removable drives in the sidebar: the `mtp://` and `ios://` backends, the drives +//! and their hotplug watches, adapted to the shell. use std::cell::RefCell; +use std::collections::HashMap; use std::rc::{Rc, Weak}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use tunal_core::{Locations, Uri}; use tunal_devices::DevicePlace; +use tunal_devices::drives::{self, Kind, Removal, Volume}; use tunal_devices::ios::{self, IosLocation}; use tunal_devices::mtp::{self, MtpLocation}; +use crate::folder::format; use crate::shell::Shell; use crate::shell::places::Place; @@ -17,17 +20,29 @@ use crate::shell::places::Place; const PHONE: &str = "\u{e32c}"; /// Material Symbols `apps`, for an iPhone's `Apps` folder. const APPS: &str = "\u{e5c3}"; +/// Material Symbols `usb`, `sd_card`, `album`, `hard_drive`. +const USB: &str = "\u{e1e0}"; +const CARD: &str = "\u{e623}"; +const DISC: &str = "\u{e019}"; +const DISK: &str = "\u{f80e}"; + +/// Scheme of a drive that is not mounted yet: its path is the drive's id. +const DRIVE_SCHEME: &str = "drive"; thread_local! { static SHELL: RefCell> = const { RefCell::new(Weak::new()) }; static IOS: RefCell>> = const { RefCell::new(None) }; + static LISTS: RefCell = RefCell::default(); } /// Each backend's latest entries; the sidebar shows them together. #[derive(Default)] struct Lists { + drives: Vec, mtp: Vec, ios: Vec, + /// What runs on a drive right now, by its id. + busy: HashMap, } pub struct Backends { @@ -57,13 +72,13 @@ pub fn register(locations: &mut Locations) -> Backends { pub fn attach(shell: &Rc, backends: Backends) { SHELL.with(|s| *s.borrow_mut() = Rc::downgrade(shell)); IOS.with(|i| *i.borrow_mut() = backends.ios.clone()); - let lists = Arc::new(Mutex::new(Lists::default())); + + drives::watch(|list| show(move |l| l.drives = list)); let source = backends.mtp.clone(); - let mtp_lists = lists.clone(); let watched = mtp::watch(backends.mtp, move || { let places = source.places(); - show(&mtp_lists, |l| l.mtp = places); + show(|l| l.mtp = places); }); // No hotplug (no udev netlink in a sandbox): phones just don't show up. if let Err(e) = watched { @@ -74,45 +89,259 @@ pub fn attach(shell: &Rc, backends: Backends) { let source = location.clone(); if let Err(e) = ios::watch(location, move || { let places = source.places(); - show(&lists, |l| l.ios = places); + show(|l| l.ios = places); }) { eprintln!("tunal: iPhones: {e}"); } } } -/// True for sidebar entries that can be ejected: the iPhones themselves, not their `Apps`. -pub fn can_eject(uri: &Uri) -> bool { - uri.scheme() == ios::SCHEME && uri.path() == b"/" +/// An entry of a device's menu. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Item { + Mount, + Unmount, + Remove(Removal), + /// Lets go of a phone. + Eject, } -/// Closes the device at `uri`; it shows again once replugged. -pub fn eject(uri: &Uri) { - let ios = IOS.with(|i| i.borrow().clone()); - if let Some(ios) = ios.filter(|_| can_eject(uri)) { - // Closing talks to no one, but the device lock may wait on a transfer. - let uri = uri.clone(); - std::thread::spawn(move || ios.eject(&uri)); +impl Item { + fn label(self) -> (&'static str, &'static str) { + match self { + Self::Mount => ("Mount", DISK), + Self::Unmount => ("Unmount", "\u{e8fb}"), + Self::Remove(Removal::PowerOff) => ("Safely remove", "\u{e646}"), + Self::Remove(Removal::Eject) | Self::Eject => ("Eject", "\u{e8fb}"), + } } } -/// Updates one backend's list (on a device thread) and shows all of them. -fn show(lists: &Mutex, update: impl FnOnce(&mut Lists)) { - let places: Vec = { - let mut l = lists.lock().unwrap_or_else(|e| e.into_inner()); - update(&mut l); - l.mtp.iter().chain(&l.ios).cloned().collect() +/// The drive a sidebar entry stands for. +fn drive(uri: &Uri) -> Option { + LISTS.with(|l| { + let l = l.borrow(); + l.drives.iter().find(|v| place_uri(v) == *uri).cloned() + }) +} + +fn place_uri(volume: &Volume) -> Uri { + match &volume.mount { + Some(dir) => Uri::from_path(dir), + None => Uri::new(DRIVE_SCHEME, "", volume.block.as_bytes()), + } +} + +fn is_busy(volume: &Volume) -> bool { + LISTS.with(|l| l.borrow().busy.contains_key(&volume.block)) +} + +fn items(uri: &Uri) -> Vec { + if let Some(volume) = drive(uri) { + if is_busy(&volume) { + return Vec::new(); + } + let first = match volume.mount { + Some(_) => Item::Unmount, + None => Item::Mount, + }; + let removal = volume.removal.map(Item::Remove); + return std::iter::once(first).chain(removal).collect(); + } + // The iPhones themselves, not their `Apps`. + if uri.scheme() == ios::SCHEME && uri.path() == b"/" { + return vec![Item::Eject]; + } + Vec::new() +} + +/// Labels and glyphs of the menu items of the entry at `uri`. +pub fn menu_items(uri: &Uri) -> Vec<(&'static str, &'static str)> { + items(uri).into_iter().map(Item::label).collect() +} + +/// Runs menu item `choice` (an index into [`menu_items`]). +pub fn menu_activated(uri: &Uri, choice: usize) { + if let Some(item) = items(uri).get(choice).copied() { + run(uri, item); + } +} + +/// What the button of the entry at `uri` does, if it has one. +pub fn eject_label(uri: &Uri) -> Option<&'static str> { + items(uri) + .into_iter() + .find(|i| matches!(i, Item::Unmount | Item::Eject)) + .map(|i| i.label().0) +} + +/// The button of the entry at `uri` was clicked. +pub fn eject(uri: &Uri) { + let item = items(uri) + .into_iter() + .find(|i| matches!(i, Item::Unmount | Item::Eject)); + if let Some(item) = item { + run(uri, item); + } +} + +/// Mounts a drive that isn't yet and opens it; false for anything else. +pub fn open(uri: &Uri, new_tab: bool) -> bool { + if !is_unmounted(uri) { + return false; + } + if let Some(volume) = drive(uri) { + mount(volume, Some(new_tab)); + } + true +} + +/// True for the entry of a drive that has no folder yet. +pub fn is_unmounted(uri: &Uri) -> bool { + uri.scheme() == DRIVE_SCHEME +} + +fn run(uri: &Uri, item: Item) { + if item == Item::Eject { + if let Some(ios) = IOS.with(|i| i.borrow().clone()) { + // Closing talks to no one, but the device lock may wait on a transfer. + let uri = uri.clone(); + std::thread::spawn(move || ios.eject(&uri)); + } + return; + } + let Some(volume) = drive(uri) else { + return; }; - let _ = slint::invoke_from_event_loop(move || { - let items = places - .into_iter() - .map(|p| { - let app = p.uri.scheme() == ios::SCHEME && !can_eject(&p.uri); - Place::new(p.name, if app { APPS } else { PHONE }, p.uri) - }) - .collect(); - if let Some(shell) = SHELL.with(|s| s.borrow().upgrade()) { - shell.set_devices(items); + let name = name(&volume); + match item { + Item::Mount => mount(volume, None), + Item::Unmount => work(volume, "Unmounting…", drives::unmount, move |r| { + told(r, "unmount", &name, |n| format!("{n} is unmounted")) + }), + Item::Remove(_) => work(volume, "Removing…", drives::remove, move |r| { + told(r, "remove", &name, |n| format!("{n} is safe to take out")) + }), + Item::Eject => {} + } +} + +/// Mounts `volume`; with `open` its folder opens then, in a new tab or not. +fn mount(volume: Volume, open: Option) { + let name = name(&volume); + work(volume, "Mounting…", drives::mount, move |result| { + let dir = match result { + Ok(dir) => dir, + Err(e) => return told(Err(e), "mount", &name, |_| String::new()), + }; + if let (Some(new_tab), Some(shell)) = (open, shell()) { + shell.open_at(Uri::from_path(&dir), new_tab); } }); } + +/// Runs `job` on `volume` off the UI thread, with `text` in its row meanwhile. +fn work( + volume: Volume, + text: &'static str, + job: impl FnOnce(&Volume) -> Result + Send + 'static, + done: impl FnOnce(Result) + Send + 'static, +) { + if is_busy(&volume) { + return; + } + let id = volume.block.clone(); + LISTS.with(|l| l.borrow_mut().busy.insert(id.clone(), text)); + refresh(); + std::thread::spawn(move || { + let result = job(&volume); + let _ = slint::invoke_from_event_loop(move || { + LISTS.with(|l| l.borrow_mut().busy.remove(&id)); + refresh(); + done(result); + }); + }); +} + +fn told(result: Result<(), drives::Error>, verb: &str, name: &str, ok: fn(&str) -> String) { + let message = match result { + Ok(()) => ok(name), + Err(drives::Error::Dismissed) => return, + Err(drives::Error::Failed(why)) => format!("Can't {verb} {name}: {why}"), + }; + if let Some(shell) = shell() { + shell.notify(message); + } +} + +fn shell() -> Option> { + SHELL.with(|s| s.borrow().upgrade()) +} + +fn name(volume: &Volume) -> String { + if !volume.label.is_empty() { + return volume.label.clone(); + } + let kind = match volume.kind { + Kind::Usb => "USB drive", + Kind::Card => "memory card", + Kind::Disc => "disc", + Kind::Other => "drive", + }; + format!("{} {kind}", format::size(volume.size)) +} + +fn drive_place(volume: &Volume, busy: Option<&&'static str>) -> Place { + let glyph = match volume.kind { + Kind::Usb => USB, + Kind::Card => CARD, + Kind::Disc => DISC, + Kind::Other => DISK, + }; + let mut place = Place::new(name(volume), glyph, place_uri(volume)); + place.detail = match busy { + Some(text) => (*text).to_owned(), + None if volume.mount.is_none() => "Not mounted".to_owned(), + // Without a label the name has the size. + None if volume.label.is_empty() => "Mounted".to_owned(), + None => format::size(volume.size), + }; + place +} + +/// Updates the lists (from any thread) and shows them. Panes in a drive that went away go home. +fn show(update: impl FnOnce(&mut Lists) + Send + 'static) { + let _ = slint::invoke_from_event_loop(move || { + let gone = LISTS.with(|l| { + let mut l = l.borrow_mut(); + let mut mounts: Vec<_> = l.drives.iter().filter_map(|v| v.mount.clone()).collect(); + update(&mut l); + mounts.retain(|m| !l.drives.iter().any(|v| v.mount.as_ref() == Some(m))); + mounts + }); + if let Some(shell) = shell() { + for dir in gone { + shell.leave(&dir); + } + } + refresh(); + }); +} + +fn refresh() { + let places = LISTS.with(|l| { + let l = l.borrow(); + let drives = l + .drives + .iter() + .map(|v| drive_place(v, l.busy.get(&v.block))); + let phones = l.mtp.iter().chain(&l.ios).cloned().map(|p| { + let app = p.uri.scheme() == ios::SCHEME && p.uri.path() != b"/"; + Place::new(p.name, if app { APPS } else { PHONE }, p.uri) + }); + drives.chain(phones).collect() + }); + if let Some(shell) = shell() { + shell.set_devices(places); + } +} diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index a7b8ab4..0fcb6ab 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -669,9 +669,14 @@ impl Shell { .map(|(i, p)| { let (name, tip) = path::shown_name(&p.uri, p.name.clone()); let picture = p.picture.as_deref().and_then(look::picture); + let eject = (section == Section::Devices) + .then(|| crate::devices_bridge::eject_label(&p.uri)) + .flatten(); PlaceItem { name: name.into(), tip: tip.into(), + detail: p.detail.as_str().into(), + eject: eject.unwrap_or_default().into(), glyph: p.shown_glyph().into(), has_picture: picture.is_some(), picture: picture.unwrap_or_default(), @@ -749,11 +754,8 @@ impl Shell { else { return; }; - if new_tab { - self.open_tab(vec![uri]); - self.show_current(); - } else { - self.go(uri); + if !crate::devices_bridge::open(&uri, new_tab) { + self.open_at(uri, new_tab); } } @@ -798,8 +800,10 @@ impl Shell { items.push(item(text, icon, disabled)); } } - if self.ejectable(section, index).is_some() { - items.push(item("Eject", "\u{e8fb}", false)); + if let Some(uri) = self.device_uri(section, index) { + for (label, glyph) in crate::devices_bridge::menu_items(&uri) { + items.push(item(label, glyph, false)); + } } if section == Section::Network { for (label, glyph) in crate::net_bridge::menu_items(index) { @@ -824,12 +828,35 @@ impl Shell { } } - /// The URI of a device entry that can be ejected. - fn ejectable(&self, section: Section, index: usize) -> Option { + fn device_uri(&self, section: Section, index: usize) -> Option { let places = self.places.borrow(); let place = places.get(section, index)?; - (section == Section::Devices && crate::devices_bridge::can_eject(&place.uri)) - .then(|| place.uri.clone()) + (section == Section::Devices).then(|| place.uri.clone()) + } + + /// The button of a device entry. + fn eject_place(&self, section: Section, index: usize) { + if let Some(uri) = self.device_uri(section, index) { + crate::devices_bridge::eject(&uri); + } + } + + /// Panes showing a folder in `dir` go home: it is no longer there. + pub(crate) fn leave(&self, dir: &std::path::Path) { + let panes: Vec<_> = self + .tabs + .borrow() + .iter() + .flat_map(|t| t.panes.clone()) + .filter(|p| { + p.dir() + .and_then(|u| u.to_path()) + .is_some_and(|p| p.starts_with(dir)) + }) + .collect(); + for pane in panes { + pane.go(Uri::from_path(&places::home())); + } } fn place_menu_activated(&self, choice: usize) { @@ -839,9 +866,9 @@ impl Shell { match choice { 0 => self.open_place(section, index, true), c if section == Section::Network => crate::net_bridge::menu_activated(index, c - 1), - 1 if section == Section::Devices => { - if let Some(uri) = self.ejectable(section, index) { - crate::devices_bridge::eject(&uri); + c if section == Section::Devices => { + if let Some(uri) = self.device_uri(section, index) { + crate::devices_bridge::menu_activated(&uri, c - 1); } } c => { @@ -980,6 +1007,7 @@ impl Shell { .borrow() .get(section, index) .map(|p| p.uri.clone()) + .filter(|u| !crate::devices_bridge::is_unmounted(u)) } /// Adds folders to `section` at `slot` (the end for `None`). @@ -1107,6 +1135,12 @@ impl Shell { s.open_place(sec, index.max(0) as usize, new_tab) } ); + on!( + on_place_ejected, + |s, i, index| if let Some(sec) = section(i) { + s.eject_place(sec, index.max(0) as usize) + } + ); on!(on_section_toggled, |s, i| if let Some(sec) = section(i) { s.places.borrow_mut().toggle(sec); s.show_chrome() diff --git a/crates/tunal/src/shell/places.rs b/crates/tunal/src/shell/places.rs index f7e3663..2742498 100644 --- a/crates/tunal/src/shell/places.rs +++ b/crates/tunal/src/shell/places.rs @@ -44,7 +44,7 @@ impl Section { match self { Self::Places => "", Self::Bookmarks => "Bookmark a folder to keep it here", - Self::Devices => "No phones connected", + Self::Devices => "No drives or phones connected", Self::Network => "No network locations", } } @@ -75,6 +75,8 @@ pub struct Place { pub picture: Option, /// One of the places every user has: it can't be renamed, removed or leave its section. pub standard: bool, + /// A second line under the name, empty for none. + pub detail: String, } impl Place { @@ -86,6 +88,7 @@ impl Place { icon: None, picture: None, standard: false, + detail: String::new(), } } diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index 04056c6..8e32240 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -253,6 +253,7 @@ export component MainWindow inherits Window { in property current-place-row; in property current-place-rows-before; callback place-opened(int, int, bool); + callback place-ejected(int, int); callback section-toggled(int); callback add-bookmark(); callback place-menu-requested(int, int); @@ -461,6 +462,9 @@ export component MainWindow inherits Window { open(section, index, new-tab) => { root.place-opened(section, index, new-tab); } + eject(section, index) => { + root.place-ejected(section, index); + } toggle(section) => { root.section-toggled(section); } diff --git a/crates/tunal/ui/components/icon.slint b/crates/tunal/ui/components/icon.slint index a996320..4bd783d 100644 --- a/crates/tunal/ui/components/icon.slint +++ b/crates/tunal/ui/components/icon.slint @@ -22,6 +22,7 @@ export component Icon inherits Text { // Codepoints of the glyphs in use. export global Icons { out property folder: "\u{e2c7}"; + out property eject: "\u{e8fb}"; out property home: "\u{e88a}"; out property check: "\u{e5ca}"; out property close: "\u{e5cd}"; diff --git a/crates/tunal/ui/shell/sidebar.slint b/crates/tunal/ui/shell/sidebar.slint index 0092025..269ceec 100644 --- a/crates/tunal/ui/shell/sidebar.slint +++ b/crates/tunal/ui/shell/sidebar.slint @@ -11,6 +11,10 @@ export struct PlaceItem { name: string, // The real name of a folder shown by another one. tip: string, + // A second line under the name. + detail: string, + // Names the button at the end of the row (Unmount, Eject), empty for none. + eject: string, glyph: string, // An image in place of the glyph. picture: image, @@ -123,6 +127,7 @@ export component Sidebar inherits Rectangle { in property rows-before; callback open(section: int, index: int, new-tab: bool); callback toggle(section: int); + callback eject(section: int, index: int); callback add-bookmark(); callback add-connection(); // Right click on an item, at window coordinates. @@ -254,6 +259,7 @@ export component Sidebar inherits Rectangle { picture: item.picture; has-picture: item.has-picture; title: item.name; + supporting: item.detail; tooltip: item.tip; selected: item.current; own-fill: false; @@ -271,6 +277,19 @@ export component Sidebar inherits Rectangle { root.item-menu(s, i, self.absolute-position.x + self.mouse-x, self.absolute-position.y + root.row-height); } } + + if item.eject != "": VerticalLayout { + alignment: center; + IconButton { + icon: Icons.eject; + size: 28px; + icon-size: 18px; + tooltip: item.eject; + clicked => { + root.eject(s, i); + } + } + } } } } diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 3fa5bc5..6184136 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -308,5 +308,10 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Verified: package built and listed, its binary drew a PNG; user install + uninstall in a scratch PREFIX; --system with a stand-in sudo. - Not done: the package and --system not run against the real /usr. +## Drives in the sidebar (user request) +- Done: `tunal-devices::drives` (UDisks2 over zbus: list, hotplug, mount, unmount, power off/eject); Devices section lists USB drives, cards, discs and inner disks the system does not run on (under /run/media, /media, /mnt or unmounted); click mounts and opens, row button unmounts (ejects an iPhone), menu has Mount/Unmount/Safely remove; panes in a drive that went away go home. +- Verified: clippy on tunal + tunal-devices, release build; the user's USB stick opened, unmounted and mounted again under Xvfb. +- Not done: Safely remove not run (needs a replug); inner disks, cards and discs not tried; locked (LUKS) drives are not listed; no test run. + ## Later - diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index d53b89f..b9d7c4d 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -21,6 +21,7 @@ optdepends=( "7zip: 7z and most other archives" "libarchive: tar archives" "zip: zip archives" + "udisks2: USB drives and other disks" "usbmuxd: iOS devices" ) options=(!debug !lto)