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.

9.0 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Camera & Controller › Controller (shared/pad-share.js), one-to-one and Multi-device.
//   Receive (first): the controllers other computers share with this one; the one picked plays here as an Xbox 360
//   or DualShock 4 controller (Windows: the ViGEmBus driver, Install puts it in; Linux: uinput). A Mac can't
//   receive one: it says so.
//   Share: Share my controller with other computers, its switch and the computers picked for it (several at once
//   in Multi-device); which controller only when this computer sees more than one (the Gamepad API shows one once
//   a button is pressed). The tab's own switch turns sending and receiving both off.
// The chosen controller is read here, in this window, only while it's shared and the window is open.
//   const p = UI.padCard(); body.append(...p.cards); p.update(state)
'use strict';

(function () {
  const t = (k, v) => I18n.t(k, v);
  const plat = /^Mac/.test(navigator.platform) ? 'mac' : /^Win/.test(navigator.platform) ? 'win' : 'linux';
  // Standard Gamepad buttons → remote.pad bits 0..13: A B X Y LB RB Back Start L3 R3 Up Down Left Right.
  const BTN = [0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15];
  let sending = false;
  let raf = 0;
  let want = ''; // the chosen controller's id ('' the first one)
  const pads = () => [...(navigator.getGamepads ? navigator.getGamepads() : [])].filter(Boolean);
  const chosen = () => { const all = pads(); return all.find((g) => g.id === want) || (want ? null : all[0]) || null; };
  const short = (id) => String(id || '').replace(/\s*\(.*$/, '').trim() || t('Controller');

  function poll() {
    raf = 0;
    if (!sending) return;
    const g = chosen();
    if (g) {
      let b = 0;
      BTN.forEach((k, i) => { if (g.buttons[k] && g.buttons[k].pressed) b |= 1 << i; });
      const val = (i) => (g.buttons[i] ? g.buttons[i].value : 0);
      UI.api.padState({ b, lx: g.axes[0] || 0, ly: g.axes[1] || 0, rx: g.axes[2] || 0, ry: g.axes[3] || 0, lt: val(6), rt: val(7) });
    }
    raf = requestAnimationFrame(poll);
  }
  function setSending(on) {
    sending = on;
    if (on && !raf) raf = requestAnimationFrame(poll);
  }

  // Is a phone (or a TV) picked: in session one-to-one, or the sidebar's device in Multi-device.
  const phoneShown = (s) => !!(UI.deviceKind && UI.deviceKind(s) !== 'computer')
    || (s.peers || []).some((d) => d && d.selected && /^(android|ios|tv)$/.test(d.os || ''));

  UI.padCard = () => {
    let last = null;
    let namedAs = null;

    // ---- receive: which controller plays here ----
    const macNote = UI.note('info', t('A Mac can’t receive a controller: macOS has no virtual controller driver. It can share its own with Windows and Linux.'));
    const recvSw = UI.switch((v) => UI.api.setPads({ receive: v }), { label: t('Let a shared controller play here') });
    const recvRow = UI.row(t('Let a shared controller play here'), t('Games here see an Xbox 360 or DualShock 4 controller'), [recvSw.el || recvSw]);
    const fromSel = UI.select([], (v) => UI.api.setPads({ from: v }));
    fromSel.el.setAttribute('aria-label', t('Controller to receive'));
    const fromRow = UI.row(t('Controller to receive'), t('Only one controller plays here at a time'), [fromSel.el]);
    const kindSel = UI.select([{ value: 'xbox', label: 'Xbox 360' }, { value: 'ds4', label: 'DualShock 4' }], (v) => UI.api.setPads({ kind: v }));
    const kindRow = UI.row(t('Shows up as'), '', [kindSel.el]);
    const installBtn = UI.button(plat === 'win' ? t('Install driver') : t('Set up'), () => UI.api.setPads({ install: true }));
    const driverRow = UI.row(t('Virtual controller'), '', [installBtn]);
    const recvCard = UI.card(t('Receive a controller'), [macNote, recvRow, fromRow, kindRow, driverRow], { cls: 'keep-on' });

    // ---- send: this computer's controller to the computers picked ----
    const padSel = UI.select([], (v) => { want = v; UI.api.setPads({ pad: v, padName: short(v) }); });
    padSel.el.setAttribute('aria-label', t('Controller to share'));
    const padRow = UI.row(t('Controller to share'), '', [padSel.el]);
    // The computers it plays on, picked in a list (several at once in Multi-device).
    const pickWho = (p, then) => {
      const devs = (p.devices || []).map((d) => ({ id: d.id, name: d.name, os: d.os, connected: !!d.connected }));
      if (!UI.pickDevices || devs.length < 2) return then(devs.map((d) => d.id)); // one computer: that one
      UI.pickDevices({ title: t('Share my controller with'), devs, sel: (p.to || []).length ? p.to : devs.filter((d) => d.connected).map((d) => d.id), onSave: (to) => then(to === 'all' ? devs.map((d) => d.id) : to) });
    };
    const shareSw = UI.switch((v) => {
      const p = last && last.pads;
      if (!p) return;
      if (v && !(p.to || []).length) { shareSw.set(false); return pickWho(p, (to) => UI.api.setPads({ to, share: to.length > 0 })); } // on once they're picked
      UI.api.setPads({ share: v });
    }, { label: t('Share my controller with other computers') });
    const whoBtn = UI.button(t('Change'), () => last && last.pads && pickWho(last.pads, (to) => UI.api.setPads({ to, share: to.length > 0 })), 'small');
    const shareRow = UI.row(t('Share my controller with other computers'), '', [whoBtn, shareSw.el || shareSw]);
    const sendCard = UI.card(t('Share a controller'), [shareRow, padRow], { cls: 'keep-on' });

    const redraw = () => { if (last) paint(last); };
    window.addEventListener('gamepadconnected', redraw);
    window.addEventListener('gamepaddisconnected', redraw);

    function paint(s) {
      const p = s.pads;
      want = p.pad || '';
      // Controllers here: the picker only when there's more than one.
      const all = pads();
      padSel.options(all.length ? all.map((g) => ({ value: g.id, label: short(g.id) })) : [{ value: '', label: t('None found') }]);
      padSel.set(chosen() ? chosen().id : '');
      padRow.hidden = all.length < 2;
      padRow.setHint(t('{count} found. Press a button on another to list it too', { count: all.length }));
      const g = chosen();
      const name = g ? short(g.id) : '';
      if (name && name !== namedAs) { namedAs = name; UI.api.setPads({ padName: name }); } // what the others see it as
      // Where it plays.
      const devs = p.devices || [];
      const to = devs.filter((d) => (p.to || []).includes(d.id));
      shareSw.set(!!(p.share && to.length));
      shareSw.disable(!devs.length);
      whoBtn.hidden = devs.length < 2;
      shareRow.setHint(!devs.length ? t('No computer to share it with yet')
        : !all.length ? t('Plug in a controller and press a button on it')
          : p.share && to.length ? t('{controller} plays on {names}', { controller: name || t('Controller'), names: to.map((d) => d.name).join(', ') })
            : t('{controller}: each computer it’s shared with sees it as its own controller', { controller: name || t('Controller') }));
      setSending(!!(p.on && p.share && to.length));
      // Receive.
      const can = !!p.canReceive;
      macNote.hidden = can;
      recvRow.hidden = fromRow.hidden = kindRow.hidden = driverRow.hidden = !can;
      if (can) {
        recvSw.set(!!p.receive);
        const offers = p.offers || [];
        fromSel.options([{ value: '', label: t('The first one that plays') },
          ...offers.map((o) => ({ value: o.from, label: t('{controller} on {device}', { controller: o.name, device: o.device || t('another computer') }) })),
          ...(p.from && !offers.some((o) => o.from === p.from) ? [{ value: p.from, label: t('A computer not sharing now') }] : [])]);
        fromSel.set(p.from || '');
        fromRow.setHint(!offers.length ? t('No controller is shared with this computer now') : t('Only one controller plays here at a time'));
        fromRow.hidden = !p.receive;
        kindRow.hidden = !p.receive;
        kindSel.set(p.kind || 'xbox');
        const from = p.playing && (offers.find((o) => o.from === p.playing) || {});
        recvRow.setHint(p.busy ? t(p.busy) : p.message ? p.message
          : from ? t('{controller} on {device} is playing here', { controller: from.name || t('Controller'), device: from.device || t('another computer') })
            : t('Games here see an Xbox 360 or DualShock 4 controller'));
        driverRow.hidden = p.driver === 'ready';
        installBtn.disabled = !!p.busy;
        driverRow.setHint(p.driver === 'missing' || !p.driver
          ? (plat === 'win' ? t('Needs the ViGEmBus driver (free, signed). Install asks once for permission') : t('Needs access to /dev/uinput. Set up asks once for permission'))
          : t(p.driver));
      }
    }

    return {
      cards: [recvCard, sendCard],
      el: recvCard,
      update(s) {
        last = s;
        // Computers only: with a phone, an iPhone or iPad (or a TV) in session or picked in the sidebar, the
        // Controller tab is gone.
        const phone = phoneShown(s);
        sendCard.hidden = recvCard.hidden = !s.pads || phone;
        if (s.pads && !phone) paint(s);
        else if (!s.pads) setSending(false); // a controller already shared to computers keeps playing while a phone is shown
      },
    };
  };
})();