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.

6.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// TwinDesk Web on this computer (shared/web/webwire.js), for main.js and Multi-device's mesh/main.js
// alike (port of windows/web.js): its screen (and the virtual monitor for Extend), its sound (the
// PulseAudio / PipeWire loopback source, loopback.js), input through the helper, the Remote page, notifications, the shared folder, media keys, the virtual camera and
// the file-paste shortcut.
// setupWeb(c): c.settings(), c.save(), c.pushState(), c.t, c.device() → {id, name}, c.helper, c.smb,
//   c.notifs, c.fileClip, c.vdd? and c.pcScreen? (Extend), c.kvm() (home or not), c.devctl(),
//   c.loadVcam?(). Returns webwire's {hub, view(), actions, shutdown()}; the actions are ipc handlers.
'use strict';

const os = require('os');
const path = require('path');
const { app, ipcMain, shell, Notification, screen: displays } = require('electron');
const P = require('../shared/protocol.js');
const { receivedDir } = require('../shared/received.js');
const { DevLocal } = require('../shared/devlocal.js');
const { startWeb, pcShare } = require('../shared/web/webwire.js');
const { airplayHost } = require('../shared/airplay/viewer.js');
const RemoteInput = require('./remote-input');
const loopback = require('./loopback');

const WAYLAND = process.env.XDG_SESSION_TYPE === 'wayland';
// The helper's screen pixels (Wayland: Electron's are those already).
const rectOf = (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 apple = (c) => !!c && ['ios', 'ipados', 'mac'].includes(c.os);

function setupWeb(c) {
  const { PhoneRemote } = require('../shared/phone-remote.js');
  const settings = c.settings;
  const helper = c.helper;
  const home = () => { const k = c.kvm(); return !k || k.mode === 'home'; };
  let web = null;
  const { share, smbInfo } = pcShare(c.smb, () => (web ? web.hub.host : os.hostname()));
  const vdd = c.vdd;
  let extending = false; // the virtual monitor is the web device's
  web = startWeb({
    dir: app.getPath('userData'), root: path.join(__dirname, '..'), t: c.t,
    settings, save: c.save, pushState: c.pushState,
    self: () => ({ id: c.device().id, name: c.device().name, os: 'linux', version: app.getVersion() }),
    receivedDir: () => receivedDir(settings(), app.getPath('downloads')),
    say: (title, body, onClick) => {
      if (!Notification.isSupported()) return;
      try {
        const n = new Notification({ title, body });
        if (onClick) n.on('click', onClick);
        n.show();
      } catch {}
    },
    reveal: (p) => shell.showItemInFolder(p),
    open: (p) => shell.openPath(p),
    // The default output's monitor (PulseAudio or PipeWire): it hears what the speakers play, so it
    // can't be muted without silencing what's sent.
    capture: {
      audio: 'source', source: { acquire: () => loopback.acquire(), release: () => loopback.release() },
      engines: {
        list: () => [{ id: 'monitor', label: c.t('PulseAudio / PipeWire monitor'), hint: c.t('Captures the default output. This computer can’t be muted while sending: the capture hears what the speakers play.'), mute: false }],
        get: () => 'monitor', set: () => {}, mute: () => false, setMute: () => {},
      },
    },
    // Extend: the virtual monitor (vdd.js), in the web device's shape, while Share screen isn't using it.
    extend: vdd ? {
      can: () => !!vdd.state.installed && (extending || ((!c.pcScreen || c.pcScreen.mode !== 'extend') && !vdd.state.on)),
      async display(dev) {
        let [w, h] = dev && dev.w > 0 && dev.h > 0 ? [dev.w / 2, dev.h / 2] : [1920, 1080];
        const k = Math.max(1, 720 / Math.min(w, h));
        [w, h] = [Math.round((w * k) / 2) * 2, Math.round((h * k) / 2) * 2];
        extending = true;
        vdd.addMode(w, h);
        const mon = await vdd.setOn(true).catch(() => null);
        if (!mon || !mon.name) { extending = false; return null; }
        const now = (await vdd.setMode(mon, w, h).catch(() => mon)) || mon;
        return displays.getAllDisplays().find((d) => { const r = rectOf(d); return r.x === now.x && r.y === now.y; })
          || (WAYLAND ? { id: now.name, bounds: { x: now.x, y: now.y, width: now.width, height: now.height }, scaleFactor: 1 } : null);
      },
      release() {
        if (!extending) return;
        extending = false;
        vdd.setOn(false).catch(() => {});
      },
    } : null,
    // The viewer's mouse, keyboard and pen, aimed at the display it watches (the helper's screen pixels).
    touch: true, // the viewer's fingers are real touch here (in.tc → the helper's `touch`)
    input: (bus, target) => {
      const ri = new RemoteInput({
        link: { get peerOs() { return apple(bus.current) ? P.OS.MAC : P.OS.WIN; } },
        helper,
        settings: { pcScreen: { input: true }, get keys() { return settings().keys; } },
        inputAllowed: () => settings().web.control !== false && home(),
      });
      const at = (r, x, y) => ({ x: Math.round(r.x + x * (r.width - 1)), y: Math.round(r.y + y * (r.height - 1)) });
      for (const ty of RemoteInput.TYPES) bus.on(`t:${ty}`, (m) => {
        if (m.wid != null) return;
        const d = target();
        if (!d) return;
        const r = rectOf(d);
        ri.handle(m, (x, y) => helper.send('moveTo', at(r, x, y)), null, (x, y, pen) => helper.send('pen', { ...at(r, x, y), pen }),
          false, (list) => helper.send('touch', RemoteInput.touchCmd(list, (x, y) => at(r, x, y))));
      });
      bus.on('closed', () => ri.release());
      return ri;
    },
    deck: c.deck, // the Deck (shared/deck.js), none while its module is off
    remote: (bus, getSettings) => new PhoneRemote({ server: bus, helper, getSettings, atHome: home, onChange: c.pushState,
      loadPad: () => require('./gamepad'), save: c.save }),
    notifs: c.notifs && c.notifs.want ? c.notifs : null,
    devLocal: (c.devctl() && c.devctl().local) || new DevLocal(),
    smbInfo,
    share,
    key: (code) => {
      helper.send('inject', { ev: { t: P.T.K_KEY_DOWN, code } });
      helper.send('inject', { ev: { t: P.T.K_KEY_UP, code } });
    },
    vcam: c.loadVcam || null,
    airplay: airplayHost({ dir: app.getPath('userData'), name: () => c.device().name, t: c.t, pushState: c.pushState,
      opts: () => { const w = settings().web; return { music: w.airplayMusic !== false, sound: w.airplaySound !== false, full: w.airplayFull === true }; } }),
    fileClip: c.fileClip && c.fileClip.offerLocal ? c.fileClip : null,
  });
  // An iPhone's or iPad's Show screen: its Screen Mirroring can come here instead (shared/nativescreen.js).
  require('../shared/nativescreen.js').NativeScreen.airplay = () => {
    if (!settings().web.airplay) web.actions.webAirplaySet(true);
    return c.device().name;
  };
  for (const [name, fn] of Object.entries(web.actions)) ipcMain.handle(name, (_e, arg) => fn(arg));
  return web;
}

module.exports = { setupWeb };