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.

59.5 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith, Erdoğan Yeşil. GPL-3.0, see LICENSE.
// Shared cursor + keyboard: the state machine for both roles, one partner at a time.
//   driving: this Mac's input goes to the partner device (owner)
//   driven:  the partner device's input drives this Mac
// Ownership model adapted from Beamer (one owner of the input at a time, routes, fail open).
//
// Messages come through the hub's bus, which says which device each one is from (`from`), so a
// message from a device that is not the partner is never mistaken for the partner's. The partner
// is the device our input goes to (driving) or comes from (driven). A phone partner is driven through
// the phone bridge (phone-bridge.js): its replies come back here through onPartnerMessage().
//
// Events: 'change' — this.view changed.
'use strict';

const { WheelScale } = require('../../shared/wheelscale.js');
const { EventEmitter } = require('events');
const P = require('../../shared/protocol.js');
const { CapsSync } = require('../../shared/capsync.js');
const E = require('../../shared/kvm-edges.js');
const blepipe = require('../../shared/blepipe.js');
const { KvmMoves } = require('../../shared/kvm-moves.js');
const { LaneMesh, LANE_TYPES, meshNative } = require('../../shared/inputlane.js');
const { KeyLayout } = require('../../shared/keylayout.js');
const CL = require('../../shared/cursorlock.js');
const store = require('./store');
// Hold a key to cross (#230; in Multi-device, only this Mac's own mouse and trackpad at its edges)
// and the emergency return (#178).
const Crossing = require('../../shared/crossing.js');
// Cursor portals (shared/cursor-portals.js): an edge range of one of our displays that leads to a range of a
// display on another computer (never a phone), opt-in (kvm.portalsOn), saved per device (kvm.portalsByPeer).
const Portals = require('../../shared/cursor-portals.js');
const PORTAL_VERSION = 3;
const PORTAL_MODIFIERS = ['Command', 'Control', 'Alt', 'Shift']; // keys a way back may need (shared/cursor-portals.js)

// {them} = the other computer's name (Kvm._them).
const REFUSED = { busy: '{them} is using this computer right now', not_allowed: '{them} doesn’t accept input from here' };

const OFF_BLE = 'Cursor sharing is off over Bluetooth';

class Kvm extends EventEmitter {
  // hub: hub.js (bus, sessions, select, selectedId, device); helper: the Mac helper; getSettings;
  // clipboard, input, drop, fileSend: the features; layoutSync: layout-sync.js (the edges come from it).
  constructor({ hub, layoutSync, helper, getSettings, clipboard, input, drop, fileSend }) {
    super();
    Object.assign(this, { hub, layoutSync, helper, getSettings, clipboard, input, drop, fileSend });
    this.dragOut = null; // id of our file drag while it is on the PC and not yet dropped
    fileSend.on('policy', () => this.config());
    fileSend.on('dragEnd', (drag) => {
      if (this.dragOut === drag) this.dragOut = null;
    });
    drop.dragIn.isDriven = () => this.mode === 'driven';
    this.mode = 'home';
    this.route = 0;
    this.peerRoute = 0;
    this.selBack = null; // the device selected before a crossing selected the partner, until it accepts (#245)
    this.partner = null; // the device our input goes to (driving) or comes from (driven); null at home
    this._busyId = null; // the partner link marked busy while driving/driven (see _markBusy)
    this.keyboardOnly = false; // the hotkey moved the keyboard only (no edge, no mouse)
    this.lastName = '';
    this.message = '';
    this.tapError = null;
    this.acceptTimer = null;
    // k.mm summed while driving, sent as one (shared/kvm-moves.js): paced for Bluetooth, and held
    // (still summed) while the socket is backed up, so the pointer never replays old moves.
    this._driveWss = (x) => this._drive(x); // bound once: nothing new per move
    this.moves = new KvmMoves({
      send: (m) => this.mode === 'driving' && this._driveMove(m),
      delay: () => (this._movesBle() ? P.KVM_MOVE_BLE_MS : 0),
      backlog: () => (this.lanes.drive.quiet ? 0 : this._movesBle() ? blepipe.backlog() : this._movesQueued()),
      limit: () => (this._movesBle() ? P.KVM_BLE_BACKLOG : P.KVM_IP_BACKLOG),
      maxWait: () => (this._movesBle() ? Infinity : P.KVM_MOVE_MAX_WAIT_MS),
    });
    // The input lane (shared/inputlane.js) of each device with an app that has one: moves over UDP,
    // events numbered on both. Through the partner's lane only, never through the phone bridge.
    this.lanes = new LaneMesh({
      lane: (id) => (!id || (this.local && this.local.drives(id)) ? null : this._session(id) && this._session(id).lane()),
      il: (id) => (this._session(id) && this._session(id).il) || null,
      partner: () => this.partner,
      route: () => this.peerRoute,
      move: (dx, dy, id) => this._laneMove(dx, dy, id),
      deliver: (m, id) => (m.t === P.T.K_GESTURE ? this._onGesture(m, id) : this._onK(m, id)),
      speed: () => this.cfg.speed, // the helper's lane applies it to the moves it injects
    });
    // … and on the driven side, the moves that came in the same turn go to the helper as one.
    this.injectMoves = new KvmMoves({
      send: (m) => this.mode === 'driven' && (this.helper.sendMove ? this.helper.sendMove(m.dx, m.dy) : this.helper.send('inject', { ev: { t: P.T.K_MOVE, dx: m.dx, dy: m.dy } })),
    });
    this.keys = new KeyLayout((cmd, args) => this.helper.request(cmd, args), (cmd, args) => this.helper.send(cmd, args)); // shortcuts and alphabets across layouts
    this.local = null; // phone-bridge.js: drives a phone itself (its input goes through adb, not the link)
    this.locked = false; // cursor lock (shared/cursorlock.js): the pointer stays on the device it is on
    this.lockAt = 0;
    this.lockKey = new CL.LockKey(() => this.getSettings().keys.lockKeys);
    this.jumpKeys = new (require('../../shared/jumpkeys.js').JumpKeys)(() => this.cfg.jumps, (id) => this.jumpTo(id)); // jump shortcuts while driving
    this.drivenMouse = false; // driven with the mouse too (not keyboard only): the edges are watched
    this.helperPortalVersion = 0; // the helper's portalCapabilities (0: an older helper, no portals)
    this.portalIds = new Map(); // the helper's portal id -> { peer, rule }
    this.portalReturn = null; // driven, come in through a portal: { target, id, returns } (the ways back are their ranges)
    this.portalExits = []; // driven, come over an edge: the driver's portals here, ways back beside the edges
    this.pendingPortal = null;

    // Message types -> handler(m, fromId). The bus delivers them; onPartnerMessage() replays a phone bridge's.
    const K = [P.T.K_MOVE, P.T.K_DOWN, P.T.K_UP, P.T.K_WHEEL, P.T.K_KEY_DOWN, P.T.K_KEY_UP];
    this.handlers = {
      [P.T.KVM_TAKE]: (m, from) => this._onTake(m, from),
      [P.T.KVM_LINK]: (m, from) => this._onLink(m, from), // the other side switched it: follow, no echo
      [P.T.KVM_LAYOUT]: (m, from) => this._onOldLayout(m, from), // a one-to-one app's edge: placed as it says
      [P.T.KVM_ACCEPT]: (m, from) => {
        if (this.mode === 'driving' && from === this.partner && m.route === this.route) { clearTimeout(this.acceptTimer); this.selBack = null; }
      },
      [P.T.KVM_REFUSE]: (m, from) => {
        if (this.mode !== 'driving' || from !== this.partner || m.route !== this.route) return;
        this.goHome(this._them(REFUSED[m.why] || '{them} refused', from), false);
        this._selectBack();
      },
      [P.T.KVM_HOME]: (m, from) => {
        if (this.mode !== 'driving' || from !== this.partner || m.route !== this.route) return;
        // back through another of our portals to it: onto that portal's own stretch here
        const rule = m.portal && typeof m.portal.id === 'string' ? this.rulesFor(from).find((r) => r.id === m.portal.id) : null;
        if (rule && Number.isFinite(m.portal.offset) && Portals.usableTarget(this._myDisplays(), rule.source)) {
          const offset = Portals.mapOffset({ source: rule.target, target: rule.source }, m.portal.offset);
          this.helper.send('capture', { on: false });
          this.helper.request('placePortal', { display: rule.source.display, side: rule.source.side, offset, deadlineMs: Date.now() + 700 }, 750).catch(() => {});
          this._setMode('home', '');
          return;
        }
        // driving a phone through a computer: back at the edge that led to the phone; else the side the monitor map says
        const side = this.viaSide || (E.SIDES.includes(m.side) ? m.side : this._sideOf(from));
        // kept on the part of that side that touches the device (an offset it never mapped went to another monitor)
        const offset = typeof m.offset === 'number' && !this.viaSide ? this.layoutSync.land(side, m.offset, from) : m.offset;
        this.helper.send('capture', typeof m.offset === 'number' && side ? { on: false, side, offset } : { on: false });
        this._setMode('home', '');
      },
      [P.T.KVM_RELEASE]: (m, from) => {
        if (this.mode === 'driven' && from === this.partner && m.route >= this.peerRoute) this._drivenHome('');
      },
      [P.T.KVM_NEXT]: (m, from) => this._onNext(m, from), // a device we drive hands the input on (a chain)
      [P.T.K_GESTURE]: (m, from) => this._onWire(m, from),
      [P.T.KVM_LOCK]: (m, from) => {
        if (this.mode !== 'home' && from === this.partner) this.setLocked(m.on === true, false);
      },
    };
    for (const t of K) this.handlers[t] = (m, from) => this._onWire(m, from);
    // Caps Lock follows the input (shared/capsync.js, #131): after kvm.take / kvm.home are handled.
    this.caps = new CapsSync({ helper: this.helper, platform: 'mac' });
    for (const [t, mode] of [[P.T.KVM_TAKE, 'driven'], [P.T.KVM_HOME, 'home']]) {
      const h = this.handlers[t];
      this.handlers[t] = (m, from) => { const r = h(m, from); if (this.mode === mode) this.caps.expect(); return r; };
    }
    this.handlers[P.T.KVM_CAPS] = (m, from) => { if (this.mode === 'home' || from === this.partner) this.caps.onPeer(m); };
    for (const t of Object.keys(this.handlers)) this.hub.bus.on(t, (m, from) => this.handlers[t](m, from));

    this.hub.bus.onPeer('welcome', (id) => { this.lanes.attach(id); this._onPeerUp(id); });
    this.hub.bus.onPeer('closed', (id) => this._onPeerDown(id));
    // Onto Bluetooth with Over Bluetooth off: everything home; back on Wi-Fi it crosses again.
    this.hub.bus.onPeer('transport', (id) => this._bleCheck(id));
    this.hub.on('selected', (id) => this._onSelected(id));

    setInterval(() => this._tick(), 250);
    const checkPortals = () => this.helper.request('portalCapabilities', {}, 1000).then((r) => {
      this.helperPortalVersion = r && r.version === PORTAL_VERSION ? PORTAL_VERSION : 0;
      this.config();
      this.emit('change');
    }, () => { this.helperPortalVersion = 0; });
    helper.on('ready', () => { meshNative(helper); checkPortals(); setTimeout(() => this.config(), 150); }); // each device's own helper lane (#273)
    if (helper.running) { meshNative(helper); checkPortals(); }
    helper.on('exit', () => {
      this.helperPortalVersion = 0;
      if (this.mode === 'driving') this.goHome('The helper stopped');
      else if (this.mode === 'driven') this._drivenHome('The helper stopped');
    });
    helper.on('event', (name, ev) => this._onHelper(name, ev));
  }

