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.2 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith, Erdoğan Yeşil. GPL-3.0, see LICENSE.
// Share screen to several devices at once (docs/screen-mesh.md), Windows and Linux. Every connected
// device gets a PcScreen of its own, made by `make(scopedLink)` on a link scoped to that device
// (hub.scoped), so each target has its own WebRTC session, mode, monitor and policy. The stream table
// (shared/screen-mesh.js) holds what each target gets and checks it against this computer's displays;
// there is one virtual display adapter, so at most one target can be on Extend.
//
// This object is also the single-peer API the rest of the app grew up with (`pcScreen`): setMode(),
// view(), the tray's Share Screen, Extend and Mirror and the Share screen page's Mode act on the ACTIVE
// target, so with one device everything behaves as before. Active is the device that is already being
// shared to, else the one whose viewer is open and watching (its Monitor 2), else the selected device
// (#256: the selection follows the pointer's last crossing, so Extend went to the Mac the pointer had
// just visited instead of the Linux computer watching). The selected device wins among several.
// Settings changes (apply, sizeExtend, applyInput, sendState, shutdown) reach every target.
'use strict';

const { EventEmitter } = require('events');
const S = require('./screen-mesh.js');
const { channel, MAX: MAX_CH } = require('./screen-ch.js');

const UI_MODE = { off: 'none', mirror: 'mirror', extend: 'virtual' };

class PcScreenSet extends EventEmitter {
  // hub: hub.js; make(scopedLink, extendFree) -> PcScreen; model() -> raw displays of this computer.
  constructor({ hub, make, model, onChange = () => {} }) {
    super();
    Object.assign(this, { hub, make, model, onChange });
    this.byId = new Map(); // device id -> PcScreen
    this.all = [];
    this.table = {}; // { [deviceId]: choice } of shared/screen-mesh.js
    this.extras = new Map(); // device id -> Map(ch -> PcScreen): more screens to a device that takes them (shared/screen-ch.js)
    hub.on('peerAdded', (id) => this._ensure(id));
    hub.on('peerRemoved', (id) => this._gone(id));
    this.first = this._create(hub.scoped(null));
    for (const id of hub._connectedIds()) this._ensure(id);
  }

  _create(raw) {
    const link = channel(raw, 0); // stream 0: what it always was; it doesn't hear an extra stream's messages
    const pc = this.make(link, () => this._extendFree(pc));
    pc.link = link;
    this.all.push(pc);
    return pc;
  }

  _ensure(id) {
    if (this.byId.has(id)) return;
    const pc = this.first.link.id === null ? this.first : this._create(this.hub.scoped(null));
    pc.link.bind(id);
    this.byId.set(id, pc);
    pc.welcome(); // the link's own 'welcome' went out before this unit was bound
    this.onChange();
  }

  _gone(id) {
    delete this.table[id];
    for (const pc of (this.extras.get(id) || new Map()).values()) if (pc.mode !== 'off') pc.setMode('off');
    this.onChange();
  }

  _extendFree(pc) {
    return !this.all.some((x) => x !== pc && x.mode === 'extend');
  }

  get active() {
    const live = [...this.byId].filter(([id]) => this.hub.sessions.get(id)?.connected).map(([, u]) => u);
    const sel = this.byId.get(this.hub.selectedId);
    const pick = (list) => (list.includes(sel) ? sel : list[0]);
    const sharing = live.filter((u) => u.mode && u.mode !== 'off');
    if (sharing.length) return pick(sharing);
    const watching = live.filter((u) => u.mac && u.mac.told && u.mac.accept); // its viewer said it watches (pcscreen.js screen.policy)
    if (watching.length) return pick(watching);
    return sel || live[0] || this.first;
  }

  unit(id) {
    return id ? this.byId.get(id) || null : this.active;
  }

  get displays() {
    return S.normalizeDisplays(this.model());
  }

