One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.3.2
Toby Kalkmanb69065b8d6c0
diff --git a/README.md b/README.mdindex c695f3f..e26dd84 100644--- a/README.md+++ b/README.md@@ -46,7 +46,7 @@ machine's settings.| Mac | Windows ||---|---|-| <img src="assets/mac-overview.png" width="400" alt="Beamer's Overview page on the Mac: where input is, whether the link is up, and the two everyday controls"> | <img src="assets/windows-overview.png" width="400" alt="Beamer's Overview page on Windows: where input is, and a switch for each direction"> |+| <img src="assets/mac-overview.png" width="400" alt="Beamer's Overview page on the Mac: where input is, whether the link is up, and the two everyday controls"> | <img src="assets/windows-overview.png" width="400" alt="Beamer's Overview page on Windows: where input is, Send input and Pause crossing, and a switch for each direction"> || <img src="assets/mac-design.png" width="400" alt="Beamer's Design page on the Mac: the notch and edge styles with live previews, and the colour schemes"> | <img src="assets/windows-design.png" width="400" alt="Beamer's Design page on Windows: the glow switch, Glow and Beam with live previews, and the colour schemes"> |## What it does@@ -55,13 +55,15 @@ machine's settings.through the MacBook's notch. The pointer arrives at the same point along the border. The edgelights up as you push, and the trackpad ticks at every quarter of the way through.- **Or press a key.** Double-tap or hold a trigger key to switch without moving the pointer. Right- Option on the Mac and Right Ctrl on the PC to start with; on the Mac it can be any key you like.+ Option on the Mac and Right Ctrl on the PC to start with; on either machine it can be any key+ that types nothing, recorded by pressing it.- **Either way round.** The Mac drives the PC and the PC drives the Mac. Each machine has a switchper direction, so you can turn one way off and keep the other.- **The clipboard comes with you.** Text and images, both ways, at the moment you switch. Filesstay where they are.- **Your shortcuts still work.** Cmd becomes Ctrl and Option becomes Alt on Windows, so Cmd+C- copies there too. The PC gets the reverse: its Ctrl+C arrives on the Mac as Cmd+C.+ copies there too. The PC gets the reverse: its Ctrl+C arrives on the Mac as Cmd+C. Either+ machine can switch to Positional instead, where each key arrives as the key in its place.- **Media keys follow you.** Play, pause, skip, mute and volume act on whichever machine you aredriving. Brightness stays with the Mac.- **Keys and buttons that stay put.** Each machine keeps a list of keys and mouse buttons that keep@@ -73,7 +75,9 @@ machine's settings.- **Make it yours.** The edge as a glow or a beam, five colour schemes, the notch as a beam or anisland with a meter, and how hard you push before it crosses.- **Out of the way when it should be.** A full-screen app holds the edges, so a game or a film never- loses the pointer; the trigger key still works. Switch to a PC that is asleep and Beamer wakes it.+ loses the pointer; the trigger key still works. Pause crossing does the same by hand. A drag+ that reaches the edge stays a drag. Switch to a machine that is asleep and Beamer wakes it, where+ that machine answers wake-on-LAN: a PC usually does, a MacBook on Wi-Fi usually does not.- **Your network, nobody else's.** No server in the middle. The two machines talk to each otherdirectly, encrypted, and you pair them once with a six-digit code. More in [SECURITY.md](SECURITY.md).- **Free and open source.** No account, no subscription, GPL-3.0.@@ -86,10 +90,10 @@ About Beamer.| Page | Mac | Windows ||---|---|---|-| Overview | Where input is, the link, the everyday controls, start at login | Where input is, a switch per direction, start at sign-in |-| Crossing | Ways in (edge, corner, notch, shortcut), which edge, resistance | Ways in (edge, corner, shortcut), the arrangement with the Mac, resistance |+| Overview | Where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at login | Where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at sign-in |+| Crossing | Ways in (edge, corner, notch, shortcut), which edge, never while dragging, resistance | Ways in (edge, corner, shortcut), the arrangement with the Mac, never while dragging, resistance || Design | Notch style, edge glow or beam, colour scheme, haptics, with live previews | Glow on or off, Glow or Beam, colour scheme, with live previews |-| Keyboard | Trigger key (recorded), double-tap or hold, modifier style, what stays on this Mac | Trigger key, double-tap or hold, what stays on this PC |+| Keyboard | Trigger key (recorded), double-tap or hold, what stays on this Mac, modifier style | Trigger key (recorded), double-tap or hold, what stays on this PC, modifier style || Pairing | Choose a PC and type its code | Pair a Mac shows the code || Connection | The PC's address, port and token | This PC's address, port and token || Permissions / Firewall | Accessibility and Input Monitoring | Whether Windows Firewall lets the Mac in, with a one-button fix |diff --git a/VERSION b/VERSIONindex 3a3cd8c..1892b92 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.3.1+1.3.2diff --git a/assets/mac-overview.png b/assets/mac-overview.pngindex 9612252..ad0e502 100644Binary files a/assets/mac-overview.png and b/assets/mac-overview.png differdiff --git a/assets/windows-overview.png b/assets/windows-overview.pngindex b4ed4db..b298368 100644Binary files a/assets/windows-overview.png and b/assets/windows-overview.png differdiff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex e9b6bbf..e8424ec 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -759,6 +759,8 @@ class ControlWindow(AppKit.NSObject):# Set by TrayApp once it exists: the listener for the PC's input, and# the second way an arrangement changed here can reach the PC.self.windows_input = None+ # Set by TrayApp: saves one direction's switch, as its menu ticks do.+ self.direction_handler = Noneself.last_capture_attempt = 0.0# Set by TrayApp: the beacon listener whose PCs the Pair module lists.self.discovery = None@@ -1175,8 +1177,39 @@ class ControlWindow(AppKit.NSObject):[self._keyboard_module(), self._pause_module()], bottom_rule=False, gap=theme.MODULE_GAP, fill=None)widgets.add(body, self.daily.view)+ widgets.add(body, self._directions_module().view)widgets.add(body, self._login_module().view)+ @objc.python_method+ def _directions_module(self):+ """The menu bar's two ticks, here too, as the PC has them on its Overview: either+ direction can be switched off while the other keeps working."""+ module = widgets.Module(spacing=10)+ module.add(widgets.eyebrow("Directions"))+ self.send_switch = widgets.Switch(+ "This Mac drives Windows", on_change=lambda on: self._set_direction(send_to_windows=on)+ )+ module.add(self.send_switch.view)+ self.receive_switch = widgets.Switch(+ "Windows drives this Mac", on_change=lambda on: self._set_direction(allow_windows_to_drive=on)+ )+ module.add(self.receive_switch.view)+ self._show_directions()+ return module++ @objc.python_method+ def _set_direction(self, **change):+ if self.direction_handler is not None:+ self.direction_handler(**change)+ self._show_directions()++ @objc.python_method+ def _show_directions(self):+ cfg = self.controller.cfg+ for switch, value in ((self.send_switch, cfg.send_to_windows), (self.receive_switch, cfg.allow_windows_to_drive)):+ if switch.value != bool(value):+ switch.value = value+@objc.python_methoddef _login_module(self):module = widgets.Module(spacing=10)@@ -2023,6 +2056,7 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef refresh(self):controller = self.controller+ self._show_directions()access = accessibility_granted()listening = input_monitoring_granted()self._permission(self.access_status, self.access_button, access)@@ -2160,6 +2194,7 @@ class TrayApp(rumps.App):controller, settings_store, logger)self.control_window.quit_handler = self.quit_app+ self.control_window.direction_handler = self._set_directioninstall_main_menu(self.control_window)self.gesture_overlay = GestureOverlay(controller, logger)self.edge_glow = EdgeGlow(controller, logger)diff --git a/mac_app/pages.py b/mac_app/pages.pyindex 0c8a404..c858e49 100644--- a/mac_app/pages.py+++ b/mac_app/pages.py@@ -8,7 +8,7 @@ from __future__ import annotations# (key, name, SF Symbol, what the page is for), in sidebar order; Cmd+1 is the first.PAGES = (("overview", "Overview", "gauge.with.needle",- "Where input is, whether the link is up, and the two controls you reach for every day."),+ "Where input is, whether the link is up, and the controls you reach for every day."),("crossing", "Crossing", "cursorarrow.motionlines","How the pointer passes from this Mac to Windows, and how hard the edge pushes back first."),("design", "Design", "paintpalette",diff --git a/mac_app/setup.py b/mac_app/setup.pyindex 46e5baf..674ef74 100644--- a/mac_app/setup.py+++ b/mac_app/setup.py@@ -41,6 +41,7 @@ setup("theme","tokens","wake",+ "wol","widgets","windows_input",],diff --git a/mac_app/tests/test_shared_copies.py b/mac_app/tests/test_shared_copies.pyindex 1fd722a..d8f4e73 100644--- a/mac_app/tests/test_shared_copies.py+++ b/mac_app/tests/test_shared_copies.py@@ -1,6 +1,6 @@"""The files both apps share are kept byte-identical, not merely similar.-`protocol.py`, `receiver.py` and `return_edge.py` each exist once in mac_app+`ignored.py`, `protocol.py`, `receiver.py`, `return_edge.py` and `wol.py` each exist once in mac_appand once in win_app because neither app can import across the other'sdirectory -- both are packaged as self-contained bundles. Everythingplatform-shaped in them is injected at construction instead, so there is no@@ -19,7 +19,7 @@ import unittest_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))-SHARED_MODULES = ("ignored.py", "protocol.py", "receiver.py", "return_edge.py")+SHARED_MODULES = ("ignored.py", "protocol.py", "receiver.py", "return_edge.py", "wol.py")SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py")diff --git a/mac_app/tests/test_wake.py b/mac_app/tests/test_wake.pyindex 8c4de2d..99425fb 100644--- a/mac_app/tests/test_wake.py+++ b/mac_app/tests/test_wake.py@@ -102,6 +102,15 @@ class WakingControllerTests(unittest.TestCase):if thread.name == "wake":thread.join(timeout=5)+ def test_a_pc_that_refused_the_token_is_not_woken(self):+ from bridge import AUTH_FAILED_STATUS++ self.controller.connection_status = AUTH_FAILED_STATUS+ self.assertFalse(self.controller.set_redirecting(True))+ self._wait_for_wake_thread()+ self.assertEqual(self.sent, [])+ self.assertFalse(self.controller.waking)+def test_switch_while_unreachable_sends_the_packet_and_shows_waking(self):# The wake thread must see the packet as sent before the window is checked.self.controller.stop_event.set()diff --git a/mac_app/wake.py b/mac_app/wake.pyindex 2e61190..5d17aaf 100644--- a/mac_app/wake.py+++ b/mac_app/wake.py@@ -1,89 +1,22 @@-"""Wake-on-LAN for the PC, and the controller that sends it when a switch finds the PC asleep.--The hardware address is never typed. It is read from this Mac's ARP table whenever a-connection succeeds -- the Mac has just exchanged packets with the PC, so the entry is fresh ---and stored with the rest of that PC's settings.+"""The controller that wakes the PC when a switch finds it asleep. The packet, the ARP lookup and+the address parsing are in wol.py, shared with the Windows app, which wakes this Mac the same way."""from __future__ import annotations-import re-import socket-import subprocessimport threading-from bridge import KVMController+from bridge import AUTH_FAILED_STATUS, KVMController+from wol import WAKE_WINDOW_SECONDS, lookup_mac, mac_from_arp_output, magic_packet, parse_mac, send_magic_packet++__all__ = [+ "NOT_WOKEN_STATUS", "WAKE_WINDOW_SECONDS", "WAKING_STATUS", "WakingController",+ "lookup_mac", "mac_from_arp_output", "magic_packet", "parse_mac", "send_magic_packet",+]-WOL_PORT = 9-# Sleep answers in a few seconds; hibernate and a cold boot take most of a minute. Past this-# the PC is reported as not woken rather than the switch waiting forever.-WAKE_WINDOW_SECONDS = 60.0WAKING_STATUS = "Waking Windows…"NOT_WOKEN_STATUS = "Windows did not wake"-# Six groups of one or two hex digits: Windows pads and joins with "-", macOS leaves a leading-# zero off and joins with ":".-_MAC_PATTERN = re.compile(r"(?<![0-9A-Fa-f])([0-9A-Fa-f]{1,2}(?:[:-][0-9A-Fa-f]{1,2}){5})(?![0-9A-Fa-f])")---def parse_mac(text: str):- """The address as six upper-case, zero-padded pairs joined with ":", or None."""- match = _MAC_PATTERN.fullmatch(text.strip()) if isinstance(text, str) else None- if match is None:- return None- return ":".join(part.zfill(2).upper() for part in re.split(r"[:-]", match.group(1)))---def mac_from_arp_output(output: str, ip: str):- """The hardware address `arp` printed for `ip`, from either platform's layout:-- Windows 192.168.1.3 02-1a-2b-3c-0d-4e dynamic- macOS ? (192.168.1.3) at 2:1a:2b:3c:d:4e on en0 ifscope [ethernet]- """- ip_pattern = re.compile(r"(?<![\d.])" + re.escape(ip) + r"(?![\d.])")- for line in output.splitlines():- if not ip_pattern.search(line):- continue- match = _MAC_PATTERN.search(line)- if match is not None:- return parse_mac(match.group(1))- return None---def lookup_mac(host: str):- """The hardware address this Mac's ARP table holds for `host`, or None. Only useful right- after talking to the host, which is the only time it is called."""- try:- ip = socket.gethostbyname(host)- completed = subprocess.run(["arp", "-n", ip], capture_output=True, text=True, timeout=3.0, check=False)- except (OSError, subprocess.SubprocessError):- return None- return mac_from_arp_output(completed.stdout, ip)---def magic_packet(mac: str) -> bytes:- address = parse_mac(mac)- if address is None:- raise ValueError(f"not a hardware address: {mac!r}")- return b"\xff" * 6 + bytes.fromhex(address.replace(":", "")) * 16---def send_magic_packet(mac: str, host: str = None) -> None:- """Broadcast the packet, and also send it straight at the host's last address, which is- what gets through on a network that filters broadcasts."""- packet = magic_packet(mac)- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- try:- sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)- sock.sendto(packet, ("255.255.255.255", WOL_PORT))- if host:- try:- sock.sendto(packet, (host, WOL_PORT))- except OSError:- pass- finally:- sock.close()-class WakingController(KVMController):"""KVMController plus wake-on-LAN. A switch attempted while the PC is unreachable sends the@@ -122,11 +55,17 @@ class WakingController(KVMController):return bool(self.cfg.mac_address) and not self.connecteddef set_redirecting(self, value, edge=None, offset=None):- if value and not self.redirecting and not self.connected and self.cfg.mac_address:+ if value and not self.redirecting and not self.connected and self.cfg.mac_address and not self._refused():self.wake()return Falsereturn super().set_redirecting(value, edge, offset)+ def _refused(self) -> bool:+ """A PC that answered and refused -- the token, or the protocol version -- is awake, and+ waking it would hide why; the switch says the refusal instead."""+ status = self._connection_status or ""+ return status == AUTH_FAILED_STATUS or "protocol v" in status or "older Beamer" in status+def wake(self) -> bool:"""Sends the packet and starts waiting, unless a wake is already in flight."""with self._wake_lock:diff --git a/mac_app/widgets.py b/mac_app/widgets.pyindex d07ab59..54980d4 100644--- a/mac_app/widgets.py+++ b/mac_app/widgets.py@@ -961,6 +961,11 @@ class Ruler:self.on_change(value)+# Loaded if a config names them, never offered by the recorder, as on Windows: typing keys a+# double-tap or a hold would take from every app.+UNRECORDABLE_TRIGGERS = {"enter", "tab", "space", "backspace", "esc"}++class KeyRecorder:"""A keycap that records the next key pressed as the trigger. Clicking arms it; the next keyor modifier press that Beamer can use as a trigger becomes the value, anything else cancels.@@ -1010,7 +1015,7 @@ class KeyRecorder:# A key Beamer cannot use as a trigger cancels, so the previous value is what shows.name = SPECIAL_KEY_NAMES.get(int(event.keyCode()))self._stop()- if name in KEY_NAME_TO_CODE:+ if name in KEY_NAME_TO_CODE and name not in UNRECORDABLE_TRIGGERS:self.set_value(name)if self.on_change is not None:self.on_change(name)diff --git a/mac_app/wol.py b/mac_app/wol.pynew file mode 100644index 0000000..670c569--- /dev/null+++ b/mac_app/wol.py@@ -0,0 +1,108 @@+"""Wake-on-LAN, shared by both apps: each machine wakes the other when a switch finds it asleep.++The hardware address is never typed. Each end reads it from its own ARP table whenever a+connection succeeds -- the two machines have just exchanged packets, so the entry is fresh --+and stores it with the rest of its settings.+"""++from __future__ import annotations++import re+import socket+import subprocess+import sys++WOL_PORT = 9+# Sleep answers in a few seconds; hibernate and a cold boot take most of a minute. Past this+# the other machine is reported as not woken rather than the switch waiting forever.+WAKE_WINDOW_SECONDS = 60.0++# Six groups of one or two hex digits: Windows pads and joins with "-", macOS leaves a leading+# zero off and joins with ":".+_MAC_PATTERN = re.compile(r"(?<![0-9A-Fa-f])([0-9A-Fa-f]{1,2}(?:[:-][0-9A-Fa-f]{1,2}){5})(?![0-9A-Fa-f])")+++def parse_mac(text: str):+ """The address as six upper-case, zero-padded pairs joined with ":", or None."""+ match = _MAC_PATTERN.fullmatch(text.strip()) if isinstance(text, str) else None+ if match is None:+ return None+ return ":".join(part.zfill(2).upper() for part in re.split(r"[:-]", match.group(1)))+++def mac_from_arp_output(output: str, ip: str):+ """The hardware address `arp` printed for `ip`, from either platform's layout:++ Windows 192.168.1.3 02-1a-2b-3c-0d-4e dynamic+ macOS ? (192.168.1.3) at 2:1a:2b:3c:d:4e on en0 ifscope [ethernet]+ """+ ip_pattern = re.compile(r"(?<![\d.])" + re.escape(ip) + r"(?![\d.])")+ for line in output.splitlines():+ if not ip_pattern.search(line):+ continue+ match = _MAC_PATTERN.search(line)+ if match is not None:+ return parse_mac(match.group(1))+ return None+++def lookup_mac(host: str):+ """The hardware address this machine's ARP table holds for `host`, or None. Only useful+ right after talking to the host, which is the only time it is called. On Windows `arp` is a+ console program, so it is started with no window: Beamer there is a tray app, and a console+ flashing up on every connection is exactly what it must never do."""+ windows = sys.platform == "win32"+ try:+ ip = socket.gethostbyname(host)+ completed = subprocess.run(+ ["arp", "-a", ip] if windows else ["arp", "-n", ip],+ capture_output=True,+ text=True,+ timeout=3.0,+ check=False,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if windows else 0,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ return mac_from_arp_output(completed.stdout, ip)+++def magic_packet(mac: str) -> bytes:+ address = parse_mac(mac)+ if address is None:+ raise ValueError(f"not a hardware address: {mac!r}")+ return b"\xff" * 6 + bytes.fromhex(address.replace(":", "")) * 16+++def send_magic_packet(mac: str, host: str = None) -> None:+ """Broadcast the packet, send it to the host's own subnet, and straight at its last address.+ The limited broadcast leaves by one interface only, which on a machine with a VPN or a+ virtual adapter can be the wrong one; the subnet's broadcast is routed out of the right one;+ and the direct send is what gets through on a network that filters broadcasts."""+ packet = magic_packet(mac)+ targets = ["255.255.255.255"]+ if host:+ subnet = subnet_broadcast(host)+ if subnet:+ targets.append(subnet)+ targets.append(host)+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)+ for index, target in enumerate(targets):+ try:+ sock.sendto(packet, (target, WOL_PORT))+ except OSError:+ if index == 0:+ raise+ finally:+ sock.close()+++def subnet_broadcast(host: str):+ """The /24 broadcast for a dotted IPv4 address, the size of nearly every home network, or+ None for anything else."""+ parts = host.split(".") if isinstance(host, str) else []+ if len(parts) != 4 or not all(part.isdigit() and int(part) <= 255 for part in parts):+ return None+ return ".".join(parts[:3] + ["255"])diff --git a/win_app/app_config.py b/win_app/app_config.pyindex e0c9024..9fbae5a 100644--- a/win_app/app_config.py+++ b/win_app/app_config.py@@ -7,6 +7,7 @@ import tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Path+import capture_winimport ignoredimport protocol@@ -17,30 +18,21 @@ EDGES = ("left", "right", "top", "bottom")CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")METHODS = ("edge", "corner", "shortcut")TRIGGER_STYLES = ("double_tap", "hold")-# Wire names, which are Mac-shaped: "cmd_r" is the right Ctrl key on this-# keyboard. Named here so the window can label them in Windows' own words-# without a second table to keep in step.-TRIGGER_KEYS = {- "cmd_r": "Right Ctrl",- "cmd": "Left Ctrl",- "alt_r": "Right Alt",- "alt": "Left Alt",- "ctrl_r": "Right Windows",- "ctrl": "Left Windows",- "shift_r": "Right Shift",- "menu": "Menu",-}-# The virtual key each trigger arrives as, so the ignored list can refuse the trigger.+# Any named key that is not a character can be the trigger, recorded by pressing it, as on the+# Mac: a modifier, a function key, a navigation key. Stored as its wire name, which is Mac-shaped --+# "cmd_r" is the right Ctrl key on this keyboard -- so every trigger saved before the recorder+# (eight fixed keys, 1.2 to 1.3.1) is still one. Media and browser keys are left out: they are+# what the stays-on-this-PC list is for. The undifferentiated 0x10-0x12 never reach the hook.+_NOT_TRIGGERS = {0x10, 0x11, 0x12} | set(range(0xA6, 0xB4))TRIGGER_VKS = {- "cmd_r": 0xA3,- "cmd": 0xA2,- "alt_r": 0xA5,- "alt": 0xA4,- "ctrl_r": 0x5C,- "ctrl": 0x5B,- "shift_r": 0xA1,- "menu": 0x5D,+ name: vk for vk, name in capture_win.VK_TO_NAME.items() if vk not in _NOT_TRIGGERS}+TRIGGER_KEYS = {name: capture_win.VK_TITLES[vk] for name, vk in TRIGGER_VKS.items()}+# Loaded if a config names them, never offered by the recorder, as on the Mac: Backspace, Tab,+# Enter, Esc and Space are typing keys a double-tap or a hold would take from every app, and+# Windows gives a window no key-down for Print Screen, so it cannot be recorded at all.+UNRECORDABLE_TRIGGER_VKS = {0x08, 0x09, 0x0D, 0x1B, 0x20, 0x2C}+MODIFIER_STYLES = ("semantic", "positional")class ConfigError(Exception):@@ -72,6 +64,11 @@ class Config:trigger_key: str = "cmd_r"trigger_style: str = "double_tap"double_tap_ms: int = 300+ # How this PC's Ctrl and Windows keys arrive on the Mac, the Mac's own two styles: Semantic+ # makes Ctrl+C Cmd+C there, Positional keeps each key where it sits.+ modifier_style: str = "semantic"+ # A push against the edge with a button held is a drag, not a crossing, as on the Mac.+ block_while_dragging: bool = True# The Mac's address is learned, never typed: it is the peer address the# Mac's own link arrives from.mac_host: str = ""@@ -86,6 +83,9 @@ class Config:# own number, above: one slider for each direction, because the hand does# not feel a trackpad and a mouse the same way.mac_resistance_px: int = 120+ # The Mac's hardware address, read from this PC's ARP table whenever the link comes up, so a+ # switch that finds the Mac asleep can send it a wake-on-LAN packet. Never typed.+ mac_hardware_address: str = ""# Keys and buttons that stay on this PC while its input is on the Mac; see ignored.py.ignored_inputs: list = field(default_factory=list)@@ -159,8 +159,14 @@ def validate_config(config: Config) -> None:double_tap_ms = int(config.double_tap_ms)except (TypeError, ValueError) as exc:raise ConfigError("double_tap_ms must be greater than zero") from exc- if isinstance(config.double_tap_ms, bool) or double_tap_ms <= 0:- raise ConfigError("double_tap_ms must be greater than zero")+ if isinstance(config.double_tap_ms, bool) or not 50 <= double_tap_ms <= 2000:+ raise ConfigError("double_tap_ms must be between 50 and 2000")+ if config.modifier_style not in MODIFIER_STYLES:+ raise ConfigError(f"modifier_style must be one of: {', '.join(MODIFIER_STYLES)}")+ if not isinstance(config.block_while_dragging, bool):+ raise ConfigError("block_while_dragging must be true or false")+ if not isinstance(config.mac_hardware_address, str):+ raise ConfigError("mac_hardware_address must be text")if not isinstance(config.crossing_methods, list) or any(method not in METHODS for method in config.crossing_methods):@@ -172,9 +178,9 @@ def validate_config(config: Config) -> None:try:resistance = int(value)except (TypeError, ValueError) as exc:- raise ConfigError(f"{name} must be a whole number of pixels, zero or more") from exc- if isinstance(value, bool) or resistance < 0:- raise ConfigError(f"{name} must be a whole number of pixels, zero or more")+ raise ConfigError(f"{name} must be a whole number of pixels from 0 to 500") from exc+ if isinstance(value, bool) or not 0 <= resistance <= 500:+ raise ConfigError(f"{name} must be a whole number of pixels from 0 to 500")if not isinstance(config.allow_mac_to_drive, bool):raise ConfigError("allow_mac_to_drive must be true or false")try:@@ -228,6 +234,9 @@ def config_from_dict(raw: dict) -> Config:trigger_key=trigger_key,trigger_style=raw.get("trigger_style", "double_tap"),double_tap_ms=int(raw.get("double_tap_ms", 300)),+ modifier_style=raw.get("modifier_style", "semantic"),+ block_while_dragging=raw.get("block_while_dragging", True),+ mac_hardware_address=raw.get("mac_hardware_address", "") or "",mac_host=raw.get("mac_host", "") or "",mac_return_edge=raw.get("mac_return_edge", "") or "",arrangement_set_at=int(raw.get("arrangement_set_at", 0)),@@ -280,6 +289,9 @@ def config_to_dict(config: Config) -> dict:"trigger_key": config.trigger_key,"trigger_style": config.trigger_style,"double_tap_ms": int(config.double_tap_ms),+ "modifier_style": config.modifier_style,+ "block_while_dragging": config.block_while_dragging,+ "mac_hardware_address": config.mac_hardware_address,"mac_host": config.mac_host,"mac_return_edge": config.mac_return_edge,"arrangement_set_at": int(config.arrangement_set_at),diff --git a/win_app/capture_win.py b/win_app/capture_win.pyindex c62fe83..123f644 100644--- a/win_app/capture_win.py+++ b/win_app/capture_win.py@@ -331,7 +331,10 @@ class Trigger:if name != self.key:return Falseif self.style == "hold":- return True+ # Except a release at home that the trigger never pressed: the key went down before+ # it became the trigger -- recorded in Hold, it is still held as it is recorded -- so+ # Windows has its key-down and must see it let go.+ return down or self._held or redirectingif not down and self._release_owed:self._release_owed = Falsereturn Truediff --git a/win_app/desktop_win.py b/win_app/desktop_win.pyindex 119ee8d..532f4f1 100644--- a/win_app/desktop_win.py+++ b/win_app/desktop_win.py@@ -28,6 +28,21 @@ if _IS_WINDOWS:user32.GetCursorPos.argtypes = [ctypes.POINTER(POINT)]user32.SetCursorPos.argtypes = [ctypes.c_int, ctypes.c_int]user32.EnumDisplayMonitors.argtypes = [ctypes.c_void_p, ctypes.c_void_p, MONITORENUMPROC, ctypes.c_ssize_t]+ user32.GetForegroundWindow.restype = ctypes.c_void_p+ user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]+ user32.GetClassNameW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_int]+ user32.GetWindowRect.argtypes = [ctypes.c_void_p, ctypes.POINTER(RECT)]+ user32.MonitorFromWindow.restype = ctypes.c_void_p+ user32.MonitorFromWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ user32.GetMonitorInfoW.argtypes = [ctypes.c_void_p, ctypes.c_void_p]+ user32.GetAsyncKeyState.restype = ctypes.c_short+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.restype = ctypes.c_void_p+ kernel32.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]+ kernel32.QueryFullProcessImageNameW.argtypes = [+ ctypes.c_void_p, ctypes.c_ulong, ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_ulong)+ ]+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]def _require() -> None:@@ -87,3 +102,89 @@ def set_cursor_position(x: int, y: int) -> None:"while a window above its integrity level is in front, until a click on this PC",error, blocker,)+++# What SHQueryUserNotificationState says while something owns the whole screen. 3 is a Direct3D+# exclusive full-screen game and 4 is Presentation Settings, both unambiguous. 2, QUNS_BUSY, is+# also what a borderless game or a browser on F11 gives, but overlays such as NVIDIA's raise it+# with nothing full screen at all (PowerToys PR #45891 split it out of its own guard for that), so+# it counts only with the foreground window covering its whole monitor. A maximised window stops+# at the taskbar and never does, which is what keeps this from becoming the size test the Mac+# learned catches every zoomed window.+_EXCLUSIVE_STATES = {3, 4}+QUNS_BUSY = 2+# The desktop and the taskbar are monitor-sized and foreground whenever the desktop is clicked.+_SHELL_CLASSES = {"Progman", "WorkerW", "Shell_TrayWnd", "Shell_SecondaryTrayWnd"}+++def full_screen_app():+ """The name of the foreground app while it is full screen, else None. GUI thread, once a+ second, as the Mac checks."""+ _require()+ state = ctypes.c_int(0)+ if ctypes.windll.shell32.SHQueryUserNotificationState(ctypes.byref(state)) != 0:+ return None+ if state.value in _EXCLUSIVE_STATES or (state.value == QUNS_BUSY and _foreground_covers_its_monitor()):+ return _foreground_app_name() or "An app"+ return None+++class MONITORINFO(ctypes.Structure):+ _fields_ = [("cbSize", ctypes.c_ulong), ("rcMonitor", RECT), ("rcWork", RECT), ("dwFlags", ctypes.c_ulong)]+++def _foreground_covers_its_monitor() -> bool:+ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return False+ name = ctypes.create_unicode_buffer(64)+ user32.GetClassNameW(hwnd, name, 64)+ if name.value in _SHELL_CLASSES:+ return False+ window = RECT()+ if not user32.GetWindowRect(hwnd, ctypes.byref(window)):+ return False+ info = MONITORINFO()+ info.cbSize = ctypes.sizeof(MONITORINFO)+ monitor = user32.MonitorFromWindow(hwnd, 2) # MONITOR_DEFAULTTONEAREST+ if not monitor or not user32.GetMonitorInfoW(monitor, ctypes.byref(info)):+ return False+ screen = info.rcMonitor+ return (window.left, window.top, window.right, window.bottom) == (+ screen.left, screen.top, screen.right, screen.bottom+ )+++# The hook reports logical buttons; GetAsyncKeyState reads physical ones, so with the buttons+# swapped in Settings the left and right virtual keys trade places.+_BUTTON_VKS = {"left": 0x01, "right": 0x02, "middle": 0x04, "back": 0x05, "forward": 0x06}+++def button_down(name: str) -> bool:+ _require()+ vk = _BUTTON_VKS.get(name)+ if vk is None:+ return False+ if vk in (0x01, 0x02) and user32.GetSystemMetrics(23): # SM_SWAPBUTTON+ vk = 0x03 - vk+ return bool(user32.GetAsyncKeyState(vk) & 0x8000)+++def _foreground_app_name():+ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return None+ pid = ctypes.c_ulong(0)+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))+ handle =kernel32.OpenProcess(0x1000, False, pid.value) # PROCESS_QUERY_LIMITED_INFORMATION+ if not handle:+ return None+ try:+ size = ctypes.c_ulong(260)+ buffer = ctypes.create_unicode_buffer(size.value)+ if not kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):+ return None+ name = buffer.value.rsplit("\\", 1)[-1]+ return name[:-4] if name.lower().endswith(".exe") else name+ finally:+ kernel32.CloseHandle(handle)diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex 760a2ec..9774d2e 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -37,6 +37,7 @@ from app_config import (ConfigError,TRIGGER_KEYS,TRIGGER_VKS,+ UNRECORDABLE_TRIGGER_VKS,default_config,default_config_path,load_config,@@ -45,6 +46,7 @@ from app_config import ()import autostart_winimport capture_win+import desktop_winfrom edge_glow import EdgeGlow, GlowPreview as EdgeGlowPreview, PreviewLoopimport firewall_winimport ignored@@ -103,6 +105,14 @@ CORNER_CHOICES = (("bottom_right", "Bottom-right"),)TRIGGER_STYLE_CHOICES = (("double_tap", "Double-tap"), ("hold", "Hold"))+MODIFIER_STYLE_CHOICES = (("semantic", "Semantic"), ("positional", "Positional"))+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.",+}+FULL_SCREEN_CHECK_MS = 1000GLOW_STYLE_CHOICES = (("glow", "Glow"), ("beam", "Beam"))GLOW_COLOUR_CHOICES = (("signal", "Signal"),@@ -183,6 +193,8 @@ class StatusBridge(QObject):learned = Signal(str, object, object)# Either link, telling us the two machines' arrangement changed at the other end.arrangement = Signal(str, int)+ alert = Signal(str, str)+ mac_learned = Signal(str)class WindowsApplication(QWidget):@@ -234,6 +246,10 @@ class WindowsApplication(QWidget):arrangement_callback=self.bridge.arrangement.emit,)self.sender.send_peer_home = self.server.send_home+ self.sender.on_alert = self.bridge.alert.emit+ self.sender.on_mac_learned = self.bridge.mac_learned.emit+ self.bridge.alert.connect(self._on_alert)+ self.bridge.mac_learned.connect(self._on_mac_learned)self.hooks = capture_win.Hooks(self._on_hook_key, self.sender.on_mouse, self.sender.on_motion)self._trigger = capture_win.Trigger()self._sending_detail = "Not connected to the Mac"@@ -260,6 +276,10 @@ class WindowsApplication(QWidget):self.refresh_timer.setInterval(250)self.refresh_timer.timeout.connect(self._refresh_window)self.refresh_timer.start()+ self.full_screen_timer = QTimer(self)+ self.full_screen_timer.setInterval(FULL_SCREEN_CHECK_MS)+ self.full_screen_timer.timeout.connect(self._check_full_screen)+ self.full_screen_timer.start()# Otherwise the heading, the "Input:"/"Now:" readouts and the sidebar dots sit blank# for the first 250ms every launch, waiting for the timer's first tick.self._refresh_window()@@ -351,12 +371,14 @@ class WindowsApplication(QWidget):self.sidebar.select(key)if key != "keyboard":self.ignored_recorder.cancel()+ self.trigger_recorder.cancel()self._run_previews()# -- Overview ---------------------------------------------------------------------------def _overview_page(self, layout, current) -> None:layout.addWidget(self._link_module())+ layout.addWidget(self._input_module())layout.addWidget(self._daily_module(current))def _link_module(self) -> QWidget:@@ -378,8 +400,78 @@ class WindowsApplication(QWidget):self.location_readout = widgets.label("", "readout", wrap=True)where_row.addWidget(self.location_readout, 1)module.body.addLayout(where_row)+ # Shown only while there is a figure: the trip is measured while input is on the Mac.+ self.round_trip_row = QWidget()+ trip_row = QHBoxLayout(self.round_trip_row)+ trip_row.setContentsMargins(0, 0, 0, 0)+ trip_row.setSpacing(6)+ trip_row.addWidget(widgets.label("Round trip:", "note"))+ self.round_trip_readout = widgets.label("", "readout", wrap=True)+ trip_row.addWidget(self.round_trip_readout, 1)+ self.round_trip_row.setVisible(False)+ module.body.addWidget(self.round_trip_row)+ return module++ def _input_module(self) -> QWidget:+ """The Mac's two everyday buttons: send input across without the shortcut or an edge, and+ hold the edges for a while."""+ module = widgets.Module("Keyboard and mouse")+ self.redirect_button = QPushButton("Send input to your Mac")+ self.redirect_button.setProperty("vernier", "primary")+ self.redirect_button.setCursor(Qt.CursorShape.PointingHandCursor)+ self.redirect_button.clicked.connect(self.toggle_redirect)+ module.body.addWidget(self.redirect_button)+ self.pause_button = QPushButton("Pause crossing")+ self.pause_button.setCursor(Qt.CursorShape.PointingHandCursor)+ self.pause_button.clicked.connect(self.toggle_pause)+ module.body.addWidget(self.pause_button)+ self.crossing_state = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.crossing_state)return module+ def toggle_redirect(self) -> None:+ self.sender.toggle()++ def toggle_pause(self) -> None:+ self.sender.crossing_paused = not self.sender.crossing_paused+ self._refresh_window()++ def _crossing_state_sentence(self) -> str:+ methods = set(self._config.crossing_methods) if self._config is not None else set()+ if not methods & {"edge", "corner"}:+ return "Only the shortcut is switched on; there is nothing to pause."+ if self.sender.crossing_paused:+ return "Paused. The edge and corner do nothing until you resume; the shortcut still works."+ if self.sender.full_screen_app is not None:+ return (+ f"Off while {self.sender.full_screen_app} is full screen, so the pointer stays put at "+ "the edges; the shortcut still works."+ )+ return "On. Pause it to lean on an edge without switching."++ def _check_full_screen(self) -> None:+ """The Mac's rule: a full-screen app in front holds the edges, the shortcut still works.+ A failure stops the check for the run rather than logging once a second."""+ try:+ self.sender.full_screen_app = desktop_win.full_screen_app()+ except Exception:+ self.sender.full_screen_app = None+ self.full_screen_timer.stop()+ LOGGER.exception("Could not tell whether an app is full screen; crossing stays on")++ def _on_alert(self, title: str, message: str) -> None:+ if self._closing:+ return+ if message.startswith("Cannot switch"):+ QApplication.beep()+ self.tray.showMessage(title, message, QIcon(str(ICON_PATH)), 4000)++ def _on_mac_learned(self, address: str) -> None:+ if self._config is None or self._config.mac_hardware_address == address:+ return+ self._config.mac_hardware_address = address+ self._persist()+def _daily_module(self, current: Config) -> QWidget:module = widgets.Module("Every day")self.allow_switch = widgets.Switch("Let your Mac drive this PC")@@ -495,6 +587,12 @@ class WindowsApplication(QWidget):module.body.addWidget(self.corner_choice.view)self.corner_choice.set_enabled("corner" in current.crossing_methods)+ self.dragging_switch = widgets.Switch("Never while dragging")+ self.dragging_switch.setFont(theme.font(theme.TYPE["body"]))+ self.dragging_switch.setChecked(current.block_while_dragging)+ self.dragging_switch.toggled.connect(self._set_block_while_dragging)+ module.body.addWidget(self.dragging_switch)+now_row = QHBoxLayout()now_row.setSpacing(6)# Named, not just "Now": this line is the Mac's half of the border --@@ -529,6 +627,13 @@ class WindowsApplication(QWidget):self.sender.update_config(self._config)self._reflect_look()+ def _set_block_while_dragging(self, enabled: bool) -> None:+ if self._config is None:+ return+ self._config.block_while_dragging = bool(enabled)+ self._persist()+ self.sender.update_config(self._config)+def _set_corner(self, corner: str) -> None:if self._config is None:return@@ -559,7 +664,7 @@ class WindowsApplication(QWidget):row = QHBoxLayout()row.setSpacing(10)self.resistance_slider = QSlider(Qt.Orientation.Horizontal)- self.resistance_slider.setRange(0, 300)+ self.resistance_slider.setRange(0, 500)self.resistance_slider.setValue(current.crossing_resistance_px)self.resistance_slider.valueChanged.connect(self._resistance_changed)row.addWidget(self.resistance_slider, 1)@@ -594,6 +699,25 @@ class WindowsApplication(QWidget):def _keyboard_page(self, layout, current: Config) -> None:layout.addWidget(self._shortcut_module(current))layout.addWidget(self._ignored_module(current))+ layout.addWidget(self._modifier_module(current))++ def _modifier_module(self, current: Config) -> QWidget:+ module = widgets.Module("Modifier keys")+ self.modifier_choice = widgets.Choice(+ MODIFIER_STYLE_CHOICES, columns=2, current=current.modifier_style, on_change=self._set_modifier_style+ )+ module.body.addWidget(self.modifier_choice.view)+ self.modifier_note = widgets.label(MODIFIER_NOTES[current.modifier_style], "note", wrap=True)+ module.body.addWidget(self.modifier_note)+ return module++ def _set_modifier_style(self, value: str) -> None:+ self.modifier_note.setText(MODIFIER_NOTES[value])+ if self._config is None:+ return+ self._config.modifier_style = value+ self._persist()+ self.sender.update_config(self._config)def _ignored_module(self, current: Config) -> QWidget:module = widgets.Module("Stays on this PC")@@ -672,10 +796,18 @@ class WindowsApplication(QWidget):"Use this key to send input to your Mac, and to bring it back.", "note", wrap=True))- self.trigger_key_choice = widgets.Choice(- tuple(TRIGGER_KEYS.items()), columns=2, current=current.trigger_key, on_change=self._set_trigger_key+ self.trigger_recorder = widgets.InputRecorder(+ TRIGGER_KEYS.get(current.trigger_key, current.trigger_key),+ self._record_trigger,+ capture_win.hook_vk,+ keys_only=True,)- module.body.addWidget(self.trigger_key_choice.view)+ self.trigger_recorder.HINT = "Click, then press the key"+ self.trigger_recorder.hint.setText(self.trigger_recorder.HINT)+ module.body.addWidget(self.trigger_recorder)+ self.trigger_note = widgets.label("", "note-amber", wrap=True)+ self.trigger_note.setVisible(False)+ module.body.addWidget(self.trigger_note)self.trigger_style_choice = widgets.Choice(TRIGGER_STYLE_CHOICES, columns=2, current=current.trigger_style, on_change=self._set_trigger_style)@@ -685,7 +817,8 @@ class WindowsApplication(QWidget):row = QHBoxLayout()row.setSpacing(10)self.double_tap_slider = QSlider(Qt.Orientation.Horizontal)- self.double_tap_slider.setRange(150, 600)+ # The Mac's range: the store takes 50 to 2000 ms, but only about 150 to 600 is useful.+ self.double_tap_slider.setRange(50, 1000)self.double_tap_slider.setValue(current.double_tap_ms)self.double_tap_slider.valueChanged.connect(self._double_tap_changed)row.addWidget(self.double_tap_slider, 1)@@ -696,12 +829,29 @@ class WindowsApplication(QWidget):self._update_style_hint(current.trigger_style)return module- def _set_trigger_key(self, value: str) -> None:+ def _record_trigger(self, kind: str, value) -> None:+ """Any key that types nothing, as on the Mac: a modifier, a function key, a navigation+ key. A key that types a character would stop typing it, so it is refused, and said so."""+ name = None+ if kind == "key" and value not in UNRECORDABLE_TRIGGER_VKS:+ name = next((n for n, vk in TRIGGER_VKS.items() if vk == value), None)+ if name is None:+ self.trigger_note.setText(+ "That key cannot be the shortcut. Choose a modifier such as Right Ctrl, a function "+ "key, or a key like Insert or Scroll Lock."+ )+ self.trigger_note.setVisible(True)+ return+ self.trigger_note.setVisible(False)+ self.trigger_recorder.set_title(TRIGGER_KEYS[name])if self._config is None:return- self._config.trigger_key = value+ self._config.trigger_key = nameself._persist()self._configure_trigger(self._config)+ if ignored.key(value) in self._config.ignored_inputs:+ # The shortcut always stays with Beamer, so it cannot also be on the stays-here list.+ self._set_ignored([entry for entry in self._config.ignored_inputs if entry != ignored.key(value)])def _set_trigger_style(self, value: str) -> None:if self._config is None:@@ -1166,6 +1316,10 @@ class WindowsApplication(QWidget):self.open_action.triggered.connect(self.show_window)self.status_action = menu.addAction(self._title())self.status_action.setEnabled(False)+ self.redirect_action = menu.addAction("Send input to your Mac")+ self.redirect_action.triggered.connect(self.toggle_redirect)+ self.pause_action = menu.addAction("Pause crossing")+ self.pause_action.triggered.connect(self.toggle_pause)menu.addSeparator()# One tick per direction, each the same switch the Overview page shows, so either# direction can be turned off while the other keeps working and the two never disagree.@@ -1180,6 +1334,8 @@ class WindowsApplication(QWidget):self.drive_action.setChecked(self.allow_switch.isChecked())self.send_action.setChecked(self.send_switch.isChecked())menu.addSeparator()+ menu.addAction("Reload configuration").triggered.connect(self.reload_config)+ menu.addSeparator()menu.addAction("About Beamer").triggered.connect(self.show_about)menu.addAction("Quit Beamer").triggered.connect(self.quit)self.tray.setContextMenu(menu)@@ -1188,6 +1344,56 @@ class WindowsApplication(QWidget):self.tray.activated.connect(self._on_tray_activated)self.tray.show()+ def reload_config(self) -> None:+ """Re-reads config.json, for the times it was edited outside the window, and shows it."""+ try:+ config = load_config(self.config_path)+ except (ConfigError, OSError) as exc:+ LOGGER.warning("Configuration not reloaded: %s", exc)+ self._on_alert("Beamer", f"Could not reload the configuration: {exc}")+ return+ self._host = config.host+ self._apply_config(config)+ self._configure_trigger(config)+ self._reflect_config(config)+ LOGGER.info("Configuration reloaded from %s", self.config_path)++ def _reflect_config(self, config: Config) -> None:+ """Every control on every page set from `config`, without any of them saving back."""+ for box in (*self.way_boxes.values(), self.dragging_switch, self.glow_toggle,+ self.resistance_slider, self.double_tap_slider):+ box.blockSignals(True)+ try:+ for value, box in self.way_boxes.items():+ box.setChecked(value in config.crossing_methods)+ self.dragging_switch.setChecked(config.block_while_dragging)+ self.glow_toggle.setChecked(config.edge_glow)+ self.resistance_slider.setValue(config.crossing_resistance_px)+ self.double_tap_slider.setValue(config.double_tap_ms)+ finally:+ for box in (*self.way_boxes.values(), self.dragging_switch, self.glow_toggle,+ self.resistance_slider, self.double_tap_slider):+ box.blockSignals(False)+ self.resistance_readout.setText(f"{config.crossing_resistance_px} px")+ self._update_resistance_hint(config.crossing_resistance_px)+ self.double_tap_readout.setText(f"{config.double_tap_ms} ms")+ self.double_tap_slider.setEnabled(config.trigger_style != "hold")+ self.corner_choice.set_value(config.crossing_corner)+ self.corner_choice.set_enabled("corner" in config.crossing_methods)+ self.edge_choice.set_value(config.mac_return_edge or "right")+ self.trigger_recorder.set_title(TRIGGER_KEYS.get(config.trigger_key, config.trigger_key))+ self.trigger_style_choice.set_value(config.trigger_style)+ self._update_style_hint(config.trigger_style)+ self.modifier_choice.set_value(config.modifier_style)+ self.modifier_note.setText(MODIFIER_NOTES[config.modifier_style])+ self.glow_style_choice.set_value(config.glow_style)+ self.glow_colour_choice.set_value(config.glow_colour)+ self._reflect_look()+ self._show_ignored(list(config.ignored_inputs))+ self.host_entry.setText(config.host)+ self.port_entry.setText(str(config.port))+ self.token_entry.setText(config.auth_token)+def _on_tray_activated(self, reason) -> None:if reason in (QSystemTrayIcon.ActivationReason.Trigger, QSystemTrayIcon.ActivationReason.DoubleClick):self.show_window()@@ -1255,6 +1461,10 @@ class WindowsApplication(QWidget):LOGGER.info("Ignoring %s as the Mac's address: that is this PC", host)host = Nonechanged = False+ if host and host != self._config.mac_host and self._config.mac_hardware_address:+ # A different Mac: the old one's hardware address would wake the wrong machine.+ self._config.mac_hardware_address = ""+ changed = Truefor name, value in (("mac_host", host), ("mac_return_edge", edge or ""), ("mac_resistance_px", resistance)):if value in (None, "") or getattr(self._config, name) == value:continue@@ -1313,6 +1523,7 @@ class WindowsApplication(QWidget):def hideEvent(self, event) -> None:super().hideEvent(event)self.ignored_recorder.cancel()+ self.trigger_recorder.cancel()self._run_previews()def changeEvent(self, event) -> None:@@ -1408,6 +1619,26 @@ class WindowsApplication(QWidget):location = "On your Mac" if self.sender.redirecting else "On this PC"if location != self.location_readout.text():self.location_readout.setText(location)+ trip = self.sender.round_trip_ms+ trip_text = f"{trip} ms" if trip is not None else ""+ if trip_text != self.round_trip_readout.text():+ self.round_trip_readout.setText(trip_text)+ self.round_trip_row.setVisible(trip is not None)+ redirect_text = "Bring input back to this PC" if self.sender.redirecting else "Send input to your Mac"+ if redirect_text != self.redirect_button.text():+ self.redirect_button.setText(redirect_text)+ self.redirect_action.setText(redirect_text)+ sending = self._config is not None and self._config.send_to_mac+ self.redirect_button.setEnabled(sending)+ self.redirect_action.setEnabled(sending)+ pause_text = "Resume crossing" if self.sender.crossing_paused else "Pause crossing"+ if pause_text != self.pause_button.text():+ self.pause_button.setText(pause_text)+ self.pause_action.setText(pause_text)+ widgets.set_role(self.pause_button, "primary" if self.sender.crossing_paused else "")+ sentence = self._crossing_state_sentence()+ if sentence != self.crossing_state.text():+ self.crossing_state.setText(sentence)# "On your Mac" above already says this while redirecting; the hint is for the rest --# not connected, or the hooks failing to install -- and stays quiet in the boring case.send_hint = "" if self.sender.redirecting or self._sending_detail in (diff --git a/win_app/pages_win.py b/win_app/pages_win.pyindex ff7505d..a76b29e 100644--- a/win_app/pages_win.py+++ b/win_app/pages_win.py@@ -8,7 +8,7 @@ from __future__ import annotations# (key, name, what the page is for), in sidebar order; Ctrl+1 is the first.PAGES = (("overview", "Overview",- "Where input is right now, and the two switches you reach for every day."),+ "Where input is right now, and the controls you reach for every day."),("crossing", "Crossing","How input leaves this PC: the ways in, the arrangement with your Mac, and how hard the edge ""pushes back first."),@@ -16,7 +16,8 @@ PAGES = ("How crossing looks on this PC: the light along the edge that leads to your Mac. Every ""change applies as you make it."),("keyboard", "Keyboard",- "The key that sends input to your Mac, and the keys and buttons that stay on this PC."),+ "The key that sends input to your Mac, the keys and buttons that stay on this PC, and how its "+ "Ctrl and Windows keys arrive on the Mac."),("pairing", "Pairing","Connect a Mac to this PC by typing the code it shows here. Once per Mac."),("connection", "Connection",diff --git a/win_app/sender.py b/win_app/sender.pyindex 713ea5a..f4dbbed 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -19,6 +19,7 @@ is armed only while the Mac is not driving this PC, so a pointer the Mac ismoving cannot push itself back out through the border it just came in by."""+import collectionsimport ipaddressimport loggingimport queue@@ -31,6 +32,7 @@ from typing import Callable, Optionalimport ignoredimport protocolimport return_edge+import wolLOGGER = logging.getLogger(__name__)@@ -50,7 +52,17 @@ _GATE_EXEMPT_TYPES = CONTROL_MESSAGE_TYPES | {_LOCAL_CLIPBOARD_SENTINEL_TYPE}# its type and data, so the mark never reaches the wire._RELEASE_MARK = "_release"-OLD_RECEIVER_STATUS = "The Mac did not answer the handshake — it is probably running an older Beamer; update it"+ROUND_TRIP_SAMPLES = 8+ROUND_TRIP_MAX_AGE_SECONDS = 5.0+WAKE_POLL_SECONDS = 0.5+WAKING_STATUS = "Waking your Mac…"+NOT_WOKEN_STATUS = "Your Mac did not wake"++# The capture names this PC's Ctrl "cmd" and its Windows key "ctrl", the Semantic style, so Ctrl+C+# is Cmd+C on the Mac. Positional swaps them back.+POSITIONAL_SWAP = {"cmd": "ctrl", "cmd_r": "ctrl_r", "ctrl": "cmd", "ctrl_r": "cmd_r"}++OLD_RECEIVER_STATUS ="The Mac did not answer the handshake — it is probably running an older Beamer; update it"AUTH_FAILED_STATUS = "The Mac could not be authenticated — check the shared token matches on both sides"@@ -145,6 +157,8 @@ class MacSender:socket_factory=_default_socket_factory,is_local=is_this_machine,clock=time.monotonic,+ wake_sender=wol.send_magic_packet,+ mac_lookup=wol.lookup_mac,) -> None:self._status_callback = status_callbackself._redirect_callback = redirect_callback@@ -198,6 +212,23 @@ class MacSender:# The receiver's way of sending the Mac's input home, handed in by the# app that owns both halves.self.send_peer_home = None+ # Both hold the edges and leave the shortcut working, as on the Mac: Pause crossing,+ # which a restart forgets, and the name of a full-screen app in front, set by the app.+ self.crossing_paused = False+ self.full_screen_app = None+ # The buttons of this PC's own mouse that are down, so a push with one held is a drag.+ self._buttons_held = set()+ # (title, message) for a notification, and the Mac's hardware address when the ARP table+ # names a new one; both called off the GUI thread.+ self.on_alert = None+ self.on_mac_learned = None+ self._wake_sender = wake_sender+ self._mac_lookup = mac_lookup+ self._waking = False+ self._wake_lock = threading.Lock()+ self._unacked_sent_at = collections.deque()+ self._round_trips = collections.deque(maxlen=ROUND_TRIP_SAMPLES)+ self._round_trip_at = 0.0# -- state the GUI reads ------------------------------------------------@@ -214,6 +245,28 @@ class MacSender:def edge(self) -> Optional[str]:return self._edge+ @property+ def waking(self) -> bool:+ return self._waking++ @property+ def round_trip_ms(self) -> Optional[int]:+ """The Mac's figure, measured the same way: the upper median of the last few trips from+ an input event's send to the ACK naming it, or None while input is not on the Mac, the+ link is down, or nothing fresh has been acknowledged for a few seconds."""+ if not self.redirecting or not self.connected:+ return None+ with self._sequence_lock:+ trips = sorted(self._round_trips)+ measured_at = self._round_trip_at+ if not trips or self._clock() - measured_at > ROUND_TRIP_MAX_AGE_SECONDS:+ return None+ return int(round(trips[len(trips) // 2] * 1000))++ @property+ def edges_held(self) -> bool:+ return self.crossing_paused or self.full_screen_app is not None+def set_receiving(self, receiving: bool) -> None:"""Called when the Mac takes input on this PC, and again when it givesit back. While it is True nothing here arms, sends or crosses."""@@ -245,6 +298,7 @@ class MacSender:def stop(self) -> None:self._stop_event.set()+ self._buttons_held.clear()self.set_redirecting(False)self._drop_connection()for thread in self._threads:@@ -291,15 +345,18 @@ class MacSender:return (self._clock() - last) <= ACK_TIMEOUT_SECONDSdef on_key(self, name: str, down: bool, vk: Optional[int] = None) -> bool:+ # Held keys are known by their virtual key where there is one: the name is the character+ # with Shift applied, so Shift let go before A made A's release arrive as "a" and miss.+ held = vk if vk is not None else nameif not self.redirecting:# A key that went down on the Mac and is still held after input# came home: the Mac was sent its release when input left, and# Windows never saw it go down, so it must see neither its# autorepeats nor its release. The entry goes on the release.- if name not in self._keys_down:+ if held not in self._keys_down:return Falseif not down:- self._keys_down.pop(name, None)+ self._keys_down.pop(held, None)return Trueif not self._link_live():self._force_local("the link to the Mac went quiet")@@ -307,21 +364,38 @@ class MacSender:if vk is not None and self._ignore_gate.keeps(ignored.key(vk), down):return Falseif down:- self._keys_down[name] = True- self._enqueue({"type": protocol.MSG_KEYDOWN, "data": {"key": name}})+ # The name it went down under is kept, so its release matches even if Shift or the+ # modifier style changes while it is held.+ wire = self._keys_down.get(held) or self._wire_name(name)+ self._keys_down[held] = wire+ self._enqueue({"type": protocol.MSG_KEYDOWN, "data": {"key": wire}})else:- self._keys_down.pop(name, None)+ wire = self._keys_down.pop(held, None) or self._wire_name(name)# Marked, so a release still queued when input comes home is sent# rather than dropped by the gate: the Mac has the key-down.- self._enqueue({"type": protocol.MSG_KEYUP, "data": {"key": name}, _RELEASE_MARK: True})+ self._enqueue({"type": protocol.MSG_KEYUP, "data": {"key": wire}, _RELEASE_MARK: True})return True+ def _wire_name(self, name: str) -> str:+ """The capture names Ctrl "cmd" and the Windows key "ctrl", the Semantic style;+ Positional swaps them back, so each key arrives as the Mac key in its place."""+ if self._setting("modifier_style", "semantic") == "positional":+ return POSITIONAL_SWAP.get(name, name)+ return name+def on_mouse(self, message: int, x: int, y: int, mouse_data: int) -> bool:"""Buttons and the wheel, and swallowing a move -- never the distanceit covered, which comes from on_motion. Returns True when the eventbelongs to the Mac and Windows must not see it."""import capture_win+ button = capture_win.button_of(message, mouse_data)+ if button is not None:+ name, down = button+ if down:+ self._buttons_held.add(name)+ else:+ self._buttons_held.discard(name)if not self.redirecting:return Falseif not self._link_live():@@ -382,7 +456,14 @@ class MacSender:PC's own mouse, and its push out means the pointer is going back tothe Mac with this mouse behind it (27-09-2026: it was ignored, and onlythe Mac's trackpad could take the pointer back)."""- if not self.connected:+ if not self.connected or self.edges_held:+ return+ if self._buttons_held and self._setting("block_while_dragging", True) and self._still_dragging():+ # A drag that reaches the edge is dragging, not leaving: the push so far is dropped,+ # as the Mac drops it, so letting go at the edge does not finish a crossing.+ for candidate in (self._corner_model, self._edge_model):+ if candidate is not None:+ candidate.reset()returntry:desktop = self._desktop_module()@@ -411,12 +492,25 @@ class MacSender:send_home = self.send_peer_homeif send_home is None or not send_home():LOGGER.warning("cannot cross: the Mac is driving this PC and cannot be reached")+ self._alert("Cannot switch — the Mac is driving this PC and cannot be reached")returnself._receiving = False# The model names the edge on the far side, not the one just left:# it is the same border, read from the other end.self.set_redirecting(True, arrival_edge=outcome.edge, offset=outcome.offset)+ def _still_dragging(self) -> bool:+ """A release the hook never saw -- let go over the secure desktop or an elevated window --+ would otherwise hold the edge shut for good, so each button is asked of Windows again."""+ is_down = getattr(self._desktop_module(), "button_down", None)+ if is_down is not None:+ try:+ self._buttons_held = {name for name in self._buttons_held if is_down(name)}+ except Exception:+ LOGGER.exception("Could not read the mouse buttons; treating none as held")+ self._buttons_held = set()+ return bool(self._buttons_held)+# -- switching ----------------------------------------------------------def set_redirecting(self, value, arrival_edge=None, offset=None) -> bool:@@ -430,6 +524,8 @@ class MacSender:if value:if not self.connected:LOGGER.warning("cannot redirect: the Mac is not connected")+ if not self.wake():+ self._alert(f"Cannot switch — {self._status}")return Falseif self._receiving:# The Mac is driving this PC over the other link, so switching@@ -439,6 +535,7 @@ class MacSender:if send_home is not None and send_home():return TrueLOGGER.warning("cannot redirect: the Mac is driving this PC and cannot be reached")+ self._alert("Cannot switch — the Mac is driving this PC and cannot be reached")return Falseself.redirecting = Trueself._pin_point = self._desktop_module().cursor_position()@@ -461,8 +558,8 @@ class MacSender:# The entries stay, so the physical releases here are swallowed.self.redirecting = Falseself._ignore_gate.reset()- for name in list(self._keys_down):- self._enqueue_control({"type": protocol.MSG_KEYUP, "data": {"key": name}, _RELEASE_MARK: True})+ for wire in list(self._keys_down.values()):+ self._enqueue_control({"type": protocol.MSG_KEYUP, "data": {"key": wire}, _RELEASE_MARK: True})self._pin_point = Noneself._last_point = None# A fresh model, not a reset one: the old one disarmed itself at@@ -570,12 +667,83 @@ class MacSender:self._last_sent_seq = 0self._last_ack_seq = -1self._last_ack_at = now+ self._unacked_sent_at.clear()+ self._round_trips.clear()+ self._round_trip_at = 0.0self._connected_at = nowself._last_send_at = nowself._set_status(f"Connected to the Mac at {host}")LOGGER.info("connected to the Mac at %s:%s", host, port)+ self._learn_mac_address(host)return True+ def _learn_mac_address(self, host) -> None:+ """Read the Mac's hardware address from the ARP table while the entry is fresh, for the+ wake-up a later switch may need."""+ try:+ address = self._mac_lookup(host)+ except Exception:+ LOGGER.exception("hardware address lookup failed")+ return+ if not address or address == self._setting("mac_hardware_address", ""):+ return+ # Not written here: the config is the app's own object, which the app saves.+ LOGGER.info("learned the Mac's hardware address from the ARP table")+ if self.on_mac_learned is not None:+ try:+ self.on_mac_learned(address)+ except Exception:+ LOGGER.exception("on_mac_learned callback failed")++ def wake(self) -> bool:+ """Send the Mac a wake-on-LAN packet and wait up to a minute for the link, as the Mac+ does for the PC. Nothing is queued: the person switches again once the Mac is up. False+ when there is no address to wake or a wake is already in flight."""+ address = self._setting("mac_hardware_address", "")+ if not address or self.connected or self._status in (AUTH_FAILED_STATUS, OLD_RECEIVER_STATUS) \+ or "protocol v" in self._status:+ # A Mac that answered and refused is awake; waking it would hide why.+ return False+ with self._wake_lock:+ if self._waking:+ return True+ self._waking = True+ threading.Thread(target=self._wake_worker, args=(address,), name="Beamer-wake-mac", daemon=True).start()+ return True++ def _wake_worker(self, address) -> None:+ started = self._clock()+ try:+ self._wake_sender(address, self._setting("mac_host", "") or None)+ except (OSError, ValueError) as exc:+ LOGGER.warning("wake-on-LAN packet not sent: %s", exc)+ self._waking = False+ self._alert("Could not send the wake-up packet")+ return+ LOGGER.info("sent wake-on-LAN to the Mac")+ self._alert(WAKING_STATUS)+ while not self._stop_event.wait(WAKE_POLL_SECONDS):+ if self.connected:+ self._waking = False+ LOGGER.info("the Mac woke and connected")+ self._alert("Your Mac is awake — switch again to send input")+ return+ if self._clock() - started >= wol.WAKE_WINDOW_SECONDS:+ break+ self._waking = False+ if self._stop_event.is_set():+ return+ LOGGER.warning("the Mac did not answer within %.0fs of the wake-on-LAN packet", wol.WAKE_WINDOW_SECONDS)+ self._alert(NOT_WOKEN_STATUS)++ def _alert(self, message: str) -> None:+ if self.on_alert is None:+ return+ try:+ self.on_alert("Beamer", message)+ except Exception:+ LOGGER.exception("Alert callback failed")+def _outbound_worker(self) -> None:while not self._stop_event.is_set():try:@@ -608,7 +776,9 @@ class MacSender:seq = self._last_sent_seqdata = dict(message.get("data", {}))data["seq"] = seq- self._send_raw({"type": message_type, "data": data})+ if self._send_raw({"type": message_type, "data": data}):+ with self._sequence_lock:+ self._unacked_sent_at.append((seq, self._last_send_at))def send_arrangement(self, mac_edge: str, set_at: int) -> bool:"""Tell the Mac where the machines are, when the change was made here."""@@ -720,7 +890,23 @@ class MacSender:raise protocol.ProtocolError("ACK seq moved backwards")if seq > self._last_sent_seq:raise protocol.ProtocolError("ACK seq is ahead of the sender")+ advanced = seq > self._last_ack_seqself._last_ack_seq = seq+ if advanced:+ self._measure_round_trip(seq, self._clock())++ def _measure_round_trip(self, seq, now) -> None:+ """Under _sequence_lock. From the send of the event the ACK names, as on the Mac: the+ receiver acknowledges the highest seq it has handled on a timer, so an older one would+ only measure that timer."""+ sent_at = None+ while self._unacked_sent_at and self._unacked_sent_at[0][0] <= seq:+ sent_seq, at = self._unacked_sent_at.popleft()+ if sent_seq == seq:+ sent_at = at+ if sent_at is not None:+ self._round_trips.append(now - sent_at)+ self._round_trip_at = nowdef _apply_inbound_clipboard(self, data) -> None:if not isinstance(data, dict):@@ -773,6 +959,7 @@ class MacSender:def _force_local(self, reason) -> None:if self.redirecting:LOGGER.error("%s; input forced back to this PC", reason)+ self._alert("Input returned to this PC")self.redirecting = Falseself._pin_point = Noneif self._redirect_callback is not None:diff --git a/win_app/tests/test_parity.py b/win_app/tests/test_parity.pynew file mode 100644index 0000000..4d4e75e--- /dev/null+++ b/win_app/tests/test_parity.py@@ -0,0 +1,220 @@+"""What the PC gained so each machine offers the same control as the other (27-09-2026 parity+audit, docs/parity-audit-27-09-2026.md): a recorded trigger key, the modifier style, Pause+crossing, the full-screen hold, never crossing while dragging, alerts, and waking the Mac."""++import time+import unittest+from dataclasses import replace++import app_config+import capture_win+import protocol+from app_config import ConfigError, config_from_dict, config_to_dict, default_config+import sender as sender_module+import test_sender+from test_sender import MONITORS, MacSenderWithLink, make_config, wait_for+from fakes import FakeClipboard, FakeDesktop, wait_for_calls+++def raw(**values):+ return {"host": "192.0.2.3", "port": 24820, "auth_token": "t", **values}+++class TriggerKeyTests(unittest.TestCase):+ def test_every_key_that_types_nothing_can_be_the_trigger(self):+ for name in ("f13", "insert", "scroll_lock", "shift", "caps_lock", "page_down", "esc"):+ self.assertEqual(config_from_dict(raw(trigger_key=name)).trigger_key, name)++ def test_the_eight_keys_saved_before_the_recorder_still_load(self):+ for name in ("cmd_r", "cmd", "alt_r", "alt", "ctrl_r", "ctrl", "shift_r", "menu"):+ self.assertEqual(config_from_dict(raw(trigger_key=name)).trigger_key, name)++ def test_a_character_or_a_media_key_is_refused(self):+ for name in ("a", "media_next", "volume_up", "browser_back"):+ with self.assertRaises(ConfigError):+ config_from_dict(raw(trigger_key=name))++ def test_every_trigger_is_titled_in_windows_words(self):+ self.assertEqual(app_config.TRIGGER_KEYS["cmd_r"], "Right Ctrl")+ self.assertEqual(app_config.TRIGGER_KEYS["ctrl"], "Left Windows")+ self.assertEqual(app_config.TRIGGER_KEYS["f13"], "F13")++ def test_a_recorded_trigger_is_what_the_hook_names_it(self):+ for name, vk in app_config.TRIGGER_VKS.items():+ self.assertEqual(capture_win.VK_TO_NAME[vk], name)+ trigger = capture_win.Trigger("f13", "double_tap", 300)+ self.assertIsNone(trigger.feed("f13", True, 0.0))+ self.assertEqual(trigger.feed("f13", True, 0.1), capture_win.TOGGLE)+++class ReviewFixTests(unittest.TestCase):+ def test_a_key_recorded_in_hold_style_while_held_is_let_go_on_windows(self):+ # Right Alt went down before it was the trigger, so Windows has its key-down.+ trigger = capture_win.Trigger("cmd_r", "hold", 300)+ trigger.configure("alt_r", "hold", 300)+ self.assertIsNone(trigger.feed("alt_r", False, 0.0))+ self.assertFalse(trigger.claims("alt_r", False, False))+ # A hold that is the trigger's own still swallows every event of the key.+ self.assertEqual(trigger.feed("alt_r", True, 1.0), capture_win.REDIRECT)+ self.assertTrue(trigger.claims("alt_r", True, True))++ def test_typing_keys_are_never_offered_as_the_trigger(self):+ for vk in (0x08, 0x09, 0x0D, 0x1B, 0x20, 0x2C):+ self.assertIn(vk, app_config.UNRECORDABLE_TRIGGER_VKS)++ def test_the_subnet_broadcast_of_a_home_address(self):+ import wol++ self.assertEqual(wol.subnet_broadcast("192.168.1.10"), "192.168.1.255")+ self.assertIsNone(wol.subnet_broadcast("mac.local"))+ self.assertIsNone(wol.subnet_broadcast(None))+++class ConfigRangeTests(unittest.TestCase):+ def test_the_macs_ranges(self):+ config_to_dict(replace(default_config(), auth_token="t", double_tap_ms=50, crossing_resistance_px=500))+ for change in ({"double_tap_ms": 40}, {"double_tap_ms": 2001}, {"crossing_resistance_px": 501}):+ with self.assertRaises(ConfigError):+ config_to_dict(replace(default_config(), auth_token="t", **change))++ def test_new_fields_default_and_round_trip(self):+ config = config_from_dict(raw())+ self.assertEqual(config.modifier_style, "semantic")+ self.assertTrue(config.block_while_dragging)+ self.assertEqual(config.mac_hardware_address, "")+ saved = config_to_dict(replace(config, modifier_style="positional", block_while_dragging=False))+ again = config_from_dict(saved)+ self.assertEqual((again.modifier_style, again.block_while_dragging), ("positional", False))++ def test_an_unknown_modifier_style_is_refused(self):+ with self.assertRaises(ConfigError):+ config_from_dict(raw(modifier_style="sideways"))+++class HeldEdgeTests(unittest.TestCase):+ def setUp(self):+ self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))+ self.link = MacSenderWithLink(desktop=self.desktop)+ self.sender = self.link.sender++ def tearDown(self):+ self.link.close()++ def push(self, times=10):+ for _ in range(times):+ self.sender.on_motion(-20, 0)++ def test_pause_holds_the_edge_and_leaves_the_shortcut(self):+ self.sender.crossing_paused = True+ self.push()+ self.assertFalse(self.sender.redirecting)+ self.assertTrue(self.sender.shortcut_armed)+ self.sender.crossing_paused = False+ self.push()+ self.assertTrue(self.sender.redirecting)++ def test_a_full_screen_app_holds_the_edge(self):+ self.sender.full_screen_app = "Game"+ self.push()+ self.assertFalse(self.sender.redirecting)++ def test_a_drag_against_the_edge_does_not_cross(self):+ self.sender.on_mouse(capture_win.WM_LBUTTONDOWN, 0, 500, 0)+ self.push()+ self.assertFalse(self.sender.redirecting)+ self.sender.on_mouse(capture_win.WM_LBUTTONUP, 0, 500, 0)+ self.push()+ self.assertTrue(self.sender.redirecting)++ def test_a_button_whose_release_was_never_seen_does_not_hold_the_edge_for_ever(self):+ # Let go over the secure desktop: the hook never saw the release, Windows says it is up.+ self.desktop.button_down = lambda name: False+ self.sender.on_mouse(capture_win.WM_MBUTTONDOWN, 0, 500, 0)+ self.push()+ self.assertTrue(self.sender.redirecting)++ def test_a_drag_crosses_when_the_setting_is_off(self):+ self.sender.update_config(make_config(block_while_dragging=False))+ self.sender.on_mouse(capture_win.WM_LBUTTONDOWN, 0, 500, 0)+ self.push()+ self.assertTrue(self.sender.redirecting)+++class AlertAndWakeTests(unittest.TestCase):+ def setUp(self):+ self.alerts = []+ self.packets = []+ self.sender = sender_module.MacSender(+ desktop=FakeDesktop(MONITORS, cursor=(900, 500)),+ clipboard=FakeClipboard(),+ is_local=lambda host: False,+ wake_sender=lambda mac, host: self.packets.append((mac, host)),+ mac_lookup=lambda host: None,+ )+ self.sender.on_alert = lambda title, message: self.alerts.append(message)++ def test_a_switch_with_no_link_and_no_address_says_why(self):+ self.sender.update_config(make_config())+ self.assertFalse(self.sender.set_redirecting(True))+ self.assertTrue(self.alerts and self.alerts[0].startswith("Cannot switch"))+ self.assertEqual(self.packets, [])++ def test_a_switch_with_no_link_wakes_a_mac_whose_address_is_known(self):+ self.sender.update_config(make_config(mac_hardware_address="02:1A:2B:3C:0D:4E"))+ self.assertFalse(self.sender.set_redirecting(True))+ self.assertTrue(wait_for(lambda: self.packets))+ self.assertEqual(self.packets[0], ("02:1A:2B:3C:0D:4E", "127.0.0.1"))+ self.assertTrue(wait_for(lambda: "Waking your Mac…" in self.alerts))+ self.sender._stop_event.set()++ def test_a_mac_that_refused_the_token_is_not_woken(self):+ self.sender.update_config(make_config(mac_hardware_address="02:1A:2B:3C:0D:4E"))+ self.sender._status = sender_module.AUTH_FAILED_STATUS+ self.assertFalse(self.sender.set_redirecting(True))+ self.assertEqual(self.packets, [])+ self.assertTrue(self.alerts[0].endswith(sender_module.AUTH_FAILED_STATUS))++ def test_a_dead_link_sending_input_home_says_so(self):+ self.sender.redirecting = True+ self.sender._force_local("the link went quiet")+ self.assertEqual(self.alerts, ["Input returned to this PC"])+++class ModifierAndRoundTripTests(test_sender.LinkTests):+ """Over the real loopback link to the Mac's receiver, reusing LinkTests' set-up; its own+ tests are proved in test_sender and not run twice."""++ def test_positional_sends_ctrl_as_control(self):+ self.sender.update_config(make_config(port=self.port, modifier_style="positional"))+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.sender.on_key("cmd", True)+ # The style changes while the key is held: its release still matches its press.+ self.sender.update_config(make_config(port=self.port))+ self.sender.on_key("cmd", False)+ wait_for_calls(self.injector.calls, 2)+ self.assertEqual(self.injector.calls, [("key", ("ctrl", True)), ("key", ("ctrl", False))])++ def test_shift_let_go_first_still_releases_the_capital(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.sender.on_key("A", True, 0x41)+ self.sender.on_key("a", False, 0x41)+ wait_for_calls(self.injector.calls, 2)+ self.assertEqual(self.injector.calls, [("key", ("A", True)), ("key", ("A", False))])+ self.assertEqual(self.sender._keys_down, {})++ def test_the_round_trip_is_measured_while_input_is_on_the_mac(self):+ self.assertIsNone(self.sender.round_trip_ms)+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ for _ in range(5):+ self.sender.on_motion(3, 0)+ time.sleep(0.05)+ self.assertTrue(wait_for(lambda: self.sender.round_trip_ms is not None), "no round trip measured")+ self.assertGreaterEqual(self.sender.round_trip_ms, 0)+++for _name in [n for n in dir(test_sender.LinkTests) if n.startswith("test_")]:+ setattr(ModifierAndRoundTripTests, _name, None)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_shared_copies.py b/win_app/tests/test_shared_copies.pyindex 1fd722a..d8f4e73 100644--- a/win_app/tests/test_shared_copies.py+++ b/win_app/tests/test_shared_copies.py@@ -1,6 +1,6 @@"""The files both apps share are kept byte-identical, not merely similar.-`protocol.py`, `receiver.py` and `return_edge.py` each exist once in mac_app+`ignored.py`, `protocol.py`, `receiver.py`, `return_edge.py` and `wol.py` each exist once in mac_appand once in win_app because neither app can import across the other'sdirectory -- both are packaged as self-contained bundles. Everythingplatform-shaped in them is injected at construction instead, so there is no@@ -19,7 +19,7 @@ import unittest_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))-SHARED_MODULES = ("ignored.py", "protocol.py", "receiver.py", "return_edge.py")+SHARED_MODULES = ("ignored.py", "protocol.py", "receiver.py", "return_edge.py", "wol.py")SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py")diff --git a/win_app/widgets.py b/win_app/widgets.pyindex ab437ac..0960fa9 100644--- a/win_app/widgets.py+++ b/win_app/widgets.py@@ -322,11 +322,13 @@ class InputRecorder(QPushButton):Qt.MouseButton.ForwardButton: "forward",}- def __init__(self, title: str, on_record, hook_vk, parent: QWidget | None = None) -> None:+ def __init__(self, title: str, on_record, hook_vk, parent: QWidget | None = None, keys_only: bool = False) -> None:super().__init__(parent)self.title = titleself.on_record = on_recordself.hook_vk = hook_vk+ # The trigger is a key: a mouse button while it records cancels, as on the Mac.+ self.keys_only = keys_onlyself.armed = Falseself.left_ctrl_held = Falseself.setProperty("vernier", "keycap")@@ -345,6 +347,13 @@ class InputRecorder(QPushButton):row.addWidget(self.hint, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)self.clicked.connect(self._toggle)+ def set_title(self, title: str) -> None:+ """What the keycap says while it is not recording: the trigger recorder shows its key."""+ self.title = title+ self.setAccessibleName(title)+ if not self.armed:+ self.key.setText(title)+def cancel(self) -> None:self.left_ctrl_held = Falseif not self.armed:@@ -391,7 +400,7 @@ class InputRecorder(QPushButton):return Trueif kind == QEvent.Type.MouseButtonPress:name = self.BUTTONS.get(event.button())- if name is None:+ if name is None or self.keys_only:# The left button disarms, and the press goes where it was aimed -- except onto# this keycap, where it would arm it again.inside = isinstance(watched, QWidget) and (watched is self or self.isAncestorOf(watched))diff --git a/win_app/wol.py b/win_app/wol.pynew file mode 100644index 0000000..670c569--- /dev/null+++ b/win_app/wol.py@@ -0,0 +1,108 @@+"""Wake-on-LAN, shared by both apps: each machine wakes the other when a switch finds it asleep.++The hardware address is never typed. Each end reads it from its own ARP table whenever a+connection succeeds -- the two machines have just exchanged packets, so the entry is fresh --+and stores it with the rest of its settings.+"""++from __future__ import annotations++import re+import socket+import subprocess+import sys++WOL_PORT = 9+# Sleep answers in a few seconds; hibernate and a cold boot take most of a minute. Past this+# the other machine is reported as not woken rather than the switch waiting forever.+WAKE_WINDOW_SECONDS = 60.0++# Six groups of one or two hex digits: Windows pads and joins with "-", macOS leaves a leading+# zero off and joins with ":".+_MAC_PATTERN = re.compile(r"(?<![0-9A-Fa-f])([0-9A-Fa-f]{1,2}(?:[:-][0-9A-Fa-f]{1,2}){5})(?![0-9A-Fa-f])")+++def parse_mac(text: str):+ """The address as six upper-case, zero-padded pairs joined with ":", or None."""+ match = _MAC_PATTERN.fullmatch(text.strip()) if isinstance(text, str) else None+ if match is None:+ return None+ return ":".join(part.zfill(2).upper() for part in re.split(r"[:-]", match.group(1)))+++def mac_from_arp_output(output: str, ip: str):+ """The hardware address `arp` printed for `ip`, from either platform's layout:++ Windows 192.168.1.3 02-1a-2b-3c-0d-4e dynamic+ macOS ? (192.168.1.3) at 2:1a:2b:3c:d:4e on en0 ifscope [ethernet]+ """+ ip_pattern = re.compile(r"(?<![\d.])" + re.escape(ip) + r"(?![\d.])")+ for line in output.splitlines():+ if not ip_pattern.search(line):+ continue+ match = _MAC_PATTERN.search(line)+ if match is not None:+ return parse_mac(match.group(1))+ return None+++def lookup_mac(host: str):+ """The hardware address this machine's ARP table holds for `host`, or None. Only useful+ right after talking to the host, which is the only time it is called. On Windows `arp` is a+ console program, so it is started with no window: Beamer there is a tray app, and a console+ flashing up on every connection is exactly what it must never do."""+ windows = sys.platform == "win32"+ try:+ ip = socket.gethostbyname(host)+ completed = subprocess.run(+ ["arp", "-a", ip] if windows else ["arp", "-n", ip],+ capture_output=True,+ text=True,+ timeout=3.0,+ check=False,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if windows else 0,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ return mac_from_arp_output(completed.stdout, ip)+++def magic_packet(mac: str) -> bytes:+ address = parse_mac(mac)+ if address is None:+ raise ValueError(f"not a hardware address: {mac!r}")+ return b"\xff" * 6 + bytes.fromhex(address.replace(":", "")) * 16+++def send_magic_packet(mac: str, host: str = None) -> None:+ """Broadcast the packet, send it to the host's own subnet, and straight at its last address.+ The limited broadcast leaves by one interface only, which on a machine with a VPN or a+ virtual adapter can be the wrong one; the subnet's broadcast is routed out of the right one;+ and the direct send is what gets through on a network that filters broadcasts."""+ packet = magic_packet(mac)+ targets = ["255.255.255.255"]+ if host:+ subnet = subnet_broadcast(host)+ if subnet:+ targets.append(subnet)+ targets.append(host)+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)+ for index, target in enumerate(targets):+ try:+ sock.sendto(packet, (target, WOL_PORT))+ except OSError:+ if index == 0:+ raise+ finally:+ sock.close()+++def subnet_broadcast(host: str):+ """The /24 broadcast for a dotted IPv4 address, the size of nearly every home network, or+ None for anything else."""+ parts = host.split(".") if isinstance(host, str) else []+ if len(parts) != 4 or not all(part.isdigit() and int(part) <= 255 for part in parts):+ return None+ return ".".join(parts[:3] + ["255"])