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.
JavaScript androidapple-ecosystemconnectelectronfile-sharingintel-unison-alternativeiosios-windowskde-connect-alternativekvmlinuxmacbookmacosmouse-sharingphone-link-alternativeproductivityscreen-sharingsidecar-alternativesynergy-alternativewindows
// TwinDesk — Copyright (C) 2026 inukaasith, Erdoğan Yeşil. GPL-3.0, see LICENSE.
// Main-window actions (preload-app.js → here; copy of windows/mesh/ipc.js). Every value is validated by
// settings.apply().
const { app, ipcMain, dialog, shell, BrowserWindow, clipboard } = 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: hub, link (the selected device's facade), discovery, screen, clip, kvm, terminal, fileDrop, smb, apps, phone, phoneViews, connectPhoneDev(d), settings, save(), push(), buildState(),
// checkFirewall(), fixFirewall(), setStartup(on)
function setupIpc(ctx) {
const { hub, link, discovery, screen, clip, kvm, layoutSync, terminal, 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());
// 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: { theme } and/or { accent } ('' follows the system); local only.
handle('setLook', (o) => o && typeof o === 'object' && change('ui', {
...(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.phoneHub().act(r));
const pairWith = (d) => {
discovery.clearInvite(d.id);
if (P.isPhoneOs(d.os)) return ctx.connectPhoneDev(d); // a phone has no server to pair with
link.startPairing({ address: d.address, port: d.port, macName: d.name, id: d.id }); // id: one met over Bluetooth
};
handle('pair', (target) => {
if (typeof target !== 'string' || !target.trim()) return;
const found = discovery.get(target) || discovery.near(target);
if (found) return pairWith(found);
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());
handle('deviceDo', (c) => c && typeof c === 'object' && ctx.devctl() && ctx.devctl().do(c)); // Overview: ring, lock, quick settings… (shared/devctl.js)
// A chat's answer (Messages' chat apps: shared/chats.js) or a notification's.
handle('history', (r) => { if (r && typeof r === 'object' && ctx.history) ctx.history(r); });
handle('qrPair', () => ctx.qrPair()); // Connection: the phone pairing QR code's link
handle('adbQr', (on) => ctx.adbQr(on === true)); // wireless debugging: pair with a QR code
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))
: !ctx.notifs ? false : r.dismiss ? ctx.notifs.dismiss(String(r.id || '')) : Number.isInteger(r.act) ? ctx.notifs.act(String(r.id || ''), r.act) // Overview's × and buttons (shared/notifacts.js)
: ctx.notifs.reply(String(r.id || ''), r.text))); // a phone chat's Reply, typed here
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();
const id = hub.selectedId;
if (id) ctx.batteryAlerts.forget(id);
link.forget();
sshd.revokeAll(); // forgotten: it may not log in any more
if (id) kvm.forgetDevice(id);
});
// 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));
// 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);
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);
});
// Devices (docs/mesh.md): the selected one takes the one-to-one features; Forget drops one device.
handle('setActivePeer', (id) => typeof id === 'string' && hub.select(id.slice(0, 64)));
handle('iosScreen', (id) => typeof id === 'string' && ctx.iosScreen && ctx.iosScreen(id.slice(0, 64))); // an iPhone's screen through a USB cable of the mesh
handle('forgetPeer', (id) => {
if (typeof id !== 'string') return;
const deviceId = id.slice(0, 64);
ctx.batteryAlerts.forget(deviceId);
// Drop the pairing before removing it from the layout.
ctx.proximityLock?.forget(deviceId);
hub.forgetPeer(deviceId);
kvm.forgetDevice(deviceId);
});
handle('wakePeer', (id) => typeof id === 'string' && wake.wake(id));
handle('setWake', (on) => wake.set(on === true)); // A switch
handle('checkWake', () => wake.check());
// The page's device's Monitor 2 (#256): the first one, else one of its own while the first shows another.
const viewerOf = () => (ctx.viewers && ctx.viewers() && ctx.viewers().of(hub.selectedId)) || screen;
handle('openMonitor', () => (ctx.viewers && ctx.viewers() ? ctx.viewers().open(hub.selectedId) : screen.open(false)));
handle('remoteScreen', (arg) => arg && typeof arg === 'object' && viewerOf().control({ share: arg.share, mode: arg.mode })); // screen.ctl, to the page's device
handle('setPortals', (arg) => arg && typeof arg === 'object' && kvm.setPortals(arg.rules, arg.peer)); // Cursor portals (mesh/kvm.js)
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, edges, shared, locked, ...rest } = partial && typeof partial === 'object' ? partial : {}; // edges: setEdge only
change('kvm', rest, () => kvm.applyConfig());
if ('keyboard' in rest) (ctx.phoneRemote ? ctx.phoneRemote.refresh() : ctx.loadRemote()); // voice typing follows Keyboard
});
// Dev only (windows/test/dev/e2e-app.js, MACSHARE_DEV_PORT set): a helper event, as if the helper
// had sent it (kvm.js gets it through the same listener). Without that variable there is no handler.
if (process.env.MACSHARE_DEV_PORT) {
handle('devHelperEvent', (name, msg) => kvm.helper.emit('event', String(name).slice(0, 40), msg && typeof msg === 'object' ? msg : {}));
}
// The shared layout (docs/mesh.md): device `id` goes to grid cell (x, y); a device there moves to
// its old cell (swap). false when the arguments are not valid or the device is not in the mesh.
handle('setLinkedFor', (id, on) => typeof id === 'string' && kvm.setLinkedFor(id.slice(0, 64), !!on));
handle('setLayoutCell', (id, x, y) => {
if (typeof id !== 'string' || !id || id.length > 64) return false;
if (!Number.isInteger(x) || !Number.isInteger(y)) return false;
return layoutSync.place(id, x, y);
});
// The monitor map (#225): device `id` dropped with its top-left at (x, y) in the plane (it goes where it
// may, layout-world.js drop); snap: how close edges line up. Returns where it went, or null.
handle('moveOnMap', (id, x, y, snap) => {
if (typeof id !== 'string' || !id || id.length > 64 || !Number.isFinite(x) || !Number.isFinite(y)) return null;
return layoutSync.move(id, x, y, Number.isFinite(snap) ? Math.max(0, Math.min(2000, snap)) : undefined);
});
// Off the map: the devices line up from the grid again.
handle('resetMap', () => layoutSync.resetWorld());
handle('setMapSkip', (on) => layoutSync.setSkip(on === true)); // offline computers: passed or not
handle('setMapWhole', (id, on) => typeof id === 'string' && id.length <= 64 && layoutSync.setWhole(id, on === true)); // #376: the whole edge
// A device off the map (its cell is removed from the shared layout). false when it has no cell.
handle('removeFromLayout', (id) => {
if (typeof id !== 'string' || !id || id.length > 64) return false;
return layoutSync.remove(id);
});
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, () => { if (ctx.viewers && ctx.viewers()) ctx.viewers().each((v) => v.applyAudio()); else 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('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 off: TwinDesk restarts one to one
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
// Media controls: made for every phone when turned on; off, each one stops. The Bluetooth speaker: loaded when first on.
if (partial && 'phoneMedia' in partial && ctx.nowPlaying) ctx.nowPlaying.apply();
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.id, 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 (shared/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));
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, () => { terminal.apply(); sshd.apply(); });
});
handle('setupSshd', () => sshd.setup());
handle('openTerminal', () => terminal.open());
// Apps: a Mac sends its own (apps.js, through its screen stream); a PC or Linux computer through peerapps.js.
const macPeer = () => link.peerOs === P.OS.MAC;
handle('listApps', () => (macPeer() ? apps.refresh() : peerApps.refresh()));
handle('launchApp', (id) => { if (!macPeer()) peerApps.launch(id); else { apps.launch(id); screen.ensureHidden(); } });
handle('pinApp', (id) => typeof id === 'string' && macPeer() && apps.pin(id, true)); // a launcher in the app menu
handle('setMacApps', (partial) => change('macApps', partial, () => peerApps.apply()));
handle('setPcApps', (partial) => change('pcApps', partial, () => { pcApps.apply(); pcApps.input.release(); if (peerApps) peerApps.apply(); }));
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, outboxHours: [0, 1, 24, 168].includes(partial.outboxHours) ? partial.outboxHours : undefined, clipReceived: typeof partial.clipReceived === 'boolean' ? partial.clipReceived : undefined,
// Show shared folders from (Multi-device): 'all' or the device ids picked
mountFrom: partial.mountFrom === 'all' ? 'all' : Array.isArray(partial.mountFrom) ? partial.mountFrom.filter((x) => typeof x === 'string').slice(0, 32) : 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(); });
});
// 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.mounted ? smb.open() : smb.openOverWifi && smb.openOverWifi())); // through Bluetooth: Wi-Fi Direct first
handle('openDrive', (id) => { const u = typeof id === 'string' && smb.unitOf ? smb.unitOf(id) : null; if (u && u.mounted) u.open(); }); // another device's folder (Files)
// File Sharing › TwinDesk Drive (shared/drive-host.js createMesh): 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, to) => {
const list = (Array.isArray(paths) ? paths : []).filter((p) => typeof p === 'string' && path.isAbsolute(p)).slice(0, 1000);
if (!list.length) return;
// Multi-device: the devices picked on File Sharing (each its own send, now or when it's back), else the selected one.
const ids = Array.isArray(to) ? to.filter((x) => typeof x === 'string').slice(0, 10) : [];
const units = ids.map((id) => fileDrop.unit && fileDrop.unit(id)).filter(Boolean);
if (units.length) for (const u of units) u.send(list);
else fileDrop.send(list); // now, or when the device is back (shared/outbox.js)
};
handle('sendFiles', sendFiles);
handle('chooseSendFiles', async (to) => {
const win = BrowserWindow.getFocusedWindow();
const r = await dialog.showOpenDialog(win, { title: 'Send files', buttonLabel: 'Send', properties: ['openFile', 'multiSelections'] });
if (!r.canceled) sendFiles(r.filePaths, to);
});
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('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 folder: 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)
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('setPcScreenMode', (mode) => pcScreen.setMode(mode));
// Share screen to one target: { mode: 'off'|'mirror'|'extend', displayId? } for device `id` (screen-mesh stream table).
handle('setPcScreenTarget', (id, choice) => typeof id === 'string' && choice && typeof choice === 'object' ? pcScreen.setTarget(id, choice) : undefined);
// 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) for (const u of ctx.phone.all || []) u.bridge.modesChanged(); // ADB or Native (shared/phonemodes.js), every phone
if (partial && ('enterSends' in partial || 'arrowSwipe' in partial) && ctx.phoneViews) ctx.phoneViews.applyOpts();
}));
// 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();
});
// ReZume tab (shared/rezume.js): loaded when it's first turned on; here only with one phone (shared/rezume-solo.js).
handle('setReZume', (m) => change('rezume', m && typeof m === 'object' ? m : {}, () => (ctx.rezume ? ctx.rezume.apply() : ctx.loadReZume())));
handle('rezumeDo', (m) => {
if (m && m.a === 'with' && ctx.rezumeWith) return void ctx.rezumeWith(typeof m.id === 'string' ? m.id.slice(0, 64) : ''); // the device ReZume is with (shared/rezume-solo.js)
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();
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 : '');
});
// General › Modules (shared/modules.js): applies after a restart.
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();
});
// TwinDesk iPhone (shared/iossign.js): one action, and Choose an IPA….
handle('iosSign', (o) => require('../../shared/iossign-host.js').act(ctx.iosSign && ctx.iosSign(), require('electron').dialog, o));
handle('iosSignIpa', () => require('../../shared/iossign-host.js').pickIpa(ctx.iosSign && ctx.iosSign(), require('electron').dialog));
// 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', (o) => { const d = ctx.deck && ctx.deck(); return d ? d.state(o === true, o === 'mix').catch(() => ({})) : {}; }); // sound devices, Bluetooth devices, displays (OBS's: true; each app's volume: 'mix')
// OBS Studio's port and password (#394): Multi-device had no way to set them, so Connect did nothing.
handle('deckObs', () => { const d = ctx.deck && ctx.deck(); return d ? d.obsConfig() : null; });
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
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
// Remote tab: each phone's Remote page here (shared/perphone.js phoneRemote).
handle('setRemote', (m) => {
if (!m || typeof m !== 'object') return;
// Off at start: not made; turned on, made for every phone (and they hear it).
if ('allow' in m && !ctx.phoneRemote && m.allow === true) { ctx.settings.remote.allow = true; ctx.loadRemote(); }
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();
});
// Camera tab: the selected computer's camera here, this one's there (shared/camshare.js).
handle('camera', (m) => {
if (m && m.do === 'on') return ctx.setCamera(m.on === true); // Camera's switch: loads it, or stops it
if (m && m.do === 'from') return ctx.setCameraFrom && ctx.setCameraFrom(m.id); // Camera from: whose camera shows here
const c = ctx.camShare;
if (!c || !m || typeof m !== 'object') return;
if (m.do === 'view') { if (typeof m.id === 'string' && c.setFrom) c.setFrom(m.id); c.view(m.show === true); } // id: the camera picked at the top; 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 === 'shareTo') c.setShareTo(m.to); // who may see it: 'all' or [ids]
else if (m.do === 'stop') c.stopSending(typeof m.id === 'string' ? m.id : undefined); // one computer viewing it, or all
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);
});
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.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)));
phone('phoneScreenAct', (key) => (key === 'rotate' || key === 'screenPower') && ctx.phoneViews.screenAct(key));
phone('phoneRetry', (id) => { const u = typeof id === 'string' && id ? ctx.phone.unit(id.slice(0, 64)) : null; (u || 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
handle('phoneAssets', () => (ctx.phone ? ctx.phone.assetsView() : { wallpaper: '', apps: [] }));
handle('skipSetup', () => change('setup', { skipped: ctx.buildState().setup.missing, done: true }));
handle('checkFirewall', () => ctx.checkFirewall());
handle('fixFirewall', () => ctx.fixFirewall());
handle('fixInput', () => ctx.fixInput()); // Wayland: the helper's own input access (system.js, #144)
handle('leaveInputGroup', () => ctx.leaveInputGroup());
handle('removeInput', () => ctx.removeInput());
handle('installVdd', () => ctx.vdd.install()); // X11 Extend: the connector helper (vdd.js)
handle('removeVdd', () => ctx.vdd.remove());
handle('setStartup', (on) => ctx.setStartup(on === true));
handle('quit', () => app.quit()); // General › Quit (some desktops have no tray)
// Not on the same network: Bluetooth on/off, and giving up on moving to Wi-Fi (netlink.js).
// Bluetooth with computers stays as the one-to-one app has it: with Multi-device on Linux, computers
// connect over the network only (docs/multi-device.md), so the switch changes nothing here.
handle('setNet', (partial) => {
if (partial?.ble === false && settings.net.ble !== false) ctx.proximityLock?.reset();
const { blePc, ...rest } = partial && typeof partial === 'object' ? partial : {};
change('net', rest, () => ctx.applyNet());
});
handle('setMesh', (partial) => change('mesh', partial, () => ctx.applyMesh && ctx.applyMesh()));
// Debug (shared/debug-start.js, docs/debug.md): ask any device of the mesh; who may debug this computer.
handle('debugAsk', (to, op, args) => {
const d = ctx.dbg && ctx.dbg();
if (!d || typeof to !== 'string' || typeof op !== 'string') return { ok: false, error: 'off' };
return d.ask(to, op, args && typeof args === 'object' ? args : {});
});
handle('setDebug', (o) => {
const d = ctx.dbg && ctx.dbg();
if (d && o && typeof o === 'object') change('mesh', { debug: d.next(o) });
});
// Only what Debug kept, in the log folder.
handle('debugShow', (p) => {
const dir = require('../../shared/applog.js').dir();
if (typeof p === 'string' && dir && path.resolve(p).startsWith(path.resolve(dir) + path.sep)) shell.showItemInFolder(p);
});
handle('netCancel', () => { ctx.proximityLock?.reset(); return ctx.net?.cancel(); });
handle('wifiSetup', () => ctx.wifi && ctx.wifi.setup()); // Keep Wi-Fi while hosting: the password prompt (wifi.js)
handle('netJoinHotspot', (arg) => ctx.joinHotspot(arg));
handle('openBluetoothSettings', () => ctx.openBluetoothSettings());
// 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
});
// Mesh managers (shared/mesh-mgr.js): manager mode, a computer added or let go, its Biometric unlock,
// this computer's answer to a manager, Revoke, and a manager's action.
// Camera & Controller › Controller (shared/pad-share.js): a window's controller state, and the settings.
ipcMain.on('padState', (_e, st) => { const p = ctx.padShare(); if (p) p.fromWindow(st); });
handle('setPads', (o) => { const p = ctx.padShare(); if (p && o && typeof o === 'object') p.set(o); });
handle('setMgr', (o) => {
const m = ctx.mgr && ctx.mgr();
if (!m || !o || typeof o !== 'object') return null;
const id = (v) => (typeof v === 'string' ? v : '');
if (typeof o.on === 'boolean') m.setOn(o.on);
if (o.pick && typeof o.pick.on === 'boolean') m.pick(id(o.pick.id), o.pick.on);
if (o.unlock && typeof o.unlock.on === 'boolean') m.setUnlock(id(o.unlock.id), o.unlock.on);
if (o.answer && typeof o.answer.yes === 'boolean') m.answer(id(o.answer.mgr), String(o.answer.perm), o.answer.yes);
if (o.revoke) m.revoke(id(o.revoke));
ctx.push();
if (o.act) return m.act(id(o.act.to), String(o.act.do));
return null;
});
// Biometric unlock from this computer (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));
if (op === 'unlockAll') return u.wantAll(Array.isArray(arg) ? arg.map(String) : []); // a mesh manager: one after another
return u.state();
});
// The matrix (shared/ui-matrix.js): one of this computer's own cells, its pair with a device one way. The
// selected device's pair is the settings (the pages show it: pairsync-mesh.js tells it), any other's its
// saved pair (shared/consent.js tells it).
// Notifications › Across devices: any cell, set where each end keeps it (shared/mesh-edges.js setCell).
handle('setCell', (from, to, feature, on) => {
const e = ctx.edges && ctx.edges();
if (e && typeof from === 'string' && typeof to === 'string' && typeof feature === 'string' && typeof on === 'boolean') e.setCell(from, to, feature, on);
ctx.push();
});
// Terminal in Multi-device (shared/ui-term-mesh.js): a nickname, or the answer to a computer asking for a shell here.
handle('termMesh', (o) => {
if (!o || typeof o !== 'object') return null;
if (o.nick && typeof o.nick.id === 'string') {
const n = ctx.termNames && ctx.termNames();
const r = n ? n.set(o.nick.id, String(o.nick.name || '')) : { ok: false, why: 'bad' };
ctx.push();
return r;
}
if (o.answer && typeof o.answer.id === 'string') {
const ps = ctx.pairSync && ctx.pairSync();
if (ps) ps.answer(o.answer.id, 'terminal', o.answer.yes === true);
ctx.push();
}
return null;
});
handle('setConsent', (id, feature, dir, on) => {
const c = ctx.consent && ctx.consent();
const F = require('../pairsync').FEATURES;
if (!c || typeof id !== 'string' || !F[feature] || !F[feature][dir] || typeof on !== 'boolean') return;
if (id === hub.selectedId) {
const [sec, key] = F[feature][dir];
return change(sec, { [key]: on }, AFTER[sec]);
}
c.set(id, feature, dir, on);
ctx.push();
});
// pairsync.js applies a value the other computer changed, with the same side effects.
const AFTER = {
clipboard: () => clip.applySettings(),
monitor: () => { if (ctx.viewers && ctx.viewers()) ctx.viewers().each((v) => v.applyAudio()); else screen.applyAudio(); pcScreen.apply(); }, // pacing (pair.sync 'pace'); Steady: a new session
notifs: () => notifs.applySettings(),
audio: () => sound.apply(),
kvm: () => kvm.applyConfig(),
pcApps: () => { pcApps.apply(); pcApps.input.release(); },
macApps: () => peerApps.apply(),
terminal: () => { terminal.apply(); sshd.apply(); },
files: () => { smb.applyMount(); kvm.applyConfig(); fileClip.apply(); },
};
return { set: (section, partial) => change(section, partial, AFTER[section]) };
}
module.exports = setupIpc;