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.

8.7 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// An Android phone's screen on any computer of the mesh, through the computer it's connected to
// (shared/phone-relay.js), the same on the Mac, Windows and Linux (each mesh/main.js calls it once):
//   - the Android phones connected here go to every computer of the mesh, and come from theirs:
//       phone.screens {phones: [{id, name}]}   the phones the sender serves now
//   - Show Phone Screen of one connected to another computer: through that computer;
//   - ours, for the computers that show one: wireless debugging (or the cable) held up while it's
//     watched (phone-bridge.js relayHold: whatever the modes here are), a scrcpy session of its own
//     on it (several may run on a phone), kept while it's watched, the window's input on it.
'use strict';

const { EventEmitter } = require('events');
const P = require('./protocol.js');
const { ScreenHost, RelayScreen, ACTION, PANELS } = require('./phone-relay.js');

const T = P.T;
const ID = /^[0-9A-Za-z_-]{8,128}$/;
const IDLE_MS = 15000; // our own session, unwatched this long: closed (a window opened again soon takes it)
const ADB_MS = 30000; // wireless debugging coming up for it: at most this long
const ADB_POLL_MS = 500;

// A phone's screen for the mesh as soon as adb is up for it: the events and input calls of scrcpy.js's
// Session (phone-relay.js's host takes it as it is, before there's a picture).
class PhoneScreen extends EventEmitter {
  // phone: {name, hold(on), ready() -> {adb, serial, opts} | null, why() -> the bridge's message}
  constructor(phone, Session) {
    super();
    this.phone = phone;
    this.Session = Session;
    this.s = null;
    this.closed = false;
    this.width = 0;
    this.height = 0;
    phone.hold(true);
    this._wait(Date.now());
  }

  _wait(since) {
    if (this.closed) return;
    const r = this.phone.ready();
    if (r) return this._start(r);
    if (Date.now() - since > ADB_MS) return this._close(this.phone.why() || 'Wireless debugging on the phone isn’t ready');
    this.timer = setTimeout(() => this._wait(since), ADB_POLL_MS);
  }

  _start(r) {
    const s = new this.Session(r.adb, r.serial, { ...(r.opts || {}), audio: false, control: true });
    this.s = s;
    s.on('size', (z) => { this.width = z.width; this.height = z.height; this.emit('size', z); });
    s.on('video', (p) => this.emit('video', p));
    s.on('closed', (why, meta) => this._close(why, meta));
    s.start().then(() => console.log(`[relay] ${this.phone.name}: its screen goes to the mesh`),
      (e) => { console.log(`[relay] ${this.phone.name}: ${e.message}`); s._close(e.message); });
  }

  _close(why, meta) {
    if (this.closed) return;
    this.closed = true;
    clearTimeout(this.timer);
    this.phone.hold(false);
    if (this.s && !this.s.closed) this.s.stop();
    console.log(`[relay] ${this.phone.name}: its screen for the mesh ended (${why})`);
    this.emit('closed', why, meta);
  }

  stop() { this._close('stopped'); }
  _on(fn) { if (this.s && !this.s.closed) fn(this.s); }
  touch(...a) { this._on((s) => s.touch(...a)); }
  scroll(...a) { this._on((s) => s.scroll(...a)); }
  key(...a) { this._on((s) => s.key(...a)); }
  tap(k) { this._on((s) => s.tap(k)); }
  backOrScreenOn(a) { this._on((s) => s.backOrScreenOn(a)); }
  setDisplayPower(on) { this._on((s) => s.setDisplayPower(on)); }
  simple(t) { this._on((s) => s.simple(t)); }
}

