Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
1 change: 1 addition & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
112 changes: 112 additions & 0 deletions src/airdrop.rs
Original file line number Diff line number Diff line change
@@ -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<Net>) {
let Some(dir) = directories::UserDirs::new().and_then(|d| d.download_dir().map(Path::to_path_buf)) else { return };
let mut seen: Option<HashSet<PathBuf>> = None;
let mut arrivals: HashMap<PathBuf, Arrival> = HashMap::new();
let mut dir_changed: Option<SystemTime> = 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::<HashSet<_>>(),
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")
}
17 changes: 17 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<Layout>,
/// When `layout` last changed (unix ms), so both computers keep the newest.
Expand All @@ -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(),
Expand Down
14 changes: 14 additions & 0 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
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);
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading