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.

21.6 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Share screen (copy of windows/pcscreen.js): this computer's
// screen in a window on the other one. Mirror = one existing monitor; Extend = the virtual monitor
// (vdd.js). On X11 each monitor is a desktopCapturer source; on Wayland the desktop's portal asks
// which screen to share (PipeWire), once per start. The screen's sound comes from loopback.js. Sharing starts off every
// time the app starts. We offer an `rtc2` session (kind `screen` / `screen+audio`) while sharing is
// on and the Mac's `screen.policy` accepts (sender.js); `in.*` without `wid` from the Mac are
// injected by the helper (remote-input.js).
// `screen.policy` means "a viewer is open and watching" (any peer); nothing is captured
// while it is false. A peer that never sends one (an older app) counts as watching, after a moment
// for its first policy to arrive. We tell the viewer what we share (`screen.state`) and, when
// "Let <peer> start and switch this screen" is on (pcScreen.remote), obey its `screen.ctl`.
// Multi-device: one per device (shared/pcscreen-set.js), each on its own link, sender and mode; the set
// gives a unit made after its device's 'welcome' that welcome (welcome()), its own Mirror monitor
// (monitorId) and extendFree() (one virtual monitor: one device on Extend).
const { desktopCapturer, powerMonitor, screen: displays } = require('electron');
const P = require('../shared/protocol.js');
const RemoteInput = require('./remote-input');
const loopback = require('./loopback');

const WAYLAND = process.env.XDG_SESSION_TYPE === 'wayland';

// A display's rectangle in the helper's pixels (Windows has screen.dipToScreenRect; Linux doesn't):
// X11 works in physical pixels (Electron's DIP × the scale factor); a Wayland compositor's logical
// pixels are Electron's DIP.
function screenRect(d) {
  const k = WAYLAND ? 1 : d.scaleFactor || 1;
  const b = d.bounds;
  return { x: Math.round(b.x * k), y: Math.round(b.y * k), width: Math.round(b.width * k), height: Math.round(b.height * k) };
}

const T = P.T;
const RETRY_MS = 2000; // a capture that ended by itself (the session locked): tried again, doubling up to 30 s

class PcScreen {
  // opts: link, helper, sender, vdd, settings (shared), popup(kind, text), inputAllowed() (KVM at home), onChange(), needDriver?() (Extend asked, no driver)
  //   extendFree?() (Multi-device: no other device is on Extend)
  constructor(opts) {
    Object.assign(this, opts);
    this.monitorId = null; // this target's own Mirror monitor (Multi-device), else the shared setting's
    this.mode = 'off'; // 'off' | 'mirror' | 'extend' — never saved
    this.mac = { accept: false, width: 0, height: 0, told: false }; // the viewer's screen.policy (told: it sent one)
    this.sending = null; // {session, displayId, rect (physical px), key}
    this.status = { status: 'off', error: '', name: '', width: 0, height: 0 };
    this.input = new RemoteInput(opts);
    this.busy = false;
    this.lastMode = 'mirror'; // what screen.ctl {share:true} starts (the last mode used)
    this.stateKey = ''; // the last screen.state sent on this connection
    this.retries = 0;
    this.retryTimer = null;
    this.live = false; // the capture reached 'live' (a start that never does is not retried on Wayland)

    const link = this.link;
    link.on('welcome', () => this.welcome());
    link.on('closed', () => { clearTimeout(this.policyTimer); this.mac.accept = false; this.stateKey = ''; this.apply(); });
    // The session moved (Bluetooth -> a Wi-Fi Direct link, or back): a session offered on the old path
    // never connects on the new one; the transport is part of the key, so apply() starts again.
    link.on('transport', () => this.apply());
    link.on(T.SCREEN_CTL, (m) => this._onCtl(m));
    link.on(T.SCREEN_POLICY, (m) => {
      const n = (v) => (Number.isInteger(v) && v >= 320 && v <= 7680 ? v : 0);
      const size = this.mac.width + 'x' + this.mac.height;
      // A viewer that only says accept keeps the size it told before (Windows viewers send no size).
      const width = n(m.width) || (m.width === undefined ? this.mac.width : 0);
      const height = n(m.height) || (m.height === undefined ? this.mac.height : 0);
      this.mac = { accept: m.accept === true, width, height, told: true, multi: m.multi === true }; // multi: that viewer takes extra streams (shared/screen-ch.js)
      if (this.mode === 'extend' && this.cfg.extendSize === 'mac' && size !== this.mac.width + 'x' + this.mac.height) this.sizeExtend();
      else this.apply();
    });
    for (const t of RemoteInput.TYPES) link.on(t, (m) => this._input(m));

    this.sender.on('state', (session, s) => {
      if (!this.sending || session !== this.sending.session) return;
      Object.assign(this.status, s);
      if (s.status === 'ended' || s.status === 'failed') {
        const live = this.live; // a start that never reached 'live' failed the capture itself
        this._stopSend(true);
        if (live) this._retryLater(); else this._failedBeforeLive('The screen couldn’t be captured. Start sharing again.');
      }
      if (s.status === 'live') { this.live = true; this.retries = 0; if (this.retryTimer) clearTimeout(this.retryTimer); }
      this.onChange();
    });
    this.sender.on('stats', (session, st) => {
      if (!this.sending || session !== this.sending.session) return;
      this.stats = st;
      this.onChange();
    });
    // A monitor came or went (or changed size): the shared one may be different now.
    for (const ev of ['display-added', 'display-removed', 'display-metrics-changed']) displays.on(ev, () => this.apply());
    // A locked session can't be captured: the picture ends there, and nothing else changes when it's
    // unlocked (#81, as on Windows). Unlocked or awake: at once, and again a moment later.
    for (const ev of ['unlock-screen', 'resume']) powerMonitor.on(ev, () => { this.retries = 0; this.apply(); this._retryLater(); });
  }


