S026: Android phones as mtp:// locations with hotplug and Devices places

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
astar76 2026-11-18 21:02:17 -06:00
commit 134095472e
18 changed files with 1547 additions and 159 deletions

3
Cargo.lock generated
View file

@ -5544,6 +5544,7 @@ dependencies = [
"slint-build",
"toml",
"tunal-core",
"tunal-devices",
"tunal-dirmeta",
"tunal-elevate",
"tunal-theme",
@ -5564,8 +5565,10 @@ dependencies = [
name = "tunal-devices"
version = "0.1.0"
dependencies = [
"futures-lite",
"jiff",
"nusb",
"tunal-core",
]
[[package]]

View file

@ -33,3 +33,4 @@ nusb = "0.2"
base64 = "0.23"
hmac = "0.13"
sha1 = "0.11"
futures-lite = "2"

View file

@ -10,11 +10,11 @@ Android phones as `mtp://` locations with hotplug and places entries.
crates/tunal-devices/src/mtp/ session API; crates/tunal/src/devices_bridge.rs (from S024); places API.
## Steps
- [ ] `mtp://<serial>/<storage>/<path>` `Location`: path ↔ handle cache, invalidated by MTP events; list/stat/read/write/mkdir/rename/delete (permanent, confirm).
- [ ] nusb hotplug watch; device and its storages in places Devices.
- [ ] Clear messages: interface busy (another program holds the phone), no USB permission, phone locked / not in file transfer mode (no storages).
- [ ] Smoke without a device.
- [ ] PROGRESS entry, INDEX line, commit `S026: …`
- [x] `mtp://<serial>/<storage>/<path>` `Location`: path ↔ handle cache, invalidated by MTP events; list/stat/read/write/mkdir/rename/delete (permanent, confirm).
- [x] nusb hotplug watch; device and its storages in places Devices.
- [x] Clear messages: interface busy (another program holds the phone), no USB permission, phone locked / not in file transfer mode (no storages).
- [x] Smoke without a device.
- [x] PROGRESS entry, INDEX line, commit `S026: …`
## End criteria
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.

View file

@ -57,7 +57,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
- [ ] [S024 — iOS devices over AFC](09%20Devices/S024-ios-afc.md) · Opus high
- [x] [S025 — MTP protocol over nusb](09%20Devices/S025-mtp-protocol.md) · Opus high
- [ ] [S026 — Android devices over MTP](09%20Devices/S026-mtp-location.md) · Opus high
- [x] [S026 — Android devices over MTP](09%20Devices/S026-mtp-location.md) · Opus high
## 10 Network

View file

@ -8,3 +8,5 @@ publish.workspace = true
[dependencies]
nusb.workspace = true
jiff.workspace = true
tunal-core = { path = "../tunal-core" }
futures-lite.workspace = true

View file

@ -0,0 +1,165 @@
//! Byte-level builders for replay scripts, written independently of the crate's encoder.
#![allow(dead_code)]
use tunal_devices::mtp::Step;
pub const PACKET: usize = 512;
pub const STORAGE: u32 = 0x0001_0001;
pub fn pattern(len: usize, seed: u32) -> Vec<u8> {
let mut x = seed;
(0..len)
.map(|_| {
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(x >> 16) as u8
})
.collect()
}
pub fn container(kind: u16, code: u16, tid: u32, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&((12 + payload.len()) as u32).to_le_bytes());
out.extend_from_slice(&kind.to_le_bytes());
out.extend_from_slice(&code.to_le_bytes());
out.extend_from_slice(&tid.to_le_bytes());
out.extend_from_slice(payload);
out
}
pub fn params_bytes(params: &[u32]) -> Vec<u8> {
params.iter().flat_map(|p| p.to_le_bytes()).collect()
}
pub fn u32s(values: &[u32]) -> Vec<u8> {
let mut out = (values.len() as u32).to_le_bytes().to_vec();
out.extend(params_bytes(values));
out
}
pub fn u16s(values: &[u16]) -> Vec<u8> {
let mut out = (values.len() as u32).to_le_bytes().to_vec();
out.extend(values.iter().flat_map(|v| v.to_le_bytes()));
out
}
pub fn ptp_string(s: &str) -> Vec<u8> {
if s.is_empty() {
return vec![0];
}
let units: Vec<u16> = s.encode_utf16().chain([0]).collect();
let mut out = vec![units.len() as u8];
out.extend(units.iter().flat_map(|u| u.to_le_bytes()));
out
}
pub fn device_info() -> Vec<u8> {
let ops = [
0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1007, 0x1008, 0x1009, 0x100B, 0x100C, 0x100D,
0x1019, 0x101A, 0x101B, 0x9803, 0x9804, 0x9805, 0x95C1,
];
let mut d = Vec::new();
d.extend(100u16.to_le_bytes());
d.extend(6u32.to_le_bytes());
d.extend(100u16.to_le_bytes());
d.extend(ptp_string("microsoft.com: 1.0; android.com: 1.0;"));
d.extend(0u16.to_le_bytes());
d.extend(u16s(&ops));
d.extend(u16s(&[0x4002, 0x4003]));
d.extend(u16s(&[0xD401]));
d.extend(u16s(&[]));
d.extend(u16s(&[0x3000, 0x3001, 0x3009]));
for s in ["Example Phones", "Model X", "1.0", "SER123"] {
d.extend(ptp_string(s));
}
d
}
pub fn storage_info() -> Vec<u8> {
let mut d = Vec::new();
d.extend(3u16.to_le_bytes()); // fixed RAM
d.extend(2u16.to_le_bytes()); // hierarchical
d.extend(0u16.to_le_bytes());
d.extend(64_000_000_000u64.to_le_bytes());
d.extend(12_345_678_901u64.to_le_bytes());
d.extend(0xFFFF_FFFFu32.to_le_bytes());
d.extend(ptp_string("Internal shared storage"));
d.extend(ptp_string(""));
d
}
pub fn object_info(format: u16, size: u32, parent: u32, name: &str, modified: &str) -> Vec<u8> {
let mut d = Vec::new();
d.extend(STORAGE.to_le_bytes());
d.extend(format.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend(size.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 4 * 6]);
d.extend(parent.to_le_bytes());
d.extend((if format == 0x3001 { 1u16 } else { 0 }).to_le_bytes());
d.extend([0u8; 8]);
d.extend(ptp_string(name));
d.extend(ptp_string(""));
d.extend(ptp_string(modified));
d.extend(ptp_string(""));
d
}
/// SendObjectInfo dataset as the client sends it (no dates).
pub fn new_object_info(name: &str, size: u32, parent: u32, folder: bool) -> Vec<u8> {
let mut d = Vec::new();
d.extend(STORAGE.to_le_bytes());
d.extend((if folder { 0x3001u16 } else { 0x3000 }).to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend(size.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 4 * 6]);
d.extend(parent.to_le_bytes());
d.extend((if folder { 1u16 } else { 0 }).to_le_bytes());
d.extend([0u8; 8]);
d.extend(ptp_string(name));
d.extend(ptp_string(""));
d.extend(ptp_string(""));
d.extend(ptp_string(""));
d
}
/// A replay script built one transaction at a time; transaction ids count from 0.
#[derive(Default)]
pub struct Script {
pub steps: Vec<Step>,
tid: u32,
}
impl Script {
/// Command `op`, then the host's data `out` or the device's `data` (with or without a
/// zero-length packet), then response `code` with `response` parameters.
pub fn exchange(
&mut self,
op: u16,
params: &[u32],
out: Option<Vec<u8>>,
data: Option<(Vec<u8>, bool)>,
code: u16,
response: &[u32],
) {
let tid = self.tid;
self.steps
.push(Step::Out(container(1, op, tid, &params_bytes(params))));
if let Some(out) = out {
self.steps.push(Step::Out(container(2, op, tid, &out)));
}
if let Some((data, zlp)) = data {
self.steps.push(Step::In {
data: container(2, op, tid, &data),
zlp,
});
}
self.steps.push(Step::In {
data: container(3, code, tid, &params_bytes(response)),
zlp: true,
});
self.tid += 1;
}
}

View file

@ -0,0 +1,268 @@
//! Smoke run of the `mtp://` location against scripted phones:
//! `cargo run -p tunal-devices --example mtp_location`
//!
//! One phone is browsed through the `Location` trait (list, stat, read, write, mkdir,
//! rename, delete); a busy one and a locked one show their messages.
mod common;
use std::io::{Read, Write};
use std::ops::ControlFlow;
use common::*;
use tunal_core::{Location, Uri, WriteMode};
use tunal_devices::mtp::{self, MtpLocation, ReplayTransport, Transport, code};
fn main() {
let ok = code::OK;
let root = code::ROOT;
let mut s = Script::default();
s.exchange(code::OPEN_SESSION, &[1], None, None, ok, &[]);
s.exchange(
code::GET_DEVICE_INFO,
&[],
None,
Some((device_info(), true)),
ok,
&[],
);
s.exchange(
code::GET_STORAGE_IDS,
&[],
None,
Some((u32s(&[STORAGE]), true)),
ok,
&[],
);
s.exchange(
code::GET_STORAGE_INFO,
&[STORAGE],
None,
Some((storage_info(), true)),
ok,
&[],
);
// list the storage
s.exchange(
code::GET_OBJECT_HANDLES,
&[STORAGE, 0, root],
None,
Some((u32s(&[1, 2]), true)),
ok,
&[],
);
s.exchange(
code::GET_OBJECT_INFO,
&[1],
None,
Some((object_info(0x3001, 0, 0, "DCIM", ""), true)),
ok,
&[],
);
s.exchange(
code::GET_OBJECT_INFO,
&[2],
None,
Some((object_info(0x3000, 5, 0, "a.txt", "20260115T093000"), true)),
ok,
&[],
);
// stat a.txt, read it
s.exchange(
code::GET_OBJECT_INFO,
&[2],
None,
Some((object_info(0x3000, 5, 0, "a.txt", "20260115T093000"), true)),
ok,
&[],
);
s.exchange(
code::GET_PARTIAL_OBJECT_64,
&[2, 0, 0, 5],
None,
Some((b"hello".to_vec(), true)),
ok,
&[],
);
// write b.txt
s.exchange(
code::SEND_OBJECT_INFO,
&[STORAGE, root],
Some(new_object_info("b.txt", 6, 0, false)),
None,
ok,
&[STORAGE, root, 3],
);
s.exchange(
code::SEND_OBJECT,
&[],
Some(b"world!".to_vec()),
None,
ok,
&[],
);
// mkdir New
s.exchange(
code::SEND_OBJECT_INFO,
&[STORAGE, root],
Some(new_object_info("New", 0, 0, true)),
None,
ok,
&[STORAGE, root, 4],
);
s.exchange(
code::GET_OBJECT_INFO,
&[4],
None,
Some((object_info(0x3001, 0, 0, "New", ""), true)),
ok,
&[],
);
// rename a.txt → c.txt
s.exchange(
code::SET_OBJECT_PROP_VALUE,
&[2, 0xDC07],
Some(ptp_string("c.txt")),
None,
ok,
&[],
);
s.exchange(
code::GET_OBJECT_INFO,
&[2],
None,
Some((object_info(0x3000, 5, 0, "c.txt", "20260115T093000"), true)),
ok,
&[],
);
// delete b.txt, list again
s.exchange(code::DELETE_OBJECT, &[3, 0], None, None, ok, &[]);
s.exchange(
code::GET_OBJECT_HANDLES,
&[STORAGE, 0, root],
None,
Some((u32s(&[1, 2, 4]), true)),
ok,
&[],
);
s.exchange(
code::GET_OBJECT_INFO,
&[1],
None,
Some((object_info(0x3001, 0, 0, "DCIM", ""), true)),
ok,
&[],
);
s.exchange(
code::GET_OBJECT_INFO,
&[2],
None,
Some((object_info(0x3000, 5, 0, "c.txt", "20260115T093000"), true)),
ok,
&[],
);
s.exchange(
code::GET_OBJECT_INFO,
&[4],
None,
Some((object_info(0x3001, 0, 0, "New", ""), true)),
ok,
&[],
);
let mut locked = Script::default();
locked.exchange(code::OPEN_SESSION, &[1], None, None, ok, &[]);
locked.exchange(
code::GET_DEVICE_INFO,
&[],
None,
Some((device_info(), true)),
ok,
&[],
);
locked.exchange(
code::GET_STORAGE_IDS,
&[],
None,
Some((u32s(&[]), true)),
ok,
&[],
);
// opening it checks again: still locked
locked.exchange(
code::GET_STORAGE_IDS,
&[],
None,
Some((u32s(&[]), true)),
ok,
&[],
);
let location = MtpLocation::new();
let replay = |steps| Ok(Box::new(ReplayTransport::new(PACKET, steps)) as Box<dyn Transport>);
location.connect("SER123", "Phone", None, replay(s.steps));
location.connect("busy", "Busy phone", None, Err(mtp::Error::Busy));
location.connect("locked", "Locked phone", None, replay(locked.steps));
for p in location.places() {
println!("place: {} → {}", p.name, p.uri);
}
for key in ["busy", "locked"] {
match list(&location, &Uri::new("mtp", key, "/")) {
Err(e) => println!("open {key}: {e}"),
Ok(names) => println!("open {key}: {names:?}"),
}
}
let dev = Uri::new("mtp", "SER123", "/");
let storage = Uri::new("mtp", "SER123", "/00010001");
println!(
"device root: {:?}",
list(&location, &dev).expect("list device")
);
println!(
"storage: {:?}",
list(&location, &storage).expect("list storage")
);
let a = storage.join(b"a.txt");
let st = location.stat(&a).expect("stat");
println!(
"stat a.txt: {} bytes, {:?}",
st.size,
st.mtime.map(mtp::format_date)
);
let mut text = String::new();
location
.open_read(&a)
.expect("open")
.read_to_string(&mut text)
.expect("read");
println!("read a.txt: {text:?}");
let b = storage.join(b"b.txt");
let mut w = location
.open_write(&b, WriteMode::CreateNew)
.expect("open_write");
w.write_all(b"world!").expect("write");
w.flush().expect("upload");
println!(
"wrote b.txt; again with CreateNew: {:?}",
location.open_write(&b, WriteMode::CreateNew).err()
);
location.mkdir(&storage.join(b"New")).expect("mkdir");
location
.rename(&a, &storage.join(b"c.txt"))
.expect("rename");
location.delete(&b).expect("delete");
println!(
"storage now: {:?}",
list(&location, &storage).expect("list storage")
);
}
fn list(location: &dyn Location, dir: &Uri) -> tunal_core::Result<Vec<String>> {
let mut names = Vec::new();
location.list(dir, &mut |chunk| {
names.extend(chunk.into_iter().map(|e| e.display_name));
ControlFlow::Continue(())
})?;
Ok(names)
}

View file

@ -10,10 +10,11 @@ use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use tunal_devices::mtp::{self, NewObject, ReplayTransport, Session, Step, code};
mod common;
use common::*;
use tunal_devices::mtp::{self, NewObject, ReplayTransport, Session, code};
const PACKET: usize = 512;
const STORAGE: u32 = 0x0001_0001;
const CHUNK: usize = 256 * 1024;
fn main() {
@ -34,29 +35,9 @@ fn main() {
let upload_path = dir.join("upload.bin");
std::fs::write(&upload_path, &upload).expect("write upload");
let mut script = Vec::new();
let mut tid = 0;
let mut exchange = |op: u16,
params: &[u32],
out: Option<Vec<u8>>,
data: Option<(Vec<u8>, bool)>,
code: u16,
response: &[u32]| {
script.push(Step::Out(container(1, op, tid, &params_bytes(params))));
if let Some(out) = out {
script.push(Step::Out(container(2, op, tid, &out)));
}
if let Some((data, zlp)) = data {
script.push(Step::In {
data: container(2, op, tid, &data),
zlp,
});
}
script.push(Step::In {
data: container(3, code, tid, &params_bytes(response)),
zlp: true,
});
tid += 1;
let mut script = Script::default();
let mut exchange = |op, params: &[u32], out, data, code, response: &[u32]| {
script.exchange(op, params, out, data, code, response)
};
let ok = code::OK;
exchange(code::OPEN_SESSION, &[1], None, None, ok, &[]);
@ -147,7 +128,7 @@ fn main() {
exchange(
code::SEND_OBJECT_INFO,
&[STORAGE, 1],
Some(new_object_info(upload.len() as u32)),
Some(new_object_info("upload.bin", upload.len() as u32, 1, false)),
None,
ok,
&[STORAGE, 1, 5],
@ -167,7 +148,7 @@ fn main() {
exchange(code::DELETE_OBJECT, &[6, 0], None, None, ok, &[]);
exchange(code::CLOSE_SESSION, &[], None, None, ok, &[]);
let mut s = Session::new(ReplayTransport::new(PACKET, script));
let mut s = Session::new(ReplayTransport::new(PACKET, script.steps));
let info = s.open(1).expect("open session").clone();
println!(
"device: {} {} {} serial {}, {} operations",
@ -254,105 +235,6 @@ fn main() {
}
}
fn pattern(len: usize, seed: u32) -> Vec<u8> {
let mut x = seed;
(0..len)
.map(|_| {
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(x >> 16) as u8
})
.collect()
}
fn container(kind: u16, code: u16, tid: u32, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&((12 + payload.len()) as u32).to_le_bytes());
out.extend_from_slice(&kind.to_le_bytes());
out.extend_from_slice(&code.to_le_bytes());
out.extend_from_slice(&tid.to_le_bytes());
out.extend_from_slice(payload);
out
}
fn params_bytes(params: &[u32]) -> Vec<u8> {
params.iter().flat_map(|p| p.to_le_bytes()).collect()
}
fn u32s(values: &[u32]) -> Vec<u8> {
let mut out = (values.len() as u32).to_le_bytes().to_vec();
out.extend(params_bytes(values));
out
}
fn u16s(values: &[u16]) -> Vec<u8> {
let mut out = (values.len() as u32).to_le_bytes().to_vec();
out.extend(values.iter().flat_map(|v| v.to_le_bytes()));
out
}
fn ptp_string(s: &str) -> Vec<u8> {
if s.is_empty() {
return vec![0];
}
let units: Vec<u16> = s.encode_utf16().chain([0]).collect();
let mut out = vec![units.len() as u8];
out.extend(units.iter().flat_map(|u| u.to_le_bytes()));
out
}
fn device_info() -> Vec<u8> {
let ops = [
0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1007, 0x1008, 0x1009, 0x100B, 0x100C, 0x100D,
0x1019, 0x101A, 0x101B, 0x9803, 0x9804, 0x9805, 0x95C1,
];
let mut d = Vec::new();
d.extend(100u16.to_le_bytes());
d.extend(6u32.to_le_bytes());
d.extend(100u16.to_le_bytes());
d.extend(ptp_string("microsoft.com: 1.0; android.com: 1.0;"));
d.extend(0u16.to_le_bytes());
d.extend(u16s(&ops));
d.extend(u16s(&[0x4002, 0x4003]));
d.extend(u16s(&[0xD401]));
d.extend(u16s(&[]));
d.extend(u16s(&[0x3000, 0x3001, 0x3009]));
for s in ["Example Phones", "Model X", "1.0", "SER123"] {
d.extend(ptp_string(s));
}
d
}
fn storage_info() -> Vec<u8> {
let mut d = Vec::new();
d.extend(3u16.to_le_bytes()); // fixed RAM
d.extend(2u16.to_le_bytes()); // hierarchical
d.extend(0u16.to_le_bytes());
d.extend(64_000_000_000u64.to_le_bytes());
d.extend(12_345_678_901u64.to_le_bytes());
d.extend(0xFFFF_FFFFu32.to_le_bytes());
d.extend(ptp_string("Internal shared storage"));
d.extend(ptp_string(""));
d
}
fn object_info(format: u16, size: u32, parent: u32, name: &str, modified: &str) -> Vec<u8> {
let mut d = Vec::new();
d.extend(STORAGE.to_le_bytes());
d.extend(format.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend(size.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 4 * 6]);
d.extend(parent.to_le_bytes());
d.extend((if format == 0x3001 { 1u16 } else { 0 }).to_le_bytes());
d.extend([0u8; 8]);
d.extend(ptp_string(name));
d.extend(ptp_string(""));
d.extend(ptp_string(modified));
d.extend(ptp_string(""));
d
}
/// Two children of folder 1, padded with an unknown property so the dataset fills whole
/// packets (the device then skips the zero-length packet).
fn prop_list(song_size: u64) -> Vec<u8> {
@ -416,21 +298,3 @@ fn prop_list(song_size: u64) -> Vec<u8> {
);
d
}
fn new_object_info(size: u32) -> Vec<u8> {
let mut d = Vec::new();
d.extend(STORAGE.to_le_bytes());
d.extend(0x3000u16.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend(size.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 4 * 6]);
d.extend(1u32.to_le_bytes());
d.extend(0u16.to_le_bytes());
d.extend([0u8; 8]);
d.extend(ptp_string("upload.bin"));
d.extend(ptp_string(""));
d.extend(ptp_string(""));
d.extend(ptp_string(""));
d
}

View file

@ -0,0 +1,61 @@
//! USB hotplug: phones with an MTP interface join and leave an [`MtpLocation`].
use std::sync::Arc;
use futures_lite::StreamExt;
use futures_lite::future::block_on;
use nusb::DeviceInfo;
use nusb::hotplug::HotplugEvent;
use super::{Error, MtpLocation, Transport, UsbTransport, devices, mtp_interface};
/// Adds the connected phones, then follows plugs and unplugs on a thread of its own;
/// `on_change` runs (on that thread or a device's event thread) after every change.
pub fn watch(
location: Arc<MtpLocation>,
on_change: impl Fn() + Send + Sync + 'static,
) -> Result<(), Error> {
location.set_on_change(Arc::new(on_change));
// Watch first so a phone plugged in during the first scan isn't missed.
let mut events = nusb::watch_devices().map_err(|e| Error::Usb(e.to_string()))?;
std::thread::Builder::new()
.name("tunal-mtp-hotplug".into())
.spawn(move || {
for info in devices().unwrap_or_default() {
connect(&location, &info);
}
location.changed();
while let Some(event) = block_on(events.next()) {
match event {
HotplugEvent::Connected(info) if mtp_interface(&info).is_some() => {
connect(&location, &info)
}
HotplugEvent::Connected(_) => {}
HotplugEvent::Disconnected(id) => location.disconnect_usb(id),
}
}
})
.map_err(|e| Error::Usb(e.to_string()))?;
Ok(())
}
fn connect(location: &MtpLocation, info: &DeviceInfo) {
let name = info.product_string().unwrap_or("Phone");
let transport = UsbTransport::open(info).map(|t| Box::new(t) as Box<dyn Transport>);
location.connect(&key(info), name, Some(info.id()), transport);
}
/// URI authority: the serial number (URI-safe characters only), else the bus position.
fn key(info: &DeviceInfo) -> String {
let serial: String = info
.serial_number()
.unwrap_or_default()
.chars()
.filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
.collect();
if serial.is_empty() {
format!("usb-{}-{}", info.busnum(), info.device_address())
} else {
serial
}
}

View file

@ -0,0 +1,875 @@
//! `mtp://<device>/<storage>/<path>` locations over open MTP sessions. `<storage>` is the
//! storage id in hex; paths map to object handles through a cache that MTP events and our
//! own changes keep current.
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::Duration;
use tunal_core::{
Capabilities, Entry, Error as CoreError, Kind, ListSink, Location, Result, Uri, Watch,
WatchCallback, WatchEvent, WriteMode, display_name, mime,
};
use super::{Container, Error, Events, NewObject, Object, Session, StorageInfo, Transport, code};
pub const SCHEME: &str = "mtp";
/// Bytes per partial read while streaming a file from the device.
const READ_CHUNK: u32 = 1 << 20;
/// How long the event thread waits before checking that its device is still there.
const EVENT_WAIT: Duration = Duration::from_secs(5);
type OnChange = Arc<dyn Fn() + Send + Sync>;
type Phone = Session<Box<dyn Transport>>;
/// A sidebar entry: one per storage, or one for the device while it has a problem.
#[derive(Clone, Debug)]
pub struct DevicePlace {
pub name: String,
pub uri: Uri,
}
/// Every connected MTP device, by URI authority.
#[derive(Default)]
pub struct MtpLocation {
devices: Mutex<HashMap<String, Arc<Device>>>,
on_change: Mutex<Option<OnChange>>,
}
struct Device {
key: String,
name: String,
usb: Option<nusb::DeviceId>,
session: Mutex<Option<Phone>>,
state: Mutex<State>,
cache: Mutex<Cache>,
watchers: Mutex<Vec<(u64, Uri, WatchCallback)>>,
}
#[derive(Default)]
struct State {
storages: Vec<(u32, StorageInfo)>,
/// Shown instead of the storages (busy, no permission, locked phone).
problem: Option<String>,
}
#[derive(Default)]
struct Cache {
/// Objects of `(storage, parent)`.
children: HashMap<(u32, u32), Vec<Object>>,
/// URI of every object seen, for events.
paths: HashMap<u32, Uri>,
}
static NEXT_WATCH: AtomicU64 = AtomicU64::new(1);
static NEXT_SPOOL: AtomicU64 = AtomicU64::new(1);
impl MtpLocation {
pub fn new() -> Self {
Self::default()
}
/// Called (on a device thread) whenever devices or their storages change.
pub fn set_on_change(&self, f: OnChange) {
*lock(&self.on_change) = Some(f);
}
/// Opens a session on `transport` and adds the device as `key` (a URI authority).
/// A failure is kept as the device's problem and shown when its root is opened.
pub fn connect(
&self,
key: &str,
name: &str,
usb: Option<nusb::DeviceId>,
transport: std::result::Result<Box<dyn Transport>, Error>,
) {
let mut state = State::default();
let mut session = None;
let mut events = None;
let mut name = name.to_owned();
match transport.and_then(|mut t| {
events = t.take_events();
let mut s = Session::new(t);
let info = s.open(1)?;
if !info.model.is_empty() {
name = info.model.clone();
}
Ok(s)
}) {
Ok(mut s) => {
state = read_storages(&mut s);
session = Some(s);
}
Err(e) => state.problem = Some(problem(&e)),
}
let device = Arc::new(Device {
key: key.to_owned(),
name,
usb,
session: Mutex::new(session),
state: Mutex::new(state),
cache: Mutex::new(Cache::default()),
watchers: Mutex::new(Vec::new()),
});
if let Some(events) = events {
let weak = Arc::downgrade(&device);
let on_change = lock(&self.on_change).clone();
std::thread::Builder::new()
.name("tunal-mtp-events".into())
.spawn(move || run_events(weak, events, on_change))
.ok();
}
if let Some(old) = lock(&self.devices).insert(key.to_owned(), device) {
old.gone();
}
self.changed();
}
/// Removes the device that came from USB device `id`.
pub fn disconnect_usb(&self, id: nusb::DeviceId) {
let removed: Vec<Arc<Device>> = {
let mut devices = lock(&self.devices);
let keys: Vec<String> = devices
.values()
.filter(|d| d.usb == Some(id))
.map(|d| d.key.clone())
.collect();
keys.iter().filter_map(|k| devices.remove(k)).collect()
};
if !removed.is_empty() {
removed.iter().for_each(|d| d.gone());
self.changed();
}
}
/// Sidebar entries, devices by name.
pub fn places(&self) -> Vec<DevicePlace> {
let mut devices: Vec<Arc<Device>> = lock(&self.devices).values().cloned().collect();
devices.sort_by(|a, b| a.name.cmp(&b.name).then(a.key.cmp(&b.key)));
let mut out = Vec::new();
for d in devices {
let state = lock(&d.state);
if state.problem.is_some() || state.storages.is_empty() {
out.push(DevicePlace {
name: d.name.clone(),
uri: Uri::new(SCHEME, &d.key, "/"),
});
continue;
}
let single = state.storages.len() == 1;
for (id, info) in &state.storages {
let label = if info.description.is_empty() {
&info.volume_label
} else {
&info.description
};
out.push(DevicePlace {
name: if single || label.is_empty() {
d.name.clone()
} else {
format!("{} · {label}", d.name)
},
uri: storage_uri(&d.key, *id),
});
}
}
out
}
pub(super) fn changed(&self) {
let f = lock(&self.on_change).clone();
if let Some(f) = f {
f();
}
}
fn device(&self, uri: &Uri) -> Result<Arc<Device>> {
lock(&self.devices)
.get(uri.authority())
.cloned()
.ok_or(CoreError::NotFound)
}
}
/// Where a URI points on its device.
enum Target {
/// The device itself: its storages are the folders.
Device,
Storage(u32),
Object(u32, Object),
}
impl Device {
/// Tells watchers the device went away.
fn gone(&self) {
for (_, _, cb) in lock(&self.watchers).iter() {
cb(WatchEvent::Error(CoreError::Remote(
"phone disconnected".into(),
)));
}
}
fn session(&self) -> Result<MutexGuard<'_, Option<Phone>>> {
let guard = lock(&self.session);
if guard.is_none() {
let problem = lock(&self.state).problem.clone();
return Err(CoreError::Remote(
problem.unwrap_or_else(|| "not connected".into()),
));
}
Ok(guard)
}
fn storage(&self, segment: &[u8]) -> Result<u32> {
let id = std::str::from_utf8(segment)
.ok()
.and_then(|s| u32::from_str_radix(s, 16).ok())
.ok_or(CoreError::NotFound)?;
let state = lock(&self.state);
if state.storages.iter().any(|(s, _)| *s == id) {
Ok(id)
} else {
Err(CoreError::NotFound)
}
}
/// The objects of `parent` in `storage` (whose URI is `dir`), from the cache unless
/// `fresh`.
fn children(
&self,
s: &mut Phone,
storage: u32,
parent: u32,
dir: &Uri,
fresh: bool,
) -> Result<Vec<Object>> {
if !fresh && let Some(list) = lock(&self.cache).children.get(&(storage, parent)) {
return Ok(list.clone());
}
let list = s.list(storage, parent).map_err(core_error)?;
let mut cache = lock(&self.cache);
for o in &list {
cache.paths.insert(o.handle, dir.join(o.name.as_bytes()));
}
cache.children.insert((storage, parent), list.clone());
Ok(list)
}
/// Walks `uri`'s path from its storage; a name missing from the cache is looked up
/// again on the device before `NotFound`.
fn resolve(&self, s: &mut Phone, uri: &Uri) -> Result<Target> {
let mut segments = uri.path().split(|&b| b == b'/').filter(|p| !p.is_empty());
let Some(first) = segments.next() else {
return Ok(Target::Device);
};
let storage = self.storage(first)?;
let mut dir = storage_uri(&self.key, storage);
let mut found: Option<Object> = None;
for name in segments {
let parent = found.as_ref().map_or(code::ROOT, |o| o.handle);
if found.as_ref().is_some_and(|o| !o.is_folder()) {
return Err(CoreError::NotFound);
}
let find = |list: Vec<Object>| list.into_iter().find(|o| o.name.as_bytes() == name);
let mut hit = find(self.children(s, storage, parent, &dir, false)?);
if hit.is_none() {
hit = find(self.children(s, storage, parent, &dir, true)?);
}
let o = hit.ok_or(CoreError::NotFound)?;
dir = dir.join(name);
found = Some(o);
}
Ok(match found {
Some(o) => Target::Object(storage, o),
None => Target::Storage(storage),
})
}
/// `(storage, parent handle)` of the folder `dir`.
fn folder(&self, s: &mut Phone, dir: &Uri) -> Result<(u32, u32)> {
match self.resolve(s, dir)? {
Target::Storage(st) => Ok((st, code::ROOT)),
Target::Object(st, o) if o.is_folder() => Ok((st, o.handle)),
Target::Object(..) => Err(CoreError::Io("not a folder".into())),
Target::Device => Err(CoreError::Unsupported),
}
}
/// Records a new or changed object under `dir`.
fn put(&self, storage: u32, dir: &Uri, object: Object) {
let mut cache = lock(&self.cache);
cache
.paths
.insert(object.handle, dir.join(object.name.as_bytes()));
if let Some(list) = cache.children.get_mut(&(storage, object.parent)) {
list.retain(|o| o.handle != object.handle && o.name != object.name);
list.push(object);
}
}
fn forget(&self, handle: u32) -> Option<Uri> {
let mut cache = lock(&self.cache);
for list in cache.children.values_mut() {
list.retain(|o| o.handle != handle);
}
cache.children.retain(|(_, parent), _| *parent != handle);
cache.paths.remove(&handle)
}
fn notify(&self, changed: Vec<Uri>) {
for (_, dir, cb) in lock(&self.watchers).iter() {
let mine: Vec<Uri> = changed
.iter()
.filter(|u| u.parent().as_ref() == Some(dir))
.cloned()
.collect();
if !mine.is_empty() {
cb(WatchEvent::Changed(mine));
}
}
}
}
impl Location for MtpLocation {
fn scheme(&self) -> &str {
SCHEME
}
fn capabilities(&self) -> Capabilities {
Capabilities {
write: true,
watch: true,
..Capabilities::default()
}
}
fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> {
let d = self.device(dir)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
let entries: Vec<Entry> = match d.resolve(s, dir)? {
Target::Device => {
let storages_before = lock(&d.state).storages.len();
if storages_before == 0 {
// A locked phone shows its storages once unlocked.
let state = read_storages(s);
let found = !state.storages.is_empty();
*lock(&d.state) = state;
if found {
drop(guard);
self.changed();
return self.list(dir, sink);
}
}
let state = lock(&d.state);
if let Some(p) = &state.problem {
return Err(CoreError::Remote(p.clone()));
}
state
.storages
.iter()
.map(|(id, _)| dir_entry(format!("{id:08x}").into_bytes()))
.collect()
}
Target::Storage(st) => to_entries(d.children(s, st, code::ROOT, dir, true)?),
Target::Object(st, o) if o.is_folder() => {
to_entries(d.children(s, st, o.handle, dir, true)?)
}
Target::Object(..) => return Err(CoreError::Io("not a folder".into())),
};
for chunk in entries.chunks(256) {
if sink(chunk.to_vec()).is_break() {
return Err(CoreError::Cancelled);
}
}
Ok(())
}
fn stat(&self, uri: &Uri) -> Result<Entry> {
let d = self.device(uri)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
match d.resolve(s, uri)? {
Target::Device | Target::Storage(_) => {
Ok(dir_entry(uri.file_name().unwrap_or(b"").to_vec()))
}
Target::Object(st, o) => match s.object(o.handle) {
Ok(fresh) => {
let dir = uri.parent().unwrap_or_else(|| uri.clone());
d.put(st, &dir, fresh.clone());
Ok(to_entry(fresh))
}
Err(e) if e.is_response(code::INVALID_OBJECT_HANDLE) => {
d.forget(o.handle);
Err(CoreError::NotFound)
}
Err(e) => Err(core_error(e)),
},
}
}
fn open_read(&self, uri: &Uri) -> Result<Box<dyn Read + Send>> {
let d = self.device(uri)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
let Target::Object(_, o) = d.resolve(s, uri)? else {
return Err(CoreError::Io("not a file".into()));
};
if o.is_folder() {
return Err(CoreError::Io("not a file".into()));
}
let partial = s.supports(code::GET_PARTIAL_OBJECT_64)
|| (s.supports(code::GET_PARTIAL_OBJECT) && o.size <= u64::from(u32::MAX));
drop(guard);
if partial {
return Ok(Box::new(ChunkReader {
device: d,
handle: o.handle,
size: o.size,
offset: 0,
buf: Vec::new(),
pos: 0,
}));
}
// Whole-object transfer on a thread of its own, through a pipe.
let (reader, mut writer) = io::pipe()?;
let handle = o.handle;
std::thread::spawn(move || {
let mut guard = lock(&d.session);
if let Some(s) = guard.as_mut() {
let _ = s.get_object(handle, &mut writer);
}
});
Ok(Box::new(Counted {
inner: reader,
left: o.size,
}))
}
fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result<Box<dyn Write + Send>> {
let d = self.device(uri)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
let (dir, name) = split(uri)?;
let (storage, parent) = d.folder(s, &dir)?;
let existing = d
.children(s, storage, parent, &dir, false)?
.into_iter()
.find(|o| o.name.as_bytes() == name);
let replace = match existing {
Some(_) if mode == WriteMode::CreateNew => return Err(CoreError::Exists),
Some(o) if o.is_folder() => return Err(CoreError::Exists),
Some(o) => Some(o.handle),
None => None,
};
drop(guard);
Ok(Box::new(Upload {
device: d,
storage,
parent,
dir,
name: String::from_utf8_lossy(name).into_owned(),
replace,
spool: spool_file()?,
len: 0,
done: false,
}))
}
fn mkdir(&self, uri: &Uri) -> Result<()> {
let d = self.device(uri)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
let (dir, name) = split(uri)?;
let (storage, parent) = d.folder(s, &dir)?;
if d.children(s, storage, parent, &dir, false)?
.iter()
.any(|o| o.name.as_bytes() == name)
{
return Err(CoreError::Exists);
}
let object = NewObject {
name: String::from_utf8_lossy(name).into_owned(),
size: 0,
modified: None,
folder: true,
};
let (_, _, handle) = s
.send_object_info(storage, parent, &object)
.map_err(core_error)?;
let created = s.object(handle).map_err(core_error)?;
d.put(storage, &dir, created);
Ok(())
}
fn rename(&self, from: &Uri, to: &Uri) -> Result<()> {
let d = self.device(from)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
let Target::Object(st, o) = d.resolve(s, from)? else {
return Err(CoreError::Unsupported);
};
let (to_dir, name) = split(to)?;
let (to_storage, to_parent) = d.folder(s, &to_dir)?;
if d.children(s, to_storage, to_parent, &to_dir, false)?
.iter()
.any(|x| x.name.as_bytes() == name && x.handle != o.handle)
{
return Err(CoreError::Exists);
}
if (to_storage, to_parent) != (st, o.parent) {
s.move_object(o.handle, to_storage, to_parent)
.map_err(core_error)?;
}
if o.name.as_bytes() != name {
s.rename(o.handle, &String::from_utf8_lossy(name))
.map_err(core_error)?;
}
d.forget(o.handle);
let moved = s.object(o.handle).map_err(core_error)?;
d.put(to_storage, &to_dir, moved);
Ok(())
}
/// Permanent: MTP has no trash, the UI confirms first.
fn delete(&self, uri: &Uri) -> Result<()> {
let d = self.device(uri)?;
let mut guard = d.session()?;
let s = guard.as_mut().expect("session checked");
let Target::Object(st, o) = d.resolve(s, uri)? else {
return Err(CoreError::Unsupported);
};
if o.is_folder()
&& !s
.object_handles(st, o.handle)
.map_err(core_error)?
.is_empty()
{
return Err(CoreError::NotEmpty);
}
s.delete_object(o.handle).map_err(core_error)?;
d.forget(o.handle);
Ok(())
}
fn watch(&self, dir: &Uri, callback: WatchCallback) -> Result<Watch> {
let d = self.device(dir)?;
let id = NEXT_WATCH.fetch_add(1, Ordering::Relaxed);
lock(&d.watchers).push((id, dir.clone(), callback));
Ok(Watch::new(WatchGuard {
device: Arc::downgrade(&d),
id,
}))
}
}
struct WatchGuard {
device: Weak<Device>,
id: u64,
}
impl Drop for WatchGuard {
fn drop(&mut self) {
if let Some(d) = self.device.upgrade() {
lock(&d.watchers).retain(|(id, _, _)| *id != self.id);
}
}
}
/// Streams a file with partial reads; the session is locked per chunk only.
struct ChunkReader {
device: Arc<Device>,
handle: u32,
size: u64,
offset: u64,
buf: Vec<u8>,
pos: usize,
}
impl Read for ChunkReader {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
if self.pos == self.buf.len() {
if self.offset >= self.size {
return Ok(0);
}
self.buf.clear();
self.pos = 0;
let want = (self.size - self.offset).min(u64::from(READ_CHUNK)) as u32;
let mut guard = lock(&self.device.session);
let s = guard
.as_mut()
.ok_or_else(|| io::Error::other("phone disconnected"))?;
let got = s
.get_partial_object(self.handle, self.offset, want, &mut self.buf)
.map_err(io::Error::other)?;
if got == 0 {
return Err(io::Error::other("phone sent no data"));
}
self.offset += got;
}
let n = out.len().min(self.buf.len() - self.pos);
out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
self.pos += n;
Ok(n)
}
}
/// A pipe reader that fails instead of ending early.
struct Counted<R> {
inner: R,
left: u64,
}
impl<R: Read> Read for Counted<R> {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
let n = self.inner.read(out)?;
if n == 0 && self.left > 0 {
return Err(io::Error::other("transfer from the phone ended early"));
}
self.left = self.left.saturating_sub(n as u64);
Ok(n)
}
}
/// MTP needs the size before the bytes: writes go to an unlinked temp file and are sent
/// on `flush` (the job engine flushes at the end; dropped unflushed = nothing sent).
struct Upload {
device: Arc<Device>,
storage: u32,
parent: u32,
dir: Uri,
name: String,
replace: Option<u32>,
spool: File,
len: u64,
done: bool,
}
impl Write for Upload {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let n = self.spool.write(data)?;
self.len += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
if self.done {
return Ok(());
}
self.spool.seek(SeekFrom::Start(0))?;
let d = &self.device;
let mut guard = lock(&d.session);
let s = guard
.as_mut()
.ok_or_else(|| io::Error::other("phone disconnected"))?;
if let Some(old) = self.replace.take() {
s.delete_object(old).map_err(io::Error::other)?;
d.forget(old);
}
let object = NewObject {
name: self.name.clone(),
size: self.len,
modified: None,
folder: false,
};
let (_, _, handle) = s
.send_object_info(self.storage, self.parent, &object)
.map_err(io::Error::other)?;
s.send_object(&mut self.spool, self.len)
.map_err(io::Error::other)?;
self.done = true;
d.put(
self.storage,
&self.dir,
Object {
handle,
storage_id: self.storage,
parent: self.parent,
format: code::FORMAT_UNDEFINED,
name: self.name.clone(),
size: self.len,
modified: Some(std::time::SystemTime::now()),
},
);
Ok(())
}
}
fn run_events(device: Weak<Device>, mut events: Box<dyn Events>, on_change: Option<OnChange>) {
loop {
let bytes = match events.next(EVENT_WAIT) {
Ok(Some(b)) => b,
Ok(None) | Err(Error::Timeout) if device.strong_count() > 0 => continue,
_ => return,
};
let (Some(d), Ok(event)) = (device.upgrade(), Container::decode(&bytes)) else {
continue;
};
let handle = event.params.first().copied().unwrap_or(0);
match event.code {
code::EVENT_STORE_ADDED
| code::EVENT_STORE_REMOVED
| code::EVENT_STORAGE_INFO_CHANGED
| code::EVENT_DEVICE_INFO_CHANGED => {
let mut guard = lock(&d.session);
if let Some(s) = guard.as_mut() {
*lock(&d.state) = read_storages(s);
*lock(&d.cache) = Cache::default();
}
drop(guard);
if let Some(f) = &on_change {
f();
}
}
code::EVENT_OBJECT_REMOVED => {
if let Some(uri) = d.forget(handle) {
d.notify(vec![uri]);
}
}
code::EVENT_OBJECT_ADDED
| code::EVENT_OBJECT_INFO_CHANGED
| code::EVENT_OBJECT_PROP_CHANGED => {
let old = lock(&d.cache).paths.get(&handle).cloned();
let object = lock(&d.session)
.as_mut()
.and_then(|s| s.object(handle).ok());
let mut changed: Vec<Uri> = old.into_iter().collect();
if let Some(o) = object {
let dir = if o.parent == code::ROOT {
Some(storage_uri(&d.key, o.storage_id))
} else {
lock(&d.cache).paths.get(&o.parent).cloned()
};
if let Some(dir) = dir {
let uri = dir.join(o.name.as_bytes());
d.forget(handle);
d.put(o.storage_id, &dir, o);
if !changed.contains(&uri) {
changed.push(uri);
}
}
}
d.notify(changed);
}
_ => {}
}
}
}
fn read_storages(s: &mut Phone) -> State {
let mut state = State::default();
match s.storage_ids() {
Ok(ids) => {
for id in ids {
// Ids with an empty low half are storages that aren't there (no card).
if id & 0xFFFF == 0 {
continue;
}
match s.storage_info(id) {
Ok(info) => state.storages.push((id, info)),
Err(e) => state.problem = Some(problem(&e)),
}
}
if state.storages.is_empty() && state.problem.is_none() {
state.problem = Some(LOCKED.into());
}
}
Err(e) => state.problem = Some(problem(&e)),
}
state
}
const LOCKED: &str = "Unlock the phone and allow file transfer (in its USB settings choose \
File transfer), then open it again";
/// The message shown for a device that can't be browsed.
fn problem(e: &Error) -> String {
match e {
Error::Busy => "Another program is using this phone. Close it, or unplug the phone \
and plug it in again"
.into(),
Error::PermissionDenied => "No permission to open this USB device. It needs a udev \
rule for phones (for example the android-udev package)"
.into(),
// Storage not available, device busy: a locked phone answers so.
Error::Response(0x2013 | 0x2019) => LOCKED.into(),
e => format!("Can't talk to this phone: {e}"),
}
}
fn core_error(e: Error) -> CoreError {
match e {
Error::Response(code::INVALID_OBJECT_HANDLE) => CoreError::NotFound,
Error::Response(0x200D..=0x200F) => CoreError::PermissionDenied,
Error::Io(m) => CoreError::Io(m),
e => CoreError::Remote(e.to_string()),
}
}
fn storage_uri(key: &str, storage: u32) -> Uri {
Uri::new(SCHEME, key, format!("/{storage:08x}"))
}
/// Parent URI and file name of `uri`.
fn split(uri: &Uri) -> Result<(Uri, &[u8])> {
match (uri.parent(), uri.file_name()) {
(Some(dir), Some(name)) if !name.is_empty() => Ok((dir, name)),
_ => Err(CoreError::Unsupported),
}
}
fn dir_entry(name: Vec<u8>) -> Entry {
Entry {
display_name: display_name(&name),
name,
kind: Kind::Dir,
size: 0,
mtime: None,
mode: 0,
uid: 0,
gid: 0,
hidden: false,
mime: mime::mime_type(b"", &Kind::Dir),
}
}
fn to_entry(o: Object) -> Entry {
let kind = if o.is_folder() { Kind::Dir } else { Kind::File };
let name = o.name.into_bytes();
Entry {
display_name: display_name(&name),
hidden: name.first() == Some(&b'.'),
mime: mime::mime_type(&name, &kind),
name,
kind,
size: o.size,
mtime: o.modified,
mode: 0,
uid: 0,
gid: 0,
}
}
fn to_entries(objects: Vec<Object>) -> Vec<Entry> {
objects.into_iter().map(to_entry).collect()
}
/// An unlinked read-write temp file.
fn spool_file() -> Result<File> {
let n = NEXT_SPOOL.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("tunal-mtp-{}-{n}", std::process::id()));
let file = File::options()
.read(true)
.write(true)
.create_new(true)
.open(&path)?;
let _ = std::fs::remove_file(&path);
Ok(file)
}
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}

