Skip to content

One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.

Beamer 1.5.9

Toby Kalkman032be6816e27
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index d2d1c05..cdfdb2a 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -46,4 +46,5 @@ body:
label: Logs
description: |
Attach Beamer.log from each machine, or paste the lines from around the time it went wrong. Open log folder in Beamer's menu shows where it is.
+ On Linux, the file is ~/.config/Beamer/Beamer.log; on Flatpak, it is ~/.var/app/uk.co.kalkman.beamer/config/Beamer/Beamer.log.
The log holds your machines' names and local network addresses; remove them if you would rather not share them.
diff --git a/README.md b/README.md
index 3dff16c..b80b2f9 100644
--- a/README.md
+++ b/README.md
@@ -380,12 +380,12 @@ password-authenticated key exchange, from the six-digit code. What that does and
<summary><strong>Update check</strong></summary>
Once a day, and at start, Beamer asks GitHub's public releases API for the latest release of this
-repository and compares its version with its own. A new minor or major version is always offered;
-a patch release (1.5.0 to 1.5.1) only when its release notes ask for it, so a run of small fixes
-does not nag. Drafts and pre-releases never count and nothing is downloaded. When a newer one is out, the menu says Beamer X is available and Overview offers a
-Download button that opens the release page. The request is an ordinary HTTPS request, so GitHub
-sees the address it came from, as it would for a browser. Switch it off with Check for updates on
-Overview.
+repository and compares its version with its own, on the Mac, Windows and Linux. Every newer stable
+release counts; drafts and pre-releases never do, and nothing is downloaded or installed. When a newer
+one is out, the menu says Beamer X is available and the window shows a notice: What's new opens the
+release page, and Dismiss hides that version for good. The Flatpak notice says how to update through
+your software store. The request is an ordinary HTTPS request, so GitHub sees the address it came
+from, as it would for a browser. Switch it off with Check for updates on Overview.
</details>
@@ -539,4 +539,6 @@ reply. Before a pull request, read [CONTRIBUTING.md](CONTRIBUTING.md). Report se
A bug report is far easier to act on with each machine's log attached. Open log folder in each
machine's menu opens it: `~/Library/Logs/Beamer/Beamer.log` on the Mac and
`%LOCALAPPDATA%\Beamer\Beamer.log` on Windows.
+On Linux, find it at `~/.config/Beamer/Beamer.log`; Flatpak stores it at
+`~/.var/app/uk.co.kalkman.beamer/config/Beamer/Beamer.log`.
They hold your machines' names and local network addresses, so look them over before posting.
diff --git a/VERSION b/VERSION
index 1cc9c18..2b26b8d 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.8
+1.5.9
diff --git a/WIRE.md b/WIRE.md
index 620f922..3164117 100644
--- a/WIRE.md
+++ b/WIRE.md
@@ -1322,6 +1322,22 @@ report can be read from the log.
## 10. Text and shared settings
+**`identify_screens`** briefly labels the recipient's physical displays with the numbers shown
+on the sender's Crossing map. Both ends advertise the optional `identify_screens` capability;
+older peers receive no request. Wire version 6 is unchanged.
+
+```json
+{"type":"identify_screens","data":{"displays":{"0":2,"1":1}}}
+```
+
+`displays` contains one to sixteen syntactically valid display keys with unique integer labels
+from 1 to 16. Structurally invalid requests are ignored. If the supplied key set differs from
+the recipient's current display keys, the recipient replaces the supplied labels with numbers
+for all its current displays. Labels use each machine's top-to-bottom, left-to-right map order.
+The receiver shows click-through, non-activating overlays for three seconds, without changing
+input ownership, saving settings or relaying the request. This is a control message, without
+an input sequence number or acknowledgement.
+
**`text`** is a string the receiver types as it stands, for a phone's keyboard, where naming each
key would lose accents and emoji. The receiver advertises `text` only if it can type any Unicode
text.
diff --git a/core/identify_screens.py b/core/identify_screens.py
new file mode 100644
index 0000000..95e8af3
--- /dev/null
+++ b/core/identify_screens.py
@@ -0,0 +1,13 @@
+"""Physical screen labels shared by the Crossing map and temporary overlays."""
+
+from core import ways
+
+OVERLAY_SECONDS = 3.0
+
+
+def display_numbers(tile):
+ """Number a machine's displays in the map's top-to-bottom, left-to-right order."""
+ if not tile or not tile.get("displays"):
+ return {"0": 1}
+ return {frame["display"]: index + 1
+ for index, frame in enumerate(ways._display_frames(tile))}
diff --git a/core/ignored.py b/core/ignored.py
index 7f9f8e9..4ea44ca 100644
--- a/core/ignored.py
+++ b/core/ignored.py
@@ -50,14 +50,23 @@ class Gate:
forgets remote presses when input comes home, while locally kept presses remain until their
physical releases arrive. It is called from other threads, hence the lock."""
- def __init__(self, entries=()):
+ def __init__(self, entries=(), *, mouse_only=False):
self.entries = frozenset(entries)
+ self.mouse_only = mouse_only
self._sent = set()
self._kept = set()
self._lock = threading.Lock()
- def configure(self, entries):
- self.entries = frozenset(entries)
+ def configure(self, entries, *, mouse_only=False):
+ with self._lock:
+ self.entries = frozenset(entries)
+ self.mouse_only = mouse_only
+
+ def keeps_tap(self, entry):
+ """Dead keys, composed text and toggles arrive as whole presses, without a later release."""
+ kept = self.keeps(entry, True)
+ self.keeps(entry, False)
+ return kept
def keeps(self, entry, down):
with self._lock:
@@ -69,7 +78,7 @@ class Gate:
if not down:
self._kept.discard(entry)
return True
- if entry in self.entries:
+ if entry in self.entries or (self.mouse_only and entry.startswith(("key:", "media:"))):
if down:
self._kept.add(entry)
return True
diff --git a/core/link.py b/core/link.py
index 7a41aa1..597962e 100644
--- a/core/link.py
+++ b/core/link.py
@@ -26,6 +26,7 @@ from core import protocol
from core import receiver
from core.i18n import tr
from core.response_time import ResponseTime
+from core.link_timing import LinkTiming
LOGGER = logging.getLogger("Beamer")
@@ -48,7 +49,8 @@ LOG_SECONDS = 60.0
FOLLOW_AFTER_SECONDS = 10.0
FOLLOW_EVERY_SECONDS = 30.0
SEND_CHUNK = 65536
-_CAP_FOR = {protocol.MSG_GESTURE: "gestures", protocol.MSG_TEXT: "text", protocol.MSG_SETTINGS: "settings"}
+_CAP_FOR = {protocol.MSG_GESTURE: "gestures", protocol.MSG_TEXT: "text", protocol.MSG_SETTINGS: "settings",
+ protocol.MSG_IDENTIFY_SCREENS: "identify_screens"}
class LinkEnded(Exception):
@@ -117,6 +119,8 @@ class OutboundLink:
self._pending = None
self._session = None
self._outbox = collections.deque()
+ self._queued_at = {}
+ self._timing = LinkTiming("outbound")
self._cond = threading.Condition(self._lock)
self._seq = 0
self.last_sent_seq = 0
@@ -505,6 +509,7 @@ class OutboundLink:
self._last_rx = self._last_tx = self._last_progress = self._logged_at = now
self._live = True
name = self._name(entry)
+ self._timing.connected(sock)
writer = threading.Thread(target=self._write, args=(sock, session), name="Beamer-link-writer", daemon=True)
writer.start()
message = (tr("Connected to {name} via the secure macOS 27 fallback").format(name=name) if self.via_tunnel
@@ -528,12 +533,14 @@ class OutboundLink:
reason, kind, self._drop_reason = self._drop_reason, "failed", None
self._close()
writer.join(timeout=1.0)
+ self._timing.flush(force=True, ping_ms=self.response_time_ms)
self.down_since = self._clock()
self._followed_at = None
self._report(False, reason, kind)
def _reset_link_state(self):
self._outbox.clear()
+ self._queued_at.clear()
self._queued_bytes = 0
self._ping_queued = False
self._writing = False
@@ -593,6 +600,7 @@ class OutboundLink:
raise LinkEnded(tr("{name} took too long to send one message").format(name=name), "stopped")
body = bytes(buffer[protocol.HEADER_SIZE:protocol.HEADER_SIZE + length])
del buffer[:protocol.HEADER_SIZE + length]
+ dispatch_at = time.monotonic()
plain = session.open_raw(body)
try:
if len(plain) > protocol.SMALL_MESSAGE_BYTES and not self._large_due(began or now):
@@ -600,6 +608,7 @@ class OutboundLink:
else:
self._deal(protocol.parse_message(plain), began or now)
finally:
+ self._timing.add("read_dispatch", time.monotonic() - dispatch_at)
if length - 20 > protocol.SMALL_MESSAGE_BYTES:
self._end_ack_pause(self._clock())
began = now if buffer else None
@@ -610,6 +619,7 @@ class OutboundLink:
if buffer and now - began > protocol.FRAME_COMPLETE_SECONDS:
raise LinkEnded(tr("{name} took too long to send one message").format(name=name), "stopped")
self._tick(self._clock())
+ self._timing.flush(ping_ms=self.response_time_ms)
def _large_due(self, began):
if self._large is None:
@@ -709,7 +719,7 @@ class OutboundLink:
ordered = sorted(sample for sample, _held in period)
count = len(ordered)
LOGGER.info(
- "round trip to %s: %d samples, median %.1f ms, 95th percentile %.1f ms, largest %.1f ms, mean held_us %.0f",
+ "round trip to %s: %d samples, median %.1f ms, 95th percentile %.1f ms, largest %.1f ms, mean held_us %.0f (input ACK, outbound connection)",
self.peer_name, count, ordered[count // 2] * 1000, ordered[math.ceil(count * 0.95) - 1] * 1000,
ordered[-1] * 1000, sum(held for _sample, held in period) / count)
@@ -787,6 +797,7 @@ class OutboundLink:
data["seq"] = self._seq
message = {"type": message["type"], "data": data}
self.last_sent_seq = self._seq
+ self._queued_at[self._seq] = time.monotonic()
self._outbox.append(message)
self._cond.notify()
return True
@@ -798,14 +809,20 @@ class OutboundLink:
while not self._outbox or self._stall.is_set():
if self._sock is not sock:
return
+ waited_at = time.monotonic()
self._cond.wait(0.05)
+ self._timing.add("writer_wait_lag", time.monotonic() - waited_at - 0.05)
if self._sock is not sock:
return
message = self._outbox.popleft()
+ queued_at = self._queued_at.pop((message.get("data") or {}).get("seq"), None)
self._queued_bytes = max(0, self._queued_bytes - _weight(message))
self._writing = True
self._last_progress = self._clock()
seq = message.get("data", {}).get("seq")
+ write_at = time.monotonic()
+ if queued_at is not None:
+ self._timing.add("input_queue", write_at - queued_at)
if seq is not None and message["type"] in protocol.INPUT_TYPES:
# Before the write: the peer's `ack` can reach the reader before this thread
# runs again, and it must find the seq already counted as sent.
@@ -831,6 +848,7 @@ class OutboundLink:
with self._cond:
self._ping_queued = False
self._last_tx = self._clock()
+ self._timing.add("write", time.monotonic() - write_at)
self._writing = False
except (OSError, protocol.ProtocolError, ValueError) as exc:
LOGGER.info("Sending to %s failed: %s", self.peer_name, exc)
diff --git a/core/link_timing.py b/core/link_timing.py
new file mode 100644
index 0000000..4da315e
--- /dev/null
+++ b/core/link_timing.py
@@ -0,0 +1,52 @@
+"""Bounded, local timings; never subtract clocks on different machines."""
+
+import logging
+import socket
+import threading
+import time
+
+
+LOGGER = logging.getLogger("Beamer")
+LOG_SECONDS = 30.0
+
+
+class LinkTiming:
+ def __init__(self, direction, clock=time.monotonic):
+ self.direction = direction
+ self.clock = clock
+ self.lock = threading.Lock()
+ self.stages = {}
+ self.logged_at = clock()
+ self.route = "unavailable"
+
+ def connected(self, sock):
+ try:
+ local, remote = sock.getsockname(), sock.getpeername()
+ self.route = f"{local[0]}:{local[1]}->{remote[0]}:{remote[1]}"
+ LOGGER.info("link route %s %s interface_address=%s nodelay=%d send_buffer=%d receive_buffer=%d",
+ self.direction, self.route, local[0],
+ bool(sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)),
+ sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
+ sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF))
+ except (AttributeError, OSError, TypeError, IndexError):
+ # Test sockets and a connection closed during setup may have no endpoints.
+ self.route = "unavailable"
+
+ def add(self, stage, elapsed):
+ elapsed = max(0.0, elapsed) * 1000
+ with self.lock:
+ count, total, largest = self.stages.get(stage, (0, 0.0, 0.0))
+ self.stages[stage] = count + 1, total + elapsed, max(largest, elapsed)
+
+ def flush(self, force=False, ping_ms=None):
+ now = self.clock()
+ with self.lock:
+ if not force and now - self.logged_at < LOG_SECONDS:
+ return
+ stages, self.stages = self.stages, {}
+ self.logged_at = now
+ if stages:
+ fields = " ".join(f"{name}_ms(count/mean/max)={count}/{total / count:.3f}/{largest:.3f}"
+ for name, (count, total, largest) in sorted(stages.items()))
+ LOGGER.info("link timing %s %s ping_rtt_ms=%s %s", self.direction, self.route,
+ ping_ms if ping_ms is not None else "unavailable", fields)
diff --git a/core/owner.py b/core/owner.py
index 9214a3b..4e0227b 100644
--- a/core/owner.py
+++ b/core/owner.py
@@ -150,6 +150,11 @@ class Owner:
def away(self):
return self.on is not None
+ @property
+ def pressed_keys(self):
+ """Key names held on the current peer, excluding presses retained locally."""
+ return frozenset(key for kind, key in self._pressed.get(self.on, {}) if kind == "key")
+
@property
def chain(self):
"""The active route, including the refusal's named onward machine when there is one."""
@@ -354,10 +359,20 @@ class Owner:
def clipboard_changed(self):
self._clipboard_at = set()
+ def clipboard_failed(self, peer):
+ """A queued read or post failed, so the next take must try this clipboard again."""
+ self._clipboard_at.discard(peer)
+
+ def clipboard_pending(self):
+ """A local copy completed after crossing; send it only to an accepted current owner."""
+ if self.on is None or self._wait is not None:
+ return []
+ return self._clipboard_to(self.on)
+
def clipboard_arrived(self, peer, began_at, message):
- let_go = self._let_go.pop(peer, None)
- if let_go is None or began_at - let_go > CLIPBOARD_AFTER:
+ if not self.expects_clipboard(peer, began_at):
return []
+ self._let_go.pop(peer)
self._clipboard_at = {peer}
actions = [SetClipboard(message)]
if self.on is not None:
@@ -370,7 +385,7 @@ class Owner:
by `clipboard_arrived`'s own rule, however long it then took to arrive. A link asks this,
without the app's lock, before it reads a frame too large for any other message."""
let_go = self._let_go.get(peer)
- return let_go is not None and began - let_go <= CLIPBOARD_AFTER
+ return let_go is not None and 0 <= began - let_go <= CLIPBOARD_AFTER
def _clipboard_to(self, peer):
if peer in self._clipboard_at:
@@ -448,7 +463,7 @@ class Owner:
self._wait = None
if peer is not None:
self._hold_back(peer, why)
- return self._stay() + [Unreachable(peer, why, other)] + self._replay_held()
+ return self._stay() + [Unreachable(peer, why, other)] + self.clipboard_pending() + self._replay_held()
def held_back(self, peer):
"""Whether `peer` refused, or did not take, a move a moment ago and is not asked again yet."""
diff --git a/core/protocol.py b/core/protocol.py
index cf9a3d6..ac31a06 100644
--- a/core/protocol.py
+++ b/core/protocol.py
@@ -109,6 +109,7 @@ MSG_GESTURE = "gesture"
MSG_SWITCH = "switch"
MSG_ARRANGEMENT = "arrangement"
MSG_SETTINGS = "settings"
+MSG_IDENTIFY_SCREENS = "identify_screens"
# System trackpad gestures. The Mac classifies one at the end of the movement and sends a
# single message; the name is the finger motion, not its meaning, so the receiver decides
@@ -378,6 +379,25 @@ def settings_msg(data: dict) -> dict:
return {"type": MSG_SETTINGS, "data": dict(data)}
+def identify_screens_msg(displays: dict) -> dict:
+ """One machine's map labels; optional on wire 6, sent only to capable peers."""
+ return {"type": MSG_IDENTIFY_SCREENS, "data": {"displays": dict(displays)}}
+
+
+def read_identify_screens(message):
+ parsed = read_message(message)
+ if parsed is None or parsed[0] != MSG_IDENTIFY_SCREENS:
+ return None
+ displays = parsed[1].get("displays")
+ if (not isinstance(displays, dict) or not 1 <= len(displays) <= 16
+ or any(not isinstance(key, str) or _DISPLAY_KEY.fullmatch(key) is None
+ or type(number) is not int or not 1 <= number <= 16
+ for key, number in displays.items())
+ or len(set(displays.values())) != len(displays)):
+ return None
+ return dict(displays)
+
+
def gesture_msg(name: str) -> dict:
"""One completed system gesture (a GESTURE_* name). Unknown message types are
ignored by the receiver, so this needs no protocol version bump."""
diff --git a/core/receiver.py b/core/receiver.py
index 2ddda48..b8596f1 100644
--- a/core/receiver.py
+++ b/core/receiver.py
@@ -20,6 +20,7 @@ from . import peerlist
from . import protocol
from .i18n import tr, trc
from .response_time import ResponseTime
+from .link_timing import LinkTiming
LOGGER = logging.getLogger(__name__)
@@ -36,6 +37,9 @@ LOCK_CHECK_SECONDS = 0.5
INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0
SLOW_INJECTION_SECONDS = 0.25
SLOW_INJECTION_LOG_INTERVAL_SECONDS = 1.0
+CLIPBOARD_RETRY_ATTEMPTS = 20
+CLIPBOARD_RETRY_SECONDS = 0.05
+CLIPBOARD_RETRY_WINDOW_SECONDS = 1.0
# Windows hands the port back only when whatever holds it lets go — WinNAT's
# dynamic reservations move on every reboot and can land on ours — so a bind
# that fails is waited out rather than ending the listener.
@@ -120,6 +124,8 @@ IDLE_TAKEOVER_SECONDS = 3.0
# Frames waiting to go to one peer. A peer that stops reading is closed at this, rather than let a
# queue grow without end; it is well past anything a working link queues between two writes.
OUTBOX_LIMIT = 512
+INBOX_LIMIT = 512
+INBOX_BYTES = protocol.MAX_FRAME_BYTES
ADMITTED = "admitted"
WRONG_ID = "wrong_id"
@@ -356,13 +362,14 @@ class PeerBook:
class _Link:
- """One authenticated link an initiator opened to this machine. Its reader thread deals with
- what arrives; its writer thread sends everything that goes out, in order (the `outbox`) and
+ """One authenticated link an initiator opened to this machine. Read-ahead keeps motion current
+ while its serving thread injects; its writer sends everything that goes out (the `outbox`) and
the `ack`s when they are due, so nothing that holds the responder's lock ever waits on a
socket."""
def __init__(self, sock, session, peer_id, key_id, host, name, caps, own_id, own_caps, allow_drive, platform="") -> None:
self.sock = sock
+ self.timing = LinkTiming("inbound")
self.peer_platform = platform # the hello's: the Mac scales a PC's wheel lines by it
self.session = session
self.peer_id = peer_id
@@ -381,6 +388,9 @@ class _Link:
self.closed = threading.Event()
self.cond = threading.Condition()
self.outbox = collections.deque()
+ self.inbox = collections.deque()
+ self.inbox_bytes = 0
+ self.read_done = False
self.dealt = 0 # the highest seq dealt with
self.dealt_at = 0.0
self.pending_since = None # when the first input not yet acknowledged was dealt with
@@ -405,14 +415,52 @@ class _Link:
with self.cond:
if self.closed.is_set():
return False
+ if message.get("type") == protocol.MSG_IDENTIFY_SCREENS and "identify_screens" not in self.caps:
+ return True
if len(self.outbox) >= OUTBOX_LIMIT:
LOGGER.warning("%s stopped reading; closing its link", self.name)
self._close_locked()
return False
self.outbox.append(message)
- self.cond.notify()
+ self.cond.notify_all()
return True
+ def receive(self, message, size: int) -> bool:
+ move = (protocol.read_input(message)
+ if isinstance(message, dict) and message.get("type") == protocol.MSG_MOUSEMOVE else None)
+ with self.cond:
+ while not self.closed.is_set():
+ if move is not None and not (move["dx"] and move["dy"]) and self.inbox:
+ previous = protocol.read_input(self.inbox[-1][0])
+ if (previous is not None and previous["type"] == protocol.MSG_MOUSEMOVE
+ and move["seq"] > previous["seq"]
+ and (previous["dx"] > 0) == (move["dx"] > 0)
+ and (previous["dx"] < 0) == (move["dx"] < 0)
+ and (previous["dy"] > 0) == (move["dy"] > 0)
+ and (previous["dy"] < 0) == (move["dy"] < 0)):
+ dx, dy = previous["dx"] + move["dx"], previous["dy"] + move["dy"]
+ if abs(dx) <= protocol.MOVE_MAX and abs(dy) <= protocol.MOVE_MAX:
+ # Wire motion is relative: keeping just the last delta loses travel.
+ # Diagonal samples must retain their tangent positions and individual
+ # corner pressure. Reversals and axis changes stay separate too.
+ self.inbox[-1][0] = protocol.mousemove_msg(dx, dy, move["seq"])
+ return True
+ if len(self.inbox) < INBOX_LIMIT and self.inbox_bytes + size <= INBOX_BYTES:
+ break
+ self.cond.wait()
+ if self.closed.is_set():
+ return False
+ item = [message, size, time.monotonic(), False]
+ self.inbox.append(item)
+ self.inbox_bytes += size
+ self.cond.notify_all()
+ if move is None:
+ # Focus changes ownership. Finish every control record before reading beyond it,
+ # including the ownership check that precedes parsing a large clipboard frame.
+ while not item[3] and not self.closed.is_set():
+ self.cond.wait()
+ return not self.closed.is_set()
+
def dealt_with(self, seq: int) -> None:
with self.cond:
if seq <= self.dealt:
@@ -421,7 +469,7 @@ class _Link:
self.dealt, self.dealt_at = seq, now
if self.pending_since is None:
self.pending_since = now
- self.cond.notify()
+ self.cond.notify_all()
def close(self) -> None:
with self.cond:
@@ -465,7 +513,8 @@ class LinkResponder:
`owner_callback(peer or None)` when ownership begins or ends, always in the order it did; `arrival_callback(edge, x, y)`
and `pressure_callback(edge, pressure, crossed, part)` for the crossing effects;
`arrangement_callback(peer, {edge, set_at, by})`; `settings_callback(peer, data)`, only from a
- peer whose `caps` list `settings`; `paired_callback(peer, ids)`; `link_callback(peer, up)`; and
+ peer whose `caps` list `settings`; `identify_callback(peer, labels)` when both ends support
+ screen identification; `paired_callback(peer, ids)`; `link_callback(peer, up)`; and
`announce(peer)`, the messages to send once a link is up (section 3, announcements).
`status_callback(state, detail)` takes ServerState.
@@ -492,6 +541,7 @@ class LinkResponder:
pressure_callback=None,
arrangement_callback=None,
settings_callback=None,
+ identify_callback=None,
paired_callback=None,
link_callback=None,
announce=None,
@@ -510,6 +560,7 @@ class LinkResponder:
self._callbacks = {
"owner": owner_callback, "arrival": arrival_callback, "pressure": pressure_callback,
"arrangement": arrangement_callback, "settings": settings_callback, "paired": paired_callback,
+ "identify": identify_callback,
"link": link_callback,
}
self._announce = announce or (lambda peer: [])
@@ -849,6 +900,7 @@ class LinkResponder:
link.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError:
pass
+ link.timing.connected(link.sock)
with self._lock:
earlier = self._links.get(link.peer_id)
self._links[link.peer_id] = link
@@ -858,6 +910,7 @@ class LinkResponder:
if earlier is not None:
earlier.close()
writer = threading.Thread(target=self._writer, args=(link,), name="Beamer-v6-writer", daemon=True)
+ reader = threading.Thread(target=self._read_ahead, args=(link,), name="Beamer-v6-reader", daemon=True)
try:
self._run(after)
writer.start()
@@ -871,37 +924,67 @@ class LinkResponder:
link.post(message)
except Exception:
LOGGER.exception("Announcements for %s failed", link.name)
+ reader.start()
while not link.closed.is_set():
+ with link.cond:
+ while not link.inbox and not link.read_done and not link.closed.is_set():
+ link.cond.wait()
+ if link.closed.is_set() or not link.inbox:
+ break
+ item = link.inbox.popleft()
+ message, size, queued_at, _done = item
+ link.inbox_bytes -= size
+ link.cond.notify_all()
+ dispatch_at = time.monotonic()
+ link.timing.add("receive_queue", dispatch_at - queued_at)
try:
- plain = link.session.open_raw(protocol.recv_frame(link.sock))
- if len(plain) > protocol.SMALL_MESSAGE_BYTES and self._owner is not link:
- # Only the owner's clipboard is this large; opening it was enough to keep
- # the counter in step, and parsing it is the peer's to make this machine pay for.
- LOGGER.info("Dropped a %d byte frame from %s, which does not own this machine", len(plain), link.name)
- continue
- message = protocol.parse_message(plain)
- except socket.timeout:
- LOGGER.warning("%s went quiet, or took too long over one message; its link is over", link.name)
- break
- except (protocol.ConnectionClosed, protocol.ProtocolError, OSError) as exc:
- if not link.closed.is_set():
- LOGGER.info("The link from %s ended: %s", link.name, exc)
- break
- self._dispatch(link, message)
+ self._dispatch(link, message)
+ finally:
+ with link.cond:
+ item[3] = True
+ link.cond.notify_all()
+ link.timing.add("dispatch", time.monotonic() - dispatch_at)
+ link.timing.flush(ping_ms=link.response_time_ms)
finally:
+ link.close()
with self._lock:
current = self._links.get(link.peer_id) is link
if current:
del self._links[link.peer_id]
after = self._end_locked(link)
- link.close()
self._run(after)
+ if reader.ident is not None:
+ reader.join(timeout=1.0)
if writer.ident is not None:
writer.join(timeout=1.0)
+ link.timing.flush(force=True, ping_ms=link.response_time_ms)
if current:
self._callback("link", link.peer_id, False)
self._report()
+ def _read_ahead(self, link: _Link) -> None:
+ try:
+ while not link.closed.is_set():
+ frame = protocol.recv_frame(link.sock)
+ decode_at = time.monotonic()
+ plain = link.session.open_raw(frame)
+ if len(plain) > protocol.SMALL_MESSAGE_BYTES and self._owner is not link:
+ LOGGER.info("Dropped a %d byte frame from %s, which does not own this machine", len(plain), link.name)
+ continue
+ message = protocol.parse_message(plain)
+ link.timing.add("decode", time.monotonic() - decode_at)
+ if not link.receive(message, len(plain)):
+ return
+ except socket.timeout:
+ LOGGER.warning("%s went quiet, or took too long over one message; its link is over", link.name)
+ except (protocol.ConnectionClosed, protocol.ProtocolError, OSError) as exc:
+ if not link.closed.is_set():
+ LOGGER.info("The link from %s ended: %s", link.name, exc)
+ finally:
+ with link.cond:
+ link.read_done = True
+ link.cond.notify_all()
+
def _writer(self, link: _Link) -> None:
"""Everything this link sends, in order, and its `ack`s when they are due (section 9)."""
while True:
@@ -922,6 +1005,7 @@ class LinkResponder:
break
due = ack_due(link.last_ack_at, link.pending_since)
if now >= due:
+ link.timing.add("ack_due_lag", now - due)
seq = link.dealt
held_us = int((now - link.dealt_at) * 1_000_000) if seq > link.acked else 0
link.acked, link.last_ack_at, link.pending_since = seq, now, None
@@ -934,7 +1018,9 @@ class LinkResponder:
if link.response_time_enabled:
due = min(due, link.next_response_probe)
link.cond.wait(due - now)
+ link.timing.add("writer_wait_lag", time.monotonic() - due)
try:
+ write_at = time.monotonic()
# Only this thread sends once the link is up, so sealing and sending need not be
# one step under the session's lock to keep the counters in order.
frame = memoryview(link.session.seal(message))
@@ -943,6 +1029,7 @@ class LinkResponder:
link.response_time.sent(message["data"]["probe"])
while sent < len(frame):
sent += link.sock.send(frame[sent:sent + SEND_CHUNK])
+ link.timing.add("write", time.monotonic() - write_at)
except (OSError, protocol.ProtocolError, ValueError) as exc:
LOGGER.info("Sending to %s failed: %s", link.name, exc)
link.close()
@@ -967,6 +1054,10 @@ class LinkResponder:
parsed = protocol.read_message(message)
if parsed is not None and "settings" in link.caps:
self._callback("settings", link.peer_id, parsed[1])
+ elif kind == protocol.MSG_IDENTIFY_SCREENS:
+ labels = protocol.read_identify_screens(message)
+ if labels is not None and "identify_screens" in link.caps and "identify_screens" in link.own_caps:
+ self._callback("identify", link.peer_id, labels)
elif kind == protocol.MSG_PING:
self._on_ping(link, message)
elif kind == protocol.MSG_PAIRED:
@@ -997,8 +1088,10 @@ class LinkResponder:
if read["type"] == protocol.MSG_MOUSEMOVE:
self._record_incoming_move(link, read)
after = []
+ lock_at = time.monotonic()
try:
with self._lock:
+ link.timing.add("input_lock", time.monotonic() - lock_at)
takes = self._owner is link and self._takes(link, read)
if takes:
self._owner_input_at = time.monotonic()
@@ -1009,14 +1102,20 @@ class LinkResponder:
# something injected before it still goes, or that key stays down after.
if self._releases_held(link, read):
self._inject_timed_locked(link, read)
- elif not (read["type"] == protocol.MSG_MOUSEMOVE and self._zones_locked(link, read, after)):
- self._inject_timed_locked(link, read)
+ else:
+ zones_at = time.monotonic()
+ consumed = read["type"] == protocol.MSG_MOUSEMOVE and self._zones_locked(link, read, after)
+ link.timing.add("zones", time.monotonic() - zones_at)
+ if not consumed:
+ self._inject_timed_locked(link, read)
except Exception:
LOGGER.exception("Input from %s could not be injected", link.name)
self._input_error_status(link)
finally:
link.dealt_with(read["seq"])
+ callbacks_at = time.monotonic()
self._run(after)
+ link.timing.add("input_callbacks", time.monotonic() - callbacks_at)
def _record_incoming_move(self, link: _Link, read: dict) -> None:
now = time.monotonic()
@@ -1053,6 +1152,7 @@ class LinkResponder:
self._inject_locked(link, read)
finally:
elapsed = time.monotonic() - began
+ link.timing.add("inject", elapsed)
now = time.monotonic()
if elapsed >= SLOW_INJECTION_SECONDS and now - link.slow_injection_at >= SLOW_INJECTION_LOG_INTERVAL_SECONDS:
link.slow_injection_at = now
@@ -1104,8 +1204,12 @@ class LinkResponder:
dx, dy = self.input_scale.move(dx, dy)
if not (dx or dy):
return
+ seam_at = time.monotonic()
dx, dy = self._clip_to_return_seam(dx, dy)
+ link.timing.add("return_seam", time.monotonic() - seam_at)
+ inject_at = time.monotonic()
injector.inject_mouse_move(dx, dy)
+ link.timing.add("mouse_inject", time.monotonic() - inject_at)
elif kind in (protocol.MSG_MOUSEDOWN, protocol.MSG_MOUSEUP):
down = kind == protocol.MSG_MOUSEDOWN
if down:
@@ -1424,6 +1528,7 @@ class LinkResponder:
`refuse`. Returns what is left to do without the lock."""
if link is None or self._owner is not link:
return []
+ stamp = self._clipboard_stamp() if let_go else None
self._owner = None
self._owner_input_at = None
self._reach = frozenset()
@@ -1436,7 +1541,7 @@ class LinkResponder:
after = []
if let_go:
visit = self._visit
- after.append(lambda: self._clipboard_later(lambda: self._clipboard_back(link, visit)))
+ after.append(lambda: self._clipboard_later(lambda: self._clipboard_back(link, visit, stamp)))
elif why is not None and not link.closed.is_set():
link.post(protocol.refuse_msg(link.route, why))
return after
@@ -1532,11 +1637,13 @@ class LinkResponder:
if self._owner is not link:
return
visit = self._visit
- self._clipboard_later(lambda: self._set_clipboard(link, visit, text, image))
+ self._clipboard_later(lambda: self._set_clipboard(link, visit, text, image), (id(link), visit))
- def _clipboard_later(self, job) -> None:
+ def _clipboard_later(self, job, write=None) -> None:
with self._clipboard_jobs_lock:
- self._clipboard_jobs.append(job)
+ if write is not None and self._clipboard_jobs and self._clipboard_jobs[-1][1] == write:
+ self._clipboard_jobs.pop()
+ self._clipboard_jobs.append((job, write))
if self._clipboard_running:
return
self._clipboard_running = True
@@ -1553,7 +1660,7 @@ class LinkResponder:
if not self._clipboard_jobs:
self._clipboard_running = False
return
- job = self._clipboard_jobs.popleft()
+ job, _ = self._clipboard_jobs.popleft()
try:
job()
except Exception:
@@ -1562,18 +1669,34 @@ class LinkResponder:
def _set_clipboard(self, link: _Link, visit: int, text, image) -> None:
"""A write begins only while its sender still owns this machine in the visit it was sent in;
one already in flight when the ownership ends is not taken back, as it cannot be."""
- with self._lock:
- if self._owner is not link or self._visit != visit:
+ initial_stamp = self._clipboard_stamp()
+ clipboard = self._clipboard_module()
+ deadline = time.monotonic() + CLIPBOARD_RETRY_WINDOW_SECONDS
+ for attempt in range(CLIPBOARD_RETRY_ATTEMPTS):
+ if attempt and time.monotonic() >= deadline:
+ break
+ with self._lock:
+ if self._owner is not link or self._visit != visit or link.closed.is_set():
+ return
+ if attempt and (initial_stamp is None or self._clipboard_stamp() != initial_stamp):
return
- try:
- if not self._clipboard_module().set_contents(text, image):
- LOGGER.warning("Could not set the clipboard %s sent", link.name)
- except Exception:
- LOGGER.exception("Could not set the clipboard %s sent", link.name)
- stamp = self._clipboard_stamp()
- with self._lock:
- if self._visit == visit:
- self._clipboard_mark = stamp
+ try:
+ written = clipboard.set_contents(text, image)
+ except Exception:
+ written = False
+ if attempt == CLIPBOARD_RETRY_ATTEMPTS - 1:
+ LOGGER.exception("Could not set the clipboard %s sent", link.name)
+ if written:
+ # The adapter's own write stamp must not absorb a local copy made just after it.
+ write_stamp = getattr(clipboard, "write_stamp", None)
+ stamp = write_stamp() if write_stamp is not None else self._clipboard_stamp()
+ with self._lock:
+ if self._visit == visit:
+ self._clipboard_mark = stamp
+ return
+ if attempt < CLIPBOARD_RETRY_ATTEMPTS - 1:
+ time.sleep(CLIPBOARD_RETRY_SECONDS)
+ LOGGER.warning("Could not set the clipboard %s sent", link.name)
def _clipboard_stamp(self):
stamp = getattr(self._clipboard_module(), "change_stamp", None)
@@ -1585,24 +1708,43 @@ class LinkResponder:
LOGGER.exception("Could not read the clipboard's change stamp")
return None
- def _clipboard_back(self, link: _Link, visit: int) -> None:
+ def _clipboard_back(self, link: _Link, visit: int, stamp) -> None:
"""A let-go owner gets this machine's clipboard only when something other than its own
`clipboard` messages changed it during the visit, so an idle machine gives nothing away;
and never once another ownership has begun or the clipboard changed while it was read, so
- what it gets is never the next owner's. Nor when the clipboard could not be read as the
- visit began (a Wayland session not up yet): what changed during it cannot be told. The mark
- is read here, after any write the owner had queued has updated it."""
+ what it gets is never the next owner's or a copy made after letting go. Nor when the
+ clipboard stamp could not be read as the visit began or ended (a Wayland session not up
+ yet): what changed during it cannot be told. The mark is read here, after any write the
+ owner had queued has updated it."""
with self._lock:
if self._visit != visit:
return
mark = self._clipboard_mark
- stamp = self._clipboard_stamp()
if stamp is None or mark is None or stamp == mark:
return
- try:
- text, image = self._clipboard_module().get_contents()
- except Exception:
- LOGGER.exception("Could not read the clipboard for %s", link.name)
+ deadline = time.monotonic() + CLIPBOARD_RETRY_WINDOW_SECONDS
+ for attempt in range(CLIPBOARD_RETRY_ATTEMPTS):
+ if attempt and time.monotonic() >= deadline:
+ LOGGER.warning("Could not read the clipboard for %s", link.name)
+ return
+ with self._lock:
+ if self._visit != visit or self._owner is not None or link.closed.is_set():
+ return
+ # A retry belongs to the same copy, never a local copy made after letting go.
+ if self._clipboard_stamp() != stamp:
+ return
+ try:
+ text, image = self._clipboard_module().get_contents()
+ except Exception:
+ text, image = None, None
+ if attempt == CLIPBOARD_RETRY_ATTEMPTS - 1:
+ LOGGER.exception("Could not read the clipboard for %s", link.name)
+ if text is not None or image is not None:
+ break
+ if attempt < CLIPBOARD_RETRY_ATTEMPTS - 1:
+ time.sleep(CLIPBOARD_RETRY_SECONDS)
+ else:
+ LOGGER.warning("Could not read the clipboard for %s", link.name)
return
if "clipboard" not in link.caps or not text or len(text.encode("utf-8", "replace")) > protocol.CLIPBOARD_MAX_BYTES:
text = None
diff --git a/core/tests/responder_harness.py b/core/tests/responder_harness.py
index d6ba3c3..2782849 100644
--- a/core/tests/responder_harness.py
+++ b/core/tests/responder_harness.py
@@ -187,7 +187,7 @@ def wait_for(predicate, timeout=3.0):
class Machine:
"""A responder listening on loopback, with fakes at every platform edge."""
- def __init__(self, peers, zones=(), caps=CAPS, away=False, desktop=None, notch_span=None, own=HERE, name="Here", unlock=None, hardware=None, hw=None):
+ def __init__(self, peers, zones=(), caps=CAPS, away=False, desktop=None, notch_span=None, own=HERE, name="Here", unlock=None, hardware=None, hw=None, identify_callback=None):
self.own = own
self.settings = Settings(peers, zones, own)
self.book = receiver.PeerBook(self.settings.load, self.settings.save)
@@ -222,6 +222,7 @@ class Machine:
pressure_callback=lambda edge, pressure, crossed, part: self.pressures.append((edge, pressure, crossed, part)),
arrangement_callback=lambda peer, read: self.arrangements.append((peer, read)),
settings_callback=lambda peer, data: self.settings_seen.append((peer, data)),
+ identify_callback=identify_callback,
paired_callback=lambda peer, ids: self.paired.append((peer, ids)),
link_callback=lambda peer, up: self.links.append((peer, up)),
announce=lambda peer: list(self.announcements.get(peer, [])),
diff --git a/core/tests/test_clipboard_reliability.py b/core/tests/test_clipboard_reliability.py
new file mode 100644
index 0000000..c61c0ca
--- /dev/null
+++ b/core/tests/test_clipboard_reliability.py
@@ -0,0 +1,230 @@
+"""Clipboard retries against transient platform failures, without native GUI imports."""
+
+import threading
+import unittest
+from types import SimpleNamespace
+from unittest import mock
+
+from core import protocol, receiver
+from core.tests.responder_harness import FakeClipboard, FakeInjector
+
+
+class ClipboardReliability(unittest.TestCase):
+ def setUp(self):
+ self.clipboard = FakeClipboard("before")
+ self.sent = []
+ self.link = SimpleNamespace(name="Peer", closed=threading.Event(),
+ caps={"clipboard"}, own_caps={"clipboard"},
+ held={}, post=self.sent.append)
+ self.responder = receiver.LinkResponder(None, lambda: {}, status_callback=lambda *_: None,
+ clipboard=self.clipboard, injector=FakeInjector())
+ self.responder._owner = self.link
+ self.responder._visit = 1
+ self.responder._clipboard_mark = self.clipboard.stamp
+
+ def receive(self):
+ self.responder._set_clipboard(self.link, 1, "peer text", None)
+
+ def return_clipboard(self):
+ self.clipboard.copy("copied remotely")
+ self.let_go()
+ self.responder._clipboard_worker()
+
+ def let_go(self):
+ self.responder._clipboard_running = True
+ with self.responder._lock:
+ after = self.responder._end_locked(self.link, let_go=True)
+ self.responder._run(after)
+
+ def test_a_home_copy_before_the_queued_return_runs_is_not_sent(self):
+ self.clipboard.copy("copied remotely")
+ self.let_go()
+ self.clipboard.copy("private home copy")
+ self.responder._clipboard_worker()
+ self.assertEqual(self.sent, [])
+
+ def test_a_home_copy_before_the_return_is_queued_is_not_sent(self):
+ self.clipboard.copy("copied remotely")
+ self.responder._clipboard_running = True
+ with self.responder._lock:
+ after = self.responder._end_locked(self.link, let_go=True)
+ self.clipboard.copy("private home copy")
+ self.responder._run(after)
+ self.responder._clipboard_worker()
+ self.assertEqual(self.sent, [])
+
+ def test_an_unavailable_let_go_stamp_never_returns_a_clipboard(self):
+ self.clipboard.copy("copied remotely")
+ with mock.patch.object(self.clipboard, "change_stamp", return_value=None):
+ self.let_go()
+ self.responder._clipboard_worker()
+ self.assertEqual(self.sent, [])
+
+ def test_a_burst_keeps_only_the_newest_pending_write(self):
+ self.responder._clipboard_running = True
+ for n in range(300):
+ self.responder._on_clipboard(self.link, protocol.clipboard_msg(f"copy {n}"))
+ self.assertLessEqual(len(self.responder._clipboard_jobs), 1)
+ self.responder._clipboard_worker()
+ self.assertEqual(self.clipboard.text, "copy 299")
+
+ def test_pending_writes_do_not_coalesce_across_a_return_job(self):
+ self.responder._clipboard_running = True
+ self.responder._on_clipboard(self.link, protocol.clipboard_msg("peer text"))
+ self.let_go()
+ self.responder._owner = self.link
+ self.responder._on_clipboard(self.link, protocol.clipboard_msg("new peer text"))
+ self.assertEqual(len(self.responder._clipboard_jobs), 3)
+ self.responder._clipboard_worker()
+ self.assertEqual(self.clipboard.set_calls, [("peer text", None), ("new peer text", None)])
+ self.assertEqual(self.sent, [])
+
+ def test_a_write_finishing_after_let_go_updates_the_mark_before_return(self):
+ original = self.clipboard.set_contents
+
+ def write(*args):
+ original(*args)
+ self.let_go()
+ return True
+
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=write):
+ self.receive()
+ self.responder._clipboard_worker()
+ self.assertEqual(self.clipboard.text, "peer text")
+ self.assertEqual(self.sent, [])
+
+ def test_a_contended_inbound_write_recovers_without_another_crossing(self):
+ original = self.clipboard.set_contents
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=[False, True]) as write:
+ write.side_effect = lambda *args: False if write.call_count == 1 else original(*args)
+ with mock.patch.object(receiver.time, "sleep"):
+ self.receive()
+ self.assertEqual(self.clipboard.text, "peer text")
+
+ def test_a_failed_write_does_not_hide_a_local_copy_from_return(self):
+ self.clipboard.copy("copied remotely")
+ with mock.patch.object(self.clipboard, "set_contents", return_value=False), \
+ mock.patch.object(receiver.time, "sleep"):
+ self.receive()
+ self.let_go()
+ self.responder._clipboard_worker()
+ self.assertEqual(self.sent, [protocol.clipboard_msg("copied remotely")])
+
+ def test_a_local_copy_cancels_a_contended_inbound_write(self):
+ original = self.clipboard.set_contents
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=[False, True]) as write:
+ write.side_effect = lambda *args: False if write.call_count == 1 else original(*args)
+ with mock.patch.object(receiver.time, "sleep", side_effect=lambda _: self.clipboard.copy("new local")):
+ self.receive()
+ self.assertEqual(self.clipboard.text, "new local")
+
+ def test_a_new_visit_cancels_an_inbound_retry(self):
+ original = self.clipboard.set_contents
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=[False, True]) as write:
+ write.side_effect = lambda *args: False if write.call_count == 1 else original(*args)
+ with mock.patch.object(receiver.time, "sleep", side_effect=lambda _: setattr(self.responder, "_visit", 2)):
+ self.receive()
+ self.assertEqual(self.clipboard.text, "before")
+
+ def test_a_closed_link_cancels_an_inbound_retry(self):
+ with mock.patch.object(self.clipboard, "set_contents", return_value=False), \
+ mock.patch.object(receiver.time, "sleep", side_effect=lambda _: self.link.closed.set()):
+ self.receive()
+ self.assertEqual(self.clipboard.text, "before")
+
+ def test_a_write_exception_is_retried(self):
+ original = self.clipboard.set_contents
+ attempts = iter([False, True])
+
+ def write(*args):
+ if not next(attempts):
+ raise OSError("clipboard busy")
+ return original(*args)
+
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=write), \
+ mock.patch.object(receiver.time, "sleep"):
+ self.receive()
+ self.assertEqual(self.clipboard.text, "peer text")
+
+ def test_a_copy_immediately_after_a_successful_write_is_returned(self):
+ original = self.clipboard.set_contents
+ write_stamp = []
+
+ def write(*args):
+ original(*args)
+ write_stamp.append(self.clipboard.stamp)
+ self.clipboard.copy("local immediately after write")
+ return True
+
+ self.clipboard.write_stamp = lambda: write_stamp[-1]
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=write):
+ self.receive()
+ self.let_go()
+ self.responder._clipboard_worker()
+ self.assertEqual(self.sent, [protocol.clipboard_msg("local immediately after write")])
+
+ def test_a_contended_return_read_recovers_at_the_same_stamp(self):
+ original = self.clipboard.get_contents
+ reads = iter([False, True])
+
+ def read():
+ return original() if next(reads) else (None, None)
+
+ with mock.patch.object(self.clipboard, "get_contents", side_effect=read), \
+ mock.patch.object(receiver.time, "sleep"):
+ self.return_clipboard()
+ self.assertEqual(self.sent, [protocol.clipboard_msg("copied remotely")])
+
+ def test_a_return_read_exception_is_retried(self):
+ original = self.clipboard.get_contents
+ reads = iter([False, True])
+
+ def read():
+ if not next(reads):
+ raise OSError("clipboard busy")
+ return original()
+
+ with mock.patch.object(self.clipboard, "get_contents", side_effect=read), \
+ mock.patch.object(receiver.time, "sleep"):
+ self.return_clipboard()
+ self.assertEqual(self.sent, [protocol.clipboard_msg("copied remotely")])
+
+ def test_a_local_copy_after_let_go_is_never_read_for_a_return_retry(self):
+ with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \
+ mock.patch.object(receiver.time, "sleep", side_effect=lambda _: self.clipboard.copy("private local")):
+ self.return_clipboard()
+ self.assertEqual(self.sent, [])
+ self.assertEqual(self.clipboard.text, "private local")
+
+ def test_a_new_owner_cancels_a_return_retry(self):
+ with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \
+ mock.patch.object(receiver.time, "sleep", side_effect=lambda _: setattr(self.responder, "_owner", self.link)):
+ self.return_clipboard()
+ self.assertEqual(self.sent, [])
+
+ def test_a_closed_link_cancels_a_return_retry(self):
+ with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \
+ mock.patch.object(receiver.time, "sleep", side_effect=lambda _: self.link.closed.set()):
+ self.return_clipboard()
+ self.assertEqual(self.sent, [])
+
+ def test_a_copy_changing_during_a_return_read_is_not_sent(self):
+ def read():
+ self.clipboard.copy("private local")
+ return self.clipboard.text, None
+
+ with mock.patch.object(self.clipboard, "get_contents", side_effect=read):
+ self.return_clipboard()
+ self.assertEqual(self.sent, [])
+
+ def test_an_unreadable_start_of_visit_never_returns_a_clipboard(self):
+ self.responder._clipboard_mark = None
+ self.return_clipboard()
+ self.assertEqual(self.sent, [])
+
+ def test_repeated_contention_is_bounded(self):
+ with mock.patch.object(self.clipboard, "set_contents", return_value=False) as write, \
+ mock.patch.object(receiver.time, "sleep"):
+ self.receive()
+ self.assertGreater(write.call_count, 1)
+ self.assertLessEqual(write.call_count, 25)
diff --git a/core/tests/test_clipboard_stress.py b/core/tests/test_clipboard_stress.py
new file mode 100644
index 0000000..2111585
--- /dev/null
+++ b/core/tests/test_clipboard_stress.py
@@ -0,0 +1,54 @@
+"""Encrypted clipboard bursts over loopback; all desktop edges are synthetic."""
+
+import unittest
+
+from core import protocol
+from core.tests.responder_harness import B, Initiator, Machine, entry, wait_for
+
+
+class ClipboardWireStress(unittest.TestCase):
+ def setUp(self):
+ self.machine = Machine([entry(B, "Peer")]).start()
+ self.addCleanup(self.machine.stop)
+
+ def connect(self):
+ link = Initiator(self.machine)
+ self.addCleanup(link.close)
+ link.handshake()
+ route = link.take()
+ self.assertEqual(link.answer(route)[0], protocol.MSG_ACCEPT)
+ self.assertTrue(wait_for(lambda: self.machine.responder.owner == B))
+ return link
+
+ def test_rapid_successive_unicode_copies_keep_order_and_reach_the_newest_copy(self):
+ link = self.connect()
+ copies = [f"copy {n}: café, 日本語, Україна, \U0001d11e\nsecond line" for n in range(300)]
+ for text in copies:
+ link.send(protocol.clipboard_msg(text))
+ self.assertTrue(wait_for(lambda: self.machine.clipboard.text == copies[-1], timeout=5))
+ indices = [copies.index(text) for text, _ in self.machine.clipboard.set_calls]
+ self.assertEqual(indices, sorted(set(indices)))
+
+ def test_large_unicode_boundary_and_oversize_do_not_drop_the_next_copy(self):
+ link = self.connect()
+ largest = "\U0001d11e" * (protocol.CLIPBOARD_MAX_BYTES // 4)
+ link.send(protocol.clipboard_msg(largest))
+ self.assertTrue(wait_for(lambda: self.machine.clipboard.text == largest))
+ for text in (largest + "x", "after oversize"):
+ link.send(protocol.clipboard_msg(text))
+ self.assertTrue(wait_for(lambda: len(self.machine.clipboard.set_calls) == 2))
+ self.assertEqual(self.machine.clipboard.set_calls, [(largest, None), ("after oversize", None)])
+
+ def test_resume_with_a_new_link_accepts_a_fresh_clipboard(self):
+ before = self.connect()
+ before.send(protocol.clipboard_msg("before sleep"))
+ self.assertTrue(wait_for(lambda: self.machine.clipboard.text == "before sleep"))
+ before.close()
+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))
+ after = self.connect()
+ after.send(protocol.clipboard_msg("after wake"))
+ self.assertTrue(wait_for(lambda: self.machine.clipboard.text == "after wake"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_i18n_coverage.py b/core/tests/test_i18n_coverage.py
index cd354b3..e97b096 100644
--- a/core/tests/test_i18n_coverage.py
+++ b/core/tests/test_i18n_coverage.py
@@ -15,6 +15,7 @@ import re
import subprocess
import sys
import unittest
+from unittest import mock
from pathlib import Path
@@ -52,6 +53,7 @@ NOT_SHOWN = {
"dispatch", "ExecMethod_", "Methods_", "persistentDomainForName_",
"beginActivityWithOptions_reason_", "asset_path", "CreateMutexW", "QKeySequence",
"_turn_off_clashes", "exception", "_force_local", "stringForKey_", "open_dbus_connection", "update",
+ "require_version", "_log_helper_failure",
}
@@ -89,6 +91,10 @@ def _prose(node) -> bool:
def _not_shown(node: ast.Call, parent, parents, exception_classes) -> bool:
name = _name(node.func)
+ if name in {"insert", "remove"} and _owner(node.func) == "environment":
+ return bool(node.args and isinstance(node.args[0], ast.Constant)
+ and isinstance(node.args[0].value, str)
+ and re.fullmatch(r"[A-Z][A-Z0-9_]*", node.args[0].value))
if name == "__init__" and name in NOT_SHOWN:
ancestor = parent
while ancestor is not None and not isinstance(ancestor, ast.ClassDef):
@@ -115,6 +121,9 @@ def hard_coded(path: Path) -> list[str]:
if not isinstance(node, ast.Call) or _not_shown(node, parents.get(node), parents, exception_classes):
continue
for arg in list(node.args) + [keyword.value for keyword in node.keywords]:
+ # Win32's class name is a system identifier; the following title remains visible text.
+ if _name(node.func) == "CreateWindowExW" and len(node.args) > 1 and arg is node.args[1]:
+ continue
if _prose(arg):
found.append(f"{path.relative_to(ROOT).as_posix()}:{arg.lineno}: {_name(node.func)}({ast.unparse(arg)[:70]})")
return found
@@ -171,6 +180,13 @@ def import_time_tr(path: Path) -> list[str]:
class I18nCoverageTests(unittest.TestCase):
+ def test_win32_window_class_is_an_identifier_but_its_title_is_visible(self):
+ path = ROOT / "win_app/clipboard_win.py"
+ source = 'win32.CreateWindowExW(0, "STATIC", "Visible title", 0)'
+ with mock.patch.object(Path, "read_text", return_value=source):
+ found = hard_coded(path)
+ self.assertEqual(found, ["win_app/clipboard_win.py:1: CreateWindowExW('Visible title')"])
+
def test_no_hard_coded_user_visible_strings(self):
found = [line for path in source_files() for line in hard_coded(path)]
self.assertEqual(found, [], "mark these with tr() or N_() from core.i18n:\n" + "\n".join(found))
diff --git a/core/tests/test_identify_screens_core.py b/core/tests/test_identify_screens_core.py
new file mode 100644
index 0000000..4191c3d
--- /dev/null
+++ b/core/tests/test_identify_screens_core.py
@@ -0,0 +1,99 @@
+"""Core screen numbering and link contracts, separate from the native overlay tests."""
+
+import unittest
+
+from core import protocol, receiver, ways
+from core.tests.responder_harness import B, CAPS, HERE, TOKENS, Machine, entry, wait_for
+from core.tests.test_link import Side
+
+
+class ScreenNumberTests(unittest.TestCase):
+ def test_numbers_follow_map_order_even_with_split_display_offsets(self):
+ from core.identify_screens import display_numbers
+ tile = {"x": 100, "y": 200, "w": 300, "h": 200, "displays": {
+ "0": {"x": 1920, "y": 0, "w": 1920, "h": 1080},
+ "2": {"x": 0, "y": -1080, "w": 1920, "h": 1080},
+ "1": {"x": 0, "y": 0, "w": 1920, "h": 1080}},
+ "display_offsets": {"2": {"x": 500, "y": 500}}}
+ self.assertEqual(display_numbers(tile), {"2": 1, "1": 2, "0": 3})
+ self.assertEqual([display_numbers(tile)[frame["display"]]
+ for frame in ways._display_frames(tile)], [1, 2, 3])
+
+ def test_single_display_fallback_needs_no_saved_geometry(self):
+ from core.identify_screens import display_numbers
+ self.assertEqual(display_numbers({}), {"0": 1})
+ self.assertEqual(display_numbers(None), {"0": 1})
+
+
+class IdentifyProtocolTests(unittest.TestCase):
+ def test_message_round_trips_without_changing_wire_version(self):
+ labels = {"1": 1, "0": 2}
+ message = protocol.identify_screens_msg(labels)
+ self.assertEqual(message, {"type": "identify_screens", "data": {"displays": labels}})
+ self.assertEqual(protocol.read_identify_screens(message), labels)
+ labels["0"] = 3
+ self.assertEqual(protocol.read_identify_screens(message), {"1": 1, "0": 2})
+ self.assertEqual(protocol.LINK_VERSION, 6)
+
+ def test_rejects_invalid_labels_before_showing_any_overlay(self):
+ for labels in ({}, [], {"0": True}, {"0": 0}, {"0": 17}, {"0": 1.5},
+ {"0": 1, "1": 1}, {"a" * 65: 1}, {"bad key": 1},
+ {"é": 1}, {str(n): n + 1 for n in range(17)}):
+ with self.subTest(labels=labels):
+ message = {"type": "identify_screens", "data": {"displays": labels}}
+ self.assertIsNone(protocol.read_identify_screens(message))
+ for message in (None, {}, {"type": "identify_screens", "data": []},
+ {"type": "settings", "data": {"displays": {"0": 1}}}):
+ self.assertIsNone(protocol.read_identify_screens(message))
+
+
+class IdentifyLinkTests(unittest.TestCase):
+ def test_older_outbound_peer_is_a_successful_no_op(self):
+ link = Side().link()
+ link._live = True
+ link._caps = frozenset(CAPS)
+ self.assertTrue(link.post(protocol.identify_screens_msg({"0": 1})))
+ self.assertEqual(list(link._outbox), [])
+ self.assertEqual(link.last_sent_seq, 0)
+
+ def test_existing_link_delivers_both_directions_without_taking_input_ownership(self):
+ caps = tuple(CAPS) + ("identify_screens",)
+ seen = []
+ machine = Machine([entry(B, "Peer")], caps=caps,
+ identify_callback=lambda peer, labels: seen.append((peer, labels))).start()
+ self.addCleanup(machine.stop)
+ side = Side(machine)
+ identity = side.identity
+ side.identity = lambda: identity(caps=list(caps))
+ link = side.link()
+ self.addCleanup(link.stop)
+ link.start()
+ self.assertTrue(wait_for(lambda: bool(side.ups)))
+ self.assertTrue(link.post(protocol.identify_screens_msg({"0": 2, "1": 1})))
+ self.assertTrue(wait_for(lambda: bool(seen)))
+ self.assertEqual(seen, [(B, {"0": 2, "1": 1})])
+ self.assertIsNone(machine.responder.owner)
+ self.assertEqual(machine.injected(), [])
+ self.assertTrue(machine.responder.send(B, protocol.identify_screens_msg({"0": 1})))
+ self.assertTrue(wait_for(lambda: bool(side.messages)))
+ self.assertEqual(protocol.read_identify_screens(side.messages[0]), {"0": 1})
+ self.assertEqual(link.last_sent_seq, 0)
+
+ def test_older_inbound_peer_gets_no_new_message(self):
+ machine = Machine([entry(B, "Peer")])
+ link = receiver._Link(None, None, B, protocol.key_id(TOKENS[B]), "127.0.0.1",
+ "Older", CAPS, HERE, CAPS, True)
+ machine.responder._links[B] = link
+ self.assertTrue(machine.responder.send(B, protocol.identify_screens_msg({"0": 1})))
+ self.assertEqual(list(link.outbox), [])
+
+ def test_receiver_ignores_unnegotiated_and_unknown_requests(self):
+ seen = []
+ machine = Machine([entry(B, "Peer")], identify_callback=lambda *args: seen.append(args))
+ link = receiver._Link(None, None, B, protocol.key_id(TOKENS[B]), "127.0.0.1",
+ "Older", CAPS, HERE, CAPS, True)
+ machine.responder._dispatch(link, protocol.identify_screens_msg({"0": 1}))
+ machine.responder._dispatch(link, {"type": "future_request", "data": {}})
+ self.assertEqual(seen, [])
+ self.assertEqual(machine.injected(), [])
+ self.assertFalse(link.closed.is_set())
diff --git a/core/tests/test_ignored.py b/core/tests/test_ignored.py
index b7db42c..11f0d1f 100644
--- a/core/tests/test_ignored.py
+++ b/core/tests/test_ignored.py
@@ -6,6 +6,41 @@ from core import ignored
class GateTests(unittest.TestCase):
+ def test_mouse_only_keeps_every_key_and_media_key_but_not_buttons(self):
+ gate = ignored.Gate(mouse_only=True)
+ for entry in ("key:0", "key:65535", "key:a", "key:text", "media:volume_up"):
+ with self.subTest(entry=entry):
+ self.assertTrue(gate.keeps(entry, True))
+ self.assertTrue(gate.keeps(entry, False))
+ for entry in ("button:left", "button:forward"):
+ self.assertFalse(gate.keeps(entry, True))
+ self.assertFalse(gate.keeps(entry, False))
+
+ def test_mouse_only_toggle_keeps_releases_with_their_presses(self):
+ gate = ignored.Gate()
+ self.assertFalse(gate.keeps("key:12", True))
+ gate.configure([], mouse_only=True)
+ self.assertFalse(gate.keeps("key:12", False))
+ self.assertTrue(gate.keeps("key:12", True))
+ gate.configure([], mouse_only=False)
+ self.assertTrue(gate.keeps("key:12", True), "local repeat stays local")
+ self.assertTrue(gate.keeps("key:12", False))
+ self.assertFalse(gate.keeps("key:12", True))
+
+ def test_mouse_only_preserves_individually_ignored_buttons(self):
+ gate = ignored.Gate(["button:back"], mouse_only=True)
+ self.assertTrue(gate.keeps("button:back", True))
+ gate.configure(["button:back"], mouse_only=False)
+ self.assertTrue(gate.keeps("button:back", False))
+
+ def test_composed_text_and_dead_key_taps_do_not_pin_their_route(self):
+ gate = ignored.Gate(mouse_only=True)
+ self.assertTrue(gate.keeps_tap("key:65"))
+ gate.configure([], mouse_only=False)
+ self.assertFalse(gate.keeps_tap("key:65"))
+ gate.configure([], mouse_only=True)
+ self.assertTrue(gate.keeps_tap("key:65"))
+
def test_a_listed_press_and_its_release_stay_here(self):
gate = ignored.Gate([ignored.button("back")])
self.assertTrue(gate.keeps("button:back", True))
diff --git a/core/tests/test_link.py b/core/tests/test_link.py
index 9d30aea..c90500a 100644
--- a/core/tests/test_link.py
+++ b/core/tests/test_link.py
@@ -516,6 +516,18 @@ class LinkLiveTests(unittest.TestCase):
self.assertTrue(self.link.post(protocol.focus_v6(route, HERE, resistance_px=120, reach=[])))
self.assertTrue(wait_for(lambda: any(m["type"] == protocol.MSG_ACCEPT for m in self.side.messages)), self.side.messages)
+ def test_fast_overlapping_typing_survives_the_outbound_queue(self):
+ self.take()
+ expected = []
+ for _ in range(100):
+ for name, down in (("shift", True), ("a", True), ("b", True), ("a", False),
+ ("b", False), ("shift", False), ("o", True), ("o", True),
+ ("o", False), ("o", True), ("o", False)):
+ self.assertTrue(self.link.send_input(protocol.key_msg("keydown" if down else "keyup", name)))
+ expected.append(("key", name, down))
+ self.assertTrue(wait_for(lambda: self.link._last_ack_seq == len(expected)))
+ self.assertEqual(self.machine.injected(), expected)
+
def test_send_input_numbers_from_one_and_the_responder_injects_for_its_owner(self):
self.take()
self.assertTrue(self.link.send_input(protocol.key_msg("keydown", "a")))
diff --git a/core/tests/test_link_latency.py b/core/tests/test_link_latency.py
new file mode 100644
index 0000000..b28bdcd
--- /dev/null
+++ b/core/tests/test_link_latency.py
@@ -0,0 +1,93 @@
+"""Directional ACK latency and diagnostics, using real encrypted loopback links."""
+
+import time
+import unittest
+
+from core import protocol
+from core.tests.test_link import Side
+from core.tests.responder_harness import B, HERE, TOKENS, Machine, entry, wait_for
+
+
+class DirectionalLatencyTests(unittest.TestCase):
+ def test_slow_receiver_delays_only_its_input_direction_and_logs_the_stage(self):
+ slow = Machine([entry(B, "A")]).start()
+ fast = Machine([entry(HERE, "B", token=TOKENS[B])], own=B).start()
+ self.addCleanup(slow.stop)
+ self.addCleanup(fast.stop)
+ forward = Side(slow).link()
+ backward = Side(fast, peer=B, own=HERE).link()
+ self.addCleanup(forward.stop)
+ self.addCleanup(backward.stop)
+ forward.start()
+ backward.start()
+ self.assertTrue(wait_for(lambda: forward.live() and backward.live()))
+ for link, target in ((forward, HERE), (backward, B)):
+ self.assertTrue(link.post(protocol.focus_v6(1, target, resistance_px=120, reach=[])))
+ self.assertTrue(wait_for(lambda: slow.responder.driven and fast.responder.driven))
+ original = slow.injector.inject_key
+
+ def delayed(key, down, us=None):
+ time.sleep(0.02)
+ original(key, down, us=us)
+
+ slow.injector.inject_key = delayed
+ inbound_route = slow.responder._links[B].timing.route
+ with self.assertLogs("Beamer", "INFO") as captured:
+ for _ in range(24):
+ self.assertTrue(forward.send_input(protocol.key_msg("keydown", "a")))
+ self.assertTrue(backward.send_input(protocol.key_msg("keydown", "a")))
+ self.assertTrue(wait_for(lambda: forward._last_ack_seq == 24 and backward._last_ack_seq == 1))
+ self.assertGreater(forward.round_trips()[-1], 0.35)
+ self.assertGreater(forward.round_trips()[-1] - forward.round_trips()[0], 0.2)
+ self.assertLess(backward.round_trips()[-1], 0.2)
+ forward.stop()
+ backward.stop()
+ slow.stop()
+ fast.stop()
+ self.assertTrue(wait_for(lambda: any(inbound_route in line and "inject_ms" in line
+ for line in captured.output), 5.0))
+ text = "\n".join(captured.output)
+ self.assertIn("link timing inbound", text)
+ self.assertIn("inject_ms", text)
+ self.assertIn("dispatch_ms", text)
+
+ def test_lock_wait_is_measured_separately_from_injection(self):
+ machine = Machine([entry(B, "A")]).start()
+ self.addCleanup(machine.stop)
+ link = Side(machine).link()
+ self.addCleanup(link.stop)
+ link.start()
+ self.assertTrue(wait_for(link.live))
+ link.post(protocol.focus_v6(1, HERE, resistance_px=120, reach=[]))
+ self.assertTrue(wait_for(lambda: machine.responder.driven))
+ with machine.responder._lock:
+ link.send_input(protocol.mousemove_msg(1, 1))
+ self.assertTrue(wait_for(lambda: link._written_seq == 1))
+ time.sleep(0.1)
+ self.assertTrue(wait_for(lambda: link._last_ack_seq == 1))
+ inbound = machine.responder._links[B]
+ with inbound.timing.lock:
+ lock_max = inbound.timing.stages["input_lock"][2]
+ inject_max = inbound.timing.stages["inject"][2]
+ self.assertGreater(lock_max, 50)
+ self.assertLess(inject_max, lock_max)
+
+ def test_route_logs_use_actual_socket_endpoints(self):
+ machine = Machine([entry(B, "A")]).start()
+ self.addCleanup(machine.stop)
+ link = Side(machine).link()
+ self.addCleanup(link.stop)
+ with self.assertLogs("Beamer", "INFO") as captured:
+ link.start()
+ self.assertTrue(wait_for(link.live))
+ self.assertTrue(wait_for(lambda: sum("link route" in line for line in captured.output) == 2))
+ link.stop()
+ text = "\n".join(captured.output)
+ self.assertIn("link route outbound", text)
+ self.assertIn("link route inbound", text)
+ self.assertIn("127.0.0.1", text)
+ self.assertIn("nodelay=1", text)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_linux_accent_holds.py b/core/tests/test_linux_accent_holds.py
new file mode 100644
index 0000000..f61a7c6
--- /dev/null
+++ b/core/tests/test_linux_accent_holds.py
@@ -0,0 +1,83 @@
+"""Accent key presses retain shortcut and held-key semantics without native injection."""
+
+from pathlib import Path
+import sys
+import unittest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "win_app"))
+
+import inject_portal
+import inject_x11
+
+
+class AccentKeymap:
+ min_keycode, max_keycode = 8, 255
+ symbols = {26: (ord("e"), ord("E")), 32: (ord("o"), ord("O")),
+ 48: (0xfe51, 0xfe52), 50: (0xffe1, 0xffe1),
+ 108: (0xfe03, 0xfe03)}
+
+ def keysym(self, code, mods, group):
+ if code == 26 and mods & 32:
+ return ord("é")
+ return self.symbols.get(code, (0, 0))[bool(mods & 1)]
+
+ def modifier_mask(self, code):
+ return {50: 1, 108: 32}.get(code, 0)
+
+ def text(self, symbol):
+ return chr(symbol) if 0 < symbol < 0xfe00 else None
+
+ def empty(self, code):
+ return code not in self.symbols
+
+
+class AccentHoldTests(unittest.TestCase):
+ def test_x11_holds_remapped_altgr_and_composed_characters_until_release(self):
+ for character, us in (("é", "e"), ("ô", "o")):
+ with self.subTest(character=character):
+ layout = inject_x11.Layout(AccentKeymap())
+ state = inject_x11.KeyState()
+ steps = inject_x11.plan_key(character, True, us, state, layout, 0, 0)
+ self.assertEqual(steps, [(inject_x11.MAP, 255, ord(character), False),
+ (inject_x11.PRESS, 255)])
+ self.assertEqual(state.chars_down, {character: (255, None)})
+ self.assertEqual(state.taps_down, set())
+ self.assertEqual(inject_x11.plan_key(character, True, us, state, layout, 0, 0), [])
+ self.assertEqual(inject_x11.plan_key(character, False, us, state, layout, 0, 0),
+ [(inject_x11.RELEASE, 255)])
+ self.assertEqual(state.chars_down, {})
+
+ def test_wayland_composition_repeat_becomes_shortcut_without_releasing_modifier(self):
+ for modifier in ("ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r"):
+ with self.subTest(modifier=modifier):
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ state = inject_x11.KeyState()
+ initial = inject_x11.plan_key("ô", True, "o", state, layout, 0, 0)
+ self.assertIn((inject_x11.PRESS, 48), initial)
+ self.assertIn((inject_x11.RELEASE, 32), initial)
+ self.assertEqual(state.taps_down, {"ô"})
+ modifier_steps = inject_x11.plan_key(modifier, True, None, state, layout, 0, 0)
+ modifier_code = modifier_steps[0][1]
+ self.assertEqual(inject_x11.plan_key("ô", True, "o", state, layout, 0, 0),
+ [(inject_x11.PRESS, 32)])
+ self.assertEqual(state.mods_down, {modifier})
+ self.assertEqual(state.taps_down, set())
+ self.assertEqual(state.chars_down, {"ô": (32, None)})
+ self.assertEqual(inject_x11.plan_key("ô", True, "o", state, layout, 0, 0), [])
+ self.assertEqual(inject_x11.plan_key("ô", False, "o", state, layout, 0, 0),
+ [(inject_x11.RELEASE, 32)])
+ self.assertEqual(inject_x11.plan_key(modifier, False, None, state, layout, 0, 0),
+ [(inject_x11.RELEASE, modifier_code)])
+ self.assertEqual((state.mods_down, state.named_down, state.chars_down, state.taps_down),
+ (set(), set(), {}, set()))
+
+ def test_x11_without_spares_never_replaces_held_input_with_compose_taps(self):
+ layout = inject_x11.Layout(AccentKeymap())
+ layout.spare = lambda: []
+ state = inject_x11.KeyState()
+ self.assertEqual(inject_x11.plan_key("ô", True, "o", state, layout, 0, 0), [])
+ self.assertEqual((state.chars_down, state.taps_down), ({}, set()))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_linux_accent_keymaps.py b/core/tests/test_linux_accent_keymaps.py
new file mode 100644
index 0000000..46f6d78
--- /dev/null
+++ b/core/tests/test_linux_accent_keymaps.py
@@ -0,0 +1,97 @@
+"""Pure libxkbcommon proof against installed layouts and compose data; no display or GUI."""
+
+import ctypes
+import ctypes.util
+from pathlib import Path
+import sys
+import unittest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "win_app"))
+
+import inject_portal
+import inject_x11
+import xkb_x11
+
+
[email protected](sys.platform.startswith("linux") and ctypes.util.find_library("xkbcommon"),
+ "requires Linux's installed XKB layouts and compose data")
+class InstalledLayoutTests(unittest.TestCase):
+ def keymap(self, symbols):
+ keymap = xkb_x11.Keymap.from_text('''xkb_keymap {
+ xkb_keycodes { include "evdev+aliases(qwerty)" };
+ xkb_types { include "complete" };
+ xkb_compat { include "complete" };
+ xkb_symbols { include "pc+%s+inet(evdev)" };
+ };''' % symbols)
+ self.addCleanup(keymap.close)
+ return keymap
+
+ def typed(self, steps, keymap, locks):
+ lib = keymap._xkb
+ p, u32 = ctypes.c_void_p, ctypes.c_uint32
+ lib.xkb_compose_table_new_from_locale.restype = p
+ lib.xkb_compose_table_new_from_locale.argtypes = [p, ctypes.c_char_p, ctypes.c_int]
+ lib.xkb_compose_state_new.restype = p
+ lib.xkb_compose_state_new.argtypes = [p, ctypes.c_int]
+ lib.xkb_compose_state_feed.argtypes = [p, u32]
+ lib.xkb_compose_state_get_status.argtypes = [p]
+ lib.xkb_compose_state_get_utf8.argtypes = [p, ctypes.c_char_p, ctypes.c_size_t]
+ lib.xkb_compose_state_reset.argtypes = [p]
+ lib.xkb_compose_state_unref.argtypes = [p]
+ lib.xkb_compose_table_unref.argtypes = [p]
+ table = lib.xkb_compose_table_new_from_locale(keymap._context, b"en_US.UTF-8", 0)
+ self.assertTrue(table)
+ compose = lib.xkb_compose_state_new(table, 0)
+ held, output = set(), []
+ try:
+ for code, down in inject_portal.wayland_steps(steps):
+ code += 8
+ if not down:
+ held.discard(code)
+ continue
+ held.add(code)
+ mask = locks
+ for modifier in held:
+ mask |= keymap.modifier_mask(modifier)
+ symbol = keymap.keysym(code, mask, 0)
+ lib.xkb_compose_state_feed(compose, symbol)
+ status = lib.xkb_compose_state_get_status(compose)
+ if status == 2: # XKB_COMPOSE_COMPOSED
+ buffer = ctypes.create_string_buffer(64)
+ lib.xkb_compose_state_get_utf8(compose, buffer, len(buffer))
+ output.append(buffer.value.decode())
+ lib.xkb_compose_state_reset(compose)
+ elif status == 0:
+ text = keymap.text(symbol)
+ if text and text.isprintable():
+ output.append(text)
+ elif status == 3:
+ self.fail("planned strokes cancelled XKB compose")
+ self.assertEqual(held, set(), "input planning left physical keys held")
+ return "".join(output)
+ finally:
+ lib.xkb_compose_state_unref(compose)
+ lib.xkb_compose_table_unref(table)
+
+ def test_spanish_latin_american_and_international_layouts_type_accents(self):
+ for symbols in ("es", "latam", "us(intl)"):
+ for layout_class in (inject_x11.Layout, inject_portal.WaylandLayout):
+ for locks in (0, 2, 16, 18):
+ with self.subTest(symbols=symbols, backend=layout_class.__name__, locks=locks):
+ keymap = self.keymap(symbols)
+ state = inject_x11.KeyState()
+ layout = layout_class(keymap)
+ text = "Agustín Cómo imágenes éôü ÉÔÜ €"
+ steps = inject_x11.plan_text(text, state, layout, 0, locks)
+ self.assertFalse(any(step[0] == inject_x11.MAP for step in steps))
+ self.assertEqual(self.typed(steps, keymap, locks), text)
+
+ def test_plain_us_keeps_the_explicit_wayland_limit_and_x11_unicode_remap(self):
+ keymap = self.keymap("us")
+ self.assertEqual(inject_x11.plan_text("é", inject_x11.KeyState(), inject_portal.WaylandLayout(keymap), 0, 0), [])
+ steps = inject_x11.plan_text("é", inject_x11.KeyState(), inject_x11.Layout(keymap), 0, 0)
+ self.assertTrue(any(step[0] == inject_x11.MAP and step[2] == 0xe9 for step in steps))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_linux_accents.py b/core/tests/test_linux_accents.py
new file mode 100644
index 0000000..31cca94
--- /dev/null
+++ b/core/tests/test_linux_accents.py
@@ -0,0 +1,219 @@
+"""Windows capture to Linux input planning, without a GUI or native input injection."""
+
+from pathlib import Path
+from types import SimpleNamespace
+import sys
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "win_app"))
+
+import capture_win
+import inject_portal
+import inject_x11
+import sender
+from core import owner, protocol
+
+
+class AccentKeymap:
+ # Spanish-like dead accents, plus an AltGr vowel. AltGr is deliberately Mod3.
+ KEYS = {26: ("e", "E"), 32: ("o", "O"), 30: ("u", "U"), 31: ("i", "I"),
+ 48: (0xfe51, 0xfe52), 49: (0xfe57, 0xfe57), 50: (0xffe1, 0xffe1),
+ 108: (0xfe03, 0xfe03)}
+ min_keycode, max_keycode = 8, 255
+
+ def keysym(self, code, mods, group):
+ if group != 0:
+ return 0
+ if code == 31 and mods & 32:
+ return 0x20ac # EuroSign is a legacy XKB keysym, not a Unicode-prefixed one.
+ if code == 26 and mods & 32:
+ return ord("É" if mods & 1 else "é")
+ pair = self.KEYS.get(code)
+ if pair is None:
+ return 0
+ upper = bool(mods & 1) != bool(mods & 2 and isinstance(pair[0], str))
+ value = pair[int(upper)]
+ return ord(value) if isinstance(value, str) else value
+
+ def modifier_mask(self, code):
+ return {50: 1, 108: 32}.get(code, 0)
+
+ def text(self, sym):
+ return chr(sym) if 0 < sym < 0xfe00 else None
+
+ def empty(self, code):
+ return code not in self.KEYS
+
+
+class CaptureApi:
+ def GetForegroundWindow(self):
+ return 99
+
+ def GetWindowThreadProcessId(self, window, process):
+ return 17
+
+ def GetKeyboardLayout(self, thread):
+ return "Spanish" if thread == 17 else "US"
+
+ def ToUnicodeEx(self, vk, scan, state, buffer, size, flags, layout):
+ if vk == 0xde:
+ buffer[0] = "´" if layout == "Spanish" else "'"
+ return -1 if layout == "Spanish" else 1
+ buffer[0] = "e"
+ return 1
+
+
+class AccentTests(unittest.TestCase):
+ def test_capture_reads_foreground_layout_instead_of_hook_thread_layout(self):
+ state = capture_win.KeyboardState()
+ with patch.object(capture_win, "user32", CaptureApi()):
+ dead = capture_win.key_name(0xde, 0, state, capture_win._to_unicode)
+ self.assertIsInstance(dead, capture_win.DeadKey)
+ self.assertEqual(capture_win.key_name(0x45, 0, state, capture_win._to_unicode), "é")
+
+ def test_no_foreground_window_uses_hook_layout(self):
+ api = CaptureApi()
+ api.GetForegroundWindow = lambda: 0
+ with patch.object(capture_win, "user32", api):
+ self.assertEqual(capture_win._to_unicode(0xde, 0, {}), "'")
+
+ def test_altgr_printable_uses_text_but_unchanged_shortcut_stays_a_key(self):
+ state = capture_win.KeyboardState()
+ state.altgr_down = True
+
+ def translate(vk, scan, modifiers):
+ return "é" if modifiers.get(0x12, 0) & 0x80 else "e"
+
+ translated = capture_win.key_name(0x45, 0, state, translate)
+ self.assertIsInstance(translated, capture_win.TextInput)
+ self.assertEqual(translated.text, "é")
+ self.assertEqual(capture_win.key_name(0x45, 0, state, lambda *args: "e"), "e")
+
+ def test_windows_dead_keys_survive_sender_wire_and_both_linux_planners(self):
+ for accent, base, want, strokes in (("´", "e", "é", [26]),
+ ("^", "o", "ô", [48, 32]),
+ ("¨", "u", "ü", [49, 30])):
+ for layout_class in (inject_x11.Layout, inject_portal.WaylandLayout):
+ with self.subTest(accent=accent, backend=layout_class.__name__):
+ keyboard = capture_win.KeyboardState()
+ translate = lambda vk, scan, mods: capture_win.DeadKey(accent) if vk == 0xde else base
+ link_sender = self.link_sender()
+ dead = capture_win.key_name(0xde, 0, keyboard, translate)
+ self.assertTrue(link_sender.on_dead_key(0xde))
+ self.assertIsInstance(dead, capture_win.DeadKey)
+ capture_win.key_name(0xde, 0, keyboard, translate, False)
+ name = capture_win.key_name(ord(base.upper()), 0, keyboard, translate)
+ self.assertEqual(name, want)
+ self.assertTrue(link_sender.on_key(name, True, ord(base.upper()), base))
+ self.assertTrue(link_sender.on_key(base, False, ord(base.upper()), base))
+ messages = self.messages(link_sender)
+ self.assertEqual([m["key"] for m in messages], [want, want])
+ state = inject_x11.KeyState()
+ layout = layout_class(AccentKeymap())
+ steps = []
+ for read in messages:
+ steps += inject_x11.plan_key(read["key"], read["type"] == "keydown", read["us"], state, layout, 0, 0)
+ presses = [s[1] for s in steps if s[0] == inject_x11.PRESS and s[1] not in (50, 108)]
+ if layout.can_remap:
+ self.assertEqual(steps, [(inject_x11.MAP, 255, ord(want), False),
+ (inject_x11.PRESS, 255), (inject_x11.RELEASE, 255)])
+ else:
+ self.assertFalse(any(step[0] == inject_x11.MAP for step in steps))
+ self.assertEqual(presses, strokes)
+ self.assertEqual(state.chars_down, {})
+
+ def test_text_and_repeated_composed_keys_restore_modifiers_and_release_strokes(self):
+ for locks in (0, 2):
+ with self.subTest(locks=locks):
+ state = inject_x11.KeyState()
+ state.mods_down = {"shift_r"}
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ steps = inject_x11.plan_key("ô", True, "o", state, layout, 0, locks)
+ self.assertTrue(steps)
+ self.assertEqual(steps, inject_x11.plan_key("ô", True, "o", state, layout, 0, locks))
+ self.assertEqual(inject_x11.plan_key("ô", False, "o", state, layout, 0, locks), [])
+ self.assertEqual(steps[0], (inject_x11.RELEASE, 62))
+ self.assertEqual(steps[-1], (inject_x11.PRESS, 62))
+ self.assertEqual(state.mods_down, {"shift_r"})
+ self.assertEqual(state.chars_down, {})
+ self.assertTrue(inject_x11.plan_text("éôü", state, layout, 0, locks))
+
+ def test_altgr_text_from_sender_brackets_ctrl_alt_and_reaches_wayland(self):
+ link_sender = self.link_sender()
+ link_sender.on_key("cmd", True, 0xa2)
+ link_sender.on_key("alt_r", True, 0xa5)
+ link_sender.on_text("é", 0x45)
+ messages = self.messages(link_sender)
+ self.assertTrue(any(m.get("text") == "é" for m in messages))
+ state = inject_x11.KeyState()
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ for read in messages:
+ if read["type"] == "text":
+ steps = inject_x11.plan_text(read["text"], state, layout, 0, 0)
+ self.assertIn((inject_x11.PRESS, 26), steps)
+ self.assertEqual(state.mods_down, set())
+ else:
+ inject_x11.plan_key(read["key"], read["type"] == "keydown", read["us"], state, layout, 0, 0)
+ self.assertEqual(state.mods_down, {"ctrl", "alt_r"})
+
+ def test_unavailable_layout_character_and_chord_are_not_replaced_with_compose(self):
+ state = inject_x11.KeyState()
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ self.assertEqual(inject_x11.plan_key("ô", True, None, state, layout, 1, 0), [])
+ state.mods_down = {"ctrl"}
+ self.assertEqual(inject_x11.plan_key("ô", True, "o", state, layout, 0, 0), [(inject_x11.PRESS, 32)])
+
+ def test_legacy_altgr_keysym_is_looked_up_by_its_unicode_text(self):
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ steps = inject_x11.plan_text("€", inject_x11.KeyState(), layout, 0, 0)
+ self.assertIn((inject_x11.PRESS, 31), steps)
+
+ def test_repeated_composition_follows_lock_changes(self):
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ state = inject_x11.KeyState()
+ first = inject_x11.plan_key("ô", True, "o", state, layout, 0, 0)
+ repeat = inject_x11.plan_key("ô", True, "o", state, layout, 0, 2)
+ self.assertNotEqual(repeat, first)
+ self.assertIn((inject_x11.PRESS, 50), repeat[-5:])
+ self.assertEqual(inject_x11.plan_key("ô", False, "o", state, layout, 0, 2), [])
+
+ def test_composition_does_not_release_another_held_character(self):
+ layout = inject_portal.WaylandLayout(AccentKeymap())
+ state = inject_x11.KeyState()
+ inject_x11.plan_key("o", True, "o", state, layout, 0, 0)
+ self.assertEqual(inject_x11.plan_key("ô", True, None, state, layout, 0, 0), [])
+ self.assertEqual(state.chars_down, {"o": (32, None)})
+
+ def test_altgr_dead_key_keeps_composition_until_the_next_character(self):
+ state = capture_win.KeyboardState()
+ state.altgr_down = True
+
+ def translate(vk, scan, modifiers):
+ return capture_win.DeadKey("´") if vk == 0xde and modifiers.get(0x12) else "e"
+
+ self.assertIsInstance(capture_win.key_name(0xde, 0, state, translate), capture_win.DeadKey)
+ result = capture_win.key_name(0x45, 0, state, translate)
+ self.assertIsInstance(result, capture_win.TextInput)
+ self.assertEqual(result.text, "é")
+
+ @staticmethod
+ def link_sender():
+ result = sender.LinkSender(None, lambda: {}, links=lambda _: SimpleNamespace(live=lambda peer: True))
+ result._owner = owner.Owner(bytes(range(16)), lambda: 0)
+ result._owner.on = bytes(range(16, 32))
+ return result
+
+ @staticmethod
+ def messages(link_sender):
+ messages = []
+ while not link_sender._outbound.empty():
+ action = link_sender._outbound.get_nowait()
+ message = dict(action.message)
+ message["data"] = dict(message["data"], seq=len(messages) + 1)
+ messages.append(protocol.read_input(protocol.parse_message(protocol.dumps_message(message))))
+ return messages
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_owner.py b/core/tests/test_owner.py
index b74c6b9..ea362c5 100644
--- a/core/tests/test_owner.py
+++ b/core/tests/test_owner.py
@@ -626,6 +626,61 @@ class LinkTests(OwnerCase):
class ClipboardTests(OwnerCase):
+ def test_a_copy_during_a_failed_chain_take_goes_before_replayed_input(self):
+ for outcome in ("refused", "timeout", "link_lost"):
+ with self.subTest(outcome=outcome):
+ clock = Clock()
+ o = owner.Owner("A", clock)
+ o.link_up("B", True)
+ o.link_up("C", True)
+ o.go("B")
+ o.accept("B", {"route": o.route})
+ o.switch("B", {"route": o.route, "next": "C"})
+ o.clipboard_changed()
+ self.assertEqual(o.clipboard_pending(), [])
+ paste = key("keydown", "v")
+ o.input(paste)
+ if outcome == "refused":
+ actions = o.refuse("C", {"route": o.route, "why": "owned"})
+ elif outcome == "timeout":
+ clock.now += owner.TAKE_WAIT
+ actions = o.tick()
+ else:
+ actions = o.link_down("C")
+ self.assertIn(SendClipboard("B"), actions)
+ self.assertLess(actions.index(SendClipboard("B")), actions.index(Send("B", paste)))
+
+ def test_a_failed_read_or_post_remains_pending_for_a_later_attempt(self):
+ self.take("B")
+ self.o.clipboard_failed("B")
+ self.assertEqual(self.o.clipboard_pending(), [SendClipboard("B")])
+ self.assertEqual(self.o.clipboard_pending(), [])
+
+ def test_a_copy_after_a_crossing_reaches_the_active_peer(self):
+ self.take("B")
+ for _ in range(50):
+ self.o.clipboard_changed()
+ self.assertEqual(self.o.clipboard_pending(), [SendClipboard("B")])
+ self.assertEqual(self.o.clipboard_pending(), [])
+ self.o.go(None)
+ self.o.clipboard_changed()
+ self.assertEqual(self.o.clipboard_pending(), [])
+
+ def test_a_retry_waits_for_the_take_to_be_accepted(self):
+ self.o.go("B")
+ self.o.clipboard_failed("B")
+ self.assertEqual(self.o.clipboard_pending(), [])
+ self.o.accept("B", {"route": self.o.route})
+ self.assertEqual(self.o.clipboard_pending(), [SendClipboard("B")])
+
+ def test_a_frame_started_before_let_go_cannot_consume_the_return_clipboard(self):
+ self.take("B")
+ self.o.go(None)
+ message = {"type": "clipboard", "data": {"text": "copied on B"}}
+ self.assertFalse(self.o.expects_clipboard("B", 999.9))
+ self.assertEqual(self.o.clipboard_arrived("B", 999.9, message), [])
+ self.assertEqual(self.o.clipboard_arrived("B", 1000.1, message), [SetClipboard(message)])
+
def test_a_refused_take_does_not_count_as_having_the_clipboard(self):
self.o.go("B")
self.o.refuse("B", {"route": 1, "why": "owned"})
diff --git a/core/tests/test_receiver_backlog.py b/core/tests/test_receiver_backlog.py
new file mode 100644
index 0000000..922c73d
--- /dev/null
+++ b/core/tests/test_receiver_backlog.py
@@ -0,0 +1,283 @@
+"""Receiver backpressure and input ordering over authenticated encrypted loopback sockets."""
+
+import itertools
+import json
+import socket
+import threading
+import time
+import unittest
+from unittest import mock
+
+from core import protocol, receiver
+from core.tests.responder_harness import B, Initiator, Machine, entry, wait_for
+
+
+class ReceiverBacklogTests(unittest.TestCase):
+ def owner(self):
+ machine = Machine([entry(B, "Driver")]).start()
+ self.addCleanup(machine.stop)
+ link = Initiator(machine, B)
+ self.addCleanup(link.close)
+ link.handshake()
+ route = link.take()
+ self.assertEqual(link.answer(route)[0], protocol.MSG_ACCEPT)
+ return machine, link
+
+ def test_1000_hz_motion_stays_current_with_a_slow_injector(self):
+ self.load(drag=False)
+
+ def test_1000_hz_drag_stays_current_and_releases_the_button(self):
+ self.load(drag=True)
+
+ def load(self, drag):
+ machine, link = self.owner()
+ if drag:
+ pressed = link.input({"type": "mousedown", "data": {"button": "left"}})
+ self.assertIsNotNone(link.acked(pressed))
+ first_seq = link.seq + 1
+ last_seq = link.seq + 400
+ original = machine.injector.inject_mouse_move
+ completed, sent = [], {}
+ dispatch = machine.responder._dispatch
+ peak_pending = 0
+
+ def slow(dx, dy):
+ time.sleep(0.004)
+ original(dx, dy)
+
+ def measured(inbound, message):
+ dispatch(inbound, message)
+ read = protocol.read_input(message)
+ if read is not None and read["type"] == protocol.MSG_MOUSEMOVE:
+ completed.append((read["seq"], time.monotonic()))
+
+ machine.injector.inject_mouse_move = slow
+ machine.responder._dispatch = measured
+ started = time.monotonic()
+ for index in range(400):
+ deadline = started + index / 1000
+ time.sleep(max(0, deadline - time.monotonic()))
+ sent[index + first_seq] = time.monotonic()
+ link.move(1, 0)
+ highest = completed[-1][0] if completed else first_seq - 1
+ peak_pending = max(peak_pending, index + first_seq - highest)
+ sending_seconds = time.monotonic() - started
+ self.assertIsNotNone(link.acked(last_seq, timeout=8))
+ self.assertTrue(wait_for(lambda: completed and completed[-1][0] == last_seq))
+ delays = sorted(done - sent[seq] for seq, done in completed)
+ moves = [call for call in machine.injected() if call[0] == "move"]
+ metrics = {
+ "motion_hz": 1000, "events": 400, "injector_delay_ms": 4, "drag": drag,
+ "sending_ms": round(sending_seconds * 1000, 2),
+ "native_calls": len(moves), "peak_pending_input_samples": peak_pending,
+ "latency_p95_ms": round(delays[int((len(delays) - 1) * .95)] * 1000, 2),
+ "latency_max_ms": round(max(delays) * 1000, 2),
+ "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)
+ 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(peak_pending, 100, metrics)
+ self.assertLess(len(moves), 200, metrics)
+
+ def test_pending_moves_merge_without_crossing_input_or_focus_barriers(self):
+ machine, link = self.owner()
+ entered, release = threading.Event(), threading.Event()
+ original = machine.injector.inject_mouse_move
+
+ def blocked(dx, dy):
+ if not entered.is_set():
+ entered.set()
+ release.wait(3)
+ original(dx, dy)
+
+ machine.injector.inject_mouse_move = blocked
+ self.addCleanup(release.set)
+ link.move(1, 0)
+ self.assertTrue(entered.wait(1))
+ link.move(2, 0)
+ link.move(4, 0)
+ link.input({"type": "mousedown", "data": {"button": "left"}})
+ link.move(3, 2)
+ link.move(5, 4)
+ link.input(protocol.scroll_msg(2, -1))
+ link.key("keydown", "a")
+ link.move(-2, 1)
+ link.move(-3, 2)
+ link.key("keyup", "a")
+ link.input({"type": "mouseup", "data": {"button": "left"}})
+ last = link.move(20, 30)
+ # The blocked native call must not also stop frame receipt.
+ inbound = machine.responder._links[B]
+ self.assertTrue(wait_for(lambda: inbound.inbox and
+ inbound.inbox[-1][0].get("type") == "mousedown", 1))
+ self.assertLess(inbound.dealt, last)
+ release.set()
+ self.assertIsNotNone(link.acked(last))
+ link.let_go()
+ dropped = link.move(20, 30)
+ self.assertIsNotNone(link.acked(dropped))
+ calls = machine.injected()
+ self.assertEqual(calls[:2], [("move", 1, 0), ("move", 6, 0)])
+ grouped = []
+ for moves, group in itertools.groupby(calls, key=lambda call: call[0] == "move"):
+ values = list(group)
+ if moves:
+ grouped.append(("move", sum(call[1] for call in values), sum(call[2] for call in values)))
+ else:
+ grouped.extend(values)
+ self.assertEqual(grouped, [
+ ("move", 7, 0), ("button", "left", True),
+ ("move", 8, 6), ("scroll", 2, -1, "line"), ("key", "a", True),
+ ("move", -5, 3), ("key", "a", False), ("button", "left", False), ("move", 20, 30),
+ ])
+
+ def test_focus_then_large_clipboard_uses_ordered_ownership(self):
+ machine, link = self.owner()
+ link.let_go()
+ self.assertTrue(wait_for(lambda: not machine.responder.driven))
+ entered, release = threading.Event(), threading.Event()
+ focus = machine.responder._on_focus
+
+ def delayed(inbound, message):
+ entered.set()
+ release.wait(2)
+ focus(inbound, message)
+
+ machine.responder._on_focus = delayed
+ self.addCleanup(release.set)
+ route = link.take()
+ self.assertTrue(entered.wait(1))
+ text = "x" * (protocol.SMALL_MESSAGE_BYTES + 1)
+ message = protocol.clipboard_msg(text)
+ self.assertGreater(len(protocol.dumps_message(message)), protocol.SMALL_MESSAGE_BYTES)
+ link.send(message)
+ release.set()
+ self.assertEqual(link.answer(route)[0], protocol.MSG_ACCEPT)
+ self.assertTrue(wait_for(lambda: (text, None) in machine.clipboard.set_calls))
+
+ def test_half_close_drains_motion_and_key_releases_before_cleanup(self):
+ machine, link = self.owner()
+ entered, release = threading.Event(), threading.Event()
+ original = machine.injector.inject_mouse_move
+
+ def blocked(dx, dy):
+ if not entered.is_set():
+ entered.set()
+ release.wait(2)
+ original(dx, dy)
+
+ machine.injector.inject_mouse_move = blocked
+ self.addCleanup(release.set)
+ link.move(1, 0)
+ self.assertTrue(entered.wait(1))
+ link.move(2, 0)
+ link.move(3, 0)
+ link.key("keydown", "a")
+ link.key("keyup", "a")
+ link.sock.shutdown(socket.SHUT_WR)
+ inbound = machine.responder._links[B]
+ self.assertTrue(wait_for(lambda: inbound.inbox and
+ inbound.inbox[-1][0].get("type") == "keydown"))
+ release.set()
+ self.assertTrue(wait_for(lambda: machine.links and machine.links[-1] == (B, False)))
+ self.assertEqual(machine.injected(), [
+ ("move", 1, 0), ("move", 5, 0), ("key", "a", True), ("key", "a", False),
+ ])
+ self.assertFalse(machine.responder.driven)
+
+ def test_close_while_the_reader_waits_for_focus_ends_both_threads(self):
+ machine, link = self.owner()
+ entered, release, reader_done = threading.Event(), threading.Event(), threading.Event()
+ focus = machine.responder._on_focus
+ read_ahead = machine.responder._read_ahead
+
+ def delayed(inbound, message):
+ entered.set()
+ release.wait(2)
+ focus(inbound, message)
+
+ def read(inbound):
+ try:
+ read_ahead(inbound)
+ finally:
+ reader_done.set()
+
+ # A replacement connection lets this test observe its exact reader's lifetime.
+ machine.responder._on_focus = delayed
+ machine.responder._read_ahead = read
+ self.addCleanup(release.set)
+ replacement = Initiator(machine, B)
+ self.addCleanup(replacement.close)
+ replacement.handshake()
+ self.assertTrue(wait_for(lambda: machine.responder._links.get(B) is not None and
+ machine.responder._links[B].sock.getpeername() == replacement.sock.getsockname()))
+ inbound = machine.responder._links[B]
+ replacement.take()
+ self.assertTrue(entered.wait(1))
+ inbound.close()
+ self.assertTrue(reader_done.wait(1))
+ release.set()
+ self.assertTrue(wait_for(lambda: not machine.responder.links()))
+ self.assertFalse(machine.responder.driven)
+
+
+class InboxTests(unittest.TestCase):
+ def setUp(self):
+ left, right = socket.socketpair()
+ self.addCleanup(left.close)
+ self.addCleanup(right.close)
+ self.link = receiver._Link(left, None, B, None, "127.0.0.1", "Driver", [], None, [], True)
+ self.addCleanup(self.link.close)
+
+ def moves(self, values):
+ for dx, dy, seq in values:
+ self.assertTrue(self.link.receive(protocol.mousemove_msg(dx, dy, seq), 80))
+ return [(read["dx"], read["dy"], read["seq"])
+ for read in (protocol.read_input(item[0]) for item in self.link.inbox)]
+
+ def test_relative_travel_is_preserved_with_the_latest_sequence(self):
+ self.assertEqual(self.moves([(2, 0, 1), (3, 0, 2), (4, 0, 3)]), [(9, 0, 3)])
+
+ def test_reversals_and_axis_changes_do_not_create_or_erase_edge_pushes(self):
+ self.assertEqual(self.moves([(120, 0, 1), (0, 120, 2), (0, -120, 3)]),
+ [(120, 0, 1), (0, 120, 2), (0, -120, 3)])
+
+ def test_delta_overflow_and_decreasing_sequences_stay_separate(self):
+ self.assertEqual(self.moves([(65535, 0, 2), (1, 0, 3), (2, 0, 1)]),
+ [(65535, 0, 2), (1, 0, 3), (2, 0, 1)])
+
+ def test_both_queue_limits_block_and_close_wakes_the_reader(self):
+ for cap, value in (("INBOX_LIMIT", 1), ("INBOX_BYTES", 100)):
+ with self.subTest(cap=cap), mock.patch.object(receiver, cap, value):
+ self.link.closed.clear()
+ self.link.inbox.clear()
+ self.link.inbox_bytes = 0
+ self.link.receive(protocol.mousemove_msg(1, 0, 1), 80)
+ result = []
+ entered = threading.Event()
+
+ def receive():
+ entered.set()
+ result.append(self.link.receive(protocol.mousemove_msg(-1, 0, 2), 80))
+
+ reader = threading.Thread(target=receive)
+ reader.start()
+ self.assertTrue(entered.wait(1))
+ reader.join(.03)
+ self.assertTrue(reader.is_alive())
+ self.assertEqual(len(self.link.inbox), 1)
+ self.link.close()
+ reader.join(1)
+ self.assertFalse(reader.is_alive())
+ self.assertEqual(result, [False])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_rel1510_input.py b/core/tests/test_rel1510_input.py
new file mode 100644
index 0000000..e26d273
--- /dev/null
+++ b/core/tests/test_rel1510_input.py
@@ -0,0 +1,193 @@
+"""Input regressions found by the independent 1.5.10 candidate review."""
+
+import sys
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+from core.tests import test_linux_accents as accents
+from core.tests import test_windows_accent_releases as windows
+
+capture_win = windows.capture_win
+
+
+class BackendPolicyTests(unittest.TestCase):
+ def test_saved_mouse_only_applies_only_to_a_supported_backend(self):
+ for supported in (False, True):
+ with self.subTest(supported=supported):
+ config = SimpleNamespace(mouse_only=True)
+ link = accents.sender.LinkSender(None, lambda: {},
+ mouse_only_supported=supported,
+ links=lambda _: SimpleNamespace(live=lambda peer: True))
+ link.refresh = lambda: None
+ link.update_config(config)
+ link._owner = accents.owner.Owner(bytes(range(16)), lambda: 0)
+ link._owner.on = bytes(range(16, 32))
+ self.assertTrue(config.mouse_only, "The saved X11 preference must survive a Wayland session")
+ self.assertEqual(link._ignore_gate.mouse_only, supported)
+ self.assertEqual(link.on_key("enter", True, 28), not supported)
+ self.assertEqual(link.on_key("enter", False, 28), not supported)
+ messages = accents.AccentTests.messages(link)
+ self.assertEqual([(m["type"], m.get("key")) for m in messages],
+ [] if supported else [("keydown", "enter"), ("keyup", "enter")])
+
+
+class RetainedModifierTests(unittest.TestCase):
+ def test_linux_windows_chords_preserve_remote_modifiers_in_either_order(self):
+ for name, vk in (("alt", 0xa4), ("cmd", 0xa2), ("shift", 0xa0)):
+ for modifier_first in (False, True):
+ with self.subTest(modifier=name, modifier_first=modifier_first), patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ link._peers[link._owner.on] = {"platform": "linux"}
+ keys = [(name, vk), ("ctrl", 0x5b)]
+ if not modifier_first:
+ keys.reverse()
+ for key, code in keys:
+ link.on_key(key, True, code)
+ link.on_key("s", True, 0x53)
+ link.on_key("s", False, 0x53)
+ for key, code in reversed(keys):
+ link.on_key(key, False, code)
+ messages = accents.AccentTests.messages(link)
+ self.assertFalse(any(m.get("key") == "spotlight" for m in messages))
+ self.assertEqual([(m["type"], m.get("key")) for m in messages if m.get("key") == "s"],
+ [("keydown", "s"), ("keyup", "s")])
+ self.assertEqual(link._owner.pressed_keys, frozenset())
+ self.assertEqual(link._intent_windows_up, set())
+ self.assertEqual(link._intent_keys_up, set())
+
+ def test_buffered_windows_key_is_cancelled_on_return_home(self):
+ with patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ peer = link._owner.on
+ link._peers[peer] = {"platform": "macos"}
+ self.assertTrue(link.on_key("cmd", True, 0x5b))
+ self.assertTrue(link.set_redirecting(False))
+ link.on_key("cmd", False, 0x5b)
+ accents.AccentTests.messages(link)
+ link._owner.on = peer
+ link.on_key("s", True, 0x53)
+ link.on_key("s", False, 0x53)
+ self.assertEqual([(m["type"], m.get("key")) for m in accents.AccentTests.messages(link)],
+ [("keydown", "s"), ("keyup", "s")])
+ self.assertIsNone(link._pending_windows_key)
+ self.assertEqual(link._intent_windows_up, set())
+ link.on_key("cmd", True, 0x5b)
+ link.on_key("cmd", False, 0x5b)
+ self.assertEqual([m["type"] for m in accents.AccentTests.messages(link)],
+ ["keydown", "keyup"])
+
+ def test_cancelled_windows_release_cleans_intent_even_with_mouse_only_on(self):
+ with patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ peer = link._owner.on
+ link._peers[peer] = {"platform": "macos"}
+ link.on_key("cmd", True, 0x5b)
+ link.set_redirecting(False)
+ accents.AccentTests.messages(link)
+ link._owner.on = peer
+ link._ignore_gate.configure([], mouse_only=True)
+ link.on_key("cmd", False, 0x5b)
+ self.assertIsNone(link._pending_windows_key)
+ self.assertEqual(link._intent_windows_up, set())
+ link._ignore_gate.configure([], mouse_only=False)
+ link.on_key("s", True, 0x53)
+ link.on_key("s", False, 0x53)
+ self.assertEqual([(m["type"], m.get("key")) for m in accents.AccentTests.messages(link)],
+ [("keydown", "s"), ("keyup", "s")])
+
+ def test_home_windows_hold_never_activates_remote_intent_after_crossing(self):
+ with patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ peer = link._owner.on
+ link._peers[peer] = {"platform": "macos"}
+ link._owner.on = None
+ link._ignore_gate.configure([], mouse_only=True)
+ self.assertFalse(link.on_key("cmd", True, 0x5b))
+ link._owner.on = peer
+ link._ignore_gate.configure([], mouse_only=False)
+ link.on_key("s", True, 0x53)
+ link.on_key("s", False, 0x53)
+ self.assertFalse(link.on_key("cmd", False, 0x5b))
+ self.assertEqual([(m["type"], m.get("key")) for m in accents.AccentTests.messages(link)],
+ [("keydown", "s"), ("keyup", "s")])
+ self.assertEqual(link._intent_windows_up, set())
+ self.assertEqual(link._intent_keys_up, set())
+
+ def test_home_ctrl_hold_does_not_cancel_remote_intent_after_crossing(self):
+ with patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ peer = link._owner.on
+ link._peers[peer] = {"platform": "macos"}
+ link._owner.on = None
+ self.assertFalse(link.on_key("ctrl", True, 0xa2))
+ link._owner.on = peer
+ link.on_key("cmd", True, 0x5b)
+ link.on_key("s", True, 0x53)
+ link.on_key("s", False, 0x53)
+ link.on_key("cmd", False, 0x5b)
+ self.assertFalse(link.on_key("ctrl", False, 0xa2))
+ self.assertEqual([(m["type"], m.get("key")) for m in accents.AccentTests.messages(link)],
+ [("keydown", "spotlight"), ("keyup", "spotlight")])
+
+ def test_retained_windows_key_never_activates_remote_intent(self):
+ for retained in (0x5b, 0x5c):
+ with self.subTest(retained=retained), patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ link._peers[link._owner.on] = {"platform": "macos"}
+ link._ignore_gate.configure([], mouse_only=True)
+ self.assertFalse(link.on_key("cmd", True, retained))
+ link._ignore_gate.configure([], mouse_only=False)
+ self.assertTrue(link.on_key("s", True, 0x53))
+ self.assertTrue(link.on_key("s", False, 0x53))
+ self.assertFalse(link.on_key("cmd", False, retained))
+ self.assertEqual([(m["type"], m.get("key")) for m in accents.AccentTests.messages(link)],
+ [("keydown", "s"), ("keyup", "s")])
+ self.assertEqual(link._intent_windows_up, set())
+ self.assertEqual(link._intent_keys_up, set())
+ link.on_key("cmd", True, retained)
+ link.on_key("cmd", False, retained)
+ self.assertEqual([m["type"] for m in accents.AccentTests.messages(link)],
+ ["keydown", "keyup"])
+
+ def test_retained_ctrl_does_not_cancel_a_remote_windows_shortcut(self):
+ with patch.object(sys, "platform", "win32"):
+ link = accents.AccentTests.link_sender()
+ link._peers[link._owner.on] = {"platform": "macos"}
+ link._ignore_gate.configure([], mouse_only=True)
+ self.assertFalse(link.on_key("ctrl", True, 0xa2))
+ link._ignore_gate.configure([], mouse_only=False)
+ link.on_key("cmd", True, 0x5b)
+ link.on_key("s", True, 0x53)
+ link.on_key("s", False, 0x53)
+ link.on_key("cmd", False, 0x5b)
+ self.assertFalse(link.on_key("ctrl", False, 0xa2))
+ self.assertEqual([(m["type"], m.get("key")) for m in accents.AccentTests.messages(link)],
+ [("keydown", "spotlight"), ("keyup", "spotlight")])
+ self.assertEqual(link._intent_windows_up, set())
+ self.assertEqual(link._intent_keys_up, set())
+
+
+class AccentSpaceTests(unittest.TestCase):
+ def test_altgr_dead_accent_space_is_text_with_balanced_modifiers(self):
+ hook = windows.WindowsReleaseTests()
+ hook.setUp()
+ self.addCleanup(hook.doCleanups)
+ hook.translate = lambda vk, scan, modifiers: capture_win.DeadKey("~")
+ hook.feed(0xa5, True)
+ hook.feed(0xde, True)
+ hook.feed(0xde, False)
+ hook.feed(0x20, True)
+ hook.feed(0x20, False)
+ hook.feed(0xa5, False)
+ messages = hook.messages()
+ self.assertEqual([(m["type"], m.get("key"), m.get("text")) for m in messages],
+ [("keydown", "alt_r", None), ("keyup", "alt_r", None),
+ ("text", None, "~"), ("keydown", "alt_r", None),
+ ("keyup", "alt_r", None)])
+ self.assertEqual(hook.sender._keys_down, {})
+ self.assertEqual(hook.hooks._text_keyups_swallowed, set())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_rel1510b_geometry.py b/core/tests/test_rel1510b_geometry.py
new file mode 100644
index 0000000..596d400
--- /dev/null
+++ b/core/tests/test_rel1510b_geometry.py
@@ -0,0 +1,72 @@
+"""Queued motion must retain the crossing decisions made by individual samples."""
+
+import unittest
+from types import SimpleNamespace
+
+from core import protocol, receiver, return_edge
+from core.tests.responder_harness import B, HERE, FakeDesktop, Machine, entry
+
+
+class ReceiverQueuedGeometryTests(unittest.TestCase):
+ def deliver(self, moves, pointer, model, queued):
+ desktop = FakeDesktop(cursor=pointer)
+ machine = Machine([entry(B, "Driver")], desktop=desktop)
+ link = receiver._Link(
+ SimpleNamespace(shutdown=lambda _how: None), None, B, None,
+ "127.0.0.1", "Driver", [], HERE, [], True,
+ )
+ responder = machine.responder
+ responder._owner = link
+ responder._armed = [(B, model)]
+ responder._zones_live = True
+ original = machine.injector.inject_mouse_move
+
+ def move_pointer(dx, dy):
+ original(dx, dy)
+ x, y = desktop.cursor
+ bounds = desktop.monitors()[0]
+ desktop.cursor = (
+ min(bounds.right, max(bounds.x, x + dx)),
+ min(bounds.bottom, max(bounds.y, y + dy)),
+ )
+
+ machine.injector.inject_mouse_move = move_pointer
+ messages = [protocol.mousemove_msg(dx, dy, seq)
+ for seq, (dx, dy) in enumerate(moves, 1)]
+ if queued:
+ for message in messages:
+ link.receive(message, len(protocol.dumps_message(message)))
+ messages = [item[0] for item in link.inbox]
+ for message in messages:
+ responder._dispatch(link, message)
+ switches = [message for message in link.outbox
+ if message.get("type") == protocol.MSG_SWITCH]
+ return desktop.cursor, len(switches)
+
+ def test_queued_diagonal_motion_does_not_cross_after_leaving_selected_part(self):
+ def run(queued):
+ return self.deliver(
+ [(1, 4), (200, 1)], (1919, 358),
+ return_edge.PartEdge("right", ["start"], resistance_px=120, clock=lambda: 0),
+ queued,
+ )
+
+ direct = run(False)
+ self.assertEqual(direct, ((1919, 363), 0))
+ self.assertEqual(run(True), direct)
+
+ def test_queued_diagonal_motion_keeps_corner_push_pressure(self):
+ def run(queued):
+ return self.deliver(
+ [(119, 1), (1, 119)], (1919, 1079),
+ return_edge.CornerPush("bottom_right", "right", resistance_px=200, clock=lambda: 0),
+ queued,
+ )
+
+ direct = run(False)
+ self.assertEqual(direct, ((1919, 1079), 1))
+ self.assertEqual(run(True), direct)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_responder_input.py b/core/tests/test_responder_input.py
index 77d0be6..7e59718 100644
--- a/core/tests/test_responder_input.py
+++ b/core/tests/test_responder_input.py
@@ -83,6 +83,18 @@ class Acks(Case):
class Liveness(Case):
+ def test_fast_overlapping_typing_arrives_in_order_without_missing_keys(self):
+ link = self.owner()
+ expected = []
+ for _ in range(100):
+ for name, down in (("shift", True), ("a", True), ("b", True), ("a", False),
+ ("b", False), ("shift", False), ("o", True), ("o", True),
+ ("o", False), ("o", True), ("o", False)):
+ seq = link.key("keydown" if down else "keyup", name)
+ expected.append(("key", name, down))
+ self.assertIsNotNone(link.acked(seq))
+ self.assertEqual(self.machine.injected(), expected)
+
def test_a_large_frame_arriving_slowly_keeps_the_link(self):
with mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 0.5):
link = self.owner()
diff --git a/core/tests/test_updates.py b/core/tests/test_updates.py
index 02e2b6e..69303fa 100644
--- a/core/tests/test_updates.py
+++ b/core/tests/test_updates.py
@@ -10,9 +10,9 @@ def release(tag, **extra):
class NewerReleaseTests(unittest.TestCase):
- def test_a_patch_release_is_quiet_unless_its_notes_announce_it(self):
- self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.1", body="Small fixes.")))
- self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.1")))
+ def test_every_newer_stable_patch_is_offered(self):
+ self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1", body="Small fixes.")))
+ self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1")))
self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1", body="Fixes a crash.\n<!-- announce -->")))
def test_a_quiet_patch_still_offers_the_minor_version_someone_is_behind(self):
@@ -29,7 +29,9 @@ class NewerReleaseTests(unittest.TestCase):
def test_versions_compare_as_numbers(self):
self.assertIsNotNone(updates.newer_release("1.9.0", release("v1.10.0")))
- self.assertIsNone(updates.newer_release("1.4", release("v1.4.1")))
+ self.assertIsNotNone(updates.newer_release("1.4", release("v1.4.1")))
+ self.assertIsNotNone(updates.newer_release("1.5.9", release("v1.5.10")))
+ self.assertIsNone(updates.newer_release("1.5.10", release("v1.5.9")))
def test_drafts_prereleases_and_odd_tags_never_count(self):
self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0", prerelease=True)))
@@ -78,6 +80,20 @@ class BetaTests(unittest.TestCase):
class CheckerTests(unittest.TestCase):
+ def test_switching_off_during_a_request_discards_its_answer(self):
+ enabled = True
+ results = []
+
+ def fetcher():
+ nonlocal enabled
+ enabled = False
+ return json.dumps(release("v1.6.0")).encode()
+
+ checker = updates.Checker("1.5.9", lambda: enabled, results.append, fetcher=fetcher)
+ checker.check_once()
+ self.assertEqual(results, [])
+ self.assertIsNone(checker.latest)
+
def make(self, payload=None, enabled=True, error=None):
results = []
@@ -114,5 +130,18 @@ class CheckerTests(unittest.TestCase):
self.assertEqual(len(results), 1)
+class NoticeTests(unittest.TestCase):
+ def test_dismissal_survives_a_new_check_but_not_a_newer_version(self):
+ found = ("1.5.10", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.10")
+ self.assertEqual(updates.visible_notice(found, True, ""), found)
+ self.assertIsNone(updates.visible_notice(found, True, "1.5.10"))
+ newer = ("1.5.11", updates.RELEASES_PAGE)
+ self.assertEqual(updates.visible_notice(newer, True, "1.5.10"), newer)
+
+ def test_off_setting_hides_a_cached_result_and_none_stays_hidden(self):
+ self.assertIsNone(updates.visible_notice(("1.6.0", updates.RELEASES_PAGE), False, ""))
+ self.assertIsNone(updates.visible_notice(None, True, ""))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/core/tests/test_windows_accent_releases.py b/core/tests/test_windows_accent_releases.py
new file mode 100644
index 0000000..a27a5e0
--- /dev/null
+++ b/core/tests/test_windows_accent_releases.py
@@ -0,0 +1,190 @@
+"""Exercise the real Windows hook and sender without native hooks or GUI imports."""
+
+import ctypes
+from pathlib import Path
+import sys
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "win_app"))
+
+import capture_win
+from core.tests import test_linux_accents as accents
+
+
+class HookData(ctypes.Structure):
+ _fields_ = [("vkCode", ctypes.c_ulong), ("scanCode", ctypes.c_ulong),
+ ("flags", ctypes.c_ulong), ("time", ctypes.c_ulong),
+ ("dwExtraInfo", ctypes.c_size_t)]
+
+
+class HookApi:
+ def CallNextHookEx(self, *args):
+ return 99
+
+
+class WindowsReleaseTests(unittest.TestCase):
+ def setUp(self):
+ self.sender = accents.AccentTests.link_sender()
+ def route(name, down, vk, us):
+ if isinstance(name, capture_win.TextInput):
+ return self.sender.on_text(name.text, vk, down)
+ if isinstance(name, capture_win.DeadKey):
+ return self.sender.on_dead_key(vk, down)
+ return self.sender.on_key(name, down, vk, us)
+ self.hooks = capture_win.Hooks(route, lambda *args: False, lambda *args: None)
+ self.translate = lambda vk, scan, state: "€" if state.get(0x12) else "e"
+ for replacement in (patch.object(capture_win, "KBDLLHOOKSTRUCT", HookData, create=True),
+ patch.object(capture_win, "user32", HookApi()),
+ patch.object(capture_win, "_to_unicode", lambda *args: self.translate(*args))):
+ replacement.start()
+ self.addCleanup(replacement.stop)
+
+ def feed(self, vk, down, scan=0, flags=0):
+ data = HookData(vk, scan, flags, 0, 0)
+ return self.hooks._keyboard_proc(capture_win.HC_ACTION,
+ capture_win.WM_KEYDOWN if down else capture_win.WM_KEYUP,
+ ctypes.byref(data))
+
+ def messages(self):
+ return accents.AccentTests.messages(self.sender)
+
+ def test_ordinary_repeat_cannot_turn_into_altgr_text_and_lose_its_release(self):
+ self.feed(0x45, True, 0x12)
+ self.feed(0xa5, True)
+ self.feed(0x45, True, 0x12)
+ self.feed(0x45, False, 0x12)
+ self.feed(0xa5, False)
+ messages = self.messages()
+ self.assertFalse(any(m["type"] == "text" for m in messages))
+ self.assertEqual([(m["type"], m.get("key")) for m in messages if m.get("key") == "e"],
+ [("keydown", "e"), ("keydown", "e"), ("keyup", "e")])
+ self.assertEqual(self.sender._keys_down, {})
+
+ def test_release_uses_original_press_even_when_new_layout_is_dead_or_unavailable(self):
+ for changed in (capture_win.DeadKey("´"), None, "", "x"):
+ with self.subTest(changed=changed):
+ self.translate = lambda *args: "'"
+ self.feed(0xde, True, 0x28)
+ self.translate = lambda *args: changed
+ self.feed(0xde, False, 0x28)
+ self.assertEqual([(m["type"], m.get("key")) for m in self.messages()],
+ [("keydown", "'"), ("keyup", "'")])
+ self.assertEqual(self.sender._keys_down, {})
+
+ def test_swallowed_dead_release_does_not_depend_on_new_layout(self):
+ self.translate = lambda *args: capture_win.DeadKey("´")
+ self.assertEqual(self.feed(0xde, True), 1)
+ self.translate = lambda *args: None
+ self.assertEqual(self.feed(0xde, False), 1)
+ self.assertEqual(self.hooks._dead_keys_swallowed, set())
+
+ def test_explicit_ctrl_right_alt_shortcut_is_never_text(self):
+ for ctrl in (0xa2, 0xa3):
+ with self.subTest(ctrl=ctrl):
+ self.feed(ctrl, True, 0x1d)
+ self.feed(0xa5, True)
+ self.feed(0x45, True, 0x12)
+ self.feed(0x45, False, 0x12)
+ self.feed(0xa5, False)
+ self.feed(ctrl, False, 0x1d)
+ messages = self.messages()
+ self.assertFalse(any(m["type"] == "text" for m in messages))
+ self.assertEqual([(m["type"], m.get("key")) for m in messages if m.get("key") == "e"],
+ [("keydown", "e"), ("keyup", "e")])
+ self.assertEqual(self.sender._keys_down, {})
+
+ def test_synthetic_altgr_ctrl_does_not_disable_altgr_text(self):
+ self.feed(0xa2, True, 0x21d)
+ self.feed(0xa5, True)
+ self.feed(0x45, True, 0x12)
+ self.feed(0x45, False, 0x12)
+ self.feed(0xa5, False)
+ self.feed(0xa2, False, 0x21d)
+ self.assertEqual([m["text"] for m in self.messages() if m["type"] == "text"], ["€"])
+ self.assertEqual(self.sender._keys_down, {})
+
+ def test_altgr_synthetic_ctrl_release_cannot_release_a_physical_ctrl(self):
+ self.feed(0xa2, True, 0x1d)
+ self.feed(0xa2, True, 0x21d)
+ self.feed(0xa5, True)
+ self.feed(0xa5, False)
+ self.feed(0xa2, False, 0x21d)
+ self.assertIn(0xa2, self.sender._keys_down)
+ self.feed(0xa2, False, 0x1d)
+ messages = self.messages()
+ self.assertEqual([(m["type"], m["key"]) for m in messages if m.get("key") == "ctrl"],
+ [("keydown", "ctrl"), ("keyup", "ctrl")])
+
+ def test_ctrl_during_altgr_text_repeat_stays_a_balanced_shortcut(self):
+ self.feed(0xa5, True)
+ self.feed(0x45, True, 0x12)
+ self.feed(0xa3, True, 0x1d)
+ self.feed(0x45, True, 0x12)
+ self.feed(0x45, False, 0x12)
+ self.feed(0xa3, False, 0x1d)
+ self.feed(0xa5, False)
+ messages = self.messages()
+ self.assertEqual([m["text"] for m in messages if m["type"] == "text"], ["€"])
+ self.assertEqual([(m["type"], m.get("key")) for m in messages if m.get("key") == "e"],
+ [("keydown", "e"), ("keyup", "e")])
+ self.assertEqual(self.sender._keys_down, {})
+
+ def test_pending_dead_accent_cannot_turn_a_ctrl_shortcut_into_text(self):
+ self.translate = lambda vk, *args: capture_win.DeadKey("^") if vk == 0xde else "x"
+ self.feed(0xde, True, 0x28)
+ self.feed(0xde, False, 0x28)
+ self.feed(0xa2, True, 0x1d)
+ self.feed(0x58, True, 0x2d)
+ self.feed(0x58, False, 0x2d)
+ self.feed(0xa2, False, 0x1d)
+ messages = self.messages()
+ self.assertFalse(any(m["type"] == "text" for m in messages))
+ self.assertEqual([(m["type"], m.get("key")) for m in messages if m.get("key") == "x"],
+ [("keydown", "x"), ("keyup", "x")])
+ self.assertEqual(self.sender._keys_down, {})
+
+ def test_text_release_allows_new_ignore_rule_on_the_next_press(self):
+ self.feed(0xa5, True)
+ self.feed(0x45, True, 0x12)
+ self.feed(0x45, False, 0x12)
+ self.feed(0xa5, False)
+ self.messages()
+ self.sender._ignore_gate.configure(["key:69"])
+ self.assertEqual(self.feed(0x45, True, 0x12), 99)
+ self.assertEqual(self.feed(0x45, False, 0x12), 99)
+ self.assertEqual(self.messages(), [])
+
+ def test_dead_release_allows_new_ignore_rule_on_the_next_press(self):
+ self.translate = lambda *args: capture_win.DeadKey("´")
+ self.feed(0xde, True, 0x28)
+ self.feed(0xde, False, 0x28)
+ self.sender._ignore_gate.configure(["key:222"])
+ self.translate = lambda *args: "'"
+ self.assertEqual(self.feed(0xde, True, 0x28), 99)
+ self.assertEqual(self.feed(0xde, False, 0x28), 99)
+ self.assertEqual(self.messages(), [])
+
+ def test_local_altgr_press_keeps_its_release_after_crossing_to_peer(self):
+ self.sender._owner.on = None
+ self.assertEqual(self.feed(0xa5, True), 99)
+ self.assertEqual(self.feed(0x45, True, 0x12), 99)
+ self.sender._owner.on = bytes(range(16, 32))
+ self.assertEqual(self.feed(0x45, True, 0x12), 99)
+ self.assertEqual(self.feed(0x45, False, 0x12), 99)
+ self.feed(0xa5, False)
+ self.assertFalse(any(m["type"] == "text" for m in self.messages()))
+
+ def test_local_dead_press_keeps_its_release_after_layout_and_owner_change(self):
+ self.sender._owner.on = None
+ self.translate = lambda *args: capture_win.DeadKey("´")
+ self.assertEqual(self.feed(0xde, True, 0x28), 99)
+ self.sender._owner.on = bytes(range(16, 32))
+ self.translate = lambda *args: "'"
+ self.assertEqual(self.feed(0xde, True, 0x28), 99)
+ self.assertEqual(self.feed(0xde, False, 0x28), 99)
+ self.assertEqual(self.messages(), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_windows_tools.py b/core/tests/test_windows_tools.py
new file mode 100644
index 0000000..0a4f8d9
--- /dev/null
+++ b/core/tests/test_windows_tools.py
@@ -0,0 +1,42 @@
+import subprocess
+import sys
+import unittest
+
+from core import windows_tools
+
+
+class WindowsToolOutputTests(unittest.TestCase):
+ def test_oem_and_ansi_are_decoded_with_the_callers_encoding(self):
+ self.assertEqual(windows_tools.decode_output(b"\x90lodie", "cp850"), "Élodie")
+ self.assertEqual(windows_tools.decode_output(b"Jos\xe9", "cp1252"), "José")
+
+ def test_bom_overrides_the_legacy_encoding(self):
+ for encoding in ("utf-8-sig", "utf-16", "utf-16-be"):
+ text = "Élodie: C:\\Users\\José"
+ data = text.encode(encoding)
+ if encoding == "utf-16-be":
+ data = b"\xfe\xff" + data
+ with self.subTest(encoding=encoding):
+ self.assertEqual(windows_tools.decode_output(data, "cp850"), text)
+
+ def test_xml_declaration_does_not_override_the_actual_pipe_encoding(self):
+ self.assertEqual(
+ windows_tools.decode_output(b'<?xml version="1.0" encoding="UTF-16"?><User>\x90lodie</User>', "cp850"),
+ '<?xml version="1.0" encoding="UTF-16"?><User>Élodie</User>',
+ )
+
+ def test_invalid_bytes_are_replaced_and_line_endings_are_normalised(self):
+ self.assertEqual(windows_tools.decode_output(b"invalid \x90\r\nnext\rlast", "cp1252"), "invalid \ufffd\nnext\nlast")
+
+ def test_real_pipe_captures_both_streams_without_losing_exit_status(self):
+ result = windows_tools.run([
+ sys.executable, "-c",
+ "import os; os.write(1, b'\\x90lodie\\r\\n'); os.write(2, b'acc\\x8as refus\\x82'); raise SystemExit(7)",
+ ], encoding="cp850", timeout=5)
+ self.assertEqual(result.stdout, "Élodie\n")
+ self.assertEqual(result.stderr, "accès refusé")
+ self.assertEqual(result.returncode, 7)
+
+ def test_timeout_still_reaches_the_caller(self):
+ with self.assertRaises(subprocess.TimeoutExpired):
+ windows_tools.run([sys.executable, "-c", "import time; time.sleep(5)"], timeout=0.05)
diff --git a/core/updates.py b/core/updates.py
index a4788fe..36fbea2 100644
--- a/core/updates.py
+++ b/core/updates.py
@@ -39,16 +39,11 @@ def parse_version(text):
return parsed[0] if parsed else None
-# In a release's notes, where GitHub renders nothing, it offers a patch release as an update too.
-ANNOUNCE = "<!-- announce -->"
-
-
def newer_release(current, payload):
"""(version text, page url) when `payload`, the API's JSON, names a release worth offering over
- `current`, else None. A new minor or major version always is; a patch release (1.4.0 to 1.4.1)
- only when its notes carry ANNOUNCE, so frequent small releases do not nag. Drafts and
+ `current`, else None. Every newer stable version counts, including patch releases. Drafts and
prereleases never count, nor does a tag that names a beta. A beta install is offered its own
- release (1.5.0-beta.1 to 1.5.0) and anything newer without the announce, never an older one."""
+ release (1.5.0-beta.1 to 1.5.0) and anything newer, never an older one."""
if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"):
return None
tag = payload.get("tag_name")
@@ -58,15 +53,17 @@ def newer_release(current, payload):
theirs, (ours, beta) = theirs[0], ours
if theirs < ours or (theirs == ours and not beta):
return None
- body = payload.get("body")
- if not beta and theirs[:2] == ours[:2] and not (isinstance(body, str) and ANNOUNCE in body):
- return None
url = payload.get("html_url")
if not isinstance(url, str) or not url.startswith("https://github.com/kalkman-code/beamer/"):
url = RELEASES_PAGE
return (str(tag).lstrip("v"), url)
+def visible_notice(found, enabled, dismissed):
+ """Dismissal is local to one version; the off setting also hides cached answers."""
+ return found if enabled and found and found[0] != dismissed else None
+
+
def fetch(url=LATEST_URL):
"""The response body as bytes. The Mac goes through Foundation, which trusts the system's
certificates; a bundled Python has no certificate store of its own there."""
@@ -129,6 +126,8 @@ class Checker:
self._failed = True
return
self._failed = False
+ if not self.enabled() or self._stop.is_set():
+ return
self.latest = newer_release(self.current, payload)
if self.latest:
self.logger.info("Beamer %s is available", self.latest[0])
diff --git a/core/windows_tools.py b/core/windows_tools.py
new file mode 100644
index 0000000..090e2d8
--- /dev/null
+++ b/core/windows_tools.py
@@ -0,0 +1,27 @@
+"""Decode Windows tool pipes after capture, outside subprocess's reader threads."""
+
+import codecs
+import os
+import subprocess
+
+
+def decode_output(data: bytes, encoding: str = "oem") -> str:
+ # schtasks declares UTF-16 even when its redirected pipe contains OEM bytes.
+ # Only a byte-order mark overrides the caller's knowledge of the tool.
+ if data.startswith(codecs.BOM_UTF8):
+ encoding = "utf-8-sig"
+ elif data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
+ encoding = "utf-16"
+ elif encoding in ("oem", "mbcs") and os.name != "nt":
+ encoding = "utf-8"
+ return data.decode(encoding, errors="replace").replace("\r\n", "\n").replace("\r", "\n")
+
+
+def run(args: list, *, encoding: str = "oem", timeout=None, startupinfo=None) -> subprocess.CompletedProcess:
+ result = subprocess.run(
+ args, capture_output=True, timeout=timeout, startupinfo=startupinfo,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ result.stdout = decode_output(result.stdout, encoding)
+ result.stderr = decode_output(result.stderr, encoding)
+ return result
diff --git a/core/wol.py b/core/wol.py
index 670c569..43acea4 100644
--- a/core/wol.py
+++ b/core/wol.py
@@ -12,6 +12,8 @@ import socket
import subprocess
import sys
+from core import windows_tools
+
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.
@@ -54,14 +56,13 @@ def lookup_mac(host: str):
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,
- )
+ if windows:
+ completed = windows_tools.run(["arp", "-a", ip], timeout=3.0)
+ else:
+ completed = subprocess.run(
+ ["arp", "-n", ip], capture_output=True, text=True, timeout=3.0, check=False,
+ creationflags=0,
+ )
except (OSError, subprocess.SubprocessError):
return None
return mac_from_arp_output(completed.stdout, ip)
diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xml
index 876cee9..b4cc078 100644
--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml
+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml
@@ -43,8 +43,11 @@
</screenshots>
<content_rating type="oars-1.1"/>
<releases>
+ <release version="1.5.9" date="2026-10-21">
+ <description><p>Reduces mouse input building up on a slow receiver by reading ahead and combining waiting horizontal or vertical movement. Total travel and the order of buttons, keys and scrolling are preserved. Diagonal moves, reversals and axis changes stay separate to preserve crossing zones.</p><p>Improves clipboard reliability around switching machines, including brief retries when the clipboard is busy. Adds a visible notice for newer stable updates, with What's new and a per-version Dismiss button. Flatpak users get store update guidance. Linux builds now check GitHub for new versions too; turn off Check for updates in Settings to stop it. Nothing downloads or installs automatically.</p><p>Adds a Mouse only switch on macOS, Windows and Linux X11 to keep the keyboard on the machine you are using while sharing the mouse and clipboard. This switch is unavailable on Wayland.</p><p>Improves Windows-to-Linux accent handling by reading the foreground Windows app's layout, preserving printable AltGr output and trying Linux AltGr levels and supported single-accent dead-key sequences. Wayland still cannot type characters outside these supported layout paths.</p><p>Includes the missing library for generating pairing QR codes in Linux Flatpak builds. The README and bug-report form now list the Linux log locations.</p><p>Adds Identify screens on the Crossing page, showing numbers on local and directly linked desktop displays for three seconds. Machines on older versions are left out.</p><p>On Windows, Beamer no longer crashes at startup when the account name has an accented letter, such as É; thanks to kinowill for tracking it down.</p><p>While machines are linked, Beamer's log now summarises connection timings about every 30 seconds and tries to add a final summary when a connection ends: how long each machine spends queueing, sending, reading and applying input and scheduling its acknowledgement, and which addresses each connection uses. These lines hold times, counts and addresses only, not keys, text or pointer positions.</p></description>
+ </release>
<release version="1.5.8" date="2026-10-20">
- <description><p>The Windows installer and Beamer.exe are now signed with a Certum code-signing certificate, so Windows no longer shows an unknown publisher. Nothing else changes from 1.5.7.</p></description>
+ <description><p>The Windows installer and Beamer.exe are now signed with a Certum code-signing certificate, so Windows shows the publisher's name; SmartScreen may still warn until the certificate builds a reputation. Nothing else changes from 1.5.7.</p></description>
</release>
<release version="1.5.7" date="2026-10-20">
<description><p>Keeps the address you chose for a machine after reconnects and restarts, instead of replacing it with a discovered or incoming one.</p></description>
diff --git a/locales/beamer.pot b/locales/beamer.pot
index 0483dde..c0faf6d 100644
--- a/locales/beamer.pot
+++ b/locales/beamer.pot
@@ -1609,6 +1609,14 @@ msgstr ""
msgid "Idle"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "What's new"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Dismiss"
+msgstr ""
+
#: mac_app/kvm_bridge_app.py mac_app/machines.py mac_app/machines_panel.py mac_app/widgets.py win_app/crossing_ledger.py win_app/peers_view.py
msgid "Mac"
msgstr ""
@@ -1653,6 +1661,10 @@ msgstr ""
msgid "Download"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Mouse only"
+msgstr ""
+
#: mac_app/kvm_bridge_app.py
msgid "Reverse other machines' scrolling"
msgstr ""
@@ -1697,6 +1709,14 @@ msgstr ""
msgid "Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept."
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Identify screens"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Show these numbers on every linked machine's screens for 3 seconds."
+msgstr ""
+
#: mac_app/kvm_bridge_app.py
msgid "Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"
msgstr ""
@@ -1945,6 +1965,10 @@ msgstr ""
msgid "Appearance"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Keyboard sharing"
+msgstr ""
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "Another machine's pointer here"
msgstr ""
@@ -2220,6 +2244,10 @@ msgstr ""
msgid "System follows your Mac's light or dark setting."
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Keep this machine's keyboard here. Pointer and clipboard sharing stay on."
+msgstr ""
+
#: mac_app/kvm_bridge_app.py
msgid "Pointer speed for another machine's mouse or trackpad while it drives this Mac."
msgstr ""
@@ -2456,6 +2484,11 @@ msgstr ""
msgid "Download Beamer {version}"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer {version} is available."
+msgstr ""
+
#. {reason} is the system's reason for refusing the login item.
#: mac_app/kvm_bridge_app.py
#, python-brace-format
@@ -4162,6 +4195,10 @@ msgstr ""
msgid "Send input to another machine"
msgstr ""
+#: win_app/identify_overlay.py
+msgid "Beamer — Identify screens"
+msgstr ""
+
#: win_app/kvm_bridge_win.py
msgid "Beamer's website"
msgstr ""
@@ -4543,6 +4580,10 @@ msgstr ""
msgid "This desktop has no system tray, so Beamer's window is all there is: closing it quits Beamer."
msgstr ""
+#: win_app/kvm_bridge_win.py
+msgid "Update through your software store."
+msgstr ""
+
#: win_app/kvm_bridge_win.py
msgid "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
msgstr ""
diff --git a/locales/it.po b/locales/it.po
index 5ee9c4a..bdb6322 100644
--- a/locales/it.po
+++ b/locales/it.po
@@ -1618,6 +1618,14 @@ msgstr "Scorciatoia: {style} {key} ·"
msgid "Idle"
msgstr "Inattivo"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "What's new"
+msgstr "Novità"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Dismiss"
+msgstr "Ignora"
+
#: mac_app/kvm_bridge_app.py mac_app/machines.py mac_app/machines_panel.py mac_app/widgets.py win_app/crossing_ledger.py win_app/peers_view.py
msgid "Mac"
msgstr "Mac"
@@ -1662,6 +1670,10 @@ msgstr "Controlla aggiornamenti"
msgid "Download"
msgstr "Scarica"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Mouse only"
+msgstr "Solo mouse"
+
#: mac_app/kvm_bridge_app.py
msgid "Reverse other machines' scrolling"
msgstr "Inverti lo scorrimento degli altri computer"
@@ -1708,6 +1720,14 @@ msgstr "Stesse vie su tutti i computer"
msgid "Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept."
msgstr "Imposta le vie di tutti i computer da questa schermata. Attivarlo non cambia nulla finché non le modifichi; ciascun computer conserva le proprie vie."
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Identify screens"
+msgstr "Identifica gli schermi"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Show these numbers on every linked machine's screens for 3 seconds."
+msgstr "Mostra questi numeri sugli schermi di tutti i computer collegati per 3 secondi."
+
# New in 1.5.5: awaiting Lorenzo's check
#: mac_app/kvm_bridge_app.py
msgid "Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"
@@ -1971,6 +1991,10 @@ msgstr "Nessuno"
msgid "Appearance"
msgstr "Aspetto della finestra"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Keyboard sharing"
+msgstr "Condivisione della tastiera"
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "Another machine's pointer here"
msgstr "Il puntatore di un altro computer qui"
@@ -2263,6 +2287,10 @@ msgstr "Questa finestra"
msgid "System follows your Mac's light or dark setting."
msgstr "Sistema segue l'impostazione chiara o scura del Mac."
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Keep this machine's keyboard here. Pointer and clipboard sharing stay on."
+msgstr "Mantieni la tastiera su questo computer. Il puntatore e gli appunti restano condivisi."
+
#: mac_app/kvm_bridge_app.py
msgid "Pointer speed for another machine's mouse or trackpad while it drives this Mac."
msgstr "Velocità del puntatore per il mouse o il trackpad di un altro computer mentre controlla questo Mac."
@@ -2507,6 +2535,11 @@ msgstr "Disattivato"
msgid "Download Beamer {version}"
msgstr "Scarica Beamer {version}"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer {version} is available."
+msgstr "Beamer {version} è disponibile."
+
#. {reason} is the system's reason for refusing the login item.
#: mac_app/kvm_bridge_app.py
#, python-brace-format
@@ -4224,6 +4257,10 @@ msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer
msgid "Send input to another machine"
msgstr "Invia input a un altro computer"
+#: win_app/identify_overlay.py
+msgid "Beamer — Identify screens"
+msgstr "Beamer — Identifica gli schermi"
+
#: win_app/kvm_bridge_win.py
msgid "Beamer's website"
msgstr "Sito di Beamer"
@@ -4611,6 +4648,10 @@ msgstr "Se disattivato, chiudere la finestra chiude Beamer. Apri di nuovo Beamer
msgid "This desktop has no system tray, so Beamer's window is all there is: closing it quits Beamer."
msgstr "Questo desktop non ha un'area di notifica, quindi la finestra di Beamer è tutto ciò che c'è: chiuderla chiude Beamer."
+#: win_app/kvm_bridge_win.py
+msgid "Update through your software store."
+msgstr "Aggiorna tramite il tuo gestore software."
+
#: win_app/kvm_bridge_win.py
msgid "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
msgstr "Si avvia con privilegi elevati all'accesso senza richiesta UAC, così Beamer può inviare input alle app amministratore."
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index 42cfc85..ee56d04 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -30,6 +30,7 @@ from core import crossing_state
from core import profiles
from core import shake
from core import effects
+from core import identify_screens
import frame_clock
import keyboard_layout
import media_keys
@@ -79,7 +80,7 @@ ROUND_TRIP_MAX_AGE_SECONDS = 5.0
# the ownership by force after one second), then goes ahead.
LET_GO_WAIT_SECONDS = 1.3
OWN_PLATFORM = "macos"
-CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt")
+CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt", "identify_screens")
MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause", "brightness_up", "brightness_down"})
# Why input came home, in words, for the alert. A why that is not here comes home quietly.
@@ -643,7 +644,7 @@ class KVMController:
self._last_tap_event_at = self.clock()
self._hid_unseen_since = None
self._move_reason = None
- self.ignore_gate = ignored.Gate(cfg.ignored_inputs)
+ self.ignore_gate = ignored.Gate(cfg.ignored_inputs, mouse_only=cfg.mouse_only)
# Crossing: the engine is pure and runs on the event-tap thread; the
# desktop bounds come from CoreGraphics (already in the top-left
# global space CGEventGetLocation uses, so nothing is flipped) and are
@@ -663,6 +664,7 @@ class KVMController:
self.notch_range = None
self.notch_depth = 0.0
self.on_crossing = None
+ self.on_identify_screens = None
self._crossing_failed = False
self._crossing_failed_at = 0.0
self._cursor_read_error_logged = False
@@ -707,6 +709,7 @@ class KVMController:
self._pasteboard_busy = False
self.owner = owner_module.Owner(protocol.id_text(self.identity()["id"]), clock, resistance_px=int(self.crossing.resistance_px))
self._clipboard_stamp = None
+ self._clipboard_written_stamp = None
self._paired_ids = ()
self._go_generation = 0
self._home_notify = True
@@ -931,6 +934,38 @@ class KVMController:
return copy.deepcopy(self.book._load().get("layout", {}).get(
protocol.id_text(self.identity()["id"]), {}).get("displays", {}))
+ def identify_screens(self):
+ self.crossing_displays_changed()
+ with self.book.lock:
+ settings = copy.deepcopy(self.book._load() or {})
+ layout = ways.derive_layout(settings, gap=0)
+ if settings.get("layout_set_at", 0):
+ layout.update(settings.get("layout") or {})
+ own = protocol.id_text(self.identity()["id"])
+ self._show_identify_screens(identify_screens.display_numbers(layout.get(own)))
+ desktops = {entry.get("id") for entry in peerlist.desktops(self.book.peers())}
+ sent = set()
+ for peer, link in list(self._peers_up.items()):
+ if peer in desktops and link.live() and "identify_screens" in link.caps:
+ link.post(protocol.identify_screens_msg(identify_screens.display_numbers(layout.get(peer))))
+ sent.add(peer)
+ if self.responder is not None:
+ for ident in self.responder.links():
+ peer = protocol.id_text(ident)
+ if peer in desktops and peer not in sent and "identify_screens" in (self.responder.caps_of(ident) or ()):
+ self.responder.send(ident, protocol.identify_screens_msg(
+ identify_screens.display_numbers(layout.get(peer))))
+
+ def receive_identify_screens(self, peer, labels):
+ if isinstance(peer, bytes):
+ peer = protocol.id_text(peer)
+ if peer in {entry.get("id") for entry in peerlist.desktops(self.book.peers())}:
+ self._show_identify_screens(labels)
+
+ def _show_identify_screens(self, labels):
+ if self.on_identify_screens is not None:
+ self.on_identify_screens(dict(labels))
+
def crossing_displays_changed(self):
displays = self.crossing_display_map()
if displays == getattr(self, "_crossing_displays", None):
@@ -1242,7 +1277,7 @@ class KVMController:
self.translator.modifier_down.clear()
self.translator.printable_down.clear()
self.translator.reset_mouse_accumulators()
- self.ignore_gate.configure(cfg.ignored_inputs)
+ self.ignore_gate.configure(cfg.ignored_inputs, mouse_only=cfg.mouse_only)
if self._memory is not None:
self._memory.follow(cfg)
self.crossing = self._crossing_engine()
@@ -1274,7 +1309,7 @@ class KVMController:
if "shortcut" not in cfg.crossing.get("methods", ()):
self.last_trigger_down = 0.0
self.trigger_suppressed = False
- self.ignore_gate.configure(cfg.ignored_inputs)
+ self.ignore_gate.configure(cfg.ignored_inputs, mouse_only=cfg.mouse_only)
if self._memory is not None:
self._memory.follow(cfg)
self.crossing = self._crossing_engine()
@@ -2460,6 +2495,7 @@ class KVMController:
if kind == protocol.MSG_SWITCH:
read = protocol.read_switch(message)
if read is not None:
+ self._note_clipboard()
data = {"route": read["route"], "next": protocol.id_text(read["next"]),
"edge": read["edge"], "offset": read["offset"]}
if "taken_over_by" in read:
@@ -2468,7 +2504,8 @@ class KVMController:
elif kind == protocol.MSG_ACCEPT:
read = protocol.read_accept(message)
if read is not None:
- self._step(lambda owner: owner.accept(peer, read))
+ self._note_clipboard()
+ self._step(lambda owner: owner.accept(peer, read) + owner.clipboard_pending())
elif kind == protocol.MSG_REFUSE:
read = protocol.read_refuse(message)
if read is not None:
@@ -2491,6 +2528,10 @@ class KVMController:
data = message.get("data")
if isinstance(data, dict) and "settings" in link.caps and self.on_settings is not None:
self.on_settings(data, peer)
+ elif kind == protocol.MSG_IDENTIFY_SCREENS:
+ labels = protocol.read_identify_screens(message)
+ if labels is not None and "identify_screens" in link.caps:
+ self.receive_identify_screens(peer, labels)
elif kind == protocol.MSG_PAIRED:
ids = protocol.read_paired(message)
if ids is not None:
@@ -2593,15 +2634,19 @@ class KVMController:
"""Sends in the order the owner gave them, except that reading the pasteboard (which can take
seconds, while the event tap waits for the owner's lock) is done on a thread of its own:
what follows a clipboard read for the same peer waits for it, and everything else goes on."""
+ generation = stamp = None
+ if isinstance(action, owner_module.SendClipboard):
+ stamp = self._clipboard_stamp
+ generation = self.owner._visit_route
with self._clip_lock:
waiting = self._clip_wait.get(action.peer)
if waiting is not None:
- waiting.append(action)
+ waiting.append((action, generation, stamp) if isinstance(action, owner_module.SendClipboard) else action)
return
if isinstance(action, owner_module.SendClipboard):
waiting = self._clip_wait[action.peer] = collections.deque()
try:
- self._on_pasteboard_locked(lambda peer=action.peer: self._clipboard_then_rest(peer, waiting))
+ self._on_pasteboard_locked(lambda peer=action.peer: self._clipboard_then_rest(peer, waiting, generation, stamp))
except RuntimeError:
# No thread at shutdown: nothing must wait behind a read that never starts.
del self._clip_wait[action.peer]
@@ -2638,15 +2683,35 @@ class KVMController:
except Exception:
self.logger.exception("pasteboard work failed")
- def _clipboard_then_rest(self, peer, waiting):
+ def _clipboard_then_rest(self, peer, waiting, generation=None, stamp=None):
"""The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs to
the link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the
machine that reconnects will be taken afresh. A clipboard asked for again takes its turn
among the pasteboard's other work, behind any write decided before it."""
+ sent = False
+ current_stamp = self._clipboard_stamp_now()
+ if current_stamp is not None and current_stamp == self._clipboard_written_stamp:
+ # A known peer write queued before this read may replace its original source stamp.
+ stamp = current_stamp
try:
- self._send_clipboard(peer, waiting)
- except Exception:
- self.logger.exception("the clipboard could not be sent")
+ for attempt in range(3):
+ if generation is not None and (self.owner.on != peer or self.owner._visit_route != generation):
+ break
+ if attempt:
+ time.sleep(0.05)
+ if stamp is None or self._clipboard_stamp_now() != stamp:
+ break
+ try:
+ sent = self._send_clipboard(peer, waiting, generation, stamp)
+ except Exception:
+ if attempt == 2:
+ self.logger.exception("the clipboard could not be sent")
+ if sent:
+ break
+ finally:
+ if not sent:
+ with self._owner_lock:
+ self.owner.clipboard_failed(peer)
while True:
with self._clip_lock:
if self._clip_wait.get(peer) is not waiting:
@@ -2655,8 +2720,9 @@ class KVMController:
del self._clip_wait[peer]
return
action = waiting.popleft()
- if isinstance(action, owner_module.SendClipboard):
- self._on_pasteboard_locked(lambda: self._clipboard_then_rest(peer, waiting))
+ if isinstance(action, tuple):
+ action, generation, stamp = action
+ self._on_pasteboard_locked(lambda: self._clipboard_then_rest(peer, waiting, generation, stamp))
return
try:
self._send(action)
@@ -2851,19 +2917,27 @@ class KVMController:
"""Before this Mac takes a peer: if the clipboard changed by its owner's hand since this
Mac last wrote it from a peer, no peer holds what it holds now."""
stamp = self._clipboard_stamp_now()
- if stamp != self._clipboard_stamp:
+ if stamp is not None and stamp != self._clipboard_stamp:
self._clipboard_stamp = stamp
with self._owner_lock:
self.owner.clipboard_changed()
+ return True
+ return False
- def _send_clipboard(self, peer, waiting):
+ def _send_clipboard(self, peer, waiting, generation=None, stamp=None):
"""Read this Mac's clipboard and send it as a clipboard message. Text over CLIPBOARD_MAX_BYTES
and an image protocol.png_fits refuses are each dropped on their own, so an oversized
screenshot still lets its text through; with nothing left nothing is sent. Nothing is sent
either when `waiting` was dropped with its link while the pasteboard was read."""
if self._peers_up.get(peer) is None:
return
+ if generation is not None and (self.owner.on != peer or self.owner._visit_route != generation or
+ (stamp is not None and self._clipboard_stamp_now() != stamp)):
+ return
text, image = self.clipboard.get_contents()
+ if generation is not None and (self.owner.on != peer or self.owner._visit_route != generation or
+ (stamp is not None and self._clipboard_stamp_now() != stamp)):
+ return
with self._clip_lock:
if self._clip_wait.get(peer) is not waiting:
return
@@ -2882,15 +2956,33 @@ class KVMController:
if not text and image is None:
self.logger.debug("local clipboard is empty; not sending it")
return
- link.post(protocol.clipboard_msg(text or None, image))
+ return link.post(protocol.clipboard_msg(text or None, image))
def _set_clipboard(self, message):
read = protocol.read_clipboard(message)
if read is None or (read["text"] is None and read["image"] is None):
return
- if not self.clipboard.set_contents(read["text"], read["image"]):
- self.logger.warning("failed to set the local clipboard from an inbound message")
- self._clipboard_stamp = self._clipboard_stamp_now()
+ started_stamp = self._clipboard_stamp_now()
+ for attempt in range(3):
+ if attempt:
+ time.sleep(0.05)
+ if started_stamp is None or self._clipboard_stamp_now() != started_stamp:
+ break
+ try:
+ written = self.clipboard.set_contents(read["text"], read["image"])
+ except Exception:
+ written = False
+ if attempt == 2:
+ self.logger.exception("failed to set the local clipboard from an inbound message")
+ if written:
+ stamp = getattr(self.clipboard, "write_stamp", self._clipboard_stamp_now)()
+ with self._owner_lock:
+ self._clipboard_stamp = stamp
+ self._clipboard_written_stamp = stamp
+ return
+ self.logger.warning("failed to set the local clipboard from an inbound message")
+ with self._owner_lock:
+ self.owner.clipboard_changed()
# The outbound worker
@@ -2916,6 +3008,8 @@ class KVMController:
def _owner_tick(self):
self._check_tap_watchdog()
+ if self.redirecting and not self.receiving and self._note_clipboard():
+ self._step(lambda owner: owner.clipboard_pending())
deadline = self.owner.deadline()
if deadline is not None and self.clock() >= deadline:
self._step(lambda owner: owner.tick())
diff --git a/mac_app/clipboard_mac.py b/mac_app/clipboard_mac.py
index 418d2d4..0497be3 100644
--- a/mac_app/clipboard_mac.py
+++ b/mac_app/clipboard_mac.py
@@ -27,6 +27,7 @@ LOGGER = logging.getLogger("Beamer")
# then and after forget_sync. A switch sends the clipboard only when the count has moved since,
# so an unchanged screenshot is not pushed across on every switch.
_synced_count = None
+_written_count = None
# Every read and write of the contents, from whichever thread: one at a time. The change count is
# left out, so a caller that only asks whether the pasteboard moved never waits behind a slow read.
@@ -67,7 +68,21 @@ def get_contents():
try:
with _LOCK:
pasteboard = AppKit.NSPasteboard.generalPasteboard()
- return _text_from_pasteboard(pasteboard), _png_from_pasteboard(pasteboard)
+ for _ in range(3):
+ count = pasteboard.changeCount()
+ text, png = None, None
+ try:
+ text = _text_from_pasteboard(pasteboard)
+ except Exception:
+ LOGGER.exception("failed to read pasteboard text")
+ try:
+ png = _png_from_pasteboard(pasteboard)
+ except Exception:
+ LOGGER.exception("failed to read the pasteboard image")
+ if count == pasteboard.changeCount():
+ return text, png
+ LOGGER.warning("the pasteboard kept changing during a read")
+ return None, None
except Exception:
LOGGER.exception("failed to read the macOS clipboard")
return None, None
@@ -107,18 +122,23 @@ def forget_sync():
_synced_count = None
+def write_stamp():
+ """The peer write's count, so a later local copy remains eligible for sharing."""
+ return _written_count
+
+
def set_contents(text, png):
"""Replace the general pasteboard with `text` and/or `png`. Returns True
when at least one of them was set, False otherwise. Only the PNG
representation is written for the image; every current app pastes it,
and a TIFF alongside would double the memory for nothing. Never raises."""
- global _synced_count
+ global _synced_count, _written_count
if AppKit is None or (text is None and png is None):
return False
try:
with _LOCK:
pasteboard = AppKit.NSPasteboard.generalPasteboard()
- pasteboard.clearContents()
+ count = pasteboard.clearContents()
wrote = False
if text is not None:
wrote |= bool(pasteboard.setString_forType_(text, AppKit.NSPasteboardTypeString))
@@ -126,7 +146,7 @@ def set_contents(text, png):
data = AppKit.NSData.dataWithBytes_length_(png, len(png))
wrote |= bool(pasteboard.setData_forType_(data, AppKit.NSPasteboardTypePNG))
if wrote:
- _synced_count = pasteboard.changeCount()
+ _synced_count = _written_count = count
return wrote
except Exception:
LOGGER.exception("failed to set the macOS clipboard")
diff --git a/mac_app/config.py b/mac_app/config.py
index bab5634..8382f66 100644
--- a/mac_app/config.py
+++ b/mac_app/config.py
@@ -102,6 +102,7 @@ class Config:
appearance: str = "system"
# Keys and buttons that stay on this Mac while its input is on Windows; see ignored.py.
ignored_inputs: list = field(default_factory=list)
+ mouse_only: bool = False
def _stamp(value) -> int:
@@ -222,4 +223,5 @@ def parse_config(raw: dict) -> Config:
appearance=raw.get("appearance") if raw.get("appearance") in APPEARANCES else "system",
language=raw.get("language") if raw.get("language") in ("auto", "en", "it") else "auto",
ignored_inputs=raw.get("ignored_inputs", []),
+ mouse_only=raw.get("mouse_only", False),
)
diff --git a/mac_app/diagram.py b/mac_app/diagram.py
index eb3bdf1..94c30e9 100644
--- a/mac_app/diagram.py
+++ b/mac_app/diagram.py
@@ -16,6 +16,7 @@ import pages
import theme
from core.resistance_strip import MAX_RESISTANCE, resistance_x
from core import ways as core_ways
+from core import identify_screens
from core.i18n import N_, tr
POSITION_WORDS = {"right of": N_("right of"), "left of": N_("left of"),
@@ -28,6 +29,22 @@ def _rect(frame):
return ((x, y), (w, h))
+def _beside_display_numbers(frame, badges):
+ x, y, width, height = frame
+ spans = [(x, x + width)]
+ for badge in badges:
+ if badge.isHidden():
+ continue
+ box = badge.frame()
+ if y + height <= box.origin.y or y >= box.origin.y + box.size.height:
+ continue
+ left, right = box.origin.x - 4, box.origin.x + box.size.width + 4
+ spans = [(start, end) for a, b in spans
+ for start, end in ((a, min(b, left)), (max(a, right), b)) if end > start]
+ left, right = max(spans, key=lambda span: span[1] - span[0]) if spans else (x, x + 1)
+ return left, y, right - left, height
+
+
def _set_layer_frame_if_changed(layer, frame):
x, y, width, height = frame[0][0], frame[0][1], frame[1][0], frame[1][1]
current = layer.frame()
@@ -432,6 +449,7 @@ class AtlasCanvas(AppKit.NSView):
self.layer().addSublayer_(self.focus_layer)
self.layer_for_tile = {}
self.display_layers = {}
+ self.display_number_layers = {}
self.label_for_tile = {}
self.state_for_tile = {}
self.outcome_for_tile = {}
@@ -535,6 +553,8 @@ class AtlasCanvas(AppKit.NSView):
if key not in self.tiles:
for layer in self.display_layers.pop(key, []):
layer.removeFromSuperlayer()
+ for layer in self.display_number_layers.pop(key, []):
+ layer.removeFromSuperlayer()
for layer in (self.layer_for_tile.pop(key), self.label_for_tile.pop(key),
self.state_for_tile.pop(key), self.outcome_for_tile.pop(key),
self.dot_for_tile.pop(key), self.cycle_for_tile.pop(key),
@@ -681,6 +701,8 @@ class AtlasCanvas(AppKit.NSView):
check.setLineCap_(Quartz.kCALineCapRound)
check.setLineJoin_(Quartz.kCALineJoinRound)
check.setFrame_(((0, 0), (CYCLE_BOX, CYCLE_BOX)))
+ check.setAnchorPoint_((0, 0))
+ check.setPosition_((0, 0))
check.setHidden_(True)
cycle.addSublayer_(check)
grip = Quartz.CAShapeLayer.layer()
@@ -708,7 +730,11 @@ class AtlasCanvas(AppKit.NSView):
@staticmethod
def _title_top(frame):
- return frame[1] + (frame[3] - 20) / 2 if frame[3] < 56 else frame[1] + 10
+ if frame[3] < 32:
+ return frame[1] + 11
+ if frame[3] < 44:
+ return frame[1] + max(12, frame[3] - 21)
+ return frame[1] + (4 if frame[3] < 56 else 10)
@objc.python_method
def _shows_cycle(self, key):
@@ -716,10 +742,17 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def _title_rect(self, key, frame):
+ return _beside_display_numbers(self._title_without_numbers(key, frame),
+ self.display_number_layers.get(key, ()))
+
+ @objc.python_method
+ def _title_without_numbers(self, key, frame):
"""The name's text rect. Beside the shortcut-cycle tick the name stays centred on the tile while
it fits the room left symmetric by the tick, else takes the room left of the tick; a tile 44 to
56pt tall puts the name on its own row above the tick."""
x, y, width, height = frame
+ if height < 32:
+ return x + 5, self._title_top(frame), max(1, width - 10), max(1, height - 12)
if not self._shows_cycle(key):
return x + 8, self._title_top(frame), max(1, width - 16), 20
if 44 <= height < 56:
@@ -735,6 +768,8 @@ class AtlasCanvas(AppKit.NSView):
"""The shortcut-cycle tick: its own column at the right end of the name's line, or in the
bottom-right corner of a tile 44 to 56pt tall, under the name."""
x, y, width, height = frame
+ if height < 32:
+ return x + width - 15, y + 1, 10, 10
if 44 <= height < 56:
return x + width - 8 - CYCLE_BOX, y + height - 4 - CYCLE_BOX, CYCLE_BOX, CYCLE_BOX
return x + width - 8 - CYCLE_BOX, AtlasCanvas._title_top(frame) + 10 - CYCLE_BOX / 2, CYCLE_BOX, CYCLE_BOX
@@ -860,7 +895,45 @@ class AtlasCanvas(AppKit.NSView):
(screen["w"] * scale_x, screen["h"] * scale_y)))
layer.setHidden_(False)
theme.tint(layer, background="well", border="edge")
+ numbered_frames = core_ways._display_frames(self.tiles[key])
+ numbers = identify_screens.display_numbers(self.tiles[key])
+ badges = self.display_number_layers.setdefault(key, [])
+ while len(badges) < len(numbered_frames):
+ badge = _text_layer(theme.TYPE["note"], "ink_2")
+ badge.setCornerRadius_(theme.RADIUS["field"])
+ theme.tint(badge, background="panel", foreground="ink_2")
+ self.layer().insertSublayer_below_(badge, title)
+ badges.append(badge)
+ for index, badge in enumerate(badges):
+ badge.setHidden_(index >= len(numbered_frames))
+ if index >= len(numbered_frames):
+ continue
+ screen = numbered_frames[index]
+ display = screen.get("display") or "0"
+ badge.setString_(str(numbers[display]))
+ scale_x = frame[2] / self.tiles[key]["w"]
+ scale_y = frame[3] / self.tiles[key]["h"]
+ left = frame[0] + (screen["x"] - self.tiles[key]["x"]) * scale_x
+ top = frame[1] + (screen["y"] - self.tiles[key]["y"]) * scale_y
+ bottom = frame[1] + (screen["y"] + screen["h"] - self.tiles[key]["y"]) * scale_y
+ if frame[3] < 32:
+ badge.setFontSize_(7)
+ badge_frame = ((left + 5, top + 1), (12, 8))
+ elif frame[3] < 44:
+ badge.setFontSize_(8)
+ badge_frame = ((left + 5, top + 1), (14, 10))
+ elif frame[3] < 56:
+ badge.setFontSize_(10)
+ badge_frame = ((left + 5, bottom - 15), (16, 14))
+ else:
+ badge.setFontSize_(theme.TYPE["note"])
+ badge_frame = ((left + 5, bottom - 23), (20, 18))
+ _set_layer_frame_if_changed(badge, badge_frame)
title.setString_(self.labels.get(key, tr("Machine · {id}").format(id=key[-6:])))
+ title_size = 10 if frame[3] < 32 else theme.TYPE["body"]
+ if title.fontSize() != title_size:
+ title.setFont_(theme.font(title_size, 600))
+ title.setFontSize_(title_size)
title.setWrapped_(False)
title.setTruncationMode_(Quartz.kCATruncationEnd)
_set_layer_frame_if_changed(title, _rect(self._title_rect(key, frame)))
@@ -876,8 +949,8 @@ class AtlasCanvas(AppKit.NSView):
status = self.tile_words.get(key) or status
state_layer.setString_(status)
state_layer.setAlignmentMode_(Quartz.kCAAlignmentLeft)
- _set_layer_frame_if_changed(state_layer, ((frame[0] + 24, frame[1] + 35),
- (max(1, frame[2] - 32), 16)))
+ _set_layer_frame_if_changed(state_layer, _rect(_beside_display_numbers(
+ (frame[0] + 24, frame[1] + 35, max(1, frame[2] - 32), 16), badges)))
state_layer.setHidden_(frame[3] < 72)
theme.tint(state_layer, foreground="amber" if gap else "ink_3")
crosses = status_info.get("crosses", is_own)
@@ -892,14 +965,15 @@ class AtlasCanvas(AppKit.NSView):
outcome = ""
outcome_layer.setString_(tr("Set elsewhere") if elsewhere and not is_own else outcome)
_set_layer_frame_if_changed(
- outcome_layer, ((frame[0] + 8, frame[1] + frame[3] - 22),
- (max(1, frame[2] - 16), 14)))
+ outcome_layer, _rect(_beside_display_numbers(
+ (frame[0] + 8, frame[1] + frame[3] - 22, max(1, frame[2] - 16), 14), badges)))
outcome_layer.setHidden_(frame[3] < 56)
theme.tint(outcome_layer, foreground="ink_3" if elsewhere else "signal" if outcome_kind == "crosses" else
"amber" if state in ("gap", "between", "set-elsewhere", "set_elsewhere", "overlap") else "ink_3")
_set_layer_frame_if_changed(dot, ((frame[0] + 12, frame[1] + 40), (6, 6)))
dot.setCornerRadius_(3)
- dot.setHidden_(frame[3] < 72)
+ dot.setHidden_(frame[3] < 72 or any(
+ AppKit.NSIntersectsRect(dot.frame(), badge.frame()) for badge in badges if not badge.isHidden()))
word = self.tile_words.get(key)
theme.tint(dot, background=("signal" if word in (tr("Desk"), tr("Own")) else "ink_3") if word else
"ink_3" if key in self.older else "signal" if status_info.get("linked") else "ink_3")
@@ -908,7 +982,10 @@ class AtlasCanvas(AppKit.NSView):
ticked = self.cycle.get(key, True) is True
cycle_layer.setBorderWidth_(0 if ticked else 1)
theme.tint(cycle_layer, background="ink_2" if ticked else "well", border="edge")
- cycle_layer.sublayers()[0].setHidden_(not ticked)
+ check = cycle_layer.sublayers()[0]
+ check.setHidden_(not ticked)
+ tick_scale = self._cycle_box(frame)[2] / CYCLE_BOX
+ check.setAffineTransform_(Quartz.CGAffineTransformMakeScale(tick_scale, tick_scale))
if self.display_layers.get(key):
z_position = max(layer.zPosition() for layer in self.display_layers[key]) + 1.0
for layer in (title, state_layer, outcome_layer, dot, cycle_layer):
@@ -1613,6 +1690,7 @@ class AtlasCanvas(AppKit.NSView):
self.dot_for_tile.get(key), self.cycle_for_tile.get(key),
self.resize_layers.get(key), self.focus_layer]
layers.extend(self.display_layers.get(key, ()))
+ layers.extend(self.display_number_layers.get(key, ()))
for layer in layers:
if layer is not None:
layer.removeAllAnimations()
diff --git a/mac_app/identify_overlay.py b/mac_app/identify_overlay.py
new file mode 100644
index 0000000..86939cd
--- /dev/null
+++ b/mac_app/identify_overlay.py
@@ -0,0 +1,97 @@
+"""Brief, click-through display labels. All AppKit work stays on the main thread."""
+
+import AppKit
+from PyObjCTools import AppHelper
+
+import desktop_mac
+import theme
+from core.identify_screens import OVERLAY_SECONDS, display_numbers
+
+
+class IdentifyPanel(AppKit.NSPanel):
+ def canBecomeKeyWindow(self):
+ return False
+
+ def canBecomeMainWindow(self):
+ return False
+
+
+class IdentifyOverlay:
+ DURATION = OVERLAY_SECONDS
+ SIZE = 220.0
+
+ def __init__(self, logger):
+ self.logger = logger
+ self.panels = []
+ self._generation = 0
+
+ def show(self, labels):
+ self.hide()
+ generation = self._generation
+ try:
+ displays = desktop_mac.display_map()
+ if set(labels) != set(displays):
+ labels = display_numbers({"x": 0, "y": 0, "w": 1, "h": 1, "displays": {
+ key: {"x": rect.x, "y": rect.y, "w": rect.width, "h": rect.height}
+ for key, rect in displays.items()}})
+ primary_height = AppKit.NSScreen.screens()[0].frame().size.height
+ for key, number in labels.items():
+ rect = displays.get(key)
+ if rect is None:
+ continue
+ size = min(self.SIZE, rect.width, rect.height)
+ frame = ((rect.x + (rect.width - size) / 2,
+ primary_height - rect.y - (rect.height + size) / 2), (size, size))
+ panel = self._panel(frame, number)
+ self.panels.append(panel)
+ panel.orderFrontRegardless()
+ AppHelper.callLater(self.DURATION, self._expire, generation)
+ except Exception:
+ self.hide()
+ self.logger.exception("could not identify this Mac's displays")
+
+ def _panel(self, frame, number):
+ panel = IdentifyPanel.alloc().initWithContentRect_styleMask_backing_defer_(
+ frame, AppKit.NSWindowStyleMaskBorderless | AppKit.NSWindowStyleMaskNonactivatingPanel,
+ AppKit.NSBackingStoreBuffered, False)
+ panel.setReleasedWhenClosed_(False)
+ panel.setLevel_(AppKit.NSStatusWindowLevel)
+ panel.setOpaque_(False)
+ panel.setHasShadow_(True)
+ panel.setBackgroundColor_(AppKit.NSColor.clearColor())
+ panel.setIgnoresMouseEvents_(True)
+ panel.setHidesOnDeactivate_(False)
+ panel.setCollectionBehavior_(
+ AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces
+ | AppKit.NSWindowCollectionBehaviorFullScreenAuxiliary
+ | AppKit.NSWindowCollectionBehaviorIgnoresCycle
+ | AppKit.NSWindowCollectionBehaviorStationary)
+ view = panel.contentView()
+ view.setWantsLayer_(True)
+ view.layer().setCornerRadius_(theme.RADIUS["keycap"])
+ view.layer().setBorderWidth_(1)
+ theme.tint(view.layer(), background="panel", border="edge")
+ label = AppKit.NSTextField.labelWithString_(str(number))
+ label.setFont_(theme.mono_font(min(128, frame[1][0] * 0.58), 700))
+ label.setTextColor_(theme.colour("ink"))
+ label.setAlignment_(AppKit.NSTextAlignmentCenter)
+ label.setTranslatesAutoresizingMaskIntoConstraints_(False)
+ view.addSubview_(label)
+ AppKit.NSLayoutConstraint.activateConstraints_([
+ label.centerXAnchor().constraintEqualToAnchor_(view.centerXAnchor()),
+ label.centerYAnchor().constraintEqualToAnchor_(view.centerYAnchor()),
+ label.widthAnchor().constraintLessThanOrEqualToAnchor_(view.widthAnchor()),
+ ])
+ panel.identify_number = number
+ return panel
+
+ def _expire(self, generation):
+ if generation == self._generation:
+ self.hide()
+
+ def hide(self):
+ self._generation += 1
+ for panel in self.panels:
+ panel.orderOut_(None)
+ panel.close()
+ self.panels.clear()
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index c5165c5..11fc307 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -35,6 +35,7 @@ from core import crash_log
from core import effects
from core.i18n import matches_translation, LANGUAGES, N_, tr, trc, install
import effects_overlay
+import identify_overlay
import gestures
import hardware_mac
import ignored_titles
@@ -1213,6 +1214,7 @@ class ControlWindow(AppKit.NSObject):
# made during this run needs a relaunch before the keyboard crosses, however ready the tap looks.
self.granted_at_launch = accessibility_granted() and input_monitoring_granted()
self.update_checker = None
+ self._update = None
# The list of paired machines and the pairing sheet; TrayApp gives it the pairing service.
self.panel = machines_panel.MachinesPanel(controller, settings_store, logger, self)
self._machines_first = None
@@ -1287,6 +1289,7 @@ class ControlWindow(AppKit.NSObject):
self.sidebar.footer_icon.setImage_(menu_bar_glyph("local"))
divider = widgets.box("rule")
pane = widgets.stack(spacing=0)
+ pane.setDetachesHiddenViews_(True)
for view in (top, self.sidebar.view, divider, pane):
content.addSubview_(view)
self.sidebar_width = self.sidebar.view.widthAnchor().constraintEqualToConstant_(theme.SIDEBAR_WIDTH[1])
@@ -1312,6 +1315,17 @@ class ControlWindow(AppKit.NSObject):
pane.leadingAnchor().constraintEqualToAnchor_(divider.trailingAnchor()),
pane.trailingAnchor().constraintEqualToAnchor_(content.trailingAnchor()),
])
+ self.update_notice = widgets.Module()
+ self.update_notice_text = widgets.Label("", theme.TYPE["body"], wrap=True)
+ self.update_notice.add(self.update_notice_text.view)
+ actions = widgets.stack(vertical=False, spacing=12)
+ self.update_notes = widgets.Button(tr("What's new"), self, "downloadUpdate:")
+ self.update_dismiss = widgets.Button(tr("Dismiss"), self, "dismissUpdate:")
+ widgets.add(actions, self.update_notes.view, full_width=False)
+ widgets.add(actions, self.update_dismiss.view, full_width=False)
+ self.update_notice.add(actions)
+ self.update_notice.view.setHidden_(True)
+ widgets.add(pane, self.update_notice.view)
# The page host is the only part of the pane that gives way when the window is resized;
# the commit bar keeps its height on every page.
host = widgets.stack(spacing=0)
@@ -1536,6 +1550,7 @@ class ControlWindow(AppKit.NSObject):
self.pointer_numeral.set(str(self.pointer_ruler.value))
self.scroll_numeral.set(str(self.scroll_ruler.value))
self.reverse_scroll_box.value = raw["reverse_scroll"]
+ self.mouse_only_box.value = raw["mouse_only"]
self.appearance_select.value = raw["appearance"]
self.language_select.value = raw["language"]
self._apply_appearance(raw["appearance"])
@@ -2923,10 +2938,34 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def show_update(self, found):
"""`found` is (version, url) for a newer release, or None."""
+ if not self.controller.cfg.check_updates:
+ found = None
+ self._update = found
self.update_url = found[1] if found else None
if found:
self.update_button.set_title(tr("Download Beamer {version}").format(version=found[0]))
motion.set_hidden(self.update_button.view, found is None)
+ self._refresh_update_notice()
+
+ @objc.python_method
+ def _refresh_update_notice(self):
+ found = updates.visible_notice(self._update, self.controller.cfg.check_updates,
+ self.settings_store.current().get("dismissed_update_version", ""))
+ if found:
+ self.update_notice_text.set(tr("Beamer {version} is available.").format(version=found[0]))
+ self.update_notice.view.setHidden_(not bool(found))
+
+ def dismissUpdate_(self, _sender):
+ if not self._update:
+ return
+ try:
+ cfg = self.settings_store.save(config_to_raw(self.controller.cfg),
+ settings_changes={"dismissed_update_version": self._update[0]})
+ except SettingsError as exc:
+ self.logger.warning("Update dismissal could not be saved: %s", exc)
+ return
+ self.controller.update_config(cfg)
+ self._refresh_update_notice()
def downloadUpdate_(self, _sender):
if self.update_url:
@@ -3162,7 +3201,12 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _keyboard_page(self, body):
- # Modifier keys first: chosen once, while the list below grows as keys are added.
+ module = widgets.Module()
+ self.mouse_only_box = widgets.Switch(tr("Mouse only"), on_change=self._changed)
+ module.add(widgets.eyebrow(tr("Keyboard sharing")))
+ module.add(self.mouse_only_box.view)
+ module.add(widgets.note(tr("Keep this machine's keyboard here. Pointer and clipboard sharing stay on.")).view)
+ widgets.add(body, module.view)
widgets.add(body, self._modifier_module().view)
widgets.add(body, self._ignored_module().view)
widgets.add(body, self._speed_module().view)
@@ -3332,6 +3376,11 @@ class ControlWindow(AppKit.NSObject):
self.atlas_canvas.on_cycle_change = self._set_shortcut_cycle
self.atlas_canvas.on_leave_out = lambda peer: self._set_atlas_left_out(peer, True)
module.add(self.atlas_canvas)
+ self.identify_screens_button = widgets.action_button(
+ tr("Identify screens"), self.controller.identify_screens, scale="small")
+ self.identify_screens_button.view.setToolTip_(
+ tr("Show these numbers on every linked machine's screens for 3 seconds."))
+ module.add(self.identify_screens_button.view, full_width=False)
self.atlas_canvas_hint = widgets.note(tr("Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"))
module.add(self.atlas_canvas_hint.view)
module.body.setCustomSpacing_afterView_(8, self.atlas_canvas)
@@ -4454,6 +4503,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def show(self):
+ self._refresh_update_notice()
if self.activation_policy_handler is not None:
self.activation_policy_handler(window_open=True)
self._select_page(pages.opening_page(
@@ -4538,6 +4588,7 @@ class ControlWindow(AppKit.NSObject):
try:
raw["trigger_key"] = self.key_recorder.value
raw["ignored_inputs"] = list(self.ignored_entries)
+ raw["mouse_only"] = self.mouse_only_box.value
raw["trigger_style"] = self.style_select.value
raw["double_tap_ms"] = self.double_tap_ruler.value
raw["pointer_speed"] = self.pointer_ruler.value / 100
@@ -5015,6 +5066,8 @@ class TrayApp(rumps.App):
self.notch_island = NotchIsland(controller, logger)
self.notch_beam = NotchBeam(controller, logger)
self.effects_overlay = effects_overlay.EffectsOverlay(controller, logger)
+ self.identify_overlay = identify_overlay.IdentifyOverlay(logger)
+ self.controller.on_identify_screens = lambda labels: AppHelper.callAfter(self.identify_overlay.show, labels)
self.haptics = Haptics(logger)
self._resistance_pressure_timer = None
self.control_window.preview = self.edge_glow.preview
@@ -5105,6 +5158,8 @@ class TrayApp(rumps.App):
def _update_found(self, found):
"""On the main thread. The version line in the menu becomes the way to the download."""
+ if not self.controller.cfg.check_updates:
+ found = None
self.update_url = found[1] if found else None
if found:
_set_tray_title(self.header_item, tr("Beamer {version} is available…").format(version=found[0]))
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index 848d5f4..9192330 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -56,7 +56,7 @@ MOVED_CROSSING = ("methods", "edge", "edge_parts", "corner", "arrangement_set_at
ZONE_KINDS = tuple(method for method in METHODS if method != "shortcut")
# Fields settings.json has that Config has no name for; everything else in it is Config's own.
SETTINGS_ONLY = ("schema", "machine_id", "name", "port", "shortcut", "migrated_token_sha256", "peers", "zones", "crossing",
- "layout", "layout_set_at", "layout_by", "show_in_dock", "show_in_tray")
+ "layout", "layout_set_at", "layout_by", "show_in_dock", "show_in_tray", "dismissed_update_version")
PEER_DEFAULTS = {
"id": "", "name": "", "platform": "", "token": "", "host": "", "port": 0, "hw": "", "send": True,
"allow_drive": True, "in_use": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 0,
@@ -132,6 +132,7 @@ def editable_default_config():
reverse_scroll=False,
appearance="system",
ignored_inputs=[],
+ mouse_only=False,
)
@@ -171,6 +172,7 @@ def config_to_raw(cfg):
"reverse_scroll": cfg.reverse_scroll,
"appearance": cfg.appearance,
"ignored_inputs": list(cfg.ignored_inputs),
+ "mouse_only": cfg.mouse_only,
}
@@ -882,6 +884,8 @@ class SettingsStore:
raise SettingsError(f"{name} must be a number from 0.25 to 4")
if not isinstance(cfg.reverse_scroll, bool):
raise SettingsError("reverse_scroll must be true or false")
+ if not isinstance(cfg.mouse_only, bool):
+ raise SettingsError("mouse_only must be true or false")
try:
ignored.validate(cfg.ignored_inputs)
except ValueError as exc:
diff --git a/mac_app/setup.py b/mac_app/setup.py
index 4282bb2..a6e5960 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -31,6 +31,7 @@ setup(
"gestures",
"hardware_mac",
"ignored_titles",
+ "identify_overlay",
"input_injector_mac",
"key_codes",
"keyboard_layout",
@@ -80,7 +81,7 @@ setup(
"objc", "AppKit", "ApplicationServices", "Quartz", "UserNotifications",
"core.crash_log", "core.effects", "core.i18n", "core.locale", "core.idle_pointer", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",
"core.peerlist", "core.protocol", "core.receiver", "core.return_edge", "core.settings_sync",
- "core.updates", "core.wol",
+ "core.updates", "core.wol", "core.identify_screens",
"core.fx_ink", "core.fx_instrument", "core.fx_membrane", "core.fx_sparks", "core.fx_warp",
"core.fx_light", "core.fx_material", "core.fx_folio", "core.fx_selvedge",
],
diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.py
index f942b9f..510b606 100644
--- a/mac_app/tests/test_bridge.py
+++ b/mac_app/tests/test_bridge.py
@@ -1705,6 +1705,7 @@ class CrossingWiringTests(unittest.TestCase):
up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}
self.assertIsNone(self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, down, None))
self.assertTrue(self.controller.redirecting)
+ settle(self.controller)
self.assertIsNone(self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, up, None))
self.assertFalse(self.controller.redirecting)
self.assertEqual(
diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.py
index e3a85ba..eac1c9f 100644
--- a/mac_app/tests/test_clipboard_mac.py
+++ b/mac_app/tests/test_clipboard_mac.py
@@ -49,6 +49,7 @@ class FakePasteboard:
def clearContents(self):
self.cleared += 1
self.count += 1
+ return self.count
def setString_forType_(self, text, kind):
self.written.append((kind, text))
@@ -144,6 +145,35 @@ class ChangedContentsTests(unittest.TestCase):
clipboard_mac.get_contents = real
self.assertEqual(clipboard_mac.changed_contents()[0], "copied")
+ def test_image_failure_keeps_the_text_representation(self):
+ def failed_image(kind):
+ raise RuntimeError("image provider failed")
+ self.board.dataForType_ = failed_image
+ self.assertEqual(clipboard_mac.get_contents(), ("copied", None))
+
+ def test_copy_during_read_retries_the_newest_stable_snapshot(self):
+ original = self.board.stringForType_
+ def read(kind):
+ old = original(kind)
+ self.board.count += 1
+ self.board.string = "latest"
+ self.board.stringForType_ = original
+ return old
+ self.board.stringForType_ = read
+ self.assertEqual(clipboard_mac.get_contents(), ("latest", None))
+
+ def test_local_copy_during_peer_write_is_not_marked_synchronised(self):
+ original = self.board.setString_forType_
+ def write(text, kind):
+ wrote = original(text, kind)
+ self.board.count += 1
+ self.board.string = "local copy"
+ return wrote
+ self.board.setString_forType_ = write
+ self.assertTrue(clipboard_mac.set_contents("peer", None))
+ self.assertNotEqual(clipboard_mac.write_stamp(), self.board.count)
+ self.assertEqual(clipboard_mac.changed_contents(), ("local copy", None))
+
def test_a_new_link_sends_it_again(self):
clipboard_mac.changed_contents()
clipboard_mac.forget_sync()
diff --git a/mac_app/tests/test_identify_screens.py b/mac_app/tests/test_identify_screens.py
new file mode 100644
index 0000000..8ae6356
--- /dev/null
+++ b/mac_app/tests/test_identify_screens.py
@@ -0,0 +1,238 @@
+"""Synthetic map numbering, both Mac links, and non-activating display panels."""
+
+import logging
+import sys
+import threading
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import AppKit
+
+AppKit.NSApplication.sharedApplication()
+
+import bridge
+import diagram
+import identify_overlay
+from core import identify_screens, protocol, ways
+from core.return_edge import Rect
+from test_crossing_page_machines import Page
+
+OWN = protocol.id_text(bytes(range(1, 17)))
+PEER = protocol.id_text(bytes(range(21, 37)))
+OLDER = protocol.id_text(bytes(range(41, 57)))
+PHONE = protocol.id_text(bytes(range(61, 77)))
+DISPLAYS = {"0": dict(x=1920, y=0, w=1512, h=982),
+ "1": dict(x=0, y=0, w=1920, h=1080)}
+
+
+class OverlayTests(unittest.TestCase):
+ def setUp(self):
+ self.overlay = identify_overlay.IdentifyOverlay(logging.getLogger("identify-test"))
+ self.addCleanup(self.overlay.hide)
+ self.later = []
+ patcher = mock.patch.object(identify_overlay.AppHelper, "callLater",
+ lambda delay, callback, *args: self.later.append((delay, callback, args)))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ patcher = mock.patch.object(identify_overlay.desktop_mac, "display_map", return_value={
+ "0": Rect(1920, 0, 1512, 982), "1": Rect(0, 0, 1920, 1080)})
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_numbered_panels_ignore_clicks_and_never_become_key_or_main(self):
+ app = AppKit.NSApplication.sharedApplication()
+ key, main = app.keyWindow(), app.mainWindow()
+ self.overlay.show({"0": 2, "1": 1})
+ self.assertEqual([panel.identify_number for panel in self.overlay.panels], [2, 1])
+ for panel in self.overlay.panels:
+ self.assertTrue(panel.ignoresMouseEvents())
+ self.assertFalse(panel.canBecomeKeyWindow())
+ self.assertFalse(panel.canBecomeMainWindow())
+ self.assertTrue(panel.styleMask() & AppKit.NSWindowStyleMaskNonactivatingPanel)
+ self.assertTrue(panel.collectionBehavior() & AppKit.NSWindowCollectionBehaviorFullScreenAuxiliary)
+ self.assertEqual(app.keyWindow(), key)
+ self.assertEqual(app.mainWindow(), main)
+
+ def test_each_label_is_centred_on_its_physical_display(self):
+ self.overlay.show({"0": 2, "1": 1})
+ for panel, centre in zip(self.overlay.panels, (2676, 960)):
+ frame = panel.frame()
+ self.assertEqual(frame.origin.x + frame.size.width / 2, centre)
+
+ def test_timeout_hides_and_releases_all_panels_after_three_seconds(self):
+ self.overlay.show({"0": 2, "1": 1})
+ panels = list(self.overlay.panels)
+ delay, expire, args = self.later[-1]
+ self.assertEqual(delay, 3.0)
+ expire(*args)
+ self.assertEqual(self.overlay.panels, [])
+ self.assertFalse(any(panel.isVisible() for panel in panels))
+
+ def test_repeat_invocation_replaces_panels_and_old_timeout_cannot_hide_new_ones(self):
+ self.overlay.show({"0": 2, "1": 1})
+ previous = list(self.overlay.panels)
+ _delay, old_expire, old_args = self.later[-1]
+ self.overlay.show({"0": 2, "1": 1})
+ old_expire(*old_args)
+ self.assertEqual(len(self.overlay.panels), 2)
+ self.assertTrue(self.overlay.panels[0].isVisible())
+ self.assertFalse(any(panel.isVisible() for panel in previous))
+ _delay, expire, args = self.later[-1]
+ expire(*args)
+ self.assertEqual(self.overlay.panels, [])
+
+ def test_stale_request_is_replaced_by_numbers_for_all_current_displays(self):
+ self.overlay.show({"missing": 3})
+ self.assertEqual([panel.identify_number for panel in self.overlay.panels], [1, 2])
+
+ def test_newly_attached_display_is_identified_with_the_same_live_numbering(self):
+ self.overlay.show({"1": 1})
+ self.assertEqual([panel.identify_number for panel in self.overlay.panels], [1, 2])
+
+
+class RoutingTests(unittest.TestCase):
+ def setUp(self):
+ self.controller = object.__new__(bridge.KVMController)
+ self.settings = dict(machine_id=OWN, peers=[dict(id=PEER, port=24820),
+ dict(id=OLDER, port=24820), dict(id=PHONE, port=0)],
+ layout_set_at=1, layout={OWN: dict(x=0, y=0, w=320, h=100, displays=DISPLAYS),
+ PEER: dict(x=320, y=0, w=320, h=100, displays=DISPLAYS)})
+ self.controller.book = SimpleNamespace(lock=threading.RLock(), _load=lambda: self.settings,
+ peers=lambda: self.settings["peers"])
+ self.controller.identity = lambda: {"id": protocol.read_id(OWN)}
+ self.controller.crossing_displays_changed = mock.Mock()
+ self.controller.on_identify_screens = mock.Mock()
+ self.controller.logger = logging.getLogger("identify-routing-test")
+ self.controller._peers_up = {}
+ self.controller.responder = None
+
+ def link(self, peer, capable=True):
+ return SimpleNamespace(peer_id=peer, live=lambda: True, post=mock.Mock(),
+ caps={"identify_screens"} if capable else set())
+
+ def test_local_and_peer_labels_match_the_map_and_older_peers_receive_nothing(self):
+ current, older, phone = self.link(PEER), self.link(OLDER, False), self.link(PHONE)
+ self.controller._peers_up = {PEER: current, OLDER: older, PHONE: phone}
+ self.controller.identify_screens()
+ expected = identify_screens.display_numbers(ways.derive_layout(self.settings, gap=0)[OWN])
+ self.controller.on_identify_screens.assert_called_once_with(expected)
+ self.assertEqual(protocol.read_identify_screens(current.post.call_args.args[0]), expected)
+ older.post.assert_not_called()
+ phone.post.assert_not_called()
+
+ def test_inbound_only_link_receives_once_and_dual_link_is_not_duplicated(self):
+ current = self.link(PEER)
+ self.controller._peers_up = {PEER: current}
+ server = SimpleNamespace(links=lambda: [protocol.read_id(PEER), protocol.read_id(OLDER)],
+ caps_of=lambda _peer: {"identify_screens"}, send=mock.Mock())
+ self.controller.responder = server
+ self.controller.identify_screens()
+ self.assertEqual(current.post.call_count, 1)
+ self.assertEqual(server.send.call_count, 1)
+ self.assertEqual(server.send.call_args.args[0], protocol.read_id(OLDER))
+
+ def test_received_request_is_local_only_and_requires_capable_desktop(self):
+ labels = {"0": 2, "1": 1}
+ self.controller._link_message(self.link(PEER), protocol.identify_screens_msg(labels))
+ self.controller.on_identify_screens.assert_called_once_with(labels)
+ self.controller.on_identify_screens.reset_mock()
+ self.controller._link_message(self.link(OLDER, False), protocol.identify_screens_msg(labels))
+ self.controller._link_message(self.link(PHONE), protocol.identify_screens_msg(labels))
+ self.controller.on_identify_screens.assert_not_called()
+
+
+class MapTests(unittest.TestCase):
+ def test_smallest_valid_tiles_keep_title_number_and_cycle_within_the_tile(self):
+ smallest = ways.resize_tile(dict(x=0, y=0, w=160, h=100), 40)
+ self.assertEqual((smallest["w"], smallest["h"]), (40, 25))
+ for height in (25, 28, 31):
+ canvas = diagram.AtlasCanvas.alloc().init().setup()
+ canvas.setFrame_(((0, 0), (600, 300)))
+ tiles = {OWN: dict(smallest, h=height), PEER: dict(smallest, x=40, h=height)}
+ canvas.show_layout(tiles, {}, {OWN: "This Mac", PEER: "A long peer name"}, OWN, OWN,
+ cycle={PEER: True}, cycle_enabled=True)
+ frames = {OWN: (20, 20, 40, height), PEER: (60, 20, 40, height)}
+ with mock.patch.object(canvas, "_map", return_value=(frames, 1)):
+ canvas._draw(False)
+ for key, (x, y, width, tile_height) in frames.items():
+ title = canvas.label_for_tile[key]
+ number = canvas.display_number_layers[key][0]
+ cycle = canvas.cycle_for_tile[key]
+ visible = [title, number] + ([] if cycle.isHidden() else [cycle])
+ self.assertGreaterEqual(title.frame().size.width, 24)
+ self.assertGreaterEqual(title.frame().size.height, 12)
+ for layer in visible:
+ box = layer.frame()
+ self.assertGreaterEqual(box.origin.x, x)
+ self.assertGreaterEqual(box.origin.y, y)
+ self.assertLessEqual(box.origin.x + box.size.width, x + width)
+ self.assertLessEqual(box.origin.y + box.size.height, y + tile_height)
+ for index, first in enumerate(visible):
+ for second in visible[index + 1:]:
+ self.assertFalse(AppKit.NSIntersectsRect(first.frame(), second.frame()))
+ if not cycle.isHidden():
+ tick = cycle.sublayers()[0].frame()
+ self.assertLessEqual(tick.origin.x + tick.size.width, cycle.frame().size.width)
+ self.assertLessEqual(tick.origin.y + tick.size.height, cycle.frame().size.height)
+
+ def test_compact_titles_keep_readable_width_and_separate_number_and_cycle_rows(self):
+ from test_map_ticks import canvas_for
+
+ for size in ((260, 260), (200, 260)):
+ canvas = canvas_for(size=size)
+ for key, tile in canvas._map()[0].items():
+ title = canvas.label_for_tile[key].frame()
+ self.assertGreaterEqual(title.size.width, min(18, tile[2] - 16))
+ self.assertGreaterEqual(title.origin.y, tile[1])
+ self.assertLessEqual(title.origin.y + title.size.height, tile[1] + tile[3])
+ cycle = canvas.cycle_for_tile[key]
+ for badge in canvas.display_number_layers[key]:
+ self.assertFalse(AppKit.NSIntersectsRect(title, badge.frame()))
+ if not cycle.isHidden():
+ self.assertFalse(AppKit.NSIntersectsRect(cycle.frame(), badge.frame()))
+
+ def test_display_badges_match_overlay_labels_including_single_display(self):
+ canvas = diagram.AtlasCanvas.alloc().init().setup()
+ canvas.setFrame_(((0, 0), (600, 300)))
+ tiles = {OWN: dict(x=0, y=0, w=320, h=100, displays=DISPLAYS),
+ PEER: dict(x=320, y=0, w=160, h=100)}
+ canvas.show_layout(tiles, {}, {OWN: "This Mac", PEER: "Peer"}, OWN, OWN)
+ canvas._draw(False)
+ for peer, tile in tiles.items():
+ expected = [str(value) for value in identify_screens.display_numbers(tile).values()]
+ self.assertEqual([str(layer.string()) for layer in canvas.display_number_layers[peer]], expected)
+
+ def test_numbers_do_not_overlap_name_status_or_footer_on_stacked_or_split_displays(self):
+ for displays in (DISPLAYS, {"0": dict(x=0, y=0, w=1920, h=1080),
+ "1": dict(x=0, y=1080, w=1920, h=1080)}):
+ canvas = diagram.AtlasCanvas.alloc().init().setup()
+ canvas.setFrame_(((0, 0), (600, 300)))
+ tile = dict(x=0, y=0, w=320, h=100, displays=displays)
+ canvas.show_layout({OWN: tile}, {OWN: {"platform": "macOS"}}, {OWN: "This Mac"}, OWN, OWN)
+ canvas._draw(False)
+ for badge in canvas.display_number_layers[OWN]:
+ for text in (canvas.label_for_tile[OWN], canvas.state_for_tile[OWN], canvas.outcome_for_tile[OWN]):
+ if not text.isHidden():
+ self.assertFalse(AppKit.NSIntersectsRect(text.frame(), badge.frame()))
+
+
+class ButtonTests(Page):
+ def test_crossing_button_runs_identify_without_modifying_settings(self):
+ with mock.patch.object(bridge.KVMController, "identify_screens") as identify:
+ window = self.build([])
+ before = self.store.current()
+ button = window.identify_screens_button
+ self.assertEqual(button.title, "Identify screens")
+ self.assertTrue(button.view.isEnabled())
+ button.target.fire_(button.view)
+ identify.assert_called_once_with()
+ self.assertEqual(self.store.current(), before)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_ignored_inputs.py b/mac_app/tests/test_ignored_inputs.py
index 517643e..7acddc3 100644
--- a/mac_app/tests/test_ignored_inputs.py
+++ b/mac_app/tests/test_ignored_inputs.py
@@ -31,6 +31,19 @@ def other_button(number):
class TapTests(unittest.TestCase):
+ def test_mouse_only_keeps_typing_and_media_here_but_sends_mouse_buttons(self):
+ self.controller.apply_settings(replace(self.controller.cfg, mouse_only=True))
+ for event_type in (FakeQuartz.kCGEventKeyDown, FakeQuartz.kCGEventKeyUp):
+ event = key_event(KEY_A, "a")
+ self.assertIs(self.tap(event_type, event), event)
+ media = (8, (7 << 16) | 0x0A00)
+ self.assertIs(self.controller._handle_system_event(media), media)
+ self.assertEqual(self.sent(), [])
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventLeftMouseDown, {}))
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventLeftMouseUp, {}))
+ self.assertEqual(self.sent(), [(protocol.MSG_MOUSEDOWN, {"button": "left"}),
+ (protocol.MSG_MOUSEUP, {"button": "left"})])
+
def setUp(self):
self.controller = KVMController(
replace(make_config(PAIRED_TOKEN), ignored_inputs=[ignored.key(KEY_F13), ignored.button("back"), ignored.media("volume_up")]),
@@ -149,6 +162,19 @@ class TapTests(unittest.TestCase):
class SettingsTests(unittest.TestCase):
+ def test_mouse_only_defaults_off_and_survives_save_reload(self):
+ raw = settings_store.config_to_raw(settings_store.editable_default_config())
+ raw.pop("mouse_only")
+ self.assertFalse(settings_store.config_module.parse_config(raw).mouse_only)
+ with tempfile.TemporaryDirectory() as directory:
+ store = settings_store.SettingsStore(Path(directory) / "settings.json")
+ raw["mouse_only"] = True
+ store.save(raw)
+ self.assertTrue(store.load().mouse_only)
+ raw["mouse_only"] = "true"
+ with self.assertRaises(settings_store.SettingsError):
+ store.save(raw)
+
def test_the_list_survives_a_save_and_a_load(self):
with tempfile.TemporaryDirectory() as directory:
store = settings_store.SettingsStore(Path(directory) / "config.json")
diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.py
index de9da18..b6258fd 100644
--- a/mac_app/tests/test_mac_links.py
+++ b/mac_app/tests/test_mac_links.py
@@ -9,6 +9,7 @@ import sys
import threading
import time
import unittest
+from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -340,11 +341,11 @@ class SlowPasteboardTests(Base):
settle(self.controller)
self.assertEqual(self.order, [protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD])
- def test_stopping_during_the_read_still_lets_the_machine_go_after_it(self):
+ def test_stopping_during_the_read_skips_the_clipboard_and_still_lets_the_machine_go(self):
self.take()
threading.Timer(0.2, self.release.set).start()
self.controller.stop()
- self.assertIn(protocol.MSG_CLIPBOARD, self.order)
+ self.assertNotIn(protocol.MSG_CLIPBOARD, self.order)
let_go = [m for m in self.link.posted if m["type"] == protocol.MSG_FOCUS][-1]["data"]
self.assertEqual(let_go["target"], self.own)
@@ -566,6 +567,194 @@ class ComingHomeTests(Base):
class ClipboardTests(Base):
+ def test_a_read_finishing_after_home_never_posts_private_local_text(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ self.link.posted.clear()
+ self.clipboard.copy("before home")
+ def copied_after_home():
+ self.controller.set_redirecting(False)
+ self.clipboard.copy("private local text")
+ return self.clipboard.text, None
+ with mock.patch.object(self.clipboard, "get_contents", side_effect=copied_after_home) as read:
+ self.controller._owner_tick()
+ settle(self.controller)
+ self.assertEqual(read.call_count, 1)
+ self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())
+
+ def test_a_source_retry_stops_after_home_even_if_the_stamp_is_unchanged(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ self.link.posted.clear()
+ self.clipboard.copy("before home")
+ stamp = self.clipboard.stamp
+ def unavailable_after_home():
+ self.controller.set_redirecting(False)
+ return None, None
+ with mock.patch.object(self.clipboard, "get_contents", side_effect=unavailable_after_home) as read:
+ self.controller._owner_tick()
+ settle(self.controller)
+ self.assertEqual(read.call_count, 1)
+ self.assertEqual(self.clipboard.stamp, stamp)
+ self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())
+
+ def test_copies_while_the_panel_is_hidden_reach_the_active_peer(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ for text in ("first", "日本語 — café 𝄞", "large " * 20000):
+ self.clock.value += 0.1
+ self.clipboard.copy(text)
+ self.controller._owner_tick()
+ settle(self.controller)
+ self.assertEqual(self.link.posted[-1], protocol.clipboard_msg(text))
+
+ def test_a_transient_read_or_post_failure_recovers_without_another_crossing(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ for failure in ("read", "read_exception", "post", "post_exception"):
+ with self.subTest(failure=failure):
+ text = "new local copy: " + failure
+ self.clipboard.copy(text)
+ read, post = self.clipboard.get_contents, self.link.post
+ calls = []
+ def attempt(*args):
+ calls.append(True)
+ if len(calls) == 1:
+ if failure.endswith("exception"):
+ raise OSError("clipboard temporarily busy")
+ return (None, None) if failure == "read" else False
+ return read() if failure.startswith("read") else post(*args)
+ target, name = (self.clipboard, "get_contents") if failure.startswith("read") else (self.link, "post")
+ with mock.patch.object(target, name, side_effect=attempt):
+ self.controller._owner_tick()
+ settle(self.controller)
+ self.assertEqual(len(calls), 2)
+ self.assertEqual(self.link.posted[-1], protocol.clipboard_msg(text))
+
+ def test_a_persistent_source_read_failure_is_bounded_and_releases_input(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ self.clipboard.copy("temporarily unreadable")
+ with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)) as read:
+ self.controller._owner_tick()
+ self.controller._step(lambda owner: owner.input({"type": "keydown", "data": {"key": "a"}}))
+ settle(self.controller)
+ self.assertEqual(read.call_count, 3)
+ self.assertEqual(self.link.sent[-1]["type"], protocol.MSG_KEYDOWN)
+
+ def test_a_source_retry_never_reads_a_newer_copy_for_the_old_attempt(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ self.clipboard.copy("first generation")
+ def changed_while_busy():
+ self.clipboard.copy("new generation")
+ return None, None
+ with mock.patch.object(self.clipboard, "get_contents", side_effect=changed_while_busy) as read:
+ self.controller._owner_tick()
+ settle(self.controller)
+ self.assertEqual(read.call_count, 1)
+ self.controller._owner_tick()
+ settle(self.controller)
+ self.assertEqual(self.link.posted[-1], protocol.clipboard_msg("new generation"))
+
+ def test_an_inbound_write_exception_is_retried(self):
+ write = self.clipboard.set_contents
+ calls = []
+ def temporarily_busy(text, image):
+ calls.append(text)
+ if len(calls) == 1:
+ raise OSError("clipboard temporarily busy")
+ return write(text, image)
+ with mock.patch.object(self.clipboard, "set_contents", side_effect=temporarily_busy):
+ self.controller._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(calls, ["remote copy", "remote copy"])
+ self.assertEqual(self.clipboard.text, "remote copy")
+
+ def test_a_copy_completed_before_accept_is_forwarded_on_accept(self):
+ self.up()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.clipboard.copy("copy completed after the crossing")
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ settle(self.controller)
+ self.assertEqual(self.link.posted[-1], protocol.clipboard_msg(self.clipboard.text))
+
+ def test_a_failed_read_is_tried_again_on_the_next_crossing(self):
+ self.up()
+ read = self.clipboard.get_contents
+ self.clipboard.get_contents = lambda: (None, None)
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ self.controller.set_redirecting(False)
+ self.clipboard.get_contents = read
+ self.link.posted.clear()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.assertIn(protocol.clipboard_msg("hello"), self.link.posted)
+
+ def test_a_failed_post_is_tried_again_on_the_next_crossing(self):
+ self.up()
+ post = self.link.post
+ self.link.post = lambda message: False if message["type"] == protocol.MSG_CLIPBOARD else post(message)
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.link.arrives(self.controller, protocol.accept_msg(1))
+ self.controller.set_redirecting(False)
+ self.link.post = post
+ self.link.posted.clear()
+ self.controller.set_redirecting(True)
+ settle(self.controller)
+ self.assertIn(protocol.clipboard_msg("hello"), self.link.posted)
+
+ def test_failed_inbound_writes_do_not_swallow_a_local_copy(self):
+ self.up()
+ self.controller._note_clipboard()
+ before = self.controller._clipboard_stamp
+ self.clipboard.copy("local copy")
+ self.clipboard.set_contents = lambda text, image: False
+ self.controller._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(self.controller._clipboard_stamp, before)
+
+ def test_an_inbound_write_retry_keeps_a_newer_local_copy(self):
+ self.up()
+ calls = []
+ def copied_while_busy(text, image):
+ calls.append(text)
+ self.clipboard.copy("newer local copy")
+ return False
+ self.clipboard.set_contents = copied_while_busy
+ self.controller._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(calls, ["remote copy"])
+ self.assertEqual(self.clipboard.text, "newer local copy")
+
+ def test_a_copy_during_a_peer_write_is_not_mistaken_for_the_peer_write(self):
+ self.up()
+ self.controller._note_clipboard()
+ write_stamp = self.clipboard.stamp + 1
+ self.clipboard.write_stamp = lambda: write_stamp
+ write = self.clipboard.set_contents
+ def copied_after_write(text, image):
+ result = write(text, image)
+ self.clipboard.copy("new local copy")
+ return result
+ self.clipboard.set_contents = copied_after_write
+ self.controller._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(self.controller._clipboard_stamp, write_stamp)
+ self.assertTrue(self.controller._note_clipboard())
+
def test_a_clipboard_from_the_machine_just_let_go_is_taken_once(self):
self.up()
self.controller.set_redirecting(True)
@@ -631,6 +820,9 @@ class ClipboardTests(Base):
# same machine waits for it.
from core import owner as owner_module
self.up()
+ self.controller._note_clipboard()
+ self.controller.owner.go(self.peer)
+ self.controller.owner.accept(self.peer, {"route": self.controller.owner.route})
order = []
post, send_input = self.link.post, self.link.send_input
self.link.post = lambda message: order.append(message["type"]) or post(message)
diff --git a/mac_app/tests/test_mouse_only_page.py b/mac_app/tests/test_mouse_only_page.py
new file mode 100644
index 0000000..0a8bd40
--- /dev/null
+++ b/mac_app/tests/test_mouse_only_page.py
@@ -0,0 +1,26 @@
+"""The Keyboard page's mouse-only switch, without showing the window."""
+
+import unittest
+from unittest import mock
+
+from mac_app.tests.test_crossing_page_machines import Page, kvm_bridge_app
+from mac_app.settings_store import config_to_raw
+
+
+class MouseOnlyPageTests(Page):
+ def test_load_and_apply_round_trip_through_the_existing_settings_path(self):
+ window = self.build([])
+ self.addCleanup(window.window.close)
+ self.assertFalse(window.mouse_only_box.value)
+ raw = config_to_raw(window.controller.cfg)
+ raw["mouse_only"] = True
+ window._load(raw)
+ self.assertTrue(window.mouse_only_box.value)
+ with mock.patch.object(window.controller, "apply_settings"):
+ kvm_bridge_app.ControlWindow._apply_settings(window)
+ self.assertTrue(window.settings_store.load().mouse_only)
+ self.assertFalse(window.window.isVisible())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_update_notice.py b/mac_app/tests/test_update_notice.py
new file mode 100644
index 0000000..c43ceae
--- /dev/null
+++ b/mac_app/tests/test_update_notice.py
@@ -0,0 +1,56 @@
+"""Native update notice, built offscreen with synthetic settings; Claude pass only."""
+
+from types import SimpleNamespace
+from unittest import mock
+
+import kvm_bridge_app as kvm
+import settings_store
+import test_crossing_page_machines as fixture
+
+
+FOUND = ("1.5.11", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.11")
+
+
+class UpdateNoticeTest(fixture.Page):
+ def test_dismissal_survives_rebuilding_and_other_settings_changes(self):
+ window = self.build([])
+ window.show_update(FOUND)
+ self.assertFalse(window.update_notice.view.isHidden())
+ self.assertFalse(window.window.isVisible())
+ window.dismissUpdate_(None)
+ self.assertTrue(window.update_notice.view.isHidden())
+ self.assertEqual(self.store.current()["dismissed_update_version"], "1.5.11")
+ cfg = self.store.save(settings_store.config_to_raw(self.controller.cfg))
+ self.controller.update_config(cfg)
+ self.store._cache = None
+ window = self.build([])
+ window.show_update(FOUND)
+ self.assertTrue(window.update_notice.view.isHidden())
+ window.show_update(("1.5.12", FOUND[1]))
+ self.assertFalse(window.update_notice.view.isHidden())
+
+ def test_switching_off_hides_the_notice_and_late_answers(self):
+ window = self.build([])
+ window.show_update(FOUND)
+ window._set_check_updates(False)
+ self.assertFalse(self.controller.cfg.check_updates)
+ self.assertTrue(window.update_notice.view.isHidden())
+ window.show_update(FOUND)
+ self.assertTrue(window.update_notice.view.isHidden())
+ self.assertIsNone(window.update_url)
+
+ def test_whats_new_opens_the_release_only_on_a_click(self):
+ window = self.build([])
+ workspace = mock.Mock()
+ with mock.patch.object(kvm.AppKit, "NSWorkspace", SimpleNamespace(sharedWorkspace=lambda: workspace)):
+ window.show_update(FOUND)
+ self.assertEqual(workspace.openURL_.call_count, 0)
+ window.update_notes.view.performClick_(None)
+ self.assertEqual(workspace.openURL_.call_args.args[0].absoluteString(), FOUND[1])
+
+ def test_failed_save_keeps_the_notice_available(self):
+ window = self.build([])
+ window.show_update(FOUND)
+ with mock.patch.object(self.store, "save", side_effect=settings_store.SettingsError("read only")):
+ window.dismissUpdate_(None)
+ self.assertFalse(window.update_notice.view.isHidden())
diff --git a/mac_app/tests/test_window_geometry.py b/mac_app/tests/test_window_geometry.py
index 0601bfa..4d4fa95 100644
--- a/mac_app/tests/test_window_geometry.py
+++ b/mac_app/tests/test_window_geometry.py
@@ -32,6 +32,7 @@ def offscreen_control_window():
store._cache, _changes = profiles.after_load(
store._complete(settings), platform="mac", capable=(), now=time.time(), app=settings_store.PROFILE_APP_VERSION)
store.save = mock.Mock(return_value=cfg)
+ store.save_settings = mock.Mock()
logger = logging.getLogger("test-window-geometry")
from wake import WakingController
diff --git a/mac_app/windows_input.py b/mac_app/windows_input.py
index f2b0a13..f606b44 100644
--- a/mac_app/windows_input.py
+++ b/mac_app/windows_input.py
@@ -71,6 +71,7 @@ class WindowsInput:
arrangement_callback=self._on_arrangement,
settings_callback=self._on_settings,
paired_callback=self._on_paired,
+ identify_callback=controller.receive_identify_screens,
link_callback=self._on_link,
announce=self._announce,
)
diff --git a/tools/identify_screens_smoke.py b/tools/identify_screens_smoke.py
new file mode 100644
index 0000000..f9df700
--- /dev/null
+++ b/tools/identify_screens_smoke.py
@@ -0,0 +1,61 @@
+"""Native runner only: temporary screen labels, without opening the Beamer app or settings."""
+
+import logging
+from pathlib import Path
+import sys
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "win_app"))
+
+from PySide6.QtCore import QTimer
+from PySide6.QtWidgets import QApplication
+from core.identify_screens import display_numbers
+from core.return_edge import Rect
+from identify_overlay import IdentifyScreens
+
+
+def main():
+ logging.basicConfig(level=logging.INFO)
+ app = QApplication([])
+ screens = app.screens()
+ print(f"platform={app.platformName()} screens={len(screens)}", flush=True)
+ displays = {str(index): Rect(screen.geometry().x(), screen.geometry().y(),
+ screen.geometry().width(), screen.geometry().height())
+ for index, screen in enumerate(screens)}
+ tile = {"x": 0, "y": 0, "w": 160, "h": 100, "displays": {
+ key: {"x": rect.x, "y": rect.y, "w": rect.width, "h": rect.height}
+ for key, rect in displays.items()}}
+ overlay = IdentifyScreens()
+ state = {"shown": False, "focus": False, "helper_focus": False}
+ prior = app.activeWindow()
+
+ def inspect():
+ state["shown"] = overlay._ready or bool(screens) and len(overlay.windows) == len(screens)
+ if not state["shown"]:
+ return
+ polling.stop()
+ state["focus"] = app.activeWindow() is prior
+ helper_focus = getattr(overlay, "helper_focus", None)
+ state["helper_focus"] = helper_focus is None or not any(helper_focus.values())
+ print(f"platform={app.platformName()} screens={len(screens)} "
+ f"backend={overlay._backend or 'native Qt'} helper_ready={overlay._ready} "
+ f"qt_windows={len(overlay.windows)} "
+ f"focus_preserved={state['focus']} helper_focus={helper_focus}", flush=True)
+ QTimer.singleShot(4000, app.quit)
+
+ polling = QTimer()
+ polling.timeout.connect(inspect)
+ polling.start(25)
+ overlay.show_numbers(display_numbers(tile), displays)
+ QTimer.singleShot(9000, app.quit)
+ app.exec()
+ expired = not overlay.windows and overlay._process is None
+ overlay.stop()
+ passed = state["shown"] and state["focus"] and state["helper_focus"] and expired
+ print(f"shown={state['shown']} expired={expired} result={'PASS' if passed else 'FAIL'}")
+ return 0 if passed else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/uk.co.kalkman.beamer.json b/uk.co.kalkman.beamer.json
index da4ea48..5d734c7 100644
--- a/uk.co.kalkman.beamer.json
+++ b/uk.co.kalkman.beamer.json
@@ -85,6 +85,13 @@
"sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", "sha256": "4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"}],
"build-options": {"env": {"PIP_FIND_LINKS": "."}}
},
+ {
+ "name": "python3-segno",
+ "buildsystem": "simple",
+ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app segno==1.6.6"],
+ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/d6/02/12c73fd423eb9577b97fc1924966b929eff7074ae6b2e15dd3d30cb9e4ae/segno-1.6.6-py3-none-any.whl", "sha256": "28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7"}],
+ "build-options": {"env": {"PIP_FIND_LINKS": "."}}
+ },
{
"name": "python3-xlib",
"buildsystem": "simple",
diff --git a/win_app/app_config.py b/win_app/app_config.py
index 407358d..682e3ba 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -187,6 +187,7 @@ class Config:
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)
+ mouse_only: bool = False
# The window's own palette: follow Windows, or keep one. tokens.APPEARANCES is the home of
# these three values.
appearance: str = "system"
@@ -313,6 +314,8 @@ def validate_config(config: Config) -> None:
raise ConfigError(f"{name} must be a number from 0.25 to 4")
if not isinstance(config.reverse_scroll, bool):
raise ConfigError("reverse_scroll must be true or false")
+ if not isinstance(config.mouse_only, bool):
+ raise ConfigError("mouse_only must be true or false")
try:
reconnect_interval_s = float(config.reconnect_interval_s)
except (TypeError, ValueError) as exc:
@@ -430,6 +433,7 @@ def config_from_dict(raw: dict) -> Config:
arrangement_set_at=int(raw.get("arrangement_set_at", 0)),
mac_resistance_px=int(raw.get("mac_resistance_px", 120)),
ignored_inputs=raw.get("ignored_inputs", []),
+ mouse_only=raw.get("mouse_only", False),
appearance=raw.get("appearance") if raw.get("appearance") in tokens.APPEARANCES else "system",
machine_id=raw.get("machine_id", "") or "",
name=raw.get("name", "") or "",
@@ -515,6 +519,7 @@ def config_to_dict(config: Config) -> dict:
"arrangement_set_at": int(config.arrangement_set_at),
"mac_resistance_px": int(config.mac_resistance_px),
"ignored_inputs": list(config.ignored_inputs),
+ "mouse_only": config.mouse_only,
"appearance": config.appearance,
"machine_id": config.machine_id,
"name": config.name,
diff --git a/win_app/autostart_win.py b/win_app/autostart_win.py
index dca55d8..aeee30d 100644
--- a/win_app/autostart_win.py
+++ b/win_app/autostart_win.py
@@ -24,6 +24,8 @@ from typing import Callable, Optional
from xml.sax.saxutils import escape
import xml.etree.ElementTree as ET
+from core import windows_tools
+
TASK_PREFIX = "Beamer-"
CREATE_NO_WINDOW = 0x08000000
NAME_SAM_COMPATIBLE = 2
@@ -35,7 +37,7 @@ Runner = Callable[[list], "subprocess.CompletedProcess"]
def _run(args: list) -> subprocess.CompletedProcess:
- return subprocess.run(args, capture_output=True, text=True, creationflags=CREATE_NO_WINDOW)
+ return windows_tools.run(args)
def _process_user() -> str:
diff --git a/win_app/build.spec b/win_app/build.spec
index bf057c3..f86a722 100644
--- a/win_app/build.spec
+++ b/win_app/build.spec
@@ -13,7 +13,8 @@ analysis = Analysis(
pathex=[str(source_dir), str(source_dir.parent)],
binaries=[],
datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"),
- (str(source_dir.parent / "VERSION"), ".")]
+ (str(source_dir.parent / "VERSION"), "."),
+ (str(source_dir / "identify_layer_shell.py"), ".")]
+ [(str(path), "locales") for path in (source_dir.parent / "locales").glob("*.po")],
# core/effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see; they are
# among core_modules. segno is imported inside a try in qr_code.py, so it is named here as well.
diff --git a/win_app/capture_win.py b/win_app/capture_win.py
index e1ee887..3041a62 100644
--- a/win_app/capture_win.py
+++ b/win_app/capture_win.py
@@ -29,9 +29,9 @@ callback thread:
moving -- read as this PC's own push against the same edge and sent this
PC's input straight out to the Mac, which left the Mac's own notch and
shortcut dead until someone pressed Send input to Windows.
-- The character a key produces is read with only shift and caps lock applied,
- never Ctrl/Alt/Win, exactly as the Mac's translator does it, so a chord
- arrives as a modifier plus the plain key rather than as a control character.
+- Shortcuts use the plain key with Shift and Caps Lock applied. When right Alt
+ changes that translation into printable text, AltGr's character travels as
+ text with the peer's modifiers bracketed around it.
Pointer movement comes from Raw Input, not from the mouse hook, and that is
not a preference. A low-level hook reports the cursor's position, which
@@ -335,17 +335,21 @@ VK_CAPITAL = 0x14
class KeyboardState:
"""The keyboard bytes ToUnicodeEx is asked to translate against: shift and
- caps lock as they really are, every other modifier cleared. Held as a
+ caps lock as they really are, plus AltGr for text; other modifiers cleared. Held as a
plain dict of virtual key to byte so the translation is testable without
Windows. Dead accents stay here in software, never in Windows' keyboard state."""
def __init__(self) -> None:
self.shift_down = False
self.caps_lock = False
+ self.altgr_down = False
+ self.ctrl_down: Set[int] = set()
self.pending_dead_key: Optional[str] = None
- def bytes_for(self) -> Dict[int, int]:
+ def bytes_for(self, altgr: bool = True) -> Dict[int, int]:
state = {VK_SHIFT: 0x80 if self.shift_down else 0x00, VK_CAPITAL: 0x01 if self.caps_lock else 0x00}
+ if altgr and self.altgr_down and not self.ctrl_down:
+ state.update({0x11: 0x80, 0x12: 0x80, 0xA5: 0x80})
return state
@@ -369,19 +373,24 @@ def key_name(
down: bool = True,
) -> Optional[Union[str, DeadKey, TextInput]]:
"""The wire name for one key press: a named key where there is one, else
- the character it types with only shift and caps lock applied. A dead key
+ the character it types with Shift and Caps Lock applied (AltGr text is separate). A dead key
waits for the next printable character; a key with no usable character is
ignored."""
+ if state.ctrl_down:
+ state.pending_dead_key = None
named = VK_TO_NAME.get(vk)
if named is not None:
if state.pending_dead_key and named == "space":
character, state.pending_dead_key = state.pending_dead_key, None
- return character
+ return TextInput(character) if state.altgr_down and not state.ctrl_down else character
if state.pending_dead_key and named not in MODIFIER_NAMES:
state.pending_dead_key = None
return named
character = translate(vk, scan, state.bytes_for())
+ altgr_text = state.altgr_down and not state.ctrl_down and character != translate(vk, scan, state.bytes_for(False))
if isinstance(character, DeadKey):
+ if state.ctrl_down:
+ return character.character
if down:
state.pending_dead_key = character.character
return DeadKey(character.character)
@@ -391,6 +400,9 @@ def key_name(
if down and state.pending_dead_key:
character = _compose_dead_key(state.pending_dead_key, character)
state.pending_dead_key = None
+ altgr_text = state.altgr_down and not state.ctrl_down
+ if down and altgr_text and isinstance(character, str):
+ return TextInput(character)
return character
@@ -525,6 +537,8 @@ class Hooks:
self._state = KeyboardState()
self._dead_keys_swallowed: Set[int] = set()
self._text_keyups_swallowed: Set[int] = set()
+ self._key_names: Dict[int, Tuple[str, Optional[str]]] = {}
+ self._composed_local: Dict[int, Union[DeadKey, TextInput]] = {}
self._failure: Optional[BaseException] = None
self._handles: List[int] = []
# Kept alive for as long as the hooks are installed: a callback that
@@ -562,8 +576,14 @@ class Hooks:
LOGGER.error("The hook thread did not stop within two seconds")
else:
self._text_keyups_swallowed.clear()
+ self._key_names.clear()
+ self._dead_keys_swallowed.clear()
+ self._composed_local.clear()
else:
self._text_keyups_swallowed.clear()
+ self._key_names.clear()
+ self._dead_keys_swallowed.clear()
+ self._composed_local.clear()
self._thread = None
self._thread_id = None
@@ -617,6 +637,9 @@ class Hooks:
_unregister_window_class(module)
self._callbacks = []
self._text_keyups_swallowed.clear()
+ self._key_names.clear()
+ self._dead_keys_swallowed.clear()
+ self._composed_local.clear()
def _window_proc(self, hwnd, message, wparam, lparam):
if message == WM_INPUT:
@@ -638,37 +661,78 @@ class Hooks:
down = wparam in KEY_DOWN_MESSAGES
if not down and wparam not in KEY_UP_MESSAGES:
return user32.CallNextHookEx(None, code, wparam, lparam)
+ if data.vkCode == 0xA2 and data.scanCode == 0x21D:
+ # AltGr's synthetic Ctrl shares a VK with a real held Ctrl, but is not its release.
+ return user32.CallNextHookEx(None, code, wparam, lparam)
if data.vkCode in (0xA0, 0xA1, 0x10): # noqa: shift, either side
self._state.shift_down = down
elif data.vkCode == VK_CAPITAL and down:
self._state.caps_lock = not self._state.caps_lock
+ elif data.vkCode == 0xA5:
+ self._state.altgr_down = down
+ elif data.vkCode in (0x11, 0xA2, 0xA3) and data.scanCode != 0x21D:
+ # Windows marks AltGr's synthetic left Ctrl with scan code 0x21D.
+ if down:
+ self._state.ctrl_down.add(data.vkCode)
+ else:
+ self._state.ctrl_down.discard(data.vkCode)
+ if data.vkCode in self._composed_local:
+ if not down:
+ name = self._composed_local.pop(data.vkCode)
+ self._on_key(name, False, data.vkCode, None)
+ return user32.CallNextHookEx(None, code, wparam, lparam)
+ held = self._key_names.get(data.vkCode)
+ if held is not None:
+ if not down:
+ del self._key_names[data.vkCode]
+ if self._on_key(held[0], down, data.vkCode, held[1]):
+ return 1
+ return user32.CallNextHookEx(None, code, wparam, lparam)
+ if data.vkCode in self._dead_keys_swallowed:
+ if not down:
+ self._dead_keys_swallowed.discard(data.vkCode)
+ self._on_key(DeadKey(""), False, data.vkCode, None)
+ return 1
if data.vkCode in self._text_keyups_swallowed:
if not down:
self._text_keyups_swallowed.discard(data.vkCode)
+ self._on_key(TextInput(""), False, data.vkCode, None)
else:
repeated = key_name(data.vkCode, data.scanCode, self._state, _to_unicode, True)
- if isinstance(repeated, str) and len(repeated) == 1:
+ if self._state.ctrl_down and isinstance(repeated, str):
+ us = None if data.flags & LLKHF_EXTENDED else SCAN_TO_US.get(data.scanCode)
+ self._text_keyups_swallowed.discard(data.vkCode)
+ self._key_names[data.vkCode] = (repeated, us)
+ if self._on_key(repeated, True, data.vkCode, us):
+ return 1
+ return user32.CallNextHookEx(None, code, wparam, lparam)
+ elif isinstance(repeated, str) and len(repeated) == 1:
self._on_key(TextInput(repeated), True, data.vkCode, None)
+ elif isinstance(repeated, TextInput):
+ self._on_key(repeated, True, data.vkCode, None)
return 1
name = key_name(data.vkCode, data.scanCode, self._state, _to_unicode, down)
if isinstance(name, TextInput):
if down and self._on_key(name, down, data.vkCode, None):
self._text_keyups_swallowed.add(data.vkCode)
return 1
+ if down:
+ self._composed_local[data.vkCode] = name
return user32.CallNextHookEx(None, code, wparam, lparam)
if isinstance(name, DeadKey):
- if not down and data.vkCode in self._dead_keys_swallowed:
- self._dead_keys_swallowed.discard(data.vkCode)
- return 1
if down and self._on_key(name, down, data.vkCode, None):
self._dead_keys_swallowed.add(data.vkCode)
return 1
if down:
self._state.pending_dead_key = None
+ self._composed_local[data.vkCode] = name
return user32.CallNextHookEx(None, code, wparam, lparam)
if name is None:
return user32.CallNextHookEx(None, code, wparam, lparam)
us = None if data.flags & LLKHF_EXTENDED else SCAN_TO_US.get(data.scanCode)
+ if down:
+ # A repeat and release belong to this press even if layout or AltGr changes.
+ self._key_names[data.vkCode] = (name, us)
if self._on_key(name, down, data.vkCode, us):
return 1
except Exception:
@@ -798,6 +862,11 @@ if _IS_WINDOWS:
ctypes.c_void_p,
]
user32.GetKeyboardLayout.restype = ctypes.c_void_p
+ user32.GetKeyboardLayout.argtypes = [ctypes.c_ulong]
+ user32.GetForegroundWindow.restype = ctypes.c_void_p
+ user32.GetForegroundWindow.argtypes = []
+ user32.GetWindowThreadProcessId.restype = ctypes.c_ulong
+ user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]
# Handles are pointers: without these, ctypes truncates them to a 32-bit
# int and a 64-bit module handle comes back as rubbish.
kernel32.GetModuleHandleW.restype = ctypes.c_void_p
@@ -925,7 +994,7 @@ def hand_motion(flags: int, last_x: int, last_y: int, extra_information: int) ->
def _to_unicode(vk: int, scan: int, state: Dict[int, int]) -> Optional[Union[str, DeadKey]]:
"""The character `vk` types under `state`, or None. Called with the
- non-shift modifiers already cleared, so a chord yields its plain key.
+ shortcut modifiers cleared, or AltGr added to read its printable text.
ToUnicodeEx is asked not to change the keyboard state (the 1<<2 flag):
the dead accent is tracked in KeyboardState instead.
@@ -936,7 +1005,10 @@ def _to_unicode(vk: int, scan: int, state: Dict[int, int]) -> Optional[Union[str
for key, value in state.items():
key_state[key] = bytes([value])
buffer = ctypes.create_unicode_buffer(8)
- layout = user32.GetKeyboardLayout(0)
+ # The hook's thread does not follow the foreground app's input-language changes.
+ window = user32.GetForegroundWindow()
+ thread = user32.GetWindowThreadProcessId(window, None) if window else 0
+ layout = user32.GetKeyboardLayout(thread)
count = user32.ToUnicodeEx(vk, scan, key_state, buffer, len(buffer), 1 << 2, layout)
if count < 0:
return DeadKey(buffer.value[:abs(count)]) if buffer.value else None
diff --git a/win_app/clipboard_win.py b/win_app/clipboard_win.py
index 92a1e77..97dd7b7 100644
--- a/win_app/clipboard_win.py
+++ b/win_app/clipboard_win.py
@@ -23,6 +23,7 @@ import ctypes
import logging
import struct
import sys
+import threading
import time
from typing import Optional, Tuple
@@ -57,6 +58,14 @@ if _IS_WINDOWS:
kernel32.GlobalSize.argtypes = [ctypes.c_void_p]
user32.GetClipboardSequenceNumber.restype = ctypes.c_uint32
user32.GetClipboardSequenceNumber.argtypes = []
+ user32.CreateWindowExW.restype = ctypes.c_void_p
+ user32.CreateWindowExW.argtypes = [
+ ctypes.c_uint32, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32,
+ ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
+ ]
+ user32.DestroyWindow.restype = ctypes.c_int
+ user32.DestroyWindow.argtypes = [ctypes.c_void_p]
CF_DIB = 8
CF_UNICODETEXT = 13
@@ -76,6 +85,8 @@ _ALPHA_MASK = 0xFF000000
# then and after forget_sync. A switch sends the clipboard only when the number has moved since,
# so an unchanged screenshot is not pushed across on every switch.
_synced_sequence = None
+_written_sequence = None
+_LOCK = threading.RLock()
OPEN_RETRY_ATTEMPTS = 5
OPEN_RETRY_DELAY_SECONDS = 0.05
@@ -203,13 +214,13 @@ def dib_to_png(dib: bytes) -> Optional[bytes]:
return None
-def _open_clipboard(win32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep):
- """Try OpenClipboard(None) up to `attempts` times, sleeping `delay`
+def _open_clipboard(win32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep, owner=None):
+ """Try OpenClipboard(owner) up to `attempts` times, sleeping `delay`
seconds between tries. Pure orchestration over an injected `win32` (the
real user32 WinDLL, or a duck-typed fake) so the retry/backoff decision
is testable without a real Windows clipboard."""
for attempt in range(attempts):
- if win32.OpenClipboard(None):
+ if win32.OpenClipboard(owner):
return True
if attempt + 1 < attempts:
sleep(delay)
@@ -276,8 +287,16 @@ def _get_contents(win32, mem32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_D
LOGGER.warning("could not open the clipboard for reading")
return None, None
try:
- text = _read_clipboard_text(win32, mem32)
- dib = _read_clipboard_dib(win32, mem32)
+ try:
+ text = _read_clipboard_text(win32, mem32)
+ except Exception:
+ LOGGER.exception("failed to read clipboard text")
+ text = None
+ try:
+ dib = _read_clipboard_dib(win32, mem32)
+ except Exception:
+ LOGGER.exception("failed to read the clipboard image")
+ dib = None
finally:
win32.CloseClipboard()
# Converted after the clipboard is closed: a Retina-sized DIB takes
@@ -286,28 +305,40 @@ def _get_contents(win32, mem32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_D
return text, dib_to_png(dib) if dib is not None else None
-def _set_contents(win32, mem32, text, png, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep):
+def _set_contents(win32, mem32, text, png, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep, written=None):
dib = png_to_dib(png) if png is not None else None
if png is not None and dib is None:
LOGGER.warning("inbound clipboard image did not decode; setting the text only")
if text is None and dib is None:
return False
- if not _open_clipboard(win32, attempts, delay, sleep):
- LOGGER.warning("could not open the clipboard for writing")
+ # EmptyClipboard with a NULL owner makes SetClipboardData fail. A message-only window
+ # belongs to this worker even when the app has no visible panel, and never takes focus.
+ owner = win32.CreateWindowExW(0, "STATIC", None, 0, 0, 0, 0, 0, -3, None, None, None)
+ if not owner:
+ LOGGER.warning("could not create the clipboard owner")
return False
try:
- win32.EmptyClipboard()
- wrote = False
- if text is not None:
- # CF_UNICODETEXT is CRLF by convention; a Mac's LF alone reads as one
- # line in the older Windows apps.
- text = text.replace("\r\n", "\n").replace("\n", "\r\n")
- wrote |= _put_clipboard_data(win32, mem32, CF_UNICODETEXT, text.encode("utf-16-le") + b"\x00\x00")
- if dib is not None:
- wrote |= _put_clipboard_data(win32, mem32, CF_DIB, dib)
- return wrote
+ if not _open_clipboard(win32, attempts, delay, sleep, owner=owner):
+ LOGGER.warning("could not open the clipboard for writing")
+ return False
+ try:
+ if not win32.EmptyClipboard():
+ return False
+ wrote = False
+ if text is not None:
+ # CF_UNICODETEXT is CRLF by convention; a Mac's LF alone reads as one
+ # line in the older Windows apps.
+ text = text.replace("\r\n", "\n").replace("\n", "\r\n")
+ wrote |= _put_clipboard_data(win32, mem32, CF_UNICODETEXT, text.encode("utf-16-le") + b"\x00\x00")
+ if dib is not None:
+ wrote |= _put_clipboard_data(win32, mem32, CF_DIB, dib)
+ if wrote and written is not None:
+ written(win32.GetClipboardSequenceNumber())
+ return wrote
+ finally:
+ win32.CloseClipboard()
finally:
- win32.CloseClipboard()
+ win32.DestroyWindow(owner)
def get_contents() -> Tuple[Optional[str], Optional[bytes]]:
@@ -317,7 +348,8 @@ def get_contents() -> Tuple[Optional[str], Optional[bytes]]:
if not _IS_WINDOWS:
return None, None
try:
- return _get_contents(user32, kernel32)
+ with _LOCK:
+ return _get_contents(user32, kernel32)
except Exception:
LOGGER.exception("failed to read the Windows clipboard")
return None, None
@@ -350,18 +382,23 @@ def forget_sync() -> None:
_synced_sequence = None
+def write_stamp():
+ """The last peer write, rather than a newer copy made after CloseClipboard."""
+ return _written_sequence
+
+
def set_contents(text: Optional[str], png: Optional[bytes]) -> bool:
"""Replace the Windows clipboard with `text` and/or `png`. Returns True
when at least one was set, False if this isn't Windows or the write
failed. Never raises."""
- global _synced_sequence
if not _IS_WINDOWS:
return False
+ def remember(sequence):
+ global _synced_sequence, _written_sequence
+ _synced_sequence = _written_sequence = sequence
try:
- wrote = _set_contents(user32, kernel32, text, png)
- if wrote:
- _synced_sequence = user32.GetClipboardSequenceNumber()
- return wrote
+ with _LOCK:
+ return _set_contents(user32, kernel32, text, png, written=remember)
except Exception:
LOGGER.exception("failed to set the Windows clipboard")
return False
diff --git a/win_app/diagram.py b/win_app/diagram.py
index 203a68a..4e39fac 100644
--- a/win_app/diagram.py
+++ b/win_app/diagram.py
@@ -15,6 +15,7 @@ import pages_win
import theme
import tokens
from core import ways
+from core.identify_screens import display_numbers
from core.resistance_strip import MAX_RESISTANCE, resistance_x
OTHER = N_("Other machine")
@@ -893,7 +894,11 @@ class AtlasCanvas(QWidget):
@staticmethod
def _title_top(rect):
- return rect.top()+7 if rect.height() >= 56 else rect.center().y()-11
+ if rect.height() < 32:
+ return rect.top() + 11
+ if rect.height() < 44:
+ return rect.top() + max(12, rect.height() - 21)
+ return rect.top() + (4 if rect.height() < 56 else 7)
def _shows_cycle(self, peer):
return (not self.remote and not self.read_only and self.cycle_mode == "ticked"
@@ -903,11 +908,14 @@ class AtlasCanvas(QWidget):
def _cycle_box(rect):
"""The shortcut-cycle tick: its own column at the right end of the name's line, or in the
bottom row of a tile 44 to 56pt tall, leaving its corner free for the resize grip."""
+ if rect.height() < 32:
+ return QRectF(rect.right() - 15, rect.top() + 1, 10, 10)
if 44 <= rect.height() < 56:
return QRectF(rect.right() - RESIZE_GRIP - 4 - CYCLE_BOX,
rect.bottom() - 4 - CYCLE_BOX, CYCLE_BOX, CYCLE_BOX)
margin = RESIZE_GRIP + 4 if rect.height() < 44 else 8
- return QRectF(rect.right() - margin - CYCLE_BOX, AtlasCanvas._title_top(rect) + 11 - CYCLE_BOX/2,
+ title_half = 10 if rect.height() < 56 else 11
+ return QRectF(rect.right() - margin - CYCLE_BOX, AtlasCanvas._title_top(rect) + title_half - CYCLE_BOX/2,
CYCLE_BOX, CYCLE_BOX)
@staticmethod
@@ -915,11 +923,18 @@ class AtlasCanvas(QWidget):
return AtlasCanvas._cycle_box(rect).adjusted(-4, -4, 4, 4)
def _title_rect(self, peer, rect):
+ return self._beside_display_numbers(self._title_without_numbers(peer, rect),
+ [box for _, _, box in self._display_number_boxes(peer, rect)])
+
+ def _title_without_numbers(self, peer, rect):
"""The name's text rect. Beside the shortcut-cycle tick the name stays centred on the tile while
it fits the room left symmetric by the tick, else takes the room left of the tick; a tile 44 to
56pt tall puts the name on its own row above the tick, 20pt tall so a 44pt tile still fits both."""
+ if rect.height() < 32:
+ return QRectF(rect.left() + 5, rect.top() + 11, max(1, rect.width() - 10), max(1, rect.height() - 12))
if not self._shows_cycle(peer):
- return QRectF(rect.left()+8, self._title_top(rect), max(1, rect.width()-16), 22)
+ return QRectF(rect.left()+8, self._title_top(rect), max(1, rect.width()-16),
+ 20 if rect.height() < 56 else 22)
if 44 <= rect.height() < 56:
return QRectF(rect.left()+8, rect.top()+4, max(1, rect.width()-16), 20)
room = 8 + CYCLE_BOX + 6
@@ -927,10 +942,40 @@ class AtlasCanvas(QWidget):
if (rect.height() >= 56 and QFontMetrics(theme.font(tokens.TYPE["body"], 650)).horizontalAdvance(label)
<= rect.width() - 2*room):
return QRectF(rect.left()+room, self._title_top(rect), rect.width()-2*room, 22)
- return QRectF(rect.left()+8, self._title_top(rect), max(1, self._cycle_box(rect).left()-6-rect.left()-8), 22)
+ return QRectF(rect.left()+8, self._title_top(rect), max(1, self._cycle_box(rect).left()-6-rect.left()-8),
+ 20 if rect.height() < 56 else 22)
+
+ def _display_number_boxes(self, peer, rect):
+ tile = self.tiles[peer]
+ boxes = []
+ for display, number in display_numbers(tile).items():
+ frame = self.display_rect(peer, display) if tile.get("displays") else rect
+ if rect.height() < 32:
+ box = QRectF(frame.left() + 5, frame.top() + 1, 12, 8)
+ elif rect.height() < 44:
+ box = QRectF(frame.left() + 5, frame.top() + 1, 14, 10)
+ elif rect.height() < 56:
+ box = QRectF(frame.left() + 5, frame.bottom() - 15, 16, 14)
+ else:
+ box = QRectF(frame.left() + 5, frame.bottom() - 21, 18, 16)
+ boxes.append((display, number, box))
+ return boxes
+
+ @staticmethod
+ def _beside_display_numbers(row, badges):
+ spans = [(row.left(), row.right())]
+ for badge in badges:
+ if badge.bottom() < row.top() or badge.top() > row.bottom():
+ continue
+ spans = [(a, b) for left, right in spans
+ for a, b in ((left, min(right, badge.left() - 4)),
+ (max(left, badge.right() + 4), right)) if b > a]
+ left, right = max(spans, key=lambda span: span[1] - span[0], default=(row.left(), row.left()))
+ return QRectF(left, row.top(), max(0, right - left), row.height())
def paintEvent(self, _event):
self._geometry()
+ self.display_number_rects = []
self.seam_paths = []
self.wrap_marks = []
self.wrap_label_rects = []
@@ -968,6 +1013,8 @@ class AtlasCanvas(QWidget):
painter.setBrush(_colour(fill))
painter.drawRoundedRect(rect, tokens.RADIUS["button"], tokens.RADIUS["button"])
displays = tile.get("displays") or {}
+ number_boxes = self._display_number_boxes(peer, rect)
+ badge_rects = [box for _, _, box in number_boxes]
if isinstance(displays, dict) and len(displays) > 1:
for screen in ways._display_frames(tile):
screen_rect = self.display_rect(peer, screen["display"]).adjusted(2, 2, -2, -2)
@@ -989,7 +1036,7 @@ class AtlasCanvas(QWidget):
sentence_keys = state_data.get("sentence_keys", [])
legacy = state_data.get("legacy", False)
painter.setPen(_colour("ink"))
- painter.setFont(theme.font(tokens.TYPE["body"], 650))
+ painter.setFont(theme.font(10 if rect.height() < 32 else tokens.TYPE["body"], 650))
title = self.labels.get(peer, f"Machine · {peer[-6:]}")
title_room = self._title_rect(peer, rect)
painter.drawText(title_room, Qt.AlignmentFlag.AlignCenter,
@@ -999,10 +1046,12 @@ class AtlasCanvas(QWidget):
if detail and rect.height() >= 56:
painter.setPen(_colour("ink_2"))
painter.setFont(theme.font(tokens.TYPE["note"]))
- painter.drawText(QRectF(rect.left()+24, rect.top()+31, max(1, rect.width()-32), 16),
+ detail_room = self._beside_display_numbers(
+ QRectF(rect.left()+24, rect.top()+31, max(1, rect.width()-32), 16), badge_rects)
+ painter.drawText(detail_room,
Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignLeft,
painter.fontMetrics().elidedText(detail, Qt.TextElideMode.ElideRight,
- max(1, round(rect.width()-32))))
+ max(1, round(detail_room.width()))))
if legacy and rect.height() >= 78:
painter.setPen(_colour("amber"))
painter.setFont(theme.font(tokens.TYPE["note"]))
@@ -1024,8 +1073,19 @@ class AtlasCanvas(QWidget):
painter.setPen(_colour("signal" if foot == "Crosses" else "amber" if foot in
("Drag to connect", "Overlaps") else "ink_3"))
painter.setFont(theme.font(tokens.TYPE["note"]))
- painter.drawText(QRectF(rect.left()+7, rect.bottom()-24, max(1, rect.width()-14), 16),
- Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter, foot)
+ footer_room = self._beside_display_numbers(
+ QRectF(rect.left()+7, rect.bottom()-24, max(1, rect.width()-14), 16), badge_rects)
+ painter.drawText(footer_room, Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
+ painter.fontMetrics().elidedText(foot, Qt.TextElideMode.ElideRight,
+ max(1, round(footer_room.width()))))
+ for display, number, number_box in number_boxes:
+ self.display_number_rects.append((peer, display, number, number_box))
+ painter.setPen(QPen(_colour("edge"), 1.0))
+ painter.setBrush(_colour("ground"))
+ painter.drawRoundedRect(number_box, 3, 3)
+ painter.setFont(theme.mono_font(7 if rect.height() < 32 else 8 if rect.height() < 44 else 10, 700))
+ painter.setPen(_colour("ink"))
+ painter.drawText(number_box, Qt.AlignmentFlag.AlignCenter, str(number))
if self._shows_cycle(peer):
box = self._cycle_box(rect)
ticked = bool(self.cycle.get(peer, True))
@@ -1038,9 +1098,10 @@ class AtlasCanvas(QWidget):
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
painter.setBrush(Qt.BrushStyle.NoBrush)
- check = QPainterPath(QPointF(box.left()+4.5, box.top()+8.5))
- check.lineTo(box.left()+7, box.top()+11)
- check.lineTo(box.left()+11.5, box.top()+5)
+ tick_scale = box.width() / CYCLE_BOX
+ check = QPainterPath(QPointF(box.left()+4.5*tick_scale, box.top()+8.5*tick_scale))
+ check.lineTo(box.left()+7*tick_scale, box.top()+11*tick_scale)
+ check.lineTo(box.left()+11.5*tick_scale, box.top()+5*tick_scale)
painter.drawPath(check)
painter.setOpacity(1.0)
own_id = self._own_id()
diff --git a/win_app/firewall_win.py b/win_app/firewall_win.py
index 97ce77e..54c500e 100644
--- a/win_app/firewall_win.py
+++ b/win_app/firewall_win.py
@@ -15,7 +15,7 @@ import subprocess
import sys
from typing import Iterable, Optional, Sequence
-from core import protocol
+from core import protocol, windows_tools
from core.i18n import tr
LOGGER = logging.getLogger(__name__)
@@ -278,15 +278,14 @@ def _powershell(script: str, timeout: float = 60.0) -> str:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
- completed = subprocess.run(
+ completed = windows_tools.run(
[exe, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
- capture_output=True,
+ encoding="utf-8",
timeout=timeout,
- creationflags=subprocess.CREATE_NO_WINDOW,
startupinfo=startupinfo,
)
- stdout = completed.stdout.decode("utf-8", errors="replace")
- stderr = completed.stderr.decode("utf-8", errors="replace").strip()
+ stdout = completed.stdout
+ stderr = completed.stderr.strip()
if completed.returncode != 0:
raise RuntimeError(stderr.splitlines()[0] if stderr else f"PowerShell exited with code {completed.returncode}")
return stdout
diff --git a/win_app/identify_layer_shell.py b/win_app/identify_layer_shell.py
new file mode 100644
index 0000000..d8f59dd
--- /dev/null
+++ b/win_app/identify_layer_shell.py
@@ -0,0 +1,128 @@
+"""Optional system-GTK helper: layer-shell is not part of Qt's Python bindings.
+
+ https://wmww.github.io/gtk-layer-shell/
+ A missing binding, compositor protocol or exact monitor match leaves Qt to fall back.
+"""
+
+import json
+import sys
+
+
+def run():
+ import cairo
+ import gi
+
+ gi.require_foreign("cairo")
+ gi.require_version("Gdk", "3.0")
+ gi.require_version("Gtk", "3.0")
+ gi.require_version("GtkLayerShell", "0.1")
+ gi.require_version("PangoCairo", "1.0")
+ from gi.repository import Gdk, GLib, Gtk, GtkLayerShell, Pango, PangoCairo
+
+ if not Gtk.init_check([])[0]:
+ print("GTK could not open the Wayland display", file=sys.stderr, flush=True)
+ return 1
+ if not GtkLayerShell.is_supported():
+ print("The Wayland compositor does not offer layer-shell", file=sys.stderr, flush=True)
+ return 1
+ assignments, palette, face = json.loads(sys.argv[1]), json.loads(sys.argv[2]), sys.argv[3]
+ display = Gdk.Display.get_default()
+ monitors = [display.get_monitor(index) for index in range(display.get_n_monitors())]
+ matched = []
+ for assignment in assignments:
+ monitor = next((monitor for monitor in monitors if
+ [monitor.get_geometry().x, monitor.get_geometry().y,
+ monitor.get_geometry().width, monitor.get_geometry().height] == assignment["geometry"]), None)
+ if monitor is None:
+ geometries = [[m.get_geometry().x, m.get_geometry().y,
+ m.get_geometry().width, m.get_geometry().height] for m in monitors]
+ print(f"GTK monitor geometry mismatch: wanted {assignment['geometry']}, available {geometries}",
+ file=sys.stderr, flush=True)
+ return 1
+ monitors.remove(monitor)
+ matched.append((monitor, assignment["number"]))
+
+ def rgb(value):
+ return tuple(int(value[index:index + 2], 16) / 255 for index in (1, 3, 5))
+
+ drawn = set()
+ ready = False
+
+ def draw(widget, context, number):
+ nonlocal ready
+ context.set_operator(cairo.OPERATOR_SOURCE)
+ context.set_source_rgba(0, 0, 0, 0)
+ context.paint()
+ context.set_operator(cairo.OPERATOR_OVER)
+ size = widget.get_allocated_width()
+ radius = 12
+ for x, y, start in ((size-radius, radius, -90), (size-radius, size-radius, 0),
+ (radius, size-radius, 90), (radius, radius, 180)):
+ import math
+ context.arc(x, y, radius - 0.5, math.radians(start), math.radians(start + 90))
+ context.close_path()
+ context.set_source_rgb(*rgb(palette["panel"]))
+ context.fill_preserve()
+ context.set_source_rgb(*rgb(palette["edge"]))
+ context.set_line_width(1)
+ context.stroke()
+ layout = PangoCairo.create_layout(context)
+ font = Pango.FontDescription.from_string(face)
+ font.set_absolute_size(112 * Pango.SCALE)
+ font.set_weight(Pango.Weight.BOLD)
+ layout.set_font_description(font)
+ layout.set_text(str(number), -1)
+ _, ink = layout.get_pixel_extents()
+ context.move_to((size - ink.width) / 2 - ink.x, (size - ink.height) / 2 - ink.y)
+ context.set_source_rgb(*rgb(palette["ink"]))
+ PangoCairo.show_layout(context, layout)
+ drawn.add(widget)
+ if not ready and len(drawn) == len(windows):
+ ready = True
+ focus = {"focus_window": any(window.has_toplevel_focus() for window in windows),
+ "active_window": any(window.is_active() for window in windows),
+ "active_overlay": any(window.has_focus() for window in windows)}
+ print("focus " + json.dumps(focus), flush=True)
+ if any(focus.values()):
+ Gtk.main_quit()
+ return False
+ print("ready", flush=True)
+ GLib.timeout_add(3000, lambda: (Gtk.main_quit(), False)[1])
+ return False
+
+ windows = []
+ for monitor, number in matched:
+ # Layer-shell supplies the role; Gtk toplevels wait for a separate WM configure.
+ window = Gtk.Window(type=Gtk.WindowType.POPUP)
+ window.set_accept_focus(False)
+ window.set_focus_on_map(False)
+ window.set_decorated(False)
+ window.set_app_paintable(True)
+ visual = window.get_screen().get_rgba_visual()
+ if visual is not None:
+ window.set_visual(visual)
+ window.set_default_size(208, 208)
+ GtkLayerShell.init_for_window(window)
+ GtkLayerShell.set_namespace(window, "beamer-identify")
+ GtkLayerShell.set_layer(window, GtkLayerShell.Layer.OVERLAY)
+ GtkLayerShell.set_monitor(window, monitor)
+ GtkLayerShell.set_keyboard_mode(window, GtkLayerShell.KeyboardMode.NONE)
+ GtkLayerShell.set_exclusive_zone(window, -1)
+ window.connect("draw", draw, number)
+ window.connect("realize", lambda widget: widget.input_shape_combine_region(cairo.Region()))
+ windows.append(window)
+ for window in windows:
+ window.show_all()
+
+ Gtk.main()
+ for window in windows:
+ window.destroy()
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(run())
+ except (ImportError, ValueError, RuntimeError, AttributeError) as exc:
+ print(f"Layer-shell helper {type(exc).__name__}: {str(exc)[:512]}", file=sys.stderr, flush=True)
+ raise SystemExit(1)
diff --git a/win_app/identify_overlay.py b/win_app/identify_overlay.py
new file mode 100644
index 0000000..0edbf88
--- /dev/null
+++ b/win_app/identify_overlay.py
@@ -0,0 +1,317 @@
+"""Brief, input-transparent display numbers, on the GUI thread."""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from pathlib import Path
+import sys
+
+from PySide6.QtCore import QObject, QProcess, QProcessEnvironment, QRect, QRectF, Qt, QTimer
+from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPen
+from PySide6.QtWidgets import QWidget
+
+sys.path.append(str(Path(__file__).resolve().parent.parent))
+
+from core.identify_screens import OVERLAY_SECONDS
+from core.i18n import tr
+
+import edge_glow
+import theme
+import tokens
+
+LOGGER = logging.getLogger(__name__)
+DURATION_MS = round(OVERLAY_SECONDS * 1000)
+CARD_SIZE = 208
+
+
+def _position(rect):
+ return (rect.get("x", 0), rect.get("y", 0)) if isinstance(rect, dict) else (rect.x, rect.y)
+
+
+def screen_assignments(screens, displays, labels, *, wayland=False):
+ """Native monitor enumeration may differ from Qt's; match origins before indices.
+
+ The portal's display keys already index Qt's cached screens, whereas Windows and
+ XRandR enumerate physical monitors independently of Qt.
+ """
+ remaining = list(screens)
+ result = []
+ for key, number in labels.items():
+ if not remaining:
+ break
+ screen = None
+ if wayland and key.isdecimal() and int(key) < len(screens):
+ candidate = screens[int(key)]
+ if candidate in remaining:
+ screen = candidate
+ rect = displays.get(key)
+ if screen is None and rect is not None:
+ x, y = _position(rect)
+ screen = next((one for one in remaining
+ if (one.geometry().x(), one.geometry().y()) == (x, y)), None)
+ if screen is None:
+ screen = next((one for one in remaining
+ if (round(one.geometry().x() * one.devicePixelRatio()),
+ round(one.geometry().y() * one.devicePixelRatio())) == (x, y)), None)
+ if screen is None:
+ # A single-display legacy tile has no physical geometry to match.
+ if len(labels) == 1 and len(screens) == 1:
+ screen = remaining[0]
+ else:
+ continue
+ remaining.remove(screen)
+ result.append((screen, number))
+ return result
+
+
+class ScreenNumber(QWidget):
+ def __init__(self, screen, number, geometry=None):
+ super().__init__(None, Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint
+ | Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.WindowTransparentForInput
+ | Qt.WindowType.WindowDoesNotAcceptFocus)
+ self.number = number
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
+ self.setWindowTitle(tr("Beamer — Identify screens"))
+ self.setScreen(screen)
+ self.setGeometry(geometry or screen.geometry())
+ if QGuiApplication.platformName() == "xcb":
+ self.setWindowFlags((self.windowFlags() & ~Qt.WindowType.WindowType_Mask)
+ | Qt.WindowType.ToolTip | Qt.WindowType.X11BypassWindowManagerHint)
+
+ def paintEvent(self, event):
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ size = min(CARD_SIZE, self.width() - 16, self.height() - 16)
+ card = QRectF((self.width() - size) / 2, (self.height() - size) / 2, size, size)
+ painter.setBrush(QColor(tokens.PALETTE["panel"]))
+ painter.setPen(QPen(QColor(tokens.PALETTE["edge"]), 1.0))
+ painter.drawRoundedRect(card, 12, 12)
+ painter.setFont(theme.mono_font(size * 0.54, 700))
+ painter.setPen(QColor(tokens.PALETTE["ink"]))
+ painter.drawText(card, Qt.AlignmentFlag.AlignCenter, str(self.number))
+
+
+class IdentifyScreens(QObject):
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.windows = []
+ self._process = None
+ self._ready = False
+ self._backend = ""
+ self.helper_focus = None
+ self._helper_stderr = b""
+ self._pending = []
+ self._expiry = QTimer(self)
+ self._expiry.setSingleShot(True)
+ self._expiry.timeout.connect(self.stop)
+ self._startup = QTimer(self)
+ self._startup.setSingleShot(True)
+ self._startup.timeout.connect(self._fallback)
+
+ def show_numbers(self, labels, displays):
+ self.stop()
+ self.helper_focus = None
+ wayland = QGuiApplication.platformName().startswith("wayland")
+ assignments = screen_assignments(QGuiApplication.screens(), displays, labels, wayland=wayland)
+ if not assignments:
+ return
+ self._pending = assignments
+ if sys.platform.startswith("linux") and wayland:
+ self._start_layer_shell(assignments)
+ else:
+ self._show_qt()
+
+ def _start_layer_shell(self, assignments):
+ self._backend = "layer-shell"
+ self._helper_stderr = b""
+ process = QProcess(self)
+ self._process = process
+ environment = QProcessEnvironment.systemEnvironment()
+ for name in ("PYTHONHOME", "PYTHONPATH"):
+ environment.remove(name)
+ environment.insert("GDK_BACKEND", "wayland")
+ if getattr(sys, "frozen", False):
+ environment.insert("LD_LIBRARY_PATH", os.environ.get("LD_LIBRARY_PATH_ORIG", ""))
+ process.setProcessEnvironment(environment)
+ process.readyReadStandardOutput.connect(lambda: self._helper_output(process))
+ process.readyReadStandardError.connect(lambda: self._read_helper_stderr(process))
+ process.errorOccurred.connect(lambda _error: self._helper_finished(process))
+ process.finished.connect(lambda *_args: self._helper_finished(process))
+ payload = [{"geometry": [s.geometry().x(), s.geometry().y(), s.geometry().width(), s.geometry().height()],
+ "number": number} for s, number in assignments]
+ self._startup.start(5000)
+ process.start("/usr/bin/python3", [str(Path(__file__).with_name("identify_layer_shell.py")),
+ json.dumps(payload), json.dumps(tokens.PALETTE), theme.mono()])
+
+ def _start_x11(self):
+ self._backend = "XWayland frameless per-screen windows"
+ self._helper_stderr = b""
+ process = QProcess(self)
+ self._process = process
+ environment = QProcessEnvironment.systemEnvironment()
+ environment.insert("QT_QPA_PLATFORM", "xcb")
+ environment.remove("XDG_ACTIVATION_TOKEN")
+ process.setProcessEnvironment(environment)
+ process.readyReadStandardOutput.connect(lambda: self._helper_output(process))
+ process.readyReadStandardError.connect(lambda: self._read_helper_stderr(process))
+ process.errorOccurred.connect(lambda _error: self._helper_finished(process))
+ process.finished.connect(lambda *_args: self._helper_finished(process))
+ payload = [{"geometry": [s.geometry().x(), s.geometry().y(), s.geometry().width(), s.geometry().height()],
+ "name": s.name(), "number": number} for s, number in self._pending]
+ entry = [] if getattr(sys, "frozen", False) else [str(Path(__file__))]
+ self._startup.start(5000)
+ process.start(sys.executable, entry + ["--identify-x11", json.dumps(payload)])
+
+ def _helper_output(self, process):
+ while process is self._process and process.canReadLine():
+ line = bytes(process.readLine()).strip()
+ if line.startswith(b"focus "):
+ self.helper_focus = json.loads(line[6:])
+ elif line == b"ready":
+ self._ready = True
+ self._startup.stop()
+ self._expiry.start(DURATION_MS + 250)
+ LOGGER.info("Identify screens: %s", self._backend)
+
+ def _helper_finished(self, process):
+ if process is not self._process:
+ return
+ ready = self._ready
+ if not ready:
+ self._log_helper_failure(process, "exited before readiness")
+ self._process = None
+ process.deleteLater()
+ if not ready:
+ self._fallback()
+
+ def _read_helper_stderr(self, process):
+ if process is self._process:
+ self._helper_stderr = (self._helper_stderr + bytes(process.readAllStandardError()))[-2048:]
+
+ def _log_helper_failure(self, process, reason):
+ self._read_helper_stderr(process)
+ detail = self._helper_stderr.decode("utf-8", errors="replace").strip() or process.errorString()
+ LOGGER.warning("Identify screens: %s helper %s (exit %s, %s): %s", self._backend, reason,
+ process.exitCode(), process.exitStatus(), detail)
+
+ def _fallback(self):
+ self._startup.stop()
+ process = self._process
+ if process is not None:
+ self._log_helper_failure(process, "did not become ready before the startup deadline")
+ self._process = None
+ process.kill()
+ process.waitForFinished(250)
+ process.deleteLater()
+ if self._backend == "layer-shell" and os.environ.get("DISPLAY"):
+ LOGGER.info("Identify screens: Wayland layer-shell unavailable; using XWayland frameless per-screen windows")
+ self._start_x11()
+ return
+ if QGuiApplication.platformName().startswith("wayland"):
+ LOGGER.warning("Identify screens: this Wayland session has neither working layer-shell nor XWayland; no non-focusing overlay is available")
+ return
+ self._show_qt()
+
+ def _show_qt(self):
+ for screen, number in self._pending:
+ window = ScreenNumber(screen, number)
+ self.windows.append(window)
+ window.show()
+ edge_glow.keep_on_top(window)
+ self._expiry.start(DURATION_MS)
+
+ def stop(self):
+ self._startup.stop()
+ self._expiry.stop()
+ for window in self.windows:
+ window.close()
+ window.deleteLater()
+ self.windows.clear()
+ process, self._process = self._process, None
+ if process is not None:
+ process.kill()
+ process.waitForFinished(250)
+ process.deleteLater()
+ self._ready = False
+ self._backend = ""
+ self._pending = []
+
+
+def x11_screen_regions(screens, payload):
+ """Match outputs across Qt backends by connector or geometry, then desktop fraction.
+
+ XWayland may expose one virtual output for the whole desktop. In that case the
+ existing crossing helper's desktop-fraction mapping retains each source region.
+ """
+ from effect_overlay_x11 import mapped_point
+
+ source = QRect()
+ target = QRect()
+ for item in payload:
+ source = source.united(QRect(*item["geometry"]))
+ for screen in screens:
+ target = target.united(screen.geometry())
+ remaining = list(screens)
+ found = []
+ for item in payload:
+ rect = QRect(*item["geometry"])
+ screen = (next((s for s in remaining if s.name() == item["name"]), None)
+ if len(screens) == len(payload) else None)
+ if screen is None and len(screens) == len(payload):
+ screen = next((s for s in remaining if s.geometry() == rect), None)
+ if screen is None and len(screens) == len(payload):
+ x, y = mapped_point(rect.center().x(), rect.center().y(),
+ [source.x(), source.y(), source.width(), source.height()], target)
+ screen = min(remaining, key=lambda s: (s.geometry().center().x()-x)**2
+ + (s.geometry().center().y()-y)**2)
+ if screen is not None:
+ remaining.remove(screen)
+ found.append((screen, item["number"], screen.geometry()))
+ elif len(screens) == 1:
+ x, y = mapped_point(rect.x(), rect.y(), [source.x(), source.y(), source.width(), source.height()], target)
+ region = QRect(round(x), round(y), round(rect.width()*target.width()/source.width()),
+ round(rect.height()*target.height()/source.height()))
+ found.append((screens[0], item["number"], region))
+ else:
+ raise ValueError("XWayland output geometry does not match the desktop")
+ return found
+
+
+def run_x11_helper(payload):
+ from PySide6.QtWidgets import QApplication
+
+ app = QApplication([])
+ app.setQuitOnLastWindowClosed(False)
+ theme.init_fonts()
+ windows = []
+ for screen, number, geometry in x11_screen_regions(app.screens(), json.loads(payload)):
+ window = ScreenNumber(screen, number, geometry)
+ windows.append(window)
+ window.show()
+ def mapped():
+ focus = {"focus_window": app.focusWindow() is not None,
+ "active_window": app.activeWindow() is not None,
+ "active_overlay": any(window.isActiveWindow() for window in windows)}
+ print("focus " + json.dumps(focus), flush=True)
+ if any(focus.values()):
+ app.exit(1)
+ return
+ print("ready", flush=True)
+ QTimer.singleShot(DURATION_MS, app.quit)
+
+ QTimer.singleShot(100, mapped)
+ result = app.exec()
+ for window in windows:
+ window.close()
+ return result
+
+
+if __name__ == "__main__":
+ if len(sys.argv) != 3 or sys.argv[1] != "--identify-x11":
+ raise SystemExit(2)
+ raise SystemExit(run_x11_helper(sys.argv[2]))
diff --git a/win_app/inject_portal.py b/win_app/inject_portal.py
index 6bdbc35..bab78cc 100644
--- a/win_app/inject_portal.py
+++ b/win_app/inject_portal.py
@@ -12,8 +12,8 @@ token (persist_mode 2), kept in the state directory, so later starts ask nothing
Keys are pressed by evdev code on the keyboard the desktop gives, whose layout it hands over with
the device and whose locks and group it reports as they change. A character is typed as on X11
(inject_x11.plan_key: the layout's own key, Shift worked around it, the US place under a chord),
-with two differences. The desktop's keymap cannot be changed, so a character the layout has no key
-for is not typed (logged once). And a held key is repeated by the app it reaches, not the server,
+with two differences. The desktop's keymap cannot be changed, so a character with no plain,
+Shift, AltGr or supported dead-accent sequence is not typed (logged once). And a held key is repeated by the app it reaches, not the server,
so a key typed with Shift changed around it is let go at once and each of the peer's repeats types
it again. The desktop reports a lock's new state only after the lock key is let go, a moment later,
so input after a Caps Lock or Num Lock Beamer plays waits for that report (LOCK_SECONDS at most): a
@@ -101,6 +101,8 @@ def _report_permission(status: str, detail: str = "", retryable: bool = False) -
class WaylandLayout(Layout):
"""inject_x11's Layout over the desktop's keymap, which cannot be changed: no spare keys."""
+ can_remap = False
+
def spare(self) -> List[int]:
return []
diff --git a/win_app/inject_x11.py b/win_app/inject_x11.py
index dd8087d..c27ce25 100644
--- a/win_app/inject_x11.py
+++ b/win_app/inject_x11.py
@@ -7,6 +7,8 @@ current layout group, read through XKB (xkb_x11), with Shift pressed or let go a
layout needs; when this layout has no key for it, on its US place under a chord or for a letter of
another script, as input_injector._by_place; otherwise on a spare keycode mapped to it, which stays
mapped so a second press needs no remap (every remap makes each client reread the keymap).
+Text input tries AltGr levels and canonical dead-accent sequences before remapping. Key input
+retains a held key on X11; Wayland uses those sequences because its keymap cannot be changed.
Auto-repeat is the server's, as for a key held on this machine's own keyboard: the server repeats
a key XTest holds (measured on Xvfb, 01-10-2026), so the peer's repeats of a held key are not
@@ -28,6 +30,7 @@ import logging
import os
import threading
import time
+import unicodedata
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
@@ -54,6 +57,13 @@ REMAP_PAUSE_SECONDS = 0.05
PRESS, RELEASE, MAP, NO_REPEAT, REPEAT = "press", "release", "map", "no_repeat", "repeat"
+# XKB dead-key symbols for canonical accents accepted by desktop compose tables.
+DEAD_ACCENTS = {"\u0300": 0xfe50, "\u0301": 0xfe51, "\u0302": 0xfe52,
+ "\u0303": 0xfe53, "\u0304": 0xfe54, "\u0306": 0xfe55,
+ "\u0307": 0xfe56, "\u0308": 0xfe57, "\u030a": 0xfe58,
+ "\u030b": 0xfe59, "\u030c": 0xfe5a, "\u0327": 0xfe5b,
+ "\u0328": 0xfe5c}
+
def repeat_state_file() -> Path:
"""Where the keycodes whose auto-repeat this module turned off are written: it is the X
@@ -77,10 +87,13 @@ class Layout:
key at a US place types there. `mapped` holds the spare keycodes this module mapped since the
keymap was last read."""
+ can_remap = True
+
def __init__(self, keymap) -> None:
self.keymap = keymap
self.mapped: Dict[int, int] = {}
self._found: Dict[Tuple[int, int], Dict[str, Tuple[int, bool]]] = {}
+ self._strokes: dict = {}
def find(self, character: str, group: int, locks: int) -> Optional[Tuple[int, bool]]:
"""(keycode, shift) for the key typing `character`, without Shift preferred, or None."""
@@ -126,6 +139,42 @@ class Layout:
def map(self, keycode: int, keysym: int) -> None:
self.mapped[keycode] = keysym
self._found.clear()
+ self._strokes.clear()
+
+ def sequence(self, character: str, group: int, locks: int) -> Optional[list]:
+ """Layout strokes for an AltGr character or a canonical dead-accent composition."""
+ table = self._strokes.get((group, locks))
+ if table is None:
+ keymap = self.keymap
+ levels = [(0, ()), (SHIFT_MASK, (SHIFT_L,))]
+ modifier_mask = getattr(keymap, "modifier_mask", None)
+ if modifier_mask is not None:
+ for code in range(keymap.min_keycode, keymap.max_keycode + 1):
+ if keymap.keysym(code, 0, group) == 0xfe03: # ISO_Level3_Shift
+ mask = modifier_mask(code)
+ if mask:
+ levels += [(mask, (code,)), (mask | SHIFT_MASK, (code, SHIFT_L))]
+ break
+ table = {}
+ for mask, modifiers in levels:
+ for code in range(keymap.min_keycode, keymap.max_keycode + 1):
+ symbol = keymap.keysym(code, locks | mask, group)
+ if symbol:
+ table.setdefault(symbol, (code, modifiers))
+ text = keymap.text(symbol)
+ if text:
+ table.setdefault(text, (code, modifiers))
+ self._strokes[(group, locks)] = table
+ direct = table.get(character)
+ if direct is not None:
+ return [direct]
+ decomposed = unicodedata.normalize("NFD", character)
+ if len(decomposed) == 2 and decomposed[1] in DEAD_ACCENTS:
+ dead = table.get(DEAD_ACCENTS[decomposed[1]])
+ base = table.get(decomposed[0])
+ if dead is not None and base is not None:
+ return [dead, base]
+ return None
class KeyState:
@@ -137,6 +186,7 @@ class KeyState:
# A held character: its keycode, and for one typed with Shift changed around it, whether
# it needs Shift, for each repeat to be typed again (None when the server repeats it).
self.chars_down: Dict[str, Tuple[int, Optional[bool]]] = {}
+ self.taps_down: Set[str] = set()
self.spares: Dict[int, int] = {} # keysym to keycode, least recently used first
def held_shift(self) -> List[int]:
@@ -180,6 +230,19 @@ def _shift_around(keycode: int, shift: bool, state: KeyState) -> list:
return [(PRESS, keycode)]
+def _tap_strokes(strokes: list, state: KeyState) -> Optional[list]:
+ held_keys = state.named_down | {code for code, _shift in state.chars_down.values()}
+ if any(code in held_keys for code, _modifiers in strokes):
+ return None
+ held = [NAME_TO_CODE[name] + KEYCODE_OFFSET for name in sorted(state.mods_down)]
+ steps = [(RELEASE, code) for code in held]
+ for code, modifiers in strokes:
+ steps += [(PRESS, mod) for mod in modifiers]
+ steps += [(PRESS, code), (RELEASE, code)]
+ steps += [(RELEASE, mod) for mod in reversed(modifiers)]
+ return steps + [(PRESS, code) for code in held]
+
+
_warned: Set[str] = set()
@@ -216,6 +279,18 @@ def plan_key(name: str, down: bool, us: Optional[str], state: KeyState, layout:
_warn_once("Unknown key name ignored: %r", name)
return []
character = name
+ chord = bool(state.mods_down & CHORD_KEYS)
+ if character in state.taps_down:
+ if not down:
+ state.taps_down.discard(character)
+ return []
+ if not chord:
+ strokes = layout.sequence(character, group, locks)
+ steps = _tap_strokes(strokes, state) if strokes is not None else None
+ if steps is None:
+ _warn_once("Current keyboard state cannot repeat %r", character)
+ return steps or []
+ state.taps_down.discard(character)
held = state.chars_down.get(character)
if not down:
if held is None:
@@ -228,7 +303,6 @@ def plan_key(name: str, down: bool, us: Optional[str], state: KeyState, layout:
keycode, shift = held
# Shift is worked out again: the peer may have pressed or let go of its own since.
return [] if shift is None else [(RELEASE, keycode)] + _shift_around(keycode, shift, state)
- chord = bool(state.mods_down & CHORD_KEYS)
found = layout.find(character, group, locks)
if found is not None:
keycode, shift = found
@@ -243,6 +317,11 @@ def plan_key(name: str, down: bool, us: Optional[str], state: KeyState, layout:
if place is not None:
state.chars_down[character] = (place[0], None)
return [(PRESS, place[0])]
+ strokes = layout.sequence(character, group, locks) if not chord and not layout.can_remap else None
+ steps = _tap_strokes(strokes, state) if strokes is not None else None
+ if steps is not None:
+ state.taps_down.add(character)
+ return steps
spare = _spare_steps(character, layout, state)
if spare is None:
_warn_once("No spare key left to type %r", character)
@@ -265,6 +344,11 @@ def plan_text(text: str, state: KeyState, layout: Layout, group: int, locks: int
keycode, shift = found
steps += _shift_around(keycode, shift, bare)
else:
+ strokes = layout.sequence(character, group, locks)
+ typed = _tap_strokes(strokes, bare) if strokes is not None else None
+ if typed is not None:
+ steps += typed
+ continue
spare = _spare_steps(character, layout, bare)
if spare is None:
_warn_once("No spare key left to type %r", character)
@@ -570,5 +654,6 @@ def release_all() -> None:
_state.mods_down.clear()
_state.named_down.clear()
_state.chars_down.clear()
+ _state.taps_down.clear()
_buttons_down.clear()
_scroll_carry[0] = _scroll_carry[1] = 0.0
diff --git a/win_app/input_injector.py b/win_app/input_injector.py
index 9f12727..1809c9d 100644
--- a/win_app/input_injector.py
+++ b/win_app/input_injector.py
@@ -11,6 +11,7 @@ import unicodedata
from typing import Callable, Dict, List, Optional, Set, Tuple
from core.keytable import EVDEV_US
+from core import windows_tools
LOGGER = logging.getLogger(__name__)
@@ -484,7 +485,8 @@ def inject_mouse_move(dx: int, dy: int) -> None:
# either; a click on the PC does, and so does restarting the service, which
# takes the window with it and leaves Windows to activate an ordinary one.
GAMEINPUT_WINDOW_CLASS = "GameInputServiceWindow"
-GAMEINPUT_RESTART = ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "Restart-Service GameInputSvc -Force"]
+GAMEINPUT_RESTART = ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Restart-Service GameInputSvc -Force"]
# A restart that did not free the pointer must not become a restart loop.
GAMEINPUT_RESTART_COOLDOWN_SECONDS = 60.0
@@ -539,10 +541,7 @@ def release_gameinput_foreground(after: Optional[Callable[[], None]] = None) ->
"GameInput's service window has the foreground, where Windows refuses Beamer's input; restarting GameInputSvc to free it"
)
try:
- completed = subprocess.run(
- GAMEINPUT_RESTART, capture_output=True, text=True, timeout=30,
- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
- )
+ completed = windows_tools.run(GAMEINPUT_RESTART, encoding="utf-8", timeout=30)
except (OSError, subprocess.TimeoutExpired):
LOGGER.exception("Could not restart GameInputSvc; a click on this PC frees the pointer")
return
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index 22905e3..bd7ac9b 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -71,6 +71,7 @@ from edge_glow import EdgeGlow, PreviewLoop
from frame_clock import set_divisor
from effect_overlay import EffectOverlay, desktop_box, logical_point
from effect_overlay_x11 import EffectOverlayX11Proxy, available as xwayland_available
+from identify_overlay import IdentifyScreens
from effect_previews import EffectStill, SwitchStill, TileHover
from core import idle_pointer
from core import ignored
@@ -98,6 +99,7 @@ from core.receiver import LinkResponder, ServerState
from core import return_edge
from core import settings_sync
from core import ways, crossing_state, profiles
+from core.identify_screens import display_numbers
from sender import OWN_PLATFORM, LinkSender
from shake_stroke import shake_stroke
import theme
@@ -321,6 +323,7 @@ class StatusBridge(QObject):
arrangement = Signal(str, str, int, str, object, object)
# Either link, carrying a peer's Same on all machines state: (peer id, data).
settings = Signal(str, object)
+ identify = Signal(object)
shook_home = Signal(object)
alert = Signal(str, str)
# (version, url) when a newer Beamer is out, else None.
@@ -564,6 +567,8 @@ class WindowsApplication(QWidget):
self.bridge.peers_changed.connect(self._on_peers_changed)
self.bridge.arrangement.connect(self._on_arrangement)
self.bridge.settings.connect(self._on_settings)
+ self.bridge.identify.connect(self._on_identify_screens)
+ self.identify_screens = IdentifyScreens(self)
self.bridge.shook_home.connect(self._on_shake)
self.bridge.update.connect(self._on_update)
self.bridge.rules_ready.connect(self._listen)
@@ -615,6 +620,7 @@ class WindowsApplication(QWidget):
protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None
),
settings_callback=lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data),
+ identify_callback=lambda peer, labels: self.bridge.identify.emit(labels),
paired_callback=self._store_paired,
link_callback=lambda peer, up: self.bridge.peers_changed.emit(),
announce=self._announce,
@@ -640,6 +646,7 @@ class WindowsApplication(QWidget):
),
desktop=platform_parts.desktop,
clipboard=platform_parts.clipboard,
+ mouse_only_supported=not platform_parts.WAYLAND,
)
self._own_display_map = {}
app = QApplication.instance()
@@ -656,6 +663,7 @@ class WindowsApplication(QWidget):
# Same on all machines, over either link: applied on the GUI thread, and announced with
# this PC's own arrangement the moment a link comes up.
self.sender.settings_callback = lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data)
+ self.sender.identify_callback = lambda peer, labels: self.bridge.identify.emit(labels)
self.sender.arrangement_callback = lambda peer, read: self.bridge.arrangement.emit(
protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"),
protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None
@@ -801,7 +809,25 @@ class WindowsApplication(QWidget):
row_layout.addWidget(widgets.rule())
self.stack = QStackedWidget()
- row_layout.addWidget(self.stack, 1)
+ pane = QWidget()
+ pane_layout = QVBoxLayout(pane)
+ pane_layout.setContentsMargins(0, 0, 0, 0)
+ pane_layout.setSpacing(0)
+ self.update_notice = widgets.Module("", heading=True)
+ self.update_notice_text = self.update_notice.eyebrow
+ actions = QHBoxLayout()
+ self.update_notes = QPushButton(tr("What's new"))
+ self.update_notes.clicked.connect(self.open_update)
+ actions.addWidget(self.update_notes)
+ self.update_dismiss = QPushButton(tr("Dismiss"))
+ self.update_dismiss.clicked.connect(self._dismiss_update)
+ actions.addWidget(self.update_dismiss)
+ actions.addStretch(1)
+ self.update_notice.body.addLayout(actions)
+ self.update_notice.hide()
+ pane_layout.addWidget(self.update_notice)
+ pane_layout.addWidget(self.stack, 1)
+ row_layout.addWidget(pane, 1)
outer.addWidget(row, 1)
footer = QFrame()
@@ -1105,11 +1131,43 @@ class WindowsApplication(QWidget):
def _on_update(self, found) -> None:
"""(version, url) for a newer release, or None; on the GUI thread."""
+ if self._config is None or not self._config.check_updates:
+ found = None
self._update = found
self.update_button.setText(tr("Download Beamer {version}").format(version=found[0]) if found else tr("Download"))
- motion.set_shown(self.update_button, found is not None)
+ motion.set_shown(self.update_button, found is not None and not portal.sandboxed())
self.header_action.setText(tr("Beamer {version} is available…").format(version=found[0]) if found else tr("Beamer {version}").format(version=VERSION))
self.header_action.setEnabled(found is not None)
+ self._refresh_update_notice()
+
+ def _refresh_update_notice(self) -> None:
+ try:
+ settings = app_config.load_settings(self.config_path)
+ except (ConfigError, OSError):
+ LOGGER.exception("Update notice settings could not be read")
+ self.update_notice.hide()
+ return
+ found = updates.visible_notice(self._update, self._config is not None and self._config.check_updates,
+ settings.get("dismissed_update_version", ""))
+ if found:
+ text = tr("Beamer {version} is available.").format(version=found[0])
+ if portal.sandboxed():
+ text += " " + tr("Update through your software store.")
+ self.update_notice_text.setText(text)
+ self.update_notice.setVisible(bool(found))
+
+ def _dismiss_update(self) -> None:
+ if not self._update:
+ return
+ try:
+ with app_config.SETTINGS_LOCK:
+ settings = app_config.load_settings(self.config_path)
+ settings["dismissed_update_version"] = self._update[0]
+ app_config.write_settings(self.config_path, settings)
+ except (ConfigError, OSError):
+ LOGGER.exception("Update dismissal could not be saved")
+ return
+ self._refresh_update_notice()
def open_update(self) -> None:
if self._update:
@@ -1685,6 +1743,24 @@ class WindowsApplication(QWidget):
def _send_to(self, peer: bytes, message: dict) -> bool:
return self.sender.send_to(peer, message) or self.server.send(peer, message)
+ def _identify_screens(self) -> None:
+ self._displays_changed()
+ tiles = {**self._config.layout, **ways.derive_layout(self._crossing_view_settings(), gap=0),
+ **self.atlas_canvas.tiles}
+ self._on_identify_screens(display_numbers(tiles.get(self._config.machine_id)))
+ for peer, caps in self._peer_caps().items():
+ if "identify_screens" in caps:
+ self._send_to(peer, protocol.identify_screens_msg(display_numbers(tiles.get(protocol.id_text(peer)))))
+
+ def _on_identify_screens(self, labels) -> None:
+ self._refresh_own_displays()
+ displays = self._own_displays()
+ if displays and set(labels) != set(displays):
+ physical = {key: ({"x": rect.x, "y": rect.y, "w": rect.width, "h": rect.height}
+ if not isinstance(rect, dict) else rect) for key, rect in displays.items()}
+ labels = display_numbers({"x": 0, "y": 0, "w": 160, "h": 100, "displays": physical})
+ self.identify_screens.show_numbers(labels, displays)
+
def _desk_messages(self, desk: dict, caps) -> list:
if "profiles" not in caps:
return []
@@ -1789,7 +1865,7 @@ class WindowsApplication(QWidget):
"platform": OWN_PLATFORM,
"app": VERSION[:32] if VERSION.isascii() and VERSION.isprintable() else "dev",
# A swipe has no shortcut every Linux desktop shares, so Linux does not offer gestures.
- "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt")
+ "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "identify_screens", "ping_rtt")
if not (cap == "gestures" and OWN_PLATFORM == "linux")],
"port": self._settings_port,
}
@@ -2159,7 +2235,12 @@ class WindowsApplication(QWidget):
line.addWidget(widgets.label(tr(text), "note", wrap=True))
line.addSpacing(12)
line.addStretch()
+ self.identify_button = QPushButton(tr("Identify screens"))
+ self.identify_button.setProperty("vernier", "small")
+ self.identify_button.setToolTip(tr("Show these numbers on every linked machine's screens for 3 seconds."))
+ self.identify_button.clicked.connect(self._identify_screens)
module.body.addWidget(legend)
+ module.body.addWidget(self.identify_button, 0, Qt.AlignmentFlag.AlignRight)
self.profile_switch_note = widgets.label(tr("Switching moves every machine to this profile's places and ways."), "note", wrap=True)
module.body.addWidget(self.profile_switch_note)
return module
@@ -3156,11 +3237,34 @@ class WindowsApplication(QWidget):
# -- Keyboard -----------------------------------------------------------------------------
def _keyboard_page(self, layout, current: Config) -> None:
- # The modifier keys are set once; the stays-here list is the one people come back to.
+ module = widgets.Module(tr("Keyboard sharing"))
+ self.mouse_only_switch = widgets.Switch(tr("Mouse only"))
+ self.mouse_only_switch.setChecked(current.mouse_only)
+ self.mouse_only_switch.toggled.connect(self._mouse_only_changed)
+ module.body.addWidget(self.mouse_only_switch)
+ module.body.addWidget(widgets.label(
+ tr("Keep this machine's keyboard here. Pointer and clipboard sharing stay on."), "note", wrap=True
+ ))
+ # InputCapture owns the keyboard too, so retained keys cannot reach local Wayland apps.
+ module.setVisible(not platform_parts.WAYLAND)
+ layout.addWidget(module)
layout.addWidget(self._modifier_module(current))
layout.addWidget(self._ignored_module(current))
layout.addWidget(self._speed_module(current))
+ def _mouse_only_changed(self, enabled: bool) -> None:
+ if self._config is None:
+ return
+ previous = self._config.mouse_only
+ self._config.mouse_only = bool(enabled)
+ if not self._persist():
+ self._config.mouse_only = previous
+ self.mouse_only_switch.blockSignals(True)
+ self.mouse_only_switch.setChecked(previous)
+ self.mouse_only_switch.blockSignals(False)
+ return
+ self.sender.update_config(self._config)
+
def _speed_module(self, current: Config) -> QWidget:
"""How a driving machine's pointer feels on this PC: it sends what its own acceleration made of
the hand's movement, and this PC's settings decide the rest."""
@@ -4925,6 +5029,7 @@ class WindowsApplication(QWidget):
slider.blockSignals(False)
self.speed_readouts[key].setText(f"{slider.value()}%")
for switch, value in ((self.reverse_scroll_switch, config.reverse_scroll),
+ (self.mouse_only_switch, config.mouse_only),
(self.updates_switch, config.check_updates),
(self.hide_switch, config.hide_addresses)):
switch.blockSignals(True)
@@ -4939,9 +5044,7 @@ class WindowsApplication(QWidget):
self.show_window()
def start(self) -> None:
- if not sys.platform.startswith("linux"):
- # No release has a Linux build yet, so a newer one is nothing this machine can install.
- self.update_checker.start()
+ self.update_checker.start()
if getattr(sys, "frozen", False) and firewall_win.is_elevated():
# Beamer's own rules before any socket opens: a listener Windows has no rule for makes
# it ask, and a click on Allow there writes rules for every network, public ones too,
@@ -5030,9 +5133,9 @@ class WindowsApplication(QWidget):
switches; everything else goes to the Mac only while the Mac has
input, and a key on the ignored list not even then."""
if isinstance(name, TextInput):
- return self.sender.on_text(name.text, vk)
+ return self.sender.on_text(name.text, vk, down)
if isinstance(name, DeadKey):
- return self.sender.on_dead_key(vk)
+ return self.sender.on_dead_key(vk, down)
if self.sender.handle_jump_key(name, down, vk):
return True
if not self.sender.shortcut_armed:
@@ -5226,6 +5329,8 @@ class WindowsApplication(QWidget):
def showEvent(self, event) -> None:
super().showEvent(event)
+ if hasattr(self, "update_notice"):
+ self._refresh_update_notice()
if hasattr(self, "refresh_timer"):
self._refresh_window()
self._run_previews()
@@ -5253,6 +5358,7 @@ class WindowsApplication(QWidget):
if self._closing:
return
self._closing = True
+ self.identify_screens.stop()
self.refresh_timer.stop()
self.update_checker.stop()
if self.pairing is not None:
@@ -5554,6 +5660,7 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--config", type=Path, default=default_config_path(), help="path to settings.json")
parser.add_argument("--hidden", action="store_true", help="start in the tray without showing the window")
parser.add_argument("--relaunched", action="store_true", help=argparse.SUPPRESS)
+ parser.add_argument("--identify-x11", help=argparse.SUPPRESS)
return parser.parse_args()
@@ -5635,6 +5742,9 @@ def prepare_windows_startup() -> None:
def main() -> None:
arguments = parse_args()
+ if arguments.identify_x11 is not None:
+ from identify_overlay import run_x11_helper
+ sys.exit(run_x11_helper(arguments.identify_x11))
try:
prepare_windows_startup()
except OSError:
diff --git a/win_app/sender.py b/win_app/sender.py
index 0fa72f3..6127742 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -139,6 +139,7 @@ class LinkSender:
desktop=None,
clipboard=None,
links=None,
+ mouse_only_supported=True,
is_local=is_this_machine,
clock=time.monotonic,
wake_sender=wol.send_magic_packet,
@@ -155,6 +156,7 @@ class LinkSender:
self._arrival_callback = arrival_callback
self._desktop = desktop
self._clipboard = clipboard
+ self._mouse_only_supported = mouse_only_supported
self._is_local = is_local
self._clock = clock
self._wake_sender = wake_sender
@@ -193,6 +195,7 @@ class LinkSender:
self._display_map = {}
self._monitors_at = 0.0
self._clipboard_stamp = None
+ self._clipboard_written_stamp = None
# The machine this PC's input last landed on, as an id text, for the shortcut's choice.
self._last_on: Optional[str] = None
self._jump_modifiers = set()
@@ -238,6 +241,7 @@ class LinkSender:
self.announce: Callable[[bytes], list] = lambda peer: []
self.arrangement_callback: Optional[Callable] = None
self.settings_callback: Optional[Callable] = None
+ self.identify_callback: Optional[Callable] = None
self.paired_callback: Optional[Callable] = None
self.link_callback: Optional[Callable[[bytes, bool], None]] = None
@@ -419,7 +423,8 @@ class LinkSender:
def update_config(self, config) -> None:
with self._config_lock:
self._config = config
- self._ignore_gate.configure(getattr(config, "ignored_inputs", None) or ())
+ self._ignore_gate.configure(getattr(config, "ignored_inputs", None) or (),
+ mouse_only=self._mouse_only_supported and getattr(config, "mouse_only", False))
own = protocol.read_id(getattr(config, "machine_id", "")) if config is not None else None
with self._lock:
if own is not None and own != self._own_id:
@@ -502,15 +507,19 @@ class LinkSender:
self.go(target)
return True
- def on_dead_key(self, vk: Optional[int] = None) -> bool:
+ def on_dead_key(self, vk: Optional[int] = None, down: bool = True) -> bool:
"""Swallow a dead key only while its live peer owns this PC's input."""
+ if not down:
+ if vk is not None:
+ self._ignore_gate.keeps(ignored.key(vk), False)
+ return True
owner = self._owner
if owner is None or not owner.away:
return False
if not self._live():
self._lost()
return False
- if vk is not None and self._ignore_gate.keeps(ignored.key(vk), True):
+ if self._ignore_gate.keeps_tap(ignored.key(vk) if vk is not None else "key:dead"):
return False
return True
@@ -534,12 +543,9 @@ class LinkSender:
if not self._live():
self._lost()
return False
- if vk is not None:
- entry = ignored.key(vk)
- kept = self._ignore_gate.keeps(entry, True)
- self._ignore_gate.keeps(entry, False)
- if kept:
- return False
+ entry = ignored.key(vk) if vk is not None else f"key:{name}"
+ if self._ignore_gate.keeps_tap(entry):
+ return False
if not self._input_tap(name):
return False
self._input_method_tap_releases.add(held)
@@ -552,25 +558,23 @@ class LinkSender:
data = self._keys_down.pop(held, None) or self._key_data(name, us)
if self._shake_detector is not None:
self._shake_detector.held(self._clock(), bool(self._keys_down or self._buttons_held))
+ if vk in self._intent_windows_up or vk in self._intent_keys_up:
+ if not down:
+ self._intent_windows_up.discard(vk)
+ self._intent_keys_up.discard(vk)
+ self._ignore_gate.keeps(ignored.key(vk), False)
+ return True
if owner.away:
if not self._live():
self._lost()
return False
- if vk is not None and self._ignore_gate.keeps(ignored.key(vk), down):
+ if self._ignore_gate.keeps(ignored.key(vk) if vk is not None else f"key:{name}", down):
return False
- elif vk is not None and not down:
- self._ignore_gate.keeps(ignored.key(vk), False)
+ elif not down:
+ self._ignore_gate.keeps(ignored.key(vk) if vk is not None else f"key:{name}", False)
target = self._peers.get(owner.on) or {}
to_mac = not sys.platform.startswith("linux") and target.get("platform") == "macos"
to_linux = not sys.platform.startswith("linux") and target.get("platform") == "linux"
- if vk in self._intent_windows_up:
- if not down:
- self._intent_windows_up.discard(vk)
- return True
- if vk in self._intent_keys_up:
- if not down:
- self._intent_keys_up.discard(vk)
- return True
if vk in (0x5B, 0x5C) and (to_mac or to_linux):
if down:
self._keys_down[held] = self._key_data(name, us)
@@ -581,12 +585,19 @@ class LinkSender:
self._input({"type": protocol.MSG_KEYDOWN, "data": dict(data)})
return self._input({"type": protocol.MSG_KEYUP, "data": dict(data)})
active_windows_key = self._pending_windows_key
+ remote_keys = frozenset()
+ if down and (to_mac or to_linux):
+ with self._lock:
+ remote_keys = owner.pressed_keys
if active_windows_key is None and to_mac:
- active_windows_key = next((key for key in (0x5B, 0x5C) if key in self._keys_down), None)
+ active_windows_key = next((key for key in (0x5B, 0x5C) if key in self._keys_down
+ and self._keys_down[key]["key"] in remote_keys), None)
+ other_modifiers = {0x10, 0xA0, 0xA1, 0x11, 0xA2, 0xA3, 0x12, 0xA4, 0xA5, 0x5B, 0x5C}
+ other_modifiers.discard(active_windows_key)
+ remote_modifiers = any(self._keys_down[key]["key"] in remote_keys
+ for key in other_modifiers.intersection(self._keys_down))
if down and to_mac and active_windows_key is not None and vk is not None:
- other_modifiers = {0x10, 0xA0, 0xA1, 0x11, 0xA2, 0xA3, 0x12, 0xA4, 0xA5, 0x5C}
- other_modifiers.discard(active_windows_key)
- intent = None if other_modifiers.intersection(self._keys_down) else special_keys.windows_shortcut_intent(name)
+ intent = None if remote_modifiers else special_keys.windows_shortcut_intent(name)
if intent is not None:
windows_key = active_windows_key
was_pending = self._pending_windows_key == windows_key
@@ -607,7 +618,7 @@ class LinkSender:
if pending_data is not None:
self._input({"type": protocol.MSG_KEYDOWN, "data": dict(pending_data)})
if down and to_linux and self._pending_windows_key is not None and vk is not None:
- intent = {"s": "spotlight", "h": "", "n": ""}.get(name.lower())
+ intent = None if remote_modifiers else {"s": "spotlight", "h": "", "n": ""}.get(name.lower())
if intent is not None:
windows_key = self._pending_windows_key
self._pending_windows_key = None
@@ -625,8 +636,12 @@ class LinkSender:
self._input({"type": protocol.MSG_KEYDOWN, "data": dict(pending_data)})
return self._input({"type": protocol.MSG_KEYDOWN if down else protocol.MSG_KEYUP, "data": dict(data)})
- def on_text(self, text: str, vk: Optional[int] = None) -> bool:
+ def on_text(self, text: str, vk: Optional[int] = None, down: bool = True) -> bool:
"""Sends a composed key sequence as text when this PC's input is away."""
+ if not down:
+ if vk is not None:
+ self._ignore_gate.keeps(ignored.key(vk), False)
+ return True
owner = self._owner
if owner is None:
return False
@@ -634,7 +649,8 @@ class LinkSender:
if not self._live():
self._lost()
return False
- elif vk is not None and self._ignore_gate.keeps(ignored.key(vk), True):
+ elif (self._ignore_gate.keeps(ignored.key(vk), True) if vk is not None
+ else self._ignore_gate.keeps_tap("key:text")):
return False
actions = []
with self._lock:
@@ -1009,7 +1025,7 @@ class LinkSender:
if read is not None:
with self._lock:
self._note_clipboard()
- actions = self._owner.accept(peer, read)
+ actions = self._owner.accept(peer, read) + self._owner.clipboard_pending()
self._queue(actions)
self._report(actions)
elif kind == protocol.MSG_REFUSE:
@@ -1043,6 +1059,10 @@ class LinkSender:
elif kind == protocol.MSG_SETTINGS:
if isinstance(data, dict) and self.settings_callback is not None and "settings" in self.links.caps(peer):
self._call(self.settings_callback, peer, data)
+ elif kind == protocol.MSG_IDENTIFY_SCREENS:
+ labels = protocol.read_identify_screens(message)
+ if labels is not None and self.identify_callback is not None and "identify_screens" in self.links.caps(peer):
+ self._call(self.identify_callback, peer, labels)
elif kind == protocol.MSG_PAIRED:
read = protocol.read_paired(message)
if read is not None and self.paired_callback is not None:
@@ -1160,15 +1180,20 @@ class LinkSender:
self._forget_held(peer)
self.links.close(peer, owner_module.DROPPED)
return
+ generation = stamp = None
+ if isinstance(action, owner_module.SendClipboard):
+ with self._lock:
+ stamp = self._clipboard_stamp
+ generation = self._owner._visit_route
with self._clip_lock:
waiting = self._clip_wait.get(peer)
if waiting is not None:
- waiting.append(action)
+ waiting.append((action, generation, stamp) if isinstance(action, owner_module.SendClipboard) else action)
return
if isinstance(action, owner_module.SendClipboard):
waiting = self._clip_wait[peer] = collections.deque()
try:
- self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting))
+ self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting, generation, stamp))
except RuntimeError:
# No thread at shutdown: nothing must wait behind a read that never starts.
del self._clip_wait[peer]
@@ -1176,15 +1201,35 @@ class LinkSender:
return
self._send(peer, action.message)
- def _clipboard_then_rest(self, peer: bytes, waiting) -> None:
+ def _clipboard_then_rest(self, peer: bytes, waiting, generation=None, stamp=None) -> None:
"""The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs to
the link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the
machine that reconnects will be taken afresh. A clipboard asked for again takes its turn
among the clipboard's other work, behind any write decided before it."""
+ sent = False
+ current_stamp = self._clipboard_stamp_now()
+ if current_stamp is not None and current_stamp == self._clipboard_written_stamp:
+ # A known peer write queued before this read may replace its original source stamp.
+ stamp = current_stamp
try:
- self._send_clipboard(peer, waiting)
- except Exception:
- LOGGER.exception("The clipboard could not be sent")
+ for attempt in range(3):
+ if generation is not None and (self._owner.on != peer or self._owner._visit_route != generation):
+ break
+ if attempt:
+ time.sleep(0.05)
+ if stamp is None or self._clipboard_stamp_now() != stamp:
+ break
+ try:
+ sent = self._send_clipboard(peer, waiting, generation, stamp)
+ except Exception:
+ if attempt == 2:
+ LOGGER.exception("The clipboard could not be sent")
+ if sent:
+ break
+ finally:
+ if not sent:
+ with self._lock:
+ self._owner.clipboard_failed(peer)
while True:
with self._clip_lock:
if self._clip_wait.get(peer) is not waiting:
@@ -1193,8 +1238,9 @@ class LinkSender:
del self._clip_wait[peer]
return
action = waiting.popleft()
- if isinstance(action, owner_module.SendClipboard):
- self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting))
+ if isinstance(action, tuple):
+ action, generation, stamp = action
+ self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting, generation, stamp))
return
try:
self._send(peer, action.message)
@@ -1318,46 +1364,87 @@ class LinkSender:
# -- the clipboard ------------------------------------------------------
- def _note_clipboard(self) -> None:
+ def _clipboard_stamp_now(self):
+ try:
+ return getattr(self._clipboard_module(), "change_stamp", lambda: None)()
+ except Exception:
+ LOGGER.exception("Failed to read the local clipboard's change stamp")
+ return None
+
+ def _note_clipboard(self) -> bool:
"""Under the lock, before anything that may send the clipboard: whether it changed by this
PC's own hand since this PC last sent or set it, which the owner needs to know (section 5)."""
- stamp = getattr(self._clipboard_module(), "change_stamp", lambda: None)()
+ stamp = self._clipboard_stamp_now()
if stamp is not None and stamp != self._clipboard_stamp:
self._clipboard_stamp = stamp
self._owner.clipboard_changed()
+ return True
+ return False
- def _send_clipboard(self, peer: bytes, waiting) -> None:
+ def _send_clipboard(self, peer: bytes, waiting, generation=None, stamp=None) -> Optional[bool]:
+ if generation is not None and (self._owner.on != peer or self._owner._visit_route != generation or
+ (stamp is not None and self._clipboard_stamp_now() != stamp)):
+ return
try:
text, image = self._clipboard_module().get_contents()
except Exception:
LOGGER.exception("Failed to read the local clipboard for %s", self._name(peer))
return
+ if generation is not None and (self._owner.on != peer or self._owner._visit_route != generation or
+ (stamp is not None and self._clipboard_stamp_now() != stamp)):
+ return
with self._clip_lock:
if self._clip_wait.get(peer) is not waiting:
return
caps = self.links.caps(peer)
- if text and ("clipboard" not in caps or len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES):
+ if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:
+ LOGGER.warning("Local clipboard text is too large; skipping the text")
+ text = None
+ if image is not None and not protocol.png_fits(image):
+ LOGGER.warning("Local clipboard image is invalid or too large; skipping the image")
+ image = None
+ if "clipboard" not in caps:
text = None
- if image is not None and ("clipboard_image" not in caps or not protocol.png_fits(image)):
+ if "clipboard_image" not in caps:
image = None
if not text and image is None:
return
- self.links.post(peer, protocol.clipboard_msg(text or None, image))
+ return self.links.post(peer, protocol.clipboard_msg(text or None, image))
def _set_clipboard(self, message: dict) -> None:
read = protocol.read_clipboard(message)
if read is None or (read["text"] is None and read["image"] is None):
return
- try:
- self._clipboard_module().set_contents(read["text"], read["image"])
- except Exception:
- LOGGER.exception("Failed to set the local clipboard")
- return
- self._clipboard_stamp = getattr(self._clipboard_module(), "change_stamp", lambda: None)()
+ clipboard = self._clipboard_module()
+ started_stamp = self._clipboard_stamp_now()
+ for attempt in range(3):
+ if attempt:
+ time.sleep(0.05)
+ if started_stamp is None or self._clipboard_stamp_now() != started_stamp:
+ break
+ try:
+ written = clipboard.set_contents(read["text"], read["image"])
+ except Exception:
+ written = False
+ if attempt == 2:
+ LOGGER.exception("Failed to set the local clipboard")
+ if written:
+ stamp = getattr(clipboard, "write_stamp", self._clipboard_stamp_now)()
+ with self._lock:
+ self._clipboard_stamp = stamp
+ self._clipboard_written_stamp = stamp
+ return
+ LOGGER.warning("Failed to set the local clipboard from an inbound message")
+ with self._lock:
+ self._owner.clipboard_changed()
# -- what the owner reports ---------------------------------------------
def _moved(self, moved: owner_module.Moved) -> None:
+ if self._pending_windows_key is not None:
+ # A buffered modifier belongs to the old owner; its press never reached either app.
+ self._intent_windows_up.add(self._pending_windows_key)
+ self._pending_windows_key = None
if moved.to is not None:
self._last_on = protocol.id_text(moved.to)
if self._pin_point is None:
@@ -1524,6 +1611,8 @@ class LinkSender:
return
with self._lock:
actions = owner.tick()
+ if owner.away and not self.driven() and self._note_clipboard():
+ actions += owner.clipboard_pending()
self._queue(actions)
if frozenset(owner.reach_for(None)) != self._armed_for:
# A peer began to accept this PC's input, or one left out after a failed hand-over
diff --git a/win_app/tests/test_atlas_canvas.py b/win_app/tests/test_atlas_canvas.py
index d0d2a67..7e93baa 100644
--- a/win_app/tests/test_atlas_canvas.py
+++ b/win_app/tests/test_atlas_canvas.py
@@ -130,15 +130,21 @@ class AtlasCanvasTests(unittest.TestCase):
with patch.object(diagram, "QPainter", RecordingPainter):
canvas.render(image)
tile = canvas.tile_rect("home")
+ badges = [box for peer, _display, _number, box in canvas.display_number_rects if peer == "home"]
+ self.assertEqual(len(badges), len(displays))
+ for badge in badges:
+ self.assertIn(badge, rounded_rects)
return [rect for rect in rounded_rects
if rect.left() >= tile.left() + 1 and rect.top() >= tile.top() + 1
- and rect.right() <= tile.right() - 1 and rect.bottom() <= tile.bottom() - 1]
+ and rect.right() <= tile.right() - 1 and rect.bottom() <= tile.bottom() - 1
+ and rect not in badges]
one = {"main": {"x": 0, "y": 0, "w": 1728, "h": 1117}}
two = {"left": {"x": 0, "y": 0, "w": 1728, "h": 1117},
"right": {"x": 1728, "y": 0, "w": 1728, "h": 1117}}
self.assertEqual(internal_frames(one), [])
- self.assertEqual(len(internal_frames(two)), 2)
+ self.assertCountEqual(internal_frames(two),
+ [canvas.display_rect("home", display).adjusted(2, 2, -2, -2) for display in two])
def _wrapping_canvas(self, **states):
from PySide6.QtCore import Qt
diff --git a/win_app/tests/test_atlas_crossing_colours.py b/win_app/tests/test_atlas_crossing_colours.py
index d6a1ba0..a66a9b4 100644
--- a/win_app/tests/test_atlas_crossing_colours.py
+++ b/win_app/tests/test_atlas_crossing_colours.py
@@ -25,10 +25,11 @@ class AtlasCrossingColoursTests(unittest.TestCase):
"peer", own_id="home")
def painted_tiles(self):
- from PySide6.QtGui import QPen
+ from PySide6.QtGui import QFontMetrics, QPen
import diagram
painter = mock.Mock()
+ painter.fontMetrics.side_effect = lambda: QFontMetrics(painter.setFont.call_args.args[0])
borders = []
pen = None
diff --git a/win_app/tests/test_capture_win.py b/win_app/tests/test_capture_win.py
index 7a25a01..580a756 100644
--- a/win_app/tests/test_capture_win.py
+++ b/win_app/tests/test_capture_win.py
@@ -64,6 +64,9 @@ class NameTests(unittest.TestCase):
def test_a_dead_key_is_composed_without_leaving_state_for_the_next_translation(self):
class FrenchLayout:
+ def GetForegroundWindow(self):
+ return 0
+
def __init__(self):
self.pending = False
self.flags = []
@@ -149,9 +152,11 @@ class NameTests(unittest.TestCase):
key_up = hooks._keyboard_proc(capture_win.HC_ACTION, capture_win.WM_KEYUP, ctypes.byref(data))
self.assertEqual((key_down, key_up), (1, 1))
- on_key.assert_called_once()
- self.assertIsInstance(on_key.call_args.args[0], capture_win.TextInput)
- self.assertEqual(on_key.call_args.args[1:], (True, 0x41, None))
+ self.assertEqual(on_key.call_count, 2)
+ self.assertIsInstance(on_key.call_args_list[0].args[0], capture_win.TextInput)
+ self.assertEqual(on_key.call_args_list[0].args[1:], (True, 0x41, None))
+ self.assertEqual(on_key.call_args_list[1].args[0].text, "")
+ self.assertEqual(on_key.call_args_list[1].args[1:], (False, 0x41, None))
self.assertEqual(hooks._text_keyups_swallowed, set())
def test_stopping_hooks_clears_pending_text_key_releases(self):
@@ -185,9 +190,10 @@ class NameTests(unittest.TestCase):
key_up = hooks._keyboard_proc(capture_win.HC_ACTION, capture_win.WM_KEYUP, ctypes.byref(data))
self.assertEqual((repeated_down, key_up), (1, 1))
- on_key.assert_called_once()
- self.assertEqual(on_key.call_args.args[0].text, "a")
- self.assertIsInstance(on_key.call_args.args[0], capture_win.TextInput)
+ self.assertEqual(on_key.call_count, 2)
+ self.assertEqual(on_key.call_args_list[0].args[0].text, "a")
+ self.assertIsInstance(on_key.call_args_list[0].args[0], capture_win.TextInput)
+ self.assertEqual(on_key.call_args_list[1].args[1:], (False, 0x41, None))
def test_a_key_release_does_not_consume_a_pending_dead_key(self):
state = KeyboardState()
diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.py
index 918d1c9..bbe305c 100644
--- a/win_app/tests/test_clipboard_win.py
+++ b/win_app/tests/test_clipboard_win.py
@@ -192,8 +192,18 @@ class FakeWin32:
self.mem32 = mem32
self.formats = dict(formats or {})
self.emptied = 0
+ self.open_owner = None
+ self.destroyed = []
+
+ def CreateWindowExW(self, *args):
+ return 123
+
+ def DestroyWindow(self, owner):
+ self.destroyed.append(owner)
+ return 1
def OpenClipboard(self, owner):
+ self.open_owner = owner
return 1
def CloseClipboard(self):
@@ -262,6 +272,62 @@ class ClipboardOrchestrationTests(unittest.TestCase):
self.assertEqual(self.mem32.contents(win32.formats[CF_DIB]), bgra_to_dib(2, 2, BGRA))
self.assertEqual(self.mem32.freed, [])
+ def test_write_uses_an_owned_message_window_even_when_the_panel_is_hidden(self):
+ win32 = FakeWin32(self.mem32)
+ original = win32.SetClipboardData
+ win32.SetClipboardData = lambda kind, handle: original(kind, handle) if win32.open_owner else 0
+ self.assertTrue(clipboard_win._set_contents(win32, self.mem32, "hidden", None))
+ self.assertEqual(win32.destroyed, [123])
+
+ def test_failed_empty_does_not_write_into_another_apps_clipboard(self):
+ win32 = FakeWin32(self.mem32)
+ win32.EmptyClipboard = lambda: 0
+ self.assertFalse(clipboard_win._set_contents(win32, self.mem32, "new", None))
+ self.assertEqual(win32.formats, {})
+
+ def test_image_read_failure_does_not_drop_valid_text(self):
+ win32 = FakeWin32(self.mem32, {CF_UNICODETEXT: self.mem32.handle_for("copied")})
+ original = win32.GetClipboardData
+ def read(kind):
+ if kind == CF_DIB:
+ raise OSError("image provider failed")
+ return original(kind)
+ win32.GetClipboardData = read
+ self.assertEqual(clipboard_win._get_contents(win32, self.mem32), ("copied", None))
+
+ def test_copy_after_close_is_not_marked_as_written_from_peer(self):
+ win32 = FakeWin32(self.mem32)
+ win32.sequence = 10
+ win32.GetClipboardSequenceNumber = lambda: win32.sequence
+ def close():
+ win32.sequence += 1
+ return 1
+ win32.CloseClipboard = close
+ with mock.patch.multiple(clipboard_win, _IS_WINDOWS=True, user32=win32, kernel32=self.mem32, _synced_sequence=None):
+ self.assertTrue(clipboard_win.set_contents("peer", None))
+ self.assertEqual(clipboard_win._synced_sequence, 10)
+
+ def test_contention_releases_the_owner_window_and_the_next_attempt_succeeds(self):
+ win32 = FakeWin32(self.mem32)
+ opened = win32.OpenClipboard
+ calls = []
+ def contended(owner):
+ calls.append(owner)
+ return 0 if len(calls) <= 5 else opened(owner)
+ win32.OpenClipboard = contended
+ self.assertFalse(clipboard_win._set_contents(win32, self.mem32, "copy", None, sleep=lambda _: None))
+ self.assertTrue(clipboard_win._set_contents(win32, self.mem32, "copy", None, sleep=lambda _: None))
+ self.assertEqual(win32.destroyed, [123, 123])
+ self.assertEqual(self.mem32.contents(win32.formats[CF_UNICODETEXT]), b"c\x00o\x00p\x00y\x00\x00\x00")
+
+ def test_rapid_large_unicode_writes_keep_the_latest_text(self):
+ win32 = FakeWin32(self.mem32)
+ copies = [f"copy {n}: café 日本語 \U0001d11e" for n in range(200)]
+ copies.append("\U0001d11e" * (protocol.CLIPBOARD_MAX_BYTES // 4))
+ for text in copies:
+ self.assertTrue(clipboard_win._set_contents(win32, self.mem32, text, None))
+ self.assertEqual(clipboard_win._get_contents(win32, self.mem32), (text, None))
+
def test_set_contents_writes_windows_line_endings(self):
win32 = FakeWin32(self.mem32)
self.assertTrue(clipboard_win._set_contents(win32, self.mem32, "one\ntwo\r\nthree", None))
diff --git a/win_app/tests/test_gameinput_foreground.py b/win_app/tests/test_gameinput_foreground.py
index 524211a..5ae92a2 100644
--- a/win_app/tests/test_gameinput_foreground.py
+++ b/win_app/tests/test_gameinput_foreground.py
@@ -60,7 +60,7 @@ class GameInputForegroundTests(unittest.TestCase):
def restart(args, **kwargs):
self.restarts.append((args, kwargs))
self.user32.foreground = EXPLORER
- return subprocess.CompletedProcess(args, 0, "", "")
+ return subprocess.CompletedProcess(args, 0, b"", b"")
self.clock = [1000.0]
patches = [
@@ -166,7 +166,7 @@ class GameInputForegroundTests(unittest.TestCase):
def restarts_leave_gameinput_in_front(self):
def restart(args, **kwargs):
self.restarts.append((args, kwargs))
- return subprocess.CompletedProcess(args, 0, "", "")
+ return subprocess.CompletedProcess(args, 0, b"", b"")
input_injector.subprocess.run.side_effect = restart
diff --git a/win_app/tests/test_identify_screens_qt.py b/win_app/tests/test_identify_screens_qt.py
new file mode 100644
index 0000000..7c0b0cb
--- /dev/null
+++ b/win_app/tests/test_identify_screens_qt.py
@@ -0,0 +1,249 @@
+"""Screen numbers with synthetic displays/settings; run from Claude, one process."""
+
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from PySide6.QtCore import QRect, QRectF, Qt
+from PySide6.QtTest import QTest
+from PySide6.QtWidgets import QApplication
+
+import identify_overlay
+from core import protocol
+from core.identify_screens import display_numbers
+from core.return_edge import Rect
+from diagram import AtlasCanvas
+from sender import LinkSender
+import test_crossing_page_parity as fixture
+
+
+class IdentifyOverlayTests(unittest.TestCase):
+ def setUp(self):
+ self.app = QApplication.instance() or QApplication([])
+
+ def fake_screen(self, x, y, w=1920, h=1080, ratio=1, name="display"):
+ return SimpleNamespace(geometry=lambda: QRect(x, y, w, h), devicePixelRatio=lambda: ratio, name=lambda: name)
+
+ def test_native_monitor_order_and_mixed_dpi_match_qt(self):
+ left, right = self.fake_screen(-1920, 0), self.fake_screen(0, 0, 1280, 720, 2)
+ displays = {"0": Rect(0, 0, 2560, 1440), "1": Rect(-1920, 0, 1920, 1080)}
+ assignments = identify_overlay.screen_assignments([left, right], displays, {"1": 1, "0": 2})
+ self.assertEqual(assignments, [(left, 1), (right, 2)])
+ scaled = self.fake_screen(1280, 0, 960, 540, 2)
+ assignments = identify_overlay.screen_assignments([right, scaled],
+ {"0": Rect(0, 0, 2560, 1440), "1": Rect(2560, 0, 1920, 1080)}, {"0": 1, "1": 2})
+ self.assertEqual(assignments, [(right, 1), (scaled, 2)])
+
+ def test_wayland_uses_portal_qt_keys_even_when_zone_origins_differ(self):
+ a, b = self.fake_screen(0, 0), self.fake_screen(1920, 0)
+ assignments = identify_overlay.screen_assignments([a, b],
+ {"0": Rect(40, 50, 1920, 1080), "1": Rect(1960, 50, 1920, 1080)}, {"1": 1, "0": 2}, wayland=True)
+ self.assertEqual(assignments, [(b, 1), (a, 2)])
+
+ def test_xwayland_uses_connectors_or_geometry_not_enumeration(self):
+ left = self.fake_screen(-1920, 0, name="left")
+ right = self.fake_screen(0, 0, 1280, 720, name="right")
+ payload = [{"geometry": [0, 0, 1280, 720], "name": "right", "number": 2},
+ {"geometry": [-1920, 0, 1920, 1080], "name": "left", "number": 1}]
+ self.assertEqual(identify_overlay.x11_screen_regions([left, right], payload),
+ [(right, 2, right.geometry()), (left, 1, left.geometry())])
+
+ def test_xwayland_single_virtual_output_keeps_each_physical_region(self):
+ desktop = self.fake_screen(0, 0, 3840, 1080, name="XWAYLAND0")
+ payload = [{"geometry": [0, 0, 1920, 1080], "name": "left", "number": 1},
+ {"geometry": [1920, 0, 1920, 1080], "name": "right", "number": 2}]
+ self.assertEqual(identify_overlay.x11_screen_regions([desktop], payload),
+ [(desktop, 1, QRect(0, 0, 1920, 1080)), (desktop, 2, QRect(1920, 0, 1920, 1080))])
+
+ def test_failed_layer_shell_uses_xwayland_but_never_focusable_native_fallback(self):
+ controller = identify_overlay.IdentifyScreens()
+ self.addCleanup(controller.stop)
+ controller._backend = "layer-shell"
+ with patch.dict(identify_overlay.os.environ, {"DISPLAY": ":123"}), \
+ patch.object(controller, "_start_x11") as x11, patch.object(controller, "_show_qt") as native:
+ controller._fallback()
+ x11.assert_called_once()
+ native.assert_not_called()
+ controller._backend = "XWayland frameless per-screen windows"
+ with patch.object(identify_overlay.QGuiApplication, "platformName", return_value="wayland"), \
+ patch.object(controller, "_show_qt") as native:
+ controller._fallback()
+ native.assert_not_called()
+
+ def test_flags_geometry_repeated_invocation_and_three_second_expiry(self):
+ controller = identify_overlay.IdentifyScreens()
+ self.addCleanup(controller.stop)
+ screen = self.app.primaryScreen()
+ geometry = screen.geometry()
+ display = {"0": Rect(geometry.x(), geometry.y(), geometry.width(), geometry.height())}
+ controller.show_numbers({"0": 1}, display)
+ first = controller.windows[0]
+ self.assertEqual(first.geometry(), geometry)
+ self.assertEqual(first.number, 1)
+ for flag in (Qt.WindowType.FramelessWindowHint, Qt.WindowType.WindowTransparentForInput,
+ Qt.WindowType.WindowDoesNotAcceptFocus, Qt.WindowType.WindowStaysOnTopHint):
+ self.assertTrue(first.windowFlags() & flag)
+ self.assertTrue(first.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating))
+ self.assertTrue(first.testAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents))
+ self.assertEqual(controller._expiry.interval(), 3000)
+ controller.show_numbers({"0": 2}, display)
+ self.assertFalse(first.isVisible())
+ self.assertEqual(len(controller.windows), 1)
+ self.assertEqual(controller.windows[0].number, 2)
+ QTest.qWait(3150)
+ self.assertFalse(controller.windows)
+
+ def test_helper_failed_start_and_timeout_both_fall_back(self):
+ controller = identify_overlay.IdentifyScreens()
+ self.addCleanup(controller.stop)
+ failed = Mock()
+ failed.readAllStandardError.return_value = b"optional binding missing"
+ controller._process = failed
+ controller._pending = [("screen", 1)]
+ with patch.object(controller, "_show_qt") as show:
+ controller._helper_finished(failed)
+ show.assert_called_once()
+ timed_out = Mock()
+ timed_out.readAllStandardError.return_value = b""
+ controller._process = timed_out
+ with patch.object(controller, "_show_qt") as show:
+ controller._fallback()
+ timed_out.kill.assert_called_once()
+ timed_out.waitForFinished.assert_called_once_with(250)
+ show.assert_called_once()
+
+ def test_helper_failure_logs_backend_and_bounded_stderr(self):
+ controller = identify_overlay.IdentifyScreens()
+ self.addCleanup(controller.stop)
+ process = Mock()
+ process.readAllStandardError.return_value = b"x" * 4096
+ controller._process = process
+ controller._backend = "layer-shell"
+ with self.assertLogs(identify_overlay.LOGGER, level="WARNING") as recorded:
+ controller._log_helper_failure(process, "exited before readiness")
+ self.assertEqual(len(controller._helper_stderr), 2048)
+ self.assertIn("layer-shell helper exited before readiness", recorded.output[0])
+
+ def test_map_badges_and_overlay_assignments_use_same_numbers(self):
+ tile = {"x": 0, "y": 0, "w": 320, "h": 100, "displays": {
+ "left": {"x": -1920, "y": 0, "w": 1920, "h": 1080},
+ "right": {"x": 0, "y": 0, "w": 1920, "h": 1080}}}
+ canvas = AtlasCanvas()
+ self.addCleanup(canvas.deleteLater)
+ canvas.resize(600, 260)
+ canvas.set_tiles({"own": tile}, {"own": "This PC"}, {"own": {"state": "this"}}, "own", own_id="own")
+ canvas.grab()
+ badges = {display: number for _, display, number, _ in canvas.display_number_rects}
+ self.assertEqual(badges, display_numbers(tile))
+ for _, display, _, box in canvas.display_number_rects:
+ self.assertTrue(canvas.display_rect("own", display).contains(box))
+
+ def test_sender_dispatch_and_older_peer_no_op(self):
+ callback = Mock()
+ sender = SimpleNamespace(links=SimpleNamespace(caps=lambda peer: {"identify_screens"}),
+ identify_callback=callback, _call=lambda fn, *args: fn(*args))
+ message = protocol.identify_screens_msg({"0": 1})
+ LinkSender.on_message(sender, b"peer", message)
+ callback.assert_called_once_with(b"peer", {"0": 1})
+ callback.reset_mock()
+ sender.links.caps = lambda peer: set()
+ LinkSender.on_message(sender, b"peer", message)
+ callback.assert_not_called()
+
+ def test_frozen_x11_entry_bypasses_singleton_and_real_settings(self):
+ import kvm_bridge_win as kvm
+
+ with patch.object(kvm, "parse_args", return_value=SimpleNamespace(identify_x11="[]")), \
+ patch.object(identify_overlay, "run_x11_helper", return_value=0) as child, \
+ patch.object(kvm, "_claim_instance") as claim, \
+ patch.object(kvm.app_config, "load_config") as load:
+ with self.assertRaises(SystemExit) as exit_result:
+ kvm.main()
+ self.assertEqual(exit_result.exception.code, 0)
+ child.assert_called_once_with("[]")
+ claim.assert_not_called()
+ load.assert_not_called()
+
+ def test_stacked_display_badges_leave_text_rows_clear(self):
+ badges = [QRectF(5, 29, 18, 16), QRectF(5, 79, 18, 16)]
+ for row in (QRectF(8, 7, 304, 22), QRectF(24, 31, 288, 16), QRectF(7, 76, 306, 16)):
+ room = AtlasCanvas._beside_display_numbers(row, badges)
+ self.assertTrue(row.contains(room))
+ self.assertTrue(all(not room.intersects(badge) for badge in badges))
+
+ def test_compact_tiles_keep_number_row_separate_from_readable_names(self):
+ canvas = AtlasCanvas()
+ self.addCleanup(canvas.deleteLater)
+ canvas.resize(600, 260)
+ for height in (25, 28, 31, 36, 48):
+ width = 40 if height < 32 else 140
+ tiles = {"own": {"x": 0, "y": 0, "w": width, "h": height},
+ "peer": {"x": width, "y": 0, "w": width, "h": height}}
+ canvas.set_tiles(tiles, {"own": "This PC", "peer": "Laptop"},
+ {"own": {"state": "this"}, "peer": {"state": "edge"}}, "peer",
+ cycle_mode="ticked", cycle={"peer": True}, own_id="own")
+ canvas._geometry()
+ for peer in tiles:
+ tile = canvas.tile_rect(peer)
+ title = canvas._title_rect(peer, tile)
+ badges = [box for _, _, box in canvas._display_number_boxes(peer, tile)]
+ self.assertGreater(title.width(), 24 if height < 32 else 65)
+ self.assertTrue(tile.contains(title))
+ self.assertTrue(all(not title.intersects(box) for box in badges))
+ if peer == "peer":
+ self.assertTrue(tile.contains(canvas._cycle_box(tile)))
+ self.assertTrue(all(not canvas._cycle_box(tile).intersects(box) for box in badges))
+
+
+class IdentifyPageTests(unittest.TestCase):
+ setUp = fixture.CrossingPageParityTests.setUp
+ tearDown = fixture.CrossingPageParityTests.tearDown
+ _open_window = fixture.CrossingPageParityTests._open_window
+ _close_window = fixture.CrossingPageParityTests._close_window
+ _stop_patches = fixture.CrossingPageParityTests._stop_patches
+
+ def test_button_identifies_local_and_all_capable_linked_peers(self):
+ window = self.window
+ self.assertIn("identify_screens", window._identity()["caps"])
+ capable, old = (protocol.read_id(peer["id"]) for peer in self.peers)
+ window._peer_caps = lambda: {capable: {"identify_screens"}, old: {"settings"}}
+ with patch.object(window, "_send_to", return_value=True) as send, \
+ patch.object(window.identify_screens, "show_numbers") as show:
+ window.identify_button.click()
+ show.assert_called_once()
+ send.assert_called_once()
+ self.assertEqual(send.call_args.args[0], capable)
+ self.assertEqual(protocol.read_identify_screens(send.call_args.args[1]),
+ display_numbers(window.atlas_canvas.tiles.get(protocol.id_text(capable))))
+
+ def test_stale_partial_labels_use_complete_live_numbering(self):
+ window = self.window
+ displays = {"0": Rect(1920, 0, 1920, 1080), "1": Rect(0, 0, 1920, 1080)}
+ with patch.object(window, "_refresh_own_displays"), patch.object(window, "_own_displays", return_value=displays), \
+ patch.object(window.identify_screens, "show_numbers") as show:
+ window._on_identify_screens({"0": 1})
+ show.assert_called_once_with({"1": 1, "0": 2}, displays)
+
+ def test_linked_shelved_peer_gets_all_its_display_numbers(self):
+ window = self.window
+ peer = self.peers[0]["id"]
+ tile = {"x": 160, "y": 0, "w": 320, "h": 100, "displays": {
+ "0": {"x": 1920, "y": 0, "w": 1920, "h": 1080},
+ "1": {"x": 0, "y": 0, "w": 1920, "h": 1080}}}
+ window._config.layout[peer] = tile
+ window._peer_caps = lambda: {protocol.read_id(peer): {"identify_screens"}}
+ window.atlas_canvas.tiles.pop(peer, None)
+ with patch.object(window, "_displays_changed"), \
+ patch.object(window, "_crossing_view_settings", return_value={"machine_id": window._config.machine_id,
+ "peers": [], "layout": window._config.layout}), \
+ patch.object(window, "_on_identify_screens"), patch.object(window, "_send_to") as send:
+ window._identify_screens()
+ self.assertEqual(protocol.read_identify_screens(send.call_args.args[1]), {"1": 1, "0": 2})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_ignored_inputs.py b/win_app/tests/test_ignored_inputs.py
index 7b825da..59fa4d9 100644
--- a/win_app/tests/test_ignored_inputs.py
+++ b/win_app/tests/test_ignored_inputs.py
@@ -35,6 +35,39 @@ def make_config(**overrides):
class SenderTests(unittest.TestCase):
+ def test_mouse_only_keeps_keys_dead_keys_text_and_media_here(self):
+ self.sender.update_config(rig_config(mouse_only=True))
+ for name, vk in (("a", VK_A), ("volume_up", 0xAF), ("shift", 0xA0), ("b", None)):
+ self.assertFalse(self.sender.on_key(name, True, vk))
+ self.assertFalse(self.sender.on_key(name, False, vk))
+ for vk in (VK_A, None):
+ self.assertFalse(self.sender.on_dead_key(vk))
+ self.assertFalse(self.sender.on_text("á", vk))
+ self.assertEqual(self.sent(), [])
+ self.assertEqual(self.rig.sent(B, protocol.MSG_TEXT), [])
+ self.assertTrue(self.sender.on_button("left", True))
+ self.assertTrue(self.sender.on_button("left", False))
+ self.assertEqual(self.sent(), [(protocol.MSG_MOUSEDOWN, {"button": "left"}),
+ (protocol.MSG_MOUSEUP, {"button": "left"})])
+
+ def test_mouse_only_composed_text_can_cross_again_after_switching_off(self):
+ self.rig.links.caps_of[B] = frozenset({"text"})
+ self.sender.update_config(rig_config(mouse_only=True))
+ self.assertFalse(self.sender.on_text("á", VK_A))
+ self.sender.on_key("a", False, VK_A)
+ self.sender.update_config(rig_config(mouse_only=False))
+ self.assertTrue(self.sender.on_text("á", VK_A))
+ self.assertEqual(self.rig.sent(B, protocol.MSG_TEXT), [protocol.text_msg("á")])
+
+ def test_composed_text_repeats_follow_the_press_when_mouse_only_changes(self):
+ self.rig.links.caps_of[B] = frozenset({"text"})
+ self.assertTrue(self.sender.on_text("á", VK_A))
+ self.sender.update_config(rig_config(mouse_only=True))
+ self.assertTrue(self.sender.on_text("a", VK_A))
+ self.assertTrue(self.sender.on_text("", VK_A, False))
+ self.assertFalse(self.sender.on_text("a", VK_A))
+ self.assertEqual(self.rig.sent(B, protocol.MSG_TEXT), [protocol.text_msg("á"), protocol.text_msg("a")])
+
def setUp(self):
self.rig = Rig(cursor=(900, 500), ignored_inputs=[ignored.key(VK_F13), ignored.button("back")])
self.sender = self.rig.sender
@@ -148,6 +181,17 @@ class CaptureTests(unittest.TestCase):
class ConfigTests(unittest.TestCase):
+ def test_mouse_only_defaults_off_and_survives_save_reload(self):
+ raw = app_config.config_to_dict(make_config(port=24820))
+ raw.pop("mouse_only")
+ self.assertFalse(app_config.config_from_dict(raw).mouse_only)
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "settings.json"
+ app_config.save_config(path, make_config(port=24820, mouse_only=True))
+ self.assertTrue(app_config.load_config(path).mouse_only)
+ with self.assertRaises(app_config.ConfigError):
+ app_config.validate_config(make_config(port=24820, mouse_only="true"))
+
def test_the_list_survives_a_save_and_a_load(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "settings.json"
diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.py
index 21c5395..fa74875 100644
--- a/win_app/tests/test_links.py
+++ b/win_app/tests/test_links.py
@@ -771,6 +771,9 @@ class ReviewTests(unittest.TestCase):
def test_a_read_asked_for_again_waits_its_turn_behind_a_write_decided_before_it(self):
rig = self.two()
+ rig.sender._note_clipboard()
+ rig.sender._owner.go(B)
+ rig.sender._owner.accept(B, {"route": rig.sender._owner.route})
rig.clipboard.block_get = True
rig.clipboard.block_set = True
rig.sender._deliver(owner_module.SendClipboard(B))
@@ -948,6 +951,187 @@ class MouseTests(unittest.TestCase):
self.assertEqual(self.sender.round_trip_ms, 7)
+class ClipboardReliabilityTests(unittest.TestCase):
+ def test_a_read_finishing_after_home_never_posts_private_local_text(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ rig.links.sent.clear()
+ rig.clipboard.copy("before home")
+ def copied_after_home():
+ rig.sender.set_redirecting(False)
+ rig.clipboard.copy("private local text")
+ return rig.clipboard.text, None
+ with mock.patch.object(rig.clipboard, "get_contents", side_effect=copied_after_home) as read:
+ rig.sender.tick()
+ rig.flush()
+ self.assertEqual(read.call_count, 1)
+ self.assertEqual(rig.sent(B, "clipboard"), [])
+
+ def test_a_source_retry_stops_after_home_even_if_the_stamp_is_unchanged(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ rig.links.sent.clear()
+ rig.clipboard.copy("before home")
+ stamp = rig.clipboard.stamp
+ def unavailable_after_home():
+ rig.sender.set_redirecting(False)
+ return None, None
+ with mock.patch.object(rig.clipboard, "get_contents", side_effect=unavailable_after_home) as read:
+ rig.sender.tick()
+ rig.flush()
+ self.assertEqual(read.call_count, 1)
+ self.assertEqual(rig.clipboard.stamp, stamp)
+ self.assertEqual(rig.sent(B, "clipboard"), [])
+
+ def test_copies_while_hidden_reach_the_active_peer(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ for text in ("first", "日本語 — café 𝄞", "large " * 20000):
+ rig.clipboard.copy(text)
+ rig.sender.tick()
+ self.assertEqual(rig.sent(B, "clipboard")[-1], protocol.clipboard_msg(text))
+
+ def test_a_transient_read_or_post_failure_recovers_without_another_crossing(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ for failure in ("read", "read_exception", "post", "post_exception"):
+ with self.subTest(failure=failure):
+ text = "new local copy: " + failure
+ rig.clipboard.copy(text)
+ read, post = rig.clipboard.get_contents, rig.links.post
+ calls = []
+ def attempt(*args):
+ calls.append(True)
+ if len(calls) == 1:
+ if failure.endswith("exception"):
+ raise OSError("clipboard temporarily busy")
+ return (None, None) if failure == "read" else False
+ return read() if failure.startswith("read") else post(*args)
+ target, name = (rig.clipboard, "get_contents") if failure.startswith("read") else (rig.links, "post")
+ with mock.patch.object(target, name, side_effect=attempt):
+ rig.sender.tick()
+ rig.flush()
+ self.assertEqual(len(calls), 2)
+ self.assertEqual(rig.sent(B, "clipboard")[-1], protocol.clipboard_msg(text))
+
+ def test_a_persistent_source_read_failure_is_bounded_and_releases_input(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ rig.clipboard.copy("temporarily unreadable")
+ with mock.patch.object(rig.clipboard, "get_contents", return_value=(None, None)) as read:
+ rig.sender.tick()
+ rig.sender.on_key("a", True, 0x41, "a")
+ rig.flush()
+ self.assertEqual(read.call_count, 3)
+ self.assertEqual(rig.sent(B)[-1]["type"], protocol.MSG_KEYDOWN)
+
+ def test_a_source_retry_never_reads_a_newer_copy_for_the_old_attempt(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ rig.clipboard.copy("first generation")
+ def changed_while_busy():
+ rig.clipboard.copy("new generation")
+ return None, None
+ with mock.patch.object(rig.clipboard, "get_contents", side_effect=changed_while_busy) as read:
+ rig.sender.tick()
+ rig.flush()
+ self.assertEqual(read.call_count, 1)
+ rig.sender.tick()
+ self.assertEqual(rig.sent(B, "clipboard")[-1], protocol.clipboard_msg("new generation"))
+
+ def test_an_inbound_write_exception_is_retried(self):
+ rig = Rig()
+ write = rig.clipboard.set_contents
+ calls = []
+ def temporarily_busy(text, image):
+ calls.append(text)
+ if len(calls) == 1:
+ raise OSError("clipboard temporarily busy")
+ return write(text, image)
+ with mock.patch.object(rig.clipboard, "set_contents", side_effect=temporarily_busy):
+ rig.sender._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(calls, ["remote copy", "remote copy"])
+ self.assertEqual(rig.clipboard.text, "remote copy")
+
+ def test_a_copy_completed_before_accept_is_forwarded_on_accept(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.flush()
+ rig.clipboard.copy("copy completed after the crossing")
+ rig.accept_take()
+ self.assertEqual(rig.sent(B, "clipboard")[-1], protocol.clipboard_msg(rig.clipboard.text))
+
+ def test_failed_reads_and_posts_are_tried_again_on_the_next_crossing(self):
+ for failure in ("read", "post"):
+ with self.subTest(failure=failure):
+ rig = Rig()
+ read, post = rig.clipboard.get_contents, rig.links.post
+ if failure == "read":
+ rig.clipboard.get_contents = lambda: (None, None)
+ else:
+ rig.links.post = lambda peer, message: False if message["type"] == protocol.MSG_CLIPBOARD else post(peer, message)
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ rig.sender.set_redirecting(False)
+ rig.flush()
+ rig.clipboard.get_contents, rig.links.post = read, post
+ rig.links.sent.clear()
+ rig.sender.set_redirecting(True)
+ self.assertEqual(rig.sent(B, "clipboard"), [protocol.clipboard_msg("here")])
+
+ def test_failed_inbound_writes_do_not_swallow_a_local_copy(self):
+ rig = Rig()
+ rig.sender._note_clipboard()
+ before = rig.sender._clipboard_stamp
+ rig.clipboard.copy("local copy")
+ rig.clipboard.set_contents = lambda text, image: False
+ rig.sender._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(rig.sender._clipboard_stamp, before)
+
+ def test_an_inbound_write_retry_keeps_a_newer_local_copy(self):
+ rig = Rig()
+ calls = []
+ def copied_while_busy(text, image):
+ calls.append(text)
+ rig.clipboard.copy("newer local copy")
+ return False
+ rig.clipboard.set_contents = copied_while_busy
+ rig.sender._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(calls, ["remote copy"])
+ self.assertEqual(rig.clipboard.text, "newer local copy")
+
+ def test_a_copy_during_a_peer_write_is_not_mistaken_for_the_peer_write(self):
+ rig = Rig()
+ rig.sender._note_clipboard()
+ write_stamp = rig.clipboard.stamp + 1
+ rig.clipboard.write_stamp = lambda: write_stamp
+ write = rig.clipboard.set_contents
+ def copied_after_write(text, image):
+ result = write(text, image)
+ rig.clipboard.copy("new local copy")
+ return result
+ rig.clipboard.set_contents = copied_after_write
+ rig.sender._set_clipboard(protocol.clipboard_msg("remote copy"))
+ self.assertEqual(rig.sender._clipboard_stamp, write_stamp)
+ self.assertTrue(rig.sender._note_clipboard())
+
+ def test_source_polling_does_not_run_when_the_source_is_being_driven(self):
+ rig = Rig()
+ rig.sender.set_redirecting(True)
+ rig.accept_take()
+ rig.links.sent.clear()
+ rig.driven = True
+ rig.clipboard.copy("belongs to the machine driving this one")
+ rig.sender.tick()
+ self.assertEqual(rig.sent(B, "clipboard"), [])
+
+
class SettingsTests(unittest.TestCase):
def test_a_machine_without_an_id_drives_nothing(self):
rig = Rig(up=(), machine_id="")
diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.py
index 5ce9cc2..c80a5e4 100644
--- a/win_app/tests/test_pages_win.py
+++ b/win_app/tests/test_pages_win.py
@@ -367,6 +367,29 @@ class CrossingPageTest(unittest.TestCase):
choice._buttons["quarter"].click()
self.assertEqual(app_config.load_config(self.path).frame_rate, "quarter")
+ def test_mouse_only_switch_saves_applies_and_reflects_without_resaving(self):
+ from unittest import mock
+
+ self.assertFalse(self.page.mouse_only_switch.isChecked())
+ self.page.mouse_only_switch.click()
+ self.assertTrue(app_config.load_config(self.path).mouse_only)
+ self.assertTrue(self.page.sender._ignore_gate.mouse_only)
+ config = app_config.load_config(self.path)
+ config.mouse_only = False
+ with mock.patch.object(self.page, "_persist") as persist:
+ self.page._reflect_config(config)
+ self.assertFalse(self.page.mouse_only_switch.isChecked())
+ persist.assert_not_called()
+
+ def test_mouse_only_switch_restores_state_if_saving_fails(self):
+ from unittest import mock
+
+ with mock.patch.object(self.page, "_persist", return_value=False):
+ self.page.mouse_only_switch.click()
+ self.assertFalse(self.page._config.mouse_only)
+ self.assertFalse(self.page.mouse_only_switch.isChecked())
+ self.assertFalse(self.page.sender._ignore_gate.mouse_only)
+
def test_fixture_releases_window_before_the_next_case(self):
from shiboken6 import isValid
diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.py
index cc79b0f..9d8d9d1 100644
--- a/win_app/tests/test_pairing_window.py
+++ b/win_app/tests/test_pairing_window.py
@@ -494,7 +494,6 @@ class PairingSheetWindowTest(unittest.TestCase):
self.assertTrue(self.window.sheet.code_showing)
self.assertTrue(self.window.sheet.count_label.text().startswith("Expires in "))
- # segno is in the Windows build only until phone pairing ships, and Linux with it (todo.md).
@unittest.skipIf(qr_code.segno is None, "segno is not installed")
def test_pair_phone_button_opens_the_sheet_and_generates_a_qr_in_one_click(self):
self.window._toggle_pairing_sheet()
@@ -674,7 +673,6 @@ class PairingSheetWindowTest(unittest.TestCase):
self.assertEqual(self.window.sheet.pair_note.text(),
peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_REFUSED), "Studio"))
- # segno is in the Windows build only until phone pairing ships, and Linux with it (todo.md).
@unittest.skipIf(qr_code.segno is None, "segno is not installed")
def test_the_code_shows_a_qr_unless_addresses_are_hidden(self):
from unittest import mock
diff --git a/win_app/tests/test_power_throttling.py b/win_app/tests/test_power_throttling.py
index ada461e..0bacb4a 100644
--- a/win_app/tests/test_power_throttling.py
+++ b/win_app/tests/test_power_throttling.py
@@ -63,7 +63,8 @@ class PowerThrottlingTests(unittest.TestCase):
raise Started()
with mock.patch.object(kvm_bridge_win, "_claim_instance", return_value=lambda: None), \
- mock.patch.object(kvm_bridge_win, "parse_args"), \
+ mock.patch.object(sys, "argv", ["Beamer"]), \
+ mock.patch.object(kvm_bridge_win, "prepare_windows_startup"), \
mock.patch.object(kvm_bridge_win, "configure_logging", return_value=None), \
mock.patch.object(kvm_bridge_win, "_windows_kernel32", return_value=kernel32), \
mock.patch.object(kvm_bridge_win, "QApplication", side_effect=window):
diff --git a/win_app/tests/test_settings_layout_acceptance.py b/win_app/tests/test_settings_layout_acceptance.py
index c26d7e1..8508271 100644
--- a/win_app/tests/test_settings_layout_acceptance.py
+++ b/win_app/tests/test_settings_layout_acceptance.py
@@ -255,6 +255,19 @@ class SettingsLayoutAcceptance(unittest.TestCase):
self.assertTrue(self.paints_on_one_line(button), "the label wraps or clips inside its button")
self.assertGreaterEqual(button.height(), 24 if button.property("ledger_quiet") else 30)
+ def test_identify_screens_keeps_its_label_and_stays_inside_the_narrow_page(self):
+ for width in (320, 426, 640):
+ with self.subTest(width=width):
+ self.set_size(width)
+ scroll = self.page_scroll("crossing")
+ button = self.window.identify_button
+ self.assertTrue(button.isVisibleTo(scroll.widget()))
+ self.assertTrue(self.paints_on_one_line(button))
+ self.assertGreaterEqual(button.width(), button.sizeHint().width())
+ rectangle = QRect(button.mapTo(scroll.viewport(), QPoint()), button.size())
+ self.assertGreaterEqual(rectangle.left(), 0)
+ self.assertLessEqual(rectangle.right(), scroll.viewport().width())
+
def test_send_destination_refits_when_the_column_shrinks_and_grows(self):
full_text = "Send input to Synthetic workstation with a long machine name"
with mock.patch.object(self.window, "_redirect_text", return_value=full_text):
diff --git a/win_app/tests/test_single_instance.py b/win_app/tests/test_single_instance.py
index 1c7c72b..64ee2f9 100644
--- a/win_app/tests/test_single_instance.py
+++ b/win_app/tests/test_single_instance.py
@@ -113,7 +113,7 @@ class SingleInstanceTests(unittest.TestCase):
def test_startup_migrates_the_legacy_task_before_single_instance_handling(self):
order = []
- with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True, "relaunched": False})()), \
+ with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True, "relaunched": False, "identify_x11": None})()), \
mock.patch.object(kvm_bridge_win, "prepare_windows_startup", side_effect=lambda: order.append("migrate")), \
mock.patch.object(kvm_bridge_win, "_claim_instance", side_effect=lambda: order.append("claim") or None), \
mock.patch.object(kvm_bridge_win, "activate_existing_instance") as activate:
@@ -122,7 +122,7 @@ class SingleInstanceTests(unittest.TestCase):
activate.assert_called_once_with(True, mock.ANY)
def test_failed_migration_still_reaches_instance_handling(self):
- with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True, "relaunched": False})()), \
+ with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True, "relaunched": False, "identify_x11": None})()), \
mock.patch.object(kvm_bridge_win, "prepare_windows_startup", side_effect=OSError("Access is denied")), \
mock.patch.object(kvm_bridge_win, "_claim_instance", return_value=None) as claim, \
mock.patch.object(kvm_bridge_win, "activate_existing_instance"), \
diff --git a/win_app/tests/test_update_notice.py b/win_app/tests/test_update_notice.py
new file mode 100644
index 0000000..e365613
--- /dev/null
+++ b/win_app/tests/test_update_notice.py
@@ -0,0 +1,107 @@
+"""Qt update notice with synthetic settings; run offscreen from a Claude session."""
+
+import os
+from pathlib import Path
+import sys
+import tempfile
+import threading
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parents[2])]
+
+from PySide6.QtWidgets import QApplication
+import app_config
+import kvm_bridge_win as kvm
+import theme
+
+
+FOUND = ("1.5.11", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.11")
+
+
+class UpdateNoticeTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+ theme.init_fonts()
+
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.path = Path(directory.name) / "settings.json"
+ app_config.write_settings(self.path, app_config.load_settings(self.path))
+ for blocker in (
+ patch.object(threading.Thread, "start", side_effect=AssertionError("service started")),
+ patch.object(kvm.WindowsApplication, "_make_pairing", return_value=None),
+ patch.object(kvm.autostart_win, "installed_exe", return_value=None),
+ patch("core.locale.is_us_region", return_value=False),
+ ):
+ blocker.start()
+ self.addCleanup(blocker.stop)
+ self.window = self.build()
+
+ def build(self):
+ window = kvm.WindowsApplication(self.path)
+ window.refresh_timer.stop()
+ window.full_screen_timer.stop()
+ self.addCleanup(window.deleteLater)
+ return window
+
+ def test_dismissal_survives_rebuilding_and_other_settings_changes(self):
+ self.window._on_update(FOUND)
+ self.assertFalse(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.isVisible())
+ self.window.update_dismiss.click()
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertTrue(self.window._persist())
+ self.assertEqual(app_config.load_settings(self.path)["dismissed_update_version"], "1.5.11")
+ rebuilt = self.build()
+ rebuilt._on_update(FOUND)
+ self.assertTrue(rebuilt.update_notice.isHidden())
+ rebuilt._on_update(("1.5.12", FOUND[1]))
+ self.assertFalse(rebuilt.update_notice.isHidden())
+
+ def test_switching_off_hides_the_notice_and_late_answers(self):
+ self.window._on_update(FOUND)
+ self.window._set_check_updates(False)
+ self.assertFalse(self.window._config.check_updates)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.window._on_update(FOUND)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertIsNone(self.window._update)
+
+ def test_flatpak_has_store_guidance_and_no_download_action(self):
+ with patch.object(kvm.portal, "sandboxed", return_value=True):
+ self.window._on_update(FOUND)
+ self.assertIn("software store", self.window.update_notice_text.text())
+ self.assertTrue(self.window.update_button.isHidden())
+ self.assertFalse(self.window.update_notes.isHidden())
+
+ def test_linux_start_checks_for_updates_without_waiting_for_a_toggle(self):
+ events = []
+ owner = SimpleNamespace(update_checker=SimpleNamespace(start=lambda: events.append("check")),
+ _listen=lambda: events.append("listen"))
+ with patch.object(kvm.sys, "platform", "linux"), patch.object(kvm.sys, "frozen", False, create=True):
+ kvm.WindowsApplication.start(owner)
+ self.assertEqual(events, ["check", "listen"])
+
+ def test_unreadable_settings_do_not_block_opening_the_panel(self):
+ self.window._on_update(FOUND)
+ with patch.object(app_config, "load_settings", side_effect=OSError("locked")):
+ self.window._refresh_update_notice()
+ self.assertTrue(self.window.update_notice.isHidden())
+
+ def test_whats_new_opens_the_release_only_on_a_click(self):
+ with patch.object(kvm.QDesktopServices, "openUrl") as opened:
+ self.window._on_update(FOUND)
+ self.assertEqual(opened.call_count, 0)
+ self.window.update_notes.click()
+ self.assertEqual(opened.call_args.args[0].toString(), FOUND[1])
+
+ def test_failed_save_keeps_the_notice_available(self):
+ self.window._on_update(FOUND)
+ with patch.object(app_config, "write_settings", side_effect=OSError("read only")):
+ self.window.update_dismiss.click()
+ self.assertFalse(self.window.update_notice.isHidden())
diff --git a/win_app/tests/test_windows_tool_encoding.py b/win_app/tests/test_windows_tool_encoding.py
new file mode 100644
index 0000000..136a7d1
--- /dev/null
+++ b/win_app/tests/test_windows_tool_encoding.py
@@ -0,0 +1,82 @@
+"""GH19: exercise the real pipe reader without changing accounts or sign-in tasks."""
+
+import json
+import logging
+import os
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import autostart_win
+import firewall_win
+
+
[email protected](sys.platform == "win32", "Windows pipe encodings")
+class WindowsToolEncodingTests(unittest.TestCase):
+ def test_oem_task_xml_preserves_accented_owner_and_profile(self):
+ exe = r"C:\Users\Élodie\AppData\Local\Beamer\Beamer.exe"
+ xml = autostart_win.task_xml(exe, r"STUDIO-PC\Élodie")
+ data = xml.encode("oem")
+ command = [sys.executable, "-c", f"import os; os.write(1, {data!r})"]
+ result = autostart_win._run(command)
+ self.assertEqual(result.stdout, xml)
+ with patch.object(autostart_win, "installed_exe", return_value=None):
+ self.assertTrue(autostart_win.is_enabled(lambda args: result, r"STUDIO-PC\Élodie"))
+
+ def test_oem_stderr_preserves_the_refusal_and_exit_code(self):
+ message = "Échec : accès refusé."
+ data = message.encode("oem")
+ result = autostart_win._run([
+ sys.executable, "-c", f"import os; os.write(2, {data!r}); raise SystemExit(7)",
+ ])
+ self.assertEqual(result.returncode, 7)
+ self.assertEqual(result.stderr, message)
+
+ def test_bom_marked_utf16_task_xml_is_read_as_unicode(self):
+ xml = autostart_win.task_xml(r"C:\Users\José\Beamer.exe", r"STUDIO-PC\José")
+ data = xml.encode("utf-16")
+ result = autostart_win._run([
+ sys.executable, "-c", f"import os; os.write(1, {data!r})",
+ ])
+ self.assertEqual(result.stdout, xml)
+
+ def test_firewall_powershell_utf8_preserves_non_ascii_program_path(self):
+ exe = r"C:\Users\José\AppData\Local\Beamer\Beamer.exe"
+ script = firewall_win._PREAMBLE + "[pscustomobject]@{program=" + firewall_win._quote(exe) + "} | ConvertTo-Json -Compress"
+ self.assertEqual(json.loads(firewall_win._powershell(script))["program"], exe)
+
+ def test_profile_overrides_keep_settings_and_logs_in_the_unicode_directory(self):
+ import app_config
+ import kvm_bridge_win
+
+ with tempfile.TemporaryDirectory() as directory:
+ profile = Path(directory) / "José"
+ local = profile / "AppData" / "Local"
+ roaming = profile / "AppData" / "Roaming"
+ with patch.dict(os.environ, {"USERPROFILE": str(profile), "APPDATA": str(roaming), "LOCALAPPDATA": str(local)}):
+ path = app_config.default_config_path()
+ self.assertEqual(path, local / "Beamer" / "settings.json")
+ config = app_config.default_config()
+ config.edge_glow = False
+ app_config.save_config(path, config)
+ self.assertFalse(app_config.load_config(path, unpaired_ok=True).edge_glow)
+ root = logging.getLogger()
+ previous_handlers, previous_level = list(root.handlers), root.level
+ try:
+ with patch.object(kvm_bridge_win, "LOG_PATH", None):
+ self.assertEqual(kvm_bridge_win.configure_logging(), path.with_name("Beamer.log"))
+ root.info("Élodie: %s", path)
+ finally:
+ for handler in list(root.handlers):
+ if handler not in previous_handlers:
+ handler.flush()
+ root.removeHandler(handler)
+ handler.close()
+ root.setLevel(previous_level)
+ self.assertIn("Élodie", path.with_name("Beamer.log").read_text(encoding="utf-8"))
+
+ def test_firewall_powershell_refusal_preserves_localised_text(self):
+ with self.assertRaisesRegex(RuntimeError, "Échec"):
+ firewall_win._powershell(firewall_win._PREAMBLE + "throw 'Échec : accès refusé.'")
diff --git a/win_app/xkb_x11.py b/win_app/xkb_x11.py
index 61d6937..5ffd06a 100644
--- a/win_app/xkb_x11.py
+++ b/win_app/xkb_x11.py
@@ -43,6 +43,9 @@ def _load(names=None):
xkb.xkb_state_new.argtypes = [p]
xkb.xkb_state_unref.argtypes = [p]
xkb.xkb_state_update_mask.argtypes = [p, u32, u32, u32, u32, u32, u32]
+ xkb.xkb_state_update_key.argtypes = [p, u32, ctypes.c_int]
+ xkb.xkb_state_serialize_mods.restype = u32
+ xkb.xkb_state_serialize_mods.argtypes = [p, u32]
xkb.xkb_state_key_get_one_sym.restype = u32
xkb.xkb_state_key_get_one_sym.argtypes = [p, u32]
xkb.xkb_keymap_min_keycode.restype = u32
@@ -150,6 +153,15 @@ class Keymap:
def empty(self, keycode: int) -> bool:
return self._xkb.xkb_keymap_num_layouts_for_key(self._keymap, keycode) == 0
+ def modifier_mask(self, keycode: int) -> int:
+ """Core modifier bits depressed by this key, rather than assuming AltGr is Mod5."""
+ state = self._xkb.xkb_state_new(self._keymap)
+ try:
+ self._xkb.xkb_state_update_key(state, keycode, 1)
+ return self.core_mods(self._xkb.xkb_state_serialize_mods(state, 1))
+ finally:
+ self._xkb.xkb_state_unref(state)
+
def text(self, keysym: int) -> Optional[str]:
point = self._xkb.xkb_keysym_to_utf32(keysym) if keysym else 0
return chr(point) if point else None