  // ---- the per-target choice (the page): choice = { mode: 'off'|'mirror'|'extend', displayId? } ----
  async setTarget(id, choice) {
    const pc = this.byId.get(id);
    if (!pc) return { ok: false, error: 'device' };
    if (choice && (choice.add || choice.ch)) return this._setExtra(id, pc, choice);
    const mode = UI_MODE[choice && choice.mode] ? choice.mode : 'off';
    const ids = this.hub._connectedIds();
    const size = pc._extendSize ? pc._extendSize() : [1920, 1080];
    const want = mode === 'off' ? { mode: 'none' }
      : mode === 'mirror' ? { mode: 'mirror', displayId: String(choice.displayId || (this.displays.find((d) => d.primary) || {}).id) }
        : { mode: 'virtual', size: { w: size[0], h: size[1] } };
    const r = S.setChoice(this.table, id, want, ids, this.displays);
    if (!r.ok) {
      pc.status.error = r.error === 'virtual-limit' ? 'The virtual display is already used by another device' : 'That choice isn’t possible now';
      this.onChange();
      return r;
    }
    this.table = r.table;
    if (want.mode === 'mirror') pc.monitorId = want.displayId;
    pc.place = mode !== 'off' && choice && typeof choice.place === 'string' ? choice.place.slice(0, 40) : ''; // which of its monitors it fills there (the sharing map)
    pc.stateKey = ''; // sent again with it
    await pc.setMode(mode);
    pc.sendState(); // the monitor alone may have changed
    return r;
  }

  // ---- extra streams: another screen of this computer to the same device (choice.add, or choice.ch) ----
  // Only while that device's viewer takes them (screen.policy multi) and stream 0 is sharing; mirror only.
  // Made once per (device, ch) and kept (switched off, not thrown away), at most MAX_CH per device.
  async _setExtra(id, base, choice) {
    let map = this.extras.get(id);
    const ch = Number(choice.ch) || 0;
    if (choice.mode === 'off') {
      const pc = map && map.get(ch);
      if (pc) { pc.place = ''; await pc.setMode('off'); pc.sendState(); this.onChange(); }
      return { ok: true };
    }
    if (!base.mac || !base.mac.multi || base.mode === 'off') return { ok: false, error: 'multi' };
    const displayId = String(choice.displayId || '');
    if (!this.displays.some((d) => String(d.id) === displayId)) return { ok: false, error: 'display' };
    if (!map) this.extras.set(id, (map = new Map()));
    let n = ch;
    if (!n) for (let i = 1; i <= MAX_CH && !n; i++) if (!map.get(i) || map.get(i).mode === 'off') n = i;
    if (!n || n > MAX_CH) return { ok: false, error: 'full' };
    let pc = map.get(n);
    if (!pc) {
      const raw = this.hub.scoped(null);
      raw.bind(id);
      const link = channel(raw, n);
      pc = this.make(link, () => false); // no Extend on an extra stream
      pc.link = link;
      pc.ch = n;
      this.all.push(pc);
      map.set(n, pc);
      pc.welcome();
    }
    pc.monitorId = displayId;
    pc.place = typeof choice.place === 'string' ? choice.place.slice(0, 40) : '';
    pc.stateKey = '';
    await pc.setMode('mirror');
    pc.sendState();
    this.onChange();
    return { ok: true, ch: n };
  }

  // ---- the single-peer API: the active target ----
  setMode(mode) { return this.active.setMode(mode); }
  extend() { return this.active.extend(); }
  get mode() { return this.active.mode; }
  get link() { return this.first.link; }
  applyInput() { for (const u of this.all) u.applyInput(); }
  apply() { return Promise.all(this.all.map((u) => u.apply())); }
  sizeExtend() { return Promise.all(this.all.map((u) => u.sizeExtend())); }
  sendState() { for (const u of this.all) u.sendState(); }
  shutdown() { for (const u of this.all) u.shutdown(); }

  view() {
    const a = this.active;
    return {
      ...a.view(),
      deviceId: a.link.id,
      displays: this.displays,
      // Every connected device with what it gets now, for the page's per-target choice.
      targets: [...this.byId].filter(([id]) => this.hub.sessions.get(id)?.connected).map(([id, u]) => {
        const s = this.hub.sessions.get(id);
        const more = [...(this.extras.get(id) || new Map())].filter(([, x]) => x.mode !== 'off').map(([ch, x]) => ({ ch, monitor: x.monitorId || '', place: x.place || '', status: x.status.status, error: x.status.error }));
        return { id, name: s.displayName(), os: s.peerOs, mode: u.mode, monitor: u.monitorId || '', place: u.place || '', multi: !!(u.mac && u.mac.multi), more, status: u.status.status, error: u.status.error, busy: u.busy, active: u === a };
      }),
    };
  }
}

module.exports = { PcScreenSet };