Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56971eeba1 | ||
|
|
f02dcdd8c0 | ||
|
|
e7724c6d86 | ||
|
|
a5e2aa44cd | ||
|
|
306489d8ad | ||
|
|
bfecaa5c69 | ||
|
|
1dc156739c | ||
|
|
ef72baa56d | ||
|
|
8c0589021f | ||
|
|
d349e6ff6a | ||
|
|
01e7ed7218 | ||
|
|
3c78382f20 | ||
|
|
2833b08a37 | ||
|
|
8fd476d81c | ||
|
|
31aaab0fee | ||
|
|
5245c9ee61 | ||
|
|
9f12a88a08 | ||
|
|
2b41541128 | ||
|
|
d47178916f | ||
|
|
3dc3b62477 |
No files matched your search
@@ -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: |
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -2,5 +2,6 @@
|
||||
/build
|
||||
/dist
|
||||
/capture/uur-pw-capture
|
||||
/capture/uur-wl-capture
|
||||
Cargo.lock.orig
|
||||
*.tar.gz
|
||||
Generated
+83
-1
@@ -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.6"
|
||||
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
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "uur"
|
||||
version = "0.1.3"
|
||||
version = "0.1.6"
|
||||
edition = "2021"
|
||||
description = "Native Linux companion for NetEase UU Remote: X11/Wayland input and capture, packaged as a regular desktop app"
|
||||
license = "MIT"
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.6-1-x86_64.pkg.tar.zst
|
||||
```
|
||||
|
||||
### AUR
|
||||
@@ -83,13 +83,13 @@ paru -S uur
|
||||
### Debian and Ubuntu package family
|
||||
|
||||
```bash
|
||||
sudo apt install ./uur_0.1.3_amd64.deb
|
||||
sudo apt install ./uur_0.1.6_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.6-1.x86_64.rpm
|
||||
```
|
||||
|
||||
On systems with different RPM dependency names, install the dependencies
|
||||
@@ -98,7 +98,7 @@ manually or use the portable archive.
|
||||
### Portable archive
|
||||
|
||||
```bash
|
||||
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
|
||||
sudo tar --zstd -C / -xf ./uur-0.1.6-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
@@ -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.6-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.6_amd64.deb
|
||||
```
|
||||
|
||||
### Fedora 及兼容 RPM 发行版
|
||||
|
||||
```bash
|
||||
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
|
||||
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
|
||||
```
|
||||
|
||||
如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。
|
||||
@@ -94,7 +94,7 @@ sudo dnf install ./uur-0.1.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.6-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
|
||||
|
||||
@@ -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"
|
||||
+236
-57
@@ -16,6 +16,8 @@
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <linux/dma-buf.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
@@ -23,14 +25,20 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <pipewire/pipewire.h>
|
||||
#include <spa/param/video/format-utils.h>
|
||||
#include <drm/drm_fourcc.h>
|
||||
#include "../hook/frame-protocol.h"
|
||||
|
||||
#define FRAME_FORMAT_BGRX 1
|
||||
#ifndef SPA_CHUNK_FLAG_EMPTY
|
||||
#define SPA_CHUNK_FLAG_EMPTY (1u << 1)
|
||||
#endif
|
||||
|
||||
struct frame_header {
|
||||
uint32_t magic;
|
||||
@@ -63,16 +71,31 @@ struct capture {
|
||||
int shm_fd;
|
||||
uint8_t *shm;
|
||||
size_t shm_size;
|
||||
int dmabuf_usable;
|
||||
int exit_status;
|
||||
volatile sig_atomic_t stopping;
|
||||
int was_streaming;
|
||||
uint64_t started_ms;
|
||||
uint64_t paused_ms;
|
||||
char frame_path[PATH_MAX];
|
||||
};
|
||||
|
||||
static struct capture *active_capture;
|
||||
|
||||
static uint64_t monotonic_ms(void)
|
||||
{
|
||||
struct timespec now;
|
||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
return (uint64_t)now.tv_sec * 1000 + (uint64_t)now.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
static void stop_capture(int signal_number)
|
||||
{
|
||||
(void)signal_number;
|
||||
if (active_capture != NULL && active_capture->loop != NULL)
|
||||
if (active_capture != NULL && active_capture->loop != NULL) {
|
||||
active_capture->stopping = 1;
|
||||
pw_main_loop_quit(active_capture->loop);
|
||||
}
|
||||
}
|
||||
|
||||
static struct frame_slot *slot_at(struct capture *c, uint64_t n)
|
||||
@@ -88,8 +111,8 @@ static uint8_t *slot_frame(struct frame_slot *slot)
|
||||
return (uint8_t *)slot + sizeof(struct frame_slot);
|
||||
}
|
||||
|
||||
/* Create (or resize) the shared file for the negotiated geometry and write
|
||||
* the header. Called once, from param_changed, before any frame exists. */
|
||||
/* Publish a new inode for every geometry. A Wine reader may still map the
|
||||
* previous inode: never truncate or resize memory another process is reading. */
|
||||
static int shm_setup(struct capture *c)
|
||||
{
|
||||
size_t slot_bytes = sizeof(struct frame_slot) +
|
||||
@@ -103,26 +126,30 @@ static int shm_setup(struct capture *c)
|
||||
return -1;
|
||||
}
|
||||
|
||||
c->shm_fd = open(c->frame_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC,
|
||||
0600);
|
||||
if (c->shm_fd < 0) {
|
||||
char temporary[PATH_MAX];
|
||||
if (snprintf(temporary, sizeof(temporary), "%s.XXXXXX", c->frame_path) >=
|
||||
(int)sizeof(temporary))
|
||||
return -1;
|
||||
int fd = mkostemp(temporary, O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
perror("open frame transport");
|
||||
return -1;
|
||||
}
|
||||
if (ftruncate(c->shm_fd, (off_t)total) < 0) {
|
||||
if (fchmod(fd, 0600) < 0 || ftruncate(fd, (off_t)total) < 0) {
|
||||
perror("ftruncate");
|
||||
close(fd);
|
||||
unlink(temporary);
|
||||
return -1;
|
||||
}
|
||||
c->shm = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED,
|
||||
c->shm_fd, 0);
|
||||
if (c->shm == MAP_FAILED) {
|
||||
uint8_t *mapping = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (mapping == MAP_FAILED) {
|
||||
perror("mmap");
|
||||
c->shm = NULL;
|
||||
close(fd);
|
||||
unlink(temporary);
|
||||
return -1;
|
||||
}
|
||||
c->shm_size = total;
|
||||
|
||||
struct frame_header *header = (struct frame_header *)c->shm;
|
||||
struct frame_header *header = (struct frame_header *)mapping;
|
||||
header->magic = 0x46525555u; /* "UURF" */
|
||||
header->version = UURF_VERSION;
|
||||
header->width = c->width;
|
||||
@@ -131,8 +158,29 @@ static int shm_setup(struct capture *c)
|
||||
header->format = FRAME_FORMAT_BGRX;
|
||||
atomic_init(&header->total_frames, 0);
|
||||
for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) {
|
||||
atomic_init(&slot_at(c, (uint64_t)i)->seq, 0);
|
||||
struct frame_slot *slot = (struct frame_slot *)(mapping +
|
||||
UURF_HEADER_BYTES + i * slot_bytes);
|
||||
atomic_init(&slot->seq, 0);
|
||||
}
|
||||
if (rename(temporary, c->frame_path) < 0) {
|
||||
perror("publish frame transport");
|
||||
munmap(mapping, total);
|
||||
close(fd);
|
||||
unlink(temporary);
|
||||
return -1;
|
||||
}
|
||||
if (c->shm != NULL) {
|
||||
struct frame_header *previous = (struct frame_header *)c->shm;
|
||||
atomic_store_explicit(&previous->total_frames, 0, memory_order_release);
|
||||
munmap(c->shm, c->shm_size);
|
||||
}
|
||||
if (c->shm_fd >= 0)
|
||||
close(c->shm_fd);
|
||||
c->shm = mapping;
|
||||
c->shm_fd = fd;
|
||||
c->shm_size = total;
|
||||
c->counter = 0;
|
||||
c->started_ms = monotonic_ms();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -180,6 +228,16 @@ static void publish_frame(struct capture *c, const uint8_t *pixels,
|
||||
memory_order_release);
|
||||
}
|
||||
|
||||
static int sync_dmabuf(int fd, uint64_t flags)
|
||||
{
|
||||
struct dma_buf_sync sync = {.flags = flags};
|
||||
int result;
|
||||
do {
|
||||
result = ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync);
|
||||
} while (result < 0 && errno == EINTR);
|
||||
return result;
|
||||
}
|
||||
|
||||
static void on_process(void *userdata)
|
||||
{
|
||||
struct capture *c = userdata;
|
||||
@@ -193,38 +251,67 @@ static void on_process(void *userdata)
|
||||
uint8_t *pixels = NULL;
|
||||
void *mapping = MAP_FAILED;
|
||||
size_t mapping_size = 0;
|
||||
int synchronized = 0;
|
||||
int dmabuf = plane->type == SPA_DATA_DmaBuf;
|
||||
|
||||
if (plane->chunk == NULL) {
|
||||
pw_stream_queue_buffer(c->stream, buffer);
|
||||
return;
|
||||
if (plane->chunk == NULL || plane->chunk->stride < 0 ||
|
||||
(plane->chunk->flags & (SPA_CHUNK_FLAG_CORRUPTED | SPA_CHUNK_FLAG_EMPTY)))
|
||||
goto done;
|
||||
uint32_t row_bytes = c->width *
|
||||
(c->format == SPA_VIDEO_FORMAT_BGR || c->format == SPA_VIDEO_FORMAT_RGB ? 3u : 4u);
|
||||
uint32_t stride = plane->chunk->stride > 0 ?
|
||||
(uint32_t)plane->chunk->stride : row_bytes;
|
||||
uint64_t span = (uint64_t)stride * (c->height - 1) + row_bytes;
|
||||
uint32_t data_offset = plane->chunk->offset;
|
||||
if (stride < row_bytes || span > 256u * 1024 * 1024)
|
||||
goto done;
|
||||
if (dmabuf) {
|
||||
// DMA-BUF maxsize/chunk size may be zero or placeholders. Query
|
||||
// the fd and include BOTH the plane mapping and chunk offsets.
|
||||
if (!c->dmabuf_usable || plane->fd < 0)
|
||||
goto done;
|
||||
off_t extent = lseek((int)plane->fd, 0, SEEK_END);
|
||||
uint64_t end = (uint64_t)plane->mapoffset + data_offset + span;
|
||||
if (extent < 0 || end > (uint64_t)extent)
|
||||
goto done;
|
||||
struct pollfd ready = {.fd = (int)plane->fd, .events = POLLIN};
|
||||
if (poll(&ready, 1, 100) <= 0 || !(ready.revents & POLLIN) ||
|
||||
sync_dmabuf((int)plane->fd, DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ) < 0)
|
||||
goto done;
|
||||
synchronized = 1;
|
||||
} else {
|
||||
if (plane->maxsize == 0)
|
||||
goto done;
|
||||
data_offset %= plane->maxsize;
|
||||
if ((uint64_t)data_offset + span > plane->maxsize ||
|
||||
span > plane->chunk->size)
|
||||
goto done;
|
||||
}
|
||||
if (plane->data != NULL) {
|
||||
pixels = plane->data + plane->chunk->offset;
|
||||
} else if (plane->type == SPA_DATA_MemFd && plane->fd >= 0) {
|
||||
pixels = (uint8_t *)plane->data + data_offset;
|
||||
} else if ((dmabuf || plane->type == SPA_DATA_MemFd) && plane->fd >= 0) {
|
||||
long page_size = sysconf(_SC_PAGESIZE);
|
||||
uint64_t offset = (uint64_t)plane->mapoffset + plane->chunk->offset;
|
||||
uint64_t offset = (uint64_t)plane->mapoffset + data_offset;
|
||||
uint64_t page_mask = (uint64_t)(page_size > 0 ? page_size : 4096) - 1;
|
||||
off_t aligned = (off_t)(offset & ~page_mask);
|
||||
size_t delta = (size_t)(offset - (uint64_t)aligned);
|
||||
mapping_size = delta + plane->chunk->size;
|
||||
mapping = mmap(NULL, mapping_size, PROT_READ, MAP_PRIVATE,
|
||||
mapping_size = delta + (size_t)span;
|
||||
mapping = mmap(NULL, mapping_size, PROT_READ, MAP_SHARED,
|
||||
plane->fd, aligned);
|
||||
if (mapping != MAP_FAILED)
|
||||
pixels = (uint8_t *)mapping + delta;
|
||||
}
|
||||
if (pixels != NULL) {
|
||||
int32_t signed_stride = plane->chunk->stride;
|
||||
uint32_t stride = signed_stride > 0
|
||||
? (uint32_t)signed_stride
|
||||
: (c->format == SPA_VIDEO_FORMAT_BGR ||
|
||||
c->format == SPA_VIDEO_FORMAT_RGB
|
||||
? c->width * 3
|
||||
: c->width * 4);
|
||||
uint32_t rows = stride > 0 ? plane->chunk->size / stride : 0;
|
||||
publish_frame(c, pixels, stride, rows);
|
||||
if (mapping != MAP_FAILED)
|
||||
munmap(mapping, mapping_size);
|
||||
if (c->counter == 0)
|
||||
fprintf(stderr, "capture buffer: %s, source stride %u, chunk offset %u\n",
|
||||
dmabuf ? "linear DMA-BUF" : "shared memory", stride, data_offset);
|
||||
publish_frame(c, pixels, stride, c->height);
|
||||
}
|
||||
done:
|
||||
if (synchronized)
|
||||
(void)sync_dmabuf((int)plane->fd, DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ);
|
||||
if (mapping != MAP_FAILED)
|
||||
munmap(mapping, mapping_size);
|
||||
}
|
||||
|
||||
pw_stream_queue_buffer(c->stream, buffer);
|
||||
@@ -237,7 +324,7 @@ static void on_param_changed(void *userdata, uint32_t id,
|
||||
if (param == NULL || id != SPA_PARAM_Format)
|
||||
return;
|
||||
|
||||
struct spa_video_info_raw info;
|
||||
struct spa_video_info_raw info = {0};
|
||||
if (spa_format_video_raw_parse(param, &info) < 0)
|
||||
return;
|
||||
if (info.format != SPA_VIDEO_FORMAT_BGRx &&
|
||||
@@ -250,29 +337,92 @@ static void on_param_changed(void *userdata, uint32_t id,
|
||||
return;
|
||||
}
|
||||
|
||||
if (info.size.width == 0 || info.size.height == 0 ||
|
||||
info.size.width > 16384 || info.size.height > 16384 ||
|
||||
(uint64_t)info.size.width * 4 * info.size.height > 256u * 1024 * 1024) {
|
||||
fprintf(stderr, "unsupported capture geometry\n");
|
||||
c->exit_status = 1;
|
||||
pw_main_loop_quit(c->loop);
|
||||
return;
|
||||
}
|
||||
c->width = (uint32_t)info.size.width;
|
||||
c->height = (uint32_t)info.size.height;
|
||||
c->format = info.format;
|
||||
c->stride = SPA_ROUND_UP_N(c->width * 4, 4);
|
||||
fprintf(stderr, "negotiated: %ux%u stride %u\n", c->width, c->height,
|
||||
c->stride);
|
||||
/* The DMA-BUF path mmaps the fd directly, which is only correct for a
|
||||
* linear layout. A tiled modifier needs a real importer (GBM/EGL), so
|
||||
* refuse to publish garbage rather than emit a corrupt frame. */
|
||||
c->dmabuf_usable = spa_pod_find_prop(param, NULL, SPA_FORMAT_VIDEO_modifier) != NULL &&
|
||||
info.modifier == DRM_FORMAT_MOD_LINEAR;
|
||||
fprintf(stderr, "negotiated: %ux%u stride %u modifier %#llx%s\n", c->width,
|
||||
c->height, c->stride, (unsigned long long)info.modifier,
|
||||
c->dmabuf_usable ? "" : " (DMA-BUF CPU mapping disabled)");
|
||||
|
||||
if (c->shm == NULL && shm_setup(c) < 0) {
|
||||
pw_main_loop_quit(c->loop);
|
||||
const struct frame_header *header = (const struct frame_header *)c->shm;
|
||||
if (header == NULL || header->width != c->width || header->height != c->height) {
|
||||
if (shm_setup(c) < 0) {
|
||||
c->exit_status = 1;
|
||||
pw_main_loop_quit(c->loop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void on_state_changed(void *userdata, enum pw_stream_state old,
|
||||
enum pw_stream_state state, const char *error)
|
||||
{
|
||||
(void)userdata;
|
||||
(void)old;
|
||||
struct capture *c = userdata;
|
||||
fprintf(stderr, "stream state: %s%s%s\n",
|
||||
pw_stream_state_as_string(state),
|
||||
error != NULL && error[0] != '\0' ? " - " : "",
|
||||
error != NULL ? error : "");
|
||||
if (c->stopping)
|
||||
return;
|
||||
if (state == PW_STREAM_STATE_STREAMING) {
|
||||
c->was_streaming = 1;
|
||||
c->paused_ms = 0;
|
||||
} else if (state == PW_STREAM_STATE_PAUSED && c->was_streaming) {
|
||||
if (c->paused_ms == 0)
|
||||
c->paused_ms = monotonic_ms();
|
||||
} else if (state == PW_STREAM_STATE_ERROR ||
|
||||
(state == PW_STREAM_STATE_UNCONNECTED && old != state)) {
|
||||
c->exit_status = 75;
|
||||
pw_main_loop_quit(c->loop);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_watchdog(void *userdata, uint64_t expirations)
|
||||
{
|
||||
struct capture *c = userdata;
|
||||
(void)expirations;
|
||||
uint64_t now = monotonic_ms();
|
||||
// A static desktop can legitimately produce no new frames while streaming.
|
||||
// Only a prolonged PAUSED state or a stream with no FIRST frame is fatal.
|
||||
if (!c->stopping &&
|
||||
((c->paused_ms != 0 && now - c->paused_ms >= 10000) ||
|
||||
(c->counter == 0 && now - c->started_ms >= 30000))) {
|
||||
fprintf(stderr, "capture stream stopped producing usable frames; reconnecting\n");
|
||||
c->exit_status = 75;
|
||||
pw_main_loop_quit(c->loop);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_core_error(void *userdata, uint32_t id, int sequence,
|
||||
int result, const char *message)
|
||||
{
|
||||
struct capture *c = userdata;
|
||||
(void)sequence;
|
||||
if (!c->stopping && id == PW_ID_CORE && result < 0) {
|
||||
fprintf(stderr, "PipeWire connection failed: %s\n", message);
|
||||
c->exit_status = 75;
|
||||
pw_main_loop_quit(c->loop);
|
||||
}
|
||||
}
|
||||
|
||||
static const struct pw_core_events core_events = {
|
||||
PW_VERSION_CORE_EVENTS,
|
||||
.error = on_core_error,
|
||||
};
|
||||
|
||||
static const struct pw_stream_events stream_events = {
|
||||
.version = PW_VERSION_STREAM_EVENTS,
|
||||
.process = on_process,
|
||||
@@ -280,6 +430,27 @@ static const struct pw_stream_events stream_events = {
|
||||
.state_changed = on_state_changed,
|
||||
};
|
||||
|
||||
static const struct spa_pod *capture_format(struct spa_pod_builder *builder,
|
||||
int dmabuf)
|
||||
{
|
||||
struct spa_pod_frame frame;
|
||||
spa_pod_builder_push_object(builder, &frame, SPA_TYPE_OBJECT_Format,
|
||||
SPA_PARAM_EnumFormat);
|
||||
spa_pod_builder_add(builder,
|
||||
SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video),
|
||||
SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
|
||||
SPA_FORMAT_VIDEO_format,
|
||||
SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_BGRA,
|
||||
SPA_VIDEO_FORMAT_RGBx, SPA_VIDEO_FORMAT_RGBA,
|
||||
SPA_VIDEO_FORMAT_BGR, SPA_VIDEO_FORMAT_RGB), 0);
|
||||
if (dmabuf) {
|
||||
spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier,
|
||||
SPA_POD_PROP_FLAG_MANDATORY);
|
||||
spa_pod_builder_long(builder, DRM_FORMAT_MOD_LINEAR);
|
||||
}
|
||||
return spa_pod_builder_pop(builder, &frame);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
const char *fd_text = getenv("UUR_PW_FD");
|
||||
@@ -330,6 +501,8 @@ int main(void)
|
||||
fprintf(stderr, "pw_context_connect_fd failed\n");
|
||||
return 1;
|
||||
}
|
||||
struct spa_hook core_listener;
|
||||
pw_core_add_listener(core, &core_listener, &core_events, &c);
|
||||
|
||||
struct pw_properties *props = pw_properties_new(
|
||||
PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture",
|
||||
@@ -344,39 +517,45 @@ int main(void)
|
||||
uint8_t pod_buffer[1024];
|
||||
struct spa_pod_builder pod_builder =
|
||||
SPA_POD_BUILDER_INIT(pod_buffer, sizeof(pod_buffer));
|
||||
const struct spa_pod *params[1];
|
||||
params[0] = spa_pod_builder_add_object(
|
||||
&pod_builder, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat,
|
||||
SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video),
|
||||
SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
|
||||
SPA_FORMAT_VIDEO_format,
|
||||
SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx,
|
||||
SPA_VIDEO_FORMAT_BGRA,
|
||||
SPA_VIDEO_FORMAT_RGBx,
|
||||
SPA_VIDEO_FORMAT_RGBA,
|
||||
SPA_VIDEO_FORMAT_BGR,
|
||||
SPA_VIDEO_FORMAT_RGB));
|
||||
const struct spa_pod *params[2];
|
||||
params[0] = capture_format(&pod_builder, 1);
|
||||
params[1] = capture_format(&pod_builder, 0);
|
||||
c.started_ms = monotonic_ms();
|
||||
|
||||
if (pw_stream_connect(c.stream, PW_DIRECTION_INPUT, node_id,
|
||||
PW_STREAM_FLAG_MAP_BUFFERS |
|
||||
PW_STREAM_FLAG_AUTOCONNECT |
|
||||
PW_STREAM_FLAG_RT_PROCESS,
|
||||
params, 1) < 0) {
|
||||
PW_STREAM_FLAG_AUTOCONNECT,
|
||||
params, 2) < 0) {
|
||||
fprintf(stderr, "pw_stream_connect failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
struct spa_source *watchdog = pw_loop_add_timer(pw_main_loop_get_loop(loop),
|
||||
on_watchdog, &c);
|
||||
struct timespec interval = {.tv_sec = 1};
|
||||
if (watchdog == NULL || pw_loop_update_timer(pw_main_loop_get_loop(loop),
|
||||
watchdog, &interval, &interval, false) < 0) {
|
||||
fprintf(stderr, "could not start capture watchdog\n");
|
||||
return 1;
|
||||
}
|
||||
pw_main_loop_run(loop);
|
||||
|
||||
c.stopping = 1;
|
||||
active_capture = NULL;
|
||||
pw_loop_destroy_source(pw_main_loop_get_loop(loop), watchdog);
|
||||
pw_stream_destroy(c.stream);
|
||||
spa_hook_remove(&core_listener);
|
||||
pw_core_disconnect(core);
|
||||
pw_context_destroy(context);
|
||||
pw_main_loop_destroy(loop);
|
||||
if (c.shm != NULL)
|
||||
if (c.shm != NULL) {
|
||||
struct frame_header *header = (struct frame_header *)c.shm;
|
||||
atomic_store_explicit(&header->total_frames, 0, memory_order_release);
|
||||
munmap(c.shm, c.shm_size);
|
||||
}
|
||||
if (c.shm_fd >= 0)
|
||||
close(c.shm_fd);
|
||||
unlink(c.frame_path);
|
||||
pw_deinit();
|
||||
return 0;
|
||||
return c.exit_status;
|
||||
}
|
||||
@@ -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, ®istry_listener, &c);
|
||||
if (wl_display_roundtrip(c.display) < 0 || wl_display_roundtrip(c.display) < 0) {
|
||||
c.failed = 1; goto cleanup;
|
||||
}
|
||||
if (list) {
|
||||
for (size_t i = 0; i < c.output_count; ++i) {
|
||||
printf("%s %dx%d\n", c.outputs[i].name, c.outputs[i].width, c.outputs[i].height);
|
||||
}
|
||||
goto cleanup;
|
||||
}
|
||||
if (c.manager == NULL || c.shm == NULL) {
|
||||
fprintf(stderr, "compositor does not expose wlr-screencopy with wl_shm buffers\n");
|
||||
c.failed = 1; goto cleanup;
|
||||
}
|
||||
const char *name = getenv("UUR_CAPTURE_OUTPUT");
|
||||
if (name != NULL && name[0] != '\0') {
|
||||
for (size_t i = 0; i < c.output_count; ++i) {
|
||||
if (!strcmp(name, c.outputs[i].name)) c.selected = &c.outputs[i];
|
||||
}
|
||||
} else if (c.output_count == 1) { c.selected = &c.outputs[0]; }
|
||||
if (c.selected == NULL) {
|
||||
fprintf(stderr, "select one output with uur display backend wayland --output NAME:\n");
|
||||
for (size_t i = 0; i < c.output_count; ++i) fprintf(stderr, " %s\n", c.outputs[i].name);
|
||||
c.failed = 1; goto cleanup;
|
||||
}
|
||||
while (!stopping && !c.failed) {
|
||||
c.done = 0;
|
||||
c.frame = zwlr_screencopy_manager_v1_capture_output(c.manager, 1, c.selected->proxy);
|
||||
zwlr_screencopy_frame_v1_add_listener(c.frame, &frame_listener, &c);
|
||||
while (!c.done && !stopping) {
|
||||
if (dispatch(&c) < 0) { c.failed = 1; break; }
|
||||
}
|
||||
if (c.done && !c.failed && !stopping) publish_frame(&c);
|
||||
clear_frame(&c);
|
||||
struct timespec delay = { .tv_nsec = 33333333 };
|
||||
nanosleep(&delay, NULL);
|
||||
}
|
||||
cleanup:
|
||||
clear_frame(&c);
|
||||
if (c.ring != NULL) munmap(c.ring, c.ring_size);
|
||||
if (c.ring_fd >= 0) {
|
||||
struct stat created, present;
|
||||
if (fstat(c.ring_fd, &created) == 0 && lstat(c.frame_path, &present) == 0 &&
|
||||
created.st_dev == present.st_dev && created.st_ino == present.st_ino) unlink(c.frame_path);
|
||||
close(c.ring_fd);
|
||||
}
|
||||
for (size_t i = 0; i < c.output_count; ++i) wl_output_destroy(c.outputs[i].proxy);
|
||||
if (c.manager != NULL) zwlr_screencopy_manager_v1_destroy(c.manager);
|
||||
if (c.shm != NULL) wl_shm_destroy(c.shm);
|
||||
wl_registry_destroy(c.registry); wl_display_disconnect(c.display);
|
||||
return c.failed ? 1 : 0;
|
||||
}
|
||||
@@ -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>
|
||||
@@ -47,3 +47,45 @@ mutexes; a torn read is detected, never observed.
|
||||
|
||||
The transport path is created per user and passed to the Wine adapter through
|
||||
the managed prefix configuration. It is never a global shared-memory name.
|
||||
|
||||
## Geometry and session changes
|
||||
|
||||
An exact Wine monitor rectangle maps onto the entire selected frame when their
|
||||
aspect ratios match. Pixel dimensions may differ under fractional scaling, where
|
||||
Xwayland's render size can exceed the portal's native frame size. Partial regions
|
||||
and whole-virtual-desktop requests retain the existing virtual-desktop mapping.
|
||||
This does not establish monitor identity between Wine and the portal; selecting
|
||||
a non-primary monitor still requires consistent client/input coordinates.
|
||||
|
||||
Each transport inode has immutable geometry. A negotiated size change creates
|
||||
a new mode-0600 file, initializes its header and slots, then atomically replaces
|
||||
the transport path. The previous mapping remains valid for existing readers;
|
||||
the producer never truncates it. The Wine adapter checks file identity at least
|
||||
every 250 ms and remaps replacements while serializing its capture readers.
|
||||
|
||||
The PipeWire consumer accepts explicitly linear DMA-BUFs and retains a separate
|
||||
shared-memory format offer. DMA-BUF reads use the source stride, plane offsets,
|
||||
fd extent, readiness fence and CPU-access synchronization. Implicit modifiers
|
||||
require a graphics importer and are not advertised by this CPU consumer.
|
||||
|
||||
A stream error, lost connection or ten seconds in PAUSED after streaming makes
|
||||
the helper exit with status 75. The ScreenCast supervisor retries up to three
|
||||
times using the saved restore token, with a one-second backoff. Thirty seconds
|
||||
of healthy capture resets the retry budget. An unchanged desktop in STREAMING
|
||||
does not trigger this watchdog. Recovery keeps the saved token and performs no
|
||||
token-less fallback or switch to direct capture. The portal controls whether
|
||||
restoring that choice requires confirmation. A portal Session.Closed signal
|
||||
without a matching Mutter layout change ends sharing; the user starts a new
|
||||
session explicitly. The supervisor subscribes to the raw signal on the session's
|
||||
own connection, accepting both dictionary and empty signal bodies.
|
||||
|
||||
When Mutter's DisplayConfig service is already present, the supervisor also
|
||||
subscribes to MonitorsChanged and proactively restores capture after a layout
|
||||
change. It coalesces signals during the reconnect delay. Mutter may close the
|
||||
old session before forwarding MonitorsChanged, so a Closed signal has a 250 ms
|
||||
window to correlate that transaction. Closed without a matching change stops
|
||||
capture, and process stop requests always take priority. This optional listener
|
||||
never starts a GNOME service on other desktops.
|
||||
Successful layout-driven restarts do not consume the failure retry budget.
|
||||
Only the initial session can make a token-less interactive selection; later
|
||||
restores keep that boundary even when the failure counter has been reset.
|
||||
+64
-6
@@ -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.6-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.6_amd64.deb
|
||||
```
|
||||
|
||||
The same release artifact covers Debian, Ubuntu, Linux Mint, Pop!_OS, KDE neon,
|
||||
@@ -28,10 +28,10 @@ derivatives.
|
||||
## Fedora, RHEL, and openSUSE families
|
||||
|
||||
```bash
|
||||
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
|
||||
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
|
||||
|
||||
# openSUSE
|
||||
sudo zypper install ./uur-0.1.3-1.x86_64.rpm
|
||||
sudo zypper install ./uur-0.1.6-1.x86_64.rpm
|
||||
```
|
||||
|
||||
This format also covers Fedora derivatives and RPM systems whose repositories
|
||||
@@ -42,7 +42,7 @@ provide the declared Wine, GLib, PipeWire, and portal dependencies.
|
||||
The portable archive targets conventional glibc/FHS systems:
|
||||
|
||||
```bash
|
||||
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
|
||||
sudo tar --zstd -C / -xf ./uur-0.1.6-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.
|
||||
@@ -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 |
|
||||
|
||||
+117
-8
@@ -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.6-1-x86_64.pkg.tar.zst
|
||||
```
|
||||
|
||||
Install the portal backend supplied or recommended by the selected desktop.
|
||||
@@ -60,7 +60,7 @@ Zorin OS, elementary OS, KDE neon, TUXEDO OS, Kali Linux, MX Linux, and other
|
||||
compatible derivatives:
|
||||
|
||||
```bash
|
||||
sudo apt install ./uur_0.1.3_amd64.deb
|
||||
sudo apt install ./uur_0.1.6_amd64.deb
|
||||
```
|
||||
|
||||
The package manager resolves Wine, PipeWire, and the portal frontend. Install
|
||||
@@ -74,10 +74,10 @@ dependency names. Install it with the native frontend:
|
||||
|
||||
```bash
|
||||
# Fedora and compatible systems
|
||||
sudo dnf install ./uur-0.1.3-1.x86_64.rpm
|
||||
sudo dnf install ./uur-0.1.6-1.x86_64.rpm
|
||||
|
||||
# openSUSE family
|
||||
sudo zypper install ./uur-0.1.3-1.x86_64.rpm
|
||||
sudo zypper install ./uur-0.1.6-1.x86_64.rpm
|
||||
```
|
||||
|
||||
RHEL, CentOS Stream, Rocky Linux, AlmaLinux, Oracle Linux, Nobara, Ultramarine,
|
||||
@@ -91,7 +91,7 @@ PCLinuxOS, and similar mutable/FHS systems can use the portable archive when
|
||||
they provide compatible glibc, Wine, PipeWire, and portal libraries:
|
||||
|
||||
```bash
|
||||
sudo tar --zstd -C / -xf ./uur-0.1.3-linux-x86_64.tar.zst
|
||||
sudo tar --zstd -C / -xf ./uur-0.1.6-linux-x86_64.tar.zst
|
||||
```
|
||||
|
||||
Alternatively, build and install for one user:
|
||||
@@ -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
|
||||
@@ -242,6 +243,18 @@ Stop only the managed session and its Wine prefix with:
|
||||
uur stop
|
||||
```
|
||||
|
||||
The session tracks `GameViewer.exe` in its own Wine prefix through the
|
||||
resident `winlogon.exe` adapter. This uses the Windows process table even when
|
||||
the client changes its Linux process title. It keeps a three-second handoff
|
||||
grace period without repeatedly starting `tasklist`. A failed process query
|
||||
is not treated as a client exit; a disconnected or unresponsive monitor ends
|
||||
the session with an explicit error. Stopping the session also stops this
|
||||
adapter and the capture/input helpers. Remaining Wine workers, including
|
||||
WebView2 processes that outlive their wineserver, are matched to this prefix
|
||||
and signaled through Linux pidfds to avoid PID-reuse races. Other Wine prefixes
|
||||
are left running. This residual-process cleanup needs Linux 5.3 or later;
|
||||
older kernels still use Wine's normal wineserver shutdown.
|
||||
|
||||
Useful input-backend overrides for diagnosis are:
|
||||
|
||||
```bash
|
||||
@@ -253,6 +266,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.
|
||||
|
||||
+109
-17
@@ -17,6 +17,10 @@
|
||||
*/
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#ifndef _WIN32_WINNT
|
||||
#define _WIN32_WINNT 0x0601
|
||||
#endif
|
||||
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <windows.h>
|
||||
@@ -234,6 +238,9 @@ static uint64_t frame_slot_bytes;
|
||||
static unsigned char *frame_snapshot;
|
||||
static size_t frame_snapshot_capacity;
|
||||
static size_t frame_map_size;
|
||||
static BY_HANDLE_FILE_INFORMATION frame_identity;
|
||||
static ULONGLONG frame_checked_at;
|
||||
static SRWLOCK frame_lock = SRWLOCK_INIT;
|
||||
|
||||
static char *read_ini_value(const char *path, const char *key);
|
||||
|
||||
@@ -264,39 +271,70 @@ static uint64_t load_u64(const unsigned char *p)
|
||||
return load_u32(p) | ((uint64_t)load_u32(p + 4) << 32);
|
||||
}
|
||||
|
||||
/* Open (or re-open after a resolution change) the capture file that the
|
||||
* native uur-pw-capture helper publishes. */
|
||||
static void clear_frame_map(void)
|
||||
{
|
||||
if (frame_map != NULL)
|
||||
UnmapViewOfFile(frame_map);
|
||||
if (frame_map_handle != NULL)
|
||||
CloseHandle(frame_map_handle);
|
||||
frame_map = NULL;
|
||||
frame_map_handle = NULL;
|
||||
frame_map_size = 0;
|
||||
}
|
||||
|
||||
/* Producers publish immutable geometry via atomic replacement. Re-check the
|
||||
* file identity periodically, including after an ungraceful helper restart. */
|
||||
static int ensure_frame_map(void)
|
||||
{
|
||||
HANDLE file;
|
||||
void *view;
|
||||
const unsigned char *header;
|
||||
LARGE_INTEGER size;
|
||||
BY_HANDLE_FILE_INFORMATION identity;
|
||||
WCHAR path[32768];
|
||||
ULONGLONG now = GetTickCount64();
|
||||
|
||||
if (frame_map != NULL)
|
||||
if (frame_map != NULL && now - frame_checked_at < 250 &&
|
||||
load_u64((const unsigned char *)frame_map + 24) != 0)
|
||||
return 1;
|
||||
|
||||
if (!resolve_frame_path(path, (int)(sizeof(path) / sizeof(path[0]))))
|
||||
return 0;
|
||||
file = CreateFileW(path, GENERIC_READ,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
|
||||
0, NULL);
|
||||
if (file == INVALID_HANDLE_VALUE)
|
||||
return 0;
|
||||
if (!GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES ||
|
||||
(uint64_t)size.QuadPart > SIZE_MAX) {
|
||||
CloseHandle(file);
|
||||
if (file == INVALID_HANDLE_VALUE) {
|
||||
clear_frame_map();
|
||||
return 0;
|
||||
}
|
||||
if (!GetFileInformationByHandle(file, &identity) ||
|
||||
!GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES ||
|
||||
(uint64_t)size.QuadPart > UURF_HEADER_BYTES +
|
||||
UURF_SLOT_COUNT * (8ull + 256ull * 1024 * 1024)) {
|
||||
CloseHandle(file);
|
||||
clear_frame_map();
|
||||
return 0;
|
||||
}
|
||||
frame_checked_at = now;
|
||||
if (frame_map != NULL &&
|
||||
identity.dwVolumeSerialNumber == frame_identity.dwVolumeSerialNumber &&
|
||||
identity.nFileIndexHigh == frame_identity.nFileIndexHigh &&
|
||||
identity.nFileIndexLow == frame_identity.nFileIndexLow &&
|
||||
(uint64_t)size.QuadPart == frame_map_size) {
|
||||
CloseHandle(file);
|
||||
return 1;
|
||||
}
|
||||
clear_frame_map();
|
||||
frame_map_handle = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0,
|
||||
NULL);
|
||||
CloseHandle(file);
|
||||
if (frame_map_handle == NULL)
|
||||
return 0;
|
||||
view = MapViewOfFile(frame_map_handle, FILE_MAP_READ, 0, 0, 0);
|
||||
if (view == NULL)
|
||||
if (view == NULL) {
|
||||
clear_frame_map();
|
||||
return 0;
|
||||
}
|
||||
|
||||
header = (const unsigned char *)view;
|
||||
if (load_u32(header) != UURF_MAGIC ||
|
||||
@@ -311,7 +349,10 @@ static int ensure_frame_map(void)
|
||||
frame_stride = load_u32(header + 16);
|
||||
frame_slot_bytes = 8ull + (uint64_t)frame_stride * frame_height;
|
||||
uint64_t expected = UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes;
|
||||
if (frame_width == 0 || frame_height == 0 || frame_stride < frame_width * 4 ||
|
||||
if (frame_width == 0 || frame_height == 0 ||
|
||||
frame_width > 16384 || frame_height > 16384 ||
|
||||
frame_stride != frame_width * 4 ||
|
||||
(uint64_t)frame_stride * frame_height > 256ull * 1024 * 1024 ||
|
||||
expected > (uint64_t)size.QuadPart) {
|
||||
UnmapViewOfFile(view);
|
||||
CloseHandle(frame_map_handle);
|
||||
@@ -320,6 +361,7 @@ static int ensure_frame_map(void)
|
||||
}
|
||||
frame_map_size = (size_t)size.QuadPart;
|
||||
frame_map = view;
|
||||
frame_identity = identity;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -389,7 +431,7 @@ static void draw_cursor_overlay(HDC hdc_dest, int x, int y, int width, int heigh
|
||||
/* Feed the newest desktop frame into the capture destination by drawing
|
||||
* our shared-memory frame with StretchDIBits. Works regardless of the
|
||||
* destination bitmap type (DDB or DIB section). */
|
||||
static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
|
||||
static BOOL feed_capture_frame_locked(HDC hdc_dest, int x, int y, int width,
|
||||
int height, int source_x, int source_y,
|
||||
int source_width, int source_height)
|
||||
{
|
||||
@@ -407,7 +449,8 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
|
||||
fstride = load_u32(header + 16);
|
||||
size_t frame_bytes = (size_t)fstride * fh;
|
||||
total = load_u64(header + 24);
|
||||
if (fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 ||
|
||||
if (fw != frame_width || fh != frame_height || fstride != frame_stride ||
|
||||
fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 ||
|
||||
frame_bytes / fstride != fh ||
|
||||
UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes > frame_map_size)
|
||||
return FALSE;
|
||||
@@ -449,10 +492,48 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
|
||||
screen_width = (int)fw;
|
||||
if (screen_height < 1)
|
||||
screen_height = (int)fh;
|
||||
int sx = (int)((int64_t)source_x * fw / screen_width);
|
||||
int sy = (int)((int64_t)source_y * fh / screen_height);
|
||||
int sw = (int)((int64_t)source_width * fw / screen_width);
|
||||
int sh = (int)((int64_t)source_height * fh / screen_height);
|
||||
/* The frame holds exactly one monitor, but the client may ask
|
||||
* for that monitor's whole rectangle. Wine reports the
|
||||
* compositor's monitors in its own order, so the virtual desktop
|
||||
* is only the right basis for a partial request; a complete
|
||||
* monitor request must map onto the whole frame. Fractional
|
||||
* scaling can give Xwayland and the portal different pixel
|
||||
* sizes, so compare aspect ratios rather than resolutions. */
|
||||
int sx = 0;
|
||||
int sy = 0;
|
||||
int sw = 0;
|
||||
int sh = 0;
|
||||
RECT requested;
|
||||
requested.left = (LONG)source_x;
|
||||
requested.top = (LONG)source_y;
|
||||
requested.right = (LONG)source_x + (LONG)source_width;
|
||||
requested.bottom = (LONG)source_y + (LONG)source_height;
|
||||
HMONITOR monitor = (source_width > 0 && source_height > 0)
|
||||
? MonitorFromRect(&requested, MONITOR_DEFAULTTONULL)
|
||||
: NULL;
|
||||
MONITORINFO info;
|
||||
info.cbSize = sizeof(info);
|
||||
BOOL whole_monitor = FALSE;
|
||||
if (monitor != NULL && GetMonitorInfoA(monitor, &info)) {
|
||||
whole_monitor =
|
||||
info.rcMonitor.left == requested.left &&
|
||||
info.rcMonitor.top == requested.top &&
|
||||
info.rcMonitor.right == requested.right &&
|
||||
info.rcMonitor.bottom == requested.bottom &&
|
||||
(int64_t)(info.rcMonitor.right - info.rcMonitor.left) * fh ==
|
||||
(int64_t)(info.rcMonitor.bottom - info.rcMonitor.top) * fw;
|
||||
}
|
||||
if (whole_monitor) {
|
||||
sx = 0;
|
||||
sy = 0;
|
||||
sw = (int)fw;
|
||||
sh = (int)fh;
|
||||
} else {
|
||||
sx = (int)((int64_t)source_x * fw / screen_width);
|
||||
sy = (int)((int64_t)source_y * fh / screen_height);
|
||||
sw = (int)((int64_t)source_width * fw / screen_width);
|
||||
sh = (int)((int64_t)source_height * fh / screen_height);
|
||||
}
|
||||
if (sw < 1)
|
||||
sw = (int)fw;
|
||||
if (sh < 1)
|
||||
@@ -472,6 +553,17 @@ static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
|
||||
return ok;
|
||||
}
|
||||
|
||||
static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width,
|
||||
int height, int source_x, int source_y,
|
||||
int source_width, int source_height)
|
||||
{
|
||||
AcquireSRWLockExclusive(&frame_lock);
|
||||
BOOL result = feed_capture_frame_locked(hdc_dest, x, y, width, height,
|
||||
source_x, source_y, source_width, source_height);
|
||||
ReleaseSRWLockExclusive(&frame_lock);
|
||||
return result;
|
||||
}
|
||||
|
||||
static BOOL try_capture_feed(HDC hdc_dest, int x, int y, DWORD rop,
|
||||
HDC hdc_src, int width, int height, int source_x,
|
||||
int source_y, int source_width, int source_height)
|
||||
|
||||
+42
-3
@@ -4,10 +4,34 @@
|
||||
* GameViewerService enumerates processes for a winlogon session token
|
||||
* source before it initialises; under plain Wine none exists and the
|
||||
* service never leaves its initial state (the launcher waits at the
|
||||
* splash forever). This process only needs to exist with that name.
|
||||
* splash forever). It also reports the client's Windows process presence
|
||||
* over its inherited pipe, avoiding a new Wine/tasklist process per poll.
|
||||
*/
|
||||
|
||||
#include <windows.h>
|
||||
#include <tlhelp32.h>
|
||||
|
||||
static char client_present(const WCHAR *image)
|
||||
{
|
||||
PROCESSENTRY32W entry = {0};
|
||||
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||
if (snapshot == INVALID_HANDLE_VALUE)
|
||||
return '?';
|
||||
entry.dwSize = sizeof(entry);
|
||||
if (!Process32FirstW(snapshot, &entry)) {
|
||||
CloseHandle(snapshot);
|
||||
return '?';
|
||||
}
|
||||
do {
|
||||
if (!lstrcmpiW(entry.szExeFile, image)) {
|
||||
CloseHandle(snapshot);
|
||||
return '1';
|
||||
}
|
||||
} while (Process32NextW(snapshot, &entry));
|
||||
DWORD error = GetLastError();
|
||||
CloseHandle(snapshot);
|
||||
return error == ERROR_NO_MORE_FILES ? '0' : '?';
|
||||
}
|
||||
|
||||
int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line,
|
||||
int show_command)
|
||||
@@ -16,6 +40,21 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line,
|
||||
(void)previous;
|
||||
(void)command_line;
|
||||
(void)show_command;
|
||||
Sleep(INFINITE);
|
||||
return 0;
|
||||
WCHAR image[MAX_PATH];
|
||||
DWORD length = GetEnvironmentVariableW(L"UUR_MONITOR_CLIENT", image,
|
||||
MAX_PATH);
|
||||
if (!length) {
|
||||
Sleep(INFINITE);
|
||||
return 0;
|
||||
}
|
||||
if (length >= MAX_PATH)
|
||||
return 1;
|
||||
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
for (;;) {
|
||||
char state = client_present(image);
|
||||
DWORD written;
|
||||
if (!WriteFile(output, &state, 1, &written, NULL) || written != 1)
|
||||
return 1;
|
||||
Sleep(500);
|
||||
}
|
||||
}
|
||||
+46
-3
@@ -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,8 +51,13 @@ 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"
|
||||
cursor_unsupported: "the desktop portal advertises no usable cursor mode, so screen capture cannot start. Restart the portal (systemctl --user restart xdg-desktop-portal) and retry; if it persists, check that a ScreenCast backend matching your session is installed."
|
||||
cursor_not_embedded: "the portal cannot embed the cursor; capture will continue without a cursor in the video frames"
|
||||
|
||||
session:
|
||||
already_running: "a session is already running - use it, or run `uur stop` first"
|
||||
@@ -55,6 +69,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 +83,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"
|
||||
|
||||
+45
-2
@@ -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,8 +67,13 @@ 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: "捕获助手异常退出"
|
||||
cursor_unsupported: "桌面 Portal 未声明任何可用的光标模式,无法开始屏幕采集。请重启 Portal(systemctl --user restart xdg-desktop-portal)后重试;若仍失败,请确认已安装与当前会话匹配的 ScreenCast 后端。"
|
||||
cursor_not_embedded: "Portal 无法将光标嵌入画面;采集将继续,但视频帧中不会包含光标"
|
||||
|
||||
setup:
|
||||
eula_prompt: "官方 UU 远程客户端将从网易官方渠道下载,并受其最终用户协议约束:%{url}\n使用 --accept-eula 重新运行以继续。"
|
||||
@@ -64,10 +83,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
@@ -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.6";
|
||||
|
||||
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;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# Contributor: uur contributors
|
||||
# Maintainer: uur contributors
|
||||
pkgname=uur
|
||||
pkgver=0.1.3
|
||||
pkgver=0.1.6
|
||||
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"
|
||||
|
||||
@@ -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"]
|
||||
@@ -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'
|
||||
|
||||
@@ -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.6
|
||||
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.6.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.6.tar.gz
|
||||
sha256sums = SKIP
|
||||
|
||||
pkgname = uur
|
||||
@@ -8,7 +8,7 @@
|
||||
# `uur setup` (it is never redistributed by this package).
|
||||
|
||||
pkgname=uur
|
||||
pkgver=0.1.3
|
||||
pkgver=0.1.6
|
||||
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'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
@@ -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"
|
||||
@@ -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
@@ -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
@@ -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
@@ -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();
|
||||
|
||||
+422
-55
@@ -13,25 +13,275 @@
|
||||
//! a headless remote host.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use std::io::Read;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::fd::OwnedFd;
|
||||
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 std::time::{Duration, Instant};
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
type PortalSession =
|
||||
ashpd::desktop::Session<'static, ashpd::desktop::screencast::Screencast<'static>>;
|
||||
|
||||
struct PortalCapture {
|
||||
fd: OwnedFd,
|
||||
node: u32,
|
||||
restore_token: Option<String>,
|
||||
session: PortalSession,
|
||||
closed: zbus::proxy::SignalStream<'static>,
|
||||
}
|
||||
|
||||
/// Run the capture path until interrupted.
|
||||
pub fn run_standalone() -> Result<()> {
|
||||
// Public capture uses the same lifecycle lock as run/setup so stop and
|
||||
// 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::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.context("creating capture runtime")?;
|
||||
// The portal's D-Bus connection runs on this runtime. Keep it running
|
||||
// throughout capture, including on capture-only compositors such as niri.
|
||||
runtime.block_on(async {
|
||||
let frames = frame_path()?;
|
||||
let mut failures = 0;
|
||||
let mut initial_session = true;
|
||||
let mut display_changes = watch_display_changes().await;
|
||||
loop {
|
||||
let opened = tokio::select! {
|
||||
result = portal_session(&mut config, initial_session) => result,
|
||||
_ = wait_for_stop(&stopping) => return Ok(()),
|
||||
};
|
||||
let PortalCapture {
|
||||
fd: pw_fd,
|
||||
node,
|
||||
session,
|
||||
mut closed,
|
||||
..
|
||||
} = match opened {
|
||||
Ok(opened) => opened,
|
||||
Err(error) if !initial_session && failures < 3 => {
|
||||
failures += 1;
|
||||
eprintln!("capture reconnect {failures}/3 failed: {error:#}");
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(1)) => continue,
|
||||
_ = wait_for_stop(&stopping) => return Ok(()),
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
initial_session = false;
|
||||
println!("{}", t!("capture.session_ready", node = node));
|
||||
match std::fs::remove_file(&frames) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error).context("retiring the previous capture transport"),
|
||||
}
|
||||
let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?);
|
||||
let mut healthy_since = None;
|
||||
let mut portal_closed = false;
|
||||
let mut reconfigure = false;
|
||||
let status = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = wait_for_stop(&stopping) => break None,
|
||||
_ = closed.next() => {
|
||||
// Mutter can close the old stream before forwarding
|
||||
// MonitorsChanged. Correlate that layout transaction;
|
||||
// a user Stop without a display change stays closed.
|
||||
reconfigure = tokio::time::timeout(
|
||||
Duration::from_millis(250),
|
||||
next_display_change(&mut display_changes),
|
||||
).await.is_ok();
|
||||
portal_closed = !reconfigure;
|
||||
break None;
|
||||
}
|
||||
_ = next_display_change(&mut display_changes) => {
|
||||
reconfigure = true;
|
||||
break None;
|
||||
}
|
||||
_ = tokio::time::sleep(Duration::from_millis(50)) => {
|
||||
if has_frame(&frames) && healthy_since.is_none() {
|
||||
healthy_since = Some(Instant::now());
|
||||
}
|
||||
if let Some(status) = helper.0.try_wait()
|
||||
.context("waiting for capture helper")? {
|
||||
break Some(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
drop(closed);
|
||||
drop(helper);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(2), session.close()).await;
|
||||
if stopping.load(Ordering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
// Closed without a matching layout change means Stop sharing.
|
||||
// Never silently restore that permission or use direct capture.
|
||||
if portal_closed {
|
||||
anyhow::bail!(
|
||||
"screen sharing was closed by the portal; restart uur run to share again"
|
||||
);
|
||||
}
|
||||
if healthy_since.is_some_and(|since| since.elapsed() >= Duration::from_secs(30)) {
|
||||
failures = 0;
|
||||
}
|
||||
if reconfigure {
|
||||
eprintln!("display configuration changed; restoring capture");
|
||||
} else {
|
||||
failures += 1;
|
||||
if failures > 3 {
|
||||
anyhow::bail!(
|
||||
"capture recovery failed repeatedly; restart uur run to share again"
|
||||
);
|
||||
}
|
||||
let status = status.context("capture helper stopped without an exit status")?;
|
||||
if !matches!(status.code(), Some(0 | 75) | None) {
|
||||
anyhow::bail!(
|
||||
"{} ({status}); capture recovery stopped",
|
||||
t!("capture.helper_failed")
|
||||
);
|
||||
}
|
||||
eprintln!("capture stream interrupted ({status}); reconnecting {failures}/3");
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(1)) => {},
|
||||
_ = wait_for_stop(&stopping) => return Ok(()),
|
||||
}
|
||||
// Several signals can describe one layout transaction. The next
|
||||
// handshake reads the final layout rather than replaying each one.
|
||||
if reconfigure {
|
||||
while let Some(stream) = display_changes.as_mut() {
|
||||
match stream.next().now_or_never() {
|
||||
Some(Some(_)) => {}
|
||||
Some(None) => {
|
||||
display_changes = None;
|
||||
break;
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn watch_display_changes() -> Option<zbus::proxy::SignalStream<'static>> {
|
||||
let connection = zbus::Connection::session().await.ok()?;
|
||||
let bus = zbus::fdo::DBusProxy::new(&connection).await.ok()?;
|
||||
let name = "org.gnome.Mutter.DisplayConfig".try_into().ok()?;
|
||||
if !bus.name_has_owner(name).await.ok()? {
|
||||
return None;
|
||||
}
|
||||
drop(bus);
|
||||
let proxy = zbus::Proxy::new_owned(
|
||||
connection,
|
||||
"org.gnome.Mutter.DisplayConfig",
|
||||
"/org/gnome/Mutter/DisplayConfig",
|
||||
"org.gnome.Mutter.DisplayConfig",
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
proxy.receive_signal("MonitorsChanged").await.ok()
|
||||
}
|
||||
|
||||
async fn next_display_change(changes: &mut Option<zbus::proxy::SignalStream<'static>>) {
|
||||
loop {
|
||||
match changes.as_mut() {
|
||||
Some(stream) => {
|
||||
if stream.next().await.is_some() {
|
||||
return;
|
||||
}
|
||||
*changes = None;
|
||||
}
|
||||
None => std::future::pending::<()>().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_stop(stopping: &AtomicBool) {
|
||||
while !stopping.load(Ordering::Relaxed) {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
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 +301,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())
|
||||
@@ -77,57 +327,125 @@ fn frame_path() -> Result<PathBuf> {
|
||||
/// First attempt reuses the stored restore token; if that fails (stale
|
||||
/// token, monitor changed, compositor restart) fall back to one
|
||||
/// interactive attempt and store the fresh token.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
|
||||
async fn portal_session(config: &mut Config, interactive: bool) -> Result<PortalCapture> {
|
||||
let saved_token = config.capture_restore_token.clone();
|
||||
let 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(interactive.then_some(None))
|
||||
{
|
||||
match negotiate(&screencast, source, token.as_deref()).await {
|
||||
Ok(capture) => {
|
||||
if capture.restore_token != saved_token {
|
||||
config.capture_restore_token = capture.restore_token.clone();
|
||||
config.store().context("storing the new restore token")?;
|
||||
}
|
||||
return Ok(capture);
|
||||
}
|
||||
Err(error) => {
|
||||
last_error = Some(error);
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| anyhow!("portal session failed")))
|
||||
})
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| {
|
||||
anyhow!("capture permission could not be restored; restart uur run to share again")
|
||||
}))
|
||||
}
|
||||
|
||||
/// Choose a cursor mode from the flags the portal advertises.
|
||||
///
|
||||
/// `Embedded` is what the capture path wants (the hook composites the cursor
|
||||
/// itself on X11, and an embedded cursor is the closest match elsewhere), then
|
||||
/// `Hidden`, then `Metadata`. `None` means the portal advertised no usable
|
||||
/// mode at all.
|
||||
fn choose_cursor_mode(
|
||||
available: ashpd::enumflags2::BitFlags<ashpd::desktop::screencast::CursorMode>,
|
||||
) -> Option<ashpd::desktop::screencast::CursorMode> {
|
||||
use ashpd::desktop::screencast::CursorMode;
|
||||
[
|
||||
CursorMode::Embedded,
|
||||
CursorMode::Hidden,
|
||||
CursorMode::Metadata,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|mode| available.contains(*mode))
|
||||
}
|
||||
|
||||
/// Pick a cursor mode the portal actually advertises.
|
||||
///
|
||||
/// `SelectSources` rejects a mode outside the portal's `AvailableCursorModes`
|
||||
/// with `InvalidArgument: Unavailable cursor mode N`. A portal frontend whose
|
||||
/// backend property cache is empty reports a zeroed set and rejects every
|
||||
/// mode, so choosing from the advertised flags keeps capture working on
|
||||
/// backends that offer only a subset and turns the unusable case into an
|
||||
/// actionable message instead of a raw D-Bus error.
|
||||
pub(crate) async fn preferred_cursor_mode(
|
||||
screencast: &ashpd::desktop::screencast::Screencast<'_>,
|
||||
) -> Result<ashpd::desktop::screencast::CursorMode> {
|
||||
use ashpd::desktop::screencast::CursorMode;
|
||||
|
||||
let available = match screencast.available_cursor_modes().await {
|
||||
Ok(modes) => modes,
|
||||
// ScreenCast v2 introduced the property; older portals have no
|
||||
// advertisement to consult, so keep the historical request.
|
||||
Err(ashpd::Error::RequiresVersion(2, 0..=1)) => return Ok(CursorMode::Embedded),
|
||||
Err(error) => return Err(error).context("reading ScreenCast cursor modes"),
|
||||
};
|
||||
let mode = choose_cursor_mode(available)
|
||||
.ok_or_else(|| anyhow!("{}", t!("capture.cursor_unsupported")))?;
|
||||
if mode != CursorMode::Embedded {
|
||||
// The helper publishes pixels, not PipeWire cursor metadata.
|
||||
eprintln!("{}", t!("capture.cursor_not_embedded"));
|
||||
}
|
||||
Ok(mode)
|
||||
}
|
||||
|
||||
/// One full portal handshake. Returns the PipeWire fd, the video node id
|
||||
/// and the restore token the portal issued for this selection.
|
||||
async fn negotiate(
|
||||
screencast: &ashpd::desktop::screencast::Screencast<'_>,
|
||||
screencast: &ashpd::desktop::screencast::Screencast<'static>,
|
||||
source: ashpd::desktop::screencast::SourceType,
|
||||
restore_token: Option<&str>,
|
||||
) -> Result<(OwnedFd, u32, Option<String>)> {
|
||||
use ashpd::desktop::screencast::CursorMode;
|
||||
) -> Result<PortalCapture> {
|
||||
use ashpd::desktop::PersistMode;
|
||||
|
||||
let session = screencast.create_session().await?;
|
||||
// Session.Closed carries a{sv}. ashpd 0.10 deserializes it as (), which
|
||||
// silently drops the signal. Subscribe on the SAME connection (the
|
||||
// frontend unicasts it) before starting, and ignore its optional details.
|
||||
let serialized = serde_json::to_value(&session)?;
|
||||
let path = serialized
|
||||
.as_str()
|
||||
.context("invalid portal session path")?
|
||||
.to_owned();
|
||||
let session_proxy = zbus::Proxy::new_owned(
|
||||
screencast.connection().clone(),
|
||||
"org.freedesktop.portal.Desktop",
|
||||
path,
|
||||
"org.freedesktop.portal.Session",
|
||||
)
|
||||
.await?;
|
||||
let closed = session_proxy.receive_signal("Closed").await?;
|
||||
let cursor_mode = preferred_cursor_mode(screencast).await?;
|
||||
|
||||
screencast
|
||||
.select_sources(
|
||||
&session,
|
||||
CursorMode::Embedded,
|
||||
cursor_mode,
|
||||
source.into(),
|
||||
false,
|
||||
restore_token,
|
||||
PersistMode::ExplicitlyRevoked,
|
||||
)
|
||||
.await?;
|
||||
.await?
|
||||
.response()?;
|
||||
|
||||
let response = screencast.start(&session, None).await?;
|
||||
let streams_response = response.response()?;
|
||||
@@ -140,7 +458,13 @@ async fn negotiate(
|
||||
.open_pipe_wire_remote(&session)
|
||||
.await
|
||||
.context("opening the PipeWire remote")?;
|
||||
Ok((fd, node, fresh_token))
|
||||
Ok(PortalCapture {
|
||||
fd,
|
||||
node,
|
||||
restore_token: fresh_token,
|
||||
session,
|
||||
closed,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType {
|
||||
@@ -152,34 +476,44 @@ pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType
|
||||
}
|
||||
}
|
||||
|
||||
fn find_helper() -> Result<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
PathBuf::from("/usr/lib/uur/uur-pw-capture"),
|
||||
PathBuf::from("/usr/local/lib/uur/uur-pw-capture"),
|
||||
];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/uur-pw-capture"));
|
||||
}
|
||||
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::new();
|
||||
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(PathBuf::from("/usr/lib/uur").join(name));
|
||||
candidates.push(PathBuf::from("/usr/local/lib/uur").join(name));
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur").join(name));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| {
|
||||
anyhow!("capture helper uur-pw-capture not found (build with capture/build.sh)")
|
||||
})
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
candidates.push(cwd.join("capture").join(name));
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|p| p.is_file())
|
||||
.ok_or_else(|| anyhow!("capture helper {name} not found (build with capture/build.sh)"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::choose_cursor_mode;
|
||||
use super::source_type;
|
||||
use ashpd::desktop::screencast::SourceType;
|
||||
use ashpd::desktop::screencast::{CursorMode, SourceType};
|
||||
use ashpd::enumflags2::BitFlags;
|
||||
|
||||
#[test]
|
||||
fn configured_portal_source_is_mapped() {
|
||||
@@ -187,4 +521,37 @@ mod tests {
|
||||
assert_eq!(source_type("window"), SourceType::Window);
|
||||
assert_eq!(source_type("virtual"), SourceType::Virtual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_cursor_is_preferred_when_the_portal_offers_it() {
|
||||
// gnome advertises 7 = Hidden | Embedded | Metadata.
|
||||
let available = CursorMode::Hidden | CursorMode::Embedded | CursorMode::Metadata;
|
||||
assert_eq!(choose_cursor_mode(available), Some(CursorMode::Embedded));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backend_without_embedded_cursor_falls_back_instead_of_failing() {
|
||||
// wlr advertises 3 = Hidden | Embedded; a metadata-only backend must
|
||||
// still capture rather than requesting a mode the portal rejects.
|
||||
assert_eq!(
|
||||
choose_cursor_mode(CursorMode::Metadata.into()),
|
||||
Some(CursorMode::Metadata)
|
||||
);
|
||||
assert_eq!(
|
||||
choose_cursor_mode(CursorMode::Hidden.into()),
|
||||
Some(CursorMode::Hidden)
|
||||
);
|
||||
assert_eq!(
|
||||
choose_cursor_mode(CursorMode::Hidden | CursorMode::Metadata),
|
||||
Some(CursorMode::Hidden)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_advertisement_selects_no_mode() {
|
||||
// Regression: a portal frontend with a zeroed backend property cache
|
||||
// reported AvailableCursorModes = 0 and rejected every request with
|
||||
// "InvalidArgument: Unavailable cursor mode 2".
|
||||
assert_eq!(choose_cursor_mode(BitFlags::empty()), None);
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -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
@@ -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
@@ -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()?));
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use ashpd::desktop::remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop};
|
||||
use ashpd::desktop::screencast::{CursorMode, Screencast};
|
||||
use ashpd::desktop::screencast::Screencast;
|
||||
use ashpd::desktop::PersistMode;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -140,7 +140,7 @@ async fn portal_worker(
|
||||
screencast
|
||||
.select_sources(
|
||||
&session,
|
||||
CursorMode::Embedded,
|
||||
crate::capture::preferred_cursor_mode(&screencast).await?,
|
||||
source.into(),
|
||||
false,
|
||||
None,
|
||||
|
||||
+10
-4
@@ -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
@@ -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,
|
||||
|
||||
+575
-132
@@ -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;
|
||||
|
||||
@@ -44,13 +45,7 @@ fn complete_hook_directory(dir: &Path) -> bool {
|
||||
}
|
||||
|
||||
fn hook_dir() -> Result<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
PathBuf::from("/usr/lib/uur/hook"),
|
||||
PathBuf::from("/usr/local/lib/uur/hook"),
|
||||
];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
|
||||
}
|
||||
let mut candidates = Vec::new();
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
candidates.push(dir.join("../lib/uur/hook"));
|
||||
@@ -58,6 +53,14 @@ fn hook_dir() -> Result<PathBuf> {
|
||||
candidates.push(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
candidates.push(PathBuf::from("/usr/lib/uur/hook"));
|
||||
candidates.push(PathBuf::from("/usr/local/lib/uur/hook"));
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
|
||||
}
|
||||
if let Ok(directory) = std::env::current_dir() {
|
||||
candidates.push(directory.join("build/hook"));
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|dir| complete_hook_directory(dir))
|
||||
@@ -65,32 +68,69 @@ fn hook_dir() -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
fn hook_source_dir() -> Result<PathBuf> {
|
||||
let mut candidates = vec![PathBuf::from("/usr/lib/uur/hook")];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
|
||||
hook_dir()
|
||||
}
|
||||
|
||||
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())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.push(
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(|d| d.join("../lib/uur/hook")))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
candidates.push(
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(|d| d.join("../../build/hook")))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
candidates.push(
|
||||
std::env::current_dir()
|
||||
.ok()
|
||||
.map(|dir| dir.join("build/hook"))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|dir| complete_hook_directory(dir))
|
||||
.context("hook DLLs not found (run the build first)")
|
||||
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
|
||||
@@ -104,7 +144,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(())
|
||||
@@ -118,7 +158,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
|
||||
let source_dir = hook_source_dir()?;
|
||||
let source = source_dir.join("uur-terminal-proxy.exe");
|
||||
let mux_source = source_dir.join("uur-mux-proxy.exe");
|
||||
let bin = install_dir.join("bin");
|
||||
let bin = crate::wine::client_payload_dir(install_dir);
|
||||
std::fs::create_dir_all(&bin)?;
|
||||
for status in ["uur-terminal-adapter.status", "uur-mux-adapter.status"] {
|
||||
let _ = std::fs::remove_file(bin.join(status));
|
||||
@@ -152,7 +192,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 +203,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,13 +228,11 @@ 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
|
||||
.join("bin")
|
||||
.join("MicrosoftEdgeWebview2Setup.exe");
|
||||
let bootstrapper =
|
||||
crate::wine::client_payload_dir(install_dir).join("MicrosoftEdgeWebview2Setup.exe");
|
||||
if !bootstrapper.is_file() {
|
||||
anyhow::bail!("{}", t!("session.webview_missing"));
|
||||
}
|
||||
@@ -202,7 +240,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 +249,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 +281,7 @@ fn acquire_session_lock() -> Result<std::fs::File> {
|
||||
|
||||
struct ManagedChild {
|
||||
child: Child,
|
||||
name: String,
|
||||
terminated: bool,
|
||||
}
|
||||
|
||||
@@ -263,10 +302,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 +379,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" | "winlogon"
|
||||
) {
|
||||
helper.ensure_running()?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SessionResources {
|
||||
@@ -342,9 +404,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 +433,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 +474,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,50 +502,85 @@ 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
|
||||
// process with that name satisfies the check.
|
||||
// process with that name satisfies the check. It also monitors the
|
||||
// Windows process table without repeatedly initializing Wine utilities.
|
||||
use std::os::unix::process::CommandExt;
|
||||
let marker = hook_dir()?.join("winlogon.exe");
|
||||
let _ = Command::new("wine")
|
||||
let mut monitor = Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
|
||||
.env("UUR_HOOK_LOG", log_path()?)
|
||||
.env("UUR_BRIDGE_PORT", config.bridge_port.to_string())
|
||||
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
|
||||
.env("UUR_MONITOR_CLIENT", "GameViewer.exe")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::from(log.try_clone()?))
|
||||
.arg(marker.to_string_lossy().as_ref())
|
||||
.spawn();
|
||||
.process_group(0)
|
||||
.arg(marker)
|
||||
.spawn()
|
||||
.context("starting the Windows session monitor")?;
|
||||
let monitor_output = monitor
|
||||
.stdout
|
||||
.take()
|
||||
.context("missing session monitor pipe")?;
|
||||
resources.helpers.push(ManagedChild {
|
||||
child: monitor,
|
||||
name: "winlogon".to_string(),
|
||||
terminated: false,
|
||||
});
|
||||
let mut client_monitor = ClientMonitor::new(monitor_output)?;
|
||||
|
||||
// The launcher talks to the service through the Windows Service Control
|
||||
// Manager, so the service must be started through `sc start` — a
|
||||
// directly spawned --service process is invisible to it and the UI
|
||||
// waits forever.
|
||||
if !service_running(&prefix) {
|
||||
let _ = Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.stderr(Stdio::from(log.try_clone()?))
|
||||
.args(["sc", "start", "GameViewerService"])
|
||||
.status();
|
||||
let _ = run_with_timeout(
|
||||
Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
|
||||
.args([r"C:\windows\system32\sc.exe", "start", "GameViewerService"]),
|
||||
std::time::Duration::from_secs(5),
|
||||
);
|
||||
}
|
||||
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,17 +607,19 @@ pub fn start() -> Result<()> {
|
||||
let mut missing_checks = 0u8;
|
||||
let mut relaunches = 0;
|
||||
while !stopping.load(Ordering::Relaxed) {
|
||||
let running = wine_client_process_exists(&prefix);
|
||||
if running {
|
||||
seen_client = true;
|
||||
missing_checks = 0;
|
||||
} else if seen_client {
|
||||
missing_checks = missing_checks.saturating_add(1);
|
||||
// UU hands off between short-lived launchers and its real Qt
|
||||
// process. Require a sustained absence before treating it as a
|
||||
// user-requested exit.
|
||||
if missing_checks >= 6 {
|
||||
break;
|
||||
resources.check_required_helpers()?;
|
||||
if let Some(running) = client_monitor.poll()? {
|
||||
if running {
|
||||
seen_client = true;
|
||||
missing_checks = 0;
|
||||
} else if seen_client {
|
||||
missing_checks = missing_checks.saturating_add(1);
|
||||
// UU hands off between short-lived launchers and its real Qt
|
||||
// process. Require a sustained absence before treating it as a
|
||||
// user-requested exit.
|
||||
if missing_checks >= 6 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !seen_client && std::time::Instant::now() >= deadline {
|
||||
@@ -520,26 +639,68 @@ pub fn start() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Query the Windows process table belonging to this exact Wine prefix.
|
||||
/// Read fresh process-table observations from this prefix's persistent marker.
|
||||
/// Modern Wine may host a Windows process in a Linux process whose `/proc`
|
||||
/// cmdline names another image, so Linux process-name matching is not a valid
|
||||
/// lifecycle boundary.
|
||||
fn wine_client_process_exists(prefix: &Path) -> bool {
|
||||
let output = run_with_timeout(
|
||||
Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.args([
|
||||
"tasklist",
|
||||
"/NH",
|
||||
"/FO",
|
||||
"CSV",
|
||||
"/FI",
|
||||
"IMAGENAME eq GameViewer.exe",
|
||||
]),
|
||||
std::time::Duration::from_secs(5),
|
||||
);
|
||||
output.is_some_and(|text| tasklist_contains_image(&text, "GameViewer.exe"))
|
||||
/// lifecycle boundary. A failed query never means that the client exited.
|
||||
struct ClientMonitor {
|
||||
output: std::process::ChildStdout,
|
||||
last_response: std::time::Instant,
|
||||
}
|
||||
|
||||
impl ClientMonitor {
|
||||
fn new(output: std::process::ChildStdout) -> Result<Self> {
|
||||
set_nonblocking(&output)?;
|
||||
Ok(Self {
|
||||
output,
|
||||
last_response: std::time::Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Result<Option<bool>> {
|
||||
let mut latest = None;
|
||||
let mut buffer = [0; 64];
|
||||
loop {
|
||||
match self.output.read(&mut buffer) {
|
||||
Ok(0) => anyhow::bail!("Windows session monitor disconnected"),
|
||||
Ok(count) => {
|
||||
for state in &buffer[..count] {
|
||||
latest = monitor_observation(*state)?;
|
||||
if latest.is_some() {
|
||||
self.last_response = std::time::Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error).context("reading Windows session monitor"),
|
||||
}
|
||||
}
|
||||
if self.last_response.elapsed() > std::time::Duration::from_secs(15) {
|
||||
anyhow::bail!(
|
||||
"Windows session monitor did not provide a valid observation for 15 seconds"
|
||||
);
|
||||
}
|
||||
Ok(latest)
|
||||
}
|
||||
}
|
||||
|
||||
fn monitor_observation(state: u8) -> Result<Option<bool>> {
|
||||
match state {
|
||||
b'1' => Ok(Some(true)),
|
||||
b'0' => Ok(Some(false)),
|
||||
b'?' => Ok(None),
|
||||
_ => anyhow::bail!("invalid Windows session monitor response"),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_nonblocking(pipe: &impl std::os::fd::AsRawFd) -> std::io::Result<()> {
|
||||
let fd = pipe.as_raw_fd();
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
||||
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a command with a hard timeout, returning its stdout (None on
|
||||
@@ -550,30 +711,49 @@ fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Opti
|
||||
use std::process::Stdio;
|
||||
|
||||
let mut child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let mut pipe = child.stdout.take()?;
|
||||
if set_nonblocking(&pipe).is_err() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
let mut stdout = Vec::new();
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) => {
|
||||
if std::time::Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
// Check exit before draining, so the command's final output is not
|
||||
// lost in a wait/read race. Never wait for EOF: Wine descendants can
|
||||
// retain this pipe after the utility itself has exited.
|
||||
let status = child.try_wait();
|
||||
let read = pipe
|
||||
.by_ref()
|
||||
.take(65537 - stdout.len() as u64)
|
||||
.read_to_end(&mut stdout);
|
||||
let read_failed = read.is_err_and(|error| {
|
||||
!matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
|
||||
)
|
||||
});
|
||||
if !read_failed && stdout.len() <= 65536 {
|
||||
if let Ok(Some(status)) = status {
|
||||
return status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&stdout).into_owned());
|
||||
}
|
||||
if status.is_ok() && std::time::Instant::now() < deadline {
|
||||
thread::sleep(std::time::Duration::from_millis(50));
|
||||
continue;
|
||||
}
|
||||
Err(_) => return None,
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(50));
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
let mut stdout = String::new();
|
||||
if let Some(mut pipe) = child.stdout.take() {
|
||||
let _ = pipe.read_to_string(&mut stdout);
|
||||
}
|
||||
Some(stdout)
|
||||
}
|
||||
|
||||
/// True when the Windows service reports STATE 4 (RUNNING) via `sc query`.
|
||||
@@ -582,8 +762,9 @@ fn service_running(prefix: &Path) -> bool {
|
||||
Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.args(["sc", "query", "GameViewerService"]),
|
||||
std::time::Duration::from_secs(10),
|
||||
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
|
||||
.args([r"C:\windows\system32\sc.exe", "query", "GameViewerService"]),
|
||||
std::time::Duration::from_secs(3),
|
||||
);
|
||||
match output {
|
||||
Some(text) => text.lines().any(|line| {
|
||||
@@ -594,15 +775,6 @@ fn service_running(prefix: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn tasklist_contains_image(output: &str, image: &str) -> bool {
|
||||
output.lines().any(|line| {
|
||||
line.split(',')
|
||||
.next()
|
||||
.map(|field| field.trim().trim_matches('"').eq_ignore_ascii_case(image))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
|
||||
fn log_path() -> Result<PathBuf> {
|
||||
Ok(data_dir()?.join("hook.log"))
|
||||
}
|
||||
@@ -633,6 +805,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 +886,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 +894,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 +903,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,11 +937,135 @@ 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)
|
||||
.arg("-k")
|
||||
.status();
|
||||
// Capture handles before Wine's shutdown: a WebView2 thread-group leader
|
||||
// can exit while its other threads retain the address space and pipes.
|
||||
let mut remaining = remaining_wine_processes(prefix);
|
||||
let _ = run_with_timeout(
|
||||
Command::new("wineserver")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.arg("-k"),
|
||||
std::time::Duration::from_secs(2),
|
||||
);
|
||||
// WebView2 workers can outlive their wineserver, blocked on inherited
|
||||
// pipes. Bind a pidfd before checking identity: PID reuse must never turn
|
||||
// cleanup of this managed prefix into a signal to an unrelated process.
|
||||
remaining.extend(remaining_wine_processes(prefix));
|
||||
for process in &remaining {
|
||||
signal_process(process, libc::SIGTERM);
|
||||
}
|
||||
if !remaining.is_empty() {
|
||||
thread::sleep(std::time::Duration::from_millis(250));
|
||||
for process in &remaining {
|
||||
signal_process(process, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remaining_wine_processes(prefix: &Path) -> Vec<std::os::fd::OwnedFd> {
|
||||
use std::os::fd::FromRawFd;
|
||||
|
||||
let Ok(prefix) = std::fs::canonicalize(prefix) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(entries) = std::fs::read_dir("/proc") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut processes = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let Some(pid) = entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.and_then(|name| name.parse::<u32>().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) } as i32;
|
||||
if fd < 0 {
|
||||
continue;
|
||||
}
|
||||
let process = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) };
|
||||
let directory = entry.path();
|
||||
let belongs_to_prefix = wine_process_matches(&directory, &prefix)
|
||||
|| (std::fs::read_link(directory.join("exe")).is_err()
|
||||
&& std::fs::read_dir(directory.join("task")).is_ok_and(|tasks| {
|
||||
tasks
|
||||
.flatten()
|
||||
.any(|task| wine_process_matches(&task.path(), &prefix))
|
||||
}));
|
||||
if belongs_to_prefix {
|
||||
processes.push(process);
|
||||
}
|
||||
}
|
||||
processes
|
||||
}
|
||||
|
||||
fn wine_process_matches(directory: &Path, prefix: &Path) -> bool {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
let Ok(executable) = std::fs::read_link(directory.join("exe")) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(
|
||||
executable.file_name().and_then(|name| name.to_str()),
|
||||
Some("wine" | "wine64" | "wine-preloader" | "wine64-preloader" | "wineserver")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let Ok(environment) = std::fs::read(directory.join("environ")) else {
|
||||
return false;
|
||||
};
|
||||
environment.split(|byte| *byte == 0).any(|variable| {
|
||||
variable.strip_prefix(b"WINEPREFIX=").is_some_and(|value| {
|
||||
let path = Path::new(std::ffi::OsStr::from_bytes(value));
|
||||
path.is_absolute() && std::fs::canonicalize(path).is_ok_and(|path| path == prefix)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn signal_process(process: &std::os::fd::OwnedFd, signal: i32) {
|
||||
use std::os::fd::AsRawFd;
|
||||
|
||||
unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_pidfd_send_signal,
|
||||
process.as_raw_fd(),
|
||||
signal,
|
||||
std::ptr::null::<libc::siginfo_t>(),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn wine_debug() -> String {
|
||||
@@ -729,6 +1076,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() {
|
||||
@@ -744,11 +1187,11 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tasklist_parser_matches_the_exact_image() {
|
||||
let output = "\"GameViewer.exe\",\"456\",\"Console\",\"1\"\n\
|
||||
\"GameViewerServer.exe\",\"464\",\"Console\",\"1\"\n";
|
||||
assert!(tasklist_contains_image(output, "GameViewer.exe"));
|
||||
assert!(!tasklist_contains_image(output, "GameViewerService.exe"));
|
||||
fn monitor_parser_distinguishes_absence_and_query_failure() {
|
||||
assert_eq!(monitor_observation(b'1').unwrap(), Some(true));
|
||||
assert_eq!(monitor_observation(b'0').unwrap(), Some(false));
|
||||
assert_eq!(monitor_observation(b'?').unwrap(), None);
|
||||
assert!(monitor_observation(b'X').is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+316
@@ -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(())
|
||||
})
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
|
||||
+501
-84
@@ -1,16 +1,26 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
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 +33,41 @@ 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() {
|
||||
anyhow::bail!("{}", t!("setup.prefix_failed", status = status));
|
||||
}
|
||||
flush_prefix(&prefix).context("waiting for Wine to persist the initialized prefix")?;
|
||||
|
||||
if find_client_dir(&prefix).is_some() && query_client_service(&prefix)? {
|
||||
finish_setup(&prefix)?;
|
||||
println!("{}", t!("setup.repaired", path = prefix.display()));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -57,82 +89,114 @@ 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))
|
||||
}
|
||||
|
||||
/// The Windows service NetEase's installer registers points at
|
||||
/// `GameViewerService.exe`. `GameViewerServer.exe` is a different program —
|
||||
/// the streaming/terminal server — and never appears in the service
|
||||
/// ImagePath, so matching on it made every provisioning check fail and left
|
||||
/// `uur setup` re-downloading and re-installing on an already complete prefix.
|
||||
const SERVICE_IMAGE: &str = "gameviewerservice.exe";
|
||||
|
||||
/// Extract the `ImagePath` recorded for the UU Windows service from the raw
|
||||
/// `system.reg` text. Kept pure so it can be tested without a Wine prefix.
|
||||
fn service_image_path(registry: &str) -> Option<String> {
|
||||
let mut service_section = false;
|
||||
for line in registry.lines() {
|
||||
if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) {
|
||||
service_section = section
|
||||
.0
|
||||
.to_ascii_lowercase()
|
||||
.ends_with(r"\\services\\gameviewerservice");
|
||||
} else if service_section {
|
||||
if let Some(value) = line.trim_start().strip_prefix("\"ImagePath\"=") {
|
||||
return Some(value.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read the persisted Wine service registration without starting Wine or
|
||||
/// showing component installers from `uur doctor`.
|
||||
pub fn client_service_registered(prefix: &Path) -> bool {
|
||||
let Ok(registry) = std::fs::read_to_string(prefix.join("system.reg")) else {
|
||||
return false;
|
||||
};
|
||||
service_image_path(®istry).is_some_and(|image| image.contains(SERVICE_IMAGE))
|
||||
}
|
||||
|
||||
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")?;
|
||||
// Wine may record the service under `ControlSet001` and only alias it as
|
||||
// `CurrentControlSet`, and `reg query` output is CRLF; matching the
|
||||
// executable name case-insensitively anywhere in stdout covers both.
|
||||
Ok(output.status.success()
|
||||
&& String::from_utf8_lossy(&output.stdout)
|
||||
.to_ascii_lowercase()
|
||||
.contains(SERVICE_IMAGE))
|
||||
}
|
||||
|
||||
/// Registry compatibility profile, ported from the field-tested reference
|
||||
/// implementation:
|
||||
///
|
||||
@@ -196,7 +260,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 +271,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 +306,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())
|
||||
}
|
||||
@@ -250,29 +350,145 @@ fn stop_wineserver(prefix: &Path) {
|
||||
.status();
|
||||
}
|
||||
|
||||
/// Wait for a new prefix's registry files without waiting for running services
|
||||
/// to exit. Existing prefixes can be queried through Wine immediately.
|
||||
fn flush_prefix(prefix: &Path) -> Result<()> {
|
||||
if prefix_initialized(prefix) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut child = Command::new("wineserver")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.arg("-w")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.context("starting wineserver registry wait")?;
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let result = loop {
|
||||
if prefix_initialized(prefix) {
|
||||
break Ok(());
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) if !status.success() => {
|
||||
break Err(anyhow::anyhow!(
|
||||
"wineserver registry wait failed ({status})"
|
||||
));
|
||||
}
|
||||
Err(error) => break Err(error).context("checking wineserver registry wait"),
|
||||
_ => {}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
break Err(anyhow::anyhow!(
|
||||
"Wine did not create non-empty system.reg and user.reg within 30 seconds"
|
||||
));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
};
|
||||
// This is only the `-w` waiter, not the prefix's server or its processes.
|
||||
if child.try_wait().ok().flatten().is_none() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Locate the installed client directory regardless of how NetEase spells
|
||||
/// the vendor folder ("Netease", "NetEase", ...). Case matters on Linux.
|
||||
///
|
||||
/// NetEase ships the payload both as `<root>/bin/` and as a sibling
|
||||
/// `<root>/<version>/` directory. The version directory is *not* the
|
||||
/// application root: uur reaches the client through `<root>/bin/...` for the
|
||||
/// terminal proxies and the WebView2 bootstrapper. The old search returned
|
||||
/// the first `GameViewerServer.exe` it happened to reach, so when readdir
|
||||
/// order put `<root>/<version>/` first it returned that instead, every
|
||||
/// `join("bin")` lookup missed, and `uur run` aborted with a missing WebView2
|
||||
/// bootstrapper.
|
||||
///
|
||||
/// Rank every directory that holds the launcher and pick the best-scoring,
|
||||
/// shallowest one, so the choice no longer depends on readdir order.
|
||||
pub fn find_client_dir(prefix: &Path) -> Option<PathBuf> {
|
||||
let program_files = prefix.join("drive_c").join("Program Files");
|
||||
let entries = std::fs::read_dir(&program_files).ok()?;
|
||||
let mut roots = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
if name.to_string_lossy().eq_ignore_ascii_case("netease") {
|
||||
let vendor = entry.path();
|
||||
if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) {
|
||||
let bin = found.parent()?;
|
||||
if bin
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("bin"))
|
||||
{
|
||||
return bin.parent().map(Path::to_path_buf);
|
||||
}
|
||||
return Some(bin.to_path_buf());
|
||||
if !entry
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.eq_ignore_ascii_case("netease")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
collect_client_roots(&entry.path(), 4, &mut roots);
|
||||
}
|
||||
roots.retain(|root| client_root_rank(root) > 0);
|
||||
roots.sort_by(|left, right| {
|
||||
client_root_rank(right)
|
||||
.cmp(&client_root_rank(left))
|
||||
.then_with(|| left.components().count().cmp(&right.components().count()))
|
||||
.then_with(|| left.cmp(right))
|
||||
});
|
||||
roots.dedup();
|
||||
roots.into_iter().next()
|
||||
}
|
||||
|
||||
/// Installed releases normally place their payload in bin/. A complete flat
|
||||
/// version directory remains usable when it is the only installation present.
|
||||
pub fn client_payload_dir(client: &Path) -> PathBuf {
|
||||
let bin = client.join("bin");
|
||||
if non_empty_file(&bin.join("GameViewerServer.exe")) {
|
||||
bin
|
||||
} else {
|
||||
client.to_path_buf()
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect every directory that contains the client launcher.
|
||||
fn collect_client_roots(dir: &Path, depth: u8, out: &mut Vec<PathBuf>) {
|
||||
if depth == 0 {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_client_roots(&path, depth - 1, out);
|
||||
} else if path
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("GameViewer.exe"))
|
||||
&& non_empty_file(&path)
|
||||
{
|
||||
if let Some(parent) = path.parent() {
|
||||
out.push(parent.to_path_buf());
|
||||
}
|
||||
return Some(vendor);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Score a candidate root by how well it matches the layout uur drives.
|
||||
///
|
||||
/// `bin/GameViewerServer.exe` is the strong signal: the terminal proxies and
|
||||
/// the WebView2 bootstrapper are all reached through `<root>/bin/`, so a
|
||||
/// candidate whose `bin` holds the server is the real root, while the
|
||||
/// `<root>/<version>/` payload copy only holds the launcher at its top level.
|
||||
fn client_root_rank(candidate: &Path) -> u8 {
|
||||
let bin = candidate.join("bin");
|
||||
if non_empty_file(&bin.join("GameViewerServer.exe")) {
|
||||
4 + u8::from(non_empty_file(&bin.join("MicrosoftEdgeWebview2Setup.exe")))
|
||||
} else if non_empty_file(&candidate.join("GameViewerServer.exe")) {
|
||||
2 + u8::from(non_empty_file(
|
||||
&candidate.join("MicrosoftEdgeWebview2Setup.exe"),
|
||||
))
|
||||
} else {
|
||||
// A launcher alone can be left behind by an interrupted installer.
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_file(path: &Path) -> bool {
|
||||
std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
|
||||
}
|
||||
|
||||
fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf> {
|
||||
@@ -282,7 +498,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 +544,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 +572,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 +593,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 +645,177 @@ fn purge_wine_shortcuts() {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::find_client_dir;
|
||||
use super::log_pixels_command;
|
||||
use super::registry_compat_entries;
|
||||
use super::service_image_path;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Scratch prefix with a real NetEase directory layout, removed on drop.
|
||||
struct TestPrefix(PathBuf);
|
||||
|
||||
impl TestPrefix {
|
||||
fn create() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"uur-client-dir-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Create `<prefix>/drive_c/Program Files/Netease/GameViewer/<rel>`.
|
||||
fn write_client_file(&self, rel: &str, contents: &[u8]) {
|
||||
let path = self
|
||||
.0
|
||||
.join("drive_c/Program Files/Netease/GameViewer")
|
||||
.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, contents).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestPrefix {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Populate both payload copies NetEase installs. The buggy search
|
||||
/// returned `<version>/` whenever readdir reached it first, which then
|
||||
/// failed every `join("bin")` lookup.
|
||||
fn install_both_layouts(prefix: &TestPrefix) {
|
||||
for relative in [
|
||||
"GameViewer.exe",
|
||||
"GameViewerServer.exe",
|
||||
"bin/GameViewer.exe",
|
||||
"bin/GameViewerServer.exe",
|
||||
"4.42.0.2770/GameViewer.exe",
|
||||
"4.42.0.2770/GameViewerServer.exe",
|
||||
] {
|
||||
prefix.write_client_file(relative, b"payload");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_root_is_the_directory_holding_bin_not_the_version_directory() {
|
||||
let prefix = TestPrefix::create();
|
||||
install_both_layouts(&prefix);
|
||||
|
||||
let root = find_client_dir(prefix.path()).expect("client root");
|
||||
|
||||
assert!(
|
||||
root.join("bin").join("GameViewerServer.exe").is_file(),
|
||||
"the returned root must contain bin/GameViewerServer.exe, got {}",
|
||||
root.display()
|
||||
);
|
||||
assert!(
|
||||
!root.file_name().is_some_and(|name| name == "4.42.0.2770"),
|
||||
"the version directory must not be selected, got {}",
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_root_is_stable_regardless_of_readdir_order() {
|
||||
let prefix = TestPrefix::create();
|
||||
install_both_layouts(&prefix);
|
||||
let expected = find_client_dir(prefix.path()).unwrap();
|
||||
// Repeated lookups must not alternate between the two payload copies.
|
||||
for _ in 0..16 {
|
||||
assert_eq!(find_client_dir(prefix.path()).as_ref(), Some(&expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bin_layout_outranks_a_versioned_payload_copy() {
|
||||
let prefix = TestPrefix::create();
|
||||
// The versioned copy has the launcher and server at its top level,
|
||||
// but no bin/; the real root has the payload in bin/.
|
||||
prefix.write_client_file("GameViewer.exe", b"payload");
|
||||
prefix.write_client_file("4.42.0.2770/GameViewer.exe", b"payload");
|
||||
prefix.write_client_file("4.42.0.2770/GameViewerServer.exe", b"payload");
|
||||
prefix.write_client_file("bin/GameViewerServer.exe", b"payload");
|
||||
|
||||
let root = find_client_dir(prefix.path()).expect("client root");
|
||||
|
||||
assert!(
|
||||
root.join("bin").join("GameViewerServer.exe").is_file(),
|
||||
"the bin layout must win, got {}",
|
||||
root.display()
|
||||
);
|
||||
assert!(
|
||||
!root.file_name().is_some_and(|name| name == "4.42.0.2770"),
|
||||
"the version directory must not win, got {}",
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versioned_copy_is_used_only_when_it_is_the_only_candidate() {
|
||||
let prefix = TestPrefix::create();
|
||||
prefix.write_client_file("4.42.0.2770/GameViewer.exe", b"payload");
|
||||
prefix.write_client_file("4.42.0.2770/GameViewerServer.exe", b"payload");
|
||||
|
||||
let root = find_client_dir(prefix.path()).expect("client root");
|
||||
|
||||
assert!(root.ends_with("4.42.0.2770"), "got {}", root.display());
|
||||
assert_eq!(super::client_payload_dir(&root), root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_client_reports_none() {
|
||||
let prefix = TestPrefix::create();
|
||||
std::fs::create_dir_all(prefix.path().join("drive_c/Program Files/Netease")).unwrap();
|
||||
assert!(find_client_dir(prefix.path()).is_none());
|
||||
prefix.write_client_file("GameViewer.exe", b"payload");
|
||||
prefix.write_client_file("bin/MicrosoftEdgeWebview2Setup.exe", b"payload");
|
||||
assert!(find_client_dir(prefix.path()).is_none());
|
||||
}
|
||||
|
||||
/// Real `system.reg` excerpt written by the NetEase installer, escaped
|
||||
/// exactly as Wine stores it. The service ImagePath names
|
||||
/// GameViewerService.exe, not GameViewerServer.exe.
|
||||
const INSTALLED_SYSTEM_REG: &str = concat!(
|
||||
"[System\\\\ControlSet001\\\\Services\\\\GameViewerService] 1791878366\n",
|
||||
"#time=1dd5ae8c44b323c\n",
|
||||
"\"DependOnService\"=str(7):\"RpcSs\\0Tcpip\\0NDIS\\0AFD\\0\"\n",
|
||||
"\"DisplayName\"=\"GameViewerService\"\n",
|
||||
"\"ImagePath\"=str(2):\"\\\"C:\\\\Program Files\\\\Netease\\\\GameViewer",
|
||||
"\\\\GameViewerService.exe\\\" --service\"\n",
|
||||
"\"ObjectName\"=\"LocalSystem\"\n",
|
||||
"\"Start\"=dword:00000002\n",
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn service_registration_matches_the_image_the_installer_registers() {
|
||||
// Regression: the check looked for gameviewerserver.exe, which never
|
||||
// appears in the service ImagePath, so a complete install was always
|
||||
// reported as missing and `uur setup` reinstalled on every run.
|
||||
let image = service_image_path(INSTALLED_SYSTEM_REG).expect("ImagePath parsed");
|
||||
assert!(image.contains("gameviewerservice.exe"));
|
||||
assert!(!image.contains("gameviewerserver.exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_service_section_is_not_registered() {
|
||||
let registry = "[Software\\\\Wine\\\\DllOverrides] 1\n\"winemenubuilder\"=\"\"\n";
|
||||
assert!(service_image_path(registry).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_section_without_image_path_is_not_registered() {
|
||||
let registry = "[System\\\\ControlSet001\\\\Services\\\\GameViewerService] 1\n\
|
||||
\"Start\"=dword:00000002\n";
|
||||
assert!(service_image_path(registry).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_cpp_runtime_is_preferred_for_both_uu_processes() {
|
||||
@@ -436,4 +829,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",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user