  // The device is there (a link event, or the set that made this one for a device already connected).
  welcome() {
    this.mac = { accept: false, width: 0, height: 0, told: false };
    this.stateKey = '';
    clearTimeout(this.policyTimer);
    this.policyTimer = setTimeout(() => { // never told: an older app, always watching
      if (!this.mac.told && !this.link.ch) { this.mac.accept = true; this.apply(); } // an extra stream (ch) waits for its viewer
    }, 1500);
    this.apply();
  }

  // The capture ended by itself: try again while it's still wanted.
  _retryLater() {
    if (this.retryTimer) clearTimeout(this.retryTimer);
    const connected = this.link.status.state === 'connected';
    const transport = (this.link.current && this.link.current.transport) || 'ip';
    if (!(connected && this.mode !== 'off' && !this.busy && this.mac.accept && transport !== 'ble')) return;
    const ms = Math.min(30000, RETRY_MS * 2 ** Math.min(this.retries++, 4));
    this.retryTimer = setTimeout(() => { if (!this.sending) this.apply(); }, ms);
  }

  // On Wayland a capture that never reached 'live' (the picker was dismissed, or the portal refused
  // the stream) is not retried: every attempt reopens the desktop's screen picker, so retrying looks
  // like a picker that never goes away. Stop sharing and keep the reason; the person starts again.
  _failedBeforeLive(message) {
    if (!WAYLAND) return this._retryLater();
    this._gaveUp(message);
  }

  // Off, without a retry, keeping the reason in the status (the Share screen tab shows it).
  _gaveUp(message) {
    if (this.retryTimer) { clearTimeout(this.retryTimer); this.retryTimer = null; }
    this.retries = 0;
    const was = this.mode;
    this.mode = 'off';
    if (was === 'extend') this.vdd.setOn(false).catch(() => {});
    this.stateKey = ''; // the next push tells the viewer it is off (sendState)
    this.status.status = 'off';
    this.status.error = message;
    this.onChange();
  }
  get cfg() {
    return this.settings.pcScreen;
  }

  async setMode(mode) {
    // 'last': this side's own Share switch, in the mode last picked here (the viewer's start is Mirror: _onCtl).
    if (mode === 'last') return this.lastMode === 'extend' ? this.extend() : this.setMode('mirror');
    if (!['off', 'mirror', 'extend'].includes(mode) || this.busy) return;
    if (mode === 'extend' && !this.vdd.state.installed) mode = 'mirror'; // this desktop can't add a virtual monitor
    if (mode === 'extend' && this.extendFree && !this.extendFree()) { // one virtual monitor, another device has it
      this.status.error = 'The virtual display is already used by another device';
      return this.onChange();
    }
    const was = this.mode;
    if (mode !== 'off') this.lastMode = mode;
    this.mode = mode;
    this.status.error = '';
    this.onChange();
    if (mode === 'extend' && was !== 'extend') {
      this.busy = true;
      this.onChange();
      const size = this._extendSize();
      try {
        const [w, h] = size;
        this.vdd.addMode(w, h);
        const mon = await this.vdd.setOn(true);
        if (mon && mon.name) await this.vdd.setMode(mon, w, h);
        if (!mon) this.mode = 'off';
      } finally {
        this.busy = false;
      }
      // The viewer told its size meanwhile (sizeExtend doesn't wait while busy): that size now.
      if (this.mode === 'extend' && String(this._extendSize()) !== String(size)) return this.sizeExtend();
    } else if (was === 'extend' && mode !== 'extend') {
      this._stopSend(true);
      this.vdd.setOn(false);
    }
    this.apply();
  }