  get cfg() {
    return this.getSettings().kvm;
  }

  // The phone bridge drives a phone: attach it so its replies (accept, refuse, home) come here
  // as messages from the partner. Called once by main.js and by the tests.
  attachLocal(bridge) {
    this.local = bridge;
    // A phone's answers come as the partner's messages; a PhoneSet says which phone answered.
    if (bridge) bridge.reply = (msg, id) => this.onPartnerMessage(id || this.partner, msg);
  }

  // A message as if the partner device had sent it (the phone bridge's replies).
  onPartnerMessage(id, msg) {
    if (!id || !msg) return;
    const fn = this.handlers[msg.t];
    if (fn) fn(msg, id);
  }

  // What this Mac's edges lead to: { left, right, top, bottom }, device id or null. The shared layout
  // puts the nearest device on each side (docs/mesh.md, "Shared layout").
  get edges() {
    return this.layoutSync.neighbors();
  }

  // The shared layout changed (here or on another device): the helper watches the new sides, and each
  // connected device is told which side it is on, as the older apps expect (kvm.layout).
  layoutChanged() {
    this.config();
    for (const id of this.hub.bus.connectedIds()) {
      const side = this._sideOf(id);
      if (side) this._send(id, { t: P.T.KVM_LAYOUT, pcSide: side }); // its edge towards us is the opposite
    }
  }

  // kvm.layout from a one-to-one app (no mesh): pcSide is the edge of its screen that leads to this Mac,
  // so it sits beyond the opposite edge of this one. It goes there in the shared layout (an edit, synced
  // to the others), as the one-to-one app would set it; layoutChanged() tells it our side back. A mesh
  // device's kvm.layout changes nothing: the shared layout is the one map between mesh devices.
  _onOldLayout(m, from) {
    const s = this.hub.sessions.get(from);
    if (!s || s.meshCapable || !P.SIDES.includes(m.pcSide)) return;
    const side = P.opposite(m.pcSide);
    if (this._sideOf(from) === side) return;
    const me = this.layoutSync.view().cells[this.layoutSync.selfId];
    if (!me) return;
    const [dx, dy] = { left: [-1, 0], right: [1, 0], top: [0, -1], bottom: [0, 1] }[side];
    this.layoutSync.place(from, me.x + dx, me.y + dy);
  }

  // A device was forgotten: it leaves the shared layout (a person's edit, synced to the others).
  forgetDevice(id) {
    this.layoutSync.remove(id);
    this.config();
  }

  // Settings changed (ipc.js setKvm): the switch follows the other computer, the rest is applied here.
  settingsChanged(prev) {
    if (prev && prev.linked !== this.cfg.linked) {
      const on = this.linked;
      this.cfg.linked = prev.linked; // setLinked does the work (home first, tell the peer)
      return this.setLinked(on);
    }
    this._bleCheck(this.partner); // config() too
    const k = this.cfg;
    if (this.mode === 'driving' && !this._driveOtherFor(this.partner)) this.goHome('Turned off');
    if (this.mode === 'driven' && !this._beDrivenFor(this.partner)) this._sendHome(undefined, 'Turned off');
  }

  // Messages name the other computer (it may be gone already: the last name we knew).
  _them(text, id = this.partner) {
    const s = id ? this.hub.sessions.get(id) : null;
    if (s && s.connected) this.lastName = s.displayName();
    return text.replace(/\{them\}/g, this.lastName || 'The other computer');
  }

  get view() {
    return { where: this.mode, message: this.message, tapError: this.tapError, paused: this.paused, locked: this.locked, portals: this.portalView() };
  }

  // ---- cursor portals ----

  _myDisplays() {
    return (this.layoutSync.allDisplays && this.layoutSync.allDisplays()[this.layoutSync.selfId]) || [];
  }

  _theirDisplays(id) {
    return (this.layoutSync.allDisplays && this.layoutSync.allDisplays()[id]) || [];
  }

