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.

7.4 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Multi-device camera: one CamShare (shared/camshare.js) per connected device, each on its own link (the
// hub's bus, that device only). So this computer's camera goes to several computers at once (each that opens
// it gets its own picture), and at the same time the camera picked at the top of the Camera page (Receive,
// settings.camera.from) shows here, whatever the sidebar selects.
//   - Sending: computers only, never a phone. "Share this camera" and its picker (settings.camera.shareTo)
//     say which computers may open it; each hears cam.policy for itself.
//   - Receiving: computers and iPhones that share theirs (an iPhone's app speaks camshare.js); one at a time.
//     An Android phone's camera comes through its own stack (phoneview.js openCamera), not here.
// It stands in for the single CamShare: the same calls (view, closeView, setShare, setShareTo, setDevice,
// listDevices, stopSending, sendPolicy, state) and setFrom(id) / sources().
//
//   const cm = new CamMulti({ hub, CamShare, cfg, save, popup, onChange, getLanguage, log? })
'use strict';

const P = require('./protocol.js');

const T = P.T;
const TYPES = [T.CAM_POLICY, T.CAM_OPEN, T.CAM_CLOSE, T.CAM_ANSWER, T.CAM_OFFER, T.CAM_ICE, T.CAM_STATE];

class CamMulti {
  constructor({ hub, CamShare, cfg, save, popup, onChange, getLanguage = () => 'en', log = (...a) => console.log(...a) }) {
    Object.assign(this, { hub, CamShare, cfg, save, popup, onChange, getLanguage, log });
    this.shares = new Map(); // device id → { cam: CamShare, handlers: Map(type → [fn]) }
    try { require('electron').ipcMain.setMaxListeners(64); } catch (_) { /* not in Electron (tests) */ } // a CamShare per device, each listening
    // Not tied to a device: lists this computer's cameras (its sender window does) and holds the switch.
    this.local = this._make('', { on: () => {}, send: () => false, connected: () => false, ble: () => false, closed: () => {} });
    for (const t of TYPES) hub.bus.on(t, (m, from) => this._deliver(from, t, m));
    hub.bus.onPeer('welcome', (id) => this._deliver(id, 'welcome', {}));
    hub.bus.onPeer('closed', (id) => {
      const e = this.shares.get(id);
      if (!e) return;
      for (const fn of e.handlers.get('closed') || []) fn();
      if (this.cfg().from === id) this.onChange();
    });
    for (const id of this._ids()) this._get(id).cam.sendPolicy(); // connected already: they hear it now
  }

  _session(id) { return id ? this.hub.sessions.get(id) : null; }
  _os(id) { const s = this._session(id); return s ? s.peerOs : ''; }
  _up(id) { const s = this._session(id); return !!s && s.connected; }
  _computer(id) { return this._up(id) && !P.isPhoneOs(this._os(id)); }
  // Devices whose camera can come here through camshare.js: computers and iPhones (Android has its own).
  _camPeer(id) { return this._up(id) && this._os(id) !== P.OS.ANDROID; }
  _ids() { return (this.hub.bus.connectedIds ? this.hub.bus.connectedIds() : []).filter((id) => this._camPeer(id)); }
  _name(id) { const s = this._session(id); return s ? s.displayName() : String(id || '').slice(0, 8); }

  _deliver(from, type, m) {
    if (!from || !this._camPeer(from)) return;
    const e = this._get(from);
    for (const fn of e.handlers.get(type) || []) fn(m);
  }

  _get(id) {
    let e = this.shares.get(id);
    if (e) return e;
    const handlers = new Map();
    const add = (t, fn) => { if (!handlers.has(t)) handlers.set(t, []); handlers.get(t).push(fn); };
    e = this._make(id, {
      on: add,
      send: (m) => this.hub.bus.send(id, m),
      connected: () => this._camPeer(id),
      ble: () => { const s = this._session(id); return !!s && s.transport === 'ble'; },
      closed: (fn) => add('closed', fn),
    }, handlers);
    this.shares.set(id, e);
    return e;
  }

  _make(id, link, handlers = new Map()) {
    const cam = new this.CamShare({
      getLanguage: this.getLanguage,
      link,
      cfg: this.cfg,
      save: this.save,
      popup: this.popup,
      peerName: () => this._name(id),
      onChange: () => this.onChange(),
    });
    // Computers only, and only the ones picked: a phone never gets this computer's camera.
    const allows = cam.allows.bind(cam);
    cam.allows = (who) => this._computer(who) && allows(who);
    cam.current = () => id;
    cam.sendPolicy = () => { if (id && link.connected()) link.send({ t: T.CAM_POLICY, share: cam.share && cam.allows(id) }); };
    return { cam, handlers };
  }

  _all() { return [...this.shares.values()].map((e) => e.cam); }
  _from() { const id = this.cfg().from || ''; return id && this.shares.has(id) ? this.shares.get(id).cam : null; }

  // ---- receiving: the one picked at the top ----

  // The devices sharing their camera with this one now.
  sources() {
    return [...this.shares].filter(([id, e]) => e.cam.peerShares && this._camPeer(id)).map(([id]) => ({ id, name: this._name(id), os: this._os(id) }));
  }

  // Receive from: what plays here changes at once (the one before stops).
  setFrom(id) {
    id = typeof id === 'string' ? id.slice(0, 80) : '';
    const before = this.cfg().from || '';
    if (before && before !== id && this.shares.has(before)) this.shares.get(before).cam.closeView();
    this.cfg().from = id;
    this.save();
    this.onChange();
  }

  view(show = false) {
    const c = this._from();
    if (!c) return this.popup('home', 'Pick a camera at the top of Camera first', { key: 'Pick a camera at the top of Camera first' });
    for (const o of this._all()) if (o !== c && o.viewer) o.closeView(); // one at a time
    c.view(show);
  }

  closeView() { for (const c of this._all()) c.closeView(); }

  // ---- sending: to every computer picked ----

  async setShare(on, askFirst) {
    await this.local.cam.setShare(on, askFirst); // the switch (and macOS's question)
    for (const c of this._all()) {
      if (!this.local.cam.share) c.stopSending(true);
      c.sendPolicy();
    }
    this.onChange();
  }

  setShareTo(v) {
    this.local.cam.setShareTo(v);
    for (const [id, e] of this.shares) {
      if (e.cam.sender && e.cam.sender.status && !e.cam.allows(id)) e.cam.stopSending(true); // no longer may
      e.cam.sendPolicy();
    }
    this.onChange();
  }

  setDevice(id) { this.local.cam.setDevice(id); }
  listDevices() { this.local.cam.listDevices(); }

  // Stop: every computer viewing it, or one.
  stopSending(id) {
    for (const [d, e] of this.shares) if (!id || d === id) e.cam.stopSending(true);
  }

  sendPolicy() { for (const c of this._all()) c.sendPolicy(); }

  get state() {
    const base = this.local.cam.state;
    const from = this.cfg().from || '';
    const v = this._from();
    const vs = v ? v.state : null;
    const sendingTo = [...this.shares].filter(([, e]) => e.cam.sender && e.cam.sender.status)
      .map(([id, e]) => ({ id, name: this._name(id), live: e.cam.sender.status === 'live' }));
    return {
      ...base,
      connected: this._ids().length > 0,
      from,
      fromName: from ? this._name(from) : '',
      fromConnected: !!from && this._camPeer(from),
      ble: !!(vs && vs.ble),
      peerShares: !!(vs && vs.peerShares),
      sources: this.sources(),
      sending: sendingTo.length > 0,
      sendLive: sendingTo.some((x) => x.live),
      sendingTo,
      viewing: !!(vs && vs.viewing),
      viewShown: !!(vs && vs.viewShown),
      viewStatus: vs ? vs.viewStatus : '',
      viewError: vs ? vs.viewError : '',
    };
  }
}

module.exports = { CamMulti };