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.7 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Creates the helper-backed services and wires them together: display, stream, Monitor 2 input,
// clipboard, shared cursor/keyboard. Restarts the helper if it dies and keeps the display
// awake while a PC is connected.
'use strict';

const { powerSaveBlocker } = require('electron');
const { Helper } = require('./helper');
const { Displays } = require('./displays');
const { Stream } = require('./stream');
const { Input } = require('./input');
const { SpaceSwitch, SpaceLook, DesktopRefresh } = require('./space-switch');
const P = require('../shared/protocol.js');
const Spaces = require('../shared/mac-spaces.js');
const { Clipboard } = require('./clipboard');
const { Kvm } = require('./kvm');
const { Terminal } = require('./terminal');
const { Drop } = require('./drop');
const { Smb } = require('./smb');
const { Apps } = require('./apps');
const { SshClient } = require('./ssh-client');
const { AudioHub } = require('./audiohub');
const { Audio } = require('./audio');
const { FileSend } = require('./filesend');
const { PcView } = require('./pcview');
const { PcApps } = require('./pcapps');
const { Notifs } = require('./notifs');
const { FileClip } = require('./fclip');
const { Wake } = require('./wake');
const { AppSend } = require('./appsend');
const store = require('./store');

function startServices({ server, getSettings, pushState, onHelperReady, clipboardPair }) {
  const s = getSettings;
  server.setMaxListeners(50); // one 'client'/'closed' listener per feature
  const helper = new Helper();
  require('../shared/usbadb.js').watch(helper); // a phone on the USB cable: IOKit tells (no ioreg every 2 s)
  const displays = new Displays(helper, s);
  const hub = new AudioHub(helper, s);
  const stream = new Stream(server, displays, s, hub);
  let kvm = null;
  // Stream input only when "Receive input" is on and shared input is home.
  const input = new Input(server, helper, displays, {
    enabled: () => s().streamInput !== false && (!kvm || kvm.mode === 'home'),
    swapKeys: () => server.keySwap(s()), // never between two Macs
  });
  // Previous/next desktop on the display this viewer is being shown. Same gate as stream input.
  const spaces = new SpaceSwitch({
    listen: (fn) => server.on(`t:${P.T.SCREEN_SPACE}`, fn),
    helper,
    enabled: () => s().streamInput !== false && (!kvm || kvm.mode === 'home'),
    authorize: (ctx) => Spaces.streamInputGate(ctx, () => server.current),
    targetFor: () => stream.viewedDisplay(),
    reply: (ctx, msg) => server.send(ctx, msg),
    names: () => Spaces.catalogOffer(displays.list(), { remote: s().sharing.remote !== false, held: displays.holds.has('apps-open') }).named,
    offerDisplays: () => Spaces.catalogOffer(displays.list(), { remote: s().sharing.remote !== false, held: displays.holds.has('apps-open') }).offerDisplays,
  });
  const spaceLook = new SpaceLook(helper, pushState);
  const desktopRefresh = new DesktopRefresh({
    listen: (fn) => server.on(`t:${P.T.SCREEN_DESKTOPS}`, fn),
    authorize: (ctx) => Spaces.streamInputGate(ctx, () => server.current),
    viewFor: () => stream.viewedDisplay(),
    spaceLook,
    reply: (ctx, msg) => server.send(ctx, msg),
  });

  const clipboard = new Clipboard(server, helper, s, clipboardPair);
  const drop = new Drop({ server, helper, displays, getSettings: s });
  const fileSend = new FileSend(server, s, { outboxFile: require('path').join(require('electron').app.getPath('userData'), 'outbox.json') });
  kvm = new Kvm({ server, helper, getSettings: s, clipboard, input, drop, fileSend });
  require('../shared/applog.js').linkStats(() => kvm.linkSample()); // the link's line in the log every 30 s
  const terminal = new Terminal(server, s);
  const smb = new Smb({ server, helper, getSettings: s, saveSettings: () => store.saveSettings(s()) });

  const apps = new Apps({ server, helper, displays, stream, getSettings: s });
  const sshClient = new SshClient(server, s);
  const audio = new Audio({ server, hub, stream, getSettings: s, saveSettings: () => store.saveSettings(s()) }); // save: the mixer's routes
  // This Mac's sound on more of its own speakers (Audio › This device › Choose devices), from the helper's capture,
  // which leaves TwinDesk out: nothing played here is heard again.
  const ownSound = new (require('../shared/own-sound.js').OwnSound)({ settings: s, save: () => store.saveSettings(s()), onChange: () => audio.emit('change'), capture: hub, dir: __dirname, unsupported: 'The Mac’s sound capture isn’t running (Screen Recording for TwinDesk?), so nothing plays on more speakers' });
  ownSound.apply();
  const pcView = new PcView({ server, getSettings: s, saveSettings: () => store.saveSettings(s()) });
  const pcApps = new PcApps({ server, getSettings: s });
  const notifs = new Notifs({ server, helper, getSettings: s, saveSettings: () => store.saveSettings(s()) });
  // History › Keep history: the clipboard's and notifications' history kept, encrypted (shared/histkeeper.js).
  const history = new (require('../shared/histkeeper.js').HistoryKeeper)({ dir: require('electron').app.getPath('userData'), clip: clipboard, notifs, changed: pushState });
  const fileClip = new FileClip({ server, helper, fileSend, drop, getSettings: s });
  kvm.fileClip = fileClip;
  fileClip.kvm = kvm; // the shortcut while the pointer is over there (keyboard not shared)
  const appSend = new AppSend({ server, helper, displays, getSettings: s }); // This Mac's apps on another computer
  const wake = new Wake({ server, getSettings: s, saveSettings: () => store.saveSettings(s()) });
  kvm.blockEdge = () => pcView.focused || pcApps.focused; // moving inside the PC window never crosses to the PC

  for (const x of [stream, clipboard, kvm, terminal, drop, fileSend, smb, apps, sshClient, audio, pcView, pcApps, notifs, fileClip, wake, appSend]) x.on('change', pushState);
  displays.on('change', () => {
    input.releaseAll(); // the shared display moved or changed size mid-press
    pushState();
  });

  // Helper lifecycle: (re)create the virtual display and restart the stream after every start.
  helper.on('ready', () => {
    displays.applyVirtual().then(() => stream.restart('helper started'));
    onHelperReady();
    pushState();
  });
  const exits = [];
  helper.on('exit', () => {
    pushState();
    if (helper.stopping) return;
    const now = Date.now();
    exits.push(now);
    while (exits.length && now - exits[0] > 30000) exits.shift();
    const delay = exits.length <= 2 ? 1000 : exits.length <= 5 ? 3000 : 10000;
    console.log(`[services] helper exited — restarting in ${delay / 1000} s`);
    setTimeout(() => helper.start(), delay);
  });

  // Keep the display awake while a PC is connected, or Always (app.keepAwakeAlways).
  let blocker = null;
  function updateAwake() {
    const want = s().app.keepAwake !== false && (s().app.keepAwakeAlways === true || !!server.current);
    if (want && blocker === null) blocker = powerSaveBlocker.start('prevent-display-sleep');
    if (!want && blocker !== null) {
      powerSaveBlocker.stop(blocker);
      blocker = null;
    }
  }
  server.on('client', updateAwake);
  server.on('closed', updateAwake);
  updateAwake(); // Always: from startup, nothing connected

  helper.start();

  return {
    ownSound,
    helper, displays, stream, input, spaces, spaceLook, desktopRefresh, clipboard, kvm, terminal, drop, smb, apps, sshClient, audio, pcView, pcApps, hub, fileSend, notifs, history, fileClip, wake, appSend, updateAwake,
    shutdown() {
      pcView.shutdown();
      pcApps.shutdown();
      appSend.shutdown();
      kvm.shutdown();
      hub.shutdown(); // unmute this Mac if we muted it while sending
      stream.stop('off');
      helper.stop(); // closes stdin: the helper exits and the virtual display goes away
    },
  };
}

module.exports = { startServices };