  // The computers a portal may lead to: connected, not a phone.
  _portalPeers() {
    return this.hub.bus.connectedIds().filter((id) => !P.isPhoneOs(this._peerOs(id)));
  }

  rulesFor(id) {
    const byPeer = this.cfg.portalsByPeer || {};
    return (byPeer[id] !== undefined && Portals.normalize(byPeer[id])) || [];
  }

  // What the helper watches: every usable rule towards a computer we may drive now. A rule whose source range
  // overlaps one already taken (another computer's on the same edge) is left out.
  _portalList() {
    this.portalIds = new Map();
    const k = this.cfg;
    if (!k.portalsOn || this.helperPortalVersion !== PORTAL_VERSION || !k.mouse || (this.locked && this.mode === 'home')) return [];
    const mine = this._myDisplays();
    const out = [];
    for (const id of this._portalPeers()) {
      if (!this._canDriveTo(id)) continue;
      const theirs = this._theirDisplays(id);
      for (const rule of this.rulesFor(id)) {
        // Keys only for coming back: going there needs none, except on an edge that touches another display here.
        const free = { ...rule, modifiers: [], key: '' };
        const r = k.portalKeys === 'back' && Portals.usableSource(mine, free) ? free : rule;
        if (!Portals.usableSource(mine, r) || !Portals.usableTarget(theirs, r.target)) continue;
        if (out.some((o) => o.source.display === r.source.display && o.source.side === r.source.side &&
          Math.max(o.source.from, r.source.from) < Math.min(o.source.to, r.source.to))) continue;
        const hid = `${out.length}-${r.id}`;
        this.portalIds.set(hid, { peer: id, rule: r });
        out.push({ ...r, id: hid });
      }
    }
    return out;
  }

  portalView() {
    return {
      supported: this.helperPortalVersion === PORTAL_VERSION,
      on: !!this.cfg.portalsOn,
      keys: this.cfg.portalKeys || 'there', // when the portals' keys are held: going there, coming back or both
      mine: this._myDisplays(),
      peers: this._portalPeers().map((id) => {
        const sess = this._session(id);
        return { id, name: (sess && sess.displayName && sess.displayName()) || id, os: this._peerOs(id), displays: this._theirDisplays(id), rules: this.rulesFor(id) };
      }),
    };
  }

  // The page saved a computer's portals (ipc setPortals): checked against both sides' displays.
  setPortals(value, id) {
    const rules = Portals.normalize(value);
    if (!rules || typeof id !== 'string' || !this._portalPeers().includes(id) || this.mode !== 'home') return false;
    const mine = this._myDisplays(), theirs = this._theirDisplays(id);
    const previous = this.rulesFor(id);
    if (rules.some((r) => (!Portals.usableSource(mine, r) || !Portals.usableTarget(theirs, r.target)) &&
      !previous.some((p) => JSON.stringify(p) === JSON.stringify(r)))) return false;
    this.cfg.portalsByPeer = { ...(this.cfg.portalsByPeer || {}), [id]: rules };
    return true;
  }

  // The helper crossed a portal: take the computer behind it, the pointer placed on the portal's far range.
  _onPortal(ev) {
    const hit = this.portalIds.get(ev.id);
    const r = hit && hit.rule;
    const id = hit && hit.peer;
    const before = this.hub.selectedId;
    const theirs = id ? this._theirDisplays(id) : [];
    if (!hit || this.mode !== 'home' || this.locked || !this.cfg.mouse || !this.cfg.portalsOn || !this._canDriveTo(id) ||
        !Number.isFinite(ev.offset) || ev.offset < r.source.from || ev.offset > r.source.to ||
        !Portals.usableTarget(theirs, r.target) || (this.blockEdge && this.blockEdge()) || !this.hub.select(id)) {
      this.helper.send('capture', { on: false });
      return;
    }
    const offset = Portals.mapOffset(r, ev.offset);
    // side + offset: where a computer without portals (or an older app) places the pointer instead
    const along = Portals.desktopOffset(theirs, r.target, offset);
    this._take({ where: { portal: { target: r.target, offset, id: r.id, returns: this._portalExits(id) }, side: r.target.side, offset: along === null ? 0.5 : along } }, id, before);
  }

  // Every portal to computer id is also a way back from it, each with the keys held to come back (kvm.portalKeys).
  _portalExits(id) {
    if (!this.cfg.portalsOn) return [];
    const back = this.cfg.portalKeys === 'back' || this.cfg.portalKeys === 'both';
    const theirs = this._theirDisplays(id);
    return this.rulesFor(id).filter((x) => Portals.usableTarget(theirs, x.target))
      .map((x) => ({ id: x.id, target: x.target, modifiers: back ? x.modifiers : [] }));
  }

  // Driven, a take through a portal: the helper places the pointer on that display's range first.
  _onPortalTake(m, from, done) {
    const target = Portals.endpoint(m.portal && m.portal.target);
    const offset = m.portal && m.portal.offset;
    const mine = this._myDisplays();
    if (this.helperPortalVersion !== PORTAL_VERSION || this.pendingPortal || !target || !Number.isFinite(offset) ||
        offset < target.from || offset > target.to || !Portals.usableTarget(mine, target)) return done(false);
    const pending = { from, route: m.route };
    this.pendingPortal = pending;
    this.helper.request('placePortal', { display: target.display, side: target.side, offset, deadlineMs: Date.now() + 700 }, 750).then(() => {
      if (this.pendingPortal !== pending) return;
      this.pendingPortal = null;
      done(Portals.usableTarget(this._myDisplays(), target) ? target : false);
    }, () => {
      if (this.pendingPortal !== pending) return;
      this.pendingPortal = null;
      done(false);
    });
  }

  // Cursor lock: at home no edge crosses, driven the edges aren't watched (neither the way back nor on
  // to another device), driving the partner is told (kvm.lock) and stops watching its own.
  // tell: no echo of a kvm.lock.
  setLocked(on, tell = true) {
    on = !!on;
    if (on === this.locked || (on && !this.hub.bus.connectedIds().length)) return;
    this.locked = on;
    if (tell && this.mode === 'driving') this._drive({ t: P.T.KVM_LOCK, on });
    else if (tell && this.mode === 'driven' && this.partner) this._send(this.partner, { t: P.T.KVM_LOCK, on });
    if (this.mode === 'driven' && this.drivenMouse) {
      if (on) this.helper.send('armReturn', { on: false });
      else this._armReturn();
    }
    this.config();
    this.emit('lock', on, this.mode); // main.js: the popup
    this.emit('change');
  }

  // The lock key (main.js's global shortcut, or the driver's keyboard): a press and its echo count once.
  toggleLock() {
    const now = Date.now();
    if (now - this.lockAt < CL.TOGGLE_GAP_MS) return;
    this.lockAt = now;
    this.setLocked(!this.locked);
  }

  // This device's own lock key, typed on the keyboard of the computer that drives it (ev in our key
  // codes): used up here, the app in front never gets it.
  _lockKeyHere(ev) {
    const hit = this.lockKey.intercept(ev);
    if (hit === 'press') this.toggleLock();
    return !!hit;
  }

  // Device id -> connected now.
  // Cursor sharing for one device: the selected one uses the switch, the others their own memory (#245).
  _linkedFor(id) {
    if (id && id === this.hub.selectedId) return this.linked;
    return !!id && (this.cfg.linkedBy || {})[id] !== false;
  }

  // Drive other devices / Let other devices drive this Mac, for one device. The settings hold the selected
  // device's pair (pair.sync); every other device goes by its own (hub.consent, shared/consent.js), so selecting a
  // device whose side doesn't share its mouse and keyboard doesn't stop the others (#245).
  _driveOtherFor(id) {
    return this.hub.consent ? !!this.hub.consent.get(id, 'cursor', 'out') : !!this.cfg.driveOther;
  }

  _beDrivenFor(id) {
    return this.hub.consent ? !!this.hub.consent.get(id, 'cursor', 'in') : !!this.cfg.beDriven;
  }

  _connectedTo(id) {
    const s = id ? this.hub.sessions.get(id) : null;
    return !!s && s.connected;
  }

  // The side of this Mac that leads to device id (null: none).
  _sideOf(id) {
    return E.edgeForPeer(this.edges, id);
  }

  _peerOs(id) {
    const s = id ? this.hub.sessions.get(id) : null;
    return s ? s.peerOs : P.OS.MAC;
  }

  _send(id, msg) {
    return this.hub.bus.send(id, msg);
  }

  // 'ble' when the device's session runs through Bluetooth (blepipe.js), else 'ip'.
  _transportOf(id) {
    const s = id ? this.hub.sessions.get(id) : null;
    return s && s.connected ? s.transport : 'ip';
  }

  // Over Bluetooth (kvm.ble, the same on both: pair.sync 'ble'): off, nothing crosses either way
  // while a device's session runs through Bluetooth, and it crosses again once it's on Wi-Fi.
  _pausedFor(id) {
    return this.cfg.ble === false && this._transportOf(id) === 'ble';
  }

  get onBle() {
    return this._transportOf(this.hub.selectedId) === 'ble';
  }

  get paused() {
    return this._pausedFor(this.hub.selectedId);
  }

  // The one switch (the Cursor tab, the menu bar, the hotkey's double-tap). Through Bluetooth, with
  // cursor sharing on, it is Over Bluetooth: off there leaves it on for Wi-Fi.
  setShared(on) {
    if (this.onBle && this.linked) return this._setBle(on);
    if (on && this.onBle) this.cfg.ble = true; // saved by setLinked
    this.setLinked(on);
  }

  _setBle(on) {
    if (on === (this.cfg.ble !== false)) return;
    this.cfg.ble = on;
    store.saveSettings(this.getSettings());
    this._bleCheck(this.hub.selectedId); // off: everything home first
    this.emit('linked', on, true, true);
    this.emit('change');
  }

  // Everything home when the device we drive or are driven by is on Bluetooth and Over Bluetooth is off.
  _bleCheck(id = this.partner) {
    this.config();
    if (!this.partner || id !== this.partner || !this._pausedFor(this.partner)) return;
    if (this.mode === 'driving') this.goHome(OFF_BLE);
    else if (this.mode === 'driven') this._sendHome(undefined, OFF_BLE);
  }

  // Tell the helper where the crossing sides are and whether edge crossing is armed.
  // Call after settings.kvm or the link changed.
  config() {
    const k = this.cfg;
    const edge = this._edgeConfig();
    const sides = edge.sides;
    const portals = this._portalList();
    this.helper
      .request('kvmConfig', {
        side: sides[0] || null, sides, zones: edge.zones, resistancePx: k.resistancePx, keyboard: !!k.keyboard,
        driveOther: sides.length > 0 || portals.length > 0,
        hotkey: this.getSettings().keys.hotkey || P.HOTKEY_MAC,
        crossingModifier: Crossing.modifier(k.portalsOn ? '' : k.crossingModifier), // portals have their own keys
        stayFullscreen: !!k.stayFullscreen, // #373
        portals,
        emergencyKeys: Crossing.emergency(this.getSettings().keys.emergencyKeys),
        cooldownMs: P.KVM_CROSS_COOLDOWN_MS,
        dwellMs: P.KVM_EDGE_DWELL_MS,
        gestures: k.gestures !== false, // Trackpad gestures go over as k.ge
        takeBack: !k.syncPads, // off with Sync touchpads: our own trackpad never takes the computer back (the 'local' watch)
        dragFiles: this.fileSend.dragOn && this.fileSend.anyPeerDrag, // drag.policy, both sides; each crossing checks its device (_take)
      })
      .then(() => this._setTapError(null), (e) => this._setTapError(e.message));
  }

  // The sides the helper watches: a side whose device is connected, while cursor sharing is on.
  _watchedSides() {
    return this._edgeConfig().sides;
  }

  // The monitor map (#225): the sides and the zones along them where the pointer may cross, only towards
  // a device we may drive now (an iPhone can't be driven).
  _edgeConfig() {
    const k = this.cfg;
    if (!k.mouse || (this.locked && this.mode === 'home')) return { sides: [], zones: 'none' };
    return this.layoutSync.edgeConfig((id) => this._connectedTo(id) && this._peerOs(id) !== P.OS.IOS && !this._pausedFor(id) && this._linkedFor(id) && this._driveOtherFor(id));
  }

  // Mouse and keyboard sharing as a whole (the hotkey's double-tap): off = everything home and
  // nothing crosses either way. `tell`: also switch the other computer (kvm.link), which follows.
  get linked() {
    return this.cfg.linked !== false;
  }

  setLinked(on, tell = true, card = true) {
    const id = this._connectedTo(this.hub.selectedId) ? this.hub.selectedId : null;
    if (id) this.cfg.linkedBy = { ...(this.cfg.linkedBy || {}), [id]: on }; // per pair
    if (on === this.linked) {
      if (id) store.saveSettings(this.getSettings());
      return;
    }
    if (!on) this.home();
    this.cfg.linked = on;
    store.saveSettings(this.getSettings());
    if (tell && id) this._send(id, { t: P.T.KVM_LINK, on });
    this.config();
    if (card) this.emit('linked', on, tell); // hud.js: the big card
    this.emit('change');
  }

  // The other side switched cursor sharing (kvm.link). For the selected device it is the switch itself.
  _onLink(m, from) {
    const on = m.on !== false;
    if (from === this.hub.selectedId) this.setLinked(on, false);
    else {
      this.cfg.linkedBy = { ...(this.cfg.linkedBy || {}), [from]: on };
      store.saveSettings(this.getSettings());
    }
  }

  // The selection changed: cursor sharing follows the selected device's own memory.
  _onSelected(id) {
    const by = this.cfg.linkedBy || {};
    if (id && id in by && by[id] !== this.linked) { // the switch shows its pair; the pointer stays where it is (#245)
      this.cfg.linked = by[id];
      store.saveSettings(this.getSettings());
      this.emit('change');
    }
    this.config();
  }

  // A device came up. A device that dialled us gets our cursor state (and our side of it).
  _onPeerUp(id) {
    const s = this.hub.sessions.get(id);
    if (s && s.hostUp && !s.linkUp) {
      const side = this._sideOf(id);
      if (side) this._send(id, { t: P.T.KVM_LAYOUT, pcSide: side });
      this._send(id, { t: P.T.KVM_LINK, on: this.linked });
    }
    this.config();
  }

  _onPeerDown(id) {
    if ((this.mode === 'driving' || this.mode === 'driven') && id === this.partner) {
      if (this.mode === 'driving') this.goHome(this._them('{them} disconnected', id));
      else this._drivenHome(this._them('{them} disconnected', id));
    }
    if (this.locked && !this.hub.bus.connectedIds().length) this.locked = false;
    this.config();
  }

  _setTapError(err) {
    if (this.tapError === err) return;
    this.tapError = err;
    this.emit('change');
  }

  // Keep-alive: the active partner link (driving or driven) pings every PING_MS so the other end's
  // silence watch (KVM_SILENCE_MS) never trips because that link has gone idle with two or more
  // devices. The old partner is marked idle, the new one busy (docs/mesh.md "Keep-alive").
  _markBusy(partner) {
    if (this._busyId && this._busyId !== partner) this.hub.setBusy(this._busyId, null); // not forced idle: a single link or the selected device stays busy by default
    if (partner) this.hub.setBusy(partner, true);
    this._busyId = partner || null;
  }

