All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.
JavaScript androidapple-ecosystemconnectelectronfile-sharingintel-unison-alternativeiosios-windowskde-connect-alternativekvmlinuxmacbookmacosmouse-sharingphone-link-alternativeproductivityscreen-sharingsidecar-alternativesynergy-alternativewindows
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// An iPhone's or iPad's screen over its USB cable, no app needed on it and no Start to tap. An
// IosUsbScreen does for a phone window (phoneview.js) what a scrcpy Session or a NativeScreen does:
// 'size', 'video', 'closed', start(), stop(), and the input calls. Two ways:
// - iOS 27 or later (Developer Mode on): ios-control's helper (twindesk-ios-control, CoreDevice as
// Xcode's device window uses it): the device's own H.265 picture at up to 60 fps, and input. The
// mouse is a finger, the wheel a short drag, the keys a HID keyboard (the device applies its own
// layout), the window's buttons its home, power and volume buttons.
// - Before that, or when the helper can't: mac-helper's macshare-iosusb (macOS offers a cabled,
// trusted iOS device as a capture device, as QuickTime uses it), the picture only.
// Both speak the same: JSON events on stderr, scrcpy's packets on stdout.
'use strict';
const path = require('path');
const { spawn, execFile } = require('child_process');
const { EventEmitter } = require('events');
// macOS's own capture (the Mac only); ios-control's helper (each platform's build, ios-control/build.sh).
const BIN = process.platform === 'darwin' ? path.join(__dirname, '..', 'mac-helper', '.build', 'release', 'macshare-iosusb') : '';
const CONTROL = path.join(__dirname, '..', 'ios-control', 'bin', process.arch === 'arm64' ? 'arm64' : 'x64', process.platform === 'win32' ? 'twindesk-ios-control.exe' : 'twindesk-ios-control');
const { USAGE } = require('./uhidkbd.js');
// scrcpy's (each platform's scrcpy.js) and Android's keycodes (android-keys.js), as the phone windows send them.
const ACTION = { DOWN: 0, UP: 1, MOVE: 2 };
const TYPE = { RESET_VIDEO: 17 };
const ANDROID = { HOME: 3, POWER: 26, VOLUME_UP: 24, VOLUME_DOWN: 25, VOLUME_MUTE: 164, APP_SWITCH: 187 };
// Modifier keys' usages (the HID keyboard page's 0xE0…0xE7).
const MODS = { ControlLeft: 0xe0, ShiftLeft: 0xe1, AltLeft: 0xe2, MetaLeft: 0xe3, ControlRight: 0xe4, ShiftRight: 0xe5, AltRight: 0xe6, MetaRight: 0xe7 };
// Android's keycodes (the window's buttons, phoneview.js's nav) -> the device's buttons.
const BUTTONS = { [ANDROID.HOME]: 'home', [ANDROID.POWER]: 'lock', [ANDROID.VOLUME_UP]: 'volume_up', [ANDROID.VOLUME_DOWN]: 'volume_down', [ANDROID.VOLUME_MUTE]: 'mute' };
// US-layout characters for text(): [usage, shift].
const CHARS = (() => {
const m = { '\n': [0x28, 0], '\t': [0x2b, 0], ' ': [0x2c, 0] };
for (let i = 0; i < 26; i++) { m[String.fromCharCode(97 + i)] = [0x04 + i, 0]; m[String.fromCharCode(65 + i)] = [0x04 + i, 1]; }
'1234567890'.split('').forEach((c, i) => { m[c] = [0x1e + i, 0]; });
'!@#$%^&*()'.split('').forEach((c, i) => { m[c] = [0x1e + i, 1]; });
const pairs = ['-_', '=+', '[{', ']}', '\\|', null, ';:', '\'"', '`~', ',<', '.>', '/?'];
pairs.forEach((p, i) => { if (p) { m[p[0]] = [0x2d + i, 0]; m[p[1]] = [0x2d + i, 1]; } });
return m;
})();
const MAX_FRAME = 8 * 1024 * 1024;
function listOf(bin, timeout) {
return new Promise((resolve) => {
execFile(bin, ['list'], { timeout }, (err, out) => {
if (err) return resolve([]);
try {
const a = JSON.parse(String(out).trim() || '[]');
resolve(Array.isArray(a) ? a.filter((d) => d && typeof d.id === 'string') : []);
} catch {
resolve([]);
}
});
});
}
// The iOS devices on a cable now: [{id, name, model, control}]. usbmuxd's (the helper's: its UDID and
// iOS version, at once) first; macOS's capture devices otherwise (about 2 s: they show up a moment
// after asking, and asking switches the device's USB over to capture for a moment).
const entry = (d) => ({ id: d.id, name: String(d.name || 'iPhone').slice(0, 80), model: String(d.model || '').slice(0, 40) });
const muxEntry = (d) => ({ ...entry(d), control: parseInt(String(d.version || ''), 10) >= 27 });
async function list() {
const mux = await listOf(CONTROL, 15000);
if (mux.length || !BIN) return mux.map(muxEntry);
return (await listOf(BIN, 8000)).map(entry);
}
// The iOS devices on the cable as they come and go (the helper's watch, on usbmuxd's events; no
// polling): onChange(list), list()'s entries. Without the helper in this build: never called.
// Returns stop().
function watch(onChange) {
let p = null;
let stopped = false;
let timer = null;
const run = () => {
if (stopped) return;
const c = spawn(CONTROL, ['watch'], { stdio: ['pipe', 'pipe', 'ignore'] });
p = c;
let missing = false;
let buf = '';
c.stdout.on('data', (d) => {
buf += d;
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i);
buf = buf.slice(i + 1);
try {
const a = JSON.parse(line);
if (Array.isArray(a)) onChange(a.filter((d) => d && typeof d.id === 'string').map(muxEntry));
} catch {}
}
});
c.stdin.on('error', () => {});
c.on('error', () => { missing = true; });
c.on('exit', () => {
if (p === c) p = null;
if (!stopped && !missing) timer = setTimeout(run, 10000);
});
};
run();
return () => {
stopped = true;
clearTimeout(timer);
try { p && p.stdin.end(); } catch {}
};
}
class IosUsbScreen extends EventEmitter {
// opts: {id (a device's, or '' for the first), control (iOS 27 or later: the helper), ddi (Apple's developer
// disk image's directory, shared/ios-ddi.js: mounted by the helper when the device has none), maxSize, videoBitRate}
constructor(opts = {}) {
super();
this.opts = opts;
this.closed = false;
this.size = null;
this.proc = null;
this.controlled = false;
}
// The helper first when the device has the iOS for it; when it fails before the picture comes
// (Developer Mode off, …), macOS's capture, the picture without input.
async start() {
if (this.opts.control) {
try { return await this._start(true); } catch (e) {
if (this.closed) throw e;
console.log(`[iosusb] control: ${e.message}; the picture only`);
this.emit('control', { ok: false, error: e.message });
}
}
return this._start(false);
}
_start(control) {
return new Promise((resolve, reject) => {
// A UDID (usbmuxd's list: opts.control set) means nothing to macOS's capture: its first device then.
if (!control && !BIN) return reject(Object.assign(new Error('No iPhone or iPad on a cable. Plug it in, unlock it and tap Trust.'), { messageKey: 'No iPhone or iPad on a cable. Plug it in, unlock it and tap Trust.' }));
const ddi = this.opts.ddi || IosUsbScreen.ddiDir || '';
const p = control ? spawn(CONTROL, [this.opts.id || '', ...(ddi ? ['--ddi', ddi] : [])], { stdio: ['pipe', 'pipe', 'pipe'] })
: spawn(BIN, ['capture', typeof this.opts.control === 'boolean' ? '' : this.opts.id || '', String(this.opts.maxSize || 0), String(this.opts.videoBitRate || 12000000)], { stdio: ['pipe', 'pipe', 'pipe'] });
this.proc = p;
p.stdin.on('error', () => {});
let started = false;
let errLine = '';
let ebuf = '';
p.stderr.on('data', (c) => {
ebuf += c;
let i;
while ((i = ebuf.indexOf('\n')) >= 0) {
const line = ebuf.slice(0, i);
ebuf = ebuf.slice(i + 1);
let m = null;
try { m = JSON.parse(line); } catch { console.log(`[iosusb] ${line}`); continue; }
if (m.event === 'started') { started = true; this.controlled = control; resolve(); if (control) this.emit('control', { ok: true }); }
else if (m.event === 'error') errLine = String(m.message || '').slice(0, 200);
else if (m.event === 'ended') this._close(m.why === 'unplugged' ? 'The cable came out' : 'stopped');
}
});
this._read(p.stdout);
p.on('error', (e) => { if (!started) reject(new Error(e.message)); else this._close(e.message); });
p.on('exit', (code) => {
if (!started) return void reject(Object.assign(new Error(errLine || `the screen capture stopped (${code})`), { messageKey: errLine || undefined }));
if (this.proc === p) this._close(errLine || 'stopped');
});
});
}
// scrcpy's packets, as shared/nativescreen.js reads them.
_read(stream) {
let buf = Buffer.alloc(0);
let need = 12;
let head = null;
stream.on('data', (chunk) => {
buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;
while (buf.length >= need) {
if (!head) {
const h = buf.subarray(0, 12);
buf = buf.subarray(12);
if (h[0] & 0x80) {
const w = h.readUInt32BE(4);
const ht = h.readUInt32BE(8);
if (w > 0 && ht > 0 && w < 16384 && ht < 16384) {
this.size = { width: w, height: ht };
this.emit('size', this.size);
}
continue;
}
const size = h.readUInt32BE(8);
if (size > MAX_FRAME) return this.stop();
head = { ptsFlags: h.readBigUInt64BE(0), size };
need = size;
continue;
}
const data = Buffer.from(buf.subarray(0, head.size));
buf = buf.subarray(head.size);
const f = head.ptsFlags;
head = null;
need = 12;
const config = !!(f & (1n << 62n));
if (config) this.config = data; // the latest parameter sets: a viewer that comes later starts with them (shared/phone-relay.js)
this.emit('video', { config, key: !!(f & (1n << 61n)), pts: Number(f & ((1n << 61n) - 1n)), data });
}
});
}
_cmd(m) {
if (!this.controlled || this.closed || !this.proc) return;
try { this.proc.stdin.write(`${JSON.stringify(m)}\n`); } catch {}
}
_close(why) {
if (this.closed) return;
this.closed = true;
try { this.proc && this.proc.stdin.end(); } catch {} // the helper lifts a held finger and stops the device's stream itself
const p = this.proc;
setTimeout(() => { try { p && p.kill(); } catch {} }, this.controlled ? 6000 : 1000).unref();
clearTimeout(this.wheelTimer);
this.emit('closed', why);
}
stop() { this._close('stopped'); }
// Video coordinates -> 0…1 across the picture: the helper's picture and the touch screen are both
// the device held upright, however it's turned.
_point(x, y, w, h) {
return { x: Math.max(0, Math.min(1, x / (w || 1))), y: Math.max(0, Math.min(1, y / (h || 1))) };
}
// One finger: the mouse (the window's left button is scrcpy's generic finger, -2; -1 is the
// mouse's own pointer), or a touch from a touch screen here (≥ 0); hover means nothing on iOS.
touch(action, pointerId, x, y, w, h) {
if (pointerId < -2 || (this.finger != null && this.finger !== pointerId && action !== ACTION.DOWN)) return;
const s = action === ACTION.DOWN ? 'down' : action === ACTION.MOVE ? 'move' : action === ACTION.UP ? 'up' : '';
if (!s || (s === 'move' && this.finger == null)) return;
this.finger = s === 'up' ? null : pointerId;
this._cmd({ op: 'touch', s, ...this._point(x, y, w, h) });
}
mouse(action, x, y, w, h) { this.touch(action, -1, x, y, w, h); }
// The wheel: a short drag from the pointer, the way a finger scrolls (+vs = up: the content comes
// down, so the finger moves down). Notches that come while one runs make the next one longer.
scroll(x, y, w, h, hs, vs) {
if (this.finger != null) return;
this.wheel = this.wheel || { hs: 0, vs: 0 };
this.wheel.hs += hs;
this.wheel.vs += vs;
this.wheel.at = [x, y, w, h];
if (!this.wheelTimer) this._wheel();
}
_wheel() {
const q = this.wheel;
this.wheel = null;
this.wheelTimer = null;
if (!q || this.closed || (!q.hs && !q.vs)) return;
const [x, y, w, h] = q.at;
const p = this._point(x, y, w, h);
const step = 0.06; // of the screen per notch
const clamp = (v) => Math.max(0.02, Math.min(0.98, v));
const dx = Math.max(-0.4, Math.min(0.4, -q.hs * step));
const dy = Math.max(-0.4, Math.min(0.4, q.vs * step));
const to = { x: clamp(p.x + dx), y: clamp(p.y + dy) };
const n = 8;
this._cmd({ op: 'touch', s: 'down', ...p });
let i = 0;
const move = () => {
if (this.closed) return;
i++;
const at = { x: p.x + (to.x - p.x) * i / n, y: p.y + (to.y - p.y) * i / n };
if (i < n) { this._cmd({ op: 'touch', s: 'move', ...at }); this.wheelTimer = setTimeout(move, 12); return; }
this._cmd({ op: 'touch', s: 'up', ...to });
this.wheelTimer = setTimeout(() => this._wheel(), 30); // what came meanwhile
};
this.wheelTimer = setTimeout(move, 12);
}
// A key by its place (KeyboardEvent.code; phoneview.js sends it here, keyCode()): the device's
// layout decides what it types, as with a real keyboard on it.
keyCode(code, down) {
const u = MODS[code] || USAGE[code];
if (u) this._cmd({ op: 'key', u, s: down ? 'down' : 'up' });
return !!u;
}
key() {}
// The window's buttons (Android's keycodes, phoneview.js's nav). Recents: the app switcher, a
// double press of home.
tap(keycode) {
if (keycode === ANDROID.APP_SWITCH) {
this._cmd({ op: 'button', b: 'home', s: 'press' });
return void setTimeout(() => this._cmd({ op: 'button', b: 'home', s: 'press' }), 120);
}
const b = BUTTONS[keycode];
if (b) this._cmd({ op: 'button', b, s: 'press' });
}
backOrScreenOn() {}
// Text (Enter sends and the like): typed key by key, US layout; what it has no key for is left out.
text(str) {
for (const ch of String(str).slice(0, 300)) {
const k = CHARS[ch];
if (!k) continue;
if (k[1]) this._cmd({ op: 'key', u: 0xe1, s: 'down' });
this._cmd({ op: 'key', u: k[0], s: 'down' });
this._cmd({ op: 'key', u: k[0], s: 'up' });
if (k[1]) this._cmd({ op: 'key', u: 0xe1, s: 'up' });
}
}
// The window lost its place in the picture (RESET_VIDEO): a keyframe.
simple(type) { if (type === TYPE.RESET_VIDEO) this._cmd({ op: 'keyframe' }); }
setDisplayPower() {}
resizeDisplay() {}
startApp() {}
setClipboard() {}
}
// Apple's developer disk image's directory for every session that isn't given one (main.js, from
// shared/ios-ddi.js once it has it).
IosUsbScreen.ddiDir = '';
module.exports = { IosUsbScreen, list, watch, BIN, CONTROL };