One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.11
Toby Kalkman4ad8cd0c5698
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5e086b1..4ee3b4e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -19,10 +19,11 @@ at once. Test builds appear on the releases page as pre-releases.## Pull requests-Beamer is GPL-3.0 and has one author. A pull request from anyone else changes that, so before one-is merged I will ask you to confirm the change is your own work and that you license it under-GPL-3.0, and possibly more. For anything bigger than a small, obvious fix, open an issue first so-we agree the approach before you write code.+Pull requests are welcome. Sign off every commit with `git commit -s`. The sign-off is the+[Developer Certificate of Origin](https://developercertificate.org): it confirms the change is your+own work, or that you have the right to submit it, and that you license it under GPL-3.0-only, the+licence Beamer is released under. There is no separate contributor agreement. For anything bigger+than a small, obvious fix, open an issue first so we agree the approach before you write code.## Building itdiff --git a/VERSION b/VERSIONindex f0ed379..df80819 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.10+1.5.11diff --git a/WIRE.md b/WIRE.mdindex 3164117..40eaa9b 100644--- a/WIRE.md+++ b/WIRE.md@@ -555,7 +555,11 @@ Either way:- **`mousemove`**: `dx` and `dy` are integers from -65535 to 65535, relative motion in thesender's logical pixels (points on a Mac) after its own acceleration; positive `dy` is down.The sender keeps the fractions and sends whole pixels. A phone sends its own points after its- acceleration curve.+ acceleration curve. To a peer with the `motion_path` capability, moves merged while the link is+ behind carry `samples`, at most 64 `[dx, dy]` pairs summing to `dx` and `dy`; past 64 the path+ collapses to the latest position, one pair. A receiver replays at most four samples near a wall+ or along a bent drag and moves a longer path in at most two steps, the second from the first wall+ it reaches.- **`scroll`**: `dy` and `dx` are numbers from -65535 to 65535; `mode` is `"pixel"` for atrackpad's continuous delta in points, or `"line"` for whole wheel notches. Both are in the Mac'sconvention, as version 5 sends them: `dy` and `dx` are Core Graphics' scroll axes 1 and 2 as adiff --git a/core/link.py b/core/link.pyindex b8f016d..34f42be 100644--- a/core/link.py+++ b/core/link.py@@ -228,6 +228,12 @@ class OutboundLink:def live(self):return self._live+ def pending(self):+ """Input queued to be written plus input written and not yet acknowledged: how far behind+ the peer this link is."""+ with self._lock:+ return len(self._outbox) + len(self._sent_at)+# Reading the entrydef entry(self):diff --git a/core/protocol.py b/core/protocol.pyindex ec0920f..91050d4 100644--- a/core/protocol.py+++ b/core/protocol.py@@ -1203,7 +1203,10 @@ def coalesce_mousemove(previous: dict, current: dict, *, preserve_path=True):if preserve_path:samples = before.get("samples", [[before["dx"], before["dy"]]]) + after.get("samples", [[after["dx"], after["dy"]]])if len(samples) > MOTION_SAMPLES_MAX:- return None+ # A path this long means the link is behind. Refusing the merge queued a fresh record+ # behind every 64 samples, which is how a 1000 Hz hand fell seconds behind (GH15c), so+ # the latest position wins as one step.+ samples = [[dx, dy]]merged["data"]["samples"] = samplesreturn mergeddiff --git a/core/receiver.py b/core/receiver.pyindex 1b71093..21e3982 100644--- a/core/receiver.py+++ b/core/receiver.py@@ -126,6 +126,10 @@ IDLE_TAKEOVER_SECONDS = 3.0OUTBOX_LIMIT = 512INBOX_LIMIT = 512INBOX_BYTES = protocol.MAX_FRAME_BYTES+# The longest queued path still replayed one native move per sample near a wall or along a bent+# drag. A longer one means the link is behind, and replaying it costs more than the time it covers+# (GH15c: 1.5.10 fell seconds behind a 1000 Hz hand), so it goes as one move to its latest position.+MOTION_REPLAY_SAMPLES = 4ADMITTED = "admitted"WRONG_ID = "wrong_id"@@ -1150,6 +1154,9 @@ class LinkResponder:safe = safe and isinstance(screen, crossing.Rect) and inside(screen)if safe and model._at_edge(monitors, pointer, display_map):safe = False+ if not safe and len(read["samples"]) > MOTION_REPLAY_SAMPLES:+ self._apply_collapsed_locked(link, read, after, geometry)+ return# Every sample still feeds pressure and decay. Native movement is combined only when# no moving axis can reach a wall and no drag needs the intermediate path.# A stationary axis may already be against an unused wall.@@ -1175,6 +1182,44 @@ class LinkResponder:else:self._inject_timed_locked(link, read)+ def _apply_collapsed_locked(self, link, read, after, geometry):+ """A path too long to replay, as at most two moves: up to the sample that first reaches a+ wall, then the rest, so an armed edge still feels the push past it. The zones see each move+ once with the pointer where it is, the platform clips it, and each sample is still scaled in+ turn so the fractional carry matches the path's."""+ monitors, pointer, _display_map = geometry+ samples = read["samples"]+ scale = self.input_scale.pointer if self.input_scale is not None else 1.0+ x, y = pointer+ split = len(samples)+ for index, (dx, dy) in enumerate(samples):+ x, y = x + dx * scale, y + dy * scale+ if not any(screen.x < x < screen.right and screen.y < y < screen.bottom for screen in monitors):+ split = index + 1+ break+ for part in (samples[:split], samples[split:]):+ if not part:+ continue+ move = {key: value for key, value in read.items() if key != "samples"}+ move.update(dx=sum(dx for dx, _dy in part), dy=sum(dy for _dx, dy in part))+ was_live = self._zones_live+ zones_at = time.monotonic()+ consumed = self._zones_locked(link, move, after)+ link.timing.add("zones", time.monotonic() - zones_at)+ if self._owner is not link or (was_live and not self._zones_live):+ return+ if consumed:+ continue+ if self.input_scale is None:+ self._inject_timed_locked(link, move)+ continue+ scaled_dx = scaled_dy = 0+ for dx, dy in part:+ part_dx, part_dy = self.input_scale.move(dx, dy)+ scaled_dx += part_dx+ scaled_dy += part_dy+ self._inject_timed_locked(link, dict(move, dx=scaled_dx, dy=scaled_dy), scaled=True)+def _apply_input_locked(self, link, read, after):zones_at = time.monotonic()consumed = read["type"] == protocol.MSG_MOUSEMOVE and self._zones_locked(link, read, after)diff --git a/core/tests/test_link.py b/core/tests/test_link.pyindex 415288e..96c6cda 100644--- a/core/tests/test_link.py+++ b/core/tests/test_link.py@@ -1398,6 +1398,16 @@ class GeminiFindingsTests(unittest.TestCase):link._check_sent_record()+ def test_pending_counts_input_waiting_to_be_written_and_input_not_yet_acknowledged(self):+ side = Side(None)+ link = side.link()+ self.assertEqual(link.pending(), 0)+ link._outbox.append(protocol.mousemove_msg(1, 1))+ link._outbox.append(protocol.mousemove_msg(2, 2))+ link._sent_at.append((1, 0.0))+ self.assertEqual(link.pending(), 3)++class RoundTripLogTests(unittest.TestCase):"""Section 9: every 60 seconds while input is on the link, the count, median, 95th percentile,largest and mean held_us of the round trips measured since the last line."""diff --git a/core/tests/test_motion_paths.py b/core/tests/test_motion_paths.pyindex f05a78b..2223716 100644--- a/core/tests/test_motion_paths.py+++ b/core/tests/test_motion_paths.py@@ -19,12 +19,18 @@ class MotionPathTests(unittest.TestCase):message["data"]["samples"] = samplesself.assertIsNone(protocol.read_input(message))- def test_path_limit_prevents_an_unbounded_coalesced_record(self):+ def test_a_path_past_its_limit_collapses_to_the_latest_position(self):+ # GH15c: refusing the 65th sample is what let a 1000 Hz hand queue seconds of motion.merged = protocol.mousemove_msg(1, 1, 1)for seq in range(2, 65):merged = protocol.coalesce_mousemove(merged, protocol.mousemove_msg(1, 1, seq))self.assertIsNotNone(merged)- self.assertIsNone(protocol.coalesce_mousemove(merged, protocol.mousemove_msg(1, 1, 65)))+ merged = protocol.coalesce_mousemove(merged, protocol.mousemove_msg(-3, 2, 65))+ self.assertEqual((merged["data"]["dx"], merged["data"]["dy"], merged["data"]["seq"]), (61, 66, 65))+ self.assertEqual(merged["data"]["samples"], [[61, 66]])+ self.assertEqual(protocol.read_input(merged)["samples"], [[61, 66]])+ merged = protocol.coalesce_mousemove(merged, protocol.mousemove_msg(0, -1, 66))+ self.assertEqual(merged["data"]["samples"], [[61, 66], [0, -1]])def test_legacy_coalescing_does_not_erase_diagonal_path(self):self.assertIsNone(protocol.coalesce_mousemove(protocol.mousemove_msg(119, 1, 1),diff --git a/core/tests/test_receiver_backlog.py b/core/tests/test_receiver_backlog.pyindex c182d39..de6e12b 100644--- a/core/tests/test_receiver_backlog.py+++ b/core/tests/test_receiver_backlog.py@@ -29,7 +29,12 @@ class ReceiverBacklogTests(unittest.TestCase):def test_1000_hz_drag_stays_current_and_releases_the_button(self):self.load(drag=True)- def load(self, drag):+ def test_1000_hz_bending_hand_drag_stays_current(self):+ # GH15c: a real hand bends on almost every 1000 Hz sample; 1.5.10 replayed each bend natively+ # and fell seconds behind.+ self.load(drag=True, path=((2, 0), (1, 2), (-2, 1), (-1, -2), (2, -1)))++ def load(self, drag, path=((1, 0),)):machine, link = self.owner()if drag:pressed = link.input({"type": "mousedown", "data": {"button": "left"}})@@ -58,7 +63,7 @@ class ReceiverBacklogTests(unittest.TestCase):deadline = started + index / 1000time.sleep(max(0, deadline - time.monotonic()))sent[index + first_seq] = time.monotonic()- link.move(1, 0)+ link.move(*path[index % len(path)])highest = completed[-1][0] if completed else first_seq - 1peak_pending = max(peak_pending, index + first_seq - highest)sending_seconds = time.monotonic() - started@@ -75,14 +80,15 @@ class ReceiverBacklogTests(unittest.TestCase):"final_latency_ms": round((completed[-1][1] - sent[last_seq]) * 1000, 2),}print("receiver backlog load " + json.dumps(metrics, sort_keys=True), flush=True)- self.assertEqual(sum(call[1] for call in moves), 400)- self.assertEqual(sum(call[2] for call in moves), 0)+ self.assertEqual(sum(call[1] for call in moves), sum(path[index % len(path)][0] for index in range(400)))+ self.assertEqual(sum(call[2] for call in moves), sum(path[index % len(path)][1] for index in range(400)))if drag:released = link.input({"type": "mouseup", "data": {"button": "left"}})self.assertIsNotNone(link.acked(released))self.assertEqual(machine.injected()[0], ("button", "left", True))self.assertEqual(machine.injected()[-1], ("button", "left", False))self.assertLess(metrics["final_latency_ms"], 200, metrics)+ self.assertLess(metrics["latency_p95_ms"], 100, metrics)self.assertLess(peak_pending, 100, metrics)self.assertLess(len(moves), 200, metrics)diff --git a/core/tests/test_rel1510b_geometry.py b/core/tests/test_rel1510b_geometry.pyindex 91711f6..308b11e 100644--- a/core/tests/test_rel1510b_geometry.py+++ b/core/tests/test_rel1510b_geometry.py@@ -91,6 +91,39 @@ class ReceiverQueuedGeometryTests(unittest.TestCase):self.assertEqual(self.deliver(moves, pointer, None, True, sender=True),self.deliver(moves, pointer, None, False))+ def test_a_long_bent_drag_collapses_to_one_native_move(self):+ # GH15c: replaying every bend of a 1000 Hz drag let 1.5.10 fall seconds behind.+ moves = [(2, 0), (0, 2), (-2, 0), (0, -1)] * 10+ for speed in (None, 1.4):+ with self.subTest(speed=speed):+ direct_scale = None if speed is None else receiver.InputScale(speed)+ batch_scale = None if speed is None else receiver.InputScale(speed)+ direct = self.deliver(moves, (500, 500), None, False,+ input_scale=direct_scale, held_button="left")+ calls = []+ batch = self.deliver(moves, (500, 500), None, True, sender=True, calls=calls,+ input_scale=batch_scale, held_button="left")+ self.assertEqual(batch, direct)+ self.assertEqual(len(calls), 1)+ if speed is not None:+ self.assertEqual(batch_scale._carry, direct_scale._carry)++ def test_a_long_path_near_a_wall_collapses_to_one_clipped_native_move(self):+ moves = [(3, 1), (-1, 2), (4, -1), (-2, -2), (3, 0)] * 8+ calls = []+ cursor, switches = self.deliver(moves, (1900, 500), None, True, sender=True, calls=calls)+ self.assertEqual((cursor, switches), ((1919, 500), 0))+ self.assertEqual(calls, [("move", 20, 2), ("move", 36, -2)])++ def test_a_long_path_at_an_armed_edge_still_crosses(self):+ moves = [(1, 1), (1, -1)] * 20+ calls = []+ result = self.deliver(moves, (1915, 500),+ return_edge.ReturnEdge("right", resistance_px=10, clock=lambda: 0),+ True, sender=True, calls=calls)+ self.assertEqual(result, ((1919, 500), 1))+ self.assertEqual(calls, [("move", 4, 0)])+def test_unarmed_interior_and_parallel_wall_paths_still_batch_native_calls(self):for pointer in ((500, 500), (1919, 500)):with self.subTest(pointer=pointer):diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xmlindex 6939230..95f4adc 100644--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml@@ -43,6 +43,9 @@</screenshots><content_rating type="oars-1.1"/><releases>+ <release version="1.5.11" date="2026-10-22">+ <description><p>Fixes the pointer falling seconds behind when a 1000 Hz mouse bends, reverses or drags: once the link is behind, the pointer now goes straight to its latest position instead of replaying every step. Clicks, keys, scrolling and the clipboard still arrive in order around the motion.</p><p>Moves are sent at once while the other machine keeps up, and paced only once it falls behind. A settings file this version cannot read, such as one written by a newer Beamer, no longer crashes the window and is never overwritten.</p></description>+ </release><release version="1.5.10" date="2026-10-21"><description><p>Avoids repeatedly reading clipboard contents that cannot be shared and removes an unnecessary wait when returning with an empty clipboard. Failed clipboard reads can still retry.</p><p>Limits repeated Identify screens requests and leaves machines without an active desktop link out. Disabling update checks also clears the Mac menu's stale update action. Flatpak update actions consistently point to store update guidance. Windows input recovery clears stale modifiers after returning from the secure desktop.</p><p>The separate Windows portable package keeps its settings beside the executable and protects them with a passphrase. It needs no installation or administrator rights and does not change startup tasks or firewall rules. It cannot control elevated applications or the secure desktop. Discovery keeps installed and portable copies separate without duplicating replies sent through temporary network sockets.</p></description></release>diff --git a/mac_app/settings_store.py b/mac_app/settings_store.pyindex e429584..1b9563e 100644--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@ -731,6 +731,15 @@ class SettingsStore:raise SettingsError("a zone names a peer that is not in the list")def _write(self, settings):+ # Every writer ends here, so a file this build cannot read (a newer Beamer's, or damaged) is+ # never replaced by one written from defaults; moving it aside is the user's call.+ if self.path.exists():+ try:+ existing = json.loads(self.path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ existing = None+ if not isinstance(existing, dict) or existing.get("schema") != SCHEMA:+ raise SettingsError(f"{self.path.name} is not a schema {SCHEMA} settings file, and is left as it is")_backup_before_profile_upgrade(self.path)self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)try:diff --git a/mac_app/tests/test_unreadable_settings.py b/mac_app/tests/test_unreadable_settings.pynew file mode 100644index 0000000..edcb685--- /dev/null+++ b/mac_app/tests/test_unreadable_settings.py@@ -0,0 +1,51 @@+"""A settings.json this build cannot read is never replaced; the file here is synthetic, in a+temporary folder, with a newer schema number and made-up ids."""++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import settings_store+from settings_store import SettingsError, SettingsStore++NEWER = {+ "schema": settings_store.SCHEMA + 1,+ "machine_id": "ab" * 16,+ "name": "Preview Mac",+ "peers": [{"id": "cd" * 16, "name": "Somewhere", "token": "not-a-real-token"}],+ "zones": [],+ "preview_only_section": {"anything": [1, 2, 3]},+}+++class UnreadableSettingsTests(unittest.TestCase):+ def setUp(self):+ tempdir = tempfile.TemporaryDirectory()+ self.addCleanup(tempdir.cleanup)+ self.path = Path(tempdir.name) / "settings.json"+ self.path.write_text(json.dumps(NEWER, indent=2) + "\n", encoding="utf-8")+ self.before = self.path.read_bytes()+ self.store = SettingsStore(self.path)++ def assert_untouched(self):+ self.assertEqual(self.path.read_bytes(), self.before)+ self.assertEqual(sorted(p.name for p in self.path.parent.iterdir()), ["settings.json"])++ def test_load_reports_it_and_leaves_the_file(self):+ with self.assertRaises(SettingsError):+ self.store.load_settings()+ self.assert_untouched()++ def test_a_save_does_not_replace_it(self):+ with self.assertRaises(SettingsError):+ self.store.save_settings(self.store._fresh())+ self.assert_untouched()+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/app_config.py b/win_app/app_config.pyindex cf810a8..94891ba 100644--- a/win_app/app_config.py+++ b/win_app/app_config.py@@ -715,6 +715,19 @@ def learn_peer_id(settings: dict, index: int, peer_id: str) -> None:peers[index]["id"] = peer_id+def _refuse_unreadable_target(path: Path) -> None:+ """Every writer ends here, so a settings file this build cannot read (a newer Beamer's, or damaged)+ is never replaced by one written from defaults; the file is the user's to move aside."""+ try:+ existing = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return+ except (OSError, ValueError):+ existing = None+ if not isinstance(existing, dict) or existing.get("schema") != SCHEMA:+ raise SettingsFileError(f"{path} is not a version {SCHEMA} Beamer settings file, and is left as it is")++def _write_json(path: Path, payload: dict) -> None:"""A new file beside the old, then a rename over it."""if portable_runtime.enabled():@@ -723,6 +736,7 @@ def _write_json(path: Path, payload: dict) -> None:except PortableStoreError as exc:raise SettingsFileError("Portable settings could not be saved") from excreturn+ _refuse_unreadable_target(path)_backup_before_profile_upgrade(path)path.parent.mkdir(parents=True, exist_ok=True)temporary_path = Nonediff --git a/win_app/capture_portal.py b/win_app/capture_portal.pyindex bc78d90..cba1c26 100644--- a/win_app/capture_portal.py+++ b/win_app/capture_portal.py@@ -5,8 +5,9 @@ Wayland lets no app see input meant for another, so capture is the desktop's. Bebarriers on the outside edges of this machine's zones (the edge, its thirds, or a corner's twowalls) and the compositor, when the pointer pushes through one, captures every keyboard andpointer and sends their events to Beamer over libei until Beamer lets go (Release). Nothing else-can start a capture, so input leaves this machine only across an edge: the shortcut and the tray-bring it home but cannot send it away, and Beamer sees no key at all while input is here.+can start a capture, so input leaves this machine only across an edge: the shortcut (heard through+GlobalShortcuts) pushes the pointer through a barrier with relative RemoteDesktop motion, and+Beamer sees no other key at all while input is here.A push into a barrier is not yet a crossing. The barrier holds the pointer, as Windows holds it atthe edge of the desktop, and the movement that follows feeds the sender's own zone models, so the@@ -479,6 +480,7 @@ class Hooks:selected = barriers(models, self._zones, display_map=display_map,warn_unmatched=self._warn_unmatched_display)if not selected:+ LOGGER.info("Shortcut push: no placed barrier leads to that machine")return Falsewall, (x1, y1, x2, y2) = selected[0]if wall == "right":@@ -503,6 +505,7 @@ class Hooks:nx, ny = _NORMAL[wall]moves = [(nx * PUSH_STEP_PX, ny * PUSH_STEP_PX) for _ in range(PUSH_STEPS)]+ LOGGER.info("Shortcut push through the %s barrier from %s", wall, start)inject_portal.push(*start, moves, wanted)return True@@ -852,6 +855,7 @@ class Hooks:else:pending = Noneif pending is not None:+ LOGGER.info("Shortcut push: the desktop did not capture at the %s barrier in time", pending[1])try:pending[3]()except Exception:diff --git a/win_app/inject_portal.py b/win_app/inject_portal.pyindex bab78cc..d3703d9 100644--- a/win_app/inject_portal.py+++ b/win_app/inject_portal.py@@ -581,9 +581,9 @@ class Remote:if code in LOCK_KEYS and not down:self._locks_due = time.monotonic() + LOCK_SECONDS- def move_by(self, dx: float, dy: float) -> None:+ def move_by(self, dx: float, dy: float, relative: bool = False) -> None:x, y = desktop_portal.cursor_position()- if self._with(CAP_POINTER_ABSOLUTE) is not None:+ if self._with(CAP_POINTER_ABSOLUTE) is not None and not (relative and self._with(CAP_POINTER)):self.place(x + dx, y + dy)returndevice = self._with(CAP_POINTER)@@ -808,8 +808,10 @@ def push(x: int, y: int, moves: List[Tuple[int, int]], wanted: Callable[[], boolif not wanted():returnsession.place(x, y)+ # Relative, never absolute: KWin 6.7.5 gives absolute motion a zero delta and its+ # InputCapture barriers fire only on a non-zero one (BarrierSpy::pointerMotion).for dx, dy in moves:- session.move_by(dx, dy)+ session.move_by(dx, dy, relative=True)remote().submit(go)diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex cc2c807..f69fd75 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -764,10 +764,14 @@ class WindowsApplication(QWidget):except ConfigError as exc:LOGGER.info("Configuration is not ready: %s", exc)self._status = ServerState.ERROR- self._status_detail = (- "Settings could not be read: see the log" if isinstance(exc, SettingsFileError)- else "Not paired yet: press Pair a machine on Overview"- )+ if isinstance(exc, SettingsFileError):+ # _config stays None: that is what every page reads as "no settings to show".+ self._status_detail = (+ "Settings could not be read. The file may be from a newer Beamer; it is left as it is. "+ "Install the newer Beamer, or move settings.json aside to start fresh."+ )+ else:+ self._status_detail = "Not paired yet: press Pair a machine on Overview"# Announces this PC from launch, configured or not: pairing is how a fresh install gets its# first peer, so it cannot wait for the receiver to be listening. Without a readable@@ -2729,6 +2733,8 @@ class WindowsApplication(QWidget):return dict(platform="pc", capable=self._layout_capable(), live=self._live, gone=self._gone, now=time.time())def _layout_capable(self) -> set:+ if self._config is None:+ return set()held = {entry.get("id") for entry in self._peer_entriesif "layout" in entry.get("caps", ()) or "caps" not in entry}known = self._design_peer_caps()diff --git a/win_app/sender.py b/win_app/sender.pyindex bc5f1d7..22e1628 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -44,6 +44,10 @@ LOGGER = logging.getLogger(__name__)SEND_QUEUE_SIZE = 4096MOTION_INTERVAL_SECONDS = 0.002+# Moves are paced only once this much input is queued or unacknowledged on the link: the 2 ms wait+# exists to stop a 1000 Hz stream flooding a peer that is behind, and costs a move about a+# millisecond when the peer is not, so a link that is keeping up is sent every move at once.+PACE_BACKLOG = 4MONITORS_MAX_AGE_SECONDS = 1.0TICK_SECONDS = 0.1ROUND_TRIP_MAX_AGE_SECONDS = 5.0@@ -1172,7 +1176,7 @@ class LinkSender:motion = isinstance(action, owner_module.Send) and action.message.get("type") == protocol.MSG_MOUSEMOVEif motion:delay = next_motion_at - time.monotonic()- if delay > 0:+ if delay > 0 and self.links.pending(action.peer) >= PACE_BACKLOG:# Python's Windows sleep uses a high-resolution waitable timer; an Event# wait can round this short interval to the system's 15.6 ms timer tick.time.sleep(delay)@@ -1886,6 +1890,10 @@ class LinkSet:if link is not None:link.drop(reason)+ def pending(self, peer) -> int:+ link = self._link(peer)+ return link.pending() if link is not None else 0+def round_trip_ms(self, peer) -> Optional[int]:"""The upper median of the last few trips, with the time the peer held each ACK taken off, orNone when nothing fresh has been acknowledged."""diff --git a/win_app/tests/links_rig.py b/win_app/tests/links_rig.pyindex 3600825..2b2d28f 100644--- a/win_app/tests/links_rig.py+++ b/win_app/tests/links_rig.py@@ -70,6 +70,7 @@ class FakeLinks:self.synced = []self.fail_input = Falseself.trip = None+ self.backlog = 0def start(self):pass@@ -114,6 +115,9 @@ class FakeLinks:def round_trip_ms(self, peer):return self.trip+ def pending(self, peer):+ return self.backlog+def follow(self, machines):passdiff --git a/win_app/tests/test_inject_portal.py b/win_app/tests/test_inject_portal.pyindex 45a47c1..b1c1888 100644--- a/win_app/tests/test_inject_portal.py+++ b/win_app/tests/test_inject_portal.py@@ -175,12 +175,16 @@ class RemoteTest(unittest.TestCase):self.assertEqual([item[2:] for item in self.ei.sends("absolute")], [(100.0, 100.0), (110.0, 95.0), (1919.0, 95.0)])self.assertEqual(desktop_portal.cursor_position(), (1919, 95))- def test_a_push_places_then_moves_on_the_session_thread(self):+ def test_a_push_places_then_moves_relatively_on_the_session_thread(self):+ # KWin 6.7.5 gives absolute motion a zero delta (pointer_input.cpp processMotionAbsolute)+ # and its barrier spy fires only on a non-zero one, so an absolute push never captures.self.up()inject_portal.push(200, 300, [(10, 0), (0, -5)], lambda: True)- wait_for(lambda: len(self.ei.sends("absolute")) == 3, what="the shortcut push")- self.assertEqual([item[2:] for item in self.ei.sends("absolute")],- [(200.0, 300.0), (210.0, 300.0), (210.0, 295.0)])+ wait_for(lambda: len(self.ei.sends("motion")) == 2, what="the shortcut push")+ self.assertEqual([item[1:] for item in self.ei.sends("absolute")], [("absolute", 200.0, 300.0)])+ self.assertEqual([item[1:] for item in self.ei.sends("motion")],+ [("pointer", 10, 0), ("pointer", 0, -5)])+ self.assertEqual(desktop_portal.cursor_position(), (210, 295))def test_a_queued_push_is_dropped_when_its_capture_deadline_passes(self):checked = threading.Event()diff --git a/win_app/tests/test_sender_motion_flow.py b/win_app/tests/test_sender_motion_flow.pyindex e5df633..022fa60 100644--- a/win_app/tests/test_sender_motion_flow.py+++ b/win_app/tests/test_sender_motion_flow.py@@ -28,8 +28,9 @@ class SenderMotionFlowTests(unittest.TestCase):self.assertEqual(sum(a.message["data"]["dy"] for a in list(waiting)[:-2]), 0)self.assertEqual(waiting[-2].message["type"], "keydown")- def test_worker_sends_first_immediately_and_flushes_trailing_motion_when_idle(self):- rig = self.rig()+ def run_worker(self, rig):+ """Runs the outbound worker over one move that queues a second inside its send and a third+ inside its sleep; returns what it sent and every sleep it took."""sent = []clock = [10.0]sleeps = []@@ -50,11 +51,42 @@ class SenderMotionFlowTests(unittest.TestCase):rig.sender._queue([owner.Send(B, protocol.mousemove_msg(1, 1))])with mock.patch.object(sender.time, "monotonic", side_effect=lambda: clock[0]), mock.patch.object(sender.time, "sleep", side_effect=sleep):rig.sender._outbound_worker()+ return sent, sleeps++ def test_backed_up_link_paces_motion_and_flushes_trailing_motion(self):+ rig = self.rig()+ rig.links.backlog = sender.PACE_BACKLOG+ sent, sleeps = self.run_worker(rig)self.assertEqual([(m["data"]["dx"], m["data"]["dy"]) for m in sent], [(1, 1), (6, 8)])self.assertEqual(len(sleeps), 1)self.assertAlmostEqual(sleeps[0], .002)self.assertEqual(rig.sender._outbound.unfinished_tasks, 0)+ def test_idle_link_sends_motion_at_once_without_pacing(self):+ rig = self.rig()+ rig.links.backlog = sender.PACE_BACKLOG - 1+ sent, sleeps = self.run_worker(rig)+ self.assertEqual(sleeps, [])+ self.assertEqual([(m["data"]["dx"], m["data"]["dy"]) for m in sent], [(1, 1), (2, 3)])+ self.assertEqual(rig.sender._outbound.unfinished_tasks, 0)++ def test_pacing_follows_the_backlog_of_the_peer_the_move_is_for(self):+ rig = self.rig()+ asked = []+ rig.links.pending = lambda peer: asked.append(peer) or 0+ self.run_worker(rig)+ self.assertEqual(set(asked), {B})++ def test_link_set_reports_a_peers_unsent_and_unacknowledged_input(self):+ class Linked:+ def pending(self):+ return 7++ links = sender.LinkSet(mock.Mock(_peers={}), is_local=lambda host: False)+ links._by_peer[B] = Linked()+ self.assertEqual(links.pending(B), 7)+ self.assertEqual(links.pending(b"\x01" * 16), 0)+def test_pending_high_polling_samples_are_bounded_relative_batches(self):rig = self.rig()rig.sender.set_redirecting(True)diff --git a/win_app/tests/test_unreadable_settings.py b/win_app/tests/test_unreadable_settings.pynew file mode 100644index 0000000..277e3a5--- /dev/null+++ b/win_app/tests/test_unreadable_settings.py@@ -0,0 +1,77 @@+"""A settings.json this build cannot read must not crash the window or be touched; run offscreen,+one module per process. The file here is synthetic: a newer schema number and made-up ids, no+real pairing token."""++import json+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++import test_crossing_page_parity as fixture+import app_config+import kvm_bridge_win as kvm+from kvm_bridge_win import ServerState+from PySide6.QtWidgets import QApplication+++NEWER = {+ "schema": app_config.SCHEMA + 1,+ "machine_id": "ab" * 16,+ "name": "Preview PC",+ "peers": [{"id": "cd" * 16, "name": "Somewhere", "token": "not-a-real-token"}],+ "zones": [],+ "preview_only_section": {"anything": [1, 2, 3]},+}+++class UnreadableSettingsTests(unittest.TestCase):+ def setUp(self):+ self.app = QApplication.instance() or QApplication([])+ patches = [patch.object(kvm.platform_parts, "WAYLAND", False)]+ for name, value in (("installed_exe", lambda: Path("Beamer.exe")),+ ("is_enabled", lambda: False),+ ("can_run_for_current_user", lambda: False)):+ patches.append(patch.object(kvm.autostart_win, name, value))+ for patcher in patches:+ patcher.start()+ self.addCleanup(patcher.stop)+ root = Path(__file__).resolve().parents[1] / ".test-tmp"+ root.mkdir(parents=True, exist_ok=True)+ tempdir = tempfile.TemporaryDirectory(dir=root)+ self.addCleanup(tempdir.cleanup)+ self.path = Path(tempdir.name) / "settings.json"+ self.path.write_text(json.dumps(NEWER, indent=2) + "\n", encoding="utf-8")+ self.before = self.path.read_bytes()+ self.window = kvm.WindowsApplication(self.path)+ self.window.full_screen_timer.stop()+ self.window.refresh_timer.stop()+ self.addCleanup(self.window.close)++ def test_window_opens_and_the_crossing_page_builds(self):+ fixture.settle(self.window)+ self.window._reflect_ways()+ self.assertEqual(self.window._layout_capable(), set())++ def test_the_message_says_what_happened_and_how_to_recover(self):+ self.assertEqual(self.window._status, ServerState.ERROR)+ detail = self.window._status_detail+ self.assertIn("newer", detail)+ self.assertIn("left as it is", detail)++ def test_the_file_is_untouched_by_launch_and_by_every_writer(self):+ fixture.settle(self.window)+ with self.assertRaises(app_config.SettingsFileError):+ app_config.write_settings(self.path, dict(NEWER))+ self.assertEqual(self.path.read_bytes(), self.before)+ self.assertEqual(sorted(p.name for p in self.path.parent.iterdir()), ["settings.json"])++ def test_the_setting_toggles_do_not_write_over_it(self):+ fixture.settle(self.window)+ self.window._set_show_in_tray(False)+ self.window._set_check_updates(False)+ self.assertEqual(self.path.read_bytes(), self.before)+++if __name__ == "__main__":+ unittest.main()