diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 613d220..31007bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,7 +50,7 @@ jobs: sudo apt-get update sudo apt-get install -y --no-install-recommends \ appstream binutils-mingw-w64-x86-64 desktop-file-utils \ - gcc gcc-mingw-w64-x86-64 libpipewire-0.3-dev pkg-config \ + gcc gcc-mingw-w64-x86-64 libpipewire-0.3-dev libwayland-dev pkg-config \ wine xvfb - name: Build and stage run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4442ae9..27976dd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,7 +38,7 @@ jobs: run: | sudo apt-get update sudo apt-get install -y --no-install-recommends \ - binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev \ + binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev libwayland-dev \ gcc-mingw-w64-x86-64 pkg-config zstd - name: Install nFPM env: @@ -73,7 +73,7 @@ jobs: - name: Install Arch build dependencies run: | pacman -Syu --noconfirm \ - cargo rust gcc pkgconf pipewire \ + cargo rust gcc pkgconf pipewire wayland \ mingw-w64-gcc mingw-w64-binutils - name: Build native pacman package with makepkg run: | diff --git a/.gitignore b/.gitignore index b3e17ad..6099b98 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,6 @@ /build /dist /capture/uur-pw-capture +/capture/uur-wl-capture Cargo.lock.orig *.tar.gz diff --git a/Cargo.lock b/Cargo.lock index 6367cf7..51a0a31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.5" @@ -231,6 +237,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-deque" version = "0.8.7" @@ -342,6 +357,26 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -749,6 +784,26 @@ dependencies = [ "autocfg", ] +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.3" @@ -821,6 +876,19 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -1115,6 +1183,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "siphasher" version = "1.0.3" @@ -1421,6 +1495,7 @@ dependencies = [ "futures", "input-linux-sys", "libc", + "png", "rust-i18n", "serde", "serde_json", @@ -1428,6 +1503,7 @@ dependencies = [ "tokio", "toml", "x11rb", + "zbus", ] [[package]] @@ -1718,6 +1794,12 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 36fcbba..3a9efe1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,8 @@ libc = "0.2" input-linux-sys = "0.9" x11rb = { version = "0.13", features = ["xtest"] } signal-hook = "0.3" +png = "0.18" +zbus = { version = "5", default-features = false, features = ["tokio"] } [profile.release] lto = true diff --git a/NOTICE b/NOTICE index 06620e2..5f68a5f 100644 --- a/NOTICE +++ b/NOTICE @@ -1,5 +1,9 @@ uur is original code, MIT licensed. +The vendored wlr-screencopy protocol is MIT licensed, copyright Simon Ser +(2018) and Andri Yngvason (2019). Its full license is preserved in +capture/wlr-screencopy-unstable-v1.xml. + Design ideas were learned from and are credited to: - GuoWQ222/uu-remote-for-linux (0BSD) — the wevtapi preload chain and the PipeWire/portal approach to Wayland capture. diff --git a/README.md b/README.md index 5424eaa..3250208 100644 --- a/README.md +++ b/README.md @@ -151,13 +151,25 @@ uur autostart disable # Remove the managed login entry uur wol status # Inspect the physical wired adapter's WOL state uur display status # Monitor, window, or portal virtual source uur display source virtual +uur display outputs # Native Wayland output names uur stop # Stop only uur's helpers and Wine prefix +uur uninstall --purge --dry-run # Preview complete user-data cleanup +uur uninstall --purge # Confirm cleanup before removing the system package ``` If UU was started from the desktop, choose **Quit** from the launcher's application actions. When running from a terminal, use `uur stop` or press Ctrl+C. +On niri, uur provides a native tray and an explicitly enabled direct capture +path: `uur display backend wayland --output DP-1` (use your output name). +This uses uinput and captures the chosen monitor without a portal dialog. +Return to system-consented capture with `uur display backend portal`. + +Package removal alone preserves the Wine prefix and account data. See +[complete removal](docs/distribution.md#package-removal-repair-and-per-user-state) +for the user-cleanup and package-manager steps. + Diagnostic input overrides: ```bash diff --git a/README.zh-CN.md b/README.zh-CN.md index 0e6bde5..e4b1633 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -125,7 +125,7 @@ cargo build --release --locked ./scripts/install-user.sh ``` -源码构建需要 Rust、C 编译器、PipeWire 开发文件、`pkg-config` 和 MinGW-w64 x86_64 +源码构建需要 Rust、C 编译器、PipeWire 与 Wayland 开发文件(含 `wayland-scanner`)、`pkg-config` 和 MinGW-w64 x86_64 工具链。 Gentoo、Void Linux、Slackware、Solus、ALT Linux、Exherbo、Clear Linux、Mageia、 @@ -146,12 +146,23 @@ uur autostart disable # 删除受管登录自启动项 uur wol status # 检查物理有线网卡的 WOL 状态 uur display status # 查看显示器、窗口或 Portal 虚拟源设置 uur display source virtual +uur display outputs # 查看原生 Wayland 显示器名称 uur stop # 只停止 uur 助手与专用 Wine 前缀 +uur uninstall --purge --dry-run # 预览完整用户数据清理范围 +uur uninstall --purge # 确认清理后,再用包管理器卸载系统包 ``` 从桌面启动 UU 后,可在启动器的应用操作菜单中选择“退出”;从终端运行时可执行 `uur stop` 或按 Ctrl+C。 +niri 可使用原生托盘,并明确启用直接采集:先运行 `uur display outputs` 查看名称,再运行 +`uur display backend wayland --output DP-1`(替换为自己的名称)。此模式使用 uinput, +直接采集指定显示器,不弹出 Portal 授权框;`uur display backend portal` 可恢复系统授权采集。 + +仅用包管理器卸载会保留 Wine 环境和账号数据。完整卸载请先以当前用户身份运行 +`uur uninstall --purge`,再执行 `sudo pacman -Rns uur`(Arch);其他发行版使用 +对应的包管理器。详见[完整卸载说明](docs/distribution.md#package-removal-repair-and-per-user-state)。 + 输入后端排错: ```bash diff --git a/capture/build.sh b/capture/build.sh index 47beede..636bf92 100755 --- a/capture/build.sh +++ b/capture/build.sh @@ -15,3 +15,15 @@ command -v "$cc" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$cc" >&2; exi $(pkg-config --cflags --libs libpipewire-0.3) printf 'built: %s\n' "$out/uur-pw-capture" + +generated="$root/build/capture" +mkdir -p "$generated" +wayland-scanner client-header "$root/capture/wlr-screencopy-unstable-v1.xml" \ + "$generated/wlr-screencopy-unstable-v1-client-protocol.h" +wayland-scanner private-code "$root/capture/wlr-screencopy-unstable-v1.xml" \ + "$generated/wlr-screencopy-unstable-v1-protocol.c" +"$cc" "${flags[@]}" -I"$generated" -o "$out/uur-wl-capture" \ + "$root/capture/uur-wl-capture.c" \ + "$generated/wlr-screencopy-unstable-v1-protocol.c" \ + $(pkg-config --cflags --libs wayland-client) +printf 'built: %s\n' "$out/uur-wl-capture" diff --git a/capture/uur-wl-capture.c b/capture/uur-wl-capture.c new file mode 100644 index 0000000..6f6b760 --- /dev/null +++ b/capture/uur-wl-capture.c @@ -0,0 +1,336 @@ +/* Direct Wayland monitor capture, explicitly enabled by the user. + * Uses compositor-provided wl_shm buffers; no GBM, portal or GPU import is + * required. Frames use the same private UURF transport as PipeWire capture. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-screencopy-unstable-v1-client-protocol.h" +#include "../hook/frame-protocol.h" + +struct frame_header { + uint32_t magic, version, width, height, stride, format; + _Atomic uint64_t total_frames; + uint8_t reserved[32]; +}; +_Static_assert(sizeof(struct frame_header) == UURF_HEADER_BYTES, "frame header ABI"); + +struct output { + struct wl_output *proxy; + uint32_t global; + char name[128]; + int32_t width, height; +}; + +struct capture { + struct wl_display *display; + struct wl_registry *registry; + struct wl_shm *shm; + struct zwlr_screencopy_manager_v1 *manager; + struct output outputs[64]; + size_t output_count; + struct output *selected; + struct zwlr_screencopy_frame_v1 *frame; + struct wl_buffer *buffer; + void *pixels; + size_t pixels_size; + uint32_t width, height, stride, format, flags; + int done, failed; + int ring_fd; + void *ring; + size_t ring_size; + uint32_t ring_width, ring_height; + uint64_t counter; + const char *frame_path; +}; + +static volatile sig_atomic_t stopping; +static void stop_capture(int signum) { (void)signum; stopping = 1; } + +static void output_geometry(void *data, struct wl_output *output, int32_t x, + int32_t y, int32_t physical_width, int32_t physical_height, int32_t subpixel, + const char *make, const char *model, int32_t transform) +{ + (void)data; (void)output; (void)x; (void)y; (void)physical_width; + (void)physical_height; (void)subpixel; (void)make; (void)model; (void)transform; +} +static void output_mode(void *data, struct wl_output *output, uint32_t flags, + int32_t width, int32_t height, int32_t refresh) +{ + (void)output; (void)refresh; + struct output *o = data; + if (flags & WL_OUTPUT_MODE_CURRENT) { o->width = width; o->height = height; } +} +static void output_done(void *data, struct wl_output *output) { (void)data; (void)output; } +static void output_scale(void *data, struct wl_output *output, int32_t scale) +{ (void)data; (void)output; (void)scale; } +static void output_name(void *data, struct wl_output *output, const char *name) +{ (void)output; snprintf(((struct output *)data)->name, 128, "%s", name); } +static void output_description(void *data, struct wl_output *output, const char *description) +{ (void)data; (void)output; (void)description; } +static const struct wl_output_listener output_listener = { + .geometry = output_geometry, .mode = output_mode, .done = output_done, + .scale = output_scale, .name = output_name, .description = output_description, +}; + +static void registry_global(void *data, struct wl_registry *registry, uint32_t name, + const char *interface, uint32_t version) +{ + struct capture *c = data; + if (!strcmp(interface, wl_shm_interface.name)) { + c->shm = wl_registry_bind(registry, name, &wl_shm_interface, 1); + } else if (!strcmp(interface, zwlr_screencopy_manager_v1_interface.name)) { + c->manager = wl_registry_bind(registry, name, + &zwlr_screencopy_manager_v1_interface, version < 3 ? version : 3); + } else if (!strcmp(interface, wl_output_interface.name) && c->output_count < 64) { + struct output *o = &c->outputs[c->output_count++]; + o->global = name; + o->proxy = wl_registry_bind(registry, name, &wl_output_interface, version < 4 ? version : 4); + wl_output_add_listener(o->proxy, &output_listener, o); + } +} +static void registry_remove(void *data, struct wl_registry *registry, uint32_t name) +{ + (void)registry; + struct capture *c = data; + if (c->selected != NULL && c->selected->global == name) { + fprintf(stderr, "captured output disconnected\n"); + c->failed = 1; stopping = 1; + } +} +static const struct wl_registry_listener registry_listener = { + .global = registry_global, .global_remove = registry_remove, +}; + +static int setup_ring(struct capture *c) +{ + if (c->ring != NULL) { + if (c->ring_width == c->width && c->ring_height == c->height) return 0; + fprintf(stderr, "capture geometry changed; restart uur run\n"); + return -1; + } + size_t bytes = (size_t)c->width * 4 * c->height; + c->ring_size = UURF_HEADER_BYTES + UURF_SLOT_COUNT * (sizeof(uint64_t) + bytes); + c->ring_fd = open(c->frame_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); + if (c->ring_fd < 0 || fchmod(c->ring_fd, 0600) < 0 || + ftruncate(c->ring_fd, (off_t)c->ring_size) < 0) { perror("frame transport"); return -1; } + c->ring = mmap(NULL, c->ring_size, PROT_READ | PROT_WRITE, MAP_SHARED, c->ring_fd, 0); + if (c->ring == MAP_FAILED) { c->ring = NULL; perror("frame mmap"); return -1; } + c->ring_width = c->width; c->ring_height = c->height; + struct frame_header *header = c->ring; + memset(header, 0, sizeof(*header)); + header->magic = UURF_MAGIC; header->version = UURF_VERSION; + header->width = c->width; header->height = c->height; + header->stride = c->width * 4; header->format = 1; + atomic_init(&header->total_frames, 0); + for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) { + _Atomic uint64_t *seq = (_Atomic uint64_t *)((uint8_t *)c->ring + + UURF_HEADER_BYTES + i * (sizeof(uint64_t) + bytes)); + atomic_init(seq, 0); + } + fprintf(stderr, "Wayland output %s: %ux%u\n", c->selected->name, c->width, c->height); + return 0; +} + +static int supported_format(uint32_t format) +{ + return format == WL_SHM_FORMAT_XRGB8888 || format == WL_SHM_FORMAT_ARGB8888 || + format == WL_SHM_FORMAT_XBGR8888 || format == WL_SHM_FORMAT_ABGR8888 || + format == WL_SHM_FORMAT_XRGB2101010 || format == WL_SHM_FORMAT_ARGB2101010 || + format == WL_SHM_FORMAT_XBGR2101010 || format == WL_SHM_FORMAT_ABGR2101010; +} +static int submit_buffer(struct capture *c) +{ + if (!supported_format(c->format) || c->width == 0 || c->height == 0 || + c->width > 16384 || c->height > 16384 || c->stride < c->width * 4 || + (uint64_t)c->stride * c->height > 256u * 1024 * 1024) { + fprintf(stderr, "unsupported Wayland SHM format or geometry\n"); + return -1; + } + if (setup_ring(c) < 0) return -1; + c->pixels_size = (size_t)c->stride * c->height; + int fd = memfd_create("uur-wayland-frame", MFD_CLOEXEC); + if (fd < 0) { perror("memfd_create"); return -1; } + if (ftruncate(fd, (off_t)c->pixels_size) < 0) { close(fd); return -1; } + c->pixels = mmap(NULL, c->pixels_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (c->pixels == MAP_FAILED) { c->pixels = NULL; close(fd); return -1; } + struct wl_shm_pool *pool = wl_shm_create_pool(c->shm, fd, (int32_t)c->pixels_size); + c->buffer = wl_shm_pool_create_buffer(pool, 0, (int32_t)c->width, + (int32_t)c->height, (int32_t)c->stride, c->format); + wl_shm_pool_destroy(pool); close(fd); + zwlr_screencopy_frame_v1_copy(c->frame, c->buffer); + return 0; +} +static void frame_buffer(void *data, struct zwlr_screencopy_frame_v1 *frame, + uint32_t format, uint32_t width, uint32_t height, uint32_t stride) +{ + struct capture *c = data; + c->format = format; c->width = width; c->height = height; c->stride = stride; + if (zwlr_screencopy_frame_v1_get_version(frame) < 3 && submit_buffer(c) < 0) { + c->done = 1; c->failed = 1; + } +} +static void frame_buffer_done(void *data, struct zwlr_screencopy_frame_v1 *frame) +{ + (void)frame; + struct capture *c = data; + if (submit_buffer(c) < 0) { c->done = 1; c->failed = 1; } +} +static void frame_flags(void *data, struct zwlr_screencopy_frame_v1 *frame, uint32_t flags) +{ (void)frame; ((struct capture *)data)->flags = flags; } +static void frame_ready(void *data, struct zwlr_screencopy_frame_v1 *frame, + uint32_t hi, uint32_t lo, uint32_t ns) +{ (void)frame; (void)hi; (void)lo; (void)ns; ((struct capture *)data)->done = 1; } +static void frame_failed(void *data, struct zwlr_screencopy_frame_v1 *frame) +{ (void)frame; struct capture *c = data; c->done = 1; c->failed = 1; } +static void frame_damage(void *data, struct zwlr_screencopy_frame_v1 *frame, + uint32_t x, uint32_t y, uint32_t width, uint32_t height) +{ (void)data; (void)frame; (void)x; (void)y; (void)width; (void)height; } +static void frame_dmabuf(void *data, struct zwlr_screencopy_frame_v1 *frame, + uint32_t format, uint32_t width, uint32_t height) +{ (void)data; (void)frame; (void)format; (void)width; (void)height; } +static const struct zwlr_screencopy_frame_v1_listener frame_listener = { + .buffer = frame_buffer, .flags = frame_flags, .ready = frame_ready, + .failed = frame_failed, .damage = frame_damage, + .linux_dmabuf = frame_dmabuf, .buffer_done = frame_buffer_done, +}; + +static void publish_frame(struct capture *c) +{ + size_t bytes = (size_t)c->width * 4 * c->height; + uint64_t n = ++c->counter; + _Atomic uint64_t *seq = (_Atomic uint64_t *)((uint8_t *)c->ring + + uurf_slot_offset(n, sizeof(uint64_t) + bytes)); + uint8_t *dest = (uint8_t *)seq + sizeof(uint64_t); + atomic_store_explicit(seq, 2 * n - 1, memory_order_release); + int rgb = c->format == WL_SHM_FORMAT_XBGR8888 || c->format == WL_SHM_FORMAT_ABGR8888; + int ten = c->format == WL_SHM_FORMAT_XRGB2101010 || c->format == WL_SHM_FORMAT_ARGB2101010 || + c->format == WL_SHM_FORMAT_XBGR2101010 || c->format == WL_SHM_FORMAT_ABGR2101010; + int ten_bgr = c->format == WL_SHM_FORMAT_XBGR2101010 || c->format == WL_SHM_FORMAT_ABGR2101010; + for (uint32_t y = 0; y < c->height; ++y) { + uint32_t row = c->flags & ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT ? c->height - y - 1 : y; + const uint8_t *src = (const uint8_t *)c->pixels + (size_t)row * c->stride; + uint8_t *dst = dest + (size_t)y * c->width * 4; + for (uint32_t x = 0; x < c->width; ++x, src += 4, dst += 4) { + if (ten) { + uint32_t value; memcpy(&value, src, 4); + dst[0] = (uint8_t)((((value >> (ten_bgr ? 20 : 0)) & 1023) * 255 + 511) / 1023); + dst[1] = (uint8_t)((((value >> 10) & 1023) * 255 + 511) / 1023); + dst[2] = (uint8_t)((((value >> (ten_bgr ? 0 : 20)) & 1023) * 255 + 511) / 1023); + } else { + dst[0] = src[rgb ? 2 : 0]; dst[1] = src[1]; dst[2] = src[rgb ? 0 : 2]; + } + dst[3] = 0; + } + } + atomic_store_explicit(seq, 2 * n, memory_order_release); + atomic_store_explicit(&((struct frame_header *)c->ring)->total_frames, n, memory_order_release); +} + +static int dispatch(struct capture *c) +{ + while (wl_display_prepare_read(c->display) != 0) { + if (wl_display_dispatch_pending(c->display) < 0) return -1; + if (c->done || c->failed || stopping) return 0; + } + if (wl_display_flush(c->display) < 0 && errno != EAGAIN) { + wl_display_cancel_read(c->display); return -1; + } + struct pollfd fd = { .fd = wl_display_get_fd(c->display), .events = POLLIN }; + int rc = poll(&fd, 1, 10000); + if (rc <= 0 || !(fd.revents & POLLIN)) { + wl_display_cancel_read(c->display); + if (rc == 0) fprintf(stderr, "Wayland capture frame timed out\n"); + return stopping ? 0 : -1; + } + if (wl_display_read_events(c->display) < 0) return -1; + return wl_display_dispatch_pending(c->display); +} + +static void clear_frame(struct capture *c) +{ + if (c->frame != NULL) { zwlr_screencopy_frame_v1_destroy(c->frame); c->frame = NULL; } + if (c->buffer != NULL) { wl_buffer_destroy(c->buffer); c->buffer = NULL; } + if (c->pixels != NULL) { munmap(c->pixels, c->pixels_size); c->pixels = NULL; } + c->pixels_size = 0; c->width = c->height = c->stride = c->format = c->flags = 0; +} + +int main(int argc, char **argv) +{ + struct capture c = { .ring_fd = -1 }; + int list = argc == 2 && !strcmp(argv[1], "--list-outputs"); + if (argc > 1 && !list) { fprintf(stderr, "usage: uur-wl-capture [--list-outputs]\n"); return 2; } + c.frame_path = getenv("UUR_FRAME_PATH"); + if (!list && (c.frame_path == NULL || c.frame_path[0] != '/')) { + fprintf(stderr, "UUR_FRAME_PATH must name the private absolute frame transport\n"); return 2; + } + struct sigaction sa = { .sa_handler = stop_capture }; + sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); + c.display = wl_display_connect(NULL); + if (c.display == NULL) { fprintf(stderr, "cannot connect to Wayland display\n"); return 1; } + c.registry = wl_display_get_registry(c.display); + wl_registry_add_listener(c.registry, ®istry_listener, &c); + if (wl_display_roundtrip(c.display) < 0 || wl_display_roundtrip(c.display) < 0) { + c.failed = 1; goto cleanup; + } + if (list) { + for (size_t i = 0; i < c.output_count; ++i) { + printf("%s %dx%d\n", c.outputs[i].name, c.outputs[i].width, c.outputs[i].height); + } + goto cleanup; + } + if (c.manager == NULL || c.shm == NULL) { + fprintf(stderr, "compositor does not expose wlr-screencopy with wl_shm buffers\n"); + c.failed = 1; goto cleanup; + } + const char *name = getenv("UUR_CAPTURE_OUTPUT"); + if (name != NULL && name[0] != '\0') { + for (size_t i = 0; i < c.output_count; ++i) { + if (!strcmp(name, c.outputs[i].name)) c.selected = &c.outputs[i]; + } + } else if (c.output_count == 1) { c.selected = &c.outputs[0]; } + if (c.selected == NULL) { + fprintf(stderr, "select one output with uur display backend wayland --output NAME:\n"); + for (size_t i = 0; i < c.output_count; ++i) fprintf(stderr, " %s\n", c.outputs[i].name); + c.failed = 1; goto cleanup; + } + while (!stopping && !c.failed) { + c.done = 0; + c.frame = zwlr_screencopy_manager_v1_capture_output(c.manager, 1, c.selected->proxy); + zwlr_screencopy_frame_v1_add_listener(c.frame, &frame_listener, &c); + while (!c.done && !stopping) { + if (dispatch(&c) < 0) { c.failed = 1; break; } + } + if (c.done && !c.failed && !stopping) publish_frame(&c); + clear_frame(&c); + struct timespec delay = { .tv_nsec = 33333333 }; + nanosleep(&delay, NULL); + } +cleanup: + clear_frame(&c); + if (c.ring != NULL) munmap(c.ring, c.ring_size); + if (c.ring_fd >= 0) { + struct stat created, present; + if (fstat(c.ring_fd, &created) == 0 && lstat(c.frame_path, &present) == 0 && + created.st_dev == present.st_dev && created.st_ino == present.st_ino) unlink(c.frame_path); + close(c.ring_fd); + } + for (size_t i = 0; i < c.output_count; ++i) wl_output_destroy(c.outputs[i].proxy); + if (c.manager != NULL) zwlr_screencopy_manager_v1_destroy(c.manager); + if (c.shm != NULL) wl_shm_destroy(c.shm); + wl_registry_destroy(c.registry); wl_display_disconnect(c.display); + return c.failed ? 1 : 0; +} diff --git a/capture/wlr-screencopy-unstable-v1.xml b/capture/wlr-screencopy-unstable-v1.xml new file mode 100644 index 0000000..50b1b7d --- /dev/null +++ b/capture/wlr-screencopy-unstable-v1.xml @@ -0,0 +1,232 @@ + + + + Copyright © 2018 Simon Ser + Copyright © 2019 Andri Yngvason + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol allows clients to ask the compositor to copy part of the + screen content to a client buffer. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This object is a manager which offers requests to start capturing from a + source. + + + + + Capture the next frame of an entire output. + + + + + + + + + Capture the next frame of an output's region. + + The region is given in output logical coordinates, see + xdg_output.logical_size. The region will be clipped to the output's + extents. + + + + + + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This object represents a single frame. + + When created, a series of buffer events will be sent, each representing a + supported buffer type. The "buffer_done" event is sent afterwards to + indicate that all supported buffer types have been enumerated. The client + will then be able to send a "copy" request. If the capture is successful, + the compositor will send a "flags" followed by a "ready" event. + + For objects version 2 or lower, wl_shm buffers are always supported, ie. + the "buffer" event is guaranteed to be sent. + + If the capture failed, the "failed" event is sent. This can happen anytime + before the "ready" event. + + Once either a "ready" or a "failed" event is received, the client should + destroy the frame. + + + + + Provides information about wl_shm buffer parameters that need to be + used for this frame. This event is sent once after the frame is created + if wl_shm buffers are supported. + + + + + + + + + + Copy the frame to the supplied buffer. The buffer must have a the + correct size, see zwlr_screencopy_frame_v1.buffer and + zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a + supported format. + + If the frame is successfully copied, a "flags" and a "ready" events are + sent. Otherwise, a "failed" event is sent. + + + + + + + + + + + + + + + + Provides flags about the frame. This event is sent once before the + "ready" event. + + + + + + + Called as soon as the frame is copied, indicating it is available + for reading. This event includes the time at which presentation happened + at. + + The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples, + each component being an unsigned 32-bit value. Whole seconds are in + tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo, + and the additional fractional part in tv_nsec as nanoseconds. Hence, + for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part + may have an arbitrary offset at start. + + After receiving this event, the client should destroy the object. + + + + + + + + + This event indicates that the attempted frame copy has failed. + + After receiving this event, the client should destroy the object. + + + + + + Destroys the frame. This request can be sent at any time by the client. + + + + + + + Same as copy, except it waits until there is damage to copy. + + + + + + + This event is sent right before the ready event when copy_with_damage is + requested. It may be generated multiple times for each copy_with_damage + request. + + The arguments describe a box around an area that has changed since the + last copy request that was derived from the current screencopy manager + instance. + + The union of all regions received between the call to copy_with_damage + and a ready event is the total damage since the prior ready event. + + + + + + + + + + + Provides information about linux-dmabuf buffer parameters that need to + be used for this frame. This event is sent once after the frame is + created if linux-dmabuf buffers are supported. + + + + + + + + + This event is sent once after all buffer events have been sent. + + The client should proceed to create a buffer of one of the supported + types, and send a "copy" request. + + + + diff --git a/docs/distribution.md b/docs/distribution.md index d655bff..227477c 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -95,7 +95,7 @@ cargo build --release --locked ``` This installs under `~/.local` by default. It requires Rust, a native C -compiler, PipeWire development files, `pkg-config`, and the MinGW-w64 x86_64 +compiler, PipeWire and Wayland development files (including `wayland-scanner`), `pkg-config`, and the MinGW-w64 x86_64 toolchain. ## Required first run @@ -111,3 +111,61 @@ uur run See [Platform support and usage](platform-support.md) for desktop-session and portal requirements. + +## Package removal, repair, and per-user state + +Package removal leaves the managed Wine prefix, downloaded installer cache, +configuration and logs in the user's XDG directories. This preserves login +and client data across package upgrades and reinstalls. Reinstalling the +package therefore does not create a new Wine prefix. Start with +`uur stop` followed by `uur setup --repair` for an interrupted setup. + +For a fresh prefix, stop uur and move the old prefix aside before setup: + +```bash +uur stop +uur_prefix="${XDG_DATA_HOME:-$HOME/.local/share}/uur/wine" +mv -- "$uur_prefix" "$uur_prefix.backup-$(date +%Y%m%d-%H%M%S)" +uur setup --accept-eula +``` + +The fresh prefix needs the official client installed and logged in again. +The backup retains the previous client and account data. + +`uur uninstall` stops the managed session and Wine server, removes this user's +autostart entry and recognized UU launchers/icons, and removes a source +installation identified by its installer receipt. It keeps the managed client, +account data, configuration and logs by default. Use `--purge` for a fresh +start or complete removal: + +```bash +# Preview only: no processes stopped, no files changed +uur uninstall --purge --dry-run + +# Run as the desktop user, NOT with sudo; review the paths and confirm +uur uninstall --purge + +# Remove system package files afterwards (Arch Linux) +sudo pacman -Rns uur +``` + +Purge permanently deletes the dedicated Wine prefix (including Wine Mono, +WebView2 and the official client), login/account data, installer cache, all uur +configuration and logs, and private runtime files. Back up the `uur` XDG +directories first if those data are needed. For unattended removal, explicitly +confirm with `uur uninstall --purge --yes`. The command honors the current +`XDG_DATA_HOME`, `XDG_CONFIG_HOME`, `XDG_STATE_HOME` and `XDG_RUNTIME_DIR`; use +the same values used for setup. A custom source install can be selected with +`UUR_INSTALL_PREFIX=/path/to/prefix uur uninstall --purge`. + +On Debian/Ubuntu, use `sudo apt purge uur` after the user cleanup; on Fedora, +use `sudo dnf remove uur`. Package-manager removal alone leaves per-user data +intact, including when run with `purge`: package scripts run as root and do not +erase other users' home directories. Each user should run the cleanup command +before the system package is removed. If the package was already removed, +reinstall it to get the cleanup command, run `uur uninstall --purge`, then +remove the package again; running setup is not required. Shared Wine/Mono, PipeWire and portal +packages remain the package manager's responsibility. Kernel/device settings +and compositor-granted portal permissions are not reset by user-data cleanup. +Unpin any old launcher from the desktop panel afterwards if the panel retains +its own pinned copy. diff --git a/docs/feature-parity.md b/docs/feature-parity.md index 3a75ac4..47bd263 100644 --- a/docs/feature-parity.md +++ b/docs/feature-parity.md @@ -5,7 +5,7 @@ | Control other devices | available | Official UU UI and decoder under Wine | | Receive remote video | available | Official UU UI under Wine | | Share X11 desktop | available | Wine X11 capture | -| Share Wayland desktop | available | ScreenCast portal → PipeWire → GDI adapter | +| Share Wayland desktop | available | ScreenCast/PipeWire or explicitly enabled native screencopy → GDI adapter | | Mouse and keyboard | implemented | RemoteDesktop portal → uinput → XTest capability order | | X11 multi-monitor | Wine integration | Native Wine/XRandR display topology | | Wayland monitor/window selection | available | Persistent portal source selection | @@ -14,7 +14,7 @@ | 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 | | System-audio loopback and remote mute | Wine integration | WASAPI → winepulse/winealsa | -| Native tray | Wine baseline | Official tray, with StatusNotifierItem as the native route | +| Native tray | implemented | StatusNotifierItem + DBusMenu, supervised with the session; no Wine XEmbed dependency | | Terminal | available | ConPTY/mux ABI adapters → authenticated native Rust PTY/login shell | | Quick Launch | implemented | Windows app inventory adapter → XDG desktop catalog → `gio launch` | | Desktop wallpaper | available | Capability providers → Wine desktop metadata | diff --git a/docs/platform-support.md b/docs/platform-support.md index fcc741b..b9b8f3f 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -139,8 +139,7 @@ frontend, and a backend exposing both `ScreenCast` and `RemoteDesktop`. Where those interfaces are available, uur creates one combined session for capture and input. This is the preferred unprivileged route. Examples can -include current GNOME Shell, KDE Plasma, niri with its recommended portal -configuration, COSMIC, and other sessions whose selected portal backend +include current GNOME Shell, KDE Plasma, COSMIC, and other sessions whose selected portal backend advertises both interfaces. Interface availability—not the desktop name—makes the final decision. @@ -151,7 +150,9 @@ input. XTest remains only a partial fallback for XWayland surfaces. This route commonly applies to compositors using Hyprland or wlroots-oriented portal backends, including Hyprland, Sway, Wayfire, river, labwc, dwl, Waybox, -and other wlroots-based sessions. It may also apply to a desktop whose portal +and other wlroots-based sessions. niri uses its recommended +`xdg-desktop-portal-gnome` ScreenCast integration and requires uinput when a +working RemoteDesktop session is unavailable. It may also apply to a desktop whose portal installation is incomplete or whose selected backend omits RemoteDesktop. Install the compositor's ScreenCast portal and enable uinput access. A @@ -253,6 +254,102 @@ UUR_INPUT_BACKEND=xtest uur run An override is a diagnostic tool, not a desktop-specific configuration. The default `auto` mode should be used after troubleshooting. +## Interrupted setup and Wine components + +Retry an interrupted installation without deleting the managed prefix: + +```bash +uur stop +uur setup --repair +uur doctor +uur run +``` + +The repair option runs `wineboot --update` for the managed prefix. This retries +Wine's component initialization, including its Wine Mono offer where needed. +It keeps the installed client's data, checks both the client and service +executables and the Windows service registration, and reruns the official +installer if that installation is incomplete. Failed initialization or a +failed/cancelled installer returns an error instead of reporting completion. + +The **Wine Mono Installer** is Wine's .NET runtime installer. It is separate +from **WebView2**, which uur uses for the official client's management UI. +Cancelling Mono does not establish the cause of a Wayland black screen or +failed desktop input. Those paths depend on the native capture helper, +ScreenCast/PipeWire and an authorized RemoteDesktop session or uinput. +On Arch/CachyOS, installing the matching `wine-mono` package can avoid the +Wine dialog's network download; use the package supplied for the installed +Wine version. For the existing 0.1.4 release, the equivalent manual retry is: + +```bash +uur stop +WINEPREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/uur/wine" \ + WINEDLLOVERRIDES="wevtapi=b,wtsapi32=b" wineboot --update +uur setup +``` + +To open the Wine program/component manager for this prefix: + +```bash +WINEPREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/uur/wine" \ + WINEDLLOVERRIDES="wevtapi=b,wtsapi32=b" wine uninstaller +``` + +## niri: black video or missing desktop input + +Use the niri session entry (or `niri-session`), its recommended +`xdg-desktop-portal-gnome` backend, and a running PipeWire service. A visible +Wine window only verifies its XWayland display path. Remote video still needs +the separate ScreenCast stream, and native Wayland input needs a working +RemoteDesktop session or writable `/dev/uinput`. + +Start with an actual monitor selection: + +```bash +uur display source monitor +uur doctor +test -w /dev/uinput && echo 'uinput is writable' +uur run +``` + +If the portal chooser offers **niri Dynamic Cast Target**, that stream remains +empty until a target is assigned through niri. Select a real monitor when +diagnosing black video. See [niri's screencasting documentation](https://github.com/niri-wm/niri/wiki/Screencasting). +If RemoteDesktop creation fails, the automatic policy tries uinput. When both +are unavailable it reports an error; explicitly selected XTEST can only reach +XWayland windows. The packaged udev rule and uinput module must be active for +the logged-in user; restart the graphical session after changing that setup. + +`uur run` verifies a real Wayland frame and a running GameViewerService before +announcing readiness. Startup/helper failures are reported in the terminal; +details are in `${XDG_STATE_HOME:-$HOME/.local/state}/uur/session.log` and +`${XDG_DATA_HOME:-$HOME/.local/share}/uur/hook.log`. A missing tray icon alone +does not determine whether capture or input works. + +For niri and other compositors exposing `wlr-screencopy`, uur also offers +direct, shared-memory monitor capture. This path avoids portal/PipeWire/GBM +dependencies for video and is useful when a portal cannot produce frames: + +```bash +uur display outputs +uur display backend wayland --output DP-1 # Use the name printed above +uur run +``` + +Selecting `wayland` explicitly authorizes direct monitor capture for later +runs. It does not show a system screen-sharing dialog and does not activate +automatically after portal cancellation or failure. With one output, `--output` +can be omitted; multiple outputs require an explicit name. Automatic input +selection uses uinput in this mode. Run `uur display backend portal` to return +to portal-consented capture. Direct mode captures a monitor, not individual +windows or virtual portal sources; changes to its size require restarting +the session. + +The supervised native StatusNotifierItem supplies its own icon pixels and +DBusMenu to Noctalia, Plasma and other compatible panels. Right-click it for +Open UU Remote and Quit. It re-registers when the panel's watcher restarts; +it does not depend on Wine's legacy tray being visible. + ## Reading `uur doctor` - `portal ScreenCast`: required to capture a Wayland desktop. diff --git a/locales/en.yml b/locales/en.yml index 5e27656..e55c265 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -4,9 +4,17 @@ doctor: no_portal_backend: "no xdg-desktop-portal backend found (Wayland capture/input unavailable)" present: "present" backend_x11: "X11 session: XTEST injection" - backend_wayland: "Wayland session: kernel uinput injection (portal path in development)" + backend_wayland: "Wayland session: kernel uinput injection" backend_portal: "Wayland session: standard RemoteDesktop portal" backend_none: "no graphical session detected" + backend_partial: "XWayland windows only; native Wayland desktop input requires portal or uinput" + backend_wayland_missing: "full desktop input unavailable; check RemoteDesktop authorization or /dev/uinput access" + client_incomplete: "client or server executable missing; run uur setup --repair" + service_registered: "registered; successful startup is checked by uur run" + service_missing: "missing service registration; run uur setup --repair" + webview_pending: "not installed; uur run will invoke the bundled WebView2 installer" + portal_capture_advertised: "source types advertised; authorization and real frames are checked by uur run" + portal_input_advertised: "keyboard and pointer advertised; session authorization is checked by uur run" uinput_module: "device present but kernel module not loaded (install the packaged udev rule + modules-load entry, then reboot)" uinput_permission: "not writable by this user (needs the uur udev uaccess rule or the input group)" uinput_missing: "/dev/uinput missing from this kernel" @@ -16,12 +24,13 @@ doctor: launcher_missing: "Win64 Quick Launch proxy missing; reinstall uur" xdg_launcher_missing: "install GLib's gio or gtk-launch" wallpaper_missing: "not detected; set UUR_WALLPAPER to an image path" - footer: "Everything above is advisory. Run `uur setup` to provision the managed client." + footer: "This report checks installation files and advertised capabilities. uur run verifies the input session, Wayland frames, and Windows service startup. Use uur setup --repair to retry Wine initialization after an interrupted installation." input: portal_unavailable: "Wayland portal input is not available in this session" no_display: "no graphical session detected (DISPLAY and WAYLAND_DISPLAY are unset)" - uinput_unavailable: "uinput not writable — falling back to XTEST (XWayland scope only; load the uinput module or add the udev rule for full coverage)" + uinput_unavailable: "kernel uinput injection unavailable" + wayland_no_full_input: "Wayland desktop input requires a working RemoteDesktop portal or writable /dev/uinput. Check the packaged udev rule and uinput module. Explicit xtest is limited to XWayland windows." bridge: listening: "input bridge listening on 127.0.0.1:%{port}" @@ -42,6 +51,9 @@ upstream: not_provisioned: "no provisioned client found; run `uur setup`" capture: + direct_enabled: "Direct Wayland monitor capture explicitly enabled; it uses uinput and does not show a portal consent dialog. Use uur display backend portal to restore portal capture." + portal_enabled: "Portal-consented capture enabled" + direct_started: "direct Wayland monitor capture started" session_ready: "portal session ready (video node %{node}); streaming to the private runtime transport" helper_failed: "the capture helper exited with an error" @@ -56,6 +68,10 @@ session: quick_launch_ready: "%{count} Linux applications exported to UU Quick Launch" audio_backend: "Wine audio backend: %{backend}" wine_dpi: "Wine system DPI set from Xft.dpi: %{dpi}" + waiting_capture: "waiting for the first Wayland capture frame; select a monitor in the portal dialog" + waiting_direct_capture: "waiting for the first direct Wayland monitor frame" + capture_not_ready: "No Wayland frames arrived within 120 seconds. Check the ScreenCast portal and PipeWire; select an actual monitor rather than an unassigned dynamic cast target. See the session log." + service_failed: "GameViewerService did not start. Run uur setup --repair and inspect ~/.local/state/uur/session.log and ~/.local/share/uur/hook.log." setup: eula_prompt: "The official UU Remote client will be downloaded from NetEase and is governed by their EULA: %{url}\nRe-run with --accept-eula to continue." @@ -65,10 +81,34 @@ setup: downloading: "downloading the official installer from %{url}" download_failed: "the official installer download failed" initializing_prefix: "initializing the managed Wine prefix" + prefix_failed: "Wine prefix initialization failed (%{status}); run uur setup --repair after resolving the Wine error" + repaired: "Wine prefix updated and client installation verified at %{path}" + install_failed: "The official installer failed or was cancelled (%{status}); installation is incomplete. Retry with uur setup --repair." + client_incomplete: "The installer did not provide both GameViewer.exe and GameViewerServer.exe; retry with uur setup --repair" + service_incomplete: "GameViewerService has no valid registered executable; run uur setup --repair" installing_client: "installing the official client (silent mode)" silent_install_unavailable: "the installer ignored silent mode; complete its window manually if it opened" done: "provisioned into %{path}" +tray: + title: "UU Remote" + tooltip: "UU Remote for Linux" + open: "Open UU Remote" + quit: "Quit" + registered: "native desktop tray registered" + +uninstall: + no_root: "Run uur uninstall as the desktop user, without sudo. Remove the system package separately with its package manager." + plan: "Removal plan (directories include their contents):" + purge_warning: "This permanently deletes the managed client, login/account data, Wine environment, installer cache, configuration and logs." + keep_data: "Client/account data, configuration and logs will be kept. Use --purge to remove them too." + package_hint: "System package files and shared dependencies are left to the package manager. On Arch, run sudo pacman -Rns uur after this command." + dry_run: "Preview only; no processes were stopped and no files were changed." + confirm_required: "No terminal is available for confirmation. Review --dry-run, then pass --yes to confirm removal." + confirm: "Proceed with removal? [y/N]" + cancelled: "Cancelled; no files were changed." + done: "The selected user files and recognized source-installation files have been removed." + autostart: enabled: "login autostart enabled: %{path}" disabled: "login autostart disabled" diff --git a/locales/zh-CN.yml b/locales/zh-CN.yml index 0510c8e..a60294c 100644 --- a/locales/zh-CN.yml +++ b/locales/zh-CN.yml @@ -7,6 +7,14 @@ doctor: backend_wayland: "Wayland 会话:内核 uinput 注入" backend_portal: "Wayland 会话:标准 RemoteDesktop Portal" backend_none: "未检测到图形会话" + backend_partial: "仅能控制 XWayland 窗口;原生 Wayland 桌面输入需要 Portal 或 uinput" + backend_wayland_missing: "完整桌面输入不可用;请检查 RemoteDesktop 授权或 /dev/uinput 访问权限" + client_incomplete: "缺少客户端或服务端程序;请运行 uur setup --repair" + service_registered: "已注册;uur run 会检查实际启动结果" + service_missing: "缺少服务注册;请运行 uur setup --repair" + webview_pending: "尚未安装;uur run 会调用客户端自带的 WebView2 安装器" + portal_capture_advertised: "已提供源类型;uur run 会检查授权和实际采集帧" + portal_input_advertised: "已提供键盘和指针类型;uur run 会检查实际会话授权" uinput_module: "设备存在但内核模块未加载(安装包内附的 udev 规则与 modules-load 条目,然后重启)" uinput_permission: "当前用户不可写(需要 uur 的 uaccess udev 规则或 input 组)" uinput_missing: "此内核没有 /dev/uinput" @@ -16,12 +24,13 @@ doctor: launcher_missing: "缺少 Win64 快速启动代理;请重新安装 uur" xdg_launcher_missing: "请安装 GLib 的 gio 或 gtk-launch" wallpaper_missing: "未检测到;可将 UUR_WALLPAPER 设为图片路径" - footer: "以上均为提示性检查。运行 `uur setup` 安装受管客户端。" + footer: "此报告检查安装文件与系统声明的能力。uur run 会验证输入会话、Wayland 采集帧和 Windows 服务启动。安装中断后可运行 uur setup --repair 重试 Wine 初始化。" input: portal_unavailable: "当前会话中 Wayland Portal 输入不可用" no_display: "未检测到图形会话(DISPLAY 与 WAYLAND_DISPLAY 均未设置)" - uinput_unavailable: "uinput 不可写 —— 回退到 XTEST(仅 XWayland 范围;请加载 uinput 模块或安装 udev 规则以获得完整覆盖)" + uinput_unavailable: "内核 uinput 输入不可用" + wayland_no_full_input: "Wayland 桌面输入需要可用的 RemoteDesktop Portal 或可写的 /dev/uinput。请检查安装包中的 udev 规则和 uinput 内核模块。显式选择 xtest 只能控制 XWayland 窗口。" bridge: listening: "输入桥监听于 127.0.0.1:%{port}" @@ -44,6 +53,10 @@ session: quick_launch_ready: "已向 UU 快速启动导出 %{count} 个 Linux 应用" audio_backend: "Wine 音频后端:%{backend}" wine_dpi: "已根据 Xft.dpi 设置 Wine 系统 DPI:%{dpi}" + waiting_capture: "正在等待首个 Wayland 采集帧;请在 Portal 对话框中选择监视器" + waiting_direct_capture: "正在等待原生 Wayland 显示器采集的首帧" + capture_not_ready: "120 秒内未收到 Wayland 采集帧。请检查 ScreenCast Portal 和 PipeWire,选择实际监视器而非尚未指定目标的动态投屏源,并查看会话日志。" + service_failed: "GameViewerService 未能启动。请运行 uur setup --repair,并检查 ~/.local/state/uur/session.log 和 ~/.local/share/uur/hook.log。" upstream: unreachable: "无法访问网易官方发布接口" @@ -54,6 +67,9 @@ upstream: not_provisioned: "尚未安装受管客户端;请运行 `uur setup`" capture: + direct_enabled: "已明确启用原生 Wayland 显示器采集,输入使用 uinput,不再弹出 Portal 选屏授权框。运行 uur display backend portal 可恢复 Portal 采集。" + portal_enabled: "已启用 Portal 授权采集" + direct_started: "已启动原生 Wayland 显示器采集" session_ready: "Portal 会话已建立(视频节点 %{node});正在写入私有运行时传输" helper_failed: "捕获助手异常退出" @@ -65,10 +81,34 @@ setup: downloading: "正在从 %{url} 下载官方安装包" download_failed: "官方安装包下载失败" initializing_prefix: "正在初始化受管 Wine 前缀" + prefix_failed: "Wine 前缀初始化失败(%{status});解决 Wine 错误后可运行 uur setup --repair 重试" + repaired: "已更新 Wine 前缀,并确认 %{path} 中的客户端安装完整" + install_failed: "官方安装器失败或被取消(%{status}),安装尚未完成。可运行 uur setup --repair 重试。" + client_incomplete: "安装器未提供完整的 GameViewer.exe 与 GameViewerServer.exe;请运行 uur setup --repair 重试" + service_incomplete: "GameViewerService 未注册有效的服务程序;请运行 uur setup --repair" installing_client: "正在安装官方客户端(静默模式)" silent_install_unavailable: "安装包忽略静默模式;若弹出窗口请手动完成安装" done: "已安装至 %{path}" +tray: + title: "UU 远程" + tooltip: "UU 远程 Linux 客户端" + open: "打开 UU 远程" + quit: "退出" + registered: "已注册原生桌面托盘" + +uninstall: + no_root: "请以桌面用户身份运行 uur uninstall,不要加 sudo;系统安装包另用包管理器卸载。" + plan: "将删除以下路径(目录包含其内部文件):" + purge_warning: "这会永久删除受管客户端、登录与账号数据、Wine 环境、安装包缓存、配置和日志。" + keep_data: "保留客户端、账号数据、配置和日志;加 --purge 可一并清除。" + package_hint: "系统安装文件和共享依赖由包管理器处理。在 Arch 上,请在此命令完成后执行 sudo pacman -Rns uur。" + dry_run: "仅预览,未停止进程,也未修改文件。" + confirm_required: "当前没有用于确认的终端。请先查看 --dry-run,再用 --yes 确认卸载。" + confirm: "确认删除吗?[y/N]" + cancelled: "已取消,未修改文件。" + done: "所选用户文件和可识别的源码安装文件已清除。" + autostart: enabled: "已启用登录自启动:%{path}" disabled: "已禁用登录自启动" diff --git a/nix/package.nix b/nix/package.nix index b84733e..bbb6181 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -7,6 +7,8 @@ makeWrapper, bash, pipewire, + wayland, + wayland-scanner, pulseaudio, curl, glib, @@ -34,8 +36,9 @@ rustPlatform.buildRustPackage { windowsCC windowsBinutils bash + wayland-scanner ]; - buildInputs = [ pipewire ]; + buildInputs = [ pipewire wayland ]; CC = "${stdenv.cc}/bin/cc"; UUR_BUILD_SHELL = runtimeShell; diff --git a/packaging/alpine/APKBUILD b/packaging/alpine/APKBUILD index fda68a7..028797a 100644 --- a/packaging/alpine/APKBUILD +++ b/packaging/alpine/APKBUILD @@ -7,8 +7,8 @@ pkgdesc="Native Linux companion for NetEase UU Remote" url="https://github.com/panxuc/uur" arch="x86_64" license="MIT" -depends="bash wine curl glib pulseaudio-utils xdg-desktop-portal" -makedepends="cargo rust gcc musl-dev pipewire-dev pkgconf mingw-w64-gcc mingw-w64-binutils" +depends="bash wine curl glib wayland-libs-client pulseaudio-utils xdg-desktop-portal" +makedepends="cargo rust gcc musl-dev pipewire-dev wayland-dev pkgconf mingw-w64-gcc mingw-w64-binutils" options="!check" source="$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz" builddir="$srcdir/$pkgname-$pkgver" diff --git a/packaging/alpine/Dockerfile b/packaging/alpine/Dockerfile index a9d2c8d..b1a229c 100644 --- a/packaging/alpine/Dockerfile +++ b/packaging/alpine/Dockerfile @@ -1,7 +1,7 @@ FROM alpine:edge AS build RUN apk add --no-cache \ - bash cargo rust gcc musl-dev pipewire-dev pkgconf \ + bash cargo rust gcc musl-dev pipewire-dev wayland-dev pkgconf \ mingw-w64-gcc mingw-w64-binutils WORKDIR /src @@ -16,6 +16,6 @@ RUN --mount=type=cache,target=/root/.cargo/registry \ FROM alpine:edge RUN apk add --no-cache \ - bash ca-certificates curl glib pipewire-libs pulseaudio-utils wine xdg-desktop-portal + bash ca-certificates curl glib pipewire-libs wayland-libs-client pulseaudio-utils wine xdg-desktop-portal COPY --from=build /out/ / ENTRYPOINT ["/usr/bin/uur"] diff --git a/packaging/arch/PKGBUILD.in b/packaging/arch/PKGBUILD.in index c599c40..43ba16f 100644 --- a/packaging/arch/PKGBUILD.in +++ b/packaging/arch/PKGBUILD.in @@ -5,7 +5,7 @@ pkgdesc="Native Linux companion for NetEase UU Remote" arch=('x86_64') url="https://github.com/panxuc/uur" license=('MIT') -depends=('glibc' 'gcc-libs' 'glib2' 'wine' 'curl' 'pipewire' 'xdg-desktop-portal') +depends=('glibc' 'gcc-libs' 'glib2' 'wine' 'curl' 'pipewire' 'wayland' 'xdg-desktop-portal') optdepends=( 'xdg-desktop-portal-gnome: GNOME-compatible Wayland capture and input' 'xdg-desktop-portal-kde: Plasma Wayland capture and input' diff --git a/packaging/aur/.SRCINFO b/packaging/aur/.SRCINFO index 5103761..d99ba31 100644 --- a/packaging/aur/.SRCINFO +++ b/packaging/aur/.SRCINFO @@ -9,6 +9,7 @@ pkgbase = uur makedepends = cargo makedepends = gcc makedepends = pkgconf + makedepends = wayland makedepends = mingw-w64-gcc makedepends = mingw-w64-binutils depends = glibc @@ -17,6 +18,7 @@ pkgbase = uur depends = wine depends = curl depends = pipewire + depends = wayland depends = xdg-desktop-portal optdepends = osslsigncode: Authenticode verification of official updater downloads optdepends = xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input diff --git a/packaging/aur/PKGBUILD b/packaging/aur/PKGBUILD index df1e676..6754814 100644 --- a/packaging/aur/PKGBUILD +++ b/packaging/aur/PKGBUILD @@ -21,9 +21,10 @@ depends=( 'wine' 'curl' 'pipewire' + 'wayland' 'xdg-desktop-portal' ) -makedepends=('cargo' 'gcc' 'pkgconf' 'mingw-w64-gcc' 'mingw-w64-binutils') +makedepends=('cargo' 'gcc' 'pkgconf' 'wayland' 'mingw-w64-gcc' 'mingw-w64-binutils') optdepends=( 'osslsigncode: Authenticode verification of official updater downloads' 'xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input' diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml index 4d2b4bd..aca3f8a 100644 --- a/packaging/nfpm.yaml +++ b/packaging/nfpm.yaml @@ -24,6 +24,7 @@ overrides: - wine - curl - libpipewire-0.3-0 + - libwayland-client0 - xdg-desktop-portal recommends: - xdg-desktop-portal-gnome | xdg-desktop-portal-kde | xdg-desktop-portal-wlr @@ -40,6 +41,7 @@ overrides: - wine - curl - pipewire-libs + - wayland-libs - xdg-desktop-portal recommends: - ethtool diff --git a/packaging/post-install-message b/packaging/post-install-message index a73e1b1..65c6984 100755 --- a/packaging/post-install-message +++ b/packaging/post-install-message @@ -12,4 +12,5 @@ printf '%s\n' \ 'The setup command downloads the official client from NetEase.' \ 'The --accept-eula flag records that you accepted the upstream EULA.' \ 'Run setup without that flag only when you want to read the EULA URL first.' +printf 'To remove user data completely, run %s uninstall --purge before removing the system package.\n' "$command_name" printf '\n' diff --git a/packaging/stage.sh b/packaging/stage.sh index e8f4189..55457d1 100755 --- a/packaging/stage.sh +++ b/packaging/stage.sh @@ -10,6 +10,8 @@ install -Dm0755 "$uur_binary" \ "$destination$prefix/bin/uur" install -Dm0755 "$project_root/capture/uur-pw-capture" \ "$destination$prefix/lib/uur/uur-pw-capture" +install -Dm0755 "$project_root/capture/uur-wl-capture" \ + "$destination$prefix/lib/uur/uur-wl-capture" install -Dm0755 "$project_root/packaging/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 @@ -30,3 +32,5 @@ install -Dm0644 "$project_root/LICENSE" \ "$destination$prefix/share/licenses/uur/LICENSE" install -Dm0644 "$project_root/NOTICE" \ "$destination$prefix/share/licenses/uur/NOTICE" +install -Dm0644 "$project_root/capture/wlr-screencopy-unstable-v1.xml" \ + "$destination$prefix/share/licenses/uur/wlr-screencopy-unstable-v1.xml" diff --git a/scripts/install-user.sh b/scripts/install-user.sh index b35997b..5b0a2d1 100755 --- a/scripts/install-user.sh +++ b/scripts/install-user.sh @@ -7,39 +7,64 @@ set -euo pipefail root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) readonly root prefix="${UUR_INSTALL_PREFIX:-$HOME/.local}" +data_home="${XDG_DATA_HOME:-$HOME/.local/share}" +[[ "$prefix" = /* && "$data_home" = /* && "$prefix" != *$'\n'* && "$data_home" != *$'\n'* ]] || { + printf 'install prefix and XDG_DATA_HOME must be absolute paths without newlines\n' >&2 + exit 1 +} [[ -x "$root/target/release/uur" ]] || { printf 'missing %s — run: cargo build --release\n' \ "$root/target/release/uur" >&2 exit 1 } -[[ -f "$root/build/hook/wevtapi.dll" && -f "$root/build/hook/uur-hook.dll" ]] || { - printf 'missing hook DLLs — run: ./hook/build.sh\n' >&2 - exit 1 -} -[[ -f "$root/capture/uur-pw-capture" ]] || { +components=(wevtapi.dll uur-hook.dll wtsapi32.dll winlogon.exe uur-terminal-proxy.exe uur-mux-proxy.exe uur-launch-proxy.exe) +for component in "${components[@]}"; do + [[ -f "$root/build/hook/$component" ]] || { + printf 'missing hook component %s — run: ./hook/build.sh\n' "$component" >&2 + exit 1 + } +done +[[ -f "$root/capture/uur-pw-capture" && -f "$root/capture/uur-wl-capture" ]] || { printf 'missing capture helper — run: ./capture/build.sh\n' >&2 exit 1 } install -Dm0755 "$root/target/release/uur" "$prefix/bin/uur" -for helper in uur-pw-capture; do +for helper in uur-pw-capture uur-wl-capture; do install -Dm0755 "$root/capture/$helper" "$prefix/lib/uur/$helper" done -for dll in wevtapi.dll uur-hook.dll winlogon.exe uur-terminal-proxy.exe; do +for dll in "${components[@]}"; do install -Dm0644 "$root/build/hook/$dll" "$prefix/lib/uur/hook/$dll" done # Menu entry: absolute Exec path so the user's PATH is irrelevant. install -Dm0644 "$root/packaging/uur.desktop" \ "$prefix/share/applications/uur.desktop" -sed -i "s|^Exec=.*|Exec=$prefix/bin/uur run|; s|^TryExec=.*|TryExec=$prefix/bin/uur|" \ +# Escape Desktop Entry quoted arguments, then escape the sed replacement. +desktop_binary="$prefix/bin/uur" +desktop_binary="${desktop_binary//\\/\\\\}" +desktop_binary="${desktop_binary//\"/\\\"}" +desktop_binary="${desktop_binary//\$/\\\$}" +desktop_binary="${desktop_binary//\`/\\\`}" +sed_binary="${desktop_binary//\\/\\\\}" +sed_binary="${sed_binary//&/\\&}" +sed_binary="${sed_binary//|/\\|}" +try_binary="$prefix/bin/uur" +try_binary="${try_binary//\\/\\\\}" +try_binary="${try_binary//&/\\&}" +try_binary="${try_binary//|/\\|}" +sed -i "s|^Exec=uur |Exec=\"$sed_binary\" |; s|^TryExec=uur$|TryExec=$try_binary|" \ "$prefix/share/applications/uur.desktop" if [[ -f "$root/packaging/uur-icon.png" ]]; then install -Dm0644 "$root/packaging/uur-icon.png" \ "$prefix/share/icons/hicolor/256x256/apps/uur.png" fi +# Only the source installer writes this receipt. Package managers own their +# system files; uur uninstall must not remove those behind their backs. +printf 'uur-user-install-v1\n%s/uur\n' "${data_home%/}" > "$prefix/lib/uur/user-install" + printf 'installed:\n %s/bin/uur\n %s/lib/uur/\n %s/share/applications/uur.desktop\n' \ "$prefix" "$prefix" "$prefix" UUR_COMMAND="$prefix/bin/uur" "$root/packaging/post-install-message" diff --git a/src/autostart.rs b/src/autostart.rs index 3b008ee..fc0ffe7 100644 --- a/src/autostart.rs +++ b/src/autostart.rs @@ -9,10 +9,11 @@ pub fn enable() -> Result<()> { std::fs::create_dir_all(parent)?; let executable = std::env::current_exe().context("resolving uur executable")?; let exec = desktop_exec_argument(&executable.to_string_lossy()); + let prefix = crate::config::data_dir()?.join("wine"); std::fs::write( &path, format!( - "[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\n" + "[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\nX-UUR-Managed=true\nX-UUR-Prefix={}\n", prefix.display() ), )?; println!( diff --git a/src/bridge.rs b/src/bridge.rs index 1fbfc4d..905a72a 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -133,8 +133,16 @@ pub fn print_pointer() -> Result<()> { /// input events without holding the backend lock while waiting for records. pub fn serve() -> Result<()> { let config = Config::load()?; - let preferred = + let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or_else(|_| config.input_backend.clone()); + if config.capture_backend == "wayland" { + if preferred == "auto" { + preferred = "uinput".into(); + } + if preferred == "portal" { + anyhow::bail!("direct Wayland capture uses uinput; choose UUR_INPUT_BACKEND=uinput or return to portal capture"); + } + } let selected = input::select(&preferred)?; if let Some(path) = std::env::var_os("UUR_BACKEND_STATUS") { std::fs::write(path, selected.name()).context("writing backend status")?; diff --git a/src/capture.rs b/src/capture.rs index ac1f3be..3819592 100644 --- a/src/capture.rs +++ b/src/capture.rs @@ -13,25 +13,123 @@ //! a headless remote host. use anyhow::{anyhow, Context, Result}; +use std::io::Read; use std::os::fd::AsRawFd; use std::os::fd::OwnedFd; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Child, Command}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; use crate::config::Config; /// Run the capture path until interrupted. +pub fn run_standalone() -> Result<()> { + // Public capture uses the same lifecycle lock as run/setup so stop and + // uninstall can also shut down a diagnostic ScreenCast session. Internal + // capture already runs under the supervisor's lock. + let _session_lock = crate::session::acquire_session_lock()?; + run() +} + pub fn run() -> Result<()> { let mut config = Config::load()?; - let (pw_fd, node) = portal_session(&mut config)?; - println!("{}", t!("capture.session_ready", node = node)); - - let mut helper = spawn_helper(pw_fd, node)?; - let status = helper.wait().context("waiting for capture helper")?; - if !status.success() { - anyhow::bail!("{}", t!("capture.helper_failed")); + let stopping = Arc::new(AtomicBool::new(false)); + signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?; + if config.capture_backend == "wayland" { + if config.capture_source != "monitor" { + anyhow::bail!("direct Wayland capture requires a monitor source"); + } + let mut command = Command::new(find_helper("uur-wl-capture")?); + command.env("UUR_FRAME_PATH", frame_path()?); + if let Some(output) = &config.capture_output { + command.env("UUR_CAPTURE_OUTPUT", output); + } + let mut helper = CaptureHelper(command.spawn().context("starting direct Wayland capture")?); + println!("{}", t!("capture.direct_started")); + while !stopping.load(Ordering::Relaxed) { + if let Some(status) = helper.0.try_wait()? { + if !status.success() { + anyhow::bail!("direct Wayland capture failed ({status})"); + } + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + return Ok(()); } - Ok(()) + if config.capture_backend != "portal" { + anyhow::bail!("unknown capture backend {:?}", config.capture_backend); + } + let runtime = tokio::runtime::Runtime::new().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)?); + loop { + 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")); + } + return Ok(()); + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + }) +} + +async fn wait_for_stop(stopping: &AtomicBool) { + while !stopping.load(Ordering::Relaxed) { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } +} + +struct CaptureHelper(Child); + +impl Drop for CaptureHelper { + fn drop(&mut self) { + if self.0.try_wait().ok().flatten().is_some() { + return; + } + unsafe { + libc::kill(self.0.id() as i32, libc::SIGTERM); + } + for _ in 0..100 { + if self.0.try_wait().ok().flatten().is_some() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +pub(crate) fn has_frame(path: &Path) -> bool { + let mut header = [0u8; 64]; + let Ok(mut file) = std::fs::File::open(path) else { + return false; + }; + if file.read_exact(&mut header).is_err() { + return false; + } + let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap()); + field(0) == 0x4652_5555 + && field(4) == 1 + && field(8) > 0 + && field(12) > 0 + && field(16) >= field(8).saturating_mul(4) + && field(20) == 1 + && u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0 } /// Start the native PipeWire consumer with a portal-owned descriptor. The @@ -51,7 +149,7 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result { } } - let helper = find_helper()?; + let helper = find_helper("uur-pw-capture")?; let mut command = Command::new(&helper); command .env("UUR_PW_FD", raw.to_string()) @@ -78,32 +176,34 @@ fn frame_path() -> Result { /// token, monitor changed, compositor restart) fall back to one /// interactive attempt and store the fresh token. #[allow(clippy::type_complexity)] -fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> { +async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> { let saved_token = config.capture_restore_token.clone(); - let runtime = tokio::runtime::Runtime::new().context("creating tokio runtime")?; - runtime.block_on(async move { - let screencast = ashpd::desktop::screencast::Screencast::new() - .await - .context("connecting to the ScreenCast portal")?; + let screencast = ashpd::desktop::screencast::Screencast::new() + .await + .context("connecting to the ScreenCast portal")?; - let mut last_error = None; - let source = source_type(&config.capture_source); - for token in [saved_token.clone(), 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; - config.store().context("storing the new restore token")?; - } - return Ok((fd, node)); - } - Err(error) => { - last_error = Some(error); + let mut last_error = None; + let source = source_type(&config.capture_source); + for token in saved_token + .clone() + .map(Some) + .into_iter() + .chain(std::iter::once(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; + config.store().context("storing the new restore token")?; } + return Ok((fd, node)); + } + Err(error) => { + last_error = Some(error); } } - Err(last_error.unwrap_or_else(|| anyhow!("portal session failed"))) - }) + } + Err(last_error.unwrap_or_else(|| anyhow!("portal session failed"))) } /// One full portal handshake. Returns the PipeWire fd, the video node id @@ -127,7 +227,8 @@ async fn negotiate( restore_token, PersistMode::ExplicitlyRevoked, ) - .await?; + .await? + .response()?; let response = screencast.start(&session, None).await?; let streams_response = response.response()?; @@ -152,28 +253,37 @@ pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType } } -fn find_helper() -> Result { +pub fn list_wayland_outputs() -> Result<()> { + let status = Command::new(find_helper("uur-wl-capture")?) + .arg("--list-outputs") + .status()?; + anyhow::ensure!(status.success(), "could not enumerate Wayland outputs"); + Ok(()) +} + +fn find_helper(name: &str) -> Result { let mut candidates = vec![ - PathBuf::from("/usr/lib/uur/uur-pw-capture"), - PathBuf::from("/usr/local/lib/uur/uur-pw-capture"), + 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/uur-pw-capture")); + candidates.push(PathBuf::from(home).join(".local/lib/uur").join(name)); } if let Ok(exe) = std::env::current_exe() { // dev checkout: target/debug/uur -> capture/uur-pw-capture if let Some(dir) = exe.parent() { - candidates.push(dir.join("../lib/uur/uur-pw-capture")); - candidates.push(dir.join("../../capture/uur-pw-capture")); - candidates.push(dir.join("uur-pw-capture")); + candidates.push(dir.join("../lib/uur").join(name)); + candidates.push(dir.join("../../capture").join(name)); + candidates.push(dir.join(name)); } } if let Ok(cwd) = std::env::current_dir() { - candidates.push(cwd.join("capture/uur-pw-capture")); + candidates.push(cwd.join("capture").join(name)); } - candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| { - anyhow!("capture helper uur-pw-capture not found (build with capture/build.sh)") - }) + candidates + .into_iter() + .find(|p| p.is_file()) + .ok_or_else(|| anyhow!("capture helper {name} not found (build with capture/build.sh)")) } #[cfg(test)] diff --git a/src/config.rs b/src/config.rs index f8b4d90..7ce24a8 100644 --- a/src/config.rs +++ b/src/config.rs @@ -13,7 +13,7 @@ pub struct Config { pub bridge_port: u16, /// Random per-install token the hook must present on HELLO. pub bridge_token: String, - /// Preferred input backend: "auto" | "xtest" | "portal". + /// Preferred input backend: "auto" | "xtest" | "portal" | "uinput". pub input_backend: String, /// Release channel pinned for provisioning. pub pinned_version: Option, @@ -24,6 +24,10 @@ pub struct Config { pub remote_desktop_restore_token: Option, /// Portal source type: monitor, window, or virtual. pub capture_source: String, + /// "portal" uses system consent; "wayland" is explicitly enabled direct monitor capture. + pub capture_backend: String, + /// Named Wayland output for direct capture; a single-output session needs no name. + pub capture_output: Option, } impl Default for Config { @@ -37,6 +41,8 @@ impl Default for Config { capture_restore_token: None, remote_desktop_restore_token: None, capture_source: "monitor".into(), + capture_backend: "portal".into(), + capture_output: None, } } } diff --git a/src/doctor.rs b/src/doctor.rs index f794a81..9358914 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -130,13 +130,16 @@ fn portal_capabilities() -> (bool, bool, String) { runtime.block_on(async { let (capture, sources) = match ashpd::desktop::screencast::Screencast::new().await { Ok(portal) => match portal.available_source_types().await { - Ok(types) => (true, format!("{types:?}")), + Ok(types) => (!types.is_empty(), format!("{types:?}")), Err(_) => (false, "unavailable".into()), }, Err(_) => (false, "unavailable".into()), }; let input = match ashpd::desktop::remote_desktop::RemoteDesktop::new().await { - Ok(portal) => portal.available_device_types().await.is_ok(), + Ok(portal) => portal.available_device_types().await.is_ok_and(|types| { + types.contains(ashpd::desktop::remote_desktop::DeviceType::Keyboard) + && types.contains(ashpd::desktop::remote_desktop::DeviceType::Pointer) + }), Err(_) => false, }; (capture, input, sources) @@ -176,6 +179,32 @@ pub fn report() -> Result<()> { }; line(ok(missing_wine), "wine", &wine_detail); + let prefix = crate::config::data_dir()?.join("wine"); + line( + ok(!crate::wine::prefix_initialized(&prefix)), + "managed Wine prefix", + &prefix.display().to_string(), + ); + let client = crate::wine::find_client_dir(&prefix); + let client_detail = client + .as_ref() + .map(|path| path.display().to_string()) + .unwrap_or_else(|| t!("doctor.client_incomplete").to_string()); + line(ok(client.is_none()), "UU client and server", &client_detail); + let service = crate::wine::client_service_registered(&prefix); + let service_detail = if service { + t!("doctor.service_registered").to_string() + } else { + t!("doctor.service_missing").to_string() + }; + line(ok(!service), "GameViewerService", &service_detail); + let webview_detail = if crate::wine::webview2_installed(&prefix) { + t!("doctor.present").to_string() + } else { + t!("doctor.webview_pending").to_string() + }; + line("info", "WebView2 runtime", &webview_detail); + let backends = portal_backends(); let has_portal_impl = !backends.is_empty(); let portal_detail = if backends.is_empty() { @@ -187,7 +216,7 @@ pub fn report() -> Result<()> { let (portal_capture, portal_input, portal_sources) = portal_capabilities(); let portal_capture_detail = if portal_capture { - t!("doctor.present").to_string() + t!("doctor.portal_capture_advertised").to_string() } else { t!("doctor.portal_capture_missing").to_string() }; @@ -198,7 +227,7 @@ pub fn report() -> Result<()> { ); line("info", "portal source types", &portal_sources); let portal_input_detail = if portal_input { - t!("doctor.present").to_string() + t!("doctor.portal_input_advertised").to_string() } else { t!("doctor.portal_input_missing").to_string() }; @@ -313,19 +342,62 @@ pub fn report() -> Result<()> { let uinput_missing = uinput_detail != t!("doctor.present"); line(ok(uinput_missing), "uinput (/dev/uinput)", &uinput_detail); - // Mirror the real auto policy in input::select. + // Report the configured policy; portal properties do not validate that + // the compositor can successfully create an authorized session. let session_type = std::env::var("XDG_SESSION_TYPE").unwrap_or_default(); - let (backend, backend_note) = if session_type == "wayland" && portal_input { - ("portal", t!("doctor.backend_portal").to_string()) - } else if session_type == "wayland" && !uinput_missing { - ("uinput", t!("doctor.backend_wayland").to_string()) - } else if std::env::var("DISPLAY").is_ok() { - ("xtest", t!("doctor.backend_x11").to_string()) - } else { - ("none", t!("doctor.backend_none").to_string()) - }; + let on_wayland = session_type == "wayland" || std::env::var_os("WAYLAND_DISPLAY").is_some(); + let configured = crate::config::Config::load()?; line( "info", + "capture backend", + &format!( + "{} ({})", + configured.capture_backend, + configured + .capture_output + .as_deref() + .unwrap_or("selected/default output") + ), + ); + let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or(configured.input_backend); + if configured.capture_backend == "wayland" && preferred == "auto" { + preferred = "uinput".into(); + } + let (status, backend, backend_note) = match preferred.as_str() { + "portal" => ( + ok(!portal_input), + "portal", + t!("doctor.backend_portal").to_string(), + ), + "uinput" => ( + ok(uinput_missing), + "uinput", + t!("doctor.backend_wayland").to_string(), + ), + "xtest" if on_wayland => ("WARN", "xtest", t!("doctor.backend_partial").to_string()), + "xtest" => ( + ok(std::env::var_os("DISPLAY").is_none()), + "xtest", + t!("doctor.backend_x11").to_string(), + ), + "auto" if on_wayland && portal_input => { + ("info", "portal", t!("doctor.backend_portal").to_string()) + } + "auto" if on_wayland && !uinput_missing => { + ("info", "uinput", t!("doctor.backend_wayland").to_string()) + } + "auto" if on_wayland => ( + "MISS", + "none", + t!("doctor.backend_wayland_missing").to_string(), + ), + "auto" if std::env::var_os("DISPLAY").is_some() => { + ("info", "xtest", t!("doctor.backend_x11").to_string()) + } + _ => ("MISS", "none", t!("doctor.backend_none").to_string()), + }; + line( + status, "input backend", &format!("{backend} ({backend_note})"), ); diff --git a/src/input/mod.rs b/src/input/mod.rs index 44c049e..7a2aa33 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -24,7 +24,11 @@ pub trait InputBackend: Send { /// kernel-level uinput device when the compositor only provides ScreenCast. /// - X11 sessions use XTEST, which needs no extra privileges. pub fn select(preferred: &str) -> Result> { - let on_wayland = std::env::var("WAYLAND_DISPLAY").is_ok(); + let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland"); + if !matches!(preferred, "auto" | "portal" | "uinput" | "xtest") { + anyhow::bail!("unknown input backend {preferred:?}; use auto, portal, uinput, or xtest"); + } if preferred == "portal" || (preferred == "auto" && on_wayland) { match portal::PortalBackend::connect() { @@ -39,10 +43,12 @@ pub fn select(preferred: &str) -> Result> { Err(error) if preferred == "uinput" => return Err(error), Err(error) => { eprintln!("{}: {error}", t!("input.uinput_unavailable")); - // fall through to XTEST: partial reachability beats nothing } } } + if on_wayland && preferred == "auto" { + anyhow::bail!("{}", t!("input.wayland_no_full_input")); + } if std::env::var("DISPLAY").is_ok() { return Ok(Box::new(xtest::XtestBackend::connect()?)); } diff --git a/src/input/uinput.rs b/src/input/uinput.rs index 61b31af..7e6e43e 100644 --- a/src/input/uinput.rs +++ b/src/input/uinput.rs @@ -12,7 +12,7 @@ const UI_SET_EVBIT: libc::Ioctl = 0x4004_5564_u64 as libc::Ioctl; const UI_SET_KEYBIT: libc::Ioctl = 0x4004_5565_u64 as libc::Ioctl; const UI_SET_RELBIT: libc::Ioctl = 0x4004_5566_u64 as libc::Ioctl; const UI_SET_ABSBIT: libc::Ioctl = 0x4004_5567_u64 as libc::Ioctl; -// struct uinput_setup = name[80] + input_id(8) + ff_effects_max(4) = 92 bytes +// struct uinput_setup = input_id(8) + name[80] + ff_effects_max(4) = 92 bytes const UI_DEV_SETUP: libc::Ioctl = 0x405C_5503_u64 as libc::Ioctl; // struct uinput_abs_setup = u16 code + input_absinfo(24) = 28 bytes const UI_ABS_SETUP: libc::Ioctl = 0x401C_5504_u64 as libc::Ioctl; @@ -40,6 +40,8 @@ const BTN_MIDDLE: u16 = 0x112; const BTN_SIDE: u16 = 0x116; const BTN_EXTRA: u16 = 0x117; const BTN_TOOL_PEN: u16 = 0x140; +const BTN_TOUCH: u16 = 0x14a; +const BTN_STYLUS: u16 = 0x14b; const BUS_VIRTUAL: u16 = 0x06; @@ -53,14 +55,14 @@ struct InputEvent { value: i32, } -/// struct uinput_setup: name[80] + input_id(4×u16) + ff_effects_max(u32). +/// Linux ABI: input_id(4×u16), then name[80], then ff_effects_max(u32). #[repr(C)] struct UinputSetup { - name: [u8; 80], bustype: u16, vendor: u16, product: u16, version: u16, + name: [u8; 80], ff_effects_max: u32, } @@ -142,7 +144,9 @@ impl UinputDevice { maximum, fuzz: 0, flat: 0, - resolution: 0, + // libinput requires physical axis resolution for tablets. A + // 65.535 mm virtual surface maps the full normalized range. + resolution: 1000, }; let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_ABS_SETUP, &setup) }; if rc < 0 { @@ -235,6 +239,8 @@ impl Devices { ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_ABS as u32)?; ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_SYN as u32)?; tablet.keybit(BTN_TOOL_PEN)?; + tablet.keybit(BTN_TOUCH)?; + tablet.keybit(BTN_STYLUS)?; tablet.absbit(ABS_X, 65535)?; tablet.absbit(ABS_Y, 65535)?; tablet.finish()?; diff --git a/src/main.rs b/src/main.rs index c73223a..6621b45 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,8 @@ mod protocol; mod proxy; mod session; mod terminal; +mod tray; +mod uninstall; mod upstream; mod video; mod wallpaper; @@ -46,6 +48,9 @@ enum Command { /// Accept the NetEase UU Remote EULA non-interactively. #[arg(long)] accept_eula: bool, + /// Update the existing Wine prefix, retry Wine components, and repair an incomplete client installation. + #[arg(long)] + repair: bool, }, /// Print the live environment report (sessions, wine, portals, backends). Doctor, @@ -57,6 +62,18 @@ enum Command { Run, /// Stop every uur-owned process and the managed Wine prefix. Stop, + /// Remove this user's integration and source installation; optionally erase all managed data. + Uninstall { + /// Delete the managed Wine prefix, account data, installer cache, configuration and logs. + #[arg(long)] + purge: bool, + /// Show the exact removal plan without stopping processes or changing files. + #[arg(long)] + dry_run: bool, + /// Confirm removal without an interactive prompt. + #[arg(long)] + yes: bool, + }, /// Manage optional XDG login autostart. Autostart { #[command(subcommand)] @@ -87,6 +104,9 @@ enum Command { /// Internal desktop suspend/idle inhibitor. Not part of the public CLI. #[command(hide = true, name = "__inhibit")] InternalInhibit, + /// Internal native desktop tray. Not part of the public CLI. + #[command(hide = true, name = "__tray")] + InternalTray, /// Internal authenticated XDG application launcher. #[command(hide = true, name = "__launcher")] InternalLauncher, @@ -138,6 +158,21 @@ enum DisplayAction { Status, /// Use a monitor, one window, or a portal-provided virtual display. Source { source: DisplaySource }, + /// Choose portal capture, or explicitly enable direct Wayland monitor capture. + Backend { + backend: CaptureBackend, + /// Name from `uur display outputs`; required if more than one output is present. + #[arg(long)] + output: Option, + }, + /// List native Wayland outputs without capturing their content. + Outputs, +} + +#[derive(Clone, ValueEnum)] +enum CaptureBackend { + Portal, + Wayland, } #[derive(Clone, ValueEnum)] @@ -165,12 +200,20 @@ fn main() -> Result<()> { i18n::init(); let cli = Cli::parse(); match cli.command { - Command::Setup { accept_eula } => wine::setup(accept_eula), + Command::Setup { + accept_eula, + repair, + } => wine::setup(accept_eula, repair), Command::Doctor => doctor::report(), Command::Pointer => bridge::print_pointer(), - Command::Capture => capture::run(), + Command::Capture => capture::run_standalone(), Command::Run => session::start(), Command::Stop => session::stop(), + Command::Uninstall { + purge, + dry_run, + yes, + } => uninstall::run(purge, dry_run, yes), Command::Autostart { action } => match action { AutostartAction::Enable => autostart::enable(), AutostartAction::Disable => autostart::disable(), @@ -182,12 +225,43 @@ fn main() -> Result<()> { WolAction::Disable { interface } => wol::configure(interface.as_deref(), false), }, Command::Display { action } => { + if matches!(action, DisplayAction::Outputs) { + return capture::list_wayland_outputs(); + } let mut config = config::Config::load()?; match action { DisplayAction::Status => { println!("{}", t!("display.status", source = config.capture_source)); + println!("capture backend: {}", config.capture_backend); + if let Some(output) = &config.capture_output { + println!("output: {output}"); + } Ok(()) } + DisplayAction::Backend { backend, output } => { + config.capture_backend = match backend { + CaptureBackend::Portal => "portal", + CaptureBackend::Wayland => "wayland", + } + .into(); + config.capture_output = output; + if config.capture_backend == "wayland" { + config.capture_source = "monitor".into(); + } + config.capture_restore_token = None; + config.remote_desktop_restore_token = None; + config.store()?; + println!( + "{}", + if config.capture_backend == "wayland" { + t!("capture.direct_enabled").to_string() + } else { + t!("capture.portal_enabled").to_string() + } + ); + Ok(()) + } + DisplayAction::Outputs => unreachable!(), DisplayAction::Source { source } => { config.capture_source = source.as_str().to_string(); config.capture_restore_token = None; @@ -203,6 +277,7 @@ fn main() -> Result<()> { Command::InternalTerminal => terminal::serve(), Command::InternalWallpaper => wallpaper::serve(), Command::InternalInhibit => inhibit::serve(), + Command::InternalTray => tray::serve(), Command::InternalLauncher => launcher::serve(), Command::Upstream { action: UpstreamAction::Check, diff --git a/src/session.rs b/src/session.rs index ae85f1a..7d554fb 100644 --- a/src/session.rs +++ b/src/session.rs @@ -251,8 +251,7 @@ fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command { } fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> { - let marker = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application"); - if marker.exists() { + if crate::wine::webview2_installed(prefix) { return Ok(()); } let bootstrapper = install_dir @@ -265,7 +264,7 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> { let status = webview2_install_command(prefix, &bootstrapper) .status() .context("running the WebView2 bootstrapper")?; - if !status.success() { + if !status.success() || !crate::wine::webview2_installed(prefix) { anyhow::bail!("{}", t!("session.webview_failed")); } Ok(()) @@ -274,7 +273,7 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> { /// Single-instance guard: an flock held for the lifetime of the session. /// A second click on the launcher exits with a clear message instead of /// fighting over the bridge port. -fn acquire_session_lock() -> Result { +pub(crate) fn acquire_session_lock() -> Result { use std::os::unix::io::AsRawFd; let state = std::env::var("XDG_STATE_HOME") .map(PathBuf::from) @@ -306,6 +305,7 @@ fn acquire_session_lock() -> Result { struct ManagedChild { child: Child, + name: String, terminated: bool, } @@ -326,10 +326,21 @@ impl ManagedChild { .with_context(|| format!("starting internal helper {argument}"))?; Ok(Self { child, + name: argument.to_string(), terminated: false, }) } + fn ensure_running(&mut self) -> Result<()> { + if let Some(status) = self.child.try_wait()? { + anyhow::bail!( + "helper {} exited ({status}); see $XDG_STATE_HOME/uur/session.log (normally ~/.local/state/uur/session.log)", + self.name + ); + } + Ok(()) + } + fn terminate(&mut self) { if self.terminated { return; @@ -392,6 +403,18 @@ impl SessionResources { let _ = std::fs::remove_file(path); } } + + fn check_required_helpers(&mut self) -> Result<()> { + for helper in &mut self.helpers { + if matches!( + helper.name.as_str(), + "__bridge" | "__capture" | "__terminal" | "__launcher" + ) { + helper.ensure_running()?; + } + } + Ok(()) + } } impl Drop for SessionResources { @@ -405,9 +428,15 @@ pub fn start() -> Result<()> { let _session_lock = acquire_session_lock()?; rotate_session_log(); let config = Config::load()?; + let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland"); let prefix = data_dir()?.join("wine"); let install_dir = crate::wine::find_client_dir(&prefix) - .context("client not provisioned; run `uur setup` first")?; + .context("client installation incomplete; run `uur setup --repair` first")?; + if !crate::wine::client_service_registered(&prefix) { + anyhow::bail!("{}", t!("setup.service_incomplete")); + } + let mut resources = SessionResources::new(prefix.clone()); if let Some(dpi) = xft_dpi() { match crate::wine::set_log_pixels(&prefix, dpi) { Ok(()) => println!("{}", t!("session.wine_dpi", dpi = dpi)), @@ -428,6 +457,11 @@ pub fn start() -> Result<()> { // Bridge configuration as a file inside the prefix: any process the // Wine service manager respawns reads it, env or not. let frames = frame_path()?; + match std::fs::remove_file(&frames) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("removing the previous capture transport"), + } let backend_status = crate::config::runtime_dir()?.join("backend"); let _ = std::fs::remove_file(&backend_status); std::env::set_var("UUR_FRAME_PATH", &frames); @@ -464,7 +498,10 @@ pub fn start() -> Result<()> { signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?; let log = open_session_log()?; - let mut resources = SessionResources::new(prefix.clone()); + match ManagedChild::spawn_internal("__tray", &log) { + Ok(helper) => resources.helpers.push(helper), + Err(error) => eprintln!("native tray unavailable: {error}"), + } let _ = std::fs::remove_file(&terminal_config); std::env::set_var("UUR_TERMINAL_CONFIG", &terminal_config); resources.cleanup_files.push(terminal_config.clone()); @@ -489,14 +526,29 @@ pub fn start() -> Result<()> { resources .helpers .push(ManagedChild::spawn_internal("__bridge", &log)?); - wait_for_bridge(config.bridge_port, &stopping)?; + wait_for_bridge( + config.bridge_port, + &stopping, + resources.helpers.last_mut().unwrap(), + )?; let selected_backend = std::fs::read_to_string(&backend_status).unwrap_or_default(); let _ = std::fs::remove_file(&backend_status); - if std::env::var_os("WAYLAND_DISPLAY").is_some() && selected_backend.trim() != "portal" { + if on_wayland && selected_backend.trim() != "portal" { resources .helpers .push(ManagedChild::spawn_internal("__capture", &log)?); } + if on_wayland { + println!( + "{}", + if config.capture_backend == "wayland" { + t!("session.waiting_direct_capture").to_string() + } else { + t!("session.waiting_capture").to_string() + } + ); + wait_for_capture(&frames, &stopping, &mut resources)?; + } // The service enumerates processes for a winlogon session token source // before it initialises; under plain Wine none exists. A sleeping @@ -527,12 +579,18 @@ pub fn start() -> Result<()> { .args(["sc", "start", "GameViewerService"]) .status(); } - for _ in 0..150 { - if service_running(&prefix) { - break; + let service_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !service_running(&prefix) { + resources.check_required_helpers()?; + if stopping.load(Ordering::Relaxed) { + anyhow::bail!("session startup cancelled"); + } + if std::time::Instant::now() >= service_deadline { + anyhow::bail!("{}", t!("session.service_failed")); } thread::sleep(std::time::Duration::from_millis(200)); } + println!("{}", t!("session.server_running")); println!("{}", t!("session.launching_client")); let ui = install_dir.join("GameViewer.exe"); @@ -559,6 +617,7 @@ pub fn start() -> Result<()> { let mut missing_checks = 0u8; 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; @@ -652,7 +711,7 @@ fn service_running(prefix: &Path) -> bool { .env("WINEPREFIX", prefix) .env("WINEDEBUG", wine_debug()) .args(["sc", "query", "GameViewerService"]), - std::time::Duration::from_secs(10), + std::time::Duration::from_secs(3), ); match output { Some(text) => text.lines().any(|line| { @@ -702,6 +761,35 @@ pub fn stop() -> Result<()> { Ok(()) } +/// Activate the official client's existing single-instance UI from the +/// native tray without starting another capture/input supervisor. +pub(crate) fn show_client() -> Result<()> { + let prefix = data_dir()?.join("wine"); + let install = + crate::wine::find_client_dir(&prefix).context("managed client is not installed")?; + let Some((pid, start)) = read_session_identity()? else { + anyhow::bail!("managed session is not running"); + }; + if process_start_time(pid).ok() != Some(start) { + anyhow::bail!("managed session is not running"); + } + let mut child = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n") + .current_dir(&install) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .arg(install.join("GameViewer.exe")) + .spawn() + .context("showing the managed client")?; + thread::spawn(move || { + let _ = child.wait(); + }); + Ok(()) +} + fn state_dir() -> PathBuf { std::env::var("XDG_STATE_HOME") .map(PathBuf::from) @@ -754,7 +842,7 @@ fn unix_path_to_wine(path: &Path) -> String { format!("Z:{}", path.display()).replace('/', "\\") } -fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> { +fn wait_for_bridge(port: u16, stopping: &AtomicBool, helper: &mut ManagedChild) -> Result<()> { // The first RemoteDesktop portal grant is intentionally interactive. // Keep the supervisor alive while the user chooses a monitor instead of // treating a two-second consent delay as a bridge failure. @@ -762,6 +850,7 @@ fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> { if stopping.load(Ordering::Relaxed) { anyhow::bail!("session startup cancelled"); } + helper.ensure_running()?; if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { return Ok(()); } @@ -770,6 +859,27 @@ fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> { anyhow::bail!("input bridge did not become ready") } +fn wait_for_capture( + frames: &Path, + stopping: &AtomicBool, + resources: &mut SessionResources, +) -> Result<()> { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + loop { + if stopping.load(Ordering::Relaxed) { + anyhow::bail!("session startup cancelled"); + } + resources.check_required_helpers()?; + if crate::capture::has_frame(frames) { + return Ok(()); + } + if std::time::Instant::now() >= deadline { + anyhow::bail!("{}", t!("session.capture_not_ready")); + } + thread::sleep(std::time::Duration::from_millis(50)); + } +} + fn wait_for_runtime_file(path: &Path, stopping: &AtomicBool) -> Result<()> { for _ in 0..250 { if stopping.load(Ordering::Relaxed) { diff --git a/src/tray.rs b/src/tray.rs new file mode 100644 index 0000000..1279c29 --- /dev/null +++ b/src/tray.rs @@ -0,0 +1,316 @@ +//! Native StatusNotifierItem and DBusMenu, independent of Wine's XEmbed tray. +//! The supervisor owns this helper, so closing the session removes the item. + +use anyhow::{Context, Result}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tokio::sync::mpsc::{unbounded_channel, UnboundedSender}; +use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; + +type Pixmap = (i32, i32, Vec); +type Properties = HashMap; +type Layout = (i32, Properties, Vec); + +#[derive(Clone, Copy)] +enum Action { + Show, + Stop, +} + +struct Tray { + actions: UnboundedSender, + icon: Pixmap, +} + +#[zbus::interface(name = "org.kde.StatusNotifierItem")] +impl Tray { + #[zbus(property)] + fn category(&self) -> &str { + "ApplicationStatus" + } + #[zbus(property)] + fn id(&self) -> &str { + "uur" + } + #[zbus(property)] + fn title(&self) -> String { + t!("tray.title").to_string() + } + #[zbus(property)] + fn status(&self) -> &str { + "Active" + } + #[zbus(property)] + fn window_id(&self) -> i32 { + 0 + } + #[zbus(property)] + fn icon_name(&self) -> &str { + "uur" + } + #[zbus(property)] + fn icon_theme_path(&self) -> &str { + "" + } + #[zbus(property)] + fn icon_pixmap(&self) -> Vec { + vec![self.icon.clone()] + } + #[zbus(property)] + fn attention_icon_name(&self) -> &str { + "" + } + #[zbus(property)] + fn attention_icon_pixmap(&self) -> Vec { + Vec::new() + } + #[zbus(property)] + fn attention_movie_name(&self) -> &str { + "" + } + #[zbus(property)] + fn overlay_icon_name(&self) -> &str { + "" + } + #[zbus(property)] + fn overlay_icon_pixmap(&self) -> Vec { + Vec::new() + } + #[zbus(property)] + fn item_is_menu(&self) -> bool { + false + } + #[zbus(property)] + fn menu(&self) -> OwnedObjectPath { + OwnedObjectPath::try_from("/MenuBar").unwrap() + } + #[zbus(property)] + fn tool_tip(&self) -> (String, Vec, String, String) { + ( + "uur".into(), + vec![self.icon.clone()], + t!("tray.title").to_string(), + t!("tray.tooltip").to_string(), + ) + } + + fn activate(&self, _x: i32, _y: i32) { + let _ = self.actions.send(Action::Show); + } + fn secondary_activate(&self, _x: i32, _y: i32) { + let _ = self.actions.send(Action::Show); + } + // Hosts draw the menu returned by Menu; no X11 popup is necessary. + fn context_menu(&self, _x: i32, _y: i32) {} + fn scroll(&self, _delta: i32, _orientation: &str) {} + fn provide_xdg_activation_token(&self, _token: &str) {} +} + +struct Menu { + actions: UnboundedSender, +} + +#[zbus::interface(name = "com.canonical.dbusmenu")] +impl Menu { + #[zbus(property)] + fn version(&self) -> u32 { + 3 + } + #[zbus(property)] + fn text_direction(&self) -> &str { + "ltr" + } + #[zbus(property)] + fn status(&self) -> &str { + "normal" + } + #[zbus(property)] + fn icon_theme_path(&self) -> Vec { + Vec::new() + } + + fn get_layout( + &self, + parent_id: i32, + recursion_depth: i32, + property_names: Vec, + ) -> zbus::fdo::Result<(u32, Layout)> { + let properties = menu_properties(parent_id, &property_names)?; + let mut children = Vec::new(); + if parent_id == 0 && recursion_depth != 0 { + for id in [1, 2] { + let child = ( + id, + menu_properties(id, &property_names)?, + Vec::::new(), + ); + children.push( + OwnedValue::try_from(Value::new(child)) + .map_err(|error| zbus::fdo::Error::Failed(error.to_string()))?, + ); + } + } + Ok((1, (parent_id, properties, children))) + } + + fn get_group_properties( + &self, + ids: Vec, + property_names: Vec, + ) -> zbus::fdo::Result> { + let ids = if ids.is_empty() { vec![0, 1, 2] } else { ids }; + ids.into_iter() + .map(|id| Ok((id, menu_properties(id, &property_names)?))) + .collect() + } + + fn get_property(&self, id: i32, name: &str) -> zbus::fdo::Result { + menu_properties(id, &[])? + .remove(name) + .ok_or_else(|| zbus::fdo::Error::InvalidArgs(format!("unknown menu property {name}"))) + } + + fn event( + &self, + id: i32, + event_id: &str, + _data: OwnedValue, + _timestamp: u32, + ) -> zbus::fdo::Result<()> { + let action = match id { + 1 => Action::Show, + 2 => Action::Stop, + 0 => return Ok(()), + _ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())), + }; + if event_id == "clicked" { + let _ = self.actions.send(action); + } + Ok(()) + } + + fn event_group(&self, events: Vec<(i32, String, OwnedValue, u32)>) -> Vec { + events + .into_iter() + .filter_map(|(id, event, data, timestamp)| { + self.event(id, &event, data, timestamp).err().map(|_| id) + }) + .collect() + } + + fn about_to_show(&self, id: i32) -> zbus::fdo::Result { + menu_properties(id, &[])?; + Ok(false) + } + + fn about_to_show_group(&self, ids: Vec) -> (Vec, Vec) { + ( + Vec::new(), + ids.into_iter().filter(|id| !(0..=2).contains(id)).collect(), + ) + } +} + +fn menu_properties(id: i32, requested: &[String]) -> zbus::fdo::Result { + let mut properties = Properties::new(); + let string = |value: String| OwnedValue::from(zbus::zvariant::Str::from(value)); + match id { + 0 => { + properties.insert("children-display".into(), string("submenu".into())); + } + 1 | 2 => { + properties.insert( + "label".into(), + string(if id == 1 { + t!("tray.open").to_string() + } else { + t!("tray.quit").to_string() + }), + ); + properties.insert("enabled".into(), OwnedValue::from(true)); + properties.insert("visible".into(), OwnedValue::from(true)); + } + _ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())), + } + if !requested.is_empty() { + properties.retain(|key, _| requested.contains(key)); + } + Ok(properties) +} + +fn icon_pixmap() -> Result { + let mut decoder = png::Decoder::new(std::io::Cursor::new(include_bytes!( + "../packaging/uur-icon.png" + ))); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); + let mut reader = decoder.read_info().context("reading tray icon")?; + let mut pixels = vec![ + 0; + reader + .output_buffer_size() + .context("tray icon size overflow")? + ]; + let info = reader + .next_frame(&mut pixels) + .context("decoding tray icon")?; + anyhow::ensure!( + info.color_type == png::ColorType::Rgba, + "tray icon must be RGBA" + ); + pixels.truncate(info.buffer_size()); + // SNI requires network-byte-order ARGB32, not PNG's RGBA byte order. + for pixel in pixels.as_chunks_mut::<4>().0 { + pixel.rotate_right(1); + } + Ok((info.width.try_into()?, info.height.try_into()?, pixels)) +} + +pub fn serve() -> Result<()> { + let stopping = Arc::new(AtomicBool::new(false)); + signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?; + tokio::runtime::Runtime::new()?.block_on(async { + let (actions, mut receiver) = unbounded_channel(); + let connection = zbus::connection::Builder::session()? + .serve_at("/StatusNotifierItem", Tray { actions: actions.clone(), icon: icon_pixmap()? })? + .serve_at("/MenuBar", Menu { actions })?.build().await?; + let bus = zbus::fdo::DBusProxy::new(&connection).await?; + let mut watcher_owner = None; + let mut timer = tokio::time::interval(std::time::Duration::from_secs(1)); + loop { + tokio::select! { + action = receiver.recv() => match action { + Some(Action::Show) => { + tokio::task::spawn_blocking(|| { + if let Err(error) = crate::session::show_client() { eprintln!("tray: {error}"); } + }); + } + Some(Action::Stop) => { + tokio::task::spawn_blocking(crate::session::stop).await??; + break; + } + None => break, + }, + _ = timer.tick() => { + if stopping.load(Ordering::Relaxed) { break; } + let owner = bus.get_name_owner("org.kde.StatusNotifierWatcher".try_into()?).await.ok(); + if owner != watcher_owner { + if owner.is_some() { + let watcher = zbus::Proxy::new(&connection, "org.kde.StatusNotifierWatcher", + "/StatusNotifierWatcher", "org.kde.StatusNotifierWatcher").await?; + match watcher.call::<_, _, ()>("RegisterStatusNotifierItem", &("/StatusNotifierItem",)).await { + Ok(()) => { + println!("{}", t!("tray.registered")); + watcher_owner = owner; + } + Err(error) => eprintln!("tray registration: {error}"), + } + } else { watcher_owner = None; } + } + } + } + } + Ok(()) + }) +} diff --git a/src/uninstall.rs b/src/uninstall.rs new file mode 100644 index 0000000..4ff79fe --- /dev/null +++ b/src/uninstall.rs @@ -0,0 +1,489 @@ +//! Explicit per-user removal. Distribution-owned files stay with the package +//! manager; a source installation is identified by its installer receipt. + +use anyhow::{Context, Result}; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{IsTerminal, Write}; +use std::os::unix::fs::MetadataExt; +use std::path::{Component, Path, PathBuf}; +use std::process::{Command, Stdio}; + +#[derive(Clone, Copy)] +enum Removal { + File, + Tree, + EmptyDirectory, +} + +struct Plan { + home: PathBuf, + data: PathBuf, + config: PathBuf, + state: PathBuf, + runtime: PathBuf, + entries: BTreeMap, + source_install: bool, +} + +pub fn run(purge: bool, dry_run: bool, yes: bool) -> Result<()> { + if unsafe { libc::geteuid() } == 0 { + anyhow::bail!("{}", t!("uninstall.no_root")); + } + let mut plan = Plan::build(purge)?; + println!("{}", t!("uninstall.plan")); + for (path, removal) in &plan.entries { + if !matches!(removal, Removal::EmptyDirectory) { + println!(" {}", path.display()); + } + } + if purge { + println!("{}", t!("uninstall.purge_warning")); + } else { + println!("{}", t!("uninstall.keep_data")); + } + println!("{}", t!("uninstall.package_hint")); + if dry_run { + println!("{}", t!("uninstall.dry_run")); + return Ok(()); + } + if !yes { + if !std::io::stdin().is_terminal() { + anyhow::bail!("{}", t!("uninstall.confirm_required")); + } + print!("{} ", t!("uninstall.confirm")); + std::io::stdout().flush()?; + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer)?; + if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") { + println!("{}", t!("uninstall.cancelled")); + return Ok(()); + } + } + + crate::session::stop()?; + // Keep setup/run excluded until the directory cleanup has finished. + let _session_lock = crate::session::acquire_session_lock()?; + stop_prefix(&plan.data.join("wine"))?; + // Revalidate the displayed targets after stopping the session. Do not add + // newly discovered files to a plan the user has already confirmed. + plan.validate()?; + // Remove integrations first, then the trees; the running ELF can be + // unlinked on Linux, so source installs need no second helper process. + let trees: Vec<_> = plan + .entries + .iter() + .filter_map(|(path, removal)| matches!(removal, Removal::Tree).then_some(path.clone())) + .collect(); + plan.entries.retain(|path, removal| { + !matches!(removal, Removal::File) + || !trees + .iter() + .any(|root| path != root && path.starts_with(root)) + }); + let mut removals: Vec<_> = plan + .entries + .iter() + .filter(|(_, removal)| !matches!(removal, Removal::EmptyDirectory)) + .collect(); + // Keep the receipt until all installed files are removed, so a failed + // cleanup can be retried from another copy of uur. + removals.sort_by_key( + |(path, _)| match path.file_name().and_then(|name| name.to_str()) { + Some("user-install") => 2, + Some("uur") if path.parent().and_then(Path::file_name) == Some("bin".as_ref()) => 1, + _ => 0, + }, + ); + for (path, removal) in removals { + remove(path, *removal)?; + } + for (path, removal) in plan.entries.iter().rev() { + if matches!(removal, Removal::EmptyDirectory) { + remove(path, *removal)?; + } + } + println!("{}", t!("uninstall.done")); + if !plan.source_install { + println!("{}", t!("uninstall.package_hint")); + } + Ok(()) +} + +impl Plan { + fn build(purge: bool) -> Result { + let home = absolute(PathBuf::from( + std::env::var_os("HOME").context("HOME is unset")?, + ))?; + let data_home = xdg_home("XDG_DATA_HOME", &home.join(".local/share"))?; + let config_home = xdg_home("XDG_CONFIG_HOME", &home.join(".config"))?; + let state_home = xdg_home("XDG_STATE_HOME", &home.join(".local/state"))?; + let runtime_home = xdg_home( + "XDG_RUNTIME_DIR", + &PathBuf::from(format!("/tmp/uur-{}", unsafe { libc::geteuid() })), + )?; + let mut plan = Self { + home: home.clone(), + data: data_home.join("uur"), + config: config_home.join("uur"), + state: state_home.join("uur"), + runtime: runtime_home.join("uur"), + entries: BTreeMap::new(), + source_install: false, + }; + plan.entries.insert(plan.runtime.clone(), Removal::Tree); + if purge { + for path in [&plan.data, &plan.config, &plan.state] { + plan.entries.insert(path.clone(), Removal::Tree); + } + } + let default_scope = data_home == home.join(".local/share"); + let mut desktops = BTreeSet::new(); + scan_files(&data_home.join("applications"), 8, &mut desktops)?; + // Old releases placed compatibility aliases in ~/.local/share even + // when XDG_DATA_HOME was set. Only entries tied to this prefix qualify. + scan_files(&home.join(".local/share/applications"), 8, &mut desktops)?; + scan_files(&desktop_dir(&home, &config_home), 1, &mut desktops)?; + let autostart = config_home.join("autostart/uur.desktop"); + if autostart.exists() { + desktops.insert(autostart); + } + let mut removed_icons = BTreeSet::new(); + let mut kept_icons = BTreeSet::new(); + let mut remove_default_icons = default_scope; + for path in desktops { + if path + .extension() + .is_none_or(|extension| extension != "desktop") + { + continue; + } + let content = std::fs::read_to_string(&path) + .with_context(|| format!("reading {}", path.display()))?; + let icon = desktop_value(&content, "Icon").unwrap_or_default(); + if plan.owns_desktop(&content, default_scope) { + remove_default_icons |= path.starts_with(home.join(".local/share/applications")) + || path.starts_with(desktop_dir(&home, &config_home)); + plan.entries.insert(path, Removal::File); + removed_icons.insert(icon.to_string()); + } else { + kept_icons.insert(icon.to_string()); + } + } + let mut icon_roots = BTreeSet::from([data_home.join("icons")]); + if remove_default_icons { + icon_roots.insert(home.join(".local/share/icons")); + } + for icons in icon_roots { + let mut files = BTreeSet::new(); + scan_files(&icons, 6, &mut files)?; + for path in files { + let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else { + continue; + }; + let alias = stem.strip_suffix(".0").unwrap_or(stem); + if (removed_icons.contains(stem) || removed_icons.contains(alias)) + && !kept_icons.contains(stem) + && !kept_icons.contains(alias) + { + plan.entries.insert(path, Removal::File); + } + } + } + plan.source_files()?; + plan.validate()?; + Ok(plan) + } + + fn owns_desktop(&self, content: &str, default_scope: bool) -> bool { + let prefix = self.data.join("wine"); + if let Some(recorded) = desktop_value(content, "X-UUR-Prefix") { + return desktop_value(content, "X-UUR-Managed") == Some("true") + && recorded == prefix.to_string_lossy(); + } + let managed = desktop_value(content, "X-UUR-Managed") == Some("true") + || desktop_value(content, "Comment") == Some("Start the managed UU Remote session") + || desktop_value(content, "Comment") == Some("UU Remote for Linux (uur)"); + if managed && default_scope { + return true; + } + // Wine writes an explicit WINEPREFIX assignment in its launchers. + // Match the entire quoted/unquoted value, not a filename substring. + let exec = desktop_value(content, "Exec").unwrap_or_default(); + let prefix = prefix.to_string_lossy(); + let references_prefix = [ + format!("WINEPREFIX=\"{prefix}\" "), + format!("WINEPREFIX='{prefix}' "), + format!("WINEPREFIX={prefix} "), + ] + .iter() + .any(|assignment| exec.contains(assignment)); + references_prefix && exec.to_ascii_lowercase().contains("gameviewer") + } + + fn source_files(&mut self) -> Result<()> { + let executable = std::env::current_exe()?; + let mut prefixes = BTreeSet::from([self.home.join(".local")]); + if let Some(prefix) = executable.parent().and_then(Path::parent) { + if executable.parent().and_then(Path::file_name) == Some("bin".as_ref()) { + prefixes.insert(prefix.to_path_buf()); + } + } + if let Some(prefix) = std::env::var_os("UUR_INSTALL_PREFIX") { + prefixes.insert(absolute(PathBuf::from(prefix))?); + } + for prefix in prefixes { + let receipt = prefix.join("lib/uur/user-install"); + let marked = std::fs::read_to_string(&receipt).is_ok_and(|content| { + content == format!("uur-user-install-v1\n{}\n", self.data.display()) + }); + // Support the previous source installer, but only while executing + // its ~/.local/bin/uur and with the matching generated menu entry. + let legacy = prefix == self.home.join(".local") + && std::fs::canonicalize(prefix.join("bin/uur")).ok() == Some(executable.clone()) + && std::fs::read_to_string(prefix.join("share/applications/uur.desktop")) + .is_ok_and(|content| { + desktop_value(&content, "TryExec") + == Some(prefix.join("bin/uur").to_string_lossy().as_ref()) + }); + if !marked && !legacy { + continue; + } + self.source_install = true; + for relative in [ + "bin/uur", + "lib/uur/user-install", + "lib/uur/uur-pw-capture", + "lib/uur/uur-wl-capture", + "lib/uur/hook/wevtapi.dll", + "lib/uur/hook/uur-hook.dll", + "lib/uur/hook/wtsapi32.dll", + "lib/uur/hook/winlogon.exe", + "lib/uur/hook/uur-terminal-proxy.exe", + "lib/uur/hook/uur-mux-proxy.exe", + "lib/uur/hook/uur-launch-proxy.exe", + "share/applications/uur.desktop", + "share/icons/hicolor/256x256/apps/uur.png", + ] { + let path = prefix.join(relative); + if std::fs::symlink_metadata(&path).is_ok() { + self.entries.insert(path, Removal::File); + } + } + for relative in ["lib/uur/hook", "lib/uur"] { + self.entries + .insert(prefix.join(relative), Removal::EmptyDirectory); + } + } + Ok(()) + } + + fn validate(&self) -> Result<()> { + // Session shutdown/locking access these paths before tree removal. + // Reject redirected state rather than following a link while writing + // the lock or stopping an unrelated Wine prefix. + for path in [ + &self.data, + &self.state, + &self.runtime, + &self.state.join("session.lock"), + &self.data.join("wine"), + ] { + if path.is_symlink() { + anyhow::bail!("refusing redirected session state: {}", path.display()); + } + if std::fs::metadata(path) + .is_ok_and(|metadata| metadata.uid() != unsafe { libc::geteuid() }) + { + anyhow::bail!("session state belongs to another user: {}", path.display()); + } + } + for (path, removal) in &self.entries { + let path = absolute(path.clone())?; + // Resolve ancestor links, but never resolve the final link: remove + // symlink entries themselves, not the objects they point at. + let resolved = path + .parent() + .and_then(|parent| std::fs::canonicalize(parent).ok()) + .map(|parent| parent.join(path.file_name().unwrap_or_default())) + .unwrap_or_else(|| path.clone()); + if path == self.home || resolved == self.home || path.parent().is_none() { + anyhow::bail!("refusing to remove {}", path.display()); + } + // Never allow a receipt or an XDG override to select system trees. + for system in [ + "/usr", "/etc", "/opt", "/var", "/nix", "/bin", "/lib", "/sbin", "/boot", "/dev", + "/proc", "/sys", + ] { + if path.starts_with(system) || resolved.starts_with(system) { + anyhow::bail!("refusing to remove system path {}", path.display()); + } + } + match std::fs::symlink_metadata(&path) { + Ok(metadata) => { + if metadata.uid() != unsafe { libc::geteuid() } { + anyhow::bail!( + "refusing to remove a path owned by another user: {}", + path.display() + ); + } + if matches!(removal, Removal::Tree) + && !metadata.file_type().is_symlink() + && (path.join(".git").exists() || path.join("Cargo.toml").exists()) + { + anyhow::bail!("refusing to remove a source checkout: {}", path.display()); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| format!("checking {}", path.display())) + } + } + } + Ok(()) + } +} + +fn absolute(path: PathBuf) -> Result { + if !path.is_absolute() { + anyhow::bail!( + "uninstall requires absolute XDG/install paths: {}", + path.display() + ); + } + let mut normalized = PathBuf::from("/"); + for component in path.components() { + match component { + Component::Normal(part) => normalized.push(part), + Component::ParentDir => { + normalized.pop(); + } + _ => {} + } + } + Ok(normalized) +} + +fn xdg_home(variable: &str, fallback: &Path) -> Result { + absolute( + std::env::var_os(variable) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| fallback.to_path_buf()), + ) +} + +fn desktop_value<'a>(content: &'a str, key: &str) -> Option<&'a str> { + let mut main_section = false; + for line in content.lines() { + if line.starts_with('[') { + main_section = line == "[Desktop Entry]"; + } else if main_section { + if let Some((name, value)) = line.split_once('=') { + if name == key { + return Some(value); + } + } + } + } + None +} + +fn desktop_dir(home: &Path, config_home: &Path) -> PathBuf { + // user-dirs.dirs is data, not a shell script: never source it. + std::fs::read_to_string(config_home.join("user-dirs.dirs")) + .ok() + .and_then(|content| { + content.lines().find_map(|line| { + let value = line.strip_prefix("XDG_DESKTOP_DIR=\"")?.strip_suffix('"')?; + let path = value + .strip_prefix("$HOME/") + .map(|suffix| home.join(suffix)) + .unwrap_or_else(|| PathBuf::from(value)); + (path.is_absolute() && path != home).then_some(path) + }) + }) + .unwrap_or_else(|| home.join("Desktop")) +} + +fn scan_files(dir: &Path, depth: u8, files: &mut BTreeSet) -> Result<()> { + if depth == 0 { + return Ok(()); + } + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).with_context(|| format!("listing {}", dir.display())), + }; + for entry in entries { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + scan_files(&entry.path(), depth - 1, files)?; + } else if kind.is_file() { + files.insert(entry.path()); + } + } + Ok(()) +} + +fn stop_prefix(prefix: &Path) -> Result<()> { + if !prefix.is_dir() || prefix.is_symlink() { + return Ok(()); + } + match Command::new("wineserver") + .env("WINEPREFIX", prefix) + .arg("-k") + .stdin(Stdio::null()) + .status() + { + // -k exits 1 when stop already shut down this prefix's server. The + // following -w, with a deadline, is the actual shutdown check. + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).context("stopping the managed wineserver"), + } + let mut wait = Command::new("wineserver") + .env("WINEPREFIX", prefix) + .arg("-w") + .stdin(Stdio::null()) + .spawn()?; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + if let Some(status) = wait.try_wait()? { + if !status.success() { + anyhow::bail!("wineserver shutdown failed"); + } + return Ok(()); + } + if std::time::Instant::now() >= deadline { + let _ = wait.kill(); + let _ = wait.wait(); + anyhow::bail!("managed wineserver is still running; no files were removed"); + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } +} + +fn remove(path: &Path, removal: Removal) -> Result<()> { + let metadata = match std::fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).with_context(|| format!("checking {}", path.display())), + }; + let result = match removal { + Removal::Tree if metadata.is_dir() && !metadata.file_type().is_symlink() => { + std::fs::remove_dir_all(path) + } + Removal::EmptyDirectory if metadata.is_dir() => std::fs::remove_dir(path), + _ => std::fs::remove_file(path), + }; + match result { + Err(error) + if matches!(removal, Removal::EmptyDirectory) + && error.kind() == std::io::ErrorKind::DirectoryNotEmpty => + { + Ok(()) + } + other => other.with_context(|| format!("removing {}", path.display())), + } +} diff --git a/src/wine.rs b/src/wine.rs index c4a78db..80912ba 100644 --- a/src/wine.rs +++ b/src/wine.rs @@ -6,11 +6,20 @@ use crate::config::Config; const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd"; const EULA_URL: &str = "https://uuyc.163.com/contact/20240402/40294_1146065.html"; +const SETUP_DLL_OVERRIDES: &str = "wevtapi=b,wtsapi32=b"; + +struct SetupPrefix(PathBuf); + +impl Drop for SetupPrefix { + fn drop(&mut self) { + stop_wineserver(&self.0); + } +} /// One-time provisioning. Deliberately quiet: progress on stdout, nothing /// else. NetEase binaries are never redistributed — they are fetched from /// the official feed into a per-user prefix. -pub fn setup(accept_eula: bool) -> Result<()> { +pub fn setup(accept_eula: bool, repair: bool) -> Result<()> { let mut config = Config::load()?; if !config.eula_accepted { @@ -23,19 +32,40 @@ pub fn setup(accept_eula: bool) -> Result<()> { println!("{}", t!("setup.eula_recorded")); } + let _session_lock = crate::session::acquire_session_lock()?; let data = crate::config::data_dir()?; let prefix = data.join("wine"); std::fs::create_dir_all(&prefix).context("creating wine prefix directory")?; let cache = data.join("cache"); std::fs::create_dir_all(&cache).context("creating cache directory")?; + let _prefix_cleanup = SetupPrefix(prefix.clone()); - if find_client_dir(&prefix).is_some() { - apply_registry_compat(&prefix)?; - let uur_bin = std::env::current_exe().unwrap_or_default(); - let _ = adopt_shortcut(&prefix, &uur_bin); + if !repair + && prefix_initialized(&prefix) + && find_client_dir(&prefix).is_some() + && client_service_registered(&prefix) + { + finish_setup(&prefix)?; println!("{}", t!("setup.already_provisioned")); - stop_wineserver(&prefix); + return Ok(()); + } + + println!("{}", t!("setup.initializing_prefix")); + let status = Command::new("wineboot") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES) + .arg(if repair { "--update" } else { "--init" }) + .status() + .context("running wineboot")?; + if !status.success() || !prefix_initialized(&prefix) { + anyhow::bail!("{}", t!("setup.prefix_failed", status = status)); + } + + if find_client_dir(&prefix).is_some() && query_client_service(&prefix)? { + finish_setup(&prefix)?; + println!("{}", t!("setup.repaired", path = prefix.display())); return Ok(()); } @@ -57,82 +87,96 @@ pub fn setup(accept_eula: bool) -> Result<()> { anyhow::bail!("{}", t!("setup.download_failed")); } - println!("{}", t!("setup.initializing_prefix")); - let _ = Command::new("wineboot") - .env("WINEPREFIX", &prefix) - .env("WINEDEBUG", wine_debug()) - .arg("--init") - .status() - .context("running wineboot")?; - - // The preload chain only works if Wine resolves wevtapi to the native - // shim in the application directory instead of its builtin. - let _ = Command::new("wine") - .env("WINEPREFIX", &prefix) - .env("WINEDEBUG", wine_debug()) - .args([ - "reg", - "add", - r"HKCU\Software\Wine\DllOverrides", - "/v", - "wevtapi", - "/t", - "REG_SZ", - "/d", - "native", - "/f", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .context("registering wevtapi dll override")?; - println!("{}", t!("setup.installing_client")); let status = Command::new("wine") .env("WINEPREFIX", &prefix) .env("WINEDEBUG", wine_debug()) + .env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES) .arg(installer.to_string_lossy().as_ref()) .arg("/S") .status() .context("launching installer")?; if !status.success() { - println!("{}", t!("setup.silent_install_unavailable")); + anyhow::bail!("{}", t!("setup.install_failed", status = status)); } + find_client_dir(&prefix).context(t!("setup.client_incomplete").to_string())?; + if !query_client_service(&prefix)? { + anyhow::bail!("{}", t!("setup.service_incomplete")); + } + + finish_setup(&prefix)?; + println!("{}", t!("setup.done", path = prefix.display().to_string())); + Ok(()) +} + +fn finish_setup(prefix: &Path) -> Result<()> { // winemenubuilder generated its entries during the install: adopt the // start-menu one for the full session, then stop it from producing raw // shortcuts ever again, and sweep desktop copies. - let _ = Command::new("wine") - .env("WINEPREFIX", &prefix) - .env("WINEDEBUG", wine_debug()) - .args([ - "reg", - "add", - r"HKCU\Software\Wine\DllOverrides", - "/v", - "winemenubuilder", - "/t", - "REG_SZ", - "/d", - "", - "/f", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .context("disabling winemenubuilder")?; - apply_registry_compat(&prefix)?; + set_dll_override(prefix, "wevtapi", "native")?; + set_dll_override(prefix, "winemenubuilder", "")?; + apply_registry_compat(prefix)?; let uur_bin = std::env::current_exe().unwrap_or_default(); - let _ = adopt_shortcut(&prefix, &uur_bin); + let _ = adopt_shortcut(prefix, &uur_bin); purge_wine_shortcuts(); - println!("{}", t!("setup.done", path = prefix.display().to_string())); - stop_wineserver(&prefix); Ok(()) } +pub fn prefix_initialized(prefix: &Path) -> bool { + ["system.reg", "user.reg"] + .iter() + .all(|name| std::fs::metadata(prefix.join(name)).is_ok_and(|metadata| metadata.len() > 0)) +} + +pub fn webview2_installed(prefix: &Path) -> bool { + let application = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application"); + find_dir_recursive(&application, "msedgewebview2.exe", 3) + .is_some_and(|path| std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0)) +} + +/// 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; + }; + let mut service_section = false; + for line in registry.lines() { + if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) { + service_section = section + .0 + .to_ascii_lowercase() + .ends_with(r"\\services\\gameviewerservice"); + } else if service_section && line.starts_with("\"ImagePath\"=") { + return line.to_ascii_lowercase().contains("gameviewerserver.exe"); + } + } + false +} + +fn query_client_service(prefix: &Path) -> Result { + let output = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES) + .args([ + "reg", + "query", + r"HKLM\System\CurrentControlSet\Services\GameViewerService", + "/v", + "ImagePath", + ]) + .stdin(Stdio::null()) + .output() + .context("checking the UU Windows service registration")?; + Ok(output.status.success() + && String::from_utf8_lossy(&output.stdout) + .to_ascii_lowercase() + .contains("gameviewerserver.exe")) +} + /// Registry compatibility profile, ported from the field-tested reference /// implementation: /// @@ -196,7 +240,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> { format!("HKCU\\{key}") }; for (value, reg_type, data) in &values { - let _ = Command::new("wine") + let status = Command::new("wine") .env("WINEPREFIX", prefix) .env("WINEDEBUG", wine_debug()) .args([ @@ -207,6 +251,9 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> { .stderr(Stdio::null()) .status() .with_context(|| format!("reg add {full} /v {value}"))?; + if !status.success() { + anyhow::bail!("Wine rejected registry compatibility setting {full} /v {value}"); + } } } Ok(()) @@ -294,15 +341,21 @@ pub fn find_client_dir(prefix: &Path) -> Option { let vendor = entry.path(); if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) { let bin = found.parent()?; - if bin + let candidate = if bin .file_name() .is_some_and(|name| name.eq_ignore_ascii_case("bin")) { - return bin.parent().map(Path::to_path_buf); + 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); } - return Some(bin.to_path_buf()); } - return Some(vendor); } } None @@ -315,7 +368,11 @@ fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option let entries = std::fs::read_dir(start).ok()?; for entry in entries.flatten() { let path = entry.path(); - if path.is_file() && path.file_name().map(|n| n == needle).unwrap_or(false) { + if path.is_file() + && path + .file_name() + .is_some_and(|name| name.eq_ignore_ascii_case(needle)) + { return Some(path); } if path.is_dir() { @@ -357,8 +414,11 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> { }; let mut icon_name = String::new(); - let home = std::env::var("HOME").unwrap_or_default(); - let icons = PathBuf::from(home).join(".local/share/icons"); + let data_home = crate::config::data_dir()? + .parent() + .context("no data home")? + .to_path_buf(); + let icons = data_home.join("icons"); let mut best = 0u32; if let Ok(sizes) = fs::read_dir(icons.join("hicolor")) { for size in sizes.flatten() { @@ -382,9 +442,7 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> { } } - let applications = std::env::var("HOME") - .map(|h| PathBuf::from(h).join(".local/share/applications")) - .context("no home")?; + let applications = data_home.join("applications"); std::fs::create_dir_all(&applications)?; let entry = applications.join(format!("{name}.desktop")); let exec = uur_bin.display(); @@ -405,7 +463,9 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> { {icon_line}Terminal=false\n\ NoDisplay=true\n\ X-UUR-Managed=true\n\ - Categories=Network;RemoteAccess;\n" + X-UUR-Prefix={}\n\ + Categories=Network;RemoteAccess;\n", + prefix.display() ), ) .with_context(|| format!("writing {}", entry.display()))?;