  _setMode(mode, message) {
    const prev = this.mode;
    if (prev !== mode) console.log(`[kvm] ${prev} -> ${mode}${message ? ` (${message})` : ''}`);
    this.mode = mode;
    if (prev === 'driving' && mode !== 'driving') this.lanes.drive.idle(); // the helper's lane: no more moves from the tap
    this.lanes.active(mode !== 'home'); // the partner's lane pinged more often
    // The partner link is busy while input is shared; idle at home.
    this._markBusy(mode === 'home' ? null : this.partner);
    if (prev !== mode && this.locked) { // moved by the hotkey, the menu bar or a disconnect: the lock was for where it was
      this.locked = false;
      if (prev === 'home') this.config();
    }
    if (prev !== mode) this.lockKey.reset();
    if (prev !== mode) this.helper.send('emergencyActive', { on: mode !== 'home' }); // the emergency shortcut works while a session is on
    if (prev !== mode) { // crossing either way: what our keys type (the layout may have changed)
      this.keys.reset();
      if (mode !== 'home') this.keys.refresh();
    }
    if (mode === 'home') this.partner = null;
    if (prev !== mode) this.emit('where', mode, prev); // hud.js shows it
    this.message = message || '';
    if (mode !== 'driving') {
      clearTimeout(this.acceptTimer);
      this.moves.drop();
    }
    this.emit('change');
  }

  _tick() {
    if (this.mode === 'home') return;
    if (this.mode === 'driving') this.helper.send('keepalive');
    const s = this.partner ? this.hub.sessions.get(this.partner) : null;
    if (!s || !s.connected || Date.now() - s.lastRx > (s.transport === 'ble' ? P.KVM_SILENCE_BLE_MS : P.KVM_SILENCE_MS)) {
      const text = this._them('{them} stopped answering');
      if (this.mode === 'driving') this.goHome(text);
      else {
        if (s && s.connected) this._send(this.partner, { t: P.T.KVM_HOME, route: this.peerRoute }); // the link may only have hiccupped: tell the driver too, or it goes on driving a computer that let go (only the emergency keys bring it back)
        this._drivenHome(text);
      }
    }
  }

  // ---- owner: this Mac drives a device ----

  _canDrive() {
    return this.mode === 'home' && this._canDriveTo(this.hub.selectedId);
  }

  _canDriveTo(id) {
    return this._connectedTo(id) && this._peerOs(id) !== P.OS.IOS && this._driveOtherFor(id) && this._linkedFor(id) && !this._pausedFor(id);
  }

  // A connected computer (not a phone) we may drive, to drive the phone `id` through.
  _relayFor(id) {
    for (const sess of this.hub.sessions.list()) {
      const sid = sess.id;
      if (sid !== id && sess.connected && !P.isPhoneOs(this._peerOs(sid)) && this._canDriveTo(sid)) return sid;
    }
    return null;
  }

  // id: the device the input goes to (the selected one for the hotkey, the neighbour for an edge).
  // back: the device selected before a crossing selected id, selected again if id doesn't take the input.
  _take(fields, id, back = null) {
    this.selBack = back && back !== id ? back : null;
    const k = this.cfg;
    this.route++;
    // A phone this Mac has no working bridge to (wireless debugging not set up here, or down): another
    // computer that has one drives it for us (kvm.take with `via`); the phone hands the pointer back to us.
    let target = id || null;
    let via = '';
    if (id && this.local && this.local.drives(id) && this.local.drivable && !this.local.drivable(id)) {
      const relay = this._relayFor(id);
      if (relay) { target = relay; via = id; }
    }
    this.viaSide = via && fields.where.side ? P.opposite(fields.where.side) : null; // our edge that leads to the phone
    this.partner = target;
    this.lanes.drive.reset(this.route);
    this.keyboardOnly = !fields.where.side;
    this._setMode('driving', '');
    this.input.releaseAll();
    const take = { t: P.T.KVM_TAKE, route: this.route, mouse: !!k.mouse && !this.keyboardOnly, keyboard: !!k.keyboard, ...fields.where, ...(via ? { via } : {}) };
    // Come over any other way: the portals there still lead back here (a take through one carries them in portal)
    if (!take.portal && target) take.portalReturns = this._portalExits(target);
    // Only to a device that takes drags (its drag.policy; the helper picks one up if any device does).
    const takes = this.fileSend.peerDragOf(this.partner);
    const plan = fields.paths && fields.paths.length && takes ? this.fileSend.planDrag(fields.paths) : null;
    if (fields.paths && fields.paths.length && !takes) console.log('[drag] out: not sent (' + this._them('{them} doesn’t take file drags') + ')');
    if (plan) take.drag = { count: plan.items.length };
    this._drive(take);
    const to = this.partner;
    if (to && !(this.local && this.local.drives(to))) this.caps.handOver((m) => this._send(to, m)); // our Caps Lock, there
    if (plan) {
      this.dragOut = this.fileSend.startDrag(plan); // drag.start right after kvm.take
      console.log(`[drag] out ${this.dragOut}: ${plan.items.length} item(s), ${plan.files} file(s), ${plan.bytes} bytes`);
    } else if (fields.paths && fields.paths.length && takes) console.log('[drag] out: nothing sendable in', fields.paths);
    this.clipboard.sendIfChanged('switch');
    clearTimeout(this.acceptTimer);
    const route = this.route;
    this.acceptTimer = setTimeout(() => {
      if (this.mode === 'driving' && this.route === route) {
        this.goHome(this._them('{them} didn’t answer'));
        this._selectBack();
      }
    }, P.KVM_TAKE_TIMEOUT_MS);
  }

  // A take that failed (refused, or no answer): the selection goes back to the device it was on, so a
  // device that doesn't accept input doesn't take the one-to-one features, nor its pair's switches (#245).
  _selectBack() {
    const id = this.selBack;
    this.selBack = null;
    if (id) this.hub.select(id);
  }

  // Row 9: take our input home (helper stops capturing). Tells the partner unless it refused.
  goHome(message, tellPeer = true) {
    if (this.mode !== 'driving') return;
    if (this.dragOut) {
      this.fileSend.cancelDrag(this.dragOut, true); // came back without dropping the files on the PC
      this.dragOut = null;
    }
    this.helper.send('capture', { on: false });
    if (tellPeer && this.partner) this._drive({ t: P.T.KVM_RELEASE, route: ++this.route });
    this._setMode('home', message);
  }

  // Moves to the partner through Bluetooth (not to the phone bridge): paced for the radio.
  _movesBle() {
    return this._transportOf(this.partner) === 'ble' && !(this.local && this.local.drives(this.partner));
  }

  // Bytes waiting on the partner's socket.
  _movesQueued() {
    if (!this.partner || (this.local && this.local.drives(this.partner))) return 0;
    const s = this.hub.sessions.get(this.partner);
    return s ? s.bufferedAmount || 0 : 0;
  }

  // The link to the device driven or driving now, for the log's line every 30 s (shared/applog.js):
  // null when there's none.
  linkSample() {
    const s = this.partner && this.hub.sessions.get(this.partner);
    if (!s || !s.connected) return null;
    const rtt = s.status && s.status.rtt != null ? s.status.rtt : s.ctx ? s.ctx.rttMs : null;
    return { rtt, lane: this.lanes.rtt(), queued: s.bufferedAmount || 0 };
  }

  _flushMove() {
    this.moves.flush();
  }

  // To the helper: a move summed with the others of this turn; anything else after them. The phone
  // Remote's moves (smooth: the helper eases them out) go as they are.
  _injectEv(ev) {
    if (ev.t === P.T.K_MOVE && !ev.smooth) return this.injectMoves.add(ev.dx, ev.dy);
    this.injectMoves.flush();
    this.helper.send('inject', { ev });
  }

  _session(id) {
    return (id && this.hub.sessions.get(id)) || null;
  }

  // A summed move while driving: on the partner's input lane when there is one, else as always.
  _driveMove(m) {
    if (!this.lanes.drive.move(m.dx, m.dy, this._driveWss)) this._drive({ t: P.T.K_MOVE, dx: m.dx, dy: m.dy });
  }

