Merge branch 'main' into windows-msi-installer

This commit is contained in:
Ferdinand Schober
2026-05-06 10:45:03 +02:00
committed by GitHub
47 changed files with 2855 additions and 1277 deletions

24
.editorconfig Normal file
View File

@@ -0,0 +1,24 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.rs]
indent_style = space
indent_size = 4
max_line_length = 100
[*.{yml,yaml}]
indent_style = space
indent_size = 2
[*.toml]
indent_style = space
indent_size = 4
[*.nix]
indent_style = space
indent_size = 2

34
.githooks/pre-commit Executable file
View File

@@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
# Ensure we're at the repo root
cd "$(git rev-parse --show-toplevel)" || exit 1
echo "Running cargo fmt (auto-format)..."
# Run formatter to apply fixes but do not stage them. If formatting changed,
# fail the commit so the user can review and stage the changes manually.
cargo fmt --all
if ! git diff --quiet --exit-code; then
echo "" >&2
echo "ERROR: cargo fmt modified files. Review changes, stage them, and commit again." >&2
git --no-pager diff --name-only
exit 1
fi
echo "Running cargo clippy..."
# Matches CI: deny warnings to keep code health strict
if ! cargo clippy --workspace --all-targets --all-features -- -D warnings; then
echo "" >&2
echo "ERROR: clippy found warnings/errors. Fix them before committing." >&2
exit 1
fi
echo "Running cargo test..."
if ! cargo test --workspace --all-features; then
echo "" >&2
echo "ERROR: Some tests failed. Fix tests before committing." >&2
exit 1
fi
echo "All pre-commit checks passed."
exit 0

View File

@@ -7,6 +7,10 @@ on:
branches: ["main"]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
nix:
strategy:
@@ -19,7 +23,7 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
submodules: recursive

View File

@@ -1,10 +1,17 @@
name: "pre-release"
name: "Release"
run-name: "Release - ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || github.event.inputs.name || github.ref_name }}"
on:
push:
branches: [ "main" ]
tags:
- v**
workflow_dispatch:
inputs:
name:
description: 'Development release name'
required: false
default: ''
env:
CARGO_TERM_COLOR: always
@@ -13,19 +20,40 @@ jobs:
linux-release-build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: install dependencies
run: |
sudo apt-get update
sudo apt-get install libx11-dev libxtst-dev
sudo apt-get install libadwaita-1-dev libgtk-4-dev
- name: Release Build
run: cargo build --release
run: |
cargo build --release
cp target/release/lan-mouse lan-mouse-linux-x86_64
- name: Upload build artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: lan-mouse-linux
path: target/release/lan-mouse
name: lan-mouse-linux-x86_64
path: lan-mouse-linux-x86_64
linux-arm64-release-build:
runs-on: ubuntu-22.04-arm
steps:
- uses: actions/checkout@v6
- name: install dependencies
run: |
sudo apt-get update
sudo apt-get install libx11-dev libxtst-dev
sudo apt-get install libadwaita-1-dev libgtk-4-dev
- name: Release Build
run: |
cargo build --release
cp target/release/lan-mouse lan-mouse-linux-arm64
- name: Upload build artifact
uses: actions/upload-artifact@v6
with:
name: lan-mouse-linux-arm64
path: lan-mouse-linux-arm64
windows-release-build:
runs-on: windows-latest
@@ -64,7 +92,7 @@ jobs:
gvsbuild build --msys-dir=C:\msys64 gtk4 libadwaita librsvg
Move-Item "C:\Program Files\Git\usr\notbin" "C:\Program Files\Git\usr\bin"
Move-Item "C:\Program Files\Git\notbin" "C:\Program Files\Git\bin"
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Release Build
run: cargo build --release
- name: Create Archive
@@ -72,19 +100,21 @@ jobs:
mkdir "lan-mouse-windows"
Get-Childitem -Path "C:\\gtk-build\\gtk\\x64\\release\\bin\\*.dll" -File -Recurse | Copy-Item -Destination "lan-mouse-windows"
Copy-Item -Path "target\release\lan-mouse.exe" -Destination "lan-mouse-windows"
Compress-Archive -Path "lan-mouse-windows\*" -DestinationPath lan-mouse-windows.zip
Compress-Archive -Path "lan-mouse-windows\*" -DestinationPath lan-mouse-windows-x86_64.zip
- name: Upload build artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: lan-mouse-windows
path: lan-mouse-windows.zip
name: lan-mouse-windows-x86_64
path: lan-mouse-windows-x86_64.zip
macos-release-build:
runs-on: macos-15-intel
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: install dependencies
run: brew install gtk4 libadwaita imagemagick
run: |
brew install --cask inkscape
brew install gtk4 libadwaita imagemagick librsvg
- name: Release Build
run: |
cargo build --release
@@ -102,21 +132,23 @@ jobs:
cd target/release/bundle/osx
zip -r "lan-mouse-macos-intel.zip" "Lan Mouse.app"
- name: Upload build artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: lan-mouse-macos-intel
path: target/release/bundle/osx/lan-mouse-macos-intel.zip
macos-aarch64-release-build:
runs-on: macos-14
macos-arm64-release-build:
runs-on: macos-15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: install dependencies
run: brew install gtk4 libadwaita imagemagick
run: |
brew install --cask inkscape
brew install gtk4 libadwaita imagemagick librsvg
- name: Release Build
run: |
cargo build --release
cp target/release/lan-mouse lan-mouse-macos-aarch64
cp target/release/lan-mouse lan-mouse-macos-arm64
- name: Make icns
run: scripts/makeicns.sh
- name: Install cargo bundle
@@ -128,29 +160,45 @@ jobs:
- name: Zip bundle
run: |
cd target/release/bundle/osx
zip -r "lan-mouse-macos-aarch64.zip" "Lan Mouse.app"
zip -r "lan-mouse-macos-arm64.zip" "Lan Mouse.app"
- name: Upload build artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: lan-mouse-macos-aarch64
path: target/release/bundle/osx/lan-mouse-macos-aarch64.zip
name: lan-mouse-macos-arm64
path: target/release/bundle/osx/lan-mouse-macos-arm64.zip
pre-release:
name: "Pre Release"
needs: [windows-release-build, linux-release-build, macos-release-build, macos-aarch64-release-build]
release:
name: "Release"
needs: [windows-release-build, linux-release-build, linux-arm64-release-build, macos-release-build, macos-arm64-release-build]
runs-on: "ubuntu-latest"
steps:
- name: Download build artifacts
uses: actions/download-artifact@v4
- name: Create Release
uses: "marvinpinto/action-automatic-releases@latest"
- name: Create Pre-Release
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
uses: softprops/action-gh-release@v2
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "latest"
token: ${{ secrets.GITHUB_TOKEN }}
tag_name: ${{ github.event.inputs.name || github.ref_name }}
name: ${{ github.event.inputs.name || github.ref_name }}
prerelease: true
title: "Development Build"
generate_release_notes: true
files: |
lan-mouse-linux/lan-mouse
lan-mouse-linux-x86_64/lan-mouse-linux-x86_64
lan-mouse-linux-arm64/lan-mouse-linux-arm64
lan-mouse-macos-intel/lan-mouse-macos-intel.zip
lan-mouse-macos-aarch64/lan-mouse-macos-aarch64.zip
lan-mouse-windows/lan-mouse-windows.zip
lan-mouse-macos-arm64/lan-mouse-macos-arm64.zip
lan-mouse-windows-x86_64/lan-mouse-windows-x86_64.zip
- name: Create Tagged Release
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
name: ${{ github.ref_name }}
generate_release_notes: true
files: |
lan-mouse-linux-x86_64/lan-mouse-linux-x86_64
lan-mouse-linux-arm64/lan-mouse-linux-arm64
lan-mouse-macos-intel/lan-mouse-macos-intel.zip
lan-mouse-macos-arm64/lan-mouse-macos-arm64.zip
lan-mouse-windows-x86_64/lan-mouse-windows-x86_64.zip

View File

@@ -9,12 +9,16 @@ on:
env:
CARGO_TERM_COLOR: always
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
fmt:
name: Formatting
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: cargo fmt
run: cargo fmt --check
@@ -35,7 +39,7 @@ jobs:
- clippy
- test
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: Swatinem/rust-cache@v2
- name: Install Linux deps
if: runner.os == 'Linux'

View File

