7 Commits
Author SHA1 Message Date
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
20 changed files with 1345 additions and 285 deletions

No files matched your search

Generated
+1 -1
View File
@@ -1487,7 +1487,7 @@ dependencies = [
[[package]]
name = "uur"
version = "0.1.5"
version = "0.1.6"
dependencies = [
"anyhow",
"ashpd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "uur"
version = "0.1.5"
version = "0.1.6"
edition = "2021"
description = "Native Linux companion for NetEase UU Remote: X11/Wayland input and capture, packaged as a regular desktop app"
license = "MIT"
+4 -4
View File
@@ -69,7 +69,7 @@ recipes and release artifacts share one version and filesystem layout.
Install a downloaded release package with pacman:
```bash
sudo pacman -U ./dist/uur-0.1.5-1-x86_64.pkg.tar.zst
sudo pacman -U ./dist/uur-0.1.6-1-x86_64.pkg.tar.zst
```
### AUR
@@ -83,13 +83,13 @@ paru -S uur
### Debian and Ubuntu package family
```bash
sudo apt install ./uur_0.1.5_amd64.deb
sudo apt install ./uur_0.1.6_amd64.deb
```
### Fedora and compatible RPM systems
```bash
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
```
On systems with different RPM dependency names, install the dependencies
@@ -98,7 +98,7 @@ manually or use the portable archive.
### Portable archive
```bash
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.6-linux-x86_64.tar.zst
```
### Nix and NixOS
+4 -4
View File
@@ -66,7 +66,7 @@ uur run
使用 pacman 安装下载的正式发布包:
```bash
sudo pacman -U ./dist/uur-0.1.5-1-x86_64.pkg.tar.zst
sudo pacman -U ./dist/uur-0.1.6-1-x86_64.pkg.tar.zst
```
### AUR
@@ -80,13 +80,13 @@ paru -S uur
### Debian、Ubuntu 及兼容发行版
```bash
sudo apt install ./uur_0.1.5_amd64.deb
sudo apt install ./uur_0.1.6_amd64.deb
```
### Fedora 及兼容 RPM 发行版
```bash
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
```
如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。
@@ -94,7 +94,7 @@ sudo dnf install ./uur-0.1.5-1.x86_64.rpm
### 通用压缩包
```bash
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.6-linux-x86_64.tar.zst
```
### Nix 与 NixOS
+236 -57
View File
@@ -16,6 +16,8 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/dma-buf.h>
#include <poll.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdint.h>
@@ -23,14 +25,20 @@
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <pipewire/pipewire.h>
#include <spa/param/video/format-utils.h>
#include <drm/drm_fourcc.h>
#include "../hook/frame-protocol.h"
#define FRAME_FORMAT_BGRX 1
#ifndef SPA_CHUNK_FLAG_EMPTY
#define SPA_CHUNK_FLAG_EMPTY (1u << 1)
#endif
struct frame_header {
uint32_t magic;
@@ -63,16 +71,31 @@ struct capture {
int shm_fd;
uint8_t *shm;
size_t shm_size;
int dmabuf_usable;
int exit_status;
volatile sig_atomic_t stopping;
int was_streaming;
uint64_t started_ms;
uint64_t paused_ms;
char frame_path[PATH_MAX];
};
static struct capture *active_capture;
static uint64_t monotonic_ms(void)
{
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (uint64_t)now.tv_sec * 1000 + (uint64_t)now.tv_nsec / 1000000;
}
static void stop_capture(int signal_number)
{
(void)signal_number;
if (active_capture != NULL && active_capture->loop != NULL)
if (active_capture != NULL && active_capture->loop != NULL) {
active_capture->stopping = 1;
pw_main_loop_quit(active_capture->loop);
}
}
static struct frame_slot *slot_at(struct capture *c, uint64_t n)
@@ -88,8 +111,8 @@ static uint8_t *slot_frame(struct frame_slot *slot)
return (uint8_t *)slot + sizeof(struct frame_slot);
}
/* Create (or resize) the shared file for the negotiated geometry and write
* the header. Called once, from param_changed, before any frame exists. */
/* Publish a new inode for every geometry. A Wine reader may still map the
* previous inode: never truncate or resize memory another process is reading. */
static int shm_setup(struct capture *c)
{
size_t slot_bytes = sizeof(struct frame_slot) +
@@ -103,26 +126,30 @@ static int shm_setup(struct capture *c)
return -1;
}
c->shm_fd = open(c->frame_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC,
0600);
if (c->shm_fd < 0) {
char temporary[PATH_MAX];
if (snprintf(temporary, sizeof(temporary), "%s.XXXXXX", c->frame_path) >=
(int)sizeof(temporary))
return -1;
int fd = mkostemp(temporary, O_CLOEXEC);
if (fd < 0) {
perror("open frame transport");
return -1;
}
if (ftruncate(c->shm_fd, (off_t)total) < 0) {
if (fchmod(fd, 0600) < 0 || ftruncate(fd, (off_t)total) < 0) {
perror("ftruncate");
close(fd);
unlink(temporary);
return -1;
}
c->shm = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED,
c->shm_fd, 0);
if (c->shm == MAP_FAILED) {
uint8_t *mapping = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mapping == MAP_FAILED) {
perror("mmap");
c->shm = NULL;
close(fd);
unlink(temporary);
return -1;
}
c->shm_size = total;
struct frame_header *header = (struct frame_header *)c->shm;
struct frame_header *header = (struct frame_header *)mapping;
header->magic = 0x46525555u; /* "UURF" */
header->version = UURF_VERSION;
header->width = c->width;
@@ -131,8 +158,29 @@ static int shm_setup(struct capture *c)
header->format = FRAME_FORMAT_BGRX;
atomic_init(&header->total_frames, 0);
for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) {
atomic_init(&slot_at(c, (uint64_t)i)->seq, 0);
struct frame_slot *slot = (struct frame_slot *)(mapping +
UURF_HEADER_BYTES + i * slot_bytes);
atomic_init(&slot->seq, 0);
}
if (rename(temporary, c->frame_path) < 0) {
perror("publish frame transport");
munmap(mapping, total);
close(fd);
unlink(temporary);
return -1;
}
if (c->shm != NULL) {
struct frame_header *previous = (struct frame_header *)c->shm;
atomic_store_explicit(&previous->total_frames, 0, memory_order_release);
munmap(c->shm, c->shm_size);
}
if (c->shm_fd >= 0)
close(c->shm_fd);
c->shm = mapping;
c->shm_fd = fd;
c->shm_size = total;
c->counter = 0;
c->started_ms = monotonic_ms();
return 0;
}
@@ -180,6 +228,16 @@ static void publish_frame(struct capture *c, const uint8_t *pixels,
memory_order_release);
}
static int sync_dmabuf(int fd, uint64_t flags)
{
struct dma_buf_sync sync = {.flags = flags};
int result;
do {
result = ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync);
} while (result < 0 && errno == EINTR);
return result;
}
static void on_process(void *userdata)
{
struct capture *c = userdata;
@@ -193,38 +251,67 @@ static void on_process(void *userdata)
uint8_t *pixels = NULL;
void *mapping = MAP_FAILED;
size_t mapping_size = 0;
int synchronized = 0;
int dmabuf = plane->type == SPA_DATA_DmaBuf;
if (plane->chunk == NULL) {
pw_stream_queue_buffer(c->stream, buffer);
return;
if (plane->chunk == NULL || plane->chunk->stride < 0 ||
(plane->chunk->flags & (SPA_CHUNK_FLAG_CORRUPTED | SPA_CHUNK_FLAG_EMPTY)))
goto done;
uint32_t row_bytes = c->width *
(c->format == SPA_VIDEO_FORMAT_BGR || c->format == SPA_VIDEO_FORMAT_RGB ? 3u : 4u);
uint32_t stride = plane->chunk->stride > 0 ?
(uint32_t)plane->chunk->stride : row_bytes;
uint64_t span = (uint64_t)stride * (c->height - 1) + row_bytes;
uint32_t data_offset = plane->chunk->offset;
if (stride < row_bytes || span > 256u * 1024 * 1024)
goto done;
if (dmabuf) {
// DMA-BUF maxsize/chunk size may be zero or placeholders. Query
// the fd and include BOTH the plane mapping and chunk offsets.
if (!c->dmabuf_usable || plane->fd < 0)
goto done;
off_t extent = lseek((int)plane->fd, 0, SEEK_END);
uint64_t end = (uint64_t)plane->mapoffset + data_offset + span;
if (extent < 0 || end > (uint64_t)extent)
goto done;
struct pollfd ready = {.fd = (int)plane->fd, .events = POLLIN};
if (poll(&ready, 1, 100) <= 0 || !(ready.revents & POLLIN) ||
sync_dmabuf((int)plane->fd, DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ) < 0)
goto done;
synchronized = 1;
} else {
if (plane->maxsize == 0)
goto done;
data_offset %= plane->maxsize;
if ((uint64_t)data_offset + span > plane->maxsize ||
span > plane->chunk->size)
goto done;
}
if (plane->data != NULL) {
pixels = plane->data + plane->chunk->offset;
} else if (plane->type == SPA_DATA_MemFd && plane->fd >= 0) {
pixels = (uint8_t *)plane->data + data_offset;
} else if ((dmabuf || plane->type == SPA_DATA_MemFd) && plane->fd >= 0) {
long page_size = sysconf(_SC_PAGESIZE);
uint64_t offset = (uint64_t)plane->mapoffset + plane->chunk->offset;
uint64_t offset = (uint64_t)plane->mapoffset + data_offset;
uint64_t page_mask = (uint64_t)(page_size > 0 ? page_size : 4096) - 1;
off_t aligned = (off_t)(offset & ~page_mask);
size_t delta = (size_t)(offset - (uint64_t)aligned);
mapping_size = delta + plane->chunk->size;
mapping = mmap(NULL, mapping_size, PROT_READ, MAP_PRIVATE,
mapping_size = delta + (size_t)span;
mapping = mmap(NULL, mapping_size, PROT_READ, MAP_SHARED,
plane->fd, aligned);
if (mapping != MAP_FAILED)
pixels = (uint8_t *)mapping + delta;
}
if (pixels != NULL) {
int32_t signed_stride = plane->chunk->stride;
uint32_t stride = signed_stride > 0
? (uint32_t)signed_stride
: (c->format == SPA_VIDEO_FORMAT_BGR ||
c->format == SPA_VIDEO_FORMAT_RGB
? c->width * 3
: c->width * 4);
uint32_t rows = stride > 0 ? plane->chunk->size / stride : 0;
publish_frame(c, pixels, stride, rows);
if (mapping != MAP_FAILED)
munmap(mapping, mapping_size);
if (c->counter == 0)
fprintf(stderr, "capture buffer: %s, source stride %u, chunk offset %u\n",
dmabuf ? "linear DMA-BUF" : "shared memory", stride, data_offset);
publish_frame(c, pixels, stride, c->height);
}
done:
if (synchronized)
(void)sync_dmabuf((int)plane->fd, DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ);
if (mapping != MAP_FAILED)
munmap(mapping, mapping_size);
}
pw_stream_queue_buffer(c->stream, buffer);
@@ -237,7 +324,7 @@ static void on_param_changed(void *userdata, uint32_t id,
if (param == NULL || id != SPA_PARAM_Format)
return;
struct spa_video_info_raw info;
struct spa_video_info_raw info = {0};
if (spa_format_video_raw_parse(param, &info) < 0)
return;
if (info.format != SPA_VIDEO_FORMAT_BGRx &&
@@ -250,29 +337,92 @@ static void on_param_changed(void *userdata, uint32_t id,
return;
}
if (info.size.width == 0 || info.size.height == 0 ||
info.size.width > 16384 || info.size.height > 16384 ||
(uint64_t)info.size.width * 4 * info.size.height > 256u * 1024 * 1024) {
fprintf(stderr, "unsupported capture geometry\n");
c->exit_status = 1;
pw_main_loop_quit(c->loop);
return;
}
c->width = (uint32_t)info.size.width;
c->height = (uint32_t)info.size.height;
c->format = info.format;
c->stride = SPA_ROUND_UP_N(c->width * 4, 4);
fprintf(stderr, "negotiated: %ux%u stride %u\n", c->width, c->height,
c->stride);
/* The DMA-BUF path mmaps the fd directly, which is only correct for a
* linear layout. A tiled modifier needs a real importer (GBM/EGL), so
* refuse to publish garbage rather than emit a corrupt frame. */
c->dmabuf_usable = spa_pod_find_prop(param, NULL, SPA_FORMAT_VIDEO_modifier) != NULL &&
info.modifier == DRM_FORMAT_MOD_LINEAR;
fprintf(stderr, "negotiated: %ux%u stride %u modifier %#llx%s\n", c->width,
c->height, c->stride, (unsigned long long)info.modifier,
c->dmabuf_usable ? "" : " (DMA-BUF CPU mapping disabled)");
if (c->shm == NULL && shm_setup(c) < 0) {
pw_main_loop_quit(c->loop);
const struct frame_header *header = (const struct frame_header *)c->shm;
if (header == NULL || header->width != c->width || header->height != c->height) {
if (shm_setup(c) < 0) {
c->exit_status = 1;
pw_main_loop_quit(c->loop);
}
}
}
static void on_state_changed(void *userdata, enum pw_stream_state old,
enum pw_stream_state state, const char *error)
{
(void)userdata;
(void)old;
struct capture *c = userdata;
fprintf(stderr, "stream state: %s%s%s\n",
pw_stream_state_as_string(state),
error != NULL && error[0] != '\0' ? " - " : "",
error != NULL ? error : "");
if (c->stopping)
return;
if (state == PW_STREAM_STATE_STREAMING) {
c->was_streaming = 1;
c->paused_ms = 0;
} else if (state == PW_STREAM_STATE_PAUSED && c->was_streaming) {
if (c->paused_ms == 0)
c->paused_ms = monotonic_ms();
} else if (state == PW_STREAM_STATE_ERROR ||
(state == PW_STREAM_STATE_UNCONNECTED && old != state)) {
c->exit_status = 75;
pw_main_loop_quit(c->loop);
}
}
static void on_watchdog(void *userdata, uint64_t expirations)
{
struct capture *c = userdata;
(void)expirations;
uint64_t now = monotonic_ms();
// A static desktop can legitimately produce no new frames while streaming.
// Only a prolonged PAUSED state or a stream with no FIRST frame is fatal.
if (!c->stopping &&
((c->paused_ms != 0 && now - c->paused_ms >= 10000) ||
(c->counter == 0 && now - c->started_ms >= 30000))) {
fprintf(stderr, "capture stream stopped producing usable frames; reconnecting\n");
c->exit_status = 75;
pw_main_loop_quit(c->loop);
}
}
static void on_core_error(void *userdata, uint32_t id, int sequence,
int result, const char *message)
{
struct capture *c = userdata;
(void)sequence;
if (!c->stopping && id == PW_ID_CORE && result < 0) {
fprintf(stderr, "PipeWire connection failed: %s\n", message);
c->exit_status = 75;
pw_main_loop_quit(c->loop);
}
}
static const struct pw_core_events core_events = {
PW_VERSION_CORE_EVENTS,
.error = on_core_error,
};
static const struct pw_stream_events stream_events = {
.version = PW_VERSION_STREAM_EVENTS,
.process = on_process,
@@ -280,6 +430,27 @@ static const struct pw_stream_events stream_events = {
.state_changed = on_state_changed,
};
static const struct spa_pod *capture_format(struct spa_pod_builder *builder,
int dmabuf)
{
struct spa_pod_frame frame;
spa_pod_builder_push_object(builder, &frame, SPA_TYPE_OBJECT_Format,
SPA_PARAM_EnumFormat);
spa_pod_builder_add(builder,
SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video),
SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
SPA_FORMAT_VIDEO_format,
SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_BGRA,
SPA_VIDEO_FORMAT_RGBx, SPA_VIDEO_FORMAT_RGBA,
SPA_VIDEO_FORMAT_BGR, SPA_VIDEO_FORMAT_RGB), 0);
if (dmabuf) {
spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier,
SPA_POD_PROP_FLAG_MANDATORY);
spa_pod_builder_long(builder, DRM_FORMAT_MOD_LINEAR);
}
return spa_pod_builder_pop(builder, &frame);
}
int main(void)
{
const char *fd_text = getenv("UUR_PW_FD");
@@ -330,6 +501,8 @@ int main(void)
fprintf(stderr, "pw_context_connect_fd failed\n");
return 1;
}
struct spa_hook core_listener;
pw_core_add_listener(core, &core_listener, &core_events, &c);
struct pw_properties *props = pw_properties_new(
PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture",
@@ -344,39 +517,45 @@ int main(void)
uint8_t pod_buffer[1024];
struct spa_pod_builder pod_builder =
SPA_POD_BUILDER_INIT(pod_buffer, sizeof(pod_buffer));
const struct spa_pod *params[1];
params[0] = spa_pod_builder_add_object(
&pod_builder, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat,
SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video),
SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
SPA_FORMAT_VIDEO_format,
SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx,
SPA_VIDEO_FORMAT_BGRA,
SPA_VIDEO_FORMAT_RGBx,
SPA_VIDEO_FORMAT_RGBA,
SPA_VIDEO_FORMAT_BGR,
SPA_VIDEO_FORMAT_RGB));
const struct spa_pod *params[2];
params[0] = capture_format(&pod_builder, 1);
params[1] = capture_format(&pod_builder, 0);
c.started_ms = monotonic_ms();
if (pw_stream_connect(c.stream, PW_DIRECTION_INPUT, node_id,
PW_STREAM_FLAG_MAP_BUFFERS |
PW_STREAM_FLAG_AUTOCONNECT |
PW_STREAM_FLAG_RT_PROCESS,
params, 1) < 0) {
PW_STREAM_FLAG_AUTOCONNECT,
params, 2) < 0) {
fprintf(stderr, "pw_stream_connect failed\n");
return 1;
}
struct spa_source *watchdog = pw_loop_add_timer(pw_main_loop_get_loop(loop),
on_watchdog, &c);
struct timespec interval = {.tv_sec = 1};
if (watchdog == NULL || pw_loop_update_timer(pw_main_loop_get_loop(loop),
watchdog, &interval, &interval, false) < 0) {
fprintf(stderr, "could not start capture watchdog\n");
return 1;
}
pw_main_loop_run(loop);
c.stopping = 1;
active_capture = NULL;
pw_loop_destroy_source(pw_main_loop_get_loop(loop), watchdog);
pw_stream_destroy(c.stream);
spa_hook_remove(&core_listener);
pw_core_disconnect(core);
pw_context_destroy(context);
pw_main_loop_destroy(loop);
if (c.shm != NULL)
if (c.shm != NULL) {
struct frame_header *header = (struct frame_header *)c.shm;
atomic_store_explicit(&header->total_frames, 0, memory_order_release);
munmap(c.shm, c.shm_size);
}
if (c.shm_fd >= 0)
close(c.shm_fd);
unlink(c.frame_path);
pw_deinit();
return 0;
return c.exit_status;
}
+42
View File
@@ -47,3 +47,45 @@ mutexes; a torn read is detected, never observed.
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.
## Geometry and session changes
An exact Wine monitor rectangle maps onto the entire selected frame when their
aspect ratios match. Pixel dimensions may differ under fractional scaling, where
Xwayland's render size can exceed the portal's native frame size. Partial regions
and whole-virtual-desktop requests retain the existing virtual-desktop mapping.
This does not establish monitor identity between Wine and the portal; selecting
a non-primary monitor still requires consistent client/input 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. The ScreenCast supervisor retries 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.
+5 -5
View File
@@ -12,13 +12,13 @@ needed for system-wide package installation.
paru -S uur
# Downloaded release package
sudo pacman -U ./uur-0.1.5-1-x86_64.pkg.tar.zst
sudo pacman -U ./uur-0.1.6-1-x86_64.pkg.tar.zst
```
## Debian, Ubuntu, and derivatives
```bash
sudo apt install ./uur_0.1.5_amd64.deb
sudo apt install ./uur_0.1.6_amd64.deb
```
The same release artifact covers Debian, Ubuntu, Linux Mint, Pop!_OS, KDE neon,
@@ -28,10 +28,10 @@ derivatives.
## Fedora, RHEL, and openSUSE families
```bash
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
# openSUSE
sudo zypper install ./uur-0.1.5-1.x86_64.rpm
sudo zypper install ./uur-0.1.6-1.x86_64.rpm
```
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:
```bash
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.6-linux-x86_64.tar.zst
```
## Nix and NixOS
+17 -5
View File
@@ -46,7 +46,7 @@ paru -S uur
From a downloaded Arch package:
```bash
sudo pacman -U ./uur-0.1.5-1-x86_64.pkg.tar.zst
sudo pacman -U ./uur-0.1.6-1-x86_64.pkg.tar.zst
```
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:
```bash
sudo apt install ./uur_0.1.5_amd64.deb
sudo apt install ./uur_0.1.6_amd64.deb
```
The package manager resolves Wine, PipeWire, and the portal frontend. Install
@@ -74,10 +74,10 @@ dependency names. Install it with the native frontend:
```bash
# Fedora and compatible systems
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
# openSUSE family
sudo zypper install ./uur-0.1.5-1.x86_64.rpm
sudo zypper install ./uur-0.1.6-1.x86_64.rpm
```
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:
```bash
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.6-linux-x86_64.tar.zst
```
Alternatively, build and install for one user:
@@ -243,6 +243,18 @@ Stop only the managed session and its Wine prefix with:
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:
```bash
+109 -17
View File
@@ -17,6 +17,10 @@
*/
#define WIN32_LEAN_AND_MEAN
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
@@ -234,6 +238,9 @@ static uint64_t frame_slot_bytes;
static unsigned char *frame_snapshot;
static size_t frame_snapshot_capacity;
static size_t frame_map_size;
static BY_HANDLE_FILE_INFORMATION frame_identity;
static ULONGLONG frame_checked_at;
static SRWLOCK frame_lock = SRWLOCK_INIT;
static char *read_ini_value(const char *path, const char *key);
@@ -264,39 +271,70 @@ static uint64_t load_u64(const unsigned char *p)
return load_u32(p) | ((uint64_t)load_u32(p + 4) << 32);
}
/* Open (or re-open after a resolution change) the capture file that the
* native uur-pw-capture helper publishes. */
static void clear_frame_map(void)
{
if (frame_map != NULL)
UnmapViewOfFile(frame_map);
if (frame_map_handle != NULL)
CloseHandle(frame_map_handle);
frame_map = NULL;
frame_map_handle = NULL;
frame_map_size = 0;
}
/* Producers publish immutable geometry via atomic replacement. Re-check the
* file identity periodically, including after an ungraceful helper restart. */
static int ensure_frame_map(void)
{
HANDLE file;
void *view;
const unsigned char *header;
LARGE_INTEGER size;
BY_HANDLE_FILE_INFORMATION identity;
WCHAR path[32768];
ULONGLONG now = GetTickCount64();
if (frame_map != NULL)
if (frame_map != NULL && now - frame_checked_at < 250 &&
load_u64((const unsigned char *)frame_map + 24) != 0)
return 1;
if (!resolve_frame_path(path, (int)(sizeof(path) / sizeof(path[0]))))
return 0;
file = CreateFileW(path, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
0, NULL);
if (file == INVALID_HANDLE_VALUE)
return 0;
if (!GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES ||
(uint64_t)size.QuadPart > SIZE_MAX) {
CloseHandle(file);
if (file == INVALID_HANDLE_VALUE) {
clear_frame_map();
return 0;
}
if (!GetFileInformationByHandle(file, &identity) ||
!GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES ||
(uint64_t)size.QuadPart > UURF_HEADER_BYTES +
UURF_SLOT_COUNT * (8ull + 256ull * 1024 * 1024)) {
CloseHandle(file);
clear_frame_map();
return 0;
}
frame_checked_at = now;
if (frame_map != NULL &&
identity.dwVolumeSerialNumber == frame_identity.dwVolumeSerialNumber &&
identity.nFileIndexHigh == frame_identity.nFileIndexHigh &&
identity.nFileIndexLow == frame_identity.nFileIndexLow &&
(uint64_t)size.QuadPart == frame_map_size) {
CloseHandle(file);
return 1;
}
clear_frame_map();
frame_map_handle = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0,
NULL);
CloseHandle(file);
if (frame_map_handle == NULL)
return 0;
view = MapViewOfFile(frame_map_handle, FILE_MAP_READ, 0, 0, 0);
if (view == NULL)
if (view == NULL) {
clear_frame_map();
return 0;
}
header = (const unsigned char *)view;
if (load_u32(header) != UURF_MAGIC ||
@@ -311,7 +349,10 @@ static int ensure_frame_map(void)
frame_stride = load_u32(header + 16);
frame_slot_bytes = 8ull + (uint64_t)frame_stride * frame_height;
uint64_t expected = UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes;
if (frame_width == 0 || frame_height == 0 || frame_stride < frame_width * 4 ||
if (frame_width == 0 || frame_height == 0 ||
frame_width > 16384 || frame_height > 16384 ||
frame_stride != frame_width * 4 ||
(uint64_t)frame_stride * frame_height > 256ull * 1024 * 1024 ||
expected > (uint64_t)size.QuadPart) {
UnmapViewOfFile(view);
CloseHandle(frame_map_handle);
@@ -320,6 +361,7 @@ static int ensure_frame_map(void)
}
frame_map_size = (size_t)size.QuadPart;
frame_map = view;
frame_identity = identity;
return 1;
}
@@ -389,7 +431,7 @@ static void draw_cursor_overlay(HDC hdc_dest, int x, int y, int width, int heigh
/* Feed the newest desktop frame into the capture destination by drawing
* our shared-memory frame with StretchDIBits. Works regardless of the
* destination bitmap type (DDB or DIB section). */
static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
static BOOL feed_capture_frame_locked(HDC hdc_dest, int x, int y, int width,
int height, int source_x, int source_y,
int source_width, int source_height)
{
@@ -407,7 +449,8 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
fstride = load_u32(header + 16);
size_t frame_bytes = (size_t)fstride * fh;
total = load_u64(header + 24);
if (fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 ||
if (fw != frame_width || fh != frame_height || fstride != frame_stride ||
fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 ||
frame_bytes / fstride != fh ||
UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes > frame_map_size)
return FALSE;
@@ -449,10 +492,48 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
screen_width = (int)fw;
if (screen_height < 1)
screen_height = (int)fh;
int sx = (int)((int64_t)source_x * fw / screen_width);
int sy = (int)((int64_t)source_y * fh / screen_height);
int sw = (int)((int64_t)source_width * fw / screen_width);
int sh = (int)((int64_t)source_height * fh / screen_height);
/* The frame holds exactly one monitor, but the client may ask
* for that monitor's whole rectangle. Wine reports the
* compositor's monitors in its own order, so the virtual desktop
* is only the right basis for a partial request; a complete
* monitor request must map onto the whole frame. Fractional
* scaling can give Xwayland and the portal different pixel
* sizes, so compare aspect ratios rather than resolutions. */
int sx = 0;
int sy = 0;
int sw = 0;
int sh = 0;
RECT requested;
requested.left = (LONG)source_x;
requested.top = (LONG)source_y;
requested.right = (LONG)source_x + (LONG)source_width;
requested.bottom = (LONG)source_y + (LONG)source_height;
HMONITOR monitor = (source_width > 0 && source_height > 0)
? MonitorFromRect(&requested, MONITOR_DEFAULTTONULL)
: NULL;
MONITORINFO info;
info.cbSize = sizeof(info);
BOOL whole_monitor = FALSE;
if (monitor != NULL && GetMonitorInfoA(monitor, &info)) {
whole_monitor =
info.rcMonitor.left == requested.left &&
info.rcMonitor.top == requested.top &&
info.rcMonitor.right == requested.right &&
info.rcMonitor.bottom == requested.bottom &&
(int64_t)(info.rcMonitor.right - info.rcMonitor.left) * fh ==
(int64_t)(info.rcMonitor.bottom - info.rcMonitor.top) * fw;
}
if (whole_monitor) {
sx = 0;
sy = 0;
sw = (int)fw;
sh = (int)fh;
} else {
sx = (int)((int64_t)source_x * fw / screen_width);
sy = (int)((int64_t)source_y * fh / screen_height);
sw = (int)((int64_t)source_width * fw / screen_width);
sh = (int)((int64_t)source_height * fh / screen_height);
}
if (sw < 1)
sw = (int)fw;
if (sh < 1)
@@ -472,6 +553,17 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
return ok;
}
static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
int height, int source_x, int source_y,
int source_width, int source_height)
{
AcquireSRWLockExclusive(&frame_lock);
BOOL result = feed_capture_frame_locked(hdc_dest, x, y, width, height,
source_x, source_y, source_width, source_height);
ReleaseSRWLockExclusive(&frame_lock);
return result;
}
static BOOL try_capture_feed(HDC hdc_dest, int x, int y, DWORD rop,
HDC hdc_src, int width, int height, int source_x,
int source_y, int source_width, int source_height)
+42 -3
View File
@@ -4,10 +4,34 @@
* GameViewerService enumerates processes for a winlogon session token
* source before it initialises; under plain Wine none exists and 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 <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 show_command)
@@ -16,6 +40,21 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line,
(void)previous;
(void)command_line;
(void)show_command;
Sleep(INFINITE);
return 0;
WCHAR image[MAX_PATH];
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"
session_ready: "portal session ready (video node %{node}); streaming to the private runtime transport"
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:
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 显示器采集"
session_ready: "Portal 会话已建立(视频节点 %{node});正在写入私有运行时传输"
helper_failed: "捕获助手异常退出"
cursor_unsupported: "桌面 Portal 未声明任何可用的光标模式,无法开始屏幕采集。请重启 Portal(systemctl --user restart xdg-desktop-portal)后重试;若仍失败,请确认已安装与当前会话匹配的 ScreenCast 后端。"
cursor_not_embedded: "Portal 无法将光标嵌入画面;采集将继续,但视频帧中不会包含光标"
setup:
eula_prompt: "官方 UU 远程客户端将从网易官方渠道下载,并受其最终用户协议约束:%{url}\n使用 --accept-eula 重新运行以继续。"
+1 -1
View File
@@ -25,7 +25,7 @@ let
in
rustPlatform.buildRustPackage {
pname = "uur";
version = "0.1.5";
version = "0.1.6";
src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;
+1 -1
View File
@@ -1,7 +1,7 @@
# Contributor: uur contributors
# Maintainer: uur contributors
pkgname=uur
pkgver=0.1.5
pkgver=0.1.6
pkgrel=0
pkgdesc="Native Linux companion for NetEase UU Remote"
url="https://github.com/panxuc/uur"
+2 -2
View File
@@ -1,6 +1,6 @@
pkgbase = uur
pkgdesc = Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)
pkgver = 0.1.5
pkgver = 0.1.6
pkgrel = 1
url = https://github.com/panxuc/uur
install = uur.install
@@ -33,7 +33,7 @@ pkgbase = uur
optdepends = libva-utils: VA-API capability diagnostics
optdepends = vulkan-tools: Vulkan and Vulkan Video capability diagnostics
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
pkgname = uur
+1 -1
View File
@@ -8,7 +8,7 @@
# `uur setup` (it is never redistributed by this package).
pkgname=uur
pkgver=0.1.5
pkgver=0.1.6
pkgrel=1
pkgdesc="Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)"
arch=('x86_64')
+290 -33
View File
@@ -13,6 +13,7 @@
//! a headless remote host.
use anyhow::{anyhow, Context, Result};
use futures::{FutureExt, StreamExt};
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::fd::OwnedFd;
@@ -20,9 +21,21 @@ use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::config::Config;
type PortalSession =
ashpd::desktop::Session<'static, ashpd::desktop::screencast::Screencast<'static>>;
struct PortalCapture {
fd: OwnedFd,
node: u32,
restore_token: Option<String>,
session: PortalSession,
closed: zbus::proxy::SignalStream<'static>,
}
/// Run the capture path until interrupted.
pub fn run_standalone() -> Result<()> {
// Public capture uses the same lifecycle lock as run/setup so stop and
@@ -62,31 +75,170 @@ pub fn run() -> Result<()> {
if config.capture_backend != "portal" {
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
// throughout capture, including on capture-only compositors such as niri.
runtime.block_on(async {
let (pw_fd, node) = tokio::select! {
result = portal_session(&mut config) => result?,
_ = wait_for_stop(&stopping) => return Ok(()),
};
println!("{}", t!("capture.session_ready", node = node));
let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?);
let frames = frame_path()?;
let mut failures = 0;
let mut initial_session = true;
let mut display_changes = watch_display_changes().await;
loop {
let opened = tokio::select! {
result = portal_session(&mut config, initial_session) => result,
_ = wait_for_stop(&stopping) => return Ok(()),
};
let PortalCapture {
fd: pw_fd,
node,
session,
mut closed,
..
} = match opened {
Ok(opened) => opened,
Err(error) if !initial_session && failures < 3 => {
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;
println!("{}", t!("capture.session_ready", node = node));
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_helper(pw_fd, node)?);
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 let Some(status) = helper.0.try_wait()
.context("waiting for capture helper")? {
break Some(status);
}
}
}
};
drop(closed);
drop(helper);
let _ = tokio::time::timeout(Duration::from_secs(2), session.close()).await;
if stopping.load(Ordering::Relaxed) {
return Ok(());
}
if let Some(status) = helper.0.try_wait().context("waiting for capture helper")? {
if !status.success() {
anyhow::bail!("{}", t!("capture.helper_failed"));
// Closed without a matching layout change means Stop sharing.
// Never silently restore that permission or use direct capture.
if portal_closed {
anyhow::bail!(
"screen sharing was closed by the portal; restart uur run to share again"
);
}
if healthy_since.is_some_and(|since| since.elapsed() >= Duration::from_secs(30)) {
failures = 0;
}
if reconfigure {
eprintln!("display configuration changed; restoring capture");
} else {
failures += 1;
if failures > 3 {
anyhow::bail!(
"capture recovery failed repeatedly; restart uur run to share again"
);
}
return Ok(());
let status = status.context("capture helper stopped without an exit status")?;
if !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;
}
})
}
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()
}
async fn next_display_change(changes: &mut Option<zbus::proxy::SignalStream<'static>>) {
loop {
match changes.as_mut() {
Some(stream) => {
if stream.next().await.is_some() {
return;
}
*changes = None;
}
None => std::future::pending::<()>().await,
}
}
}
async fn wait_for_stop(stopping: &AtomicBool) {
while !stopping.load(Ordering::Relaxed) {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -175,8 +327,7 @@ fn frame_path() -> Result<PathBuf> {
/// First attempt reuses the stored restore token; if that fails (stale
/// token, monitor changed, compositor restart) fall back to one
/// interactive attempt and store the fresh token.
#[allow(clippy::type_complexity)]
async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
async fn portal_session(config: &mut Config, interactive: bool) -> Result<PortalCapture> {
let saved_token = config.capture_restore_token.clone();
let screencast = ashpd::desktop::screencast::Screencast::new()
.await
@@ -188,40 +339,106 @@ async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
.clone()
.map(Some)
.into_iter()
.chain(std::iter::once(None))
.chain(interactive.then_some(None))
{
match negotiate(&screencast, source, token.as_deref()).await {
Ok((fd, node, fresh_token)) => {
if fresh_token != saved_token {
config.capture_restore_token = fresh_token;
Ok(capture) => {
if capture.restore_token != saved_token {
config.capture_restore_token = capture.restore_token.clone();
config.store().context("storing the new restore token")?;
}
return Ok((fd, node));
return Ok(capture);
}
Err(error) => {
last_error = Some(error);
}
}
}
Err(last_error.unwrap_or_else(|| anyhow!("portal session failed")))
Err(last_error.unwrap_or_else(|| {
anyhow!("capture permission could not be restored; restart uur run to share again")
}))
}
/// 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
/// and the restore token the portal issued for this selection.
async fn negotiate(
screencast: &ashpd::desktop::screencast::Screencast<'_>,
screencast: &ashpd::desktop::screencast::Screencast<'static>,
source: ashpd::desktop::screencast::SourceType,
restore_token: Option<&str>,
) -> Result<(OwnedFd, u32, Option<String>)> {
use ashpd::desktop::screencast::CursorMode;
) -> Result<PortalCapture> {
use ashpd::desktop::PersistMode;
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
.select_sources(
&session,
CursorMode::Embedded,
cursor_mode,
source.into(),
false,
restore_token,
@@ -241,7 +458,13 @@ async fn negotiate(
.open_pipe_wire_remote(&session)
.await
.context("opening the PipeWire remote")?;
Ok((fd, node, fresh_token))
Ok(PortalCapture {
fd,
node,
restore_token: fresh_token,
session,
closed,
})
}
pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType {
@@ -262,13 +485,7 @@ pub fn list_wayland_outputs() -> Result<()> {
}
fn find_helper(name: &str) -> Result<PathBuf> {
let mut candidates = vec![
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));
}
let mut candidates = Vec::new();
if let Ok(exe) = std::env::current_exe() {
// dev checkout: target/debug/uur -> capture/uur-pw-capture
if let Some(dir) = exe.parent() {
@@ -277,6 +494,11 @@ fn find_helper(name: &str) -> Result<PathBuf> {
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() {
candidates.push(cwd.join("capture").join(name));
}
@@ -288,8 +510,10 @@ fn find_helper(name: &str) -> Result<PathBuf> {
#[cfg(test)]
mod tests {
use super::choose_cursor_mode;
use super::source_type;
use ashpd::desktop::screencast::SourceType;
use ashpd::desktop::screencast::{CursorMode, SourceType};
use ashpd::enumflags2::BitFlags;
#[test]
fn configured_portal_source_is_mapped() {
@@ -297,4 +521,37 @@ mod tests {
assert_eq!(source_type("window"), SourceType::Window);
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);
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
use anyhow::{anyhow, Context, Result};
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 std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -140,7 +140,7 @@ async fn portal_worker(
screencast
.select_sources(
&session,
CursorMode::Embedded,
crate::capture::preferred_cursor_mode(&screencast).await?,
source.into(),
false,
None,
+254 -117
View File
@@ -45,13 +45,7 @@ fn complete_hook_directory(dir: &Path) -> bool {
}
fn hook_dir() -> Result<PathBuf> {
let mut candidates = vec![
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"));
}
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/hook"));
@@ -59,6 +53,14 @@ fn hook_dir() -> Result<PathBuf> {
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
.into_iter()
.find(|dir| complete_hook_directory(dir))
@@ -66,32 +68,7 @@ fn hook_dir() -> Result<PathBuf> {
}
fn hook_source_dir() -> Result<PathBuf> {
let mut candidates = vec![PathBuf::from("/usr/lib/uur/hook")];
if let Ok(home) = std::env::var("HOME") {
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
}
candidates.push(
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|d| d.join("../lib/uur/hook")))
.unwrap_or_default(),
);
candidates.push(
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|d| d.join("../../build/hook")))
.unwrap_or_default(),
);
candidates.push(
std::env::current_dir()
.ok()
.map(|dir| dir.join("build/hook"))
.unwrap_or_default(),
);
candidates
.into_iter()
.find(|dir| complete_hook_directory(dir))
.context("hook DLLs not found (run the build first)")
hook_dir()
}
static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
@@ -181,7 +158,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
let source_dir = hook_source_dir()?;
let source = source_dir.join("uur-terminal-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)?;
for status in ["uur-terminal-adapter.status", "uur-mux-adapter.status"] {
let _ = std::fs::remove_file(bin.join(status));
@@ -254,9 +231,8 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
if crate::wine::webview2_installed(prefix) {
return Ok(());
}
let bootstrapper = install_dir
.join("bin")
.join("MicrosoftEdgeWebview2Setup.exe");
let bootstrapper =
crate::wine::client_payload_dir(install_dir).join("MicrosoftEdgeWebview2Setup.exe");
if !bootstrapper.is_file() {
anyhow::bail!("{}", t!("session.webview_missing"));
}
@@ -408,7 +384,7 @@ impl SessionResources {
for helper in &mut self.helpers {
if matches!(
helper.name.as_str(),
"__bridge" | "__capture" | "__terminal" | "__launcher"
"__bridge" | "__capture" | "__terminal" | "__launcher" | "winlogon"
) {
helper.ensure_running()?;
}
@@ -552,32 +528,46 @@ pub fn start() -> Result<()> {
// The service enumerates processes for a winlogon session token source
// 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 _ = Command::new("wine")
let mut monitor = Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
.env("UUR_HOOK_LOG", log_path()?)
.env("UUR_BRIDGE_PORT", config.bridge_port.to_string())
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone())
.stdout(Stdio::from(log.try_clone()?))
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
.env("UUR_MONITOR_CLIENT", "GameViewer.exe")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::from(log.try_clone()?))
.arg(marker.to_string_lossy().as_ref())
.spawn();
.process_group(0)
.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
// Manager, so the service must be started through `sc start` — a
// directly spawned --service process is invisible to it and the UI
// waits forever.
if !service_running(&prefix) {
let _ = Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.stdout(Stdio::from(log.try_clone()?))
.stderr(Stdio::from(log.try_clone()?))
.args(["sc", "start", "GameViewerService"])
.status();
let _ = run_with_timeout(
Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
.args([r"C:\windows\system32\sc.exe", "start", "GameViewerService"]),
std::time::Duration::from_secs(5),
);
}
let service_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !service_running(&prefix) {
@@ -618,17 +608,18 @@ pub fn start() -> Result<()> {
let mut relaunches = 0;
while !stopping.load(Ordering::Relaxed) {
resources.check_required_helpers()?;
let running = wine_client_process_exists(&prefix);
if running {
seen_client = true;
missing_checks = 0;
} else if seen_client {
missing_checks = missing_checks.saturating_add(1);
// UU hands off between short-lived launchers and its real Qt
// process. Require a sustained absence before treating it as a
// user-requested exit.
if missing_checks >= 6 {
break;
if let Some(running) = client_monitor.poll()? {
if running {
seen_client = true;
missing_checks = 0;
} else if seen_client {
missing_checks = missing_checks.saturating_add(1);
// UU hands off between short-lived launchers and its real Qt
// process. Require a sustained absence before treating it as a
// user-requested exit.
if missing_checks >= 6 {
break;
}
}
}
if !seen_client && std::time::Instant::now() >= deadline {
@@ -648,26 +639,68 @@ pub fn start() -> Result<()> {
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`
/// cmdline names another image, so Linux process-name matching is not a valid
/// lifecycle boundary.
fn wine_client_process_exists(prefix: &Path) -> bool {
let output = run_with_timeout(
Command::new("wine")
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
"tasklist",
"/NH",
"/FO",
"CSV",
"/FI",
"IMAGENAME eq GameViewer.exe",
]),
std::time::Duration::from_secs(5),
);
output.is_some_and(|text| tasklist_contains_image(&text, "GameViewer.exe"))
/// lifecycle boundary. A failed query never means that the client exited.
struct ClientMonitor {
output: std::process::ChildStdout,
last_response: std::time::Instant,
}
impl ClientMonitor {
fn new(output: std::process::ChildStdout) -> Result<Self> {
set_nonblocking(&output)?;
Ok(Self {
output,
last_response: std::time::Instant::now(),
})
}
fn poll(&mut self) -> Result<Option<bool>> {
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
@@ -678,30 +711,49 @@ fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Opti
use std::process::Stdio;
let mut child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.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;
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) => {
if std::time::Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return None;
}
// Check exit before draining, so the command's final output is not
// lost in a wait/read race. Never wait for EOF: Wine descendants can
// retain this pipe after the utility itself has exited.
let status = child.try_wait();
let read = pipe
.by_ref()
.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`.
@@ -710,7 +762,8 @@ fn service_running(prefix: &Path) -> bool {
Command::new("wine")
.env("WINEPREFIX", prefix)
.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),
);
match output {
@@ -722,15 +775,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> {
Ok(data_dir()?.join("hook.log"))
}
@@ -925,10 +969,103 @@ fn parse_xft_dpi(resources: &str) -> Option<u32> {
}
fn stop_wineserver(prefix: &Path) {
let _ = Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-k")
.status();
// Capture handles before Wine's shutdown: a WebView2 thread-group leader
// can exit while its other threads retain the address space and pipes.
let mut remaining = remaining_wine_processes(prefix);
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;
};
if !matches!(
executable.file_name().and_then(|name| name.to_str()),
Some("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 {
@@ -1050,11 +1187,11 @@ mod tests {
}
#[test]
fn tasklist_parser_matches_the_exact_image() {
let output = "\"GameViewer.exe\",\"456\",\"Console\",\"1\"\n\
\"GameViewerServer.exe\",\"464\",\"Console\",\"1\"\n";
assert!(tasklist_contains_image(output, "GameViewer.exe"));
assert!(!tasklist_contains_image(output, "GameViewerService.exe"));
fn monitor_parser_distinguishes_absence_and_query_failure() {
assert_eq!(monitor_observation(b'1').unwrap(), Some(true));
assert_eq!(monitor_observation(b'0').unwrap(), Some(false));
assert_eq!(monitor_observation(b'?').unwrap(), None);
assert!(monitor_observation(b'X').is_err());
}
#[test]
+329 -31
View File
@@ -1,6 +1,7 @@
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::config::Config;
@@ -59,9 +60,10 @@ pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
.arg(if repair { "--update" } else { "--init" })
.status()
.context("running wineboot")?;
if !status.success() || !prefix_initialized(&prefix) {
if !status.success() {
anyhow::bail!("{}", t!("setup.prefix_failed", status = status));
}
flush_prefix(&prefix).context("waiting for Wine to persist the initialized prefix")?;
if find_client_dir(&prefix).is_some() && query_client_service(&prefix)? {
finish_setup(&prefix)?;
@@ -136,12 +138,16 @@ pub fn webview2_installed(prefix: &Path) -> bool {
.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
/// 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;
};
/// The Windows service NetEase's installer registers points at
/// `GameViewerService.exe`. `GameViewerServer.exe` is a different program —
/// the streaming/terminal server — and never appears in the service
/// ImagePath, so matching on it made every provisioning check fail and left
/// `uur setup` re-downloading and re-installing on an already complete prefix.
const SERVICE_IMAGE: &str = "gameviewerservice.exe";
/// Extract the `ImagePath` recorded for the UU Windows service from the raw
/// `system.reg` text. Kept pure so it can be tested without a Wine prefix.
fn service_image_path(registry: &str) -> Option<String> {
let mut service_section = false;
for line in registry.lines() {
if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) {
@@ -149,11 +155,22 @@ pub fn client_service_registered(prefix: &Path) -> bool {
.0
.to_ascii_lowercase()
.ends_with(r"\\services\\gameviewerservice");
} else if service_section && line.starts_with("\"ImagePath\"=") {
return line.to_ascii_lowercase().contains("gameviewerserver.exe");
} else if service_section {
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> {
@@ -171,10 +188,13 @@ fn query_client_service(prefix: &Path) -> Result<bool> {
.stdin(Stdio::null())
.output()
.context("checking the UU Windows service registration")?;
// Wine may record the service under `ControlSet001` and only alias it as
// `CurrentControlSet`, and `reg query` output is CRLF; matching the
// executable name case-insensitively anywhere in stdout covers both.
Ok(output.status.success()
&& String::from_utf8_lossy(&output.stdout)
.to_ascii_lowercase()
.contains("gameviewerserver.exe"))
.contains(SERVICE_IMAGE))
}
/// Registry compatibility profile, ported from the field-tested reference
@@ -330,35 +350,145 @@ fn stop_wineserver(prefix: &Path) {
.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
/// 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> {
let program_files = prefix.join("drive_c").join("Program Files");
let entries = std::fs::read_dir(&program_files).ok()?;
let mut roots = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name();
if name.to_string_lossy().eq_ignore_ascii_case("netease") {
let vendor = entry.path();
if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) {
let bin = found.parent()?;
let candidate = if bin
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("bin"))
{
bin.parent()?.to_path_buf()
} else {
bin.to_path_buf()
};
if std::fs::metadata(candidate.join("GameViewer.exe"))
.is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
&& std::fs::metadata(&found).is_ok_and(|metadata| metadata.len() > 0)
{
return Some(candidate);
}
if !entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case("netease")
{
continue;
}
collect_client_roots(&entry.path(), 4, &mut roots);
}
roots.retain(|root| client_root_rank(root) > 0);
roots.sort_by(|left, right| {
client_root_rank(right)
.cmp(&client_root_rank(left))
.then_with(|| left.components().count().cmp(&right.components().count()))
.then_with(|| left.cmp(right))
});
roots.dedup();
roots.into_iter().next()
}
/// Installed releases normally place their payload in bin/. A complete flat
/// version directory remains usable when it is the only installation present.
pub fn client_payload_dir(client: &Path) -> PathBuf {
let bin = client.join("bin");
if non_empty_file(&bin.join("GameViewerServer.exe")) {
bin
} else {
client.to_path_buf()
}
}
/// Collect every directory that contains the client launcher.
fn collect_client_roots(dir: &Path, depth: u8, out: &mut Vec<PathBuf>) {
if depth == 0 {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_client_roots(&path, depth - 1, out);
} else if path
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("GameViewer.exe"))
&& non_empty_file(&path)
{
if let Some(parent) = path.parent() {
out.push(parent.to_path_buf());
}
}
}
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> {
@@ -515,9 +645,177 @@ fn purge_wine_shortcuts() {
#[cfg(test)]
mod tests {
use super::find_client_dir;
use super::log_pixels_command;
use super::registry_compat_entries;
use super::service_image_path;
use std::path::Path;
use std::path::PathBuf;
/// Scratch prefix with a real NetEase directory layout, removed on drop.
struct TestPrefix(PathBuf);
impl TestPrefix {
fn create() -> Self {
let path = std::env::temp_dir().join(format!(
"uur-client-dir-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
/// Create `<prefix>/drive_c/Program Files/Netease/GameViewer/<rel>`.
fn write_client_file(&self, rel: &str, contents: &[u8]) {
let path = self
.0
.join("drive_c/Program Files/Netease/GameViewer")
.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, contents).unwrap();
}
}
impl Drop for TestPrefix {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Populate both payload copies NetEase installs. The buggy search
/// returned `<version>/` whenever readdir reached it first, which then
/// failed every `join("bin")` lookup.
fn install_both_layouts(prefix: &TestPrefix) {
for relative in [
"GameViewer.exe",
"GameViewerServer.exe",
"bin/GameViewer.exe",
"bin/GameViewerServer.exe",
"4.42.0.2770/GameViewer.exe",
"4.42.0.2770/GameViewerServer.exe",
] {
prefix.write_client_file(relative, b"payload");
}
}
#[test]
fn client_root_is_the_directory_holding_bin_not_the_version_directory() {
let prefix = TestPrefix::create();
install_both_layouts(&prefix);
let root = find_client_dir(prefix.path()).expect("client root");
assert!(
root.join("bin").join("GameViewerServer.exe").is_file(),
"the returned root must contain bin/GameViewerServer.exe, got {}",
root.display()
);
assert!(
!root.file_name().is_some_and(|name| name == "4.42.0.2770"),
"the version directory must not be selected, got {}",
root.display()
);
}
#[test]
fn client_root_is_stable_regardless_of_readdir_order() {
let prefix = TestPrefix::create();
install_both_layouts(&prefix);
let expected = find_client_dir(prefix.path()).unwrap();
// Repeated lookups must not alternate between the two payload copies.
for _ in 0..16 {
assert_eq!(find_client_dir(prefix.path()).as_ref(), Some(&expected));
}
}
#[test]
fn bin_layout_outranks_a_versioned_payload_copy() {
let prefix = TestPrefix::create();
// The versioned copy has the launcher and server at its top level,
// but no bin/; the real root has the payload in bin/.
prefix.write_client_file("GameViewer.exe", b"payload");
prefix.write_client_file("4.42.0.2770/GameViewer.exe", b"payload");
prefix.write_client_file("4.42.0.2770/GameViewerServer.exe", b"payload");
prefix.write_client_file("bin/GameViewerServer.exe", b"payload");
let root = find_client_dir(prefix.path()).expect("client root");
assert!(
root.join("bin").join("GameViewerServer.exe").is_file(),
"the bin layout must win, got {}",
root.display()
);
assert!(
!root.file_name().is_some_and(|name| name == "4.42.0.2770"),
"the version directory must not win, got {}",
root.display()
);
}
#[test]
fn versioned_copy_is_used_only_when_it_is_the_only_candidate() {
let prefix = TestPrefix::create();
prefix.write_client_file("4.42.0.2770/GameViewer.exe", b"payload");
prefix.write_client_file("4.42.0.2770/GameViewerServer.exe", b"payload");
let root = find_client_dir(prefix.path()).expect("client root");
assert!(root.ends_with("4.42.0.2770"), "got {}", root.display());
assert_eq!(super::client_payload_dir(&root), root);
}
#[test]
fn missing_client_reports_none() {
let prefix = TestPrefix::create();
std::fs::create_dir_all(prefix.path().join("drive_c/Program Files/Netease")).unwrap();
assert!(find_client_dir(prefix.path()).is_none());
prefix.write_client_file("GameViewer.exe", b"payload");
prefix.write_client_file("bin/MicrosoftEdgeWebview2Setup.exe", b"payload");
assert!(find_client_dir(prefix.path()).is_none());
}
/// Real `system.reg` excerpt written by the NetEase installer, escaped
/// exactly as Wine stores it. The service ImagePath names
/// GameViewerService.exe, not GameViewerServer.exe.
const INSTALLED_SYSTEM_REG: &str = concat!(
"[System\\\\ControlSet001\\\\Services\\\\GameViewerService] 1791878366\n",
"#time=1dd5ae8c44b323c\n",
"\"DependOnService\"=str(7):\"RpcSs\\0Tcpip\\0NDIS\\0AFD\\0\"\n",
"\"DisplayName\"=\"GameViewerService\"\n",
"\"ImagePath\"=str(2):\"\\\"C:\\\\Program Files\\\\Netease\\\\GameViewer",
"\\\\GameViewerService.exe\\\" --service\"\n",
"\"ObjectName\"=\"LocalSystem\"\n",
"\"Start\"=dword:00000002\n",
);
#[test]
fn service_registration_matches_the_image_the_installer_registers() {
// Regression: the check looked for gameviewerserver.exe, which never
// appears in the service ImagePath, so a complete install was always
// reported as missing and `uur setup` reinstalled on every run.
let image = service_image_path(INSTALLED_SYSTEM_REG).expect("ImagePath parsed");
assert!(image.contains("gameviewerservice.exe"));
assert!(!image.contains("gameviewerserver.exe"));
}
#[test]
fn missing_service_section_is_not_registered() {
let registry = "[Software\\\\Wine\\\\DllOverrides] 1\n\"winemenubuilder\"=\"\"\n";
assert!(service_image_path(registry).is_none());
}
#[test]
fn service_section_without_image_path_is_not_registered() {
let registry = "[System\\\\ControlSet001\\\\Services\\\\GameViewerService] 1\n\
\"Start\"=dword:00000002\n";
assert!(service_image_path(registry).is_none());
}
#[test]
fn bundled_cpp_runtime_is_preferred_for_both_uu_processes() {