13 Commits
Author SHA1 Message Date
Xuc Pan ef72baa56d chore(release): prepare v0.1.5 2026-10-13 15:31:16 +08:00
Xuc Pan 8c0589021f fix: repair Wine setup and niri capture, input and tray (#22)
* fix(setup): verify provisioning and runtime readiness

* feat: add explicit per-user uninstall and purge

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

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

No files matched your search

+1 -1
View File
@@ -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: |
+2 -2
View File
@@ -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: |
+1
View File
@@ -2,5 +2,6 @@
/build
/dist
/capture/uur-pw-capture
/capture/uur-wl-capture
Cargo.lock.orig
*.tar.gz
Generated
+83 -1
View File
@@ -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"
@@ -1413,7 +1487,7 @@ dependencies = [
[[package]]
name = "uur"
version = "0.1.3"
version = "0.1.5"
dependencies = [
"anyhow",
"ashpd",
@@ -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"
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "uur"
version = "0.1.3"
version = "0.1.5"
edition = "2021"
description = "Native Linux companion for NetEase UU Remote: X11/Wayland input and capture, packaged as a regular desktop app"
license = "MIT"
@@ -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
+4
View File
@@ -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.
+20 -4
View File
@@ -69,7 +69,7 @@ recipes and release artifacts share one version and filesystem layout.
Install a downloaded release package with pacman:
```bash
sudo pacman -U ./dist/uur-0.1.3-1-x86_64.pkg.tar.zst
sudo pacman -U ./dist/uur-0.1.5-1-x86_64.pkg.tar.zst
```
### AUR
@@ -83,13 +83,13 @@ paru -S uur
### Debian and Ubuntu package family
```bash
sudo apt install ./uur_0.1.3_amd64.deb
sudo apt install ./uur_0.1.5_amd64.deb
```
### Fedora and compatible RPM systems
```bash
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
```
On systems with different RPM dependency names, install the dependencies
@@ -98,7 +98,7 @@ manually or use the portable archive.
### Portable archive
```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
```
### Nix and NixOS
@@ -151,9 +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
+19 -5
View File
@@ -66,7 +66,7 @@ uur run
使用 pacman 安装下载的正式发布包:
```bash
sudo pacman -U ./dist/uur-0.1.3-1-x86_64.pkg.tar.zst
sudo pacman -U ./dist/uur-0.1.5-1-x86_64.pkg.tar.zst
```
### AUR
@@ -80,13 +80,13 @@ paru -S uur
### Debian、Ubuntu 及兼容发行版
```bash
sudo apt install ./uur_0.1.3_amd64.deb
sudo apt install ./uur_0.1.5_amd64.deb
```
### Fedora 及兼容 RPM 发行版
```bash
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
```
如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。
@@ -94,7 +94,7 @@ sudo dnf install ./uur-0.1.3-1.x86_64.rpm
### 通用压缩包
```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
```
### Nix 与 NixOS
@@ -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,9 +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
+12
View File
@@ -15,3 +15,15 @@ command -v "$cc" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$cc" >&2; exi
$(pkg-config --cflags --libs libpipewire-0.3)
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"
+336
View File
@@ -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 <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <wayland-client.h>
#include "wlr-screencopy-unstable-v1-client-protocol.h"
#include "../hook/frame-protocol.h"
struct frame_header {
uint32_t magic, version, width, height, stride, format;
_Atomic uint64_t total_frames;
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, &registry_listener, &c);
if (wl_display_roundtrip(c.display) < 0 || wl_display_roundtrip(c.display) < 0) {
c.failed = 1; goto cleanup;
}
if (list) {
for (size_t i = 0; i < c.output_count; ++i) {
printf("%s %dx%d\n", c.outputs[i].name, c.outputs[i].width, c.outputs[i].height);
}
goto cleanup;
}
if (c.manager == NULL || c.shm == NULL) {
fprintf(stderr, "compositor does not expose wlr-screencopy with wl_shm buffers\n");
c.failed = 1; goto cleanup;
}
const char *name = getenv("UUR_CAPTURE_OUTPUT");
if (name != NULL && name[0] != '\0') {
for (size_t i = 0; i < c.output_count; ++i) {
if (!strcmp(name, c.outputs[i].name)) c.selected = &c.outputs[i];
}
} else if (c.output_count == 1) { c.selected = &c.outputs[0]; }
if (c.selected == NULL) {
fprintf(stderr, "select one output with uur display backend wayland --output NAME:\n");
for (size_t i = 0; i < c.output_count; ++i) fprintf(stderr, " %s\n", c.outputs[i].name);
c.failed = 1; goto cleanup;
}
while (!stopping && !c.failed) {
c.done = 0;
c.frame = zwlr_screencopy_manager_v1_capture_output(c.manager, 1, c.selected->proxy);
zwlr_screencopy_frame_v1_add_listener(c.frame, &frame_listener, &c);
while (!c.done && !stopping) {
if (dispatch(&c) < 0) { c.failed = 1; break; }
}
if (c.done && !c.failed && !stopping) publish_frame(&c);
clear_frame(&c);
struct timespec delay = { .tv_nsec = 33333333 };
nanosleep(&delay, NULL);
}
cleanup:
clear_frame(&c);
if (c.ring != NULL) munmap(c.ring, c.ring_size);
if (c.ring_fd >= 0) {
struct stat created, present;
if (fstat(c.ring_fd, &created) == 0 && lstat(c.frame_path, &present) == 0 &&
created.st_dev == present.st_dev && created.st_ino == present.st_ino) unlink(c.frame_path);
close(c.ring_fd);
}
for (size_t i = 0; i < c.output_count; ++i) wl_output_destroy(c.outputs[i].proxy);
if (c.manager != NULL) zwlr_screencopy_manager_v1_destroy(c.manager);
if (c.shm != NULL) wl_shm_destroy(c.shm);
wl_registry_destroy(c.registry); wl_display_disconnect(c.display);
return c.failed ? 1 : 0;
}
+232
View File
@@ -0,0 +1,232 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_screencopy_unstable_v1">
<copyright>
Copyright © 2018 Simon Ser
Copyright © 2019 Andri Yngvason
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<description summary="screen content capturing on client buffers">
This protocol allows clients to ask the compositor to copy part of the
screen content to a client buffer.
Warning! The protocol described in this file is experimental and
backward incompatible changes may be made. Backward compatible changes
may be added together with the corresponding interface version bump.
Backward incompatible changes are done by bumping the version number in
the protocol and interface names and resetting the interface version.
Once the protocol is to be declared stable, the 'z' prefix and the
version number in the protocol and interface names are removed and the
interface version number is reset.
</description>
<interface name="zwlr_screencopy_manager_v1" version="3">
<description summary="manager to inform clients and begin capturing">
This object is a manager which offers requests to start capturing from a
source.
</description>
<request name="capture_output">
<description summary="capture an output">
Capture the next frame of an entire output.
</description>
<arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
<arg name="overlay_cursor" type="int"
summary="composite cursor onto the frame"/>
<arg name="output" type="object" interface="wl_output"/>
</request>
<request name="capture_output_region">
<description summary="capture an output's region">
Capture the next frame of an output's region.
The region is given in output logical coordinates, see
xdg_output.logical_size. The region will be clipped to the output's
extents.
</description>
<arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
<arg name="overlay_cursor" type="int"
summary="composite cursor onto the frame"/>
<arg name="output" type="object" interface="wl_output"/>
<arg name="x" type="int"/>
<arg name="y" type="int"/>
<arg name="width" type="int"/>
<arg name="height" type="int"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the manager">
All objects created by the manager will still remain valid, until their
appropriate destroy request has been called.
</description>
</request>
</interface>
<interface name="zwlr_screencopy_frame_v1" version="3">
<description summary="a frame ready for copy">
This object represents a single frame.
When created, a series of buffer events will be sent, each representing a
supported buffer type. The "buffer_done" event is sent afterwards to
indicate that all supported buffer types have been enumerated. The client
will then be able to send a "copy" request. If the capture is successful,
the compositor will send a "flags" followed by a "ready" event.
For objects version 2 or lower, wl_shm buffers are always supported, ie.
the "buffer" event is guaranteed to be sent.
If the capture failed, the "failed" event is sent. This can happen anytime
before the "ready" event.
Once either a "ready" or a "failed" event is received, the client should
destroy the frame.
</description>
<event name="buffer">
<description summary="wl_shm buffer information">
Provides information about wl_shm buffer parameters that need to be
used for this frame. This event is sent once after the frame is created
if wl_shm buffers are supported.
</description>
<arg name="format" type="uint" enum="wl_shm.format" summary="buffer format"/>
<arg name="width" type="uint" summary="buffer width"/>
<arg name="height" type="uint" summary="buffer height"/>
<arg name="stride" type="uint" summary="buffer stride"/>
</event>
<request name="copy">
<description summary="copy the frame">
Copy the frame to the supplied buffer. The buffer must have a the
correct size, see zwlr_screencopy_frame_v1.buffer and
zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a
supported format.
If the frame is successfully copied, a "flags" and a "ready" events are
sent. Otherwise, a "failed" event is sent.
</description>
<arg name="buffer" type="object" interface="wl_buffer"/>
</request>
<enum name="error">
<entry name="already_used" value="0"
summary="the object has already been used to copy a wl_buffer"/>
<entry name="invalid_buffer" value="1"
summary="buffer attributes are invalid"/>
</enum>
<enum name="flags" bitfield="true">
<entry name="y_invert" value="1" summary="contents are y-inverted"/>
</enum>
<event name="flags">
<description summary="frame flags">
Provides flags about the frame. This event is sent once before the
"ready" event.
</description>
<arg name="flags" type="uint" enum="flags" summary="frame flags"/>
</event>
<event name="ready">
<description summary="indicates frame is available for reading">
Called as soon as the frame is copied, indicating it is available
for reading. This event includes the time at which presentation happened
at.
The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,
each component being an unsigned 32-bit value. Whole seconds are in
tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,
and the additional fractional part in tv_nsec as nanoseconds. Hence,
for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part
may have an arbitrary offset at start.
After receiving this event, the client should destroy the object.
</description>
<arg name="tv_sec_hi" type="uint"
summary="high 32 bits of the seconds part of the timestamp"/>
<arg name="tv_sec_lo" type="uint"
summary="low 32 bits of the seconds part of the timestamp"/>
<arg name="tv_nsec" type="uint"
summary="nanoseconds part of the timestamp"/>
</event>
<event name="failed">
<description summary="frame copy failed">
This event indicates that the attempted frame copy has failed.
After receiving this event, the client should destroy the object.
</description>
</event>
<request name="destroy" type="destructor">
<description summary="delete this object, used or not">
Destroys the frame. This request can be sent at any time by the client.
</description>
</request>
<!-- Version 2 additions -->
<request name="copy_with_damage" since="2">
<description summary="copy the frame when it's damaged">
Same as copy, except it waits until there is damage to copy.
</description>
<arg name="buffer" type="object" interface="wl_buffer"/>
</request>
<event name="damage" since="2">
<description summary="carries the coordinates of the damaged region">
This event is sent right before the ready event when copy_with_damage is
requested. It may be generated multiple times for each copy_with_damage
request.
The arguments describe a box around an area that has changed since the
last copy request that was derived from the current screencopy manager
instance.
The union of all regions received between the call to copy_with_damage
and a ready event is the total damage since the prior ready event.
</description>
<arg name="x" type="uint" summary="damaged x coordinates"/>
<arg name="y" type="uint" summary="damaged y coordinates"/>
<arg name="width" type="uint" summary="current width"/>
<arg name="height" type="uint" summary="current height"/>
</event>
<!-- Version 3 additions -->
<event name="linux_dmabuf" since="3">
<description summary="linux-dmabuf buffer information">
Provides information about linux-dmabuf buffer parameters that need to
be used for this frame. This event is sent once after the frame is
created if linux-dmabuf buffers are supported.
</description>
<arg name="format" type="uint" summary="fourcc pixel format"/>
<arg name="width" type="uint" summary="buffer width"/>
<arg name="height" type="uint" summary="buffer height"/>
</event>
<event name="buffer_done" since="3">
<description summary="all buffer types reported">
This event is sent once after all buffer events have been sent.
The client should proceed to create a buffer of one of the supported
types, and send a "copy" request.
</description>
</event>
</interface>
</protocol>
+64 -6
View File
@@ -12,13 +12,13 @@ needed for system-wide package installation.
paru -S uur
# Downloaded release package
sudo pacman -U ./uur-0.1.3-1-x86_64.pkg.tar.zst
sudo pacman -U ./uur-0.1.5-1-x86_64.pkg.tar.zst
```
## Debian, Ubuntu, and derivatives
```bash
sudo apt install ./uur_0.1.3_amd64.deb
sudo apt install ./uur_0.1.5_amd64.deb
```
The same release artifact covers Debian, Ubuntu, Linux Mint, Pop!_OS, KDE neon,
@@ -28,10 +28,10 @@ derivatives.
## Fedora, RHEL, and openSUSE families
```bash
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
# openSUSE
sudo zypper install ./uur-0.1.3-1.x86_64.rpm
sudo zypper install ./uur-0.1.5-1.x86_64.rpm
```
This format also covers Fedora derivatives and RPM systems whose repositories
@@ -42,7 +42,7 @@ provide the declared Wine, GLib, PipeWire, and portal dependencies.
The portable archive targets conventional glibc/FHS systems:
```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
```
## Nix and NixOS
@@ -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.
+2 -2
View File
@@ -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 |
+105 -8
View File
@@ -46,7 +46,7 @@ paru -S uur
From a downloaded Arch package:
```bash
sudo pacman -U ./uur-0.1.3-1-x86_64.pkg.tar.zst
sudo pacman -U ./uur-0.1.5-1-x86_64.pkg.tar.zst
```
Install the portal backend supplied or recommended by the selected desktop.
@@ -60,7 +60,7 @@ Zorin OS, elementary OS, KDE neon, TUXEDO OS, Kali Linux, MX Linux, and other
compatible derivatives:
```bash
sudo apt install ./uur_0.1.3_amd64.deb
sudo apt install ./uur_0.1.5_amd64.deb
```
The package manager resolves Wine, PipeWire, and the portal frontend. Install
@@ -74,10 +74,10 @@ dependency names. Install it with the native frontend:
```bash
# Fedora and compatible systems
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
sudo dnf install ./uur-0.1.5-1.x86_64.rpm
# openSUSE family
sudo zypper install ./uur-0.1.3-1.x86_64.rpm
sudo zypper install ./uur-0.1.5-1.x86_64.rpm
```
RHEL, CentOS Stream, Rocky Linux, AlmaLinux, Oracle Linux, Nobara, Ultramarine,
@@ -91,7 +91,7 @@ PCLinuxOS, and similar mutable/FHS systems can use the portable archive when
they provide compatible glibc, Wine, PipeWire, and portal libraries:
```bash
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.5-linux-x86_64.tar.zst
```
Alternatively, build and install for one user:
@@ -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.
+44 -3
View File
@@ -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"
@@ -55,6 +67,11 @@ session:
webview_failed: "WebView2 installation failed"
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."
@@ -64,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"
+43 -2
View File
@@ -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}"
@@ -43,6 +52,11 @@ session:
webview_failed: "WebView2 安装失败"
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: "无法访问网易官方发布接口"
@@ -53,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: "捕获助手异常退出"
@@ -64,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: "已禁用登录自启动"
+5 -2
View File
@@ -7,6 +7,8 @@
makeWrapper,
bash,
pipewire,
wayland,
wayland-scanner,
pulseaudio,
curl,
glib,
@@ -23,7 +25,7 @@ let
in
rustPlatform.buildRustPackage {
pname = "uur";
version = "0.1.3";
version = "0.1.5";
src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;
@@ -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;
+3 -3
View File
@@ -1,14 +1,14 @@
# Contributor: uur contributors
# Maintainer: uur contributors
pkgname=uur
pkgver=0.1.3
pkgver=0.1.5
pkgrel=0
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"
+2 -2
View File
@@ -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"]
+1 -1
View File
@@ -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'
+4 -2
View File
@@ -1,6 +1,6 @@
pkgbase = uur
pkgdesc = Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)
pkgver = 0.1.3
pkgver = 0.1.5
pkgrel = 1
url = https://github.com/panxuc/uur
install = uur.install
@@ -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
@@ -31,7 +33,7 @@ pkgbase = uur
optdepends = libva-utils: VA-API capability diagnostics
optdepends = vulkan-tools: Vulkan and Vulkan Video capability diagnostics
optdepends = nvidia-utils: NVENC and NVDEC capability diagnostics on NVIDIA GPUs
source = uur-0.1.3.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.3.tar.gz
source = uur-0.1.5.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.5.tar.gz
sha256sums = SKIP
pkgname = uur
+3 -2
View File
@@ -8,7 +8,7 @@
# `uur setup` (it is never redistributed by this package).
pkgname=uur
pkgver=0.1.3
pkgver=0.1.5
pkgrel=1
pkgdesc="Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)"
arch=('x86_64')
@@ -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'
+2
View File
@@ -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
+1
View File
@@ -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'
+4
View File
@@ -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"
+7
View File
@@ -9,6 +9,13 @@ Comment[zh_CN]=在本 Linux 桌面启动完整的 UU 远程会话
Exec=uur run
TryExec=uur
Icon=uur
StartupWMClass=gameviewer.exe
Terminal=false
Categories=Network;RemoteAccess;
Keywords=remote;desktop;uu;网易;远程;
Actions=Quit;
[Desktop Action Quit]
Name=Quit
Name[zh_CN]=退出
Exec=uur stop
+33 -8
View File
@@ -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"
+2 -1
View File
@@ -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!(
+59 -1
View File
@@ -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")?;
@@ -219,6 +227,7 @@ fn pump(stream: &mut TcpStream, backend: &mut dyn input::InputBackend) -> Result
let mut header = [0u8; protocol::HEADER_BYTES];
let mut record = [0u8; RECORD_BYTES];
let mut injected: u64 = 0;
let mut warned_unsupported_key = false;
loop {
// EOF is the hook exiting: a clean disconnect, not an error.
match stream.read_exact(&mut header) {
@@ -236,6 +245,19 @@ fn pump(stream: &mut TcpStream, backend: &mut dyn input::InputBackend) -> Result
protocol::RECORD_MOUSE | protocol::RECORD_KEYBOARD => {
stream.read_exact(&mut record)?;
let record = protocol::read_record(&record);
if record.kind == protocol::RECORD_KEYBOARD && record.code == 0 {
// Unicode and scan-code SendInput events do not carry a
// virtual-key code. Text/scan-code transport is not
// supported yet, but one such event must not tear down
// the connection and block later ordinary key events.
if !warned_unsupported_key {
eprintln!(
"ignoring keyboard input without a virtual-key code; Unicode and scan-code input are not supported yet"
);
warned_unsupported_key = true;
}
continue;
}
dispatch(backend, &record)?;
injected += 1;
}
@@ -302,6 +324,9 @@ mod tests {
"test"
}
fn key(&mut self, code: u16, down: bool) -> Result<()> {
if code == 0 {
anyhow::bail!("invalid virtual-key code");
}
self.0.send(format!("key {code} {down}"))?;
Ok(())
}
@@ -342,6 +367,39 @@ mod tests {
)
}
fn input_packet(kind: u32, code: u16, state: u16) -> Vec<u8> {
let mut packet = Vec::new();
for value in [protocol::MAGIC, protocol::VERSION, kind, 16, kind] {
packet.extend_from_slice(&value.to_le_bytes());
}
packet.extend_from_slice(&code.to_le_bytes());
packet.extend_from_slice(&state.to_le_bytes());
packet.extend_from_slice(&0i32.to_le_bytes());
packet.extend_from_slice(&0i32.to_le_bytes());
packet
}
#[test]
fn zero_virtual_key_does_not_disconnect_later_keyboard_input() {
let (shared, events) = shared();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let (mut server, _) = listener.accept().unwrap();
let mut backend = connection(&shared);
let thread = thread::spawn(move || pump(&mut server, &mut backend).unwrap());
client
.write_all(&input_packet(protocol::RECORD_KEYBOARD, 0, 1))
.unwrap();
client
.write_all(&input_packet(protocol::RECORD_KEYBOARD, 65, 1))
.unwrap();
drop(client);
assert_eq!(thread.join().unwrap(), 1);
assert_eq!(events.try_iter().collect::<Vec<_>>(), ["key 65 true"]);
}
#[test]
fn idle_connection_does_not_block_another_connections_motion() {
let (shared, events) = shared();
+153 -43
View File
@@ -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<Child> {
}
}
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<PathBuf> {
/// 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<PathBuf> {
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<PathBuf> {
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)]
+7 -1
View File
@@ -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<String>,
@@ -24,6 +24,10 @@ pub struct Config {
pub remote_desktop_restore_token: Option<String>,
/// 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<String>,
}
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,
}
}
}
+86 -14
View File
@@ -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})"),
);
+8 -2
View File
@@ -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<Box<dyn InputBackend>> {
let on_wayland = std::env::var("WAYLAND_DISPLAY").is_ok();
let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland");
if !matches!(preferred, "auto" | "portal" | "uinput" | "xtest") {
anyhow::bail!("unknown input backend {preferred:?}; use auto, portal, uinput, or xtest");
}
if preferred == "portal" || (preferred == "auto" && on_wayland) {
match portal::PortalBackend::connect() {
@@ -39,10 +43,12 @@ pub fn select(preferred: &str) -> Result<Box<dyn InputBackend>> {
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()?));
}
+10 -4
View File
@@ -12,7 +12,7 @@ const UI_SET_EVBIT: libc::Ioctl = 0x4004_5564_u64 as libc::Ioctl;
const UI_SET_KEYBIT: libc::Ioctl = 0x4004_5565_u64 as libc::Ioctl;
const UI_SET_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()?;
+77 -2
View File
@@ -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<String>,
},
/// 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,
+323 -17
View File
@@ -4,10 +4,11 @@
//! session ends.
use anyhow::{Context, Result};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
@@ -93,6 +94,68 @@ fn hook_source_dir() -> Result<PathBuf> {
.context("hook DLLs not found (run the build first)")
}
static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// Replace a managed prefix file without inheriting the source's permissions.
/// Nix store files are read-only; copying them directly leaves the prefix
/// read-only too, so the next run cannot overwrite them. A temporary file in
/// the destination directory keeps the replacement atomic and also repairs
/// read-only files left by earlier uur versions.
fn deploy_file(source: &Path, target: &Path) -> Result<()> {
let parent = target
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let filename = target
.file_name()
.context("deployment target has no file name")?
.to_string_lossy();
let mut temporary = None;
for _ in 0..32 {
let sequence = DEPLOY_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let path = parent.join(format!(
".{filename}.uur-{}-{sequence}.tmp",
std::process::id()
));
match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => {
temporary = Some((path, file));
break;
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(error).with_context(|| {
format!("creating temporary deployment for {}", target.display())
});
}
}
}
let Some((temporary_path, mut output)) = temporary else {
anyhow::bail!("could not create a temporary file for {}", target.display());
};
let copy_result = (|| -> Result<()> {
let mut input = File::open(source)
.with_context(|| format!("opening deployment source {}", source.display()))?;
std::io::copy(&mut input, &mut output)
.with_context(|| format!("copying deployment source {}", source.display()))?;
output.flush()?;
Ok(())
})();
drop(output);
if let Err(error) = copy_result {
let _ = std::fs::remove_file(&temporary_path);
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary_path, target) {
let _ = std::fs::remove_file(&temporary_path);
return Err(error).with_context(|| format!("deploying to {}", target.display()));
}
Ok(())
}
/// Install the native preload DLLs in the managed prefix, outside the
/// proprietary application directory. Wine's native override resolves them
/// from system32, so client updates never overwrite uur and uur never edits an
@@ -104,7 +167,7 @@ fn deploy_hooks(prefix: &Path) -> Result<()> {
for dll in ["wevtapi.dll", "uur-hook.dll", "wtsapi32.dll"] {
let from = source.join(dll);
let to = target.join(dll);
std::fs::copy(&from, &to)
deploy_file(&from, &to)
.with_context(|| format!("deploying {} to {}", dll, target.display()))?;
}
Ok(())
@@ -152,7 +215,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
std::fs::copy(&target, &backup)
.with_context(|| format!("backing up {}", target.display()))?;
}
std::fs::copy(&source, &target)
deploy_file(&source, &target)
.with_context(|| format!("deploying native terminal proxy to {}", target.display()))?;
std::fs::write(marker, b"managed by uur\n")?;
@@ -163,7 +226,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
std::fs::copy(&mux_target, &mux_backup)
.with_context(|| format!("backing up {}", mux_target.display()))?;
}
std::fs::copy(&mux_source, &mux_target)
deploy_file(&mux_source, &mux_target)
.with_context(|| format!("deploying native mux proxy to {}", mux_target.display()))?;
std::fs::write(mux_marker, b"managed by uur\n")?;
Ok(bin.join("uu-terminal-bridge.runtime"))
@@ -188,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
@@ -202,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(())
@@ -211,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<std::fs::File> {
pub(crate) fn acquire_session_lock() -> Result<std::fs::File> {
use std::os::unix::io::AsRawFd;
let state = std::env::var("XDG_STATE_HOME")
.map(PathBuf::from)
@@ -243,6 +305,7 @@ fn acquire_session_lock() -> Result<std::fs::File> {
struct ManagedChild {
child: Child,
name: String,
terminated: bool,
}
@@ -263,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;
@@ -329,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 {
@@ -342,9 +428,21 @@ 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)),
Err(error) => eprintln!("could not sync Wine DPI from Xft.dpi: {error}"),
}
}
deploy_hooks(&prefix)?;
crate::wine::set_dll_override(&prefix, "wtsapi32", "native")?;
// Re-apply migrations on every launch so an updated uur package repairs
@@ -359,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);
@@ -395,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());
@@ -420,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
@@ -458,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");
@@ -490,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;
@@ -583,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| {
@@ -633,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)
@@ -685,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.
@@ -693,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(());
}
@@ -701,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) {
@@ -714,6 +893,37 @@ fn wait_for_runtime_file(path: &Path, stopping: &AtomicBool) -> Result<()> {
anyhow::bail!("native terminal bridge did not become ready")
}
fn xft_dpi() -> Option<u32> {
use x11rb::connection::Connection;
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt};
let (connection, screen) = x11rb::connect(None).ok()?;
let root = connection.setup().roots.get(screen)?.root;
let resource_manager = connection
.intern_atom(false, b"RESOURCE_MANAGER")
.ok()?
.reply()
.ok()?
.atom;
let resource_manager = connection
.get_property(false, root, resource_manager, AtomEnum::STRING, 0, 16_384)
.ok()?
.reply()
.ok()?;
parse_xft_dpi(&String::from_utf8_lossy(&resource_manager.value))
}
fn parse_xft_dpi(resources: &str) -> Option<u32> {
resources.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
if name.trim() != "Xft.dpi" {
return None;
}
let dpi = value.trim().parse::<f64>().ok()?;
(dpi.is_finite() && (96.0..=480.0).contains(&dpi)).then(|| dpi.round() as u32)
})
}
fn stop_wineserver(prefix: &Path) {
let _ = Command::new("wineserver")
.env("WINEPREFIX", prefix)
@@ -729,6 +939,102 @@ fn wine_debug() -> String {
mod tests {
use super::*;
use std::ffi::OsStr;
use std::os::unix::fs::PermissionsExt;
struct TestDirectory(PathBuf);
impl TestDirectory {
fn create() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
for _ in 0..32 {
let path = std::env::temp_dir().join(format!(
"uur-session-deploy-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("creating test directory: {error}"),
}
}
panic!("could not create a unique test directory");
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TestDirectory {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn deploy_file_repairs_readonly_targets_and_is_repeatable() {
let directory = TestDirectory::create();
let source = directory.path().join("store/uur-hook.dll");
let target = directory.path().join("prefix/system32/uur-hook.dll");
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(&source, b"new hook contents").unwrap();
std::fs::write(&target, b"old hook contents").unwrap();
std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o444)).unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o444)).unwrap();
deploy_file(&source, &target).unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"new hook contents");
assert_ne!(
std::fs::metadata(&target).unwrap().permissions().mode() & 0o200,
0
);
deploy_file(&source, &target).unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"new hook contents");
assert_ne!(
std::fs::metadata(&target).unwrap().permissions().mode() & 0o200,
0
);
assert_eq!(
std::fs::read_dir(target.parent().unwrap()).unwrap().count(),
1
);
}
#[test]
fn deploy_file_does_not_inherit_readonly_source_permissions() {
let directory = TestDirectory::create();
let source = directory.path().join("store/uur-hook.dll");
let target = directory.path().join("prefix/system32/uur-hook.dll");
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(&source, b"hook contents").unwrap();
std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o444)).unwrap();
deploy_file(&source, &target).unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"hook contents");
assert_ne!(
std::fs::metadata(&target).unwrap().permissions().mode() & 0o200,
0
);
}
#[test]
fn parses_xft_dpi_resources() {
assert_eq!(parse_xft_dpi("Xft.antialias: 1\nXft.dpi: 192\n"), Some(192));
assert_eq!(parse_xft_dpi("Xft.dpi: 168.4\n"), Some(168));
}
#[test]
fn ignores_invalid_xft_dpi_resources() {
assert_eq!(parse_xft_dpi("Xft.dpi: 72\n"), None);
assert_eq!(parse_xft_dpi("Xft.dpi: 500\n"), None);
assert_eq!(parse_xft_dpi("Xft.dpi: automatic\n"), None);
assert_eq!(parse_xft_dpi("Xft.antialias: 192\n"), None);
}
#[test]
fn webview2_installer_uses_builtin_wow64_dlls() {
+316
View File
@@ -0,0 +1,316 @@
//! Native StatusNotifierItem and DBusMenu, independent of Wine's XEmbed tray.
//! The supervisor owns this helper, so closing the session removes the item.
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
type Pixmap = (i32, i32, Vec<u8>);
type Properties = HashMap<String, OwnedValue>;
type Layout = (i32, Properties, Vec<OwnedValue>);
#[derive(Clone, Copy)]
enum Action {
Show,
Stop,
}
struct Tray {
actions: UnboundedSender<Action>,
icon: Pixmap,
}
#[zbus::interface(name = "org.kde.StatusNotifierItem")]
impl Tray {
#[zbus(property)]
fn category(&self) -> &str {
"ApplicationStatus"
}
#[zbus(property)]
fn id(&self) -> &str {
"uur"
}
#[zbus(property)]
fn title(&self) -> String {
t!("tray.title").to_string()
}
#[zbus(property)]
fn status(&self) -> &str {
"Active"
}
#[zbus(property)]
fn window_id(&self) -> i32 {
0
}
#[zbus(property)]
fn icon_name(&self) -> &str {
"uur"
}
#[zbus(property)]
fn icon_theme_path(&self) -> &str {
""
}
#[zbus(property)]
fn icon_pixmap(&self) -> Vec<Pixmap> {
vec![self.icon.clone()]
}
#[zbus(property)]
fn attention_icon_name(&self) -> &str {
""
}
#[zbus(property)]
fn attention_icon_pixmap(&self) -> Vec<Pixmap> {
Vec::new()
}
#[zbus(property)]
fn attention_movie_name(&self) -> &str {
""
}
#[zbus(property)]
fn overlay_icon_name(&self) -> &str {
""
}
#[zbus(property)]
fn overlay_icon_pixmap(&self) -> Vec<Pixmap> {
Vec::new()
}
#[zbus(property)]
fn item_is_menu(&self) -> bool {
false
}
#[zbus(property)]
fn menu(&self) -> OwnedObjectPath {
OwnedObjectPath::try_from("/MenuBar").unwrap()
}
#[zbus(property)]
fn tool_tip(&self) -> (String, Vec<Pixmap>, String, String) {
(
"uur".into(),
vec![self.icon.clone()],
t!("tray.title").to_string(),
t!("tray.tooltip").to_string(),
)
}
fn activate(&self, _x: i32, _y: i32) {
let _ = self.actions.send(Action::Show);
}
fn secondary_activate(&self, _x: i32, _y: i32) {
let _ = self.actions.send(Action::Show);
}
// Hosts draw the menu returned by Menu; no X11 popup is necessary.
fn context_menu(&self, _x: i32, _y: i32) {}
fn scroll(&self, _delta: i32, _orientation: &str) {}
fn provide_xdg_activation_token(&self, _token: &str) {}
}
struct Menu {
actions: UnboundedSender<Action>,
}
#[zbus::interface(name = "com.canonical.dbusmenu")]
impl Menu {
#[zbus(property)]
fn version(&self) -> u32 {
3
}
#[zbus(property)]
fn text_direction(&self) -> &str {
"ltr"
}
#[zbus(property)]
fn status(&self) -> &str {
"normal"
}
#[zbus(property)]
fn icon_theme_path(&self) -> Vec<String> {
Vec::new()
}
fn get_layout(
&self,
parent_id: i32,
recursion_depth: i32,
property_names: Vec<String>,
) -> zbus::fdo::Result<(u32, Layout)> {
let properties = menu_properties(parent_id, &property_names)?;
let mut children = Vec::new();
if parent_id == 0 && recursion_depth != 0 {
for id in [1, 2] {
let child = (
id,
menu_properties(id, &property_names)?,
Vec::<OwnedValue>::new(),
);
children.push(
OwnedValue::try_from(Value::new(child))
.map_err(|error| zbus::fdo::Error::Failed(error.to_string()))?,
);
}
}
Ok((1, (parent_id, properties, children)))
}
fn get_group_properties(
&self,
ids: Vec<i32>,
property_names: Vec<String>,
) -> zbus::fdo::Result<Vec<(i32, Properties)>> {
let ids = if ids.is_empty() { vec![0, 1, 2] } else { ids };
ids.into_iter()
.map(|id| Ok((id, menu_properties(id, &property_names)?)))
.collect()
}
fn get_property(&self, id: i32, name: &str) -> zbus::fdo::Result<OwnedValue> {
menu_properties(id, &[])?
.remove(name)
.ok_or_else(|| zbus::fdo::Error::InvalidArgs(format!("unknown menu property {name}")))
}
fn event(
&self,
id: i32,
event_id: &str,
_data: OwnedValue,
_timestamp: u32,
) -> zbus::fdo::Result<()> {
let action = match id {
1 => Action::Show,
2 => Action::Stop,
0 => return Ok(()),
_ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())),
};
if event_id == "clicked" {
let _ = self.actions.send(action);
}
Ok(())
}
fn event_group(&self, events: Vec<(i32, String, OwnedValue, u32)>) -> Vec<i32> {
events
.into_iter()
.filter_map(|(id, event, data, timestamp)| {
self.event(id, &event, data, timestamp).err().map(|_| id)
})
.collect()
}
fn about_to_show(&self, id: i32) -> zbus::fdo::Result<bool> {
menu_properties(id, &[])?;
Ok(false)
}
fn about_to_show_group(&self, ids: Vec<i32>) -> (Vec<i32>, Vec<i32>) {
(
Vec::new(),
ids.into_iter().filter(|id| !(0..=2).contains(id)).collect(),
)
}
}
fn menu_properties(id: i32, requested: &[String]) -> zbus::fdo::Result<Properties> {
let mut properties = Properties::new();
let string = |value: String| OwnedValue::from(zbus::zvariant::Str::from(value));
match id {
0 => {
properties.insert("children-display".into(), string("submenu".into()));
}
1 | 2 => {
properties.insert(
"label".into(),
string(if id == 1 {
t!("tray.open").to_string()
} else {
t!("tray.quit").to_string()
}),
);
properties.insert("enabled".into(), OwnedValue::from(true));
properties.insert("visible".into(), OwnedValue::from(true));
}
_ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())),
}
if !requested.is_empty() {
properties.retain(|key, _| requested.contains(key));
}
Ok(properties)
}
fn icon_pixmap() -> Result<Pixmap> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(include_bytes!(
"../packaging/uur-icon.png"
)));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().context("reading tray icon")?;
let mut pixels = vec![
0;
reader
.output_buffer_size()
.context("tray icon size overflow")?
];
let info = reader
.next_frame(&mut pixels)
.context("decoding tray icon")?;
anyhow::ensure!(
info.color_type == png::ColorType::Rgba,
"tray icon must be RGBA"
);
pixels.truncate(info.buffer_size());
// SNI requires network-byte-order ARGB32, not PNG's RGBA byte order.
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.rotate_right(1);
}
Ok((info.width.try_into()?, info.height.try_into()?, pixels))
}
pub fn serve() -> Result<()> {
let stopping = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?;
signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?;
tokio::runtime::Runtime::new()?.block_on(async {
let (actions, mut receiver) = unbounded_channel();
let connection = zbus::connection::Builder::session()?
.serve_at("/StatusNotifierItem", Tray { actions: actions.clone(), icon: icon_pixmap()? })?
.serve_at("/MenuBar", Menu { actions })?.build().await?;
let bus = zbus::fdo::DBusProxy::new(&connection).await?;
let mut watcher_owner = None;
let mut timer = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
tokio::select! {
action = receiver.recv() => match action {
Some(Action::Show) => {
tokio::task::spawn_blocking(|| {
if let Err(error) = crate::session::show_client() { eprintln!("tray: {error}"); }
});
}
Some(Action::Stop) => {
tokio::task::spawn_blocking(crate::session::stop).await??;
break;
}
None => break,
},
_ = timer.tick() => {
if stopping.load(Ordering::Relaxed) { break; }
let owner = bus.get_name_owner("org.kde.StatusNotifierWatcher".try_into()?).await.ok();
if owner != watcher_owner {
if owner.is_some() {
let watcher = zbus::Proxy::new(&connection, "org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher", "org.kde.StatusNotifierWatcher").await?;
match watcher.call::<_, _, ()>("RegisterStatusNotifierItem", &("/StatusNotifierItem",)).await {
Ok(()) => {
println!("{}", t!("tray.registered"));
watcher_owner = owner;
}
Err(error) => eprintln!("tray registration: {error}"),
}
} else { watcher_owner = None; }
}
}
}
}
Ok(())
})
}
+489
View File
@@ -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<PathBuf, Removal>,
source_install: bool,
}
pub fn run(purge: bool, dry_run: bool, yes: bool) -> Result<()> {
if unsafe { libc::geteuid() } == 0 {
anyhow::bail!("{}", t!("uninstall.no_root"));
}
let mut plan = Plan::build(purge)?;
println!("{}", t!("uninstall.plan"));
for (path, removal) in &plan.entries {
if !matches!(removal, Removal::EmptyDirectory) {
println!(" {}", path.display());
}
}
if purge {
println!("{}", t!("uninstall.purge_warning"));
} else {
println!("{}", t!("uninstall.keep_data"));
}
println!("{}", t!("uninstall.package_hint"));
if dry_run {
println!("{}", t!("uninstall.dry_run"));
return Ok(());
}
if !yes {
if !std::io::stdin().is_terminal() {
anyhow::bail!("{}", t!("uninstall.confirm_required"));
}
print!("{} ", t!("uninstall.confirm"));
std::io::stdout().flush()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer)?;
if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
println!("{}", t!("uninstall.cancelled"));
return Ok(());
}
}
crate::session::stop()?;
// Keep setup/run excluded until the directory cleanup has finished.
let _session_lock = crate::session::acquire_session_lock()?;
stop_prefix(&plan.data.join("wine"))?;
// Revalidate the displayed targets after stopping the session. Do not add
// newly discovered files to a plan the user has already confirmed.
plan.validate()?;
// Remove integrations first, then the trees; the running ELF can be
// unlinked on Linux, so source installs need no second helper process.
let trees: Vec<_> = plan
.entries
.iter()
.filter_map(|(path, removal)| matches!(removal, Removal::Tree).then_some(path.clone()))
.collect();
plan.entries.retain(|path, removal| {
!matches!(removal, Removal::File)
|| !trees
.iter()
.any(|root| path != root && path.starts_with(root))
});
let mut removals: Vec<_> = plan
.entries
.iter()
.filter(|(_, removal)| !matches!(removal, Removal::EmptyDirectory))
.collect();
// Keep the receipt until all installed files are removed, so a failed
// cleanup can be retried from another copy of uur.
removals.sort_by_key(
|(path, _)| match path.file_name().and_then(|name| name.to_str()) {
Some("user-install") => 2,
Some("uur") if path.parent().and_then(Path::file_name) == Some("bin".as_ref()) => 1,
_ => 0,
},
);
for (path, removal) in removals {
remove(path, *removal)?;
}
for (path, removal) in plan.entries.iter().rev() {
if matches!(removal, Removal::EmptyDirectory) {
remove(path, *removal)?;
}
}
println!("{}", t!("uninstall.done"));
if !plan.source_install {
println!("{}", t!("uninstall.package_hint"));
}
Ok(())
}
impl Plan {
fn build(purge: bool) -> Result<Self> {
let home = absolute(PathBuf::from(
std::env::var_os("HOME").context("HOME is unset")?,
))?;
let data_home = xdg_home("XDG_DATA_HOME", &home.join(".local/share"))?;
let config_home = xdg_home("XDG_CONFIG_HOME", &home.join(".config"))?;
let state_home = xdg_home("XDG_STATE_HOME", &home.join(".local/state"))?;
let runtime_home = xdg_home(
"XDG_RUNTIME_DIR",
&PathBuf::from(format!("/tmp/uur-{}", unsafe { libc::geteuid() })),
)?;
let mut plan = Self {
home: home.clone(),
data: data_home.join("uur"),
config: config_home.join("uur"),
state: state_home.join("uur"),
runtime: runtime_home.join("uur"),
entries: BTreeMap::new(),
source_install: false,
};
plan.entries.insert(plan.runtime.clone(), Removal::Tree);
if purge {
for path in [&plan.data, &plan.config, &plan.state] {
plan.entries.insert(path.clone(), Removal::Tree);
}
}
let default_scope = data_home == home.join(".local/share");
let mut desktops = BTreeSet::new();
scan_files(&data_home.join("applications"), 8, &mut desktops)?;
// Old releases placed compatibility aliases in ~/.local/share even
// when XDG_DATA_HOME was set. Only entries tied to this prefix qualify.
scan_files(&home.join(".local/share/applications"), 8, &mut desktops)?;
scan_files(&desktop_dir(&home, &config_home), 1, &mut desktops)?;
let autostart = config_home.join("autostart/uur.desktop");
if autostart.exists() {
desktops.insert(autostart);
}
let mut removed_icons = BTreeSet::new();
let mut kept_icons = BTreeSet::new();
let mut remove_default_icons = default_scope;
for path in desktops {
if path
.extension()
.is_none_or(|extension| extension != "desktop")
{
continue;
}
let content = std::fs::read_to_string(&path)
.with_context(|| format!("reading {}", path.display()))?;
let icon = desktop_value(&content, "Icon").unwrap_or_default();
if plan.owns_desktop(&content, default_scope) {
remove_default_icons |= path.starts_with(home.join(".local/share/applications"))
|| path.starts_with(desktop_dir(&home, &config_home));
plan.entries.insert(path, Removal::File);
removed_icons.insert(icon.to_string());
} else {
kept_icons.insert(icon.to_string());
}
}
let mut icon_roots = BTreeSet::from([data_home.join("icons")]);
if remove_default_icons {
icon_roots.insert(home.join(".local/share/icons"));
}
for icons in icon_roots {
let mut files = BTreeSet::new();
scan_files(&icons, 6, &mut files)?;
for path in files {
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let alias = stem.strip_suffix(".0").unwrap_or(stem);
if (removed_icons.contains(stem) || removed_icons.contains(alias))
&& !kept_icons.contains(stem)
&& !kept_icons.contains(alias)
{
plan.entries.insert(path, Removal::File);
}
}
}
plan.source_files()?;
plan.validate()?;
Ok(plan)
}
fn owns_desktop(&self, content: &str, default_scope: bool) -> bool {
let prefix = self.data.join("wine");
if let Some(recorded) = desktop_value(content, "X-UUR-Prefix") {
return desktop_value(content, "X-UUR-Managed") == Some("true")
&& recorded == prefix.to_string_lossy();
}
let managed = desktop_value(content, "X-UUR-Managed") == Some("true")
|| desktop_value(content, "Comment") == Some("Start the managed UU Remote session")
|| desktop_value(content, "Comment") == Some("UU Remote for Linux (uur)");
if managed && default_scope {
return true;
}
// Wine writes an explicit WINEPREFIX assignment in its launchers.
// Match the entire quoted/unquoted value, not a filename substring.
let exec = desktop_value(content, "Exec").unwrap_or_default();
let prefix = prefix.to_string_lossy();
let references_prefix = [
format!("WINEPREFIX=\"{prefix}\" "),
format!("WINEPREFIX='{prefix}' "),
format!("WINEPREFIX={prefix} "),
]
.iter()
.any(|assignment| exec.contains(assignment));
references_prefix && exec.to_ascii_lowercase().contains("gameviewer")
}
fn source_files(&mut self) -> Result<()> {
let executable = std::env::current_exe()?;
let mut prefixes = BTreeSet::from([self.home.join(".local")]);
if let Some(prefix) = executable.parent().and_then(Path::parent) {
if executable.parent().and_then(Path::file_name) == Some("bin".as_ref()) {
prefixes.insert(prefix.to_path_buf());
}
}
if let Some(prefix) = std::env::var_os("UUR_INSTALL_PREFIX") {
prefixes.insert(absolute(PathBuf::from(prefix))?);
}
for prefix in prefixes {
let receipt = prefix.join("lib/uur/user-install");
let marked = std::fs::read_to_string(&receipt).is_ok_and(|content| {
content == format!("uur-user-install-v1\n{}\n", self.data.display())
});
// Support the previous source installer, but only while executing
// its ~/.local/bin/uur and with the matching generated menu entry.
let legacy = prefix == self.home.join(".local")
&& std::fs::canonicalize(prefix.join("bin/uur")).ok() == Some(executable.clone())
&& std::fs::read_to_string(prefix.join("share/applications/uur.desktop"))
.is_ok_and(|content| {
desktop_value(&content, "TryExec")
== Some(prefix.join("bin/uur").to_string_lossy().as_ref())
});
if !marked && !legacy {
continue;
}
self.source_install = true;
for relative in [
"bin/uur",
"lib/uur/user-install",
"lib/uur/uur-pw-capture",
"lib/uur/uur-wl-capture",
"lib/uur/hook/wevtapi.dll",
"lib/uur/hook/uur-hook.dll",
"lib/uur/hook/wtsapi32.dll",
"lib/uur/hook/winlogon.exe",
"lib/uur/hook/uur-terminal-proxy.exe",
"lib/uur/hook/uur-mux-proxy.exe",
"lib/uur/hook/uur-launch-proxy.exe",
"share/applications/uur.desktop",
"share/icons/hicolor/256x256/apps/uur.png",
] {
let path = prefix.join(relative);
if std::fs::symlink_metadata(&path).is_ok() {
self.entries.insert(path, Removal::File);
}
}
for relative in ["lib/uur/hook", "lib/uur"] {
self.entries
.insert(prefix.join(relative), Removal::EmptyDirectory);
}
}
Ok(())
}
fn validate(&self) -> Result<()> {
// Session shutdown/locking access these paths before tree removal.
// Reject redirected state rather than following a link while writing
// the lock or stopping an unrelated Wine prefix.
for path in [
&self.data,
&self.state,
&self.runtime,
&self.state.join("session.lock"),
&self.data.join("wine"),
] {
if path.is_symlink() {
anyhow::bail!("refusing redirected session state: {}", path.display());
}
if std::fs::metadata(path)
.is_ok_and(|metadata| metadata.uid() != unsafe { libc::geteuid() })
{
anyhow::bail!("session state belongs to another user: {}", path.display());
}
}
for (path, removal) in &self.entries {
let path = absolute(path.clone())?;
// Resolve ancestor links, but never resolve the final link: remove
// symlink entries themselves, not the objects they point at.
let resolved = path
.parent()
.and_then(|parent| std::fs::canonicalize(parent).ok())
.map(|parent| parent.join(path.file_name().unwrap_or_default()))
.unwrap_or_else(|| path.clone());
if path == self.home || resolved == self.home || path.parent().is_none() {
anyhow::bail!("refusing to remove {}", path.display());
}
// Never allow a receipt or an XDG override to select system trees.
for system in [
"/usr", "/etc", "/opt", "/var", "/nix", "/bin", "/lib", "/sbin", "/boot", "/dev",
"/proc", "/sys",
] {
if path.starts_with(system) || resolved.starts_with(system) {
anyhow::bail!("refusing to remove system path {}", path.display());
}
}
match std::fs::symlink_metadata(&path) {
Ok(metadata) => {
if metadata.uid() != unsafe { libc::geteuid() } {
anyhow::bail!(
"refusing to remove a path owned by another user: {}",
path.display()
);
}
if matches!(removal, Removal::Tree)
&& !metadata.file_type().is_symlink()
&& (path.join(".git").exists() || path.join("Cargo.toml").exists())
{
anyhow::bail!("refusing to remove a source checkout: {}", path.display());
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(error).with_context(|| format!("checking {}", path.display()))
}
}
}
Ok(())
}
}
fn absolute(path: PathBuf) -> Result<PathBuf> {
if !path.is_absolute() {
anyhow::bail!(
"uninstall requires absolute XDG/install paths: {}",
path.display()
);
}
let mut normalized = PathBuf::from("/");
for component in path.components() {
match component {
Component::Normal(part) => normalized.push(part),
Component::ParentDir => {
normalized.pop();
}
_ => {}
}
}
Ok(normalized)
}
fn xdg_home(variable: &str, fallback: &Path) -> Result<PathBuf> {
absolute(
std::env::var_os(variable)
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| fallback.to_path_buf()),
)
}
fn desktop_value<'a>(content: &'a str, key: &str) -> Option<&'a str> {
let mut main_section = false;
for line in content.lines() {
if line.starts_with('[') {
main_section = line == "[Desktop Entry]";
} else if main_section {
if let Some((name, value)) = line.split_once('=') {
if name == key {
return Some(value);
}
}
}
}
None
}
fn desktop_dir(home: &Path, config_home: &Path) -> PathBuf {
// user-dirs.dirs is data, not a shell script: never source it.
std::fs::read_to_string(config_home.join("user-dirs.dirs"))
.ok()
.and_then(|content| {
content.lines().find_map(|line| {
let value = line.strip_prefix("XDG_DESKTOP_DIR=\"")?.strip_suffix('"')?;
let path = value
.strip_prefix("$HOME/")
.map(|suffix| home.join(suffix))
.unwrap_or_else(|| PathBuf::from(value));
(path.is_absolute() && path != home).then_some(path)
})
})
.unwrap_or_else(|| home.join("Desktop"))
}
fn scan_files(dir: &Path, depth: u8, files: &mut BTreeSet<PathBuf>) -> Result<()> {
if depth == 0 {
return Ok(());
}
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("listing {}", dir.display())),
};
for entry in entries {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_dir() {
scan_files(&entry.path(), depth - 1, files)?;
} else if kind.is_file() {
files.insert(entry.path());
}
}
Ok(())
}
fn stop_prefix(prefix: &Path) -> Result<()> {
if !prefix.is_dir() || prefix.is_symlink() {
return Ok(());
}
match Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-k")
.stdin(Stdio::null())
.status()
{
// -k exits 1 when stop already shut down this prefix's server. The
// following -w, with a deadline, is the actual shutdown check.
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).context("stopping the managed wineserver"),
}
let mut wait = Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-w")
.stdin(Stdio::null())
.spawn()?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
if let Some(status) = wait.try_wait()? {
if !status.success() {
anyhow::bail!("wineserver shutdown failed");
}
return Ok(());
}
if std::time::Instant::now() >= deadline {
let _ = wait.kill();
let _ = wait.wait();
anyhow::bail!("managed wineserver is still running; no files were removed");
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
fn remove(path: &Path, removal: Removal) -> Result<()> {
let metadata = match std::fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("checking {}", path.display())),
};
let result = match removal {
Removal::Tree if metadata.is_dir() && !metadata.file_type().is_symlink() => {
std::fs::remove_dir_all(path)
}
Removal::EmptyDirectory if metadata.is_dir() => std::fs::remove_dir(path),
_ => std::fs::remove_file(path),
};
match result {
Err(error)
if matches!(removal, Removal::EmptyDirectory)
&& error.kind() == std::io::ErrorKind::DirectoryNotEmpty =>
{
Ok(())
}
other => other.with_context(|| format!("removing {}", path.display())),
}
}
+37 -4
View File
@@ -276,12 +276,13 @@ fn detect_runtime_provider() -> Option<PathBuf> {
.and_then(OsStr::to_str)
.unwrap_or_default();
let candidate = match executable {
"swaybg" => argument_after(&arguments, "-i"),
"xwallpaper" => arguments.last().cloned(),
"mpvpaper" => arguments.last().cloned(),
"swaybg" => argument_after(&arguments, "-i").map(PathBuf::from),
"xwallpaper" => arguments.last().map(PathBuf::from),
"mpvpaper" => arguments.last().map(PathBuf::from),
"wpaperd" => wpaperd_link(&entry.path()),
_ => None,
};
if let Some(path) = candidate.and_then(|value| resolve_candidate(PathBuf::from(value))) {
if let Some(path) = candidate.and_then(resolve_candidate) {
return Some(path);
}
}
@@ -303,6 +304,32 @@ fn argument_after(arguments: &[String], option: &str) -> Option<String> {
.map(|pair| pair[1].clone())
}
/// wpaperd >= 1.1.0 mirrors the current wallpaper of every output as a
/// symlink under `$XDG_STATE_HOME/wpaperd/wallpapers`, rewritten on each
/// change. Image paths are written verbatim, so absolute targets are used
/// as-is while relative ones resolve against wpaperd's working directory.
/// The newest resolvable link wins; leftovers from earlier runs are older.
fn wpaperd_link(proc: &Path) -> Option<PathBuf> {
let cwd = std::fs::read_link(proc.join("cwd")).ok()?;
std::fs::read_dir(state_home().join("wpaperd/wallpapers"))
.ok()?
.flatten()
.filter_map(|entry| {
let link = entry.path();
let target = std::fs::read_link(&link).ok()?;
let target = if target.is_absolute() {
target
} else {
cwd.join(target)
};
let path = resolve_candidate(target)?;
let modified = std::fs::symlink_metadata(&link).ok()?.modified().ok()?;
Some((modified, path))
})
.max_by_key(|(modified, _)| *modified)
.map(|(_, path)| path)
}
fn wallpaper_from_value(value: &str, provider: &'static str) -> Option<Wallpaper> {
let value = value.trim().trim_matches(['\'', '"']);
if value.is_empty() {
@@ -545,6 +572,12 @@ fn config_home() -> PathBuf {
.unwrap_or_else(|| home_dir().join(".config"))
}
fn state_home() -> PathBuf {
std::env::var_os("XDG_STATE_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".local/state"))
}
fn home_dir() -> PathBuf {
std::env::var_os("HOME")
.map(PathBuf::from)
+193 -74
View File
@@ -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<bool> {
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(())
@@ -239,6 +286,39 @@ pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
Ok(())
}
pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
let status = log_pixels_command(prefix, dpi)
.status()
.context("setting the Wine system DPI")?;
if !status.success() {
anyhow::bail!("Wine rejected the system DPI value {dpi}");
}
Ok(())
}
fn log_pixels_command(prefix: &Path, dpi: u32) -> Command {
let mut command = Command::new("wine");
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
"reg",
"add",
r"HKCU\Control Panel\Desktop",
"/v",
"LogPixels",
"/t",
"REG_DWORD",
"/d",
&dpi.to_string(),
"/f",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
command
}
fn wine_debug() -> String {
std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string())
}
@@ -261,15 +341,21 @@ pub fn find_client_dir(prefix: &Path) -> Option<PathBuf> {
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
@@ -282,7 +368,11 @@ fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf>
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() {
@@ -324,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() {
@@ -349,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();
@@ -372,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()))?;
@@ -422,7 +515,9 @@ fn purge_wine_shortcuts() {
#[cfg(test)]
mod tests {
use super::log_pixels_command;
use super::registry_compat_entries;
use std::path::Path;
#[test]
fn bundled_cpp_runtime_is_preferred_for_both_uu_processes() {
@@ -436,4 +531,28 @@ mod tests {
assert!(values.contains(&("msvcp140", "REG_SZ", "native,builtin")));
}
}
#[test]
fn system_dpi_command_writes_winecfg_logpixels_value() {
let command = log_pixels_command(Path::new("/tmp/wine-prefix"), 192);
let args = command
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>();
assert_eq!(
args,
[
"reg",
"add",
r"HKCU\Control Panel\Desktop",
"/v",
"LogPixels",
"/t",
"REG_DWORD",
"/d",
"192",
"/f",
]
);
}
}