diff --git a/CHANGELOG.md b/CHANGELOG.md index d334987..86ff7b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ All notable changes to MagicInput are documented here. The project follows [Sema - **Each keyboard stays on its own computer.** Once a computer's own keyboard has been used, clicking it with its own mouse no longer pulls the other computer's keyboard over, so clicking on the PC doesn't interrupt typing on the Mac (and the other way round). The keyboards only move with the pointer when it crosses the edge. A computer without a keyboard still borrows the other one's when clicked. - Opening MagicInput (Spotlight, Finder, the Start menu) brings back a hidden menu bar / tray icon, until it's hidden again from its menu. +### Added + +- **AirDrop to the PC.** Files AirDropped to the Mac move on to the PC's Downloads folder (and show in Explorer) when you were working on the PC: the pointer is there, or the PC's own keyboard or mouse was used more recently than the Mac's. Set `airdrop = "always"` or `"never"` in the Mac's config file to change that. They travel encrypted over a connection of their own, so the pointer stays smooth. The first time, macOS asks to let MagicInput access the Downloads folder. Both computers need this version. + ## [0.5.0] - 2026-10-19 ### Changed diff --git a/Cargo.toml b/Cargo.toml index 5dd1318..eccd11a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,7 @@ window-vibrancy = "0.8.1" wry = "0.57.0" [target."cfg(windows)".dependencies] -windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_System_Threading", "Win32_UI_Shell", "Win32_System_Registry", "Win32_Storage_Packaging_Appx"] } +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_UI_Shell", "Win32_System_Registry", "Win32_Storage_Packaging_Appx"] } windows = { version = "0.62", features = ["ApplicationModel"] } [target.'cfg(target_os = "macos")'.dependencies] diff --git a/README.md b/README.md index d2d6e92..25c5186 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ Your Mac's keyboard and trackpad are right there, and so is the PC's monitor. Ma | Arrange like System Settings | Drag the PC next to your displays, iPad (Sidecar) included, and move the iPad itself. The pointer crosses only where the screens touch, at the matching height. | | Keyboard follows the click | No keyboard on the PC? Click into a text field with its own mouse and keep typing on the Mac keyboard (and the other way round). | | Copy and paste across | Copied text follows the pointer to the other computer. | +| AirDrop to the PC | AirDrop from your iPhone to the Mac while you're working on the PC, and the file lands in the PC's Downloads folder. | | Mac shortcuts on the PC | ⌘C copies on Windows (Ctrl and ⌘ swap automatically; can be turned off). | | Private and local | Finds the other computer on your network by itself. Encrypted end to end, paired with a short code, refuses anything outside your local network. No account, no cloud, no telemetry. | | Smooth on Wi-Fi | Late pointer updates are replayed as a quick glide instead of a jump. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 09ff3d8..380a628 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -42,6 +42,7 @@ After the handshake both sides exchange `Hello` (name, OS, protocol version, scr | `Focus` | The sender was clicked with its own mouse: send your keys here (keyboard follows the click). | | `Layout` | The arrangement changed; the newest one wins. | | `Ping` | Keep-alive every second when idle; a silent link is dropped after 5 s. | +| `Offer`, `Answer`, `Data`, `Received` | A file AirDropped to the Mac, on a connection of its own (opened with `Offer` instead of a hello, so a big file never holds up the pointer). The PC takes it if the Mac's user is working on the PC, or if the PC was used more recently; the Mac removes its copy after `Received`. | Bursts of movement are merged before sending. On the receiving side, movement that arrives later than usual (Wi-Fi often holds packets) is queued, together with anything behind it, and replayed at double speed, so the pointer glides instead of jumping and clicks still land in the right place. diff --git a/src/airdrop.rs b/src/airdrop.rs new file mode 100644 index 0000000..6a19ca7 --- /dev/null +++ b/src/airdrop.rs @@ -0,0 +1,112 @@ +//! AirDrop relay (Mac): files AirDropped to this Mac move on to the other computer's Downloads +//! folder when that's where you're working (`airdrop` in the config: auto, always or never). +//! +//! AirDrop always saves into ~/Downloads and marks the file as coming from `sharingd`. We watch +//! for new files with that mark, wait until they stop growing, then offer them to the other +//! computer; once it has saved one, the copy here is removed. + +use std::collections::{HashMap, HashSet}; +use std::ffi::CString; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime}; + +use log::{info, warn}; + +use crate::config::{AirDrop, Config}; +use crate::core::Core; +use crate::net::Net; + +/// A new file that hasn't shown the AirDrop mark by then isn't an AirDrop. +const MARK_WAIT: Duration = Duration::from_secs(60); + +/// A new file in Downloads, until it's known whether it's a finished AirDrop. +struct Arrival { + since: Instant, + size: u64, + /// Checks in a row its size stayed the same. + steady: u32, +} + +pub fn watch(core: &'static Core, net: Arc) { + let Some(dir) = directories::UserDirs::new().and_then(|d| d.download_dir().map(Path::to_path_buf)) else { return }; + let mut seen: Option> = None; + let mut arrivals: HashMap = HashMap::new(); + let mut dir_changed: Option = None; + let mut warned = false; + loop { + std::thread::sleep(Duration::from_secs(1)); + let changed = std::fs::metadata(&dir).and_then(|m| m.modified()).ok(); + if changed != dir_changed || seen.is_none() { + let entries = match std::fs::read_dir(&dir) { + Ok(rd) => rd.flatten().map(|e| e.path()).collect::>(), + Err(e) => { + if !warned { + warn!("Can't read {} for AirDrops ({e}): allow MagicInput to access the Downloads folder", dir.display()); + warned = true; + } + continue; + } + }; + dir_changed = changed; + // Files that were there before we started stay put; only new arrivals move. + if let Some(seen) = &seen { + for p in entries.difference(seen) { + arrivals.insert(p.clone(), Arrival { since: Instant::now(), size: u64::MAX, steady: 0 }); + } + } + seen = Some(entries); + } + + let mut ready = Vec::new(); + arrivals.retain(|p, a| { + let Some(size) = std::fs::metadata(p).ok().filter(|m| m.is_file()).map(|m| m.len()) else { return false }; + if !airdropped(p) { + return a.since.elapsed() < MARK_WAIT; + } + a.steady = if size == a.size { a.steady + 1 } else { 0 }; + a.size = size; + if a.steady >= 2 { + ready.push(p.clone()); + return false; + } + true + }); + + for p in ready { + let force = match Config::read().map(|c| c.airdrop).unwrap_or_default() { + AirDrop::Never => continue, + AirDrop::Always => true, + AirDrop::Auto => match core.using_peer() { + Some(false) => continue, + Some(true) => true, + // The other computer takes it if it was used more recently. + None => false, + }, + }; + let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned(); + match net.send_file(&p, force) { + Ok(true) => { + info!("AirDrop {name} moved to the other computer's Downloads"); + if let Err(e) = std::fs::remove_file(&p) { + warn!("Couldn't remove {name} here after sending it: {e}"); + } + } + Ok(false) => info!("AirDrop {name} stays on this Mac"), + Err(e) => warn!("Couldn't send AirDrop {name} to the other computer ({e}); it stays on this Mac"), + } + } + } +} + +/// The file was saved by AirDrop (its quarantine mark names `sharingd`). +fn airdropped(path: &Path) -> bool { + unsafe extern "C" { + fn getxattr(path: *const i8, name: *const i8, value: *mut u8, size: usize, position: u32, options: i32) -> isize; + } + let Ok(p) = CString::new(path.as_os_str().as_bytes()) else { return false }; + let mut buf = [0u8; 256]; + let n = unsafe { getxattr(p.as_ptr(), c"com.apple.quarantine".as_ptr(), buf.as_mut_ptr(), buf.len(), 0, 0) }; + n > 0 && String::from_utf8_lossy(&buf[..n as usize]).split(';').nth(2) == Some("sharingd") +} diff --git a/src/config.rs b/src/config.rs index 8d49ed2..353e2d7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -25,6 +25,20 @@ impl Layout { } } +/// Where files AirDropped to this Mac go. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum AirDrop { + /// To the computer you were working on: they move to the other computer's Downloads folder + /// when that's the one you used last. + #[default] + Auto, + /// Always to the other computer. + Always, + /// They stay on this Mac. + Never, +} + pub const DEFAULT_PORT: u16 = 24842; const CODE_ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTUVWXYZ"; @@ -58,6 +72,8 @@ pub struct Config { /// This computer's own keyboard has been used, so clicking here never borrows the other /// computer's keyboard: each keyboard types on its own computer until the pointer crosses. pub has_keyboard: bool, + /// Where files AirDropped to this Mac go (Mac only). + pub airdrop: AirDrop, /// Arrangement from the settings window; `None` = auto / `peer_side`. pub layout: Option, /// When `layout` last changed (unix ms), so both computers keep the newest. @@ -84,6 +100,7 @@ impl Default for Config { show_tray: false, keyboard_follows_click: true, has_keyboard: false, + airdrop: AirDrop::Auto, layout: None, layout_time: 0, license: String::new(), diff --git a/src/core.rs b/src/core.rs index ec807ba..8e8f9ac 100644 --- a/src/core.rs +++ b/src/core.rs @@ -153,6 +153,20 @@ impl Core { self.mode.load(Ordering::SeqCst) == REMOTE } + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] // used by the AirDrop relay + /// Whether the person is working on the other computer right now (`Some(true)`: this + /// keyboard or mouse goes there), on this one (`Some(false)`: the other computer's input + /// drives this one), or it isn't clear (`None`: each computer uses its own). + pub fn using_peer(&self) -> Option { + let st = self.st.lock().unwrap(); + match self.mode.load(Ordering::SeqCst) { + REMOTE => Some(true), + CONTROLLED => Some(false), + _ if st.keys_to_peer => Some(true), + _ => None, + } + } + fn send(&self, m: Msg) { let _ = self.out.send(m); } diff --git a/src/lib.rs b/src/lib.rs index 19f08eb..069c8c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ //! Shared entry point for `magicinput` (command line) and `magicinputw` (Windows background, no window). +#[cfg(target_os = "macos")] +mod airdrop; mod config; mod core; mod geom; @@ -188,6 +190,11 @@ fn run(mut cfg: Config) { Err(e) => exit(&e.to_string()), }; std::thread::spawn(|| status::publish_loop(platform::core())); + #[cfg(target_os = "macos")] + { + let net = net.clone(); + std::thread::spawn(move || airdrop::watch(core, net)); + } std::thread::spawn(move || watch_config(core, net)); std::thread::spawn(license_loop); if cfg.show_tray { diff --git a/src/net.rs b/src/net.rs index b8baea9..2bc9386 100644 --- a/src/net.rs +++ b/src/net.rs @@ -2,8 +2,10 @@ use std::collections::HashMap; use std::error::Error; +use std::fs::File; use std::io::{Read, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs}; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use std::thread; @@ -24,6 +26,12 @@ const NOISE: &str = "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s"; const SERVICE: &str = "_magicinput._tcp.local."; const MAX_FRAME: usize = 65535; const TIMEOUT: Duration = Duration::from_secs(5); +/// File connections wait longer: saving the end of a big file can take a while. +const FILE_TIMEOUT: Duration = Duration::from_secs(30); +// Only Macs send files (AirDrops) for now. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +/// File data per message (a frame holds 65535 bytes, minus encryption and message overhead). +const CHUNK: usize = 60_000; struct Active { generation: u64, @@ -248,7 +256,11 @@ impl Net { access: true, }; write_msg(&mut stream, &mut noise, &hello)?; - let Msg::Hello { id, name, os, version, peer_side, screens, layout, layout_time, .. } = read_msg(&mut stream, &mut noise)? else { + let first = read_msg(&mut stream, &mut noise)?; + if let Msg::Offer { name, size, force, idle_ms } = first { + return receive_offer(&mut stream, &mut noise, &name, size, force, idle_ms); + } + let Msg::Hello { id, name, os, version, peer_side, screens, layout, layout_time, .. } = first else { return Err("expected hello".into()); }; if version != PROTOCOL_VERSION { @@ -304,6 +316,31 @@ impl Net { Ok(()) } + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + /// Offer a file to the other computer over a connection of its own. `force`: our user is + /// working on the other computer. Returns whether it took the file and saved all of it. + pub fn send_file(&self, path: &Path, force: bool) -> Res { + let addr = { + let active = self.active.lock().unwrap(); + let Some(a) = active.as_ref() else { return Ok(false) }; + let port = self.found.lock().unwrap().get(&a.peer_id).map(|f| f.port); + SocketAddr::new(a.stream.peer_addr()?.ip(), port.unwrap_or(self.cfg.read().unwrap().port)) + }; + let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2))?; + stream.set_nodelay(true)?; + stream.set_read_timeout(Some(FILE_TIMEOUT))?; + stream.set_write_timeout(Some(FILE_TIMEOUT))?; + let psk = *self.psk.lock().unwrap(); + let mut noise = handshake(&mut stream, &psk, true)?; + let Msg::Hello { version, .. } = read_msg(&mut stream, &mut noise)? else { + return Err("expected hello".into()); + }; + if version != PROTOCOL_VERSION { + return Err(format!("the other computer runs protocol v{version}, we run v{PROTOCOL_VERSION}").into()); + } + offer_file(&mut stream, &mut noise, path, force, crate::platform::idle_ms()) + } + /// Sends queued messages, and a ping every second so both sides notice a dead link. fn writer(&self, out: Receiver) { loop { @@ -448,6 +485,114 @@ fn handshake(stream: &mut TcpStream, psk: &[u8; 32], initiator: bool) -> Res Res<()> { + stream.set_read_timeout(Some(FILE_TIMEOUT))?; + stream.set_write_timeout(Some(FILE_TIMEOUT))?; + let here = crate::platform::idle_ms(); + let accept = force || here < idle_ms; + info!("Offered {name} ({size} bytes): {} (used {here} ms ago here, {idle_ms} ms ago there)", if accept { "taking it" } else { "leaving it there" }); + let dir = directories::UserDirs::new().and_then(|d| d.download_dir().map(Path::to_path_buf)).ok_or("no Downloads folder")?; + if let Some(path) = receive_file(stream, noise, name, size, accept, &dir)? { + info!("Saved {}", path.display()); + crate::platform::reveal(&path); + } + Ok(()) +} + +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +/// Sender side of a file connection, after the hello. +fn offer_file(stream: &mut TcpStream, noise: &mut TransportState, path: &Path, force: bool, idle_ms: u64) -> Res { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + let name = path.file_name().and_then(|n| n.to_str()).ok_or("file name isn't text")?.to_string(); + write_msg(stream, noise, &Msg::Offer { name, size, force, idle_ms })?; + let Msg::Answer { accept } = read_msg(stream, noise)? else { + return Err("expected an answer".into()); + }; + if !accept { + return Ok(false); + } + let mut buf = vec![0u8; CHUNK]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + write_msg(stream, noise, &Msg::Data(buf[..n].to_vec()))?; + } + match read_msg(stream, noise)? { + Msg::Received => Ok(true), + _ => Err("expected a receipt".into()), + } +} + +/// Receiver side: answer, then save the file into `dir` under a free name. Nothing is left +/// behind if the transfer breaks off. +fn receive_file(stream: &mut TcpStream, noise: &mut TransportState, name: &str, size: u64, accept: bool, dir: &Path) -> Res> { + write_msg(stream, noise, &Msg::Answer { accept })?; + if !accept { + return Ok(None); + } + static PART: AtomicU64 = AtomicU64::new(0); + let name = safe_name(name); + let part = dir.join(format!("{name}.{}.magicinput", PART.fetch_add(1, Ordering::SeqCst))); + let r = (|| -> Res { + let mut file = File::create(&part)?; + let mut got = 0u64; + while got < size { + let Msg::Data(d) = read_msg(stream, noise)? else { + return Err("expected file data".into()); + }; + got += d.len() as u64; + if got > size { + return Err("more data than announced".into()); + } + file.write_all(&d)?; + } + file.sync_all()?; + drop(file); + let dest = free_path(dir, &name); + std::fs::rename(&part, &dest)?; + write_msg(stream, noise, &Msg::Received)?; + Ok(dest) + })(); + if r.is_err() { + let _ = std::fs::remove_file(&part); + } + r.map(Some) +} + +/// A file name that is safe on Windows and macOS: no folders, no reserved characters. +fn safe_name(name: &str) -> String { + let s: String = name.chars().map(|c| if c.is_control() || r#"/\:*?"<>|"#.contains(c) { '_' } else { c }).collect(); + let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace()); + let stem = s.split('.').next().unwrap_or("").to_ascii_uppercase(); + let reserved = ["CON", "PRN", "AUX", "NUL"].contains(&stem.as_str()) + || (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit()); + match s { + "" => "file".into(), + s if reserved => format!("_{s}"), + s => s.into(), + } +} + +/// `dir/name`, or `dir/name (2).ext` and so on if that's taken. +fn free_path(dir: &Path, name: &str) -> PathBuf { + let (stem, ext) = match name.rsplit_once('.') { + Some((s, e)) if !s.is_empty() => (s, format!(".{e}")), + _ => (name, String::new()), + }; + let mut path = dir.join(name); + let mut n = 2; + while path.exists() { + path = dir.join(format!("{stem} ({n}){ext}")); + n += 1; + } + path +} + fn write_msg(stream: &mut TcpStream, noise: &mut TransportState, msg: &Msg) -> Res<()> { let plain = postcard::to_stdvec(msg)?; if plain.len() + 16 > MAX_FRAME { @@ -520,6 +665,53 @@ mod tests { assert!(!same_lan("8.8.8.8".parse().unwrap())); } + #[test] + fn file_travels_in_pieces_and_lands_under_a_free_name() { + let dir = std::env::temp_dir().join(format!("magicinput-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let src = dir.join("photo.heic"); + let data: Vec = (0..150_000u32).map(|i| i as u8).collect(); + std::fs::write(&src, &data).unwrap(); + std::fs::write(dir.join("out/photo.heic"), b"already here").unwrap(); + + let (ra, rb, mut a, mut b) = pair([3; 32], [3; 32]); + let (mut na, mut nb) = (ra.unwrap(), rb.unwrap()); + let sender = thread::spawn(move || offer_file(&mut a, &mut na, &src, true, 0).unwrap()); + let Msg::Offer { name, size, force, .. } = read_msg(&mut b, &mut nb).unwrap() else { panic!("expected an offer") }; + assert_eq!((name.as_str(), size, force), ("photo.heic", 150_000, true)); + let saved = receive_file(&mut b, &mut nb, &name, size, true, &dir.join("out")).unwrap().unwrap(); + assert!(sender.join().unwrap(), "sender saw the receipt"); + assert_eq!(saved, dir.join("out/photo (2).heic")); + assert_eq!(std::fs::read(&saved).unwrap(), data); + assert_eq!(std::fs::read_dir(dir.join("out")).unwrap().count(), 2, "no part file left"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn declined_files_stay_with_the_sender() { + let dir = std::env::temp_dir().join(format!("magicinput-test-decline-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let src = dir.join("a.txt"); + std::fs::write(&src, b"hi").unwrap(); + let (ra, rb, mut a, mut b) = pair([4; 32], [4; 32]); + let (mut na, mut nb) = (ra.unwrap(), rb.unwrap()); + let sender = thread::spawn(move || offer_file(&mut a, &mut na, &src, false, 0).unwrap()); + let Msg::Offer { name, size, .. } = read_msg(&mut b, &mut nb).unwrap() else { panic!("expected an offer") }; + assert_eq!(receive_file(&mut b, &mut nb, &name, size, false, &dir).unwrap(), None); + assert!(!sender.join().unwrap()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn file_names_are_made_safe() { + assert_eq!(safe_name("../../etc/passwd"), "_.._etc_passwd"); + assert_eq!(safe_name("a:b*c?.txt"), "a_b_c_.txt"); + assert_eq!(safe_name("con.txt"), "_con.txt"); + assert_eq!(safe_name(" ... "), "file"); + assert_eq!(safe_name("IMG_0001.HEIC"), "IMG_0001.HEIC"); + } + #[test] fn wrong_code_is_rejected() { let (_ra, rb, _a, _b) = pair([1; 32], [2; 32]); diff --git a/src/platform/macos.rs b/src/platform/macos.rs index 0f6e67a..cfecb3b 100644 --- a/src/platform/macos.rs +++ b/src/platform/macos.rs @@ -66,6 +66,7 @@ unsafe extern "C" { fn CGEventPost(tap: u32, e: Ref); fn CGEventSourceCreate(state: i32) -> Ref; fn CGEventSourceSetLocalEventsSuppressionInterval(source: Ref, seconds: f64); + fn CGEventSourceSecondsSinceLastEventType(state: i32, event_type: u32) -> f64; fn CGWarpMouseCursorPosition(p: CGPoint) -> i32; fn CGAssociateMouseAndMouseCursorPosition(connected: u32) -> i32; @@ -478,3 +479,14 @@ pub fn inject_key(hid: u16, down: bool) { post(e, modifier_flags(&st.mods)); } } + +/// How long ago (ms) this computer's own keyboard, mouse or trackpad was last used. +pub fn idle_ms() -> u64 { + // HID system state, any input event type. + (unsafe { CGEventSourceSecondsSinceLastEventType(1, u32::MAX) } * 1000.0) as u64 +} + +/// Show a file in Finder. +pub fn reveal(path: &std::path::Path) { + let _ = std::process::Command::new("open").arg("-R").arg(path).spawn(); +} diff --git a/src/platform/mod.rs b/src/platform/mod.rs index 11b148f..121ce70 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -1,6 +1,6 @@ //! OS-specific input capture and injection. Each backend exposes the same free functions: //! `init`, `run_capture`, `cleanup`, `displays`, `warp`, `grab_begin`, `grab_end`, -//! `inject_move`, `inject_button`, `inject_wheel`, `inject_key`. +//! `inject_move`, `inject_button`, `inject_wheel`, `inject_key`, `idle_ms`, `reveal`. use std::sync::OnceLock; diff --git a/src/platform/windows.rs b/src/platform/windows.rs index feb280f..63a6a7d 100644 --- a/src/platform/windows.rs +++ b/src/platform/windows.rs @@ -285,3 +285,20 @@ pub fn inject_key(hid: u16, down: bool) { }; send(&[INPUT { r#type: INPUT_KEYBOARD, Anonymous: INPUT_0 { ki } }]); } + +/// How long ago (ms) this computer's own keyboard or mouse was last used. +pub fn idle_ms() -> u64 { + let mut info = LASTINPUTINFO { cbSize: size_of::() as u32, dwTime: 0 }; + unsafe { + if GetLastInputInfo(&mut info) == 0 { + return u64::MAX; + } + windows_sys::Win32::System::SystemInformation::GetTickCount().wrapping_sub(info.dwTime) as u64 + } +} + +/// Show a file in Explorer. +pub fn reveal(path: &std::path::Path) { + use std::os::windows::process::CommandExt; + let _ = std::process::Command::new("explorer").raw_arg(format!("/select,\"{}\"", path.display())).spawn(); +} diff --git a/src/proto.rs b/src/proto.rs index 18c1c31..774c13b 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -103,4 +103,15 @@ pub enum Msg { /// Only sent by MagicInput 0.4 (its trial status); ignored. Access { ok: bool }, Ping, + /// The rest travel on a connection of their own (so a big file never holds up the pointer). + /// Sender -> receiver, instead of a hello: a file that arrived by AirDrop. The receiver takes + /// it if `force` (the sender's user is working on the receiver) or if it was used more + /// recently than the sender (`idle_ms` ago). + Offer { name: String, size: u64, force: bool, idle_ms: u64 }, + /// Receiver -> sender: whether it takes the file. + Answer { accept: bool }, + /// Sender -> receiver: the next piece of the file. + Data(Vec), + /// Receiver -> sender: the whole file is saved, so the sender can remove its copy. + Received, }