  // A move from a device's input lane: summed for the helper at once, without a message object per
  // move (_onK's k.mm path, which copies the message first).
  _laneMove(dx, dy, from) {
    if (this.mode !== 'driven' || from !== this.partner) return;
    const speed = this.cfg.speed;
    this.injectMoves.add(dx * speed, dy * speed);
  }

  // A click, key, wheel or gesture while driving: numbered for the lane when there is one.
  _driveEvent(msg) {
    if (!LANE_TYPES.has(msg.t) || !this.lanes.o.lane(this.partner)) return this._drive(msg);
    this.lanes.drive.event(msg, this._driveWss);
  }

  // Input from a device on WSS: numbered or with totals (an app with the input lane) through that
  // lane's order, the rest as always.
  _onWire(m, from) {
    if (this.lanes.wire(m, from)) return;
    if (m.t === P.T.K_GESTURE) this._onGesture(m, from);
    else this._onK(m, from);
  }

  // Input while driving goes to the partner: to the phone bridge when the partner is the phone, else to
  // that device's socket.
  _drive(msg) {
    if (!this.partner) return;
    if (this.local && this.local.drives(this.partner)) this.local.handle(msg, this.partner);
    else this._send(this.partner, msg);
  }

  _onHelper(name, ev) {
    const k = this.cfg;
    switch (name) {
      case 'edge':
        this._onEdge(ev);
        break;
      case 'portal':
        this._onPortal(ev);
        break;
      // Double-tap: switches mouse and keyboard sharing off (everything home)
      // and on again. In keyboard-only mode (Cursor off + "Switch the keyboard with the hotkey") it
      // moves the keyboard over and back instead.
      case 'hotkey':
        if (!this.hub.bus.connectedIds().length) break; // nothing connected: the hotkey does nothing (no sharing to switch)
        if (false && k.hotkeySwitch && !k.mouse && k.keyboard && this.linked) { // keyboard-only switching is one-to-one only
          if (this.mode === 'home') {
            if (!this._canDrive()) return;
            this.helper.send('capture', { on: true, mouse: false, keyboard: true });
            this._take({ where: {} }, this.hub.selectedId);
          } else this.home();
          break;
        }
        // Off (by the switch, the hotkey or the other computer) → on, cursor included: the same
        // state the Cursor tab's one switch shows. On → off.
        if (this.linked && k.mouse) this.setLinked(false);
        else {
          if (!k.mouse) {
            k.mouse = true;
            this.config();
          }
          if (this.linked) {
            store.saveSettings(this.getSettings());
            this.emit('linked', true, true);
            this.emit('change');
          } else this.setLinked(true);
        }
        break;
      case 'ev': {
        if (!ev.ev) return;
        const e = ev.ev;
        if (this.mode !== 'driving') return this.lanes.drive.skip(e, this._driveWss); // numbered by the helper's lane: its number goes all the same
        if (this.jumpKeys.intercept(e)) return; // a jump shortcut: to that device, not typed there
        if (this.local && this.local.drives(this.partner) && this._lockKeyHere(e)) return; // a phone has no lock key: ours counts there
        if (this.fileClip && this.fileClip.intercept(e)) return this.lanes.drive.skip(e, this._driveWss); // copy/paste shortcut: done over there
        if (e.t === P.T.K_MOVE) {
          this.lanes.drive.nativeTotals(e); // the helper's lane is down: its totals go with the move
          this.moves.add(e.dx, e.dy);
          return;
        }
        this._flushMove();
        if (this.dragOut && e.t === P.T.K_UP && e.b === 0) this.dragOut = null; // dropped on the PC (drag.end follows)
        this._driveEvent(this.keys.tag(e)); // keys with the letter they type here (shared/keylayout.js)
        break;
      }
      // Shaken while driving (the helper's capture spots it, natively): the pointer comes home (kvm.shakeHome).
      case 'shake':
        if (this.mode === 'driving' && this.cfg.shakeHome !== false) this.goHome('');
        break;
      case 'emergency':
        this._emergency();
        break;
      case 'captureEnded':
        if (this.mode === 'driving') this.goHome(ev.reason === 'deadman' ? 'Input came back by itself (safety timeout)' : '');
        break;
      // This computer's own mouse or trackpad moved or clicked while driven (the helper's return
      // watch): it takes the computer back. The driver's pointer comes back where it left, ours stays
      // where the driver left it, and the two pointers work apart again: either one crosses over.
      // Sync touchpads on (kvm.syncPads): every mouse moves the one pointer, nobody takes it back.
      case 'local':
        if (this.mode === 'driven' && !this.locked && !this.cfg.syncPads) this._sendHome(undefined, '');
        break;
      case 'return':
        if (this.mode === 'driven' && !this.locked) this._onReturn(ev);
        break;
    }
  }

  // The helper crossed one of our edges (ev.side) at ev.offset: take the device behind it.
  _onEdge(ev) {
    // The one-to-one helper (macshare-helper-multi not built) says no side: it watches the first one we sent.
    const side = E.SIDES.includes(ev.side) ? ev.side : this._watchedSides()[0] || null;
    const r = side ? this.layoutSync.cross(side, ev.offset) : null; // the monitor map: who is there, where along it
    const id = r ? r.to : null;
    const before = this.hub.selectedId;
    if (this.mode !== 'home' || this.locked || !id || !this._canDriveTo(id) || !this.cfg.mouse || (!ev.moving && this.blockEdge && this.blockEdge(side))) {
      // The helper already captures (it started at the edge); undo that if we can't cross.
      this.helper.send('capture', { on: false });
      if (!this.hub.bus.connectedIds().length) this._setMode('home', 'Nothing connected');
      return;
    }
    if (!this.hub.select(id)) {
      this.helper.send('capture', { on: false });
      return;
    }
    this._take({ where: { side: P.opposite(side), offset: r.offset }, paths: ev.drag && ev.drag.paths }, id, before);
    if (ev.moving && this.onMoveWindow) this.onMoveWindow(ev, id); // a window grabbed with the move key (main.js)
  }

  // ---- driven: a device drives this Mac ----

  _onTake(m, from) {
    const refuse = (why) => this._send(from, { t: P.T.KVM_REFUSE, route: m.route, why });
    if (this.mode === 'driving') return refuse(P.REFUSE.BUSY);
    if (this.mode === 'driven' && from !== this.partner) return refuse(P.REFUSE.BUSY); // another device drives us
    if (!this._beDrivenFor(from) || !this._linkedFor(from) || this._pausedFor(from)) return refuse(P.REFUSE.NOT_ALLOWED);
    if (this.mode === 'driven' && !(m.route > this.peerRoute)) return;
    const first = this.mode !== 'driven';
    if (m.portal && m.mouse !== false && !m._portal) {
      // Through a portal: placed on its range, else as an ordinary crossing (side, offset)
      return this._onPortalTake(m, from, (target) => {
        if (this.mode === 'driving' || (this.mode === 'driven' && from !== this.partner)) return refuse(P.REFUSE.BUSY);
        this._onTake({ ...m, _portal: target || 'none' }, from);
      });
    }
    this.portalReturn = m._portal && m._portal !== 'none'
      ? { target: m._portal, id: typeof m.portal.id === 'string' ? m.portal.id : '', returns: this._portalReturns(m.portal.returns, m._portal) } : null;
    // Come over an ordinary edge (or a shortcut): the driver's portals here are ways back too, beside the edges
    this.portalExits = this.portalReturn ? [] : this._portalReturns(m.portalReturns, null);
    this.partner = from;
    this.peerRoute = m.route;
    if (m.drag) console.log(`[drag] in: the PC crossed with a drag of ${m.drag.count} item(s)`);
    if (m.drag) this.drop.armDrag();
    this._setMode('driven', '');
    this._send(from, { t: P.T.KVM_ACCEPT, route: m.route });
    this.lanes.take(from, m.route); // the lane's totals start again (a move that came ahead goes now)
    if (first) this.input.releaseAll();
    this.drivenMouse = m.mouse !== false;
    if (m.mouse !== false) {
      if (this.portalReturn) { /* placed by placePortal */ }
      else if (typeof m.side === 'string') this.helper.send('place', { side: m.side, offset: Number(m.offset) || 0.5 });
      else if (first) this.helper.send('place', { center: true });
      if (!this.locked) this._armReturn();
    }
    this.drop.dragIn.onDriven(); // after 'place': the native drag starts where the pointer came in
  }

