Skip to content

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.

13.5 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Controller sharing (Camera & Controller › Controller), one-to-one and Multi-device: a controller plugged
// into one computer plays on others, as a real Xbox 360 or DualShock 4 controller there, through the driver
// Real gamepad uses (windows/gamepad.js: ViGEmBus; linux/gamepad.js: uinput). A Mac has no such driver: it
// only sends.
//   Sending: pick which controller (the window lists the ones it sees) and which computers it plays on; in
//   Multi-device several at once. Each gets pad.offer {name} (what it is, so it can be picked there), then the
//   states. The controller is read in this computer's TwinDesk window (the Gamepad API, shared/ui-pads.js)
//   while it's shared; nothing polls otherwise.
//   Receiving: the page lists the controllers offered to this computer; the one picked (settings.pads.from)
//   plays here, only that one. Its states come on the session and, when it is up, on the input lane too
//   (UDP, shared/inputlane.js PAD): numbered, the newest copy kept, so a lost packet never holds a stick back.
//   pad.offer {name}                         → a computer it's shared with (again every 20 s while shared)
//   pad.state {n, b, lx, ly, rx, ry, lt, rt} → the same (buttons as remote.pad: A B X Y LB RB Back Start L3 R3
//                                              Up Down Left Right, bits 0..13; sticks -1..1 with y down; triggers 0..1)
//   pad.off   {}                             → no longer shared with it: it unplugs and forgets the offer
// settings.pads = { on: bool (Controller's switch: off, nothing is sent or received), share: bool (Share my controller),
//                   pad: the chosen controller ('' the first one), to: [device ids] (the computers picked for it),
//                   receive: bool, from: device id whose controller plays here ('' the first one that plays, as before), kind: 'xbox' | 'ds4' }
//
//   const p = new PadShare({ send(id, msg), on(type, fn(msg, from)), connected(id), devices() → [{id, name, os,
//                            connected}], lane?(id) → InputLane, getSettings, save, loadPad?, onChange })
//   PadShare.link(link) → {send, on, connected}: a one-to-one app's partner link (link.current.deviceId)
//   p.fromWindow(state); p.set({on?, pad?, padName?, to?, receive?, from?, kind?, install?}); p.view(); p.stop()
'use strict';

const { padBytes } = require('./phone-remote.js');

const T = { STATE: 'pad.state', OFF: 'pad.off', OFFER: 'pad.offer' };
const IDLE_MS = 30000; // no state this long from the one playing here: unplugged
const MIN_GAP_MS = 8; // at most 125 states a second
const OFFER_MS = 20000; // the offer again, while shared
const OFFER_TTL = 65000; // an offer not heard again this long is gone (the sender quit)
const MAX_TO = 10;
const id = (v) => (typeof v === 'string' ? v.slice(0, 80) : '');
const name = (v) => (typeof v === 'string' ? v.replace(/[\p{Cc}\p{Cf}]/gu, '').trim().slice(0, 80) : '');

function clean(v) {
  const o = v && typeof v === 'object' ? v : {};
  const to = Array.isArray(o.to) ? o.to : typeof o.to === 'string' && o.to ? [o.to] : []; // one device before
  return {
    on: typeof o.on === 'boolean' ? o.on : !!(v && typeof v === 'object'), // settings from before the switch: on, as it was; none yet: off (light by default)
    share: typeof o.share === 'boolean' ? o.share : to.length > 0, // settings from before its switch: shared where it went
    pad: typeof o.pad === 'string' ? o.pad.slice(0, 200) : '',
    to: [...new Set(to.map(id).filter(Boolean))].slice(0, MAX_TO),
    receive: o.receive === true,
    from: id(o.from),
    kind: o.kind === 'ds4' ? 'ds4' : 'xbox',
  };
}

class PadShare {
  constructor(o) {
    Object.assign(this, { onChange: () => {}, loadPad: null, save: () => {}, lane: () => null, devices: () => [] }, o);
    this.n = 0; // our states' number
    this.lastN = new Map(); // sender → the newest number applied
    this.heard = new WeakSet(); // lanes whose PAD we listen to
    this.offers = new Map(); // sender → {name, at}: controllers shared with this computer
    this.driver = null;
    this.driverState = ''; // '' not looked at, 'missing', 'ready', or the reason it can't be
    this.proc = null;
    this.playing = ''; // whose controller plays here now
    this.busy = '';
    this.message = '';
    this.padName = ''; // the chosen controller's name, from the window
    this.sentAt = new Map(); // device → when we last sent it a state
    this.lastKey = '';
    this.idle = null;
    this.timer = null;
    this.on(T.STATE, (m, from) => this._heard(m, from));
    this.on(T.OFFER, (m, from) => this._offer(m, from));
    this.on(T.OFF, (m, from) => {
      this.offers.delete(from);
      if (from === this.playing) this._unplug();
      this.onChange();
    });
    this._tick();
  }

