devices: USB drives and other disks in the sidebar, with mount and unmount
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
9bdb4a1adf
commit
ef04575f35
14 changed files with 589 additions and 49 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -7107,6 +7107,7 @@ dependencies = [
|
|||
"tempfile",
|
||||
"tokio",
|
||||
"tunal-core",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -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 |
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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" }
|
||||
|
|
|
|||
240
crates/tunal-devices/src/drives.rs
Normal file
240
crates/tunal-devices/src/drives.rs
Normal file
|
|
@ -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<String, HashMap<String, OwnedValue>>;
|
||||
type Objects = HashMap<OwnedObjectPath, Interfaces>;
|
||||
|
||||
#[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<String>,
|
||||
/// Its label, empty for none.
|
||||
pub label: String,
|
||||
pub kind: Kind,
|
||||
pub size: u64,
|
||||
pub mount: Option<PathBuf>,
|
||||
pub removal: Option<Removal>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// The user closed the password prompt.
|
||||
Dismissed,
|
||||
/// A message to show.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl From<zbus::Error> 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<Volume>) + 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<Volume>)) -> 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<Vec<Volume>> {
|
||||
let manager = Proxy::new(conn, SERVICE, ROOT, "org.freedesktop.DBus.ObjectManager")?;
|
||||
let objects: Objects = manager.call("GetManagedObjects", &())?;
|
||||
let mut found: Vec<Volume> = 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<Volume> {
|
||||
let block = interfaces.get(BLOCK)?;
|
||||
let filesystem = interfaces.get(FILESYSTEM)?;
|
||||
// An inner disk.
|
||||
let system = flag(block, "HintSystem");
|
||||
let mounts: Vec<PathBuf> = value::<Vec<Vec<u8>>>(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::<String>(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::<OwnedObjectPath>(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<String, OwnedValue>) -> Kind {
|
||||
let text = |key| value::<String>(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<T: TryFrom<OwnedValue>>(map: &HashMap<String, OwnedValue>, key: &str) -> Option<T> {
|
||||
T::try_from(map.get(key)?.try_clone().ok()?).ok()
|
||||
}
|
||||
|
||||
fn flag(map: &HashMap<String, OwnedValue>, key: &str) -> bool {
|
||||
value(map, key).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Calls `method` of `interface` with no options: polkit may ask the user.
|
||||
fn call<R>(path: &str, interface: &str, method: &str) -> Result<R, Error>
|
||||
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<PathBuf, Error> {
|
||||
call::<String>(&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)
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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<Weak<Shell>> = const { RefCell::new(Weak::new()) };
|
||||
static IOS: RefCell<Option<Arc<IosLocation>>> = const { RefCell::new(None) };
|
||||
static LISTS: RefCell<Lists> = RefCell::default();
|
||||
}
|
||||
|
||||
/// Each backend's latest entries; the sidebar shows them together.
|
||||
#[derive(Default)]
|
||||
struct Lists {
|
||||
drives: Vec<Volume>,
|
||||
mtp: Vec<DevicePlace>,
|
||||
ios: Vec<DevicePlace>,
|
||||
/// What runs on a drive right now, by its id.
|
||||
busy: HashMap<String, &'static str>,
|
||||
}
|
||||
|
||||
pub struct Backends {
|
||||
|
|
@ -57,13 +72,13 @@ pub fn register(locations: &mut Locations) -> Backends {
|
|||
pub fn attach(shell: &Rc<Shell>, 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<Shell>, 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<Lists>, update: impl FnOnce(&mut Lists)) {
|
||||
let places: Vec<DevicePlace> = {
|
||||
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<Volume> {
|
||||
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<Item> {
|
||||
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<bool>) {
|
||||
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<T: Send + 'static>(
|
||||
volume: Volume,
|
||||
text: &'static str,
|
||||
job: impl FnOnce(&Volume) -> Result<T, drives::Error> + Send + 'static,
|
||||
done: impl FnOnce(Result<T, drives::Error>) + 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<Rc<Shell>> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Uri> {
|
||||
fn device_uri(&self, section: Section, index: usize) -> Option<Uri> {
|
||||
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()
|
||||
|
|
|
|||
|
|
@ -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<PathBuf>,
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -253,6 +253,7 @@ export component MainWindow inherits Window {
|
|||
in property <int> current-place-row;
|
||||
in property <int> 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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export component Icon inherits Text {
|
|||
// Codepoints of the glyphs in use.
|
||||
export global Icons {
|
||||
out property <string> folder: "\u{e2c7}";
|
||||
out property <string> eject: "\u{e8fb}";
|
||||
out property <string> home: "\u{e88a}";
|
||||
out property <string> check: "\u{e5ca}";
|
||||
out property <string> close: "\u{e5cd}";
|
||||
|
|
|
|||
|
|
@ -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 <int> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
-
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in a new issue