  // The virtual monitor's size: chosen, or what the Mac asks for (else 1920 × 1080).
  _extendSize() {
    const m = /^(\d+)x(\d+)$/.exec(this.cfg.extendSize);
    if (m) return [Number(m[1]), Number(m[2])];
    if (!this.mac.width) return [1920, 1080];
    // A phone tells its pixels: a monitor half that size, so text is readable there (the Mac's
    // Extend for a phone has the same size in points).
    const even = (v, min) => Math.max(min, Math.round(v / 4) * 2);
    if (P.isPhoneOs(this.link.peerOs)) return [even(this.mac.width, 480), even(this.mac.height, 360)];
    return [this.mac.width, this.mac.height];
  }

  // Extend size changed while Extend is on: a size the driver doesn't know yet needs a device restart.
  async sizeExtend() {
    if (this.mode !== 'extend' || this.busy) return this.apply();
    this.busy = true;
    this.onChange();
    try {
      const [w, h] = this._extendSize();
      if (this.vdd.addMode(w, h)) {
        this._stopSend(true);
        await this.vdd.setOn(false);
        await this.vdd.setOn(true);
      }
      const mon = await this.vdd.find().catch(() => null);
      if (mon) await this.vdd.setMode(mon, w, h);
    } finally {
      this.busy = false;
    }
    this.apply();
  }

  // Stream size: scale down (on the GPU, by the capturer) to at most maxHeight, keeping the shape.
  _streamSize(rect) {
    const max = this.cfg.maxHeight;
    if (!max || rect.height <= max) return [rect.width, rect.height];
    return [Math.round((rect.width * max) / rect.height / 2) * 2, max];
  }

  // The display to share: Extend → the virtual monitor; Mirror → the chosen one (else the main one).
  async _target() {
    const all = displays.getAllDisplays();
    if (this.mode === 'extend') {
      const mon = await this.vdd.find().catch(() => null);
      if (!mon) return null;
      // Wayland: Mutter's geometry when Electron doesn't list the new monitor (yet).
      return all.find((d) => { const r = screenRect(d); return r.x === mon.x && r.y === mon.y; })
        || (WAYLAND ? { id: mon.name, label: 'Virtual remote monitor', bounds: { x: mon.x, y: mon.y, width: mon.width, height: mon.height }, scaleFactor: 1 } : null);
    }
    return all.find((d) => String(d.id) === (this.monitorId || this.cfg.monitor)) || displays.getPrimaryDisplay();
  }

  // After welcome, a policy, a settings or display change.
  async apply() {
    if (this.applying) { this.again = true; return; }
    this.applying = true;
    try {
      do {
        this.again = false;
        await this._applyOnce();
      } while (this.again);
    } finally {
      this.applying = false;
    }
    this.onChange();
  }