  // The sides of this Mac that have a device behind them: while we are driven the helper watches them
  // (the way back to the driver, and every edge that leads on to another device).
  _returnSides() {
    return this.layoutSync.edgeConfig().sides;
  }

  // The driver's portals to this Mac (kvm.take portal.returns), checked against our displays: the ways back.
  // From an older driver, only the one it came through, with no keys.
  _portalReturns(value, target) {
    const mine = this._myDisplays();
    const list = Array.isArray(value) ? value.slice(0, 32) : [];
    const out = list.filter((x) => x && typeof x.id === 'string' && Portals.usableTarget(mine, x.target) &&
      Array.isArray(x.modifiers) && x.modifiers.every((m) => PORTAL_MODIFIERS.includes(m)))
      .map((x) => ({ id: x.id, target: Portals.endpoint(x.target), modifiers: [...new Set(x.modifiers)] }));
    return out.length || !target ? out : [{ id: '', target, modifiers: [] }];
  }

  _armReturn() {
    const pr = this.portalReturn;
    if (pr) {
      // the ways back are the portals' ranges only (the helper's portalReturns); side, zones and portal for an older helper
      const mine = this._myDisplays();
      const from = Portals.desktopOffset(mine, pr.target, pr.target.from);
      const to = Portals.desktopOffset(mine, pr.target, pr.target.to);
      if (from !== null && to !== null) {
        this.returnSide = pr.target.side;
        const portals = pr.returns.map((x) => ({ ...x.target, modifiers: x.modifiers }));
        const sides = [...new Set([pr.target.side, ...portals.map((x) => x.side)])];
        this.helper.send('armReturn', { on: true, side: pr.target.side, sides, zones: `${from.toFixed(6)}-${to.toFixed(6)}`, portal: pr.target, portals, resistancePx: this.cfg.resistancePx });
        return;
      }
      this.portalReturn = null;
    }
    const { sides, zones } = this.layoutSync.edgeConfig();
    // side: the first one, for a helper from before several sides (it watches that one; a newer one reads sides)
    this.returnSide = sides[0] || null;
    const exits = (this.portalExits || []).map((x) => ({ ...x.target, modifiers: x.modifiers }));
    this.helper.send('armReturn', { on: true, side: sides[0] || null, sides, zones, resistancePx: this.cfg.resistancePx,
      ...(exits.length ? { portals: exits, portalOnly: false } : {}) });
  }

  // The helper saw the pointer leave this Mac (driven) through msg.side. Back to the driver: kvm.home as
  // before. Past another device: kvm.next, so the driver takes that device (see _onNext). Nothing behind
  // that side: ignored. The watch is armed again unless we went home, so a driver that did not take the
  // device leaves the edge live.
  _onReturn(msg) {
    // Come in through a portal: back to the driver. Through the same one, the pointer where it left (its pin
    // there); through another of its portals, onto that portal's stretch there.
    if (this.portalReturn) {
      if (msg.moving && this.onMoveWindow) this.onMoveWindow(msg, this.partner);
      const out = Number.isInteger(msg.portal) ? this.portalReturn.returns[msg.portal] : null;
      const other = out && out.id && out.id !== this.portalReturn.id && Number.isFinite(msg.portalOffset);
      return this._sendHome(undefined, '', null, other ? { id: out.id, offset: msg.portalOffset } : null);
    }
    // Come over an edge, out through one of the driver's portals: onto that portal's stretch there
    const exit = Number.isInteger(msg.portal) && this.portalExits ? this.portalExits[msg.portal] : null;
    if (exit && Number.isFinite(msg.portalOffset)) {
      if (msg.moving && this.onMoveWindow) this.onMoveWindow(msg, this.partner);
      return this._sendHome(undefined, '', null, { id: exit.id, offset: msg.portalOffset });
    }
    // An older (one-side) helper names none: it watches the first side we armed. Its offset is ours along that
    // side and still needs mapping; sent as it was, the driver read it along its own edge (another monitor).
    const side = E.SIDES.includes(msg.side) ? msg.side : this.returnSide || null;
    const r = side ? this.layoutSync.cross(side, msg.offset) : null; // the monitor map: who is there, where along it
    const to = r ? r.to : null;
    if (!side || to === this.partner || (!to && side === this.layoutSync.sideTo(this.partner))) {
      if (msg.moving && this.onMoveWindow) this.onMoveWindow(msg, this.partner); // a window grabbed with the move key (main.js)
      return this._sendHome(to === this.partner ? r.offset : msg.offset, '', side ? P.opposite(side) : null);
    }
    // offset: ours along that side; the driver maps it again through the map (cross from us)
    if (to) this._send(this.partner, { t: P.T.KVM_NEXT, route: this.peerRoute, to, side, offset: Number(msg.offset) || 0 });
    this._armReturn();
  }

  // A device we drive (the partner) reached an edge that leads to device `to` (kvm.next): the chain. Only the
  // one we drive may say it, only for a neighbour in the layout that is connected to us, and never from a
  // phone (it ends a chain). We release the device and take `to`, as an edge crossing would: the device it
  // reached sees the input come in through the side opposite to the one it left by.
  _onNext(m, from) {
    if (this.mode !== 'driving' || from !== this.partner || m.route !== this.route || this.keyboardOnly || this.locked) return;
    if (P.isPhoneOs(this._peerOs(from))) return; // a phone has no edges of its own: it ends a chain
    const side = E.SIDES.includes(m.side) ? m.side : null;
    const to = typeof m.to === 'string' ? m.to : '';
    if (!side || !to || to === from || to === this.hub.device.id) return;
    const r = this.layoutSync.cross(side, m.offset, from);
    if (!r || r.to !== to) return; // not the device beyond `from` there (the monitor map)
    if (!this._canDriveTo(to) || !this.cfg.mouse) return; // connected, and our switch and cursor sharing for it
    if (!this.hub.select(to)) return;
    this.route++;
    this._send(from, { t: P.T.KVM_RELEASE, route: this.route }); // the device we drove goes home
    this._take({ where: { side: P.opposite(side), offset: r.offset } }, to, from);
  }

  _onK(m, from) {
    if (this.mode !== 'driven' || from !== this.partner) return;
    const k = this.cfg;
    const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
    let ev;
    switch (m.t) {
      case P.T.K_MOVE:
        ev = { t: m.t, dx: num(m.dx) * k.speed, dy: num(m.dy) * k.speed };
        break;
      case P.T.K_DOWN:
      case P.T.K_UP:
        ev = { t: m.t, b: Math.max(0, Math.min(4, num(m.b) | 0)) };
        if (m.t === P.T.K_UP && ev.b === 0) this.drop.release(); // a drag from the PC ends here
        break;
      case P.T.K_WHEEL: {
        const s = k.reverseScroll ? -1 : 1;
        const mode = m.mode === 'line' ? 'line' : 'pixel';
        if (!this.wheel || this.wheel.mode !== mode) this.wheel = Object.assign(new WheelScale(), { mode }); // Scrolling speed here (#315)
        const w = this.wheel.scale(num(m.dx) * s, num(m.dy) * s, k.scrollSpeed);
        if (!w.dx && !w.dy) return; // less than a line so far: it adds up
        ev = { t: m.t, dx: w.dx, dy: w.dy, mode };
        break;
      }
      default:
        if (typeof m.code !== 'string' || m.code.length > 32) return;
        // Esc during a drag from the PC cancels it (injected, it would go to the frontmost app).
        if (m.code === 'Escape' && this.drop.dragIn.dragging) {
          if (m.t === P.T.K_KEY_DOWN) this.drop.dragIn.cancel();
          return;
        }
        ev = { t: m.t, code: this._swapKeys(from) ? P.mapKeyFromOtherPlatform(m.code) : m.code };
        if (this._lockKeyHere(ev)) return;
        ev.code = this.keys.code(m.t === P.T.K_KEY_DOWN, ev.code, m.ch, m.tx, m.im); // a shortcut's letter: our key for it
        if (!ev.code) return; // another alphabet's letter: typed as it is
    }
    this._injectEv(ev);
  }

