mirror of
https://github.com/feschber/lan-mouse.git
synced 2026-05-15 06:06:07 -06:00
[PR #418] Wall-press auto-release, scroll preferences, GUI singleton, and macOS QoL #412
Labels
No labels
Xorg
documentation
enhancement
macos
pull-request
question
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference: github-starred/lan-mouse#412
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/feschber/lan-mouse/pull/418
Author: @jondkinney
Created: 4/30/2026
Status: 🔄 Open
Base:
main← Head:auto-release-and-scroll-invert📝 Commits (10+)
86151f5feat: cross-platform wall-press auto-release fallback3025422fix(proto): tolerate undecodable peer datagrams instead of disconnectingfbce4a5proto: add Bounds(width, height) event variantb6b91c0feat(emulation): display_bounds + warp_cursor for all backends2d21456feat(emulation): send Bounds + warp cursor on Enter588c6a7feat(capture): cache peer bounds and use as wall-press upper clampa26ae8bfix(emulation/wlroots): set axis_source for continuous scroll eventsd0de131ui: wrap window content in GtkScrolledWindow9ed25b0feat: per-receiver natural-scroll preference for forwarded eventsdc09e88fix(capture/macos): emit classic-direction scroll deltas on the wire📊 Changes
50 files changed (+4748 additions, -597 deletions)
View changed files
📝
.gitignore(+1 -0)📝
Cargo.lock(+494 -204)📝
Cargo.toml(+5 -1)📝
input-capture/Cargo.toml(+1 -0)📝
input-capture/src/dummy.rs(+2 -2)📝
input-capture/src/layer_shell.rs(+67 -17)📝
input-capture/src/lib.rs(+574 -11)📝
input-capture/src/libei.rs(+5 -2)📝
input-capture/src/macos.rs(+257 -20)📝
input-capture/src/windows.rs(+1 -1)📝
input-capture/src/windows/event_thread.rs(+66 -12)📝
input-capture/src/x11.rs(+1 -1)📝
input-emulation/src/lib.rs(+49 -0)📝
input-emulation/src/libei.rs(+49 -2)📝
input-emulation/src/macos.rs(+110 -1)📝
input-emulation/src/windows.rs(+41 -4)📝
input-emulation/src/wlroots.rs(+219 -5)📝
input-emulation/src/x11.rs(+38 -1)📝
input-emulation/src/xdg_desktop_portal.rs(+13 -1)📝
lan-mouse-gtk/resources/authorization_window.ui(+78 -82)...and 30 more files
📄 Description
Summary
Ten independent feature areas, each useful on its own:
CGSessionCopyCurrentDictionaryat cross-decision time; Windows registers forWM_WTSSESSION_CHANGE. The complementary direction — cursor already on the peer when the host locks — is covered by §2's wall-press auto-release: host-side input hooks keep running under the lock screen, so pushing against the host-adjacent edge of the peer ejects the cursor back to the host without any extra plumbing.Boundsproto event so the host knows the guest's extent and can clamp / warp accurately. Doubles as the user-facing escape hatch for §1's locked-host-while-on-peer case.lan-mouselaunched twice no longer opens a second window. Decoupled from the daemon socket; headlesslan-mouse daemonworkflow unchanged.Helloproto event lets each peer surface the other's build commit hash in the GUI, with a soft-warn color indicator on mismatch. Listen-side mirror so version visibility doesn't depend on outbound reachability.JKMBP-M4-Max.localand similar Bonjour names now Just Work becausegetaddrinfowalks/etc/nsswitch.conf/ mDNS //etc/hostsinstead of pure-DNS-only.0.0.0.0bind, so reply packets always source from the IP the peer dialed.if-watchsupervisor with periodic reconciliation handles interface plug/unplug and admin-disable._lan-mouse._udp.local.Bonjour service whose TXT record names the OS-preferred-interface IP. Dialer biases toward that IP via a 200ms happy-eyeballs head-start, so multi-homed peers connect via the right interface (Mac service order / Linux default route) without a manualips=[…]workaround.History is pre-cleaned: each commit single-purpose. Diagnostic markers at
log::info!([wp-begin],[release-warp],[bootstrap],[cursor-pos],mdns: …,wall-press …) are intentional — setLAN_MOUSE_LOG_LEVEL=warnto silence.1. Host-lock cross-suppression
When the host's screen is locked, prevent the cursor from leaving for the peer — the host's lock screen consumes keyboard events before any capture hook sees them, so a mouse-only-on-peer state is broken-by-design. This section standardizes that prevention across all platforms; previously Wayland enforced it (because the compositor revokes input on lock) but macOS and Windows didn't, so users on those hosts could silently end up in the half-broken state.
Two cases worth distinguishing:
virtual_cursormodel, and pushing against the host-adjacent edge of the peer fires the wall-press release as if everything were normal. Verified end-to-end on macOS host ↔ Linux peer: lock the Mac while cursor is on Linux, push left, cursor returns. Same mechanism works on Windows host (and on Wayland host where the compositor handles it natively). Release-bind chord and peer-sideLeaveare the alternative recovery paths.Wayland (
free) — the compositor revokes input on layer-shell surfaces when the screen locks, sowl_pointer.Enterstops firing AND the in-flightwl_pointer.Leavearrives, naturally tearing down whichever direction was in play. No code needed.macOS (
8cd86ba/9d6f427/76f3544) — initial attempt wasCFNotificationCenterAddObserverforcom.apple.screenIsLocked/Unlocked, but those callbacks never fired in practice because lan-mouse's main thread runs the GLib event loop, not a CFRunLoop, and the distnoted mach port attaches to the main thread regardless of which thread calledAddObserver. Replaced with a directCGSessionCopyCurrentDictionary["CGSSessionScreenIsLocked"]poll evaluated at the moment a barrier crossing is about to commit — ~10–50 µs of XPC to WindowServer, paid only on cross attempts (a few per minute), zero per-event overhead during in-flight capture. Mid-capture lock isn't separately handled and doesn't need to be: §2's wall-press is the user-facing recovery path and it works under the lock screen because the CGEventTap keeps running.Windows (
8cd86ba) —WTSRegisterSessionNotificationon the existing message-only window;window_procflips aHOST_LOCKEDthread-local onWTS_SESSION_LOCK/WTS_SESSION_UNLOCKand gatescheck_client_activation. Convenience extra: also synthesizesCaptureEvent::AutoReleaseif a capture is already in flight when the lock fires — same hand-off into §2's release plumbing, so the cursor returns to the host the instant the lock screen comes up rather than waiting for the user to wall-press out. Possible because the WTS notification arrives unconditionally; on macOS the equivalent would require polling on every motion event during capture, and §2's wall-press already covers it.2. Wall-press auto-release
User pushes cursor past the host-adjacent edge of the guest and keeps pushing for N more pixels → capture releases. Threshold tunable in GUI; 0 disables.
The triggering scenario is two locked screens. When the peer's screen is locked, its lock screen owns the input pipeline before lan-mouse's capture barrier can fire — so the peer can't detect the user crossing back and never sends
Leaveto the host. The host stays in capture mode indefinitely: every keystroke goes to the (probably-locked) guest, and there's no way to unlock the host without first recovering the cursor via the release-bind chord (Ctrl+Shift+Meta+Alt). Wall-press auto-release breaks this deadlock by treating sustained motion past the host-adjacent edge as an explicit "I want out" signal — without protocol cooperation from the peer, which is the part that's broken.Same mechanism doubles as §1's escape hatch. When the host's screen is locked while the cursor is already on the peer, the host's input hook keeps running under the lock screen, so wall-press still accumulates and still fires. Without it, a user whose host locks mid-capture would have to fall back to the release-bind chord or wait for the peer to fire a
Leave. With it, "lock the Mac with cursor on Linux, push left, cursor returns" Just Works on every platform that has wall-press configured.The naive virtual-cursor accumulator runs away if the user holds against the wall, so the protocol-based fix adds
ProtoEvent::Bounds(width, height)(sent by emulation right after Enter), caches it per-position, and clampsvirtual_posto the peer's actual extent. Emulation also warps the cursor on Enter sovirtual_pos = 0lines up with the guest's actual cursor.display_boundsandwarp_cursorare added as trait methods onInputEmulationand implemented for every backend exceptxdg_desktop_portal(no protocol support — falls back to heuristic-only path).Peer-Leave deadline gate (
34605a7): wall-press used to fire the moment the threshold was crossed, which raced the peer-side layer-shell handover and only "worked correctly" because the network round-trip beat 200px of physical motion. With the gate, wall-press defers AutoRelease for ~150ms after threshold and cancels if a peerLeavearrives in that window. Result: in normal operation the layer-shell handover always wins (no spurious wall-press fires); in true fallback scenarios (peer's layer-shell suppressed, or §1's locked-host-stuck-on-peer case) the deadline elapses and wall-press fires as designed.Bundled forward-compat fix (
3025422): we now log-and-skip undecodable peer datagrams instead of disconnecting. Necessary because peers running pre-Boundsbuilds can interop with this branch.3. Scroll handling
macOS capture (
dc09e88): Wire convention canonicalized to classic mouse-wheel direction regardless of the user's macOS Natural Scrolling preference (read viaCFPreferencesCopyAppValue). Without a fixed wire convention, the receiver-side toggle has no stable reference. Opposite offeschber/lan-mouse#415, which negated unconditionally and traded the bug for the opposite-preference user.wlroots emulation (
a26ae8b): Continuous-scroll events (trackpad) were silently dropped by Hyprland/Sway/GNOME-Shell because theaxis()event lacked a companionaxis_sourcein the samewl_pointer.frame. Spec calls it a "hint"; in practice it's load-bearing for continuous scroll. One extra emit per axis frame fixes it.Receiver-side
Natural scrollingtoggle (9ed25b0): New GUI preference, off by default — wire is classic, receiver re-inverts. Mirrors libinput'snatural_scroll, applied to forwarded events specifically (which on Wayland bypass libinput).macOS line→tick mapping (
19d36bf): Capture used to map one macOS scroll-line to 40 v120 units (1/3 of a wheel tick), so receivers using the discrete count (Slack via XWayland, terminals readingaxis_value120) needed 3+ notches before any scroll registered. macOS already amplifiesSCROLL_WHEEL_EVENT_DELTAby velocity, so one line should map directly to one full v120 tick. Slow-notch and fast-flick behavior is now symmetric across native-Wayland and XWayland clients.4. Cross-platform GUI singleton (
60041ae)Dedicated
lan-mouse-gui.sock(Unix) /127.0.0.1:5253(Windows), separate from the daemon socket. First GUI binds; later launches connect, send a byte, and exit. Primary forwards into the GTK main loop and callswindow.present().Decoupled from the daemon socket on purpose:
lan-mouse daemonheadless workflow is unchanged. Stale-socket recovery if the primary crashed without cleanup. Defense-in-depth viaapp.windows().first()for the in-process activation path. Unit test covers acquire → signal → re-acquire.5. macOS QoL
afe9456) wires to GtkWindow'swindow.closeaction, which on macOS hides the window and flips the activation policy toAccessory— effectively collapses to the menu bar. Linux/Windows unchanged.8a86b9d) fits every preference group on first paint on ≥1440px-tall displays. Tiling Wayland WMs ignoredefault-height, so no effect there.8b0a169) scopes the group label to what it actually controls. Description retightened (66df7e5) to frame it as a peer-locked-screen fallback rather than a positive-action feature, since the deadline gate (§2) makes that its actual role.39752ee): 3stry_wait()poll on the daemon child with SIGKILL fallback, plus a process-levelstd::thread5s force-exit backstop scheduled outside the GTK main loop (so a wedged loop can't prevent it). Worst-case quit latency 5s; normal completes in <1s.56f828f): emulation backend pokesIOPMAssertionDeclareUserActivitywhenever a forwarded event arrives, so a peer-driven keystroke or click wakes the macOS display from idle-sleep. Without this, lan-mouse would keep pumping events to a blanked screen.3743edd): cursor over the release-threshold slider no longer eats main-window scroll events. Capture-phase handler suppressesGtkScale's own scroll-to-adjust handler (so the slider value stays put) AND forwards the scroll to the ancestorScrolledWindow(so the page scrolls naturally).6. Cross-machine cursor position sync
The host computes its cursor's position as a normalized fraction
(nx, ny) ∈ [0, 1]against its own bounds and sendsProtoEvent::CursorPos { pos, nx, ny }right after Enter. The receiver scales against its own live bounds and pins the on-axis dimension to the entry edge. Self-sufficient — works on the very first crossing, noBoundsround-trip needed.One architectural change to flag for review: the release path is now split.
release_capture(release-bind chord, backend auto-release) computes a host-side cursor warp from the cachedvirtual_cursor.release_capture_handover(used when the peer takes over viaReleaseNotifyorProtoEvent::Leave) skips the host warp so the peer's authoritativeCursorPosis the only signal seating our shared cursor.7. Peer version exchange (
29da4d8)ProtoEvent::Hello { commit: [u8; 8] }carries each peer'sshadow_rsSHORT_COMMITonce per session. Sender fires immediately after DTLS auth; listener mirrors the event back so the connect side'sreceive_looppopulatesClientState::peer_commitfor the right handle. Disconnect path clears it.Each outgoing-connection row's collapsed subtitle renders match status with Pango-colored markup: green when commits match, orange when mismatched or when the peer hasn't sent
Hello(older build). Soft-warn only — version mismatch never refuses traffic. The local commit reaches the GTK frontend (separate process) via an explicitlocal_commitparameter onlan_mouse_gtk::run, stashed in aOnceLockso per-row UI can compare against each peer's hash without an IPC round-trip.EventType::Hellois appended to the enum so existing IDs are untouched. Old peers hit the existingInvalidEventIdskip path from3025422and silently ignore the event — backward interop preserved.Listen-side mirror (
1ea7148): the original implementation readpeer_commitonly off the outgoing-connect path, on the assumption that bidirectional setups always have a working outbound connection in both directions. That assumption broke the moment any direction's outbound was down (e.g. peer's TCP listener temporarily not bound) — version display silently said "unknown" while the peer was happily sending events to us inbound. NewEmulationEvent::PeerHello { addr, commit }variant fired from the listen-side Hello handler; service mapsaddr → ClientHandleviaclient_manager.get_client(addr)and stampspeer_commitexactly like the connect path. Version visibility is now independent of outbound reachability.8. Hostname resolution via the OS resolver (
9ce3847)hickory_resolver::TokioResolveronly consults/etc/resolv.confand queries upstream DNS servers — which means it can't see/etc/hosts, mDNS/Avahi/Bonjour, NetBIOS, or anything else in the system's full name-resolution stack. On a typical home LAN there's no DNS server that knows about peer machine names, so users had to fall back to typing IP addresses, which broke the moment they moved their setup to a different network.Swap to
tokio::net::lookup_host, which callsgetaddrinfo. That walks/etc/nsswitch.confon Linux (picking up Avahi-resolved.localnames,/etc/hosts, and DNS), uses Bonjour for.localon macOS, and the full Windows resolver on Windows. A Bonjour hostname likeJKMBP-M4-Max.localnow resolves on every modern network without explicit configuration; the user can carry their two machines between LANs and the connection still finds them. Drop thehickory-resolverdependency entirely; lookup failures surface asio::Error, already covered byServiceError::Io.9. Multi-homed DTLS listener (
2c7ce2e/4c80ed0)When a host has two interfaces on the same subnet (macOS Wi-Fi
en0+ USB-C docken7both on192.168.1.0/24), a single0.0.0.0:portDTLS listener silently breaks for peers that dial the non-routed IP: the kernel sources its reply from the routing table's preferred interface, so the reply's src-IP doesn't match the 4-tuple the peer expects, andwebrtc-dtlsdrops the packet.Replace the single
0.0.0.0bind with oneListenerper local IPv4 address (loopback + link-local skipped), each socket bound to a specific IP so the kernel uses that IP as source — symmetric replies guaranteed regardless of the routing table. Anif-watchsupervisor task adds/drops listener slots dynamically on interface up/down; plugging a dock or toggling Wi-Fi no longer requires a lan-mouse restart.The supervisor also runs a 30-second reconciliation tick that diffs the live
getifaddrsset against the listeners HashMap.if-watchon macOS uses Network.framework, which doesn't reliably fireIfEvent::Downwhen an interface is administratively disabled (e.g. user toggles Wi-Fi off in System Settings); the polling backup catches whatever the event stream misses, both adds and drops.Falls back to a single
0.0.0.0bind only if interface enumeration or every per-IP bind fails — preserves single-NIC behavior and ensures we never silently fail to listen.Removes the previous user-facing workaround of forcing
ips = ["192.168.1.88"]on the peer.10. mDNS-SD service-order discovery (
5ae6fee)Even with a multi-homed listener (§9), the dialer still has to choose which of the peer's IPs to dial first — and plain hostname resolution returns every interface's IP without ranking.
connect_any's parallel race picks whichever DTLS handshake completes first, which is RTT-roughly-correct but not always what the user wanted. The classic symptom: Wi-Fi wins the race even when the user has Ethernet ranked higher in macOS's service order, leading to a stuttery session over Wi-Fi while a healthy wired path sits idle.Each lan-mouse instance now publishes a
_lan-mouse._udp.local.Bonjour service whose TXT record carriesprimary=<ipv4>, where<ipv4>is the IP of the interface that owns the default route — which on macOS reflects service order, on Linux the lowest-metric default route, on Windows whateverGetBestRoute2selects. The dialer continuously browses the same service type and cachespeer_hostname → primary_ipv4in aRc<RefCell<HashMap>>shared withLanMouseConnection.connect_anyextended with happy-eyeballs head-start: if a preferred address is known, dial it alone for 200ms before joining the rest of the candidate list to the race. A healthy preferred path virtually always wins; a broken one only delays connect by 200ms before fallbacks kick in. (Cf. RFC 8305 IPv6→IPv4 fallback delay.)Subsystem gated by a new
mdns_discoveryconfig flag (default true) and a corresponding GUI switch under a new "Network Discovery" preferences group. Toggling off unregisters the service, aborts the browse task, and shuts the daemon, but preserves theprimary_cacheso already-known hints stay queryable until overwritten — useful on networks where mDNS multicast (224.0.0.251) is firewalled. A 30-seconddiscovery_refresh_tickre-publishes the TXT record so it stays accurate when the OS-preferred interface changes (e.g. user toggles Wi-Fi off and Ethernet takes over).New deps:
mdns-sd(cross-platform mDNS responder, doesn't piggyback on system Avahi/Bonjour),netdev(default-route lookup),hostname(local hostname for the service instance name).Falls back gracefully when
ServiceDaemon::newfails (multicast group locked / no perms), no interface owns the default route, or the peer isn't announcing (old version or discovery disabled there) — the dialer just seespreferred = Noneand the existingconnect_anyrace runs unchanged.Test plan
Verified locally: macOS host (2056×1329 logical) ↔ Hyprland guest (2400×1500 logical) over both wired and wifi LAN. Crossings at top / middle / bottom of source land proportionally on destination, both directions, including fast back-and-forth within the same second. Wall-press auto-release deadline gate behaves correctly: never fires on healthy crosses, fires after the deadline elapses on locked-peer scenarios. Trackpad and mouse-wheel scrolling forward correctly with both natural and classic preference combinations, including single-notch behavior in Slack (XWayland) and ghostty (native Wayland). macOS Cmd+W / Cmd+Q / GUI singleton verified. Peer version exchange shows green-matched on same-commit pairs and orange-unknown when one side runs a pre-Hello build, and remains correct in one-direction-down scenarios (listen-side mirror). Host-lock suppression verified on macOS (
Cmd+Ctrl+Qlock; cursor refuses to cross until unlock; with cursor already on Linux, push-left wall-press cleanly returns the cursor to the locked Mac). mDNS-SD primary-IP hint verified on a multi-homed Mac (Wi-Fi + Ethernet on same subnet): Linux dialer consistently selects the Ethernet path even when Wi-Fi wins a raw RTT race.Open items (not blocking — environment access):
Build hygiene:
cargo fmt --allclean,cargo clippy --workspace --all-targets --all-features -- -D warningsclean,cargo test --workspacepasses (1 new test inlan-mouse-ipc).🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.