  // A one-to-one app's partner (shared/peer.js: link.current, link.send, link.on(type, fn(msg))).
  static link(link) {
    const cur = () => { const c = link.current; return c && c.deviceId ? c : null; };
    return {
      send: (to, m) => { const c = cur(); if (c && c.deviceId === to) link.send(m); },
      on: (t, fn) => link.on(t, (m) => { const c = cur(); if (c) fn(m, c.deviceId); }),
      connected: (to) => { const c = cur(); return !!c && c.deviceId === to; },
      devices: () => { const c = cur(); return c && !/^(android|ios)$/.test(c.os || '') ? [{ id: c.deviceId, name: c.name || c.deviceName || '', os: c.os || '', connected: true }] : []; },
    };
  }

  get cfg() {
    const s = this.getSettings();
    const c = clean(s.pads);
    if (JSON.stringify(c) !== JSON.stringify(s.pads)) s.pads = c;
    return s.pads;
  }

  get sharing() { const c = this.cfg; return c.on && c.share && c.to.length > 0; }

  set(p) {
    const c = this.cfg;
    const before = this.sharing ? c.to.slice() : [];
    if ('on' in p) c.on = p.on === true;
    if ('share' in p) c.share = p.share === true;
    if ('pad' in p) c.pad = clean({ pad: p.pad }).pad;
    if ('padName' in p) this.padName = name(p.padName);
    if ('to' in p) c.to = clean({ to: p.to }).to;
    if ('receive' in p) c.receive = p.receive === true;
    if ('from' in p) c.from = id(p.from);
    if ('kind' in p) c.kind = p.kind === 'ds4' ? 'ds4' : 'xbox';
    this.save();
    const now = this.sharing ? c.to : [];
    for (const d of before) if (!now.includes(d)) this.send(d, { t: T.OFF }); // no longer shared with it
    if ('to' in p || 'on' in p || 'share' in p || 'padName' in p || 'pad' in p) this._offerAll(); // what it is, for the ones it goes to
    if (!c.on || !c.receive || (this.playing && this.playing !== c.from)) this._unplug();
    if ('kind' in p && this.proc) this._unplug(); // plugged in again as the other one on the next state
    if ((c.receive && c.on) || p.install) this._check(p.install === true);
    this._tick();
    this.onChange();
  }

  // ---- sending ----
  _offerAll() {
    if (!this.sharing) return;
    for (const d of this.cfg.to) if (this.connected(d)) this.send(d, { t: T.OFFER, name: this.padName || 'Controller' });
  }

  // While shared: the offer again now and then (a computer that came later, or came back, sees it); offers
  // heard here and not again are dropped.
  _tick() {
    const want = this.sharing || this.offers.size > 0;
    if (want && !this.timer) {
      this.timer = setInterval(() => {
        this._offerAll();
        const old = Date.now() - OFFER_TTL;
        let gone = false;
        for (const [from, o] of this.offers) if (o.at < old) { this.offers.delete(from); gone = true; }
        if (gone) this.onChange();
        if (!this.sharing && !this.offers.size) { clearInterval(this.timer); this.timer = null; }
      }, OFFER_MS);
      if (this.timer.unref) this.timer.unref();
    } else if (!want && this.timer) { clearInterval(this.timer); this.timer = null; }
  }

  // A device that connects: our offer at once, if it's one we share with.
  hello(dev) { if (this.sharing && this.cfg.to.includes(dev) && this.connected(dev)) this.send(dev, { t: T.OFFER, name: this.padName || 'Controller' }); }

  fromWindow(st) {
    if (!this.sharing || !st || typeof st !== 'object') return;
    const to = this.cfg.to.filter((d) => this.connected(d));
    if (!to.length) return;
    const msg = { t: T.STATE, b: (Number(st.b) >>> 0) & 0x3fff, lx: +st.lx || 0, ly: +st.ly || 0, rx: +st.rx || 0, ry: +st.ry || 0, lt: +st.lt || 0, rt: +st.rt || 0 };
    const key = JSON.stringify(msg);
    const now = Date.now();
    const last = this.sentAt.get('') || 0;
    if (key === this.lastKey && now - last < 1000) return; // unchanged: once a second keeps it plugged in
    if (now - last < MIN_GAP_MS && key !== this.lastKey && msg.b === JSON.parse(this.lastKey || '{"b":-1}').b) return; // sticks only: thinned
    this.lastKey = key;
    this.sentAt.set('', now);
    msg.n = ++this.n;
    const bytes = padBytes(msg);
    for (const d of to) {
      const lane = this.lane(d);
      if (lane && lane.sendPad) lane.sendPad(msg.n, bytes); // the fast copy
      this.send(d, msg); // the sure one
    }
  }

