Files
photoreport/apps/desktop/src-tauri/src/camera_wpd.rs
T
spark e6b5f2e390
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Failing after 14m55s
Let a Windows release, a Linux or Windows cable, and a future Developer ID join the desktop build.
The installer job was waiting on a commented matrix row, USB stayed on Image Capture, face detection could not read the Windows CPU, and notarisation had nowhere to put an Apple account.
2026-11-26 15:09:36 +00:00

326 lines
10 KiB
Rust

//! Windows USB via the portable-device API (the PTP driver Windows already owns). The device is
//! opened for this pass and released before we return, so the body is not left on the computer screen.
// The whole module is COM. Edition 2024 does not treat an `unsafe fn` body as an unsafe block.
#![allow(unsafe_op_in_unsafe_fn)]
use std::path::Path;
use windows::{
Win32::{
Devices::PortableDevices::{
IEnumPortableDeviceObjectIDs, IPortableDevice, IPortableDeviceContent,
IPortableDeviceKeyCollection, IPortableDeviceManager, IPortableDeviceValues,
PortableDevice, PortableDeviceKeyCollection, PortableDeviceManager,
PortableDeviceValues, WPD_CLIENT_MAJOR_VERSION, WPD_CLIENT_MINOR_VERSION,
WPD_CLIENT_NAME, WPD_CLIENT_REVISION, WPD_DEVICE_OBJECT_ID, WPD_OBJECT_DATE_CREATED,
WPD_OBJECT_ORIGINAL_FILE_NAME, WPD_OBJECT_SIZE, WPD_RESOURCE_DEFAULT,
},
System::Com::{
CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,
CoTaskMemFree, IStream, STGM_READ,
StructuredStorage::{PROPVARIANT, PropVariantClear},
},
System::Variant::VT_FILETIME,
},
core::{PCWSTR, PWSTR, w},
};
pub struct Shot {
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
object_id: String,
}
pub struct Report {
pub model: Option<String>,
pub id: String,
pub error: Option<String>,
pub shots: Vec<Shot>,
pub downloaded: Vec<(String, u64)>,
pub clock: Option<String>,
pub clock_unsupported: bool,
}
pub fn init_thread() {
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
}
}
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
unsafe { read_card(dir, wanted) }
}
unsafe fn read_card(dir: &Path, wanted: &[String]) -> Result<Report, String> {
let manager: IPortableDeviceManager =
CoCreateInstance(&PortableDeviceManager, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
let mut count = 0u32;
manager
.GetDevices(std::ptr::null_mut(), &mut count)
.map_err(|err| err.to_string())?;
if count == 0 {
return Ok(empty());
}
let mut ids = vec![PWSTR::null(); count as usize];
manager
.GetDevices(ids.as_mut_ptr(), &mut count)
.map_err(|err| err.to_string())?;
let device_id = ids.first().copied().unwrap_or(PWSTR::null());
let id_text = if device_id.is_null() {
String::new()
} else {
device_id.to_string().unwrap_or_default()
};
for id in &ids {
if !id.is_null() && id.0 != device_id.0 {
CoTaskMemFree(Some(id.0 as *const _));
}
}
if id_text.is_empty() {
return Ok(empty());
}
let device: IPortableDevice = CoCreateInstance(&PortableDevice, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
let client: IPortableDeviceValues =
CoCreateInstance(&PortableDeviceValues, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
client
.SetStringValue(&WPD_CLIENT_NAME, w!("PhotoReport"))
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_MAJOR_VERSION, 1)
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_MINOR_VERSION, 0)
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_REVISION, 0)
.map_err(|err| err.to_string())?;
let wide_id = wide(&id_text);
let device_name = friendly_name(&manager, PCWSTR(wide_id.as_ptr()));
device
.Open(PCWSTR(wide_id.as_ptr()), &client)
.map_err(|err| err.to_string())?;
let content = device.Content().map_err(|err| err.to_string())?;
let mut shots = Vec::new();
collect(&content, WPD_DEVICE_OBJECT_ID, 0, &mut shots).map_err(|err| err.to_string())?;
let mut downloaded = Vec::new();
let mut error = None;
for shot in &shots {
let asked = wanted.iter().any(|name| name == &shot.name);
if !asked {
continue;
}
match copy_one(&content, dir, shot) {
Ok(size) => downloaded.push((shot.name.clone(), size)),
Err(err) => error = Some(err),
}
}
if !device_id.is_null() {
CoTaskMemFree(Some(device_id.0 as *const _));
}
// `device` drops here, which closes the PTP session.
Ok(Report {
model: Some(device_name),
id: "wpd".into(),
error,
shots,
downloaded,
clock: None,
clock_unsupported: true,
})
}
fn empty() -> Report {
Report {
model: None,
id: "wpd".into(),
error: None,
shots: Vec::new(),
downloaded: Vec::new(),
clock: None,
clock_unsupported: false,
}
}
unsafe fn friendly_name(manager: &IPortableDeviceManager, id: PCWSTR) -> String {
let mut chars = 0u32;
if manager
.GetDeviceFriendlyName(id, PWSTR::null(), &mut chars)
.is_err()
|| chars <= 1
{
return "USB camera".to_string();
}
let mut buf = vec![0u16; chars as usize];
if manager
.GetDeviceFriendlyName(id, PWSTR(buf.as_mut_ptr()), &mut chars)
.is_err()
{
return "USB camera".to_string();
}
let end = (chars as usize).saturating_sub(1).min(buf.len());
let name = String::from_utf16_lossy(&buf[..end]);
if name.is_empty() {
return "USB camera".to_string();
}
name
}
unsafe fn collect(
content: &IPortableDeviceContent,
parent: PCWSTR,
depth: u32,
shots: &mut Vec<Shot>,
) -> windows::core::Result<()> {
if depth > 12 {
return Ok(());
}
let enumerator: IEnumPortableDeviceObjectIDs = content.EnumObjects(0, parent, None)?;
loop {
let mut batch = [PWSTR::null(); 32];
let mut fetched = 0u32;
let hr = enumerator.Next(&mut batch, &mut fetched);
if hr.is_err() || fetched == 0 {
break;
}
for id in batch.iter().take(fetched as usize) {
if id.is_null() {
continue;
}
let object_id = id.to_string().unwrap_or_default();
CoTaskMemFree(Some(id.0 as *const _));
if object_id.is_empty() {
continue;
}
if let Some(shot) = shot_of(content, &object_id)? {
shots.push(shot);
}
let child = wide(&object_id);
collect(content, PCWSTR(child.as_ptr()), depth + 1, shots)?;
}
}
Ok(())
}
unsafe fn shot_of(
content: &IPortableDeviceContent,
object_id: &str,
) -> windows::core::Result<Option<Shot>> {
let keys: IPortableDeviceKeyCollection =
CoCreateInstance(&PortableDeviceKeyCollection, None, CLSCTX_INPROC_SERVER)?;
keys.Add(&WPD_OBJECT_ORIGINAL_FILE_NAME)?;
keys.Add(&WPD_OBJECT_SIZE)?;
keys.Add(&WPD_OBJECT_DATE_CREATED)?;
let properties = content.Properties()?;
let object_wide = wide(object_id);
let values = properties.GetValues(PCWSTR(object_wide.as_ptr()), &keys)?;
let name_ptr = values
.GetStringValue(&WPD_OBJECT_ORIGINAL_FILE_NAME)
.unwrap_or(PWSTR::null());
if name_ptr.is_null() {
return Ok(None);
}
let name = name_ptr.to_string().unwrap_or_default();
CoTaskMemFree(Some(name_ptr.0 as *const _));
if !is_still(&name) {
return Ok(None);
}
let size = values
.GetUnsignedLargeIntegerValue(&WPD_OBJECT_SIZE)
.unwrap_or(0);
let created_ms = filetime_ms(&values);
Ok(Some(Shot {
name,
size,
created_ms,
object_id: object_id.to_string(),
}))
}
unsafe fn filetime_ms(values: &IPortableDeviceValues) -> Option<i64> {
let mut variant = values.GetValue(&WPD_OBJECT_DATE_CREATED).ok()?;
let ms = filetime_of(&variant);
let _ = PropVariantClear(&mut variant);
ms
}
/// 100-nanosecond ticks since 1601-01-01, which is how a portable device stores a capture time.
unsafe fn filetime_of(variant: &PROPVARIANT) -> Option<i64> {
let header = &variant.Anonymous.Anonymous;
if header.vt != VT_FILETIME {
return None;
}
let filetime = header.Anonymous.filetime;
let ticks = (u64::from(filetime.dwHighDateTime) << 32) | u64::from(filetime.dwLowDateTime);
const EPOCH_DIFF: u64 = 116_444_736_000_000_000;
if ticks < EPOCH_DIFF {
return None;
}
let unix_100ns = ticks - EPOCH_DIFF;
Some((unix_100ns / 10_000) as i64)
}
unsafe fn copy_one(
content: &IPortableDeviceContent,
dir: &Path,
shot: &Shot,
) -> Result<u64, String> {
let dest = dir.join(&shot.name);
if let Ok(meta) = std::fs::metadata(&dest) {
if meta.len() > 0 {
return Ok(meta.len());
}
}
std::fs::create_dir_all(dir).map_err(|err| err.to_string())?;
let resources = content.Transfer().map_err(|err| err.to_string())?;
let object_wide = wide(&shot.object_id);
let mut stream: Option<IStream> = None;
let mut optimal = 0u32;
resources
.GetStream(
PCWSTR(object_wide.as_ptr()),
&WPD_RESOURCE_DEFAULT,
STGM_READ.0 as u32,
&mut optimal,
&mut stream,
)
.map_err(|err| err.to_string())?;
let stream = stream.ok_or("no_stream")?;
let mut file = std::fs::File::create(&dest).map_err(|err| err.to_string())?;
let mut buffer = vec![0u8; 1024 * 256];
loop {
let mut read = 0u32;
let hr = stream.Read(
buffer.as_mut_ptr() as *mut _,
buffer.len() as u32,
Some(&mut read),
);
if hr.is_err() {
let _ = std::fs::remove_file(&dest);
return Err(hr.to_string());
}
if read == 0 {
break;
}
use std::io::Write;
file.write_all(&buffer[..read as usize])
.map_err(|err| err.to_string())?;
}
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
Ok(meta.len())
}
fn is_still(name: &str) -> bool {
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain(std::iter::once(0)).collect()
}