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.

31.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Main-window actions (preload-app.js → here). Every value is validated by settings.apply().
const { ipcMain, dialog, shell, BrowserWindow, clipboard, Menu, app } = require('electron');
const path = require('path');
const P = require('../shared/protocol.js');
const { receivedDir } = require('../shared/received.js');
const { LINKS } = require('../shared/about.js');
const { apply } = require('./settings');

// ctx: link, discovery, screen, clip, kvm, terminal, fileDrop, smb, apps, phone, phoneViews, connectPhoneDev(d), settings, save(), push(), buildState(),
//      checkFirewall(), fixFirewall(), setStartup(on)
function setupIpc(ctx) {
  const { link, discovery, screen, clip, kvm, sshd, fileDrop, smb, apps, sound, pcScreen, pcApps, peerApps, vdd, notifs, fileClip, wake, settings } = ctx;

  const handle = (name, fn) => ipcMain.handle(name, (_e, ...args) => fn(...args));
  const change = (section, partial, after) => {
    if (!apply(settings, section, partial)) return;
    ctx.save();
    if (after) after();
    ctx.push();
  };

  handle('getState', () => ctx.buildState());
  // Biometric unlock from this PC (shared/unlock-client.js): Unlock other computers, and Unlock.
  handle('unlocker', (op, arg) => {
    const u = ctx.unlocker && ctx.unlocker();
    if (!u) return null;
    if (op === 'on') return u.setOn(arg === true);
    if (op === 'unlock') return u.want(String(arg));
    return u.state();
  });
  // A local UI preference: never synchronized to another device.
  handle('setLanguage', (language) => {
    if (!require('../shared/i18n.js').savedLanguage(language)) return;
    change('ui', { language }, () => ctx.onLanguage());
  });
  // General › Appearance: { style }, { theme } and/or { accent } ('' follows the system); local only.
  handle('setLook', (o) => o && typeof o === 'object' && change('ui', {
    ...(typeof o.style === 'string' ? { style: o.style } : {}), ...(typeof o.theme === 'string' ? { theme: o.theme } : {}), ...(typeof o.accent === 'string' ? { accent: o.accent } : {}),
  }, () => ctx.onLook && ctx.onLook()));
  // Calls, Messages and Photos (shared/phonehub.js, loaded the first time it's used).
  handle('hub', (r) => ctx.hub().act(r));

  // via: one of its routes (Found nearby lists each network it is on), else the best one.
  const pairWith = (d, via) => {
    discovery.clearInvite(d.id);
    if (P.isPhoneOs(d.os)) return ctx.connectPhoneDev(d); // a phone has no server to pair with
    const address = via && (d.routes || []).some((r) => r.address === via) ? via : d.address;
    link.startPairing({ address, port: d.port, macName: d.name, id: d.id, route: via && address === via ? via : '' }); // id: one met over Bluetooth
  };
  handle('pair', (target, via) => {
    if (typeof target !== 'string' || !target.trim()) return;
    const found = discovery.get(target) || discovery.near(target);
    if (found) return pairWith(found, typeof via === 'string' ? via : '');
    const m = /^\s*([^\s:]+)(?::(\d{1,5}))?\s*$/.exec(target);
    if (!m) return;
    const port = m[2] ? Number(m[2]) : P.PORT;
    if (port < 1 || port > 65535) return;
    link.startPairing({ address: m[1], port, macName: m[1] });
  });
  // Connect by address: ask who is there (unicast probe works where broadcast is blocked); no
  // answer in PROBE_REPLY_MS → try WSS on that address directly ("No TwinDesk at …" if nothing).
  handle('connectAddress', async (text) => {
    const m = typeof text === 'string' && /^\s*([^\s:]+)(?::(\d{1,5}))?\s*$/.exec(text);
    if (!m) return;
    const d = m[2] ? null : await discovery.ask(m[1]);
    if (d) return pairWith(d);
    const port = m[2] ? Number(m[2]) : P.PORT;
    if (port >= 1 && port <= 65535) link.startPairing({ address: m[1], port, macName: m[1] });
  });
  handle('refreshFound', () => discovery.refresh());
  // A chat's answer (Messages' chat apps: shared/chats.js) or a notification's.
  handle('notifReply', (r) => r && typeof r === 'object' && (r.chat ? !!(ctx.chats && ctx.chats() && ctx.chats().reply(String(r.chat), r.text, r.image, r.remove === true))
    : r.dismiss ? notifs.dismiss(String(r.id || '')) : Number.isInteger(r.act) ? notifs.act(String(r.id || ''), r.act) // Overview's × and buttons (shared/notifacts.js)
      : notifs.reply(String(r.id || ''), r.text))); // a phone chat's Reply, typed here
  handle('qrPair', () => ctx.qrPair());
  handle('adbQr', (on) => ctx.adbQr(on === true)); // wireless debugging: pair with a QR code // Connection: the phone pairing QR code's link
  handle('importCancel', () => ctx.explorer() && ctx.explorer().cancel()); // Phone Files: stop importing into Explorer's folder
  // TwinDesk iPhone (shared/iossign.js): one action, and Choose an IPA….
  handle('iosSign', (o) => require('../shared/iossign-host.js').act(ctx.iosSign && ctx.iosSign(), dialog, o));
  handle('iosSignIpa', () => require('../shared/iossign-host.js').pickIpa(ctx.iosSign && ctx.iosSign(), dialog));
  handle('deviceDo', (c) => c && typeof c === 'object' && ctx.devctl() && ctx.devctl().do(c)); // Overview: ring, lock, quick settings… (shared/devctl.js)
  handle('copyText', (text) => typeof text === 'string' && text.length < 1000 && clipboard.writeText(text));
  // Activity copies a notification or a call. Text only, capped, never a path and never a shell.
  handle('copyLiteral', (text) => {
    if (typeof text !== 'string' || !text || text.length > 256 * 1024) return;
    clipboard.writeText(text);
  });
  handle('confirmCode', () => link.confirmCode());
  handle('cancelPair', () => { ctx.cancelPhoneInvite(); link.cancelPair(); });
  handle('forget', () => {
    ctx.proximityLock?.cancel();
    link.forget();
    sshd.revokeAll(); // forgotten: it may not log in any more
  });
  // Disconnect (either side of the session); Connect again / Take over the computer we're a guest of.
  handle('disconnect', () => { ctx.proximityLock?.cancel(); return link.disconnect(); });
  handle('connectAgain', () => link.connect(true));
  handle('setRoute', (address) => link.setRoute(address)); // Paired › Network: '' automatic, or one of its addresses
  // Connect on a paired device in our list that connects to us: a phone is asked as usual, a
  // computer is invited and its hello takes the session over.
  handle('connectGuest', (id) => {
    if (typeof id !== 'string') return;
    const d = discovery.get(id) || discovery.near(id);
    if (!d) return;
    if (P.isPhoneOs(d.os)) return ctx.connectPhoneDev(d);
    link.expect(id);
    discovery.invite(d.address);
  });
  handle('respondPair', (allow) => link.respondPair(allow === true)); // host: Allow / Deny
  handle('forgetGuest', (id) => {
    if (typeof id !== 'string') return false;
    ctx.batteryAlerts.forget(id);
    return link.forgetGuest(id);
  });
  handle('wakePeer', (id) => typeof id === 'string' && wake.wake(id));
  handle('setWake', (on) => wake.set(on === true)); // A switch
  handle('checkWake', () => wake.check());
  handle('openMonitor', () => screen.open(false));
  handle('remoteScreen', (arg) => arg && typeof arg === 'object' && screen.control({ share: arg.share, mode: arg.mode })); // screen.ctl

  handle('setKvm', (partial) => {
    if (partial && typeof partial.linked === 'boolean') kvm.setLinked(partial.linked); // home first, tells the other side
    if (partial && typeof partial.shared === 'boolean') kvm.setShared(partial.shared); // the Cursor tab's switch (Over Bluetooth through it)
    if (partial && typeof partial.locked === 'boolean') kvm.setLocked(partial.locked); // cursor lock: not a setting
    const { linked, shared, locked, ...rest } = partial && typeof partial === 'object' ? partial : {};
    change('kvm', rest, () => kvm.applyConfig());
    if ('keyboard' in rest) (ctx.phoneRemote ? ctx.phoneRemote.refresh() : ctx.loadRemote()); // voice typing follows Keyboard
  });
  handle('setLayout', (side) => kvm.setLayout(side));
  handle('setPortals', (arg) => arg && typeof arg === 'object' && kvm.setPortals(arg.rules, arg.peer)); // Cursor portals (kvm.js)
  handle('moveKvm', (arg) => arg && typeof arg === 'object' && kvm.moveTo(arg.side, Number(arg.along))); // the crossing map
  handle('identifyDisplays', () => kvm.map.identify());
  handle('setKeys', (partial) => change('keys', partial, () => kvm.applyConfig())); // the hotkey lives in the helper
  handle('setApp', (partial) => {
    if (!partial || typeof partial !== 'object') return;
    const { proximityLock, ...appSettings } = partial;
    change('app', appSettings, () => ctx.onApp && ctx.onApp());
  });
  handle('setProximityLock', (on) => {
    if (typeof on !== 'boolean' || (on && !ctx.proximityLock?.supported)) return;
    if (!on) ctx.proximityLock?.cancel();
    change('app', { proximityLock: on }, () => ctx.proximityLock?.apply?.()); // Linux: the session watcher starts or stops
  });
  handle('setUpdates', (partial) => {
    const p = partial || {};
    const next = {};
    if (typeof p.auto === 'boolean') next.auto = p.auto;
    if (typeof p.skipped === 'string') next.skipped = p.skipped;
    if (typeof p.install === 'boolean') next.install = p.install;
    change('updates', next, () => { if ('install' in next) ctx.updates.setInstall(next.install); ctx.updates.start(); });
  });
  handle('skipUpdate', (version) => ctx.updates && ctx.updates.skip && ctx.updates.skip(version));
  handle('unskipUpdate', () => ctx.updates && ctx.updates.unskip && ctx.updates.unskip());
  handle('checkUpdates', () => ctx.updates.check(true));
  handle('openUpdate', () => ctx.updates.open());
  handle('openLink', (key) => (key === 'logs' ? require('../shared/applog.js').open() : Object.hasOwn(LINKS, key) && shell.openExternal(LINKS[key]))); // About page: only its own links, and the log folder
  handle('setMonitor', (partial) => change('monitor', partial, () => { screen.applyAudio(); pcScreen.apply(); })); // apply(): Playback › Steady takes a new session (pcscreen.js)
  handle('setClipboard', (partial) => change('clipboard', partial, () => clip.applySettings()));
  handle('copyHistory', (index) => clip.copyHistory(Number(index)));
  handle('openClip', (index) => { // Recent's Open / Email / Call (shared/clipact.js): from the app's own copy
    const h = (clip.history || [])[Number(index)];
    const a = h && !h.image && require('../shared/clipact.js').of(h.text);
    if (a) shell.openExternal(a.url);
  });
  handle('clearHistory', () => clip.clearHistory());
  handle('history', (r) => { if (r && typeof r === 'object' && ctx.history) ctx.history(r); });
  handle('setTab', (tab) => change('ui', { tab }));
  handle('setChats', (on) => { change('ui', { chats: on === true }); if (ctx.chats && ctx.chats()) ctx.chats().sync(); }); // Messages: WhatsApp, Telegram and Instagram there too
  handle('setOverview', (o) => o && typeof o === 'object' && change('ui', { overview: { ...settings.ui.overview, ...o } })); // General › Overview // invalid names fall back in normalize()
  handle('setMulti', (on) => require('./multi').set(on === true)); // Multi-device: TwinDesk restarts
  // The Deck page (shared/ui-deck.js): the layout, Try (runs a button here), the app picker.
  handle('deckSave', (layout) => { const d = ctx.deck && ctx.deck(); if (d && layout && typeof layout === 'object') d.save(layout); });
  handle('deckTry', (action) => { const d = ctx.deck && ctx.deck(); if (d && action && typeof action === 'object') d.exec(action).catch(() => {}); });
  handle('deckApps', () => { const d = ctx.deck && ctx.deck(); return d ? d.apps().catch(() => []) : []; });
  handle('deckPick', async (o) => { // the Deck page: a file, folder or script for a tile (its path stays here)
    const { dialog, BrowserWindow } = require('electron');
    const kind = o && o.kind;
    const r = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow() || undefined, {
      properties: kind === 'folder' ? ['openDirectory'] : kind === 'any' ? ['openFile', 'openDirectory'] : ['openFile'],
      ...(kind === 'script' ? { title: 'Choose a script', buttonLabel: 'Choose' } : {}),
    });
    return r.canceled || !r.filePaths.length ? '' : r.filePaths[0];
  });
  handle('deckRun', (a) => { const d = ctx.deck && ctx.deck(); return d && a && typeof a === 'object' ? d.exec(a).then(() => ({ ok: true }), (e) => ({ ok: false, why: e.message })) : { ok: false }; }); // Try
  handle('deckState', (obs) => { const d = ctx.deck && ctx.deck(); return d ? d.state(obs === true, obs === 'mix').catch(() => ({})) : {}; }); // sound devices, Bluetooth devices, displays (OBS's: obs; each app's volume: 'mix')
  handle('deckGitHub', (v) => { const d = ctx.deck && ctx.deck(); return d && d.gitHub && (v === undefined || v === null || typeof v === 'string') ? d.gitHub(v) : { hasToken: false }; }); // the Build widget's GitHub token: kept sealed, never sent back
  handle('deckObs', () => { const d = ctx.deck && ctx.deck(); return d ? d.obsConfig() : null; }); // OBS Studio's port, and whether a password is kept
  handle('deckSetObs', (v) => { const d = ctx.deck && ctx.deck(); return d && v && typeof v === 'object' ? d.setObs(v) : { on: false }; }); // → OBS's state with them
  // General › Modules (shared/modules.js): {id, on, wasOn} a switch, {restored: id} its page is back on.
  handle('setModules', (m) => {
    if (!m || typeof m !== 'object') return;
    const Mods = require('../shared/modules.js');
    settings.modules = typeof m.restored === 'string' ? Mods.restored(settings.modules, m.restored) : Mods.set(settings.modules, String(m.id), m.on === true, m.wasOn === true);
    ctx.save();
    ctx.push();
  });
  handle('setEncoder', (hw) => { require('./encoder').write(hw !== false); ctx.push(); }); // General › Advanced › Hardware encoder (#133): applies after a restart
  handle('relaunch', () => { app.relaunch({ args: process.argv.slice(1).filter((a) => a !== '--hidden') }); app.quit(); }); // General › Advanced: a setting read at startup
  handle('setAudio', (partial) => change('audio', partial, () => {
    sound.apply();
    const mic = ctx.loadMic && ctx.loadMic(); // Microphone: loaded when first on
    if (mic) mic.apply();
    if (partial && ('micReceive' in partial || 'micOut' in partial) && ctx.phone && ctx.phone.bridge && ctx.phone.bridge._sound) ctx.phone.bridge._sound(); // a phone's microphone, now
    // Loaded when first turned on (applied then); off, the loaded one stops.
    if (partial && 'phoneMedia' in partial && ctx.nowPlaying) ctx.nowPlaying.apply(); else if (partial && 'phoneMedia' in partial) ctx.loadNowPlaying();
    if (partial && 'phoneBt' in partial && ctx.btAudio) ctx.btAudio.apply(); else if (partial && 'phoneBt' in partial) ctx.loadBtAudio();
  }));
  // Audio › the mixer (shared/ui-sound-mix.js): a device's speakers for our sound (out) or ours for its (in);
  // this computer's own speakers' volume (read with no level).
  handle('soundRoute', (o) => { if (o && typeof o === 'object' && typeof o.id === 'string' && (Array.isArray(o.outs) || o.outs === null)) sound.setRoute(o.dir === 'in' ? 'in' : 'out', o.outs); ctx.push(); });
  handle('soundSpeakers', (list) => { if (Array.isArray(list) && list.length <= 32 && sound.setSpeakers) sound.setSpeakers(list); }); // this computer's speakers, from the settings window (every device's mixer lists them)
  handle('soundOwn', (v) => { const o = ctx.ownSound && ctx.ownSound(); if (!o) return; if (Array.isArray(v) && v.length <= 8) o.set(v); else if (v && typeof v === 'object' && typeof v.mode === 'string') o.mode(v.mode); else if (v && typeof v === 'object' && typeof v.def === 'string') o.setDefault(v.def); ctx.push(); }); // This device: System default or Choose devices, the speakers picked (own-sound.js)
  handle('soundVolume', (level) => require('../shared/sound-local.js').volume(process.platform, kvm.helper, level).catch(() => ({ volume: null })));
  handle('phoneMedia', (m) => m && ctx.nowPlaying && ctx.nowPlaying.control(String(m.a || ''), m.pos));
  handle('phoneBtPick', (id) => typeof id === 'string' && id && ctx.btAudio && ctx.btAudio.pick(id));
  // Camera tab: the other computer's camera here, this one's there (shared/camshare.js).
  // Camera & Controller › Controller (shared/pad-share.js): the states read in the window, and its settings.
  ipcMain.on('padState', (_e, st) => { const p = ctx.padShare && ctx.padShare(); if (p) p.fromWindow(st); });
  handle('setPads', (o) => { const p = ctx.padShare && ctx.padShare(); if (p && o && typeof o === 'object') p.set(o); });
  handle('camera', (m) => {
    if (m && m.do === 'on') return ctx.setCamera(m.on === true); // Camera's switch: loads it, or stops it
    const c = ctx.camShare;
    if (!c || !m || typeof m !== 'object') return;
    if (m.do === 'view') c.view(m.show === true); // show: its window too
    else if (m.do === 'close') c.closeView();
    else if (m.do === 'share') c.setShare(m.on === true);
    else if (m.do === 'device') c.setDevice(m.id);
    else if (m.do === 'stop') c.stopSending();
    else if (m.do === 'devices') c.listDevices();
    // Camera › Virtual camera (shared/vcam.js).
    else if (m.do === 'virtual' && ctx.vcam) ctx.vcam.setOn(m.on === true);
    else if (m.do === 'vcamRemove' && ctx.vcam) ctx.vcam.remove();
    else if (m.do === 'rotate' && ctx.vcam) ctx.vcam.turn();
    else if (m.do === 'mirror' && ctx.vcam) ctx.vcam.setMirror(m.on === true);
  });
  // ReZume tab (shared/rezume.js): loaded when it's first turned on.
  handle('setReZume', (m) => change('rezume', m && typeof m === 'object' ? m : {}, () => (ctx.rezume ? ctx.rezume.apply() : ctx.loadReZume())));
  handle('rezumeDo', (m) => {
    const h = ctx.rezume;
    if (!h || !m) return;
    if (m.a === 'take') h.take();
    else if (m.a === 'dismiss') h.dismiss();
    else if (m.a === 'push') h.push();
    // ReZume › Allowed apps: one app let through or not, or forgotten (no app: the whole list).
    else if (m.a === 'allow' && typeof m.app === 'string') h.allow(m.list, m.app, m.on === true);
    else if (m.a === 'forget') h.forget(m.list, typeof m.app === 'string' ? m.app : '');
  });
  // Remote tab: the phone's Remote page here (shared/phone-remote.js).
  handle('setRemote', (m) => {
    if (!m || typeof m !== 'object') return;
    // Off at start: not loaded; turned on, it loads (and answers the phone).
    if ('allow' in m && !ctx.phoneRemote && m.allow === true) { ctx.settings.remote.allow = true; ctx.loadRemote(); }
    else if ('allow' in m && ctx.phoneRemote) ctx.phoneRemote.setAllow(m.allow === true);
    if ('pad' in m && ctx.phoneRemote) ctx.phoneRemote.setPad(m.pad === true); // Real gamepad
    if ('padKind' in m && ctx.phoneRemote) ctx.phoneRemote.setPadKind(m.padKind === 'ds4' ? 'ds4' : 'xbox'); // Xbox 360 or DualShock 4 (#266)
    ctx.save();
    ctx.push();
  });
  handle('setTerminal', (partial) => {
    const p = partial && typeof partial === 'object' ? { enabled: partial.enabled, allowMac: partial.allowMac } : {};
    Object.keys(p).forEach((k) => p[k] === undefined && delete p[k]);
    change('terminal', p, () => { if (ctx.terminal) ctx.terminal.apply(); else ctx.loadTerminal(); sshd.apply(); });
  });
  handle('setupSshd', () => sshd.setup());
  handle('openTerminal', () => ctx.terminal && ctx.terminal.open());
  handle('setFiles', (partial) => {
    // shareOn/shareFolder only change through share()/unshare()
    const p = partial && typeof partial === 'object' ? { dropToMac: partial.dropToMac, mountMac: partial.mountMac, acceptFromMac: partial.acceptFromMac, edgeDrag: partial.edgeDrag,
      shortcuts: partial.shortcuts, copyKeys: partial.copyKeys, pasteKeys: partial.pasteKeys, plain: partial.plain, outboxHours: [0, 1, 24, 168].includes(partial.outboxHours) ? partial.outboxHours : undefined, clipReceived: typeof partial.clipReceived === 'boolean' ? partial.clipReceived : undefined , shelf: typeof partial.shelf === 'boolean' ? partial.shelf : undefined } : {};
    Object.keys(p).forEach((k) => p[k] === undefined && delete p[k]);
    change('files', p, () => { smb.applyMount(); kvm.applyConfig(); fileClip.apply(); link.setPlain(settings.files.plain === true); });
  });
  // File Sharing › TwinDesk Drive (shared/drive-host.js): loaded when turned on, and only then.
  handle('setDrive', async (on) => {
    const d = on === true ? ctx.loadDrive() : ctx.getDrive();
    if (d) await d.setOn(on === true);
    else { settings.drive.on = false; ctx.save(); }
    ctx.push();
  });
  const setDriveFolder = async (f) => {
    const d = ctx.getDrive();
    if (d) await d.setFolder(f);
    else { settings.drive.folder = f; ctx.save(); }
    ctx.push();
  };
  handle('pickDriveFolder', async () => {
    const r = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), { properties: ['openDirectory', 'createDirectory'] });
    if (!r.canceled && r.filePaths[0]) await setDriveFolder(r.filePaths[0]);
  });
  handle('resetDriveFolder', () => setDriveFolder(''));
  // File Sharing › Shared folders and the Share folder sheet (shared/folders-host.js).
  for (const n of ['folderShare', 'folderSheet', 'folderAdd', 'folderRemove', 'folderDevices', 'folderAccept', 'folderDecline', 'folderOpen']) handle(n, (a) => { const f = ctx.folders && ctx.folders(); return f ? f.actions[n](a) : undefined; });
  handle('openDriveFolder', () => { const d = ctx.getDrive(); if (d) shell.openPath(d.folder()); });
  // Send files (paths from the drop zone or Choose…), notifications.
  const sendFiles = (paths) => {
    const list = (Array.isArray(paths) ? paths : []).filter((p) => typeof p === 'string' && path.win32.isAbsolute(p)).slice(0, 1000);
    if (list.length) fileDrop.send(list); // now, or when the device is back (shared/outbox.js)
  };
  handle('sendFiles', sendFiles);
  handle('chooseSendFiles', async () => {
    const win = BrowserWindow.getFocusedWindow();
    const r = await dialog.showOpenDialog(win, { title: 'Send files', buttonLabel: 'Send', properties: ['openFile', 'multiSelections'] });
    if (!r.canceled) sendFiles(r.filePaths);
  });
  handle('setNotifs', (partial) => {
    const p = partial && typeof partial === 'object' ? { send: partial.send, receive: partial.receive, hideText: partial.hideText } : {};
    Object.keys(p).forEach((k) => p[k] === undefined && delete p[k]);
    if (partial && typeof partial.batteryAlerts === 'boolean') p.batteryAlerts = partial.batteryAlerts;
    Object.assign(p, require('../shared/notifrules.js').clean(partial, settings.notifs)); // style, otpCopy, quiet, phoneApps
    change('notifs', p, () => {
      ctx.batteryAlerts.setting(settings.notifs.batteryAlerts);
      notifs.applySettings();
    });
  });
  handle('muteNotifApp', (arg) => arg && typeof arg.app === 'string' && notifs.setMuted(arg.app.slice(0, 300), arg.muted === true));
  handle('clearNotifHistory', () => notifs.clearHistory && notifs.clearHistory());
  handle('openNotifiedApp', (arg) => arg && typeof arg.app === 'string' && ctx.phoneViews && ctx.phoneViews.openNotified(arg.app.slice(0, 200), String(arg.appName || '').slice(0, 100)));
  // General › Received files (shared/received.js): chosen here only, never by the page itself.
  handle('chooseReceivedFolder', async () => {
    const win = BrowserWindow.getFocusedWindow();
    const r = await dialog.showOpenDialog(win, { title: 'Folder for received files', buttonLabel: 'Use this folder',
      defaultPath: receivedDir(settings, app.getPath('downloads')), properties: ['openDirectory', 'createDirectory'] });
    if (!r.canceled && r.filePaths[0]) change('files', { receivedFolder: r.filePaths[0] });
  });
  handle('resetReceivedFolder', () => change('files', { receivedFolder: '' }));
  handle('openReceivedFolder', () => shell.openPath(receivedDir(settings, app.getPath('downloads'))));
  handle('setShareOn', (on) => smb.setShareOn(on === true));
  handle('chooseShareFolder', async () => {
    const win = BrowserWindow.getFocusedWindow();
    const r = await dialog.showOpenDialog(win, { title: 'Folder to share with the other computer', properties: ['openDirectory', 'createDirectory'] });
    if (!r.canceled && r.filePaths[0]) await smb.chooseFolder(r.filePaths[0]);
  });
  handle('removeShare', () => smb.unshare());
  handle('openMacDrive', () => (smb.drive ? shell.openPath(smb.drive + '\\') : smb.openOverWifi && smb.openOverWifi())); // through Bluetooth: Wi-Fi Direct first
  handle('cancelDrop', () => fileDrop.cancel());
  handle('pauseSend', (batch) => typeof batch === 'string' && fileDrop.pause(batch));
  handle('resumeSend', (id) => typeof id === 'string' && fileDrop.resume(id));
  handle('forgetSend', (id) => typeof id === 'string' && fileDrop.forget(id));
  // Activity › Show in Explorer: index into the received list, never a path from the page.
  handle('revealDrop', (index) => {
    const recv = ctx.fileRecv;
    if (recv && typeof recv.reveal === 'function') recv.reveal(index);
  });
  handle('clearFiles', () => ctx.clearFiles && ctx.clearFiles());
  handle('showFileShelf', (view) => ctx.showFileShelf && ctx.showFileShelf({ view: view === 'shelf' ? 'shelf' : 'recent' })); // File Shelf (shared/file-shelf.js)
  // With another PC the apps come through peerapps.js (no Monitor 2 or Start pinning).
  const pcPeer = () => link.peerOs !== P.OS.MAC; // a PC or a Linux computer
  handle('listApps', () => (pcPeer() ? peerApps.refresh() : apps.refresh()));
  handle('launchApp', (id) => { if (pcPeer()) peerApps.launch(id); else { apps.launch(id); screen.ensureHidden(); } });
  handle('pinApp', (id) => typeof id === 'string' && !pcPeer() && apps.pin(id, true)); // Pin to Start
  handle('setPcScreen', (partial) => {
    const size = settings.pcScreen.extendSize;
    change('pcScreen', partial, () => { pcScreen.applyInput(); if (!settings.pcScreen.input) pcApps.input.release(); if (settings.pcScreen.extendSize !== size) pcScreen.sizeExtend(); else pcScreen.apply(); });
  });
  handle('setMacApps', (partial) => change('macApps', partial, () => peerApps.apply()));
  handle('setPcApps', (partial) => change('pcApps', partial, () => { pcApps.apply(); pcApps.input.release(); if (peerApps) peerApps.apply(); }));
  handle('setPcScreenMode', (mode) => pcScreen.setMode(mode));
  // A phone as the peer (phone.js, phone-bridge.js, phoneview.js; there once our server runs)
  const phone = (name, fn) => handle(name, (...args) => (ctx.phone ? fn(...args) : undefined));
  phone('connectPhone', (id) => { ctx.proximityLock?.cancel(); return ctx.phone.connect(String(id)); });
  phone('disconnectPhone', () => { ctx.proximityLock?.cancel(); return ctx.phone.disconnect(); });
  handle('setPhone', (partial) => change('phone', partial, () => {
    if (partial && 'input' in partial && ctx.phone) ctx.phone.bridge.tellVia();
    if (partial && ('input' in partial || 'mirror' in partial || 'soundVia' in partial) && ctx.phone) ctx.phone.bridge.modesChanged(); // ADB or Native (shared/phonemodes.js)
    if (partial && 'controls' in partial && ctx.phoneViews) ctx.phoneViews.applyControls(); // the open phone windows move theirs
    if (partial && ('enterSends' in partial || 'arrowSwipe' in partial) && ctx.phoneViews) ctx.phoneViews.applyOpts(); // and light their switches
  }));
  // The phone as a drive (phonedrive.js). The Mount page's switch: off unmounts and stops
  // everything (nothing runs until Mount anyway).
  phone('phoneMount', () => settings.mount.on && ctx.phoneDrive.mount());
  phone('phoneUnmount', () => ctx.phoneDrive.unmount());
  handle('setMount', (partial) => change('mount', partial, () => !settings.mount.on && ctx.phoneDrive && ctx.phoneDrive.stop()));
  phone('phonePair', (arg) => arg && typeof arg === 'object' && ctx.phone.bridge.pair(arg.code, arg.where));
  phone('phoneScreen', (open) => {
    if (open === false) {
      for (const v of ctx.phoneViews.list()) if (v.kind === 'screen') ctx.phoneViews.close(v.id);
    } else ctx.phoneViews.openScreen();
  });
  phone('phoneCamera', (open, opts) => {
    if (open === false) {
      for (const v of ctx.phoneViews.list()) if (v.kind === 'camera') ctx.phoneViews.close(v.id);
    } else ctx.phoneViews.openCamera(opts);
  });
  handle('takePhoto', () => !!ctx.takePhoto && ctx.takePhoto()); // Camera › Take a photo with the phone (shared/phonephoto.js)
  handle('scanDocument', () => !!ctx.scanDocument && ctx.scanDocument()); // Camera › Scan document (shared/phonephoto.js)
  phone('phoneListCameras', () => ctx.phone && ctx.phone.bridge ? ctx.phone.bridge.listCameras() : []);
  phone('phoneOpenApp', (arg) => arg && typeof arg.id === 'string' && ctx.phoneViews.openApp(arg.id.slice(0, 200), String(arg.name || '').slice(0, 100)));
  phone('phoneCloseView', (id) => ctx.phoneViews.close(Number(id)));
  // Right-click on a phone app: open it, or pin it to Start (phoneview.js).
  phone('phoneAppMenu', (arg) => {
    if (!arg || typeof arg.id !== 'string' || !/^[\w.]{1,200}$/.test(arg.id)) return;
    const name = String(arg.name || arg.id).slice(0, 100);
    Menu.buildFromTemplate([
      { label: 'Open in a Window', click: () => ctx.phoneViews.openApp(arg.id, name) },
      { label: 'Pin to Start', click: () => ctx.phoneViews.pin(arg.id, name) },
    ]).popup();
  });
  phone('phoneRetry', () => ctx.phone.bridge.retry()); // also Set Up, when nothing used wireless debugging
  phone('phoneInstallFull', () => ctx.phone.bridge.installFull());
  phone('phoneInstallApps', () => require('../shared/apkinstall.js').choose(ctx.phone.bridge, (s) => (ctx.t ? ctx.t(s) : s))); // Phone › Apps › Install Apps
  phone('phoneScreenAct', (key) => (key === 'rotate' || key === 'screenPower') && ctx.phoneViews.screenAct(key)); // the Phone page's Rotate and Phone screen off
  handle('phoneAssets', () => (ctx.phone ? ctx.phone.assetsView() : { wallpaper: '', apps: [] }));
  handle('installVdd', () => vdd.install());
  handle('removeVdd', () => vdd.remove());
  handle('skipSetup', () => change('setup', { skipped: ctx.buildState().setup.missing, done: true }));
  handle('checkFirewall', () => ctx.checkFirewall());
  handle('fixFirewall', () => ctx.fixFirewall());
  handle('setStartup', (on) => ctx.setStartup(on === true));
  // Not on the same network: Bluetooth on/off, and giving up on moving to Wi-Fi (netlink.js).
  handle('setNet', (partial) => {
    if (partial?.ble === false && settings.net.ble !== false) ctx.proximityLock?.reset();
    change('net', partial, () => ctx.applyNet());
  });
  handle('netCancel', () => { ctx.proximityLock?.reset(); return ctx.net?.cancel(); });
  handle('netJoinHotspot', (arg) => ctx.joinHotspot(arg));
  handle('netLocation', () => shell.openExternal('ms-settings:privacy-location')); // netsh's Wi-Fi commands need it (wifi.js)
  handle('openBluetoothSettings', () => shell.openExternal('ms-settings:bluetooth'));
  // Connect with Wi-Fi Direct (a session on Bluetooth), or back to Bluetooth (the link ends, whatever it was made for).
  // on = 'hotspot': Connect with hotspot (a phone's; the Overview asks for its name and password).
  handle('netWifi', (on) => {
    if (!ctx.net) return;
    if (on) return void ctx.net.need(on === 'hotspot' ? 'hotspot' : 'user');
    ctx.proximityLock?.reset();
    ctx.net.drop();
    if (ctx.pcScreen.mode !== 'off') ctx.pcScreen.setMode('off'); // Bluetooth can't carry the screen
  });

  // pairsync.js applies a value the other computer changed, with the same side effects.
  const AFTER = {
    clipboard: () => clip.applySettings(),
    monitor: () => { screen.applyAudio(); pcScreen.apply(); }, // pacing (pair.sync 'pace'); Steady: a new session
    notifs: () => notifs.applySettings(),
    audio: () => { // pair.sync: the sound, and a phone's microphone (its Audio page's switch)
      sound.apply();
      const mic = ctx.loadMic && ctx.loadMic();
      if (mic) mic.apply();
      if (ctx.phone && ctx.phone.bridge && ctx.phone.bridge._sound) ctx.phone.bridge._sound();
    },
    kvm: () => kvm.applyConfig(),
    pcApps: () => { pcApps.apply(); pcApps.input.release(); },
    pcScreen: () => pcScreen.apply(), // Resolution (pair.sync 'res', with a phone): a new session at that size
    rezume: () => (ctx.rezume ? ctx.rezume.apply() : ctx.loadReZume()),
    remote: () => (ctx.phoneRemote ? ctx.phoneRemote.setAllow(settings.remote.allow) : ctx.loadRemote()),
    terminal: () => { if (ctx.terminal) ctx.terminal.apply(); else ctx.loadTerminal(); sshd.apply(); },
    files: () => { smb.applyMount(); kvm.applyConfig(); fileClip.apply(); },
  };
  return { set: (section, partial) => change(section, partial, AFTER[section]) };
}

module.exports = setupIpc;