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
Multi-device portals: back through any portal, keys going there, coming back or both (#401)
Pengusto64da0eb548ba
diff --git a/mac-helper/Sources/macshare-helper/Capture.swift b/mac-helper/Sources/macshare-helper/Capture.swiftindex 977cfbb0..a565f859 100644--- a/mac-helper/Sources/macshare-helper/Capture.swift+++ b/mac-helper/Sources/macshare-helper/Capture.swift@@ -136,8 +136,13 @@ final class Capture {let display: CGDirectDisplayIDlet side: Stringlet from: Double, to: Double+ var modifiers: [String] = [] // held to go back through it (Multi-device, kvm.portalKeys)}var portalReturn: PortalReturn?+#if MULTI+ // Came in through a portal: every portal from the driver to this Mac is a way back, each to its own place there.+ var portalReturns: [PortalReturn] = []+#endifvar portals: [Portal] = [] { didSet { portalPush.removeAll(); lastPortalPoint = nil } }private var portalPush: [String: (push: Double, at: Double, since: Double)] = [:]private var lastPortalPoint: (point: CGPoint, at: Double)?@@ -352,7 +357,7 @@ final class Capture {#endifvar returnStops: [String] {#if MULTI- return portalReturn != nil ? [] : returnSides+ return portalReturns.isEmpty ? returnSides : []#elseif portalReturn != nil { return [] }if !stopsKnown || stopsSide != returnSide {@@ -364,16 +369,21 @@ final class Capture {#endif}- var portalReturnStop: PortalReturnStop? {+ var portalReturnStops: [PortalReturnStop] {#if MULTI- guard let portal = portalReturn, !returnSides.isEmpty, CGDisplayIsActive(portal.display) != 0 else { return nil }- return PortalReturnStop(display: CGDisplayBounds(portal.display), side: portal.side, range: portal.from...portal.to)+ guard !returnSides.isEmpty else { return [] }+ return portalReturns.compactMap(Capture.stop)#else- guard let portal = portalReturn, returnSide != nil, CGDisplayIsActive(portal.display) != 0 else { return nil }- return PortalReturnStop(display: CGDisplayBounds(portal.display), side: portal.side, range: portal.from...portal.to)+ guard let portal = portalReturn, returnSide != nil, let stop = Capture.stop(portal) else { return [] }+ return [stop]#endif}+ private static func stop(_ portal: PortalReturn) -> PortalReturnStop? {+ guard CGDisplayIsActive(portal.display) != 0 else { return nil }+ return PortalReturnStop(display: CGDisplayBounds(portal.display), side: portal.side, range: portal.from...portal.to)+ }+func warp(_ p: CGPoint) {CGWarpMouseCursorPosition(p)CGAssociateMouseAndMouseCursorPosition(1) // also ends the ~0.25 s local-event suppression after a warp@@ -382,7 +392,7 @@ final class Capture {#if MULTIfunc armReturn(on: Bool, sides: [String], resistance: Double) {watchLocal(on)- if !on { portalReturn = nil }+ if !on { portalReturns = [] }returnSides = on ? sides : []returnResistance = resistanceretBy.removeAll()@@ -393,17 +403,27 @@ final class Capture {func checkReturn(_ p: CGPoint, dx: Double, dy: Double, flags: CGEventFlags) {guard !returnSides.isEmpty else { return }guard !returnRequiresModifier || allowsCrossing(required: crossingModifier, flags: flags) else { retBy.removeAll(); return }- // Came in through a portal: the way back is that portal's range only.- if let portal = portalReturn {- let portalEdge = portalReturnStop.map { portalReturnContains(p, stop: $0) } ?? false- var st = retBy[portal.side] ?? (push: 0.0, at: 0.0, since: 0.0)- let off = push(&st, p, dx, dy, portal.side, returnResistance, returnZones, edgeOverride: portalEdge)- retBy[portal.side] = st- guard let off = off else { return }+ // Came in through a portal: the ways back are the portals' ranges only, each with its own keys.+ if !portalReturns.isEmpty {+ var hit: (index: Int, side: String, offset: Double, local: Double)? = nil+ for (i, portal) in portalReturns.enumerated() {+ let key = "portal\(i)"+ guard let stop = Capture.stop(portal), portal.modifiers.allSatisfy({ allowsCrossing(required: $0, flags: flags) }) else {+ retBy[key] = nil+ continue+ }+ let onEdge = portalReturnContains(p, stop: stop)+ var st = retBy[key] ?? (push: 0.0, at: 0.0, since: 0.0)+ let off = push(&st, p, dx, dy, portal.side, returnResistance, nil, edgeOverride: onEdge)+ retBy[key] = st+ if hit == nil, let off = off { hit = (i, portal.side, off, portalLocalOffset(p, stop: stop)) }+ }+ guard let portal = hit else { return }returnSides = []lastCross = now()Flash.shared.leave(at: p, side: portal.side)- var out: [String: Any] = ["event": "return", "side": portal.side, "offset": off]+ var out: [String: Any] = ["event": "return", "side": portal.side, "offset": portal.offset,+ "portal": portal.index, "portalOffset": portal.local]if let d = returnDrag(at: p) { out["drag"] = d }let moving = WindowGrab.shared.take(keepUp: false)if moving != 0 { out["moving"] = moving; out["movingPid"] = WindowGrab.shared.pid }@@ -452,7 +472,7 @@ final class Capture {/// Return-edge check while driven; called for local moves and for injected relative moves.func checkReturn(_ p: CGPoint, dx: Double, dy: Double, flags: CGEventFlags) {guard !returnRequiresModifier || allowsCrossing(required: crossingModifier, flags: flags) else { ret.push = 0; return }- let portalEdge: Bool? = portalReturn == nil ? nil : (portalReturnStop.map { portalReturnContains(p, stop: $0) } ?? false)+ let portalEdge: Bool? = portalReturn == nil ? nil : (portalReturnStops.first.map { portalReturnContains(p, stop: $0) } ?? false)guard let side = returnSide, let off = push(&ret, p, dx, dy, side, returnResistance, returnZones, edgeOverride: portalEdge) else { return }returnSide = nillastCross = now()diff --git a/mac-helper/Sources/macshare-helper/InjectRelative.swift b/mac-helper/Sources/macshare-helper/InjectRelative.swiftindex 58097316..0a91ef13 100644--- a/mac-helper/Sources/macshare-helper/InjectRelative.swift+++ b/mac-helper/Sources/macshare-helper/InjectRelative.swift@@ -32,7 +32,7 @@ extension Injector {if remoteOverview { return }let cur = CGEvent(source: nil)?.location ?? .zerolet to = Screens.walk(from: cur, to: CGPoint(x: cur.x + dx, y: cur.y + dy), stops: Capture.shared.returnStops,- portalStop: Capture.shared.portalReturnStop)+ portalStops: Capture.shared.portalReturnStops)var type = CGEventType.mouseMovedvar b = 0if let held = heldButtons.min() {@@ -50,6 +50,11 @@ extension Injector {e?.flags = flagspost(e)if WindowGrab.shared.grabbing { WindowGrab.shared.move(to: to) } // a grabbed window follows (Grab.swift)+#if MULTI+ // Multi-device sends no modifier state with moves: the keys the driver holds are the ones injected here.+ Capture.shared.checkReturn(to, dx: dx, dy: dy, flags: Capture.shared.remoteCrossingFlags.union(flags))+#elseCapture.shared.checkReturn(to, dx: dx, dy: dy, flags: Capture.shared.remoteCrossingFlags)+#endif}}diff --git a/mac-helper/Sources/macshare-helper/PortalEdge.swift b/mac-helper/Sources/macshare-helper/PortalEdge.swiftindex 47a2fecd..a43915f1 100644--- a/mac-helper/Sources/macshare-helper/PortalEdge.swift+++ b/mac-helper/Sources/macshare-helper/PortalEdge.swift@@ -30,6 +30,14 @@ func portalReturnContains(_ p: CGPoint, stop: PortalReturnStop) -> Bool {return edge && offset >= stop.range.lowerBound && offset <= stop.range.upperBound}+// Where along the stop's display edge p is, 0-1 of that display (the driver maps it back onto its own portal).+func portalLocalOffset(_ p: CGPoint, stop: PortalReturnStop) -> Double {+ let d = stop.display+ let vertical = stop.side == "left" || stop.side == "right"+ let t = vertical ? (p.y - d.minY) / max(1, d.height) : (p.x - d.minX) / max(1, d.width)+ return min(max(Double(t), 0), 1)+}+func portalSharedEdgeHit(from start: CGPoint, to end: CGPoint, display: CGRect, side: String,range: ClosedRange<Double>, displays: [CGRect]) -> PortalEdgeHit? {guard display.width >= 4, display.height >= 4, display.contains(start),diff --git a/mac-helper/Sources/macshare-helper/Screens.swift b/mac-helper/Sources/macshare-helper/Screens.swiftindex d3c70f95..19b15f3b 100644--- a/mac-helper/Sources/macshare-helper/Screens.swift+++ b/mac-helper/Sources/macshare-helper/Screens.swift@@ -102,13 +102,13 @@ enum Screens {/// Where a relative move from `from` to `to` ends: like `clamp`, but it follows the path display/// by display and stops on the edge of a `stops` side where it is an outer edge, so a large jump/// can't land on a display past the return edge (the rest counts toward the resistance).- static func walk(from: CGPoint, to: CGPoint, stops: [String], portalStop: PortalReturnStop? = nil) -> CGPoint {- walk(from: from, to: to, stops: stops, portalStop: portalStop, displays: displays())+ static func walk(from: CGPoint, to: CGPoint, stops: [String], portalStops: [PortalReturnStop] = []) -> CGPoint {+ walk(from: from, to: to, stops: stops, portalStops: portalStops, displays: displays())}// Geometry with an explicit display list also allows deterministic tests without an event tap.- static func walk(from: CGPoint, to: CGPoint, stops: [String], portalStop: PortalReturnStop? = nil, displays ds: [CGRect]) -> CGPoint {- if stops.isEmpty && portalStop == nil { return clamp(to, from: from, displays: ds) }+ static func walk(from: CGPoint, to: CGPoint, stops: [String], portalStops: [PortalReturnStop] = [], displays ds: [CGRect]) -> CGPoint {+ if stops.isEmpty && portalStops.isEmpty { return clamp(to, from: from, displays: ds) }var p = fromfor _ in 0..<8 {guard let d = containing(p, ds) else { break }@@ -121,7 +121,7 @@ enum Screens {if vy < 0, to.y < d.minY { let k = (d.minY - p.y) / vy; if k < t { t = k; side = "top" } }if side.isEmpty { break }let e = CGPoint(x: min(max(p.x + vx * t, d.minX), d.maxX - 1), y: min(max(p.y + vy * t, d.minY), d.maxY - 1))- if let portal = portalStop, portal.display == d, portal.side == side, portalReturnContains(e, stop: portal) { return e }+ if portalStops.contains(where: { $0.display == d && $0.side == side && portalReturnContains(e, stop: $0) }) { return e }if stops.contains(side) && isOuterEdge(e, side: side, displays: ds) { return e }// Step just over the edge, onto the next display (or off the desktop: clamp below).let next = CGPoint(x: side == "right" ? d.maxX : side == "left" ? d.minX - 1 : e.x,diff --git a/mac-helper/Sources/macshare-helper/main.swift b/mac-helper/Sources/macshare-helper/main.swiftindex 11df2e4b..5ea09e6d 100644--- a/mac-helper/Sources/macshare-helper/main.swift+++ b/mac-helper/Sources/macshare-helper/main.swift@@ -191,16 +191,10 @@ func handle(_ line: String) {Capture.shared.returnZones = zones(msg["zones"])Capture.shared.returnRequiresModifier = (msg["requireModifier"] as? Bool) ?? false#if MULTI- // Came in through a portal (kvm.take portal): the way back is its range (`sides` is its side alone).- if (msg["on"] as? Bool) == true, let value = msg["portal"] as? [String: Any],- let display = value["display"] as? String, let displayID = UInt32(display), CGDisplayIsActive(displayID) != 0,- let side = value["side"] as? String, ["left", "right", "top", "bottom"].contains(side),- let from = (value["from"] as? NSNumber)?.doubleValue, let to = (value["to"] as? NSNumber)?.doubleValue,- from.isFinite, to.isFinite, from >= 0, to <= 1, from < to {- Capture.shared.portalReturn = Capture.PortalReturn(display: displayID, side: side, from: from, to: to)- } else {- Capture.shared.portalReturn = nil- }+ // Came in through a portal (kvm.take portal): the ways back are the driver's portals to this Mac (portals,+ // in order; a return names one by its index), or from an older app the one it came through (portal).+ let listed = (msg["portals"] as? [[String: Any]]) ?? (msg["portal"] as? [String: Any]).map { [$0] } ?? []+ Capture.shared.portalReturns = (msg["on"] as? Bool) == true ? listed.compactMap(portalReturn) : []let sides = (msg["sides"] as? [String]) ?? [(msg["side"] as? String) ?? "right"]Capture.shared.armReturn(on: (msg["on"] as? Bool) ?? false, sides: sides, resistance: num("resistancePx", 120))#else@@ -504,3 +498,16 @@ signal(SIGPIPE, SIG_IGN) // main closed a pipe (e.g. the audio fd): just stop wrNSApplication.shared.setActivationPolicy(.prohibited)log("ready")NSApplication.shared.run()++#if MULTI+/// One way back through a portal (armReturn portals): a display's edge range and the keys held to cross it.+func portalReturn(_ value: [String: Any]) -> Capture.PortalReturn? {+ guard let display = value["display"] as? String, let displayID = UInt32(display), CGDisplayIsActive(displayID) != 0,+ let side = value["side"] as? String, ["left", "right", "top", "bottom"].contains(side),+ let from = (value["from"] as? NSNumber)?.doubleValue, let to = (value["to"] as? NSNumber)?.doubleValue,+ from.isFinite, to.isFinite, from >= 0, to <= 1, from < to else { return nil }+ let modifiers = (value["modifiers"] as? [String]) ?? []+ guard modifiers.allSatisfy({ ["Command", "Control", "Alt", "Shift"].contains($0) }) else { return nil }+ return Capture.PortalReturn(display: displayID, side: side, from: from, to: to, modifiers: modifiers)+}+#endifdiff --git a/mac-helper/test/portal-edge.swift b/mac-helper/test/portal-edge.swiftindex f26f3212..bcf2b21a 100644--- a/mac-helper/test/portal-edge.swift+++ b/mac-helper/test/portal-edge.swift@@ -34,15 +34,16 @@ struct PortalEdgeTest {precondition(!portalReturnContains(CGPoint(x: 150, y: 198), stop: stop), "not yet at the edge")precondition(!portalReturnContains(CGPoint(x: 150, y: 200), stop: stop), "not on the selected display")let start = CGPoint(x: 150, y: 180), toNeighbor = CGPoint(x: 150, y: 250)- precondition(Screens.walk(from: start, to: toNeighbor, stops: [], portalStop: stop, displays: displays) == CGPoint(x: 150, y: 199),+ precondition(Screens.walk(from: start, to: toNeighbor, stops: [], portalStops: [stop], displays: displays) == CGPoint(x: 150, y: 199),"injected movement stops at the selected occupied edge for a shortcut-free return")precondition(Screens.walk(from: start, to: toNeighbor, stops: [], displays: displays) == toNeighbor,"without an active portal the same move goes to the local display")let outsideStart = CGPoint(x: 110, y: 180), outsideTarget = CGPoint(x: 110, y: 250)- precondition(Screens.walk(from: outsideStart, to: outsideTarget, stops: [], portalStop: stop, displays: displays) == outsideTarget,+ precondition(Screens.walk(from: outsideStart, to: outsideTarget, stops: [], portalStops: [stop], displays: displays) == outsideTarget,"outside the configured interval movement reaches the local display")+ precondition(abs(portalLocalOffset(CGPoint(x: 125, y: 199), stop: stop) - 0.25) < 0.0001, "a quarter along the display, for the driver")let otherStop = PortalReturnStop(display: left, side: "bottom", range: 0...1)- precondition(Screens.walk(from: start, to: toNeighbor, stops: [], portalStop: otherStop, displays: displays) == toNeighbor,+ precondition(Screens.walk(from: start, to: toNeighbor, stops: [], portalStops: [otherStop], displays: displays) == toNeighbor,"a portal on another display must not stop this one")print("shared-edge portal geometry: ok")}diff --git a/mac/mesh/ipc.js b/mac/mesh/ipc.jsindex 6f72a8de..84fd936a 100644--- a/mac/mesh/ipc.js+++ b/mac/mesh/ipc.js@@ -38,7 +38,7 @@ const SCHEMA = {virtual: { enabled: bool, width: (v) => Math.round(clamp(640, 3840, 1920)(v)), height: (v) => Math.round(clamp(480, 2160, 1080)(v)), hiDPI: bool, hz: oneOf([30, 60], 60) },kvm: {pcSide: oneOf(P.SIDES, 'right'), mouse: bool, keyboard: bool, driveOther: bool, beDriven: bool,- resistancePx: (v) => Math.round(clamp(0, 400, 120)(v)), crossingModifier: Crossing.modifier, stayFullscreen: bool, speed: clamp(0.25, 4, 1), scrollSpeed: clamp(0.25, 4, 1), reverseScroll: bool, hotkeySwitch: bool, linked: bool, gestures: bool, ble: bool, syncPads: bool, shakeHome: bool, portalsOn: bool,+ resistancePx: (v) => Math.round(clamp(0, 400, 120)(v)), crossingModifier: Crossing.modifier, stayFullscreen: bool, speed: clamp(0.25, 4, 1), scrollSpeed: clamp(0.25, 4, 1), reverseScroll: bool, hotkeySwitch: bool, linked: bool, gestures: bool, ble: bool, syncPads: bool, shakeHome: bool, portalsOn: bool, portalKeys: oneOf(['there', 'back', 'both'], 'there'),jumps: require('../../shared/jumpkeys.js').clean, // jump shortcuts (Mouse › Screen, Keyboard)},keys: { swapCtrlCmd: bool, hotkey: oneOf(P.HOTKEYS, 'AltRight'), lockKeys: (v) => CL.validKeys(v, CL.DEFAULT_KEYS.mac), emergencyKeys: Crossing.emergency, modMap: require('../../shared/modmap.js').clean },diff --git a/mac/mesh/kvm.js b/mac/mesh/kvm.jsindex b5a782f3..954c6b9a 100644--- a/mac/mesh/kvm.js+++ b/mac/mesh/kvm.js@@ -30,6 +30,7 @@ const Crossing = require('../../shared/crossing.js');// 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' };@@ -112,6 +113,15 @@ class Kvm extends EventEmitter {},[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 saysconst 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)@@ -271,7 +281,10 @@ class Kvm extends EventEmitter {for (const id of this._portalPeers()) {if (!this._canDriveTo(id)) continue;const theirs = this._theirDisplays(id);- for (const r of this.rulesFor(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;@@ -287,6 +300,7 @@ class Kvm extends EventEmitter {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 bothmine: this._myDisplays(),peers: this._portalPeers().map((id) => {const sess = this._session(id);@@ -323,7 +337,11 @@ class Kvm extends EventEmitter {const offset = Portals.mapOffset(r, ev.offset);// side + offset: where a computer without portals (or an older app) places the pointer insteadconst along = Portals.desktopOffset(theirs, r.target, offset);- this._take({ where: { portal: { target: r.target, offset }, side: r.target.side, offset: along === null ? 0.5 : along } }, id, before);+ // returns: every portal to that computer is a way back from it, each with the keys held to come back+ const back = this.cfg.portalKeys === 'back' || this.cfg.portalKeys === 'both';+ const returns = this.rulesFor(id).filter((x) => Portals.usableTarget(theirs, x.target))+ .map((x) => ({ id: x.id, target: x.target, modifiers: back ? x.modifiers : [] }));+ this._take({ where: { portal: { target: r.target, offset, id: r.id, returns }, side: r.target.side, offset: along === null ? 0.5 : along } }, id, before);}// Driven, a take through a portal: the helper places the pointer on that display's range first.@@ -889,7 +907,8 @@ class Kvm extends EventEmitter {this._onTake({ ...m, _portal: target || 'none' }, from);});}- this.portalReturn = m._portal && m._portal !== 'none' ? { target: m._portal } : null;+ 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;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)`);@@ -914,16 +933,29 @@ class Kvm extends EventEmitter {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 ? out : [{ id: '', target, modifiers: [] }];+ }+_armReturn() {const pr = this.portalReturn;if (pr) {- // the way back is the portal's range only (the helper's portalReturn)+ // the ways back are the portals' ranges only (the helper's portalReturns); side, zones and portal for an older helperconst 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;- this.helper.send('armReturn', { on: true, side: pr.target.side, sides: [pr.target.side], zones: `${from.toFixed(6)}-${to.toFixed(6)}`, portal: pr.target, resistancePx: this.cfg.resistancePx });+ 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;@@ -939,10 +971,13 @@ class Kvm extends EventEmitter {// 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, the pointer where it left (its pin there)+ // 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);- return this._sendHome(undefined, '');+ 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);}// 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).@@ -1087,9 +1122,11 @@ class Kvm extends EventEmitter {// 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).- _sendHome(offset, message, side = null) {+ // 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;diff --git a/mac/mesh/test/kvm-portals.test.js b/mac/mesh/test/kvm-portals.test.jsindex 01b03431..04f37c2d 100644--- a/mac/mesh/test/kvm-portals.test.js+++ b/mac/mesh/test/kvm-portals.test.js@@ -146,4 +146,56 @@ test('a portal from A’s display 1 right edge to B’s display 9 bottom edge: o}});+test('two portals: in through one, back through the other, the keys only coming back', async () => {+ const A = await node('A');+ const B = await node('B');+ try {+ await pair(B, A);+ await waitFor(() => linked(A, B), 'linked');+ const a = mac(A, [{ id: '1', name: 'Built-in', x: 0, y: 0, w: 1000, h: 600, primary: true }]);+ const b = mac(B, [{ id: '9', name: 'Studio', x: 0, y: 0, w: 2000, h: 1000, primary: true },+ { id: '8', name: 'Side', x: 2000, y: 0, w: 1000, h: 1000, primary: false }]);+ a.layoutSync.displaysChanged(); b.layoutSync.displaysChanged();+ await waitFor(() => (a.layoutSync.allDisplays()[B.id] || []).length === 2 && (b.layoutSync.allDisplays()[A.id] || []).length === 1, 'displays exchanged');+ await sleep(50);++ const p1 = { id: 'p1', source: { display: '1', side: 'top', from: 0, to: 0.5 }, target: { display: '9', side: 'bottom', from: 0, to: 1 }, modifiers: ['Command'], key: '' };+ const p2 = { id: 'p2', source: { display: '1', side: 'top', from: 0.5, to: 1 }, target: { display: '8', side: 'bottom', from: 0, to: 1 }, modifiers: ['Command'], key: '' };+ assert.ok(a.kvm.setPortals([p1, p2], B.id), 'saved');+ a.settings.kvm.portalsOn = true;+ a.settings.kvm.portalKeys = 'back';+ a.kvm.config();+ const cfg = a.helper.last('kvmConfig');+ assert.deepStrictEqual(cfg.portals.map((r) => r.modifiers), [[], []], 'no keys going there on an open edge');+ assert.strictEqual(a.kvm.view.portals.keys, 'back');++ // In through p1: B arms both portals as ways back, each with its keys.+ a.helper.emit('event', 'portal', { id: cfg.portals[0].id, offset: 0.25 });+ await waitFor(() => b.kvm.mode === 'driven', 'B driven');+ const arm = b.helper.last('armReturn');+ assert.deepStrictEqual(arm.portals.map((x) => [x.display, x.side, x.modifiers]), [['9', 'bottom', ['Command']], ['8', 'bottom', ['Command']]]);+ assert.strictEqual(arm.portal.display, '9', 'an older helper keeps the way it came');++ // Back through p2 (index 1), a quarter along: A places the pointer a quarter along p2's stretch.+ const homes = [];+ A.hub.bus.on(T.KVM_HOME, (m) => homes.push(m));+ b.helper.emit('event', 'return', { side: 'bottom', offset: 0.9, portal: 1, portalOffset: 0.25 });+ await waitFor(() => a.kvm.mode === 'home', 'A home');+ assert.deepStrictEqual(homes[0].portal, { id: 'p2', offset: 0.25 });+ const place = a.helper.last('placePortal');+ assert.strictEqual(place.display, '1');+ assert.strictEqual(place.side, 'top');+ assert.strictEqual(place.offset, 0.625);++ // In through p1 and back through p1: as before, the pointer where it left.+ a.helper.emit('event', 'portal', { id: cfg.portals[0].id, offset: 0.25 });+ await waitFor(() => b.kvm.mode === 'driven', 'B driven again');+ b.helper.emit('event', 'return', { side: 'bottom', offset: 0.3, portal: 0, portalOffset: 0.5 });+ await waitFor(() => homes.length === 2, 'home again');+ assert.strictEqual(homes[1].portal, undefined);+ } finally {+ close(A, B);+ }+});+runTests(tests);diff --git a/shared/lang/de.js b/shared/lang/de.jsindex ae667b91..20018e45 100644--- a/shared/lang/de.js+++ b/shared/lang/de.js@@ -2805,5 +2805,10 @@"Shortcut to bring everything back to {device}": "Tastenkürzel, um alles zu {device} zurückzuholen","Another app uses the shortcut for {devices}. Pick other keys.": "Eine andere App nutzt das Tastenkürzel für {devices}. Wähle andere Tasten.","Choose a page": "Seite wählen",- "Choose a space": "Bereich wählen"+ "Choose a space": "Bereich wählen",+ "When to hold the keys": "Wann die Tasten halten",+ "Coming back works through any portal on the other computer, each to its own place here.": "Zurück geht es durch jedes Portal auf dem anderen Computer, jeweils an seine eigene Stelle hier.",+ "Going there": "Auf dem Hinweg",+ "Coming back": "Auf dem Rückweg",+ "Both ways": "In beide Richtungen"});diff --git a/shared/lang/en.js b/shared/lang/en.jsindex 36ab5f45..e8ecc1d3 100644--- a/shared/lang/en.js+++ b/shared/lang/en.js@@ -2807,5 +2807,10 @@"Shortcut to bring everything back to {device}": "Shortcut to bring everything back to {device}","Another app uses the shortcut for {devices}. Pick other keys.": "Another app uses the shortcut for {devices}. Pick other keys.","Choose a page": "Choose a page",- "Choose a space": "Choose a space"+ "Choose a space": "Choose a space",+ "When to hold the keys": "When to hold the keys",+ "Coming back works through any portal on the other computer, each to its own place here.": "Coming back works through any portal on the other computer, each to its own place here.",+ "Going there": "Going there",+ "Coming back": "Coming back",+ "Both ways": "Both ways"});diff --git a/shared/lang/es.js b/shared/lang/es.jsindex 051a329d..f0134cf1 100644--- a/shared/lang/es.js+++ b/shared/lang/es.js@@ -2805,5 +2805,10 @@"Shortcut to bring everything back to {device}": "Atajo para traer todo de vuelta a {device}","Another app uses the shortcut for {devices}. Pick other keys.": "Otra app usa el atajo de {devices}. Elige otras teclas.","Choose a page": "Elige una página",- "Choose a space": "Elige un espacio"+ "Choose a space": "Elige un espacio",+ "When to hold the keys": "Cuándo mantener las teclas",+ "Coming back works through any portal on the other computer, each to its own place here.": "Se vuelve por cualquier portal del otro ordenador, cada uno a su propio lugar aquí.",+ "Going there": "Al ir",+ "Coming back": "Al volver",+ "Both ways": "En ambos sentidos"});diff --git a/shared/lang/pt-BR.js b/shared/lang/pt-BR.jsindex 8e60ccd6..d5a57592 100644--- a/shared/lang/pt-BR.js+++ b/shared/lang/pt-BR.js@@ -2807,5 +2807,10 @@"Shortcut to bring everything back to {device}": "Atalho para trazer tudo de volta para {device}","Another app uses the shortcut for {devices}. Pick other keys.": "Outro app usa o atalho de {devices}. Escolha outras teclas.","Choose a page": "Escolha uma página",- "Choose a space": "Escolha um espaço"+ "Choose a space": "Escolha um espaço",+ "When to hold the keys": "Quando segurar as teclas",+ "Coming back works through any portal on the other computer, each to its own place here.": "A volta funciona por qualquer portal no outro computador, cada um para o seu próprio lugar aqui.",+ "Going there": "Na ida",+ "Coming back": "Na volta",+ "Both ways": "Nos dois sentidos"});diff --git a/shared/lang/ru.js b/shared/lang/ru.jsindex b865a4d1..789e40cf 100644--- a/shared/lang/ru.js+++ b/shared/lang/ru.js@@ -2807,5 +2807,10 @@"Shortcut to bring everything back to {device}": "Сочетание, чтобы вернуть всё на {device}","Another app uses the shortcut for {devices}. Pick other keys.": "Другое приложение использует сочетание для {devices}. Выберите другие клавиши.","Choose a page": "Выберите страницу",- "Choose a space": "Выберите пространство"+ "Choose a space": "Выберите пространство",+ "When to hold the keys": "Когда удерживать клавиши",+ "Coming back works through any portal on the other computer, each to its own place here.": "Вернуться можно через любой портал на другом компьютере, каждый ведёт в своё место здесь.",+ "Going there": "Туда",+ "Coming back": "Обратно",+ "Both ways": "В обе стороны"});diff --git a/shared/lang/tr.js b/shared/lang/tr.jsindex 1e35f7a1..0b53ddaa 100644--- a/shared/lang/tr.js+++ b/shared/lang/tr.js@@ -2807,5 +2807,10 @@"Shortcut to bring everything back to {device}": "Her şeyi {device} cihazına geri getirme kısayolu","Another app uses the shortcut for {devices}. Pick other keys.": "Başka bir uygulama {devices} için kısayolu kullanıyor. Başka tuşlar seçin.","Choose a page": "Bir sayfa seçin",- "Choose a space": "Bir alan seçin"+ "Choose a space": "Bir alan seçin",+ "When to hold the keys": "Tuşlar ne zaman basılı tutulsun",+ "Coming back works through any portal on the other computer, each to its own place here.": "Geri dönüş, diğer bilgisayardaki herhangi bir portaldan yapılır; her biri buradaki kendi yerine götürür.",+ "Going there": "Giderken",+ "Coming back": "Dönerken",+ "Both ways": "Her iki yönde"});diff --git a/shared/lang/zh-CN.js b/shared/lang/zh-CN.jsindex 7887ad8f..783d7474 100644--- a/shared/lang/zh-CN.js+++ b/shared/lang/zh-CN.js@@ -2808,5 +2808,10 @@"Shortcut to bring everything back to {device}": "将一切带回 {device} 的快捷键","Another app uses the shortcut for {devices}. Pick other keys.": "另一个应用正在使用 {devices} 的快捷键。请选择其他按键。","Choose a page": "选择页面",- "Choose a space": "选择空间"+ "Choose a space": "选择空间",+ "When to hold the keys": "何时按住按键",+ "Coming back works through any portal on the other computer, each to its own place here.": "可以从另一台电脑上的任意传送门返回,每个都回到这里对应的位置。",+ "Going there": "去程",+ "Coming back": "返程",+ "Both ways": "双向"});diff --git a/shared/ui-cursor-portals.js b/shared/ui-cursor-portals.jsindex 76aaec27..6224fe33 100644--- a/shared/ui-cursor-portals.js+++ b/shared/ui-cursor-portals.js@@ -81,11 +81,16 @@ const CursorPortalsUI = {const key = UI.select(keyOptions, (v) => { pick.key = v; check(); });key.el.setAttribute('aria-label', t('Additional shortcut key'));const keysRow = UI.row(t('Hold to go through'), t('Held while the pointer reaches the portal. Needed on an edge that touches another display here.'), [el('div', { class: 'cp-chips' }, chips.map((c) => c.b)), key.el]);+ // Multi-device on the Mac: when the keys are held (kvm.portalKeys); coming back works through any of the portals there+ const way = UI.select([{ value: 'there', label: t('Going there') }, { value: 'back', label: t('Coming back') }, { value: 'both', label: t('Both ways') }],+ (v) => api.setKvm({ portalKeys: v }));+ way.el.setAttribute('aria-label', t('When to hold the keys'));+ const wayRow = UI.row(t('When to hold the keys'), t('Coming back works through any portal on the other computer, each to its own place here.'), [way.el]);const status = el('span', { class: 'cp-status', attrs: { role: 'status' } });const add = UI.button(t('Add portal'), () => addRule());const addRow = el('div', { class: 'cp-add' }, [status, add]);const list = el('div', { class: 'cp-list' });- const editor = el('div', { class: 'cp-editor' }, [peerSeg, stage, stageHint, keysRow, addRow, list]);+ const editor = el('div', { class: 'cp-editor' }, [peerSeg, stage, stageHint, keysRow, wayRow, addRow, list]);const wrap = UI.card(t('Cursor portals'), [intro, note, editor]);wrap.classList.add('cp-card');@@ -348,6 +353,8 @@ const CursorPortalsUI = {state = { ...ps, peers, on };where = kv.where || kv.mode || 'home';sw.set(on);+ wayRow.hidden = !ps.keys;+ if (ps.keys) way.set(ps.keys);editor.hidden = !on || !peers.length;if (!peers.some((x) => x.id === peerId)) { peerId = peers.length ? peers[0].id : ''; pick.dst = null; }// the computer picker (Multi-device: several)