  // Ctrl/Cmd swap for keys from a device (never between two Macs).
  _swapKeys(id) {
    return this.getSettings().keys.swapCtrlCmd !== false && P.keySwapNeeded(P.OS.MAC, this._peerOs(id));
  }

  // A trackpad gesture from the other computer, done the Mac way. Pinches and
  // system swipes become real macOS gesture events (Gesture.swift), so macOS itself zooms and
  // moves Spaces / Mission Control with the fingers. One-off gestures (from a PC), and everything
  // when MACSHARE_GESTURE_KEYS=1, use Mac keys (no Ctrl/Cmd swap) and Mission Control's own app.
  _onGesture(m, from) {
    if (this.mode !== 'driven' || from !== this.partner || this.cfg.gestures === false || !m || typeof m.g !== 'string') return;
    const native = !process.env.MACSHARE_GESTURE_KEYS;
    const num = (v) => (Number.isFinite(v) ? v : 0);
    const PH = ['begin', 'change', 'end', 'cancel'];
    if (native && m.g === 'dock') {
      const motion = [1, 2, 3, 4].includes(m.motion) ? (m.motion === 4 ? 3 : m.motion) : 0;
      if (!motion) return;
      this.helper.send('gesture', { kind: 'dock', motion, v: num(m.v), exit: num(m.exit), phase: PH.includes(m.phase) ? m.phase : 'change' });
      return;
    }
    if (native && m.g === 'zoom') {
      // A pinch from a PC may come without phases: begin it, and end it when the steps stop.
      if (!this.pinching || m.phase === 'begin') {
        this.pinching = true;
        this.helper.send('gesture', { kind: 'zoom', v: 0, phase: 'begin' });
      }
      if (m.phase !== 'begin') this.helper.send('gesture', { kind: 'zoom', v: num(m.v), phase: 'change' });
      clearTimeout(this.pinchTimer);
      const end = () => {
        this.pinching = false;
        this.helper.send('gesture', { kind: 'zoom', v: 0, phase: 'end' });
      };
      if (m.phase === 'end') end();
      else this.pinchTimer = setTimeout(end, 250);
      return;
    }
    if (m.g === 'dock') { // keys mode: only the meaning, at the end
      if (m.phase !== 'end' || typeof m.mean !== 'string') return;
      return this._onGesture({ g: m.mean }, from);
    }
    const combo = (...codes) => {
      for (const code of codes) this.helper.send('inject', { ev: { t: P.T.K_KEY_DOWN, code } });
      for (const code of codes.slice().reverse()) this.helper.send('inject', { ev: { t: P.T.K_KEY_UP, code } });
    };
    const mc = (arg) => require('child_process').execFile('/System/Applications/Mission Control.app/Contents/MacOS/Mission Control', arg ? [arg] : [], () => {});
    switch (m.g) {
      case 'zoom': { // pinch: ⌘+ / ⌘− for every 0.15 of magnification
        if (m.phase === 'begin') this.zoomAcc = 0;
        this.zoomAcc = (this.zoomAcc || 0) + (Number.isFinite(m.v) ? m.v : 0);
        while (this.zoomAcc >= 0.15) { combo('MetaLeft', 'Equal'); this.zoomAcc -= 0.15; }
        while (this.zoomAcc <= -0.15) { combo('MetaLeft', 'Minus'); this.zoomAcc += 0.15; }
        break;
      }
      case 'smartZoom': combo('MetaLeft', 'Digit0'); break;
      case 'back': combo('MetaLeft', 'BracketLeft'); break;
      case 'forward': combo('MetaLeft', 'BracketRight'); break;
      case 'overview': mc(); break;
      case 'appWindows': mc('2'); break;
      case 'desktop': mc('1'); break;
      case 'spaceLeft': combo('ControlLeft', 'ArrowLeft'); break;
      case 'spaceRight': combo('ControlLeft', 'ArrowRight'); break;
      case 'launcher': { // Apps (macOS 26+), else Launchpad, else Spotlight
        const open = (app, next) => require('child_process').execFile('/usr/bin/open', ['-a', app], (err) => err && next());
        open('Apps', () => open('Launchpad', () => combo('MetaLeft', 'Space')));
        break;
      }
      default: break; // rotate: no Mac-wide meaning
    }
  }

  // Rows 8c: send the input home to the partner (return edge or hotkey).
  // side: the driver's side the pointer comes back through (the monitor map: it can be any of them).
  // portal: back through another of the driver's portals ({ id, offset along its range here }).
  _sendHome(offset, message, side = null, portal = null) {
    if (this.mode !== 'driven') return;
    const msg = { t: P.T.KVM_HOME, route: this.peerRoute };
    if (portal) msg.portal = portal;
    if (typeof offset === 'number') msg.offset = offset;
    if (side && typeof offset === 'number') msg.side = side;
    const to = this.partner;
    this._send(to, msg);
    this.caps.handOver((c) => this._send(to, c)); // our Caps Lock, home
    this._drivenHome(message);
  }

  // Rows 8b / 9b: stop being driven.
  _drivenHome(message) {
    if (this.mode !== 'driven') return;
    this.drop.cancelDrag();
    this.drop.dragIn.cancel(); // before releaseAll: the held button must not drop the files
    this.helper.send('releaseAll');
    this.helper.send('armReturn', { on: false });
    this.portalReturn = null;
    this.portalExits = [];
    this._setMode('home', message);
    this.clipboard.sendIfChanged('switch');
  }

  // The emergency shortcut (#178; the helper already stopped capturing, or let go of what it
  // injected): everything home, and sharing off until it's turned on again.
  _emergency() {
    this.home();
    if (this.linked) this.setLinked(false);
    this.helper.send('emergencyActive', { on: false });
  }

  // Menu bar "Bring Mouse and Keyboard Back".
  // Jump shortcuts (kvm.jumps; Mouse › Screen and Keyboard): the pointer straight to device `id`, coming in by
  // its edge that faces this computer (its middle), as if it had crossed; 'self' brings everything home.
  jumpTo(id) {
    if (id === 'self') { this.home(); return true; }
    if (!id || this.mode === 'driven' || this.locked || !this.cfg.mouse || !this._canDriveTo(id)) return false;
    if (this.mode === 'driving') {
      if (this.partner === id) return true;
      this.goHome('');
    }
    const before = this.hub.selectedId;
    if (!this.hub.select(id)) return false;
    const side = this._sideOf(id);
    this.helper.send('capture', { on: true, mouse: true, keyboard: !!this.cfg.keyboard });
    this._take({ where: { side: side ? P.opposite(side) : 'left', offset: 0.5 } }, id, before);
    return true;
  }

  home() {
    if (this.mode === 'driving') this.goHome('');
    else if (this.mode === 'driven') this._sendHome(undefined, '');
  }

  // App quitting: give everything back.
  shutdown() {
    if (this.mode === 'driving') this.goHome('');
    else if (this.mode === 'driven') this._sendHome(undefined, '');
  }
}

module.exports = { Kvm };