  // ---- receiving ----
  _offer(m, from) {
    if (!from) return;
    const had = this.offers.get(from);
    const n = name(m && m.name) || 'Controller';
    this.offers.set(from, { name: n, at: Date.now() });
    this._tick();
    if (!had || had.name !== n) this.onChange();
  }

  _listen(from) {
    const lane = this.lane(from);
    if (!lane || !lane.on || this.heard.has(lane)) return;
    this.heard.add(lane);
    lane.on('pad', (n, bytes) => this._apply(from, n, bytes));
  }

  // The newest copy only: one that comes after a newer one (the other path was faster) is dropped. A number far
  // below the newest is the sender starting again.
  _fresh(from, n) {
    if (!Number.isInteger(n)) return true; // an older sender: no number
    const last = this.lastN.get(from) || 0;
    if (n <= last && last - n < 10000) return false;
    this.lastN.set(from, n);
    return true;
  }

  async _heard(m, from) {
    if (!this.offers.has(from)) this._offer({}, from); // an older sender: no offer, its states say it
    else this.offers.get(from).at = Date.now();
    this._listen(from);
    return this._apply(from, m.n, padBytes(m));
  }

  // Only the one picked here plays; everything else is ignored.
  async _apply(from, n, bytes) {
    const c = this.cfg;
    if (!c.on || !c.receive || !this.loadPad || !from) return;
    if (c.from ? from !== c.from : (this.playing && this.playing !== from)) return; // the one picked; none picked: the first keeps it, as before
    this.playing = from;
    clearTimeout(this.idle);
    this.idle = setTimeout(() => this._unplug(), IDLE_MS);
    if (!this._fresh(from, n)) return;
    if (!this.proc) await this._plug();
    if (this.proc) this.proc.stdin.write(bytes);
  }

  // Whether the driver is there (the page's Install button); install: put it in now (one prompt on Windows).
  async _check(install) {
    if (!this.loadPad || this.busy) return;
    try {
      if (!this.driver) this.driver = this.loadPad();
      if (!install && this.driverState === 'ready') return;
      const c = await this.driver.check();
      if (!c.supported) { this.driverState = c.message || 'Not on this computer'; this.onChange(); return; }
      if (c.installed) { this.driverState = 'ready'; this.onChange(); return; }
      this.driverState = 'missing';
      if (!install) { this.onChange(); return; }
      this.busy = 'Installing…';
      this.message = '';
      this.onChange();
      await this.driver.install();
      this.driverState = 'ready';
    } catch (e) {
      this.message = e.message || String(e);
    }
    this.busy = '';
    this.onChange();
  }

  async _plug() {
    if (this.busy || this.proc) return;
    try {
      if (!this.driver) this.driver = this.loadPad();
      this.busy = 'Checking…';
      this.onChange();
      const c = await this.driver.check();
      if (!c.supported) throw new Error(c.message || 'Not on this computer');
      if (!c.installed) { this.busy = 'Installing…'; this.onChange(); await this.driver.install(); }
      this.driverState = 'ready';
      this.busy = '';
      this.message = '';
      const cfg = this.cfg;
      if (!cfg.on || !cfg.receive) return;
      const p = this.driver.feed(() => { if (this.proc === p) { this.proc = null; this.onChange(); } }, cfg.kind);
      this.proc = p;
    } catch (e) {
      this.busy = '';
      this.message = e.message || String(e);
      this.cfg.receive = false; // not installed: off again, and why
      this.save();
    }
    this.onChange();
  }

  _unplug() {
    clearTimeout(this.idle);
    const p = this.proc;
    this.proc = null;
    this.playing = '';
    this.lastN.clear();
    if (p) { try { p.stdin.write(padBytes({})); p.stdin.end(); } catch (_) { /* gone */ } }
    this.onChange();
  }

  stop() {
    if (this.sharing) for (const d of this.cfg.to) this.send(d, { t: T.OFF });
    this._unplug();
    if (this.timer) { clearInterval(this.timer); this.timer = null; }
  }

  view() {
    const c = this.cfg;
    const devs = this.devices().filter((d) => d && d.id && !/^(android|ios)$/.test(d.os || ''));
    const nameOf = (d) => (devs.find((x) => x.id === d) || {}).name || '';
    return {
      on: c.on, share: c.share, pad: c.pad, to: c.to, receive: c.receive, from: c.from, kind: c.kind,
      devices: devs.map((d) => ({ id: d.id, name: d.name || '', os: d.os || '', connected: !!d.connected })),
      offers: [...this.offers].map(([from, o]) => ({ from, device: nameOf(from), name: o.name })),
      canReceive: !!this.loadPad, driver: this.driverState, busy: this.busy, message: this.message,
      playing: this.proc ? this.playing : '',
    };
  }
}

module.exports = { PadShare, T, clean };