View file

@ -2,6 +2,8 @@
//! operations Android phones offer. All calls block; run them off the UI thread.
mod container;
mod hotplug;
mod location;
mod ops;
mod replay;
mod session;
@ -10,15 +12,21 @@ mod transport;
use std::fmt;
pub use container::{Container, Header, Kind, Reader, Value, Writer, format_date, parse_date};
pub use hotplug::watch;
pub use location::{DevicePlace, MtpLocation, SCHEME};
pub use ops::{DeviceInfo, NewObject, Object, ObjectInfo, StorageInfo};
pub use replay::{ReplayTransport, Step};
pub use session::Session;
pub use transport::{Transport, UsbTransport, devices, mtp_interface};
pub use transport::{Events, Transport, UsbTransport, devices, mtp_interface};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
/// The USB device has no usable MTP interface.
NoInterface,
/// Another program (or kernel driver that can't be detached) holds the interface.
Busy,
/// No access to the USB device node (udev rules).
PermissionDenied,
Usb(String),
Disconnected,
Timeout,
@ -40,6 +48,8 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::NoInterface => f.write_str("no MTP interface on this device"),
Error::Busy => f.write_str("another program is using the device"),
Error::PermissionDenied => f.write_str("no permission to open the USB device"),
Error::Usb(e) => write!(f, "USB error: {e}"),
Error::Disconnected => f.write_str("device disconnected"),
Error::Timeout => f.write_str("device did not answer"),
@ -74,6 +84,15 @@ pub mod code {
/// Android: 64-bit offset partial read.
pub const GET_PARTIAL_OBJECT_64: u16 = 0x95C1;
pub const EVENT_OBJECT_ADDED: u16 = 0x4002;
pub const EVENT_OBJECT_REMOVED: u16 = 0x4003;
pub const EVENT_STORE_ADDED: u16 = 0x4004;
pub const EVENT_STORE_REMOVED: u16 = 0x4005;
pub const EVENT_OBJECT_INFO_CHANGED: u16 = 0x4007;
pub const EVENT_DEVICE_INFO_CHANGED: u16 = 0x4008;
pub const EVENT_STORAGE_INFO_CHANGED: u16 = 0x400C;
pub const EVENT_OBJECT_PROP_CHANGED: u16 = 0xC801;
pub const OK: u16 = 0x2001;
pub const SESSION_ALREADY_OPEN: u16 = 0x201E;
pub const INVALID_OBJECT_HANDLE: u16 = 0x2009;

View file

@ -23,6 +23,38 @@ pub trait Transport: Send {
fn receive(&mut self, max: usize) -> Result<Vec<u8>, Error>;
/// One interrupt-in transfer (an event container), `None` when nothing came in `timeout`.
fn event(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error>;
/// Moves the interrupt endpoint out for a thread of its own (events then never block
/// bulk transfers); `None` when there is none.
fn take_events(&mut self) -> Option<Box<dyn Events>> {
None
}
}
/// The interrupt-in endpoint on its own: one event container per call.
pub trait Events: Send {
fn next(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error>;
}
impl<T: Transport + ?Sized> Transport for Box<T> {
fn max_packet_size(&self) -> usize {
(**self).max_packet_size()
}
fn send(&mut self, data: &[u8]) -> Result<(), Error> {
(**self).send(data)
}
fn receive(&mut self, max: usize) -> Result<Vec<u8>, Error> {
(**self).receive(max)
}
fn event(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error> {
(**self).event(timeout)
}
fn take_events(&mut self) -> Option<Box<dyn Events>> {
(**self).take_events()
}
}
/// An MTP interface claimed on a USB device.
@ -109,10 +141,25 @@ impl Transport for UsbTransport {
}
fn event(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error> {
let Some(ep) = &mut self.interrupt else {
std::thread::sleep(timeout);
return Ok(None);
};
match &mut self.interrupt {
Some(ep) => UsbEvents::read(ep, timeout),
None => {
std::thread::sleep(timeout);
Ok(None)
}
}
}
fn take_events(&mut self) -> Option<Box<dyn Events>> {
let ep = self.interrupt.take()?;
Some(Box::new(UsbEvents(ep)))
}
}
struct UsbEvents(Endpoint<Interrupt, In>);
impl UsbEvents {
fn read(ep: &mut Endpoint<Interrupt, In>, timeout: Duration) -> Result<Option<Vec<u8>>, Error> {
let size = ep.max_packet_size().max(64);
match ep
.transfer_blocking(Buffer::new(size), timeout)
@ -125,8 +172,19 @@ impl Transport for UsbTransport {
}
}
impl Events for UsbEvents {
fn next(&mut self, timeout: Duration) -> Result<Option<Vec<u8>>, Error> {
Self::read(&mut self.0, timeout)
}
}
fn usb_error(e: nusb::Error) -> Error {
Error::Usb(e.to_string())
match e.kind() {
nusb::ErrorKind::Busy => Error::Busy,
nusb::ErrorKind::PermissionDenied => Error::PermissionDenied,
nusb::ErrorKind::Disconnected => Error::Disconnected,
_ => Error::Usb(e.to_string()),
}
}
fn transfer_error(e: TransferError) -> Error {

View file

@ -11,6 +11,7 @@ tunal-theme = { path = "../tunal-theme" }
png.workspace = true
tunal-core = { path = "../tunal-core" }
tunal-elevate = { path = "../tunal-elevate" }
tunal-devices = { path = "../tunal-devices" }
tunal-dirmeta = { path = "../tunal-dirmeta" }
tunal-thumbs = { path = "../tunal-thumbs" }
jiff.workspace = true

View file

@ -0,0 +1,51 @@
//! Phones in the sidebar: the `mtp://` backend and its hotplug watch, adapted to the shell.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use tunal_core::Locations;
use tunal_devices::mtp::{self, MtpLocation};
use crate::shell::Shell;
use crate::shell::places::Place;
/// Material Symbols `smartphone`.
const PHONE: &str = "\u{e32c}";
thread_local! {
static SHELL: RefCell<Weak<Shell>> = const { RefCell::new(Weak::new()) };
}
/// Adds the `mtp://` backend to `locations`.
pub fn register(locations: &mut Locations) -> Arc<MtpLocation> {
let mtp = Arc::new(MtpLocation::new());
locations.register(mtp.clone());
mtp
}
/// Fills the Devices section now and on every plug, unplug or storage change.
pub fn attach(shell: &Rc<Shell>, mtp: Arc<MtpLocation>) {
SHELL.with(|s| *s.borrow_mut() = Rc::downgrade(shell));
let source = mtp.clone();
let watched = mtp::watch(mtp, move || {
let places = source.places();
let _ = slint::invoke_from_event_loop(move || {
let items = places
.into_iter()
.map(|p| Place {
name: p.name,
glyph: PHONE,
uri: p.uri,
})
.collect();
if let Some(shell) = SHELL.with(|s| s.borrow().upgrade()) {
shell.set_devices(items);
}
});
});
// No hotplug (no udev netlink in a sandbox): phones just don't show up.
if let Err(e) = watched {
eprintln!("tunal: phones: {e}");
}
}

View file

@ -1,6 +1,7 @@
mod actions;
mod config;
mod desktop_apps;
mod devices_bridge;
mod dnd;
mod folder;
mod icons;
@ -83,7 +84,10 @@ fn window(
.iter()
.map(|dirs| dirs.iter().map(|d| Uri::from_path(d)).collect())
.collect();
let shell = shell::Shell::attach(&ui, Locations::with_local(), tabs, blocking);
let mut locations = Locations::with_local();
let mtp = devices_bridge::register(&mut locations);
let shell = shell::Shell::attach(&ui, locations, tabs, blocking);
devices_bridge::attach(&shell, mtp);
// `TUNAL_SETTINGS=<page 0-4>` opens the settings dialog (screenshots).
if let Some(page) = std::env::var("TUNAL_SETTINGS")
.ok()

View file

@ -457,6 +457,14 @@ impl Shell {
}
}
/// Replaces the sidebar's Devices entries.
pub(crate) fn set_devices(&self, items: Vec<places::Place>) {
self.places
.borrow_mut()
.set_section(Section::Devices, items);
self.show_chrome();
}
pub(crate) fn show_chrome(&self) {
let Some(ui) = self.ui.upgrade() else {
return;

View file

@ -147,7 +147,6 @@ impl Places {
}
/// Replaces the items of a section the app fills at run time (devices, network).
#[expect(dead_code, reason = "the device and network plans fill these sections")]
pub fn set_section(&mut self, section: Section, items: Vec<Place>) {
match section {
Section::Devices => self.devices = items,

View file

@ -184,6 +184,15 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Not done: arrival fade, scroll cancel and live toggle not watched (single frames); a link badge hides while a thumbnail shows; video frame change doesn't redo existing thumbnails; plain `workspace` clippy red until S026 fixes `tunal-devices`. Screenshots now draw once, run `Shell::settle_thumbs`, then draw again.
- Later: preview panel; thumbnails for PDFs; remote locations (SFTP/devices) need a read path in the pool.
## S026 — Android devices over MTP
- Done: `mtp::MtpLocation` (`Location`, scheme `mtp`): `mtp://<serial>/` = the device (its storages as folders `<id hex>`), `mtp://<serial>/<storage>/<path>`. Path → handle walk over a children cache (miss → one fresh listing), handle → URI map for events; list (always fresh), stat (fresh ObjectInfo), open_read (GetPartialObject(64) in 1 MiB chunks, session locked per chunk; else GetObject on a thread through a pipe, short stream → error), open_write (spooled to an unlinked temp file, sent on `flush`; unflushed drop sends nothing; Overwrite deletes the old object first), mkdir, rename (move + ObjectFileName), delete (permanent, `NotEmpty` for non-empty folders; trash Unsupported so the UI confirms). Capabilities write + watch. Watch: per-device interrupt thread (`Transport::take_events`) turns ObjectAdded/Removed/InfoChanged/PropChanged into `Changed([child uris])` for the watched folder; storage events re-read storages and refresh the sidebar.
- `mtp::watch(location, on_change)` (hotplug.rs): nusb `watch_devices` + initial scan, key = serial (URI-safe) else `usb-<bus>-<addr>`; `connect(key, name, usb id, transport)` / `disconnect_usb(id)` / `places() -> Vec<DevicePlace { name, uri }>` (one per storage, "Model · Storage" when several; one device entry while it has a problem). `mtp::Error::{Busy, PermissionDenied}` from nusb kinds.
- Messages (shown as the folder error when the device entry is opened): busy, no USB permission (udev rule), locked / no file transfer (no storages; re-checked on open, StoreAdded refreshes).
- App: `devices_bridge.rs` (`register` adds the backend to `Locations`, `attach` fills Devices via `Shell::set_devices`, glyph `smartphone`); hotplug failure → one stderr line. Example helpers moved to `examples/common`; new `--example mtp_location` (busy/locked phones, list/stat/read/write/mkdir/rename/delete over replay).
- Verified: workspace build, clippy -D warnings, fmt --check and the screenshot in a scratch worktree (HEAD + S026 only; the shared checkout fails on S018's in-flight settings files); app with no phone: Devices "No phones connected", no error; `mtp_location` and `mtp_replay` pass.
- Not done: real phone, hotplug events, MTP events, permission message (S036). Breadcrumb shows the serial and storage hex, not names. Long transfers hold the device lock (listing waits).
- Later: device/storage names in breadcrumb; cancel a running GetObject (MTP Cancel request); free space in the sidebar tooltip.
## Later
- (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034.
-