27 Commits
Author SHA1 Message Date
Xuc Pan 8d8bff5e0f release: v0.1.7 2026-11-09 23:27:18 +08:00
Xuc Pan 8423dc77b2 test(config): retain keyboard defaults coverage after integration 2026-11-09 23:27:18 +08:00
Xuc Pan d5db0ebdf3 fix(portal): bound pending input across capture recovery 2026-11-09 23:26:21 +08:00
Xuc Pan eb862b5529 fix(audio): select the managed default capture source explicitly 2026-11-09 23:26:21 +08:00
falcon-jin 98af6fce28 feat(capture): support consented multi-monitor desktops with recovery (#32) 2026-11-09 23:26:07 +08:00
喵喵机 6d0e733cd7 fix(input): preserve keyboard modifiers while preventing forged lock keys (#34) 2026-11-09 23:25:07 +08:00
Mobsama 62cf979dd6 fix(rpm): use portable runtime dependencies (#31) 2026-11-09 23:20:09 +08:00
Xuc Pan 56971eeba1 release: v0.1.6 2026-10-18 01:31:34 +08:00
Xuc Pan f02dcdd8c0 fix(session): monitor Windows lifetime without repeated Wine startups
Keep process observations in the resident session marker and bound utility pipe reads. Reap managed-prefix Wine workers through pidfds, including WebView2 thread groups whose leaders already exited.
2026-10-18 01:31:34 +08:00
moxuunandXuc Pan e7724c6d86 fix(hook): map a full-monitor capture request onto the whole frame (#30)
* fix(hook): map a full-monitor capture request onto the whole frame

The Wine hook scaled the client's source rectangle by the virtual desktop
size, on the assumption that a captured frame covers every monitor. The
Wayland portal capture path selects a single monitor, so on a multi-monitor
desktop the frame is narrower than the virtual desktop and the horizontal
scale factor was wrong.

With a 4480x1600 virtual desktop and a 2560x1600 frame, a request for the
whole 2560x1600 monitor produced:

    sw = 2560 * 2560 / 4480 = 1462

That sampled only the left 57% of the frame and stretched it across the
destination, dropping the right 43%. The vertical factor stayed correct
(1600 * 1600 / 1600), which is why the symptom was a missing right edge
rather than a visible aspect distortion. On a single monitor the virtual
desktop equals the frame and the two factors agree, so the bug stayed
hidden.

Detect the case where the requested rectangle covers exactly one Wine
monitor whose size equals the frame, and use the whole frame. Every other
request keeps the previous virtual-desktop mapping, so partial regions are
unchanged.

This does not add portal coordinates to the frame protocol. Portal
coordinates are compositor coordinates and Wine enumerates monitors in a
different order, so capturing a monitor that is not the Wine primary
monitor still needs a separate output-to-monitor mapping.

* fix(hook): keep full-monitor geometry across fractional scaling

GNOME 125 percent scaling can expose a 2048x1152 Wine monitor while the selected Portal frame remains 1280x720. Match the aspect ratio of an exact monitor rectangle instead of requiring equal pixel dimensions; leave partial and virtual-desktop requests on the existing path.

Verified with real isolated GNOME dual monitors, native DMA-BUF capture, and a real Windows FFmpeg GDI consumer. The old fractional-scale output drops the desktop panel; the revised output preserves the whole image. No test scripts added.

---------

Co-authored-by: Xuc Pan <[email protected]>
2026-10-18 00:18:41 +08:00
迢辰andXuc Pan a5e2aa44cd fix(capture): map the DMA-BUF frames niri actually sends (#26)
* fix(capture): map the DMA-BUF frames niri actually sends

`uur run` reported "No Wayland frames arrived within 120 seconds" on a
session where the portal handshake succeeded. The session log showed the
stream never leaving negotiation:

    portal session ready (video node 73)
    stream state: connecting
    stream state: paused
    stream state: error - no more input formats
    stream state: unconnected

Three separate defects in `uur-pw-capture`:

1. The format filter omitted `modifier`. niri marks that property
   MANDATORY (SPA flags 0x18), and SPA filtering fails unless both sides
   carry a mandatory property -- which surfaces as "no more input
   formats". The filter now advertises LINEAR, the layout the frame
   protocol already assumes.

2. `on_process` only handled `data != NULL` and `SPA_DATA_MemFd`. niri
   delivers SPA_DATA_DmaBuf planes, which carry an fd and no pointer, so
   every frame was dropped in silence. Since the session negotiates
   LINEAR, that fd is directly mappable without GBM/EGL; the helper now
   mmaps it. A non-linear modifier is refused instead of publishing
   garbage.

3. DMA-BUF producers leave `chunk->size` and `maxsize` at 1. Both the
   mapping length and the row count were derived from those, so the mmap
   covered one byte and `rows` came out zero -- publishing an all-black
   frame. Both now use the negotiated stride and height.

Verified on niri 26.04 with Wine 11.19: the stream reaches `streaming`,
~60 fps (1195 frames in 20 s), and the published frame decodes to the
real desktop rather than black.

* fix(capture): validate DMA-BUFs and recover interrupted screen streams

Use immutable transport files across geometry changes and remap Wine readers safely. Bound stream recovery and preserve portal stop-sharing intent. Refs #29.

* fix(capture): watch Mutter layout changes and support older build headers

* fix(capture): keep display changes outside the failure retry budget

* fix(capture): honor portal stop signals during GNOME recovery

Subscribe before starting on the portal-owned D-Bus connection and accept the real Session.Closed dictionary body. Correlate Mutter's close-before-MonitorsChanged ordering without restarting an explicit Stop Sharing session.

Verified in a private GNOME 51.1 namespace with real GBM DMA-BUF, 100/125 percent scaling, portrait and landscape, and native Stop Sharing. Existing 48 tests and strict clippy pass. Real Wine GDI reader captured 120 final-run frames across four layout changes with no hook fallbacks. No test scripts added.

---------

Co-authored-by: Xuc Pan <[email protected]>
2026-10-15 16:57:34 +08:00
迢辰andXuc Pan 306489d8ad fix(capture): choose a cursor mode the portal advertises (#25)
* fix(capture): choose a cursor mode the portal advertises

`uur run` on a Wayland session aborted during capture negotiation:

    Error: Portal request didn't succeed: Other
    Error: ZBus Error: org.freedesktop.portal.Error.InvalidArgument:
           Unavailable cursor mode 2

`negotiate` hardcoded `CursorMode::Embedded` (2). The portal frontend
validates that against the backend's `AvailableCursorModes` and rejects
anything outside it, so any backend that does not offer Embedded could
never start a session. A frontend whose backend property cache is empty
reports `AvailableCursorModes = 0` and then rejects every mode, which is
what made this fail even on backends that do support Embedded: restarting
`xdg-desktop-portal` restored the flags from 0 to 7 and mode 2 was
accepted again.

`preferred_cursor_mode` now reads the advertised flags and picks Embedded,
then Hidden, then Metadata. If none are advertised it fails with an
actionable message naming the portal restart, instead of surfacing a raw
D-Bus error. Older portals that do not implement the v2 property keep the
previous behaviour.

The same hardcoded mode in the RemoteDesktop input path is routed through
the shared helper.

Adds four tests: preference order, subset fallback, the empty-advertisement
regression, and source-type mapping.

* fix(capture): preserve portal errors and report cursor fallback

---------

Co-authored-by: Xuc Pan <[email protected]>
2026-10-15 14:44:04 +08:00
迢辰andXuc Pan bfecaa5c69 fix(wine): select the client root that actually holds bin/ (#24)
* fix(wine): select the client root that actually holds bin/

`uur run` aborted with "WebView2 bootstrapper missing from the client
directory" on a complete install.

`find_client_dir` searched depth-first for `GameViewerServer.exe` and
returned the first hit, special-casing only a parent named `bin`. NetEase
ships the payload twice: as `<root>/bin/` and as a sibling
`<root>/<version>/`. When readdir order reached `<root>/<version>/` first,
that directory was returned as the client root. It has no `bin/`
subdirectory, so every `join("bin")` lookup missed -- the WebView2
bootstrapper and the terminal proxies -- and the session bailed out.
`deploy_terminal_proxy` then created a spurious `bin/` inside the version
directory and wrote proxies into it.

Now every directory holding `GameViewer.exe` is collected and ranked:
`bin/GameViewerServer.exe` scores highest because that is the layout uur
drives, then `bin/MicrosoftEdgeWebview2Setup.exe`, then a top-level
server. Ties break on path depth, then lexically, so the choice no longer
depends on readdir order. A versioned copy is still used when it is the
only candidate.

Adds four tests covering both layouts, readdir stability, and the
fallback.

* fix(wine): require complete payloads and support flat client layouts

---------

Co-authored-by: Xuc Pan <[email protected]>
2026-10-15 14:44:00 +08:00
迢辰andXuc Pan 1dc156739c fix(wine): make setup detect a provisioned prefix (#23)
* fix(wine): make setup detect a provisioned prefix

Two defects made `uur setup` fail on a fully installed prefix.

1. The service check matched `gameviewerserver.exe`, but the Windows
   service NetEase registers uses `GameViewerService.exe` as its
   ImagePath. `GameViewerServer.exe` is the streaming server and never
   appears in the service registration, so `client_service_registered`
   and `query_client_service` always returned false. A completed
   install was reported as "GameViewerService has no valid registered
   executable" and setup re-downloaded and re-installed every run.

   Both checks now share one `SERVICE_IMAGE` constant, and the
   `system.reg` parse is factored into a pure `service_image_path`
   helper so it is testable without a Wine prefix.

2. `wineboot --init` returns before wineserver flushes
   `system.reg`/`user.reg` to disk (measured ~7s on Wine 11), so a
   freshly created prefix was misread as uninitialized and setup
   aborted with "Wine prefix initialization failed (exit status: 0)".
   Added a bounded `flush_prefix` barrier that waits for `wineserver -w`
   to return, then polls for the registry files.

Verified on Wine 11.19: a clean install into an isolated prefix
succeeds end to end, re-running setup takes the already-provisioned
fast path, and `setup --repair` verifies without reinstalling.

* fix(wine): bound prefix readiness waits without blocking on services

---------

Co-authored-by: Xuc Pan <[email protected]>
2026-10-15 14:41:50 +08:00
Xuc Pan ef72baa56d chore(release): prepare v0.1.5 2026-10-13 15:31:16 +08:00
Xuc Pan 8c0589021f fix: repair Wine setup and niri capture, input and tray (#22)
* fix(setup): verify provisioning and runtime readiness

* feat: add explicit per-user uninstall and purge

* fix: restore niri input and provide native capture and tray

* fix(build): declare Wayland scanner and release dependencies
2026-10-13 15:26:06 +08:00
Xuc Pan d349e6ff6a chore(release): prepare v0.1.4 2026-10-05 23:40:39 +08:00
Xuc Pan 01e7ed7218 Merge pull request #20 from panxuc/fix-issue-18-prefix-deploy
fix: make managed prefix deployment repeatable
2026-10-05 23:33:03 +08:00
Xuc Pan 3c78382f20 test(session): cover first deployment from readonly source 2026-10-05 23:24:53 +08:00
Xuc Pan 2833b08a37 fix(session): make prefix deployment repeatable 2026-10-05 23:19:31 +08:00
Xuc Pan 8fd476d81c Merge pull request #16 from panxuc/fix-issue-14-input-bridge
fix: keep input bridge alive for unsupported key events
2026-10-05 23:11:28 +08:00
Xuc Pan 31aaab0fee fix(bridge): ignore zero virtual-key input 2026-09-30 06:59:52 +08:00
Xuc Pan 5245c9ee61 fix(desktop): improve HiDPI and exit integration 2026-09-25 03:04:51 +08:00
Xuc Pan 9f12a88a08 fix(desktop): improve HiDPI and exit integration 2026-09-25 03:04:51 +08:00
Muush 2b41541128 fix(wallpaper): resolve wpaperd relative targets from its working directory
wpaperd writes configured image paths verbatim into the state symlink, so
targets relative to its working directory dangle under symlink semantics
and link.canonicalize() fails for every output. Read /proc/<pid>/cwd where
the process is matched and resolve relative targets against it; absolute
targets keep filesystem semantics.
2026-09-24 23:14:23 +08:00
Xuc Pan d47178916f fix(wallpaper): resolve wpaperd links from link location 2026-09-24 13:13:12 +08:00
Muush 3dc3b62477 feat(wallpaper): detect wpaperd wallpapers from state links
wpaperd mirrors the current wallpaper of every output as a symlink
under $XDG_STATE_HOME/wpaperd/wallpapers, rewritten on each change.
Identify the wpaperd process in the runtime provider scan and resolve
the newest link, joining relative targets with $HOME.
2026-09-24 13:13:12 +08:00
59 changed files with 6890 additions and 641 deletions

No files matched your search

+7 -2
View File
@@ -13,6 +13,8 @@ jobs:
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
with: with:
components: clippy, rustfmt components: clippy, rustfmt
- name: Install X11 headers for the compatibility library
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libx11-dev pkg-config
- name: Rust checks - name: Rust checks
run: | run: |
cargo fmt --check cargo fmt --check
@@ -22,6 +24,8 @@ jobs:
/tmp/frame-protocol /tmp/frame-protocol
cc -std=c11 -O2 -Wall -Wextra -Werror tests/cursor-overlay.c -o /tmp/cursor-overlay cc -std=c11 -O2 -Wall -Wextra -Werror tests/cursor-overlay.c -o /tmp/cursor-overlay
/tmp/cursor-overlay /tmp/cursor-overlay
- name: Build the lock-modifier compatibility library
run: ./compat/build.sh
- name: Build - name: Build
run: cargo build --locked --release run: cargo build --locked --release
@@ -50,13 +54,14 @@ jobs:
sudo apt-get update sudo apt-get update
sudo apt-get install -y --no-install-recommends \ sudo apt-get install -y --no-install-recommends \
appstream binutils-mingw-w64-x86-64 desktop-file-utils \ appstream binutils-mingw-w64-x86-64 desktop-file-utils \
gcc gcc-mingw-w64-x86-64 libpipewire-0.3-dev pkg-config \ gcc gcc-mingw-w64-x86-64 libpipewire-0.3-dev libwayland-dev \
wine xvfb libx11-dev libxtst-dev pkg-config wine xvfb
- name: Build and stage - name: Build and stage
run: | run: |
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
stage="$(mktemp -d)" stage="$(mktemp -d)"
./packaging/stage.sh "$stage" ./packaging/stage.sh "$stage"
test -x "$stage/usr/bin/uur" test -x "$stage/usr/bin/uur"
+4 -3
View File
@@ -38,8 +38,8 @@ jobs:
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y --no-install-recommends \ sudo apt-get install -y --no-install-recommends \
binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev \ binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev libwayland-dev \
gcc-mingw-w64-x86-64 pkg-config zstd gcc-mingw-w64-x86-64 libx11-dev pkg-config zstd
- name: Install nFPM - name: Install nFPM
env: env:
NFPM_VERSION: 2.47.0 NFPM_VERSION: 2.47.0
@@ -73,7 +73,7 @@ jobs:
- name: Install Arch build dependencies - name: Install Arch build dependencies
run: | run: |
pacman -Syu --noconfirm \ pacman -Syu --noconfirm \
cargo rust gcc pkgconf pipewire \ cargo rust gcc pkgconf pipewire wayland libx11 \
mingw-w64-gcc mingw-w64-binutils mingw-w64-gcc mingw-w64-binutils
- name: Build native pacman package with makepkg - name: Build native pacman package with makepkg
run: | run: |
@@ -84,6 +84,7 @@ jobs:
CARGO_BUILD_JOBS=2 cargo build --release --locked CARGO_BUILD_JOBS=2 cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
./packaging/build-arch-package.sh "$1/dist" ./packaging/build-arch-package.sh "$1/dist"
' _ "$GITHUB_WORKSPACE" ' _ "$GITHUB_WORKSPACE"
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
+1
View File
@@ -2,5 +2,6 @@
/build /build
/dist /dist
/capture/uur-pw-capture /capture/uur-pw-capture
/capture/uur-wl-capture
Cargo.lock.orig Cargo.lock.orig
*.tar.gz *.tar.gz
Generated
+83 -1
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "aho-corasick" name = "aho-corasick"
version = "1.1.5" version = "1.1.5"
@@ -231,6 +237,15 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "crc32fast"
version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "crossbeam-deque" name = "crossbeam-deque"
version = "0.8.7" version = "0.8.7"
@@ -342,6 +357,26 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.2" version = "1.2.2"
@@ -749,6 +784,26 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]] [[package]]
name = "mio" name = "mio"
version = "1.2.3" version = "1.2.3"
@@ -821,6 +876,19 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags 2.13.1",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.6" version = "0.1.6"
@@ -1115,6 +1183,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.3" version = "1.0.3"
@@ -1413,7 +1487,7 @@ dependencies = [
[[package]] [[package]]
name = "uur" name = "uur"
version = "0.1.3" version = "0.1.7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"ashpd", "ashpd",
@@ -1421,6 +1495,7 @@ dependencies = [
"futures", "futures",
"input-linux-sys", "input-linux-sys",
"libc", "libc",
"png",
"rust-i18n", "rust-i18n",
"serde", "serde",
"serde_json", "serde_json",
@@ -1428,6 +1503,7 @@ dependencies = [
"tokio", "tokio",
"toml", "toml",
"x11rb", "x11rb",
"zbus",
] ]
[[package]] [[package]]
@@ -1718,6 +1794,12 @@ dependencies = [
"syn 3.0.4", "syn 3.0.4",
] ]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]] [[package]]
name = "zmij" name = "zmij"
version = "1.0.23" version = "1.0.23"
+3 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "uur" name = "uur"
version = "0.1.3" version = "0.1.7"
edition = "2021" edition = "2021"
description = "Native Linux companion for NetEase UU Remote: X11/Wayland input and capture, packaged as a regular desktop app" description = "Native Linux companion for NetEase UU Remote: X11/Wayland input and capture, packaged as a regular desktop app"
license = "MIT" license = "MIT"
@@ -21,6 +21,8 @@ libc = "0.2"
input-linux-sys = "0.9" input-linux-sys = "0.9"
x11rb = { version = "0.13", features = ["xtest"] } x11rb = { version = "0.13", features = ["xtest"] }
signal-hook = "0.3" signal-hook = "0.3"
png = "0.18"
zbus = { version = "5", default-features = false, features = ["tokio"] }
[profile.release] [profile.release]
lto = true lto = true
+4
View File
@@ -1,5 +1,9 @@
uur is original code, MIT licensed. uur is original code, MIT licensed.
The vendored wlr-screencopy protocol is MIT licensed, copyright Simon Ser
(2018) and Andri Yngvason (2019). Its full license is preserved in
capture/wlr-screencopy-unstable-v1.xml.
Design ideas were learned from and are credited to: Design ideas were learned from and are credited to:
- GuoWQ222/uu-remote-for-linux (0BSD) — the wevtapi preload chain and the - GuoWQ222/uu-remote-for-linux (0BSD) — the wevtapi preload chain and the
PipeWire/portal approach to Wayland capture. PipeWire/portal approach to Wayland capture.
+21 -4
View File
@@ -69,7 +69,7 @@ recipes and release artifacts share one version and filesystem layout.
Install a downloaded release package with pacman: Install a downloaded release package with pacman:
```bash ```bash
sudo pacman -U ./dist/uur-0.1.3-1-x86_64.pkg.tar.zst sudo pacman -U ./dist/uur-0.1.7-1-x86_64.pkg.tar.zst
``` ```
### AUR ### AUR
@@ -83,13 +83,13 @@ paru -S uur
### Debian and Ubuntu package family ### Debian and Ubuntu package family
```bash ```bash
sudo apt install ./uur_0.1.3_amd64.deb sudo apt install ./uur_0.1.7_amd64.deb
``` ```
### Fedora and compatible RPM systems ### Fedora and compatible RPM systems
```bash ```bash
sudo dnf install ./uur-0.1.3-1.x86_64.rpm sudo dnf install ./uur-0.1.7-1.x86_64.rpm
``` ```
On systems with different RPM dependency names, install the dependencies On systems with different RPM dependency names, install the dependencies
@@ -98,7 +98,7 @@ manually or use the portable archive.
### Portable archive ### Portable archive
```bash ```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst sudo tar --zstd -C / -xf ./uur-0.1.7-linux-x86_64.tar.zst
``` ```
### Nix and NixOS ### Nix and NixOS
@@ -126,6 +126,7 @@ An `APKBUILD` is included under `packaging/alpine/`.
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
./scripts/install-user.sh ./scripts/install-user.sh
``` ```
@@ -151,9 +152,25 @@ uur autostart disable # Remove the managed login entry
uur wol status # Inspect the physical wired adapter's WOL state uur wol status # Inspect the physical wired adapter's WOL state
uur display status # Monitor, window, or portal virtual source uur display status # Monitor, window, or portal virtual source
uur display source virtual uur display source virtual
uur display outputs # Native Wayland output names
uur stop # Stop only uur's helpers and Wine prefix uur stop # Stop only uur's helpers and Wine prefix
uur uninstall --purge --dry-run # Preview complete user-data cleanup
uur uninstall --purge # Confirm cleanup before removing the system package
``` ```
If UU was started from the desktop, choose **Quit** from the launcher's
application actions. When running from a terminal, use `uur stop` or press
Ctrl+C.
On niri, uur provides a native tray and an explicitly enabled direct capture
path: `uur display backend wayland --output DP-1` (use your output name).
This uses uinput and captures the chosen monitor without a portal dialog.
Return to system-consented capture with `uur display backend portal`.
Package removal alone preserves the Wine prefix and account data. See
[complete removal](docs/distribution.md#package-removal-repair-and-per-user-state)
for the user-cleanup and package-manager steps.
Diagnostic input overrides: Diagnostic input overrides:
```bash ```bash
+20 -5
View File
@@ -66,7 +66,7 @@ uur run
使用 pacman 安装下载的正式发布包: 使用 pacman 安装下载的正式发布包:
```bash ```bash
sudo pacman -U ./dist/uur-0.1.3-1-x86_64.pkg.tar.zst sudo pacman -U ./dist/uur-0.1.7-1-x86_64.pkg.tar.zst
``` ```
### AUR ### AUR
@@ -80,13 +80,13 @@ paru -S uur
### Debian、Ubuntu 及兼容发行版 ### Debian、Ubuntu 及兼容发行版
```bash ```bash
sudo apt install ./uur_0.1.3_amd64.deb sudo apt install ./uur_0.1.7_amd64.deb
``` ```
### Fedora 及兼容 RPM 发行版 ### Fedora 及兼容 RPM 发行版
```bash ```bash
sudo dnf install ./uur-0.1.3-1.x86_64.rpm sudo dnf install ./uur-0.1.7-1.x86_64.rpm
``` ```
如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。 如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。
@@ -94,7 +94,7 @@ sudo dnf install ./uur-0.1.3-1.x86_64.rpm
### 通用压缩包 ### 通用压缩包
```bash ```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst sudo tar --zstd -C / -xf ./uur-0.1.7-linux-x86_64.tar.zst
``` ```
### Nix 与 NixOS ### Nix 与 NixOS
@@ -122,10 +122,11 @@ docker build -f packaging/alpine/Dockerfile .
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
./scripts/install-user.sh ./scripts/install-user.sh
``` ```
源码构建需要 Rust、C 编译器、PipeWire 开发文件、`pkg-config` 和 MinGW-w64 x86_64 源码构建需要 Rust、C 编译器、PipeWire 与 Wayland 开发文件(含 `wayland-scanner`)、`pkg-config` 和 MinGW-w64 x86_64
工具链。 工具链。
Gentoo、Void Linux、Slackware、Solus、ALT Linux、Exherbo、Clear Linux、Mageia、 Gentoo、Void Linux、Slackware、Solus、ALT Linux、Exherbo、Clear Linux、Mageia、
@@ -146,9 +147,23 @@ uur autostart disable # 删除受管登录自启动项
uur wol status # 检查物理有线网卡的 WOL 状态 uur wol status # 检查物理有线网卡的 WOL 状态
uur display status # 查看显示器、窗口或 Portal 虚拟源设置 uur display status # 查看显示器、窗口或 Portal 虚拟源设置
uur display source virtual uur display source virtual
uur display outputs # 查看原生 Wayland 显示器名称
uur stop # 只停止 uur 助手与专用 Wine 前缀 uur stop # 只停止 uur 助手与专用 Wine 前缀
uur uninstall --purge --dry-run # 预览完整用户数据清理范围
uur uninstall --purge # 确认清理后,再用包管理器卸载系统包
``` ```
从桌面启动 UU 后,可在启动器的应用操作菜单中选择“退出”;从终端运行时可执行
`uur stop` 或按 Ctrl+C。
niri 可使用原生托盘,并明确启用直接采集:先运行 `uur display outputs` 查看名称,再运行
`uur display backend wayland --output DP-1`(替换为自己的名称)。此模式使用 uinput,
直接采集指定显示器,不弹出 Portal 授权框;`uur display backend portal` 可恢复系统授权采集。
仅用包管理器卸载会保留 Wine 环境和账号数据。完整卸载请先以当前用户身份运行
`uur uninstall --purge`,再执行 `sudo pacman -Rns uur`(Arch);其他发行版使用
对应的包管理器。详见[完整卸载说明](docs/distribution.md#package-removal-repair-and-per-user-state)。
输入后端排错: 输入后端排错:
```bash ```bash
+12
View File
@@ -15,3 +15,15 @@ command -v "$cc" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$cc" >&2; exi
$(pkg-config --cflags --libs libpipewire-0.3) $(pkg-config --cflags --libs libpipewire-0.3)
printf 'built: %s\n' "$out/uur-pw-capture" printf 'built: %s\n' "$out/uur-pw-capture"
generated="$root/build/capture"
mkdir -p "$generated"
wayland-scanner client-header "$root/capture/wlr-screencopy-unstable-v1.xml" \
"$generated/wlr-screencopy-unstable-v1-client-protocol.h"
wayland-scanner private-code "$root/capture/wlr-screencopy-unstable-v1.xml" \
"$generated/wlr-screencopy-unstable-v1-protocol.c"
"$cc" "${flags[@]}" -I"$generated" -o "$out/uur-wl-capture" \
"$root/capture/uur-wl-capture.c" \
"$generated/wlr-screencopy-unstable-v1-protocol.c" \
$(pkg-config --cflags --libs wayland-client)
printf 'built: %s\n' "$out/uur-wl-capture"
+709 -133
View File
File diff suppressed because it is too large. Load diff
+350
View File
@@ -0,0 +1,350 @@
/* Direct Wayland monitor capture, explicitly enabled by the user.
* Uses compositor-provided wl_shm buffers; no GBM, portal or GPU import is
* required. Frames use the same private UURF transport as PipeWire capture.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <wayland-client.h>
#include "wlr-screencopy-unstable-v1-client-protocol.h"
#include "../hook/frame-protocol.h"
struct frame_header {
uint32_t magic, version, width, height, stride, format;
_Atomic uint64_t total_frames;
uint32_t flags, monitor_count;
uint8_t reserved[24];
struct uurf_monitor_layout monitors[UURF_MAX_MONITORS];
};
_Static_assert(sizeof(struct frame_header) == UURF_HEADER_BYTES, "frame header ABI");
struct output {
struct wl_output *proxy;
uint32_t global;
char name[128];
int32_t width, height;
};
struct capture {
struct wl_display *display;
struct wl_registry *registry;
struct wl_shm *shm;
struct zwlr_screencopy_manager_v1 *manager;
struct output outputs[64];
size_t output_count;
struct output *selected;
struct zwlr_screencopy_frame_v1 *frame;
struct wl_buffer *buffer;
void *pixels;
size_t pixels_size;
uint32_t width, height, stride, format, flags;
int done, failed;
int ring_fd;
void *ring;
size_t ring_size;
uint32_t ring_width, ring_height;
uint64_t counter;
const char *frame_path;
};
static volatile sig_atomic_t stopping;
static void stop_capture(int signum) { (void)signum; stopping = 1; }
static void output_geometry(void *data, struct wl_output *output, int32_t x,
int32_t y, int32_t physical_width, int32_t physical_height, int32_t subpixel,
const char *make, const char *model, int32_t transform)
{
(void)data; (void)output; (void)x; (void)y; (void)physical_width;
(void)physical_height; (void)subpixel; (void)make; (void)model; (void)transform;
}
static void output_mode(void *data, struct wl_output *output, uint32_t flags,
int32_t width, int32_t height, int32_t refresh)
{
(void)output; (void)refresh;
struct output *o = data;
if (flags & WL_OUTPUT_MODE_CURRENT) { o->width = width; o->height = height; }
}
static void output_done(void *data, struct wl_output *output) { (void)data; (void)output; }
static void output_scale(void *data, struct wl_output *output, int32_t scale)
{ (void)data; (void)output; (void)scale; }
static void output_name(void *data, struct wl_output *output, const char *name)
{ (void)output; snprintf(((struct output *)data)->name, 128, "%s", name); }
static void output_description(void *data, struct wl_output *output, const char *description)
{ (void)data; (void)output; (void)description; }
static const struct wl_output_listener output_listener = {
.geometry = output_geometry, .mode = output_mode, .done = output_done,
.scale = output_scale, .name = output_name, .description = output_description,
};
static void registry_global(void *data, struct wl_registry *registry, uint32_t name,
const char *interface, uint32_t version)
{
struct capture *c = data;
if (!strcmp(interface, wl_shm_interface.name)) {
c->shm = wl_registry_bind(registry, name, &wl_shm_interface, 1);
} else if (!strcmp(interface, zwlr_screencopy_manager_v1_interface.name)) {
c->manager = wl_registry_bind(registry, name,
&zwlr_screencopy_manager_v1_interface, version < 3 ? version : 3);
} else if (!strcmp(interface, wl_output_interface.name) && c->output_count < 64) {
struct output *o = &c->outputs[c->output_count++];
o->global = name;
o->proxy = wl_registry_bind(registry, name, &wl_output_interface, version < 4 ? version : 4);
wl_output_add_listener(o->proxy, &output_listener, o);
}
}
static void registry_remove(void *data, struct wl_registry *registry, uint32_t name)
{
(void)registry;
struct capture *c = data;
if (c->selected != NULL && c->selected->global == name) {
fprintf(stderr, "captured output disconnected\n");
c->failed = 1; stopping = 1;
}
}
static const struct wl_registry_listener registry_listener = {
.global = registry_global, .global_remove = registry_remove,
};
static int setup_ring(struct capture *c)
{
if (c->ring != NULL) {
if (c->ring_width == c->width && c->ring_height == c->height) return 0;
fprintf(stderr, "capture geometry changed; restart uur run\n");
return -1;
}
size_t bytes = (size_t)c->width * 4 * c->height;
c->ring_size = UURF_HEADER_BYTES + UURF_SLOT_COUNT * (sizeof(uint64_t) + bytes);
c->ring_fd = open(c->frame_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);
if (c->ring_fd < 0 || fchmod(c->ring_fd, 0600) < 0 ||
ftruncate(c->ring_fd, (off_t)c->ring_size) < 0) { perror("frame transport"); return -1; }
c->ring = mmap(NULL, c->ring_size, PROT_READ | PROT_WRITE, MAP_SHARED, c->ring_fd, 0);
if (c->ring == MAP_FAILED) { c->ring = NULL; perror("frame mmap"); return -1; }
c->ring_width = c->width; c->ring_height = c->height;
struct frame_header *header = c->ring;
memset(header, 0, sizeof(*header));
header->magic = UURF_MAGIC; header->version = UURF_VERSION;
header->width = c->width; header->height = c->height;
header->stride = c->width * 4; header->format = 1;
atomic_init(&header->total_frames, 0);
header->flags = 0;
header->monitor_count = 1;
header->monitors[0].logical_x = 0;
header->monitors[0].logical_y = 0;
header->monitors[0].logical_width = c->width;
header->monitors[0].logical_height = c->height;
header->monitors[0].frame_x = 0;
header->monitors[0].frame_y = 0;
header->monitors[0].frame_width = c->width;
header->monitors[0].frame_height = c->height;
header->monitors[0].capture_width = c->width;
header->monitors[0].capture_height = c->height;
for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) {
_Atomic uint64_t *seq = (_Atomic uint64_t *)((uint8_t *)c->ring +
UURF_HEADER_BYTES + i * (sizeof(uint64_t) + bytes));
atomic_init(seq, 0);
}
fprintf(stderr, "Wayland output %s: %ux%u\n", c->selected->name, c->width, c->height);
return 0;
}
static int supported_format(uint32_t format)
{
return format == WL_SHM_FORMAT_XRGB8888 || format == WL_SHM_FORMAT_ARGB8888 ||
format == WL_SHM_FORMAT_XBGR8888 || format == WL_SHM_FORMAT_ABGR8888 ||
format == WL_SHM_FORMAT_XRGB2101010 || format == WL_SHM_FORMAT_ARGB2101010 ||
format == WL_SHM_FORMAT_XBGR2101010 || format == WL_SHM_FORMAT_ABGR2101010;
}
static int submit_buffer(struct capture *c)
{
if (!supported_format(c->format) || c->width == 0 || c->height == 0 ||
c->width > 16384 || c->height > 16384 || c->stride < c->width * 4 ||
(uint64_t)c->stride * c->height > 256u * 1024 * 1024) {
fprintf(stderr, "unsupported Wayland SHM format or geometry\n");
return -1;
}
if (setup_ring(c) < 0) return -1;
c->pixels_size = (size_t)c->stride * c->height;
int fd = memfd_create("uur-wayland-frame", MFD_CLOEXEC);
if (fd < 0) { perror("memfd_create"); return -1; }
if (ftruncate(fd, (off_t)c->pixels_size) < 0) { close(fd); return -1; }
c->pixels = mmap(NULL, c->pixels_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (c->pixels == MAP_FAILED) { c->pixels = NULL; close(fd); return -1; }
struct wl_shm_pool *pool = wl_shm_create_pool(c->shm, fd, (int32_t)c->pixels_size);
c->buffer = wl_shm_pool_create_buffer(pool, 0, (int32_t)c->width,
(int32_t)c->height, (int32_t)c->stride, c->format);
wl_shm_pool_destroy(pool); close(fd);
zwlr_screencopy_frame_v1_copy(c->frame, c->buffer);
return 0;
}
static void frame_buffer(void *data, struct zwlr_screencopy_frame_v1 *frame,
uint32_t format, uint32_t width, uint32_t height, uint32_t stride)
{
struct capture *c = data;
c->format = format; c->width = width; c->height = height; c->stride = stride;
if (zwlr_screencopy_frame_v1_get_version(frame) < 3 && submit_buffer(c) < 0) {
c->done = 1; c->failed = 1;
}
}
static void frame_buffer_done(void *data, struct zwlr_screencopy_frame_v1 *frame)
{
(void)frame;
struct capture *c = data;
if (submit_buffer(c) < 0) { c->done = 1; c->failed = 1; }
}
static void frame_flags(void *data, struct zwlr_screencopy_frame_v1 *frame, uint32_t flags)
{ (void)frame; ((struct capture *)data)->flags = flags; }
static void frame_ready(void *data, struct zwlr_screencopy_frame_v1 *frame,
uint32_t hi, uint32_t lo, uint32_t ns)
{ (void)frame; (void)hi; (void)lo; (void)ns; ((struct capture *)data)->done = 1; }
static void frame_failed(void *data, struct zwlr_screencopy_frame_v1 *frame)
{ (void)frame; struct capture *c = data; c->done = 1; c->failed = 1; }
static void frame_damage(void *data, struct zwlr_screencopy_frame_v1 *frame,
uint32_t x, uint32_t y, uint32_t width, uint32_t height)
{ (void)data; (void)frame; (void)x; (void)y; (void)width; (void)height; }
static void frame_dmabuf(void *data, struct zwlr_screencopy_frame_v1 *frame,
uint32_t format, uint32_t width, uint32_t height)
{ (void)data; (void)frame; (void)format; (void)width; (void)height; }
static const struct zwlr_screencopy_frame_v1_listener frame_listener = {
.buffer = frame_buffer, .flags = frame_flags, .ready = frame_ready,
.failed = frame_failed, .damage = frame_damage,
.linux_dmabuf = frame_dmabuf, .buffer_done = frame_buffer_done,
};
static void publish_frame(struct capture *c)
{
size_t bytes = (size_t)c->width * 4 * c->height;
uint64_t n = ++c->counter;
_Atomic uint64_t *seq = (_Atomic uint64_t *)((uint8_t *)c->ring +
uurf_slot_offset(n, sizeof(uint64_t) + bytes));
uint8_t *dest = (uint8_t *)seq + sizeof(uint64_t);
atomic_store_explicit(seq, 2 * n - 1, memory_order_release);
int rgb = c->format == WL_SHM_FORMAT_XBGR8888 || c->format == WL_SHM_FORMAT_ABGR8888;
int ten = c->format == WL_SHM_FORMAT_XRGB2101010 || c->format == WL_SHM_FORMAT_ARGB2101010 ||
c->format == WL_SHM_FORMAT_XBGR2101010 || c->format == WL_SHM_FORMAT_ABGR2101010;
int ten_bgr = c->format == WL_SHM_FORMAT_XBGR2101010 || c->format == WL_SHM_FORMAT_ABGR2101010;
for (uint32_t y = 0; y < c->height; ++y) {
uint32_t row = c->flags & ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT ? c->height - y - 1 : y;
const uint8_t *src = (const uint8_t *)c->pixels + (size_t)row * c->stride;
uint8_t *dst = dest + (size_t)y * c->width * 4;
for (uint32_t x = 0; x < c->width; ++x, src += 4, dst += 4) {
if (ten) {
uint32_t value; memcpy(&value, src, 4);
dst[0] = (uint8_t)((((value >> (ten_bgr ? 20 : 0)) & 1023) * 255 + 511) / 1023);
dst[1] = (uint8_t)((((value >> 10) & 1023) * 255 + 511) / 1023);
dst[2] = (uint8_t)((((value >> (ten_bgr ? 0 : 20)) & 1023) * 255 + 511) / 1023);
} else {
dst[0] = src[rgb ? 2 : 0]; dst[1] = src[1]; dst[2] = src[rgb ? 0 : 2];
}
dst[3] = 0;
}
}
atomic_store_explicit(seq, 2 * n, memory_order_release);
atomic_store_explicit(&((struct frame_header *)c->ring)->total_frames, n, memory_order_release);
}
static int dispatch(struct capture *c)
{
while (wl_display_prepare_read(c->display) != 0) {
if (wl_display_dispatch_pending(c->display) < 0) return -1;
if (c->done || c->failed || stopping) return 0;
}
if (wl_display_flush(c->display) < 0 && errno != EAGAIN) {
wl_display_cancel_read(c->display); return -1;
}
struct pollfd fd = { .fd = wl_display_get_fd(c->display), .events = POLLIN };
int rc = poll(&fd, 1, 10000);
if (rc <= 0 || !(fd.revents & POLLIN)) {
wl_display_cancel_read(c->display);
if (rc == 0) fprintf(stderr, "Wayland capture frame timed out\n");
return stopping ? 0 : -1;
}
if (wl_display_read_events(c->display) < 0) return -1;
return wl_display_dispatch_pending(c->display);
}
static void clear_frame(struct capture *c)
{
if (c->frame != NULL) { zwlr_screencopy_frame_v1_destroy(c->frame); c->frame = NULL; }
if (c->buffer != NULL) { wl_buffer_destroy(c->buffer); c->buffer = NULL; }
if (c->pixels != NULL) { munmap(c->pixels, c->pixels_size); c->pixels = NULL; }
c->pixels_size = 0; c->width = c->height = c->stride = c->format = c->flags = 0;
}
int main(int argc, char **argv)
{
struct capture c = { .ring_fd = -1 };
int list = argc == 2 && !strcmp(argv[1], "--list-outputs");
if (argc > 1 && !list) { fprintf(stderr, "usage: uur-wl-capture [--list-outputs]\n"); return 2; }
c.frame_path = getenv("UUR_FRAME_PATH");
if (!list && (c.frame_path == NULL || c.frame_path[0] != '/')) {
fprintf(stderr, "UUR_FRAME_PATH must name the private absolute frame transport\n"); return 2;
}
struct sigaction sa = { .sa_handler = stop_capture };
sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL);
c.display = wl_display_connect(NULL);
if (c.display == NULL) { fprintf(stderr, "cannot connect to Wayland display\n"); return 1; }
c.registry = wl_display_get_registry(c.display);
wl_registry_add_listener(c.registry, &registry_listener, &c);
if (wl_display_roundtrip(c.display) < 0 || wl_display_roundtrip(c.display) < 0) {
c.failed = 1; goto cleanup;
}
if (list) {
for (size_t i = 0; i < c.output_count; ++i) {
printf("%s %dx%d\n", c.outputs[i].name, c.outputs[i].width, c.outputs[i].height);
}
goto cleanup;
}
if (c.manager == NULL || c.shm == NULL) {
fprintf(stderr, "compositor does not expose wlr-screencopy with wl_shm buffers\n");
c.failed = 1; goto cleanup;
}
const char *name = getenv("UUR_CAPTURE_OUTPUT");
if (name != NULL && name[0] != '\0') {
for (size_t i = 0; i < c.output_count; ++i) {
if (!strcmp(name, c.outputs[i].name)) c.selected = &c.outputs[i];
}
} else if (c.output_count == 1) { c.selected = &c.outputs[0]; }
if (c.selected == NULL) {
fprintf(stderr, "select one output with uur display backend wayland --output NAME:\n");
for (size_t i = 0; i < c.output_count; ++i) fprintf(stderr, " %s\n", c.outputs[i].name);
c.failed = 1; goto cleanup;
}
while (!stopping && !c.failed) {
c.done = 0;
c.frame = zwlr_screencopy_manager_v1_capture_output(c.manager, 1, c.selected->proxy);
zwlr_screencopy_frame_v1_add_listener(c.frame, &frame_listener, &c);
while (!c.done && !stopping) {
if (dispatch(&c) < 0) { c.failed = 1; break; }
}
if (c.done && !c.failed && !stopping) publish_frame(&c);
clear_frame(&c);
struct timespec delay = { .tv_nsec = 33333333 };
nanosleep(&delay, NULL);
}
cleanup:
clear_frame(&c);
if (c.ring != NULL) munmap(c.ring, c.ring_size);
if (c.ring_fd >= 0) {
struct stat created, present;
if (fstat(c.ring_fd, &created) == 0 && lstat(c.frame_path, &present) == 0 &&
created.st_dev == present.st_dev && created.st_ino == present.st_ino) unlink(c.frame_path);
close(c.ring_fd);
}
for (size_t i = 0; i < c.output_count; ++i) wl_output_destroy(c.outputs[i].proxy);
if (c.manager != NULL) zwlr_screencopy_manager_v1_destroy(c.manager);
if (c.shm != NULL) wl_shm_destroy(c.shm);
wl_registry_destroy(c.registry); wl_display_disconnect(c.display);
return c.failed ? 1 : 0;
}
+232
View File
@@ -0,0 +1,232 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_screencopy_unstable_v1">
<copyright>
Copyright © 2018 Simon Ser
Copyright © 2019 Andri Yngvason
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<description summary="screen content capturing on client buffers">
This protocol allows clients to ask the compositor to copy part of the
screen content to a client buffer.
Warning! The protocol described in this file is experimental and
backward incompatible changes may be made. Backward compatible changes
may be added together with the corresponding interface version bump.
Backward incompatible changes are done by bumping the version number in
the protocol and interface names and resetting the interface version.
Once the protocol is to be declared stable, the 'z' prefix and the
version number in the protocol and interface names are removed and the
interface version number is reset.
</description>
<interface name="zwlr_screencopy_manager_v1" version="3">
<description summary="manager to inform clients and begin capturing">
This object is a manager which offers requests to start capturing from a
source.
</description>
<request name="capture_output">
<description summary="capture an output">
Capture the next frame of an entire output.
</description>
<arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
<arg name="overlay_cursor" type="int"
summary="composite cursor onto the frame"/>
<arg name="output" type="object" interface="wl_output"/>
</request>
<request name="capture_output_region">
<description summary="capture an output's region">
Capture the next frame of an output's region.
The region is given in output logical coordinates, see
xdg_output.logical_size. The region will be clipped to the output's
extents.
</description>
<arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
<arg name="overlay_cursor" type="int"
summary="composite cursor onto the frame"/>
<arg name="output" type="object" interface="wl_output"/>
<arg name="x" type="int"/>
<arg name="y" type="int"/>
<arg name="width" type="int"/>
<arg name="height" type="int"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the manager">
All objects created by the manager will still remain valid, until their
appropriate destroy request has been called.
</description>
</request>
</interface>
<interface name="zwlr_screencopy_frame_v1" version="3">
<description summary="a frame ready for copy">
This object represents a single frame.
When created, a series of buffer events will be sent, each representing a
supported buffer type. The "buffer_done" event is sent afterwards to
indicate that all supported buffer types have been enumerated. The client
will then be able to send a "copy" request. If the capture is successful,
the compositor will send a "flags" followed by a "ready" event.
For objects version 2 or lower, wl_shm buffers are always supported, ie.
the "buffer" event is guaranteed to be sent.
If the capture failed, the "failed" event is sent. This can happen anytime
before the "ready" event.
Once either a "ready" or a "failed" event is received, the client should
destroy the frame.
</description>
<event name="buffer">
<description summary="wl_shm buffer information">
Provides information about wl_shm buffer parameters that need to be
used for this frame. This event is sent once after the frame is created
if wl_shm buffers are supported.
</description>
<arg name="format" type="uint" enum="wl_shm.format" summary="buffer format"/>
<arg name="width" type="uint" summary="buffer width"/>
<arg name="height" type="uint" summary="buffer height"/>
<arg name="stride" type="uint" summary="buffer stride"/>
</event>
<request name="copy">
<description summary="copy the frame">
Copy the frame to the supplied buffer. The buffer must have a the
correct size, see zwlr_screencopy_frame_v1.buffer and
zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a
supported format.
If the frame is successfully copied, a "flags" and a "ready" events are
sent. Otherwise, a "failed" event is sent.
</description>
<arg name="buffer" type="object" interface="wl_buffer"/>
</request>
<enum name="error">
<entry name="already_used" value="0"
summary="the object has already been used to copy a wl_buffer"/>
<entry name="invalid_buffer" value="1"
summary="buffer attributes are invalid"/>
</enum>
<enum name="flags" bitfield="true">
<entry name="y_invert" value="1" summary="contents are y-inverted"/>
</enum>
<event name="flags">
<description summary="frame flags">
Provides flags about the frame. This event is sent once before the
"ready" event.
</description>
<arg name="flags" type="uint" enum="flags" summary="frame flags"/>
</event>
<event name="ready">
<description summary="indicates frame is available for reading">
Called as soon as the frame is copied, indicating it is available
for reading. This event includes the time at which presentation happened
at.
The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,
each component being an unsigned 32-bit value. Whole seconds are in
tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,
and the additional fractional part in tv_nsec as nanoseconds. Hence,
for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part
may have an arbitrary offset at start.
After receiving this event, the client should destroy the object.
</description>
<arg name="tv_sec_hi" type="uint"
summary="high 32 bits of the seconds part of the timestamp"/>
<arg name="tv_sec_lo" type="uint"
summary="low 32 bits of the seconds part of the timestamp"/>
<arg name="tv_nsec" type="uint"
summary="nanoseconds part of the timestamp"/>
</event>
<event name="failed">
<description summary="frame copy failed">
This event indicates that the attempted frame copy has failed.
After receiving this event, the client should destroy the object.
</description>
</event>
<request name="destroy" type="destructor">
<description summary="delete this object, used or not">
Destroys the frame. This request can be sent at any time by the client.
</description>
</request>
<!-- Version 2 additions -->
<request name="copy_with_damage" since="2">
<description summary="copy the frame when it's damaged">
Same as copy, except it waits until there is damage to copy.
</description>
<arg name="buffer" type="object" interface="wl_buffer"/>
</request>
<event name="damage" since="2">
<description summary="carries the coordinates of the damaged region">
This event is sent right before the ready event when copy_with_damage is
requested. It may be generated multiple times for each copy_with_damage
request.
The arguments describe a box around an area that has changed since the
last copy request that was derived from the current screencopy manager
instance.
The union of all regions received between the call to copy_with_damage
and a ready event is the total damage since the prior ready event.
</description>
<arg name="x" type="uint" summary="damaged x coordinates"/>
<arg name="y" type="uint" summary="damaged y coordinates"/>
<arg name="width" type="uint" summary="current width"/>
<arg name="height" type="uint" summary="current height"/>
</event>
<!-- Version 3 additions -->
<event name="linux_dmabuf" since="3">
<description summary="linux-dmabuf buffer information">
Provides information about linux-dmabuf buffer parameters that need to
be used for this frame. This event is sent once after the frame is
created if linux-dmabuf buffers are supported.
</description>
<arg name="format" type="uint" summary="fourcc pixel format"/>
<arg name="width" type="uint" summary="buffer width"/>
<arg name="height" type="uint" summary="buffer height"/>
</event>
<event name="buffer_done" since="3">
<description summary="all buffer types reported">
This event is sent once after all buffer events have been sent.
The client should proceed to create a buffer of one of the supported
types, and send a "copy" request.
</description>
</event>
</interface>
</protocol>
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Build the Wine lock-modifier shim (LD_PRELOAD, links libX11).
set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)
readonly root
out="$root/build/compat"
cc="${CC:-gcc}"
flags=(-std=c11 -O2 -Wall -Wextra -Werror -fPIC -pthread)
command -v "$cc" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$cc" >&2; exit 1; }
command -v pkg-config >/dev/null 2>&1 || { printf 'missing tool: pkg-config\n' >&2; exit 1; }
mkdir -p "$out"
"$cc" "${flags[@]}" -shared -o "$out/libuur-lock-mods.so" \
"$root/compat/uur-lock-mods.c" \
$(pkg-config --cflags --libs x11) -ldl
printf 'built: %s\n' "$out/libuur-lock-mods.so"
+193
View File
@@ -0,0 +1,193 @@
/* Process-local workaround for Wine/UU lock-key reconciliation. */
#define _GNU_SOURCE
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include <X11/keysym.h>
#include <dlfcn.h>
#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef Bool (*predicate_fn)(Display *, XEvent *, XPointer);
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
static unsigned int requested_mask;
static int enabled;
static _Atomic unsigned long generation = 1;
static _Thread_local Display *cached_display;
static _Thread_local unsigned long cached_generation;
static _Thread_local unsigned int cached_mask;
#define EVENT_FUNCTIONS(X) \
X(int, XNextEvent, (Display *d, XEvent *e), (d, e), rc == 0) \
X(int, XPeekEvent, (Display *d, XEvent *e), (d, e), rc == 0) \
X(int, XWindowEvent, (Display *d, Window w, long m, XEvent *e), (d, w, m, e), rc == 0) \
X(Bool, XCheckWindowEvent, (Display *d, Window w, long m, XEvent *e), (d, w, m, e), rc != 0) \
X(int, XMaskEvent, (Display *d, long m, XEvent *e), (d, m, e), rc == 0) \
X(Bool, XCheckMaskEvent, (Display *d, long m, XEvent *e), (d, m, e), rc != 0) \
X(Bool, XCheckTypedEvent, (Display *d, int t, XEvent *e), (d, t, e), rc != 0) \
X(Bool, XCheckTypedWindowEvent, (Display *d, Window w, int t, XEvent *e), (d, w, t, e), rc != 0) \
X(int, XIfEvent, (Display *d, XEvent *e, predicate_fn p, XPointer a), (d, e, p, a), rc == 0) \
X(int, XPeekIfEvent, (Display *d, XEvent *e, predicate_fn p, XPointer a), (d, e, p, a), rc == 0) \
X(Bool, XCheckIfEvent, (Display *d, XEvent *e, predicate_fn p, XPointer a), (d, e, p, a), rc != 0)
#define DECLARE(result, name, args, call, success) static result (*real_##name) args;
EVENT_FUNCTIONS(DECLARE)
#undef DECLARE
static int (*real_XRefreshKeyboardMapping)(XMappingEvent *);
static Status (*real_XkbRefreshKeyboardMapping)(XkbMapNotifyEvent *);
static int (*real_XCloseDisplay)(Display *);
static void *symbol(const char *name)
{
void *address = dlsym(RTLD_NEXT, name);
if (address == NULL) {
fprintf(stderr, "uur keyboard compatibility: cannot resolve %s\n", name);
abort();
}
return address;
}
static int wine_process(void)
{
char executable[PATH_MAX];
ssize_t size = readlink("/proc/self/exe", executable, sizeof(executable) - 1);
if (size <= 0 || (size_t)size >= sizeof(executable) - 1)
return 0;
executable[size] = '\0';
char *deleted = strstr(executable, " (deleted)");
if (deleted != NULL)
*deleted = '\0';
char *name = strrchr(executable, '/');
name = name == NULL ? executable : name + 1;
if (*name == '.')
name++;
char *wrapped = strstr(name, "-wrapped");
if (wrapped != NULL && wrapped[8] == '\0')
*wrapped = '\0';
return !strcmp(name, "wine") || !strcmp(name, "wine64") ||
!strcmp(name, "wine-preloader") || !strcmp(name, "wine64-preloader") ||
!strcmp(name, "wineserver");
}
static void initialize(void)
{
#define RESOLVE(result, name, args, call, success) real_##name = symbol(#name);
EVENT_FUNCTIONS(RESOLVE)
#undef RESOLVE
real_XRefreshKeyboardMapping = symbol("XRefreshKeyboardMapping");
real_XkbRefreshKeyboardMapping = symbol("XkbRefreshKeyboardMapping");
real_XCloseDisplay = symbol("XCloseDisplay");
if (getenv("WINEPREFIX") == NULL || !wine_process())
return;
const char *mask = getenv("UUR_STRIP_LOCK_MODS");
requested_mask = 0xff;
if (mask != NULL && strcmp(mask, "auto")) {
char *end;
errno = 0;
unsigned long value = strtoul(mask, &end,
mask[0] == '0' && (mask[1] == 'x' || mask[1] == 'X') ? 16 : 10);
if (errno || end == mask || *end != '\0' || value > 0xff) {
fprintf(stderr, "uur keyboard compatibility: invalid modifier mask\n");
return;
}
requested_mask = (unsigned int)value;
}
enabled = requested_mask != 0;
}
/* A modifier shared with a shortcut/layout key is left alone. CapsLock and
* ShiftLock are never removed: their state affects character translation. */
static unsigned int locking_mask(Display *display)
{
unsigned long current = atomic_load_explicit(&generation, memory_order_relaxed);
if (cached_display == display && cached_generation == current)
return cached_mask;
unsigned int mask = 0;
XModifierKeymap *mapping = XGetModifierMapping(display);
if (mapping != NULL) {
for (int modifier = 3; modifier < 8; ++modifier) {
int locking = 0, other = 0;
for (int key = 0; key < mapping->max_keypermod; ++key) {
KeyCode code = mapping->modifiermap[modifier * mapping->max_keypermod + key];
if (code == 0)
continue;
int lock_key = 0;
for (int level = 0; level < 4; ++level) {
KeySym sym = XkbKeycodeToKeysym(display, code, 0, level);
if (sym == XK_Num_Lock || sym == XK_Scroll_Lock)
lock_key = 1;
else if (sym != NoSymbol)
other = 1;
}
if (lock_key)
locking = 1;
else
other = 1;
}
if (locking && !other)
mask |= 1u << modifier;
}
XFreeModifiermap(mapping);
}
cached_display = display;
cached_generation = current;
cached_mask = mask & requested_mask;
return cached_mask;
}
static void scrub(Display *display, XEvent *event)
{
if (!enabled || event == NULL)
return;
if (event->type == MappingNotify) {
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return;
}
if (event->type != KeyPress && event->type != KeyRelease)
return;
/* NumLock changes keypad virtual keys in EVENT_event_to_vkey(). Leave
* those events intact rather than turning numeric input into navigation. */
KeySym key = XkbKeycodeToKeysym(display, event->xkey.keycode, 0, 0);
if (IsKeypadKey(key))
return;
event->xkey.state &= ~locking_mask(display);
}
#define IMPLEMENT(result, name, args, call, success) \
result name args { \
pthread_once(&init_once, initialize); \
result rc = real_##name call; \
if (success) scrub(d, e); \
return rc; \
}
EVENT_FUNCTIONS(IMPLEMENT)
#undef IMPLEMENT
int XRefreshKeyboardMapping(XMappingEvent *event)
{
pthread_once(&init_once, initialize);
int result = real_XRefreshKeyboardMapping(event);
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return result;
}
Status XkbRefreshKeyboardMapping(XkbMapNotifyEvent *event)
{
pthread_once(&init_once, initialize);
Status result = real_XkbRefreshKeyboardMapping(event);
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return result;
}
int XCloseDisplay(Display *display)
{
pthread_once(&init_once, initialize);
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return real_XCloseDisplay(display);
}
+2 -2
View File
@@ -6,7 +6,7 @@ adapts stable Windows APIs at runtime; the Rust host owns policy, desktop
integration, and process lifetime. integration, and process lifetime.
```text ```text
UU Remote / Wine UU Remote / Wine (LD_PRELOAD: compat/libuur-lock-mods.so)
└─ PE ABI adapter (SendInput, GDI/DXGI capture entry points) └─ PE ABI adapter (SendInput, GDI/DXGI capture entry points)
└─ authenticated loopback protocol + private frame transport └─ authenticated loopback protocol + private frame transport
└─ Rust session supervisor └─ Rust session supervisor
@@ -62,7 +62,7 @@ RAII cleanup terminates only those helper groups and the one managed Wine
prefix. There are no permanent daemons, global `pkill` calls, or required prefix. There are no permanent daemons, global `pkill` calls, or required
systemd units. systemd units.
Frame data lives in `$XDG_RUNTIME_DIR/uur/frames.v1` with mode 0600. The path is Frame data lives in `$XDG_RUNTIME_DIR/uur/frames.v3` with mode 0600. The path is
passed through the adapter configuration, so users and concurrent sessions do passed through the adapter configuration, so users and concurrent sessions do
not share a global `/dev/shm` object. not share a global `/dev/shm` object.
+80 -8
View File
@@ -1,16 +1,18 @@
# Capture frame protocol # Capture frame protocol
How frames travel from the compositor (via PipeWire) into the client's How frames travel from the compositor (via PipeWire) into the client's
capture calls. Two producers/consumers, one shared file, no locks. capture calls. Multiple selected monitor streams are composed into one virtual
desktop frame in the shared transport; the Windows hook crops each monitor
request from that frame.
```text ```text
xdg-desktop-portal ScreenCast xdg-desktop-portal ScreenCast
│ (portal-consented session; per-monitor) │ (portal-consented session; one stream per selected monitor)
▼ ▼
uur-pw-capture (C) ── PipeWire stream, BGRx, SHM buffers uur-pw-capture (C) ── PipeWire streams, BGRx, desktop composition
│ writes slots, seqlock per slot │ writes slots, seqlock per slot
▼ ▼
$XDG_RUNTIME_DIR/uur/frames.v1 (mode 0600, 64-byte header + 3 slots) $XDG_RUNTIME_DIR/uur/frames.v3 (mode 0600, 704-byte header + 3 slots)
│ mapped read-only by the PE hook through its configured Wine Z: path │ mapped read-only by the PE hook through its configured Wine Z: path
▼ ▼
uur-hook.dll ── intercepts static/dynamic gdi32!BitBlt/StretchBlt calls; uur-hook.dll ── intercepts static/dynamic gdi32!BitBlt/StretchBlt calls;
@@ -19,20 +21,31 @@ uur-hook.dll ── intercepts static/dynamic gdi32!BitBlt/StretchBlt calls;
## Shared file layout ## Shared file layout
All integers little-endian. Total size = 64 + 3 × (8 + stride × height). All integers little-endian. Total size = 704 + 3 × (8 + stride × height).
| offset | type | field | | offset | type | field |
| --- | --- | --- | | --- | --- | --- |
| 0 | u32 | magic `0x46525555` ("UURF") | | 0 | u32 | magic `0x46525555` ("UURF") |
| 4 | u32 | protocol version = 1 | | 4 | u32 | protocol version = 3 |
| 8 | u32 | frame width (px) | | 8 | u32 | frame width (px) |
| 12 | u32 | frame height (px) | | 12 | u32 | frame height (px) |
| 16 | u32 | stride (bytes per row) | | 16 | u32 | stride (bytes per row) |
| 20 | u32 | format: 1 = BGRx (32 bits per pixel) | | 20 | u32 | format: 1 = BGRx (32 bits per pixel) |
| 24 | u64 | total frames written (monotonic counter) | | 24 | u64 | total frames written (monotonic counter) |
| 32..64 | — | reserved, zero | | 32 | u32 | flags: bit 0 means the frame is a virtual-desktop composite |
| 36 | u32 | monitor layout record count (1..16) |
| 40 | u64 | producer CLOCK_MONOTONIC heartbeat in milliseconds; zero if unsupported |
| 48..64 | — | reserved, zero |
Slot *i* (i = 0, 1, 2) at offset `64 + i × (8 + stride × height)`: The fixed-size monitor table starts at offset 64 and contains 16 records of
40 bytes each. Unused records are zero. Each record contains signed logical
`x` and `y`, logical `width` and `height`, then unsigned `frame_x`, `frame_y`,
`frame_width` and `frame_height` describing that monitor's rectangle in the
composited frame, then `capture_width` and `capture_height` for the negotiated
source stream resolution. A single-stream capture has one record covering the
full frame.
Slot *i* (i = 0, 1, 2) at offset `704 + i × (8 + stride × height)`:
| offset | type | field | | offset | type | field |
| --- | --- | --- | | --- | --- | --- |
@@ -47,3 +60,62 @@ mutexes; a torn read is detected, never observed.
The transport path is created per user and passed to the Wine adapter through The transport path is created per user and passed to the Wine adapter through
the managed prefix configuration. It is never a global shared-memory name. the managed prefix configuration. It is never a global shared-memory name.
## Geometry and session changes
For one selected stream, an exact Wine monitor rectangle maps onto the entire
frame when their aspect ratios match. With multiple selected monitor streams,
the producer uses portal position/size metadata to compose the streams into a
virtual desktop frame; Wine monitor rectangles then crop their matching region.
If a portal omits layout metadata, streams are arranged left to right. Fractional
scaling is normalized to a shared frame scale; each stream is resampled into
its reported logical rectangle. The hook matches Wine monitor bounds to the
captured layout and crops in monitor-local coordinates, so differing monitor
resolutions and vertical offsets do not shift the top edge of a screen.
The capture service's virtual display API uses the composed frame rectangles
relative to the primary monitor, including a common pixel scale. UI and WebView
processes retain native display geometry. Raw source pixel sizes remain metadata
and are never combined with logical origins. Portals without stable output
identity require the selected monitor count to match Wine's monitor count for
per-monitor matching; otherwise the composite is used as a whole.
Multiple monitors are explicitly enabled with `uur display source monitor
--multiple`, followed by a new session and monitor selection in the portal.
Upgrading preserves existing grants. Choosing `uur display source monitor`
returns to a single selected source. Absolute input selects the consented node
containing the logical position, then sends that node's local coordinates.
Each transport inode has immutable geometry. A negotiated size change creates
a new mode-0600 file, initializes its header and slots, then atomically replaces
the transport path. The previous mapping remains valid for existing readers;
the producer never truncates it. The Wine adapter checks file identity at least
every 250 ms and remaps replacements while serializing its capture readers.
The PipeWire consumer accepts explicitly linear DMA-BUFs and retains a separate
shared-memory format offer. DMA-BUF reads use the source stride, plane offsets,
fd extent, readiness fence and CPU-access synchronization. Implicit modifiers
require a graphics importer and are not advertised by this CPU consumer.
A stream error, lost connection or ten seconds in PAUSED after streaming makes
the helper exit with status 75. A ten-second expired producer heartbeat also
restarts a hung helper, independently of desktop changes. Both ScreenCast and
combined RemoteDesktop supervisors retry up to three
times using the saved restore token, with a one-second backoff. Thirty seconds
of healthy capture resets the retry budget. An unchanged desktop in STREAMING
does not trigger this watchdog. Recovery keeps the saved token and performs no
token-less fallback or switch to direct capture. The portal controls whether
restoring that choice requires confirmation. A portal Session.Closed signal
without a matching Mutter layout change ends sharing; the user starts a new
session explicitly. The supervisor subscribes to the raw signal on the session's
own connection, accepting both dictionary and empty signal bodies.
When Mutter's DisplayConfig service is already present, the supervisor also
subscribes to MonitorsChanged and proactively restores capture after a layout
change. It coalesces signals during the reconnect delay. Mutter may close the
old session before forwarding MonitorsChanged, so a Closed signal has a 250 ms
window to correlate that transaction. Closed without a matching change stops
capture, and process stop requests always take priority. This optional listener
never starts a GNOME service on other desktops.
Successful layout-driven restarts do not consume the failure retry budget.
Only the initial session can make a token-less interactive selection; later
restores keep that boundary even when the failure counter has been reset.
+66 -7
View File
@@ -12,13 +12,13 @@ needed for system-wide package installation.
paru -S uur paru -S uur
# Downloaded release package # Downloaded release package
sudo pacman -U ./uur-0.1.3-1-x86_64.pkg.tar.zst sudo pacman -U ./uur-0.1.7-1-x86_64.pkg.tar.zst
``` ```
## Debian, Ubuntu, and derivatives ## Debian, Ubuntu, and derivatives
```bash ```bash
sudo apt install ./uur_0.1.3_amd64.deb sudo apt install ./uur_0.1.7_amd64.deb
``` ```
The same release artifact covers Debian, Ubuntu, Linux Mint, Pop!_OS, KDE neon, The same release artifact covers Debian, Ubuntu, Linux Mint, Pop!_OS, KDE neon,
@@ -28,10 +28,10 @@ derivatives.
## Fedora, RHEL, and openSUSE families ## Fedora, RHEL, and openSUSE families
```bash ```bash
sudo dnf install ./uur-0.1.3-1.x86_64.rpm sudo dnf install ./uur-0.1.7-1.x86_64.rpm
# openSUSE # openSUSE
sudo zypper install ./uur-0.1.3-1.x86_64.rpm sudo zypper install ./uur-0.1.7-1.x86_64.rpm
``` ```
This format also covers Fedora derivatives and RPM systems whose repositories This format also covers Fedora derivatives and RPM systems whose repositories
@@ -42,7 +42,7 @@ provide the declared Wine, GLib, PipeWire, and portal dependencies.
The portable archive targets conventional glibc/FHS systems: The portable archive targets conventional glibc/FHS systems:
```bash ```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst sudo tar --zstd -C / -xf ./uur-0.1.7-linux-x86_64.tar.zst
``` ```
## Nix and NixOS ## Nix and NixOS
@@ -79,7 +79,7 @@ sudo apk add ~/packages/*/x86_64/uur-*.apk
Gentoo, Funtoo, Void Linux, Slackware, Solus, Clear Linux, ALT Linux, Exherbo, Gentoo, Funtoo, Void Linux, Slackware, Solus, Clear Linux, ALT Linux, Exherbo,
Mageia, OpenMandriva, PCLinuxOS, Venom Linux, and other FHS/glibc systems can Mageia, OpenMandriva, PCLinuxOS, Venom Linux, and other FHS/glibc systems can
install the portable release archive or build from source. Their native recipe install the portable release archive or build from source. Their native recipe
can call `packaging/stage.sh` after the three standard builds; the staged tree can call `packaging/stage.sh` after the standard builds (`hook`, `capture`, `compat`); the staged tree
is shared with pacman, deb, rpm, APK, and the portable archive. is shared with pacman, deb, rpm, APK, and the portable archive.
GNU Guix can wrap the same source build and staged tree. Flatpak and Snap need GNU Guix can wrap the same source build and staged tree. Flatpak and Snap need
@@ -91,11 +91,12 @@ manifests granting Wine execution, session D-Bus, PipeWire, and input access.
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
./scripts/install-user.sh ./scripts/install-user.sh
``` ```
This installs under `~/.local` by default. It requires Rust, a native C This installs under `~/.local` by default. It requires Rust, a native C
compiler, PipeWire development files, `pkg-config`, and the MinGW-w64 x86_64 compiler, PipeWire and Wayland development files (including `wayland-scanner`), `pkg-config`, and the MinGW-w64 x86_64
toolchain. toolchain.
## Required first run ## Required first run
@@ -111,3 +112,61 @@ uur run
See [Platform support and usage](platform-support.md) for desktop-session and See [Platform support and usage](platform-support.md) for desktop-session and
portal requirements. portal requirements.
## Package removal, repair, and per-user state
Package removal leaves the managed Wine prefix, downloaded installer cache,
configuration and logs in the user's XDG directories. This preserves login
and client data across package upgrades and reinstalls. Reinstalling the
package therefore does not create a new Wine prefix. Start with
`uur stop` followed by `uur setup --repair` for an interrupted setup.
For a fresh prefix, stop uur and move the old prefix aside before setup:
```bash
uur stop
uur_prefix="${XDG_DATA_HOME:-$HOME/.local/share}/uur/wine"
mv -- "$uur_prefix" "$uur_prefix.backup-$(date +%Y%m%d-%H%M%S)"
uur setup --accept-eula
```
The fresh prefix needs the official client installed and logged in again.
The backup retains the previous client and account data.
`uur uninstall` stops the managed session and Wine server, removes this user's
autostart entry and recognized UU launchers/icons, and removes a source
installation identified by its installer receipt. It keeps the managed client,
account data, configuration and logs by default. Use `--purge` for a fresh
start or complete removal:
```bash
# Preview only: no processes stopped, no files changed
uur uninstall --purge --dry-run
# Run as the desktop user, NOT with sudo; review the paths and confirm
uur uninstall --purge
# Remove system package files afterwards (Arch Linux)
sudo pacman -Rns uur
```
Purge permanently deletes the dedicated Wine prefix (including Wine Mono,
WebView2 and the official client), login/account data, installer cache, all uur
configuration and logs, and private runtime files. Back up the `uur` XDG
directories first if those data are needed. For unattended removal, explicitly
confirm with `uur uninstall --purge --yes`. The command honors the current
`XDG_DATA_HOME`, `XDG_CONFIG_HOME`, `XDG_STATE_HOME` and `XDG_RUNTIME_DIR`; use
the same values used for setup. A custom source install can be selected with
`UUR_INSTALL_PREFIX=/path/to/prefix uur uninstall --purge`.
On Debian/Ubuntu, use `sudo apt purge uur` after the user cleanup; on Fedora,
use `sudo dnf remove uur`. Package-manager removal alone leaves per-user data
intact, including when run with `purge`: package scripts run as root and do not
erase other users' home directories. Each user should run the cleanup command
before the system package is removed. If the package was already removed,
reinstall it to get the cleanup command, run `uur uninstall --purge`, then
remove the package again; running setup is not required. Shared Wine/Mono, PipeWire and portal
packages remain the package manager's responsibility. Kernel/device settings
and compositor-granted portal permissions are not reset by user-data cleanup.
Unpin any old launcher from the desktop panel afterwards if the panel retains
its own pinned copy.
+6 -6
View File
@@ -5,16 +5,16 @@
| Control other devices | available | Official UU UI and decoder under Wine | | Control other devices | available | Official UU UI and decoder under Wine |
| Receive remote video | available | Official UU UI under Wine | | Receive remote video | available | Official UU UI under Wine |
| Share X11 desktop | available | Wine X11 capture | | Share X11 desktop | available | Wine X11 capture |
| Share Wayland desktop | available | ScreenCast portal → PipeWire → GDI adapter | | Share Wayland desktop | available | ScreenCast/PipeWire or explicitly enabled native screencopy → GDI adapter |
| Mouse and keyboard | implemented | RemoteDesktop portal → uinput → XTest capability order | | Mouse and keyboard | implemented | RemoteDesktop portal → uinput → XTest capability order; process-local NumLock/ScrollLock workaround for ordinary controller keys; keypad/case behavior remains native |
| X11 multi-monitor | Wine integration | Native Wine/XRandR display topology | | X11 multi-monitor | Wine integration | Native Wine/XRandR display topology |
| Wayland monitor/window selection | available | Persistent portal source selection | | Wayland monitor/window selection | available | Persistent portal source selection |
| Wayland virtual source | available when advertised | `uur display source virtual` → ScreenCast Virtual source | | Wayland virtual source | available when advertised | `uur display source virtual` → ScreenCast Virtual source |
| Independent Wayland multi-screen switching | in progress | Multiple PipeWire streams → UU display topology adapter | | Wayland multi-screen capture | available | Multiple PipeWire streams → virtual desktop composite → per-monitor crops |
| Clipboard and phone IME text | planned | RemoteDesktop Clipboard portal, then X11 fallback | | Clipboard and phone IME text | planned | RemoteDesktop Clipboard portal, then X11 fallback |
| Speaker and microphone audio | available through Wine | PulseAudio, pipewire-pulse, or ALSA selected from live capabilities | | Speaker and microphone audio | Wine fallback capture | PulseAudio, pipewire-pulse, or ALSA; proprietary dual-channel audio driver unavailable |
| System-audio loopback and remote mute | Wine integration | WASAPI → winepulse/winealsa | | System-audio loopback | explicit default-input override | `uur audio source system` selects a real PulseAudio monitor for the fallback stream; remote mute needs separate validation |
| Native tray | Wine baseline | Official tray, with StatusNotifierItem as the native route | | Native tray | implemented | StatusNotifierItem + DBusMenu, supervised with the session; no Wine XEmbed dependency |
| Terminal | available | ConPTY/mux ABI adapters → authenticated native Rust PTY/login shell | | Terminal | available | ConPTY/mux ABI adapters → authenticated native Rust PTY/login shell |
| Quick Launch | implemented | Windows app inventory adapter → XDG desktop catalog → `gio launch` | | Quick Launch | implemented | Windows app inventory adapter → XDG desktop catalog → `gio launch` |
| Desktop wallpaper | available | Capability providers → Wine desktop metadata | | Desktop wallpaper | available | Capability providers → Wine desktop metadata |
+170 -11
View File
@@ -46,7 +46,7 @@ paru -S uur
From a downloaded Arch package: From a downloaded Arch package:
```bash ```bash
sudo pacman -U ./uur-0.1.3-1-x86_64.pkg.tar.zst sudo pacman -U ./uur-0.1.7-1-x86_64.pkg.tar.zst
``` ```
Install the portal backend supplied or recommended by the selected desktop. Install the portal backend supplied or recommended by the selected desktop.
@@ -60,7 +60,7 @@ Zorin OS, elementary OS, KDE neon, TUXEDO OS, Kali Linux, MX Linux, and other
compatible derivatives: compatible derivatives:
```bash ```bash
sudo apt install ./uur_0.1.3_amd64.deb sudo apt install ./uur_0.1.7_amd64.deb
``` ```
The package manager resolves Wine, PipeWire, and the portal frontend. Install The package manager resolves Wine, PipeWire, and the portal frontend. Install
@@ -74,10 +74,10 @@ dependency names. Install it with the native frontend:
```bash ```bash
# Fedora and compatible systems # Fedora and compatible systems
sudo dnf install ./uur-0.1.3-1.x86_64.rpm sudo dnf install ./uur-0.1.7-1.x86_64.rpm
# openSUSE family # openSUSE family
sudo zypper install ./uur-0.1.3-1.x86_64.rpm sudo zypper install ./uur-0.1.7-1.x86_64.rpm
``` ```
RHEL, CentOS Stream, Rocky Linux, AlmaLinux, Oracle Linux, Nobara, Ultramarine, RHEL, CentOS Stream, Rocky Linux, AlmaLinux, Oracle Linux, Nobara, Ultramarine,
@@ -91,7 +91,7 @@ PCLinuxOS, and similar mutable/FHS systems can use the portable archive when
they provide compatible glibc, Wine, PipeWire, and portal libraries: they provide compatible glibc, Wine, PipeWire, and portal libraries:
```bash ```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst sudo tar --zstd -C / -xf ./uur-0.1.7-linux-x86_64.tar.zst
``` ```
Alternatively, build and install for one user: Alternatively, build and install for one user:
@@ -100,6 +100,7 @@ Alternatively, build and install for one user:
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
./scripts/install-user.sh ./scripts/install-user.sh
``` ```
@@ -132,6 +133,31 @@ Openbox, Fluxbox, IceWM, dwm, qtile, herbstluftwm, spectrwm, and FVWM.
Wine captures the X11 desktop directly and uur injects input with XTest. A Wine captures the X11 desktop directly and uur injects input with XTest. A
ScreenCast portal is not required for this path. ScreenCast portal is not required for this path.
#### Lock modifier bits in the client's key events
Wine can inject a NumLock correction pair on each ordinary key when the
official client's low-level hook blocks lock-key synchronization. This affects
controller-side typing before uur's remote-input bridge receives any records.
The process-local `libuur-lock-mods.so` workaround discovers exclusive NumLock
and ScrollLock modifiers from each X11 display's actual keymap. With
`strip_lock_mods = "auto"` (the default), it filters those bits on ordinary key
events. Numeric masks further restrict the discovered set; `"0"` disables it.
It preserves Super, Ctrl, Alt, AltGr, Shift and CapsLock rather than assuming
that Mod2 and Mod4 are both locks, and refreshes its mapping after layout
changes. No X server, compositor or user lock setting is changed.
Keypad events keep their original state so NumLock-on digits do not become
navigation keys. CapsLock also keeps its case semantics. These events retain
Wine's native reconciliation behavior and can still trigger lock-key
corrections. Use `WINEDEBUG=+key,+keyboard uur run` and the
private session log to distinguish real key conversions from correction
pairs. `uur doctor` reports the local lock state and configured workaround.
After acquiring the session lock, a shim-enabled run restarts only the managed
Wine prefix so its service manager and service-spawned clients receive the
same compatibility environment. Other Wine prefixes remain running.
### Wayland session with ScreenCast and RemoteDesktop portals ### Wayland session with ScreenCast and RemoteDesktop portals
Requirements: a working session D-Bus, PipeWire, the xdg-desktop-portal Requirements: a working session D-Bus, PipeWire, the xdg-desktop-portal
@@ -139,8 +165,7 @@ frontend, and a backend exposing both `ScreenCast` and `RemoteDesktop`.
Where those interfaces are available, uur creates one combined session for Where those interfaces are available, uur creates one combined session for
capture and input. This is the preferred unprivileged route. Examples can capture and input. This is the preferred unprivileged route. Examples can
include current GNOME Shell, KDE Plasma, niri with its recommended portal include current GNOME Shell, KDE Plasma, COSMIC, and other sessions whose selected portal backend
configuration, COSMIC, and other sessions whose selected portal backend
advertises both interfaces. Interface availability—not the desktop name—makes advertises both interfaces. Interface availability—not the desktop name—makes
the final decision. the final decision.
@@ -151,7 +176,9 @@ input. XTest remains only a partial fallback for XWayland surfaces.
This route commonly applies to compositors using Hyprland or wlroots-oriented This route commonly applies to compositors using Hyprland or wlroots-oriented
portal backends, including Hyprland, Sway, Wayfire, river, labwc, dwl, Waybox, portal backends, including Hyprland, Sway, Wayfire, river, labwc, dwl, Waybox,
and other wlroots-based sessions. It may also apply to a desktop whose portal and other wlroots-based sessions. niri uses its recommended
`xdg-desktop-portal-gnome` ScreenCast integration and requires uinput when a
working RemoteDesktop session is unavailable. It may also apply to a desktop whose portal
installation is incomplete or whose selected backend omits RemoteDesktop. installation is incomplete or whose selected backend omits RemoteDesktop.
Install the compositor's ScreenCast portal and enable uinput access. A Install the compositor's ScreenCast portal and enable uinput access. A
@@ -178,19 +205,43 @@ the `pipewire-pulse` compatibility server. A native PipeWire session without
PulseAudio compatibility uses Wine's ALSA driver. `uur doctor` prints the live PulseAudio compatibility uses Wine's ALSA driver. `uur doctor` prints the live
choice; this is independent from PipeWire's Wayland video role. choice; this is independent from PipeWire's Wayland video role.
UU's `nevaudio.sys` driver is unavailable under Wine. Its fallback can label
the default recording input as system sound, even when that input is a physical
microphone. To choose system sound explicitly with PulseAudio or pipewire-pulse:
```bash
uur audio sources
uur audio source system
uur stop
uur run
```
`system` resolves the default output's real monitor source before startup;
an unavailable selection stops startup with a diagnostic. The override applies
only to Wine's default capture endpoint in this managed prefix. An explicitly
selected device in UU keeps its own routing. Host audio defaults and other apps
are unchanged. `uur audio source SOURCE_NAME` selects another listed input;
`uur audio source default` follows the existing audio environment again.
The selected output is resolved again on the next session, so restart after
changing audio hardware. This provides one fallback capture stream; simultaneous
independent speaker and microphone channels still need the official driver.
### Displays and virtual sources ### Displays and virtual sources
```bash ```bash
uur display status uur display status
uur display source monitor uur display source monitor
uur display source monitor --multiple
uur display source window uur display source window
uur display source virtual uur display source virtual
``` ```
The command clears the old restore token so the next Portal session can create The command clears the old restore token so the next Portal session can create
or select the requested source. X11 exposes its XRandR topology to Wine. or select the requested source. With `monitor --multiple`, the chooser can select
Wayland currently carries one selected stream; independent multi-stream multiple displays; uur composes those PipeWire streams into the virtual desktop
switching is the next display-topology adapter. frame and crops each Wine monitor request from it. X11 exposes its XRandR
topology to Wine directly. Upgrades preserve existing restore tokens; multiple
monitor selection is an explicit choice and applies to the next session.
## First run and normal use ## First run and normal use
@@ -242,6 +293,18 @@ Stop only the managed session and its Wine prefix with:
uur stop uur stop
``` ```
The session tracks `GameViewer.exe` in its own Wine prefix through the
resident `winlogon.exe` adapter. This uses the Windows process table even when
the client changes its Linux process title. It keeps a three-second handoff
grace period without repeatedly starting `tasklist`. A failed process query
is not treated as a client exit; a disconnected or unresponsive monitor ends
the session with an explicit error. Stopping the session also stops this
adapter and the capture/input helpers. Remaining Wine workers, including
WebView2 processes that outlive their wineserver, are matched to this prefix
and signaled through Linux pidfds to avoid PID-reuse races. Other Wine prefixes
are left running. This residual-process cleanup needs Linux 5.3 or later;
older kernels still use Wine's normal wineserver shutdown.
Useful input-backend overrides for diagnosis are: Useful input-backend overrides for diagnosis are:
```bash ```bash
@@ -253,6 +316,102 @@ UUR_INPUT_BACKEND=xtest uur run
An override is a diagnostic tool, not a desktop-specific configuration. The An override is a diagnostic tool, not a desktop-specific configuration. The
default `auto` mode should be used after troubleshooting. default `auto` mode should be used after troubleshooting.
## Interrupted setup and Wine components
Retry an interrupted installation without deleting the managed prefix:
```bash
uur stop
uur setup --repair
uur doctor
uur run
```
The repair option runs `wineboot --update` for the managed prefix. This retries
Wine's component initialization, including its Wine Mono offer where needed.
It keeps the installed client's data, checks both the client and service
executables and the Windows service registration, and reruns the official
installer if that installation is incomplete. Failed initialization or a
failed/cancelled installer returns an error instead of reporting completion.
The **Wine Mono Installer** is Wine's .NET runtime installer. It is separate
from **WebView2**, which uur uses for the official client's management UI.
Cancelling Mono does not establish the cause of a Wayland black screen or
failed desktop input. Those paths depend on the native capture helper,
ScreenCast/PipeWire and an authorized RemoteDesktop session or uinput.
On Arch/CachyOS, installing the matching `wine-mono` package can avoid the
Wine dialog's network download; use the package supplied for the installed
Wine version. For the existing 0.1.4 release, the equivalent manual retry is:
```bash
uur stop
WINEPREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/uur/wine" \
WINEDLLOVERRIDES="wevtapi=b,wtsapi32=b" wineboot --update
uur setup
```
To open the Wine program/component manager for this prefix:
```bash
WINEPREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/uur/wine" \
WINEDLLOVERRIDES="wevtapi=b,wtsapi32=b" wine uninstaller
```
## niri: black video or missing desktop input
Use the niri session entry (or `niri-session`), its recommended
`xdg-desktop-portal-gnome` backend, and a running PipeWire service. A visible
Wine window only verifies its XWayland display path. Remote video still needs
the separate ScreenCast stream, and native Wayland input needs a working
RemoteDesktop session or writable `/dev/uinput`.
Start with an actual monitor selection:
```bash
uur display source monitor
uur doctor
test -w /dev/uinput && echo 'uinput is writable'
uur run
```
If the portal chooser offers **niri Dynamic Cast Target**, that stream remains
empty until a target is assigned through niri. Select a real monitor when
diagnosing black video. See [niri's screencasting documentation](https://github.com/niri-wm/niri/wiki/Screencasting).
If RemoteDesktop creation fails, the automatic policy tries uinput. When both
are unavailable it reports an error; explicitly selected XTEST can only reach
XWayland windows. The packaged udev rule and uinput module must be active for
the logged-in user; restart the graphical session after changing that setup.
`uur run` verifies a real Wayland frame and a running GameViewerService before
announcing readiness. Startup/helper failures are reported in the terminal;
details are in `${XDG_STATE_HOME:-$HOME/.local/state}/uur/session.log` and
`${XDG_DATA_HOME:-$HOME/.local/share}/uur/hook.log`. A missing tray icon alone
does not determine whether capture or input works.
For niri and other compositors exposing `wlr-screencopy`, uur also offers
direct, shared-memory monitor capture. This path avoids portal/PipeWire/GBM
dependencies for video and is useful when a portal cannot produce frames:
```bash
uur display outputs
uur display backend wayland --output DP-1 # Use the name printed above
uur run
```
Selecting `wayland` explicitly authorizes direct monitor capture for later
runs. It does not show a system screen-sharing dialog and does not activate
automatically after portal cancellation or failure. With one output, `--output`
can be omitted; multiple outputs require an explicit name. Automatic input
selection uses uinput in this mode. Run `uur display backend portal` to return
to portal-consented capture. Direct mode captures a monitor, not individual
windows or virtual portal sources; changes to its size require restarting
the session.
The supervised native StatusNotifierItem supplies its own icon pixels and
DBusMenu to Noctalia, Plasma and other compatible panels. Right-click it for
Open UU Remote and Quit. It re-registers when the panel's watcher restarts;
it does not depend on Wine's legacy tray being visible.
## Reading `uur doctor` ## Reading `uur doctor`
- `portal ScreenCast`: required to capture a Wayland desktop. - `portal ScreenCast`: required to capture a Wayland desktop.
+4 -3
View File
@@ -3,11 +3,12 @@
## Frame sources ## Frame sources
- X11 sessions expose the XRandR monitor topology directly to Wine. - X11 sessions expose the XRandR monitor topology directly to Wine.
- Wayland monitor and window sources use ScreenCast/PipeWire. - Wayland monitor and window sources use ScreenCast/PipeWire. Monitor selection
supports multiple outputs with `uur display source monitor --multiple` and
composes their streams into the virtual desktop
frame consumed by the Wine capture adapter.
- `uur display source virtual` requests the portal's Virtual source type and - `uur display source virtual` requests the portal's Virtual source type and
stores its restore token. stores its restore token.
- A multi-stream compositor will combine or expose several PipeWire nodes to
UU's display topology for independent Wayland screen switching.
## Codec capabilities ## Codec capabilities
+22 -2
View File
@@ -5,9 +5,29 @@
#include <stdint.h> #include <stdint.h>
#define UURF_MAGIC 0x46525555u #define UURF_MAGIC 0x46525555u
#define UURF_VERSION 1u #define UURF_VERSION 3u
#define UURF_SLOT_COUNT 3u #define UURF_SLOT_COUNT 3u
#define UURF_HEADER_BYTES 64u #define UURF_BASE_HEADER_BYTES 64u
#define UURF_MAX_MONITORS 16u
#define UURF_MONITOR_BYTES 40u
#define UURF_HEADER_BYTES \
(UURF_BASE_HEADER_BYTES + UURF_MAX_MONITORS * UURF_MONITOR_BYTES)
#define UURF_FLAG_COMPOSITE 1u
struct uurf_monitor_layout {
int32_t logical_x;
int32_t logical_y;
uint32_t logical_width;
uint32_t logical_height;
uint32_t frame_x;
uint32_t frame_y;
uint32_t frame_width;
uint32_t frame_height;
uint32_t capture_width;
uint32_t capture_height;
};
_Static_assert(sizeof(struct uurf_monitor_layout) == UURF_MONITOR_BYTES,
"monitor layout ABI changed");
static inline size_t uurf_slot_offset(uint64_t sequence, size_t slot_bytes) static inline size_t uurf_slot_offset(uint64_t sequence, size_t slot_bytes)
{ {
+5
View File
@@ -75,6 +75,11 @@ static int capture_round_trip(void)
put_u32(transport + 16, stride); put_u32(transport + 16, stride);
put_u32(transport + 20, 1); put_u32(transport + 20, 1);
put_u64(transport + 24, 1); put_u64(transport + 24, 1);
put_u32(transport + 36, 1);
put_u32(transport + UURF_BASE_HEADER_BYTES + 8, width);
put_u32(transport + UURF_BASE_HEADER_BYTES + 12, height);
put_u32(transport + UURF_BASE_HEADER_BYTES + 24, width);
put_u32(transport + UURF_BASE_HEADER_BYTES + 28, height);
unsigned char *slot = transport + uurf_slot_offset(1, slot_bytes); unsigned char *slot = transport + uurf_slot_offset(1, slot_bytes);
put_u64(slot, 2); put_u64(slot, 2);
for (size_t offset = 8; offset < slot_bytes; offset += 4) { for (size_t offset = 8; offset < slot_bytes; offset += 4) {
+952 -20
View File
File diff suppressed because it is too large. Load diff
+42 -3
View File
@@ -4,10 +4,34 @@
* GameViewerService enumerates processes for a winlogon session token * GameViewerService enumerates processes for a winlogon session token
* source before it initialises; under plain Wine none exists and the * source before it initialises; under plain Wine none exists and the
* service never leaves its initial state (the launcher waits at the * service never leaves its initial state (the launcher waits at the
* splash forever). This process only needs to exist with that name. * splash forever). It also reports the client's Windows process presence
* over its inherited pipe, avoiding a new Wine/tasklist process per poll.
*/ */
#include <windows.h> #include <windows.h>
#include <tlhelp32.h>
static char client_present(const WCHAR *image)
{
PROCESSENTRY32W entry = {0};
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return '?';
entry.dwSize = sizeof(entry);
if (!Process32FirstW(snapshot, &entry)) {
CloseHandle(snapshot);
return '?';
}
do {
if (!lstrcmpiW(entry.szExeFile, image)) {
CloseHandle(snapshot);
return '1';
}
} while (Process32NextW(snapshot, &entry));
DWORD error = GetLastError();
CloseHandle(snapshot);
return error == ERROR_NO_MORE_FILES ? '0' : '?';
}
int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line,
int show_command) int show_command)
@@ -16,6 +40,21 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line,
(void)previous; (void)previous;
(void)command_line; (void)command_line;
(void)show_command; (void)show_command;
Sleep(INFINITE); WCHAR image[MAX_PATH];
return 0; DWORD length = GetEnvironmentVariableW(L"UUR_MONITOR_CLIENT", image,
MAX_PATH);
if (!length) {
Sleep(INFINITE);
return 0;
}
if (length >= MAX_PATH)
return 1;
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;) {
char state = client_present(image);
DWORD written;
if (!WriteFile(output, &state, 1, &written, NULL) || written != 1)
return 1;
Sleep(500);
}
} }
+46 -3
View File
@@ -4,9 +4,17 @@ doctor:
no_portal_backend: "no xdg-desktop-portal backend found (Wayland capture/input unavailable)" no_portal_backend: "no xdg-desktop-portal backend found (Wayland capture/input unavailable)"
present: "present" present: "present"
backend_x11: "X11 session: XTEST injection" backend_x11: "X11 session: XTEST injection"
backend_wayland: "Wayland session: kernel uinput injection (portal path in development)" backend_wayland: "Wayland session: kernel uinput injection"
backend_portal: "Wayland session: standard RemoteDesktop portal" backend_portal: "Wayland session: standard RemoteDesktop portal"
backend_none: "no graphical session detected" backend_none: "no graphical session detected"
backend_partial: "XWayland windows only; native Wayland desktop input requires portal or uinput"
backend_wayland_missing: "full desktop input unavailable; check RemoteDesktop authorization or /dev/uinput access"
client_incomplete: "client or server executable missing; run uur setup --repair"
service_registered: "registered; successful startup is checked by uur run"
service_missing: "missing service registration; run uur setup --repair"
webview_pending: "not installed; uur run will invoke the bundled WebView2 installer"
portal_capture_advertised: "source types advertised; authorization and real frames are checked by uur run"
portal_input_advertised: "keyboard and pointer advertised; session authorization is checked by uur run"
uinput_module: "device present but kernel module not loaded (install the packaged udev rule + modules-load entry, then reboot)" uinput_module: "device present but kernel module not loaded (install the packaged udev rule + modules-load entry, then reboot)"
uinput_permission: "not writable by this user (needs the uur udev uaccess rule or the input group)" uinput_permission: "not writable by this user (needs the uur udev uaccess rule or the input group)"
uinput_missing: "/dev/uinput missing from this kernel" uinput_missing: "/dev/uinput missing from this kernel"
@@ -16,12 +24,13 @@ doctor:
launcher_missing: "Win64 Quick Launch proxy missing; reinstall uur" launcher_missing: "Win64 Quick Launch proxy missing; reinstall uur"
xdg_launcher_missing: "install GLib's gio or gtk-launch" xdg_launcher_missing: "install GLib's gio or gtk-launch"
wallpaper_missing: "not detected; set UUR_WALLPAPER to an image path" wallpaper_missing: "not detected; set UUR_WALLPAPER to an image path"
footer: "Everything above is advisory. Run `uur setup` to provision the managed client." footer: "This report checks installation files and advertised capabilities. uur run verifies the input session, Wayland frames, and Windows service startup. Use uur setup --repair to retry Wine initialization after an interrupted installation."
input: input:
portal_unavailable: "Wayland portal input is not available in this session" portal_unavailable: "Wayland portal input is not available in this session"
no_display: "no graphical session detected (DISPLAY and WAYLAND_DISPLAY are unset)" no_display: "no graphical session detected (DISPLAY and WAYLAND_DISPLAY are unset)"
uinput_unavailable: "uinput not writable — falling back to XTEST (XWayland scope only; load the uinput module or add the udev rule for full coverage)" uinput_unavailable: "kernel uinput injection unavailable"
wayland_no_full_input: "Wayland desktop input requires a working RemoteDesktop portal or writable /dev/uinput. Check the packaged udev rule and uinput module. Explicit xtest is limited to XWayland windows."
bridge: bridge:
listening: "input bridge listening on 127.0.0.1:%{port}" listening: "input bridge listening on 127.0.0.1:%{port}"
@@ -42,8 +51,13 @@ upstream:
not_provisioned: "no provisioned client found; run `uur setup`" not_provisioned: "no provisioned client found; run `uur setup`"
capture: capture:
direct_enabled: "Direct Wayland monitor capture explicitly enabled; it uses uinput and does not show a portal consent dialog. Use uur display backend portal to restore portal capture."
portal_enabled: "Portal-consented capture enabled"
direct_started: "direct Wayland monitor capture started"
session_ready: "portal session ready (video node %{node}); streaming to the private runtime transport" session_ready: "portal session ready (video node %{node}); streaming to the private runtime transport"
helper_failed: "the capture helper exited with an error" helper_failed: "the capture helper exited with an error"
cursor_unsupported: "the desktop portal advertises no usable cursor mode, so screen capture cannot start. Restart the portal (systemctl --user restart xdg-desktop-portal) and retry; if it persists, check that a ScreenCast backend matching your session is installed."
cursor_not_embedded: "the portal cannot embed the cursor; capture will continue without a cursor in the video frames"
session: session:
already_running: "a session is already running - use it, or run `uur stop` first" already_running: "a session is already running - use it, or run `uur stop` first"
@@ -55,6 +69,11 @@ session:
webview_failed: "WebView2 installation failed" webview_failed: "WebView2 installation failed"
quick_launch_ready: "%{count} Linux applications exported to UU Quick Launch" quick_launch_ready: "%{count} Linux applications exported to UU Quick Launch"
audio_backend: "Wine audio backend: %{backend}" audio_backend: "Wine audio backend: %{backend}"
wine_dpi: "Wine system DPI set from Xft.dpi: %{dpi}"
waiting_capture: "waiting for the first Wayland capture frame; select a monitor in the portal dialog"
waiting_direct_capture: "waiting for the first direct Wayland monitor frame"
capture_not_ready: "No Wayland frames arrived within 120 seconds. Check the ScreenCast portal and PipeWire; select an actual monitor rather than an unassigned dynamic cast target. See the session log."
service_failed: "GameViewerService did not start. Run uur setup --repair and inspect ~/.local/state/uur/session.log and ~/.local/share/uur/hook.log."
setup: setup:
eula_prompt: "The official UU Remote client will be downloaded from NetEase and is governed by their EULA: %{url}\nRe-run with --accept-eula to continue." eula_prompt: "The official UU Remote client will be downloaded from NetEase and is governed by their EULA: %{url}\nRe-run with --accept-eula to continue."
@@ -64,10 +83,34 @@ setup:
downloading: "downloading the official installer from %{url}" downloading: "downloading the official installer from %{url}"
download_failed: "the official installer download failed" download_failed: "the official installer download failed"
initializing_prefix: "initializing the managed Wine prefix" initializing_prefix: "initializing the managed Wine prefix"
prefix_failed: "Wine prefix initialization failed (%{status}); run uur setup --repair after resolving the Wine error"
repaired: "Wine prefix updated and client installation verified at %{path}"
install_failed: "The official installer failed or was cancelled (%{status}); installation is incomplete. Retry with uur setup --repair."
client_incomplete: "The installer did not provide both GameViewer.exe and GameViewerServer.exe; retry with uur setup --repair"
service_incomplete: "GameViewerService has no valid registered executable; run uur setup --repair"
installing_client: "installing the official client (silent mode)" installing_client: "installing the official client (silent mode)"
silent_install_unavailable: "the installer ignored silent mode; complete its window manually if it opened" silent_install_unavailable: "the installer ignored silent mode; complete its window manually if it opened"
done: "provisioned into %{path}" done: "provisioned into %{path}"
tray:
title: "UU Remote"
tooltip: "UU Remote for Linux"
open: "Open UU Remote"
quit: "Quit"
registered: "native desktop tray registered"
uninstall:
no_root: "Run uur uninstall as the desktop user, without sudo. Remove the system package separately with its package manager."
plan: "Removal plan (directories include their contents):"
purge_warning: "This permanently deletes the managed client, login/account data, Wine environment, installer cache, configuration and logs."
keep_data: "Client/account data, configuration and logs will be kept. Use --purge to remove them too."
package_hint: "System package files and shared dependencies are left to the package manager. On Arch, run sudo pacman -Rns uur after this command."
dry_run: "Preview only; no processes were stopped and no files were changed."
confirm_required: "No terminal is available for confirmation. Review --dry-run, then pass --yes to confirm removal."
confirm: "Proceed with removal? [y/N]"
cancelled: "Cancelled; no files were changed."
done: "The selected user files and recognized source-installation files have been removed."
autostart: autostart:
enabled: "login autostart enabled: %{path}" enabled: "login autostart enabled: %{path}"
disabled: "login autostart disabled" disabled: "login autostart disabled"
+45 -2
View File
@@ -7,6 +7,14 @@ doctor:
backend_wayland: "Wayland 会话:内核 uinput 注入" backend_wayland: "Wayland 会话:内核 uinput 注入"
backend_portal: "Wayland 会话:标准 RemoteDesktop Portal" backend_portal: "Wayland 会话:标准 RemoteDesktop Portal"
backend_none: "未检测到图形会话" backend_none: "未检测到图形会话"
backend_partial: "仅能控制 XWayland 窗口;原生 Wayland 桌面输入需要 Portal 或 uinput"
backend_wayland_missing: "完整桌面输入不可用;请检查 RemoteDesktop 授权或 /dev/uinput 访问权限"
client_incomplete: "缺少客户端或服务端程序;请运行 uur setup --repair"
service_registered: "已注册;uur run 会检查实际启动结果"
service_missing: "缺少服务注册;请运行 uur setup --repair"
webview_pending: "尚未安装;uur run 会调用客户端自带的 WebView2 安装器"
portal_capture_advertised: "已提供源类型;uur run 会检查授权和实际采集帧"
portal_input_advertised: "已提供键盘和指针类型;uur run 会检查实际会话授权"
uinput_module: "设备存在但内核模块未加载(安装包内附的 udev 规则与 modules-load 条目,然后重启)" uinput_module: "设备存在但内核模块未加载(安装包内附的 udev 规则与 modules-load 条目,然后重启)"
uinput_permission: "当前用户不可写(需要 uur 的 uaccess udev 规则或 input 组)" uinput_permission: "当前用户不可写(需要 uur 的 uaccess udev 规则或 input 组)"
uinput_missing: "此内核没有 /dev/uinput" uinput_missing: "此内核没有 /dev/uinput"
@@ -16,12 +24,13 @@ doctor:
launcher_missing: "缺少 Win64 快速启动代理;请重新安装 uur" launcher_missing: "缺少 Win64 快速启动代理;请重新安装 uur"
xdg_launcher_missing: "请安装 GLib 的 gio 或 gtk-launch" xdg_launcher_missing: "请安装 GLib 的 gio 或 gtk-launch"
wallpaper_missing: "未检测到;可将 UUR_WALLPAPER 设为图片路径" wallpaper_missing: "未检测到;可将 UUR_WALLPAPER 设为图片路径"
footer: "以上均为提示性检查。运行 `uur setup` 安装受管客户端。" footer: "此报告检查安装文件与系统声明的能力。uur run 会验证输入会话、Wayland 采集帧和 Windows 服务启动。安装中断后可运行 uur setup --repair 重试 Wine 初始化。"
input: input:
portal_unavailable: "当前会话中 Wayland Portal 输入不可用" portal_unavailable: "当前会话中 Wayland Portal 输入不可用"
no_display: "未检测到图形会话(DISPLAY 与 WAYLAND_DISPLAY 均未设置)" no_display: "未检测到图形会话(DISPLAY 与 WAYLAND_DISPLAY 均未设置)"
uinput_unavailable: "uinput 不可写 —— 回退到 XTEST(仅 XWayland 范围;请加载 uinput 模块或安装 udev 规则以获得完整覆盖)" uinput_unavailable: "内核 uinput 输入不可用"
wayland_no_full_input: "Wayland 桌面输入需要可用的 RemoteDesktop Portal 或可写的 /dev/uinput。请检查安装包中的 udev 规则和 uinput 内核模块。显式选择 xtest 只能控制 XWayland 窗口。"
bridge: bridge:
listening: "输入桥监听于 127.0.0.1:%{port}" listening: "输入桥监听于 127.0.0.1:%{port}"
@@ -43,6 +52,11 @@ session:
webview_failed: "WebView2 安装失败" webview_failed: "WebView2 安装失败"
quick_launch_ready: "已向 UU 快速启动导出 %{count} 个 Linux 应用" quick_launch_ready: "已向 UU 快速启动导出 %{count} 个 Linux 应用"
audio_backend: "Wine 音频后端:%{backend}" audio_backend: "Wine 音频后端:%{backend}"
wine_dpi: "已根据 Xft.dpi 设置 Wine 系统 DPI:%{dpi}"
waiting_capture: "正在等待首个 Wayland 采集帧;请在 Portal 对话框中选择监视器"
waiting_direct_capture: "正在等待原生 Wayland 显示器采集的首帧"
capture_not_ready: "120 秒内未收到 Wayland 采集帧。请检查 ScreenCast Portal 和 PipeWire,选择实际监视器而非尚未指定目标的动态投屏源,并查看会话日志。"
service_failed: "GameViewerService 未能启动。请运行 uur setup --repair,并检查 ~/.local/state/uur/session.log 和 ~/.local/share/uur/hook.log。"
upstream: upstream:
unreachable: "无法访问网易官方发布接口" unreachable: "无法访问网易官方发布接口"
@@ -53,8 +67,13 @@ upstream:
not_provisioned: "尚未安装受管客户端;请运行 `uur setup`" not_provisioned: "尚未安装受管客户端;请运行 `uur setup`"
capture: capture:
direct_enabled: "已明确启用原生 Wayland 显示器采集,输入使用 uinput,不再弹出 Portal 选屏授权框。运行 uur display backend portal 可恢复 Portal 采集。"
portal_enabled: "已启用 Portal 授权采集"
direct_started: "已启动原生 Wayland 显示器采集"
session_ready: "Portal 会话已建立(视频节点 %{node});正在写入私有运行时传输" session_ready: "Portal 会话已建立(视频节点 %{node});正在写入私有运行时传输"
helper_failed: "捕获助手异常退出" helper_failed: "捕获助手异常退出"
cursor_unsupported: "桌面 Portal 未声明任何可用的光标模式,无法开始屏幕采集。请重启 Portal(systemctl --user restart xdg-desktop-portal)后重试;若仍失败,请确认已安装与当前会话匹配的 ScreenCast 后端。"
cursor_not_embedded: "Portal 无法将光标嵌入画面;采集将继续,但视频帧中不会包含光标"
setup: setup:
eula_prompt: "官方 UU 远程客户端将从网易官方渠道下载,并受其最终用户协议约束:%{url}\n使用 --accept-eula 重新运行以继续。" eula_prompt: "官方 UU 远程客户端将从网易官方渠道下载,并受其最终用户协议约束:%{url}\n使用 --accept-eula 重新运行以继续。"
@@ -64,10 +83,34 @@ setup:
downloading: "正在从 %{url} 下载官方安装包" downloading: "正在从 %{url} 下载官方安装包"
download_failed: "官方安装包下载失败" download_failed: "官方安装包下载失败"
initializing_prefix: "正在初始化受管 Wine 前缀" initializing_prefix: "正在初始化受管 Wine 前缀"
prefix_failed: "Wine 前缀初始化失败(%{status});解决 Wine 错误后可运行 uur setup --repair 重试"
repaired: "已更新 Wine 前缀,并确认 %{path} 中的客户端安装完整"
install_failed: "官方安装器失败或被取消(%{status}),安装尚未完成。可运行 uur setup --repair 重试。"
client_incomplete: "安装器未提供完整的 GameViewer.exe 与 GameViewerServer.exe;请运行 uur setup --repair 重试"
service_incomplete: "GameViewerService 未注册有效的服务程序;请运行 uur setup --repair"
installing_client: "正在安装官方客户端(静默模式)" installing_client: "正在安装官方客户端(静默模式)"
silent_install_unavailable: "安装包忽略静默模式;若弹出窗口请手动完成安装" silent_install_unavailable: "安装包忽略静默模式;若弹出窗口请手动完成安装"
done: "已安装至 %{path}" done: "已安装至 %{path}"
tray:
title: "UU 远程"
tooltip: "UU 远程 Linux 客户端"
open: "打开 UU 远程"
quit: "退出"
registered: "已注册原生桌面托盘"
uninstall:
no_root: "请以桌面用户身份运行 uur uninstall,不要加 sudo;系统安装包另用包管理器卸载。"
plan: "将删除以下路径(目录包含其内部文件):"
purge_warning: "这会永久删除受管客户端、登录与账号数据、Wine 环境、安装包缓存、配置和日志。"
keep_data: "保留客户端、账号数据、配置和日志;加 --purge 可一并清除。"
package_hint: "系统安装文件和共享依赖由包管理器处理。在 Arch 上,请在此命令完成后执行 sudo pacman -Rns uur。"
dry_run: "仅预览,未停止进程,也未修改文件。"
confirm_required: "当前没有用于确认的终端。请先查看 --dry-run,再用 --yes 确认卸载。"
confirm: "确认删除吗?[y/N]"
cancelled: "已取消,未修改文件。"
done: "所选用户文件和可识别的源码安装文件已清除。"
autostart: autostart:
enabled: "已启用登录自启动:%{path}" enabled: "已启用登录自启动:%{path}"
disabled: "已禁用登录自启动" disabled: "已禁用登录自启动"
+8 -3
View File
@@ -7,6 +7,9 @@
makeWrapper, makeWrapper,
bash, bash,
pipewire, pipewire,
wayland,
wayland-scanner,
xorg,
pulseaudio, pulseaudio,
curl, curl,
glib, glib,
@@ -23,7 +26,7 @@ let
in in
rustPlatform.buildRustPackage { rustPlatform.buildRustPackage {
pname = "uur"; pname = "uur";
version = "0.1.3"; version = "0.1.6";
src = lib.cleanSource ../.; src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock; cargoLock.lockFile = ../Cargo.lock;
@@ -34,15 +37,16 @@ rustPlatform.buildRustPackage {
windowsCC windowsCC
windowsBinutils windowsBinutils
bash bash
wayland-scanner
]; ];
buildInputs = [ pipewire ]; buildInputs = [ pipewire wayland xorg.libX11 xorg.libXext ];
CC = "${stdenv.cc}/bin/cc"; CC = "${stdenv.cc}/bin/cc";
UUR_BUILD_SHELL = runtimeShell; UUR_BUILD_SHELL = runtimeShell;
doCheck = false; doCheck = false;
postPatch = '' postPatch = ''
patchShebangs hook/build.sh capture/build.sh packaging/stage.sh patchShebangs hook/build.sh capture/build.sh compat/build.sh packaging/stage.sh
''; '';
postBuild = '' postBuild = ''
@@ -51,6 +55,7 @@ rustPlatform.buildRustPackage {
UU_MINGW_DLLTOOL=${windowsBinutils}/bin/${targetPrefix}dlltool \ UU_MINGW_DLLTOOL=${windowsBinutils}/bin/${targetPrefix}dlltool \
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
''; '';
installPhase = '' installPhase = ''
+4 -3
View File
@@ -1,14 +1,14 @@
# Contributor: uur contributors # Contributor: uur contributors
# Maintainer: uur contributors # Maintainer: uur contributors
pkgname=uur pkgname=uur
pkgver=0.1.3 pkgver=0.1.7
pkgrel=0 pkgrel=0
pkgdesc="Native Linux companion for NetEase UU Remote" pkgdesc="Native Linux companion for NetEase UU Remote"
url="https://github.com/panxuc/uur" url="https://github.com/panxuc/uur"
arch="x86_64" arch="x86_64"
license="MIT" license="MIT"
depends="bash wine curl glib pulseaudio-utils xdg-desktop-portal" depends="bash wine curl glib wayland-libs-client libx11 pulseaudio-utils xdg-desktop-portal"
makedepends="cargo rust gcc musl-dev pipewire-dev pkgconf mingw-w64-gcc mingw-w64-binutils" makedepends="cargo rust gcc musl-dev pipewire-dev wayland-dev libx11-dev pkgconf mingw-w64-gcc mingw-w64-binutils"
options="!check" options="!check"
source="$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz" source="$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz"
builddir="$srcdir/$pkgname-$pkgver" builddir="$srcdir/$pkgname-$pkgver"
@@ -17,6 +17,7 @@ build() {
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
} }
check() { check() {
+3 -2
View File
@@ -1,7 +1,7 @@
FROM alpine:edge AS build FROM alpine:edge AS build
RUN apk add --no-cache \ RUN apk add --no-cache \
bash cargo rust gcc musl-dev pipewire-dev pkgconf \ bash cargo rust gcc musl-dev pipewire-dev wayland-dev libx11-dev pkgconf \
mingw-w64-gcc mingw-w64-binutils mingw-w64-gcc mingw-w64-binutils
WORKDIR /src WORKDIR /src
@@ -12,10 +12,11 @@ RUN --mount=type=cache,target=/root/.cargo/registry \
&& cargo build --release --locked \ && cargo build --release --locked \
&& ./hook/build.sh \ && ./hook/build.sh \
&& ./capture/build.sh \ && ./capture/build.sh \
&& ./compat/build.sh \
&& ./packaging/stage.sh /out && ./packaging/stage.sh /out
FROM alpine:edge FROM alpine:edge
RUN apk add --no-cache \ RUN apk add --no-cache \
bash ca-certificates curl glib pipewire-libs pulseaudio-utils wine xdg-desktop-portal bash ca-certificates curl glib pipewire-libs wayland-libs-client libx11 pulseaudio-utils wine xdg-desktop-portal
COPY --from=build /out/ / COPY --from=build /out/ /
ENTRYPOINT ["/usr/bin/uur"] ENTRYPOINT ["/usr/bin/uur"]
+1 -1
View File
@@ -5,7 +5,7 @@ pkgdesc="Native Linux companion for NetEase UU Remote"
arch=('x86_64') arch=('x86_64')
url="https://github.com/panxuc/uur" url="https://github.com/panxuc/uur"
license=('MIT') license=('MIT')
depends=('glibc' 'gcc-libs' 'glib2' 'wine' 'curl' 'pipewire' 'xdg-desktop-portal') depends=('glibc' 'gcc-libs' 'glib2' 'wine' 'curl' 'pipewire' 'wayland' 'libx11' 'libxext' 'xdg-desktop-portal')
optdepends=( optdepends=(
'xdg-desktop-portal-gnome: GNOME-compatible Wayland capture and input' 'xdg-desktop-portal-gnome: GNOME-compatible Wayland capture and input'
'xdg-desktop-portal-kde: Plasma Wayland capture and input' 'xdg-desktop-portal-kde: Plasma Wayland capture and input'
+4 -2
View File
@@ -1,6 +1,6 @@
pkgbase = uur pkgbase = uur
pkgdesc = Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge) pkgdesc = Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)
pkgver = 0.1.3 pkgver = 0.1.6
pkgrel = 1 pkgrel = 1
url = https://github.com/panxuc/uur url = https://github.com/panxuc/uur
install = uur.install install = uur.install
@@ -9,6 +9,7 @@ pkgbase = uur
makedepends = cargo makedepends = cargo
makedepends = gcc makedepends = gcc
makedepends = pkgconf makedepends = pkgconf
makedepends = wayland
makedepends = mingw-w64-gcc makedepends = mingw-w64-gcc
makedepends = mingw-w64-binutils makedepends = mingw-w64-binutils
depends = glibc depends = glibc
@@ -17,6 +18,7 @@ pkgbase = uur
depends = wine depends = wine
depends = curl depends = curl
depends = pipewire depends = pipewire
depends = wayland
depends = xdg-desktop-portal depends = xdg-desktop-portal
optdepends = osslsigncode: Authenticode verification of official updater downloads optdepends = osslsigncode: Authenticode verification of official updater downloads
optdepends = xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input optdepends = xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input
@@ -31,7 +33,7 @@ pkgbase = uur
optdepends = libva-utils: VA-API capability diagnostics optdepends = libva-utils: VA-API capability diagnostics
optdepends = vulkan-tools: Vulkan and Vulkan Video capability diagnostics optdepends = vulkan-tools: Vulkan and Vulkan Video capability diagnostics
optdepends = nvidia-utils: NVENC and NVDEC capability diagnostics on NVIDIA GPUs optdepends = nvidia-utils: NVENC and NVDEC capability diagnostics on NVIDIA GPUs
source = uur-0.1.3.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.3.tar.gz source = uur-0.1.6.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.6.tar.gz
sha256sums = SKIP sha256sums = SKIP
pkgname = uur pkgname = uur
+6 -2
View File
@@ -8,7 +8,7 @@
# `uur setup` (it is never redistributed by this package). # `uur setup` (it is never redistributed by this package).
pkgname=uur pkgname=uur
pkgver=0.1.3 pkgver=0.1.7
pkgrel=1 pkgrel=1
pkgdesc="Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)" pkgdesc="Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)"
arch=('x86_64') arch=('x86_64')
@@ -21,9 +21,12 @@ depends=(
'wine' 'wine'
'curl' 'curl'
'pipewire' 'pipewire'
'wayland'
'libx11'
'libxext'
'xdg-desktop-portal' 'xdg-desktop-portal'
) )
makedepends=('cargo' 'gcc' 'pkgconf' 'mingw-w64-gcc' 'mingw-w64-binutils') makedepends=('cargo' 'gcc' 'pkgconf' 'wayland' 'libx11' 'mingw-w64-gcc' 'mingw-w64-binutils')
optdepends=( optdepends=(
'osslsigncode: Authenticode verification of official updater downloads' 'osslsigncode: Authenticode verification of official updater downloads'
'xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input' 'xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input'
@@ -49,6 +52,7 @@ build() {
cargo build --release --locked cargo build --release --locked
./hook/build.sh ./hook/build.sh
./capture/build.sh ./capture/build.sh
./compat/build.sh
} }
check() { check() {
+7
View File
@@ -15,6 +15,13 @@ command -v makepkg >/dev/null 2>&1 || {
exit 2 exit 2
} }
cargo build --manifest-path "$project_root/Cargo.toml" --release --locked
"$project_root/hook/build.sh"
"$project_root/capture/build.sh"
if [[ -f "$project_root/compat/build.sh" ]]; then
"$project_root/compat/build.sh"
fi
sed -e "s|@UUR_VERSION@|$version|g" \ sed -e "s|@UUR_VERSION@|$version|g" \
-e "s|@UUR_PROJECT_ROOT@|$project_root|g" \ -e "s|@UUR_PROJECT_ROOT@|$project_root|g" \
"$project_root/packaging/arch/PKGBUILD.in" >"$build_dir/PKGBUILD" "$project_root/packaging/arch/PKGBUILD.in" >"$build_dir/PKGBUILD"
+1
View File
@@ -15,6 +15,7 @@ find "$output" -maxdepth 1 -type f \
cargo build --manifest-path "$project_root/Cargo.toml" --release --locked cargo build --manifest-path "$project_root/Cargo.toml" --release --locked
"$project_root/hook/build.sh" "$project_root/hook/build.sh"
"$project_root/capture/build.sh" "$project_root/capture/build.sh"
"$project_root/compat/build.sh"
"$project_root/packaging/stage.sh" "$stage" "$project_root/packaging/stage.sh" "$stage"
tar --zstd -C "$stage" -cf "$output/uur-${version}-linux-x86_64.tar.zst" . tar --zstd -C "$stage" -cf "$output/uur-${version}-linux-x86_64.tar.zst" .
+10 -3
View File
@@ -24,6 +24,9 @@ overrides:
- wine - wine
- curl - curl
- libpipewire-0.3-0 - libpipewire-0.3-0
- libwayland-client0
- libx11-6
- libxext6
- xdg-desktop-portal - xdg-desktop-portal
recommends: recommends:
- xdg-desktop-portal-gnome | xdg-desktop-portal-kde | xdg-desktop-portal-wlr - xdg-desktop-portal-gnome | xdg-desktop-portal-kde | xdg-desktop-portal-wlr
@@ -35,11 +38,15 @@ overrides:
rpm: rpm:
depends: depends:
- glibc - glibc
- libgcc - "libgcc_s.so.1()(64bit)"
- glib2 - /usr/bin/gdbus
- /usr/bin/gsettings
- wine - wine
- curl - curl
- pipewire-libs - "libpipewire-0.3.so.0()(64bit)"
- "libwayland-client.so.0()(64bit)"
- "libX11.so.6()(64bit)"
- "libXext.so.6()(64bit)"
- xdg-desktop-portal - xdg-desktop-portal
recommends: recommends:
- ethtool - ethtool
+1
View File
@@ -12,4 +12,5 @@ printf '%s\n' \
'The setup command downloads the official client from NetEase.' \ 'The setup command downloads the official client from NetEase.' \
'The --accept-eula flag records that you accepted the upstream EULA.' \ 'The --accept-eula flag records that you accepted the upstream EULA.' \
'Run setup without that flag only when you want to read the EULA URL first.' 'Run setup without that flag only when you want to read the EULA URL first.'
printf 'To remove user data completely, run %s uninstall --purge before removing the system package.\n' "$command_name"
printf '\n' printf '\n'
+6
View File
@@ -10,6 +10,10 @@ install -Dm0755 "$uur_binary" \
"$destination$prefix/bin/uur" "$destination$prefix/bin/uur"
install -Dm0755 "$project_root/capture/uur-pw-capture" \ install -Dm0755 "$project_root/capture/uur-pw-capture" \
"$destination$prefix/lib/uur/uur-pw-capture" "$destination$prefix/lib/uur/uur-pw-capture"
install -Dm0755 "$project_root/capture/uur-wl-capture" \
"$destination$prefix/lib/uur/uur-wl-capture"
install -Dm0755 "$project_root/build/compat/libuur-lock-mods.so" \
"$destination$prefix/lib/uur/libuur-lock-mods.so"
install -Dm0755 "$project_root/packaging/post-install-message" \ install -Dm0755 "$project_root/packaging/post-install-message" \
"$destination$prefix/lib/uur/post-install-message" "$destination$prefix/lib/uur/post-install-message"
for component in wevtapi.dll uur-hook.dll wtsapi32.dll winlogon.exe uur-terminal-proxy.exe uur-mux-proxy.exe uur-launch-proxy.exe; do for component in wevtapi.dll uur-hook.dll wtsapi32.dll winlogon.exe uur-terminal-proxy.exe uur-mux-proxy.exe uur-launch-proxy.exe; do
@@ -30,3 +34,5 @@ install -Dm0644 "$project_root/LICENSE" \
"$destination$prefix/share/licenses/uur/LICENSE" "$destination$prefix/share/licenses/uur/LICENSE"
install -Dm0644 "$project_root/NOTICE" \ install -Dm0644 "$project_root/NOTICE" \
"$destination$prefix/share/licenses/uur/NOTICE" "$destination$prefix/share/licenses/uur/NOTICE"
install -Dm0644 "$project_root/capture/wlr-screencopy-unstable-v1.xml" \
"$destination$prefix/share/licenses/uur/wlr-screencopy-unstable-v1.xml"
+7
View File
@@ -9,6 +9,13 @@ Comment[zh_CN]=在本 Linux 桌面启动完整的 UU 远程会话
Exec=uur run Exec=uur run
TryExec=uur TryExec=uur
Icon=uur Icon=uur
StartupWMClass=gameviewer.exe
Terminal=false Terminal=false
Categories=Network;RemoteAccess; Categories=Network;RemoteAccess;
Keywords=remote;desktop;uu;网易;远程; Keywords=remote;desktop;uu;网易;远程;
Actions=Quit;
[Desktop Action Quit]
Name=Quit
Name[zh_CN]=退出
Exec=uur stop
+1
View File
@@ -17,3 +17,4 @@ cc -std=c11 -O2 -Wall -Wextra -Werror \
"$temporary/cursor-overlay" "$temporary/cursor-overlay"
"$project_root/hook/build.sh" "$project_root/hook/build.sh"
"$project_root/capture/build.sh" "$project_root/capture/build.sh"
"$project_root/compat/build.sh"
+38 -7
View File
@@ -7,39 +7,70 @@ set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)
readonly root readonly root
prefix="${UUR_INSTALL_PREFIX:-$HOME/.local}" prefix="${UUR_INSTALL_PREFIX:-$HOME/.local}"
data_home="${XDG_DATA_HOME:-$HOME/.local/share}"
[[ "$prefix" = /* && "$data_home" = /* && "$prefix" != *$'\n'* && "$data_home" != *$'\n'* ]] || {
printf 'install prefix and XDG_DATA_HOME must be absolute paths without newlines\n' >&2
exit 1
}
[[ -x "$root/target/release/uur" ]] || { [[ -x "$root/target/release/uur" ]] || {
printf 'missing %s — run: cargo build --release\n' \ printf 'missing %s — run: cargo build --release\n' \
"$root/target/release/uur" >&2 "$root/target/release/uur" >&2
exit 1 exit 1
} }
[[ -f "$root/build/hook/wevtapi.dll" && -f "$root/build/hook/uur-hook.dll" ]] || { components=(wevtapi.dll uur-hook.dll wtsapi32.dll winlogon.exe uur-terminal-proxy.exe uur-mux-proxy.exe uur-launch-proxy.exe)
printf 'missing hook DLLs — run: ./hook/build.sh\n' >&2 for component in "${components[@]}"; do
[[ -f "$root/build/hook/$component" ]] || {
printf 'missing hook component %s — run: ./hook/build.sh\n' "$component" >&2
exit 1
}
done
[[ -f "$root/capture/uur-pw-capture" && -f "$root/capture/uur-wl-capture" ]] || {
printf 'missing capture helper — run: ./capture/build.sh\n' >&2
exit 1 exit 1
} }
[[ -f "$root/capture/uur-pw-capture" ]] || { [[ -f "$root/build/compat/libuur-lock-mods.so" ]] || {
printf 'missing capture helper — run: ./capture/build.sh\n' >&2 printf 'missing lock-modifier shim — run: ./compat/build.sh\n' >&2
exit 1 exit 1
} }
install -Dm0755 "$root/target/release/uur" "$prefix/bin/uur" install -Dm0755 "$root/target/release/uur" "$prefix/bin/uur"
for helper in uur-pw-capture; do for helper in uur-pw-capture uur-wl-capture; do
install -Dm0755 "$root/capture/$helper" "$prefix/lib/uur/$helper" install -Dm0755 "$root/capture/$helper" "$prefix/lib/uur/$helper"
done done
for dll in wevtapi.dll uur-hook.dll winlogon.exe uur-terminal-proxy.exe; do install -Dm0755 "$root/build/compat/libuur-lock-mods.so" \
"$prefix/lib/uur/libuur-lock-mods.so"
for dll in "${components[@]}"; do
install -Dm0644 "$root/build/hook/$dll" "$prefix/lib/uur/hook/$dll" install -Dm0644 "$root/build/hook/$dll" "$prefix/lib/uur/hook/$dll"
done done
# Menu entry: absolute Exec path so the user's PATH is irrelevant. # Menu entry: absolute Exec path so the user's PATH is irrelevant.
install -Dm0644 "$root/packaging/uur.desktop" \ install -Dm0644 "$root/packaging/uur.desktop" \
"$prefix/share/applications/uur.desktop" "$prefix/share/applications/uur.desktop"
sed -i "s|^Exec=.*|Exec=$prefix/bin/uur run|; s|^TryExec=.*|TryExec=$prefix/bin/uur|" \ # Escape Desktop Entry quoted arguments, then escape the sed replacement.
desktop_binary="$prefix/bin/uur"
desktop_binary="${desktop_binary//\\/\\\\}"
desktop_binary="${desktop_binary//\"/\\\"}"
desktop_binary="${desktop_binary//\$/\\\$}"
desktop_binary="${desktop_binary//\`/\\\`}"
sed_binary="${desktop_binary//\\/\\\\}"
sed_binary="${sed_binary//&/\\&}"
sed_binary="${sed_binary//|/\\|}"
try_binary="$prefix/bin/uur"
try_binary="${try_binary//\\/\\\\}"
try_binary="${try_binary//&/\\&}"
try_binary="${try_binary//|/\\|}"
sed -i "s|^Exec=uur |Exec=\"$sed_binary\" |; s|^TryExec=uur$|TryExec=$try_binary|" \
"$prefix/share/applications/uur.desktop" "$prefix/share/applications/uur.desktop"
if [[ -f "$root/packaging/uur-icon.png" ]]; then if [[ -f "$root/packaging/uur-icon.png" ]]; then
install -Dm0644 "$root/packaging/uur-icon.png" \ install -Dm0644 "$root/packaging/uur-icon.png" \
"$prefix/share/icons/hicolor/256x256/apps/uur.png" "$prefix/share/icons/hicolor/256x256/apps/uur.png"
fi fi
# Only the source installer writes this receipt. Package managers own their
# system files; uur uninstall must not remove those behind their backs.
printf 'uur-user-install-v1\n%s/uur\n' "${data_home%/}" > "$prefix/lib/uur/user-install"
printf 'installed:\n %s/bin/uur\n %s/lib/uur/\n %s/share/applications/uur.desktop\n' \ printf 'installed:\n %s/bin/uur\n %s/lib/uur/\n %s/share/applications/uur.desktop\n' \
"$prefix" "$prefix" "$prefix" "$prefix" "$prefix" "$prefix"
UUR_COMMAND="$prefix/bin/uur" "$root/packaging/post-install-message" UUR_COMMAND="$prefix/bin/uur" "$root/packaging/post-install-message"
+111 -1
View File
@@ -4,6 +4,116 @@ use anyhow::{Context, Result};
use std::path::Path; use std::path::Path;
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
fn pactl(arguments: &[&str]) -> Result<String> {
let output = Command::new("pactl")
.args(arguments)
.env("LC_ALL", "C")
.stdin(Stdio::null())
.output()
.context("querying PulseAudio; install pactl and enable PulseAudio or pipewire-pulse")?;
anyhow::ensure!(
output.status.success(),
"pactl failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
Ok(String::from_utf8(output.stdout)?.trim().to_owned())
}
/// Resolve only a real, available source. Explicit loopback selection must
/// fail if unavailable rather than silently capturing a physical microphone.
pub fn capture_source(selection: Option<&str>) -> Result<Option<String>> {
let Some(selection) = selection else {
return Ok(None);
};
anyhow::ensure!(
!selection.is_empty() && !selection.chars().any(char::is_control),
"invalid audio source name"
);
let sources: Vec<serde_json::Value> =
serde_json::from_str(&pactl(&["--format=json", "list", "sources"])?)?;
let name = if selection == "system" {
let default = pactl(&["get-default-sink"])?;
let sinks: Vec<serde_json::Value> =
serde_json::from_str(&pactl(&["--format=json", "list", "sinks"])?)?;
sinks
.iter()
.find(|sink| sink["name"].as_str() == Some(&default))
.and_then(|sink| sink["monitor_source"].as_str())
.context("the default output has no system-audio monitor source")?
.to_owned()
} else {
selection.to_owned()
};
anyhow::ensure!(sources.iter().any(|source| source["name"].as_str() == Some(&name)),
"audio source {name:?} is unavailable; use `uur audio sources` to choose an available source");
Ok(Some(name))
}
pub fn print_sources() -> Result<()> {
let sources: Vec<serde_json::Value> =
serde_json::from_str(&pactl(&["--format=json", "list", "sources"])?)?;
println!("Default source: {}", pactl(&["get-default-source"])?);
for source in sources {
let name = source["name"]
.as_str()
.context("audio source has no name")?;
let description = source["description"].as_str().unwrap_or(name);
let monitor = source["monitor_source"].as_str().is_some()
|| source["monitor_of_sink"]
.as_u64()
.is_some_and(|index| index != u64::from(u32::MAX));
println!(
"{name}\t{}\t{description}",
if monitor {
"system monitor"
} else {
"capture input"
}
);
}
Ok(())
}
pub fn configure_source(selection: &str) -> Result<()> {
let choice = (selection != "default").then_some(selection);
let resolved = capture_source(choice)?;
crate::config::Config::update(|stored| {
stored.audio_capture_source = choice.map(ToOwned::to_owned)
})?;
println!(
"Wine default audio capture: {}; applies after `uur stop` and `uur run`",
resolved
.as_deref()
.unwrap_or("follow the existing audio environment")
);
if choice == Some("system") {
println!("The fallback capture input will carry system sound. Separate simultaneous microphone and speaker channels still require the official audio driver.");
}
Ok(())
}
pub(crate) fn apply_capture_env(
command: &mut Command,
config: &crate::config::Config,
) -> Result<()> {
if config.audio_capture_source.is_none() {
return Ok(());
}
// Each process resolves once, before starting the managed wineserver/SCM.
static SOURCE: std::sync::OnceLock<std::result::Result<Option<String>, String>> =
std::sync::OnceLock::new();
match SOURCE.get_or_init(|| {
capture_source(config.audio_capture_source.as_deref()).map_err(|e| format!("{e:#}"))
}) {
Ok(Some(source)) => {
command.env("PULSE_SOURCE", source);
}
Ok(None) => {}
Err(error) => anyhow::bail!("Wine audio capture unavailable: {error}"),
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend { pub enum Backend {
PipeWirePulse, PipeWirePulse,
@@ -52,7 +162,7 @@ pub fn sync_wine(prefix: &Path) -> Result<Backend> {
Backend::None => None, Backend::None => None,
}; };
if let Some(driver) = driver { if let Some(driver) = driver {
let status = Command::new("wine") let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all") .env("WINEDEBUG", "-all")
.args([ .args([
+2 -1
View File
@@ -9,10 +9,11 @@ pub fn enable() -> Result<()> {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
let executable = std::env::current_exe().context("resolving uur executable")?; let executable = std::env::current_exe().context("resolving uur executable")?;
let exec = desktop_exec_argument(&executable.to_string_lossy()); let exec = desktop_exec_argument(&executable.to_string_lossy());
let prefix = crate::config::data_dir()?.join("wine");
std::fs::write( std::fs::write(
&path, &path,
format!( format!(
"[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\n" "[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\nX-UUR-Managed=true\nX-UUR-Prefix={}\n", prefix.display()
), ),
)?; )?;
println!( println!(
+86 -6
View File
@@ -133,8 +133,16 @@ pub fn print_pointer() -> Result<()> {
/// input events without holding the backend lock while waiting for records. /// input events without holding the backend lock while waiting for records.
pub fn serve() -> Result<()> { pub fn serve() -> Result<()> {
let config = Config::load()?; let config = Config::load()?;
let preferred = let mut preferred =
std::env::var("UUR_INPUT_BACKEND").unwrap_or_else(|_| config.input_backend.clone()); std::env::var("UUR_INPUT_BACKEND").unwrap_or_else(|_| config.input_backend.clone());
if config.capture_backend == "wayland" {
if preferred == "auto" {
preferred = "uinput".into();
}
if preferred == "portal" {
anyhow::bail!("direct Wayland capture uses uinput; choose UUR_INPUT_BACKEND=uinput or return to portal capture");
}
}
let selected = input::select(&preferred)?; let selected = input::select(&preferred)?;
if let Some(path) = std::env::var_os("UUR_BACKEND_STATUS") { if let Some(path) = std::env::var_os("UUR_BACKEND_STATUS") {
std::fs::write(path, selected.name()).context("writing backend status")?; std::fs::write(path, selected.name()).context("writing backend status")?;
@@ -148,25 +156,48 @@ pub fn serve() -> Result<()> {
let backend_handle = backend.clone(); let backend_handle = backend.clone();
let addr = format!("127.0.0.1:{}", config.bridge_port); let addr = format!("127.0.0.1:{}", config.bridge_port);
let listener = TcpListener::bind(&addr).with_context(|| format!("binding {addr}"))?; let listener = TcpListener::bind(&addr).with_context(|| format!("binding {addr}"))?;
listener.set_nonblocking(true)?;
println!("{}", t!("bridge.listening", port = config.bridge_port)); println!("{}", t!("bridge.listening", port = config.bridge_port));
// The service process hooks itself too, so multiple authenticated // The service process hooks itself too, so multiple authenticated
// connections coexist; each gets its own thread. Injection is // connections coexist; each gets its own thread. Injection is
// serialized through the single backend. // serialized through the single backend.
for stream in listener.incoming() { loop {
let stream = match stream { backend.lock().unwrap().backend.check_health()?;
Ok(s) => s, let stream = match listener.accept() {
Err(_) => continue, Ok((stream, _)) => stream,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(std::time::Duration::from_millis(50));
continue;
}
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::Interrupted | std::io::ErrorKind::ConnectionAborted
) =>
{
continue
}
Err(error) => return Err(error).context("accepting hook connection"),
}; };
let config = config.clone(); let config = config.clone();
let backend_handle = backend_handle.clone(); let backend_handle = backend_handle.clone();
thread::spawn(move || { thread::spawn(move || {
let mut stream = stream; let mut stream = stream;
if stream
.set_read_timeout(Some(std::time::Duration::from_secs(5)))
.is_err()
{
return;
}
match authenticate(&mut stream, &config) { match authenticate(&mut stream, &config) {
Ok(true) => {} Ok(true) => {}
Ok(false) => return, Ok(false) => return,
Err(_) => return, Err(_) => return,
} }
if stream.set_read_timeout(None).is_err() {
return;
}
use input::InputBackend; use input::InputBackend;
// Read sockets without holding the shared desktop input lock. // Read sockets without holding the shared desktop input lock.
let mut connection = ConnectionInput { let mut connection = ConnectionInput {
@@ -191,7 +222,6 @@ pub fn serve() -> Result<()> {
let _ = connection.release_all(); let _ = connection.release_all();
}); });
} }
Ok(())
} }
fn authenticate(stream: &mut TcpStream, config: &Config) -> Result<bool> { fn authenticate(stream: &mut TcpStream, config: &Config) -> Result<bool> {
@@ -219,6 +249,7 @@ fn pump(stream: &mut TcpStream, backend: &mut dyn input::InputBackend) -> Result
let mut header = [0u8; protocol::HEADER_BYTES]; let mut header = [0u8; protocol::HEADER_BYTES];
let mut record = [0u8; RECORD_BYTES]; let mut record = [0u8; RECORD_BYTES];
let mut injected: u64 = 0; let mut injected: u64 = 0;
let mut warned_unsupported_key = false;
loop { loop {
// EOF is the hook exiting: a clean disconnect, not an error. // EOF is the hook exiting: a clean disconnect, not an error.
match stream.read_exact(&mut header) { match stream.read_exact(&mut header) {
@@ -236,6 +267,19 @@ fn pump(stream: &mut TcpStream, backend: &mut dyn input::InputBackend) -> Result
protocol::RECORD_MOUSE | protocol::RECORD_KEYBOARD => { protocol::RECORD_MOUSE | protocol::RECORD_KEYBOARD => {
stream.read_exact(&mut record)?; stream.read_exact(&mut record)?;
let record = protocol::read_record(&record); let record = protocol::read_record(&record);
if record.kind == protocol::RECORD_KEYBOARD && record.code == 0 {
// Unicode and scan-code SendInput events do not carry a
// virtual-key code. Text/scan-code transport is not
// supported yet, but one such event must not tear down
// the connection and block later ordinary key events.
if !warned_unsupported_key {
eprintln!(
"ignoring keyboard input without a virtual-key code; Unicode and scan-code input are not supported yet"
);
warned_unsupported_key = true;
}
continue;
}
dispatch(backend, &record)?; dispatch(backend, &record)?;
injected += 1; injected += 1;
} }
@@ -302,6 +346,9 @@ mod tests {
"test" "test"
} }
fn key(&mut self, code: u16, down: bool) -> Result<()> { fn key(&mut self, code: u16, down: bool) -> Result<()> {
if code == 0 {
anyhow::bail!("invalid virtual-key code");
}
self.0.send(format!("key {code} {down}"))?; self.0.send(format!("key {code} {down}"))?;
Ok(()) Ok(())
} }
@@ -342,6 +389,39 @@ mod tests {
) )
} }
fn input_packet(kind: u32, code: u16, state: u16) -> Vec<u8> {
let mut packet = Vec::new();
for value in [protocol::MAGIC, protocol::VERSION, kind, 16, kind] {
packet.extend_from_slice(&value.to_le_bytes());
}
packet.extend_from_slice(&code.to_le_bytes());
packet.extend_from_slice(&state.to_le_bytes());
packet.extend_from_slice(&0i32.to_le_bytes());
packet.extend_from_slice(&0i32.to_le_bytes());
packet
}
#[test]
fn zero_virtual_key_does_not_disconnect_later_keyboard_input() {
let (shared, events) = shared();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let (mut server, _) = listener.accept().unwrap();
let mut backend = connection(&shared);
let thread = thread::spawn(move || pump(&mut server, &mut backend).unwrap());
client
.write_all(&input_packet(protocol::RECORD_KEYBOARD, 0, 1))
.unwrap();
client
.write_all(&input_packet(protocol::RECORD_KEYBOARD, 65, 1))
.unwrap();
drop(client);
assert_eq!(thread.join().unwrap(), 1);
assert_eq!(events.try_iter().collect::<Vec<_>>(), ["key 65 true"]);
}
#[test] #[test]
fn idle_connection_does_not_block_another_connections_motion() { fn idle_connection_does_not_block_another_connections_motion() {
let (shared, events) = shared(); let (shared, events) = shared();
+541 -65
View File
@@ -1,9 +1,9 @@
//! Portal side of the capture path. //! Portal side of the capture path.
//! //!
//! Negotiates an xdg-desktop-portal ScreenCast session, obtains a private //! Negotiates an xdg-desktop-portal ScreenCast session, obtains a private
//! PipeWire file descriptor and the video node id, then hands both to the //! PipeWire file descriptor and the consented video nodes, then hands them to
//! C capture helper (`uur-pw-capture`) which runs the PipeWire stream and //! the C capture helper (`uur-pw-capture`) which runs the PipeWire streams and
//! publishes frames into a private XDG runtime file (see //! composites their frames into a private XDG runtime file (see
//! docs/capture-protocol.md). //! docs/capture-protocol.md).
//! //!
//! Consent: the first run shows the compositor's share dialog once. The //! Consent: the first run shows the compositor's share dialog once. The
@@ -13,30 +13,333 @@
//! a headless remote host. //! a headless remote host.
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use futures::{FutureExt, StreamExt};
use std::io::Read;
use std::os::fd::AsRawFd; use std::os::fd::AsRawFd;
use std::os::fd::OwnedFd; use std::os::fd::OwnedFd;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::process::{Child, Command}; use std::process::{Child, Command};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::config::Config; use crate::config::Config;
const FRAME_PROTOCOL_VERSION: u32 = 3;
type PortalSession =
ashpd::desktop::Session<'static, ashpd::desktop::screencast::Screencast<'static>>;
struct PortalCapture {
fd: OwnedFd,
streams: Vec<CaptureStream>,
restore_token: Option<String>,
session: PortalSession,
closed: zbus::proxy::SignalStream<'static>,
}
#[derive(Clone, Debug)]
pub(crate) struct CaptureStream {
pub(crate) node: u32,
pub(crate) x: i32,
pub(crate) y: i32,
pub(crate) width: u32,
pub(crate) height: u32,
}
/// Run the capture path until interrupted. /// Run the capture path until interrupted.
pub fn run_standalone() -> Result<()> {
// Public capture uses the same lifecycle lock as run/setup so stop and
// uninstall can also shut down a diagnostic ScreenCast session. Internal
// capture already runs under the supervisor's lock.
let _session_lock = crate::session::acquire_session_lock()?;
run()
}
pub fn run() -> Result<()> { pub fn run() -> Result<()> {
let mut config = Config::load()?; let mut config = Config::load()?;
let (pw_fd, node) = portal_session(&mut config)?; let stopping = Arc::new(AtomicBool::new(false));
println!("{}", t!("capture.session_ready", node = node)); signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?;
signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?;
let mut helper = spawn_helper(pw_fd, node)?; if config.capture_backend == "wayland" {
let status = helper.wait().context("waiting for capture helper")?; if config.capture_source != "monitor" {
if !status.success() { anyhow::bail!("direct Wayland capture requires a monitor source");
anyhow::bail!("{}", t!("capture.helper_failed")); }
let mut command = Command::new(find_helper("uur-wl-capture")?);
command.env("UUR_FRAME_PATH", frame_path()?);
if let Some(output) = &config.capture_output {
command.env("UUR_CAPTURE_OUTPUT", output);
}
let mut helper = CaptureHelper(command.spawn().context("starting direct Wayland capture")?);
println!("{}", t!("capture.direct_started"));
while !stopping.load(Ordering::Relaxed) {
if let Some(status) = helper.0.try_wait()? {
if !status.success() {
anyhow::bail!("direct Wayland capture failed ({status})");
}
return Ok(());
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
return Ok(());
} }
Ok(()) if config.capture_backend != "portal" {
anyhow::bail!("unknown capture backend {:?}", config.capture_backend);
}
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.context("creating capture runtime")?;
// The portal's D-Bus connection runs on this runtime. Keep it running
// throughout capture, including on capture-only compositors such as niri.
runtime.block_on(async {
let frames = frame_path()?;
let mut failures = 0;
let mut initial_session = true;
let mut display_changes = watch_display_changes().await;
loop {
let opened = tokio::select! {
result = portal_session(&mut config, initial_session) => result,
_ = wait_for_stop(&stopping) => return Ok(()),
};
let PortalCapture {
fd: pw_fd,
streams,
session,
mut closed,
..
} = match opened {
Ok(opened) => opened,
Err(error) if !initial_session && failures < 3 && !user_cancelled(&error) => {
failures += 1;
eprintln!("capture reconnect {failures}/3 failed: {error:#}");
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(1)) => continue,
_ = wait_for_stop(&stopping) => return Ok(()),
}
}
Err(error) => return Err(error),
};
initial_session = false;
let nodes = streams
.iter()
.map(|stream| stream.node.to_string())
.collect::<Vec<_>>()
.join(",");
println!("{}", t!("capture.session_ready", node = nodes));
match std::fs::remove_file(&frames) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("retiring the previous capture transport"),
}
let mut helper = CaptureHelper(spawn_capture_helper(pw_fd, &streams)?);
let mut healthy_since = None;
let mut portal_closed = false;
let mut reconfigure = false;
let status = loop {
tokio::select! {
biased;
_ = wait_for_stop(&stopping) => break None,
_ = closed.next() => {
// Mutter can close the old stream before forwarding
// MonitorsChanged. Correlate that layout transaction;
// a user Stop without a display change stays closed.
reconfigure = tokio::time::timeout(
Duration::from_millis(250),
next_display_change(&mut display_changes),
).await.is_ok();
portal_closed = !reconfigure;
break None;
}
_ = next_display_change(&mut display_changes) => {
reconfigure = true;
break None;
}
_ = tokio::time::sleep(Duration::from_millis(50)) => {
if has_frame(&frames) && healthy_since.is_none() {
healthy_since = Some(Instant::now());
}
if helper_stalled(&frames) {
eprintln!("capture helper heartbeat expired; reconnecting");
break None;
}
if let Some(status) = helper.0.try_wait()
.context("waiting for capture helper")? {
break Some(status);
}
}
}
};
drop(closed);
drop(helper);
let _ = tokio::time::timeout(Duration::from_secs(2), session.close()).await;
if stopping.load(Ordering::Relaxed) {
return Ok(());
}
// Closed without a matching layout change means Stop sharing.
// Never silently restore that permission or use direct capture.
if portal_closed {
anyhow::bail!(
"screen sharing was closed by the portal; restart uur run to share again"
);
}
if healthy_since.is_some_and(|since| since.elapsed() >= Duration::from_secs(30)) {
failures = 0;
}
if reconfigure {
eprintln!("display configuration changed; restoring capture");
} else {
failures += 1;
if failures > 3 {
anyhow::bail!(
"capture recovery failed repeatedly; restart uur run to share again"
);
}
if status
.as_ref()
.is_some_and(|status| !matches!(status.code(), Some(0 | 75) | None))
{
anyhow::bail!(
"{} ({status:?}); capture recovery stopped",
t!("capture.helper_failed")
);
}
eprintln!("capture stream interrupted ({status:?}); reconnecting {failures}/3");
}
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(1)) => {},
_ = wait_for_stop(&stopping) => return Ok(()),
}
// Several signals can describe one layout transaction. The next
// handshake reads the final layout rather than replaying each one.
if reconfigure {
while let Some(stream) = display_changes.as_mut() {
match stream.next().now_or_never() {
Some(Some(_)) => {}
Some(None) => {
display_changes = None;
break;
}
None => break,
}
}
}
}
})
}
pub(crate) async fn watch_display_changes() -> Option<zbus::proxy::SignalStream<'static>> {
let connection = zbus::Connection::session().await.ok()?;
let bus = zbus::fdo::DBusProxy::new(&connection).await.ok()?;
let name = "org.gnome.Mutter.DisplayConfig".try_into().ok()?;
if !bus.name_has_owner(name).await.ok()? {
return None;
}
drop(bus);
let proxy = zbus::Proxy::new_owned(
connection,
"org.gnome.Mutter.DisplayConfig",
"/org/gnome/Mutter/DisplayConfig",
"org.gnome.Mutter.DisplayConfig",
)
.await
.ok()?;
proxy.receive_signal("MonitorsChanged").await.ok()
}
pub(crate) async fn next_display_change(changes: &mut Option<zbus::proxy::SignalStream<'static>>) {
loop {
match changes.as_mut() {
Some(stream) => {
if stream.next().await.is_some() {
return;
}
*changes = None;
}
None => std::future::pending::<()>().await,
}
}
}
async fn wait_for_stop(stopping: &AtomicBool) {
while !stopping.load(Ordering::Relaxed) {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
}
pub(crate) struct CaptureHelper(pub(crate) Child);
impl Drop for CaptureHelper {
fn drop(&mut self) {
if self.0.try_wait().ok().flatten().is_some() {
return;
}
unsafe {
libc::kill(self.0.id() as i32, libc::SIGTERM);
}
for _ in 0..100 {
if self.0.try_wait().ok().flatten().is_some() {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let _ = self.0.kill();
let _ = self.0.wait();
}
}
pub(crate) fn has_frame(path: &Path) -> bool {
let mut header = [0u8; 64];
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
if file.read_exact(&mut header).is_err() {
return false;
}
let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap());
field(0) == 0x4652_5555
&& field(4) == FRAME_PROTOCOL_VERSION
&& field(8) > 0
&& field(12) > 0
&& field(16) >= field(8).saturating_mul(4)
&& field(20) == 1
&& (1..=16).contains(&field(36))
&& u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0
}
/// The producer heartbeat advances even when the desktop is static. A zero
/// value belongs to a producer without heartbeat support, never a stale frame.
pub(crate) fn helper_stalled(path: &Path) -> bool {
let mut header = [0u8; 48];
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
if file.read_exact(&mut header).is_err()
|| u32::from_le_bytes(header[4..8].try_into().unwrap()) != FRAME_PROTOCOL_VERSION
{
return false;
}
let heartbeat = u64::from_le_bytes(header[40..48].try_into().unwrap());
let mut now: libc::timespec = unsafe { std::mem::zeroed() };
if heartbeat == 0 || unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now) } != 0 {
return false;
}
let milliseconds = (now.tv_sec as u64).saturating_mul(1000) + now.tv_nsec as u64 / 1_000_000;
milliseconds.saturating_sub(heartbeat) > 10_000
} }
/// Start the native PipeWire consumer with a portal-owned descriptor. The /// Start the native PipeWire consumer with a portal-owned descriptor. The
/// descriptor remains private to the child and is never reopened by path. /// descriptor remains private to the child and is never reopened by path.
pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> { pub(crate) fn spawn_helper(pw_fd: OwnedFd, streams: &[CaptureStream]) -> Result<Child> {
spawn_capture_helper(pw_fd, streams)
}
fn spawn_capture_helper(pw_fd: OwnedFd, streams: &[CaptureStream]) -> Result<Child> {
anyhow::ensure!(!streams.is_empty(), "ScreenCast returned no streams");
anyhow::ensure!(
streams.len() <= 16,
"too many ScreenCast streams (maximum 16)"
);
// The helper inherits this descriptor: strip close-on-exec and keep the // The helper inherits this descriptor: strip close-on-exec and keep the
// OwnedFd alive across the spawn (closing it would invalidate the number // OwnedFd alive across the spawn (closing it would invalidate the number
// the child receives). // the child receives).
@@ -51,11 +354,21 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
} }
} }
let helper = find_helper()?; let helper = find_helper("uur-pw-capture")?;
let mut command = Command::new(&helper); let mut command = Command::new(&helper);
let stream_specs = streams
.iter()
.map(|stream| {
format!(
"{},{},{},{},{}",
stream.node, stream.x, stream.y, stream.width, stream.height
)
})
.collect::<Vec<_>>()
.join(";");
command command
.env("UUR_PW_FD", raw.to_string()) .env("UUR_PW_FD", raw.to_string())
.env("UUR_PW_NODE", node.to_string()) .env("UUR_PW_STREAMS", stream_specs)
.env("UUR_FRAME_PATH", frame_path()?); .env("UUR_FRAME_PATH", frame_path()?);
if let Ok(debug) = std::env::var("UUR_PW_DEBUG") { if let Ok(debug) = std::env::var("UUR_PW_DEBUG") {
command.env("PIPEWIRE_DEBUG", debug); command.env("PIPEWIRE_DEBUG", debug);
@@ -66,81 +379,201 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
Ok(child) Ok(child)
} }
fn frame_path() -> Result<PathBuf> { pub(crate) fn frame_path() -> Result<PathBuf> {
if let Some(path) = std::env::var_os("UUR_FRAME_PATH") { if let Some(path) = std::env::var_os("UUR_FRAME_PATH") {
return Ok(PathBuf::from(path)); return Ok(PathBuf::from(path));
} }
Ok(crate::config::runtime_dir()?.join("frames.v1")) Ok(crate::config::runtime_dir()?.join("frames.v3"))
} }
/// Open the portal session and return (inherited fd number, node id). /// Open the portal session and return its PipeWire streams and node ids.
/// First attempt reuses the stored restore token; if that fails (stale /// First attempt reuses the stored restore token; if that fails (stale
/// token, monitor changed, compositor restart) fall back to one /// token, monitor changed, compositor restart) fall back to one
/// interactive attempt and store the fresh token. /// interactive attempt and store the fresh token.
#[allow(clippy::type_complexity)] async fn portal_session(config: &mut Config, interactive: bool) -> Result<PortalCapture> {
fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
let saved_token = config.capture_restore_token.clone(); let saved_token = config.capture_restore_token.clone();
let runtime = tokio::runtime::Runtime::new().context("creating tokio runtime")?; let screencast = ashpd::desktop::screencast::Screencast::new()
runtime.block_on(async move { .await
let screencast = ashpd::desktop::screencast::Screencast::new() .context("connecting to the ScreenCast portal")?;
.await
.context("connecting to the ScreenCast portal")?;
let mut last_error = None; let mut last_error = None;
let source = source_type(&config.capture_source); let source = source_type(&config.capture_source);
for token in [saved_token.clone(), None] { for token in saved_token
match negotiate(&screencast, source, token.as_deref()).await { .clone()
Ok((fd, node, fresh_token)) => { .map(Some)
if fresh_token != saved_token { .into_iter()
config.capture_restore_token = fresh_token; .chain(interactive.then_some(None))
config.store().context("storing the new restore token")?; {
} match negotiate(
return Ok((fd, node)); &screencast,
source,
config.capture_multiple,
token.as_deref(),
)
.await
{
Ok(capture) => {
if capture.restore_token != saved_token {
config.capture_restore_token = capture.restore_token.clone();
Config::update(|stored| {
if stored.capture_source == config.capture_source
&& stored.capture_multiple == config.capture_multiple
&& stored.capture_backend == config.capture_backend
{
stored.capture_restore_token = capture.restore_token.clone();
}
})
.context("storing the new restore token")?;
} }
Err(error) => { return Ok(capture);
last_error = Some(error); }
Err(error) => {
if user_cancelled(&error) {
return Err(error);
} }
last_error = Some(error);
} }
} }
Err(last_error.unwrap_or_else(|| anyhow!("portal session failed"))) }
Err(last_error.unwrap_or_else(|| {
anyhow!("capture permission could not be restored; restart uur run to share again")
}))
}
pub(crate) fn user_cancelled(error: &anyhow::Error) -> bool {
error.chain().any(|source| {
matches!(
source.downcast_ref::<ashpd::Error>(),
Some(ashpd::Error::Response(
ashpd::desktop::ResponseError::Cancelled
))
) || matches!(
source.downcast_ref::<ashpd::desktop::ResponseError>(),
Some(ashpd::desktop::ResponseError::Cancelled)
)
}) })
} }
/// Choose a cursor mode from the flags the portal advertises.
///
/// `Embedded` is what the capture path wants (the hook composites the cursor
/// itself on X11, and an embedded cursor is the closest match elsewhere), then
/// `Hidden`, then `Metadata`. `None` means the portal advertised no usable
/// mode at all.
fn choose_cursor_mode(
available: ashpd::enumflags2::BitFlags<ashpd::desktop::screencast::CursorMode>,
) -> Option<ashpd::desktop::screencast::CursorMode> {
use ashpd::desktop::screencast::CursorMode;
[
CursorMode::Embedded,
CursorMode::Hidden,
CursorMode::Metadata,
]
.into_iter()
.find(|mode| available.contains(*mode))
}
/// Pick a cursor mode the portal actually advertises.
///
/// `SelectSources` rejects a mode outside the portal's `AvailableCursorModes`
/// with `InvalidArgument: Unavailable cursor mode N`. A portal frontend whose
/// backend property cache is empty reports a zeroed set and rejects every
/// mode, so choosing from the advertised flags keeps capture working on
/// backends that offer only a subset and turns the unusable case into an
/// actionable message instead of a raw D-Bus error.
pub(crate) async fn preferred_cursor_mode(
screencast: &ashpd::desktop::screencast::Screencast<'_>,
) -> Result<ashpd::desktop::screencast::CursorMode> {
use ashpd::desktop::screencast::CursorMode;
let available = match screencast.available_cursor_modes().await {
Ok(modes) => modes,
// ScreenCast v2 introduced the property; older portals have no
// advertisement to consult, so keep the historical request.
Err(ashpd::Error::RequiresVersion(2, 0..=1)) => return Ok(CursorMode::Embedded),
Err(error) => return Err(error).context("reading ScreenCast cursor modes"),
};
let mode = choose_cursor_mode(available)
.ok_or_else(|| anyhow!("{}", t!("capture.cursor_unsupported")))?;
if mode != CursorMode::Embedded {
// The helper publishes pixels, not PipeWire cursor metadata.
eprintln!("{}", t!("capture.cursor_not_embedded"));
}
Ok(mode)
}
/// One full portal handshake. Returns the PipeWire fd, the video node id /// One full portal handshake. Returns the PipeWire fd, the video node id
/// and the restore token the portal issued for this selection. /// and the restore token the portal issued for this selection.
async fn negotiate( async fn negotiate(
screencast: &ashpd::desktop::screencast::Screencast<'_>, screencast: &ashpd::desktop::screencast::Screencast<'static>,
source: ashpd::desktop::screencast::SourceType, source: ashpd::desktop::screencast::SourceType,
multiple: bool,
restore_token: Option<&str>, restore_token: Option<&str>,
) -> Result<(OwnedFd, u32, Option<String>)> { ) -> Result<PortalCapture> {
use ashpd::desktop::screencast::CursorMode;
use ashpd::desktop::PersistMode; use ashpd::desktop::PersistMode;
let session = screencast.create_session().await?; let session = screencast.create_session().await?;
// Session.Closed carries a{sv}. ashpd 0.10 deserializes it as (), which
// silently drops the signal. Subscribe on the SAME connection (the
// frontend unicasts it) before starting, and ignore its optional details.
let serialized = serde_json::to_value(&session)?;
let path = serialized
.as_str()
.context("invalid portal session path")?
.to_owned();
let session_proxy = zbus::Proxy::new_owned(
screencast.connection().clone(),
"org.freedesktop.portal.Desktop",
path,
"org.freedesktop.portal.Session",
)
.await?;
let closed = session_proxy.receive_signal("Closed").await?;
let cursor_mode = preferred_cursor_mode(screencast).await?;
screencast screencast
.select_sources( .select_sources(
&session, &session,
CursorMode::Embedded, cursor_mode,
source.into(), source.into(),
false, multiple && matches!(source, ashpd::desktop::screencast::SourceType::Monitor),
restore_token, restore_token,
PersistMode::ExplicitlyRevoked, PersistMode::ExplicitlyRevoked,
) )
.await?; .await?
.response()?;
let response = screencast.start(&session, None).await?; let response = screencast.start(&session, None).await?;
let streams_response = response.response()?; let streams_response = response.response()?;
let streams = streams_response.streams(); let streams = streams_response
let stream = streams.first().context("no monitor selected")?; .streams()
let node = stream.pipe_wire_node_id(); .iter()
.map(|stream| {
let (x, y) = stream.position().unwrap_or((i32::MIN, i32::MIN));
let (width, height) = stream.size().unwrap_or((0, 0));
CaptureStream {
node: stream.pipe_wire_node_id(),
x,
y,
width: u32::try_from(width).unwrap_or(0),
height: u32::try_from(height).unwrap_or(0),
}
})
.collect::<Vec<_>>();
anyhow::ensure!(!streams.is_empty(), "no monitor selected");
let fresh_token = streams_response.restore_token().map(String::from); let fresh_token = streams_response.restore_token().map(String::from);
let fd = screencast let fd = screencast
.open_pipe_wire_remote(&session) .open_pipe_wire_remote(&session)
.await .await
.context("opening the PipeWire remote")?; .context("opening the PipeWire remote")?;
Ok((fd, node, fresh_token)) Ok(PortalCapture {
fd,
streams,
restore_token: fresh_token,
session,
closed,
})
} }
pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType { pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType {
@@ -152,34 +585,44 @@ pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType
} }
} }
fn find_helper() -> Result<PathBuf> { pub fn list_wayland_outputs() -> Result<()> {
let mut candidates = vec![ let status = Command::new(find_helper("uur-wl-capture")?)
PathBuf::from("/usr/lib/uur/uur-pw-capture"), .arg("--list-outputs")
PathBuf::from("/usr/local/lib/uur/uur-pw-capture"), .status()?;
]; anyhow::ensure!(status.success(), "could not enumerate Wayland outputs");
if let Ok(home) = std::env::var("HOME") { Ok(())
candidates.push(PathBuf::from(home).join(".local/lib/uur/uur-pw-capture")); }
}
fn find_helper(name: &str) -> Result<PathBuf> {
let mut candidates = Vec::new();
if let Ok(exe) = std::env::current_exe() { if let Ok(exe) = std::env::current_exe() {
// dev checkout: target/debug/uur -> capture/uur-pw-capture // dev checkout: target/debug/uur -> capture/uur-pw-capture
if let Some(dir) = exe.parent() { if let Some(dir) = exe.parent() {
candidates.push(dir.join("../lib/uur/uur-pw-capture")); candidates.push(dir.join("../lib/uur").join(name));
candidates.push(dir.join("../../capture/uur-pw-capture")); candidates.push(dir.join("../../capture").join(name));
candidates.push(dir.join("uur-pw-capture")); candidates.push(dir.join(name));
} }
} }
if let Ok(cwd) = std::env::current_dir() { candidates.push(PathBuf::from("/usr/lib/uur").join(name));
candidates.push(cwd.join("capture/uur-pw-capture")); candidates.push(PathBuf::from("/usr/local/lib/uur").join(name));
if let Ok(home) = std::env::var("HOME") {
candidates.push(PathBuf::from(home).join(".local/lib/uur").join(name));
} }
candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| { if let Ok(cwd) = std::env::current_dir() {
anyhow!("capture helper uur-pw-capture not found (build with capture/build.sh)") candidates.push(cwd.join("capture").join(name));
}) }
candidates
.into_iter()
.find(|p| p.is_file())
.ok_or_else(|| anyhow!("capture helper {name} not found (build with capture/build.sh)"))
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::choose_cursor_mode;
use super::source_type; use super::source_type;
use ashpd::desktop::screencast::SourceType; use ashpd::desktop::screencast::{CursorMode, SourceType};
use ashpd::enumflags2::BitFlags;
#[test] #[test]
fn configured_portal_source_is_mapped() { fn configured_portal_source_is_mapped() {
@@ -187,4 +630,37 @@ mod tests {
assert_eq!(source_type("window"), SourceType::Window); assert_eq!(source_type("window"), SourceType::Window);
assert_eq!(source_type("virtual"), SourceType::Virtual); assert_eq!(source_type("virtual"), SourceType::Virtual);
} }
#[test]
fn embedded_cursor_is_preferred_when_the_portal_offers_it() {
// gnome advertises 7 = Hidden | Embedded | Metadata.
let available = CursorMode::Hidden | CursorMode::Embedded | CursorMode::Metadata;
assert_eq!(choose_cursor_mode(available), Some(CursorMode::Embedded));
}
#[test]
fn a_backend_without_embedded_cursor_falls_back_instead_of_failing() {
// wlr advertises 3 = Hidden | Embedded; a metadata-only backend must
// still capture rather than requesting a mode the portal rejects.
assert_eq!(
choose_cursor_mode(CursorMode::Metadata.into()),
Some(CursorMode::Metadata)
);
assert_eq!(
choose_cursor_mode(CursorMode::Hidden.into()),
Some(CursorMode::Hidden)
);
assert_eq!(
choose_cursor_mode(CursorMode::Hidden | CursorMode::Metadata),
Some(CursorMode::Hidden)
);
}
#[test]
fn an_empty_advertisement_selects_no_mode() {
// Regression: a portal frontend with a zeroed backend property cache
// reported AvailableCursorModes = 0 and rejected every request with
// "InvalidArgument: Unavailable cursor mode 2".
assert_eq!(choose_cursor_mode(BitFlags::empty()), None);
}
} }
+122 -14
View File
@@ -1,6 +1,10 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
/// Persistent user configuration. Everything lives under the XDG state and /// Persistent user configuration. Everything lives under the XDG state and
/// config directories; the managed Wine prefix lives under data. /// config directories; the managed Wine prefix lives under data.
@@ -13,7 +17,7 @@ pub struct Config {
pub bridge_port: u16, pub bridge_port: u16,
/// Random per-install token the hook must present on HELLO. /// Random per-install token the hook must present on HELLO.
pub bridge_token: String, pub bridge_token: String,
/// Preferred input backend: "auto" | "xtest" | "portal". /// Preferred input backend: "auto" | "xtest" | "portal" | "uinput".
pub input_backend: String, pub input_backend: String,
/// Release channel pinned for provisioning. /// Release channel pinned for provisioning.
pub pinned_version: Option<String>, pub pinned_version: Option<String>,
@@ -24,6 +28,23 @@ pub struct Config {
pub remote_desktop_restore_token: Option<String>, pub remote_desktop_restore_token: Option<String>,
/// Portal source type: monitor, window, or virtual. /// Portal source type: monitor, window, or virtual.
pub capture_source: String, pub capture_source: String,
/// Multiple consented monitors are opt-in; existing grants stay intact.
pub capture_multiple: bool,
/// "portal" uses system consent; "wayland" is explicitly enabled direct monitor capture.
pub capture_backend: String,
/// Named Wayland output for direct capture; a single-output session needs no name.
pub capture_output: Option<String>,
/// Override Wine's default capture source: "system" or a PulseAudio source
/// name. None follows the user's existing audio environment.
pub audio_capture_source: Option<String>,
/// Strip these X11 modifier bits from key events handed to the managed
/// client. Wine reconciles its asynchronous keyboard state against the
/// modifier bits on every key event and, when the client's low-level hook
/// swallows lock keys, forges a lock-key down/up pair per keystroke. The
/// "auto" discovers NumLock/ScrollLock from the actual X11 keymap.
/// Shortcut, layout, case and keypad modifiers are preserved. Numeric
/// masks restrict this discovered set; 0 disables the workaround.
pub strip_lock_mods: Option<String>,
} }
impl Default for Config { impl Default for Config {
@@ -37,6 +58,11 @@ impl Default for Config {
capture_restore_token: None, capture_restore_token: None,
remote_desktop_restore_token: None, remote_desktop_restore_token: None,
capture_source: "monitor".into(), capture_source: "monitor".into(),
capture_multiple: false,
capture_backend: "portal".into(),
capture_output: None,
audio_capture_source: None,
strip_lock_mods: Some("auto".into()),
} }
} }
} }
@@ -110,24 +136,104 @@ pub fn runtime_dir() -> Result<PathBuf> {
impl Config { impl Config {
pub fn load() -> Result<Self> { pub fn load() -> Result<Self> {
let path = config_path()?; let path = config_path()?;
if !path.exists() { match std::fs::read_to_string(&path) {
let config = Self::default(); Ok(raw) => toml::from_str(&raw).context("parsing config.toml"),
config.store()?; Err(error) if error.kind() == std::io::ErrorKind::NotFound => Self::update(|_| {}),
return Ok(config); Err(error) => Err(error).with_context(|| format!("reading {}", path.display())),
} }
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("reading {}", path.display()))?;
toml::from_str(&raw).context("parsing config.toml")
} }
pub fn store(&self) -> Result<()> { pub fn store(&self) -> Result<()> {
let path = config_path()?; let (path, _lock) = Self::write_lock()?;
if let Some(parent) = path.parent() { self.store_locked(&path)
std::fs::create_dir_all(parent) }
.with_context(|| format!("creating {}", parent.display()))?;
/// Serialize read/modify/write across the capture, input and frontend
/// processes. Background token saves must not overwrite other fields.
pub fn update(change: impl FnOnce(&mut Self)) -> Result<Self> {
let (path, _lock) = Self::write_lock()?;
let mut config = match std::fs::read_to_string(&path) {
Ok(raw) => toml::from_str(&raw).context("parsing config.toml")?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Self::default(),
Err(error) => return Err(error).context("reading configuration for update"),
};
change(&mut config);
config.store_locked(&path)?;
Ok(config)
}
fn write_lock() -> Result<(PathBuf, std::fs::File)> {
let mut path = config_path()?;
// Do not replace a user-created symlink to declarative configuration.
if std::fs::symlink_metadata(&path).is_ok_and(|meta| meta.file_type().is_symlink()) {
path = std::fs::canonicalize(&path).context("resolving configuration symlink")?;
} }
std::fs::write(&path, toml::to_string_pretty(self)?) let parent = path.parent().context("configuration has no parent")?;
.with_context(|| format!("writing {}", path.display())) std::fs::create_dir_all(parent)?;
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.mode(0o600)
.open(path.with_extension("toml.lock"))?;
loop {
if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } == 0 {
break;
}
let error = std::io::Error::last_os_error();
if error.kind() != std::io::ErrorKind::Interrupted {
return Err(error).context("locking configuration");
}
}
Ok((path, lock))
}
fn store_locked(&self, path: &std::path::Path) -> Result<()> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let parent = path.parent().context("configuration has no parent")?;
let mut document = match std::fs::read_to_string(path) {
Ok(raw) => {
toml::from_str::<toml::Table>(&raw).context("parsing existing configuration")?
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => toml::Table::new(),
Err(error) => return Err(error).context("reading existing configuration"),
};
// Keep keys belonging to newer versions. JSON includes None fields,
// allowing explicitly cleared optional fields to remove old values.
for name in serde_json::to_value(self)?.as_object().unwrap().keys() {
document.remove(name);
}
document.extend(toml::Value::try_from(self)?.as_table().unwrap().clone());
let text = toml::to_string_pretty(&document)?;
for _ in 0..32 {
let temporary = parent.join(format!(
".uur-config-{}-{}.tmp",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let mut file = match std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o600)
.open(&temporary)
{
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error).context("creating configuration temporary file"),
};
let result = (|| -> Result<()> {
file.write_all(text.as_bytes())?;
file.sync_all()?;
std::fs::rename(&temporary, path)?;
std::fs::File::open(parent)?.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
return result.with_context(|| format!("writing {}", path.display()));
}
anyhow::bail!("could not create a configuration temporary file")
} }
} }
@@ -158,5 +264,7 @@ input_backend = "auto"
assert!(config.remote_desktop_restore_token.is_none()); assert!(config.remote_desktop_restore_token.is_none());
assert!(config.capture_restore_token.is_none()); assert!(config.capture_restore_token.is_none());
assert_eq!(config.capture_source, "monitor"); assert_eq!(config.capture_source, "monitor");
assert!(!config.capture_multiple);
assert_eq!(config.strip_lock_mods.as_deref(), Some("auto"));
} }
} }
+121 -14
View File
@@ -130,13 +130,16 @@ fn portal_capabilities() -> (bool, bool, String) {
runtime.block_on(async { runtime.block_on(async {
let (capture, sources) = match ashpd::desktop::screencast::Screencast::new().await { let (capture, sources) = match ashpd::desktop::screencast::Screencast::new().await {
Ok(portal) => match portal.available_source_types().await { Ok(portal) => match portal.available_source_types().await {
Ok(types) => (true, format!("{types:?}")), Ok(types) => (!types.is_empty(), format!("{types:?}")),
Err(_) => (false, "unavailable".into()), Err(_) => (false, "unavailable".into()),
}, },
Err(_) => (false, "unavailable".into()), Err(_) => (false, "unavailable".into()),
}; };
let input = match ashpd::desktop::remote_desktop::RemoteDesktop::new().await { let input = match ashpd::desktop::remote_desktop::RemoteDesktop::new().await {
Ok(portal) => portal.available_device_types().await.is_ok(), Ok(portal) => portal.available_device_types().await.is_ok_and(|types| {
types.contains(ashpd::desktop::remote_desktop::DeviceType::Keyboard)
&& types.contains(ashpd::desktop::remote_desktop::DeviceType::Pointer)
}),
Err(_) => false, Err(_) => false,
}; };
(capture, input, sources) (capture, input, sources)
@@ -176,6 +179,32 @@ pub fn report() -> Result<()> {
}; };
line(ok(missing_wine), "wine", &wine_detail); line(ok(missing_wine), "wine", &wine_detail);
let prefix = crate::config::data_dir()?.join("wine");
line(
ok(!crate::wine::prefix_initialized(&prefix)),
"managed Wine prefix",
&prefix.display().to_string(),
);
let client = crate::wine::find_client_dir(&prefix);
let client_detail = client
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_else(|| t!("doctor.client_incomplete").to_string());
line(ok(client.is_none()), "UU client and server", &client_detail);
let service = crate::wine::client_service_registered(&prefix);
let service_detail = if service {
t!("doctor.service_registered").to_string()
} else {
t!("doctor.service_missing").to_string()
};
line(ok(!service), "GameViewerService", &service_detail);
let webview_detail = if crate::wine::webview2_installed(&prefix) {
t!("doctor.present").to_string()
} else {
t!("doctor.webview_pending").to_string()
};
line("info", "WebView2 runtime", &webview_detail);
let backends = portal_backends(); let backends = portal_backends();
let has_portal_impl = !backends.is_empty(); let has_portal_impl = !backends.is_empty();
let portal_detail = if backends.is_empty() { let portal_detail = if backends.is_empty() {
@@ -187,7 +216,7 @@ pub fn report() -> Result<()> {
let (portal_capture, portal_input, portal_sources) = portal_capabilities(); let (portal_capture, portal_input, portal_sources) = portal_capabilities();
let portal_capture_detail = if portal_capture { let portal_capture_detail = if portal_capture {
t!("doctor.present").to_string() t!("doctor.portal_capture_advertised").to_string()
} else { } else {
t!("doctor.portal_capture_missing").to_string() t!("doctor.portal_capture_missing").to_string()
}; };
@@ -198,7 +227,7 @@ pub fn report() -> Result<()> {
); );
line("info", "portal source types", &portal_sources); line("info", "portal source types", &portal_sources);
let portal_input_detail = if portal_input { let portal_input_detail = if portal_input {
t!("doctor.present").to_string() t!("doctor.portal_input_advertised").to_string()
} else { } else {
t!("doctor.portal_input_missing").to_string() t!("doctor.portal_input_missing").to_string()
}; };
@@ -218,6 +247,17 @@ pub fn report() -> Result<()> {
let audio = crate::audio::detect(); let audio = crate::audio::detect();
line("info", "audio backend", audio.label()); line("info", "audio backend", audio.label());
let audio_config = crate::config::Config::load()?;
match crate::audio::capture_source(audio_config.audio_capture_source.as_deref()) {
Ok(source) => line(
"info",
"Wine default audio capture",
source
.as_deref()
.unwrap_or("existing audio environment; may be a microphone"),
),
Err(error) => line("warn", "Wine default audio capture", &format!("{error:#}")),
}
let video = crate::video::detect(); let video = crate::video::detect();
line( line(
@@ -313,19 +353,86 @@ pub fn report() -> Result<()> {
let uinput_missing = uinput_detail != t!("doctor.present"); let uinput_missing = uinput_detail != t!("doctor.present");
line(ok(uinput_missing), "uinput (/dev/uinput)", &uinput_detail); line(ok(uinput_missing), "uinput (/dev/uinput)", &uinput_detail);
// Mirror the real auto policy in input::select. // Report the configured policy; portal properties do not validate that
// the compositor can successfully create an authorized session.
let session_type = std::env::var("XDG_SESSION_TYPE").unwrap_or_default(); let session_type = std::env::var("XDG_SESSION_TYPE").unwrap_or_default();
let (backend, backend_note) = if session_type == "wayland" && portal_input { let on_wayland = session_type == "wayland" || std::env::var_os("WAYLAND_DISPLAY").is_some();
("portal", t!("doctor.backend_portal").to_string()) let configured = crate::config::Config::load()?;
} else if session_type == "wayland" && !uinput_missing { if std::env::var_os("DISPLAY").is_some() {
("uinput", t!("doctor.backend_wayland").to_string()) match crate::input::xtest::lock_state() {
} else if std::env::var("DISPLAY").is_ok() { Ok(state) => line("info", "X11 lock state", &state),
("xtest", t!("doctor.backend_x11").to_string()) Err(error) => line("WARN", "X11 lock state", &error.to_string()),
} else { }
("none", t!("doctor.backend_none").to_string()) let policy = configured.strip_lock_mods.as_deref().unwrap_or("disabled");
}; let shim = crate::session::lock_mods_shim();
let disabled = matches!(policy, "disabled" | "0" | "0x0" | "0x00");
line(
if !disabled && shim.is_none() {
"WARN"
} else {
"info"
},
"Wine keyboard workaround",
&format!(
"{policy}; shim={}; case/keypad remain native",
shim.as_deref()
.map(|path| path.display().to_string())
.unwrap_or_else(|| "not installed".into())
),
);
}
line( line(
"info", "info",
"capture backend",
&format!(
"{} ({}; multiple={})",
configured.capture_backend,
configured
.capture_output
.as_deref()
.unwrap_or("selected/default output"),
configured.capture_multiple
),
);
let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or(configured.input_backend);
if configured.capture_backend == "wayland" && preferred == "auto" {
preferred = "uinput".into();
}
let (status, backend, backend_note) = match preferred.as_str() {
"portal" => (
ok(!portal_input),
"portal",
t!("doctor.backend_portal").to_string(),
),
"uinput" => (
ok(uinput_missing),
"uinput",
t!("doctor.backend_wayland").to_string(),
),
"xtest" if on_wayland => ("WARN", "xtest", t!("doctor.backend_partial").to_string()),
"xtest" => (
ok(std::env::var_os("DISPLAY").is_none()),
"xtest",
t!("doctor.backend_x11").to_string(),
),
"auto" if on_wayland && portal_input => {
("info", "portal", t!("doctor.backend_portal").to_string())
}
"auto" if on_wayland && !uinput_missing => {
("info", "uinput", t!("doctor.backend_wayland").to_string())
}
"auto" if on_wayland => (
"MISS",
"none",
t!("doctor.backend_wayland_missing").to_string(),
),
"auto" if std::env::var_os("DISPLAY").is_some() => {
("info", "xtest", t!("doctor.backend_x11").to_string())
}
_ => ("MISS", "none", t!("doctor.backend_none").to_string()),
};
line(
status,
"input backend", "input backend",
&format!("{backend} ({backend_note})"), &format!("{backend} ({backend_note})"),
); );
+11 -2
View File
@@ -7,6 +7,9 @@ use anyhow::Result;
/// A desktop input sink. Records arrive already normalized by `protocol`. /// A desktop input sink. Records arrive already normalized by `protocol`.
pub trait InputBackend: Send { pub trait InputBackend: Send {
fn name(&self) -> &'static str; fn name(&self) -> &'static str;
fn check_health(&self) -> Result<()> {
Ok(())
}
fn key(&mut self, vkey: u16, down: bool) -> Result<()>; fn key(&mut self, vkey: u16, down: bool) -> Result<()>;
fn button(&mut self, button: u16, down: bool) -> Result<()>; fn button(&mut self, button: u16, down: bool) -> Result<()>;
@@ -24,7 +27,11 @@ pub trait InputBackend: Send {
/// kernel-level uinput device when the compositor only provides ScreenCast. /// kernel-level uinput device when the compositor only provides ScreenCast.
/// - X11 sessions use XTEST, which needs no extra privileges. /// - X11 sessions use XTEST, which needs no extra privileges.
pub fn select(preferred: &str) -> Result<Box<dyn InputBackend>> { pub fn select(preferred: &str) -> Result<Box<dyn InputBackend>> {
let on_wayland = std::env::var("WAYLAND_DISPLAY").is_ok(); let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland");
if !matches!(preferred, "auto" | "portal" | "uinput" | "xtest") {
anyhow::bail!("unknown input backend {preferred:?}; use auto, portal, uinput, or xtest");
}
if preferred == "portal" || (preferred == "auto" && on_wayland) { if preferred == "portal" || (preferred == "auto" && on_wayland) {
match portal::PortalBackend::connect() { match portal::PortalBackend::connect() {
@@ -39,10 +46,12 @@ pub fn select(preferred: &str) -> Result<Box<dyn InputBackend>> {
Err(error) if preferred == "uinput" => return Err(error), Err(error) if preferred == "uinput" => return Err(error),
Err(error) => { Err(error) => {
eprintln!("{}: {error}", t!("input.uinput_unavailable")); eprintln!("{}: {error}", t!("input.uinput_unavailable"));
// fall through to XTEST: partial reachability beats nothing
} }
} }
} }
if on_wayland && preferred == "auto" {
anyhow::bail!("{}", t!("input.wayland_no_full_input"));
}
if std::env::var("DISPLAY").is_ok() { if std::env::var("DISPLAY").is_ok() {
return Ok(Box::new(xtest::XtestBackend::connect()?)); return Ok(Box::new(xtest::XtestBackend::connect()?));
} }
+394 -46
View File
@@ -1,12 +1,14 @@
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use ashpd::desktop::remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop}; use ashpd::desktop::remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop};
use ashpd::desktop::screencast::{CursorMode, Screencast}; use ashpd::desktop::screencast::Screencast;
use ashpd::desktop::PersistMode; use ashpd::desktop::PersistMode;
use futures::StreamExt;
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, SyncSender}; use std::sync::mpsc::{self, SyncSender};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use std::time::Instant;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use super::InputBackend; use super::InputBackend;
@@ -28,15 +30,103 @@ struct Motion {
y: f64, y: f64,
} }
struct CaptureGuard(std::process::Child); /// Select a consented stream in the same logical layout used by the compositor.
/// A point in a monitor gap is clamped to the closest selected monitor.
impl Drop for CaptureGuard { fn absolute_target(
fn drop(&mut self) { streams: &[crate::capture::CaptureStream],
let _ = self.0.kill(); x: f64,
let _ = self.0.wait(); y: f64,
) -> Result<(u32, f64, f64)> {
anyhow::ensure!(
x.is_finite() && y.is_finite(),
"invalid absolute pointer position"
);
anyhow::ensure!(
!streams.is_empty() && streams.len() <= 16,
"invalid input stream count"
);
let mut streams = streams.to_vec();
if streams
.iter()
.any(|stream| stream.width == 0 || stream.height == 0)
{
use std::io::Read;
let mut header = [0u8; 704];
std::fs::File::open(crate::capture::frame_path()?)?.read_exact(&mut header)?;
let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap());
anyhow::ensure!(
field(0) == 0x4652_5555
&& field(4) == 3
&& field(36) as usize == streams.len()
&& u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0,
"capture layout is not ready for pointer routing"
);
for (index, stream) in streams.iter_mut().enumerate() {
let offset = 64 + index * 40;
stream.x = field(offset) as i32;
stream.y = field(offset + 4) as i32;
stream.width = field(offset + 8);
stream.height = field(offset + 12);
}
} }
anyhow::ensure!(
streams
.iter()
.all(|stream| stream.width > 0 && stream.height > 0),
"missing pointer stream dimensions"
);
if streams
.iter()
.any(|stream| stream.x == i32::MIN || stream.y == i32::MIN)
{
let mut next_x = 0i64;
for stream in &mut streams {
stream.x = i32::try_from(next_x).context("input stream layout is too wide")?;
stream.y = 0;
next_x += i64::from(stream.width);
}
}
let left = streams
.iter()
.map(|stream| i64::from(stream.x))
.min()
.unwrap();
let top = streams
.iter()
.map(|stream| i64::from(stream.y))
.min()
.unwrap();
let right = streams
.iter()
.map(|stream| i64::from(stream.x) + i64::from(stream.width))
.max()
.unwrap();
let bottom = streams
.iter()
.map(|stream| i64::from(stream.y) + i64::from(stream.height))
.max()
.unwrap();
let global_x = left as f64 + x.clamp(0.0, 65535.0) * (right - left - 1) as f64 / 65535.0;
let global_y = top as f64 + y.clamp(0.0, 65535.0) * (bottom - top - 1) as f64 / 65535.0;
let mut best = None;
let mut distance = f64::INFINITY;
for stream in &streams {
let local_x = (global_x - f64::from(stream.x)).clamp(0.0, f64::from(stream.width - 1));
let local_y = (global_y - f64::from(stream.y)).clamp(0.0, f64::from(stream.height - 1));
let dx = global_x - f64::from(stream.x) - local_x;
let dy = global_y - f64::from(stream.y) - local_y;
let current = dx * dx + dy * dy;
// The producer draws later streams last when rectangles overlap.
if current <= distance {
best = Some((stream.node, local_x, local_y));
distance = current;
}
}
best.context("no input stream matches the pointer position")
} }
use crate::capture::CaptureHelper as CaptureGuard;
/// Wayland input through the freedesktop RemoteDesktop portal. The actual /// Wayland input through the freedesktop RemoteDesktop portal. The actual
/// backend can be GNOME, KDE, COSMIC, or any future implementation; uur never /// backend can be GNOME, KDE, COSMIC, or any future implementation; uur never
/// branches on a desktop name. /// branches on a desktop name.
@@ -46,18 +136,21 @@ pub struct PortalBackend {
motion_queued: Arc<AtomicBool>, motion_queued: Arc<AtomicBool>,
held_keys: HashSet<i32>, held_keys: HashSet<i32>,
held_buttons: HashSet<i32>, held_buttons: HashSet<i32>,
failure: Arc<Mutex<Option<String>>>,
} }
impl PortalBackend { impl PortalBackend {
pub fn connect() -> Result<Self> { pub fn connect() -> Result<Self> {
let mut config = crate::config::Config::load()?; let mut config = crate::config::Config::load()?;
let restore_token = config.remote_desktop_restore_token.clone();
let (sender, receiver) = unbounded_channel(); let (sender, receiver) = unbounded_channel();
let (ready_sender, ready_receiver) = mpsc::sync_channel(1); let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
let pending_motion = Arc::new(Mutex::new(None)); let pending_motion = Arc::new(Mutex::new(None));
let motion_queued = Arc::new(AtomicBool::new(false)); let motion_queued = Arc::new(AtomicBool::new(false));
let worker_motion = pending_motion.clone(); let worker_motion = pending_motion.clone();
let worker_queued = motion_queued.clone(); let worker_queued = motion_queued.clone();
let failure = Arc::new(Mutex::new(None));
let worker_failure = failure.clone();
let worker_config = config.clone();
std::thread::Builder::new() std::thread::Builder::new()
.name("uur-portal-input".into()) .name("uur-portal-input".into())
@@ -70,12 +163,15 @@ impl PortalBackend {
runtime.block_on(portal_worker( runtime.block_on(portal_worker(
receiver, receiver,
ready_sender.clone(), ready_sender.clone(),
restore_token, worker_config,
worker_motion, worker_motion,
worker_queued, worker_queued,
worker_failure.clone(),
)) ))
}); });
if let Err(error) = result { if let Err(error) = result {
*worker_failure.lock().unwrap() = Some(error.to_string());
eprintln!("portal input worker stopped: {error:#}");
let _ = ready_sender.send(Err(error.to_string())); let _ = ready_sender.send(Err(error.to_string()));
} }
}) })
@@ -87,7 +183,15 @@ impl PortalBackend {
.map_err(|error| anyhow!(error))?; .map_err(|error| anyhow!(error))?;
if fresh_token != config.remote_desktop_restore_token { if fresh_token != config.remote_desktop_restore_token {
config.remote_desktop_restore_token = fresh_token; config.remote_desktop_restore_token = fresh_token;
config.store()?; crate::config::Config::update(|stored| {
if stored.capture_source == config.capture_source
&& stored.capture_multiple == config.capture_multiple
&& stored.capture_backend == config.capture_backend
{
stored.remote_desktop_restore_token =
config.remote_desktop_restore_token.clone();
}
})?;
} }
Ok(Self { Ok(Self {
@@ -96,31 +200,139 @@ impl PortalBackend {
motion_queued, motion_queued,
held_keys: HashSet::new(), held_keys: HashSet::new(),
held_buttons: HashSet::new(), held_buttons: HashSet::new(),
failure,
}) })
} }
fn submit(&self, event: impl FnOnce(Reply) -> Event) -> Result<()> { fn submit(&self, event: impl FnOnce(Reply) -> Event) -> Result<()> {
if let Some(error) = self.failure.lock().unwrap().clone() {
anyhow::bail!("portal input session failed: {error}");
}
let (reply_sender, reply_receiver) = mpsc::sync_channel(1); let (reply_sender, reply_receiver) = mpsc::sync_channel(1);
self.sender self.sender
.send(event(reply_sender)) .send(event(reply_sender))
.map_err(|_| anyhow!("portal input session closed"))?; .map_err(|_| anyhow!("portal input session closed"))?;
reply_receiver let result = reply_receiver
.recv_timeout(Duration::from_secs(3)) // Allow the helper shutdown, reconnect delay and portal restore
.context("portal input request timed out")? // to finish while keeping a stalled session bounded.
.map_err(|error| anyhow!(error)) .recv_timeout(Duration::from_secs(10))
.context("portal input request timed out")
.and_then(|result| result.map_err(|error| anyhow!(error)));
if let Err(error) = &result {
*self.failure.lock().unwrap() = Some(error.to_string());
}
result
} }
} }
async fn portal_worker( async fn portal_worker(
mut receiver: UnboundedReceiver<Event>, receiver: UnboundedReceiver<Event>,
ready: SyncSender<std::result::Result<Option<String>, String>>, ready: SyncSender<std::result::Result<Option<String>, String>>,
configured: crate::config::Config,
pending_motion: Arc<Mutex<Option<Motion>>>,
motion_queued: Arc<AtomicBool>,
failure: Arc<Mutex<Option<String>>>,
) -> Result<()> {
let mut worker = PortalWorker {
restore_token: configured.remote_desktop_restore_token.clone(),
configured,
receiver,
ready,
pending_motion,
motion_queued,
failure,
initial: true,
opened: false,
held_keys: HashSet::new(),
held_buttons: HashSet::new(),
};
let mut display_changes = crate::capture::watch_display_changes().await;
let mut failures = 0u8;
loop {
worker.opened = false;
match portal_session_worker(&mut worker, &mut display_changes).await {
Ok(SessionExit::Shutdown) => return Ok(()),
Ok(SessionExit::Reconnect { layout, healthy }) => {
if healthy {
failures = 0;
}
if !layout {
failures += 1;
}
anyhow::ensure!(failures <= 3, "portal capture recovery exhausted");
anyhow::ensure!(worker.restore_token.is_some(),
"portal capture changed without a restorable grant; restart uur run to share again");
eprintln!(
"restoring the consented RemoteDesktop session after {}",
if layout {
"a display change"
} else {
"a capture failure"
}
);
tokio::time::sleep(Duration::from_millis(if layout { 250 } else { 1000 })).await;
while tokio::time::timeout(
Duration::from_millis(100),
crate::capture::next_display_change(&mut display_changes),
)
.await
.is_ok()
{}
}
Err(error)
if !worker.initial
&& !worker.opened
&& failures < 3
&& worker.restore_token.is_some()
&& !crate::capture::user_cancelled(&error) =>
{
failures += 1;
eprintln!("portal restore {failures}/3 failed: {error:#}");
tokio::time::sleep(Duration::from_secs(1)).await;
}
Err(error) => return Err(error),
}
}
}
struct PortalWorker {
receiver: UnboundedReceiver<Event>,
ready: SyncSender<std::result::Result<Option<String>, String>>,
configured: crate::config::Config,
restore_token: Option<String>, restore_token: Option<String>,
pending_motion: Arc<Mutex<Option<Motion>>>, pending_motion: Arc<Mutex<Option<Motion>>>,
motion_queued: Arc<AtomicBool>, motion_queued: Arc<AtomicBool>,
) -> Result<()> { failure: Arc<Mutex<Option<String>>>,
initial: bool,
opened: bool,
held_keys: HashSet<i32>,
held_buttons: HashSet<i32>,
}
enum SessionExit {
Shutdown,
Reconnect { layout: bool, healthy: bool },
}
async fn portal_session_worker(
worker: &mut PortalWorker,
display_changes: &mut Option<zbus::proxy::SignalStream<'static>>,
) -> Result<SessionExit> {
let PortalWorker {
receiver,
ready,
configured,
restore_token,
pending_motion,
motion_queued,
failure,
initial,
opened,
held_keys,
held_buttons,
} = worker;
let portal = RemoteDesktop::new().await?; let portal = RemoteDesktop::new().await?;
let screencast = Screencast::new().await?; let screencast = Screencast::new().await?;
let configured = crate::config::Config::load()?;
let source = crate::capture::source_type(&configured.capture_source); let source = crate::capture::source_type(&configured.capture_source);
let available = portal.available_device_types().await?; let available = portal.available_device_types().await?;
if !available.contains(DeviceType::Keyboard) || !available.contains(DeviceType::Pointer) { if !available.contains(DeviceType::Keyboard) || !available.contains(DeviceType::Pointer) {
@@ -128,6 +340,18 @@ async fn portal_worker(
} }
let session = portal.create_session().await?; let session = portal.create_session().await?;
let serialized = serde_json::to_value(&session)?;
let session_proxy = zbus::Proxy::new_owned(
portal.connection().clone(),
"org.freedesktop.portal.Desktop",
serialized
.as_str()
.context("invalid portal session path")?
.to_owned(),
"org.freedesktop.portal.Session",
)
.await?;
let mut closed = session_proxy.receive_signal("Closed").await?;
portal portal
.select_devices( .select_devices(
&session, &session,
@@ -140,29 +364,112 @@ async fn portal_worker(
screencast screencast
.select_sources( .select_sources(
&session, &session,
CursorMode::Embedded, crate::capture::preferred_cursor_mode(&screencast).await?,
source.into(), source.into(),
false, configured.capture_multiple && configured.capture_source == "monitor",
None, None,
PersistMode::DoNot, PersistMode::DoNot,
) )
.await? .await?
.response()?; .response()?;
let selection = portal.start(&session, None).await?.response()?; let selection = portal.start(&session, None).await?.response()?;
let stream = selection *opened = true;
anyhow::ensure!(
selection.devices().contains(DeviceType::Keyboard)
&& selection.devices().contains(DeviceType::Pointer),
"RemoteDesktop grant did not include keyboard and pointer"
);
let selected_streams = selection
.streams() .streams()
.and_then(|streams| streams.first()) .context("RemoteDesktop portal returned no screen streams")?;
.context("RemoteDesktop portal returned no screen stream")?; anyhow::ensure!(
let stream_id = stream.pipe_wire_node_id(); !selected_streams.is_empty(),
let (logical_width, logical_height) = stream.size().unwrap_or((65535, 65535)); "RemoteDesktop portal returned no screen streams"
);
let streams = selected_streams
.iter()
.map(|stream| {
let (x, y) = stream.position().unwrap_or((i32::MIN, i32::MIN));
let (width, height) = stream.size().unwrap_or((0, 0));
crate::capture::CaptureStream {
node: stream.pipe_wire_node_id(),
x,
y,
width: u32::try_from(width).unwrap_or(0),
height: u32::try_from(height).unwrap_or(0),
}
})
.collect::<Vec<_>>();
let pipewire = screencast.open_pipe_wire_remote(&session).await?; let pipewire = screencast.open_pipe_wire_remote(&session).await?;
let _capture = CaptureGuard(crate::capture::spawn_helper(pipewire, stream_id)?); let mut capture = CaptureGuard(crate::capture::spawn_helper(pipewire, &streams)?);
let token = selection.restore_token().map(ToOwned::to_owned); let token = selection.restore_token().map(ToOwned::to_owned);
ready *restore_token = token.clone();
.send(Ok(token)) if *initial {
.map_err(|_| anyhow!("portal setup receiver closed"))?; ready
.send(Ok(token))
while let Some(event) = receiver.recv().await { .map_err(|_| anyhow!("portal setup receiver closed"))?;
*initial = false;
} else {
crate::config::Config::update(|stored| {
if stored.capture_source == configured.capture_source
&& stored.capture_multiple == configured.capture_multiple
&& stored.capture_backend == configured.capture_backend
{
stored.remote_desktop_restore_token = token;
}
})?;
for key in held_keys.iter().copied() {
portal
.notify_keyboard_keycode(&session, key, KeyState::Pressed)
.await?;
}
for button in held_buttons.iter().copied() {
portal
.notify_pointer_button(&session, button, KeyState::Pressed)
.await?;
}
}
let mut healthy_since = None;
let mut health_tick = tokio::time::interval(Duration::from_millis(50));
let outcome: Result<SessionExit> = async {
loop {
if let Some(error) = failure.lock().unwrap().clone() {
anyhow::bail!("portal input session failed: {error}");
}
let event = tokio::select! {
biased;
_ = closed.next() => {
let layout = tokio::time::timeout(Duration::from_millis(250),
crate::capture::next_display_change(display_changes)).await.is_ok();
anyhow::ensure!(layout, "screen sharing was closed by the portal; restart uur run to share again");
break Ok(SessionExit::Reconnect { layout: true,
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
},
_ = crate::capture::next_display_change(display_changes) => {
break Ok(SessionExit::Reconnect { layout: true,
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
},
_ = health_tick.tick() => {
if crate::capture::helper_stalled(&crate::capture::frame_path()?) {
eprintln!("portal capture helper heartbeat expired; reconnecting");
break Ok(SessionExit::Reconnect { layout: false,
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
}
if crate::capture::has_frame(&crate::capture::frame_path()?) && healthy_since.is_none() {
healthy_since = Some(Instant::now());
}
if let Some(status) = capture.0.try_wait()? {
anyhow::ensure!(status.code() == Some(75), "portal capture helper exited ({status})");
break Ok(SessionExit::Reconnect { layout: false,
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
}
continue;
},
event = receiver.recv() => match event {
Some(event) => event,
None => break Ok(SessionExit::Shutdown),
},
};
match event { match event {
Event::Key(code, down, reply) => { Event::Key(code, down, reply) => {
let result = portal let result = portal
@@ -176,6 +483,9 @@ async fn portal_worker(
}, },
) )
.await; .await;
if result.is_ok() {
if down { held_keys.insert(code); } else { held_keys.remove(&code); }
}
answer(reply, result)?; answer(reply, result)?;
} }
Event::Button(button, down, reply) => { Event::Button(button, down, reply) => {
@@ -190,25 +500,22 @@ async fn portal_worker(
}, },
) )
.await; .await;
if result.is_ok() {
if down { held_buttons.insert(button); } else { held_buttons.remove(&button); }
}
answer(reply, result)?; answer(reply, result)?;
} }
Event::FlushMotion => loop { Event::FlushMotion => {
motion_queued.store(false, Ordering::Release);
let motion = pending_motion.lock().unwrap().take(); let motion = pending_motion.lock().unwrap().take();
let Some(motion) = motion else { let Some(motion) = motion else {
motion_queued.store(false, Ordering::Release); continue;
let has_new_motion = pending_motion.lock().unwrap().is_some();
if has_new_motion
&& motion_queued
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
continue;
}
break;
}; };
let result = if motion.absolute { let result = if motion.absolute {
let logical_x = motion.x.clamp(0.0, 65535.0) * logical_width as f64 / 65535.0; let (stream_id, logical_x, logical_y) = match absolute_target(&streams, motion.x, motion.y) {
let logical_y = motion.y.clamp(0.0, 65535.0) * logical_height as f64 / 65535.0; Ok(target) => target,
Err(error) => { eprintln!("portal pointer layout not ready: {error}"); continue; }
};
portal portal
.notify_pointer_motion_absolute(&session, stream_id, logical_x, logical_y) .notify_pointer_motion_absolute(&session, stream_id, logical_x, logical_y)
.await .await
@@ -229,10 +536,14 @@ async fn portal_worker(
.await, .await,
)?; )?;
} }
Event::Shutdown => break, Event::Shutdown => break Ok(SessionExit::Shutdown),
} }
} }
Ok(()) }.await;
drop(closed);
drop(capture);
let _ = tokio::time::timeout(Duration::from_secs(2), session.close()).await;
outcome
} }
fn answer<T>(reply: Reply, result: std::result::Result<T, ashpd::Error>) -> Result<()> { fn answer<T>(reply: Reply, result: std::result::Result<T, ashpd::Error>) -> Result<()> {
@@ -246,6 +557,14 @@ impl InputBackend for PortalBackend {
"portal" "portal"
} }
fn check_health(&self) -> Result<()> {
if let Some(error) = self.failure.lock().unwrap().clone() {
anyhow::bail!("portal input worker failed: {error}");
}
anyhow::ensure!(!self.sender.is_closed(), "portal input worker stopped");
Ok(())
}
fn key(&mut self, vkey: u16, down: bool) -> Result<()> { fn key(&mut self, vkey: u16, down: bool) -> Result<()> {
let code = super::uinput::vk_to_linux_key(vkey) as i32; let code = super::uinput::vk_to_linux_key(vkey) as i32;
if code == 0 { if code == 0 {
@@ -342,7 +661,7 @@ impl Drop for PortalBackend {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{merge_motion, Motion}; use super::{absolute_target, merge_motion, Motion};
#[test] #[test]
fn absolute_motion_keeps_only_the_latest_position() { fn absolute_motion_keeps_only_the_latest_position() {
@@ -358,6 +677,35 @@ mod tests {
}; };
merge_motion(&mut pending, latest); merge_motion(&mut pending, latest);
assert_eq!(pending, Some(latest)); assert_eq!(pending, Some(latest));
let streams = [
crate::capture::CaptureStream {
node: 41,
x: -1280,
y: 0,
width: 1280,
height: 720,
},
crate::capture::CaptureStream {
node: 42,
x: 0,
y: 0,
width: 1920,
height: 1080,
},
];
assert_eq!(absolute_target(&streams, 0.0, 0.0).unwrap(), (41, 0.0, 0.0));
assert_eq!(
absolute_target(&streams, 65535.0, 65535.0).unwrap(),
(42, 1919.0, 1079.0)
);
let target = absolute_target(&streams, 1280.0 * 65535.0 / 3199.0, 0.0).unwrap();
assert_eq!(target.0, 42);
assert!(target.1.abs() < 1e-6);
assert!(absolute_target(&streams, f64::NAN, 0.0).is_err());
let mut gap = streams;
gap[1].x = 200;
let target = absolute_target(&gap, 1280.0 * 65535.0 / 3399.0, 0.0).unwrap();
assert_eq!(target, (41, 1279.0, 0.0));
} }
#[test] #[test]
+10 -4
View File
@@ -12,7 +12,7 @@ const UI_SET_EVBIT: libc::Ioctl = 0x4004_5564_u64 as libc::Ioctl;
const UI_SET_KEYBIT: libc::Ioctl = 0x4004_5565_u64 as libc::Ioctl; const UI_SET_KEYBIT: libc::Ioctl = 0x4004_5565_u64 as libc::Ioctl;
const UI_SET_RELBIT: libc::Ioctl = 0x4004_5566_u64 as libc::Ioctl; const UI_SET_RELBIT: libc::Ioctl = 0x4004_5566_u64 as libc::Ioctl;
const UI_SET_ABSBIT: libc::Ioctl = 0x4004_5567_u64 as libc::Ioctl; const UI_SET_ABSBIT: libc::Ioctl = 0x4004_5567_u64 as libc::Ioctl;
// struct uinput_setup = name[80] + input_id(8) + ff_effects_max(4) = 92 bytes // struct uinput_setup = input_id(8) + name[80] + ff_effects_max(4) = 92 bytes
const UI_DEV_SETUP: libc::Ioctl = 0x405C_5503_u64 as libc::Ioctl; const UI_DEV_SETUP: libc::Ioctl = 0x405C_5503_u64 as libc::Ioctl;
// struct uinput_abs_setup = u16 code + input_absinfo(24) = 28 bytes // struct uinput_abs_setup = u16 code + input_absinfo(24) = 28 bytes
const UI_ABS_SETUP: libc::Ioctl = 0x401C_5504_u64 as libc::Ioctl; const UI_ABS_SETUP: libc::Ioctl = 0x401C_5504_u64 as libc::Ioctl;
@@ -40,6 +40,8 @@ const BTN_MIDDLE: u16 = 0x112;
const BTN_SIDE: u16 = 0x116; const BTN_SIDE: u16 = 0x116;
const BTN_EXTRA: u16 = 0x117; const BTN_EXTRA: u16 = 0x117;
const BTN_TOOL_PEN: u16 = 0x140; const BTN_TOOL_PEN: u16 = 0x140;
const BTN_TOUCH: u16 = 0x14a;
const BTN_STYLUS: u16 = 0x14b;
const BUS_VIRTUAL: u16 = 0x06; const BUS_VIRTUAL: u16 = 0x06;
@@ -53,14 +55,14 @@ struct InputEvent {
value: i32, value: i32,
} }
/// struct uinput_setup: name[80] + input_id(4×u16) + ff_effects_max(u32). /// Linux ABI: input_id(4×u16), then name[80], then ff_effects_max(u32).
#[repr(C)] #[repr(C)]
struct UinputSetup { struct UinputSetup {
name: [u8; 80],
bustype: u16, bustype: u16,
vendor: u16, vendor: u16,
product: u16, product: u16,
version: u16, version: u16,
name: [u8; 80],
ff_effects_max: u32, ff_effects_max: u32,
} }
@@ -142,7 +144,9 @@ impl UinputDevice {
maximum, maximum,
fuzz: 0, fuzz: 0,
flat: 0, flat: 0,
resolution: 0, // libinput requires physical axis resolution for tablets. A
// 65.535 mm virtual surface maps the full normalized range.
resolution: 1000,
}; };
let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_ABS_SETUP, &setup) }; let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_ABS_SETUP, &setup) };
if rc < 0 { if rc < 0 {
@@ -235,6 +239,8 @@ impl Devices {
ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_ABS as u32)?; ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_ABS as u32)?;
ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_SYN as u32)?; ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_SYN as u32)?;
tablet.keybit(BTN_TOOL_PEN)?; tablet.keybit(BTN_TOOL_PEN)?;
tablet.keybit(BTN_TOUCH)?;
tablet.keybit(BTN_STYLUS)?;
tablet.absbit(ABS_X, 65535)?; tablet.absbit(ABS_X, 65535)?;
tablet.absbit(ABS_Y, 65535)?; tablet.absbit(ABS_Y, 65535)?;
tablet.finish()?; tablet.finish()?;
+43
View File
@@ -15,6 +15,49 @@ const FAKE_MOTION: u8 = 6;
/// XTEST detail for motion: 0 = absolute, 1 = relative. /// XTEST detail for motion: 0 = absolute, 1 = relative.
const MOTION_RELATIVE: u8 = 1; const MOTION_RELATIVE: u8 = 1;
/// Observe this display's effective lock state without changing any XKB state.
pub(crate) fn lock_state() -> Result<String> {
let (connection, screen) = x11rb::connect(None)?;
let setup = connection.setup();
let state = u16::from(
connection
.query_pointer(setup.roots[screen].root)?
.reply()?
.mask,
);
let modifiers = connection.get_modifier_mapping()?.reply()?;
let keys = connection
.get_keyboard_mapping(setup.min_keycode, setup.max_keycode - setup.min_keycode + 1)?
.reply()?;
let width = modifiers.keycodes.len() / 8;
let mut num = 0u16;
let mut scroll = 0u16;
for (index, code) in modifiers.keycodes.iter().copied().enumerate() {
if code < setup.min_keycode || width == 0 {
continue;
}
let offset = usize::from(code - setup.min_keycode) * usize::from(keys.keysyms_per_keycode);
let symbols = keys
.keysyms
.get(offset..offset + usize::from(keys.keysyms_per_keycode));
if let Some(symbols) = symbols {
if symbols.contains(&0xff7f) {
num |= 1 << (index / width);
}
if symbols.contains(&0xff14) {
scroll |= 1 << (index / width);
}
}
}
let flag = |mask| if state & mask != 0 { "on" } else { "off" };
Ok(format!(
"CapsLock={} NumLock={} ScrollLock={} (Num mask={num:#x}, Scroll mask={scroll:#x})",
flag(2),
flag(num),
flag(scroll)
))
}
/// X11 XTest injection. Works on every X11 session; on XWayland it reaches /// X11 XTest injection. Works on every X11 session; on XWayland it reaches
/// XWayland-native windows only, which is why the portal backend is /// XWayland-native windows only, which is why the portal backend is
/// preferred on Wayland-only sessions. /// preferred on Wayland-only sessions.
+1 -1
View File
@@ -66,7 +66,7 @@ pub fn prepare(prefix: &Path, proxy: &Path) -> Result<usize> {
std::fs::write(root.with_extension("keys"), keys.join("\n") + "\n")?; std::fs::write(root.with_extension("keys"), keys.join("\n") + "\n")?;
let registry_path = prefix.join("drive_c/uur-linux-apps.reg"); let registry_path = prefix.join("drive_c/uur-linux-apps.reg");
write_utf16_registry(&registry_path, &registry)?; write_utf16_registry(&registry_path, &registry)?;
let status = Command::new("wine") let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all") .env("WINEDEBUG", "-all")
.args(["reg", "import"]) .args(["reg", "import"])
+122 -9
View File
@@ -15,6 +15,8 @@ mod protocol;
mod proxy; mod proxy;
mod session; mod session;
mod terminal; mod terminal;
mod tray;
mod uninstall;
mod upstream; mod upstream;
mod video; mod video;
mod wallpaper; mod wallpaper;
@@ -46,6 +48,9 @@ enum Command {
/// Accept the NetEase UU Remote EULA non-interactively. /// Accept the NetEase UU Remote EULA non-interactively.
#[arg(long)] #[arg(long)]
accept_eula: bool, accept_eula: bool,
/// Update the existing Wine prefix, retry Wine components, and repair an incomplete client installation.
#[arg(long)]
repair: bool,
}, },
/// Print the live environment report (sessions, wine, portals, backends). /// Print the live environment report (sessions, wine, portals, backends).
Doctor, Doctor,
@@ -57,6 +62,18 @@ enum Command {
Run, Run,
/// Stop every uur-owned process and the managed Wine prefix. /// Stop every uur-owned process and the managed Wine prefix.
Stop, Stop,
/// Remove this user's integration and source installation; optionally erase all managed data.
Uninstall {
/// Delete the managed Wine prefix, account data, installer cache, configuration and logs.
#[arg(long)]
purge: bool,
/// Show the exact removal plan without stopping processes or changing files.
#[arg(long)]
dry_run: bool,
/// Confirm removal without an interactive prompt.
#[arg(long)]
yes: bool,
},
/// Manage optional XDG login autostart. /// Manage optional XDG login autostart.
Autostart { Autostart {
#[command(subcommand)] #[command(subcommand)]
@@ -72,6 +89,11 @@ enum Command {
#[command(subcommand)] #[command(subcommand)]
action: DisplayAction, action: DisplayAction,
}, },
/// Select Wine's default microphone/system-audio capture source.
Audio {
#[command(subcommand)]
action: AudioAction,
},
/// Internal input bridge process. Not part of the public CLI. /// Internal input bridge process. Not part of the public CLI.
#[command(hide = true, name = "__bridge")] #[command(hide = true, name = "__bridge")]
InternalBridge, InternalBridge,
@@ -87,6 +109,9 @@ enum Command {
/// Internal desktop suspend/idle inhibitor. Not part of the public CLI. /// Internal desktop suspend/idle inhibitor. Not part of the public CLI.
#[command(hide = true, name = "__inhibit")] #[command(hide = true, name = "__inhibit")]
InternalInhibit, InternalInhibit,
/// Internal native desktop tray. Not part of the public CLI.
#[command(hide = true, name = "__tray")]
InternalTray,
/// Internal authenticated XDG application launcher. /// Internal authenticated XDG application launcher.
#[command(hide = true, name = "__launcher")] #[command(hide = true, name = "__launcher")]
InternalLauncher, InternalLauncher,
@@ -137,7 +162,35 @@ enum DisplayAction {
/// Show the configured source type. /// Show the configured source type.
Status, Status,
/// Use a monitor, one window, or a portal-provided virtual display. /// Use a monitor, one window, or a portal-provided virtual display.
Source { source: DisplaySource }, Source {
source: DisplaySource,
/// Allow selecting several monitors in the next portal consent dialog.
#[arg(long)]
multiple: bool,
},
/// Choose portal capture, or explicitly enable direct Wayland monitor capture.
Backend {
backend: CaptureBackend,
/// Name from `uur display outputs`; required if more than one output is present.
#[arg(long)]
output: Option<String>,
},
/// List native Wayland outputs without capturing their content.
Outputs,
}
#[derive(Subcommand)]
enum AudioAction {
/// List real capture inputs and system-audio monitor sources.
Sources,
/// Use system sound, a source name, or default to follow the existing environment.
Source { source: String },
}
#[derive(Clone, ValueEnum)]
enum CaptureBackend {
Portal,
Wayland,
} }
#[derive(Clone, ValueEnum)] #[derive(Clone, ValueEnum)]
@@ -165,12 +218,24 @@ fn main() -> Result<()> {
i18n::init(); i18n::init();
let cli = Cli::parse(); let cli = Cli::parse();
match cli.command { match cli.command {
Command::Setup { accept_eula } => wine::setup(accept_eula), Command::Setup {
accept_eula,
repair,
} => wine::setup(accept_eula, repair),
Command::Doctor => doctor::report(), Command::Doctor => doctor::report(),
Command::Pointer => bridge::print_pointer(), Command::Pointer => bridge::print_pointer(),
Command::Capture => capture::run(), Command::Capture => capture::run_standalone(),
Command::Audio { action } => match action {
AudioAction::Sources => audio::print_sources(),
AudioAction::Source { source } => audio::configure_source(&source),
},
Command::Run => session::start(), Command::Run => session::start(),
Command::Stop => session::stop(), Command::Stop => session::stop(),
Command::Uninstall {
purge,
dry_run,
yes,
} => uninstall::run(purge, dry_run, yes),
Command::Autostart { action } => match action { Command::Autostart { action } => match action {
AutostartAction::Enable => autostart::enable(), AutostartAction::Enable => autostart::enable(),
AutostartAction::Disable => autostart::disable(), AutostartAction::Disable => autostart::disable(),
@@ -182,18 +247,65 @@ fn main() -> Result<()> {
WolAction::Disable { interface } => wol::configure(interface.as_deref(), false), WolAction::Disable { interface } => wol::configure(interface.as_deref(), false),
}, },
Command::Display { action } => { Command::Display { action } => {
let mut config = config::Config::load()?; if matches!(action, DisplayAction::Outputs) {
return capture::list_wayland_outputs();
}
let config = config::Config::load()?;
match action { match action {
DisplayAction::Status => { DisplayAction::Status => {
println!("{}", t!("display.status", source = config.capture_source)); println!("{}", t!("display.status", source = config.capture_source));
println!("capture backend: {}", config.capture_backend);
println!("multiple monitors: {}", config.capture_multiple);
if let Some(output) = &config.capture_output {
println!("output: {output}");
}
Ok(()) Ok(())
} }
DisplayAction::Source { source } => { DisplayAction::Backend { backend, output } => {
config.capture_source = source.as_str().to_string(); let backend = match backend {
config.capture_restore_token = None; CaptureBackend::Portal => "portal",
config.remote_desktop_restore_token = None; CaptureBackend::Wayland => "wayland",
config.store()?; };
let config = config::Config::update(|stored| {
stored.capture_backend = backend.into();
stored.capture_output = output;
if backend == "wayland" {
stored.capture_source = "monitor".into();
stored.capture_multiple = false;
}
stored.capture_restore_token = None;
stored.remote_desktop_restore_token = None;
})?;
println!(
"{}",
if config.capture_backend == "wayland" {
t!("capture.direct_enabled").to_string()
} else {
t!("capture.portal_enabled").to_string()
}
);
Ok(())
}
DisplayAction::Outputs => unreachable!(),
DisplayAction::Source { source, multiple } => {
anyhow::ensure!(
!multiple || matches!(&source, DisplaySource::Monitor),
"--multiple is supported only for monitor sources"
);
anyhow::ensure!(
!multiple || config.capture_backend == "portal",
"multi-monitor selection requires the portal capture backend"
);
config::Config::update(|stored| {
stored.capture_source = source.as_str().to_string();
stored.capture_multiple = multiple;
stored.capture_restore_token = None;
stored.remote_desktop_restore_token = None;
})?;
println!("{}", t!("display.changed", source = source.as_str())); println!("{}", t!("display.changed", source = source.as_str()));
println!(
"multiple monitors: {multiple}; selection applies on the next session"
);
Ok(()) Ok(())
} }
} }
@@ -203,6 +315,7 @@ fn main() -> Result<()> {
Command::InternalTerminal => terminal::serve(), Command::InternalTerminal => terminal::serve(),
Command::InternalWallpaper => wallpaper::serve(), Command::InternalWallpaper => wallpaper::serve(),
Command::InternalInhibit => inhibit::serve(), Command::InternalInhibit => inhibit::serve(),
Command::InternalTray => tray::serve(),
Command::InternalLauncher => launcher::serve(), Command::InternalLauncher => launcher::serve(),
Command::Upstream { Command::Upstream {
action: UpstreamAction::Check, action: UpstreamAction::Check,
+2 -2
View File
@@ -2,7 +2,7 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::path::Path; use std::path::Path;
use std::process::{Command, Stdio}; use std::process::Stdio;
pub fn sync(prefix: &Path) -> Result<Option<String>> { pub fn sync(prefix: &Path) -> Result<Option<String>> {
let http = environment_proxy("HTTP_PROXY", "http_proxy"); let http = environment_proxy("HTTP_PROXY", "http_proxy");
@@ -60,7 +60,7 @@ fn proxy_endpoint(value: &str) -> Option<String> {
} }
fn reg_add(prefix: &Path, value: &str, kind: &str, data: &str) -> Result<()> { fn reg_add(prefix: &Path, value: &str, kind: &str, data: &str) -> Result<()> {
let status = Command::new("wine") let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all") .env("WINEDEBUG", "-all")
.args([ .args([
+763 -145
View File
File diff suppressed because it is too large. Load diff
+316
View File
@@ -0,0 +1,316 @@
//! Native StatusNotifierItem and DBusMenu, independent of Wine's XEmbed tray.
//! The supervisor owns this helper, so closing the session removes the item.
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
type Pixmap = (i32, i32, Vec<u8>);
type Properties = HashMap<String, OwnedValue>;
type Layout = (i32, Properties, Vec<OwnedValue>);
#[derive(Clone, Copy)]
enum Action {
Show,
Stop,
}
struct Tray {
actions: UnboundedSender<Action>,
icon: Pixmap,
}
#[zbus::interface(name = "org.kde.StatusNotifierItem")]
impl Tray {
#[zbus(property)]
fn category(&self) -> &str {
"ApplicationStatus"
}
#[zbus(property)]
fn id(&self) -> &str {
"uur"
}
#[zbus(property)]
fn title(&self) -> String {
t!("tray.title").to_string()
}
#[zbus(property)]
fn status(&self) -> &str {
"Active"
}
#[zbus(property)]
fn window_id(&self) -> i32 {
0
}
#[zbus(property)]
fn icon_name(&self) -> &str {
"uur"
}
#[zbus(property)]
fn icon_theme_path(&self) -> &str {
""
}
#[zbus(property)]
fn icon_pixmap(&self) -> Vec<Pixmap> {
vec![self.icon.clone()]
}
#[zbus(property)]
fn attention_icon_name(&self) -> &str {
""
}
#[zbus(property)]
fn attention_icon_pixmap(&self) -> Vec<Pixmap> {
Vec::new()
}
#[zbus(property)]
fn attention_movie_name(&self) -> &str {
""
}
#[zbus(property)]
fn overlay_icon_name(&self) -> &str {
""
}
#[zbus(property)]
fn overlay_icon_pixmap(&self) -> Vec<Pixmap> {
Vec::new()
}
#[zbus(property)]
fn item_is_menu(&self) -> bool {
false
}
#[zbus(property)]
fn menu(&self) -> OwnedObjectPath {
OwnedObjectPath::try_from("/MenuBar").unwrap()
}
#[zbus(property)]
fn tool_tip(&self) -> (String, Vec<Pixmap>, String, String) {
(
"uur".into(),
vec![self.icon.clone()],
t!("tray.title").to_string(),
t!("tray.tooltip").to_string(),
)
}
fn activate(&self, _x: i32, _y: i32) {
let _ = self.actions.send(Action::Show);
}
fn secondary_activate(&self, _x: i32, _y: i32) {
let _ = self.actions.send(Action::Show);
}
// Hosts draw the menu returned by Menu; no X11 popup is necessary.
fn context_menu(&self, _x: i32, _y: i32) {}
fn scroll(&self, _delta: i32, _orientation: &str) {}
fn provide_xdg_activation_token(&self, _token: &str) {}
}
struct Menu {
actions: UnboundedSender<Action>,
}
#[zbus::interface(name = "com.canonical.dbusmenu")]
impl Menu {
#[zbus(property)]
fn version(&self) -> u32 {
3
}
#[zbus(property)]
fn text_direction(&self) -> &str {
"ltr"
}
#[zbus(property)]
fn status(&self) -> &str {
"normal"
}
#[zbus(property)]
fn icon_theme_path(&self) -> Vec<String> {
Vec::new()
}
fn get_layout(
&self,
parent_id: i32,
recursion_depth: i32,
property_names: Vec<String>,
) -> zbus::fdo::Result<(u32, Layout)> {
let properties = menu_properties(parent_id, &property_names)?;
let mut children = Vec::new();
if parent_id == 0 && recursion_depth != 0 {
for id in [1, 2] {
let child = (
id,
menu_properties(id, &property_names)?,
Vec::<OwnedValue>::new(),
);
children.push(
OwnedValue::try_from(Value::new(child))
.map_err(|error| zbus::fdo::Error::Failed(error.to_string()))?,
);
}
}
Ok((1, (parent_id, properties, children)))
}
fn get_group_properties(
&self,
ids: Vec<i32>,
property_names: Vec<String>,
) -> zbus::fdo::Result<Vec<(i32, Properties)>> {
let ids = if ids.is_empty() { vec![0, 1, 2] } else { ids };
ids.into_iter()
.map(|id| Ok((id, menu_properties(id, &property_names)?)))
.collect()
}
fn get_property(&self, id: i32, name: &str) -> zbus::fdo::Result<OwnedValue> {
menu_properties(id, &[])?
.remove(name)
.ok_or_else(|| zbus::fdo::Error::InvalidArgs(format!("unknown menu property {name}")))
}
fn event(
&self,
id: i32,
event_id: &str,
_data: OwnedValue,
_timestamp: u32,
) -> zbus::fdo::Result<()> {
let action = match id {
1 => Action::Show,
2 => Action::Stop,
0 => return Ok(()),
_ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())),
};
if event_id == "clicked" {
let _ = self.actions.send(action);
}
Ok(())
}
fn event_group(&self, events: Vec<(i32, String, OwnedValue, u32)>) -> Vec<i32> {
events
.into_iter()
.filter_map(|(id, event, data, timestamp)| {
self.event(id, &event, data, timestamp).err().map(|_| id)
})
.collect()
}
fn about_to_show(&self, id: i32) -> zbus::fdo::Result<bool> {
menu_properties(id, &[])?;
Ok(false)
}
fn about_to_show_group(&self, ids: Vec<i32>) -> (Vec<i32>, Vec<i32>) {
(
Vec::new(),
ids.into_iter().filter(|id| !(0..=2).contains(id)).collect(),
)
}
}
fn menu_properties(id: i32, requested: &[String]) -> zbus::fdo::Result<Properties> {
let mut properties = Properties::new();
let string = |value: String| OwnedValue::from(zbus::zvariant::Str::from(value));
match id {
0 => {
properties.insert("children-display".into(), string("submenu".into()));
}
1 | 2 => {
properties.insert(
"label".into(),
string(if id == 1 {
t!("tray.open").to_string()
} else {
t!("tray.quit").to_string()
}),
);
properties.insert("enabled".into(), OwnedValue::from(true));
properties.insert("visible".into(), OwnedValue::from(true));
}
_ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())),
}
if !requested.is_empty() {
properties.retain(|key, _| requested.contains(key));
}
Ok(properties)
}
fn icon_pixmap() -> Result<Pixmap> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(include_bytes!(
"../packaging/uur-icon.png"
)));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().context("reading tray icon")?;
let mut pixels = vec![
0;
reader
.output_buffer_size()
.context("tray icon size overflow")?
];
let info = reader
.next_frame(&mut pixels)
.context("decoding tray icon")?;
anyhow::ensure!(
info.color_type == png::ColorType::Rgba,
"tray icon must be RGBA"
);
pixels.truncate(info.buffer_size());
// SNI requires network-byte-order ARGB32, not PNG's RGBA byte order.
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.rotate_right(1);
}
Ok((info.width.try_into()?, info.height.try_into()?, pixels))
}
pub fn serve() -> Result<()> {
let stopping = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?;
signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?;
tokio::runtime::Runtime::new()?.block_on(async {
let (actions, mut receiver) = unbounded_channel();
let connection = zbus::connection::Builder::session()?
.serve_at("/StatusNotifierItem", Tray { actions: actions.clone(), icon: icon_pixmap()? })?
.serve_at("/MenuBar", Menu { actions })?.build().await?;
let bus = zbus::fdo::DBusProxy::new(&connection).await?;
let mut watcher_owner = None;
let mut timer = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
tokio::select! {
action = receiver.recv() => match action {
Some(Action::Show) => {
tokio::task::spawn_blocking(|| {
if let Err(error) = crate::session::show_client() { eprintln!("tray: {error}"); }
});
}
Some(Action::Stop) => {
tokio::task::spawn_blocking(crate::session::stop).await??;
break;
}
None => break,
},
_ = timer.tick() => {
if stopping.load(Ordering::Relaxed) { break; }
let owner = bus.get_name_owner("org.kde.StatusNotifierWatcher".try_into()?).await.ok();
if owner != watcher_owner {
if owner.is_some() {
let watcher = zbus::Proxy::new(&connection, "org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher", "org.kde.StatusNotifierWatcher").await?;
match watcher.call::<_, _, ()>("RegisterStatusNotifierItem", &("/StatusNotifierItem",)).await {
Ok(()) => {
println!("{}", t!("tray.registered"));
watcher_owner = owner;
}
Err(error) => eprintln!("tray registration: {error}"),
}
} else { watcher_owner = None; }
}
}
}
}
Ok(())
})
}
+490
View File
@@ -0,0 +1,490 @@
//! Explicit per-user removal. Distribution-owned files stay with the package
//! manager; a source installation is identified by its installer receipt.
use anyhow::{Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{IsTerminal, Write};
use std::os::unix::fs::MetadataExt;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
#[derive(Clone, Copy)]
enum Removal {
File,
Tree,
EmptyDirectory,
}
struct Plan {
home: PathBuf,
data: PathBuf,
config: PathBuf,
state: PathBuf,
runtime: PathBuf,
entries: BTreeMap<PathBuf, Removal>,
source_install: bool,
}
pub fn run(purge: bool, dry_run: bool, yes: bool) -> Result<()> {
if unsafe { libc::geteuid() } == 0 {
anyhow::bail!("{}", t!("uninstall.no_root"));
}
let mut plan = Plan::build(purge)?;
println!("{}", t!("uninstall.plan"));
for (path, removal) in &plan.entries {
if !matches!(removal, Removal::EmptyDirectory) {
println!(" {}", path.display());
}
}
if purge {
println!("{}", t!("uninstall.purge_warning"));
} else {
println!("{}", t!("uninstall.keep_data"));
}
println!("{}", t!("uninstall.package_hint"));
if dry_run {
println!("{}", t!("uninstall.dry_run"));
return Ok(());
}
if !yes {
if !std::io::stdin().is_terminal() {
anyhow::bail!("{}", t!("uninstall.confirm_required"));
}
print!("{} ", t!("uninstall.confirm"));
std::io::stdout().flush()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer)?;
if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
println!("{}", t!("uninstall.cancelled"));
return Ok(());
}
}
crate::session::stop()?;
// Keep setup/run excluded until the directory cleanup has finished.
let _session_lock = crate::session::acquire_session_lock()?;
stop_prefix(&plan.data.join("wine"))?;
// Revalidate the displayed targets after stopping the session. Do not add
// newly discovered files to a plan the user has already confirmed.
plan.validate()?;
// Remove integrations first, then the trees; the running ELF can be
// unlinked on Linux, so source installs need no second helper process.
let trees: Vec<_> = plan
.entries
.iter()
.filter_map(|(path, removal)| matches!(removal, Removal::Tree).then_some(path.clone()))
.collect();
plan.entries.retain(|path, removal| {
!matches!(removal, Removal::File)
|| !trees
.iter()
.any(|root| path != root && path.starts_with(root))
});
let mut removals: Vec<_> = plan
.entries
.iter()
.filter(|(_, removal)| !matches!(removal, Removal::EmptyDirectory))
.collect();
// Keep the receipt until all installed files are removed, so a failed
// cleanup can be retried from another copy of uur.
removals.sort_by_key(
|(path, _)| match path.file_name().and_then(|name| name.to_str()) {
Some("user-install") => 2,
Some("uur") if path.parent().and_then(Path::file_name) == Some("bin".as_ref()) => 1,
_ => 0,
},
);
for (path, removal) in removals {
remove(path, *removal)?;
}
for (path, removal) in plan.entries.iter().rev() {
if matches!(removal, Removal::EmptyDirectory) {
remove(path, *removal)?;
}
}
println!("{}", t!("uninstall.done"));
if !plan.source_install {
println!("{}", t!("uninstall.package_hint"));
}
Ok(())
}
impl Plan {
fn build(purge: bool) -> Result<Self> {
let home = absolute(PathBuf::from(
std::env::var_os("HOME").context("HOME is unset")?,
))?;
let data_home = xdg_home("XDG_DATA_HOME", &home.join(".local/share"))?;
let config_home = xdg_home("XDG_CONFIG_HOME", &home.join(".config"))?;
let state_home = xdg_home("XDG_STATE_HOME", &home.join(".local/state"))?;
let runtime_home = xdg_home(
"XDG_RUNTIME_DIR",
&PathBuf::from(format!("/tmp/uur-{}", unsafe { libc::geteuid() })),
)?;
let mut plan = Self {
home: home.clone(),
data: data_home.join("uur"),
config: config_home.join("uur"),
state: state_home.join("uur"),
runtime: runtime_home.join("uur"),
entries: BTreeMap::new(),
source_install: false,
};
plan.entries.insert(plan.runtime.clone(), Removal::Tree);
if purge {
for path in [&plan.data, &plan.config, &plan.state] {
plan.entries.insert(path.clone(), Removal::Tree);
}
}
let default_scope = data_home == home.join(".local/share");
let mut desktops = BTreeSet::new();
scan_files(&data_home.join("applications"), 8, &mut desktops)?;
// Old releases placed compatibility aliases in ~/.local/share even
// when XDG_DATA_HOME was set. Only entries tied to this prefix qualify.
scan_files(&home.join(".local/share/applications"), 8, &mut desktops)?;
scan_files(&desktop_dir(&home, &config_home), 1, &mut desktops)?;
let autostart = config_home.join("autostart/uur.desktop");
if autostart.exists() {
desktops.insert(autostart);
}
let mut removed_icons = BTreeSet::new();
let mut kept_icons = BTreeSet::new();
let mut remove_default_icons = default_scope;
for path in desktops {
if path
.extension()
.is_none_or(|extension| extension != "desktop")
{
continue;
}
let content = std::fs::read_to_string(&path)
.with_context(|| format!("reading {}", path.display()))?;
let icon = desktop_value(&content, "Icon").unwrap_or_default();
if plan.owns_desktop(&content, default_scope) {
remove_default_icons |= path.starts_with(home.join(".local/share/applications"))
|| path.starts_with(desktop_dir(&home, &config_home));
plan.entries.insert(path, Removal::File);
removed_icons.insert(icon.to_string());
} else {
kept_icons.insert(icon.to_string());
}
}
let mut icon_roots = BTreeSet::from([data_home.join("icons")]);
if remove_default_icons {
icon_roots.insert(home.join(".local/share/icons"));
}
for icons in icon_roots {
let mut files = BTreeSet::new();
scan_files(&icons, 6, &mut files)?;
for path in files {
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let alias = stem.strip_suffix(".0").unwrap_or(stem);
if (removed_icons.contains(stem) || removed_icons.contains(alias))
&& !kept_icons.contains(stem)
&& !kept_icons.contains(alias)
{
plan.entries.insert(path, Removal::File);
}
}
}
plan.source_files()?;
plan.validate()?;
Ok(plan)
}
fn owns_desktop(&self, content: &str, default_scope: bool) -> bool {
let prefix = self.data.join("wine");
if let Some(recorded) = desktop_value(content, "X-UUR-Prefix") {
return desktop_value(content, "X-UUR-Managed") == Some("true")
&& recorded == prefix.to_string_lossy();
}
let managed = desktop_value(content, "X-UUR-Managed") == Some("true")
|| desktop_value(content, "Comment") == Some("Start the managed UU Remote session")
|| desktop_value(content, "Comment") == Some("UU Remote for Linux (uur)");
if managed && default_scope {
return true;
}
// Wine writes an explicit WINEPREFIX assignment in its launchers.
// Match the entire quoted/unquoted value, not a filename substring.
let exec = desktop_value(content, "Exec").unwrap_or_default();
let prefix = prefix.to_string_lossy();
let references_prefix = [
format!("WINEPREFIX=\"{prefix}\" "),
format!("WINEPREFIX='{prefix}' "),
format!("WINEPREFIX={prefix} "),
]
.iter()
.any(|assignment| exec.contains(assignment));
references_prefix && exec.to_ascii_lowercase().contains("gameviewer")
}
fn source_files(&mut self) -> Result<()> {
let executable = std::env::current_exe()?;
let mut prefixes = BTreeSet::from([self.home.join(".local")]);
if let Some(prefix) = executable.parent().and_then(Path::parent) {
if executable.parent().and_then(Path::file_name) == Some("bin".as_ref()) {
prefixes.insert(prefix.to_path_buf());
}
}
if let Some(prefix) = std::env::var_os("UUR_INSTALL_PREFIX") {
prefixes.insert(absolute(PathBuf::from(prefix))?);
}
for prefix in prefixes {
let receipt = prefix.join("lib/uur/user-install");
let marked = std::fs::read_to_string(&receipt).is_ok_and(|content| {
content == format!("uur-user-install-v1\n{}\n", self.data.display())
});
// Support the previous source installer, but only while executing
// its ~/.local/bin/uur and with the matching generated menu entry.
let legacy = prefix == self.home.join(".local")
&& std::fs::canonicalize(prefix.join("bin/uur")).ok() == Some(executable.clone())
&& std::fs::read_to_string(prefix.join("share/applications/uur.desktop"))
.is_ok_and(|content| {
desktop_value(&content, "TryExec")
== Some(prefix.join("bin/uur").to_string_lossy().as_ref())
});
if !marked && !legacy {
continue;
}
self.source_install = true;
for relative in [
"bin/uur",
"lib/uur/user-install",
"lib/uur/uur-pw-capture",
"lib/uur/uur-wl-capture",
"lib/uur/libuur-lock-mods.so",
"lib/uur/hook/wevtapi.dll",
"lib/uur/hook/uur-hook.dll",
"lib/uur/hook/wtsapi32.dll",
"lib/uur/hook/winlogon.exe",
"lib/uur/hook/uur-terminal-proxy.exe",
"lib/uur/hook/uur-mux-proxy.exe",
"lib/uur/hook/uur-launch-proxy.exe",
"share/applications/uur.desktop",
"share/icons/hicolor/256x256/apps/uur.png",
] {
let path = prefix.join(relative);
if std::fs::symlink_metadata(&path).is_ok() {
self.entries.insert(path, Removal::File);
}
}
for relative in ["lib/uur/hook", "lib/uur"] {
self.entries
.insert(prefix.join(relative), Removal::EmptyDirectory);
}
}
Ok(())
}
fn validate(&self) -> Result<()> {
// Session shutdown/locking access these paths before tree removal.
// Reject redirected state rather than following a link while writing
// the lock or stopping an unrelated Wine prefix.
for path in [
&self.data,
&self.state,
&self.runtime,
&self.state.join("session.lock"),
&self.data.join("wine"),
] {
if path.is_symlink() {
anyhow::bail!("refusing redirected session state: {}", path.display());
}
if std::fs::metadata(path)
.is_ok_and(|metadata| metadata.uid() != unsafe { libc::geteuid() })
{
anyhow::bail!("session state belongs to another user: {}", path.display());
}
}
for (path, removal) in &self.entries {
let path = absolute(path.clone())?;
// Resolve ancestor links, but never resolve the final link: remove
// symlink entries themselves, not the objects they point at.
let resolved = path
.parent()
.and_then(|parent| std::fs::canonicalize(parent).ok())
.map(|parent| parent.join(path.file_name().unwrap_or_default()))
.unwrap_or_else(|| path.clone());
if path == self.home || resolved == self.home || path.parent().is_none() {
anyhow::bail!("refusing to remove {}", path.display());
}
// Never allow a receipt or an XDG override to select system trees.
for system in [
"/usr", "/etc", "/opt", "/var", "/nix", "/bin", "/lib", "/sbin", "/boot", "/dev",
"/proc", "/sys",
] {
if path.starts_with(system) || resolved.starts_with(system) {
anyhow::bail!("refusing to remove system path {}", path.display());
}
}
match std::fs::symlink_metadata(&path) {
Ok(metadata) => {
if metadata.uid() != unsafe { libc::geteuid() } {
anyhow::bail!(
"refusing to remove a path owned by another user: {}",
path.display()
);
}
if matches!(removal, Removal::Tree)
&& !metadata.file_type().is_symlink()
&& (path.join(".git").exists() || path.join("Cargo.toml").exists())
{
anyhow::bail!("refusing to remove a source checkout: {}", path.display());
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(error).with_context(|| format!("checking {}", path.display()))
}
}
}
Ok(())
}
}
fn absolute(path: PathBuf) -> Result<PathBuf> {
if !path.is_absolute() {
anyhow::bail!(
"uninstall requires absolute XDG/install paths: {}",
path.display()
);
}
let mut normalized = PathBuf::from("/");
for component in path.components() {
match component {
Component::Normal(part) => normalized.push(part),
Component::ParentDir => {
normalized.pop();
}
_ => {}
}
}
Ok(normalized)
}
fn xdg_home(variable: &str, fallback: &Path) -> Result<PathBuf> {
absolute(
std::env::var_os(variable)
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| fallback.to_path_buf()),
)
}
fn desktop_value<'a>(content: &'a str, key: &str) -> Option<&'a str> {
let mut main_section = false;
for line in content.lines() {
if line.starts_with('[') {
main_section = line == "[Desktop Entry]";
} else if main_section {
if let Some((name, value)) = line.split_once('=') {
if name == key {
return Some(value);
}
}
}
}
None
}
fn desktop_dir(home: &Path, config_home: &Path) -> PathBuf {
// user-dirs.dirs is data, not a shell script: never source it.
std::fs::read_to_string(config_home.join("user-dirs.dirs"))
.ok()
.and_then(|content| {
content.lines().find_map(|line| {
let value = line.strip_prefix("XDG_DESKTOP_DIR=\"")?.strip_suffix('"')?;
let path = value
.strip_prefix("$HOME/")
.map(|suffix| home.join(suffix))
.unwrap_or_else(|| PathBuf::from(value));
(path.is_absolute() && path != home).then_some(path)
})
})
.unwrap_or_else(|| home.join("Desktop"))
}
fn scan_files(dir: &Path, depth: u8, files: &mut BTreeSet<PathBuf>) -> Result<()> {
if depth == 0 {
return Ok(());
}
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("listing {}", dir.display())),
};
for entry in entries {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_dir() {
scan_files(&entry.path(), depth - 1, files)?;
} else if kind.is_file() {
files.insert(entry.path());
}
}
Ok(())
}
fn stop_prefix(prefix: &Path) -> Result<()> {
if !prefix.is_dir() || prefix.is_symlink() {
return Ok(());
}
match Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-k")
.stdin(Stdio::null())
.status()
{
// -k exits 1 when stop already shut down this prefix's server. The
// following -w, with a deadline, is the actual shutdown check.
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).context("stopping the managed wineserver"),
}
let mut wait = Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-w")
.stdin(Stdio::null())
.spawn()?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
if let Some(status) = wait.try_wait()? {
if !status.success() {
anyhow::bail!("wineserver shutdown failed");
}
return Ok(());
}
if std::time::Instant::now() >= deadline {
let _ = wait.kill();
let _ = wait.wait();
anyhow::bail!("managed wineserver is still running; no files were removed");
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
fn remove(path: &Path, removal: Removal) -> Result<()> {
let metadata = match std::fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("checking {}", path.display())),
};
let result = match removal {
Removal::Tree if metadata.is_dir() && !metadata.file_type().is_symlink() => {
std::fs::remove_dir_all(path)
}
Removal::EmptyDirectory if metadata.is_dir() => std::fs::remove_dir(path),
_ => std::fs::remove_file(path),
};
match result {
Err(error)
if matches!(removal, Removal::EmptyDirectory)
&& error.kind() == std::io::ErrorKind::DirectoryNotEmpty =>
{
Ok(())
}
other => other.with_context(|| format!("removing {}", path.display())),
}
}
+2 -1
View File
@@ -71,7 +71,8 @@ fn extract_version(filename: &str) -> Option<String> {
fn installed_version() -> Option<String> { fn installed_version() -> Option<String> {
let prefix = crate::config::data_dir().ok()?.join("wine"); let prefix = crate::config::data_dir().ok()?.join("wine");
crate::wine::find_client_dir(&prefix)?; crate::wine::find_client_dir(&prefix)?;
let output = Command::new("wine") let output = crate::wine::command(&prefix)
.ok()?
.env("WINEPREFIX", &prefix) .env("WINEPREFIX", &prefix)
.env("WINEDEBUG", "-all") .env("WINEDEBUG", "-all")
.args([ .args([
+38 -5
View File
@@ -90,7 +90,7 @@ pub fn sync(prefix: &Path) -> Result<Option<Wallpaper>> {
}; };
let compatible = windows_compatible_path(&wallpaper.path)?; let compatible = windows_compatible_path(&wallpaper.path)?;
let windows_path = format!("Z:{}", compatible.display()).replace('/', "\\"); let windows_path = format!("Z:{}", compatible.display()).replace('/', "\\");
let status = Command::new("wine") let status = crate::wine::command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all") .env("WINEDEBUG", "-all")
.args([ .args([
@@ -276,12 +276,13 @@ fn detect_runtime_provider() -> Option<PathBuf> {
.and_then(OsStr::to_str) .and_then(OsStr::to_str)
.unwrap_or_default(); .unwrap_or_default();
let candidate = match executable { let candidate = match executable {
"swaybg" => argument_after(&arguments, "-i"), "swaybg" => argument_after(&arguments, "-i").map(PathBuf::from),
"xwallpaper" => arguments.last().cloned(), "xwallpaper" => arguments.last().map(PathBuf::from),
"mpvpaper" => arguments.last().cloned(), "mpvpaper" => arguments.last().map(PathBuf::from),
"wpaperd" => wpaperd_link(&entry.path()),
_ => None, _ => None,
}; };
if let Some(path) = candidate.and_then(|value| resolve_candidate(PathBuf::from(value))) { if let Some(path) = candidate.and_then(resolve_candidate) {
return Some(path); return Some(path);
} }
} }
@@ -303,6 +304,32 @@ fn argument_after(arguments: &[String], option: &str) -> Option<String> {
.map(|pair| pair[1].clone()) .map(|pair| pair[1].clone())
} }
/// wpaperd >= 1.1.0 mirrors the current wallpaper of every output as a
/// symlink under `$XDG_STATE_HOME/wpaperd/wallpapers`, rewritten on each
/// change. Image paths are written verbatim, so absolute targets are used
/// as-is while relative ones resolve against wpaperd's working directory.
/// The newest resolvable link wins; leftovers from earlier runs are older.
fn wpaperd_link(proc: &Path) -> Option<PathBuf> {
let cwd = std::fs::read_link(proc.join("cwd")).ok()?;
std::fs::read_dir(state_home().join("wpaperd/wallpapers"))
.ok()?
.flatten()
.filter_map(|entry| {
let link = entry.path();
let target = std::fs::read_link(&link).ok()?;
let target = if target.is_absolute() {
target
} else {
cwd.join(target)
};
let path = resolve_candidate(target)?;
let modified = std::fs::symlink_metadata(&link).ok()?.modified().ok()?;
Some((modified, path))
})
.max_by_key(|(modified, _)| *modified)
.map(|(_, path)| path)
}
fn wallpaper_from_value(value: &str, provider: &'static str) -> Option<Wallpaper> { fn wallpaper_from_value(value: &str, provider: &'static str) -> Option<Wallpaper> {
let value = value.trim().trim_matches(['\'', '"']); let value = value.trim().trim_matches(['\'', '"']);
if value.is_empty() { if value.is_empty() {
@@ -545,6 +572,12 @@ fn config_home() -> PathBuf {
.unwrap_or_else(|| home_dir().join(".config")) .unwrap_or_else(|| home_dir().join(".config"))
} }
fn state_home() -> PathBuf {
std::env::var_os("XDG_STATE_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".local/state"))
}
fn home_dir() -> PathBuf { fn home_dir() -> PathBuf {
std::env::var_os("HOME") std::env::var_os("HOME")
.map(PathBuf::from) .map(PathBuf::from)
+519 -86
View File
@@ -1,16 +1,42 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::config::Config; use crate::config::Config;
const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd"; const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd";
const EULA_URL: &str = "https://uuyc.163.com/contact/20240402/40294_1146065.html"; const EULA_URL: &str = "https://uuyc.163.com/contact/20240402/40294_1146065.html";
const SETUP_DLL_OVERRIDES: &str = "wevtapi=b,wtsapi32=b";
/// Apply process-local compatibility to every managed-prefix Wine launch,
/// including the first utility that starts wineserver and its service manager.
pub(crate) fn command(prefix: &Path) -> Result<Command> {
let mut command = Command::new("wine");
command.env("WINEPREFIX", prefix);
let managed = crate::config::data_dir().is_ok_and(|data| data.join("wine") == prefix);
if managed {
let config = Config::load()?;
crate::audio::apply_capture_env(&mut command, &config)?;
if let Err(error) = crate::session::apply_lock_mods_env(&mut command, &config) {
eprintln!("Wine keyboard compatibility unavailable: {error}");
}
}
Ok(command)
}
struct SetupPrefix(PathBuf);
impl Drop for SetupPrefix {
fn drop(&mut self) {
stop_wineserver(&self.0);
}
}
/// One-time provisioning. Deliberately quiet: progress on stdout, nothing /// One-time provisioning. Deliberately quiet: progress on stdout, nothing
/// else. NetEase binaries are never redistributed — they are fetched from /// else. NetEase binaries are never redistributed — they are fetched from
/// the official feed into a per-user prefix. /// the official feed into a per-user prefix.
pub fn setup(accept_eula: bool) -> Result<()> { pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
let mut config = Config::load()?; let mut config = Config::load()?;
if !config.eula_accepted { if !config.eula_accepted {
@@ -23,19 +49,41 @@ pub fn setup(accept_eula: bool) -> Result<()> {
println!("{}", t!("setup.eula_recorded")); println!("{}", t!("setup.eula_recorded"));
} }
let _session_lock = crate::session::acquire_session_lock()?;
let data = crate::config::data_dir()?; let data = crate::config::data_dir()?;
let prefix = data.join("wine"); let prefix = data.join("wine");
std::fs::create_dir_all(&prefix).context("creating wine prefix directory")?; std::fs::create_dir_all(&prefix).context("creating wine prefix directory")?;
let cache = data.join("cache"); let cache = data.join("cache");
std::fs::create_dir_all(&cache).context("creating cache directory")?; std::fs::create_dir_all(&cache).context("creating cache directory")?;
let _prefix_cleanup = SetupPrefix(prefix.clone());
if find_client_dir(&prefix).is_some() { if !repair
apply_registry_compat(&prefix)?; && prefix_initialized(&prefix)
let uur_bin = std::env::current_exe().unwrap_or_default(); && find_client_dir(&prefix).is_some()
let _ = adopt_shortcut(&prefix, &uur_bin); && client_service_registered(&prefix)
{
finish_setup(&prefix)?;
println!("{}", t!("setup.already_provisioned")); println!("{}", t!("setup.already_provisioned"));
stop_wineserver(&prefix); return Ok(());
}
println!("{}", t!("setup.initializing_prefix"));
let status = Command::new("wineboot")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
.arg(if repair { "--update" } else { "--init" })
.status()
.context("running wineboot")?;
if !status.success() {
anyhow::bail!("{}", t!("setup.prefix_failed", status = status));
}
flush_prefix(&prefix).context("waiting for Wine to persist the initialized prefix")?;
if find_client_dir(&prefix).is_some() && query_client_service(&prefix)? {
finish_setup(&prefix)?;
println!("{}", t!("setup.repaired", path = prefix.display()));
return Ok(()); return Ok(());
} }
@@ -57,82 +105,114 @@ pub fn setup(accept_eula: bool) -> Result<()> {
anyhow::bail!("{}", t!("setup.download_failed")); anyhow::bail!("{}", t!("setup.download_failed"));
} }
println!("{}", t!("setup.initializing_prefix"));
let _ = Command::new("wineboot")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.arg("--init")
.status()
.context("running wineboot")?;
// The preload chain only works if Wine resolves wevtapi to the native
// shim in the application directory instead of its builtin.
let _ = Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.args([
"reg",
"add",
r"HKCU\Software\Wine\DllOverrides",
"/v",
"wevtapi",
"/t",
"REG_SZ",
"/d",
"native",
"/f",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("registering wevtapi dll override")?;
println!("{}", t!("setup.installing_client")); println!("{}", t!("setup.installing_client"));
let status = Command::new("wine") let status = command(&prefix)?
.env("WINEPREFIX", &prefix) .env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
.arg(installer.to_string_lossy().as_ref()) .arg(installer.to_string_lossy().as_ref())
.arg("/S") .arg("/S")
.status() .status()
.context("launching installer")?; .context("launching installer")?;
if !status.success() { if !status.success() {
println!("{}", t!("setup.silent_install_unavailable")); anyhow::bail!("{}", t!("setup.install_failed", status = status));
} }
find_client_dir(&prefix).context(t!("setup.client_incomplete").to_string())?;
if !query_client_service(&prefix)? {
anyhow::bail!("{}", t!("setup.service_incomplete"));
}
finish_setup(&prefix)?;
println!("{}", t!("setup.done", path = prefix.display().to_string()));
Ok(())
}
fn finish_setup(prefix: &Path) -> Result<()> {
// winemenubuilder generated its entries during the install: adopt the // winemenubuilder generated its entries during the install: adopt the
// start-menu one for the full session, then stop it from producing raw // start-menu one for the full session, then stop it from producing raw
// shortcuts ever again, and sweep desktop copies. // shortcuts ever again, and sweep desktop copies.
let _ = Command::new("wine") set_dll_override(prefix, "wevtapi", "native")?;
.env("WINEPREFIX", &prefix) set_dll_override(prefix, "winemenubuilder", "")?;
.env("WINEDEBUG", wine_debug()) apply_registry_compat(prefix)?;
.args([
"reg",
"add",
r"HKCU\Software\Wine\DllOverrides",
"/v",
"winemenubuilder",
"/t",
"REG_SZ",
"/d",
"",
"/f",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("disabling winemenubuilder")?;
apply_registry_compat(&prefix)?;
let uur_bin = std::env::current_exe().unwrap_or_default(); let uur_bin = std::env::current_exe().unwrap_or_default();
let _ = adopt_shortcut(&prefix, &uur_bin); let _ = adopt_shortcut(prefix, &uur_bin);
purge_wine_shortcuts(); purge_wine_shortcuts();
println!("{}", t!("setup.done", path = prefix.display().to_string()));
stop_wineserver(&prefix);
Ok(()) Ok(())
} }
pub fn prefix_initialized(prefix: &Path) -> bool {
["system.reg", "user.reg"]
.iter()
.all(|name| std::fs::metadata(prefix.join(name)).is_ok_and(|metadata| metadata.len() > 0))
}
pub fn webview2_installed(prefix: &Path) -> bool {
let application = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application");
find_dir_recursive(&application, "msedgewebview2.exe", 3)
.is_some_and(|path| std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0))
}
/// The Windows service NetEase's installer registers points at
/// `GameViewerService.exe`. `GameViewerServer.exe` is a different program —
/// the streaming/terminal server — and never appears in the service
/// ImagePath, so matching on it made every provisioning check fail and left
/// `uur setup` re-downloading and re-installing on an already complete prefix.
const SERVICE_IMAGE: &str = "gameviewerservice.exe";
/// Extract the `ImagePath` recorded for the UU Windows service from the raw
/// `system.reg` text. Kept pure so it can be tested without a Wine prefix.
fn service_image_path(registry: &str) -> Option<String> {
let mut service_section = false;
for line in registry.lines() {
if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) {
service_section = section
.0
.to_ascii_lowercase()
.ends_with(r"\\services\\gameviewerservice");
} else if service_section {
if let Some(value) = line.trim_start().strip_prefix("\"ImagePath\"=") {
return Some(value.to_ascii_lowercase());
}
}
}
None
}
/// Read the persisted Wine service registration without starting Wine or
/// showing component installers from `uur doctor`.
pub fn client_service_registered(prefix: &Path) -> bool {
let Ok(registry) = std::fs::read_to_string(prefix.join("system.reg")) else {
return false;
};
service_image_path(&registry).is_some_and(|image| image.contains(SERVICE_IMAGE))
}
fn query_client_service(prefix: &Path) -> Result<bool> {
let output = command(prefix)?
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
.args([
"reg",
"query",
r"HKLM\System\CurrentControlSet\Services\GameViewerService",
"/v",
"ImagePath",
])
.stdin(Stdio::null())
.output()
.context("checking the UU Windows service registration")?;
// Wine may record the service under `ControlSet001` and only alias it as
// `CurrentControlSet`, and `reg query` output is CRLF; matching the
// executable name case-insensitively anywhere in stdout covers both.
Ok(output.status.success()
&& String::from_utf8_lossy(&output.stdout)
.to_ascii_lowercase()
.contains(SERVICE_IMAGE))
}
/// Registry compatibility profile, ported from the field-tested reference /// Registry compatibility profile, ported from the field-tested reference
/// implementation: /// implementation:
/// ///
@@ -196,7 +276,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
format!("HKCU\\{key}") format!("HKCU\\{key}")
}; };
for (value, reg_type, data) in &values { for (value, reg_type, data) in &values {
let _ = Command::new("wine") let status = command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.args([ .args([
@@ -207,13 +287,16 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
.stderr(Stdio::null()) .stderr(Stdio::null())
.status() .status()
.with_context(|| format!("reg add {full} /v {value}"))?; .with_context(|| format!("reg add {full} /v {value}"))?;
if !status.success() {
anyhow::bail!("Wine rejected registry compatibility setting {full} /v {value}");
}
} }
} }
Ok(()) Ok(())
} }
pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> { pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
let status = Command::new("wine") let status = command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.args([ .args([
@@ -239,6 +322,39 @@ pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
Ok(()) Ok(())
} }
pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
let status = log_pixels_command(prefix, dpi)?
.status()
.context("setting the Wine system DPI")?;
if !status.success() {
anyhow::bail!("Wine rejected the system DPI value {dpi}");
}
Ok(())
}
fn log_pixels_command(prefix: &Path, dpi: u32) -> Result<Command> {
let mut command = command(prefix)?;
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
"reg",
"add",
r"HKCU\Control Panel\Desktop",
"/v",
"LogPixels",
"/t",
"REG_DWORD",
"/d",
&dpi.to_string(),
"/f",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
Ok(command)
}
fn wine_debug() -> String { fn wine_debug() -> String {
std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string()) std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string())
} }
@@ -250,29 +366,145 @@ fn stop_wineserver(prefix: &Path) {
.status(); .status();
} }
/// Wait for a new prefix's registry files without waiting for running services
/// to exit. Existing prefixes can be queried through Wine immediately.
fn flush_prefix(prefix: &Path) -> Result<()> {
if prefix_initialized(prefix) {
return Ok(());
}
let mut child = Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-w")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.context("starting wineserver registry wait")?;
let deadline = Instant::now() + Duration::from_secs(30);
let result = loop {
if prefix_initialized(prefix) {
break Ok(());
}
match child.try_wait() {
Ok(Some(status)) if !status.success() => {
break Err(anyhow::anyhow!(
"wineserver registry wait failed ({status})"
));
}
Err(error) => break Err(error).context("checking wineserver registry wait"),
_ => {}
}
if Instant::now() >= deadline {
break Err(anyhow::anyhow!(
"Wine did not create non-empty system.reg and user.reg within 30 seconds"
));
}
std::thread::sleep(Duration::from_millis(100));
};
// This is only the `-w` waiter, not the prefix's server or its processes.
if child.try_wait().ok().flatten().is_none() {
let _ = child.kill();
let _ = child.wait();
}
result
}
/// Locate the installed client directory regardless of how NetEase spells /// Locate the installed client directory regardless of how NetEase spells
/// the vendor folder ("Netease", "NetEase", ...). Case matters on Linux. /// the vendor folder ("Netease", "NetEase", ...). Case matters on Linux.
///
/// NetEase ships the payload both as `<root>/bin/` and as a sibling
/// `<root>/<version>/` directory. The version directory is *not* the
/// application root: uur reaches the client through `<root>/bin/...` for the
/// terminal proxies and the WebView2 bootstrapper. The old search returned
/// the first `GameViewerServer.exe` it happened to reach, so when readdir
/// order put `<root>/<version>/` first it returned that instead, every
/// `join("bin")` lookup missed, and `uur run` aborted with a missing WebView2
/// bootstrapper.
///
/// Rank every directory that holds the launcher and pick the best-scoring,
/// shallowest one, so the choice no longer depends on readdir order.
pub fn find_client_dir(prefix: &Path) -> Option<PathBuf> { pub fn find_client_dir(prefix: &Path) -> Option<PathBuf> {
let program_files = prefix.join("drive_c").join("Program Files"); let program_files = prefix.join("drive_c").join("Program Files");
let entries = std::fs::read_dir(&program_files).ok()?; let entries = std::fs::read_dir(&program_files).ok()?;
let mut roots = Vec::new();
for entry in entries.flatten() { for entry in entries.flatten() {
let name = entry.file_name(); if !entry
if name.to_string_lossy().eq_ignore_ascii_case("netease") { .file_name()
let vendor = entry.path(); .to_string_lossy()
if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) { .eq_ignore_ascii_case("netease")
let bin = found.parent()?; {
if bin continue;
.file_name() }
.is_some_and(|name| name.eq_ignore_ascii_case("bin")) collect_client_roots(&entry.path(), 4, &mut roots);
{ }
return bin.parent().map(Path::to_path_buf); roots.retain(|root| client_root_rank(root) > 0);
} roots.sort_by(|left, right| {
return Some(bin.to_path_buf()); client_root_rank(right)
.cmp(&client_root_rank(left))
.then_with(|| left.components().count().cmp(&right.components().count()))
.then_with(|| left.cmp(right))
});
roots.dedup();
roots.into_iter().next()
}
/// Installed releases normally place their payload in bin/. A complete flat
/// version directory remains usable when it is the only installation present.
pub fn client_payload_dir(client: &Path) -> PathBuf {
let bin = client.join("bin");
if non_empty_file(&bin.join("GameViewerServer.exe")) {
bin
} else {
client.to_path_buf()
}
}
/// Collect every directory that contains the client launcher.
fn collect_client_roots(dir: &Path, depth: u8, out: &mut Vec<PathBuf>) {
if depth == 0 {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_client_roots(&path, depth - 1, out);
} else if path
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("GameViewer.exe"))
&& non_empty_file(&path)
{
if let Some(parent) = path.parent() {
out.push(parent.to_path_buf());
} }
return Some(vendor);
} }
} }
None }
/// Score a candidate root by how well it matches the layout uur drives.
///
/// `bin/GameViewerServer.exe` is the strong signal: the terminal proxies and
/// the WebView2 bootstrapper are all reached through `<root>/bin/`, so a
/// candidate whose `bin` holds the server is the real root, while the
/// `<root>/<version>/` payload copy only holds the launcher at its top level.
fn client_root_rank(candidate: &Path) -> u8 {
let bin = candidate.join("bin");
if non_empty_file(&bin.join("GameViewerServer.exe")) {
4 + u8::from(non_empty_file(&bin.join("MicrosoftEdgeWebview2Setup.exe")))
} else if non_empty_file(&candidate.join("GameViewerServer.exe")) {
2 + u8::from(non_empty_file(
&candidate.join("MicrosoftEdgeWebview2Setup.exe"),
))
} else {
// A launcher alone can be left behind by an interrupted installer.
0
}
}
fn non_empty_file(path: &Path) -> bool {
std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
} }
fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf> { fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf> {
@@ -282,7 +514,11 @@ fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf>
let entries = std::fs::read_dir(start).ok()?; let entries = std::fs::read_dir(start).ok()?;
for entry in entries.flatten() { for entry in entries.flatten() {
let path = entry.path(); let path = entry.path();
if path.is_file() && path.file_name().map(|n| n == needle).unwrap_or(false) { if path.is_file()
&& path
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case(needle))
{
return Some(path); return Some(path);
} }
if path.is_dir() { if path.is_dir() {
@@ -324,8 +560,11 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
}; };
let mut icon_name = String::new(); let mut icon_name = String::new();
let home = std::env::var("HOME").unwrap_or_default(); let data_home = crate::config::data_dir()?
let icons = PathBuf::from(home).join(".local/share/icons"); .parent()
.context("no data home")?
.to_path_buf();
let icons = data_home.join("icons");
let mut best = 0u32; let mut best = 0u32;
if let Ok(sizes) = fs::read_dir(icons.join("hicolor")) { if let Ok(sizes) = fs::read_dir(icons.join("hicolor")) {
for size in sizes.flatten() { for size in sizes.flatten() {
@@ -349,9 +588,7 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
} }
} }
let applications = std::env::var("HOME") let applications = data_home.join("applications");
.map(|h| PathBuf::from(h).join(".local/share/applications"))
.context("no home")?;
std::fs::create_dir_all(&applications)?; std::fs::create_dir_all(&applications)?;
let entry = applications.join(format!("{name}.desktop")); let entry = applications.join(format!("{name}.desktop"));
let exec = uur_bin.display(); let exec = uur_bin.display();
@@ -372,7 +609,9 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
{icon_line}Terminal=false\n\ {icon_line}Terminal=false\n\
NoDisplay=true\n\ NoDisplay=true\n\
X-UUR-Managed=true\n\ X-UUR-Managed=true\n\
Categories=Network;RemoteAccess;\n" X-UUR-Prefix={}\n\
Categories=Network;RemoteAccess;\n",
prefix.display()
), ),
) )
.with_context(|| format!("writing {}", entry.display()))?; .with_context(|| format!("writing {}", entry.display()))?;
@@ -422,7 +661,177 @@ fn purge_wine_shortcuts() {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::find_client_dir;
use super::log_pixels_command;
use super::registry_compat_entries; use super::registry_compat_entries;
use super::service_image_path;
use std::path::Path;
use std::path::PathBuf;
/// Scratch prefix with a real NetEase directory layout, removed on drop.
struct TestPrefix(PathBuf);
impl TestPrefix {
fn create() -> Self {
let path = std::env::temp_dir().join(format!(
"uur-client-dir-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
/// Create `<prefix>/drive_c/Program Files/Netease/GameViewer/<rel>`.
fn write_client_file(&self, rel: &str, contents: &[u8]) {
let path = self
.0
.join("drive_c/Program Files/Netease/GameViewer")
.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, contents).unwrap();
}
}
impl Drop for TestPrefix {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Populate both payload copies NetEase installs. The buggy search
/// returned `<version>/` whenever readdir reached it first, which then
/// failed every `join("bin")` lookup.
fn install_both_layouts(prefix: &TestPrefix) {
for relative in [
"GameViewer.exe",
"GameViewerServer.exe",
"bin/GameViewer.exe",
"bin/GameViewerServer.exe",
"4.42.0.2770/GameViewer.exe",
"4.42.0.2770/GameViewerServer.exe",
] {
prefix.write_client_file(relative, b"payload");
}
}
#[test]
fn client_root_is_the_directory_holding_bin_not_the_version_directory() {
let prefix = TestPrefix::create();
install_both_layouts(&prefix);
let root = find_client_dir(prefix.path()).expect("client root");
assert!(
root.join("bin").join("GameViewerServer.exe").is_file(),
"the returned root must contain bin/GameViewerServer.exe, got {}",
root.display()
);
assert!(
!root.file_name().is_some_and(|name| name == "4.42.0.2770"),
"the version directory must not be selected, got {}",
root.display()
);
}
#[test]
fn client_root_is_stable_regardless_of_readdir_order() {
let prefix = TestPrefix::create();
install_both_layouts(&prefix);
let expected = find_client_dir(prefix.path()).unwrap();
// Repeated lookups must not alternate between the two payload copies.
for _ in 0..16 {
assert_eq!(find_client_dir(prefix.path()).as_ref(), Some(&expected));
}
}
#[test]
fn bin_layout_outranks_a_versioned_payload_copy() {
let prefix = TestPrefix::create();
// The versioned copy has the launcher and server at its top level,
// but no bin/; the real root has the payload in bin/.
prefix.write_client_file("GameViewer.exe", b"payload");
prefix.write_client_file("4.42.0.2770/GameViewer.exe", b"payload");
prefix.write_client_file("4.42.0.2770/GameViewerServer.exe", b"payload");
prefix.write_client_file("bin/GameViewerServer.exe", b"payload");
let root = find_client_dir(prefix.path()).expect("client root");
assert!(
root.join("bin").join("GameViewerServer.exe").is_file(),
"the bin layout must win, got {}",
root.display()
);
assert!(
!root.file_name().is_some_and(|name| name == "4.42.0.2770"),
"the version directory must not win, got {}",
root.display()
);
}
#[test]
fn versioned_copy_is_used_only_when_it_is_the_only_candidate() {
let prefix = TestPrefix::create();
prefix.write_client_file("4.42.0.2770/GameViewer.exe", b"payload");
prefix.write_client_file("4.42.0.2770/GameViewerServer.exe", b"payload");
let root = find_client_dir(prefix.path()).expect("client root");
assert!(root.ends_with("4.42.0.2770"), "got {}", root.display());
assert_eq!(super::client_payload_dir(&root), root);
}
#[test]
fn missing_client_reports_none() {
let prefix = TestPrefix::create();
std::fs::create_dir_all(prefix.path().join("drive_c/Program Files/Netease")).unwrap();
assert!(find_client_dir(prefix.path()).is_none());
prefix.write_client_file("GameViewer.exe", b"payload");
prefix.write_client_file("bin/MicrosoftEdgeWebview2Setup.exe", b"payload");
assert!(find_client_dir(prefix.path()).is_none());
}
/// Real `system.reg` excerpt written by the NetEase installer, escaped
/// exactly as Wine stores it. The service ImagePath names
/// GameViewerService.exe, not GameViewerServer.exe.
const INSTALLED_SYSTEM_REG: &str = concat!(
"[System\\\\ControlSet001\\\\Services\\\\GameViewerService] 1791878366\n",
"#time=1dd5ae8c44b323c\n",
"\"DependOnService\"=str(7):\"RpcSs\\0Tcpip\\0NDIS\\0AFD\\0\"\n",
"\"DisplayName\"=\"GameViewerService\"\n",
"\"ImagePath\"=str(2):\"\\\"C:\\\\Program Files\\\\Netease\\\\GameViewer",
"\\\\GameViewerService.exe\\\" --service\"\n",
"\"ObjectName\"=\"LocalSystem\"\n",
"\"Start\"=dword:00000002\n",
);
#[test]
fn service_registration_matches_the_image_the_installer_registers() {
// Regression: the check looked for gameviewerserver.exe, which never
// appears in the service ImagePath, so a complete install was always
// reported as missing and `uur setup` reinstalled on every run.
let image = service_image_path(INSTALLED_SYSTEM_REG).expect("ImagePath parsed");
assert!(image.contains("gameviewerservice.exe"));
assert!(!image.contains("gameviewerserver.exe"));
}
#[test]
fn missing_service_section_is_not_registered() {
let registry = "[Software\\\\Wine\\\\DllOverrides] 1\n\"winemenubuilder\"=\"\"\n";
assert!(service_image_path(registry).is_none());
}
#[test]
fn service_section_without_image_path_is_not_registered() {
let registry = "[System\\\\ControlSet001\\\\Services\\\\GameViewerService] 1\n\
\"Start\"=dword:00000002\n";
assert!(service_image_path(registry).is_none());
}
#[test] #[test]
fn bundled_cpp_runtime_is_preferred_for_both_uu_processes() { fn bundled_cpp_runtime_is_preferred_for_both_uu_processes() {
@@ -436,4 +845,28 @@ mod tests {
assert!(values.contains(&("msvcp140", "REG_SZ", "native,builtin"))); assert!(values.contains(&("msvcp140", "REG_SZ", "native,builtin")));
} }
} }
#[test]
fn system_dpi_command_writes_winecfg_logpixels_value() {
let command = log_pixels_command(Path::new("/tmp/wine-prefix"), 192).unwrap();
let args = command
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>();
assert_eq!(
args,
[
"reg",
"add",
r"HKCU\Control Panel\Desktop",
"/v",
"LogPixels",
"/t",
"REG_DWORD",
"/d",
"192",
"/f",
]
);
}
} }