19 Commits
Author SHA1 Message Date
Xuc Pan d349e6ff6a chore(release): prepare v0.1.4 2026-10-05 23:40:39 +08:00
Xuc Pan 01e7ed7218 Merge pull request #20 from panxuc/fix-issue-18-prefix-deploy
fix: make managed prefix deployment repeatable
2026-10-05 23:33:03 +08:00
Xuc Pan 3c78382f20 test(session): cover first deployment from readonly source 2026-10-05 23:24:53 +08:00
Xuc Pan 2833b08a37 fix(session): make prefix deployment repeatable 2026-10-05 23:19:31 +08:00
Xuc Pan 8fd476d81c Merge pull request #16 from panxuc/fix-issue-14-input-bridge
fix: keep input bridge alive for unsupported key events
2026-10-05 23:11:28 +08:00
Xuc Pan 31aaab0fee fix(bridge): ignore zero virtual-key input 2026-09-30 06:59:52 +08:00
Xuc Pan 5245c9ee61 fix(desktop): improve HiDPI and exit integration 2026-09-25 03:04:51 +08:00
Xuc Pan 9f12a88a08 fix(desktop): improve HiDPI and exit integration 2026-09-25 03:04:51 +08:00
Muush 2b41541128 fix(wallpaper): resolve wpaperd relative targets from its working directory
wpaperd writes configured image paths verbatim into the state symlink, so
targets relative to its working directory dangle under symlink semantics
and link.canonicalize() fails for every output. Read /proc/<pid>/cwd where
the process is matched and resolve relative targets against it; absolute
targets keep filesystem semantics.
2026-09-24 23:14:23 +08:00
Xuc Pan d47178916f fix(wallpaper): resolve wpaperd links from link location 2026-09-24 13:13:12 +08:00
Muush 3dc3b62477 feat(wallpaper): detect wpaperd wallpapers from state links
wpaperd mirrors the current wallpaper of every output as a symlink
under $XDG_STATE_HOME/wpaperd/wallpapers, rewritten on each change.
Identify the wpaperd process in the runtime provider scan and resolve
the newest link, joining relative targets with $HOME.
2026-09-24 13:13:12 +08:00
Xuc Pan bb6476a864 chore(release): prepare v0.1.3 2026-09-23 09:31:40 +08:00
Xuc Pan 17a09e08a5 fix(wine): use builtin DLLs for WebView2 setup 2026-09-23 09:00:41 +08:00
Xuc Pan eb9f35968e chore(release): prepare v0.1.2 2026-09-21 21:31:57 +08:00
Xuc Pan 55eaf98e75 fix(hook): align cursor overlay with GDI screen coordinates 2026-09-21 21:22:19 +08:00
dashanlkk a698c54c66 fix(hook): overlay cursor in X11 GDI captures 2026-09-21 21:22:19 +08:00
Xuc Pan c9cfc479dc fix(wine): prefer bundled msvcp140 for UU 4.41 2026-09-20 22:54:50 +08:00
HTwoOhwater fd2368058f fix(bridge): dispatch concurrent hook input without socket lifetime locking 2026-09-20 22:53:27 +08:00
Xuc Pan fba3fb9604 style(icon): update icon 2026-09-05 21:30:26 +08:00
24 changed files with 929 additions and 54 deletions

No files matched your search

