From 9a99a586edd6f308fb23a166cc214e36ab0fe91a Mon Sep 17 00:00:00 2001 From: Humberto Prado Date: Sun, 25 Oct 2026 01:16:19 +0900 Subject: [PATCH 1/2] Magic windows (preview): show a Mac window on the PC and use it there `magicinput stream` (and the Mac menu bar item "Show Front Window on ") captures the front window with ScreenCaptureKit at one pixel per point, sends each new picture as a JPEG over a connection of its own (Stream instead of a hello, then Frame + Data), and plays the Pointer, Button, Wheel and Key messages coming back into the window. It runs as its own process and ends when the copy is closed or the window goes away. The PC shows the copy in a plain window of the service (decoded with zune-jpeg, drawn with StretchDIBits), brings it to the front, resizes it when the Mac window does, and sends what's done in it back. Both sides ping when idle. An ignored test (show_test_picture) streams a moving test picture to the other computer for checking the PC side. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + Cargo.lock | 106 +++++++++++ Cargo.toml | 10 +- README.md | 1 + docs/ARCHITECTURE.md | 1 + src/lib.rs | 46 +++-- src/net.rs | 55 ++++-- src/proto.rs | 8 + src/stream.rs | 405 +++++++++++++++++++++++++++++++++++++++++++ src/ui.rs | 44 ++++- src/viewer.rs | 310 +++++++++++++++++++++++++++++++++ 11 files changed, 951 insertions(+), 36 deletions(-) create mode 100644 src/stream.rs create mode 100644 src/viewer.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 86ff7b4..2df3fa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to MagicInput are documented here. The project follows [Sema ### Added +- **Magic windows (preview): show a Mac window on the PC.** In the Mac's menu bar menu, **Show Front Window on ** opens a live copy of the window in front on the PC (or run `magicinput stream`, `--app Safari` for a given app). Click, scroll and type in the copy and it happens in the window on the Mac; close the copy, or choose **Stop Showing the Window**, to end it. The first time, allow MagicInput under Screen & System Audio Recording in the Mac's Privacy & Security settings. Pictures go over as JPEGs at up to 30 frames a second, only when the window changes, on a connection of their own. - **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 diff --git a/Cargo.lock b/Cargo.lock index 2dcebbc..6ca3a5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1709,6 +1709,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jpeg-encoder" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6" + [[package]] name = "keyboard-types" version = "0.8.3" @@ -1815,16 +1821,22 @@ dependencies = [ "crossbeam-channel", "ctrlc", "directories", + "dispatch2", "ed25519-dalek", "embed-resource", "env_logger", "getrandom 0.4.3", "if-addrs", + "jpeg-encoder", "log", "mdns-sd", "objc2", "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-media", + "objc2-core-video", "objc2-foundation", + "objc2-screen-capture-kit", "png", "postcard", "serde", @@ -1838,6 +1850,8 @@ dependencies = [ "windows", "windows-sys 0.61.2", "wry", + "zune-core", + "zune-jpeg", ] [[package]] @@ -2059,6 +2073,16 @@ dependencies = [ "objc2-quartz-core", ] +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-cloud-kit" version = "0.3.2" @@ -2070,6 +2094,28 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2", +] + [[package]] name = "objc2-core-data" version = "0.3.2" @@ -2088,7 +2134,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2", "dispatch2", + "libc", "objc2", ] @@ -2125,6 +2173,22 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "block2", + "dispatch2", + "objc2", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + [[package]] name = "objc2-core-text" version = "0.3.2" @@ -2144,10 +2208,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" dependencies = [ "bitflags 2.13.2", + "block2", "objc2", "objc2-core-foundation", "objc2-core-graphics", "objc2-io-surface", + "objc2-metal", ] [[package]] @@ -2189,6 +2255,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-quartz-core" version = "0.3.2" @@ -2201,6 +2278,25 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-screen-capture-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74b7c5390f477482f001bc354d6571a70db7e4f8d5288e860c45521fbce11394" +dependencies = [ + "bitflags 2.13.2", + "block2", + "dispatch2", + "libc", + "objc2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-foundation", + "objc2-uniform-type-identifiers", +] + [[package]] name = "objc2-ui-kit" version = "0.3.2" @@ -2222,6 +2318,16 @@ dependencies = [ "objc2-user-notifications", ] +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" +dependencies = [ + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-user-notifications" version = "0.3.2" diff --git a/Cargo.toml b/Cargo.toml index eccd11a..d616af7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,12 +36,20 @@ 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_System_SystemInformation", "Win32_UI_Shell", "Win32_System_Registry", "Win32_Storage_Packaging_Appx"] } windows = { version = "0.62", features = ["ApplicationModel"] } +zune-jpeg = "0.5" +zune-core = "0.5" [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6" +dispatch2 = "0.3" +jpeg-encoder = { version = "0.7.1", features = ["simd"] } objc2 = "0.6" -objc2-app-kit = { version = "0.3", features = ["NSBitmapImageRep", "NSButton", "NSControl", "NSFontDescriptor", "NSGraphics", "NSGraphicsContext", "NSImage", "NSImageRep", "NSResponder", "NSScreen", "NSStatusBarButton", "NSStatusItem", "NSView", "NSWorkspace", "block2", "objc2-core-foundation"] } +objc2-app-kit = { version = "0.3", features = ["NSBitmapImageRep", "NSButton", "NSControl", "NSFontDescriptor", "NSGraphics", "NSGraphicsContext", "NSImage", "NSImageRep", "NSResponder", "NSRunningApplication", "NSScreen", "NSStatusBarButton", "NSStatusItem", "NSView", "NSWorkspace", "block2", "objc2-core-foundation"] } +objc2-core-foundation = "0.3" +objc2-core-media = "0.3" +objc2-core-video = "0.3" objc2-foundation = { version = "0.3", features = ["NSString", "NSArray", "NSGeometry", "NSEnumerator", "NSURL", "NSDictionary", "NSData"] } +objc2-screen-capture-kit = "0.3" [profile.release] strip = true diff --git a/README.md b/README.md index 25c5186..5e87b43 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. | +| Magic windows (preview) | Show a Mac window on the PC from the menu bar, and use it there: clicks, scrolling and typing go back to the Mac. | | 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. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 380a628..199ae6c 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. | +| `Stream`, `Frame`, `Data`, `Pointer` | Magic windows, on a connection of their own opened with `Stream` instead of a hello. The Mac (`magicinput stream`, its own process) captures one window with ScreenCaptureKit and sends each new picture as a JPEG (`Frame`, then `Data` pieces); the PC shows it in a window of the service and sends back `Pointer` (points from the window's top left), `Button`, `Wheel` and `Key`, which the Mac plays into the window. Both sides ping when idle. | | `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/lib.rs b/src/lib.rs index 069c8c6..7e268d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,7 +12,11 @@ mod platform; mod proto; mod service; mod status; +#[cfg(target_os = "macos")] +mod stream; pub mod ui; +#[cfg(windows)] +mod viewer; use std::io::IsTerminal; @@ -64,6 +68,12 @@ enum Cmd { Uninstall, /// Show the business license, or activate a license key from your download page License { key: Option }, + /// Show this Mac's front window on the other computer, until its copy there is closed + Stream { + /// Show a window of this app instead (part of its name) + #[arg(long)] + app: Option, + }, } /// `settings` opens the settings window. Each program passes how: the window itself (Mac, and @@ -137,7 +147,30 @@ pub fn main_with(settings: fn(bool)) { Ok(m) => println!("{m}"), Err(e) => exit(&e), }, + Cmd::Stream { app } => { + init_log("magicinput-stream.log"); + #[cfg(target_os = "macos")] + if let Err(e) = stream::run(app) { + exit(&e); + } + #[cfg(not(target_os = "macos"))] + exit(&format!("Showing windows on the other computer works from a Mac for now{}", app.map(|a| format!(" ({a})")).unwrap_or_default())); + } + } +} + +/// Log to the terminal, or (started from the menu bar or Finder) to `file` next to the config. +fn init_log(file: &str) { + let mut logger = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")); + logger.format_target(false); + if !std::io::stderr().is_terminal() { + if let Ok(f) = std::fs::File::create(Config::path().with_file_name(file)) { + logger.target(env_logger::Target::Pipe(Box::new(f))); + } + } else { + logger.format_timestamp(None); } + logger.init(); } /// Run the background service (what `magicinput run` does). @@ -152,18 +185,7 @@ pub fn packaged() -> bool { } fn run(mut cfg: Config) { - let mut logger = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")); - logger.format_target(false); - // Started from Finder/Explorer: no terminal to print to, so log next to the config. - if !std::io::stderr().is_terminal() { - let path = Config::path().with_file_name("magicinput.log"); - if let Ok(f) = std::fs::File::create(&path) { - logger.target(env_logger::Target::Pipe(Box::new(f))); - } - } else { - logger.format_timestamp(None); - } - logger.init(); + init_log("magicinput.log"); if cfg.code.is_empty() { cfg.code = config::new_code(); diff --git a/src/net.rs b/src/net.rs index 2bc9386..cef40ed 100644 --- a/src/net.rs +++ b/src/net.rs @@ -20,7 +20,7 @@ use crate::config::Config; use crate::core::{Core, Peer}; use crate::proto::{Msg, Os, PROTOCOL_VERSION}; -type Res = Result>; +pub type Res = Result>; const NOISE: &str = "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s"; const SERVICE: &str = "_magicinput._tcp.local."; @@ -28,10 +28,8 @@ 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; +pub const CHUNK: usize = 60_000; struct Active { generation: u64, @@ -260,6 +258,12 @@ impl Net { if let Msg::Offer { name, size, force, idle_ms } = first { return receive_offer(&mut stream, &mut noise, &name, size, force, idle_ms); } + if let Msg::Stream { title, width, height } = first { + #[cfg(windows)] + return crate::viewer::show(stream, noise, title, width, height); + #[cfg(not(windows))] + return Err(format!("{title} ({width}x{height}): only a PC can show windows from the other computer").into()); + } let Msg::Hello { id, name, os, version, peer_side, screens, layout, layout_time, .. } = first else { return Err("expected hello".into()); }; @@ -326,18 +330,10 @@ impl Net { 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)?; + let psk = *self.psk.lock().unwrap(); + let (mut stream, mut noise) = dial(addr, &psk)?; 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()) } @@ -485,6 +481,37 @@ fn handshake(stream: &mut TcpStream, psk: &[u8; 32], initiator: bool) -> Res Res<(TcpStream, TransportState)> { + let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2))?; + stream.set_nodelay(true)?; + stream.set_read_timeout(Some(TIMEOUT))?; + stream.set_write_timeout(Some(TIMEOUT))?; + 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()); + } + Ok((stream, noise)) +} + +/// For connections that read on one thread and write on another: wait for a message without +/// holding the encryption state, then decrypt it. +pub fn read_shared(stream: &mut TcpStream, noise: &Mutex) -> Res { + let frame = read_frame(stream)?; + let mut buf = vec![0u8; frame.len()]; + let n = noise.lock().unwrap().read_message(&frame, &mut buf)?; + Ok(postcard::from_bytes(&buf[..n])?) +} + +/// Encrypt and send, holding the encryption state so messages go out in order. +pub fn write_shared(stream: &mut TcpStream, noise: &Mutex, msg: &Msg) -> Res<()> { + write_msg(stream, &mut noise.lock().unwrap(), msg) +} + /// The other computer offers a file: take it into Downloads if its user is working here (or /// this computer was used more recently), and show it. fn receive_offer(stream: &mut TcpStream, noise: &mut TransportState, name: &str, size: u64, force: bool, idle_ms: u64) -> Res<()> { diff --git a/src/proto.rs b/src/proto.rs index 774c13b..1fe9d26 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -114,4 +114,12 @@ pub enum Msg { Data(Vec), /// Receiver -> sender: the whole file is saved, so the sender can remove its copy. Received, + /// Instead of a hello, on a connection of its own: the sender (a Mac) shows one of its + /// windows on the receiver ("magic windows"). `Frame`s then come one way, and `Pointer`, + /// `Button`, `Wheel` and `Key` made in the copy go back; both sides send `Ping` when idle. + Stream { title: String, width: u32, height: u32 }, + /// A JPEG of the window (`width` x `height` points), `len` bytes in the `Data` that follow. + Frame { width: u32, height: u32, len: u32 }, + /// Where the pointer is in the streamed window, in points from its top left corner. + Pointer { x: f64, y: f64 }, } diff --git a/src/stream.rs b/src/stream.rs new file mode 100644 index 0000000..02d7d7c --- /dev/null +++ b/src/stream.rs @@ -0,0 +1,405 @@ +//! Magic windows (Mac side, `magicinput stream`): show one of this Mac's windows on the other +//! computer. ScreenCaptureKit captures the window, every new frame goes over as a JPEG, and the +//! pointer, clicks, scrolling and keys made in the copy come back and are played into the window +//! here. Runs as its own process, so the background service stays lean; it ends when the copy +//! is closed or the window goes away. + +use std::collections::HashSet; +use std::net::{SocketAddr, TcpStream}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use block2::RcBlock; +use dispatch2::DispatchQueue; +use log::{info, warn}; +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2::{AllocAnyThread, DefinedClass, define_class, msg_send}; +use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication, NSWorkspace}; +use objc2_core_foundation::CGRect; +use objc2_core_media::{CMSampleBuffer, CMTime}; +use objc2_core_video::{ + CVPixelBufferGetBaseAddress, CVPixelBufferGetBytesPerRow, CVPixelBufferGetHeight, CVPixelBufferGetWidth, + CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags, CVPixelBufferUnlockBaseAddress, kCVPixelFormatType_32BGRA, +}; +use objc2_foundation::{NSError, NSObject, NSObjectProtocol}; +use objc2_screen_capture_kit::{ + SCContentFilter, SCShareableContent, SCStream, SCStreamConfiguration, SCStreamDelegate, SCStreamOutput, + SCStreamOutputType, SCWindow, +}; +use snow::TransportState; + +use crate::config::Config; +use crate::keymap; +use crate::net::{self, CHUNK, Res}; +use crate::platform; +use crate::proto::{Button, Msg}; + +/// JPEG quality: text stays readable, a typical window is 50-150 KB. +const QUALITY: u8 = 70; +const FPS: i32 = 30; + +/// Lets ScreenCaptureKit objects cross threads (they're immutable or thread-safe). +struct Shared(T); +unsafe impl Send for Shared {} +unsafe impl Sync for Shared {} + +/// The newest frame waiting to be sent (older ones are skipped, so a slow network never lags). +struct Latest { + frame: Mutex)>>, + ready: Condvar, + ended: AtomicBool, +} + +struct Sink { + latest: Arc, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and FrameSink doesn't implement Drop. + #[unsafe(super(NSObject))] + #[name = "MagicInputFrameSink"] + #[ivars = Sink] + struct FrameSink; + + unsafe impl NSObjectProtocol for FrameSink {} + + unsafe impl SCStreamOutput for FrameSink { + #[unsafe(method(stream:didOutputSampleBuffer:ofType:))] + fn stream_did_output(&self, _stream: &SCStream, buffer: &CMSampleBuffer, kind: SCStreamOutputType) { + if kind != SCStreamOutputType::Screen { + return; + } + if let Some(frame) = encode(buffer) { + let latest = &self.ivars().latest; + *latest.frame.lock().unwrap() = Some(frame); + latest.ready.notify_one(); + } + } + } + + unsafe impl SCStreamDelegate for FrameSink { + #[unsafe(method(stream:didStopWithError:))] + fn stream_did_stop(&self, _stream: &SCStream, error: &NSError) { + warn!("Capture stopped: {}", error.localizedDescription()); + let latest = &self.ivars().latest; + latest.ended.store(true, Ordering::SeqCst); + latest.ready.notify_one(); + } + } +); + +impl FrameSink { + fn new(latest: Arc) -> Retained { + let this = Self::alloc().set_ivars(Sink { latest }); + unsafe { msg_send![super(this), init] } + } +} + +/// A captured frame as a JPEG: (width, height, bytes). Idle frames carry no picture. +fn encode(buffer: &CMSampleBuffer) -> Option<(u32, u32, Vec)> { + let image = unsafe { buffer.image_buffer() }?; + unsafe { CVPixelBufferLockBaseAddress(&image, CVPixelBufferLockFlags::ReadOnly) }; + let (w, h) = (CVPixelBufferGetWidth(&image), CVPixelBufferGetHeight(&image)); + let stride = CVPixelBufferGetBytesPerRow(&image); + let base = CVPixelBufferGetBaseAddress(&image) as *const u8; + let mut px = Vec::with_capacity(w * h * 4); + if !base.is_null() { + for row in 0..h { + px.extend_from_slice(unsafe { std::slice::from_raw_parts(base.add(row * stride), w * 4) }); + } + } + unsafe { CVPixelBufferUnlockBaseAddress(&image, CVPixelBufferLockFlags::ReadOnly) }; + if px.is_empty() { + return None; + } + let mut jpeg = Vec::new(); + jpeg_encoder::Encoder::new(&mut jpeg, QUALITY) + .encode(&px, w as u16, h as u16, jpeg_encoder::ColorType::Bgra) + .ok()?; + Some((w as u32, h as u32, jpeg)) +} + +/// The windows that can be captured right now, front to back. +fn shareable() -> Result, String> { + let (tx, rx) = mpsc::channel(); + let block = RcBlock::new(move |content: *mut SCShareableContent, error: *mut NSError| { + let r = match unsafe { Retained::retain(content) } { + Some(c) => Ok(Shared(c)), + None => Err(unsafe { error.as_ref() }.map_or("no windows".into(), |e| e.localizedDescription().to_string())), + }; + let _ = tx.send(r); + }); + unsafe { SCShareableContent::getShareableContentExcludingDesktopWindows_onScreenWindowsOnly_completionHandler(true, true, &block) }; + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(Ok(c)) => Ok(c.0), + Ok(Err(e)) => Err(format!("{e} (allow MagicInput under Screen & System Audio Recording in System Settings → Privacy & Security)")), + Err(_) => Err("macOS didn't list the windows in time".into()), + } +} + +/// The window to show: the front window of the app in front (or of the app named `app`). +fn pick(content: &SCShareableContent, app: Option<&str>) -> Option> { + let front = NSWorkspace::sharedWorkspace().frontmostApplication().map(|a| a.processIdentifier()); + let me = std::process::id() as i32; + let windows = unsafe { content.windows() }; + windows.iter().find(|w| unsafe { + let Some(owner) = w.owningApplication() else { return false }; + let pid = owner.processID(); + let wanted = match app { + Some(name) => owner.applicationName().to_string().to_lowercase().contains(&name.to_lowercase()), + None => Some(pid) == front, + }; + wanted && pid != me && w.windowLayer() == 0 && w.frame().size.width >= 50.0 && w.frame().size.height >= 50.0 + }) +} + +fn find(content: &SCShareableContent, id: u32) -> Option> { + unsafe { content.windows() }.iter().find(|w| unsafe { w.windowID() } == id) +} + +fn configuration(frame: CGRect) -> Retained { + unsafe { + let c = SCStreamConfiguration::new(); + // One pixel per point: sharp enough on the PC and a quarter of a Retina capture. + c.setWidth(frame.size.width.round() as usize); + c.setHeight(frame.size.height.round() as usize); + c.setPixelFormat(kCVPixelFormatType_32BGRA); + c.setMinimumFrameInterval(CMTime::new(1, FPS)); + c.setShowsCursor(false); + c.setQueueDepth(3); + c.setIgnoreShadowsSingleWindow(true); + c + } +} + +/// The other computer's address: the fixed one from the config, or found on the network. +fn peer_addr(cfg: &Config) -> Result { + let host = match &cfg.peer_addr { + Some(a) => a.split(':').next().unwrap_or(a).to_string(), + None => net::discover(cfg, Duration::from_millis(1500)) + .into_iter() + .find(|n| n.same_code) + .and_then(|n| n.address) + .ok_or("the other computer isn't on the network")?, + }; + format!("{host}:{}", cfg.port).parse().map_err(|e| format!("{host}: {e}")) +} + +pub fn run(app: Option) -> Result<(), String> { + let cfg = Config::load(); + platform::init()?; + let content = shareable()?; + let window = pick(&content, app.as_deref()).ok_or("no window to show (bring one to the front)")?; + let (id, frame, pid, title) = unsafe { + let owner = window.owningApplication(); + let name = owner.as_ref().map(|o| o.applicationName().to_string()).unwrap_or_default(); + let title = window.title().map(|t| t.to_string()).filter(|t| !t.is_empty()).unwrap_or(name); + (window.windowID(), window.frame(), owner.map_or(0, |o| o.processID()), title) + }; + let addr = peer_addr(&cfg)?; + let (stream, noise) = net::dial(addr, &cfg.psk()).map_err(|e| format!("connecting to {addr}: {e}"))?; + let noise = Arc::new(Mutex::new(noise)); + let (width, height) = (frame.size.width.round() as u32, frame.size.height.round() as u32); + let mut out = stream.try_clone().map_err(|e| e.to_string())?; + net::write_shared(&mut out, &noise, &Msg::Stream { title: title.clone(), width, height }).map_err(|e| e.to_string())?; + info!("Showing \"{title}\" ({width}x{height}) on {addr}"); + + // Capture. + let latest = Arc::new(Latest { frame: Mutex::new(None), ready: Condvar::new(), ended: AtomicBool::new(false) }); + let sink = FrameSink::new(latest.clone()); + let capture = unsafe { + let filter = SCContentFilter::initWithDesktopIndependentWindow(SCContentFilter::alloc(), &window); + let s = SCStream::initWithFilter_configuration_delegate( + SCStream::alloc(), + &filter, + &configuration(frame), + Some(ProtocolObject::from_ref(&*sink)), + ); + let queue = DispatchQueue::new("magicinput.stream", None); + s.addStreamOutput_type_sampleHandlerQueue_error(ProtocolObject::from_ref(&*sink), SCStreamOutputType::Screen, Some(&queue)) + .map_err(|e| e.localizedDescription().to_string())?; + let (tx, rx) = mpsc::channel(); + let done = RcBlock::new(move |error: *mut NSError| { + let _ = tx.send(error.as_ref().map(|e| e.localizedDescription().to_string())); + }); + s.startCaptureWithCompletionHandler(Some(&done)); + if let Ok(Some(e)) = rx.recv_timeout(Duration::from_secs(5)) { + return Err(format!("couldn't capture the window: {e}")); + } + Shared(s) + }; + let capture = Arc::new(capture); + + // Where the window is now (it can move), and whether it's still there. + let place = Arc::new(Mutex::new(frame)); + { + let (place, latest, capture, stream) = (place.clone(), latest.clone(), capture.clone(), stream.try_clone().map_err(|e| e.to_string())?); + std::thread::spawn(move || { + while !latest.ended.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_secs(1)); + let Ok(content) = shareable() else { continue }; + let Some(w) = find(&content, id) else { + info!("The window closed"); + let _ = stream.shutdown(std::net::Shutdown::Both); + return; + }; + let now = unsafe { w.frame() }; + let mut p = place.lock().unwrap(); + if now.size.width != p.size.width || now.size.height != p.size.height { + unsafe { capture.0.updateConfiguration_completionHandler(&configuration(now), None) }; + } + *p = now; + } + }); + } + + // Frames out (a ping when there's nothing new, so both sides notice a dead link). + { + let (latest, noise) = (latest.clone(), noise.clone()); + std::thread::spawn(move || { + loop { + let next = { + let guard = latest.frame.lock().unwrap(); + let (mut guard, _) = latest.ready.wait_timeout(guard, Duration::from_secs(1)).unwrap(); + guard.take() + }; + if latest.ended.load(Ordering::SeqCst) { + let _ = out.shutdown(std::net::Shutdown::Both); + return; + } + let r = match next { + Some((width, height, jpeg)) => send_frame(&mut out, &noise, width, height, &jpeg), + None => net::write_shared(&mut out, &noise, &Msg::Ping), + }; + if r.is_err() { + let _ = out.shutdown(std::net::Shutdown::Both); + return; + } + } + }); + } + + // Input in. + let r = play_input(stream, &noise, &place, pid, cfg.swap_ctrl_cmd); + latest.ended.store(true, Ordering::SeqCst); + latest.ready.notify_one(); + unsafe { capture.0.stopCaptureWithCompletionHandler(None) }; + info!("Stopped showing \"{title}\" ({})", r.err().map_or("closed".into(), |e| e.to_string())); + Ok(()) +} + +fn send_frame(out: &mut TcpStream, noise: &Mutex, width: u32, height: u32, jpeg: &[u8]) -> Res<()> { + net::write_shared(out, noise, &Msg::Frame { width, height, len: jpeg.len() as u32 })?; + for piece in jpeg.chunks(CHUNK) { + net::write_shared(out, noise, &Msg::Data(piece.to_vec()))?; + } + Ok(()) +} + +/// Play what's done in the copy into the window here, until the connection ends. Anything +/// still held is let go at the end. +fn play_input(mut stream: TcpStream, noise: &Mutex, place: &Mutex, pid: i32, swap: bool) -> Res<()> { + let mut at = (0.0, 0.0); + let mut keys: HashSet = HashSet::new(); + let mut buttons: HashSet