@@ -1,150 +0,0 @@
name: "Tagged Release"
on:
push:
tags:
- v**
jobs:
linux-release-build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: install dependencies
run: |
sudo apt-get update
sudo apt-get install libx11-dev libxtst-dev
sudo apt-get install libadwaita-1-dev libgtk-4-dev
- name: Release Build
run: cargo build --release
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: lan-mouse-linux
path: target/release/lan-mouse
windows-release-build:
runs-on: windows-latest
steps:
- uses: actions/setup-python@v5
with:
python-version: '3.11'
# needed for cache restore
- name: create gtk dir
run: mkdir C:\gtk-build\gtk\x64\release
- uses: actions/cache@v3
id: cache
with:
path: c:/gtk-build/gtk/x64/release/**
key: gtk-windows-build
restore-keys: gtk-windows-build
- name: Update path
run: |
echo "PKG_CONFIG=C:\gtk-build\gtk\x64\release\bin\pkgconf.exe" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
echo "C:\pkg-config-lite-0.28-1\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
echo "C:\gtk-build\gtk\x64\release\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
echo $env:GITHUB_PATH
echo $env:PATH
- name: Install dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: |
# choco install msys2
# choco install visualstudio2022-workload-vctools
# choco install pkgconfiglite
py -m venv .venv
.venv\Scripts\activate.ps1
py -m pip install gvsbuild
# see https://github.com/wingtk/gvsbuild/pull/1004
Move-Item "C:\Program Files\Git\usr\bin" "C:\Program Files\Git\usr\notbin"
Move-Item "C:\Program Files\Git\bin" "C:\Program Files\Git\notbin"
gvsbuild build --msys-dir=C:\msys64 gtk4 libadwaita librsvg
Move-Item "C:\Program Files\Git\usr\notbin" "C:\Program Files\Git\usr\bin"
Move-Item "C:\Program Files\Git\notbin" "C:\Program Files\Git\bin"
- uses: actions/checkout@v4
- name: Release Build
run: cargo build --release
- name: Create Archive
run: |
mkdir "lan-mouse-windows"
Get-Childitem -Path "C:\\gtk-build\\gtk\\x64\\release\\bin\\*.dll" -File -Recurse | Copy-Item -Destination "lan-mouse-windows"
Copy-Item -Path "target\release\lan-mouse.exe" -Destination "lan-mouse-windows"
Compress-Archive -Path "lan-mouse-windows\*" -DestinationPath lan-mouse-windows.zip
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: lan-mouse-windows
path: lan-mouse-windows.zip
macos-release-build:
runs-on: macos-15-intel
steps:
- uses: actions/checkout@v4
- name: install dependencies
run: brew install gtk4 libadwaita imagemagick
- name: Release Build
run: |
cargo build --release
cp target/release/lan-mouse lan-mouse-macos-intel
- name: Make icns
run: scripts/makeicns.sh
- name: Install cargo bundle
run: cargo install cargo-bundle
- name: Bundle
run: |
cargo bundle --release
scripts/copy-macos-dylib.sh "target/release/bundle/osx/Lan Mouse.app/Contents/MacOS/lan-mouse"
- name: Zip bundle
run: |
cd target/release/bundle/osx
zip -r "lan-mouse-macos-intel.zip" "Lan Mouse.app"
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: lan-mouse-macos-intel.zip
path: target/release/bundle/osx/lan-mouse-macos-intel.zip
macos-aarch64-release-build:
runs-on: macos-14
steps:
- uses: actions/checkout@v4
- name: install dependencies
run: brew install gtk4 libadwaita imagemagick
- name: Release Build
run: |
cargo build --release
cp target/release/lan-mouse lan-mouse-macos-aarch64
- name: Make icns
run: scripts/makeicns.sh
- name: Install cargo bundle
run: cargo install cargo-bundle
- name: Bundle
run: |
cargo bundle --release
scripts/copy-macos-dylib.sh "target/release/bundle/osx/Lan Mouse.app/Contents/MacOS/lan-mouse"
- name: Zip bundle
run: |
cd target/release/bundle/osx
zip -r "lan-mouse-macos-aarch64.zip" "Lan Mouse.app"
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: lan-mouse-macos-aarch64.zip
path: target/release/bundle/osx/lan-mouse-macos-aarch64.zip
tagged-release:
name: "Tagged Release"
needs: [windows-release-build, linux-release-build, macos-release-build, macos-aarch64-release-build]
runs-on: "ubuntu-latest"
steps:
- name: Download build artifacts
uses: actions/download-artifact@v4
- name: Create Release
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false
files: |
lan-mouse-linux/lan-mouse
lan-mouse-macos-intel/lan-mouse-macos-intel.zip
lan-mouse-macos-aarch64/lan-mouse-macos-aarch64.zip
lan-mouse-windows/lan-mouse-windows.zip

65
AGENTS.md Normal file
View File

@@ -0,0 +1,65 @@
# Lan Mouse Agent Instructions
## Overview
Lan Mouse is an open-source Software KVM sharing mouse/keyboard input across local networks. The Rust workspace combines a GTK frontend, CLI/daemon mode, and multi-OS capture/emulation backends for Linux, Windows, and macOS.
## Core principles
- **Scope discipline.** Only implement what was requested; describe follow-up work instead of absorbing it.
- **Clarify OS behavior.** Ask when requirements touch OS-specific capture/emulation (they differ significantly).
- **Docs stay current.** Update [README.md](README.md) or [DOC.md](DOC.md) when touching public APIs or platform support.
- **Rust idioms.** Use `Result`/`Option`, `thiserror` for errors, descriptive logs, and concise comments for non-obvious invariants.
## Terminology
- **Client:** A remote machine that can receive or send input events. Each client is either _active_ (receiving events) or _inactive_ (can send events back). This mutual exclusion prevents feedback loops.
- **Backend:** OS-specific implementation for capture or emulation (e.g., libei, layer-shell, wlroots, X11, Windows, macOS).
- **Handle:** A per-client identifier used to route events and track state (pressed keys, position).
## Architecture
**Pipeline:** `input-capture``lan-mouse-ipc``input-emulation`
- **input-capture:** Reads OS events into a `Stream<CaptureEvent>`. Backends tried in priority order (libei → layer-shell → X11 → fallback). Tracks `pressed_keys` to avoid stuck modifiers. `position_map` queues events when multiple clients share a screen edge.
- **input-emulation:** Replays events via the `Emulation` trait (`consume`, `create`, `destroy`, `terminate`). Maintains `pressed_keys` and releases them on disconnect.
- **lan-mouse-ipc / lan-mouse-proto:** Protocol glue and serialization. Events are UDP; connection requests are TCP on the same port. Version bumps required when serialization changes.
- **input-event:** Shared scancode enums and abstract event types—extend here, don't duplicate translations.
## Feature & cfg discipline
- Feature flags live in root `Cargo.toml`. Gate OS-specific modules with tight cfgs (e.g., `cfg(all(unix, feature = "layer_shell", not(target_os = "macos")))`).
- Prefer module-level gating over per-function cfgs to avoid empty stubs.
- New backends: add feature in `Cargo.toml`, create gated module, log backend selection.
## Async patterns
- Tokio runtime with `futures` streams and `async_trait`. Model new flows as streams or async methods.
- Avoid blocking; use `spawn_blocking` if needed. Prefer existing single-threaded stream handling.
- `InputCapture` implements `Stream` and manually pumps backends—don't short-circuit this logic.
## Commands
```sh
cargo build --workspace # full build
cargo build -p <crate> # single crate
cargo test --workspace # all tests
cargo fmt && cargo clippy --workspace --all-targets --all-features # lint
RUST_LOG=lan_mouse=debug cargo run # debug logging
```
Run from repo root—no `cd` in scripts.
## Testing
- Unit tests for utilities; integration tests for protocol behavior.
- OS-specific backends: test via GTK/CLI on target OS or document manual verification.
- Dummy backend exercises pipeline without real dependencies.
- Verify `terminate()` releases keys on unexpected disconnect.
## Workflow
1. Clarify ambiguous requirements, especially OS-specific behavior.
2. Implement minimal change; flag follow-up work.
3. Add proportional tests; run `cargo test` on affected crates.
4. Run `cargo fmt` and `cargo clippy --workspace --all-targets --all-features`.

1793
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -67,6 +67,7 @@ rustls = { version = "0.23.12", default-features = false, features = [
] }
rcgen = "0.13.1"
sha2 = "0.10.8"
notify = "8.2.0"
[target.'cfg(unix)'.dependencies]
libc = "0.2.148"
@@ -95,3 +96,5 @@ rdp_emulation = ["input-emulation/remote_desktop_portal"]
name = "Lan Mouse"
icon = ["target/icon.icns"]
identifier = "de.feschber.LanMouse"
osx_info_plist_exts = ["build-aux/macos-lsui-element.plist"]
resources = ["target/menubar-template.png"]

View File

@@ -1,4 +1,9 @@
# Lan Mouse
[![CI](https://github.com/feschber/lan-mouse/actions/workflows/rust.yml/badge.svg)](https://github.com/feschber/lan-mouse/actions/workflows/rust.yml) [![Cachix](https://github.com/feschber/lan-mouse/actions/workflows/cachix.yml/badge.svg)](https://github.com/feschber/lan-mouse/actions/workflows/cachix.yml) [![Release](https://github.com/feschber/lan-mouse/actions/workflows/release.yml/badge.svg)](https://github.com/feschber/lan-mouse/actions/workflows/release.yml)
[![crates.io](https://img.shields.io/crates/v/lan-mouse.svg)](https://crates.io/crates/lan-mouse) [![license](https://img.shields.io/crates/l/lan-mouse.svg)](https://github.com/feschber/lan-mouse/blob/main/Cargo.toml)
Lan Mouse is a *cross-platform* mouse and keyboard sharing software similar to universal-control on Apple devices.
It allows for using multiple PCs via a single set of mouse and keyboard.
This is also known as a Software KVM switch.
@@ -100,6 +105,7 @@ dnf install lan-mouse
- Unzip it
- Remove the quarantine with `xattr -rd com.apple.quarantine "Lan Mouse.app"`
- Launch the app
- Use the menu bar item to open the settings window or quit Lan Mouse. Bundled macOS builds run as a menu bar app and do not keep a Dock icon visible.
- Grant accessibility permissions in System Preferences
</details>
@@ -177,8 +183,27 @@ For a detailed list of available features, checkout the [Cargo.toml](./Cargo.tom
## Development
## Installing Dependencies for Development / Compiling from Source
### Git pre-commit hook
This repository includes a local git hooks directory `.githooks/` with a `pre-commit` script that enforces formatting, lints, and tests before allowing a commit. It is optional to enable it, but it will prevent you from committing code with failing unit tests or that needs clippy/fmt fixes. To enable the hook locally:
1. Make the hook executable:
```sh
chmod +x .githooks/pre-commit
```
2. Point git to the hooks directory (one-time per clone):
```sh
git config core.hooksPath .githooks
```
The `pre-commit` script runs `cargo fmt --all` (and fails if files were modified), `cargo clippy --workspace --all-targets --all-features -- -D warnings`, and `cargo test --workspace --all-features`.
### Dependencies & Compiling from Source
<details>
<summary>MacOS</summary>

View File

@@ -0,0 +1,8 @@
<key>LSUIElement</key>
<true/>
<key>NSAppSleepDisabled</key>
<true/>
<key>NSInputMonitoringUsageDescription</key>
<string>Lan Mouse needs Input Monitoring access to capture keyboard and mouse input and forward it to remote machines on your network.</string>
<key>NSAppleEventsUsageDescription</key>
<string>Lan Mouse uses Apple Events to deliver synthesized keyboard and mouse events to the system.</string>

View File

@@ -12,7 +12,7 @@ futures-core = "0.3.30"
log = "0.4.22"
input-event = { path = "../input-event", version = "0.3.0" }
memmap = "0.7"
tempfile = "3.8"
tempfile = "3.25.0"
thiserror = "2.0.0"
tokio = { version = "1.32.0", features = [
"io-util",
@@ -41,7 +41,8 @@ wayland-protocols-wlr = { version = "0.3.1", features = [
"client",
], optional = true }
x11 = { version = "2.21.0", features = ["xlib", "xtest"], optional = true }
ashpd = { version = "0.11.0", default-features = false, features = [
ashpd = { version = "0.13.9", default-features = false, features = [
"input_capture",
"tokio",
], optional = true }
reis = { version = "0.5.0", features = ["tokio"], optional = true }

View File

@@ -149,6 +149,10 @@ pub enum MacosCaptureCreationError {
#[cfg(target_os = "macos")]
#[error("event tap creation failed")]
EventTapCreation,
#[error("accessibility permission is required")]
AccessibilityPermission,
#[error("input monitoring permission is required")]
InputMonitoringPermission,
#[error("failed to set CG Cursor property")]
CGCursorProperty,
#[cfg(target_os = "macos")]

View File

@@ -171,6 +171,19 @@ impl InputCapture {
self.capture.release().await
}
/// Drain and return every key the capture has forwarded as
/// down-but-not-up. The caller is expected to synthesize key-up
/// events to the remote peer for each — otherwise the peer
/// retains phantom-held keys after capture is released. The
/// canonical case is the release-bind chord
/// (Ctrl+Shift+Alt+Meta): the down events were sent while
/// capture was active, but the matching up events arrive after
/// the local tap has flipped to passthrough and never reach
/// the peer.
pub fn take_pressed_keys(&mut self) -> HashSet<scancode::Linux> {
std::mem::take(&mut self.pressed_keys)
}
/// destroy the input capture
pub async fn terminate(&mut self) -> Result<(), CaptureError> {
self.capture.terminate().await

View File

@@ -2,8 +2,8 @@ use ashpd::{
desktop::{
Session,
input_capture::{
Activated, ActivatedBarrier, Barrier, BarrierID, Capabilities, InputCapture, Region,
Zones,
Activated, ActivatedBarrier, Barrier, BarrierID, Capabilities, CreateSessionOptions,
InputCapture, Region, ReleaseOptions, Zones,
},
},
enumflags2::BitFlags,
@@ -58,8 +58,8 @@ enum LibeiNotifyEvent {
}
#[allow(dead_code)]
pub struct LibeiInputCapture<'a> {
input_capture: Pin<Box<InputCapture<'a>>>,
pub struct LibeiInputCapture {
input_capture: Pin<Box<InputCapture>>,
capture_task: JoinHandle<Result<(), CaptureError>>,
event_rx: Receiver<(Position, CaptureEvent)>,
notify_capture: Sender<LibeiNotifyEvent>,
@@ -130,12 +130,15 @@ fn select_barriers(
}
async fn update_barriers(
input_capture: &InputCapture<'_>,
session: &Session<'_, InputCapture<'_>>,
input_capture: &InputCapture,
session: &Session<InputCapture>,
active_clients: &[Position],
next_barrier_id: &mut NonZeroU32,
) -> Result<(Vec<ICBarrier>, HashMap<BarrierID, Position>), ashpd::Error> {
let zones = input_capture.zones(session).await?.response()?;
let zones = input_capture
.zones(session, Default::default())
.await?
.response()?;
log::debug!("zones: {zones:?}");
let (barriers, id_map) = select_barriers(&zones, active_clients, next_barrier_id);
@@ -144,31 +147,38 @@ async fn update_barriers(
let ashpd_barriers: Vec<Barrier> = barriers.iter().copied().map(|b| b.into()).collect();
let response = input_capture
.set_pointer_barriers(session, &ashpd_barriers, zones.zone_set())
.set_pointer_barriers(
session,
&ashpd_barriers,
zones.zone_set(),
Default::default(),
)
.await?;
let response = response.response()?;
log::debug!("{response:?}");
Ok((barriers, id_map))
}
async fn create_session<'a>(
input_capture: &'a InputCapture<'a>,
) -> std::result::Result<(Session<'a, InputCapture<'a>>, BitFlags<Capabilities>), ashpd::Error> {
async fn create_session(
input_capture: &InputCapture,
) -> std::result::Result<(Session<InputCapture>, BitFlags<Capabilities>), ashpd::Error> {
log::debug!("creating input capture session");
let create_session_options = CreateSessionOptions::default().set_capabilities(
Capabilities::Keyboard | Capabilities::Pointer | Capabilities::Touchscreen,
);
input_capture
.create_session(
None,
Capabilities::Keyboard | Capabilities::Pointer | Capabilities::Touchscreen,
)
.create_session(None, create_session_options)
.await
}
async fn connect_to_eis(
input_capture: &InputCapture<'_>,
session: &Session<'_, InputCapture<'_>>,
input_capture: &InputCapture,
session: &Session<InputCapture>,
) -> Result<(ei::Context, Connection, EiConvertEventStream), CaptureError> {
log::debug!("connect_to_eis");
let fd = input_capture.connect_to_eis(session).await?;
let fd = input_capture
.connect_to_eis(session, Default::default())
.await?;
// create unix stream from fd
let stream = UnixStream::from(fd);
@@ -201,10 +211,10 @@ async fn libei_event_handler(
}
}
impl LibeiInputCapture<'_> {
impl LibeiInputCapture {
pub async fn new() -> std::result::Result<Self, LibeiCaptureCreationError> {
let input_capture = Box::pin(InputCapture::new().await?);
let input_capture_ptr = input_capture.as_ref().get_ref() as *const InputCapture<'static>;
let input_capture_ptr = input_capture.as_ref().get_ref() as *const InputCapture;
let first_session = Some(create_session(unsafe { &*input_capture_ptr }).await?);
let (event_tx, event_rx) = mpsc::channel(1);
@@ -238,10 +248,10 @@ impl LibeiInputCapture<'_> {
}
async fn do_capture(
input_capture: *const InputCapture<'static>,
input_capture: *const InputCapture,
mut capture_event: Receiver<LibeiNotifyEvent>,
notify_release: Arc<Notify>,
session: Option<(Session<'_, InputCapture<'_>>, BitFlags<Capabilities>)>,
session: Option<(Session<InputCapture>, BitFlags<Capabilities>)>,
event_tx: Sender<(Position, CaptureEvent)>,
cancellation_token: CancellationToken,
) -> Result<(), CaptureError> {
@@ -307,7 +317,7 @@ async fn do_capture(
// disable capture
log::debug!("disabling input capture");
if let Err(e) = input_capture.disable(&session).await {
if let Err(e) = input_capture.disable(&session, Default::default()).await {
log::warn!("input_capture.disable(&session) {e}");
}
if let Err(e) = session.close().await {
@@ -336,8 +346,8 @@ async fn do_capture(
}
async fn do_capture_session(
input_capture: &InputCapture<'_>,
session: &mut Session<'_, InputCapture<'_>>,
input_capture: &InputCapture,
session: &mut Session<InputCapture>,
event_tx: &Sender<(Position, CaptureEvent)>,
active_clients: &[Position],
next_barrier_id: &mut NonZeroU32,
@@ -356,7 +366,7 @@ async fn do_capture_session(
update_barriers(input_capture, session, active_clients, next_barrier_id).await?;
log::debug!("enabling session");
input_capture.enable(session).await?;
input_capture.enable(session, Default::default()).await?;
// cancellation token to release session
let release_session = Arc::new(Notify::new());
@@ -462,9 +472,9 @@ async fn do_capture_session(
Ok(())
}
async fn release_capture<'a>(
input_capture: &InputCapture<'a>,
session: &Session<'a, InputCapture<'a>>,
async fn release_capture(
input_capture: &InputCapture,
session: &Session<InputCapture>,
activated: Activated,
current_pos: Position,
) -> Result<(), CaptureError> {
@@ -484,9 +494,10 @@ async fn release_capture<'a>(
};
// release 1px to the right of the entered zone
let cursor_position = (x as f64 + dx, y as f64 + dy);
input_capture
.release(session, activated.activation_id(), Some(cursor_position))
.await?;
let release_options = ReleaseOptions::default()
.set_activation_id(activated.activation_id())
.set_cursor_position(Some(cursor_position));
input_capture.release(session, release_options).await?;
Ok(())
}
@@ -561,7 +572,7 @@ async fn handle_ei_event(
}
#[async_trait]
impl LanMouseInputCapture for LibeiInputCapture<'_> {
impl LanMouseInputCapture for LibeiInputCapture {
async fn create(&mut self, pos: Position) -> Result<(), CaptureError> {
let _ = self
.notify_capture
@@ -598,7 +609,7 @@ impl LanMouseInputCapture for LibeiInputCapture<'_> {
}
}
impl Drop for LibeiInputCapture<'_> {
impl Drop for LibeiInputCapture {
fn drop(&mut self) {
if !self.terminated {
/* this workaround is needed until async drop is stabilized */
@@ -607,10 +618,10 @@ impl Drop for LibeiInputCapture<'_> {
}
}
impl Stream for LibeiInputCapture<'_> {
impl Stream for LibeiInputCapture {
type Item = Result<(Position, CaptureEvent), CaptureError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
match self.capture_task.poll_unpin(cx) {
Poll::Ready(r) => match r.expect("failed to join") {
Ok(()) => Poll::Ready(None),

View File

@@ -2,7 +2,7 @@ use super::{Capture, CaptureError, CaptureEvent, Position, error::MacosCaptureCr
use async_trait::async_trait;
use bitflags::bitflags;
use core_foundation::{
base::{CFRelease, kCFAllocatorDefault},
base::{CFRelease, TCFType, kCFAllocatorDefault},
date::CFTimeInterval,
number::{CFBooleanRef, kCFBooleanTrue},
runloop::{CFRunLoop, CFRunLoopSource, kCFRunLoopCommonModes},
@@ -28,7 +28,7 @@ use std::{
collections::HashSet,
ffi::{CString, c_char},
pin::Pin,
sync::Arc,
sync::{Arc, OnceLock},
task::{Context, Poll, ready},
thread::{self},
};
@@ -67,6 +67,7 @@ enum ProducerEvent {
Destroy(Position),
Grab(Position),
EventTapDisabled,
DisplayReconfigured,
}
impl InputCaptureState {
@@ -176,7 +177,31 @@ impl InputCaptureState {
}
self.active_clients.remove(&p);
}
ProducerEvent::EventTapDisabled => return Err(CaptureError::EventTapDisabled),
ProducerEvent::EventTapDisabled => {
// Tap death can happen mid-capture (TCC Accessibility
// revoked, tap-timeout, etc). Release state so we
// don't leave the cursor hidden even if the outer
// task only logs this error rather than propagating.
if self.current_pos.is_some() {
self.show_cursor()?;
self.current_pos = None;
}
return Err(CaptureError::EventTapDisabled);
}
ProducerEvent::DisplayReconfigured => {
// The macOS display configuration changed — a monitor
// was plugged in/out, the resolution changed, the
// arrangement was rearranged, etc. Re-fetch the
// active-display bounds so barrier crossings and the
// cursor-warp on capture-start use the current
// geometry instead of whatever was true at process
// start.
if let Err(e) = self.update_bounds() {
log::warn!("failed to refresh display bounds: {e}");
} else {
log::info!("display reconfigured: {:?}", self.bounds);
}
}
};
Ok(())
}
@@ -385,6 +410,14 @@ fn create_event_tap<'a>(
notify_tx: Sender<ProducerEvent>,
event_tx: Sender<(Position, CaptureEvent)>,
) -> Result<CGEventTap<'a>, MacosCaptureCreationError> {
// Shared slot for the tap's mach port pointer. Stored as `usize`
// because raw pointers aren't `Send`, but the integer
// representation is — and CGEventTapEnable is documented as
// thread-safe. Set immediately after CGEventTap::new returns;
// read by the callback to recover from a TapDisabledByTimeout.
let tap_mach_port: Arc<OnceLock<usize>> = Arc::new(OnceLock::new());
let tap_mach_port_cb = Arc::clone(&tap_mach_port);
let cg_events_of_interest: Vec<CGEventType> = vec![
CGEventType::LeftMouseDown,
CGEventType::LeftMouseUp,
@@ -402,76 +435,114 @@ fn create_event_tap<'a>(
CGEventType::FlagsChanged,
];
let event_tap_callback =
move |_proxy: CGEventTapProxy, event_type: CGEventType, cg_ev: &CGEvent| {
log::trace!("Got event from tap: {event_type:?}");
let mut state = client_state.blocking_lock();
let mut capture_position = None;
let mut res_events = vec![];
let event_tap_callback = move |_proxy: CGEventTapProxy,
event_type: CGEventType,
cg_ev: &CGEvent| {
log::trace!("Got event from tap: {event_type:?}");
let mut state = client_state.blocking_lock();
let mut capture_position = None;
let mut res_events = vec![];
if matches!(event_type, CGEventType::TapDisabledByTimeout) {
// The kernel disables the tap when our callback runs
// longer than ~1s on a single event — typical causes
// are heavy load, scheduler contention, or this
// process being briefly suspended (e.g. App Nap on a
// long idle). It is NOT a fatal condition: Apple's
// documented recovery is to call CGEventTapEnable
// and resume processing. Re-enable in place and KEEP
// existing capture state so the user doesn't see the
// cursor pop back to the local screen mid-session.
if let Some(&port) = tap_mach_port_cb.get() {
log::warn!("CGEventTap disabled by timeout — re-enabling");
unsafe {
CGEventTapEnable(port as *mut c_void, true);
}
} else {
log::error!(
"CGEventTap disabled by timeout, but mach port not yet stored — cannot re-enable"
);
}
return CallbackResult::Keep;
}
if matches!(event_type, CGEventType::TapDisabledByUserInput) {
// Deliberate kill — secure-input mode (e.g. password
// field), TCC Accessibility revoked mid-session, or
// the user disabling event-monitoring. We can't
// recover from this; drop captured state synchronously
// and return Keep on this event. Otherwise the
// `current_pos.is_some()` branch below would drop this
// event (and any racing callback still in flight) back
// into `CallbackResult::Drop`, silently eating the
// user's clicks and keypresses while the tap winds
// down. Clear state + show the cursor here, then
// notify the producer loop so the service can tear
// down cleanly.
log::error!("CGEventTap disabled by user input, releasing capture state");
if state.current_pos.is_some() {
let _ = CGDisplay::show_cursor(&CGDisplay::main());
state.current_pos = None;
}
notify_tx
.blocking_send(ProducerEvent::EventTapDisabled)
.unwrap_or_else(|e| {
log::error!("Failed to send notification: {e}");
});
return CallbackResult::Keep;
}
// Are we in a client?
if let Some(current_pos) = state.current_pos {
capture_position = Some(current_pos);
get_events(
&event_type,
cg_ev,
&mut res_events,
&mut state.modifier_state,
)
.unwrap_or_else(|e| {
log::error!("Failed to get events: {e}");
});
// Keep (hidden) cursor at the edge of the screen
if matches!(
event_type,
CGEventType::TapDisabledByTimeout | CGEventType::TapDisabledByUserInput
CGEventType::MouseMoved
| CGEventType::LeftMouseDragged
| CGEventType::RightMouseDragged
| CGEventType::OtherMouseDragged
) {
log::error!("CGEventTap disabled");
state.reset_cursor().unwrap_or_else(|e| log::warn!("{e}"));
}
} else if matches!(event_type, CGEventType::MouseMoved) {
// Did we cross a barrier?
if let Some(new_pos) = state.crossed(cg_ev) {
capture_position = Some(new_pos);
state
.start_capture(cg_ev, new_pos)
.unwrap_or_else(|e| log::warn!("{e}"));
res_events.push(CaptureEvent::Begin);
notify_tx
.blocking_send(ProducerEvent::EventTapDisabled)
.unwrap_or_else(|e| {
log::error!("Failed to send notification: {e}");
});
.blocking_send(ProducerEvent::Grab(new_pos))
.expect("Failed to send notification");
}
}
// Are we in a client?
if let Some(current_pos) = state.current_pos {
capture_position = Some(current_pos);
get_events(
&event_type,
cg_ev,
&mut res_events,
&mut state.modifier_state,
)
.unwrap_or_else(|e| {
log::error!("Failed to get events: {e}");
});
// Keep (hidden) cursor at the edge of the screen
if matches!(
event_type,
CGEventType::MouseMoved
| CGEventType::LeftMouseDragged
| CGEventType::RightMouseDragged
| CGEventType::OtherMouseDragged
) {
state.reset_cursor().unwrap_or_else(|e| log::warn!("{e}"));
}
} else if matches!(event_type, CGEventType::MouseMoved) {
// Did we cross a barrier?
if let Some(new_pos) = state.crossed(cg_ev) {
capture_position = Some(new_pos);
state
.start_capture(cg_ev, new_pos)
.unwrap_or_else(|e| log::warn!("{e}"));
res_events.push(CaptureEvent::Begin);
notify_tx
.blocking_send(ProducerEvent::Grab(new_pos))
.expect("Failed to send notification");
}
}
if let Some(pos) = capture_position {
res_events.iter().for_each(|e| {
// error must be ignored, since the event channel
// may already be closed when the InputCapture instance is dropped.
let _ = event_tx.blocking_send((pos, *e));
});
// Returning Drop should stop the event from being processed
// but core fundation still returns the event
cg_ev.set_type(CGEventType::Null);
CallbackResult::Drop
} else {
CallbackResult::Keep
}
};
if let Some(pos) = capture_position {
res_events.iter().for_each(|e| {
// error must be ignored, since the event channel
// may already be closed when the InputCapture instance is dropped.
let _ = event_tx.blocking_send((pos, *e));
});
// Returning Drop should stop the event from being processed
// but core fundation still returns the event
cg_ev.set_type(CGEventType::Null);
CallbackResult::Drop
} else {
CallbackResult::Keep
}
};
let tap = CGEventTap::new(
CGEventTapLocation::Session,
@@ -482,6 +553,13 @@ fn create_event_tap<'a>(
)
.map_err(|_| MacosCaptureCreationError::EventTapCreation)?;
// Hand the mach port pointer to the callback so it can re-enable
// the tap on TapDisabledByTimeout. The pointer is valid for the
// lifetime of `tap` (which lives on the event-tap thread until
// the run loop exits).
let port_ptr = tap.mach_port().as_concrete_TypeRef() as usize;
let _ = tap_mach_port.set(port_ptr);
let tap_source: CFRunLoopSource = tap
.mach_port()
.create_runloop_source(0)
@@ -501,6 +579,9 @@ fn event_tap_thread(
ready: std::sync::mpsc::Sender<Result<CFRunLoop, MacosCaptureCreationError>>,
exit: oneshot::Sender<()>,
) {
// Clone now: create_event_tap consumes notify_tx into its closure.
let display_notify_tx = notify_tx.clone();
let _tap = match create_event_tap(client_state, notify_tx, event_tx) {
Err(e) => {
ready.send(Err(e)).expect("channel closed");
@@ -512,13 +593,62 @@ fn event_tap_thread(
tap
}
};
// Register a Quartz display-reconfiguration callback so the
// capture state's bounds get refreshed when the user plugs in a
// monitor, changes resolution, or rearranges displays. The
// callback runs on this thread's CFRunLoop. Box-leak the sender
// so the C side has a stable user_info pointer; reclaim it after
// the run loop exits.
let display_user_info = Box::into_raw(Box::new(display_notify_tx)) as *mut c_void;
unsafe {
CGDisplayRegisterReconfigurationCallback(
display_reconfiguration_callback,
display_user_info,
);
}
log::debug!("running CFRunLoop...");
CFRunLoop::run_current();
log::debug!("event tap thread exiting!...");
unsafe {
CGDisplayRemoveReconfigurationCallback(display_reconfiguration_callback, display_user_info);
// Reclaim the leaked sender Box so we don't leak a tokio
// channel sender on every capture create/destroy cycle.
drop(Box::from_raw(
display_user_info as *mut Sender<ProducerEvent>,
));
}
let _ = exit.send(());
}
/// Quartz display-reconfiguration callback. Fires twice per change:
/// once with `kCGDisplayBeginConfigurationFlag` set (BEFORE the
/// change is applied — the bounds are still stale at this point),
/// then again afterwards with the actual change flags (Add, Remove,
/// Mode, DesktopShapeChanged, etc.). Skip the begin phase; on the
/// real notification, kick the producer task to refresh bounds.
extern "C" fn display_reconfiguration_callback(_display: u32, flags: u32, user_info: *mut c_void) {
const K_CG_DISPLAY_BEGIN_CONFIGURATION_FLAG: u32 = 1 << 0;
if flags & K_CG_DISPLAY_BEGIN_CONFIGURATION_FLAG != 0 {
return;
}
if user_info.is_null() {
return;
}
// SAFETY: user_info is a Box::into_raw of Sender<ProducerEvent>
// owned by `event_tap_thread`. It's valid for the lifetime of
// that thread; the registration is removed before the box is
// freed. The callback only fires while the run loop is running
// on that thread, so we know the box is live here.
let sender = unsafe { &*(user_info as *const Sender<ProducerEvent>) };
if let Err(e) = sender.blocking_send(ProducerEvent::DisplayReconfigured) {
log::warn!("failed to notify display reconfiguration: {e}");
}
}
pub struct MacOSInputCapture {
event_rx: Receiver<(Position, CaptureEvent)>,
notify_tx: Sender<ProducerEvent>,
@@ -527,6 +657,8 @@ pub struct MacOSInputCapture {
impl MacOSInputCapture {
pub async fn new() -> Result<Self, MacosCaptureCreationError> {
request_macos_capture_permissions()?;
let state = Arc::new(Mutex::new(InputCaptureState::new()?));
let (event_tx, event_rx) = mpsc::channel(32);
let (notify_tx, mut notify_rx) = mpsc::channel(32);
@@ -580,6 +712,38 @@ impl MacOSInputCapture {
}
}
fn request_macos_capture_permissions() -> Result<(), MacosCaptureCreationError> {
// Call both request functions unconditionally so macOS surfaces both
// TCC prompts on the very first launch. TCC always returns `false` the
// first time a permission is requested (the grant only becomes visible
// on the next process launch), so returning early on the first failure
// would skip the second prompt and force the user through an extra
// relaunch just to see it.
let accessibility = request_accessibility_permission();
let input_monitoring = request_input_monitoring_permission();
if !accessibility {
return Err(MacosCaptureCreationError::AccessibilityPermission);
}
if !input_monitoring {
return Err(MacosCaptureCreationError::InputMonitoringPermission);
}
Ok(())
}
fn request_accessibility_permission() -> bool {
// Silent check. The GUI owns the one-time user-visible prompt at
// startup (see lan_mouse_gtk::macos_privacy) so retries triggered by
// clicking the "Reenable" button don't pop a fresh Accessibility
// alert every time.
unsafe { AXIsProcessTrusted() }
}
fn request_input_monitoring_permission() -> bool {
// Silent check, same reasoning as above.
unsafe { CGPreflightListenEventAccess() }
}
impl Drop for MacOSInputCapture {
fn drop(&mut self) {
self.run_loop.stop();
@@ -651,6 +815,30 @@ extern "C" {
event_source: CGEventSource,
seconds: CFTimeInterval,
);
fn CGPreflightListenEventAccess() -> bool;
/// Re-enable an event tap that was disabled by a
/// `kCGEventTapDisabledByTimeout` event. The Apple-documented
/// recovery path: see Quartz Event Services Reference. The `tap`
/// argument is a `CFMachPortRef`; we pass the raw pointer so we
/// can store it as `usize` for cross-thread sharing.
fn CGEventTapEnable(tap: *mut c_void, enable: bool);
/// Register a callback invoked when the display configuration
/// changes (monitor add/remove, resolution change, mirror,
/// rearrange, etc). See Quartz Display Services Reference.
fn CGDisplayRegisterReconfigurationCallback(
callback: extern "C" fn(u32, u32, *mut c_void),
user_info: *mut c_void,
) -> CGError;
fn CGDisplayRemoveReconfigurationCallback(
callback: extern "C" fn(u32, u32, *mut c_void),
user_info: *mut c_void,
) -> CGError;
}
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
fn AXIsProcessTrusted() -> bool;
}
unsafe fn configure_cf_settings() -> Result<(), MacosCaptureCreationError> {

View File

@@ -40,13 +40,17 @@ wayland-protocols-misc = { version = "0.3.1", features = [
"client",
], optional = true }
x11 = { version = "2.21.0", features = ["xlib", "xtest"], optional = true }
ashpd = { version = "0.11.0", default-features = false, features = [
ashpd = { version = "0.13.9", default-features = false, features = [
"remote_desktop",
"screencast",
"tokio",
], optional = true }
reis = { version = "0.5.0", features = ["tokio"], optional = true }
[target.'cfg(target_os="macos")'.dependencies]
bitflags = "2.6.0"
core-foundation = "0.10.0"
core-foundation-sys = "0.8.6"
core-graphics = { version = "0.25.0", features = ["highsierra"] }
keycode = "1.0.0"

View File

@@ -154,6 +154,10 @@ pub enum X11EmulationCreationError {
pub enum MacOSEmulationCreationError {
#[error("could not create event source")]
EventSourceCreation,
#[error("accessibility permission is required")]
AccessibilityPermission,
#[error("input control permission is required")]
InputControlPermission,
}
#[cfg(windows)]

View File

@@ -13,7 +13,7 @@ use tokio::task::JoinHandle;
use ashpd::desktop::{
PersistMode, Session,
remote_desktop::{DeviceType, RemoteDesktop},
remote_desktop::{DeviceType, RemoteDesktop, SelectDevicesOptions},
};
use async_trait::async_trait;
@@ -40,15 +40,15 @@ struct Devices {
keyboard: Arc<RwLock<Option<(ei::Device, ei::Keyboard)>>>,
}
pub(crate) struct LibeiEmulation<'a> {
pub(crate) struct LibeiEmulation {
context: ei::Context,
conn: event::Connection,
devices: Devices,
ei_task: JoinHandle<()>,
error: Arc<Mutex<Option<EmulationError>>>,
libei_error: Arc<AtomicBool>,
_remote_desktop: RemoteDesktop<'a>,
session: Session<'a, RemoteDesktop<'a>>,
_remote_desktop: RemoteDesktop,
session: Session<RemoteDesktop>,
}
/// Get the path to the RemoteDesktop token file
@@ -84,27 +84,26 @@ fn write_token(token: &str) -> io::Result<()> {
Ok(())
}
async fn get_ei_fd<'a>()
-> Result<(RemoteDesktop<'a>, Session<'a, RemoteDesktop<'a>>, OwnedFd), ashpd::Error> {
async fn get_ei_fd() -> Result<(RemoteDesktop, Session<RemoteDesktop>, OwnedFd), ashpd::Error> {
let remote_desktop = RemoteDesktop::new().await?;
let restore_token = read_token();
log::debug!("creating session ...");
let session = remote_desktop.create_session().await?;
let session = remote_desktop.create_session(Default::default()).await?;
log::debug!("selecting devices ...");
remote_desktop
.select_devices(
&session,
DeviceType::Keyboard | DeviceType::Pointer,
restore_token.as_deref(),
PersistMode::ExplicitlyRevoked,
)
.await?;
let options = SelectDevicesOptions::default()
.set_devices(DeviceType::Keyboard | DeviceType::Pointer)
.set_persist_mode(PersistMode::ExplicitlyRevoked)
.set_restore_token(restore_token.as_deref());
remote_desktop.select_devices(&session, options).await?;
log::info!("requesting permission for input emulation");
let start_response = remote_desktop.start(&session, None).await?.response()?;
let start_response = remote_desktop
.start(&session, None, Default::default())
.await?
.response()?;
// The restore token is only valid once, we need to re-save it each time
if let Some(token_str) = start_response.restore_token() {
@@ -113,11 +112,13 @@ async fn get_ei_fd<'a>()
}
}
let fd = remote_desktop.connect_to_eis(&session).await?;
let fd = remote_desktop
.connect_to_eis(&session, Default::default())
.await?;
Ok((remote_desktop, session, fd))
}
impl LibeiEmulation<'_> {
impl LibeiEmulation {
pub(crate) async fn new() -> Result<Self, LibeiEmulationCreationError> {
let (_remote_desktop, session, eifd) = get_ei_fd().await?;
let stream = UnixStream::from(eifd);
@@ -152,14 +153,14 @@ impl LibeiEmulation<'_> {
}
}
impl Drop for LibeiEmulation<'_> {
impl Drop for LibeiEmulation {
fn drop(&mut self) {
self.ei_task.abort();
}
}
#[async_trait]
impl Emulation for LibeiEmulation<'_> {
impl Emulation for LibeiEmulation {
async fn consume(
&mut self,
event: Event,

View File

@@ -61,6 +61,8 @@ unsafe impl Send for MacOSEmulation {}
impl MacOSEmulation {
pub(crate) fn new() -> Result<Self, MacOSEmulationCreationError> {
request_macos_emulation_permissions()?;
let event_source = CGEventSource::new(CGEventSourceStateID::CombinedSessionState)
.map_err(|_| MacOSEmulationCreationError::EventSourceCreation)?;
Ok(Self {
@@ -119,6 +121,42 @@ impl MacOSEmulation {
}
}
fn request_macos_emulation_permissions() -> Result<(), MacOSEmulationCreationError> {
// Request both permissions up front so the user sees both TCC prompts
// on the first launch. See the matching comment in input-capture/src/
// macos.rs::request_macos_capture_permissions for the rationale.
let accessibility = request_accessibility_permission();
let input_control = request_input_control_permission();
if !accessibility {
return Err(MacOSEmulationCreationError::AccessibilityPermission);
}
if !input_control {
return Err(MacOSEmulationCreationError::InputControlPermission);
}
Ok(())
}
fn request_accessibility_permission() -> bool {
// Silent check. The GUI owns the one-time user-visible prompt at
// startup (see lan_mouse_gtk::macos_privacy).
unsafe { AXIsProcessTrusted() }
}
fn request_input_control_permission() -> bool {
unsafe { CGPreflightPostEventAccess() }
}
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGPreflightPostEventAccess() -> bool;
}
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
fn AXIsProcessTrusted() -> bool;
}
fn key_event(event_source: CGEventSource, key: u16, state: u8, modifiers: XMods) {
let event = match CGEvent::new_keyboard_event(event_source, key, state != 0) {
Ok(e) => e,

View File

@@ -1,7 +1,10 @@
use ashpd::{
desktop::{
PersistMode, Session,
remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop},
remote_desktop::{
Axis, DeviceType, KeyState, NotifyPointerAxisOptions, RemoteDesktop,
SelectDevicesOptions,
},
},
zbus::AsyncDrop,
};
@@ -17,32 +20,31 @@ use crate::error::EmulationError;
use super::{Emulation, EmulationHandle, error::XdpEmulationCreationError};
pub(crate) struct DesktopPortalEmulation<'a> {
proxy: RemoteDesktop<'a>,
session: Session<'a, RemoteDesktop<'a>>,
pub(crate) struct DesktopPortalEmulation {
proxy: RemoteDesktop,
session: Session<RemoteDesktop>,
}
impl<'a> DesktopPortalEmulation<'a> {
pub(crate) async fn new() -> Result<DesktopPortalEmulation<'a>, XdpEmulationCreationError> {
impl DesktopPortalEmulation {
pub(crate) async fn new() -> Result<DesktopPortalEmulation, XdpEmulationCreationError> {
log::debug!("connecting to org.freedesktop.portal.RemoteDesktop portal ...");
let proxy = RemoteDesktop::new().await?;
// retry when user presses the cancel button
log::debug!("creating session ...");
let session = proxy.create_session().await?;
let session = proxy.create_session(Default::default()).await?;
log::debug!("selecting devices ...");
proxy
.select_devices(
&session,
DeviceType::Keyboard | DeviceType::Pointer,
None,
PersistMode::ExplicitlyRevoked,
)
.await?;
let options = SelectDevicesOptions::default()
.set_devices(DeviceType::Keyboard | DeviceType::Pointer)
.set_persist_mode(PersistMode::ExplicitlyRevoked);
proxy.select_devices(&session, options).await?;
log::info!("requesting permission for input emulation");
let _devices = proxy.start(&session, None).await?.response()?;
let _devices = proxy
.start(&session, None, Default::default())
.await?
.response()?;
log::debug!("started session");
let session = session;
@@ -52,7 +54,7 @@ impl<'a> DesktopPortalEmulation<'a> {
}
#[async_trait]
impl Emulation for DesktopPortalEmulation<'_> {
impl Emulation for DesktopPortalEmulation {
async fn consume(
&mut self,
event: input_event::Event,
@@ -62,7 +64,7 @@ impl Emulation for DesktopPortalEmulation<'_> {
Pointer(p) => match p {
PointerEvent::Motion { time: _, dx, dy } => {
self.proxy
.notify_pointer_motion(&self.session, dx, dy)
.notify_pointer_motion(&self.session, dx, dy, Default::default())
.await?;
}
PointerEvent::Button {
@@ -75,7 +77,12 @@ impl Emulation for DesktopPortalEmulation<'_> {
_ => KeyState::Pressed,
};
self.proxy
.notify_pointer_button(&self.session, button as i32, state)
.notify_pointer_button(
&self.session,
button as i32,
state,
Default::default(),
)
.await?;
}
PointerEvent::AxisDiscrete120 { axis, value } => {
@@ -84,7 +91,12 @@ impl Emulation for DesktopPortalEmulation<'_> {
_ => Axis::Horizontal,
};
self.proxy
.notify_pointer_axis_discrete(&self.session, axis, value / 120)
.notify_pointer_axis_discrete(
&self.session,
axis,
value / 120,
Default::default(),
)
.await?;
}
PointerEvent::Axis {
@@ -101,7 +113,12 @@ impl Emulation for DesktopPortalEmulation<'_> {
Axis::Horizontal => (value, 0.),
};
self.proxy
.notify_pointer_axis(&self.session, dx, dy, true)
.notify_pointer_axis(
&self.session,
dx,
dy,
NotifyPointerAxisOptions::default().set_finish(true),
)
.await?;
}
},
@@ -117,7 +134,12 @@ impl Emulation for DesktopPortalEmulation<'_> {
_ => KeyState::Pressed,
};
self.proxy
.notify_keyboard_keycode(&self.session, key as i32, state)
.notify_keyboard_keycode(
&self.session,
key as i32,
state,
Default::default(),
)
.await?;
}
KeyboardEvent::Modifiers { .. } => {
@@ -141,7 +163,7 @@ impl Emulation for DesktopPortalEmulation<'_> {
}
}
impl AsyncDrop for DesktopPortalEmulation<'_> {
impl AsyncDrop for DesktopPortalEmulation {
#[doc = r" Perform the async cleanup."]
#[allow(clippy::type_complexity, clippy::type_repetition_in_bounds)]
fn async_drop<'async_trait>(

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 0 3 c 0 -1.644531 1.355469 -3 3 -3 h 5 c 1.644531 0 3 1.355469 3 3 c 0 0.550781 -0.449219 1 -1 1 s -1 -0.449219 -1 -1 c 0 -0.570312 -0.429688 -1 -1 -1 h -5 c -0.570312 0 -1 0.429688 -1 1 v 5 c 0 0.570312 0.429688 1 1 1 c 0.550781 0 1 0.449219 1 1 s -0.449219 1 -1 1 c -1.644531 0 -3 -1.355469 -3 -3 z m 5 5 c 0 -1.644531 1.355469 -3 3 -3 h 5 c 1.644531 0 3 1.355469 3 3 v 5 c 0 1.644531 -1.355469 3 -3 3 h -5 c -1.644531 0 -3 -1.355469 -3 -3 z m 2 0 v 5 c 0 0.570312 0.429688 1 1 1 h 5 c 0.570312 0 1 -0.429688 1 -1 v -5 c 0 -0.570312 -0.429688 -1 -1 -1 h -5 c -0.570312 0 -1 0.429688 -1 1 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 765 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 8 0 c -4.410156 0 -8 3.589844 -8 8 s 3.589844 8 8 8 s 8 -3.589844 8 -8 s -3.589844 -8 -8 -8 z m 0 2 c 3.332031 0 6 2.667969 6 6 s -2.667969 6 -6 6 s -6 -2.667969 -6 -6 s 2.667969 -6 6 -6 z m -2.03125 2.96875 c -0.265625 0 -0.519531 0.105469 -0.707031 0.292969 c -0.390625 0.390625 -0.390625 1.023437 0 1.414062 l 1.292969 1.292969 l -1.292969 1.292969 c -0.390625 0.390625 -0.390625 1.023437 0 1.414062 s 1.023437 0.390625 1.414062 0 l 1.292969 -1.292969 l 1.292969 1.292969 c 0.390625 0.390625 1.023437 0.390625 1.414062 0 s 0.390625 -1.023437 0 -1.414062 l -1.292969 -1.292969 l 1.292969 -1.292969 c 0.390625 -0.390625 0.390625 -1.023437 0 -1.414062 c -0.1875 -0.1875 -0.441406 -0.292969 -0.707031 -0.292969 s -0.519531 0.105469 -0.707031 0.292969 l -1.292969 1.292969 l -1.292969 -1.292969 c -0.1875 -0.1875 -0.441406 -0.292969 -0.707031 -0.292969 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 13.753906 4.660156 c 0.175782 -0.199218 0.261719 -0.460937 0.246094 -0.726562 c -0.019531 -0.265625 -0.140625 -0.511719 -0.339844 -0.6875 c -0.199218 -0.175782 -0.460937 -0.261719 -0.726562 -0.246094 c -0.265625 0.019531 -0.511719 0.140625 -0.6875 0.339844 l -6.296875 7.195312 l -2.242188 -2.242187 c -0.390625 -0.390625 -1.023437 -0.390625 -1.414062 0 c -0.1875 0.1875 -0.292969 0.441406 -0.292969 0.707031 s 0.105469 0.519531 0.292969 0.707031 l 3 3 c 0.195312 0.195313 0.464843 0.304688 0.738281 0.292969 c 0.277344 -0.007812 0.539062 -0.132812 0.722656 -0.339844 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 743 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 7 1 v 6 h -6 v 2 h 6 v 6 h 2 v -6 h 6 v -2 h -6 v -6 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 228 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 7.085938 2 c 0.574218 0.007812 1.152343 0.085938 1.726562 0.238281 c 3.054688 0.820313 5.1875 3.597657 5.1875 6.761719 h 2 v 1 h -0.007812 c 0.003906 0.265625 -0.101563 0.519531 -0.285157 0.707031 l -2 2 c -0.390625 0.390625 -1.023437 0.390625 -1.414062 0 l -2 -2 c -0.1875 -0.1875 -0.289063 -0.441406 -0.289063 -0.707031 h -0.003906 v -1 h 2 c 0 -2.269531 -1.515625 -4.242188 -3.707031 -4.832031 c -2.1875 -0.585938 -4.488281 0.367187 -5.625 2.332031 c -1.132813 1.964844 -0.808594 4.429688 0.796875 6.035156 c 0.390625 0.390625 0.390625 1.023438 0 1.414063 s -1.023438 0.390625 -1.414063 0 c -2.238281 -2.238281 -2.695312 -5.710938 -1.113281 -8.449219 c 1.1875 -2.054688 3.304688 -3.324219 5.578125 -3.480469 c 0.1875 -0.015625 0.378906 -0.023437 0.570313 -0.019531 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 943 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 13.753906 4.660156 c 0.175782 -0.199218 0.261719 -0.460937 0.246094 -0.726562 c -0.019531 -0.265625 -0.140625 -0.511719 -0.339844 -0.6875 c -0.199218 -0.175782 -0.460937 -0.261719 -0.726562 -0.246094 c -0.265625 0.019531 -0.511719 0.140625 -0.6875 0.339844 l -6.296875 7.195312 l -2.242188 -2.242187 c -0.390625 -0.390625 -1.023437 -0.390625 -1.414062 0 c -0.1875 0.1875 -0.292969 0.441406 -0.292969 0.707031 s 0.105469 0.519531 0.292969 0.707031 l 3 3 c 0.195312 0.195313 0.464843 0.304688 0.738281 0.292969 c 0.277344 -0.007812 0.539062 -0.132812 0.722656 -0.339844 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 743 B

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<g fill="#2e3436">
<path d="m 1 2 h 14 v 2 h -14 z m 0 0"/>
<path d="m 1 7 h 14 v 2 h -14 z m 0 0"/>
<path d="m 1 12 h 14 v 2 h -14 z m 0 0"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 314 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 3 2 c -0.265625 0 -0.519531 0.105469 -0.707031 0.292969 c -0.390625 0.390625 -0.390625 1.023437 0 1.414062 l 4.292969 4.292969 l -4.292969 4.292969 c -0.390625 0.390625 -0.390625 1.023437 0 1.414062 s 1.023437 0.390625 1.414062 0 l 4.292969 -4.292969 l 4.292969 4.292969 c 0.390625 0.390625 1.023437 0.390625 1.414062 0 s 0.390625 -1.023437 0 -1.414062 l -4.292969 -4.292969 l 4.292969 -4.292969 c 0.390625 -0.390625 0.390625 -1.023437 0 -1.414062 c -0.1875 -0.1875 -0.441406 -0.292969 -0.707031 -0.292969 s -0.519531 0.105469 -0.707031 0.292969 l -4.292969 4.292969 l -4.292969 -4.292969 c -0.1875 -0.1875 -0.441406 -0.292969 -0.707031 -0.292969 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 822 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 8.074219 0 c -1.203125 -0.0117188 -2.40625 0.285156 -3.492188 0.890625 c -0.480469 0.269531 -0.652343 0.878906 -0.382812 1.359375 c 0.269531 0.484375 0.878906 0.65625 1.359375 0.386719 c 1.550781 -0.867188 3.4375 -0.847657 4.972656 0.050781 c 1.53125 0.898438 2.46875 2.535156 2.46875 4.3125 v 1 c 0 0.550781 0.449219 1 1 1 s 1 -0.449219 1 -1 v -1 c 0 -0.019531 0 -0.039062 -0.003906 -0.054688 c -0.019532 -2.460937 -1.332032 -4.738281 -3.457032 -5.984374 c -1.070312 -0.628907 -2.265624 -0.9492192 -3.46875 -0.960938 z m -5.199219 2.832031 c -0.066406 0 -0.132812 0.007813 -0.195312 0.023438 c -0.257813 0.058593 -0.484376 0.21875 -0.625 0.445312 c -0.6875 1.109375 -1.054688 2.390625 -1.054688 3.699219 v 5.0625 c 0 0.550781 0.449219 1 1 1 s 1 -0.449219 1 -1 v -5.0625 c 0 -0.933594 0.261719 -1.851562 0.753906 -2.644531 c 0.292969 -0.46875 0.148438 -1.082031 -0.320312 -1.375 c -0.167969 -0.105469 -0.363282 -0.15625 -0.558594 -0.148438 z m 5.125 0.167969 c -2.199219 0 -4 1.800781 -4 4 v 1 c 0 0.550781 0.449219 1 1 1 s 1 -0.449219 1 -1 v -1 c 0 -1.117188 0.882812 -2 2 -2 s 2 0.882812 2 2 v 5 s 0.007812 0.441406 0.175781 0.941406 s 0.5 1.148438 1.117188 1.765625 c 0.390625 0.390625 1.023437 0.390625 1.414062 0 s 0.390625 -1.023437 0 -1.414062 c -0.382812 -0.382813 -0.550781 -0.734375 -0.632812 -0.984375 s -0.074219 -0.308594 -0.074219 -0.308594 v -5 c 0 -2.199219 -1.800781 -4 -4 -4 z m 0 3 c -0.550781 0 -1 0.449219 -1 1 v 5 s 0 0.59375 0.144531 1.320312 c 0.144531 0.726563 0.414063 1.652344 1.148438 2.386719 c 0.390625 0.390625 1.023437 0.390625 1.414062 0 s 0.390625 -1.023437 0 -1.414062 c -0.265625 -0.265625 -0.496093 -0.839844 -0.601562 -1.363281 c -0.105469 -0.523438 -0.105469 -0.929688 -0.105469 -0.929688 v -5 c 0 -0.550781 -0.449219 -1 -1 -1 z m -3 4 c -0.550781 0 -1 0.449219 -1 1 v 3 c 0 0.550781 0.449219 1 1 1 s 1 -0.449219 1 -1 v -3 c 0 -0.550781 -0.449219 -1 -1 -1 z m 9 0 c -0.550781 0 -1 0.449219 -1 1 s 0.449219 1 1 1 s 1 -0.449219 1 -1 s -0.449219 -1 -1 -1 z m 0 0" fill="#2e3434"/>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 6 0.015625 c -0.554688 0 -1 0.445313 -1 1 v 3 c 0 0.554687 0.445312 1 1 1 h 1 v 2 h -7 v 2 h 2 v 2 h -1 c -0.554688 0 -1 0.445313 -1 1 v 3 c 0 0.554687 0.445312 1 1 1 h 4 c 0.554688 0 1 -0.445313 1 -1 v -3 c 0 -0.554687 -0.445312 -1 -1 -1 h -1 v -2 h 8 v 2 h -1 c -0.554688 0 -1 0.445313 -1 1 v 3 c 0 0.554687 0.445312 1 1 1 h 4 c 0.554688 0 1 -0.445313 1 -1 v -3 c 0 -0.554687 -0.445312 -1 -1 -1 h -1 v -2 h 2 v -2 h -7 v -2 h 1 c 0.554688 0 1 -0.445313 1 -1 v -3 c 0 -0.554687 -0.445312 -1 -1 -1 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 673 B

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<g fill="#2e3436">
<path d="m 6.5 0 c -1.378906 0 -2.5 1.121094 -2.5 2.5 v 0.5 h -3 c -0.550781 0 -1 0.449219 -1 1 s 0.449219 1 1 1 h 1 v 8 c 0 1.65625 1.34375 3 3 3 h 6 c 1.65625 0 3 -1.34375 3 -3 v -8 h 1 c 0.550781 0 1 -0.449219 1 -1 s -0.449219 -1 -1 -1 h -3.023438 v -0.5 c 0 -1.378906 -1.117187 -2.5 -2.5 -2.5 z m 0 2 h 2.976562 c 0.289063 0 0.5 0.210938 0.5 0.5 v 0.5 h -3.976562 v -0.5 c 0 -0.289062 0.210938 -0.5 0.5 -0.5 z m -2.5 3 h 8 v 8 c 0 0.5625 -0.4375 1 -1 1 h -6 c -0.5625 0 -1 -0.4375 -1 -1 z m 0 0"/>
<path d="m 7 7 v 5 c 0 0.277344 -0.222656 0.5 -0.5 0.5 s -0.5 -0.222656 -0.5 -0.5 v -5 c 0 -0.277344 0.222656 -0.5 0.5 -0.5 s 0.5 0.222656 0.5 0.5 z m 0 0"/>
<path d="m 10 7 v 5 c 0 0.277344 -0.222656 0.5 -0.5 0.5 s -0.5 -0.222656 -0.5 -0.5 v -5 c 0 -0.277344 0.222656 -0.5 0.5 -0.5 s 0.5 0.222656 0.5 0.5 z m 0 0"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1009 B

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 7.90625 0.09375 c -0.527344 -0.0273438 -1.039062 0.28125 -1.4375 0.96875 l -6.25 11.59375 c -0.535156 0.964844 0.046875 2.34375 1.09375 2.34375 h 13.15625 c 0.980469 0 1.902344 -1.160156 1.21875 -2.34375 l -6.3125 -11.53125 c -0.398438 -0.644531 -0.941406 -1.003906 -1.46875 -1.03125 z m 1.09375 3.90625 v 5 c 0.007812 0.527344 -0.472656 1 -1 1 s -1.007812 -0.472656 -1 -1 v -5 z m -1 7 c 0.550781 0 1 0.449219 1 1 s -0.449219 1 -1 1 s -1 -0.449219 -1 -1 s 0.449219 -1 1 -1 z m 0 0" fill="#2e3436"/>
</svg>

After

Width:  |  Height:  |  Size: 649 B

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<g fill="#2e3436">
<path d="m 15 10 c 0.265625 0 0.519531 0.105469 0.707031 0.292969 c 0.390625 0.390625 0.390625 1.023437 0 1.414062 l -1.292969 1.292969 l 1.292969 1.292969 c 0.390625 0.390625 0.390625 1.023437 0 1.414062 s -1.023437 0.390625 -1.414062 0 l -1.292969 -1.292969 l -1.292969 1.292969 c -0.390625 0.390625 -1.023437 0.390625 -1.414062 0 s -0.390625 -1.023437 0 -1.414062 l 1.292969 -1.292969 l -1.292969 -1.292969 c -0.390625 -0.390625 -0.390625 -1.023437 0 -1.414062 c 0.1875 -0.1875 0.441406 -0.292969 0.707031 -0.292969 s 0.519531 0.105469 0.707031 0.292969 l 1.292969 1.292969 l 1.292969 -1.292969 c 0.1875 -0.1875 0.441406 -0.292969 0.707031 -0.292969 z m 0 0"/>
<path d="m 6 0 c -0.554688 0 -1 0.445312 -1 1 v 3 c 0 0.554688 0.445312 1 1 1 h 1 v 2 h -7 v 2 h 2 v 2 h -1 c -0.554688 0 -1 0.445312 -1 1 v 3 c 0 0.554688 0.445312 1 1 1 h 4 c 0.554688 0 1 -0.445312 1 -1 v -3 c 0 -0.554688 -0.445312 -1 -1 -1 h -1 v -2 h 12 v -2 h -7 v -2 h 1 c 0.554688 0 1 -0.445312 1 -1 v -3 c 0 -0.554688 -0.445312 -1 -1 -1 z m 0 0" fill-opacity="0.34902"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -9,5 +9,23 @@
</gresource>
<gresource prefix="/de/feschber/LanMouse/icons">
<file compressed="true" preprocess="xml-stripblanks">de.feschber.LanMouse.svg</file>
<!--
Bundled Adwaita symbolic icons so the GTK frontend has a complete icon set
on platforms (notably macOS) where the Adwaita icon theme is not installed.
Registered via IconTheme::add_resource_path("/de/feschber/LanMouse/icons").
-->
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/edit-copy-symbolic.svg">icons/scalable/actions/edit-copy-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/edit-delete-symbolic.svg">icons/scalable/actions/edit-delete-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/emblem-ok-symbolic.svg">icons/scalable/actions/emblem-ok-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/list-add-symbolic.svg">icons/scalable/actions/list-add-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/object-rotate-right-symbolic.svg">icons/scalable/actions/object-rotate-right-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/object-select-symbolic.svg">icons/scalable/actions/object-select-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/open-menu-symbolic.svg">icons/scalable/actions/open-menu-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/actions/process-stop-symbolic.svg">icons/scalable/actions/process-stop-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/devices/auth-fingerprint-symbolic.svg">icons/scalable/devices/auth-fingerprint-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/devices/network-wired-symbolic.svg">icons/scalable/devices/network-wired-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/places/user-trash-symbolic.svg">icons/scalable/places/user-trash-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/status/dialog-warning-symbolic.svg">icons/scalable/status/dialog-warning-symbolic.svg</file>
<file compressed="true" preprocess="xml-stripblanks" alias="scalable/status/network-wired-disconnected-symbolic.svg">icons/scalable/status/network-wired-disconnected-symbolic.svg</file>
</gresource>
</gresources>

View File

@@ -63,7 +63,7 @@
<signal name="clicked" handler="handle_capture" swapped="true"/>
<property name="valign">center</property>
<style>
<class name="circular"/>
<class name="pill"/>
<class name="flat"/>
</style>
</object>
@@ -89,7 +89,7 @@
<property name="valign">center</property>
<signal name="clicked" handler="handle_emulation" swapped="true"/>
<style>
<class name="circular"/>
<class name="pill"/>
<class name="flat"/>
</style>
</object>

View File

@@ -4,6 +4,10 @@ mod client_row;
mod fingerprint_window;
mod key_object;
mod key_row;
#[cfg(target_os = "macos")]
mod macos_privacy;
#[cfg(target_os = "macos")]
mod macos_status_item;
mod window;
use std::{env, process, str};
@@ -47,6 +51,12 @@ pub fn run() -> Result<(), GtkError> {
}
fn gtk_main() -> glib::ExitCode {
#[cfg(target_os = "macos")]
{
configure_macos_bundle_environment();
install_macos_gtk_log_filter();
}
gio::resources_register_include!("lan-mouse.gresource").expect("Failed to register resources.");
let app = Application::builder()
@@ -64,6 +74,64 @@ fn gtk_main() -> glib::ExitCode {
app.run_with_args(&args)
}
#[cfg(target_os = "macos")]
fn install_macos_gtk_log_filter() {
glib::log_set_writer_func(|level, fields| {
if level == glib::LogLevel::Warning && is_gtk_theme_parser_warning(fields) {
return glib::LogWriterOutput::Handled;
}
glib::log_writer_default(level, fields)
});
}
#[cfg(target_os = "macos")]
fn is_gtk_theme_parser_warning(fields: &[glib::LogField<'_>]) -> bool {
let mut domain = None;
let mut message = None;
for field in fields {
match field.key() {
"GLIB_DOMAIN" => domain = field.value_str(),
"MESSAGE" => message = field.value_str(),
_ => {}
}
}
domain == Some("Gtk")
&& message.is_some_and(|message| message.starts_with("Theme parser warning: gtk.css:"))
}
#[cfg(target_os = "macos")]
fn configure_macos_bundle_environment() {
let Ok(exe) = env::current_exe() else {
return;
};
let Some(contents) = exe
.parent()
.and_then(|dir| dir.parent())
.map(std::path::Path::to_owned)
else {
return;
};
let share = contents.join("Resources").join("share");
if !share.exists() {
return;
}
let schemas = share.join("glib-2.0").join("schemas");
if schemas.exists() {
env::set_var("GSETTINGS_SCHEMA_DIR", schemas);
}
env::set_var("XDG_DATA_DIRS", &share);
env::set_var(
"GTK_DATA_PREFIX",
contents.join("Resources").to_string_lossy().as_ref(),
);
}
fn load_icons() {
let display = &Display::default().expect("Could not connect to a display.");
let icon_theme = IconTheme::for_display(display);
@@ -123,6 +191,41 @@ fn build_ui(app: &Application) {
});
let window = Window::new(app, frontend_tx);
#[cfg(target_os = "macos")]
{
window.connect_close_request(|window| {
window.set_visible(false);
glib::Propagation::Stop
});
macos_status_item::setup(app, &window);
// First-launch TCC prompts. No-op when already granted.
macos_privacy::fire_initial_prompts();
// Watch the Accessibility grant continuously for the lifetime
// of the process. On a grant, swap the warning row into its
// "relaunch required" state (the daemon subprocess already
// bailed and can't recover without a restart). On a REVOKE,
// quit immediately — an active CGEventTap at
// HeadInsertEventTap can wedge system input if the process
// lingers after losing AX, and forcing the process to exit is
// the only bulletproof way to guarantee the kernel tears the
// tap down.
let window_weak = window.downgrade();
let app_weak = app.downgrade();
macos_privacy::watch_accessibility_state(move |change| match change {
macos_privacy::AccessibilityChange::Granted => {
if let Some(window) = window_weak.upgrade() {
window.present();
window.refresh_capture_emulation_status();
}
}
macos_privacy::AccessibilityChange::Revoked => {
log::warn!("Accessibility revoked — quitting to avoid wedging system input");
if let Some(app) = app_weak.upgrade() {
app.quit();
}
}
});
}
glib::spawn_future_local(clone!(
#[weak]
@@ -171,5 +274,18 @@ fn build_ui(app: &Application) {
}
));
#[cfg(not(target_os = "macos"))]
window.present();
// On macOS, default to presenting the main window on every launch
// so the user gets a visible confirmation that the app is running
// — including the post-grant relaunch and normal Dock/Finder/`open`
// launches. Opt out by setting `LAN_MOUSE_HIDDEN=1` in the
// environment (useful for a LaunchAgent / login-item configuration
// where the user wants the app to come up quietly into the menu
// bar only, with no window on boot).
#[cfg(target_os = "macos")]
if env::var_os("LAN_MOUSE_HIDDEN").is_none() {
window.present();
}
}

View File

@@ -0,0 +1,256 @@
//! Tiny macOS Privacy-pane helpers used by the GUI.
//!
//! On macOS 13+, the Accessibility grant transitively confers the
//! listen-only event-tap privilege that Input Monitoring gates and the
//! synthesize-event privilege that Post Event gates, and the bundle
//! typically isn't even listed in those separate panes. So the single
//! user-facing action for any missing-capture or missing-emulation
//! scenario is "re-toggle Accessibility" — we don't route elsewhere.
use std::ffi::{c_uchar, c_void};
use std::process::Command;
use std::sync::Once;
use gtk::glib;
// Apple declares `AXIsProcessTrusted` as returning `Boolean` (`unsigned char`),
// NOT C's `bool`. Rust's `bool` has a strict bit pattern (0 or 1) so binding
// a `Boolean`-returning function as `-> bool` is technically UB if Apple ever
// returns a non-canonical true value. Keep these as `c_uchar` and normalize.
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
fn AXIsProcessTrusted() -> c_uchar;
fn AXIsProcessTrustedWithOptions(options: *const c_void) -> c_uchar;
}
#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
static kCFAllocatorDefault: *const c_void;
static kCFTypeDictionaryKeyCallBacks: *const c_void;
static kCFTypeDictionaryValueCallBacks: *const c_void;
static kCFBooleanTrue: *const c_void;
fn CFDictionaryCreate(
allocator: *const c_void,
keys: *const *const c_void,
values: *const *const c_void,
num: isize,
key_callbacks: *const c_void,
value_callbacks: *const c_void,
) -> *const c_void;
fn CFRelease(cf: *const c_void);
}
// kAXTrustedCheckOptionPrompt is a CFStringRef exported from ApplicationServices.
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
static kAXTrustedCheckOptionPrompt: *const c_void;
}
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGRequestListenEventAccess() -> c_uchar;
fn CGRequestPostEventAccess() -> c_uchar;
// CFMachPortRef CGEventTapCreate(
// CGEventTapLocation tap, CGEventTapPlacement place,
// CGEventTapOptions options, CGEventMask eventsOfInterest,
// CGEventTapCallBack callback, void *userInfo);
fn CGEventTapCreate(
tap: u32,
place: u32,
options: u32,
events_of_interest: u64,
callback: *const c_void,
user_info: *const c_void,
) -> *const c_void;
}
pub fn accessibility_granted() -> bool {
let raw = unsafe { AXIsProcessTrusted() };
log::debug!("AXIsProcessTrusted() = {raw}");
raw != 0
}
pub enum AccessibilityChange {
/// AX was missing at startup and the user has now granted it.
/// Capture/emulation still need a relaunch to take effect, since
/// the daemon subprocess already bailed.
Granted,
/// AX was granted and the user has now revoked it. Quit immediately
/// — leaving the process alive with an active CGEventTap at
/// HeadInsertEventTap can wedge system input (clicks/keys silently
/// consumed) until the process dies. See
/// macos-cgeventtap-drop-fallthrough-tcc-revoke skill for the
/// underlying event-tap-disable footgun.
Revoked,
}
/// Poll for Accessibility grant/revoke transitions. Starts a 1-second
/// GLib timer that fires `on_change` every time `AXIsProcessTrusted()`
/// flips, and keeps running for the lifetime of the process.
///
/// We rely on polling rather than AXObserver because the AX notification
/// API requires a trusted process to subscribe — the precondition we
/// can't assume. This runs on the GTK main thread (via
/// `timeout_add_seconds_local`).
pub fn watch_accessibility_state<F>(mut on_change: F)
where
F: FnMut(AccessibilityChange) + 'static,
{
let mut last = accessibility_granted();
log::info!("watching Accessibility state (initial = {last})");
glib::timeout_add_seconds_local(1, move || {
let current = accessibility_granted();
if current != last {
log::info!("Accessibility state flip: {last} -> {current}");
on_change(if current {
AccessibilityChange::Granted
} else {
AccessibilityChange::Revoked
});
last = current;
}
glib::ControlFlow::Continue
});
}
pub fn open_accessibility_settings() {
open_url("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility");
}
/// Spawn a fresh instance of the current `.app` bundle via Launch Services
/// after a 1-second delay, so the new instance starts *after* the current
/// process has exited — otherwise Launch Services reactivates the existing
/// process instead of launching a fresh one, and the stale IPC socket
/// would block the new daemon subprocess. The caller is responsible for
/// quitting the current process (e.g. `Application::quit()`) after this.
pub fn relaunch_bundle() {
// Resolve the .app bundle path from the current executable: it lives
// at <bundle>/Contents/MacOS/lan-mouse, so three parents up is the
// bundle root we hand to `open`.
let Ok(exe) = std::env::current_exe() else {
return;
};
let Some(bundle) = exe
.parent()
.and_then(std::path::Path::parent)
.and_then(std::path::Path::parent)
else {
return;
};
// Trailing `&` backgrounds the sleep+open so our shell call returns
// immediately; the spawned shell is adopted by launchd once we exit.
let cmd = format!("(sleep 1 && open {bundle:?}) &");
let _ = Command::new("sh").arg("-c").arg(cmd).spawn();
}
/// Make sure the app appears in System Settings → Privacy → Input Monitoring.
///
/// `CGRequestListenEventAccess()` is *supposed* to register the app in the
/// list (and prompt) on first call, but in practice — particularly after a
/// `tccutil reset ListenEvent <bundle>` — it often silently no-ops and the
/// app never gets added. The reliable way to force registration is to
/// attempt a protected action: create a `CGEventTap`. If permission is
/// missing the call returns null, but the attempt itself causes TCC to add
/// the bundle to the Input Monitoring pane so the user can toggle it on.
/// If permission already exists the tap is created successfully, and we
/// tear it down immediately so it doesn't intercept events.
unsafe fn ensure_listed_in_input_monitoring() {
let req = CGRequestListenEventAccess();
log::debug!("CGRequestListenEventAccess() = {req}");
let cb = input_monitoring_noop_tap_callback as *const c_void;
// Use kCGSessionEventTap (1), NOT kCGHIDEventTap (0). The HID tap sits
// below window-server input and requires Accessibility in addition to
// Input Monitoring, so attempting it when Accessibility isn't granted
// surfaces an Accessibility prompt as a side effect — which is confusing
// on top of the real Accessibility prompt we already fire explicitly.
// The session tap requires only Input Monitoring, so its failure is a
// clean "Input Monitoring missing" signal that TCC uses to list the
// bundle under the Input Monitoring pane.
// kCGHeadInsertEventTap = 0, kCGEventTapOptionListenOnly = 1,
// mask kCGEventKeyDown = 1 << 10.
let tap = CGEventTapCreate(1, 0, 1, 1 << 10, cb, std::ptr::null());
log::debug!("CGEventTapCreate(kCGSessionEventTap) -> {tap:?}");
if !tap.is_null() {
CFRelease(tap);
}
}
extern "C" fn input_monitoring_noop_tap_callback(
_proxy: *const c_void,
_ty: u32,
event: *const c_void,
_refcon: *const c_void,
) -> *const c_void {
// Pass through unchanged. This tap is never added to a run loop, so
// in practice the callback never fires — it exists only so the tap
// can be created (and the attempt is what forces TCC registration).
event
}
fn open_url(url: &str) {
if let Err(e) = Command::new("open").arg(url).spawn() {
log::warn!("failed to open {url}: {e}");
}
}
/// One-shot, at GUI startup: if a permission is missing, fire the system
/// prompt. This is where the familiar first-launch "Lan Mouse.app would
/// like to control this computer" alert comes from. Subsequent clicks on
/// the Reenable button use URL-scheme navigation instead, so we never
/// double up alerts on retries.
///
/// Guarded with a `Once` because GApplication::activate can fire more
/// than once in a process (reactivation, window presentation) and we
/// must not re-pop the TCC alert on each activation — that looks like a
/// bug to the user.
pub fn fire_initial_prompts() {
static FIRED: Once = Once::new();
FIRED.call_once(fire_initial_prompts_inner);
}
fn fire_initial_prompts_inner() {
if !accessibility_granted() {
// When Accessibility isn't granted yet, ONLY fire the Accessibility
// prompt. Do NOT also try to register Input Monitoring or Post Event
// — those paths have been observed to surface a second Accessibility
// dialog on top of the one we fire explicitly (Post Event is part of
// the Accessibility category on modern macOS, and CGEventTap attempts
// can bail on Accessibility before they reach the Input Monitoring
// check). Once the user grants Accessibility and relaunches, this
// branch is skipped and we register the other grants cleanly below.
log::info!("firing first-launch Accessibility prompt");
unsafe {
let key = kAXTrustedCheckOptionPrompt;
let value = kCFBooleanTrue;
let options = CFDictionaryCreate(
kCFAllocatorDefault,
&key as *const _,
&value as *const _,
1,
kCFTypeDictionaryKeyCallBacks,
kCFTypeDictionaryValueCallBacks,
);
AXIsProcessTrustedWithOptions(options);
CFRelease(options);
}
return;
}
// Accessibility is granted. Attempt Input Monitoring registration
// unconditionally — even if preflight returns true — so the bundle gets
// listed in System Settings under its own identity (otherwise launches
// from a parent process that already has Input Monitoring, e.g. Terminal,
// inherit the grant but the bundle is never listed for the user to
// toggle persistently).
log::info!("ensuring Lan Mouse is listed under Input Monitoring");
unsafe {
ensure_listed_in_input_monitoring();
}
// Same for Post Event: now that Accessibility is present, this call is
// safe — it won't surface the generic Accessibility prompt.
log::info!("ensuring Lan Mouse is listed under Accessibility > Post Event");
unsafe {
CGRequestPostEventAccess();
}
}

View File

@@ -0,0 +1,346 @@
#![allow(clashing_extern_declarations)]
use std::{
cell::RefCell,
ffi::{CStr, CString, c_char, c_double, c_uint, c_void},
sync::OnceLock,
};
use adw::prelude::*;
use gtk::{gio, glib};
use crate::window::Window;
type Id = *mut c_void;
type Class = *mut c_void;
type Sel = *mut c_void;
type Bool = i8;
struct StatusItem {
app: glib::WeakRef<adw::Application>,
window: glib::WeakRef<Window>,
_hold: gio::ApplicationHoldGuard,
_delegate: Id,
_status_item: Id,
}
thread_local! {
static STATUS_ITEM: RefCell<Option<StatusItem>> = const { RefCell::new(None) };
}
pub fn setup(app: &adw::Application, window: &Window) {
log::debug!("macos_status_item::setup entered");
STATUS_ITEM.with(|item| {
let already_initialized = item.borrow().is_some();
if already_initialized {
let mut cell = item.borrow_mut();
if let Some(existing) = cell.as_mut() {
existing.app.set(Some(app));
existing.window.set(Some(window));
}
return;
}
unsafe {
let hold = app.hold();
let ns_app = msg_send_id(class(c"NSApplication"), sel(c"sharedApplication"));
assert!(
!ns_app.is_null(),
"NSApplication sharedApplication returned null"
);
msg_send_bool_usize(ns_app, sel(c"setActivationPolicy:"), 1);
let delegate = new_delegate();
let menu = menu(&[
menu_item(c"Open Lan Mouse", c"showLanMouse:"),
separator_item(),
menu_item(c"Quit Lan Mouse", c"quitLanMouse:"),
]);
let status_bar = msg_send_id(class(c"NSStatusBar"), sel(c"systemStatusBar"));
assert!(
!status_bar.is_null(),
"NSStatusBar systemStatusBar returned null"
);
let status_item = msg_send_id_f64(status_bar, sel(c"statusItemWithLength:"), -1.0);
assert!(!status_item.is_null(), "statusItemWithLength returned null");
// Retain so the status item survives autorelease pool drain.
let status_item = msg_send_id(status_item, sel(c"retain"));
let button = msg_send_id(status_item, sel(c"button"));
assert!(!button.is_null(), "NSStatusItem.button was null");
set_button_image(button);
msg_send_void_id(button, sel(c"setToolTip:"), nsstring(c"Lan Mouse"));
msg_send_void_id(status_item, sel(c"setMenu:"), menu);
for item in menu_items(menu) {
msg_send_void_id(item, sel(c"setTarget:"), delegate);
}
install_reopen_handler(delegate);
log::debug!("macos_status_item ready at {status_item:p}");
item.replace(Some(StatusItem {
app: app.downgrade(),
window: window.downgrade(),
_hold: hold,
_delegate: delegate,
_status_item: status_item,
}));
}
});
}
// Prefer a pre-rendered template PNG (black silhouette with alpha) so macOS
// auto-tints the glyph to match the menu bar in light and dark modes.
// Falls back to the full-color icns, then to "LM" text.
unsafe fn set_button_image(button: Id) {
if let Some(image) = load_menubar_template() {
msg_send_void_bool(image, sel(c"setTemplate:"), 1);
msg_send_void_id(button, sel(c"setImage:"), image);
return;
}
if let Some(image) = load_app_icon() {
msg_send_void_id(button, sel(c"setImage:"), image);
return;
}
log::warn!("no menu bar image available; falling back to text title");
msg_send_void_id(button, sel(c"setTitle:"), nsstring(c"LM"));
}
unsafe fn load_menubar_template() -> Option<Id> {
load_resource_image(c"menubar-template", c"png", MENUBAR_ICON_SIZE)
}
unsafe fn load_app_icon() -> Option<Id> {
load_resource_image(c"icon", c"icns", MENUBAR_ICON_SIZE)
}
unsafe fn load_resource_image(name: &CStr, ext: &CStr, size_pt: c_double) -> Option<Id> {
let bundle = msg_send_id(class(c"NSBundle"), sel(c"mainBundle"));
if bundle.is_null() {
return None;
}
let path = msg_send_id_id_id(
bundle,
sel(c"pathForResource:ofType:"),
nsstring(name),
nsstring(ext),
);
if path.is_null() {
return None;
}
let image = msg_send_id_id(
msg_send_id(class(c"NSImage"), sel(c"alloc")),
sel(c"initWithContentsOfFile:"),
path,
);
if image.is_null() {
return None;
}
// Render at menu bar height; 22pt is the full status bar icon height.
msg_send_void_size(image, sel(c"setSize:"), size_pt, size_pt);
Some(image)
}
const MENUBAR_ICON_SIZE: c_double = 22.0;
unsafe fn menu(items: &[Id]) -> Id {
let menu = msg_send_id(msg_send_id(class(c"NSMenu"), sel(c"alloc")), sel(c"init"));
for item in items {
msg_send_void_id(menu, sel(c"addItem:"), *item);
}
menu
}
unsafe fn menu_item(title: &CStr, action: &CStr) -> Id {
msg_send_id_id_sel_id(
msg_send_id(class(c"NSMenuItem"), sel(c"alloc")),
sel(c"initWithTitle:action:keyEquivalent:"),
nsstring(title),
sel(action),
nsstring(c""),
)
}
unsafe fn separator_item() -> Id {
msg_send_id(class(c"NSMenuItem"), sel(c"separatorItem"))
}
unsafe fn menu_items(menu: Id) -> Vec<Id> {
let count = msg_send_usize(menu, sel(c"numberOfItems"));
(0..count)
.map(|idx| msg_send_id_usize(menu, sel(c"itemAtIndex:"), idx))
.collect()
}
unsafe fn new_delegate() -> Id {
let class = delegate_class();
msg_send_id(msg_send_id(class, sel(c"alloc")), sel(c"init"))
}
fn delegate_class() -> Class {
static CLASS: OnceLock<usize> = OnceLock::new();
*CLASS.get_or_init(|| unsafe {
let superclass = class(c"NSObject");
let class_name = CString::new("LanMouseStatusItemDelegate").unwrap();
let class = objc_allocateClassPair(superclass, class_name.as_ptr(), 0);
assert!(!class.is_null(), "failed to allocate status item delegate");
class_addMethod(
class,
sel(c"showLanMouse:"),
show_lan_mouse as *const c_void,
c"v@:@".as_ptr(),
);
class_addMethod(
class,
sel(c"quitLanMouse:"),
quit_lan_mouse as *const c_void,
c"v@:@".as_ptr(),
);
// kAEReopenApplication handler — fires when the user re-launches
// the .app while it's already running (Finder, `open`, Dock).
class_addMethod(
class,
sel(c"handleReopenEvent:withReplyEvent:"),
handle_reopen_event as *const c_void,
c"v@:@@".as_ptr(),
);
objc_registerClassPair(class);
class as usize
}) as Class
}
extern "C" fn show_lan_mouse(_this: Id, _cmd: Sel, _sender: Id) {
present_window();
}
extern "C" fn handle_reopen_event(_this: Id, _cmd: Sel, _event: Id, _reply: Id) {
log::debug!("kAEReopenApplication received — presenting main window");
present_window();
}
fn present_window() {
STATUS_ITEM.with(|item| {
let item = item.borrow();
let Some(item) = item.as_ref() else {
return;
};
if let Some(window) = item.window.upgrade() {
window.present();
}
unsafe {
let ns_app = msg_send_id(class(c"NSApplication"), sel(c"sharedApplication"));
msg_send_void_bool(ns_app, sel(c"activateIgnoringOtherApps:"), 1);
}
});
}
// Register the status-item delegate as the handler for the
// kAEReopenApplication Apple Event ('aevt'/'rapp'). NSApplication
// installs a default handler at -finishLaunching that just delegates to
// applicationShouldHandleReopen:hasVisibleWindows: — which is a no-op
// here because GApplication owns NSApp's delegate. Replacing it lets us
// re-present the window when the user double-clicks the .app while
// we're already running.
unsafe fn install_reopen_handler(delegate: Id) {
const K_CORE_EVENT_CLASS: c_uint = 0x6165_7674; // 'aevt'
const K_AE_REOPEN_APPLICATION: c_uint = 0x7261_7070; // 'rapp'
let manager = msg_send_id(
class(c"NSAppleEventManager"),
sel(c"sharedAppleEventManager"),
);
if manager.is_null() {
log::warn!("NSAppleEventManager unavailable; re-launch will not re-open window");
return;
}
msg_send_void_id_sel_u32_u32(
manager,
sel(c"setEventHandler:andSelector:forEventClass:andEventID:"),
delegate,
sel(c"handleReopenEvent:withReplyEvent:"),
K_CORE_EVENT_CLASS,
K_AE_REOPEN_APPLICATION,
);
}
extern "C" fn quit_lan_mouse(_this: Id, _cmd: Sel, _sender: Id) {
STATUS_ITEM.with(|item| {
if let Some(app) = item.borrow().as_ref().and_then(|item| item.app.upgrade()) {
app.quit();
}
});
}
unsafe fn class(name: &CStr) -> Class {
let class = objc_getClass(name.as_ptr());
assert!(!class.is_null(), "missing Objective-C class {name:?}");
class
}
unsafe fn sel(name: &CStr) -> Sel {
sel_registerName(name.as_ptr())
}
unsafe fn nsstring(value: &CStr) -> Id {
msg_send_id_ptr(
class(c"NSString"),
sel(c"stringWithUTF8String:"),
value.as_ptr(),
)
}
#[link(name = "objc")]
extern "C" {
fn objc_allocateClassPair(superclass: Class, name: *const c_char, extra_bytes: usize) -> Class;
fn objc_getClass(name: *const c_char) -> Class;
fn objc_registerClassPair(class: Class);
fn sel_registerName(name: *const c_char) -> Sel;
fn class_addMethod(class: Class, name: Sel, imp: *const c_void, types: *const c_char) -> Bool;
}
#[link(name = "AppKit", kind = "framework")]
extern "C" {}
#[link(name = "objc")]
extern "C" {
#[link_name = "objc_msgSend"]
fn msg_send_id(receiver: Id, selector: Sel) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_id_f64(receiver: Id, selector: Sel, value: c_double) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_id_id_sel_id(receiver: Id, selector: Sel, a: Id, b: Sel, c: Id) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_id_id_id(receiver: Id, selector: Sel, a: Id, b: Id) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_id_id(receiver: Id, selector: Sel, a: Id) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_void_size(receiver: Id, selector: Sel, width: c_double, height: c_double);
#[link_name = "objc_msgSend"]
fn msg_send_id_ptr(receiver: Id, selector: Sel, value: *const c_char) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_id_usize(receiver: Id, selector: Sel, value: usize) -> Id;
#[link_name = "objc_msgSend"]
fn msg_send_usize(receiver: Id, selector: Sel) -> usize;
#[link_name = "objc_msgSend"]
fn msg_send_void_bool(receiver: Id, selector: Sel, value: Bool);
#[link_name = "objc_msgSend"]
fn msg_send_void_id(receiver: Id, selector: Sel, value: Id);
#[link_name = "objc_msgSend"]
fn msg_send_bool_usize(receiver: Id, selector: Sel, value: usize) -> Bool;
#[link_name = "objc_msgSend"]
fn msg_send_void_id_sel_u32_u32(
receiver: Id,
selector: Sel,
a: Id,
b: Sel,
c: c_uint,
d: c_uint,
);
}

View File

@@ -22,6 +22,17 @@ use crate::{
use super::{client_object::ClientObject, client_row::ClientRow};
#[cfg(target_os = "macos")]
fn set_button_content_label(button: &gtk::Button, label: &str) {
// The Reenable/Grant/Relaunch button wraps its icon+label in an
// AdwButtonContent (see window.ui). Walk into it and swap the label
// rather than GtkButton::set_label, which would replace the content
// widget and drop the icon.
if let Some(content) = button.child().and_downcast::<adw::ButtonContent>() {
content.set_label(label);
}
}
glib::wrapper! {
pub struct Window(ObjectSubclass<imp::Window>)
@extends adw::ApplicationWindow, gtk::Window, gtk::Widget,
@@ -432,6 +443,10 @@ impl Window {
pub(super) fn show_toast(&self, msg: &str) {
let toast = adw::Toast::new(msg);
self.add_toast(toast);
}
pub(super) fn add_toast(&self, toast: adw::Toast) {
let toast_overlay = &self.imp().toast_overlay;
toast_overlay.add_toast(toast);
}
@@ -446,14 +461,61 @@ impl Window {
self.update_capture_emulation_status();
}
#[cfg(target_os = "macos")]
pub(super) fn refresh_capture_emulation_status(&self) {
self.update_capture_emulation_status();
}
fn update_capture_emulation_status(&self) {
let capture = self.imp().capture_active.get();
let emulation = self.imp().emulation_active.get();
self.imp().capture_status_row.set_visible(!capture);
self.imp().emulation_status_row.set_visible(!emulation);
self.imp()
.capture_emulation_group
.set_visible(!capture || !emulation);
#[cfg(target_os = "macos")]
{
// On macOS, capture and emulation share the same TCC gate
// (Accessibility). Collapse to a single warning row —
// emulation_status_row stays hidden and capture_status_row
// doubles as the shared status indicator. Its text and
// button mutate based on whether we're waiting for AX or
// waiting for the user to relaunch the app.
let anything_off = !capture || !emulation;
self.imp().emulation_status_row.set_visible(false);
self.imp().capture_status_row.set_visible(anything_off);
self.imp().capture_emulation_group.set_visible(anything_off);
if anything_off {
self.update_macos_warning_row_text();
}
}
#[cfg(not(target_os = "macos"))]
{
self.imp().capture_status_row.set_visible(!capture);
self.imp().emulation_status_row.set_visible(!emulation);
self.imp()
.capture_emulation_group
.set_visible(!capture || !emulation);
}
}
#[cfg(target_os = "macos")]
fn update_macos_warning_row_text(&self) {
let row = &self.imp().capture_status_row;
let button = &self.imp().input_capture_button;
if crate::macos_privacy::accessibility_granted() {
// AX granted but capture/emulation still off → the daemon
// subprocess bailed at startup and needs a fresh process to
// re-initialize with the new grant in place.
row.set_title("relaunch required");
row.set_subtitle("Accessibility granted — restart to activate capture and emulation");
set_button_content_label(button, "Relaunch");
} else {
// AX missing → send the user to System Settings.
row.set_title("input capture is disabled");
row.set_subtitle("grant Accessibility permission to enable");
set_button_content_label(button, "Grant");
}
}
pub(super) fn set_authorized_keys(&self, fingerprints: HashMap<String, String>) {

View File

@@ -142,11 +142,32 @@ impl Window {
#[template_callback]
fn handle_emulation(&self) {
// On macOS the emulation_status_row is hidden — capture_status_row
// acts as the shared warning (see update_capture_emulation_status).
// This handler still fires for the non-macOS platforms where the
// emulation row is distinct.
self.obj().request_emulation();
}
#[template_callback]
fn handle_capture(&self) {
#[cfg(target_os = "macos")]
{
use crate::macos_privacy;
if macos_privacy::accessibility_granted() {
// AX granted but the row is still visible => the daemon
// subprocess bailed before AX was in place and needs a
// fresh process. Quit + relaunch via Launch Services.
log::info!("capture row clicked in relaunch-required state");
macos_privacy::relaunch_bundle();
if let Some(app) = self.obj().application() {
app.quit();
}
return;
}
log::info!("capture row clicked in AX-missing state, opening pane");
macos_privacy::open_accessibility_settings();
}
self.obj().request_capture();
}

View File

@@ -43,6 +43,9 @@ bundle_path=$(dirname "$(dirname "$(dirname "$exec_path")")")
# Path to the Frameworks directory
fwks_path="$bundle_path/Contents/Frameworks"
mkdir -p "$fwks_path"
# Path to bundled GTK/GSettings data
resources_path="$bundle_path/Contents/Resources"
share_path="$resources_path/share"
# Copy and fix references for a binary (executable or dylib)
#
@@ -58,6 +61,10 @@ fix_references() {
libs=$(otool -L "$bin" | awk -v homebrew="$homebrew_path" '$0 ~ homebrew {print $1}')
echo "$libs" | while IFS= read -r old_path; do
if [ -z "$old_path" ]; then
continue
fi
local base_name="$(basename "$old_path")"
local dest="$fwks_path/$base_name"
@@ -81,6 +88,42 @@ fix_references() {
fix_references "$exec_path"
copy_runtime_data() {
mkdir -p "$share_path"
if [ -d "$homebrew_path/share/glib-2.0/schemas" ]; then
mkdir -p "$share_path/glib-2.0"
rm -rf "$share_path/glib-2.0/schemas"
cp -RL "$homebrew_path/share/glib-2.0/schemas" "$share_path/glib-2.0/schemas"
if command -v glib-compile-schemas >/dev/null 2>&1; then
glib-compile-schemas "$share_path/glib-2.0/schemas"
elif [ -x "$homebrew_path/bin/glib-compile-schemas" ]; then
"$homebrew_path/bin/glib-compile-schemas" "$share_path/glib-2.0/schemas"
fi
fi
if [ -d "$homebrew_path/share/gtk-4.0" ]; then
rm -rf "$share_path/gtk-4.0"
cp -RL "$homebrew_path/share/gtk-4.0" "$share_path/gtk-4.0"
fi
if [ -d "$homebrew_path/share/icons/Adwaita" ]; then
mkdir -p "$share_path/icons"
rm -rf "$share_path/icons/Adwaita"
cp -RL "$homebrew_path/share/icons/Adwaita" "$share_path/icons/Adwaita"
fi
}
copy_runtime_data
# cargo-bundle preserves the source path under Contents/Resources (so
# `target/menubar-template.png` lands at `Resources/target/...`). Flatten it
# so NSBundle pathForResource: finds the file at the Resources root.
if [ -f "$resources_path/target/menubar-template.png" ]; then
mv "$resources_path/target/menubar-template.png" "$resources_path/menubar-template.png"
rmdir "$resources_path/target" 2>/dev/null || true
fi
# Ensure the main executable has our Frameworks path in its RPATH
if ! otool -l "$exec_path" | grep -q "@executable_path/../Frameworks"; then
echo "Adding RPATH to $exec_path"

View File

@@ -3,8 +3,15 @@ set -e
usage() {
cat <<EOF
$0: Make a macOS icns file from an SVG with ImageMagick and iconutil.
usage: $0 [SVG [ICNS [ICONSET]]
$0: Make a macOS icns file from an SVG with rsvg-convert, ImageMagick and iconutil.
Follows the Big Sur+ icon template:
- 1024x1024 canvas with a rounded-square (squircle) background
- Icon artwork scaled to fit inside an 824x824 content area, centered
- Transparent padding outside the squircle so the Dock/Finder render it
like other first-party macOS apps.
usage: $0 [SVG [ICNS [ICONSET]]]
ARGUMENTS
SVG The SVG file to convert
@@ -28,15 +35,103 @@ iconset="${3:-./target/icon.iconset}"
set -u
mkdir -p "$iconset"
magick "$svg" -background none -resize 1024x1024 "$iconset"/icon_512x512@2x.png
magick "$svg" -background none -resize 512x512 "$iconset"/icon_512x512.png
magick "$svg" -background none -resize 256x256 "$iconset"/icon_256x256.png
magick "$svg" -background none -resize 128x128 "$iconset"/icon_128x128.png
magick "$svg" -background none -resize 64x64 "$iconset"/icon_32x32@2x.png
magick "$svg" -background none -resize 32x32 "$iconset"/icon_32x32.png
magick "$svg" -background none -resize 16x16 "$iconset"/icon_16x16.png
cp "$iconset"/icon_512x512.png "$iconset"/icon_256x256@2x.png
cp "$iconset"/icon_256x256.png "$iconset"/icon_128x128@2x.png
cp "$iconset"/icon_32x32.png "$iconset"/icon_16x16@2x.png
iconutil -c icns "$iconset" -o "$icns"
workdir="$(dirname "$iconset")/icon-work"
rm -rf "$iconset" "$workdir"
mkdir -p "$iconset" "$workdir"
# Big Sur+ macOS icon template proportions (in a 1024 canvas):
# canvas = 1024
# squircle = 824 (the white rounded-square background, inset 100px)
# content = 560 (artwork inside the squircle, with generous margin)
# radius = 185 (~22.5% of the squircle, the characteristic curvature)
CANVAS=1024
SQUIRCLE=824
CONTENT=560
RADIUS=185
BG_COLOR="#FFFFFF"
SQUIRCLE_OFFSET=$(( (CANVAS - SQUIRCLE) / 2 ))
CONTENT_OFFSET=$(( (CANVAS - CONTENT) / 2 ))
# 1) Render the SVG to the content size at full fidelity.
# rsvg-convert handles our SVG correctly; ImageMagick sometimes crops it.
rsvg-convert -w "$CONTENT" -h "$CONTENT" "$svg" -o "$workdir/content.png"
# 2) Draw the rounded-square (squircle) background on a transparent canvas.
# The squircle is inset from the canvas edges (transparent padding), so the
# Dock/Finder render it at the same visual size as other first-party apps.
magick -size ${CANVAS}x${CANVAS} xc:none \
-fill "$BG_COLOR" \
-draw "roundrectangle ${SQUIRCLE_OFFSET},${SQUIRCLE_OFFSET} $((CANVAS-SQUIRCLE_OFFSET-1)),$((CANVAS-SQUIRCLE_OFFSET-1)) $RADIUS,$RADIUS" \
"$workdir/background.png"
# 3) Composite the artwork onto the background, centered inside the content area.
magick "$workdir/background.png" \
"$workdir/content.png" -geometry +${CONTENT_OFFSET}+${CONTENT_OFFSET} -composite \
-colorspace sRGB -type TrueColorAlpha PNG32:"$workdir/icon-1024.png"
# 4) Generate each iconset size from the master so all sizes share the same
# squircle proportions and look consistent at every resolution.
for size in 1024 512 256 128 64 32 16; do
magick "$workdir/icon-1024.png" -resize ${size}x${size} \
-colorspace sRGB -type TrueColorAlpha PNG32:"$workdir/${size}.png"
done
cp "$workdir/1024.png" "$iconset"/icon_512x512@2x.png
cp "$workdir/512.png" "$iconset"/icon_512x512.png
cp "$workdir/512.png" "$iconset"/icon_256x256@2x.png
cp "$workdir/256.png" "$iconset"/icon_256x256.png
cp "$workdir/256.png" "$iconset"/icon_128x128@2x.png
cp "$workdir/128.png" "$iconset"/icon_128x128.png
cp "$workdir/64.png" "$iconset"/icon_32x32@2x.png
cp "$workdir/32.png" "$iconset"/icon_32x32.png
cp "$workdir/32.png" "$iconset"/icon_16x16@2x.png
cp "$workdir/16.png" "$iconset"/icon_16x16.png
mkdir -p "$(dirname "$icns")"
# Menu bar template icon: flatten all RGB channels to 0 (black) while keeping
# alpha so the artwork reads as a clean silhouette. NSStatusBarButton tints
# template images to match the menu bar appearance in light and dark modes.
menubar_template="$(dirname "$icns")/menubar-template.png"
rsvg-convert -w 44 -h 44 "$svg" -o "$workdir/menubar-44.png"
magick "$workdir/menubar-44.png" -channel RGB -evaluate set 0 +channel \
"$menubar_template"
if ! iconutil -c icns "$iconset" -o "$icns"; then
if ! command -v perl >/dev/null 2>&1; then
echo "iconutil failed and perl is not available for the fallback icns writer" >&2
exit 1
fi
echo "iconutil rejected the iconset; writing icns directly" >&2
perl - "$icns" "$iconset" <<'PERL'
use strict;
use warnings;
my ($icns, $iconset) = @ARGV;
my @icons = (
[ 'icp4', "$iconset/icon_16x16.png" ],
[ 'ic11', "$iconset/icon_16x16\@2x.png" ],
[ 'icp5', "$iconset/icon_32x32.png" ],
[ 'ic12', "$iconset/icon_32x32\@2x.png" ],
[ 'ic07', "$iconset/icon_128x128.png" ],
[ 'ic13', "$iconset/icon_128x128\@2x.png" ],
[ 'ic08', "$iconset/icon_256x256.png" ],
[ 'ic14', "$iconset/icon_256x256\@2x.png" ],
[ 'ic09', "$iconset/icon_512x512.png" ],
[ 'ic10', "$iconset/icon_512x512\@2x.png" ],
);
my $body = '';
for my $icon (@icons) {
my ($type, $path) = @$icon;
open my $fh, '<:raw', $path or die "$path: $!";
local $/;
my $png = <$fh>;
$body .= $type . pack('N', length($png) + 8) . $png;
}
open my $out, '>:raw', $icns or die "$icns: $!";
print {$out} 'icns' . pack('N', length($body) + 8) . $body;
PERL
fi

View File

@@ -8,7 +8,7 @@ use futures::StreamExt;
use input_capture::{
CaptureError, CaptureEvent, CaptureHandle, InputCapture, InputCaptureError, Position,
};
use input_event::scancode;
use input_event::{Event, KeyboardEvent, scancode};
use lan_mouse_proto::ProtoEvent;
use local_channel::mpsc::{Receiver, Sender, channel};
use tokio::task::{JoinHandle, spawn_local};
@@ -49,7 +49,7 @@ pub(crate) enum CaptureType {
EnterOnly,
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Debug)]
enum CaptureRequest {
/// capture must release the mouse
Release,
@@ -59,6 +59,8 @@ enum CaptureRequest {
Destroy(CaptureHandle),
/// reenable input capture
Reenable,
/// set release bind
SetReleaseBind(Vec<scancode::Linux>),
}
impl Capture {
@@ -131,6 +133,10 @@ impl Capture {
pub(crate) async fn event(&mut self) -> ICaptureEvent {
self.event_rx.recv().await.expect("channel closed")
}
pub(crate) fn set_release_bind(&mut self, bind: Vec<scancode::Linux>) {
let _ = self.request_tx.send(CaptureRequest::SetReleaseBind(bind));
}
}
/// debounce a statement `$st`, i.e. the statement is executed only if the
@@ -205,6 +211,9 @@ impl CaptureTask {
CaptureRequest::Create(h, p, t) => self.add_capture(h, p, t),
CaptureRequest::Destroy(h) => self.remove_capture(h),
CaptureRequest::Release => { /* nothing to do */ }
CaptureRequest::SetReleaseBind(bind) => {
self.release_bind.borrow_mut().clone_from(&bind);
}
},
_ = self.cancellation_token.cancelled() => return,
}
@@ -295,6 +304,9 @@ impl CaptureTask {
self.remove_capture(h);
capture.destroy(h).await?;
}
CaptureRequest::SetReleaseBind(bind) => {
self.release_bind.borrow_mut().clone_from(&bind);
}
},
_ = self.cancellation_token.cancelled() => break,
}
@@ -364,6 +376,41 @@ impl CaptureTask {
async fn release_capture(&mut self, capture: &mut InputCapture) -> Result<(), CaptureError> {
// If we have an active client, notify them we're leaving
if let Some(handle) = self.active_client.take() {
// Synthesize key-up events for every key still held in the
// capture's pressed_keys set BEFORE sending Leave. Without
// this, pressing the release-bind chord (typically all four
// modifiers) leaves the peer with phantom held modifiers:
// the down events were forwarded while capture was active,
// but the matching up events arrive after the local tap
// flips to passthrough and never reach the peer. The peer
// then runs every subsequent keystroke through those held
// mods until its watchdog times out (1+ s) or our Leave
// arrives — and Leave can be lost over UDP/DTLS.
for key in capture.take_pressed_keys() {
let key_up = ProtoEvent::Input(Event::Keyboard(KeyboardEvent::Key {
time: 0,
key: key as u32,
state: 0,
}));
if let Err(e) = self.conn.send(key_up, handle).await {
log::warn!("failed to send key-up to client {handle}: {e}");
}
}
// Reset the modifier mask too. The peer's input-emulation
// layer keeps a separate XKB-style modifier state that's
// updated by KeyboardEvent::Modifiers, distinct from the
// pressed_keys set drained above. Without this, an
// already-locked CapsLock would survive the release.
let mods_zero = ProtoEvent::Input(Event::Keyboard(KeyboardEvent::Modifiers {
depressed: 0,
latched: 0,
locked: 0,
group: 0,
}));
if let Err(e) = self.conn.send(mods_zero, handle).await {
log::warn!("failed to reset modifiers on client {handle}: {e}");
}
log::info!("sending Leave event to client {handle}");
if let Err(e) = self.conn.send(ProtoEvent::Leave(0), handle).await {
log::warn!("failed to send Leave to client {handle}: {e}");

View File

@@ -9,6 +9,8 @@ use slab::Slab;
use lan_mouse_ipc::{ClientConfig, ClientHandle, ClientState, Position};
use crate::config::ConfigClient;
#[derive(Clone, Default)]
pub struct ClientManager {
clients: Rc<RefCell<Slab<(ClientConfig, ClientState)>>>,
@@ -24,6 +26,25 @@ impl ClientManager {
.collect::<Vec<_>>()
}
pub fn add_with_config(&self, config_client: ConfigClient) -> ClientHandle {
let config = ClientConfig {
hostname: config_client.hostname,
fix_ips: config_client.ips.into_iter().collect(),
port: config_client.port,
pos: config_client.pos,
cmd: config_client.enter_hook,
};
let state = ClientState {
active: config_client.active,
ips: HashSet::from_iter(config.fix_ips.iter().cloned()),
..Default::default()
};
let handle = self.add_client();
self.set_config(handle, config);
self.set_state(handle, state);
handle
}
/// add a new client to this manager
pub fn add_client(&self) -> ClientHandle {
self.clients.borrow_mut().insert(Default::default()) as ClientHandle
@@ -230,6 +251,15 @@ impl ClientManager {
.and_then(|(c, _)| c.cmd.clone())
}
/// returns all clients that are currently registered
pub(crate) fn registered_clients(&self) -> Vec<ClientHandle> {
self.clients
.borrow()
.iter()
.map(|(h, _)| h as ClientHandle)
.collect()
}
/// returns all clients that are currently active
pub(crate) fn active_clients(&self) -> Vec<ClientHandle> {
self.clients

View File

@@ -1,6 +1,7 @@
use crate::capture_test::TestCaptureArgs;
use crate::emulation_test::TestEmulationArgs;
use clap::{Parser, Subcommand, ValueEnum};
use notify::{EventKind, RecommendedWatcher, Watcher};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env::{self, VarError};
@@ -46,7 +47,7 @@ fn default_path() -> Result<PathBuf, VarError> {
Ok(PathBuf::from(default_path))
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
struct ConfigToml {
capture_backend: Option<CaptureBackend>,
emulation_backend: Option<EmulationBackend>,
@@ -244,8 +245,14 @@ pub struct Config {
cert_path: PathBuf,
/// path to the config file used
config_path: PathBuf,
/// path to config directory (parent of above)
config_dir: PathBuf,
/// the (optional) toml config and it's path
config_toml: Option<ConfigToml>,
// filesystem watcher
watcher: notify::RecommendedWatcher,
// channel for filesystem events
watch_rx: tokio::sync::mpsc::Receiver<Result<notify::Event, notify::Error>>,
}
pub struct ConfigClient {
@@ -311,6 +318,8 @@ pub enum ConfigError {
Io(#[from] io::Error),
#[error(transparent)]
Var(#[from] VarError),
#[error(transparent)]
Watcher(#[from] notify::Error),
}
const DEFAULT_RELEASE_KEYS: [scancode::Linux; 4] =
@@ -325,6 +334,23 @@ impl Config {
.config
.clone()
.unwrap_or(default_path()?.join(CONFIG_FILE_NAME));
let config_dir = config_path
.parent()
.expect("config directory")
.to_path_buf();
// Ensure the config directory exists and write a default config file
// if none is present. Runs on every Config::new(), regardless of which
// entry path (GUI main, spawned daemon, CLI, test commands) we're on,
// so a fresh Mac never hits "No such file or directory" on config.toml
// and notify::Watcher (which requires the dir to exist on macOS
// FSEvents and some Linux backends) has a concrete path to watch.
fs::create_dir_all(&config_dir)?;
if !config_path.exists() {
let default_toml = toml::to_string_pretty(&ConfigToml::default())
.expect("default ConfigToml serialization cannot fail");
fs::write(&config_path, default_toml)?;
}
let config_toml = match ConfigToml::new(&config_path) {
Err(e) => {
@@ -342,12 +368,51 @@ impl Config {
.or(config_toml.as_ref().and_then(|c| c.cert_path.clone()))
.unwrap_or(default_path()?.join(CERT_FILE_NAME));
Ok(Config {
let (tx, watch_rx) = tokio::sync::mpsc::channel(16);
let watcher = RecommendedWatcher::new(
move |res| {
let _ = tx.blocking_send(res);
},
notify::Config::default(),
)?;
let mut config = Config {
args,
cert_path,
config_path,
config_dir,
config_toml,
})
watcher,
watch_rx,
};
config.watch()?;
Ok(config)
}
fn watch(&mut self) -> Result<(), notify::Error> {
self.watcher
.watch(&self.config_dir, notify::RecursiveMode::NonRecursive)?;
Ok(())
}
fn unwatch(&mut self) -> Result<(), notify::Error> {
self.watcher.unwatch(&self.config_dir)?;
Ok(())
}
pub async fn changed(&mut self) -> Result<(), notify::Error> {
loop {
let event = self.watch_rx.recv().await.expect("channel closed");
let event = event.expect("filesystem event");
if event.paths.contains(&self.config_path)
&& matches!(
event.kind,
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
)
&& self.read_from_disk()?
{
return Ok(());
}
}
}
/// the command to run
@@ -428,11 +493,8 @@ impl Config {
/// set authorized keys
pub fn set_authorized_keys(&mut self, fingerprints: HashMap<String, String>) {
if fingerprints.is_empty() {
return;
}
if self.config_toml.is_none() {
self.config_toml = Default::default();
self.config_toml = Some(Default::default());
}
self.config_toml
.as_mut()
@@ -440,38 +502,58 @@ impl Config {
.authorized_fingerprints = Some(fingerprints);
}
pub fn write_back(&self) -> Result<(), io::Error> {
log::info!("writing config to {:?}", &self.config_path);
/* load the current configuration file */
let current_config = match fs::read_to_string(&self.config_path) {
Ok(c) => c.parse::<DocumentMut>().unwrap_or_default(),
pub fn read_from_disk(&mut self) -> Result<bool, io::Error> {
log::info!("reading config from {:?}", &self.config_path);
let current_config = fs::read_to_string(&self.config_path)?;
let current_config = match current_config.parse::<DocumentMut>() {
Ok(c) => c,
Err(e) => {
log::info!("{:?} {e} => creating new config", self.config_path());
Default::default()
log::warn!("{:?} {e}", self.config_path());
return Ok(false);
}
};
let _current_config =
toml_edit::de::from_document::<ConfigToml>(current_config).unwrap_or_default();
let mut changed = false;
match toml_edit::de::from_document::<ConfigToml>(current_config) {
Ok(current_config) => {
changed = self
.config_toml
.as_ref()
.is_none_or(|c| c != &current_config);
self.config_toml.replace(current_config);
}
Err(e) => log::warn!("{:?} {e}", self.config_path()),
};
Ok(changed)
}
pub fn write_back(&mut self) -> Result<(), io::Error> {
log::info!("writing config to {:?}", &self.config_path);
/* the new config */
let new_config = self.config_toml.clone().unwrap_or_default();
// let new_config = toml_edit::ser::to_document::<ConfigToml>(&new_config).expect("fixme");
let new_config = toml_edit::ser::to_string_pretty(&new_config).expect("config");
/*
* TODO merge documents => eventually we might want to split this up into clients configured
* TODO merge with current config file to preserve comments
* => eventually we might want to split this up into clients configured
* via the config file and clients managed through the GUI / frontend.
* The latter should be saved to $XDG_DATA_HOME instead of $XDG_CONFIG_HOME,
* and clients configured through .config could be made permanent.
* For now we just override the config file.
*/
let _ = self.unwatch();
/* write new config to file */
if let Some(p) = self.config_path().parent() {
fs::create_dir_all(p)?;
}
let mut f = File::create(self.config_path())?;
f.write_all(new_config.as_bytes())?;
{
let mut f = File::create(self.config_path())?;
f.write_all(new_config.as_bytes())?;
f.sync_all()?;
}
let _ = self.watch();
Ok(())
}

View File

@@ -11,8 +11,8 @@ use crate::{
use futures::StreamExt;
use hickory_resolver::ResolveError;
use lan_mouse_ipc::{
AsyncFrontendListener, ClientConfig, ClientHandle, ClientState, FrontendEvent, FrontendRequest,
IpcError, IpcListenerCreationError, Position, Status,
AsyncFrontendListener, ClientHandle, FrontendEvent, FrontendRequest, IpcError,
IpcListenerCreationError, Position, Status,
};
use log;
use std::{
@@ -83,21 +83,7 @@ impl Service {
pub async fn new(config: Config) -> Result<Self, ServiceError> {
let client_manager = ClientManager::default();
for client in config.clients() {
let config = ClientConfig {
hostname: client.hostname,
fix_ips: client.ips.into_iter().collect(),
port: client.port,
pos: client.pos,
cmd: client.enter_hook,
};
let state = ClientState {
active: client.active,
ips: HashSet::from_iter(config.fix_ips.iter().cloned()),
..Default::default()
};
let handle = client_manager.add_client();
client_manager.set_config(handle, config);
client_manager.set_state(handle, state);
client_manager.add_with_config(client);
}
// load certificate
@@ -164,6 +150,7 @@ impl Service {
event = self.emulation.event() => self.handle_emulation_event(event),
event = self.capture.event() => self.handle_capture_event(event),
event = self.resolver.event() => self.handle_resolver_event(event),
_ = self.config.changed() => self.handle_config_change(),
r = signal::ctrl_c() => break r.expect("failed to wait for CTRL+C"),
}
}
@@ -255,6 +242,30 @@ impl Service {
}
}
fn handle_config_change(&mut self) {
for h in self.client_manager.registered_clients() {
self.remove_client(h);
}
for c in self.config.clients() {
let handle = self.client_manager.add_with_config(c);
log::info!("added client {handle}");
let (c, s) = self.client_manager.get_state(handle).unwrap();
if s.active {
self.client_manager.deactivate_client(handle);
self.activate_client(handle);
}
self.notify_frontend(FrontendEvent::Created(handle, c, s));
}
let release_bind = self.config.release_bind();
self.capture.set_release_bind(release_bind);
let authorized_keys = self.config.authorized_fingerprints();
self.authorized_keys
.write()
.unwrap()
.clone_from(&authorized_keys);
self.sync_frontend();
}
async fn handle_frontend_pending(&mut self) {
while let Some(event) = self.pending_frontend_events.pop_front() {
self.frontend_listener.broadcast(event).await;
@@ -477,7 +488,7 @@ impl Service {
}
fn activate_client(&mut self, handle: ClientHandle) {
log::debug!("activating client");
log::debug!("activating client {handle}");
/* resolve dns on activate */
self.resolve(handle);