+2
View File
@@ -20,6 +20,8 @@ jobs:
cargo test --locked --all-targets
cc -std=c11 -O2 -Wall -Wextra -Werror tests/frame-protocol.c -o /tmp/frame-protocol
/tmp/frame-protocol
cc -std=c11 -O2 -Wall -Wextra -Werror tests/cursor-overlay.c -o /tmp/cursor-overlay
/tmp/cursor-overlay
- name: Build
run: cargo build --locked --release
Generated
+1 -1
View File
@@ -1413,7 +1413,7 @@ dependencies = [
[[package]]
name = "uur"
version = "0.1.1"
version = "0.1.4"
dependencies = [
"anyhow",
"ashpd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "uur"
version = "0.1.1"
version = "0.1.4"
edition = "2021"
description = "Native Linux companion for NetEase UU Remote: X11/Wayland input and capture, packaged as a regular desktop app"
license = "MIT"
+8 -4
View File
@@ -69,7 +69,7 @@ recipes and release artifacts share one version and filesystem layout.
Install a downloaded release package with pacman:
```bash
sudo pacman -U ./dist/uur-0.1.1-1-x86_64.pkg.tar.zst
sudo pacman -U ./dist/uur-0.1.4-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.1_amd64.deb
sudo apt install ./uur_0.1.4_amd64.deb
```
### Fedora and compatible RPM systems
```bash
sudo dnf install ./uur-0.1.1-1.x86_64.rpm
sudo dnf install ./uur-0.1.4-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.1-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.4-linux-x86_64.tar.zst
```
### Nix and NixOS
@@ -154,6 +154,10 @@ uur display source virtual
uur stop # Stop only uur's helpers and Wine prefix
```
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.
Diagnostic input overrides:
```bash
+7 -4
View File
@@ -66,7 +66,7 @@ uur run
使用 pacman 安装下载的正式发布包:
```bash
sudo pacman -U ./dist/uur-0.1.1-1-x86_64.pkg.tar.zst
sudo pacman -U ./dist/uur-0.1.4-1-x86_64.pkg.tar.zst
```
### AUR
@@ -80,13 +80,13 @@ paru -S uur
### Debian、Ubuntu 及兼容发行版
```bash
sudo apt install ./uur_0.1.1_amd64.deb
sudo apt install ./uur_0.1.4_amd64.deb
```
### Fedora 及兼容 RPM 发行版
```bash
sudo dnf install ./uur-0.1.1-1.x86_64.rpm
sudo dnf install ./uur-0.1.4-1.x86_64.rpm
```
如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。
@@ -94,7 +94,7 @@ sudo dnf install ./uur-0.1.1-1.x86_64.rpm
### 通用压缩包
```bash
sudo tar --zstd -C / -xf ./uur-0.1.1-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.4-linux-x86_64.tar.zst
```
### Nix 与 NixOS
@@ -149,6 +149,9 @@ uur display source virtual
uur stop # 只停止 uur 助手与专用 Wine 前缀
```
从桌面启动 UU 后,可在启动器的应用操作菜单中选择“退出”;从终端运行时可执行
`uur stop` 或按 Ctrl+C。
输入后端排错:
```bash
Binary file not shown.

Before

Width:  |  Height:  |  Size: 539 KiB

After

Width:  |  Height:  |  Size: 993 KiB

+5 -5
View File
@@ -12,13 +12,13 @@ needed for system-wide package installation.
paru -S uur
# Downloaded release package
sudo pacman -U ./uur-0.1.1-1-x86_64.pkg.tar.zst
sudo pacman -U ./uur-0.1.4-1-x86_64.pkg.tar.zst
```
## Debian, Ubuntu, and derivatives
```bash
sudo apt install ./uur_0.1.1_amd64.deb
sudo apt install ./uur_0.1.4_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.1-1.x86_64.rpm
sudo dnf install ./uur-0.1.4-1.x86_64.rpm
# openSUSE
sudo zypper install ./uur-0.1.1-1.x86_64.rpm
sudo zypper install ./uur-0.1.4-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.1-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.4-linux-x86_64.tar.zst
```
## Nix and NixOS
+5 -5
View File
@@ -46,7 +46,7 @@ paru -S uur
From a downloaded Arch package:
```bash
sudo pacman -U ./uur-0.1.1-1-x86_64.pkg.tar.zst
sudo pacman -U ./uur-0.1.4-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.1_amd64.deb
sudo apt install ./uur_0.1.4_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.1-1.x86_64.rpm
sudo dnf install ./uur-0.1.4-1.x86_64.rpm
# openSUSE family
sudo zypper install ./uur-0.1.1-1.x86_64.rpm
sudo zypper install ./uur-0.1.4-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.1-linux-x86_64.tar.zst
sudo tar --zstd -C / -xf ./uur-0.1.4-linux-x86_64.tar.zst
```
Alternatively, build and install for one user:
+83
View File
@@ -0,0 +1,83 @@
#ifndef UUR_CURSOR_OVERLAY_H
#define UUR_CURSOR_OVERLAY_H
#include <limits.h>
#include <stdint.h>
typedef struct uur_cursor_rect {
int x;
int y;
int width;
int height;
} uur_cursor_rect;
typedef struct uur_cursor_shape {
/* The hotspot is in the same screen coordinates as the GDI source DC. */
int x;
int y;
int width;
int height;
int hotspot_x;
int hotspot_y;
} uur_cursor_shape;
static inline int uur_cursor_bitmap_height(int mask_height, int has_color)
{
return has_color ? mask_height : mask_height / 2;
}
static inline int uur_map_cursor_overlay(const uur_cursor_rect *source,
const uur_cursor_rect *destination,
const uur_cursor_shape *cursor,
uur_cursor_rect *overlay)
{
int64_t left;
int64_t top;
int64_t scaled_hotspot_x;
int64_t scaled_hotspot_y;
int64_t scaled_width;
int64_t scaled_height;
int64_t mapped_x;
int64_t mapped_y;
if (source->width <= 0 || source->height <= 0 ||
destination->width <= 0 || destination->height <= 0 ||
cursor->width <= 0 || cursor->height <= 0)
return 0;
left = (int64_t)cursor->x - cursor->hotspot_x;
top = (int64_t)cursor->y - cursor->hotspot_y;
/* Keep partially visible cursors at the edges of the captured region. */
if (left >= (int64_t)source->x + source->width ||
top >= (int64_t)source->y + source->height ||
left + cursor->width <= source->x ||
top + cursor->height <= source->y)
return 0;
scaled_hotspot_x = ((int64_t)cursor->hotspot_x * destination->width +
source->width / 2) / source->width;
scaled_hotspot_y = ((int64_t)cursor->hotspot_y * destination->height +
source->height / 2) / source->height;
scaled_width = ((int64_t)cursor->width * destination->width +
source->width / 2) / source->width;
scaled_height = ((int64_t)cursor->height * destination->height +
source->height / 2) / source->height;
mapped_x = (int64_t)destination->x +
(((int64_t)cursor->x - source->x) * destination->width) /
source->width - scaled_hotspot_x;
mapped_y = (int64_t)destination->y +
(((int64_t)cursor->y - source->y) * destination->height) /
source->height - scaled_hotspot_y;
if (mapped_x < INT_MIN || mapped_x > INT_MAX || mapped_y < INT_MIN ||
mapped_y > INT_MAX || scaled_width > INT_MAX ||
scaled_height > INT_MAX)
return 0;
overlay->x = (int)mapped_x;
overlay->y = (int)mapped_y;
overlay->width = scaled_width > 0 ? (int)scaled_width : 1;
overlay->height = scaled_height > 0 ? (int)scaled_height : 1;
return 1;
}
#endif
+73 -4
View File
@@ -26,6 +26,7 @@
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "cursor-overlay.h"
#include "frame-protocol.h"
#define UUR_MAGIC 0x50495555u
@@ -328,6 +329,63 @@ static BOOL source_is_screen_dc(HDC source)
GetDeviceCaps(source, TECHNOLOGY) == DT_RASDISPLAY;
}
/* GDI screen captures do not include the X11 hardware cursor. Keep the
* cursor visible in the fallback path used on X11 by compositing Wine's
* current cursor onto the capture destination after the desktop blit. */
static void draw_cursor_overlay(HDC hdc_dest, int x, int y, int width, int height,
int source_x, int source_y, int source_width,
int source_height)
{
CURSORINFO cursor;
ICONINFO icon;
BITMAP mask;
POINT position;
uur_cursor_rect source = {source_x, source_y, source_width, source_height};
uur_cursor_rect destination = {x, y, width, height};
uur_cursor_rect overlay;
uur_cursor_shape shape;
if (hdc_dest == NULL || width <= 0 || height <= 0 || source_width <= 0 ||
source_height <= 0 || source_is_screen_dc(hdc_dest))
return;
ZeroMemory(&cursor, sizeof(cursor));
cursor.cbSize = sizeof(cursor);
if (!GetCursorInfo(&cursor) || !(cursor.flags & CURSOR_SHOWING) ||
!GetCursorPos(&position))
return;
/* Wine can report a visible cursor with a null handle until the first
* real window has selected a class cursor. A generic arrow is preferable
* to dropping the cursor from the remote frame altogether. */
if (cursor.hCursor == NULL)
cursor.hCursor = LoadCursor(NULL, IDC_ARROW);
if (cursor.hCursor == NULL)
return;
ZeroMemory(&icon, sizeof(icon));
if (!GetIconInfo(cursor.hCursor, &icon))
return;
/* GetIconInfo's mask holds the cursor's actual bitmap dimensions. For a
* monochrome cursor the AND/XOR masks are stacked vertically. */
if (icon.hbmMask != NULL &&
GetObjectW(icon.hbmMask, sizeof(mask), &mask) == sizeof(mask)) {
shape.x = position.x;
shape.y = position.y;
shape.width = mask.bmWidth;
shape.height = uur_cursor_bitmap_height(mask.bmHeight,
icon.hbmColor != NULL);
shape.hotspot_x = (int)icon.xHotspot;
shape.hotspot_y = (int)icon.yHotspot;
if (uur_map_cursor_overlay(&source, &destination, &shape, &overlay))
DrawIconEx(hdc_dest, overlay.x, overlay.y, cursor.hCursor,
overlay.width, overlay.height, 0, NULL, DI_NORMAL);
}
if (icon.hbmColor != NULL)
DeleteObject(icon.hbmColor);
if (icon.hbmMask != NULL)
DeleteObject(icon.hbmMask);
}
/* 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). */
@@ -436,21 +494,32 @@ static BOOL try_capture_feed(HDC hdc_dest, int x, int y, DWORD rop,
BOOL WINAPI hook_bit_blt(HDC hdc_dest, int x, int y, int width, int height,
HDC hdc_src, int x_src, int y_src, DWORD rop)
{
BOOL result;
if (try_capture_feed(hdc_dest, x, y, rop, hdc_src, width, height, x_src,
y_src, width, height))
return TRUE;
return original_bit_blt(hdc_dest, x, y, width, height, hdc_src, x_src,
y_src, rop);
result = original_bit_blt(hdc_dest, x, y, width, height, hdc_src, x_src,
y_src, rop);
if (result && (rop & 0x00ffffffu) == SRCCOPY && hdc_src != NULL &&
source_is_screen_dc(hdc_src))
draw_cursor_overlay(hdc_dest, x, y, width, height, x_src, y_src,
width, height);
return result;
}
BOOL WINAPI hook_stretch_blt(HDC hdc_dest, int x, int y, int w, int h,
HDC hdc_src, int xs, int ys, int sw, int sh,
DWORD rop)
{
BOOL result;
if (try_capture_feed(hdc_dest, x, y, rop, hdc_src, w, h, xs, ys, sw, sh))
return TRUE;
return original_stretch_blt(hdc_dest, x, y, w, h, hdc_src, xs, ys, sw,
sh, rop);
result = original_stretch_blt(hdc_dest, x, y, w, h, hdc_src, xs, ys, sw,
sh, rop);
if (result && (rop & 0x00ffffffu) == SRCCOPY && hdc_src != NULL &&
source_is_screen_dc(hdc_src))
draw_cursor_overlay(hdc_dest, x, y, w, h, xs, ys, sw, sh);
return result;
}
/* ---- diagnostics ------------------------------------------------------ */
+1
View File
@@ -55,6 +55,7 @@ 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}"
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."
+1
View File
@@ -43,6 +43,7 @@ session:
webview_failed: "WebView2 安装失败"
quick_launch_ready: "已向 UU 快速启动导出 %{count} 个 Linux 应用"
audio_backend: "Wine 音频后端:%{backend}"
wine_dpi: "已根据 Xft.dpi 设置 Wine 系统 DPI:%{dpi}"
upstream:
unreachable: "无法访问网易官方发布接口"
+1 -1
View File
@@ -23,7 +23,7 @@ let
in
rustPlatform.buildRustPackage {
pname = "uur";
version = "0.1.1";
version = "0.1.4";
src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;
+1 -1
View File
@@ -1,7 +1,7 @@
# Contributor: uur contributors
# Maintainer: uur contributors
pkgname=uur
pkgver=0.1.1
pkgver=0.1.4
pkgrel=0
pkgdesc="Native Linux companion for NetEase UU Remote"
url="https://github.com/panxuc/uur"
+2 -2
View File
@@ -1,6 +1,6 @@
pkgbase = uur
pkgdesc = Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)
pkgver = 0.1.1
pkgver = 0.1.4
pkgrel = 1
url = https://github.com/panxuc/uur
install = uur.install
@@ -31,7 +31,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.1.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.1.tar.gz
source = uur-0.1.4.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.4.tar.gz
sha256sums = SKIP
pkgname = uur
+1 -1
View File
@@ -8,7 +8,7 @@
# `uur setup` (it is never redistributed by this package).
pkgname=uur
pkgver=0.1.1
pkgver=0.1.4
pkgrel=1
pkgdesc="Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)"
arch=('x86_64')
Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 57 KiB

+7
View File
@@ -9,6 +9,13 @@ Comment[zh_CN]=在本 Linux 桌面启动完整的 UU 远程会话
Exec=uur run
TryExec=uur
Icon=uur
StartupWMClass=gameviewer.exe
Terminal=false
Categories=Network;RemoteAccess;
Keywords=remote;desktop;uu;网易;远程;
Actions=Quit;
[Desktop Action Quit]
Name=Quit
Name[zh_CN]=退出
Exec=uur stop
+3
View File
@@ -12,5 +12,8 @@ cargo test --manifest-path "$project_root/Cargo.toml" --all-targets
cc -std=c11 -O2 -Wall -Wextra -Werror \
"$project_root/tests/frame-protocol.c" -o "$temporary/frame-protocol"
"$temporary/frame-protocol"
cc -std=c11 -O2 -Wall -Wextra -Werror \
"$project_root/tests/cursor-overlay.c" -o "$temporary/cursor-overlay"
"$temporary/cursor-overlay"
"$project_root/hook/build.sh"
"$project_root/capture/build.sh"
+327 -7
View File
@@ -1,12 +1,122 @@
use anyhow::{Context, Result};
use std::collections::{HashMap, HashSet};
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
use crate::config::Config;
use crate::input;
use crate::protocol::{self, RECORD_BYTES, RECORD_HELLO};
struct SharedInput {
backend: Box<dyn input::InputBackend>,
keys: HashMap<u16, usize>,
buttons: HashMap<u16, usize>,
}
struct ConnectionInput {
shared: Arc<Mutex<SharedInput>>,
name: &'static str,
keys: HashSet<u16>,
buttons: HashSet<u16>,
}
impl ConnectionInput {
fn press(&mut self, code: u16, down: bool, keyboard: bool) -> Result<()> {
let mut shared = self.shared.lock().unwrap();
let held = if keyboard {
&mut self.keys
} else {
&mut self.buttons
};
let owners = if keyboard {
&shared.keys
} else {
&shared.buttons
};
let count = owners.get(&code).copied().unwrap_or(0);
if !down && !held.contains(&code) {
return Ok(());
}
if down || count <= 1 {
if keyboard {
shared.backend.key(code, down)?;
} else {
shared.backend.button(code, down)?;
}
}
let owners = if keyboard {
&mut shared.keys
} else {
&mut shared.buttons
};
if down {
if held.insert(code) {
*owners.entry(code).or_default() += 1;
}
} else {
held.remove(&code);
if count <= 1 {
owners.remove(&code);
} else {
owners.insert(code, count - 1);
}
}
Ok(())
}
}
impl input::InputBackend for ConnectionInput {
fn name(&self) -> &'static str {
self.name
}
fn key(&mut self, code: u16, down: bool) -> Result<()> {
self.press(code, down, true)
}
fn button(&mut self, code: u16, down: bool) -> Result<()> {
self.press(code, down, false)
}
fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> {
self.shared.lock().unwrap().backend.motion(absolute, x, y)
}
fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> {
self.shared.lock().unwrap().backend.wheel(horizontal, delta)
}
fn release_all(&mut self) -> Result<()> {
let mut error = None;
for code in self.keys.clone() {
if let Err(e) = self.key(code, false) {
error = Some(e);
}
}
for code in self.buttons.clone() {
if let Err(e) = self.button(code, false) {
error = Some(e);
}
}
// A disconnected client must not retain ownership if a release fails.
let mut shared = self.shared.lock().unwrap();
for code in self.keys.drain() {
if let Some(count) = shared.keys.get_mut(&code) {
*count -= 1;
if *count == 0 {
shared.keys.remove(&code);
}
}
}
for code in self.buttons.drain() {
if let Some(count) = shared.buttons.get_mut(&code) {
*count -= 1;
if *count == 0 {
shared.buttons.remove(&code);
}
}
}
error.map_or(Ok(()), Err)
}
}
/// Print the X11 pointer position — the before/after observable for hook
/// verification.
pub fn print_pointer() -> Result<()> {
@@ -19,8 +129,8 @@ pub fn print_pointer() -> Result<()> {
Ok(())
}
/// Serve the in-client hook: one authenticated loopback connection at a
/// time, records dispatched to the selected input backend.
/// Serve authenticated loopback hook connections, serializing individual
/// input events without holding the backend lock while waiting for records.
pub fn serve() -> Result<()> {
let config = Config::load()?;
let preferred =
@@ -29,7 +139,12 @@ pub fn serve() -> Result<()> {
if let Some(path) = std::env::var_os("UUR_BACKEND_STATUS") {
std::fs::write(path, selected.name()).context("writing backend status")?;
}
let backend = std::sync::Arc::new(std::sync::Mutex::new(selected));
let backend_name = selected.name();
let backend = Arc::new(Mutex::new(SharedInput {
backend: selected,
keys: HashMap::new(),
buttons: HashMap::new(),
}));
let backend_handle = backend.clone();
let addr = format!("127.0.0.1:{}", config.bridge_port);
let listener = TcpListener::bind(&addr).with_context(|| format!("binding {addr}"))?;
@@ -52,9 +167,16 @@ pub fn serve() -> Result<()> {
Ok(false) => return,
Err(_) => return,
}
let mut guard = backend_handle.lock().unwrap();
println!("{}", t!("bridge.connected", backend = guard.name()));
match pump(&mut stream, guard.as_mut()) {
use input::InputBackend;
// Read sockets without holding the shared desktop input lock.
let mut connection = ConnectionInput {
shared: backend_handle,
name: backend_name,
keys: HashSet::new(),
buttons: HashSet::new(),
};
println!("{}", t!("bridge.connected", backend = connection.name()));
match pump(&mut stream, &mut connection) {
Ok(count) => {
println!("{}", t!("bridge.session_summary", count = count));
println!("{}", t!("bridge.disconnected_clean"));
@@ -66,7 +188,7 @@ pub fn serve() -> Result<()> {
);
}
}
let _ = guard.release_all();
let _ = connection.release_all();
});
}
Ok(())
@@ -97,6 +219,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) {
@@ -114,6 +237,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;
}
@@ -165,3 +301,187 @@ fn tokens_differ(a: &[u8; 32], b: &[u8; 32]) -> bool {
}
diff != 0
}
#[cfg(test)]
mod tests {
use super::*;
use crate::input::InputBackend;
use std::io::Write;
use std::sync::mpsc;
use std::time::Duration;
struct Recorder(mpsc::Sender<String>);
impl InputBackend for Recorder {
fn name(&self) -> &'static str {
"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(())
}
fn button(&mut self, code: u16, down: bool) -> Result<()> {
self.0.send(format!("button {code} {down}"))?;
Ok(())
}
fn motion(&mut self, _: bool, _: i32, _: i32) -> Result<()> {
self.0.send("motion".into())?;
Ok(())
}
fn wheel(&mut self, _: bool, _: i32) -> Result<()> {
Ok(())
}
fn release_all(&mut self) -> Result<()> {
panic!("must release only owned inputs")
}
}
fn connection(shared: &Arc<Mutex<SharedInput>>) -> ConnectionInput {
ConnectionInput {
shared: shared.clone(),
name: "test",
keys: HashSet::new(),
buttons: HashSet::new(),
}
}
fn shared() -> (Arc<Mutex<SharedInput>>, mpsc::Receiver<String>) {
let (tx, rx) = mpsc::channel();
(
Arc::new(Mutex::new(SharedInput {
backend: Box::new(Recorder(tx)),
keys: HashMap::new(),
buttons: HashMap::new(),
})),
rx,
)
}
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();
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 idle = connection(&shared);
let thread = thread::spawn(move || pump(&mut server, &mut idle).unwrap());
let mut packet = Vec::new();
for value in [
protocol::MAGIC,
1,
protocol::RECORD_MOUSE,
16,
protocol::RECORD_MOUSE,
] {
packet.extend_from_slice(&value.to_le_bytes());
}
packet.extend_from_slice(&0xffffu16.to_le_bytes());
packet.extend_from_slice(&0u16.to_le_bytes());
packet.extend_from_slice(&1i32.to_le_bytes());
packet.extend_from_slice(&0i32.to_le_bytes());
client.write_all(&packet).unwrap();
assert_eq!(
events.recv_timeout(Duration::from_secs(2)).unwrap(),
"motion"
);
let mut other = connection(&shared);
let other_thread = thread::spawn(move || other.motion(false, 1, 0).unwrap());
let delivered = events.recv_timeout(Duration::from_secs(2));
drop(client);
thread.join().unwrap();
other_thread.join().unwrap();
assert_eq!(delivered.unwrap(), "motion");
}
#[test]
fn disconnect_preserves_keys_and_buttons_held_by_another_connection() {
let (shared, events) = shared();
let mut first = connection(&shared);
let mut second = connection(&shared);
first.key(65, true).unwrap();
second.key(65, true).unwrap();
first.button(1, true).unwrap();
second.button(1, true).unwrap();
first.release_all().unwrap();
assert_eq!(
events.try_iter().collect::<Vec<_>>(),
[
"key 65 true",
"key 65 true",
"button 1 true",
"button 1 true"
]
);
second.release_all().unwrap();
assert_eq!(
events.try_iter().collect::<Vec<_>>(),
["key 65 false", "button 1 false"]
);
}
#[test]
fn disconnect_forgets_ownership_when_backend_release_fails() {
let (shared, events) = shared();
let mut client = connection(&shared);
client.key(65, true).unwrap();
client.button(1, true).unwrap();
drop(events);
assert!(client.release_all().is_err());
assert!(client.keys.is_empty());
assert!(client.buttons.is_empty());
let shared = shared.lock().unwrap();
assert!(shared.keys.is_empty());
assert!(shared.buttons.is_empty());
}
#[test]
fn repeated_press_is_released_once_and_unowned_release_is_ignored() {
let (shared, events) = shared();
let mut first = connection(&shared);
let mut second = connection(&shared);
first.key(65, true).unwrap();
first.key(65, true).unwrap();
second.key(65, false).unwrap();
first.release_all().unwrap();
assert_eq!(
events.try_iter().collect::<Vec<_>>(),
["key 65 true", "key 65 true", "key 65 false"]
);
assert!(shared.lock().unwrap().keys.is_empty());
}
}
+231 -9
View File
@@ -4,10 +4,11 @@
//! session ends.
use anyhow::{Context, Result};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
@@ -93,6 +94,68 @@ fn hook_source_dir() -> Result<PathBuf> {
.context("hook DLLs not found (run the build first)")
}
static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// Replace a managed prefix file without inheriting the source's permissions.
/// Nix store files are read-only; copying them directly leaves the prefix
/// read-only too, so the next run cannot overwrite them. A temporary file in
/// the destination directory keeps the replacement atomic and also repairs
/// read-only files left by earlier uur versions.
fn deploy_file(source: &Path, target: &Path) -> Result<()> {
let parent = target
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let filename = target
.file_name()
.context("deployment target has no file name")?
.to_string_lossy();
let mut temporary = None;
for _ in 0..32 {
let sequence = DEPLOY_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let path = parent.join(format!(
".{filename}.uur-{}-{sequence}.tmp",
std::process::id()
));
match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => {
temporary = Some((path, file));
break;
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(error).with_context(|| {
format!("creating temporary deployment for {}", target.display())
});
}
}
}
let Some((temporary_path, mut output)) = temporary else {
anyhow::bail!("could not create a temporary file for {}", target.display());
};
let copy_result = (|| -> Result<()> {
let mut input = File::open(source)
.with_context(|| format!("opening deployment source {}", source.display()))?;
std::io::copy(&mut input, &mut output)
.with_context(|| format!("copying deployment source {}", source.display()))?;
output.flush()?;
Ok(())
})();
drop(output);
if let Err(error) = copy_result {
let _ = std::fs::remove_file(&temporary_path);
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary_path, target) {
let _ = std::fs::remove_file(&temporary_path);
return Err(error).with_context(|| format!("deploying to {}", target.display()));
}
Ok(())
}
/// Install the native preload DLLs in the managed prefix, outside the
/// proprietary application directory. Wine's native override resolves them
/// from system32, so client updates never overwrite uur and uur never edits an
@@ -104,7 +167,7 @@ fn deploy_hooks(prefix: &Path) -> Result<()> {
for dll in ["wevtapi.dll", "uur-hook.dll", "wtsapi32.dll"] {
let from = source.join(dll);
let to = target.join(dll);
std::fs::copy(&from, &to)
deploy_file(&from, &to)
.with_context(|| format!("deploying {} to {}", dll, target.display()))?;
}
Ok(())
@@ -152,7 +215,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
std::fs::copy(&target, &backup)
.with_context(|| format!("backing up {}", target.display()))?;
}
std::fs::copy(&source, &target)
deploy_file(&source, &target)
.with_context(|| format!("deploying native terminal proxy to {}", target.display()))?;
std::fs::write(marker, b"managed by uur\n")?;
@@ -163,7 +226,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
std::fs::copy(&mux_target, &mux_backup)
.with_context(|| format!("backing up {}", mux_target.display()))?;
}
std::fs::copy(&mux_source, &mux_target)
deploy_file(&mux_source, &mux_target)
.with_context(|| format!("deploying native mux proxy to {}", mux_target.display()))?;
std::fs::write(mux_marker, b"managed by uur\n")?;
Ok(bin.join("uu-terminal-bridge.runtime"))
@@ -171,6 +234,22 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
/// The client UI needs the Evergreen WebView2 runtime; the official
/// bootstrapper ships inside the client's bin directory.
const WEBVIEW2_DLL_OVERRIDES: &str = "wtsapi32=b,wevtapi=b";
fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command {
let mut command = Command::new("wine");
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
// The bootstrapper is a 32-bit process. uur's native preload DLLs are
// 64-bit, so inherited global native-only overrides make its updater
// unable to load WTSAPI32.dll under WoW64.
.env("WINEDLLOVERRIDES", WEBVIEW2_DLL_OVERRIDES)
.arg(bootstrapper)
.args(["/silent", "/install"]);
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() {
@@ -183,11 +262,7 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
anyhow::bail!("{}", t!("session.webview_missing"));
}
println!("{}", t!("session.installing_webview"));
let status = Command::new("wine")
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.arg(bootstrapper.to_string_lossy().as_ref())
.args(["/silent", "/install"])
let status = webview2_install_command(prefix, &bootstrapper)
.status()
.context("running the WebView2 bootstrapper")?;
if !status.success() {
@@ -333,6 +408,12 @@ pub fn start() -> Result<()> {
let prefix = data_dir()?.join("wine");
let install_dir = crate::wine::find_client_dir(&prefix)
.context("client not provisioned; run `uur setup` first")?;
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
@@ -702,6 +783,37 @@ fn wait_for_runtime_file(path: &Path, stopping: &AtomicBool) -> Result<()> {
anyhow::bail!("native terminal bridge did not become ready")
}
fn xft_dpi() -> Option<u32> {
use x11rb::connection::Connection;
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt};
let (connection, screen) = x11rb::connect(None).ok()?;
let root = connection.setup().roots.get(screen)?.root;
let resource_manager = connection
.intern_atom(false, b"RESOURCE_MANAGER")
.ok()?
.reply()
.ok()?
.atom;
let resource_manager = connection
.get_property(false, root, resource_manager, AtomEnum::STRING, 0, 16_384)
.ok()?
.reply()
.ok()?;
parse_xft_dpi(&String::from_utf8_lossy(&resource_manager.value))
}
fn parse_xft_dpi(resources: &str) -> Option<u32> {
resources.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
if name.trim() != "Xft.dpi" {
return None;
}
let dpi = value.trim().parse::<f64>().ok()?;
(dpi.is_finite() && (96.0..=480.0).contains(&dpi)).then(|| dpi.round() as u32)
})
}
fn stop_wineserver(prefix: &Path) {
let _ = Command::new("wineserver")
.env("WINEPREFIX", prefix)
@@ -716,6 +828,116 @@ fn wine_debug() -> String {
#[cfg(test)]
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() {
let command = webview2_install_command(
Path::new("/tmp/uur-wine-prefix"),
Path::new("/tmp/MicrosoftEdgeWebview2Setup.exe"),
);
let overrides = command
.get_envs()
.find_map(|(name, value)| (name == OsStr::new("WINEDLLOVERRIDES")).then_some(value))
.flatten();
assert_eq!(overrides, Some(OsStr::new(WEBVIEW2_DLL_OVERRIDES)));
}
#[test]
fn tasklist_parser_matches_the_exact_image() {
+37 -4
View File
@@ -276,12 +276,13 @@ fn detect_runtime_provider() -> Option<PathBuf> {
.and_then(OsStr::to_str)
.unwrap_or_default();
let candidate = match executable {
"swaybg" => argument_after(&arguments, "-i"),
"xwallpaper" => arguments.last().cloned(),
"mpvpaper" => arguments.last().cloned(),
"swaybg" => argument_after(&arguments, "-i").map(PathBuf::from),
"xwallpaper" => arguments.last().map(PathBuf::from),
"mpvpaper" => arguments.last().map(PathBuf::from),
"wpaperd" => wpaperd_link(&entry.path()),
_ => None,
};
if let Some(path) = candidate.and_then(|value| resolve_candidate(PathBuf::from(value))) {
if let Some(path) = candidate.and_then(resolve_candidate) {
return Some(path);
}
}
@@ -303,6 +304,32 @@ fn argument_after(arguments: &[String], option: &str) -> Option<String> {
.map(|pair| pair[1].clone())
}
/// wpaperd >= 1.1.0 mirrors the current wallpaper of every output as a
/// symlink under `$XDG_STATE_HOME/wpaperd/wallpapers`, rewritten on each
/// change. Image paths are written verbatim, so absolute targets are used
/// as-is while relative ones resolve against wpaperd's working directory.
/// The newest resolvable link wins; leftovers from earlier runs are older.
fn wpaperd_link(proc: &Path) -> Option<PathBuf> {
let cwd = std::fs::read_link(proc.join("cwd")).ok()?;
std::fs::read_dir(state_home().join("wpaperd/wallpapers"))
.ok()?
.flatten()
.filter_map(|entry| {
let link = entry.path();
let target = std::fs::read_link(&link).ok()?;
let target = if target.is_absolute() {
target
} else {
cwd.join(target)
};
let path = resolve_candidate(target)?;
let modified = std::fs::symlink_metadata(&link).ok()?.modified().ok()?;
Some((modified, path))
})
.max_by_key(|(modified, _)| *modified)
.map(|(_, path)| path)
}
fn wallpaper_from_value(value: &str, provider: &'static str) -> Option<Wallpaper> {
let value = value.trim().trim_matches(['\'', '"']);
if value.is_empty() {
@@ -545,6 +572,12 @@ fn config_home() -> PathBuf {
.unwrap_or_else(|| home_dir().join(".config"))
}
fn state_home() -> PathBuf {
std::env::var_os("XDG_STATE_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".local/state"))
}
fn home_dir() -> PathBuf {
std::env::var_os("HOME")
.map(PathBuf::from)
+94 -5
View File
@@ -141,13 +141,15 @@ pub fn setup(accept_eula: bool) -> Result<()> {
/// - GameViewerServer.exe sees Windows 10 because current UU terminal builds
/// gate their ConPTY transport on the OS version. Native input and display
/// adapters handle the hardware capabilities separately;
/// - the UU client and service prefer their bundled msvcp140 runtime. Wine 10's
/// builtin implementation can stall UU 4.41 before the WebView starts;
/// - the service must auto-start;
/// - X11 focus/XIM tuning and CJK font substitution keep the controller
/// usable.
type RegistryEntry = (String, Vec<(&'static str, &'static str, &'static str)>);
pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
let entries: Vec<RegistryEntry> = vec![
fn registry_compat_entries() -> Vec<RegistryEntry> {
vec![
(
r#"Software\Wine\AppDefaults\msedgewebview2.exe"#.to_string(),
vec![("Version", "REG_SZ", "win8")],
@@ -156,6 +158,14 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
r#"Software\Wine\AppDefaults\GameViewerServer.exe"#.to_string(),
vec![("Version", "REG_SZ", "win10")],
),
(
r#"Software\Wine\AppDefaults\gameviewer.exe\DllOverrides"#.to_string(),
vec![("msvcp140", "REG_SZ", "native,builtin")],
),
(
r#"Software\Wine\AppDefaults\GameViewerServer.exe\DllOverrides"#.to_string(),
vec![("msvcp140", "REG_SZ", "native,builtin")],
),
(
r"System\CurrentControlSet\Services\GameViewerService".to_string(),
vec![("Start", "REG_DWORD", "2")],
@@ -175,15 +185,17 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
("MS Shell Dlg 2", "REG_SZ", "Noto Sans CJK SC"),
],
),
];
]
}
for (key, values) in &entries {
pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
for (key, values) in registry_compat_entries() {
let full = if key.starts_with("System") {
format!("HKLM\\{key}")
} else {
format!("HKCU\\{key}")
};
for (value, reg_type, data) in values {
for (value, reg_type, data) in &values {
let _ = Command::new("wine")
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
@@ -227,6 +239,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())
}
@@ -407,3 +452,47 @@ fn purge_wine_shortcuts() {
}
}
}
#[cfg(test)]
mod tests {
use super::log_pixels_command;
use super::registry_compat_entries;
use std::path::Path;
#[test]
fn bundled_cpp_runtime_is_preferred_for_both_uu_processes() {
let entries = registry_compat_entries();
for executable in ["gameviewer.exe", "GameViewerServer.exe"] {
let key = format!(r"Software\Wine\AppDefaults\{executable}\DllOverrides");
let values = entries
.iter()
.find_map(|(entry, values)| (entry == &key).then_some(values))
.unwrap_or_else(|| panic!("missing DLL overrides for {executable}"));
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",
]
);
}
}
+38
View File
@@ -0,0 +1,38 @@
#include <assert.h>
#include "../hook/cursor-overlay.h"
int main(void)
{
uur_cursor_rect source = {0, 0, 1920, 1080};
uur_cursor_rect destination = {0, 0, 1920, 1080};
uur_cursor_rect overlay;
uur_cursor_shape cursor = {100, 200, 64, 48, 16, 8};
/* A negative virtual-screen origin must not shift a primary-screen blit. */
assert(uur_map_cursor_overlay(&source, &destination, &cursor, &overlay));
assert(overlay.x == 84 && overlay.y == 192);
assert(overlay.width == 64 && overlay.height == 48);
source.x = -1920;
cursor.x = -1820;
assert(uur_map_cursor_overlay(&source, &destination, &cursor, &overlay));
assert(overlay.x == 84);
/* StretchBlt scales the cursor bitmap and hotspot together. */
destination.width = 960;
destination.height = 540;
assert(uur_map_cursor_overlay(&source, &destination, &cursor, &overlay));
assert(overlay.x == 42 && overlay.y == 96);
assert(overlay.width == 32 && overlay.height == 24);
/* A cursor overlapping the capture edge remains partially visible. */
cursor.x = -1925;
assert(uur_map_cursor_overlay(&source, &destination, &cursor, &overlay));
cursor.x = -2000;
assert(!uur_map_cursor_overlay(&source, &destination, &cursor, &overlay));
assert(uur_cursor_bitmap_height(48, 1) == 48);
assert(uur_cursor_bitmap_height(96, 0) == 48);
return 0;
}