mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 08:50:40 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25d8d0c915 | ||
|
|
1a3348dfe9 | ||
|
|
bff7ad320e | ||
|
|
17978500e4 | ||
|
|
cc2df0fbd2 | ||
|
|
2ab33b88f0 | ||
|
|
4e4062a4df | ||
|
|
73cc0a8cdd | ||
|
|
6957d63671 | ||
|
|
66c8bb3249 | ||
|
|
a18a69c19e | ||
|
|
050b8710a8 | ||
|
|
06946568b7 | ||
|
|
4c2cd143f4 | ||
|
|
2a295638d0 | ||
|
|
7e334bfe69 | ||
|
|
ef697de387 | ||
|
|
f3614f243a | ||
|
|
0543f14f0e | ||
|
|
c99a587afc |
No files matched your search
@@ -0,0 +1,57 @@
|
||||
name: 问题反馈 / Bug report
|
||||
description: 报告 bug 或使用问题 / Report a bug or problem
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
感谢反馈!请尽量填写完整,否则我们很难定位问题。/ Thanks! Please fill in everything you can.
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: 问题描述 / What happened
|
||||
description: 做了什么操作、期望什么结果、实际发生了什么;能稳定复现吗?/ Steps, expected vs actual, reproducible?
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: 版本 / Version
|
||||
description: Release 版本号(如 v0.1.1)或自己编译的提交号 / Release tag or commit
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: viewer
|
||||
attributes:
|
||||
label: 控制端 / Viewer
|
||||
options: [Mac, Windows, iPhone / iPad, Android, 其他 / Other]
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: diagnostics
|
||||
attributes:
|
||||
label: 诊断信息 / Diagnostics
|
||||
description: |
|
||||
先复现一次问题,然后在被控的 Linux 上运行下面的命令,把输出粘贴到这里(IP 会被自动抹掉,不包含密码、令牌或剪贴板内容)。
|
||||
Reproduce the problem, then run this on the Linux host and paste the output (IPs are masked; no passwords, tokens or clipboard data).
|
||||
|
||||
```sh
|
||||
{
|
||||
echo "== 系统"; grep PRETTY_NAME /etc/os-release; uname -rm
|
||||
echo "== 桌面"; echo "session=$XDG_SESSION_TYPE desktop=$XDG_CURRENT_DESKTOP"
|
||||
echo "== 显示器"; xrandr --listmonitors 2>/dev/null
|
||||
echo "== 缩放"; gsettings get org.gnome.desktop.interface scaling-factor 2>/dev/null; gsettings get org.gnome.mutter experimental-features 2>/dev/null
|
||||
echo "== 显卡"; lspci 2>/dev/null | grep -iE 'vga|3d'
|
||||
echo "== FFmpeg"; ffmpeg -hide_banner -encoders 2>/dev/null | grep -E 'h264_nvenc|libx264'
|
||||
echo "== 日志"; journalctl --user -u uuremote-native.service --since "-30min" --no-pager -o cat \
|
||||
| grep -E 'Starting|backend|Selected capture|Desktop encoder|Capture setting request|Desktop video settings|Offer for connection|WARN|ERROR' | tail -n 80
|
||||
} 2>&1 | sed -E 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/x.x.x.x/g'
|
||||
```
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: extra
|
||||
attributes:
|
||||
label: 截图或补充说明 / Screenshots, notes
|
||||
description: 显示缩放比例(如 125%)、多显示器、是否用 NVIDIA 显卡等 / Display scaling, multiple monitors, GPU, ...
|
||||
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: true
|
||||
@@ -18,3 +18,17 @@ jobs:
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo test --locked
|
||||
|
||||
test-wayland:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install build dependencies (X11 + Wayland + portal)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential pkg-config \
|
||||
libx11-dev libxext-dev libxtst-dev libxfixes-dev libgtk-3-dev \
|
||||
libwayland-dev libxkbcommon-dev libglib2.0-dev libpipewire-0.3-dev
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo test --locked --features wayland,portal
|
||||
@@ -0,0 +1,211 @@
|
||||
# AGENTS.md — guide for AI coding agents
|
||||
|
||||
This file is written for large language model agents (Claude Code, Codex, Cursor, ...) that are asked to
|
||||
**build, install, debug or develop** uu-remote-linux. Read it fully before acting. Human documentation is in
|
||||
[README.md](README.md) (Chinese) and [README.en.md](README.en.md).
|
||||
|
||||
## 1. What this project is
|
||||
|
||||
- An **unofficial Linux host** for NetEase UU Remote (网易 UU 远程). The official Mac / Windows / mobile
|
||||
clients connect to it and control the Linux desktop. There is no viewer/controller side here.
|
||||
- One Rust binary, `uuremote-server` (Cargo package `uu-remote-linux`), plus small C engines in `c_engine/`
|
||||
compiled by `build.rs`. No Wine, no NetEase binaries.
|
||||
- The host registers with the UU cloud as a **Windows PC** (`x-param-plat=1`) so the official clients accept it.
|
||||
- License GPL-3.0. Not affiliated with NetEase.
|
||||
|
||||
## 2. Ground rules (must follow)
|
||||
|
||||
1. **Privacy in logs.** Never log keystrokes, terminal text, clipboard contents, file contents, passwords,
|
||||
tokens, QR login URLs or TURN credentials. Log sizes, counts, field numbers and booleans only. Existing code
|
||||
follows this; keep it that way in every new log line.
|
||||
2. **The QR login URL is a credential.** Show the QR only to the human who owns the account. Never paste the
|
||||
URL or a QR screenshot into chats, issues, logs or commits.
|
||||
3. **Follow the official host behavior.** Protocol behavior is copied from the official hosts (Mac
|
||||
`UURemoteServer`, Windows `GameViewerServer.exe`). Do not invent message shapes; when unsure, log the field
|
||||
numbers of what the viewer sends and derive behavior from evidence.
|
||||
4. **No NetEase assets.** Do not add NetEase logos, icons, screenshots of their apps or copies of their binaries.
|
||||
5. **No personal data in source.** Nothing machine- or account-specific is compiled in; credentials come from
|
||||
the config file / environment. The only built-in default is the public client signing key in `src/auth.rs`.
|
||||
6. **Don't break other tools.** The desktop, file-transfer, terminal and port-mapping tools each open their own
|
||||
peer connection; a new offer must never close other peers.
|
||||
7. Keep changes small and tested; match the surrounding code style (dense, comment only the non-obvious).
|
||||
|
||||
## 3. Build and test
|
||||
|
||||
Dependencies (Ubuntu/Debian):
|
||||
|
||||
```sh
|
||||
sudo apt install build-essential pkg-config \
|
||||
libx11-dev libxext-dev libxtst-dev libxfixes-dev libgtk-3-dev ffmpeg
|
||||
# --features wayland: libwayland-dev libxkbcommon-dev wl-clipboard
|
||||
# --features wayland,portal: + libglib2.0-dev libpipewire-0.3-dev
|
||||
```
|
||||
|
||||
Rust stable via rustup. Commands:
|
||||
|
||||
```sh
|
||||
cargo test # unit tests (macOS builds use C stubs, also fine for development)
|
||||
cargo build --release # X11 host
|
||||
cargo build --release --features wayland # + Hyprland/wlroots
|
||||
cargo build --release --features wayland,portal # + GNOME/KDE Wayland via xdg-desktop-portal
|
||||
```
|
||||
|
||||
- `build.rs` links X11/Xext/Xtst/Xfixes and `dl` (PAM is loaded at runtime with `dlopen`), and builds the GTK3
|
||||
login window only when `pkg-config gtk+-3.0` succeeds (`UU_NO_GTK=1` forces it off).
|
||||
- The portal feature panics in `build.rs` if GIO/PipeWire development packages are missing.
|
||||
- `vendor/webrtc-dtls` is a patched copy of the upstream crate (MIT/Apache); keep it as a path dependency.
|
||||
- CI (`.github/workflows/ci.yml`) runs `cargo test --locked` on ubuntu-22.04. Pushing a `v*` tag runs
|
||||
`.github/workflows/release.yml`, which builds and publishes the x86_64 tarball; release notes come from
|
||||
`docs/release-notes/<tag>.md`.
|
||||
|
||||
## 4. Install on a user's machine (step by step)
|
||||
|
||||
1. Check the session: `echo $XDG_SESSION_TYPE $XDG_CURRENT_DESKTOP $DISPLAY $WAYLAND_DISPLAY`.
|
||||
X11 → default build. Hyprland → `--features wayland`. GNOME/KDE on Wayland → `--features wayland,portal`
|
||||
(or advise the user to pick the "on Xorg" session at the login screen, which is the best-supported path).
|
||||
2. Install dependencies and build (section 3). Copy the binary: `install -Dm755 target/release/uuremote-server ~/.local/bin/uuremote-server`.
|
||||
3. **Login (needs the human).** Run `uuremote-server login` inside the graphical session. A GTK window shows a QR
|
||||
code; the user scans it with the UU Remote mobile app and confirms. Without a display use
|
||||
`uuremote-server login --no-gui` (terminal QR). Credentials are written to `~/.config/uuremote/config.json`
|
||||
(mode 0600). Do not read the token out of that file or print it.
|
||||
4. Create a systemd user unit (`~/.config/systemd/user/uuremote-native.service`):
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=UU Remote Linux host (unofficial)
|
||||
After=graphical-session.target
|
||||
[Service]
|
||||
Environment=RUST_LOG=info
|
||||
Environment=DISPLAY=:0
|
||||
# GNOME on Xorg usually needs: Environment=XAUTHORITY=/run/user/<uid>/gdm/Xauthority
|
||||
ExecStart=%h/.local/bin/uuremote-server
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
```
|
||||
|
||||
Find the real display/Xauthority with `loginctl show-session <id> -p Display` / `ps -o args -C Xorg`.
|
||||
5. `systemctl --user daemon-reload && systemctl --user enable --now uuremote-native.service`
|
||||
6. Verify: `journalctl --user -u uuremote-native.service -f` must show
|
||||
`Device status synchronized: ... availability=Some("ready")`. If credentials are missing or expired the
|
||||
service opens the QR window on the desktop by itself (disable with `UU_LOGIN_WINDOW=0`).
|
||||
7. Ask the user to connect from the official client and check desktop, input, sound, file transfer, terminal.
|
||||
|
||||
Updating an installed binary: copy to a temp name and `mv -f` over the old one (a running binary cannot be
|
||||
overwritten in place: "text file busy"), then restart the service. Restarting kills open viewer windows; the
|
||||
viewer does not reconnect them automatically.
|
||||
|
||||
## 5. Runtime configuration
|
||||
|
||||
| Item | Meaning |
|
||||
|---|---|
|
||||
| `~/.config/uuremote/config.json` | user_id, device_id, client_id, system_id, machine_guid, token, csrf; optional `sign_key`, `ffmpeg_root`. `$UU_CONFIG` overrides the path |
|
||||
| `~/.config/uuremote/host_settings.json` | persisted 安全 settings: auto_lock, keep_mute, mute_permanent |
|
||||
| `UU_DESKTOP_BACKEND` | `auto` (default) / `x11` / `wayland` / `portal` |
|
||||
| `UU_VIDEO_ENCODER=cpu` | force libx264 instead of NVENC |
|
||||
| `UU_FFMPEG_ROOT` | FFmpeg prefix (`bin/ffmpeg`, libs in `lib/x86_64-linux-gnu`) |
|
||||
| `UU_AUDIO=0`, `UU_AUDIO_SOURCE` | disable sound / choose the Pulse source (default `@DEFAULT_MONITOR@`) |
|
||||
| `UU_LOGIN_WINDOW=0` | don't auto-open the login window |
|
||||
|
||||
Token has no expiry field; API code 1120 (HTTP 422) means invalid/expired → re-login. The config is re-read
|
||||
every 60 s.
|
||||
|
||||
## 6. Code map
|
||||
|
||||
| Path | Role |
|
||||
|---|---|
|
||||
| `src/main.rs` | entry, subcommands, room loop (one peer per `ice_id`), room renewal (deferred while connected) |
|
||||
| `src/signaling.rs` | Engine.IO v4 / Socket.IO client; `be-controlled` binary attachment = ConnectOptions (field 1 capture_type) |
|
||||
| `src/auth.rs`, `src/config.rs`, `src/login.rs`, `src/login_ui.rs` | signed REST client, config, device init + QR login, GTK window |
|
||||
| `src/webrtc.rs` | peer connection, data channels, CONTROL dispatch, initialization messages |
|
||||
| `src/video.rs`, `src/capture_setting.rs` | FFmpeg H.264 pipeline; viewer quality/fps/resolution settings |
|
||||
| `src/audio.rs` | Pulse/PipeWire monitor → Opus audio track |
|
||||
| `src/input.rs`, `src/input_mapping.rs` | input injection (X11 XTest / Wayland / portal), Windows VK → keysym |
|
||||
| `src/cursor.rs` | pointer shape mirroring (X11) |
|
||||
| `src/clipboard*.rs` | text clipboard bridge and protocol |
|
||||
| `src/file_trans.rs` | FileTransferFtp RPC |
|
||||
| `src/terminal.rs` | TERM frames + PTY sessions |
|
||||
| `src/session_lock.rs`, `c_engine/pam_check.c` | lock state reporting, auto unlock via PAM + logind |
|
||||
| `src/system_actions.rs`, `src/system_metrics.rs` | SimpleAction system commands, mute, auto-lock, SystemMetrics |
|
||||
| `src/initialization.rs`, `src/control_protocol.rs`, `src/protocol.rs` | protobuf encoders/decoders for CONTROL |
|
||||
| `src/session_ice.rs`, `src/network_diagnostics.rs` | cloud ICE servers, address-free path diagnostics |
|
||||
| `src/desktop_backend.rs`, `src/wayland.rs`, `src/portal*.rs` | backend selection, Hyprland, GNOME/KDE portal |
|
||||
| `c_engine/x11_engine.c`, `c_engine/clipboard.c` | X11 capture/input/selection |
|
||||
| `c_engine/wayland_engine.c`, `c_engine/portal_engine.c` | Wayland and portal engines |
|
||||
| `c_engine/login_window.c` | GTK3 login window |
|
||||
|
||||
Diagnostic subcommands: `login [--no-gui]`, `unlock-check` (password on stdin, prints only accepted/rejected),
|
||||
`desktop-probe [new.png]`, `desktop-video-probe`, `wayland-input-probe`, `clipboard-acceptance`,
|
||||
`portal-acceptance`, `help`. Unknown arguments exit with code 2. Builds up to v0.1.0 did **not** reject them and
|
||||
started a second full host server instead, so check that a subcommand exists in the binary you run.
|
||||
|
||||
## 7. Protocol facts (verified against the official clients)
|
||||
|
||||
- Connection types (ConnectOptions.capture_type): 1 desktop, 5 file transfer, 8 terminal, 9 port mapping.
|
||||
Video is sent only for desktop connections (capture_type ≤ 2).
|
||||
- CONTROL messages are protobuf `Message {1 seq, 2 timestamp, <which> payload}`; input arrives as JSON
|
||||
(`kbd_press`, `mouse_move_absolute` with normalized 0..1 floats, ...).
|
||||
- Echo: the viewer sends SimpleAction action 0 with its FeatureFlag; the host answers action 1 with args
|
||||
`{"seq":<request seq>}` and **its own** FeatureFlag. The viewer only uses features the host declares:
|
||||
`1 ff_capture_setting=4`, `2 ff_simple_action=2`, `3 ff_system_metrics=2`, `6 ff_file_transfer_ftp=2`,
|
||||
`8 ff_clipboard=3` (when the clipboard bridge is ready). Do not declare versions you don't implement.
|
||||
- RPC = Message 21 `RpcRequest {1 header{1 request_id}, <case>}`, answered with Message 22
|
||||
`RpcResponse {1 header (same id), <case>}`. Cases used: 2 capture_setting, 3 fps, 4 video_quality,
|
||||
6 resolution, 8 file transfer, 9 clipboard, 15 send_video_track, 16–20 plugins, 21 virtual audio policy,
|
||||
28/29 terminal.
|
||||
- CaptureSettingRequest: field 1 is an **fps option index** (1=30, 2=60, 3=90); the real frame rate is
|
||||
field 18 `fpsCount`. Field 2 quality: 1 Fast, 2 General (高清 2M), 3 HD (超清 8M), 4 Bluray (原画 20M),
|
||||
5 Auto, 6 Custom. Resolution: 16/17 pixel size or 5/6, 10 resolution_type (3 = follow remote).
|
||||
Reply `RpcResponse{2 CaptureSettingResponse{}}` (no errors = applied) and send Message 25 CaptureSettingSync.
|
||||
- SystemMetrics (Message 13): GeneralMetric `2 system_sound_support` is an enum, **2 = supported** (1 = not
|
||||
supported); SettingMetric 1 keep_mute, 2 mute_permanent, 3 auto_lock, 5 file_transfer_save_location,
|
||||
8/9/10 permission states (2 = allow).
|
||||
- Security menu: 静音运行 on → SimpleAction 14 + 18, off → 16. 远程结束后自动锁屏 → SimpleAction 19 with
|
||||
`value` (field 5) **2 = on, 1 = off**. The viewer sends these only when toggled, so the host persists them.
|
||||
- Auto unlock: host reports `SystemStateChange{1 SecureDesktopState{1 is_locked, 5 is_support_auto_logon}}`;
|
||||
the viewer (after the user enables 自动解锁被控端) sends SimpleAction 15 with args `{"key": password}`;
|
||||
failure → Message 12 `ReportError{2: -5}`.
|
||||
- File transfer: the viewer sends RPCs on CONTROL but receives only on FILE_DATA_CHANNEL, so all replies go
|
||||
out on FILE. With `ff_file_transfer_ftp=2` directory listings are zlib-compressed protobuf. `remove_dir` is
|
||||
sent for every delete and must be answered with response case **6 `result{id, file_error}`**, not
|
||||
`operation_result`. Host root is shown as ":/" (此电脑); home is "~/".
|
||||
- Terminal: BINARY channel, RPC 28 check_env → 24; frames `"TERM"`, version 1, type (enum+1), 2 flag bytes,
|
||||
session u32 LE, length u32 LE, payload; JSON `{cols,rows,shell,option}`.
|
||||
- Cursor shape = Message 15 SystemStateChange field 2. Audio: the viewer always offers an Opus m-line.
|
||||
- Login API: `/api/v1/device/windows/init` → device_id; `/qrcode/gen/login`; long-poll
|
||||
`/qrcode/login/status` (1 wait, 2 scanned, 4 confirmed); `/login/by_qrcode` → user token. QR expires after
|
||||
~5 min with HTTP 400 code 1190 (not fatal: generate a new one).
|
||||
|
||||
## 8. Known pitfalls
|
||||
|
||||
- webrtc-rs `Sample.duration` sets the gap to the **next** frame. FFmpeg 6.1 rejects `-r` together with
|
||||
`-fps_mode vfr`.
|
||||
- All-intra 60 fps saturates Wi-Fi; keep GOP ≈ 0.5 s. A bitrate cap alone does not change quality on a static
|
||||
desktop, so presets also change the CQ level.
|
||||
- X11 capture on a GPU saturated by CUDA work starves; prefer the iGPU for the desktop when available.
|
||||
- Remote keys repeat at high RTT because key-up arrives after the X autorepeat delay. XTEST repeats through the
|
||||
master keyboard; the engine disables global autorepeat only while a remote key is held.
|
||||
- Interactive shells ignore SIGTERM: the server HUPs/KILLs PTY sessions on shutdown.
|
||||
- GTK windows stop repainting while GNOME is locked or the monitor is off; test UI on Xvfb or after unlock.
|
||||
- logind `unlock-session` by the session owner clears the GNOME shield in ~3 s.
|
||||
- GNOME closes the portal session on lock; capture/input must share one portal session and be rebuilt after
|
||||
unlock. Portal input/clipboard permissions are persisted per desktop (0600 file); a revoked permission asks again.
|
||||
|
||||
## 9. Debugging checklist
|
||||
|
||||
- Connection: `Offer for connection: capture_type=`, `PeerConnection State changed`, `ICE path: ... route=`.
|
||||
- Video: `Desktop encoder: ... fps= cq= maxrate=`, `Desktop latest-frame stats`, `Video feedback totals`.
|
||||
- Viewer requests: `CONTROL message: fields=[..] simple_action=..` (numbers only), `Capture setting request`,
|
||||
`SimpleAction N (...) received`.
|
||||
- Features: `File transfer ...`, `Terminal frame`, `Native desktop clipboard text received: bytes=`,
|
||||
`Desktop audio started`, `Auto unlock result`, `Auto lock after remote session`.
|
||||
- When the viewer "does nothing" after a menu click, first check whether any message arrived; usually the
|
||||
host did not declare the matching FeatureFlag/SystemMetrics capability.
|
||||
|
||||
## 10. Contributing
|
||||
|
||||
- Run `cargo test` (and the feature builds you touched) before committing; keep commits focused.
|
||||
- New protocol behavior: cite the evidence (observed field numbers, official log strings) in a comment.
|
||||
- Update README.md / README.en.md when user-visible features or limitations change, and add
|
||||
`docs/release-notes/<tag>.md` before tagging a release.
|
||||
Generated
+1
-1
@@ -2487,7 +2487,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uu-remote-linux"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "uu-remote-linux"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
edition = "2021"
|
||||
authors = ["uu-remote-linux contributors"]
|
||||
description = "Unofficial Linux host for NetEase UU Remote: control a Linux desktop from the official clients"
|
||||
|
||||
@@ -165,6 +165,12 @@ Common environment variables:
|
||||
Host settings such as "lock after remote session" and "mute host" are stored in
|
||||
`~/.config/uuremote/host_settings.json`.
|
||||
|
||||
## Let an AI agent install or develop it
|
||||
|
||||
If you use Claude Code, Codex, Cursor or a similar coding agent, have it read [AGENTS.md](AGENTS.md) first.
|
||||
It is written for language models: build and install steps, a code map, protocol notes and development rules,
|
||||
enough to take over installation or development.
|
||||
|
||||
## How it works
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -157,6 +157,11 @@ journalctl --user -u uuremote-native.service -f # 看到 availability=Some("re
|
||||
|
||||
「远程结束后自动锁屏」「静音运行」等设置保存在 `~/.config/uuremote/host_settings.json`。
|
||||
|
||||
## 让 AI 帮你安装或开发
|
||||
|
||||
如果你用 Claude Code、Codex、Cursor 等 AI 编程工具,让它先阅读 [AGENTS.md](AGENTS.md)。
|
||||
这份文档写给大模型看,里面有编译安装步骤、代码地图、协议要点和开发规范,读完就能接手编译安装或继续开发。
|
||||
|
||||
## 工作原理
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -94,6 +94,7 @@ static void selection_transfer(GDBusConnection *bus,const gchar *sender,const gc
|
||||
g_variant_new("(oub)",p->session,serial,success),NULL,G_DBUS_CALL_FLAGS_NONE,2000,NULL,NULL);
|
||||
if (reply) g_variant_unref(reply);
|
||||
}
|
||||
int uu_portal_clipboard_supported(struct uu_portal *p) { return p && p->clipboard_enabled; }
|
||||
int uu_portal_clipboard_ready(struct uu_portal *p) { return p && p->clipboard_enabled && uu_portal_alive(p); }
|
||||
int uu_portal_clipboard_set(struct uu_portal *p,const uint8_t *text,size_t length) {
|
||||
if (!uu_portal_clipboard_ready(p) || length>CLIP_LIMIT || !g_utf8_validate((const char *)text,(gssize)length,NULL)) return -1;
|
||||
|
||||
@@ -46,6 +46,7 @@ struct uu_portal {
|
||||
int error;
|
||||
uint32_t node, width, height;
|
||||
int logical_width, logical_height;
|
||||
int absolute_stream_pixels;
|
||||
enum spa_video_format format;
|
||||
uint8_t *frame;
|
||||
size_t frame_length;
|
||||
@@ -271,6 +272,13 @@ struct uu_portal *uu_portal_open_persist(const char *restore, void (*save_token)
|
||||
*error = 0; *width = *height = 0;
|
||||
struct uu_portal *p = calloc(1, sizeof(*p));
|
||||
if (!p) { *error = 8; return NULL; }
|
||||
/* GNOME forwards NotifyPointerMotionAbsolute into Mutter's stream-to-stage
|
||||
* transform. It expects stream pixels, unlike the compositor-sized KDE path.
|
||||
* Do not apply the compositor scale twice on fractional-scale displays. */
|
||||
gchar **desktops = g_strsplit(g_getenv("XDG_CURRENT_DESKTOP") ? g_getenv("XDG_CURRENT_DESKTOP") : "", ":", -1);
|
||||
for (gchar **desktop = desktops; *desktop; desktop++)
|
||||
if (!g_ascii_strcasecmp(*desktop, "GNOME")) p->absolute_stream_pixels = 1;
|
||||
g_strfreev(desktops);
|
||||
pthread_mutex_init(&p->lock, NULL); pthread_cond_init(&p->changed, NULL);
|
||||
p->context = g_main_context_new(); g_main_context_push_thread_default(p->context);
|
||||
p->bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
|
||||
@@ -359,6 +367,9 @@ struct uu_portal *uu_portal_open_persist(const char *restore, void (*save_token)
|
||||
p->dbus_started = 1;
|
||||
*error = connect_pipewire(p);
|
||||
if (*error) { uu_portal_close(p); return NULL; }
|
||||
fprintf(stderr, "Portal pointer geometry: frame=%ux%u compositor=%dx%d absolute=%s\n",
|
||||
p->width, p->height, p->logical_width, p->logical_height,
|
||||
p->absolute_stream_pixels ? "stream-pixels" : "compositor-logical");
|
||||
*width = p->width; *height = p->height;
|
||||
return p;
|
||||
done:
|
||||
@@ -447,7 +458,8 @@ int uu_portal_move(struct uu_portal *p, double x, double y, int relative) {
|
||||
x * p->logical_width / p->width, y * p->logical_height / p->height));
|
||||
if (x < 0 || y < 0 || x >= p->width || y >= p->height) return 11;
|
||||
return notify(p, "NotifyPointerMotionAbsolute", g_variant_new("(o@a{sv}udd)", p->session, empty_options(), p->node,
|
||||
x * p->logical_width / p->width, y * p->logical_height / p->height));
|
||||
p->absolute_stream_pixels ? x : x * p->logical_width / p->width,
|
||||
p->absolute_stream_pixels ? y : y * p->logical_height / p->height));
|
||||
}
|
||||
int uu_portal_button(struct uu_portal *p, int button, int pressed) {
|
||||
if (!p) return 11;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
修复版本。/ Bug-fix release.
|
||||
|
||||
### 修复 / Fixed
|
||||
- 传入无法识别的参数(例如手误或 `--version`)时,程序不再在已运行的服务旁边再启动一个完整的被控端,
|
||||
而是打印用法并以退出码 2 结束;`help` / `-h` / `--help` 显示用法。
|
||||
An unrecognized argument (a typo, `--version`, ...) no longer starts a second full host next to the running
|
||||
service; it prints usage and exits with code 2. `help` / `-h` / `--help` print usage.
|
||||
|
||||
### 文档 / Docs
|
||||
- 新增 [AGENTS.md](https://github.com/VallierDev/uu-remote-linux/blob/v0.1.1/AGENTS.md):写给 Claude Code、Codex、Cursor 等 AI 编程工具的指南,
|
||||
包含编译安装步骤、代码地图、协议要点和开发规范。
|
||||
New AGENTS.md: a guide for AI coding agents with build/install steps, a code map, protocol notes and rules.
|
||||
|
||||
### 下载 / Download
|
||||
`uu-remote-linux-v0.1.1-x86_64-linux.tar.gz`:X11 版可执行文件(x86_64,glibc ≥ 2.35,例如 Ubuntu 22.04+)。
|
||||
Wayland 支持仍为实验性,需要从源码编译。安装步骤见 README。
|
||||
|
||||
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||
@@ -0,0 +1,22 @@
|
||||
Wayland(GNOME / KDE portal)修复版本。X11 行为不变。
|
||||
Wayland (GNOME / KDE portal) fix release. X11 behavior is unchanged.
|
||||
|
||||
### 修复 / Fixed
|
||||
- **GNOME 开启分数缩放(如 125%、150%)时,鼠标点击偏到左上方**:portal 的绝对坐标被缩放了两次。现在 GNOME 直接使用画面坐标,
|
||||
KDE 保持原有逻辑;虚拟机内按钮级点击误差 ≤ 2 像素。
|
||||
GNOME with fractional scaling: absolute pointer positions were scaled twice, so clicks landed up-left of the target.
|
||||
- **锁屏后重连时剪贴板失效**(portal):剪贴板现在会等待 portal 会话恢复,并在锁屏状态的握手中保留已授权的剪贴板能力。
|
||||
Clipboard no longer gets disabled when a connection starts while GNOME is locked (portal).
|
||||
- portal 键鼠注入失败时输出带数量上限的诊断日志(不记录按键内容)。/ Bounded diagnostics for portal input failures.
|
||||
- 日志中记录房间令牌的剩余有效时间(只记录秒数)。/ Log the room token's remaining lifetime (seconds only).
|
||||
|
||||
### 已知问题 / Known issues
|
||||
- Wayland(portal)下剪贴板目前只有「控制端 → Linux」方向可用,「Linux → 控制端」方向尚未通过验收。
|
||||
On the portal backend, clipboard works viewer → Linux only; Linux → viewer is not working yet.
|
||||
- 长时间连接(约 20 分钟)可能被云端释放,原因仍在排查。/ Long sessions may be released by the cloud after ~20 min; under investigation.
|
||||
- Wayland 支持仍为实验性,需从源码以 `--features wayland,portal` 编译。/ Wayland remains experimental (build from source).
|
||||
|
||||
### 下载 / Download
|
||||
`uu-remote-linux-v0.1.2-x86_64-linux.tar.gz`:X11 版可执行文件(x86_64,glibc ≥ 2.35)。
|
||||
|
||||
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||
@@ -0,0 +1,21 @@
|
||||
Wayland(GNOME / KDE portal)修复版本。X11 行为不变。
|
||||
Wayland (GNOME / KDE portal) fix release. X11 behavior is unchanged.
|
||||
|
||||
### 修复 / Fixed
|
||||
- **GNOME Wayland 首次连接黑屏,桌面重绘后才恢复**(#2):新建的 portal 会话会把第一帧有效画面当作锁屏残留清掉,
|
||||
静止的桌面又不会产生新帧,所以画面一直是黑的。现在只有真正检测到锁屏(或 portal 被关闭)时才丢弃旧画面。
|
||||
First connection on GNOME Wayland stayed black until the desktop redrew (#2): a fresh portal session discarded its
|
||||
first valid frame as if it came from the lock screen.
|
||||
|
||||
### 其他 / Other
|
||||
- CI 新增 `--features wayland,portal` 的编译和测试。/ CI now builds and tests `--features wayland,portal`.
|
||||
|
||||
### 已知问题 / Known issues
|
||||
- Wayland(portal)下 Mac 控制端输入的下划线可能丢失(#3,正在排查,与键盘布局有关)。
|
||||
- Wayland 下剪贴板只有「控制端 → Linux」方向可用;长连接约 20 分钟可能被云端释放(排查中)。
|
||||
- Wayland 支持仍为实验性,需从源码以 `--features wayland,portal` 编译。
|
||||
|
||||
### 下载 / Download
|
||||
`uu-remote-linux-v0.1.3-x86_64-linux.tar.gz`:X11 版可执行文件(x86_64,glibc ≥ 2.35)。
|
||||
|
||||
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||
+29
-1
@@ -196,10 +196,38 @@ impl UUAuthClient {
|
||||
if code == TOKEN_INVALID { return Err(RoomError::LoginExpired); }
|
||||
if status == 200 && code == 0 {
|
||||
if let Some(data) = body.get("data") {
|
||||
return serde_json::from_value(data.clone()).map_err(|e| RoomError::Other(format!("room data decode failed: {e}")));
|
||||
let room: RoomData = serde_json::from_value(data.clone()).map_err(|e| RoomError::Other(format!("room data decode failed: {e}")))?;
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
log::info!("Room token lifetime: remaining_s={:?}", room_token_lifetime(&room.token, now));
|
||||
return Ok(room);
|
||||
}
|
||||
}
|
||||
Err(RoomError::Other(format!("create_room error http {status} code {code}: {}",
|
||||
body.get("msg").and_then(|m| m.as_str()).unwrap_or(""))))
|
||||
}
|
||||
}
|
||||
|
||||
// Report only the remaining lifetime; never return or log token/claim contents.
|
||||
fn room_token_lifetime(token: &str, now: u64) -> Option<i64> {
|
||||
use base64::Engine as _;
|
||||
let payload = token.split('.').nth(1)?;
|
||||
if payload.len() > 16384 { return None; }
|
||||
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload)
|
||||
.or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(payload)).ok()?;
|
||||
let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
|
||||
let remaining = claims.get("exp")?.as_i64()?.saturating_sub(i64::try_from(now).ok()?);
|
||||
(remaining.unsigned_abs() <= 7 * 24 * 3600).then_some(remaining)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod room_lifetime_tests {
|
||||
use super::room_token_lifetime;
|
||||
use base64::Engine as _;
|
||||
#[test]
|
||||
fn exposes_only_remaining_seconds_and_handles_opaque_tokens() {
|
||||
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"exp":2200,"ignored":"test-only"}"#);
|
||||
assert_eq!(room_token_lifetime(&format!("h.{payload}.s"),1000),Some(1200));
|
||||
assert_eq!(room_token_lifetime("opaque",1000),None);
|
||||
assert_eq!(room_token_lifetime("h.invalid.s",1000),None);
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,15 @@ pub fn start_portal(session: std::sync::Arc<crate::portal::PortalSession>) -> Cl
|
||||
let (output,outgoing)=watch::channel(None);
|
||||
let (ready_tx,ready)=tokio::sync::oneshot::channel();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
// GNOME closes the native portal while locked. A desktop connection
|
||||
// starts its TEXT channel before CONTROL auto-unlock/capture recovery.
|
||||
// Wait for that same Arc to recover instead of permanently disabling
|
||||
// clipboard on an already authorized but temporarily closed session.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
while !session.is_alive() && std::time::Instant::now() < deadline {
|
||||
if output.is_closed() || input.has_changed().is_err() { return; }
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
let available=session.clipboard_ready(); let _=ready_tx.send(available);
|
||||
if !available { return; }
|
||||
let mut last=None; let mut pending=None;
|
||||
|
||||
+10
-3
@@ -33,11 +33,11 @@ struct PendingPointer {
|
||||
unsafe fn x11_pointer_state(_: *mut libc::c_int,_:*mut libc::c_int,_:*mut libc::c_uint)->libc::c_int {-1}
|
||||
#[derive(Default)]
|
||||
struct HeldInput { buttons: std::collections::BTreeSet<i32>, keys: std::collections::BTreeSet<u64> }
|
||||
pub struct InputInjector { portal_failures: std::sync::atomic::AtomicUsize, portal_outcomes: std::sync::atomic::AtomicUsize, portal:std::sync::Mutex<Option<std::sync::Arc<crate::portal::PortalSession>>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex<PendingPointer>, held: std::sync::Mutex<HeldInput> }
|
||||
pub struct InputInjector { portal_failures: std::sync::atomic::AtomicUsize, portal_outcomes: [std::sync::atomic::AtomicUsize; 3], portal:std::sync::Mutex<Option<std::sync::Arc<crate::portal::PortalSession>>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex<PendingPointer>, held: std::sync::Mutex<HeldInput> }
|
||||
|
||||
impl InputInjector {
|
||||
pub fn new() -> Self {
|
||||
Self { portal_failures: std::sync::atomic::AtomicUsize::new(0), portal_outcomes: std::sync::atomic::AtomicUsize::new(0), portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) }
|
||||
Self { portal_failures: std::sync::atomic::AtomicUsize::new(0), portal_outcomes: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)), portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) }
|
||||
}
|
||||
|
||||
pub fn bind_portal(&self,session:Option<std::sync::Arc<crate::portal::PortalSession>>) {
|
||||
@@ -95,6 +95,12 @@ impl InputInjector {
|
||||
}
|
||||
pub fn wire_mouse_button(&self, button: i32, is_press: bool) {
|
||||
if let Some(mapped) = crate::input_mapping::mouse_button_to_x11(button) { self.mouse_button(mapped,is_press); }
|
||||
else {
|
||||
static UNKNOWN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
if UNKNOWN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
|
||||
log::warn!("Unsupported desktop wire mouse button: {}", button);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn mouse_button(&self, button: i32, is_press: bool) {
|
||||
self.flush_pointer();
|
||||
@@ -136,7 +142,8 @@ impl InputInjector {
|
||||
// and D-Bus errors. Never include keys, coordinates, text or portal tokens.
|
||||
fn portal_result(&self, operation: &str, result: Result<(), String>) -> i32 {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
if self.portal_outcomes.fetch_add(1, Relaxed) < 16 {
|
||||
let slot = match operation { "motion" => 0, "button" => 1, _ => 2 };
|
||||
if self.portal_outcomes[slot].fetch_add(1, Relaxed) < 16 {
|
||||
log::info!("Portal input outcome: operation={} success={}", operation, result.is_ok());
|
||||
}
|
||||
match result {
|
||||
|
||||
+39
-1
@@ -49,6 +49,15 @@ use webrtc::WebRtcSession;
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
// An unknown argument must never fall through to starting a second full host server.
|
||||
const SUBCOMMANDS: [&str; 8] = ["login", "unlock-check", "desktop-probe", "desktop-video-probe", "wayland-capture",
|
||||
"wayland-input-probe", "clipboard-acceptance", "portal-acceptance"];
|
||||
if let Some(arg) = std::env::args().nth(1).filter(|a| !SUBCOMMANDS.contains(&a.as_str())) {
|
||||
let usage = format!("usage: uuremote-server [{}]\n (no argument: run the host)", SUBCOMMANDS.join(" | "));
|
||||
if matches!(arg.as_str(), "help" | "-h" | "--help") { println!("{usage}"); return Ok(()); }
|
||||
eprintln!("unknown argument: {arg}\n{usage}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
if std::env::args().nth(1).as_deref() == Some("clipboard-acceptance") {
|
||||
return tokio::task::spawn_blocking(clipboard_probe::run).await?.map_err(Into::into);
|
||||
}
|
||||
@@ -62,6 +71,35 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
|
||||
let input=InputInjector::new();
|
||||
input.bind_portal(screen.portal.clone());
|
||||
if std::env::args().nth(2).as_deref() == Some("--clipboard-targets") {
|
||||
let read = || -> Result<serde_json::Value, Box<dyn std::error::Error>> {
|
||||
Ok(serde_json::from_slice(&std::fs::read("/tmp/uuremote-clipboard-official.json")?)?)
|
||||
};
|
||||
let before = read()?;
|
||||
if before["native_wayland"] != true || before["window_active"] != true { return Err("Native clipboard fixture must be focused".into()); }
|
||||
for name in ["check", "copy"] {
|
||||
let bounds = before[format!("{name}_bounds")].as_array().ok_or("Missing test button bounds")?;
|
||||
let number = |index: usize| bounds[index].as_f64().ok_or("Invalid button bounds");
|
||||
let x = number(0)? + number(2)? / 2.0;
|
||||
let y = number(1)? + number(3)? / 2.0;
|
||||
let width = before["window_size"][0].as_f64().ok_or("Missing test window width")?;
|
||||
let height = before["window_size"][1].as_f64().ok_or("Missing test window height")?;
|
||||
input.mouse_absolute_normalized(x / width, y / height, (screen.width,screen.height));
|
||||
input.mouse_button(1,true); input.mouse_button(1,false);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
let after = read()?;
|
||||
let key = format!("{name}_activations");
|
||||
if after[&key].as_u64() != before[&key].as_u64().map(|n| n+1) {
|
||||
return Err(format!("Portal small-target click missed: {name}").into());
|
||||
}
|
||||
let position = after["last_position"].as_array().ok_or("Missing native test pointer position")?;
|
||||
if (position[0].as_f64().ok_or("Invalid pointer x")? - x).abs() > 2.0 || (position[1].as_f64().ok_or("Invalid pointer y")? - y).abs() > 2.0 {
|
||||
return Err("Portal small-target pointer error exceeds two logical pixels".into());
|
||||
}
|
||||
println!("Portal native small-target click passed: {name}; pointer_error<=2px");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
input.mouse_absolute_normalized(0.25,0.25,(screen.width,screen.height));input.flush_pointer();
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
input.mouse_absolute_normalized(0.5,0.5,(screen.width,screen.height));input.flush_pointer();
|
||||
@@ -157,7 +195,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
if login::run(gui).await.is_err() { std::process::exit(1); } // error already shown
|
||||
return Ok(());
|
||||
}
|
||||
log::info!("Starting UU Remote Pure Native Rust Server v1.0.0...");
|
||||
log::info!("Starting uu-remote-linux host v{}...", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
let mut capture = Arc::new((if desktop_backend::detect()?==desktop_backend::DesktopBackend::Portal
|
||||
&& std::env::var("UU_PORTAL_PREAUTHORIZE").ok().as_deref()!=Some("1") {
|
||||
|
||||
+20
-4
@@ -10,6 +10,7 @@ mod native {
|
||||
use std::{ffi::c_void, ptr::NonNull, sync::Mutex};
|
||||
extern "C" {
|
||||
fn uu_portal_open_persist(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), data: *mut c_void, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void;
|
||||
fn uu_portal_clipboard_supported(portal: *mut c_void) -> i32;
|
||||
fn uu_portal_clipboard_ready(portal: *mut c_void) -> i32;
|
||||
fn uu_portal_clipboard_set(portal: *mut c_void, text: *const u8, length: usize) -> i32;
|
||||
fn uu_portal_clipboard_poll(portal: *mut c_void, text: *mut u8, capacity: usize) -> i32;
|
||||
@@ -49,13 +50,24 @@ mod native {
|
||||
}
|
||||
let pointer = unsafe { uu_portal_open_persist(token.as_ref().map_or(std::ptr::null(), |v| v.as_ptr()), save_token, &mut cache as *mut _ as *mut c_void, &mut error, &mut width, &mut height) };
|
||||
let handle = NonNull::new(pointer).ok_or_else(|| super::error(error))?;
|
||||
Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(true), retry_at: Mutex::new(None), width, height })
|
||||
// A freshly opened session holds no lock-screen frame: only an observed lock (or a
|
||||
// closed stream) must discard the cached frame. Starting "locked" cleared the first
|
||||
// valid frame, and a static desktop sends no new one, so the viewer stayed black (#2).
|
||||
Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), retry_at: Mutex::new(None), width, height })
|
||||
}
|
||||
pub fn capture(&self, frame: &mut [u8]) -> Result<(), String> {
|
||||
let mut handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
|
||||
let locked = *self.locked.borrow() != Some(false);
|
||||
if locked || self.was_locked.swap(locked, std::sync::atomic::Ordering::AcqRel) {
|
||||
self.was_locked.store(locked, std::sync::atomic::Ordering::Release);
|
||||
let state = *self.locked.borrow();
|
||||
if state != Some(false) {
|
||||
// Unknown state (watcher not reported yet): show nothing but keep the cached frame.
|
||||
if state == Some(true) {
|
||||
self.was_locked.store(true, std::sync::atomic::Ordering::Release);
|
||||
unsafe { uu_portal_reset_frame(handle.0.as_ptr()) };
|
||||
}
|
||||
super::blank(frame); return Ok(());
|
||||
}
|
||||
if self.was_locked.swap(false, std::sync::atomic::Ordering::AcqRel) {
|
||||
// First unlocked capture after a real lock: drop frames captured while locked.
|
||||
unsafe { uu_portal_reset_frame(handle.0.as_ptr()) };
|
||||
super::blank(frame); return Ok(());
|
||||
}
|
||||
@@ -89,6 +101,9 @@ mod native {
|
||||
if code == 10 || code == 9 { super::blank(frame); Ok(()) } else { super::check(code) }
|
||||
}
|
||||
|
||||
pub fn clipboard_supported(&self) -> bool {
|
||||
self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_supported(handle.0.as_ptr()) != 0 })
|
||||
}
|
||||
pub fn clipboard_ready(&self) -> bool {
|
||||
self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_ready(handle.0.as_ptr()) != 0 })
|
||||
}
|
||||
@@ -144,6 +159,7 @@ pub use native::Session as PortalSession;
|
||||
pub struct PortalSession { pub width: u32, pub height: u32 }
|
||||
#[cfg(not(all(target_os = "linux", feature = "portal")))]
|
||||
impl PortalSession {
|
||||
pub fn clipboard_supported(&self) -> bool { false }
|
||||
pub fn clipboard_ready(&self) -> bool { false }
|
||||
pub fn clipboard_set(&self, _: &str) -> Result<(), String> { Err(error(2)) }
|
||||
pub fn clipboard_poll(&self) -> Option<String> { None }
|
||||
|
||||
+15
-1
@@ -271,7 +271,11 @@ impl WebRtcSession {
|
||||
let input_clone = input.clone();
|
||||
let control_capture = capture.clone();
|
||||
let control_sequence = Arc::new(std::sync::atomic::AtomicU64::new(1));
|
||||
let text_clipboard_ready = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
// Capability belongs to the granted session, including while GNOME is
|
||||
// locked. Echo can precede TEXT readiness and CONTROL auto-unlock;
|
||||
// advertising false here would disable clipboard for the entire peer.
|
||||
let portal_clipboard_supported = desktop && capture.portal.as_ref().is_some_and(|session| session.clipboard_supported());
|
||||
let text_clipboard_ready = Arc::new(std::sync::atomic::AtomicBool::new(portal_clipboard_supported));
|
||||
// One file-transfer session per peer. The viewer may send FileTransferFtp RPCs on CONTROL,
|
||||
// but it receives file traffic only through streamerDidReceiveFileData, so every reply and
|
||||
// host-initiated request goes out on FILE_DATA_CHANNEL.
|
||||
@@ -714,6 +718,16 @@ impl WebRtcSession {
|
||||
match crate::control_protocol::decode_control(&msg.data) {
|
||||
Ok(crate::control_protocol::ControlMessage::Input(event)) => {
|
||||
use crate::control_protocol::ControlInput;
|
||||
// Separate receipt budgets keep motion floods from hiding clicks.
|
||||
static RECEIPTS: [std::sync::atomic::AtomicUsize; 3] = [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
|
||||
let (slot, kind) = match &event {
|
||||
ControlInput::MouseButton {..} | ControlInput::MouseClick {..} => (0, "button"),
|
||||
ControlInput::Keyboard {..} | ControlInput::KeyboardClick {..} => (1, "keyboard"),
|
||||
_ => (2, "motion"),
|
||||
};
|
||||
if RECEIPTS[slot].fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
|
||||
log::info!("CONTROL input received: kind={}", kind);
|
||||
}
|
||||
match &event {
|
||||
ControlInput::MouseAbsolute {x,y} => input_worker.mouse_absolute_normalized(*x,*y,input_size),
|
||||
ControlInput::MouseRelative {dx,dy} => input_worker.mouse_relative(*dx,*dy),
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import AppKit
|
||||
|
||||
// Synthetic acceptance fixture: clipboard values are compared only, never shown or saved.
|
||||
final class MarkerCheck: NSObject {
|
||||
let gnome = NSTextField(labelWithString: "GNOME → Mac: not checked")
|
||||
let kde = NSTextField(labelWithString: "KDE → Mac: not checked")
|
||||
let copied = NSTextField(labelWithString: "Mac marker: not copied")
|
||||
let formats = NSTextField(labelWithString: "Known text formats: not checked")
|
||||
@objc func copyMarker() {
|
||||
NSPasteboard.general.clearContents()
|
||||
let ok = NSPasteboard.general.setString("UU-Mac-to-VM 中文🙂", forType: .string)
|
||||
copied.stringValue = ok ? "Mac marker: copied" : "Mac marker: failed"
|
||||
}
|
||||
func matches() -> Bool {
|
||||
let board = NSPasteboard.general
|
||||
let utf16 = NSPasteboard.PasteboardType("public.utf16-plain-text")
|
||||
let known = board.types ?? []
|
||||
formats.stringValue = "Known text formats: UTF-8=\(known.contains(.string)), UTF-16=\(known.contains(utf16))"
|
||||
let marker = "UU-VM-to-Mac 中文🚀"
|
||||
if board.data(forType: .string) == Data(marker.utf8) { return true }
|
||||
guard let actual = board.data(forType: utf16) else { return false }
|
||||
for encoding in [String.Encoding.utf16, .utf16LittleEndian, .utf16BigEndian] {
|
||||
guard let expected = marker.data(using: encoding) else { continue }
|
||||
if actual == expected || actual == expected + Data([0, 0]) { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
@objc func compareGnome() { gnome.stringValue = matches() ? "GNOME → Mac: PASS" : "GNOME → Mac: not matched" }
|
||||
@objc func compareKde() { kde.stringValue = matches() ? "KDE → Mac: PASS" : "KDE → Mac: not matched" }
|
||||
@objc func quit() { NSApp.terminate(nil) }
|
||||
func button(_ title: String, _ action: Selector) -> NSButton {
|
||||
NSButton(title: title, target: self, action: action)
|
||||
}
|
||||
func show() {
|
||||
let window = NSWindow(contentRect: NSRect(x: 0,y: 0,width: 500,height: 360), styleMask: [.titled,.closable], backing: .buffered, defer: false)
|
||||
window.title = "UU synthetic clipboard acceptance"
|
||||
window.isReleasedWhenClosed = false
|
||||
let stack = NSStackView(views: [
|
||||
NSTextField(labelWithString: "Only fixed test-marker matches are displayed."),
|
||||
button("Copy Mac test marker", #selector(copyMarker)), copied,
|
||||
button("Compare GNOME VM marker", #selector(compareGnome)), gnome,
|
||||
button("Compare KDE VM marker", #selector(compareKde)), kde, formats,
|
||||
button("Quit test fixture", #selector(quit))])
|
||||
stack.orientation = .vertical; stack.spacing = 14
|
||||
stack.translatesAutoresizingMaskIntoConstraints = false
|
||||
window.contentView!.addSubview(stack)
|
||||
NSLayoutConstraint.activate([stack.centerXAnchor.constraint(equalTo: window.contentView!.centerXAnchor),stack.centerYAnchor.constraint(equalTo: window.contentView!.centerYAnchor)])
|
||||
window.center(); window.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true)
|
||||
}
|
||||
}
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
let fixture = MarkerCheck()
|
||||
fixture.show()
|
||||
app.run()
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
"""Official viewer clipboard fixture; only synthetic-marker match booleans are recorded."""
|
||||
import gi,json
|
||||
from pathlib import Path
|
||||
gi.require_version('Gtk','4.0'); gi.require_version('Gdk','4.0')
|
||||
from gi.repository import Gtk,Gdk,GLib
|
||||
assert Path('/proc/sys/kernel/hostname').read_text().strip()=='uu-hyprland-test'
|
||||
state={'native_wayland':False,'mac_to_vm':False,'reverse_owned':False,'button_presses':0,'button_releases':0,'check_activations':0,'copy_activations':0,'window_active':False,'key_presses':0,'key_releases':0}
|
||||
report=Path('/tmp/uuremote-clipboard-official.json')
|
||||
app=Gtk.Application(application_id='dev.uuremote.ClipboardOfficial')
|
||||
def activate(app):
|
||||
window=Gtk.ApplicationWindow(application=app,title='UU clipboard official acceptance')
|
||||
box=Gtk.Box(orientation=Gtk.Orientation.VERTICAL,spacing=24)
|
||||
box.set_halign(Gtk.Align.CENTER);box.set_valign(Gtk.Align.CENTER)
|
||||
label=Gtk.Label(label='UU Portal clipboard acceptance')
|
||||
check=Gtk.Button(label='Check Mac → VM')
|
||||
copy=Gtk.Button(label='Copy VM → Mac')
|
||||
box.append(label);box.append(check);box.append(copy);window.set_child(box)
|
||||
clipboard=window.get_clipboard()
|
||||
def read(*_):
|
||||
state['check_activations']+=1
|
||||
def done(source,result):
|
||||
try: state['mac_to_vm']=source.read_text_finish(result)=='UU-Mac-to-VM 中文🙂'
|
||||
except GLib.Error: state['mac_to_vm']=False
|
||||
label.set_label('Mac → VM: '+('PASS' if state['mac_to_vm'] else 'not matched'))
|
||||
clipboard.read_text_async(None,done)
|
||||
def write(*_):
|
||||
state['copy_activations']+=1
|
||||
clipboard.set('UU-VM-to-Mac 中文🚀');state['reverse_owned']=True
|
||||
label.set_label('VM marker copied')
|
||||
check.connect('clicked',read);copy.connect('clicked',write)
|
||||
keys=Gtk.EventControllerKey();keys.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
|
||||
def key_seen(*_):state['key_presses']+=1;return False
|
||||
keys.connect('key-pressed',key_seen)
|
||||
keys.connect('key-released',lambda *_:state.update(key_releases=state['key_releases']+1))
|
||||
window.add_controller(keys)
|
||||
window.connect('notify::is-active',lambda *_:state.update(window_active=window.is_active()))
|
||||
gesture=Gtk.GestureClick();gesture.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
|
||||
def pressed_seen(gesture,count,x,y):
|
||||
state['button_presses']+=1
|
||||
state['last_button']=gesture.get_current_button()
|
||||
state['last_modifiers']=int(gesture.get_current_event_state())
|
||||
state['last_position']=[round(x,1),round(y,1)]
|
||||
widget=window.pick(x,y,Gtk.PickFlags.DEFAULT)
|
||||
state['last_target']='other'
|
||||
while widget:
|
||||
if widget is check:state['last_target']='check';break
|
||||
if widget is copy:state['last_target']='copy';break
|
||||
widget=widget.get_parent()
|
||||
# An observer must not compete with the button's own click gesture.
|
||||
gesture.set_state(Gtk.EventSequenceState.DENIED)
|
||||
gesture.connect('pressed',pressed_seen);window.add_controller(gesture)
|
||||
window.present();window.fullscreen()
|
||||
state['native_wayland']='wayland' in type(Gdk.Display.get_default()).__name__.lower()
|
||||
def record():
|
||||
state['window_size']=[window.get_width(),window.get_height()]
|
||||
for name,button in [('check',check),('copy',copy)]:
|
||||
ok,bounds=button.compute_bounds(window)
|
||||
if ok:state[name+'_bounds']=[bounds.get_x(),bounds.get_y(),bounds.get_width(),bounds.get_height()]
|
||||
report.write_text(json.dumps(state));return True
|
||||
GLib.timeout_add(200,record)
|
||||
app.connect('activate',activate);app.run([])
|
||||
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
"""Audit receiver progress for a bounded VM service journal interval, not contents."""
|
||||
import json,re,subprocess,sys,time,pathlib
|
||||
|
||||
class Audit:
|
||||
def __init__(self,start,end):
|
||||
self.start=start;self.end=end;self.reports=0;self.sequences={};self.last_progress=start;self.max_gap=0;self.peers=set();self.local_kinds=set();self.turn_errors=0;self.binding_errors=0;self.room_deferrals=0;self.interruptions=0
|
||||
def accept(self,stamp,message):
|
||||
if not self.start<=stamp<=self.end:return
|
||||
if 'Video receiver report:' in message:
|
||||
found=re.search(r'ssrc=(\d+) last_sequence=(\d+)',message)
|
||||
if found:
|
||||
ssrc,sequence=map(int,found.groups());self.reports+=1
|
||||
if self.sequences.get(ssrc)!=sequence:
|
||||
self.max_gap=max(self.max_gap,stamp-self.last_progress);self.last_progress=stamp
|
||||
self.sequences[ssrc]=sequence
|
||||
if 'ICE path:' in message:
|
||||
found=re.search(r'session=(\d+).*local=\w+/(\w+)',message)
|
||||
if found:self.peers.add(found[1]);self.local_kinds.add(found[2])
|
||||
if 'fail to refresh permissions:' in message:self.turn_errors+=1
|
||||
if 'bind() for refresh failed:' in message:self.binding_errors+=1
|
||||
if 'Room renewal deferred while remote connection is active' in message:self.room_deferrals+=1
|
||||
if any(text in message for text in ['Remote controller disconnected:','Live desktop stream stopped:','PeerConnection State changed: Failed','PeerConnection State changed: Disconnected','peer connection state changed: closed']):self.interruptions+=1
|
||||
def result(self):
|
||||
gap=max(self.max_gap,self.end-self.last_progress)
|
||||
passed=self.end-self.start>=3600 and self.reports>0 and len(self.sequences)==1 and len(self.peers)==1 and self.local_kinds=={'relay'} and gap<=90 and self.interruptions==0 and self.room_deferrals>0
|
||||
return dict(passed=passed,duration_s=round(self.end-self.start,3),video_reports=self.reports,video_ssrc_count=len(self.sequences),peer_count=len(self.peers),local_candidate_kinds=sorted(self.local_kinds),maximum_video_progress_gap_s=round(gap,3),interruptions=self.interruptions,turn_permission_refresh_errors=self.turn_errors,turn_channel_bind_refresh_errors=self.binding_errors,room_renewal_deferrals=self.room_deferrals)
|
||||
|
||||
def run(start,end):
|
||||
assert pathlib.Path('/proc/sys/kernel/hostname').read_text().strip()=='uu-hyprland-test'
|
||||
audit=Audit(start,end)
|
||||
proc=subprocess.Popen(['journalctl','--user','-u','uuremote-test.service','--since',f'@{start}','--until',f'@{end}','--no-pager','-o','json'],stdout=subprocess.PIPE,text=True)
|
||||
for line in proc.stdout:
|
||||
row=json.loads(line);audit.accept(int(row['__REALTIME_TIMESTAMP'])/1e6,row.get('MESSAGE',''))
|
||||
if proc.wait()!=0:raise RuntimeError('Journal read failed')
|
||||
return audit.result()
|
||||
|
||||
if __name__=='__main__':print(json.dumps(run(float(sys.argv[1]),float(sys.argv[2]) if len(sys.argv)>2 else time.time())))
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
"""Hold an ephemeral idle inhibition only in the isolated QEMU acceptance VM."""
|
||||
import pathlib,subprocess,signal,threading,sys
|
||||
assert pathlib.Path('/proc/sys/kernel/hostname').read_text().strip()=='uu-hyprland-test'
|
||||
assert subprocess.check_output(['systemd-detect-virt'],text=True).strip()=='qemu'
|
||||
import gi
|
||||
gi.require_version('Gio','2.0')
|
||||
from gi.repository import Gio,GLib
|
||||
seconds=min(4200,max(1,int(sys.argv[1]) if len(sys.argv)>1 else 3600))
|
||||
bus=Gio.bus_get_sync(Gio.BusType.SESSION,None)
|
||||
reply=bus.call_sync('org.freedesktop.ScreenSaver','/ScreenSaver','org.freedesktop.ScreenSaver','Inhibit',GLib.Variant('(ss)',('UU isolated acceptance','Timed live-connection acceptance')),GLib.VariantType.new('(u)'),Gio.DBusCallFlags.NONE,3000,None)
|
||||
cookie=reply.unpack()[0]
|
||||
stop=threading.Event()
|
||||
signal.signal(signal.SIGTERM,lambda *_:stop.set())
|
||||
signal.signal(signal.SIGINT,lambda *_:stop.set())
|
||||
print('VM timed idle inhibition acquired',flush=True)
|
||||
try:stop.wait(seconds)
|
||||
finally:
|
||||
try:
|
||||
bus.call_sync('org.freedesktop.ScreenSaver','/ScreenSaver','org.freedesktop.ScreenSaver','UnInhibit',GLib.Variant('(u)',(cookie,)),None,Gio.DBusCallFlags.NONE,3000,None)
|
||||
print('VM timed idle inhibition released',flush=True)
|
||||
except GLib.Error:print('VM idle inhibition connection closed',flush=True)
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import importlib.util,pathlib,unittest
|
||||
spec=importlib.util.spec_from_file_location('audit',pathlib.Path(__file__).with_name('endurance-audit.py'));module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
||||
class TestAudit(unittest.TestCase):
|
||||
def make(self,progress=True):
|
||||
audit=module.Audit(0,3600)
|
||||
for stamp in range(0,3601,30):audit.accept(stamp,f'Video receiver report: ssrc=99 last_sequence={stamp if progress else 1}')
|
||||
audit.accept(0,'ICE path: session=1 route=relay local=udp/relay remote=udp/host')
|
||||
audit.accept(900,'Room renewal deferred while remote connection is active')
|
||||
return audit
|
||||
def test_receiver_heartbeats_without_new_video_fail(self):self.assertFalse(self.make(False).result()['passed'])
|
||||
def test_local_relay_progress_and_deferrals_pass(self):self.assertTrue(self.make().result()['passed'])
|
||||
def test_peer_replacement_and_remote_only_relay_do_not_pass(self):
|
||||
audit=self.make();audit.accept(1000,'ICE path: session=2 route=relay local=udp/relay remote=udp/host');self.assertFalse(audit.result()['passed'])
|
||||
audit=self.make();audit.local_kinds={'srflx'};self.assertFalse(audit.result()['passed'])
|
||||
def test_turn_refresh_errors_alone_do_not_mean_video_failure(self):
|
||||
audit=self.make();audit.accept(120,'fail to refresh permissions: error 400');self.assertTrue(audit.result()['passed']);self.assertEqual(audit.result()['turn_permission_refresh_errors'],1)
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,105 @@
|
||||
#define _GNU_SOURCE
|
||||
/* Protocol-independent C bounds/lifecycle checks; never requests consent. */
|
||||
#include <assert.h>
|
||||
#include "portal_engine.c"
|
||||
static void clipboard_bounds(void) {
|
||||
int fds[2]; uint8_t bytes[8]={0};
|
||||
assert(pipe2(fds,O_NONBLOCK)==0);
|
||||
assert(write(fds[1],"abc",3)==3); close(fds[1]);
|
||||
assert(clipboard_io(fds[0],bytes,4,0)==3 && !memcmp(bytes,"abc",3)); close(fds[0]);
|
||||
assert(pipe2(fds,O_NONBLOCK)==0);
|
||||
assert(write(fds[1],"1234",4)==4); close(fds[1]);
|
||||
assert(clipboard_io(fds[0],bytes,4,0)==-1); close(fds[0]);
|
||||
assert(pipe2(fds,O_NONBLOCK)==0); close(fds[0]);
|
||||
assert(clipboard_io(fds[1],bytes,1,1)==-1); close(fds[1]);
|
||||
assert(clipboard_io(-1,bytes,0,1)==0);
|
||||
}
|
||||
int main(void) {
|
||||
clipboard_bounds();
|
||||
struct uu_portal *p = calloc(1, sizeof(*p));
|
||||
assert(p);
|
||||
pthread_mutex_init(&p->lock, NULL);
|
||||
pthread_cond_init(&p->changed, NULL);
|
||||
uint8_t storage[256];
|
||||
struct spa_pod_builder builder = SPA_POD_BUILDER_INIT(storage, sizeof(storage));
|
||||
const struct spa_pod *format = spa_format_video_raw_build(&builder, SPA_PARAM_Format,
|
||||
&SPA_VIDEO_INFO_RAW_INIT(.format=SPA_VIDEO_FORMAT_BGRA, .size=SPA_RECTANGLE(2,2), .framerate=SPA_FRACTION(60,1)));
|
||||
stream_format(p, SPA_PARAM_Format, format);
|
||||
assert(p->width == 2 && p->height == 2 && p->frame_length == 16 && !p->error);
|
||||
uint8_t pixels[16] = {0};
|
||||
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 10);
|
||||
p->sequence = 1;
|
||||
assert(uu_portal_capture(p, pixels, sizeof(pixels)-1) == 11);
|
||||
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 0);
|
||||
p->logical_width = p->logical_height = 2;
|
||||
assert(uu_portal_move(p, NAN, 1, 0) == 11);
|
||||
assert(uu_portal_move(p, 2, 1, 0) == 11);
|
||||
assert(uu_portal_alive(p));
|
||||
/* Synthetic RGBA with row padding validates both channel order and stride. */
|
||||
uint8_t source[24] = {255,0,0,255, 0,255,0,255, 99,99,99,99,
|
||||
0,0,255,255, 255,255,255,255, 88,88,88,88};
|
||||
struct spa_chunk chunk = {.offset=0, .size=20, .stride=12};
|
||||
struct spa_data data = {.type=SPA_DATA_MemPtr, .data=source, .maxsize=24, .chunk=&chunk};
|
||||
struct spa_buffer buffer = {.n_datas=1, .datas=&data};
|
||||
p->format=SPA_VIDEO_FORMAT_RGBA;
|
||||
copy_video_buffer(p, &buffer);
|
||||
const uint8_t expected[16] = {0,0,255,255, 0,255,0,255, 255,0,0,255, 255,255,255,255};
|
||||
assert(!memcmp(p->frame, expected, 16) && p->sequence == 2);
|
||||
/* Capacity still contains old bytes, but zero/short chunks are not frames. */
|
||||
for (unsigned size=0; size<20; size++) {
|
||||
chunk.size=size; copy_video_buffer(p, &buffer);
|
||||
assert(p->sequence == 2 && !memcmp(p->frame, expected, 16) && !p->error);
|
||||
}
|
||||
chunk.size=20; chunk.flags=SPA_CHUNK_FLAG_CORRUPTED;
|
||||
copy_video_buffer(p, &buffer);
|
||||
assert(p->sequence==2 && !p->error);
|
||||
chunk.flags=0;
|
||||
struct spa_meta_header header={.flags=SPA_META_HEADER_FLAG_CORRUPTED};
|
||||
struct spa_meta metadata={.type=SPA_META_Header, .size=sizeof(header), .data=&header};
|
||||
buffer.n_metas=1; buffer.metas=&metadata;
|
||||
copy_video_buffer(p, &buffer); assert(p->sequence==2 && !p->error);
|
||||
buffer.n_metas=0; buffer.metas=NULL;
|
||||
/* Explicit EMPTY is opaque black rather than a stale desktop image. */
|
||||
chunk.size=0; chunk.flags=SPA_CHUNK_FLAG_EMPTY;
|
||||
copy_video_buffer(p, &buffer); assert(p->sequence==3);
|
||||
for (unsigned pixel=0; pixel<4; pixel++) {
|
||||
assert(p->frame[pixel*4]==0 && p->frame[pixel*4+1]==0 && p->frame[pixel*4+2]==0 && p->frame[pixel*4+3]==255);
|
||||
}
|
||||
/* A valid buffer after corruption remains usable; no permanent failure. */
|
||||
chunk.size=20; chunk.flags=0; copy_video_buffer(p, &buffer);
|
||||
assert(p->sequence==4 && !memcmp(p->frame, expected, 16));
|
||||
uu_portal_reset_frame(p);
|
||||
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 10);
|
||||
copy_video_buffer(p, &buffer);
|
||||
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 0);
|
||||
p->session=g_strdup("/uu_test_session");
|
||||
GVariantBuilder clip_options; g_variant_builder_init(&clip_options,G_VARIANT_TYPE_VARDICT);
|
||||
const char *types[]={"image/png","text/plain",NULL};
|
||||
g_variant_builder_add(&clip_options,"{sv}","mime_types",g_variant_new_strv(types,-1));
|
||||
GVariant *event=g_variant_ref_sink(g_variant_new("(o@a{sv})",p->session,g_variant_builder_end(&clip_options)));
|
||||
selection_owner(NULL,NULL,NULL,NULL,NULL,event,p); g_variant_unref(event);
|
||||
assert(p->clipboard_changed && !strcmp(p->clipboard_mime,"text/plain"));
|
||||
g_variant_builder_init(&clip_options,G_VARIANT_TYPE_VARDICT);
|
||||
g_variant_builder_add(&clip_options,"{sv}","session_is_owner",g_variant_new_boolean(TRUE));
|
||||
event=g_variant_ref_sink(g_variant_new("(o@a{sv})",p->session,g_variant_builder_end(&clip_options)));
|
||||
selection_owner(NULL,NULL,NULL,NULL,NULL,event,p); g_variant_unref(event);
|
||||
assert(!p->clipboard_changed && !p->clipboard_mime);
|
||||
assert(uu_portal_clipboard_set(p,(const uint8_t *)"x",1)==-1);
|
||||
assert(uu_portal_clipboard_poll(p,NULL,CLIP_LIMIT)==-1);
|
||||
p->error=8;
|
||||
assert(!uu_portal_alive(p));
|
||||
assert(uu_portal_key(p, 'a', 1)==9); /* no input into an unusable stream */
|
||||
p->error=0;
|
||||
p->clipboard_enabled=1;
|
||||
assert(uu_portal_clipboard_supported(p));
|
||||
assert(uu_portal_clipboard_ready(p));
|
||||
atomic_store(&p->closed, 1);
|
||||
/* Closing a granted session temporarily removes readiness, not capability. */
|
||||
assert(uu_portal_clipboard_supported(p));
|
||||
assert(!uu_portal_clipboard_ready(p));
|
||||
assert(!uu_portal_alive(p));
|
||||
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 9);
|
||||
uu_portal_close(p);
|
||||
puts("Portal C bounds/lifecycle checks passed");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user