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.4 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Camera tab (Mac, PC and Linux): its switch at the top turns Camera on (off: nothing of it is
// loaded or runs, and nothing is shared); Start runs the other device's camera here. A
// phone's, back or front, through wireless debugging (phoneview.js openCamera, Android 12 or later;
// the phone's own Camera page starts it too); the other computer's, which it shares only with
// "Let … see this camera" on there (camshare.js). Its picture shows on the page (turned with
// Rotate), in a window with Window (or a click on the picture), and with Virtual camera on, in a
// camera every app here can pick ("TwinDesk Camera", shared/vcam.js), installed the first time
// it's turned on. This computer's own camera goes to the other one the same way.
// Multi-device: the camera that shows here is picked at the top (Receive: the devices sharing one, the
// sidebar's device first), whatever the sidebar selects; this computer's camera goes to every computer picked
// under Share this camera, several at once, while another one's shows here. Phones only send: a phone is
// never offered this computer's camera.
'use strict';

(() => {
  const tr = (text, vars) => window.I18n ? window.I18n.t(text, vars)
    : text.replace(/\{(\w+)\}/g, (m, k) => vars && Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m);

  let cur = null; // the last state, for the switch at the top
  let facing = 'back'; // a phone's camera to start with

  // An Android phone's camera comes through wireless debugging; an iPhone shares its own as a
  // computer does (its app sends it: camshare.js), so it is treated as one here.
  const isMesh = () => !!document.querySelector('.app-name .mesh-pill:not(.portable-pill)');
  // Multi-device: the cameras that can show here, the sidebar's device first: computers and iPhones sharing
  // theirs (camshare.js), and Android phones (through wireless debugging).
  function sources(s) {
    const c = s.camera || {};
    const peers = s.peers || [];
    const list = [
      ...(c.sources || []).map((d) => ({ id: d.id, name: d.name, kind: d.os === 'ios' ? 'ios' : 'computer' })),
      ...peers.filter((d) => d && d.id && d.os === 'android' && d.connected).map((d) => ({ id: d.id, name: d.name, kind: 'android' })),
    ];
    const sel = peers.find((d) => d.selected);
    return sel ? [...list.filter((d) => d.id === sel.id), ...list.filter((d) => d.id !== sel.id)] : list;
  }
  // The camera picked at the top (Multi-device), else the first one there.
  const picked = (s) => { const list = sources(s); const from = (s.camera || {}).from; return list.find((d) => d.id === from) || list[0] || null; };
  const adbPhone = (s) => (isMesh() ? !!(picked(s) && picked(s).kind === 'android') : UI.deviceKind(s) === 'android'); // shared/ui-kinds.js (s.client is the Mac's alone: the PC and Linux sent an iPhone's through ADB)
  const phoneCam = (s) => ((s.phone && s.phone.bridge && s.phone.bridge.windows) || []).find((w) => w.kind === 'camera') || null;
  const running = (s) => (adbPhone(s) ? !!phoneCam(s) : !!(s.camera && s.camera.viewing));
  const sourceName = (s) => (isMesh() ? (picked(s) || {}).name || '' : '');
  // {name}: the camera picked at the top in Multi-device, else the device in session.
  const fillSrc = (text) => UI.fill(isMesh() ? String(text).replace(/\{name\}/g, sourceName(cur || {})) : text);
  // A row's label set here, not refilled with the sidebar's device (UI.row's data-peer).
  function relabel(row, text, template) {
    if (!row || !row.label) return;
    if (template) row.label.dataset.peer = template; else delete row.label.dataset.peer;
    if (row.label.textContent !== text) row.label.textContent = text;
  }

  // Why it can't start now ('' when it can).
  function blocked(s) {
    const c = s.camera || {};
    if (adbPhone(s)) {
      const ph = s.phone || {};
      if (!ph.connected) return tr('Not connected');
      if (!ph.bridge || ph.bridge.state !== 'ready') return tr('Needs wireless debugging: set it up on the Phone page');
      return '';
    }
    if (isMesh()) {
      if (!picked(s)) return tr('No device shares its camera with this one yet');
      if (c.ble && c.from === picked(s).id) return tr('Through Bluetooth a camera can’t go across: connect over Wi-Fi or a cable');
      return '';
    }
    if (!c.connected) return tr('Not connected');
    if (c.ble) return tr('Through Bluetooth a camera can’t go across: connect over Wi-Fi or a cable');
    if (!c.peerShares && !c.viewing) return tr('Turn on “Let {me} see this camera” on {name} first');
    return '';
  }

  function start(on, show = false) {
    const s = cur;
    if (!s) return;
    const p = isMesh() ? picked(s) : null;
    if (adbPhone(s)) {
      if (on && p && UI.api.phonePick) UI.api.phonePick(p.id); // the Mac: that phone's camera
      UI.api.phoneCamera(on, on ? { facing, show } : undefined);
    } else UI.api.camera({ do: on ? 'view' : 'close', show, ...(on && p ? { id: p.id } : {}) });
  }

  UI.tab({
    id: 'camera',
    group: 'More',
    order: 75,
    title: tr('Camera & Controller'),
    icon: 'camera',
    color: 'linear-gradient(#bf5af2, #8944ab)',
    desc: tr('The other device’s camera here, and as a camera other apps can pick. A controller shared between computers.'),
    badge: (s) => (s.camera && s.camera.sending ? 'warn' : running(s) ? 'on' : ''),
    // The whole page: Camera and Controller both. Each has its own switch in its tab too.
    master: {
      get: (s) => !!((s.camera && s.camera.on) || (s.pads && s.pads.on)),
      set: (v) => { UI.api.camera({ do: 'on', on: v }); if (UI.api.setPads) UI.api.setPads({ on: v }); },
    },
    build(body) {
      const { api, el } = UI;
      const cam = (m) => api.camera(m);

      // The picture: what the camera's window sends (a JPEG, about 12 a second). A click opens the window.
      const img = el('img', { alt: '' });
      Object.assign(img.style, { width: '100%', height: '100%', objectFit: 'contain', display: 'block' });
      const said = el('div', { attrs: { 'data-literal': '' } });
      Object.assign(said.style, { position: 'absolute', inset: '0', display: 'grid', placeItems: 'center', textAlign: 'center', padding: '0 24px', color: '#a1a1a6' });
      const box = el('div', { title: tr('Open it in a window') }, [img, said]);
      Object.assign(box.style, { position: 'relative', aspectRatio: '16 / 9', background: '#000', borderRadius: '8px', overflow: 'hidden', cursor: 'pointer', margin: '12px' });
      box.onclick = () => cur && running(cur) && start(true, true);
      let url = '';
      if (api.onCamPreview) {
        api.onCamPreview((buf) => {
          if (!cur || !running(cur)) return;
          const next = URL.createObjectURL(new Blob([buf], { type: 'image/jpeg' }));
          img.onload = () => { if (url && url !== next) URL.revokeObjectURL(url); url = next; };
          img.src = next;
        });
      }

      const facingSeg = UI.segmented([{ value: 'back', label: window.I18n ? tr('camera.back') : 'Back' }, { value: 'front', label: window.I18n ? tr('camera.front') : 'Front' }], (v) => {
        facing = v;
        facingSeg.set(v);
        if (cur && running(cur)) api.phoneCamera(true, { facing: v }); // switches in the same window
      });
      facingSeg.set(facing);
      const rotate = UI.button(tr('Rotate'), () => cam({ do: 'rotate' }));
      rotate.title = tr('A quarter turn clockwise: here, in its window and in the virtual camera');
      const windowBtn = UI.button(tr('Window'), () => start(true, true));
      windowBtn.title = tr('Open it in a window');
      const startBtn = UI.button(tr('Start'), () => cur && start(!running(cur)));
      const controls = UI.row(tr('Camera on {name}'), '', [startBtn, facingSeg, rotate, windowBtn]);
      // More for the picture: mirrored (here, its window and the virtual camera), and for a phone's
      // camera its quality, light and zoom; Snapshot saves the picture as it shows here.
      const mirror = UI.switch((v) => cam({ do: 'mirror', on: v }), { label: tr('Mirror') });
      const mirrorRow = UI.row(tr('Mirror'), tr('Flipped left to right, as in a mirror: here, in its window and in the virtual camera'), [mirror]);
      const quality = UI.segmented([{ value: '1280', label: '720p' }, { value: '1920', label: '1080p' }, { value: '3840', label: '4K' }], (v) => { qual = Number(v); api.phoneCamera(true, { quality: qual }); });
      let qual = 1920;
      const qualityRow = UI.row(tr('Quality'), tr('The phone picks its nearest size. Higher needs a good connection'), [quality.el]);
      const light = UI.button(tr('Light'), () => api.phoneCamera(true, { do: 'torch' }));
      const zoomOut = UI.button('−', () => api.phoneCamera(true, { do: 'zoomOut' }));
      zoomOut.title = tr('Zoom out');
      const zoomIn = UI.button('+', () => api.phoneCamera(true, { do: 'zoomIn' }));
      zoomIn.title = tr('Zoom in');
      const snap = UI.button(tr('Snapshot'), () => {
        if (!img.src || img.hidden) return;
        const a = el('a', { attrs: { href: img.src, download: `Camera ${new Date().toISOString().slice(0, 19).replace(/:/g, '.')}.jpg` } });
        a.click();
      });
      snap.title = tr('Save the picture as it shows here');
      const phoneRow = UI.row(tr('Light and zoom'), '', [light, zoomOut, zoomIn, snap]);
      // Multi-device: which camera shows here, from the devices sharing one (the sidebar's device first).
      // Changing it stops the one running and leaves the new one ready to start.
      const fromSel = UI.select([], (v) => {
        const s = cur;
        if (s && running(s)) start(false);
        cam({ do: 'from', id: v });
      });
      fromSel.el.setAttribute('aria-label', tr('Receive a camera from'));
      const fromRow = UI.row(tr('Receive a camera from'), tr('The devices sharing their camera with this one'), [fromSel.el]);
      const picCard = UI.card('', [fromRow, box, controls, mirrorRow, qualityRow, phoneRow]);

      // Virtual camera: the picture also goes to a camera other apps can pick.
      const virtual = UI.switch((v) => cam({ do: 'virtual', on: v }), { label: tr('Virtual camera') });
      const vRemove = UI.button(tr('Remove'), () => cam({ do: 'vcamRemove' }));
      const vRow = UI.row(tr('Virtual camera'), '', [vRemove, virtual], { literal: true });
      // Which camera it feeds, where there's a choice (the Mac: TwinDesk Camera or OBS Virtual Camera).
      const vTarget = UI.select([], (t) => cam({ do: 'vcamTarget', target: t }));
      const vTargetRow = UI.row(tr('Send to'), tr('The camera other apps pick'), [vTarget]);
      const vCard = UI.card(tr('Virtual camera'), [vTargetRow, vRow]);

      // This computer's camera there.
      const mesh = () => !!document.querySelector('.app-name .mesh-pill:not(.portable-pill)');
      const computers = (s) => (s.peers || []).filter((d) => d && d.id && !/^(android|ios)$/.test(d.os || ''));
      // Multi-device: turning it on asks who may see it, the device picked in the sidebar ticked.
      const askWho = (s) => {
        const c = s.camera || {};
        const devs = computers(s).map((d) => ({ id: d.id, name: d.name, os: d.os, connected: !!d.connected }));
        const sel = Array.isArray(c.shareTo) ? c.shareTo : c.share ? 'all' : (computers(s).filter((d) => d.selected).map((d) => d.id));
        UI.pickDevices({ title: tr('Share this camera with'), devs, sel, onSave: (to) => { cam({ do: 'shareTo', to }); if (!c.share) cam({ do: 'share', on: true }); } });
      };
      const share = UI.switch((v) => {
        if (v && mesh() && UI.pickDevices && cur) { share.set(false); return askWho(cur); } // on once they're picked
        cam({ do: 'share', on: v });
      }, { label: tr('Share this camera') });
      const whoBtn = UI.button(tr('Change'), () => cur && askWho(cur));
      const shareRow = UI.row(tr('Let {name} see this camera'), '', [whoBtn, share]);
      const device = UI.select([{ value: '', label: tr('The default camera') }], (v) => cam({ do: 'device', id: v }));
      const deviceRow = UI.row(tr('Camera'), tr('Which camera on {me} it shows'), [device]);
      const stop = UI.button(tr('Stop'), () => cam({ do: 'stop' }), 'danger');
      const liveRow = UI.row(tr('{name} is viewing it now'), tr('The camera is on while it’s running there'), [stop]);
      // Multi-device: each computer viewing it now, each with its own Stop.
      const liveBox = UI.el('div');
      let liveKey = '';
      const ourCard = UI.card(tr('Camera on {me}'), [shareRow, deviceRow, liveRow, liveBox]);

      const note = UI.note('info', '');
      note.setAttribute('data-literal', '');
      // Take a photo / scan a document with the phone (shared/phonephoto.js). Each row is there
      // only where that action is wired, so a window without it never calls a missing API.
      const photoBtn = UI.button(tr('Take a photo'), () => api.takePhoto && api.takePhoto());
      const photoRow = UI.row(tr('Take a photo with the phone'), tr('Its camera opens. The photo comes here, copied and ready to paste, and is kept with received files'), [photoBtn]);
      const scanBtn = UI.button(tr('Scan document'), () => api.scanDocument && api.scanDocument());
      const scanRow = UI.row(tr('Scan a document with the phone'), tr('The phone’s camera scans pages into a PDF. It arrives with received files'), [scanBtn]);
      const photoCard = UI.card('', [photoRow, scanRow]);
      const pads = UI.padCard ? UI.padCard() : null; // Controller sharing (shared/ui-pads.js)
      // Two tabs, Camera and Controller, each with its own switch; the page's switch turns both on or off.
      const tabs = pads ? UI.tabbed('camera', [
        { id: 'camera', title: tr('Camera'), cards: [photoCard, picCard, vCard, ourCard, note], toggle: { get: (s) => !!(s.camera && s.camera.on), set: (v) => cam({ do: 'on', on: v }) } },
        { id: 'controller', title: tr('Controller'), cards: pads.cards, toggle: { get: (s) => !!(s.pads && s.pads.on), set: (v) => api.setPads({ on: v }), disabled: (s) => !s.pads } },
      ]) : null;
      if (tabs) body.append(tabs);
      else body.append(photoCard, picCard, vCard, ourCard, note);

      let listed = false;
      return (s) => {
        cur = s;
        if (pads) pads.update(s);
        if (tabs) tabs.update(s);
        const c = s.camera || {};
        const v = s.vcam || {};
        const phone = adbPhone(s);
        const on = running(s);
        const vName = `“${v.name || 'TwinDesk Camera'}”`;
        const w = phone ? phoneCam(s) : null;
        if (w && w.facing && w.facing !== facing) {
          facing = w.facing; // started or switched elsewhere (the phone's Camera page)
          facingSeg.set(facing);
        }

        // The picture, or what it's waiting for.
        const why = blocked(s);
        let text = '';
        if (!c.on) text = tr('Off: turn on Camera with the switch on its tab');
        else if (!on) text = fillSrc(why || tr('Press Start to run the camera on {name} here'));
        else if (phone && w && w.error) text = tr('It stopped: {error}', { error: w.error });
        else if (!phone && c.viewStatus === 'refused') text = fillSrc(tr('Turn on “Let {me} see this camera” on {name}'));
        else if (!phone && c.viewStatus === 'failed') text = tr('It didn’t start: {error}', { error: c.viewError || tr('unknown') });
        else if (!phone && c.viewStatus === 'ended') text = fillSrc(tr('{name} stopped its camera'));
        else if (!v.picture) text = phone ? tr('Starting the phone’s camera…') : fillSrc(tr('Asking {name} for its camera…'));
        said.textContent = text;
        said.hidden = !text;
        img.hidden = !on || !!text;
        if (!on && url) {
          URL.revokeObjectURL(url);
          url = '';
          img.removeAttribute('src');
        }
        startBtn.textContent = on ? tr('Stop') : tr('Start');
        startBtn.disabled = !c.on || (!on && !!why);
        startBtn.title = !on && why ? fillSrc(why) : '';
        facingSeg.el.hidden = !phone;
        // An Android phone, or an iPhone whose app can (phone.info caps 'capture'; shared/phonephoto.js canCapture)
        const pc = s.phone && s.phone.connected;
        const phoneHere = !!(phone && pc && (pc.os !== 'ios' || (s.phone.info && Array.isArray(s.phone.info.caps) && s.phone.info.caps.includes('capture'))));
        photoRow.hidden = !(phoneHere && api.takePhoto);
        scanRow.hidden = !(phoneHere && api.scanDocument);
        photoCard.hidden = photoRow.hidden && scanRow.hidden;
        rotate.disabled = !on;
        mirror.set(!!v.mirror);
        qualityRow.hidden = !phone;
        quality.set(String((w && w.quality) || qual));
        light.hidden = zoomOut.hidden = zoomIn.hidden = !phone;
        light.disabled = zoomOut.disabled = zoomIn.disabled = snap.disabled = !on || !!text;
        light.textContent = w && w.torch ? tr('Light ✓') : tr('Light');
        phoneRow.hidden = !on;
        phoneRow.label.textContent = phone ? tr('Light and zoom') : tr('Snapshot');
        windowBtn.disabled = !on;
        windowBtn.textContent = (phone ? w && w.shown : c.viewShown) ? tr('Window ✓') : tr('Window');
        controls.setHint(on ? tr('Turned {degrees}°. Click the picture or Window for a window of its own', { degrees: v.rotate || 0 }) : '');

        // Virtual camera.
        virtual.set(!!v.on);
        virtual.disable(v.supported === false || !!v.busy);
        vRemove.hidden = !v.installed || !!v.on || !!v.busy || v.removable === false;
        vTargetRow.hidden = !(v.targets && v.targets.length > 1);
        if (!vTargetRow.hidden) {
          vTarget.options(v.targets);
          vTarget.set(v.target || v.targets[0].value);
          vTarget.el.disabled = !!v.busy;
        }
        vRow.setHint(!v.checked ? tr('Checking…')
          : v.supported === false ? tr(v.message || '')
            : v.busy === 'install' ? tr(v.message || 'Installing…')
              : v.busy === 'remove' ? tr('Removing…')
                : v.ready && v.live ? tr('Sharing now: in Zoom, Teams, the browser…, choose only {camera} as the camera', { camera: vName })
                  : v.ready ? tr('Ready: the camera running here goes to {camera}. Choose only that one in the app you call from', { camera: vName })
                    : v.on ? tr(v.message || 'Not installed')
                      : tr(v.message || '') || tr('Off: the picture stays in TwinDesk. On: it’s also {camera}, a camera other apps can pick', { camera: vName }));

        // This computer's own camera (not with a phone).
        ourCard.hidden = phone && !isMesh();
        // Receive: the picker at the top (Multi-device), whatever the sidebar selects.
        const meshOn = isMesh();
        fromRow.hidden = !meshOn;
        if (meshOn) {
          const list = sources(s);
          const p = picked(s);
          fromSel.options(list.length ? list.map((d) => ({ value: d.id, label: d.kind === 'computer' ? d.name : tr('{name} (phone)', { name: d.name }) })) : [{ value: '', label: tr('No camera shared with this computer') }]);
          fromSel.set(p ? p.id : '');
          fromSel.el.disabled = !list.length;
          relabel(controls, p ? tr('Camera on {device}', { device: sourceName(s) }) : tr('Camera'));
        } else relabel(controls, UI.fill(tr('Camera on {name}')), tr('Camera on {name}'));
        // A phone shows only what it sends: this computer's camera never goes to a phone.
        if (meshOn || !phone) {
          share.set(!!c.share);
          whoBtn.hidden = !(mesh() && c.share);
          if (mesh()) relabel(shareRow, tr('Share this camera with other computers'));
          else relabel(shareRow, UI.fill(tr('Let {name} see this camera')), tr('Let {name} see this camera'));
          if (mesh() && c.share) {
            const names = Array.isArray(c.shareTo) ? computers(s).filter((d) => c.shareTo.includes(d.id)).map((d) => d.name) : null;
            shareRow.setHint(names ? (names.length ? tr('Shared with {names}', { names: names.join(', ') }) : tr('Shared with nobody yet: Change picks who')) : tr('Shared with every computer'));
          }
          if (!(mesh() && c.share)) shareRow.setHint(tr(c.shareError || '') || (c.share ? tr('{name} can run it there. A popup says so here when it does') : tr('Off: nobody sees it')));
          device.options([{ value: '', label: tr('The default camera') }, ...(c.devices || []).map((d) => ({ value: d.id, label: d.label }))]);
          device.set(c.device || '');
          deviceRow.hidden = !c.share;
          liveRow.hidden = meshOn || !c.sending;
          const viewers = meshOn ? c.sendingTo || [] : [];
          const lk = JSON.stringify(viewers);
          if (lk !== liveKey) {
            liveKey = lk;
            liveBox.replaceChildren(...viewers.map((v) => UI.row(tr('{device} is viewing it now', { device: v.name }), v.live ? tr('The camera is on while it’s running there') : tr('Starting…'),
              [UI.button(tr('Stop'), () => cam({ do: 'stop', id: v.id }), 'danger')], { literal: true })));
          }
          if (c.share && !listed) {
            listed = true;
            cam({ do: 'devices' });
          }
        }

        const message = v.ready
          ? tr(phone ? 'Apps here see it as {camera}: pick that one, not {me}’s own camera.' : 'Apps here see it as {camera}: pick that one, not {me}’s own camera. The picture goes straight between the two computers.', { camera: vName, me: UI.fill('{me}') })
          : tr(phone ? 'Turn on Virtual camera to use it as a real camera in other apps (Zoom, Teams, the browser…).' : 'Turn on Virtual camera to use it as a real camera in other apps (Zoom, Teams, the browser…). The picture goes straight between the two computers.');
        note.textContent = message;
        note.hidden = !message;
      };
    },
  });
})();