One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.0-beta.3
Toby Kalkman83015a30fd4c
diff --git a/VERSION b/VERSIONindex 5b50064..9a97bef 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.0-beta.2+1.5.0-beta.3diff --git a/core/owner.py b/core/owner.pyindex 5e97d54..65c888d 100644--- a/core/owner.py+++ b/core/owner.py@@ -32,7 +32,8 @@ from dataclasses import dataclassfrom typing import OptionalTAKE_WAIT = 1.0 # seconds a take waits for its `accept`-LEFT_OUT = 3.0 # seconds a peer that did not take a hand-over stays out of `reach`+LEFT_OUT = 3.0 # seconds a peer that did not take a hand-over, or refused a take, is not asked again+SENT_HOME_FOR = 5.0 # a peer that sent this machine home refuses it this long (receiver.SENT_HOME_SECONDS)CLIPBOARD_AFTER = 10.0 # seconds after a let-go that the machine let go may send its clipboardTAKE_MEMORY = 30.0 # seconds a take is remembered, so a late `accept` can still be let goREFUSALS = ("owned", "not_allowed", "busy", "sent_home", "malformed")@@ -160,6 +161,8 @@ class Owner:def link_down(self, peer):self._links.discard(peer)self._accepting.discard(peer)+ # Its clipboard may still have been on the way, or waiting behind a slow read: sent again.+ self._clipboard_at.discard(peer)if peer == self.on:return self._come_home("link_lost")if self._wait is not None and self._wait.chain and self._wait.peer == peer:@@ -186,6 +189,8 @@ class Owner:return []if peer not in self._links & self._accepting:return [Unreachable(peer, "unreachable")]+ if self.held_back(peer):+ return []left = self.onself._wait = Noneself.route += 1@@ -243,6 +248,7 @@ class Owner:return []# The take's own route too: a re-arm sent before its answer came raised the route past it.if peer == self.on and (route == self.route or (wait is not None and route == wait.route)):+ self._hold_back(peer, why)return self._come_home(why)return []@@ -388,9 +394,18 @@ class Owner:"""A hand-over from the machine the input is on did not happen: re-arm it without `peer`."""self._wait = Noneif peer is not None:- self._left_out[peer] = self._clock() + LEFT_OUT+ self._hold_back(peer, why)return self._stay() + [Unreachable(peer, why)] + self._replay_held()+ def held_back(self, peer):+ """Whether `peer` refused, or did not take, a move a moment ago and is not asked again yet."""+ return self._left_out.get(peer, 0) > self._clock()++ def _hold_back(self, peer, why):+ """`peer` is not asked again for as long as it would refuse: each push at its edge would+ otherwise ask, be refused, and say so."""+ self._left_out[peer] = self._clock() + (SENT_HOME_FOR if why == "sent_home" else LEFT_OUT)+def _stay(self):self.route += 1self.reach_sent = self.reach_for(self.on)diff --git a/core/settings_sync.py b/core/settings_sync.pyindex 6ae49ee..70f69f3 100644--- a/core/settings_sync.py+++ b/core/settings_sync.py@@ -222,7 +222,6 @@ def changed(before, after):return any(before.get(key) != after.get(key) for key in CROSSING_KEYS + DESIGN_KEYS)-# What the window says. `peer` is "PC" on the Mac and "Mac" on the PC.SHARED_PAGES = ("crossing", "design")diff --git a/core/tests/test_owner.py b/core/tests/test_owner.pyindex b067dbc..6b33952 100644--- a/core/tests/test_owner.py+++ b/core/tests/test_owner.py@@ -130,6 +130,56 @@ class TakeFromHomeTests(OwnerCase):self.assertEqual(moved(actions).to, None)self.assertEqual(moved(actions).why, why if why != "something_new" else "refused")self.assertFalse(self.o.away)+ self.clock.now += owner.SENT_HOME_FOR++ def test_a_machine_that_refused_a_take_is_not_taken_again_for_a_while(self):+ # The live check, 01-10-2026: every push at the laptop's edge took the rig again while the+ # Mac drove it, about 30 refusals and 30 notices in 20 seconds.+ for why in ("owned", "busy", "not_allowed"):+ with self.subTest(why=why):+ self.o.go("B")+ self.o.refuse("B", {"route": self.o.route, "why": why})+ self.clock.now += owner.LEFT_OUT / 2+ self.assertEqual(self.o.go("B"), [])+ self.assertFalse(self.o.away)+ self.clock.now += owner.LEFT_OUT / 2+ self.assertEqual(moved(self.o.go("B")).to, "B")+ self.o.go(None)++ def test_a_machine_that_sent_this_one_home_is_left_alone_for_as_long_as_it_would_refuse(self):+ # The live check, 01-10-2026: thirty "sent_home" refusals in three seconds between two machines.+ self.o.go("B")+ self.o.refuse("B", {"route": self.o.route, "why": "sent_home"})+ self.clock.now += owner.SENT_HOME_FOR - 0.1+ self.assertEqual(self.o.go("B"), [])+ self.clock.now += 0.1+ self.assertEqual(moved(self.o.go("B")).to, "B")++ def test_the_sent_home_window_is_the_responders_own(self):+ from core import receiver+ self.assertEqual(owner.SENT_HOME_FOR, receiver.SENT_HOME_SECONDS)++ def test_a_machine_held_back_does_not_hold_back_the_others(self):+ self.o.go("B")+ self.o.refuse("B", {"route": self.o.route, "why": "owned"})+ self.assertEqual(moved(self.o.go("C")).to, "C")++ def test_asking_for_a_machine_held_back_from_another_changes_nothing(self):+ self.o.go("B")+ self.o.refuse("B", {"route": self.o.route, "why": "owned"})+ self.take("C")+ route = self.o.route+ self.assertEqual(self.o.go("B"), [])+ self.assertEqual((self.o.on, self.o.route), ("C", route))++ def test_a_hand_over_refused_as_sent_home_holds_back_as_long_as_the_refusal(self):+ self.take("B")+ self.switch("B", "C")+ self.o.refuse("C", {"route": self.o.route, "why": "sent_home"})+ self.clock.now += owner.SENT_HOME_FOR - 0.1+ self.assertNotIn("C", self.o.reach_for(None))+ self.clock.now += 0.1+ self.assertIn("C", self.o.reach_for(None))def test_a_refusal_for_an_old_route_is_ignored(self):self.take("B")@@ -153,6 +203,7 @@ class TakeFromHomeTests(OwnerCase):self.o.go("B")self.o.refuse("B", {"route": 1, "why": "busy"})self.assertIsNone(self.o.on)+ self.clock.now += owner.LEFT_OUTself.take("B")self.assertEqual(self.o.on, "B")@@ -409,6 +460,7 @@ class ComingHomeTests(OwnerCase):("B", {"type": "focus", "data": {"route": self.o.route, "target": "A"}})])self.assertEqual(self.o.input(key("keyup", "shift")), [])self.assertEqual(self.o.input(key("keyup", "shift")), [LOCAL])+ self.clock.now += owner.LEFT_OUTdef test_the_owner_releases_what_it_pressed_there_before_letting_go(self):self.take("B")@@ -488,6 +540,7 @@ class ClipboardTests(OwnerCase):def test_a_refused_take_does_not_count_as_having_the_clipboard(self):self.o.go("B")self.o.refuse("B", {"route": 1, "why": "owned"})+ self.clock.now += owner.LEFT_OUTself.assertIn(SendClipboard("B"), self.take("B"))def test_the_machine_left_keeps_its_clipboard_when_the_next_one_refuses_first(self):@@ -497,6 +550,13 @@ class ClipboardTests(OwnerCase):message = {"type": "clipboard", "data": {"text": "copied on B"}}self.assertEqual(self.o.clipboard_arrived("B", 1000.25, message), [SetClipboard(message)])+ def test_a_machine_whose_link_was_lost_is_sent_the_clipboard_again(self):+ # Its clipboard may still have been on the way, or waiting behind a slow read, when the link went.+ self.take("B")+ self.o.link_down("B")+ self.o.link_up("B", True)+ self.assertIn(SendClipboard("B"), self.take("B"))+def test_the_clipboard_goes_after_the_taking_focus_and_before_any_input(self):actions = self.o.go("B")focus_at = next(i for i, a in enumerate(actions) if isinstance(a, Send))diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.pyindex 4178e4c..a5d1658 100644--- a/core/tests/test_settings_sync.py+++ b/core/tests/test_settings_sync.py@@ -236,7 +236,7 @@ class RelayTests(unittest.TestCase):class WordsTests(unittest.TestCase):def test_a_shared_page_says_so_only_while_on(self):- own = "For this Mac only; the PC keeps its own."+ own = "For this Mac only; the other machine keeps its own."everyone = settings_sync.who(["Studio", "Laptop"])self.assertEqual(settings_sync.scope("crossing", everyone, False, own), own)self.assertEqual(settings_sync.scope("design", everyone, True, own),diff --git a/core/tests/test_three_machines.py b/core/tests/test_three_machines.pyindex 559fa3d..d02bea4 100644--- a/core/tests/test_three_machines.py+++ b/core/tests/test_three_machines.py@@ -33,7 +33,9 @@ class ScriptedOwner:def __init__(self, test, own, machines):self.test = testself.own = own- self.owner = owner_module.Owner(text(own), time.monotonic)+ # Its own clock runs ahead by `ahead`, so a test can wait out a refusal's back-off at once.+ self.ahead = 0.0+ self.owner = owner_module.Owner(text(own), lambda: time.monotonic() + self.ahead)self.links = {}self.sent = []self.moved = []@@ -263,6 +265,9 @@ class Competing(unittest.TestCase):self.assertEqual(self.a.responder.owner, O)self.first.go(None)self.assertTrue(wait_for(lambda: self.a.responder.owner is None))+ # A refused machine is not asked again until its back-off has passed.+ self.assertEqual(self.second.owner.go(text(A)), [])+ self.second.ahead += owner_module.LEFT_OUTself.second.go(self.a)self.assertTrue(self.second.until(lambda: self.a.responder.owner == O2))self.assertEqual(self.second.on, text(A))@@ -302,7 +307,8 @@ class TwoDesktopsTakeEachOther(unittest.TestCase):self.assertEqual(owners[here].moved[-1].why, "busy")self.assertIsNone(x.responder.owner)self.assertIsNone(y.responder.owner)- # Neither is stuck: one take now gets in.+ # Neither is stuck: once the back-off has passed, one take gets in.+ owners[A].ahead += owner_module.LEFT_OUTowners[A].go(y)self.assertTrue(owners[A].until(lambda: y.responder.owner == A))diff --git a/mac_app/bridge.py b/mac_app/bridge.pyindex a5dfad7..9ea7971 100644--- a/mac_app/bridge.py+++ b/mac_app/bridge.py@@ -65,10 +65,6 @@ OWN_PLATFORM = "macos"CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings")MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"})-# The local sentinel a clipboard read is deferred with: the event tap must never wait on the-# pasteboard, so it queues this and the outbound worker reads it, in order with the input behind it.-_LOCAL_CLIPBOARD_SENTINEL_TYPE = "_local_clipboard"-# Why input came home, in words, for the alert. A why that is not here comes home quietly.WHY_TEXT = {"owned": "{name} is being driven from another machine",@@ -430,15 +426,6 @@ def links_from_store(settings_store, app_version):return settings_store.book(), identity-class _Literal(dict):- """A message whose key names are the receiver's own words already, which the key table must- leave alone: the gestures press the PC's Control for a zoom, and that is Control there."""---def _literal(messages):- return [_Literal(message) for message in messages]--class _MemoryBook(receiver.PeerBook):"""The peers a controller built from a Config alone has: peers[0] from the flat fields, nothingon disk. The app hands in the settings store's book instead; this is what the controller has@@ -627,6 +614,12 @@ class KVMController:self._cfg_lock = threading.Lock()self._owner_lock = threading.RLock()self._effects_lock = threading.RLock()+ # A peer whose clipboard is being read, and what was decided for it meanwhile, in order; and+ # the pasteboard's reads and writes, done one at a time in order on a thread of their own.+ self._clip_lock = threading.Lock()+ self._clip_wait = {}+ self._pasteboard_jobs = collections.deque()+ self._pasteboard_busy = Falseself.owner = owner_module.Owner(protocol.id_text(self.identity()["id"]), clock, resistance_px=int(self.crossing.resistance_px))self._clipboard_stamp = Noneself._paired_ids = ()@@ -805,6 +798,10 @@ class KVMController:def stop(self):self._return_local()+ # The let-go and what is ahead of it may be waiting behind a clipboard read: sent first.+ deadline = time.monotonic() + 1.0+ while (self._clip_wait or self._pasteboard_busy) and time.monotonic() < deadline:+ time.sleep(0.01)for link in list(self.links.values()):link.flush(0.3)self.stop_event.set()@@ -995,8 +992,8 @@ class KVMController:self.crossing.reset()def _enqueue_control(self, message):- """Queue a local control message (the clipboard sentinel) from the event tap, which must- never block. Best-effort: a momentarily full queue drops it (logged)."""+ """Queue a message the event tap made itself, which must never block. Best-effort: a+ momentarily full queue drops it (logged)."""try:self.outbound.put_nowait(message)except queue.Full:@@ -1338,6 +1335,14 @@ class KVMController:return eventif not self.connected:return event+ peer = self._primary_link.peer_id+ with self._owner_lock:+ # Held back after a refusal, as Windows' zones are: a push that cannot take it must not+ # pin the pointer and glow as if it would.+ held_back = bool(peer) and self.owner.held_back(peer)+ if held_back:+ self.crossing.reset()+ return eventtry:quartz = self.quartzlocation = quartz.CGEventGetLocation(event)@@ -1492,12 +1497,12 @@ class KVMController:# would open Mission Control or switch Spaces on the Mac while# the user is looking at Windows.fields = self._read_dock_event(event)- messages = _literal(self.dock_classifier.translate(fields) if fields is not None else [])+ messages = self.dock_classifier.translate(fields) if fields is not None else []else:gesture_view = self._convert_gesture_event(event)if gesture_view is None:return event- messages = _literal(self.gesture_translator.translate(event_type, gesture_view))+ messages = self.gesture_translator.translate(event_type, gesture_view)if not self._gesture_capture_logged:self._gesture_capture_logged = Trueself.logger.info("gesture capture active")@@ -1531,7 +1536,7 @@ class KVMController:self._overlay_gesture_capture_logged = Trueself.logger.info("gesture capture active (overlay)")try:- messages = _literal(self.gesture_translator.translate(event_type, gesture_view))+ messages = self.gesture_translator.translate(event_type, gesture_view)except Exception:self.logger.exception("overlay gesture translation failed")return@@ -1648,6 +1653,7 @@ class KVMController:peer = link.peer_idif peer and self._peers_up.get(peer) is link:self._peers_up.pop(peer, None)+ self._forget_held(peer)self._step(lambda owner: owner.link_down(peer))def _connection_worker(self):@@ -1716,6 +1722,7 @@ class KVMController:# this registered the link: undo what that could not see.if self._peers_up.get(peer) is link:del self._peers_up[peer]+ self._forget_held(peer)self._step(lambda owner: owner.link_down(peer))returnself.logger.info("connected to %s", fields["name"])@@ -1876,15 +1883,10 @@ class KVMController:effects.append(action)continuetry:- if isinstance(action, owner_module.Send):+ if isinstance(action, (owner_module.Send, owner_module.SendClipboard)):self._deliver(action)- elif isinstance(action, owner_module.SendClipboard):- if threading.current_thread() is self.capture_thread:- self._enqueue_control({"type": _LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}, "peer": action.peer})- else:- self._send_clipboard(action.peer)else:- self._set_clipboard(action.message)+ self._on_pasteboard(lambda message=action.message: self._set_clipboard(message))except Exception:# One message that cannot go must not stop the move it belongs to: its Moved is next.self.logger.exception("carrying out %s failed", type(action).__name__)@@ -1897,11 +1899,98 @@ class KVMController:elif isinstance(effect, owner_module.Unreachable):self._on_unreachable(effect)- def _deliver(self, send):+ def _deliver(self, action):+ """Sends in the order the owner gave them, except that reading the pasteboard (which can take+ seconds, while the event tap waits for the owner's lock) is done on a thread of its own:+ what follows a clipboard read for the same peer waits for it, and everything else goes on."""+ with self._clip_lock:+ waiting = self._clip_wait.get(action.peer)+ if waiting is not None:+ waiting.append(action)+ return+ if isinstance(action, owner_module.SendClipboard):+ waiting = self._clip_wait[action.peer] = collections.deque()+ try:+ self._on_pasteboard_locked(lambda peer=action.peer: self._clipboard_then_rest(peer, waiting))+ except RuntimeError:+ # No thread at shutdown: nothing must wait behind a read that never starts.+ del self._clip_wait[action.peer]+ raise+ return+ self._send(action)++ def _on_pasteboard(self, job):+ with self._clip_lock:+ self._on_pasteboard_locked(job)++ def _on_pasteboard_locked(self, job):+ """Under `_clip_lock`: `job` done after every pasteboard job before it, on the one thread+ that does them, started when there is none."""+ self._pasteboard_jobs.append(job)+ if self._pasteboard_busy:+ return+ try:+ threading.Thread(target=self._pasteboard_worker, name="Beamer-clipboard", daemon=True).start()+ except RuntimeError:+ self._pasteboard_jobs.pop()+ raise+ self._pasteboard_busy = True++ def _pasteboard_worker(self):+ while True:+ with self._clip_lock:+ if not self._pasteboard_jobs:+ self._pasteboard_busy = False+ return+ job = self._pasteboard_jobs.popleft()+ try:+ job()+ except Exception:+ self.logger.exception("pasteboard work failed")++ def _clipboard_then_rest(self, peer, waiting):+ """The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs to+ the link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the+ machine that reconnects will be taken afresh. A clipboard asked for again takes its turn+ among the pasteboard's other work, behind any write decided before it."""+ try:+ self._send_clipboard(peer, waiting)+ except Exception:+ self.logger.exception("the clipboard could not be sent")+ while True:+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ return+ if not waiting:+ del self._clip_wait[peer]+ return+ action = waiting.popleft()+ if isinstance(action, owner_module.SendClipboard):+ self._on_pasteboard_locked(lambda: self._clipboard_then_rest(peer, waiting))+ return+ try:+ self._send(action)+ except Exception:+ self.logger.exception("a message held behind the clipboard could not be sent")++ def _forget_held(self, peer):+ """`peer`'s link is lost: what waited for its clipboard is for a link that is gone."""+ with self._clip_lock:+ self._clip_wait.pop(peer, None)++ def _send(self, send):link = self._peers_up.get(send.peer)if link is None:returnmessage = send.message+ if message.get("type") == gestures.CHORD:+ receiver = "mac" if keytable.is_mac(link.peer_platform) else "windows"+ for part in gestures.chord_for(message["data"]["action"], receiver):+ if not link.send_input(part):+ if link.live():+ link.drop("The outbound queue filled")+ return+ returnif message.get("type") in protocol.INPUT_TYPES:message = self._for_peer(message, link)if message is None:@@ -1918,7 +2007,7 @@ class KVMController:def _for_peer(self, message, link):"""A captured input message as the peer it is going to names it: modifiers by the keytable (WIRE.md section 7), and media keys only to a peer that acts on them."""- if message.get("type") not in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP) or isinstance(message, _Literal):+ if message.get("type") not in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):return messagedata = dict(message["data"])key = data.get("key")@@ -1993,14 +2082,20 @@ class KVMController:with self._owner_lock:self.owner.clipboard_changed()- def _send_clipboard(self, peer):+ def _send_clipboard(self, peer, waiting):"""Read this Mac's clipboard and send it as a clipboard message. Text over CLIPBOARD_MAX_BYTESand an image over CLIPBOARD_IMAGE_MAX_BYTES are each dropped on their own, so an oversized- screenshot still lets its text through; with nothing left nothing is sent."""+ screenshot still lets its text through; with nothing left nothing is sent. Nothing is sent+ either when `waiting` was dropped with its link while the pasteboard was read."""+ if self._peers_up.get(peer) is None:+ return+ text, image = self.clipboard.get_contents()+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ returnlink = self._peers_up.get(peer)if link is None:return- text, image = self.clipboard.get_contents()if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:self.logger.warning("local clipboard text is too large; skipping the text")text = None@@ -2052,13 +2147,9 @@ class KVMController:self._step(lambda owner: owner.tick())def _process_outbound(self, message):- """Handle one dequeued item: the clipboard sentinel, or input the tap captured, which the- owner routes (to the machine it is on, held for a hand-over, or dropped when it has- already come home)."""+ """Handle one dequeued item: input the tap captured, which the owner routes (to the machine+ it is on, held for a hand-over, or dropped when it has already come home)."""kind = message.get("type")- if kind == _LOCAL_CLIPBOARD_SENTINEL_TYPE:- self._send_clipboard(message["peer"])- returnif kind in (protocol.MSG_KEYUP, protocol.MSG_MOUSEUP):# Whether or not the input is away: the release of a key pressed there that arrives# after it came home is what lets the owner stop swallowing it.diff --git a/mac_app/clipboard_mac.py b/mac_app/clipboard_mac.pyindex 88ca73f..418d2d4 100644--- a/mac_app/clipboard_mac.py+++ b/mac_app/clipboard_mac.py@@ -1,13 +1,10 @@"""macOS clipboard access via AppKit's NSPasteboard.`get_contents`/`set_contents` are called from background threads: the-outbound worker (when switching redirect to Windows, to grab the outgoing-clipboard) and the ack-receiver thread (when a clipboard message arrives from-Windows). Apple doesn't document NSPasteboard as thread-safe, but-reading/writing the general pasteboard from a background thread is widely-relied upon in practice and has not shown problems in manual testing. Flagging-here as the one part of this feature that still wants confirmation on a real-machine under load.+controller's clipboard thread, and the responder's link threads when this Mac+is driven. Apple doesn't document NSPasteboard as thread-safe, and two threads+reading it at once have raised from inside AppKit, so every read and write of+the contents takes `_LOCK`.AppKit is imported at module level (pyobjc is already a hard dependency ofthis app -- bridge.py imports Quartz/objc the same way) but guarded so the@@ -17,6 +14,7 @@ rather than mocking imports."""import logging+import threadingtry:import AppKit@@ -30,6 +28,10 @@ LOGGER = logging.getLogger("Beamer")# so an unchanged screenshot is not pushed across on every switch._synced_count = None+# Every read and write of the contents, from whichever thread: one at a time. The change count is+# left out, so a caller that only asks whether the pasteboard moved never waits behind a slow read.+_LOCK = threading.Lock()+def _text_from_pasteboard(pasteboard):text = pasteboard.stringForType_(AppKit.NSPasteboardTypeString)@@ -63,8 +65,9 @@ def get_contents():if AppKit is None:return None, Nonetry:- pasteboard = AppKit.NSPasteboard.generalPasteboard()- return _text_from_pasteboard(pasteboard), _png_from_pasteboard(pasteboard)+ with _LOCK:+ pasteboard = AppKit.NSPasteboard.generalPasteboard()+ return _text_from_pasteboard(pasteboard), _png_from_pasteboard(pasteboard)except Exception:LOGGER.exception("failed to read the macOS clipboard")return None, None@@ -113,16 +116,17 @@ def set_contents(text, png):if AppKit is None or (text is None and png is None):return Falsetry:- pasteboard = AppKit.NSPasteboard.generalPasteboard()- pasteboard.clearContents()- wrote = False- if text is not None:- wrote |= bool(pasteboard.setString_forType_(text, AppKit.NSPasteboardTypeString))- if png is not None:- data = AppKit.NSData.dataWithBytes_length_(png, len(png))- wrote |= bool(pasteboard.setData_forType_(data, AppKit.NSPasteboardTypePNG))- if wrote:- _synced_count = pasteboard.changeCount()+ with _LOCK:+ pasteboard = AppKit.NSPasteboard.generalPasteboard()+ pasteboard.clearContents()+ wrote = False+ if text is not None:+ wrote |= bool(pasteboard.setString_forType_(text, AppKit.NSPasteboardTypeString))+ if png is not None:+ data = AppKit.NSData.dataWithBytes_length_(png, len(png))+ wrote |= bool(pasteboard.setData_forType_(data, AppKit.NSPasteboardTypePNG))+ if wrote:+ _synced_count = pasteboard.changeCount()return wroteexcept Exception:LOGGER.exception("failed to set the macOS clipboard")diff --git a/mac_app/diagram.py b/mac_app/diagram.pyindex c147766..e28d02f 100644--- a/mac_app/diagram.py+++ b/mac_app/diagram.py@@ -1,5 +1,5 @@"""The Crossing page's two drawings, in Core Animation layers so every change can move: the-arrangement, which shows where the PC sits and what crosses, and the push strip, which shows how+arrangement, which shows where the other machine sits and what crosses, and the push strip, which shows howfar the pointer is pushed past the edge before it gives."""from __future__ import annotations@@ -53,7 +53,7 @@ def _collapsed(frame, side):class ArrangementDiagram(AppKit.NSView):- """This Mac's screen with the PC's beside it on the chosen side, lit where a way in crosses."""+ """This Mac's screen with the other machine's beside it on the chosen side, lit where a way in crosses."""HEIGHT = 186.0@@ -188,7 +188,7 @@ class ArrangementDiagram(AppKit.NSView):class PushStrip(AppKit.NSView):- """The last stretch of this Mac's screen, the edge, and the PC beyond it, with the push past the+ """The last stretch of this Mac's screen, the edge, and the other machine beyond it, with the push past theedge drawn in: its depth is the resistance, out of the ruler's 500 px."""HEIGHT = 44.0@@ -230,7 +230,7 @@ class PushStrip(AppKit.NSView):for layer in (self.this, self.fill, self.edge, self.this_label, self.other_label, self.pointer):root.addSublayer_(layer)self.fraction = None- self.other_name = "PC"+ self.other_name = "Other machine"self.setAccessibilityElement_(False)return self@@ -240,7 +240,7 @@ class PushStrip(AppKit.NSView):self._draw(False)@objc.python_method- def show(self, fraction, other_name="PC"):+ def show(self, fraction, other_name="Other machine"):fraction = min(1.0, max(0.0, float(fraction)))if fraction == self.fraction and other_name == self.other_name:return@@ -262,7 +262,7 @@ class PushStrip(AppKit.NSView):if width <= 0:returnedge = round(width * self.EDGE_AT)- # The full 500 px stops short of the PC's name, so the name is never under the push.+ # The full 500 px stops short of the other machine's name, so the name is never under the push.room = width - edge - 120depth = room * self.fractionmotion.transaction(animate)diff --git a/mac_app/gestures.py b/mac_app/gestures.pyindex b2bec3c..312af7f 100644--- a/mac_app/gestures.py+++ b/mac_app/gestures.py@@ -19,8 +19,10 @@ raw values:`DockSwipeClassifier` handles the tap's DockControl events and emits one`gesture` message per completed movement. `GestureTranslator` handles the-overlay's NSEvents, turning a pinch into Ctrl+wheel and a page swipe into-Alt+Arrow with no Windows-side change. A zoom gesture was never observed to+overlay's NSEvents, turning a pinch into zoom steps and a page swipe into back+or forward, each a CHORD that `chord_for` shapes for the machine it is sent to:+Ctrl+wheel and Alt+Arrow for a PC, Command with = - [ ] for a Mac, with no+change on the receiving side. A zoom gesture was never observed toreach the tap, so the overlay is the only route for it, and it remainsbest-effort.@@ -130,25 +132,43 @@ NS_EVENT_PHASE_ENDED = 8NS_EVENT_PHASE_CANCELLED = 16_PHASE_RESET_MASK = NS_EVENT_PHASE_ENDED | NS_EVENT_PHASE_CANCELLED-# Accumulated `.magnification` needed before one Ctrl+wheel zoom step fires.-# Positive magnification (fingers spreading -- zooming in) maps to a-# positive wheel delta, matching the usual "Ctrl+scroll up zooms in"-# convention in browsers and other zoomable apps.+# Accumulated `.magnification` needed before one zoom step fires. Positive+# magnification (fingers spreading) zooms in: on a PC a positive wheel delta,+# matching the usual "Ctrl+scroll up zooms in" convention in browsers and other+# zoomable apps, and on a Mac Command-=.MAGNIFY_STEP = 0.05-RECEIVERS = ("windows", "mac")+# Never on the wire: a zoom step or a page swipe whose chord is chosen when it is sent to a machine,+# since the machine input is on can change between capture and sending.+CHORD = "gesture_chord"+++def chord_for(action, receiver):+ """The messages that make `action` ("zoom_in", "zoom_out", "back", "forward") on `receiver`. The+ wire's key names are the receiver's own words, so a Mac's "cmd" is Command and Windows' "ctrl"+ is Control. `receiver` is "mac" for a Mac and anything else for a PC."""+ if action not in ("zoom_in", "zoom_out", "back", "forward"):+ raise ValueError(f"unknown gesture action: {action!r}")+ if action in ("zoom_in", "zoom_out"):+ direction = 1 if action == "zoom_in" else -1+ if receiver == "mac":+ return _chord("cmd", "=" if direction > 0 else "-")+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},+ protocol.scroll_msg(dy=direction, dx=0, mode="line"),+ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},+ ]+ if receiver == "mac":+ return _chord("cmd", "[" if action == "back" else "]")+ return _chord("alt", "left" if action == "back" else "right")class GestureTranslator:- """`receiver` is the platform of the machine being driven: a zoom or a page swipe is the- chord that machine answers to. The wire's key names are the receiver's own words, so a Mac's- "cmd" is Command and Windows' "ctrl" is Control."""-- def __init__(self, logger=None, receiver="windows"):- if receiver not in RECEIVERS:- raise ValueError(f"unknown receiver platform: {receiver!r}")- self.receiver = receiver+ """A zoom step or a page swipe comes out as one CHORD message, for `chord_for` to shape once+ the machine it goes to is known."""++ def __init__(self, logger=None):self.logger = logger or logging.getLogger("Beamer")self._magnify_accum = 0.0self._warned_types = set()@@ -193,22 +213,16 @@ class GestureTranslator:return messagesdef _zoom_step_messages(self, direction):- if self.receiver == "mac":- return _chord("cmd", "=" if direction > 0 else "-")- return [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},- protocol.scroll_msg(dy=direction, dx=0, mode="line"),- {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},- ]+ return self._shaped("zoom_in" if direction > 0 else "zoom_out")def _translate_swipe(self, ns_event):delta_x = float(ns_event.deltaX)if delta_x == 0:return []- back = delta_x > 0- if self.receiver == "mac":- return _chord("cmd", "[" if back else "]")- return _chord("alt", "left" if back else "right")+ return self._shaped("back" if delta_x > 0 else "forward")++ def _shaped(self, action):+ return [{"type": CHORD, "data": {"action": action}}]def _chord(modifier, key):diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex 485787f..5c103bb 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -1281,7 +1281,7 @@ class ControlWindow(AppKit.NSObject):)after = (self.notch_after_select.value or 1200) / 1000self.notch_note.set(- f"Once the pointer is through to Windows the notch keeps playing for {after:g} seconds, so the "+ f"Once the pointer is through to the other machine the notch keeps playing for {after:g} seconds, so the ""animation finishes instead of cutting off.")self._run_previews()@@ -1294,7 +1294,7 @@ class ControlWindow(AppKit.NSObject):hold = self.style_select.value == "hold"motion.set_hidden(self.double_tap_head, hold)self.style_hint.set(- "Input is on Windows for as long as the key is held."+ "Input is on the other machine for as long as the key is held."if holdelse "Tap twice to switch; tap twice again to come back.")@@ -1308,8 +1308,10 @@ class ControlWindow(AppKit.NSObject):f"{self.edge_select.value} edge of this screen so you can feel the size of it.")self.modifier_note.set({- "semantic": "Command arrives on Windows as Control, so Command-C copies there too, and Control arrives as the Windows key.",- "positional": "Each key arrives as the key in its place, so Command arrives as the Windows key.",+ "semantic": "On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. "+ "Between two Macs every key arrives as itself.",+ "positional": "On a PC, each key arrives as the key in its place, so Command arrives as the Windows key. "+ "Between two Macs every key arrives as itself.",}.get(self.modifier_select.value, "Custom: the key map in settings.json is kept as it is."))@objc.python_method@@ -1843,17 +1845,17 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _speed_module(self):- """How the PC's mouse feels on this Mac: the PC sends what its own acceleration made of the+ """How the other machine's mouse feels on this Mac: it sends what its own acceleration made of thehand's movement, and this Mac's settings decide the rest."""module = widgets.Module()figure, self.pointer_numeral = self._numeral("%")- module.add(self._head("The PC's pointer here", figure))+ module.add(self._head("The other machine's pointer here", figure))self.pointer_ruler = widgets.Ruler(25, 400, (25, 100, 200, 300, 400), step=5, minor=25, on_change=self._speed_moved,title="Pointer speed", arrow_step=25,)module.add(self.pointer_ruler.view)- module.add(widgets.note("Pointer speed for the PC's mouse or trackpad while it drives this Mac.").view)+ module.add(widgets.note("Pointer speed for the other machine's mouse or trackpad while it drives this Mac.").view)figure, self.scroll_numeral = self._numeral("%")module.add(self._head("Scrolling", figure))self.scroll_ruler = widgets.Ruler(@@ -1861,7 +1863,7 @@ class ControlWindow(AppKit.NSObject):title="Scroll speed", arrow_step=25,)module.add(self.scroll_ruler.view)- self.reverse_scroll_box = widgets.Switch("Reverse the PC's scrolling", on_change=self._changed)+ self.reverse_scroll_box = widgets.Switch("Reverse the other machine's scrolling", on_change=self._changed)module.add(self.reverse_scroll_box.view)return module@@ -1926,7 +1928,7 @@ class ControlWindow(AppKit.NSObject):module.add(self.hold_box.view)module.add(self._own_note())module.add(widgets.note(- "Off, your pointer can leave a full-screen game or video, and the PC's pointer can come home "+ "Off, your pointer can leave a full-screen game or video, and the other machine's pointer can come home ""through this Mac's edge. Useful if your keyboard has no key for the shortcut.").view)return module@@ -1970,11 +1972,11 @@ class ControlWindow(AppKit.NSObject):}module.add(widgets.grid([tile.view for tile in self.method_boxes.values()], 2))module.add(self._own_note(pages.OWN_NOTCH))- # The values are the side of this Mac the PC is on, which is also the edge that crosses.+ # The values are the side of this Mac the other machine is on, which is also the edge that crosses.self.edge_select = widgets.Segmented([("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below")], on_change=self._changed)- self.edge_row = widgets.field_row("Where the PC is", self.edge_select.view)[0]+ self.edge_row = widgets.field_row("Where the other machine is", self.edge_select.view)[0]module.add(self.edge_row)self.edge_note = widgets.note(pages.NOTCH_OR_CORNER_NOTE)self.edge_note.view.setHidden_(True)@@ -2052,13 +2054,13 @@ class ControlWindow(AppKit.NSObject):module = widgets.Module()module.add(widgets.eyebrow("Stays on this Mac"))module.add(widgets.note(- "These keys and buttons keep working on this Mac while its input is on Windows: a "+ "These keys and buttons keep working on this Mac while its input is on another machine: a ""mouse's back button for this Mac's browser, say, or a volume key for its speakers.").view)self.ignored_entries = []self.ignored_list = widgets.stack(spacing=6)module.add(self.ignored_list)- self.ignored_empty = widgets.note("Nothing yet. Every key and button goes to Windows while it has input.")+ self.ignored_empty = widgets.note("Nothing yet. Every key and button goes to the other machine while it has input.")module.add(self.ignored_empty.view)self.ignored_recorder = widgets.IgnoredRecorder(KEY_NAME_TO_CODE.get(self.key_recorder.value), on_recorded=self._add_ignored@@ -2127,8 +2129,8 @@ class ControlWindow(AppKit.NSObject):module.add(self.glow_box.view)module.add(self._own_note())module.add(widgets.note(- "Lights the edge, the corner or the notch as you push toward Windows. Switched off, crossing "- "still works; you feel it rather than see it. Windows sets how its own edge looks."+ "Lights the edge, the corner or the notch as you push toward the other machine. Switched off, crossing "+ "still works; you feel it rather than see it. Each machine sets how its own edge looks.").view)self.landing_box = widgets.Switch("Show where the pointer lands", on_change=self._changed)self.landing_row = widgets.stack(spacing=8)@@ -2394,12 +2396,12 @@ class ControlWindow(AppKit.NSObject):def _access_module(self):module = widgets.Module(spacing=10)self.access_status, self.access_button = self._permission_row(- module, "Accessibility", "Lets Beamer move this Mac's pointer and type on it when the PC drives.",+ module, "Accessibility", "Lets Beamer move this Mac's pointer and type on it when another machine drives.","requestAccessibility:",)module.add(widgets.hairline())self.input_status, self.input_button = self._permission_row(- module, "Input Monitoring", "Lets Beamer read this keyboard and trackpad, to send them to the PC.",+ module, "Input Monitoring", "Lets Beamer read this keyboard and trackpad, to send them to another machine.","requestInputMonitoring:",)self.capture_status = widgets.note()@@ -2804,7 +2806,7 @@ class ControlWindow(AppKit.NSObject):mac = cfg.mac_addressself.wake_state.set(self._shown(mac) if mac else "Not yet learned", ink="ink" if mac else "ink_3")self.wake_hint.set(- "Crossing to the PC while it sleeps sends a wake-up packet and waits for it."+ "Crossing to the other machine while it sleeps sends a wake-up packet and waits for it."if macelse "Read from the network the first time this Mac connects; nothing to type.")@@ -3290,6 +3292,17 @@ def parse_args(argv=None):return parser.parse_args(argv)+def stay_awake(process_info=None):+ """An activity that keeps macOS from napping Beamer or coalescing its timers, which made its+ links answer seconds late and drop (test_app_nap.py); idle system sleep is still allowed. The+ token returned must be kept for as long as Beamer runs."""+ process_info = process_info or AppKit.NSProcessInfo.processInfo()+ return process_info.beginActivityWithOptions_reason_(+ AppKit.NSActivityUserInitiatedAllowingIdleSystemSleep | AppKit.NSActivityLatencyCritical,+ "Beamer's links answer the other machines within two seconds",+ )++def main(argv=None):args = parse_args(argv)if sys.platform != "darwin":@@ -3315,6 +3328,7 @@ def main(argv=None):book, identity = bridge.links_from_store(settings_store, VERSION)controller = WakingController(cfg, logger=logger, book=book, identity=identity, hardware=hardware_mac.hardware_address_towards)app = TrayApp(controller, settings_store, logger, hidden=args.hidden)+ awake = stay_awake() # noqa: F841 (held until Beamer quits)controller.start()try:app.run()diff --git a/mac_app/pages.py b/mac_app/pages.pyindex 8fe2b33..13e6c20 100644--- a/mac_app/pages.py+++ b/mac_app/pages.py@@ -19,23 +19,23 @@ PAGES = (("permissions", "Permissions", "lock.shield","macOS must allow Beamer to read this keyboard and trackpad before it can send them anywhere."),("crossing", "Crossing", "cursorarrow.motionlines",- "Choose how the pointer or a key moves input to Windows, and how hard the edge pushes back first."),+ "Choose how the pointer or a key moves input to the other machine, and how hard the edge pushes back first."),("keyboard", "Keyboard", "keyboard",- "How this Mac's modifier keys arrive on Windows, which keys and buttons stay on this Mac, and "- "how fast the PC's pointer moves here. The switch key is on the Crossing page."),+ "How this Mac's modifier keys arrive on the other machine, which keys and buttons stay on this Mac, "+ "and how fast the other machine's pointer moves here. The switch key is on the Crossing page."),("design", "Design", "paintpalette","How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."),("connection", "Connection", "network","Where the first machine you paired is. Pairing fills these in."),)KEYS = tuple(page[0] for page in PAGES)-# Under the purpose on the pages whose settings are this Mac's alone, so nobody looks for the PC's-# on the Mac: each app sets only its own machine, and the PC's are in Beamer on the PC.+# Under the purpose on the pages whose settings are this Mac's alone, so nobody looks for the other+# machine's on the Mac: each app sets only its own machine, and the other's are in Beamer there.SCOPE = {- "crossing": "For this Mac only; the PC keeps its own. Only which side the PC is on is shared. This Mac's "- "resistance is also what its pointer meets at the PC's edge on the way back.",- "design": "For this Mac's screen only; the PC keeps its own.",- "keyboard": "For this Mac's keyboard only; the PC keeps its own.",+ "crossing": "For this Mac only; the other machine keeps its own. Only which side the other machine is on is shared. This "+ "Mac's resistance is also what its pointer meets at the other machine's edge on the way back.",+ "design": "For this Mac's screen only; the other machine keeps its own.",+ "keyboard": "For this Mac's keyboard only; the other machine keeps its own.",}# With Same on both machines on, under each row of the shared pages that stays this Mac's own.OWN_ROW = "This Mac only."@@ -172,7 +172,7 @@ def toggle_part(parts, part, on):return [name for name in ("start", "middle", "end") if name in chosen]-# The Crossing page's diagram: this Mac's screen at 16:10 and the PC's at 16:9, a gap between.+# The Crossing page's diagram: this Mac's screen at 16:10 and the other machine's at 16:9, a gap between.DIAGRAM_THIS = (120.0, 75.0)DIAGRAM_OTHER = (112.0, 63.0)DIAGRAM_GAP = 10.0@@ -292,14 +292,14 @@ def place_note(style, place, methods, has_notch):def notch_or_corner_only(methods):"""The pointer's only ways in are the notch and/or a corner, so input arrives by their own side- and Where the PC is does not steer it."""+ and Where the other machine is does not steer it."""chosen = set(methods)return bool(chosen & {"notch", "corner"}) and not chosen & {"edge", "part"}NOTCH_OR_CORNER_NOTE = ("With only the notch or a corner on, input arrives by the notch's or corner's own side, so this "- "choice does nothing on this Mac; your PC's own push still follows it."+ "choice does nothing on this Mac; the other machine's own push still follows it.")@@ -309,8 +309,8 @@ def crossing_rows(methods):chosen = set(methods)pointer = bool(chosen & {"edge", "part", "corner", "notch"})return {- # Where the PC sits, which every way in uses: a crossing arrives by it, and with only the- # shortcut on it is still the PC's edge that leads back here.+ # Where the other machine sits, which every way in uses: a crossing arrives by it, and with+ # only the shortcut on it is still that machine's edge that leads back here."edge": True,"parts": "part" in chosen,"corner": "corner" in chosen,diff --git a/mac_app/setup.py b/mac_app/setup.pyindex 13e9a7c..06f3c5b 100644--- a/mac_app/setup.py+++ b/mac_app/setup.py@@ -94,7 +94,7 @@ setup("NSPrincipalClass": "NSApplication","ATSApplicationFontsPath": "Fonts","NSHumanReadableCopyright": "Copyright 2026 Toby Kalkman",- "NSLocalNetworkUsageDescription": "Beamer needs to reach the Windows PC on your local network to forward keyboard and mouse input.",+ "NSLocalNetworkUsageDescription": "Beamer needs to reach your other computers on your local network to share keyboard and mouse input.",},}},diff --git a/mac_app/tests/bridge_fakes.py b/mac_app/tests/bridge_fakes.pyindex 919fcb0..2006ae0 100644--- a/mac_app/tests/bridge_fakes.py+++ b/mac_app/tests/bridge_fakes.py@@ -3,6 +3,7 @@ still, a clipboard that never touches the pasteboard, and the Config a controlleimport base64import logging+import timeimport configfrom core import protocol@@ -139,6 +140,14 @@ def crossing_config(token="synthetic-token", **overrides):return cfg+def settle(controller, timeout=2.0):+ """Wait until the pasteboard work the controller started is done, and what waited behind it sent."""+ deadline = time.monotonic() + timeout+ while (controller._clip_wait or controller._pasteboard_busy) and time.monotonic() < deadline:+ time.sleep(0.002)+ assert not (controller._clip_wait or controller._pasteboard_busy), "pasteboard work never finished"++def quiet_logger():logger = logging.getLogger("kvm-bridge-tests")logger.handlers = [logging.NullHandler()]diff --git a/mac_app/tests/fake_link.py b/mac_app/tests/fake_link.pyindex 624c63b..77ab388 100644--- a/mac_app/tests/fake_link.py+++ b/mac_app/tests/fake_link.py@@ -10,6 +10,9 @@ owner, the pointer, the alerts, the clipboard) is tested without a socket.The wire itself (handshake, framing, acks, liveness) is core/tests/test_link.py's; the two endstogether are test_mac_links.py's."""+import threading++from bridge_fakes import settlefrom core import protocolPEER_ID = bytes(range(1, 17))@@ -37,13 +40,31 @@ class FakeLink:self.status = ""self.peer_locked = Falseself.dialled = None- self.sent = []- self.posted = []+ self._sent = []+ self._posted = []self.dropped = []self.followed = []self.samples = []self.full = Falseself._live = False+ self._controller = None++ # A take's clipboard is read on a thread of the controller's own, and what follows it for this+ # link waits behind it: a test reading what was sent first waits for that thread to finish.++ @property+ def sent(self):+ self._settle()+ return self._sent++ @property+ def posted(self):+ self._settle()+ return self._posted++ def _settle(self):+ if self._controller is not None and threading.current_thread().name != "Beamer-clipboard":+ settle(self._controller)def start(self):self.started = True@@ -74,13 +95,13 @@ class FakeLink:def post(self, message):if not self._live or self.full:return False- self.posted.append(message)+ self._posted.append(message)return Truedef send_input(self, message):if not self._live or self.full:return False- self.sent.append(message)+ self._sent.append(message)return Truedef round_trips(self, max_age=30.0):@@ -94,6 +115,7 @@ class FakeLink:def up(self, controller, ident=PEER_ID, name="Office PC", platform="windows", caps=CAPS, accepts=True, hw=None):"""The handshake done, as the link would report it."""self._live = True+ self._controller = controllerself.peer_id = protocol.id_text(ident)self.peer_name, self.peer_platform = name, platformself.caps = frozenset(caps)@@ -116,6 +138,7 @@ class FakeLink:if began is not None:message.began_at = begancontroller._link_message(self, message)+ settle(controller)def types(self):return [message["type"] for message in self.posted]diff --git a/mac_app/tests/test_app_nap.py b/mac_app/tests/test_app_nap.pynew file mode 100644index 0000000..4ab8fb3--- /dev/null+++ b/mac_app/tests/test_app_nap.py@@ -0,0 +1,50 @@+"""The Mac app is never napped.++On 01-10-2026 macOS napped Beamer from 12:20:18 to 12:43:37 (runningboardd: "Set AppNap state ...+socket:Y cpu:Y timer:Tier5"), and in that window its links to the PC dropped 42 times: a napped+process sends its pings and acks seconds late, and the far side gives each link up after two. A+machine that may be taken at any moment by another holds an activity for as long as it runs."""++import os+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import AppKit++import kvm_bridge_app+++class FakeProcessInfo:+ def __init__(self):+ self.begun = []++ def beginActivityWithOptions_reason_(self, options, reason):+ self.begun.append((options, reason))+ return "token"+++class AppNapTests(unittest.TestCase):+ def test_beamer_holds_an_activity_that_is_neither_napped_nor_coalesced(self):+ info = FakeProcessInfo()+ token = kvm_bridge_app.stay_awake(info)+ self.assertEqual(token, "token")+ (options, reason), = info.begun+ self.assertEqual(options & AppKit.NSActivityUserInitiatedAllowingIdleSystemSleep,+ AppKit.NSActivityUserInitiatedAllowingIdleSystemSleep)+ self.assertEqual(options & AppKit.NSActivityLatencyCritical, AppKit.NSActivityLatencyCritical)+ self.assertTrue(reason)++ def test_it_lets_the_machine_sleep_when_idle(self):+ info = FakeProcessInfo()+ kvm_bridge_app.stay_awake(info)+ options = info.begun[0][0]+ self.assertFalse(options & AppKit.NSActivityIdleSystemSleepDisabled)++ def test_the_real_activity_is_taken(self):+ self.assertIsNotNone(kvm_bridge_app.stay_awake())+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.pyindex 4146979..703e8c9 100644--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@ -34,9 +34,10 @@ from bridge_fakes import ( # noqa: F401 (re-exported)crossing_config,make_config,quiet_logger,+ settle,)from fake_link import OTHER_ID, PEER_ID, FakeLink, bring_up-from gestures import DOCK_CONTROL_TYPE, MAGNIFY_TYPE, SWIPE_TYPE+from gestures import CHORD, DOCK_CONTROL_TYPE, MAGNIFY_TYPE, SWIPE_TYPEfrom input_injector_mac import INJECTED_MARK@@ -518,16 +519,16 @@ class ControllerTests(unittest.TestCase):def test_outbound_worker_survives_a_bad_message(self):# The only thread that drains the queue is never restarted, so a raise- # inside one message (the clipboard read every switch does) must force- # input local and leave the worker running for the next message.+ # inside one message must force input local and leave the worker+ # running for the next message.bring_up(self.controller)self.assertTrue(self.controller.set_redirecting(True))- self.controller.clipboard = types.SimpleNamespace(- get_contents=lambda: (_ for _ in ()).throw(RuntimeError("synthetic clipboard failure"))- )- self.controller.outbound.put_nowait(- {"type": "_local_clipboard", "data": {}, "peer": protocol.id_text(PEER_ID)}- )++ def fail(message):+ raise RuntimeError("synthetic routing failure")++ self.controller.owner.input = fail+ self.controller.outbound.put_nowait({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})self.controller.stop_event.clear()def stop_after_one():@@ -622,6 +623,7 @@ class ClipboardSyncTests(unittest.TestCase):def _take_with(self, clipboard):self.controller.clipboard = clipboardself.assertTrue(self.controller.set_redirecting(True))+ settle(self.controller)def _arrives_from_a_machine_just_let_go(self, message):self.controller.set_redirecting(True)@@ -827,13 +829,9 @@ class OverlayGestureTests(unittest.TestCase):self.assertTrue(self.controller.set_redirecting(True))self.controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.05))drained = drain(self.controller)- self.assertEqual(drained, [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},- protocol.scroll_msg(dy=1, dx=0, mode="line"),- {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},- ])- # Fed back through the normal outbound path, they reach the link- # the same way any other input event does.+ self.assertEqual(drained, [{"type": CHORD, "data": {"action": "zoom_in"}}])+ # Fed back through the normal outbound path, the chord reaches the+ # link in the shape the PC at its end answers to.for message in drained:self.controller._process_outbound(message)self.assertEqual(@@ -877,12 +875,7 @@ class OverlayGestureTests(unittest.TestCase):drained = []while not self.controller.outbound.empty():drained.append(self.controller.outbound.get_nowait())- self.assertEqual(drained, [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},- {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},- ])+ self.assertEqual(drained, [{"type": CHORD, "data": {"action": "back"}}])class MediaKeyWiringTests(unittest.TestCase):@@ -979,17 +972,17 @@ class GestureWiringTests(unittest.TestCase):returned = controller._event_tap_callback(None, SWIPE_TYPE, object(), None)self.assertIsNone(returned)drained = drain(controller)- self.assertEqual(drained, [+ self.assertEqual(drained, [{"type": CHORD, "data": {"action": "back"}}])+ # Fed back through the normal outbound path, the chord reaches the+ # link in the shape the PC at its end answers to.+ for message in drained:+ controller._process_outbound(message)+ self.assertEqual(link.sent, [{"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},{"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},{"type": protocol.MSG_KEYUP, "data": {"key": "left"}},{"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},])- # Fed back through the normal outbound path, they reach the link- # the same way any other input event does.- for message in drained:- controller._process_outbound(message)- self.assertEqual(link.sent, drained)def test_gesture_while_not_redirecting_is_passed_through_untouched(self):calls = []@@ -1044,12 +1037,7 @@ class GestureWiringTests(unittest.TestCase):drained = []while not controller.outbound.empty():drained.append(controller.outbound.get_nowait())- self.assertEqual(drained, [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},- {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},- ])+ self.assertEqual(drained, [{"type": CHORD, "data": {"action": "back"}}])def test_gesture_capture_active_logged_once_on_first_success(self):logger = logging.getLogger("kvm-bridge-tests.gesture-capture")@@ -1186,6 +1174,18 @@ class CrossingWiringTests(unittest.TestCase):self.assertEqual(kinds[-1], "cross")self.assertEqual(kinds.count("tick"), 3)+ def test_a_machine_that_just_refused_is_not_pushed_at_until_its_back_off_ends(self):+ # A push that cannot take it must not pin the pointer and glow as if it would.+ self._push(12)+ self.link.arrives(self.controller, protocol.refuse_msg(self.controller.owner.route, "owned"))+ self.assertFalse(self.controller.redirecting)+ self.feedback.clear()+ FakeQuartz.reset_cursor_spies()+ event, returned = self._move(1727.0, 558.0, 30)+ event, returned = self._move(1727.0, 558.0, 30)+ self.assertIs(returned, event)+ self.assertEqual((FakeQuartz.warp_calls, self.feedback), ([], []))+def test_this_macs_own_push_while_windows_drives_sends_the_pc_home_and_crosses(self):# Regression: this Mac's trackpad could not push back while the PC drove it. The push# itself is let through; this Mac's input follows once the PC's has let go.diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.pyindex e15e42e..e3a85ba 100644--- a/mac_app/tests/test_clipboard_mac.py+++ b/mac_app/tests/test_clipboard_mac.py@@ -3,6 +3,8 @@ real AppKit conversion (TIFF to PNG) run on data that never touches thegeneral pasteboard, so the suite leaves the machine's clipboard alone."""import struct+import threading+import timeimport unittestimport zlibimport os@@ -155,5 +157,61 @@ class ChangedContentsTests(unittest.TestCase):self.assertNotEqual(clipboard_mac.change_stamp(), before)+class _SlowBoard(FakePasteboard):+ """Counts how many threads are inside it at once, each read and write taking a moment."""++ def __init__(self):+ super().__init__(string="copied")+ self.inside = 0+ self.most = 0+ self.lock = threading.Lock()++ def _visit(self):+ with self.lock:+ self.inside += 1+ self.most = max(self.most, self.inside)+ time.sleep(0.02)+ with self.lock:+ self.inside -= 1++ def stringForType_(self, kind):+ self._visit()+ return self.string++ def clearContents(self):+ self._visit()+ super().clearContents()+++class OneAtATimeTests(unittest.TestCase):+ """NSPasteboard is not documented as thread-safe, and reading it from two threads at once has+ raised from inside AppKit: the controller's clipboard reads, its writes and the Mac's responder+ each run on threads of their own, so every read and write takes its turn."""++ def setUp(self):+ AppKit = clipboard_mac.AppKit+ self.board = _SlowBoard()+ fake_appkit = type("FakeAppKit", (), {})()+ fake_appkit.NSPasteboard = type("NSPasteboard", (), {"generalPasteboard": staticmethod(lambda: self.board)})+ fake_appkit.NSData = AppKit.NSData+ for name in ("NSPasteboardTypeString", "NSPasteboardTypePNG", "NSPasteboardTypeTIFF"):+ setattr(fake_appkit, name, getattr(AppKit, name))+ real = clipboard_mac.AppKit+ clipboard_mac.AppKit = fake_appkit+ self.addCleanup(setattr, clipboard_mac, "AppKit", real)++ def test_reads_and_writes_from_several_threads_never_overlap(self):+ work = [clipboard_mac.get_contents, lambda: clipboard_mac.set_contents("x", None)] * 3+ threads = [threading.Thread(target=job) for job in work]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(5)+ self.assertEqual(self.board.most, 1)+++OneAtATimeTests = unittest.skipIf(clipboard_mac.AppKit is None, "AppKit is only available on macOS")(OneAtATimeTests)++if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.pyindex 8699bb7..9443a39 100644--- a/mac_app/tests/test_crossing_matrix.py+++ b/mac_app/tests/test_crossing_matrix.py@@ -268,7 +268,7 @@ class WhatIsSharedTests(unittest.TestCase):line = pages.SCOPE["crossing"]self.assertNotIn("Two are shared", line)- self.assertIn("Only which side the PC is on is shared", line)+ self.assertIn("Only which side the other machine is on is shared", line)def pc_at_edge(duo, edge):diff --git a/mac_app/tests/test_driven_mac.py b/mac_app/tests/test_driven_mac.pyindex ab683cb..f72000f 100644--- a/mac_app/tests/test_driven_mac.py+++ b/mac_app/tests/test_driven_mac.py@@ -11,7 +11,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspaimport input_injector_mac as injectorfrom core import protocol-from gestures import GestureTranslator+from gestures import chord_forclass FakeEvent:@@ -349,58 +349,10 @@ class GestureInjectionTests(InjectorCase):self.assertTrue(self.quartz.posted, name)-class FakeNSGesture:- def __init__(self, magnification=0.0, delta_x=0.0, phase=0):- self.magnification = magnification- self.deltaX = delta_x- self.deltaY = 0.0- self.phase = phase---class MacShapedGestureTranslatorTests(unittest.TestCase):- def keys(self, messages):- return [(m["type"], m["data"]["key"]) for m in messages if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)]-- def test_the_default_is_still_the_windows_shaped_chord(self):- translator = GestureTranslator()- swipe = translator.translate(31, FakeNSGesture(delta_x=1))- self.assertEqual(- self.keys(swipe),- [(protocol.MSG_KEYDOWN, "alt"), (protocol.MSG_KEYDOWN, "left"), (protocol.MSG_KEYUP, "left"), (protocol.MSG_KEYUP, "alt")],- )-- def test_a_page_swipe_to_a_mac_is_command_bracket(self):- translator = GestureTranslator(receiver="mac")- back = translator.translate(31, FakeNSGesture(delta_x=1))- forward = translator.translate(31, FakeNSGesture(delta_x=-1))- self.assertEqual(- self.keys(back),- [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "["), (protocol.MSG_KEYUP, "["), (protocol.MSG_KEYUP, "cmd")],- )- self.assertEqual(self.keys(forward)[1], (protocol.MSG_KEYDOWN, "]"))-- def test_a_pinch_to_a_mac_zooms_with_command_plus_and_minus(self):- translator = GestureTranslator(receiver="mac")- zoom_in = translator.translate(30, FakeNSGesture(magnification=0.06))- zoom_out = translator.translate(30, FakeNSGesture(magnification=-0.06))- self.assertEqual(self.keys(zoom_in)[:2], [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "=")])- self.assertEqual(self.keys(zoom_out)[:2], [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "-")])- self.assertFalse([m for m in zoom_in if m["type"] == protocol.MSG_SCROLL])-- def test_the_mac_chord_names_its_us_key_so_another_layout_still_presses_a_key(self):- translator = GestureTranslator(receiver="mac")- keys = [m["data"] for m in translator.translate(31, FakeNSGesture(delta_x=1)) if m["type"] == protocol.MSG_KEYDOWN]- self.assertEqual(keys, [{"key": "cmd"}, {"key": "[", "us": "["}])- down = injector.plan_key_event("[", True, {"cmd"}, us="[")- self.assertEqual(down, (0x21, None))-- def test_a_pinch_to_windows_is_still_control_wheel(self):- zoom = GestureTranslator().translate(30, FakeNSGesture(magnification=0.06))- self.assertTrue([m for m in zoom if m["type"] == protocol.MSG_SCROLL])-- def test_an_unknown_receiver_is_refused(self):- with self.assertRaises(ValueError):- GestureTranslator(receiver="linux")+class MacChordInjectionTests(unittest.TestCase):+ def test_a_page_swipes_chord_presses_the_bracket_key_under_command(self):+ bracket = [m["data"] for m in chord_for("back", "mac") if m["type"] == protocol.MSG_KEYDOWN][1]+ self.assertEqual(injector.plan_key_event(bracket["key"], True, {"cmd"}, us=bracket["us"]), (0x21, None))if __name__ == "__main__":diff --git a/mac_app/tests/test_gestures.py b/mac_app/tests/test_gestures.pyindex e880e2f..4c5d126 100644--- a/mac_app/tests/test_gestures.py+++ b/mac_app/tests/test_gestures.py@@ -6,6 +6,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspafrom core import protocolfrom gestures import (+ CHORD,DOCK_PHASE_ENDED,DOCK_SWIPE_HID_TYPE,GESTURE_TYPE,@@ -19,6 +20,7 @@ from gestures import (NS_EVENT_PHASE_ENDED,DockSwipeClassifier,GestureTranslator,+ chord_for,sign_table_for,)@@ -44,20 +46,54 @@ class BrokenNSEvent:raise RuntimeError(f"synthetic failure reading {name!r}")+def chord(action):+ return [{"type": CHORD, "data": {"action": action}}]++def zoom_in_triple():- return [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},- protocol.scroll_msg(dy=1, dx=0, mode="line"),- {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},- ]+ return chord("zoom_in")def zoom_out_triple():- return [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},- protocol.scroll_msg(dy=-1, dx=0, mode="line"),- {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},- ]+ return chord("zoom_out")+++def keys(messages):+ return [(m["type"], m["data"].get("key")) for m in messages]+++class ChordShapeTests(unittest.TestCase):+ """What a CHORD becomes once the machine it is sent to is known."""++ def test_a_zoom_to_a_pc_is_control_wheel(self):+ self.assertEqual(chord_for("zoom_in", "windows"), [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},+ protocol.scroll_msg(dy=1, dx=0, mode="line"),+ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},+ ])+ self.assertEqual(chord_for("zoom_out", "windows")[1], protocol.scroll_msg(dy=-1, dx=0, mode="line"))++ def test_a_page_swipe_to_a_pc_is_alt_arrow(self):+ self.assertEqual(keys(chord_for("back", "windows")), [+ (protocol.MSG_KEYDOWN, "alt"), (protocol.MSG_KEYDOWN, "left"), (protocol.MSG_KEYUP, "left"), (protocol.MSG_KEYUP, "alt")])+ self.assertEqual(keys(chord_for("forward", "windows"))[1], (protocol.MSG_KEYDOWN, "right"))++ def test_a_zoom_to_a_mac_is_command_plus_and_minus(self):+ self.assertEqual(keys(chord_for("zoom_in", "mac")), [+ (protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "="), (protocol.MSG_KEYUP, "="), (protocol.MSG_KEYUP, "cmd")])+ self.assertEqual(keys(chord_for("zoom_out", "mac"))[1], (protocol.MSG_KEYDOWN, "-"))++ def test_a_page_swipe_to_a_mac_is_command_bracket(self):+ self.assertEqual(keys(chord_for("back", "mac"))[:2], [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "[")])+ self.assertEqual(keys(chord_for("forward", "mac"))[1], (protocol.MSG_KEYDOWN, "]"))++ def test_the_mac_chord_names_its_us_key_so_another_layout_still_presses_a_key(self):+ downs = [m["data"] for m in chord_for("back", "mac") if m["type"] == protocol.MSG_KEYDOWN]+ self.assertEqual(downs, [{"key": "cmd"}, {"key": "[", "us": "["}])++ def test_an_unknown_action_is_refused(self):+ with self.assertRaises(ValueError):+ chord_for("sideways", "mac")class GestureTranslatorWantsTests(unittest.TestCase):@@ -134,21 +170,11 @@ class SwipeTranslationTests(unittest.TestCase):def test_positive_delta_x_is_back(self):messages = self.translator.translate(SWIPE_TYPE, FakeNSEvent(deltaX=1.0))- self.assertEqual(messages, [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},- {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},- ])+ self.assertEqual(messages, chord("back"))def test_negative_delta_x_is_forward(self):messages = self.translator.translate(SWIPE_TYPE, FakeNSEvent(deltaX=-1.0))- self.assertEqual(messages, [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},- {"type": protocol.MSG_KEYDOWN, "data": {"key": "right"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "right"}},- {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},- ])+ self.assertEqual(messages, chord("forward"))def test_vertical_only_swipe_is_ignored(self):messages = self.translator.translate(SWIPE_TYPE, FakeNSEvent(deltaX=0.0, deltaY=1.0))diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.pyindex 397526a..d7aacc6 100644--- a/mac_app/tests/test_mac_links.py+++ b/mac_app/tests/test_mac_links.py@@ -13,7 +13,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspafrom bridge import KVMControllerfrom core import protocol-from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeClock, FakeQuartz, make_config, quiet_logger+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeClock, FakeQuartz, make_config, quiet_logger, settlefrom fake_link import CAPS, OTHER_ID, PEER_ID, FakeLink, bring_up@@ -107,6 +107,7 @@ class TakingAndLeavingTests(Base):def test_a_take_sends_the_focus_then_the_clipboard(self):self.up()self.assertTrue(self.controller.set_redirecting(True, edge="left", offset=0.4))+ settle(self.controller)take = self.focus()self.assertEqual((take["route"], take["target"], take["edge"], take["offset"]), (1, self.peer, "left", 0.4))self.assertEqual(take["resistance_px"], int(self.controller.crossing.resistance_px))@@ -191,6 +192,221 @@ class ModifierNamesTests(Base):self.assertEqual(self.send("volume_up"), "volume_up")+class _Gesture:+ def __init__(self, magnification=0.0, delta_x=0.0):+ self.magnification, self.deltaX, self.deltaY, self.phase = magnification, delta_x, 0.0, 0+++def _wait(predicate, timeout=2.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.005)+ return predicate()+++class SlowPasteboardTests(Base):+ """Reading the pasteboard can take seconds (a large image, or data an app promised lazily), and+ the event tap takes the owner's lock, so the read never holds it; input that follows a take+ still reaches the machine after the take's clipboard (WIRE.md section 5)."""++ def setUp(self):+ super().setUp()+ self.up()+ self.order = []+ post, send = self.link.post, self.link.send_input+ self.link.post = lambda message: self.order.append(message["type"]) or post(message)+ self.link.send_input = lambda message: self.order.append(message["type"]) or send(message)+ self.reading, self.release = threading.Event(), threading.Event()++ # One pasteboard, as clipboard_mac's lock makes it: a write waits for a read in progress.+ board = threading.Lock()+ write = self.clipboard.set_contents++ def slow():+ with board:+ self.reading.set()+ self.release.wait(5)+ return self.clipboard.text, None++ def written(text, image):+ with board:+ return write(text, image)++ self.clipboard.get_contents = slow+ self.clipboard.set_contents = written+ self.addCleanup(self.release.set)++ def test_a_clipboard_written_here_during_the_read_holds_no_lock_the_event_tap_takes(self):+ from core import owner as owner_module+ self.take()+ writer = threading.Thread(target=self.controller._step, daemon=True,+ args=(lambda owner: [owner_module.SetClipboard(protocol.clipboard_msg("from there"))],))+ writer.start()+ writer.join(1)+ self.assertFalse(writer.is_alive(), "the write waited for the read")+ self.assertTrue(self.controller._owner_lock.acquire(timeout=1), "the owner's lock is held through the write")+ self.controller._owner_lock.release()+ self.release.set()+ settle(self.controller)+ self.assertEqual(self.clipboard.set_calls, [("from there", None)])++ def take(self):+ taker = threading.Thread(target=self.controller.set_redirecting, args=(True,), daemon=True)+ taker.start()+ self.assertTrue(self.reading.wait(2), "the take never read the pasteboard")+ taker.join(1)+ self.assertFalse(taker.is_alive(), "the take waited for the pasteboard")++ def test_the_read_holds_no_lock_the_event_tap_takes(self):+ self.take()+ self.assertTrue(self.controller._owner_lock.acquire(timeout=1), "the owner's lock is held through the read")+ self.controller._owner_lock.release()++ def test_input_after_the_take_waits_behind_the_clipboard(self):+ self.take()+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})+ self.assertNotIn(protocol.MSG_KEYDOWN, self.order)+ self.release.set()+ self.assertTrue(_wait(lambda: protocol.MSG_KEYDOWN in self.order), self.order)+ self.assertLess(self.order.index(protocol.MSG_CLIPBOARD), self.order.index(protocol.MSG_KEYDOWN))++ def test_a_read_asked_for_again_waits_its_turn_behind_a_write_decided_before_it(self):+ from core import owner as owner_module+ self.take()+ arrived = protocol.clipboard_msg("from there")+ key = {"type": protocol.MSG_KEYDOWN, "data": {"key": "v"}}+ decide = lambda actions: threading.Thread(target=self.controller._step, args=(lambda owner: actions,), daemon=True)+ for step in (decide([owner_module.SetClipboard(arrived)]),+ decide([owner_module.SendClipboard(self.peer), owner_module.Send(self.peer, key)])):+ step.start()+ step.join(1)+ self.release.set()+ settle(self.controller)+ clipboards = [m["data"]["text"] for m in self.link.posted if m["type"] == protocol.MSG_CLIPBOARD]+ self.assertEqual(clipboards, ["hello", "from there"])+ self.assertEqual(self.order[-3:], [protocol.MSG_CLIPBOARD, protocol.MSG_CLIPBOARD, protocol.MSG_KEYDOWN])++ def test_a_link_lost_during_the_read_drops_what_waited_and_a_retake_sends_the_clipboard_after_its_focus(self):+ self.take()+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})+ self.link.down(self.controller)+ self.assertFalse(self.controller.redirecting)+ self.up()+ self.order.clear()+ threading.Thread(target=self.controller.set_redirecting, args=(True,), daemon=True).start()+ self.assertTrue(_wait(lambda: protocol.MSG_FOCUS in self.order), self.order)+ self.release.set()+ settle(self.controller)+ self.assertEqual(self.order, [protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD])++ def test_stopping_during_the_read_still_lets_the_machine_go_after_it(self):+ self.take()+ threading.Timer(0.2, self.release.set).start()+ self.controller.stop()+ self.assertIn(protocol.MSG_CLIPBOARD, self.order)+ let_go = [m for m in self.link.posted if m["type"] == protocol.MSG_FOCUS][-1]["data"]+ self.assertEqual(let_go["target"], self.own)++ def test_pointer_moves_made_during_the_read_go_one_by_one_as_made(self):+ # Never summed: the far machine's edge feels each move where its pointer is (return_edge).+ self.take()+ for dx, dy in ((3, 1), (4, -2), (5, 0)):+ self.controller._process_outbound({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": dx, "dy": dy}})+ self.release.set()+ settle(self.controller)+ moves = [m["data"] for m in self.link.sent if m["type"] == protocol.MSG_MOUSEMOVE]+ self.assertEqual(moves, [{"dx": 3, "dy": 1}, {"dx": 4, "dy": -2}, {"dx": 5, "dy": 0}])++ def test_input_flows_straight_through_once_the_clipboard_is_sent(self):+ self.take()+ self.release.set()+ self.assertTrue(_wait(lambda: protocol.MSG_CLIPBOARD in self.order))+ self.assertTrue(_wait(lambda: not self.controller._clip_wait))+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})+ self.assertEqual(self.order[-1], protocol.MSG_KEYDOWN)+++class GestureShapeTests(Base):+ """A pinch or a page swipe goes as the chord the machine it reaches answers to, decided when it+ is sent to that machine, not when it was captured."""++ def gesture(self, event_type, view, **link):+ self.up(**link)+ self.controller.set_redirecting(True)+ self.link.sent.clear()+ self.controller.handle_overlay_gesture(event_type, view)+ while not self.controller.outbound.empty():+ self.controller._process_outbound(self.controller.outbound.get_nowait())+ return [(m["type"], m["data"].get("key")) for m in self.link.sent]++ def test_a_page_swipe_to_a_mac_is_command_bracket(self):+ self.assertEqual(self.gesture(31, _Gesture(delta_x=1), platform="macos"), [+ (protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "["), (protocol.MSG_KEYUP, "["), (protocol.MSG_KEYUP, "cmd")])++ def test_a_page_swipe_to_a_pc_is_alt_arrow(self):+ self.assertEqual(self.gesture(31, _Gesture(delta_x=1)), [+ (protocol.MSG_KEYDOWN, "alt"), (protocol.MSG_KEYDOWN, "left"), (protocol.MSG_KEYUP, "left"), (protocol.MSG_KEYUP, "alt")])++ def test_a_pinch_to_a_mac_is_command_plus_and_never_a_wheel(self):+ sent = self.gesture(30, _Gesture(magnification=0.06), platform="macos")+ self.assertEqual(sent[:2], [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "=")])+ self.assertNotIn(protocol.MSG_SCROLL, [kind for kind, _ in sent])++ def test_a_pinch_to_a_pc_is_control_wheel(self):+ sent = self.gesture(30, _Gesture(magnification=0.06))+ self.assertEqual([kind for kind, _ in sent], [protocol.MSG_KEYDOWN, protocol.MSG_SCROLL, protocol.MSG_KEYUP])+ self.assertEqual(sent[0][1], "ctrl")+++class GestureThroughAHandOverTests(Base):+ """A gesture made while the PC hands the input on to a Mac is held with the rest of the input and+ goes to the Mac as the Mac's chord: the chord is chosen when it is sent, not when it was made."""++ def setUp(self):+ super().setUp()+ self.up()+ with self.controller.book.lock:+ peers = self.controller.book.data["peers"]+ peers.append({**peers[0], "id": protocol.id_text(OTHER_ID), "token": "second", "send": True})+ self.controller._sync_links()+ self.mac = self.controller.links["second"]+ self.mac.up(self.controller, ident=OTHER_ID, name="Laptop", platform="macos")+ self.controller.set_redirecting(True)+ self.link.arrives(self.controller, protocol.accept_msg(1))+ self.link.arrives(self.controller, protocol.switch_v6(1, OTHER_ID))+ self.link.sent.clear()++ def pinch(self):+ self.controller.handle_overlay_gesture(30, _Gesture(magnification=0.06))+ while not self.controller.outbound.empty():+ self.controller._process_outbound(self.controller.outbound.get_nowait())++ def test_the_pinch_waits_for_the_mac_and_reaches_it_as_command_plus(self):+ self.pinch()+ self.assertEqual(self.mac.sent, [])+ self.mac.arrives(self.controller, protocol.accept_msg(self.controller.owner.route))+ settle(self.controller)+ self.assertEqual([(m["type"], m["data"].get("key")) for m in self.mac.sent], [+ (protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "="), (protocol.MSG_KEYUP, "="), (protocol.MSG_KEYUP, "cmd")])+ self.assertEqual(self.link.sent, [])+++class ChordCutShortTests(Base):+ def test_a_link_whose_queue_fills_mid_chord_is_dropped_rather_than_left_holding_a_modifier(self):+ self.up(platform="macos")+ self.controller.set_redirecting(True)+ self.link.sent.clear()+ send = self.link.send_input+ self.link.send_input = lambda message: not self.link.sent and send(message)+ self.controller.handle_overlay_gesture(31, _Gesture(delta_x=1))+ while not self.controller.outbound.empty():+ self.controller._process_outbound(self.controller.outbound.get_nowait())+ self.assertEqual([m["data"]["key"] for m in self.link.sent], ["cmd"])+ self.assertEqual(self.link.dropped, ["The outbound queue filled"])++class ComingHomeTests(Base):def setUp(self):super().setUp()@@ -277,22 +493,26 @@ class ClipboardTests(Base):def test_the_clipboard_is_sent_again_only_after_it_changed_here(self):self.up()self.controller.set_redirecting(True)+ settle(self.controller)self.link.arrives(self.controller, protocol.accept_msg(1))self.controller.set_redirecting(False)self.link.posted.clear()self.controller.set_redirecting(True)+ settle(self.controller)self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())self.link.arrives(self.controller, protocol.accept_msg(3))self.controller.set_redirecting(False)self.clipboard.copy("something new")self.link.posted.clear()self.controller.set_redirecting(True)+ settle(self.controller)self.assertIn(protocol.MSG_CLIPBOARD, self.link.types())def test_an_oversized_text_is_skipped_but_the_take_still_goes(self):self.clipboard.text = "x" * (protocol.CLIPBOARD_MAX_BYTES + 1)self.up()self.controller.set_redirecting(True)+ settle(self.controller)self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())self.assertEqual(self.focus_count(), 1)@@ -310,7 +530,8 @@ class ClipboardTests(Base):def test_the_clipboard_goes_before_input_the_same_move_hands_on(self):# WIRE.md section 5: on the next machine's accept it gets the clipboard, then the held- # input, in order. The pasteboard is read under the owner's lock so nothing overtakes it.+ # input, in order. The pasteboard is read on its own thread, and what follows it for the+ # same machine waits for it.from core import owner as owner_moduleself.up()order = []@@ -319,6 +540,7 @@ class ClipboardTests(Base):self.link.send_input = lambda message: order.append(message["type"]) or send_input(message)key = {"type": protocol.MSG_KEYDOWN, "data": {"key": "v"}}self.controller._step(lambda owner: [owner_module.SendClipboard(self.peer), owner_module.Send(self.peer, key)])+ self.assertTrue(_wait(lambda: len(order) == 2), order)self.assertEqual(order, [protocol.MSG_CLIPBOARD, protocol.MSG_KEYDOWN])def test_a_clipboard_is_handed_on_as_rebuilt_from_what_was_read(self):diff --git a/mac_app/tests/test_mac_review.py b/mac_app/tests/test_mac_review.pyindex b3790db..eb7c80e 100644--- a/mac_app/tests/test_mac_review.py+++ b/mac_app/tests/test_mac_review.py@@ -178,19 +178,6 @@ class FailureTests(Base):self.controller.stop_event.set()thread.join(2)- def test_the_clipboard_sentinel_is_read_without_the_owner_lock(self):- bring_up(self.controller)- held = []- original = self.controller._send_clipboard-- def spy(peer):- held.append(self.controller._owner_lock._is_owned())- original(peer)-- self.controller._send_clipboard = spy- self.controller._process_outbound({"type": bridge._LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}, "peer": self.link.peer_id})- self.assertEqual(held, [False])-class CapabilityAndPairedTests(Base):def test_settings_from_a_peer_that_does_not_keep_them_are_ignored(self):diff --git a/mac_app/tests/test_mac_to_mac.py b/mac_app/tests/test_mac_to_mac.pynew file mode 100644index 0000000..88c8289--- /dev/null+++ b/mac_app/tests/test_mac_to_mac.py@@ -0,0 +1,162 @@+"""Mac to Mac on loopback: two real KVMControllers, each with the Mac's own responder+(windows_input.WindowsInput, its injector, desktop and clipboard faked as two_machines.py does),+paired to each other. Either drives the other, and every physical modifier pressed on the one is+pressed as the same key on the other (WIRE.md section 7, same family), in either style; a pinch and+a page swipe arrive as the Mac's own chords."""++import copy+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import config+import input_injector_mac+import windows_input+from bridge import KVMController+import bridge_fakes+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, crossing_config, quiet_logger+from core import protocol+from core.return_edge import Rect+from core.tests.responder_harness import FakeDesktop, FakeInjector, entry+from settings_store import SettingsStore+from two_machines import free_port, wait_for++BOUNDS = (0, 0, 1728, 1117)+# The Mac's modifier key codes, and the flag each sets while it is down.+MODIFIERS = {+ 0x38: ("Left Shift", "kCGEventFlagMaskShift"), 0x3C: ("Right Shift", "kCGEventFlagMaskShift"),+ 0x3B: ("Left Control", "kCGEventFlagMaskControl"), 0x3E: ("Right Control", "kCGEventFlagMaskControl"),+ 0x3A: ("Left Option", "kCGEventFlagMaskAlternate"), 0x3D: ("Right Option", "kCGEventFlagMaskAlternate"),+ 0x37: ("Left Command", "kCGEventFlagMaskCommand"), 0x36: ("Right Command", "kCGEventFlagMaskCommand"),+}+SWIPE_TYPE, MAGNIFY_TYPE = 31, 30+++class _Mac:+ def __init__(self, name, clock):+ self.name = name+ self.port = free_port()+ self.dir = tempfile.TemporaryDirectory()+ self.store = SettingsStore(Path(self.dir.name) / "settings.json")+ settings = copy.deepcopy(self.store.current())+ settings["port"] = self.port+ self.store.save_settings(settings)+ self.id = protocol.read_id(self.store.current()["machine_id"])+ self.text = protocol.id_text(self.id)+ self.clock = clock++ def pair_with(self, other, side, key_map):+ settings = copy.deepcopy(self.store.current())+ settings["peers"] = [entry(other.id, other.name, platform="macos", token=PAIRED_TOKEN, host="127.0.0.1",+ port=other.port, side=side)]+ settings["zones"] = [{"peer": other.text, "kind": "edge"}]+ self.store.save_settings(settings)+ cfg = crossing_config(PAIRED_TOKEN, edge=side, resistance_px=40)+ cfg.host, cfg.port, cfg.auth_token = "127.0.0.1", self.port, PAIRED_TOKEN+ cfg.reconnect_interval_s = 0.05+ cfg.key_map = key_map+ # Right Option is Beamer's own shortcut by default and stays on the Mac; moved off the+ # modifiers so every one of them is pressed through.+ cfg.trigger_key = "f19"+ self.cfg = cfg+ self.clipboard = bridge_fakes.FakeClipboard(f"on {self.name}")+ self.controller = KVMController(+ cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock, desktop_bounds=lambda: BOUNDS,+ book=self.store.book(), clipboard=self.clipboard,+ )+ self.controller.on_user_alert = lambda title, message: None+ self.injector = FakeInjector()+ left, top, right, bottom = BOUNDS+ with mock.patch.multiple(+ windows_input, input_injector_mac=self.injector,+ desktop_mac=FakeDesktop([Rect(left, top, right - left, bottom - top)], cursor=(800, 500)),+ clipboard_mac=self.clipboard,+ ):+ self.input = windows_input.WindowsInput(+ self.controller, logger=quiet_logger(), arrangement_callback=lambda *a: None, arrival_callback=lambda *a: None)++ def listen(self):+ self.input.sync(self.cfg)+ assert wait_for(lambda: self.input.server.listening), f"{self.name}'s responder never listened"++ def close(self):+ self.controller.stop()+ self.input.server.stop()+ self.dir.cleanup()++ def tap(self, event_type, fields):+ return self.controller._event_tap_callback(None, event_type, fields, None)+++class _Pair:+ style = "semantic"++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ clock = FakeClock()+ key_map = config.DEFAULT_KEY_MAP if self.style == "semantic" else config.LEGACY_POSITIONAL_KEY_MAP+ self.near, self.far = _Mac("Near Mac", clock), _Mac("Far Mac", clock)+ self.near.pair_with(self.far, "right", dict(key_map))+ self.far.pair_with(self.near, "left", dict(key_map))+ for mac in (self.near, self.far):+ mac.listen()+ self.addCleanup(mac.close)++ def drive(self, driver, driven):+ driver.controller.start()+ assert wait_for(lambda: driven.text in driver.controller._peers_up), f"{driver.name} never linked to {driven.name}: {driver.controller.connection_status}"+ self.assertTrue(driver.controller.set_redirecting(True))+ self.assertTrue(wait_for(lambda: driven.input.server.owner == driver.id))++ def keys_pressed_on(self, driven, count):+ self.assertTrue(wait_for(lambda: len([c for c in driven.injector.calls if c[0] == "key"]) >= count),+ driven.injector.calls)+ return [(name, down) for kind, name, down in (c for c in driven.injector.calls if c[0] == "key")]++ def modifiers_each_as_itself(self, driver, driven):+ self.drive(driver, driven)+ for code, (_, mask) in MODIFIERS.items():+ for down in (True, False):+ flags = getattr(FakeQuartz, mask) if down else 0+ self.assertIsNone(driver.tap(FakeQuartz.kCGEventFlagsChanged,+ {FakeQuartz.kCGKeyboardEventKeycode: code, "flags": flags}))+ pressed = self.keys_pressed_on(driven, 2 * len(MODIFIERS))+ got = [(input_injector_mac.plan_key_event(name, down, set())[0], down) for name, down in pressed]+ expected = [(code, down) for code in MODIFIERS for down in (True, False)]+ self.assertEqual(got, expected, pressed)++ def test_every_modifier_near_presses_is_pressed_as_itself_on_far(self):+ self.modifiers_each_as_itself(self.near, self.far)++ def test_every_modifier_far_presses_is_pressed_as_itself_on_near(self):+ self.modifiers_each_as_itself(self.far, self.near)+++class SemanticStyle(_Pair, unittest.TestCase):+ style = "semantic"++ def test_a_page_swipe_is_command_bracket_on_the_other_mac(self):+ self.drive(self.near, self.far)+ gesture = type("G", (), {"magnification": 0.0, "deltaX": 1.0, "deltaY": 0.0, "phase": 0})()+ self.near.controller.handle_overlay_gesture(SWIPE_TYPE, gesture)+ self.assertEqual(self.keys_pressed_on(self.far, 4), [("cmd", True), ("[", True), ("[", False), ("cmd", False)])++ def test_a_pinch_is_command_plus_on_the_other_mac(self):+ self.drive(self.near, self.far)+ gesture = type("G", (), {"magnification": 0.06, "deltaX": 0.0, "deltaY": 0.0, "phase": 0})()+ self.near.controller.handle_overlay_gesture(MAGNIFY_TYPE, gesture)+ self.assertEqual(self.keys_pressed_on(self.far, 4), [("cmd", True), ("=", True), ("=", False), ("cmd", False)])+ self.assertFalse([c for c in self.far.injector.calls if c[0] == "scroll"])+++class PositionalStyle(_Pair, unittest.TestCase):+ style = "positional"+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_wire.py b/mac_app/tests/test_mac_wire.pyindex d58b5a2..fe8c173 100644--- a/mac_app/tests/test_mac_wire.py+++ b/mac_app/tests/test_mac_wire.py@@ -136,6 +136,9 @@ class TakingTheFarMachineTests(Wire):self.assertTrue(self.connected())self.controller.set_redirecting(True)self.assertTrue(wait_for(lambda: self.machine.responder.owner is not None))+ # The take's own clipboard first, read on its own thread: a copy there before it lands is+ # overwritten by it, as one made by input sent there could not be (input waits behind it).+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls))self.machine.clipboard.copy("copied there")self.controller.set_redirecting(False)self.assertTrue(wait_for(lambda: ("copied there", None) in self.clipboard.set_calls), self.clipboard.set_calls)diff --git a/win_app/diagram.py b/win_app/diagram.pyindex 45c1907..6ce0e80 100644--- a/win_app/diagram.py+++ b/win_app/diagram.py@@ -12,6 +12,7 @@ import pages_winimport themeimport tokens+OTHER = "Other machine"SCREEN = (120.0, 75.0)GAP = 14.0PAD = 8.0@@ -42,7 +43,7 @@ def _marks(edge, methods, parts, corner, shortcut) -> dict:class ArrangementDiagram(QWidget):- """This PC's screen with your Mac's beside it on the chosen side, and on this PC's screen,+ """This PC's screen with the other machine's beside it on the chosen side, and on this PC's screen,lit, whatever crosses; the shortcut as a key cap underneath."""def __init__(self, parent: QWidget | None = None) -> None:@@ -53,8 +54,15 @@ class ArrangementDiagram(QWidget):self._angle = pages_win.SIDE_ANGLE["right"]self._marks = _marks("right", (), (), "", False)self._cap_text = ""+ self._other = OTHERself.setFixedHeight(self._height())+ def set_other_name(self, name: str) -> None:+ name = name or OTHER+ if name != self._other:+ self._other = name+ self.update()+def sizeHint(self) -> QSize:return QSize(2 * round(SCREEN[0]) + round(GAP) + 2 * round(PAD), self._height())@@ -103,7 +111,7 @@ class ArrangementDiagram(QWidget):painter.setRenderHint(QPainter.RenderHint.Antialiasing)pc, mac, pair_h = pages_win.arrangement_rects(self.width(), PAD, self._angle, SCREEN, GAP)radius = tokens.RADIUS["field"]- self._screen(painter, QRectF(*mac), "Your Mac", "panel", "edge", "ink_3", radius)+ self._screen(painter, QRectF(*mac), self._other, "panel", "edge", "ink_3", radius)self._screen(painter, QRectF(*pc), "This PC", "well", "edge", "ink_2", radius)for key, level in self._marks.items():if level <= 0.001:@@ -129,6 +137,7 @@ class ArrangementDiagram(QWidget):painter.drawRoundedRect(rect.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)painter.setPen(_colour(ink))painter.setFont(theme.font(tokens.TYPE["small"], 600))+ name = painter.fontMetrics().elidedText(name, Qt.TextElideMode.ElideRight, int(rect.width()) - 8)painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, name)@staticmethod@@ -198,7 +207,7 @@ class ArrangementDiagram(QWidget):class PushStrip(QWidget):- """A band of this screen's edge: the edge line, your Mac beyond it, and a `signal` fill from the+ """A band of this screen's edge: the edge line, the other machine beyond it, and a `signal` fill from theedge as deep as the resistance, with the pointer at its end. A change slides the fill and thepointer to the new depth, lit bright, and the light then settles."""@@ -211,6 +220,7 @@ class PushStrip(QWidget):self.setFixedHeight(self.HEIGHT)self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)+ self._other = OTHERself._value = Noneself._shown = 0.0self._glow = 0.0@@ -219,6 +229,12 @@ class PushStrip(QWidget):def minimumSizeHint(self) -> QSize:return QSize(160, self.HEIGHT)+ def set_other_name(self, name: str) -> None:+ name = name or OTHER+ if name != self._other:+ self._other = name+ self.update()+def set_edge(self, edge: str) -> None:mac_left = edge == "left"if mac_left != self._mac_left:@@ -253,7 +269,7 @@ class PushStrip(QWidget):def paintEvent(self, _event) -> None:painter = QPainter(self)painter.setRenderHint(QPainter.RenderHint.Antialiasing)- # Drawn with your Mac on the right; flipped when it is on the left.+ # Drawn with the other machine on the right; flipped when it is on the left.if self._mac_left:painter.translate(self.width(), 0)painter.scale(-1, 1)@@ -286,7 +302,10 @@ class PushStrip(QWidget):# Text drawn in the flipped frame would read backwards.painter.resetTransform()label = QRectF(self.width() - label.right(), label.top(), label.width(), label.height())- painter.drawText(label, Qt.AlignmentFlag.AlignCenter, "Your Mac")+ painter.drawText(+ label, Qt.AlignmentFlag.AlignCenter,+ painter.fontMetrics().elidedText(self._other, Qt.TextElideMode.ElideRight, int(label.width()) - 4),+ )painter.end()def _pointer(self, painter, tip: QPointF) -> None:diff --git a/win_app/firewall_win.py b/win_app/firewall_win.pyindex 9522262..5c87d71 100644--- a/win_app/firewall_win.py+++ b/win_app/firewall_win.py@@ -21,14 +21,15 @@ LOGGER = logging.getLogger(__name__)RULE_NAME = "Beamer Receiver (TCP-In)"# The pairing beacon's UDP port, written alongside the TCP rule by repair() and the installer.-# It is judged separately from the TCP rule because the two fail differently: without TCP the-# Mac cannot reach Beamer at all, while without UDP everything works except that a new Mac never-# sees this PC in its list -- and an install that predates the pairing rule has the first and-# not the second, so reporting only the TCP rule tells that user everything is fine.+# It is judged separately from the TCP rule because the two fail differently: without TCP no+# other machine can reach Beamer at all, while without UDP everything works except that a new+# machine never sees this PC in its list and this PC never hears theirs -- and an install that+# predates the pairing rule has the first and not the second, so reporting only the TCP rule+# tells that user everything is fine.PAIRING_RULE_NAME = "Beamer Pairing (UDP-In)"PAIRING_PORT = protocol.PAIRING_PORT# Pairing version 3 also hosts the pairing exchange over TCP on the same number while a code is-# on screen. Judged on its own: without it a Mac still finds this PC, then fails to finish pairing.+# on screen. Judged on its own: without it another machine still finds this PC, then fails to finish pairing.PAIRING_TCP_RULE_NAME = "Beamer Pairing (TCP-In)"_IS_WINDOWS = sys.platform == "win32"@@ -193,8 +194,8 @@ def advise(status: FirewallStatus) -> Advice:)elif not status.allowed:advice = Advice(- f"Windows Firewall has no rule letting your Mac reach Beamer on port {port}, so the Mac will say "- "Windows is unreachable. This happens when the installer was run without administrator rights. "+ f"Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will "+ "say this PC is unreachable. This happens when the installer was run without administrator rights. ""Fixing it adds the rule for private networks.","Fix the firewall","repair",@@ -204,7 +205,7 @@ def advise(status: FirewallStatus) -> Advice:names = ", ".join(alias for _, alias in status.public_interfaces if alias) or "this network"advice = Advice(f"Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and "- "your Mac cannot get in. Trusting it marks the network as private, which lets the Mac in without "+ "your other machines cannot get in. Trusting it marks the network as private, which lets them in without ""opening the port on every other network this PC joins.","Trust this network","trust",@@ -223,15 +224,16 @@ def advise(status: FirewallStatus) -> Advice:if not status.pairing_allowed:missing.append((f"the pairing beacon on UDP {PAIRING_PORT}",- "a Mac that has not been set up by hand will never see this PC in its list",+ "a machine that has not been set up by hand will never see this PC in its list, and this PC will not "+ "hear other machines' pairing announcements",))if not status.pairing_tcp_allowed:missing.append((f"the pairing exchange on TCP {PAIRING_PORT}",- "a Mac that finds this PC cannot finish pairing with it",+ "a machine that finds this PC cannot finish pairing with it",))advice = Advice(- f"Windows Firewall lets your Mac reach Beamer on port {port}, but there is no rule for "+ f"Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for "f"{' or for '.join(rule for rule, _ in missing)}, so {' and '.join(effect for _, effect in missing)}. ""Installs made before these rules existed are missing them. Fixing it adds what is missing ""and leaves the working rules alone.",@@ -242,7 +244,7 @@ def advise(status: FirewallStatus) -> Advice:else:where = "this private network" if "Private" in status.lan_profiles else "this network"return Advice(- f"Windows Firewall lets your Mac reach Beamer on port {port} on {where}, and lets a new Mac "+ f"Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine ""discover this PC.","Check again","check",diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex c348746..b5acd03 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -58,6 +58,7 @@ from effect_previews import EffectStill, SwitchStill, TileHoverfrom core import ignoredimport motionfrom core import pairing+from core import keytablefrom core import peerlistfrom core.pairing import PAIRING_PORT, PairingService, local_address_towardsimport machines_win@@ -120,10 +121,10 @@ CORNER_CHOICES = (TRIGGER_STYLE_CHOICES = (("double_tap", "Double-tap"), ("hold", "Hold"))MODIFIER_STYLE_CHOICES = (("semantic", "Same shortcuts"), ("positional", "Same positions"))MODIFIER_NOTES = {- "semantic": "Ctrl arrives on the Mac as Command and the Windows key as Control, so Ctrl+C "- "copies there too.",- "positional": "Each key arrives as the Mac key in the same place: Ctrl as Control, the Windows "- "key as Command.",+ "semantic": "On a Mac, Ctrl arrives as Command and the Windows key as Control, so Ctrl+C "+ "copies there too. Between two PCs every key arrives as itself.",+ "positional": "On a Mac, each key arrives as the Mac key in the same place: Ctrl as Control, the "+ "Windows key as Command. Between two PCs every key arrives as itself.",}FULL_SCREEN_CHECK_MS = 1000# How long a dragged slider waits, still, before the value it settled on is written to disk.@@ -175,6 +176,14 @@ def configure_logging() -> Optional[Path]:return None+def arrival_method(edge: Optional[str], driver_platform: str) -> str:+ """How input arriving at `edge` came: a Mac's notch crossing lands on this PC's bottom edge,+ and that is the only arrival an effect draws differently. No edge is a peer's shortcut or menu."""+ if edge is None:+ return "switch"+ return "notch" if edge == "bottom" and keytable.is_mac(driver_platform) else "edge"++def status_icon(state: ServerState, size: int = 64) -> QPixmap:"""The shipped colour mark with the state dot over its lower right corner: signal connected,amber waiting, fault needs attention, off stopped."""@@ -291,10 +300,8 @@ class WindowsApplication(QWidget):self._identity,status_callback=self._set_status,pressure_callback=lambda edge, pressure, crossed, part=None: self.bridge.pressure.emit(edge, pressure, crossed, part),- # The Mac's notch crossing lands on this PC's bottom edge, and that is the only- # arrival an effect draws differently. No edge is a peer's shortcut or menu.arrival_callback=lambda edge, x, y: self.bridge.arrived.emit(- "switch" if edge is None else "notch" if edge == "bottom" else "edge", edge or "", float(x), float(y)+ arrival_method(edge, self._driver_platform()), edge or "", float(x), float(y)),owner_callback=lambda peer: self.bridge.owner.emit(protocol.id_text(peer) if peer else ""),arrangement_callback=lambda peer, read: self.bridge.arrangement.emit(@@ -778,6 +785,15 @@ class WindowsApplication(QWidget):messages.append(protocol.settings_msg(self._same_state()))return messages+ def _driver_platform(self) -> str:+ """The platform of the machine driving this PC now, or "" when none is. From the peers the+ window last read, not settings.json: this runs on the responder's thread as input lands."""+ owner = self.server.owner+ if owner is None:+ return ""+ text = protocol.id_text(owner)+ return next((peer.get("platform") or "" for peer in self._peer_entries if peer.get("id") == text), "")+def _identity(self) -> dict:"""This machine as a `hello` and a `welcome` say it (section 2)."""config = self._config or default_config()@@ -888,6 +904,7 @@ class WindowsApplication(QWidget):self.shortcut_module = self._shortcut_module(current)layout.addWidget(self.shortcut_module)self._reflect_ways()+ self._reflect_other_name()@staticmethoddef _row(*items) -> QWidget:@@ -927,14 +944,14 @@ class WindowsApplication(QWidget):self.edge_choice = widgets.Choice(EDGE_CHOICES, columns=4, current=current.mac_return_edge, on_change=self._set_arrangement)- self.edge_choice.set_names("Where your Mac is")+ self.edge_choice.set_names("Where the other machine is")self.edge_unlearned = widgets.label(pages_win.NOT_LEARNED_EDGE, "note", wrap=True)self.edge_unlearned.setVisible(not current.mac_return_edge)self.crossing_rows = {"edge": self._row(- widgets.label("Where your Mac is", "key"),+ widgets.label("Where the other machine is", "key"),widgets.label(- "One border, walked both ways, so changing it here moves it on your Mac too.",+ "One border, walked both ways, so changing it here moves it on the other machine too.","note",wrap=True,),@@ -1160,9 +1177,9 @@ class WindowsApplication(QWidget):layout.addWidget(self._speed_module(current))def _speed_module(self, current: Config) -> QWidget:- """How the Mac's pointer feels on this PC: the Mac sends what its own acceleration made of+ """How the other machine's pointer feels on this PC: it sends what its own acceleration made ofthe hand's movement, and this PC's settings decide the rest."""- module = widgets.Module("The Mac's pointer here")+ module = widgets.Module("The other machine's pointer here")self.speed_sliders = {}self.speed_readouts = {}for key, name, value in (("pointer_speed", "Pointer speed", current.pointer_speed),@@ -1179,9 +1196,9 @@ class WindowsApplication(QWidget):module.body.addLayout(row)self.speed_sliders[key], self.speed_readouts[key] = slider, readoutmodule.body.addWidget(widgets.label(- "For the Mac's trackpad or mouse while it drives this PC.", "note", wrap=True+ "For the other machine's trackpad or mouse while it drives this PC.", "note", wrap=True))- self.reverse_scroll_switch = widgets.Switch("Reverse the Mac's scrolling")+ self.reverse_scroll_switch = widgets.Switch("Reverse the other machine's scrolling")self.reverse_scroll_switch.setFont(theme.font(theme.TYPE["body"]))self.reverse_scroll_switch.setChecked(current.reverse_scroll)self.reverse_scroll_switch.toggled.connect(self._reverse_scroll_changed)@@ -1259,10 +1276,10 @@ class WindowsApplication(QWidget):row_layout.addWidget(remove)self.ignored_list.addWidget(row)text = refused or (- "These keep working on this PC while its input is on your Mac: a mouse's back button for "+ "These keep working on this PC while its input is on another machine: a mouse's back button for ""this PC's browser, say, or a volume key for its speakers."if entries- else "Nothing yet. Every key and button goes to your Mac while it has input. Add one to keep "+ else "Nothing yet. Every key and button goes to the other machine while it has input. Add one to keep ""it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers.")self.ignored_note.setText(text)@@ -1301,7 +1318,7 @@ class WindowsApplication(QWidget):module = widgets.Module("Shortcut")module.body.addWidget(widgets.label(- "Use this key to send input to your Mac, and to bring it back.", "note", wrap=True+ "Use this key to send input to the other machine, and to bring it back.", "note", wrap=True))self.trigger_recorder = widgets.InputRecorder(@@ -1377,7 +1394,7 @@ class WindowsApplication(QWidget):def _update_style_hint(self, style: str) -> None:text = (- "Input is on the Mac for as long as the key is held."+ "Input is on the other machine for as long as the key is held."if style == "hold"else "Tap twice to switch; tap twice again to come back.")@@ -1432,8 +1449,8 @@ class WindowsApplication(QWidget):module.body.addWidget(self._own_note())module.body.addWidget(widgets.label(- "Lights this PC as you push toward your Mac. Switched off, crossing still works. "- "Your Mac sets how its own edge and notch look.",+ "Lights this PC as you push toward the other machine. Switched off, crossing still works. "+ "Each machine sets how its own edge looks.","note",wrap=True,)@@ -1762,6 +1779,13 @@ class WindowsApplication(QWidget):peers = []self._peer_entries = peersself.machines.set_peers(self._peer_items(peers))+ if hasattr(self, "arrangement_diagram"):+ self._reflect_other_name()++ def _reflect_other_name(self) -> None:+ name = self._machines_name() if len(self._peer_entries) == 1 else ""+ self.arrangement_diagram.set_other_name(name)+ self.resistance_strip.set_other_name(name)def _refresh_peer_states(self) -> None:"""The rows' states again from the peers last read: the links move faster than the file does."""@@ -2573,7 +2597,7 @@ class WindowsApplication(QWidget):box.setIconPixmap(QIcon(str(ICON_PATH)).pixmap(64, 64))box.setTextFormat(Qt.TextFormat.RichText)box.setText(- f"<b>Beamer {VERSION}</b><br>One keyboard and mouse for your Mac and PC.<br><br>"+ f"<b>Beamer {VERSION}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br>"f'<a href="{HOME_PAGE}" style="color: {theme.colour("signal")};">{HOME_PAGE_TEXT}</a>')box.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)diff --git a/win_app/pages_win.py b/win_app/pages_win.pyindex 634e3fe..a3aafb8 100644--- a/win_app/pages_win.py+++ b/win_app/pages_win.py@@ -15,26 +15,26 @@ PAGES = ("The machines paired with this PC, where input is right now, and the controls you reach for ""every day. Pair a machine here first."),("crossing", "Crossing",- "Choose how the pointer or a key moves input to your Mac, and how hard the edge pushes back "- "first."),+ "Choose how the pointer or a key moves input to the other machine, and how hard the edge "+ "pushes back first."),("keyboard", "Keyboard",- "How this PC's Ctrl and Windows keys arrive on your Mac, the keys and buttons that stay here, "- "and how fast your Mac's pointer moves here."),+ "How this PC's Ctrl and Windows keys arrive on the other machine, the keys and buttons that stay "+ "here, and how fast the other machine's pointer moves here."),("design", "Design",- "How crossing looks on this PC: the light as you push toward your Mac, and where the pointer "- "lands."),+ "How crossing looks on this PC: the light as you push toward the other machine, and where the "+ "pointer lands."),("connection", "Connection",- "Whether Windows Firewall lets your Mac in, this PC's address, port and shared token, and your "- "Mac's IP address, which pairing learns."),+ "Whether Windows Firewall lets your other machines in, this PC's address, port and shared token, "+ "and the other machine's IP address, which pairing learns."),)KEYS = tuple(page[0] for page in PAGES)-# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for the Mac's-# on the PC: each app sets only its own machine.+# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for the other+# machine's on the PC: each app sets only its own machine.SCOPE = {- "crossing": "For this PC only; your Mac keeps its own. Only which side your Mac is on is shared. This PC's "- "resistance is also what its pointer meets at your Mac's edge on the way back.",- "design": "For this PC's screen only; your Mac keeps its own.",- "keyboard": "For this PC's keyboard only; your Mac keeps its own.",+ "crossing": "For this PC only; the other machine keeps its own. Only which side the other machine is on is shared. This PC's "+ "resistance is also what its pointer meets at the other machine's edge on the way back.",+ "design": "For this PC's screen only; the other machine keeps its own.",+ "keyboard": "For this PC's keyboard only; the other machine keeps its own.",}# With Same on both machines on, under each row of the shared pages that stays this PC's own.OWN_ROW = "This PC only."@@ -173,10 +173,10 @@ def toggle_part(parts, part, on) -> list:return [candidate for candidate in ("start", "middle", "end") if candidate in chosen]-NOT_LEARNED_EDGE = "Not learned yet: your Mac tells this PC when it first connects, or choose a side."+NOT_LEARNED_EDGE = "Not learned yet: choose a side here or on the other machine."-def crossing_state_sentence(paired, heard, sending, connected, armed, paused, full_screen_app, name="your Mac") -> str:+def crossing_state_sentence(paired, heard, sending, connected, armed, paused, full_screen_app, name="the other machine") -> str:"""The Crossing page's line under Pause: why nothing can cross, first match wins, and only thenwhether crossing is on, held or paused. `name` is the machine it is about."""if not paired:@@ -259,7 +259,7 @@ def trigger_phrase(key_name: str, style: str) -> str:def ways_summary(methods, edge, parts, corner, key_name, style) -> str:"""The Ways in module's first line: every way input leaves for the Mac, in one sentence."""if not edge:- return "Nothing moves input to your Mac until it has connected once and told this PC which side it is on."+ return "Nothing moves input to the other machine until this PC knows which side it is on."methods = set(methods)ways = []if "edge" in methods:@@ -271,9 +271,9 @@ def ways_summary(methods, edge, parts, corner, key_name, style) -> str:if "shortcut" in methods:ways.append(f"hold {key_name}" if style == "hold" else f"press {key_name} twice")if not ways:- return "Nothing moves input to your Mac: choose at least one way below."+ return "Nothing moves input to the other machine: choose at least one way below."joined = ways[0] if len(ways) == 1 else ", ".join(ways[:-1]) + " or " + ways[-1]- return f"Input moves to your Mac when you {joined}."+ return f"Input moves to the other machine when you {joined}."# The arrangement diagram. Each side of this PC has an angle, and the Mac's screen travels rounddiff --git a/win_app/sender.py b/win_app/sender.pyindex 050591f..1e70d8f 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -349,6 +349,7 @@ class LinkSender:returnLOGGER.error("the link to %s went quiet; input returns to this PC", self._name(peer))self.links.close(peer)+ self._forget_held(peer)self._feed(lambda o: o.link_down(peer))def on_key(self, name: str, down: bool, vk: Optional[int] = None, us: Optional[str] = None) -> bool:@@ -576,6 +577,7 @@ class LinkSender:self._accepts[peer] = acceptselse:self._accepts.pop(peer, None)+ self._forget_held(peer)actions = self._owner.link_up(peer, accepts) if up else self._owner.link_down(peer)self._queue(actions)self._report(actions)@@ -721,31 +723,45 @@ class LinkSender:waiting.append(action)returnif isinstance(action, owner_module.SendClipboard):- self._clip_wait[peer] = collections.deque()- threading.Thread(target=self._clipboard_then_rest, args=(peer,), name="Beamer-links-clipboard", daemon=True).start()+ waiting = self._clip_wait[peer] = collections.deque()+ try:+ threading.Thread(target=self._clipboard_then_rest, args=(peer, waiting), name="Beamer-links-clipboard", daemon=True).start()+ except RuntimeError:+ # No thread at shutdown: nothing must wait behind a read that never starts.+ del self._clip_wait[peer]+ raisereturnself._send(peer, action.message)- def _clipboard_then_rest(self, peer: bytes) -> None:+ def _clipboard_then_rest(self, peer: bytes, waiting) -> None:+ """The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs to+ the link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the+ machine that reconnects will be taken afresh."""try:- self._send_clipboard(peer)+ self._send_clipboard(peer, waiting)except Exception:LOGGER.exception("The clipboard could not be sent")while True:with self._clip_lock:- waiting = self._clip_wait[peer]+ if self._clip_wait.get(peer) is not waiting:+ returnif not waiting:del self._clip_wait[peer]returnaction = waiting.popleft()try:if isinstance(action, owner_module.SendClipboard):- self._send_clipboard(peer)+ self._send_clipboard(peer, waiting)else:self._send(peer, action.message)except Exception:LOGGER.exception("A message held behind the clipboard could not be sent")+ def _forget_held(self, peer: bytes) -> None:+ """`peer`'s link is lost: what waited for its clipboard is for a link that is gone."""+ with self._clip_lock:+ self._clip_wait.pop(peer, None)+def _send(self, peer: bytes, message: dict) -> None:kind = message["type"]if kind == protocol.MSG_FOCUS:@@ -783,7 +799,7 @@ class LinkSender:else:style = self._setting("modifier_style", "semantic")try:- name = keytable.wire_name(physical, OWN_PLATFORM, entry.get("platform", "macos"), style)+ name = keytable.wire_name(physical, OWN_PLATFORM, entry.get("platform") or "", style)except ValueError:name = physicalif message["type"] == protocol.MSG_KEYDOWN:@@ -792,6 +808,7 @@ class LinkSender:def _send_failed(self, peer: bytes) -> None:self.links.close(peer)+ self._forget_held(peer)self._feed(lambda o: o.link_down(peer))def _feed(self, call) -> None:@@ -810,12 +827,15 @@ class LinkSender:self._clipboard_stamp = stampself._owner.clipboard_changed()- def _send_clipboard(self, peer: bytes) -> None:+ def _send_clipboard(self, peer: bytes, waiting) -> None:try:text, image = self._clipboard_module().get_contents()except Exception:LOGGER.exception("Failed to read the local clipboard for %s", self._name(peer))return+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ returncaps = self.links.caps(peer)if text and ("clipboard" not in caps or len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES):text = Nonediff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.pyindex bcaf577..15b0658 100644--- a/win_app/tests/test_crossing_matrix.py+++ b/win_app/tests/test_crossing_matrix.py@@ -229,7 +229,7 @@ class WhatIsSharedTests(unittest.TestCase):line = pages_win.SCOPE["crossing"]self.assertNotIn("Two are shared", line)- self.assertIn("Only which side your Mac is on is shared", line)+ self.assertIn("Only which side the other machine is on is shared", line)try:diff --git a/win_app/tests/test_effect_fires.py b/win_app/tests/test_effect_fires.pyindex ca26c19..ea56bd2 100644--- a/win_app/tests/test_effect_fires.py+++ b/win_app/tests/test_effect_fires.py@@ -129,6 +129,24 @@ class PressureRoutingTest(unittest.TestCase):overlay.push.assert_not_called()[email protected](kvm_bridge_win is None, "needs PySide6")+class ArrivalMethodTest(unittest.TestCase):+ """Only a Mac has a notch: a PC below this one lands on its bottom edge as an edge crossing."""++ def test_a_mac_landing_on_the_bottom_edge_came_through_its_notch(self):+ self.assertEqual(kvm_bridge_win.arrival_method("bottom", "macos"), "notch")++ def test_a_pc_landing_on_the_bottom_edge_crossed_an_edge(self):+ self.assertEqual(kvm_bridge_win.arrival_method("bottom", "windows"), "edge")++ def test_an_unknown_driver_on_the_bottom_edge_crossed_an_edge(self):+ self.assertEqual(kvm_bridge_win.arrival_method("bottom", ""), "edge")++ def test_other_edges_are_edges_and_no_edge_is_a_switch(self):+ self.assertEqual(kvm_bridge_win.arrival_method("left", "macos"), "edge")+ self.assertEqual(kvm_bridge_win.arrival_method(None, "macos"), "switch")++@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class ArrivalRoutingTest(unittest.TestCase):"""`method` is decided before _on_arrival ever runs, by the inline lambdas that wirediff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.pyindex f78c4fc..f04997e 100644--- a/win_app/tests/test_firewall_win.py+++ b/win_app/tests/test_firewall_win.py@@ -70,7 +70,7 @@ class InterpretTests(unittest.TestCase):self.assertEqual(status.public_interfaces, ())advice = advise(status)self.assertEqual(advice.action, "check")- self.assertIn("lets your Mac reach Beamer", advice.sentence)+ self.assertIn("lets your other machines reach Beamer", advice.sentence)def test_rule_scoped_to_a_profile_the_lan_is_not_on(self):# The installer's Private-only rule, but the LAN has been reclassified Public.@@ -266,6 +266,7 @@ class PairingRuleTests(unittest.TestCase):advice = advise(status)self.assertEqual(advice.action, "repair")self.assertIn("pairing beacon", advice.sentence)+ self.assertIn("will not hear other machines' pairing announcements", advice.sentence)def test_a_missing_pairing_rule_is_one_this_app_may_add_by_itself(self):# An upgrade from 1.4.x has the receiver and the UDP rule and no TCP one: the first code shown@@ -321,4 +322,4 @@ class PairingRuleTests(unittest.TestCase):# Input not arriving at all is the bigger problem; one button fixes both.status = interpret(payload([pairing_rule()]), EXE, PORT)self.assertFalse(status.allowed)- self.assertIn("no rule letting your Mac reach", advise(status).sentence)+ self.assertIn("no rule letting your other machines reach", advise(status).sentence)diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.pyindex 09c679c..99fc65d 100644--- a/win_app/tests/test_links.py+++ b/win_app/tests/test_links.py@@ -1,6 +1,7 @@"""This PC's input going to its peers (WIRE.md sections 3 to 5): the zones, the owner's decisionscarried out, the key names, the clipboard and the way home, against links that only record."""+import timeimport unittestfrom links_rig import B, C, CAPS, HERE, Rig, edge_zone, make_config@@ -368,6 +369,17 @@ class KeyTests(unittest.TestCase):rig.sender.on_key("ctrl", True, 0x5B)self.assertEqual([m["data"]["key"] for m in rig.sent(B, "keydown")], ["ctrl", "cmd"])+ def test_a_peer_of_no_known_platform_is_a_pc_and_gets_every_key_as_itself(self):+ # WIRE.md section 7: the PC family is Windows, Linux, Android and any unknown platform.+ unknown = harness.entry(B, "Something", side="left")+ del unknown["platform"]+ rig = Rig(entries=[unknown])+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.on_key("cmd", True, 0xA2)+ rig.sender.on_key("ctrl", True, 0x5B)+ self.assertEqual([m["data"]["key"] for m in rig.sent(B, "keydown")], ["ctrl", "cmd"])+def test_a_release_repeats_the_name_its_press_went_under(self):self.sender.on_key("A", True, 0x41, "a")self.sender.on_key("a", False, 0x41, "a")@@ -450,6 +462,37 @@ class ReviewTests(unittest.TestCase):self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == B and m["type"] == "keydown"]))self.assertEqual([m["type"] for t, m in rig.links.sent if t == B], ["focus", "clipboard", "keydown"])+ def test_pointer_moves_made_during_a_clipboard_read_go_one_by_one_as_made(self):+ # Never summed: the far machine's edge feels each move where its pointer is (return_edge).+ rig = self.two()+ rig.clipboard.slow_get = 0.3+ self.start_worker(rig)+ rig.sender.set_redirecting(True)+ for dx, dy in ((3, 1), (4, -2), (5, 0)):+ rig.sender.on_motion(dx, dy)+ self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == B and m["type"] == "mousemove"]))+ self.assertTrue(self.wait(lambda: not rig.sender._clip_wait))+ moves = [m["data"] for t, m in rig.links.sent if t == B and m["type"] == "mousemove"]+ self.assertEqual([(m["dx"], m["dy"]) for m in moves], [(3, 1), (4, -2), (5, 0)])++ def test_a_link_lost_during_a_clipboard_read_drops_what_waited_and_a_retake_sends_the_clipboard_after_its_focus(self):+ rig = self.two()+ rig.clipboard.slow_get = 0.4+ self.start_worker(rig)+ rig.sender.set_redirecting(True)+ self.assertTrue(self.wait(lambda: rig.sender._clip_wait))+ rig.sender.on_key("a", True, 0x41, "a")+ self.assertTrue(self.wait(lambda: rig.sender._clip_wait.get(B)))+ rig.sender.on_link(B, False)+ rig.sender.on_link(B, True, accepts=True)+ mark = len(rig.links.sent)+ rig.sender.set_redirecting(True)+ self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent[mark:] if t == B and m["type"] == "clipboard"], 2.0))+ self.assertTrue(self.wait(lambda: not rig.sender._clip_wait))+ time.sleep(0.5)+ after = [m["type"] for t, m in rig.links.sent[mark:] if t == B]+ self.assertEqual(after, ["focus", "clipboard"])+def test_a_peer_that_starts_accepting_input_arms_its_zone_at_once(self):rig = Rig(up=())rig.bring_up(B, accepts=False)diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.pyindex 2efe96d..320b463 100644--- a/win_app/tests/test_pages_win.py+++ b/win_app/tests/test_pages_win.py@@ -156,10 +156,10 @@ class CrossingWaysTest(unittest.TestCase):def test_the_summary_names_every_way_in_one_sentence(self):summary = pages_win.ways_summaryself.assertEqual(summary(["edge"], "right", [], "top_left", "Right Ctrl", "double_tap"),- "Input moves to your Mac when you push through the whole right edge.")+ "Input moves to the other machine when you push through the whole right edge.")self.assertEqual(summary(["shortcut", "part", "corner"], "left", ["start"], "bottom_right", "Right Ctrl", "hold"),- "Input moves to your Mac when you push through the top of the left edge, push diagonally into "+ "Input moves to the other machine when you push through the top of the left edge, push diagonally into ""the bottom-right corner or hold Right Ctrl.")self.assertIn("choose at least one way", summary([], "left", [], "top_left", "F13", "hold"))@@ -394,9 +394,9 @@ class CrossingPageTest(unittest.TestCase):def test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):line = pages_win.crossing_state_sentenceself.assertTrue(line(False, False, False, False, True, False, None).startswith("Not paired yet"))- self.assertTrue(line(True, False, True, False, True, False, None).startswith("Waiting to hear from your Mac"))- self.assertTrue(line(True, True, False, False, True, False, None).startswith("This PC does not drive your Mac"))- self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to your Mac"))+ self.assertTrue(line(True, False, True, False, True, False, None).startswith("Waiting to hear from the other machine"))+ self.assertTrue(line(True, True, False, False, True, False, None).startswith("This PC does not drive the other machine"))+ self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to the other machine"))self.assertTrue(line(True, True, True, True, False, False, None).startswith("Only the shortcut"))self.assertTrue(line(True, True, True, True, True, True, None).startswith("Paused."))self.assertTrue(line(True, True, True, True, True, False, "Keynote").startswith("Off while Keynote"))@@ -419,7 +419,7 @@ class CrossingPageTest(unittest.TestCase):def test_no_learned_edge_is_not_described_as_the_right_edge(self):summary = pages_win.ways_summary(["edge"], "", ["middle"], "top_right", "Right Ctrl", "double_tap")self.assertNotIn("right edge", summary)- self.assertTrue(summary.startswith("Nothing moves input to your Mac until"))+ self.assertTrue(summary.startswith("Nothing moves input to the other machine until"))self.assertIn("the whole right edge", pages_win.ways_summary(["edge"], "right", ["middle"], "top_right", "Right Ctrl", "double_tap"))diff --git a/win_app/tests/test_same_os_keys.py b/win_app/tests/test_same_os_keys.pynew file mode 100644index 0000000..31fa28b--- /dev/null+++ b/win_app/tests/test_same_os_keys.py@@ -0,0 +1,90 @@+"""Windows to Windows (WIRE.md section 7, same family): every physical modifier pressed on one PC is+pressed as the same key on the other, over real links, in either style and in either direction. The+press goes from the capture's name for the key, through LinkSender and the key table, over a link+to a LinkResponder, and is checked against the key the Windows injector would press for the name+that arrived."""++import unittest++from links_rig import make_config++import capture_win+import input_injector+import sender+from core import protocol, receiver+from core.return_edge import Rect+from core.tests import responder_harness as harness+from core.tests.responder_harness import B, HERE, TOKENS, Machine, entry, wait_for++MONITORS = [Rect(0, 0, 1920, 1080)]+MODIFIER_VKS = {+ 0xA0: "Left Shift", 0xA1: "Right Shift", 0xA2: "Left Ctrl", 0xA3: "Right Ctrl",+ 0x5B: "Left Windows", 0x5C: "Right Windows", 0xA4: "Left Alt", 0xA5: "Right Alt or AltGr",+}+++class _Pair:+ """`near` drives `far`, both Windows."""++ near, far = B, HERE++ def setUp(self):+ token = TOKENS[B]+ self.machine = Machine([entry(self.near, "Near", platform="windows", token=token)], own=self.far, name="Far").start()+ self.addCleanup(self.machine.stop)+ peer = entry(self.far, "Far", token=token, host="127.0.0.1", port=self.machine.port, side="left", linked=False,+ platform="windows")+ self.settings = harness.Settings([peer], [{"peer": protocol.id_text(self.far), "kind": "edge"}])+ self.settings.data["machine_id"] = protocol.id_text(self.near)+ book = receiver.PeerBook(self.settings.load, self.settings.save)+ self.sender = sender.LinkSender(+ book,+ lambda: {"id": self.near, "name": "Near", "platform": "windows", "app": "1.5.0", "caps": list(harness.CAPS), "port": 24820},+ zones=lambda: self.settings.data["zones"],+ desktop=harness.FakeDesktop(MONITORS, (0, 500)),+ clipboard=harness.FakeClipboard("near"),+ is_local=lambda host: False,+ arrival_callback=lambda edge, x, y: None,+ status_callback=lambda connected, detail: None,+ )+ self.sender.on_alert = lambda title, message: None++ def start(self, style):+ self.sender.start(make_config(machine_id=protocol.id_text(self.near), modifier_style=style))+ self.addCleanup(self.sender.stop)+ self.assertTrue(wait_for(lambda: self.sender.connected, 5), self.sender.status)+ self.assertTrue(self.sender.set_redirecting(True))+ self.assertTrue(wait_for(lambda: self.machine.owners and self.machine.owners[-1] == self.near))++ def pressed_there(self, style):+ self.start(style)+ for vk in MODIFIER_VKS:+ name = capture_win.VK_TO_NAME[vk]+ self.sender.on_key(name, True, vk)+ self.sender.on_key(name, False, vk)+ self.assertTrue(wait_for(lambda: len([c for c in self.machine.injected() if c[0] == "key"]) == 2 * len(MODIFIER_VKS)))+ keys = [call for call in self.machine.injected() if call[0] == "key"]+ return [(input_injector.VK_MAP[name], down) for _, name, down in keys]++ def check(self, style):+ expected = [(vk, down) for vk in MODIFIER_VKS for down in (True, False)]+ got = self.pressed_there(style)+ self.assertEqual(got, expected, [(MODIFIER_VKS.get(vk, hex(vk)), down) for vk, down in got])++ def test_every_modifier_arrives_as_itself_in_the_semantic_style(self):+ self.check("semantic")++ def test_every_modifier_arrives_as_itself_in_the_positional_style(self):+ self.check("positional")+++class NearDrivesFar(_Pair, unittest.TestCase):+ near, far = B, HERE+++class FarDrivesNear(_Pair, unittest.TestCase):+ near, far = HERE, B+++if __name__ == "__main__":+ unittest.main()