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.

2.5 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// More than one screen of a computer to the same device (Multi-device, Windows and Linux): each extra
// screen is a stream of its own, numbered (ch 1…MAX), on the same device link. channel(link, ch) is that
// link seen by one stream: what it sends carries ch, and it hears only messages with its ch. Stream 0 is
// the one there always was: it sends no ch (the bytes on the wire don't change), and hears only messages
// without one, so an extra stream's messages never reach it. A device gets extra streams only after its
// viewer says it takes them (screen.policy multi: true); otherwise a second screen replaces the first.
// 'welcome', 'closed', 'transport' and 'client' are the device's own and go to every stream.
'use strict';

const MAX = 3; // extra streams per device (so up to 4 screens of one computer on one device)
const OWN = new Set(['welcome', 'closed', 'transport', 'client', 'rtt']);

// The Mac's peers (mac/mesh/peer.js) say 't:<type>' and 'message' and send with sendToClient; the
// Windows and Linux links say the type and send with send. Both are covered; off() finds its wrapper.
function channel(link, ch) {
  const n = Number.isInteger(ch) && ch > 0 && ch <= MAX ? ch : 0;
  const mine = (m) => (n ? !!m && m.ch === n : !(m && m.ch));
  const wrapped = new Map(); // fn -> its filtered listener
  const wrap = (type, fn) => {
    if (OWN.has(type)) return fn;
    if (!wrapped.has(fn)) wrapped.set(fn, (m, ...rest) => { if (mine(m)) fn(m, ...rest); });
    return wrapped.get(fn);
  };
  const tag = (send) => (obj, ...rest) => send(obj && typeof obj === 'object' && typeof obj.t === 'string' ? { ...obj, ch: n } : obj, ...rest); // a message (send(ctx, msg) on the Mac: ctx goes as it is)
  const proxy = new Proxy(link, {
    get(target, prop) {
      if (prop === 'on' || prop === 'once') return (type, fn) => { const r = target[prop](type, wrap(type, fn)); return r === target ? proxy : r; };
      if (prop === 'off') return (type, fn) => { const r = target.off(type, wrapped.get(fn) || fn); return r === target ? proxy : r; };
      if (n && (prop === 'send' || prop === 'sendToClient') && typeof target[prop] === 'function') return tag(target[prop].bind(target));
      if (prop === 'ch') return n;
      const v = Reflect.get(target, prop, target);
      return typeof v === 'function' ? v.bind(target) : v;
    },
    set(target, prop, value) {
      return Reflect.set(target, prop, value, target);
    },
  });
  return proxy;
}

module.exports = { channel, MAX };