14 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
50 changed files with 4203 additions and 532 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 libwayland-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"
+3 -2
View File
@@ -39,7 +39,7 @@ 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 \
binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev libwayland-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 wayland \ 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
Generated
+1 -1
View File
@@ -1487,7 +1487,7 @@ dependencies = [
[[package]] [[package]]
name = "uur" name = "uur"
version = "0.1.5" version = "0.1.7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"ashpd", "ashpd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "uur" name = "uur"
version = "0.1.5" 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"
+5 -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.5-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.5_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.5-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.5-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
``` ```
+5 -4
View File
@@ -66,7 +66,7 @@ uur run
使用 pacman 安装下载的正式发布包: 使用 pacman 安装下载的正式发布包:
```bash ```bash
sudo pacman -U ./dist/uur-0.1.5-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.5_amd64.deb sudo apt install ./uur_0.1.7_amd64.deb
``` ```
### Fedora 及兼容 RPM 发行版 ### Fedora 及兼容 RPM 发行版
```bash ```bash
sudo dnf install ./uur-0.1.5-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.5-1.x86_64.rpm
### 通用压缩包 ### 通用压缩包
```bash ```bash
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst sudo tar --zstd -C / -xf ./uur-0.1.7-linux-x86_64.tar.zst
``` ```
### Nix 与 NixOS ### Nix 与 NixOS
@@ -122,6 +122,7 @@ 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
``` ```
+709 -133
View File
File diff suppressed because it is too large. Load diff
+15 -1
View File
@@ -24,7 +24,9 @@
struct frame_header { struct frame_header {
uint32_t magic, version, width, height, stride, format; uint32_t magic, version, width, height, stride, format;
_Atomic uint64_t total_frames; _Atomic uint64_t total_frames;
uint8_t reserved[32]; 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"); _Static_assert(sizeof(struct frame_header) == UURF_HEADER_BYTES, "frame header ABI");
@@ -136,6 +138,18 @@ static int setup_ring(struct capture *c)
header->width = c->width; header->height = c->height; header->width = c->width; header->height = c->height;
header->stride = c->width * 4; header->format = 1; header->stride = c->width * 4; header->format = 1;
atomic_init(&header->total_frames, 0); 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) { for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) {
_Atomic uint64_t *seq = (_Atomic uint64_t *)((uint8_t *)c->ring + _Atomic uint64_t *seq = (_Atomic uint64_t *)((uint8_t *)c->ring +
UURF_HEADER_BYTES + i * (sizeof(uint64_t) + bytes)); UURF_HEADER_BYTES + i * (sizeof(uint64_t) + bytes));
+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.
+7 -6
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.5-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.5_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.5-1.x86_64.rpm sudo dnf install ./uur-0.1.7-1.x86_64.rpm
# openSUSE # openSUSE
sudo zypper install ./uur-0.1.5-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.5-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,6 +91,7 @@ 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
``` ```
+4 -4
View File
@@ -6,14 +6,14 @@
| 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/PipeWire or explicitly enabled native screencopy → 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 | implemented | StatusNotifierItem + DBusMenu, supervised with the session; no Wine XEmbed dependency | | 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` |
+70 -8
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.5-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.5_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.5-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.5-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.5-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
@@ -179,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
@@ -243,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
+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);
}
} }
+2
View File
@@ -56,6 +56,8 @@ capture:
direct_started: "direct Wayland monitor capture started" 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"
+2
View File
@@ -72,6 +72,8 @@ capture:
direct_started: "已启动原生 Wayland 显示器采集" 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 重新运行以继续。"
+5 -3
View File
@@ -9,6 +9,7 @@
pipewire, pipewire,
wayland, wayland,
wayland-scanner, wayland-scanner,
xorg,
pulseaudio, pulseaudio,
curl, curl,
glib, glib,
@@ -25,7 +26,7 @@ let
in in
rustPlatform.buildRustPackage { rustPlatform.buildRustPackage {
pname = "uur"; pname = "uur";
version = "0.1.5"; version = "0.1.6";
src = lib.cleanSource ../.; src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock; cargoLock.lockFile = ../Cargo.lock;
@@ -38,14 +39,14 @@ rustPlatform.buildRustPackage {
bash bash
wayland-scanner wayland-scanner
]; ];
buildInputs = [ pipewire wayland ]; 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 = ''
@@ -54,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.5 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 wayland-libs-client 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 wayland-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 wayland-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 wayland-libs-client 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' 'wayland' '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'
+2 -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.5 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
@@ -33,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.5.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.5.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
+5 -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.5 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')
@@ -22,9 +22,11 @@ depends=(
'curl' 'curl'
'pipewire' 'pipewire'
'wayland' 'wayland'
'libx11'
'libxext'
'xdg-desktop-portal' 'xdg-desktop-portal'
) )
makedepends=('cargo' 'gcc' 'pkgconf' 'wayland' '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'
@@ -50,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" .
+9 -4
View File
@@ -25,6 +25,8 @@ overrides:
- curl - curl
- libpipewire-0.3-0 - libpipewire-0.3-0
- libwayland-client0 - 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
@@ -36,12 +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)"
- wayland-libs - "libwayland-client.so.0()(64bit)"
- "libX11.so.6()(64bit)"
- "libXext.so.6()(64bit)"
- xdg-desktop-portal - xdg-desktop-portal
recommends: recommends:
- ethtool - ethtool
+2
View File
@@ -12,6 +12,8 @@ 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" \ install -Dm0755 "$project_root/capture/uur-wl-capture" \
"$destination$prefix/lib/uur/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
+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"
+6
View File
@@ -29,11 +29,17 @@ done
printf 'missing capture helper — run: ./capture/build.sh\n' >&2 printf 'missing capture helper — run: ./capture/build.sh\n' >&2
exit 1 exit 1
} }
[[ -f "$root/build/compat/libuur-lock-mods.so" ]] || {
printf 'missing lock-modifier shim — run: ./compat/build.sh\n' >&2
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 uur-wl-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
install -Dm0755 "$root/build/compat/libuur-lock-mods.so" \
"$prefix/lib/uur/libuur-lock-mods.so"
for dll in "${components[@]}"; do 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
+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([
+27 -5
View File
@@ -156,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 {
@@ -199,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> {
+415 -49
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,6 +13,7 @@
//! 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::io::Read;
use std::os::fd::AsRawFd; use std::os::fd::AsRawFd;
use std::os::fd::OwnedFd; use std::os::fd::OwnedFd;
@@ -20,9 +21,32 @@ use std::path::{Path, PathBuf};
use std::process::{Child, Command}; use std::process::{Child, Command};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; 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<()> { pub fn run_standalone() -> Result<()> {
// Public capture uses the same lifecycle lock as run/setup so stop and // Public capture uses the same lifecycle lock as run/setup so stop and
@@ -62,38 +86,188 @@ pub fn run() -> Result<()> {
if config.capture_backend != "portal" { if config.capture_backend != "portal" {
anyhow::bail!("unknown capture backend {:?}", config.capture_backend); anyhow::bail!("unknown capture backend {:?}", config.capture_backend);
} }
let runtime = tokio::runtime::Runtime::new().context("creating capture runtime")?; 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 // The portal's D-Bus connection runs on this runtime. Keep it running
// throughout capture, including on capture-only compositors such as niri. // throughout capture, including on capture-only compositors such as niri.
runtime.block_on(async { runtime.block_on(async {
let (pw_fd, node) = tokio::select! { let frames = frame_path()?;
result = portal_session(&mut config) => result?, let mut failures = 0;
_ = wait_for_stop(&stopping) => return Ok(()), let mut initial_session = true;
}; let mut display_changes = watch_display_changes().await;
println!("{}", t!("capture.session_ready", node = node));
let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?);
loop { 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) { if stopping.load(Ordering::Relaxed) {
return Ok(()); return Ok(());
} }
if let Some(status) = helper.0.try_wait().context("waiting for capture helper")? { // Closed without a matching layout change means Stop sharing.
if !status.success() { // Never silently restore that permission or use direct capture.
anyhow::bail!("{}", t!("capture.helper_failed")); 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"
);
} }
return Ok(()); 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,
}
}
} }
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
} }
}) })
} }
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) { async fn wait_for_stop(stopping: &AtomicBool) {
while !stopping.load(Ordering::Relaxed) { while !stopping.load(Ordering::Relaxed) {
tokio::time::sleep(std::time::Duration::from_millis(50)).await; tokio::time::sleep(std::time::Duration::from_millis(50)).await;
} }
} }
struct CaptureHelper(Child); pub(crate) struct CaptureHelper(pub(crate) Child);
impl Drop for CaptureHelper { impl Drop for CaptureHelper {
fn drop(&mut self) { fn drop(&mut self) {
@@ -124,17 +298,48 @@ pub(crate) fn has_frame(path: &Path) -> bool {
} }
let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap()); let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap());
field(0) == 0x4652_5555 field(0) == 0x4652_5555
&& field(4) == 1 && field(4) == FRAME_PROTOCOL_VERSION
&& field(8) > 0 && field(8) > 0
&& field(12) > 0 && field(12) > 0
&& field(16) >= field(8).saturating_mul(4) && field(16) >= field(8).saturating_mul(4)
&& field(20) == 1 && field(20) == 1
&& (1..=16).contains(&field(36))
&& u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0 && 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).
@@ -151,9 +356,19 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
let helper = find_helper("uur-pw-capture")?; 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);
@@ -164,19 +379,18 @@ 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> {
async 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 screencast = ashpd::desktop::screencast::Screencast::new() let screencast = ashpd::desktop::screencast::Screencast::new()
.await .await
@@ -188,42 +402,141 @@ async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
.clone() .clone()
.map(Some) .map(Some)
.into_iter() .into_iter()
.chain(std::iter::once(None)) .chain(interactive.then_some(None))
{ {
match negotiate(&screencast, source, token.as_deref()).await { match negotiate(
Ok((fd, node, fresh_token)) => { &screencast,
if fresh_token != saved_token { source,
config.capture_restore_token = fresh_token; config.capture_multiple,
config.store().context("storing the new restore token")?; 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")?;
} }
return Ok((fd, node)); return Ok(capture);
} }
Err(error) => { Err(error) => {
if user_cancelled(&error) {
return Err(error);
}
last_error = Some(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,
) )
@@ -232,16 +545,35 @@ async fn negotiate(
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 {
@@ -262,13 +594,7 @@ pub fn list_wayland_outputs() -> Result<()> {
} }
fn find_helper(name: &str) -> Result<PathBuf> { fn find_helper(name: &str) -> Result<PathBuf> {
let mut candidates = vec![ let mut candidates = Vec::new();
PathBuf::from("/usr/lib/uur").join(name),
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));
}
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() {
@@ -277,6 +603,11 @@ fn find_helper(name: &str) -> Result<PathBuf> {
candidates.push(dir.join(name)); candidates.push(dir.join(name));
} }
} }
candidates.push(PathBuf::from("/usr/lib/uur").join(name));
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));
}
if let Ok(cwd) = std::env::current_dir() { if let Ok(cwd) = std::env::current_dir() {
candidates.push(cwd.join("capture").join(name)); candidates.push(cwd.join("capture").join(name));
} }
@@ -288,8 +619,10 @@ fn find_helper(name: &str) -> Result<PathBuf> {
#[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() {
@@ -297,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);
}
} }
+115 -13
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.
@@ -24,10 +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. /// "portal" uses system consent; "wayland" is explicitly enabled direct monitor capture.
pub capture_backend: String, pub capture_backend: String,
/// Named Wayland output for direct capture; a single-output session needs no name. /// Named Wayland output for direct capture; a single-output session needs no name.
pub capture_output: Option<String>, 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 {
@@ -41,8 +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_backend: "portal".into(),
capture_output: None, capture_output: None,
audio_capture_source: None,
strip_lock_mods: Some("auto".into()),
} }
} }
} }
@@ -116,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")
} }
} }
@@ -164,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"));
} }
} }
+37 -2
View File
@@ -247,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(
@@ -347,16 +358,40 @@ pub fn report() -> Result<()> {
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 on_wayland = session_type == "wayland" || std::env::var_os("WAYLAND_DISPLAY").is_some(); let on_wayland = session_type == "wayland" || std::env::var_os("WAYLAND_DISPLAY").is_some();
let configured = crate::config::Config::load()?; let configured = crate::config::Config::load()?;
if std::env::var_os("DISPLAY").is_some() {
match crate::input::xtest::lock_state() {
Ok(state) => line("info", "X11 lock state", &state),
Err(error) => line("WARN", "X11 lock state", &error.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", "capture backend",
&format!( &format!(
"{} ({})", "{} ({}; multiple={})",
configured.capture_backend, configured.capture_backend,
configured configured
.capture_output .capture_output
.as_deref() .as_deref()
.unwrap_or("selected/default output") .unwrap_or("selected/default output"),
configured.capture_multiple
), ),
); );
let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or(configured.input_backend); let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or(configured.input_backend);
+3
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<()>;
+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]
+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"])
+55 -17
View File
@@ -89,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,
@@ -157,7 +162,12 @@ 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. /// Choose portal capture, or explicitly enable direct Wayland monitor capture.
Backend { Backend {
backend: CaptureBackend, backend: CaptureBackend,
@@ -169,6 +179,14 @@ enum DisplayAction {
Outputs, 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)] #[derive(Clone, ValueEnum)]
enum CaptureBackend { enum CaptureBackend {
Portal, Portal,
@@ -207,6 +225,10 @@ fn main() -> Result<()> {
Command::Doctor => doctor::report(), Command::Doctor => doctor::report(),
Command::Pointer => bridge::print_pointer(), Command::Pointer => bridge::print_pointer(),
Command::Capture => capture::run_standalone(), 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 { Command::Uninstall {
@@ -228,29 +250,32 @@ fn main() -> Result<()> {
if matches!(action, DisplayAction::Outputs) { if matches!(action, DisplayAction::Outputs) {
return capture::list_wayland_outputs(); return capture::list_wayland_outputs();
} }
let mut config = config::Config::load()?; 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!("capture backend: {}", config.capture_backend);
println!("multiple monitors: {}", config.capture_multiple);
if let Some(output) = &config.capture_output { if let Some(output) = &config.capture_output {
println!("output: {output}"); println!("output: {output}");
} }
Ok(()) Ok(())
} }
DisplayAction::Backend { backend, output } => { DisplayAction::Backend { backend, output } => {
config.capture_backend = match backend { let backend = match backend {
CaptureBackend::Portal => "portal", CaptureBackend::Portal => "portal",
CaptureBackend::Wayland => "wayland", CaptureBackend::Wayland => "wayland",
} };
.into(); let config = config::Config::update(|stored| {
config.capture_output = output; stored.capture_backend = backend.into();
if config.capture_backend == "wayland" { stored.capture_output = output;
config.capture_source = "monitor".into(); if backend == "wayland" {
} stored.capture_source = "monitor".into();
config.capture_restore_token = None; stored.capture_multiple = false;
config.remote_desktop_restore_token = None; }
config.store()?; stored.capture_restore_token = None;
stored.remote_desktop_restore_token = None;
})?;
println!( println!(
"{}", "{}",
if config.capture_backend == "wayland" { if config.capture_backend == "wayland" {
@@ -262,12 +287,25 @@ fn main() -> Result<()> {
Ok(()) Ok(())
} }
DisplayAction::Outputs => unreachable!(), DisplayAction::Outputs => unreachable!(),
DisplayAction::Source { source } => { DisplayAction::Source { source, multiple } => {
config.capture_source = source.as_str().to_string(); anyhow::ensure!(
config.capture_restore_token = None; !multiple || matches!(&source, DisplaySource::Monitor),
config.remote_desktop_restore_token = None; "--multiple is supported only for monitor sources"
config.store()?; );
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(())
} }
} }
+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([
+445 -133
View File
@@ -45,13 +45,7 @@ fn complete_hook_directory(dir: &Path) -> bool {
} }
fn hook_dir() -> Result<PathBuf> { fn hook_dir() -> Result<PathBuf> {
let mut candidates = vec![ let mut candidates = Vec::new();
PathBuf::from("/usr/lib/uur/hook"),
PathBuf::from("/usr/local/lib/uur/hook"),
];
if let Ok(home) = std::env::var("HOME") {
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
}
if let Ok(exe) = std::env::current_exe() { if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() { if let Some(dir) = exe.parent() {
candidates.push(dir.join("../lib/uur/hook")); candidates.push(dir.join("../lib/uur/hook"));
@@ -59,6 +53,14 @@ fn hook_dir() -> Result<PathBuf> {
candidates.push(dir.to_path_buf()); candidates.push(dir.to_path_buf());
} }
} }
candidates.push(PathBuf::from("/usr/lib/uur/hook"));
candidates.push(PathBuf::from("/usr/local/lib/uur/hook"));
if let Ok(home) = std::env::var("HOME") {
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
}
if let Ok(directory) = std::env::current_dir() {
candidates.push(directory.join("build/hook"));
}
candidates candidates
.into_iter() .into_iter()
.find(|dir| complete_hook_directory(dir)) .find(|dir| complete_hook_directory(dir))
@@ -66,32 +68,94 @@ fn hook_dir() -> Result<PathBuf> {
} }
fn hook_source_dir() -> Result<PathBuf> { fn hook_source_dir() -> Result<PathBuf> {
let mut candidates = vec![PathBuf::from("/usr/lib/uur/hook")]; hook_dir()
if let Ok(home) = std::env::var("HOME") { }
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
/// Path of the lock-modifier shim that is LD_PRELOADed into the managed Wine
/// processes. Layout mirrors the other native helpers (installed under
/// `<prefix>/lib/uur`, found next to the build tree during development).
pub(crate) fn lock_mods_shim() -> Option<PathBuf> {
let mut candidates = Vec::new();
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
candidates.push(dir.join("../lib/uur/libuur-lock-mods.so"));
candidates.push(dir.join("../../build/compat/libuur-lock-mods.so"));
candidates.push(dir.join("libuur-lock-mods.so"));
}
} }
candidates.push( candidates.push(PathBuf::from("/usr/lib/uur/libuur-lock-mods.so"));
std::env::current_exe() candidates.push(PathBuf::from("/usr/local/lib/uur/libuur-lock-mods.so"));
.ok() if let Ok(home) = std::env::var("HOME") {
.and_then(|exe| exe.parent().map(|d| d.join("../lib/uur/hook"))) candidates.push(PathBuf::from(&home).join(".local/lib/uur/libuur-lock-mods.so"));
.unwrap_or_default(), }
); if let Ok(directory) = std::env::current_dir() {
candidates.push( candidates.push(directory.join("build/compat/libuur-lock-mods.so"));
std::env::current_exe() }
.ok() candidates.into_iter().find(|path| path.is_file())
.and_then(|exe| exe.parent().map(|d| d.join("../../build/hook"))) }
.unwrap_or_default(),
); /// Environment for the managed client: keep Wine from forging lock-key
candidates.push( /// events when X11 reports a locked modifier that the client's keyboard hook
std::env::current_dir() /// swallows. See `compat/uur-lock-mods.c` for the full rationale.
.ok() ///
.map(|dir| dir.join("build/hook")) /// This only affects the child process environment; the X server, the
.unwrap_or_default(), /// compositor and the user's NumLock setting are never touched.
); fn lock_mods_mask(config: &Config) -> Result<Option<String>> {
candidates let Some(mask) = config.strip_lock_mods.as_deref().map(str::trim) else {
.into_iter() return Ok(None);
.find(|dir| complete_hook_directory(dir)) };
.context("hook DLLs not found (run the build first)") if mask == "auto" {
return Ok(Some(mask.to_string()));
}
let value = match mask.strip_prefix("0x").or_else(|| mask.strip_prefix("0X")) {
Some(hex) => u8::from_str_radix(hex, 16),
None => mask.parse::<u8>(),
}
.context("strip_lock_mods must be auto, 0, or an 8-bit decimal/hex mask")?;
Ok((value != 0).then(|| format!("0x{value:x}")))
}
pub(crate) fn apply_lock_mods_env(command: &mut Command, config: &Config) -> Result<()> {
apply_lock_mods_with_shim(
command,
config,
lock_mods_shim().as_deref(),
std::env::var_os("LD_PRELOAD").as_deref(),
)
}
fn apply_lock_mods_with_shim(
command: &mut Command,
config: &Config,
shim: Option<&Path>,
existing: Option<&std::ffi::OsStr>,
) -> Result<()> {
let Some(mask) = lock_mods_mask(config)? else {
return Ok(());
};
let Some(shim) = shim else {
eprintln!("lock-modifier shim not found; leaving Wine keyboard handling untouched");
return Ok(());
};
// The dynamic loader splits LD_PRELOAD on ':' and whitespace and offers no
// escaping, so a path containing either cannot be expressed there.
let Some(shim_text) = shim.to_str() else {
eprintln!("lock-modifier shim path must be valid UTF-8; skipping it");
return Ok(());
};
if shim_text.contains(':') || shim_text.chars().any(|ch| ch.is_ascii_whitespace()) {
eprintln!("lock-modifier shim path cannot be expressed in LD_PRELOAD; skipping it");
return Ok(());
}
let mut preload = shim.as_os_str().to_os_string();
if let Some(existing) = existing.filter(|value| !value.is_empty()) {
preload.push(":");
preload.push(existing);
}
command
.env("UUR_STRIP_LOCK_MODS", mask)
.env("LD_PRELOAD", preload);
Ok(())
} }
static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
@@ -181,7 +245,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
let source_dir = hook_source_dir()?; let source_dir = hook_source_dir()?;
let source = source_dir.join("uur-terminal-proxy.exe"); let source = source_dir.join("uur-terminal-proxy.exe");
let mux_source = source_dir.join("uur-mux-proxy.exe"); let mux_source = source_dir.join("uur-mux-proxy.exe");
let bin = install_dir.join("bin"); let bin = crate::wine::client_payload_dir(install_dir);
std::fs::create_dir_all(&bin)?; std::fs::create_dir_all(&bin)?;
for status in ["uur-terminal-adapter.status", "uur-mux-adapter.status"] { for status in ["uur-terminal-adapter.status", "uur-mux-adapter.status"] {
let _ = std::fs::remove_file(bin.join(status)); let _ = std::fs::remove_file(bin.join(status));
@@ -236,8 +300,8 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
/// bootstrapper ships inside the client's bin directory. /// bootstrapper ships inside the client's bin directory.
const WEBVIEW2_DLL_OVERRIDES: &str = "wtsapi32=b,wevtapi=b"; const WEBVIEW2_DLL_OVERRIDES: &str = "wtsapi32=b,wevtapi=b";
fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command { fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Result<Command> {
let mut command = Command::new("wine"); let mut command = crate::wine::command(prefix)?;
command command
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
@@ -247,21 +311,20 @@ fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command {
.env("WINEDLLOVERRIDES", WEBVIEW2_DLL_OVERRIDES) .env("WINEDLLOVERRIDES", WEBVIEW2_DLL_OVERRIDES)
.arg(bootstrapper) .arg(bootstrapper)
.args(["/silent", "/install"]); .args(["/silent", "/install"]);
command Ok(command)
} }
fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> { fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
if crate::wine::webview2_installed(prefix) { if crate::wine::webview2_installed(prefix) {
return Ok(()); return Ok(());
} }
let bootstrapper = install_dir let bootstrapper =
.join("bin") crate::wine::client_payload_dir(install_dir).join("MicrosoftEdgeWebview2Setup.exe");
.join("MicrosoftEdgeWebview2Setup.exe");
if !bootstrapper.is_file() { if !bootstrapper.is_file() {
anyhow::bail!("{}", t!("session.webview_missing")); anyhow::bail!("{}", t!("session.webview_missing"));
} }
println!("{}", t!("session.installing_webview")); println!("{}", t!("session.installing_webview"));
let status = webview2_install_command(prefix, &bootstrapper) let status = webview2_install_command(prefix, &bootstrapper)?
.status() .status()
.context("running the WebView2 bootstrapper")?; .context("running the WebView2 bootstrapper")?;
if !status.success() || !crate::wine::webview2_installed(prefix) { if !status.success() || !crate::wine::webview2_installed(prefix) {
@@ -408,7 +471,7 @@ impl SessionResources {
for helper in &mut self.helpers { for helper in &mut self.helpers {
if matches!( if matches!(
helper.name.as_str(), helper.name.as_str(),
"__bridge" | "__capture" | "__terminal" | "__launcher" "__bridge" | "__capture" | "__terminal" | "__launcher" | "winlogon"
) { ) {
helper.ensure_running()?; helper.ensure_running()?;
} }
@@ -428,6 +491,7 @@ pub fn start() -> Result<()> {
let _session_lock = acquire_session_lock()?; let _session_lock = acquire_session_lock()?;
rotate_session_log(); rotate_session_log();
let config = Config::load()?; let config = Config::load()?;
let _ = lock_mods_mask(&config)?;
let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland"); || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland");
let prefix = data_dir()?.join("wine"); let prefix = data_dir()?.join("wine");
@@ -437,6 +501,15 @@ pub fn start() -> Result<()> {
anyhow::bail!("{}", t!("setup.service_incomplete")); anyhow::bail!("{}", t!("setup.service_incomplete"));
} }
let mut resources = SessionResources::new(prefix.clone()); let mut resources = SessionResources::new(prefix.clone());
let selected_audio = crate::audio::capture_source(config.audio_capture_source.as_deref())?;
if selected_audio.is_some()
|| (lock_mods_mask(&config)?.is_some() && lock_mods_shim().is_some())
{
// A server left by setup or an older client has the old environment.
// The session lock excludes a running uur session; restart only this
// managed prefix so its SCM-spawned clients inherit the same shim.
stop_wineserver(&prefix);
}
if let Some(dpi) = xft_dpi() { if let Some(dpi) = xft_dpi() {
match crate::wine::set_log_pixels(&prefix, dpi) { match crate::wine::set_log_pixels(&prefix, dpi) {
Ok(()) => println!("{}", t!("session.wine_dpi", dpi = dpi)), Ok(()) => println!("{}", t!("session.wine_dpi", dpi = dpi)),
@@ -552,32 +625,46 @@ pub fn start() -> Result<()> {
// The service enumerates processes for a winlogon session token source // The service enumerates processes for a winlogon session token source
// before it initialises; under plain Wine none exists. A sleeping // before it initialises; under plain Wine none exists. A sleeping
// process with that name satisfies the check. // process with that name satisfies the check. It also monitors the
// Windows process table without repeatedly initializing Wine utilities.
use std::os::unix::process::CommandExt;
let marker = hook_dir()?.join("winlogon.exe"); let marker = hook_dir()?.join("winlogon.exe");
let _ = Command::new("wine") let mut monitor = crate::wine::command(&prefix)?
.env("WINEPREFIX", &prefix) .env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n") .env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
.env("UUR_HOOK_LOG", log_path()?) .env("UUR_MONITOR_CLIENT", "GameViewer.exe")
.env("UUR_BRIDGE_PORT", config.bridge_port.to_string()) .stdin(Stdio::null())
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone()) .stdout(Stdio::piped())
.stdout(Stdio::from(log.try_clone()?))
.stderr(Stdio::from(log.try_clone()?)) .stderr(Stdio::from(log.try_clone()?))
.arg(marker.to_string_lossy().as_ref()) .process_group(0)
.spawn(); .arg(marker)
.spawn()
.context("starting the Windows session monitor")?;
let monitor_output = monitor
.stdout
.take()
.context("missing session monitor pipe")?;
resources.helpers.push(ManagedChild {
child: monitor,
name: "winlogon".to_string(),
terminated: false,
});
let mut client_monitor = ClientMonitor::new(monitor_output)?;
// The launcher talks to the service through the Windows Service Control // The launcher talks to the service through the Windows Service Control
// Manager, so the service must be started through `sc start` — a // Manager, so the service must be started through `sc start` — a
// directly spawned --service process is invisible to it and the UI // directly spawned --service process is invisible to it and the UI
// waits forever. // waits forever.
if !service_running(&prefix) { if !service_running(&prefix) {
let _ = Command::new("wine") let _ = run_with_timeout(
.env("WINEPREFIX", &prefix) crate::wine::command(&prefix)?
.env("WINEDEBUG", wine_debug()) .env("WINEPREFIX", &prefix)
.stdout(Stdio::from(log.try_clone()?)) .env("WINEDEBUG", wine_debug())
.stderr(Stdio::from(log.try_clone()?)) .env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
.args(["sc", "start", "GameViewerService"]) .args([r"C:\windows\system32\sc.exe", "start", "GameViewerService"]),
.status(); std::time::Duration::from_secs(5),
);
} }
let service_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); let service_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !service_running(&prefix) { while !service_running(&prefix) {
@@ -595,7 +682,8 @@ pub fn start() -> Result<()> {
println!("{}", t!("session.launching_client")); println!("{}", t!("session.launching_client"));
let ui = install_dir.join("GameViewer.exe"); let ui = install_dir.join("GameViewer.exe");
let launch = || -> Result<Child> { let launch = || -> Result<Child> {
Command::new("wine") let mut command = crate::wine::command(&prefix)?;
command
.env("WINEPREFIX", &prefix) .env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.current_dir(&install_dir) .current_dir(&install_dir)
@@ -605,9 +693,8 @@ pub fn start() -> Result<()> {
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone()) .env("UUR_BRIDGE_TOKEN", config.bridge_token.clone())
.stdout(Stdio::from(log.try_clone()?)) .stdout(Stdio::from(log.try_clone()?))
.stderr(Stdio::from(log.try_clone()?)) .stderr(Stdio::from(log.try_clone()?))
.arg(ui.to_string_lossy().as_ref()) .arg(ui.to_string_lossy().as_ref());
.spawn() command.spawn().context("launching the managed client")
.context("launching the managed client")
}; };
// Start the client detached: it IS the session's lifetime anchor. // Start the client detached: it IS the session's lifetime anchor.
@@ -618,17 +705,18 @@ pub fn start() -> Result<()> {
let mut relaunches = 0; let mut relaunches = 0;
while !stopping.load(Ordering::Relaxed) { while !stopping.load(Ordering::Relaxed) {
resources.check_required_helpers()?; resources.check_required_helpers()?;
let running = wine_client_process_exists(&prefix); if let Some(running) = client_monitor.poll()? {
if running { if running {
seen_client = true; seen_client = true;
missing_checks = 0; missing_checks = 0;
} else if seen_client { } else if seen_client {
missing_checks = missing_checks.saturating_add(1); missing_checks = missing_checks.saturating_add(1);
// UU hands off between short-lived launchers and its real Qt // UU hands off between short-lived launchers and its real Qt
// process. Require a sustained absence before treating it as a // process. Require a sustained absence before treating it as a
// user-requested exit. // user-requested exit.
if missing_checks >= 6 { if missing_checks >= 6 {
break; break;
}
} }
} }
if !seen_client && std::time::Instant::now() >= deadline { if !seen_client && std::time::Instant::now() >= deadline {
@@ -648,26 +736,68 @@ pub fn start() -> Result<()> {
Ok(()) Ok(())
} }
/// Query the Windows process table belonging to this exact Wine prefix. /// Read fresh process-table observations from this prefix's persistent marker.
/// Modern Wine may host a Windows process in a Linux process whose `/proc` /// Modern Wine may host a Windows process in a Linux process whose `/proc`
/// cmdline names another image, so Linux process-name matching is not a valid /// cmdline names another image, so Linux process-name matching is not a valid
/// lifecycle boundary. /// lifecycle boundary. A failed query never means that the client exited.
fn wine_client_process_exists(prefix: &Path) -> bool { struct ClientMonitor {
let output = run_with_timeout( output: std::process::ChildStdout,
Command::new("wine") last_response: std::time::Instant,
.env("WINEPREFIX", prefix) }
.env("WINEDEBUG", wine_debug())
.args([ impl ClientMonitor {
"tasklist", fn new(output: std::process::ChildStdout) -> Result<Self> {
"/NH", set_nonblocking(&output)?;
"/FO", Ok(Self {
"CSV", output,
"/FI", last_response: std::time::Instant::now(),
"IMAGENAME eq GameViewer.exe", })
]), }
std::time::Duration::from_secs(5),
); fn poll(&mut self) -> Result<Option<bool>> {
output.is_some_and(|text| tasklist_contains_image(&text, "GameViewer.exe")) let mut latest = None;
let mut buffer = [0; 64];
loop {
match self.output.read(&mut buffer) {
Ok(0) => anyhow::bail!("Windows session monitor disconnected"),
Ok(count) => {
for state in &buffer[..count] {
latest = monitor_observation(*state)?;
if latest.is_some() {
self.last_response = std::time::Instant::now();
}
}
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error).context("reading Windows session monitor"),
}
}
if self.last_response.elapsed() > std::time::Duration::from_secs(15) {
anyhow::bail!(
"Windows session monitor did not provide a valid observation for 15 seconds"
);
}
Ok(latest)
}
}
fn monitor_observation(state: u8) -> Result<Option<bool>> {
match state {
b'1' => Ok(Some(true)),
b'0' => Ok(Some(false)),
b'?' => Ok(None),
_ => anyhow::bail!("invalid Windows session monitor response"),
}
}
fn set_nonblocking(pipe: &impl std::os::fd::AsRawFd) -> std::io::Result<()> {
let fd = pipe.as_raw_fd();
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
} }
/// Run a command with a hard timeout, returning its stdout (None on /// Run a command with a hard timeout, returning its stdout (None on
@@ -678,39 +808,62 @@ fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Opti
use std::process::Stdio; use std::process::Stdio;
let mut child = command let mut child = command
.stdin(Stdio::null())
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::null()) .stderr(Stdio::null())
.spawn() .spawn()
.ok()?; .ok()?;
let mut pipe = child.stdout.take()?;
if set_nonblocking(&pipe).is_err() {
let _ = child.kill();
let _ = child.wait();
return None;
}
let mut stdout = Vec::new();
let deadline = std::time::Instant::now() + timeout; let deadline = std::time::Instant::now() + timeout;
loop { loop {
match child.try_wait() { // Check exit before draining, so the command's final output is not
Ok(Some(_)) => break, // lost in a wait/read race. Never wait for EOF: Wine descendants can
Ok(None) => { // retain this pipe after the utility itself has exited.
if std::time::Instant::now() >= deadline { let status = child.try_wait();
let _ = child.kill(); let read = pipe
let _ = child.wait(); .by_ref()
return None; .take(65537 - stdout.len() as u64)
} .read_to_end(&mut stdout);
let read_failed = read.is_err_and(|error| {
!matches!(
error.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
)
});
if !read_failed && stdout.len() <= 65536 {
if let Ok(Some(status)) = status {
return status
.success()
.then(|| String::from_utf8_lossy(&stdout).into_owned());
}
if status.is_ok() && std::time::Instant::now() < deadline {
thread::sleep(std::time::Duration::from_millis(50));
continue;
} }
Err(_) => return None,
} }
thread::sleep(std::time::Duration::from_millis(50)); let _ = child.kill();
let _ = child.wait();
return None;
} }
let mut stdout = String::new();
if let Some(mut pipe) = child.stdout.take() {
let _ = pipe.read_to_string(&mut stdout);
}
Some(stdout)
} }
/// True when the Windows service reports STATE 4 (RUNNING) via `sc query`. /// True when the Windows service reports STATE 4 (RUNNING) via `sc query`.
fn service_running(prefix: &Path) -> bool { fn service_running(prefix: &Path) -> bool {
let Ok(mut command) = crate::wine::command(prefix) else {
return false;
};
let output = run_with_timeout( let output = run_with_timeout(
Command::new("wine") command
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.args(["sc", "query", "GameViewerService"]), .env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
.args([r"C:\windows\system32\sc.exe", "query", "GameViewerService"]),
std::time::Duration::from_secs(3), std::time::Duration::from_secs(3),
); );
match output { match output {
@@ -722,15 +875,6 @@ fn service_running(prefix: &Path) -> bool {
} }
} }
fn tasklist_contains_image(output: &str, image: &str) -> bool {
output.lines().any(|line| {
line.split(',')
.next()
.map(|field| field.trim().trim_matches('"').eq_ignore_ascii_case(image))
.unwrap_or(false)
})
}
fn log_path() -> Result<PathBuf> { fn log_path() -> Result<PathBuf> {
Ok(data_dir()?.join("hook.log")) Ok(data_dir()?.join("hook.log"))
} }
@@ -773,7 +917,8 @@ pub(crate) fn show_client() -> Result<()> {
if process_start_time(pid).ok() != Some(start) { if process_start_time(pid).ok() != Some(start) {
anyhow::bail!("managed session is not running"); anyhow::bail!("managed session is not running");
} }
let mut child = Command::new("wine") let mut command = crate::wine::command(&prefix)?;
command
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n") .env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
@@ -781,9 +926,8 @@ pub(crate) fn show_client() -> Result<()> {
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::null()) .stdout(Stdio::null())
.stderr(Stdio::null()) .stderr(Stdio::null())
.arg(install.join("GameViewer.exe")) .arg(install.join("GameViewer.exe"));
.spawn() let mut child = command.spawn().context("showing the managed client")?;
.context("showing the managed client")?;
thread::spawn(move || { thread::spawn(move || {
let _ = child.wait(); let _ = child.wait();
}); });
@@ -835,7 +979,7 @@ fn process_start_time(pid: u32) -> Result<u64> {
} }
fn frame_path() -> Result<PathBuf> { fn frame_path() -> Result<PathBuf> {
Ok(crate::config::runtime_dir()?.join("frames.v1")) Ok(crate::config::runtime_dir()?.join("frames.v3"))
} }
fn unix_path_to_wine(path: &Path) -> String { fn unix_path_to_wine(path: &Path) -> String {
@@ -925,10 +1069,110 @@ fn parse_xft_dpi(resources: &str) -> Option<u32> {
} }
fn stop_wineserver(prefix: &Path) { fn stop_wineserver(prefix: &Path) {
let _ = Command::new("wineserver") // Capture handles before Wine's shutdown: a WebView2 thread-group leader
.env("WINEPREFIX", prefix) // can exit while its other threads retain the address space and pipes.
.arg("-k") let mut remaining = remaining_wine_processes(prefix);
.status(); let _ = run_with_timeout(
Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-k"),
std::time::Duration::from_secs(2),
);
// WebView2 workers can outlive their wineserver, blocked on inherited
// pipes. Bind a pidfd before checking identity: PID reuse must never turn
// cleanup of this managed prefix into a signal to an unrelated process.
remaining.extend(remaining_wine_processes(prefix));
for process in &remaining {
signal_process(process, libc::SIGTERM);
}
if !remaining.is_empty() {
thread::sleep(std::time::Duration::from_millis(250));
for process in &remaining {
signal_process(process, libc::SIGKILL);
}
}
}
fn remaining_wine_processes(prefix: &Path) -> Vec<std::os::fd::OwnedFd> {
use std::os::fd::FromRawFd;
let Ok(prefix) = std::fs::canonicalize(prefix) else {
return Vec::new();
};
let Ok(entries) = std::fs::read_dir("/proc") else {
return Vec::new();
};
let mut processes = Vec::new();
for entry in entries.flatten() {
let Some(pid) = entry
.file_name()
.to_str()
.and_then(|name| name.parse::<u32>().ok())
else {
continue;
};
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) } as i32;
if fd < 0 {
continue;
}
let process = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) };
let directory = entry.path();
let belongs_to_prefix = wine_process_matches(&directory, &prefix)
|| (std::fs::read_link(directory.join("exe")).is_err()
&& std::fs::read_dir(directory.join("task")).is_ok_and(|tasks| {
tasks
.flatten()
.any(|task| wine_process_matches(&task.path(), &prefix))
}));
if belongs_to_prefix {
processes.push(process);
}
}
processes
}
fn wine_process_matches(directory: &Path, prefix: &Path) -> bool {
use std::os::unix::ffi::OsStrExt;
let Ok(executable) = std::fs::read_link(directory.join("exe")) else {
return false;
};
let name = executable
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default();
let name = name.strip_suffix(" (deleted)").unwrap_or(name);
let name = name.strip_prefix('.').unwrap_or(name);
let name = name.strip_suffix("-wrapped").unwrap_or(name);
if !matches!(
name,
"wine" | "wine64" | "wine-preloader" | "wine64-preloader" | "wineserver"
) {
return false;
}
let Ok(environment) = std::fs::read(directory.join("environ")) else {
return false;
};
environment.split(|byte| *byte == 0).any(|variable| {
variable.strip_prefix(b"WINEPREFIX=").is_some_and(|value| {
let path = Path::new(std::ffi::OsStr::from_bytes(value));
path.is_absolute() && std::fs::canonicalize(path).is_ok_and(|path| path == prefix)
})
})
}
fn signal_process(process: &std::os::fd::OwnedFd, signal: i32) {
use std::os::fd::AsRawFd;
unsafe {
libc::syscall(
libc::SYS_pidfd_send_signal,
process.as_raw_fd(),
signal,
std::ptr::null::<libc::siginfo_t>(),
0,
);
}
} }
fn wine_debug() -> String { fn wine_debug() -> String {
@@ -972,6 +1216,73 @@ mod tests {
} }
} }
fn command_env(command: &Command, key: &str) -> Option<String> {
command
.get_envs()
.find(|(name, _)| *name == OsStr::new(key))
.and_then(|(_, value)| value)
.map(|value| value.to_string_lossy().into_owned())
}
#[test]
fn lock_modifier_env_is_skipped_when_disabled() {
for mask in [None, Some("0".to_string()), Some("0x00".to_string())] {
let config = Config {
strip_lock_mods: mask,
..Config::default()
};
let mut command = Command::new("wine");
apply_lock_mods_with_shim(&mut command, &config, Some(Path::new("/shim.so")), None)
.unwrap();
assert!(command_env(&command, "LD_PRELOAD").is_none());
assert!(command_env(&command, "UUR_STRIP_LOCK_MODS").is_none());
}
}
#[test]
fn lock_modifier_env_sets_mask_and_preloads_shim() {
let config = Config {
strip_lock_mods: Some("0x50".into()),
..Config::default()
};
let mut command = Command::new("wine");
apply_lock_mods_with_shim(
&mut command,
&config,
Some(Path::new("/build/compat/libuur-lock-mods.so")),
Some(OsStr::new("/nonexistent/first.so")),
)
.unwrap();
assert_eq!(
command_env(&command, "UUR_STRIP_LOCK_MODS").as_deref(),
Some("0x50")
);
let preload = command_env(&command, "LD_PRELOAD").expect("preload set");
assert!(preload.ends_with("/build/compat/libuur-lock-mods.so:/nonexistent/first.so"));
}
#[test]
fn lock_modifier_env_reports_missing_shim_without_failing() {
let config = Config::default();
let mut command = Command::new("wine");
apply_lock_mods_with_shim(&mut command, &config, None, None).unwrap();
let mask = command_env(&command, "UUR_STRIP_LOCK_MODS");
let preload = command_env(&command, "LD_PRELOAD");
assert_eq!(mask.is_some(), preload.is_some());
assert!(mask.is_none());
for path in [
"/bad path/shim.so",
"/bad\npath/shim.so",
"/bad:path/shim.so",
] {
let mut command = Command::new("wine");
apply_lock_mods_with_shim(&mut command, &config, Some(Path::new(path)), None).unwrap();
assert!(command_env(&command, "LD_PRELOAD").is_none());
assert!(command_env(&command, "UUR_STRIP_LOCK_MODS").is_none());
}
}
#[test] #[test]
fn deploy_file_repairs_readonly_targets_and_is_repeatable() { fn deploy_file_repairs_readonly_targets_and_is_repeatable() {
let directory = TestDirectory::create(); let directory = TestDirectory::create();
@@ -1041,7 +1352,8 @@ mod tests {
let command = webview2_install_command( let command = webview2_install_command(
Path::new("/tmp/uur-wine-prefix"), Path::new("/tmp/uur-wine-prefix"),
Path::new("/tmp/MicrosoftEdgeWebview2Setup.exe"), Path::new("/tmp/MicrosoftEdgeWebview2Setup.exe"),
); )
.unwrap();
let overrides = command let overrides = command
.get_envs() .get_envs()
.find_map(|(name, value)| (name == OsStr::new("WINEDLLOVERRIDES")).then_some(value)) .find_map(|(name, value)| (name == OsStr::new("WINEDLLOVERRIDES")).then_some(value))
@@ -1050,11 +1362,11 @@ mod tests {
} }
#[test] #[test]
fn tasklist_parser_matches_the_exact_image() { fn monitor_parser_distinguishes_absence_and_query_failure() {
let output = "\"GameViewer.exe\",\"456\",\"Console\",\"1\"\n\ assert_eq!(monitor_observation(b'1').unwrap(), Some(true));
\"GameViewerServer.exe\",\"464\",\"Console\",\"1\"\n"; assert_eq!(monitor_observation(b'0').unwrap(), Some(false));
assert!(tasklist_contains_image(output, "GameViewer.exe")); assert_eq!(monitor_observation(b'?').unwrap(), None);
assert!(!tasklist_contains_image(output, "GameViewerService.exe")); assert!(monitor_observation(b'X').is_err());
} }
#[test] #[test]
@@ -1065,8 +1377,8 @@ mod tests {
#[test] #[test]
fn runtime_path_converts_to_a_wine_z_path() { fn runtime_path_converts_to_a_wine_z_path() {
assert_eq!( assert_eq!(
unix_path_to_wine(Path::new("/run/user/1000/uur/frames.v1")), unix_path_to_wine(Path::new("/run/user/1000/uur/frames.v3")),
r"Z:\run\user\1000\uur\frames.v1" r"Z:\run\user\1000\uur\frames.v3"
); );
} }
} }
+1
View File
@@ -254,6 +254,7 @@ impl Plan {
"lib/uur/user-install", "lib/uur/user-install",
"lib/uur/uur-pw-capture", "lib/uur/uur-pw-capture",
"lib/uur/uur-wl-capture", "lib/uur/uur-wl-capture",
"lib/uur/libuur-lock-mods.so",
"lib/uur/hook/wevtapi.dll", "lib/uur/hook/wevtapi.dll",
"lib/uur/hook/uur-hook.dll", "lib/uur/hook/uur-hook.dll",
"lib/uur/hook/wtsapi32.dll", "lib/uur/hook/wtsapi32.dll",
+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([
+1 -1
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([
+354 -40
View File
@@ -1,6 +1,7 @@
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;
@@ -8,6 +9,22 @@ const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/
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"; 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); struct SetupPrefix(PathBuf);
impl Drop for SetupPrefix { impl Drop for SetupPrefix {
@@ -59,9 +76,10 @@ pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
.arg(if repair { "--update" } else { "--init" }) .arg(if repair { "--update" } else { "--init" })
.status() .status()
.context("running wineboot")?; .context("running wineboot")?;
if !status.success() || !prefix_initialized(&prefix) { if !status.success() {
anyhow::bail!("{}", t!("setup.prefix_failed", status = status)); 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)? { if find_client_dir(&prefix).is_some() && query_client_service(&prefix)? {
finish_setup(&prefix)?; finish_setup(&prefix)?;
@@ -88,7 +106,7 @@ pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
} }
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) .env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
@@ -136,12 +154,16 @@ pub fn webview2_installed(prefix: &Path) -> bool {
.is_some_and(|path| std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0)) .is_some_and(|path| std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0))
} }
/// Read the persisted Wine service registration without starting Wine or /// The Windows service NetEase's installer registers points at
/// showing component installers from `uur doctor`. /// `GameViewerService.exe`. `GameViewerServer.exe` is a different program —
pub fn client_service_registered(prefix: &Path) -> bool { /// the streaming/terminal server — and never appears in the service
let Ok(registry) = std::fs::read_to_string(prefix.join("system.reg")) else { /// ImagePath, so matching on it made every provisioning check fail and left
return false; /// `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; let mut service_section = false;
for line in registry.lines() { for line in registry.lines() {
if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) { if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) {
@@ -149,15 +171,26 @@ pub fn client_service_registered(prefix: &Path) -> bool {
.0 .0
.to_ascii_lowercase() .to_ascii_lowercase()
.ends_with(r"\\services\\gameviewerservice"); .ends_with(r"\\services\\gameviewerservice");
} else if service_section && line.starts_with("\"ImagePath\"=") { } else if service_section {
return line.to_ascii_lowercase().contains("gameviewerserver.exe"); if let Some(value) = line.trim_start().strip_prefix("\"ImagePath\"=") {
return Some(value.to_ascii_lowercase());
}
} }
} }
false 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> { fn query_client_service(prefix: &Path) -> Result<bool> {
let output = Command::new("wine") let output = command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES) .env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
@@ -171,10 +204,13 @@ fn query_client_service(prefix: &Path) -> Result<bool> {
.stdin(Stdio::null()) .stdin(Stdio::null())
.output() .output()
.context("checking the UU Windows service registration")?; .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() Ok(output.status.success()
&& String::from_utf8_lossy(&output.stdout) && String::from_utf8_lossy(&output.stdout)
.to_ascii_lowercase() .to_ascii_lowercase()
.contains("gameviewerserver.exe")) .contains(SERVICE_IMAGE))
} }
/// Registry compatibility profile, ported from the field-tested reference /// Registry compatibility profile, ported from the field-tested reference
@@ -240,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 status = Command::new("wine") let status = command(prefix)?
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
.args([ .args([
@@ -260,7 +296,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
} }
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([
@@ -287,7 +323,7 @@ pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
} }
pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> { pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
let status = log_pixels_command(prefix, dpi) let status = log_pixels_command(prefix, dpi)?
.status() .status()
.context("setting the Wine system DPI")?; .context("setting the Wine system DPI")?;
if !status.success() { if !status.success() {
@@ -296,8 +332,8 @@ pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
Ok(()) Ok(())
} }
fn log_pixels_command(prefix: &Path, dpi: u32) -> Command { fn log_pixels_command(prefix: &Path, dpi: u32) -> Result<Command> {
let mut command = Command::new("wine"); let mut command = command(prefix)?;
command command
.env("WINEPREFIX", prefix) .env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug()) .env("WINEDEBUG", wine_debug())
@@ -316,7 +352,7 @@ fn log_pixels_command(prefix: &Path, dpi: u32) -> Command {
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::null()) .stdout(Stdio::null())
.stderr(Stdio::null()); .stderr(Stdio::null());
command Ok(command)
} }
fn wine_debug() -> String { fn wine_debug() -> String {
@@ -330,35 +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()?; {
let candidate = if bin continue;
.file_name() }
.is_some_and(|name| name.eq_ignore_ascii_case("bin")) collect_client_roots(&entry.path(), 4, &mut roots);
{ }
bin.parent()?.to_path_buf() roots.retain(|root| client_root_rank(root) > 0);
} else { roots.sort_by(|left, right| {
bin.to_path_buf() client_root_rank(right)
}; .cmp(&client_root_rank(left))
if std::fs::metadata(candidate.join("GameViewer.exe")) .then_with(|| left.components().count().cmp(&right.components().count()))
.is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0) .then_with(|| left.cmp(right))
&& std::fs::metadata(&found).is_ok_and(|metadata| metadata.len() > 0) });
{ roots.dedup();
return Some(candidate); 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());
} }
} }
} }
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> {
@@ -515,9 +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::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::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() {
@@ -534,7 +848,7 @@ mod tests {
#[test] #[test]
fn system_dpi_command_writes_winecfg_logpixels_value() { fn system_dpi_command_writes_winecfg_logpixels_value() {
let command = log_pixels_command(Path::new("/tmp/wine-prefix"), 192); let command = log_pixels_command(Path::new("/tmp/wine-prefix"), 192).unwrap();
let args = command let args = command
.get_args() .get_args()
.map(|arg| arg.to_string_lossy().into_owned()) .map(|arg| arg.to_string_lossy().into_owned())