// hub: the mesh hub; phones(): the Android phones connected here, [{id, name, hold(on): adb wanted for
// the mesh or not, ready(): {adb, serial, opts (phone-bridge.js sessionOpts('screen'))} once adb is up,
// else null, why(): what the bridge says}]; Session: the platform's scrcpy.js Session; KeyState: its
// android-keys.js one; onChange(): which phones others serve changed.
function androidRelay({ hub, phones, Session, KeyState, onChange = () => {} }) {
  const selfId = hub.device.id;
  const theirs = new Map(); // computer id -> [{id, name}]
  const own = new Map(); // phone id -> { s, watched, idle, keys }
  let mine = '[]'; // what we said last
  const computer = (id) => { const s = hub.sessions.get(id); return !!s && s.connected && !P.isPhoneOs(s.peerOs); };

  const ours = () => (phones() || []).filter((p) => p && ID.test(String(p.id || '')));
  const list = () => ours().map((p) => ({ id: p.id, name: String(p.name || '').slice(0, 80) }));
  const tell = (id, l) => hub.bus.send(id, { t: T.PHONE_SCREENS, phones: l });

  // What we serve now, to every computer when it changed (main.js calls it with each state it shows).
  function refresh() {
    const l = list();
    const j = JSON.stringify(l);
    if (j === mine) return;
    mine = j;
    console.log(`[relay] our Android screens for the mesh: ${l.map((p) => p.name || p.id).join(', ') || 'none'}`);
    for (const id of hub.bus.connectedIds()) if (computer(id)) tell(id, l);
    // One no longer here: its session goes.
    for (const pid of [...own.keys()]) if (!l.some((p) => p.id === pid)) stopOwn(pid);
  }

  hub.bus.onPeer('welcome', (id) => { if (computer(id)) tell(id, JSON.parse(mine)); });
  hub.bus.onPeer('closed', (id) => { if (theirs.delete(id)) onChange(); });
  hub.bus.on(T.PHONE_SCREENS, (m, from) => {
    const l = (Array.isArray(m && m.phones) ? m.phones : []).slice(0, 20)
      .filter((p) => p && ID.test(String(p.id || '')))
      .map((p) => ({ id: p.id, name: String(p.name || '').slice(0, 80) }));
    if (JSON.stringify(l) === JSON.stringify(theirs.get(from) || [])) return;
    theirs.set(from, l);
    console.log(`[relay] Android screens of ${from}: ${l.map((p) => p.name || p.id).join(', ') || 'none'}`);
    onChange();
  });

  // ---- ours, for the others ----

  function session(pid) {
    let o = own.get(pid);
    if (o && o.s && !o.s.closed) return o.s;
    const p = ours().find((x) => x.id === pid);
    if (!p) return null;
    if (!o) own.set(pid, (o = { s: null, watched: 0, idle: null, keys: new KeyState() }));
    o.s = new PhoneScreen({ ...p, name: p.name || pid }, Session);
    return o.s;
  }

  function stopOwn(pid) {
    const o = own.get(pid);
    if (!o) return;
    own.delete(pid);
    clearTimeout(o.idle);
    if (o.s && !o.s.closed) o.s.stop();
  }

  const n = (x, w) => Math.round(x * w);
  ScreenHost.of(hub).add({
    find: (pid) => (ours().some((p) => p.id === pid) ? pid : ''),
    use: (pid) => {
      const s = session(pid);
      const o = own.get(pid);
      o.watched++;
      clearTimeout(o.idle);
      return s;
    },
    current: (pid) => session(pid),
    done: (pid) => {
      const o = own.get(pid);
      if (!o || --o.watched > 0) return;
      o.watched = 0;
      o.keys.clear();
      clearTimeout(o.idle);
      o.idle = setTimeout(() => stopOwn(pid), IDLE_MS);
      if (o.idle.unref) o.idle.unref();
    },
    // 0…1 of the picture -> its pixels (scrcpy takes a touch only on the size it sends); a finger, the
    // keys by their place (US QWERTY, as the phone's window does with Phone › HID keyboard off).
    input: (s, m, z) => {
      const o = [...own.values()].find((x) => x.s === s);
      switch (m.op) {
        case 'touch':
          if (z && [ACTION.DOWN, ACTION.MOVE, ACTION.UP].includes(m.a)) s.touch(m.a, -2, n(m.x, z.width), n(m.y, z.height), z.width, z.height, m.a === ACTION.UP ? 0 : 1);
          break;
        case 'scroll':
          if (z) s.scroll(n(m.x, z.width), n(m.y, z.height), z.width, z.height, Number(m.hs) || 0, Number(m.vs) || 0);
          break;
        case 'key': {
          if (typeof m.code !== 'string' || m.code.length > 32 || !o) break;
          const e = o.keys.event(m.code, !!m.down);
          if (e) s.key(m.down ? ACTION.DOWN : ACTION.UP, e.keycode, e.meta);
          break;
        }
        case 'button': s.tap(m.b | 0); break;
        case 'back': s.backOrScreenOn(m.a === ACTION.UP ? ACTION.UP : ACTION.DOWN); break;
        case 'power': s.setDisplayPower(!!m.on); break;
        case 'simple': if (PANELS.includes(m.type)) s.simple(m.type); break;
        default: break;
      }
    },
  });

  return {
    refresh,
    // Show Phone Screen of the Android phone `pid` connected to another computer: {relay: {host, id, os}}, or null.
    cableFor(pid) {
      for (const [at, l] of theirs) if (at !== selfId && computer(at) && l.some((p) => p.id === pid)) return { relay: { host: at, id: pid, os: 'android' } };
      return null;
    },
    // The Android phones whose screen another computer serves now ([{id, name, os}]: the sidebar opens it).
    screens() {
      const out = new Map();
      for (const [at, l] of theirs) if (computer(at)) for (const p of l) if (!out.has(p.id)) out.set(p.id, { id: p.id, name: p.name, os: 'android' });
      return [...out.values()];
    },
    makeRelay: (r) => new RelayScreen({ hub, host: r.host, id: r.id, os: 'android' }),
  };
}

module.exports = { androidRelay, PhoneScreen };