  async _applyOnce() {
    const connected = this.link.status.state === 'connected';
    // Bluetooth can't carry the picture: it starts once the session is on Wi-Fi (netlink.js).
    const transport = (this.link.current && this.link.current.transport) || 'ip';
    const want = connected && this.mode !== 'off' && !this.busy && this.mac.accept && transport !== 'ble';
    // Why nothing is sent, once per change (#256: "the virtual screen is there, the other side shows nothing").
    this._why(!want && this.mode !== 'off' ? (!connected ? 'its device isn’t connected' : this.busy ? 'the screen is starting'
      : !this.mac.accept ? 'nobody watches there (its viewer’s screen.policy)' : 'the session is on Bluetooth') : '');
    if (!want) return this._stopSend(connected);
    const d = await this._target();
    if (!d) this._why(this.mode === 'extend' ? 'the virtual monitor isn’t among the displays (its position as the helper sees it didn’t match any)' : 'no display to share');
    if (!d) return this._stopSend(true);
    const rect = screenRect(d);
    const [width, height] = this._streamSize(rect);
    const fps = PcScreen.fps(d, this.cfg.fps);
    // Playback › Steady is set up per session (shared/screencodec.js steady()): a change starts a new one.
    const steady = !!(this.settings.monitor && this.settings.monitor.pacing === 'steady');
    const key = [d.id, rect.x, rect.y, rect.width, rect.height, width, this.cfg.mbps, this.cfg.sound, fps, transport, steady].join(',');
    if (this.sending && this.sending.key === key) return;
    // Wayland: the portal's picker lists the virtual monitor with the others.
    if (WAYLAND && this.mode === 'extend' && this.popup) this.popup('away', 'Choose “Virtual remote monitor” to extend onto {name}');
    let sources;
    try {
      sources = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 0, height: 0 } });
    } catch (e) {
      sources = [];
    }
    // Wayland: the portal hands back the one screen the person picked (no display ids).
    const src = sources.find((s) => s.display_id === String(d.id)) || (WAYLAND || sources.length === 1 ? sources[0] : null);
    if (!src) {
      const why = WAYLAND ? 'No screen was picked to share' : 'The desktop didn’t offer that monitor for capture';
      this.status.error = why;
      this._stopSend(true);
      if (WAYLAND) this._failedBeforeLive(why);
      return;
    }
    let audio = '';
    if (this.cfg.sound) audio = await loopback.acquire().catch((e) => { this.status.error = 'Sound: ' + e.message; return ''; });
    if (!this.mode || this.mode === 'off' || !this.mac.accept) { if (audio) loopback.release(); return; }
    this._stopSend(true);
    const mbps = this.cfg.mbps; // Share screen › Quality, for phones too
    const session = this.sender.start({ sourceId: src.id, width, height, detailSource: !WAYLAND ? { width: rect.width, height: rect.height } : null, mbps, fps, steady, audio: false, audioLabel: audio, offer: { kind: 'screen', width, height } }); // its size: a viewer shapes its window to it (#255)
    this.live = false;
    this.sending = { session, displayId: d.id, rect, key, loop: !!audio };
    this.stats = null;
    Object.assign(this.status, { status: 'starting', error: '', name: d.label || src.name, width: rect.width, height: rect.height });
  }

  // Logged once per change: why this target sends nothing ('' = it may send).
  _why(reason) {
    if (reason === (this.whyNot || '')) return;
    this.whyNot = reason;
    const who = (this.link.current && this.link.current.name) || this.link.id || '';
    if (reason) console.log(`[pcscreen] ${this.mode} for ${who}: not sending, ${reason}`);
  }

  // What we offer the viewer: Extend only where this desktop can add a virtual monitor.
  // Extend from a menu or the viewer. Without the display driver: Mirror for now, and the Share
  // screen tab here, where Install is (needDriver; never an administrator prompt from afar).
  extend() {
    if (this.vdd.state.checked && !this.vdd.state.installed) {
      if (this.needDriver) this.needDriver();
      return this.setMode('mirror');
    }
    return this.setMode('extend');
  }

  // Both, always: the viewer keeps its Extend button even before the driver is here (extend()).
  _modes() {
    // Multi-device (the link is a stream of shared/screen-ch.js): an extra stream, or a device given another
    // monitor or an added virtual display, just shows that screen, with no Extend | Mirror switch there.
    if (this.link && this.link.ch !== undefined) {
      if (this.link.ch) return [];
      if (this.mode === 'mirror' && this.monitorId) {
        let main = null;
        try { main = displays.getPrimaryDisplay(); } catch (_) { /* no screen module (tests) */ }
        if (main && String(main.id) !== String(this.monitorId)) return [];
      }
    }
    return ['extend', 'mirror'];
  }

  // screen.state after welcome and whenever any of it changes (called with every state push).
  sendState() {
    if (this.link.status.state !== 'connected') return void (this.stateKey = '');
    const msg = { t: T.SCREEN_STATE, on: this.mode !== 'off', mode: this.mode, remote: this.cfg.remote, input: !!this.input.allowed, modes: this._modes(), touch: true };
    if (this.place && this.mode !== 'off') msg.place = this.place; // Multi-device: which of the viewer's monitors it fills (the sharing map; older viewers ignore it)
    const key = JSON.stringify(msg);
    if (key === this.stateKey) return;
    this.stateKey = key;
    this.link.send(msg);
  }

  // The viewer starts/stops our sharing or switches Extend/Mirror, if we let it.
  _onCtl(m) {
    // The phone viewer's Close stops sharing even when the viewer may not start and switch it.
    if (m.share === false && m.close === true) return this.setMode('off');
    if (!this.cfg.remote) {
      this.stateKey = ''; // re-send: remote false
      return this.onChange();
    }
    const mode = m.mode === 'extend' || m.mode === 'mirror' ? m.mode : null;
    if (m.share === false) return this.setMode('off');
    // Multi-device: Mirror asked from the viewer is the main card's screen (Share screen's Mirror), not a
    // monitor the map gave it before; only this device changes.
    if (mode === 'mirror' && this.link && this.link.ch === 0) { this.monitorId = ''; this.place = ''; this.stateKey = ''; }
    if (mode && (m.share === true || this.mode !== 'off')) return mode === 'extend' ? this.extend() : this.setMode(mode);
    if (mode) { this.lastMode = mode; return this.onChange(); }
    // Started from the viewer: Mirror (a virtual display doesn't always start); Extend is its switch.
    if (m.share === true && this.mode === 'off') return this.setMode('mirror');
  }

  // Frames per second to send: the display's refresh rate (30–120), so motion is never decimated.
  // cap: Share screen › Frame rate (30 or 60; 0 = the display's).
  static fps(d, cap = 0) {
    const hz = Math.min(120, Math.max(30, Math.round((d && d.displayFrequency) || 60)));
    return cap === 30 || cap === 60 ? Math.min(cap, hz) : hz;
  }

  _stopSend(tellMac) {
    this.input.release();
    this.live = false;
    if (!this.sending) return;
    const { session, loop } = this.sending;
    if (loop) loopback.release();
    this.sending = null;
    this.stats = null;
    this.status.status = 'off';
    this.sender.stop(session, tellMac);
  }

  // in.* from the Mac's PC window (no `wid`; those are app windows, pcapps.js): coordinates are
  // normalized over the shared monitor.
  _input(m) {
    if (!this.sending || m.wid != null) return;
    const r = this.sending.rect;
    const at = (x, y) => ({ x: Math.round(r.x + x * (r.width - 1)), y: Math.round(r.y + y * (r.height - 1)) });
    this.input.handle(m, (x, y) => this.helper.send('moveTo', at(x, y)), null, (x, y, pen) => this.helper.send('pen', { ...at(x, y), pen }),
      false, (list) => this.helper.send('touch', RemoteInput.touchCmd(list, at)));
  }

  applyInput() {
    if (!this.settings.pcScreen.input) this.input.release();
  }

  // Monitors for the Mirror picker.
  monitors() {
    const primary = displays.getPrimaryDisplay().id;
    const v = this.vdd.state.on && this.vdd.mon; // the virtual monitor is Extend's, not Mirror's
    return displays.getAllDisplays()
      .map((d) => ({ d, r: screenRect(d) }))
      .filter(({ r }) => !(v && r.x === v.x && r.y === v.y))
      .map(({ d, r }, i) => {
        // The monitor's own name; a laptop panel often has none (real names, not 'Monitor').
        const name = d.label || (d.internal ? 'Built-in screen' : 'Monitor ' + (i + 1));
        return { id: String(d.id), label: name + ', ' + r.width + ' × ' + r.height + (d.id === primary ? ' (main)' : '') };
      });
  }

  // Sharing ends with the app; the virtual monitor too.
  shutdown() {
    this._stopSend(true);
    if (this.mode === 'extend') this.vdd.setOn(false);
  }

  view() {
    return { ...this.cfg, mode: this.mode, busy: this.busy, mac: this.mac, ...this.status, stats: this.stats || null, extendPx: this._extendSize(), sending: !!this.sending, monitors: this.monitors(), vdd: this.vdd.view() };
  }
}

// This computer's displays as the screen-mesh model (shared/screen-mesh.js): ids are Electron's,
// positions relative to the main display, the helper's pixels (screenRect).
PcScreen.displayModel = () => {
  const primary = displays.getPrimaryDisplay();
  const rects = displays.getAllDisplays().map((d) => ({ d, r: screenRect(d) }));
  const o = rects.find(({ d }) => d.id === primary.id);
  const ox = o ? o.r.x : 0;
  const oy = o ? o.r.y : 0;
  return rects.map(({ d, r }, i) => ({
    id: String(d.id), name: d.label || (d.internal ? 'Built-in screen' : 'Monitor ' + (i + 1)),
    x: r.x - ox, y: r.y - oy, w: r.width, h: r.height, scale: d.scaleFactor || 1, primary: d.id === primary.id,
  }));
};

module.exports = PcScreen;