mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 16:50:41 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fb57b421d | ||
|
|
72c1e6101f | ||
|
|
a67731052f | ||
|
|
e6089bfb46 | ||
|
|
aa2a341d15 | ||
|
|
9622bf4c1e | ||
|
|
d7e52a098b | ||
|
|
94ff1f1c02 | ||
|
|
aafc17e626 | ||
|
|
cd6df7f03f | ||
|
|
2815a01569 | ||
|
|
664c96941c | ||
|
|
8967dfdd4b |
No files matched your search
@@ -146,7 +146,7 @@ every 60 s.
|
|||||||
| `c_engine/x11_engine.c`, `c_engine/clipboard.c` | X11 capture/input/selection |
|
| `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/wayland_engine.c`, `c_engine/portal_engine.c` | Wayland and portal engines |
|
||||||
| `src/assist.rs`, `c_engine/assist_window.c` | remote assistance (guest + account) and the unified GTK main window (assist + account/QR card) |
|
| `src/assist.rs`, `c_engine/assist_window.c` | remote assistance (guest + account) and the unified GTK main window (assist + account/QR card) |
|
||||||
| `src/viewer_main.rs`, `src/viewer/` | experimental viewer (`--features native-viewer,viewer-sdl`): cloud join, WebRTC offer side, SDL desktop window (ffmpeg CLI decode), files/terminal/portmap/power/assist tools, GTK launcher |
|
| `src/viewer_main.rs`, `src/viewer/` | experimental viewer (`--features native-viewer,viewer-sdl`): cloud join, WebRTC offer side, SDL desktop window (ffmpeg CLI decode), files/terminal/portmap/power/assist tools, device removal (`POST /api/v1/device/{id}/unbind`, verified live; shared devices use `/api/v1/device/share/{id}/unbind`, strings only), GTK launcher |
|
||||||
| `c_engine/viewer_window.c`, `c_engine/viewer_tools.c` | viewer GTK launcher and tool windows (files, port mapping, terminal list) |
|
| `c_engine/viewer_window.c`, `c_engine/viewer_tools.c` | viewer GTK launcher and tool windows (files, port mapping, terminal list) |
|
||||||
|
|
||||||
Diagnostic subcommands: `login [--no-gui]`, `unlock-check` (password on stdin, prints only accepted/rejected),
|
Diagnostic subcommands: `login [--no-gui]`, `unlock-check` (password on stdin, prints only accepted/rejected),
|
||||||
|
|||||||
Generated
+1
-1
@@ -2741,7 +2741,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uu-remote-linux"
|
name = "uu-remote-linux"
|
||||||
version = "0.2.2"
|
version = "0.2.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "uu-remote-linux"
|
name = "uu-remote-linux"
|
||||||
version = "0.2.2"
|
version = "0.2.6"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
default-run = "uuremote-server"
|
default-run = "uuremote-server"
|
||||||
authors = ["uu-remote-linux contributors"]
|
authors = ["uu-remote-linux contributors"]
|
||||||
|
|||||||
+17
-5
@@ -1,4 +1,4 @@
|
|||||||
# uu-remote-linux · Unofficial Linux host for NetEase UU Remote
|
# uu-remote-linux · Unofficial Linux host and viewer for NetEase UU Remote
|
||||||
|
|
||||||
[简体中文](README.md) | **English**
|
[简体中文](README.md) | **English**
|
||||||
|
|
||||||
@@ -7,13 +7,19 @@
|
|||||||
> NetEase UU Remote (网易 UU 远程) is a great remote-desktop tool, but there is no Linux version on its
|
> NetEase UU Remote (网易 UU 远程) is a great remote-desktop tool, but there is no Linux version on its
|
||||||
> official website. So, with the help of Claude and Codex, I wrote this open-source Linux host: install it,
|
> official website. So, with the help of Claude and Codex, I wrote this open-source Linux host: install it,
|
||||||
> and you can control your Linux machine from the official Mac / Windows / mobile UU Remote clients.
|
> and you can control your Linux machine from the official Mac / Windows / mobile UU Remote clients.
|
||||||
|
> It now also ships an **experimental Linux viewer**, `uuremote-viewer`, that controls official Windows / Mac hosts or this
|
||||||
|
> project's host from Linux (desktop, file transfer, terminal, port mapping, remote assistance; see
|
||||||
|
> [below](#experimental-native-viewer-uuremote-viewer)).
|
||||||
>
|
>
|
||||||
> This is a personal hobby project. **It is not affiliated with NetEase and is not an official client.**
|
> This is a personal hobby project. **It is not affiliated with NetEase and is not an official client.**
|
||||||
> If NetEase considers this project infringing or inappropriate, please DM me on X
|
> If NetEase considers this project infringing or inappropriate, please DM me on X
|
||||||
> **[@ai_fengshou](https://x.com/ai_fengshou)** and I will take it down right away.
|
> **[@ai_fengshou](https://x.com/ai_fengshou)** and I will take it down right away.
|
||||||
|
|
||||||
|
<p align="center"><img src="docs/images/viewer-window.png" width="720" alt="Linux viewer launcher: device list (device names redacted)"></p>
|
||||||
|
<p align="center"><sub>Linux viewer: device list (device names redacted)</sub></p>
|
||||||
|
|
||||||
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Host main window: remote assistance and account"></p>
|
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Host main window: remote assistance and account"></p>
|
||||||
<p align="center"><sub>The QR login window shown on first run (QR code blurred). The UI is in Chinese, like the official app.</sub></p>
|
<p align="center"><sub>Linux host main window: remote assistance and account (device ID, code and account redacted). The UI is in Chinese, like the official app.</sub></p>
|
||||||
|
|
||||||
<!-- Screenshot placeholder: the Linux desktop controlled from the official client. Take your own
|
<!-- Screenshot placeholder: the Linux desktop controlled from the official client. Take your own
|
||||||
screenshot, remove account/device details and NetEase logos, save it as docs/images/remote-desktop.png
|
screenshot, remove account/device details and NetEase logos, save it as docs/images/remote-desktop.png
|
||||||
@@ -411,17 +417,23 @@ hosts or this project's Linux host), and can start remote assistance with someon
|
|||||||
separate from the host `uuremote-server`; the default host build and behaviour are unchanged.
|
separate from the host `uuremote-server`; the default host build and behaviour are unchanged.
|
||||||
|
|
||||||
**Get it**: release tarballs include `uuremote-viewer` (x86_64) from this version on. Runtime needs GTK3, SDL2 (Ubuntu/Debian:
|
**Get it**: release tarballs include `uuremote-viewer` (x86_64) from this version on. Runtime needs GTK3, SDL2 (Ubuntu/Debian:
|
||||||
`libsdl2-2.0-0`) and the `ffmpeg` command; clipboard needs `wl-clipboard` (Wayland) or `xclip`/`xsel` (X11); the terminal needs a local
|
`libsdl2-2.0-0`) and the `ffmpeg` command; SDL desktop windows synchronize text clipboard directly on Wayland/X11 without extra clipboard tools; the terminal needs a local
|
||||||
terminal emulator (`TERMINAL` selects one). From source: `sudo apt install libsdl2-dev`, then
|
terminal emulator (`TERMINAL` selects one). From source: `sudo apt install libsdl2-dev`, then
|
||||||
`cargo build --release --locked --features native-viewer,viewer-sdl --bin uuremote-viewer`.
|
`cargo build --release --locked --features native-viewer,viewer-sdl --bin uuremote-viewer`.
|
||||||
|
|
||||||
|
SDL clipboard access reuses the desktop window to avoid temporary-window Dock churn on GNOME Wayland (#37).
|
||||||
|
Synchronization runs only while that window is focused and keeps the 30 KiB text limit. Selections without a supported
|
||||||
|
text format are skipped; empty-text detection depends on the SDL2 backend. Builds without SDL retain the command backend.
|
||||||
|
SDL2 reads selections synchronously, so a slow selection owner can temporarily block the window; the bridge timeout cannot interrupt it.
|
||||||
|
GNOME-to-official-Mac bidirectional clipboard synchronization is still unverified; this change does not resolve host compatibility.
|
||||||
|
|
||||||
**Use**:
|
**Use**:
|
||||||
- `uuremote-viewer login`: QR login (reuses the sibling `uuremote-server` login window; `--no-gui` prints a terminal QR). The viewer
|
- `uuremote-viewer login`: QR login (reuses the sibling `uuremote-server` login window; `--no-gui` prints a terminal QR). The viewer
|
||||||
shares `~/.config/uuremote/config.json` with the host (`UU_CONFIG` selects another), so it **cannot connect to a host on the same
|
shares `~/.config/uuremote/config.json` with the host (`UU_CONFIG` selects another), so it **cannot connect to a host on the same
|
||||||
machine with the same identity**; other devices are fine.
|
machine with the same identity**; other devices are fine.
|
||||||
- `uuremote-viewer ui`: launcher listing your devices: desktop, view-only, files, terminal, port mapping, reboot/shutdown, assistance.
|
- `uuremote-viewer ui`: launcher listing your devices: desktop, view-only, files, terminal, port mapping, reboot/shutdown, assistance.
|
||||||
- CLI: `connect DEVICE false - echo legacy [--view-only]` (desktop), `files DEVICE ls|get|put …`, `terminal DEVICE [SESSION]`,
|
- CLI: `connect DEVICE false - echo legacy [--view-only]` (desktop), `files DEVICE ls|get|put …`, `terminal DEVICE [SESSION]`,
|
||||||
`terminal-ui DEVICE NAME`, `portmap DEVICE LOCAL_PORT HOST PORT` (listens on 127.0.0.1 only), `power DEVICE reboot|shutdown`,
|
`terminal-ui DEVICE NAME`, `portmap DEVICE LOCAL_PORT HOST PORT` (listens on 127.0.0.1 only), `power DEVICE reboot|shutdown`, `unbind DEVICE` (remove a device from the account; also under "More tools" in the launcher),
|
||||||
`assist CONNECT_ID` (the code is read from one stdin line, never an argument). See `uuremote-viewer --help`.
|
`assist CONNECT_ID` (the code is read from one stdin line, never an argument). See `uuremote-viewer --help`.
|
||||||
- Ctrl+Alt+F in the desktop window opens the files window on the same connection. `UU_VIEWER_AUDIO=0` disables sound,
|
- Ctrl+Alt+F in the desktop window opens the files window on the same connection. `UU_VIEWER_AUDIO=0` disables sound,
|
||||||
`UU_VIEWER_CLIPBOARD=0` the clipboard, `UU_VIEWER_VIEW_ONLY=1` input; `UU_VIEWER_FFMPEG` selects the ffmpeg binary.
|
`UU_VIEWER_CLIPBOARD=0` the clipboard, `UU_VIEWER_VIEW_ONLY=1` input; `UU_VIEWER_FFMPEG` selects the ffmpeg binary.
|
||||||
@@ -449,7 +461,7 @@ assistance and ISO / JIS keyboards have not been tested live.
|
|||||||
| Remote assistance (ID + code) | — | — | ✅ (VM, guest host) |
|
| Remote assistance (ID + code) | — | — | ✅ (VM, guest host) |
|
||||||
| Terminal session list (create, double-click reattach, end) | — | — | ✅ (VM) |
|
| Terminal session list (create, double-click reattach, end) | — | — | ✅ (VM) |
|
||||||
| Reboot, shutdown | — | — | ✅ (VM) |
|
| Reboot, shutdown | — | — | ✅ (VM) |
|
||||||
| Wayland desktop window and clipboard | — | — | ✅ Hyprland, KDE; GNOME window works, clipboard unavailable (#37) |
|
| Wayland desktop window and clipboard | — | — | ✅ Hyprland, KDE; GNOME window works; clipboard switched to SDL in v0.2.3 (#37, final revision not re-verified live) |
|
||||||
|
|
||||||
"—" = not tested yet. Only use reboot/shutdown on machines you can restart. **Not tested live**: H.265 / 4:4:4 with official hosts, multiple monitors. Logs carry field
|
"—" = not tested yet. Only use reboot/shutdown on machines you can restart. **Not tested live**: H.265 / 4:4:4 with official hosts, multiple monitors. Logs carry field
|
||||||
numbers, sizes and states only, never keystrokes, clipboard or file contents, codes or credentials.
|
numbers, sizes and states only, never keystrokes, clipboard or file contents, codes or credentials.
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# uu-remote-linux · UU 远程 Linux 被控端(非官方)
|
# uu-remote-linux · UU 远程 Linux 被控端 + 控制端(非官方)
|
||||||
|
|
||||||
**简体中文** | [English](README.en.md)
|
**简体中文** | [English](README.en.md)
|
||||||
|
|
||||||
@@ -6,12 +6,17 @@
|
|||||||
>
|
>
|
||||||
> 网易 UU 远程非常好用,但官网一直没有 Linux 版本。于是我借助 Claude 和 Codex,写了这个开源的 Linux 被控端:
|
> 网易 UU 远程非常好用,但官网一直没有 Linux 版本。于是我借助 Claude 和 Codex,写了这个开源的 Linux 被控端:
|
||||||
> 装上之后,就能用官方的 Mac / Windows / 手机客户端远程控制你的 Linux 电脑。
|
> 装上之后,就能用官方的 Mac / Windows / 手机客户端远程控制你的 Linux 电脑。
|
||||||
|
> 现在还附带一个**实验性 Linux 控制端** `uuremote-viewer`:在 Linux 上用 UU 账号远控官方 Windows / Mac 被控端或本项目主机
|
||||||
|
> (桌面、文件传输、终端、端口映射、远程协助,详见[下文](#实验性原生控制端uuremote-viewer))。
|
||||||
>
|
>
|
||||||
> 这是个人兴趣项目,**与网易无关,也不是官方客户端**。如果网易认为本项目侵权或有不妥,
|
> 这是个人兴趣项目,**与网易无关,也不是官方客户端**。如果网易认为本项目侵权或有不妥,
|
||||||
> 请在推特私信我 **[@ai_fengshou](https://x.com/ai_fengshou)**,我会第一时间自行下架。
|
> 请在推特私信我 **[@ai_fengshou](https://x.com/ai_fengshou)**,我会第一时间自行下架。
|
||||||
|
|
||||||
|
<p align="center"><img src="docs/images/viewer-window.png" width="720" alt="Linux 控制端启动窗口:设备列表(设备名已打码)"></p>
|
||||||
|
<p align="center"><sub>Linux 控制端:设备列表(设备名已打码)</sub></p>
|
||||||
|
|
||||||
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Linux 主机主窗口:远程协助与账号"></p>
|
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Linux 主机主窗口:远程协助与账号"></p>
|
||||||
<p align="center"><sub>首次运行时弹出的扫码登录窗口(二维码已打码)</sub></p>
|
<p align="center"><sub>Linux 被控端主窗口:远程协助与账号(设备 ID、验证码和账号已打码)</sub></p>
|
||||||
|
|
||||||
<!-- 截图占位:在官方客户端里远控 Linux 桌面的效果图。请自行截图并去掉账号、设备名等信息后放到
|
<!-- 截图占位:在官方客户端里远控 Linux 桌面的效果图。请自行截图并去掉账号、设备名等信息后放到
|
||||||
docs/images/remote-desktop.png,再取消下面这行的注释。注意不要截入网易的图标和品牌素材。 -->
|
docs/images/remote-desktop.png,再取消下面这行的注释。注意不要截入网易的图标和品牌素材。 -->
|
||||||
@@ -377,15 +382,20 @@ xfce4-session xfce4-panel xfdesktop xfwm4 gnome-terminal`。
|
|||||||
也可以凭对方的设备 ID 和验证码发起远程协助。它是实验性功能,与主机 `uuremote-server` 相互独立,默认主机构建和行为不变。
|
也可以凭对方的设备 ID 和验证码发起远程协助。它是实验性功能,与主机 `uuremote-server` 相互独立,默认主机构建和行为不变。
|
||||||
|
|
||||||
**获取**:Release 包从本版本起附带 `uuremote-viewer`(x86_64)。运行时需要 GTK3、SDL2(Ubuntu/Debian:`libsdl2-2.0-0`)和
|
**获取**:Release 包从本版本起附带 `uuremote-viewer`(x86_64)。运行时需要 GTK3、SDL2(Ubuntu/Debian:`libsdl2-2.0-0`)和
|
||||||
`ffmpeg` 命令;剪贴板需要 `wl-clipboard`(Wayland)或 `xclip`/`xsel`(X11);终端功能需要本机终端程序(可用 `TERMINAL` 指定)。
|
`ffmpeg` 命令;SDL 桌面窗口直接同步文本剪贴板(Wayland/X11),无需额外剪贴板工具;终端功能需要本机终端程序(可用 `TERMINAL` 指定)。
|
||||||
从源码构建:`sudo apt install libsdl2-dev`,然后 `cargo build --release --locked --features native-viewer,viewer-sdl --bin uuremote-viewer`。
|
从源码构建:`sudo apt install libsdl2-dev`,然后 `cargo build --release --locked --features native-viewer,viewer-sdl --bin uuremote-viewer`。
|
||||||
|
|
||||||
|
SDL 剪贴板复用桌面窗口,避免 GNOME Wayland 上临时窗口引起的 Dock 跳动(#37)。仅在桌面窗口获得焦点时同步,
|
||||||
|
保留 30 KiB 文本上限;跳过不含支持的文本格式的本地选择,空文本的识别取决于 SDL2 后端。不带 SDL 的构建保留命令后端。
|
||||||
|
SDL2 同步读取选择内容,慢速的剪贴板提供者可能暂时阻塞窗口,桥接超时无法中断该原生调用。
|
||||||
|
GNOME 与官方 Mac 被控端的双向剪贴板尚未验证通过;此修改不解决被控端兼容问题。
|
||||||
|
|
||||||
**使用**:
|
**使用**:
|
||||||
- `uuremote-viewer login`:扫码登录(复用同目录下 `uuremote-server` 的登录窗口;`--no-gui` 为终端二维码)。控制端与主机共用
|
- `uuremote-viewer login`:扫码登录(复用同目录下 `uuremote-server` 的登录窗口;`--no-gui` 为终端二维码)。控制端与主机共用
|
||||||
`~/.config/uuremote/config.json`(可用 `UU_CONFIG` 另指定),因此**不能用同一身份连接本机上的主机**;控制其他设备不受影响。
|
`~/.config/uuremote/config.json`(可用 `UU_CONFIG` 另指定),因此**不能用同一身份连接本机上的主机**;控制其他设备不受影响。
|
||||||
- `uuremote-viewer ui`:启动窗口,列出账号下的设备,可进入桌面、只看模式、文件传输、终端、端口映射、重启/关机、远程协助。
|
- `uuremote-viewer ui`:启动窗口,列出账号下的设备,可进入桌面、只看模式、文件传输、终端、端口映射、重启/关机、远程协助。
|
||||||
- 命令行:`connect DEVICE false - echo legacy [--view-only]`(桌面)、`files DEVICE ls|get|put …`、`terminal DEVICE [SESSION]`、
|
- 命令行:`connect DEVICE false - echo legacy [--view-only]`(桌面)、`files DEVICE ls|get|put …`、`terminal DEVICE [SESSION]`、
|
||||||
`terminal-ui DEVICE NAME`、`portmap DEVICE LOCAL_PORT HOST PORT`(只监听 127.0.0.1)、`power DEVICE reboot|shutdown`、
|
`terminal-ui DEVICE NAME`、`portmap DEVICE LOCAL_PORT HOST PORT`(只监听 127.0.0.1)、`power DEVICE reboot|shutdown`、`unbind DEVICE`(从账号删除设备,启动窗口「更多工具」里也有)、
|
||||||
`assist CONNECT_ID`(验证码从 stdin 读取一行,不能作为参数传入)。`uuremote-viewer --help` 查看全部参数。
|
`assist CONNECT_ID`(验证码从 stdin 读取一行,不能作为参数传入)。`uuremote-viewer --help` 查看全部参数。
|
||||||
- 桌面窗口中按 Ctrl+Alt+F 打开文件窗口(复用同一连接)。`UU_VIEWER_AUDIO=0` 关闭声音,`UU_VIEWER_CLIPBOARD=0` 关闭剪贴板,
|
- 桌面窗口中按 Ctrl+Alt+F 打开文件窗口(复用同一连接)。`UU_VIEWER_AUDIO=0` 关闭声音,`UU_VIEWER_CLIPBOARD=0` 关闭剪贴板,
|
||||||
`UU_VIEWER_VIEW_ONLY=1` 只看不控,`UU_VIEWER_FFMPEG` 指定 ffmpeg 路径。
|
`UU_VIEWER_VIEW_ONLY=1` 只看不控,`UU_VIEWER_FFMPEG` 指定 ffmpeg 路径。
|
||||||
@@ -411,6 +421,6 @@ Mac 目标使用 macOS 原生键码,Windows / Linux 目标保留 Windows VK。
|
|||||||
| 远程协助(ID + 验证码) | — | — | ✅(虚拟机,访客主机) |
|
| 远程协助(ID + 验证码) | — | — | ✅(虚拟机,访客主机) |
|
||||||
| 终端会话列表(新建、双击接回、结束) | — | — | ✅(虚拟机) |
|
| 终端会话列表(新建、双击接回、结束) | — | — | ✅(虚拟机) |
|
||||||
| 重启、关机 | — | — | ✅(虚拟机) |
|
| 重启、关机 | — | — | ✅(虚拟机) |
|
||||||
| Wayland 下的桌面窗口与剪贴板 | — | — | ✅ Hyprland、KDE;GNOME 窗口正常,剪贴板不可用(#37) |
|
| Wayland 下的桌面窗口与剪贴板 | — | — | ✅ Hyprland、KDE;GNOME 窗口正常,剪贴板已于 v0.2.3 改为 SDL 直连(#37,最终版本未重新实机验收) |
|
||||||
|
|
||||||
「—」表示尚未测试。重启/关机只应在可以重启的机器上使用。**未实测**:官方被控端的 H.265 / 4:4:4、多显示器。日志只记录字段号、大小和状态,不记录键盘、剪贴板、文件内容、验证码或凭据。
|
「—」表示尚未测试。重启/关机只应在可以重启的机器上使用。**未实测**:官方被控端的 H.265 / 4:4:4、多显示器。日志只记录字段号、大小和状态,不记录键盘、剪贴板、文件内容、验证码或凭据。
|
||||||
@@ -475,6 +475,8 @@ static void build_window(void) {
|
|||||||
static void *ui_main(void *arg) {
|
static void *ui_main(void *arg) {
|
||||||
(void)arg;
|
(void)arg;
|
||||||
int ok = gtk_init_check(NULL, NULL);
|
int ok = gtk_init_check(NULL, NULL);
|
||||||
|
// The CSS hard-codes a light palette; a dark system theme would turn unstyled text white on white (#43).
|
||||||
|
if (ok) g_object_set(gtk_settings_get_default(), "gtk-theme-name", "Adwaita", "gtk-application-prefer-dark-theme", FALSE, NULL);
|
||||||
if (ok) build_window();
|
if (ok) build_window();
|
||||||
pthread_mutex_lock(&init_lock);
|
pthread_mutex_lock(&init_lock);
|
||||||
init_state = ok ? 1 : -1;
|
init_state = ok ? 1 : -1;
|
||||||
|
|||||||
@@ -474,6 +474,8 @@ static gboolean show_window(gpointer d) {
|
|||||||
static void *ui_thread(void *d) {
|
static void *ui_thread(void *d) {
|
||||||
(void)d;
|
(void)d;
|
||||||
if (!gtk_init_check(NULL, NULL)) { pthread_mutex_lock(&init_lock); init_state = -1; pthread_cond_signal(&init_cond); pthread_mutex_unlock(&init_lock); return NULL; }
|
if (!gtk_init_check(NULL, NULL)) { pthread_mutex_lock(&init_lock); init_state = -1; pthread_cond_signal(&init_cond); pthread_mutex_unlock(&init_lock); return NULL; }
|
||||||
|
// Light palette in CSS; keep a dark system theme from making unstyled text white on white (#43).
|
||||||
|
g_object_set(gtk_settings_get_default(), "gtk-theme-name", "Adwaita", "gtk-application-prefer-dark-theme", FALSE, NULL);
|
||||||
show_window(NULL); gtk_main(); return NULL;
|
show_window(NULL); gtk_main(); return NULL;
|
||||||
}
|
}
|
||||||
/* Hidden windows retain their widgets so queued idle callbacks stay valid. */
|
/* Hidden windows retain their widgets so queued idle callbacks stay valid. */
|
||||||
|
|||||||
@@ -117,6 +117,15 @@ static void more_item(GtkButton *b, gpointer kind) {
|
|||||||
if (ok) { connect_kind(k); show_toast("正在发送电源指令…"); }
|
if (ok) { connect_kind(k); show_toast("正在发送电源指令…"); }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!strcmp(k, "unbind")) {
|
||||||
|
GtkWidget *d = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE,
|
||||||
|
"确定要从账号中删除该设备吗?");
|
||||||
|
gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "删除后需要在该设备上重新登录才能再次远控。");
|
||||||
|
gtk_dialog_add_buttons(GTK_DIALOG(d), "取消", GTK_RESPONSE_CANCEL, "删除", GTK_RESPONSE_OK, NULL);
|
||||||
|
int ok = gtk_dialog_run(GTK_DIALOG(d)) == GTK_RESPONSE_OK; gtk_widget_destroy(d);
|
||||||
|
if (ok) { gtk_widget_destroy(dialog); connect_kind(k); show_toast("正在删除设备…"); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
gtk_widget_destroy(dialog);
|
gtk_widget_destroy(dialog);
|
||||||
on_tool(NULL, kind);
|
on_tool(NULL, kind);
|
||||||
}
|
}
|
||||||
@@ -126,9 +135,9 @@ static void open_more(void) {
|
|||||||
GtkWidget *area = gtk_dialog_get_content_area(GTK_DIALOG(dialog)), *box = vbox(10);
|
GtkWidget *area = gtk_dialog_get_content_area(GTK_DIALOG(dialog)), *box = vbox(10);
|
||||||
gtk_container_set_border_width(GTK_CONTAINER(box), 22);
|
gtk_container_set_border_width(GTK_CONTAINER(box), 22);
|
||||||
gtk_box_pack_start(GTK_BOX(box), label("更多工具", "h2"), FALSE, FALSE, 6);
|
gtk_box_pack_start(GTK_BOX(box), label("更多工具", "h2"), FALSE, FALSE, 6);
|
||||||
const char *names[] = {"🗂 文件传输", "▶ 观看模式", "⌨ 终端", "⇄ 端口映射", "⏻ 远程开机", "↻ 重启", "⏻ 关机"};
|
const char *names[] = {"🗂 文件传输", "▶ 观看模式", "⌨ 终端", "⇄ 端口映射", "⏻ 远程开机", "↻ 重启", "⏻ 关机", "🗑 删除设备"};
|
||||||
const char *kinds[] = {"file", "watch", "terminal", "portmap", "wol", "reboot", "shutdown"};
|
const char *kinds[] = {"file", "watch", "terminal", "portmap", "wol", "reboot", "shutdown", "unbind"};
|
||||||
for (int i = 0; i < 7; i++) {
|
for (int i = 0; i < 8; i++) {
|
||||||
GtkWidget *b = gtk_button_new(), *line = hbox(10); add_class(b, "cardbtn");
|
GtkWidget *b = gtk_button_new(), *line = hbox(10); add_class(b, "cardbtn");
|
||||||
gtk_box_pack_start(GTK_BOX(line), label(names[i], "devname"), TRUE, TRUE, 0);
|
gtk_box_pack_start(GTK_BOX(line), label(names[i], "devname"), TRUE, TRUE, 0);
|
||||||
gtk_box_pack_end(GTK_BOX(line), label("›", "hint"), FALSE, FALSE, 0);
|
gtk_box_pack_end(GTK_BOX(line), label("›", "hint"), FALSE, FALSE, 0);
|
||||||
@@ -581,6 +590,8 @@ static gboolean on_delete(GtkWidget *w, GdkEvent *e, gpointer d) { (void)w; (voi
|
|||||||
static void *run(void *arg) {
|
static void *run(void *arg) {
|
||||||
(void)arg;
|
(void)arg;
|
||||||
int ok = gtk_init_check(NULL, NULL);
|
int ok = gtk_init_check(NULL, NULL);
|
||||||
|
// The CSS hard-codes a light palette; a dark system theme would turn unstyled text white on white (#43).
|
||||||
|
if (ok) g_object_set(gtk_settings_get_default(), "gtk-theme-name", "Adwaita", "gtk-application-prefer-dark-theme", FALSE, NULL);
|
||||||
if (ok) {
|
if (ok) {
|
||||||
GtkCssProvider *css = gtk_css_provider_new();
|
GtkCssProvider *css = gtk_css_provider_new();
|
||||||
gtk_css_provider_load_from_data(css, CSS, -1, NULL);
|
gtk_css_provider_load_from_data(css, CSS, -1, NULL);
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 161 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 255 KiB |
@@ -0,0 +1,20 @@
|
|||||||
|
控制端:GNOME Wayland 下剪贴板不再让 Dock 图标跳动。/ Viewer: clipboard no longer makes GNOME Wayland Dock icons jump.
|
||||||
|
|
||||||
|
### 控制端修复 / Viewer — fixed
|
||||||
|
- **GNOME Wayland 剪贴板与 Dock 跳动**(#37,感谢 @wanglz111,#41):之前每 500 ms 调用一次 `wl-paste`,在缺少 data-control 的 GNOME 上
|
||||||
|
每次都会创建临时窗口,导致 Dock 图标持续跳动。现在桌面窗口直接通过 SDL 读写文本剪贴板,不再需要 `wl-clipboard` / `xclip`。
|
||||||
|
只在桌面窗口获得焦点时同步,仍保留 30 KiB 上限、`UU_VIEWER_CLIPBOARD=0` 关闭开关和原有协议。
|
||||||
|
早期版本已由报告者在 GNOME Wayland 实机确认 Dock 不再跳动;⚠️ 最终的焦点门控版本只有自动化测试,尚未重新实机验收。
|
||||||
|
Clipboard now goes through the existing SDL window (focused only). An earlier revision was confirmed live by the reporter;
|
||||||
|
the final focus-gated revision is covered by automated tests only.
|
||||||
|
|
||||||
|
### 已知问题 / Known issues
|
||||||
|
- 剪贴板只在控制端窗口获得焦点时同步;窗口在后台时收到的被控端剪贴板变化不会写入本机。
|
||||||
|
- 剪贴板内容提供方响应很慢时,可能短暂卡住控制端窗口(SDL2 同步读取)。
|
||||||
|
- 控制端 → 官方 Windows 被控端的剪贴板:被控端确认收到文本,但未出现在其桌面剪贴板中,仍在排查;与官方 Mac 被控端的双向剪贴板未验证。
|
||||||
|
- Clipboard syncs only while the viewer window is focused; viewer → official Windows host clipboard is still unresolved.
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.3-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。主机端与 v0.2.2 相同。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
控制端:修复 FFmpeg 9 下没有画面;新增「删除设备」。/ Viewer: fix no video with FFmpeg 9; add device removal.
|
||||||
|
|
||||||
|
### 控制端修复 / Viewer — fixed
|
||||||
|
- **FFmpeg 9 下桌面没有画面**(v0.2.2、v0.2.3 的回归):为兼容 FFmpeg 4.4 改用的 `-vsync 0` 已被 FFmpeg 9 删除,解码进程一启动就退出,
|
||||||
|
所有帧都解码失败。现在启动时探测当前 ffmpeg 支持的参数:新版本用 `-fps_mode passthrough`,旧版本(如 Ubuntu 22.04 的 4.4)用 `-vsync 0`。
|
||||||
|
已在 FFmpeg 9.0.2 上连接官方 Mac 被控端实测:0 解码错误。
|
||||||
|
Fixed: with FFmpeg 9 every frame failed to decode (`-vsync` was removed). Verified against the official Mac host on FFmpeg 9.0.2.
|
||||||
|
|
||||||
|
### 控制端新增 / Viewer — added
|
||||||
|
- **删除设备**:启动窗口「更多工具 → 删除设备」(带确认),或命令行 `uuremote-viewer unbind DEVICE`,把设备从账号中移除,
|
||||||
|
与官方客户端的「删除设备」相同。命令行方式已对一台测试设备实测删除成功;⚠️ 启动窗口里的按钮尚未实机点击验收;
|
||||||
|
分享给你的设备(`--shared`)只有字符串依据,未实测。
|
||||||
|
Remove a device from the account (CLI verified live on a test device; launcher button and `--shared` not yet verified).
|
||||||
|
|
||||||
|
### 已知问题 / Known issues
|
||||||
|
- 剪贴板只在控制端窗口获得焦点时同步;控制端 → 官方 Windows 被控端的剪贴板仍在排查。
|
||||||
|
- Clipboard syncs only while the viewer window is focused; viewer → official Windows host clipboard is still unresolved.
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.4-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。主机端与 v0.2.3 相同。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
窗口颜色修复;控制端可接收官方 Mac 被控端的剪贴板。/ Window colors fixed; viewer receives the official Mac host's clipboard.
|
||||||
|
|
||||||
|
### 修复 / Fixed
|
||||||
|
- **深色系统主题下窗口文字看不见**(#43):协助窗口、控制端启动窗口和工具窗口使用固定浅色背景,但部分文字跟随系统深色主题变成了白色。
|
||||||
|
现在这些窗口固定使用浅色主题。已在虚拟机中设置深色偏好后截图确认。
|
||||||
|
GTK windows now stay on the light theme, so text is readable under dark system themes.
|
||||||
|
- **控制端 ↔ 官方 Mac 被控端剪贴板**:Mac 被控端以 `public.utf8-plain-text`(UTF-8)提供文本,而不是 Windows 的 `CF_UNICODETEXT`,
|
||||||
|
之前控制端不会请求,剪贴板始终不同步。现在两种格式都支持;主机端发给官方客户端的格式不变。
|
||||||
|
Mac → 控制端已实机验证;⚠️ 控制端 → Mac 尚未验证。
|
||||||
|
The viewer now handles the Mac host's UTF-8 text format (Mac → viewer verified live; viewer → Mac not yet verified).
|
||||||
|
|
||||||
|
### 已验证 / Verified with the official Mac host(FFmpeg 9.0.2)
|
||||||
|
- 画面 0 解码错误,键盘输入正确,文件上传/下载/列目录 sha256 一致。
|
||||||
|
|
||||||
|
### 已知问题 / Known issues
|
||||||
|
- 剪贴板只在控制端窗口获得焦点时同步;控制端 → 官方 Windows 被控端的剪贴板仍在排查。
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.5-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
控制端可打开官方 Mac 被控端的终端;输入问题诊断日志。/ Viewer terminal works with the official Mac host; input diagnostics.
|
||||||
|
|
||||||
|
### 控制端修复 / Viewer — fixed
|
||||||
|
- **连接官方 Mac 被控端的终端**:之前一连上就断开(「Terminal channel closed」)。Mac 被控端把终端的应答发在终端通道上,
|
||||||
|
控制端现在能识别。已实机验证:可打开终端并正常回显。Mac 被控端的端口映射也已实测可用。
|
||||||
|
Terminal sessions with the official Mac host now open (verified live); port mapping with it was verified too.
|
||||||
|
|
||||||
|
### 主机端诊断 / Host diagnostics(#46)
|
||||||
|
- 收到不认识的输入事件时记一条日志(只有动作名和字段名,**不含输入内容**),用于排查手机输入法打字无反应。
|
||||||
|
- 小键盘按键记录被控端当前的 NumLock 状态(只记开/关,不记按键),用于排查小键盘不出数字。
|
||||||
|
- Logs unsupported input actions (names only, never typed text) and the server's NumLock state for numpad keys.
|
||||||
|
|
||||||
|
### 其他 / Other
|
||||||
|
- README 标题与开头加入控制端介绍并放上截图(#44)。
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.6-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
+73
-12
@@ -5,11 +5,37 @@ use crate::protocol::{decode_wire,WireValue};
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
const UNICODE_TEXT:u64=13;
|
const UNICODE_TEXT:u64=13;
|
||||||
|
/// The official Mac host offers its pasteboard text as format id 0 named `public.utf8-plain-text` (observed live).
|
||||||
|
const MAC_TEXT:&str="public.utf8-plain-text";
|
||||||
|
#[derive(Clone,Copy,PartialEq,Eq,Debug)]
|
||||||
|
enum TextFormat {Windows,Mac}
|
||||||
|
impl TextFormat {
|
||||||
|
fn of(format:&[u8])->Option<Self>{
|
||||||
|
if number(format,1)==Ok(UNICODE_TEXT){return Some(Self::Windows)}
|
||||||
|
let named=|n|text_field(format,n).is_ok_and(|s|s==MAC_TEXT);
|
||||||
|
(named(2)||named(3)).then_some(Self::Mac)
|
||||||
|
}
|
||||||
|
fn id(self)->u64{match self{Self::Windows=>UNICODE_TEXT,Self::Mac=>0}}
|
||||||
|
fn name(self)->&'static str{match self{Self::Windows=>"CF_UNICODETEXT",Self::Mac=>MAC_TEXT}}
|
||||||
|
fn encode(self,text:&str)->Vec<u8>{match self{Self::Windows=>encode_windows(text),Self::Mac=>text.as_bytes().to_vec()}}
|
||||||
|
fn decode(self,data:&[u8])->Result<String,&'static str>{
|
||||||
|
match self{
|
||||||
|
Self::Windows=>decode_windows(data),
|
||||||
|
Self::Mac=>{
|
||||||
|
let data=data.strip_suffix(&[0]).unwrap_or(data);
|
||||||
|
if data.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}
|
||||||
|
let text=std::str::from_utf8(data).map_err(|_|"invalid UTF-8 clipboard text")?;
|
||||||
|
if text.contains('\0'){return Err("embedded NUL in clipboard text");}
|
||||||
|
Ok(text.to_owned())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
const BLOCK_BYTES:usize=0x20000;
|
const BLOCK_BYTES:usize=0x20000;
|
||||||
const MAX_BYTES:usize=MAX_TEXT*2+2;
|
const MAX_BYTES:usize=MAX_TEXT*2+2;
|
||||||
pub struct ResultMessages {pub messages:Vec<(u32,Vec<u8>)>,pub text:Option<String>}
|
pub struct ResultMessages {pub messages:Vec<(u32,Vec<u8>)>,pub text:Option<String>}
|
||||||
impl Default for ResultMessages {fn default()->Self{Self{messages:Vec::new(),text:None}}}
|
impl Default for ResultMessages {fn default()->Self{Self{messages:Vec::new(),text:None}}}
|
||||||
struct Pending {key:String, count:Option<usize>, blocks:BTreeMap<usize,Vec<u8>>}
|
struct Pending {key:String, format:TextFormat, count:Option<usize>, blocks:BTreeMap<usize,Vec<u8>>}
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct State {local:Option<String>, pending:Option<Pending>}
|
pub struct State {local:Option<String>, pending:Option<Pending>}
|
||||||
pub fn format_ids(rpc:&[u8])->Vec<u64>{
|
pub fn format_ids(rpc:&[u8])->Vec<u64>{
|
||||||
@@ -62,12 +88,15 @@ fn decode_windows(data:&[u8])->Result<String,&'static str>{
|
|||||||
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}Ok(text)
|
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}Ok(text)
|
||||||
}
|
}
|
||||||
impl State{
|
impl State{
|
||||||
pub fn offer(&mut self,id:u64,text:String)->Result<Vec<u8>,&'static str>{
|
pub fn offer(&mut self,id:u64,text:String)->Result<Vec<u8>,&'static str>{self.offer_formats(id,text,&[TextFormat::Windows])}
|
||||||
|
/// Viewer offers: Windows hosts pick CF_UNICODETEXT, the official Mac host its UTF-8 type.
|
||||||
|
pub fn offer_any_host(&mut self,id:u64,text:String)->Result<Vec<u8>,&'static str>{self.offer_formats(id,text,&[TextFormat::Windows,TextFormat::Mac])}
|
||||||
|
fn offer_formats(&mut self,id:u64,text:String,formats:&[TextFormat])->Result<Vec<u8>,&'static str>{
|
||||||
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}
|
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}
|
||||||
if text.contains('\0')||encode_windows(&text).len()>MAX_BYTES{return Err("clipboard encoded text exceeds limit");}
|
if text.contains('\0')||encode_windows(&text).len()>MAX_BYTES{return Err("clipboard encoded text exceeds limit");}
|
||||||
self.local=Some(text);
|
self.local=Some(text);
|
||||||
let mut format=Vec::new();int(1,UNICODE_TEXT,&mut format);string(2,"CF_UNICODETEXT",&mut format);
|
let mut list=Vec::new();
|
||||||
let mut list=Vec::new();nested(1,&format,&mut list);
|
for kind in formats {let mut format=Vec::new();int(1,kind.id(),&mut format);string(2,kind.name(),&mut format);nested(1,&format,&mut list);}
|
||||||
Ok(request(id,1,&list))
|
Ok(request(id,1,&list))
|
||||||
}
|
}
|
||||||
pub fn request(&mut self,rpc:&[u8],next:&mut impl FnMut()->u64)->Result<ResultMessages,&'static str>{
|
pub fn request(&mut self,rpc:&[u8],next:&mut impl FnMut()->u64)->Result<ResultMessages,&'static str>{
|
||||||
@@ -78,22 +107,30 @@ impl State{
|
|||||||
if let Some(list)=bytes(clip,1)?{
|
if let Some(list)=bytes(clip,1)?{
|
||||||
out.messages.push((22,response(h,1,&[])));
|
out.messages.push((22,response(h,1,&[])));
|
||||||
let fields=decode_wire(list).map_err(|_|"invalid clipboard format list")?;
|
let fields=decode_wire(list).map_err(|_|"invalid clipboard format list")?;
|
||||||
let supports_text=fields.iter().filter(|f|f.number==1).any(|f|match f.value{WireValue::Bytes(format)=>number(format,1)==Ok(UNICODE_TEXT),_=>false});
|
let offered:Vec<TextFormat>=fields.iter().filter(|f|f.number==1).filter_map(|f|match f.value{WireValue::Bytes(format)=>TextFormat::of(format),_=>None}).collect();
|
||||||
|
let chosen=if offered.contains(&TextFormat::Windows){Some(TextFormat::Windows)}else{offered.first().copied()};
|
||||||
|
let supports_text=chosen.is_some();
|
||||||
self.pending=None;
|
self.pending=None;
|
||||||
if supports_text{
|
if !supports_text{
|
||||||
|
// Format ids/names only (never data), to learn non-Windows peers' text formats.
|
||||||
|
let formats:Vec<(u64,String)>=fields.iter().filter(|f|f.number==1).filter_map(|f|match f.value{WireValue::Bytes(format)=>Some(format),_=>None})
|
||||||
|
.take(8).map(|format|(number(format,1).unwrap_or(u64::MAX),decode_wire(format).ok().and_then(|x|x.into_iter().find_map(|y|match (y.number,y.value){(n,WireValue::Bytes(s)) if n!=1=>std::str::from_utf8(s).ok().map(|s|s.chars().take(48).collect()),_=>None})).unwrap_or_default())).collect();
|
||||||
|
log::info!("Clipboard offer without a supported text format: formats={formats:?}");
|
||||||
|
}
|
||||||
|
if let Some(format)=chosen{
|
||||||
let id=next();
|
let id=next();
|
||||||
let epoch=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() as u32;
|
let epoch=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() as u32;
|
||||||
let key=format!("{epoch:08x}-0000-4000-8000-{:012x}",id & 0xffffffffffff);
|
let key=format!("{epoch:08x}-0000-4000-8000-{:012x}",id & 0xffffffffffff);
|
||||||
let mut ask=Vec::new();int(1,UNICODE_TEXT,&mut ask);string(2,&key,&mut ask);string(3,"CF_UNICODETEXT",&mut ask);
|
let mut ask=Vec::new();int(1,format.id(),&mut ask);string(2,&key,&mut ask);string(3,format.name(),&mut ask);
|
||||||
self.pending=Some(Pending{key,count:None,blocks:BTreeMap::new()});
|
self.pending=Some(Pending{key,format,count:None,blocks:BTreeMap::new()});
|
||||||
out.messages.push((21,request(id,2,&ask)));
|
out.messages.push((21,request(id,2,&ask)));
|
||||||
}
|
}
|
||||||
}else if let Some(ask)=bytes(clip,2)?{
|
}else if let Some(ask)=bytes(clip,2)?{
|
||||||
let key=text_field(ask,2)?;
|
let key=text_field(ask,2)?;
|
||||||
if key.len()>256||key.is_empty(){return Err("invalid clipboard block key");}
|
if key.len()>256||key.is_empty(){return Err("invalid clipboard block key");}
|
||||||
let available=number(ask,1)?==UNICODE_TEXT&&self.local.is_some();
|
let format=if number(ask,1)?==UNICODE_TEXT{Some(TextFormat::Windows)}else if text_field(ask,3).is_ok_and(|s|s==MAC_TEXT){Some(TextFormat::Mac)}else{None};
|
||||||
let mut confirm=Vec::new();int(1,if available{1}else{2},&mut confirm);string(2,key,&mut confirm);
|
let data=format.zip(self.local.as_ref()).map(|(format,text)|format.encode(text));
|
||||||
let data=if available{Some(encode_windows(self.local.as_ref().unwrap()))}else{None};
|
let mut confirm=Vec::new();int(1,if data.is_some(){1}else{2},&mut confirm);string(2,key,&mut confirm);
|
||||||
if let Some(data)=&data{int(3,data.chunks(BLOCK_BYTES).len() as u64,&mut confirm);}
|
if let Some(data)=&data{int(3,data.chunks(BLOCK_BYTES).len() as u64,&mut confirm);}
|
||||||
out.messages.push((22,response(h,2,&confirm)));
|
out.messages.push((22,response(h,2,&confirm)));
|
||||||
if let Some(data)=data{
|
if let Some(data)=data{
|
||||||
@@ -144,13 +181,37 @@ impl State{
|
|||||||
else if (1..=count).all(|i|pending.blocks.contains_key(&i)){1}
|
else if (1..=count).all(|i|pending.blocks.contains_key(&i)){1}
|
||||||
else{return Ok(None);};
|
else{return Ok(None);};
|
||||||
let data:Vec<u8>=(first..first+count).flat_map(|i|pending.blocks[&i].iter().copied()).collect();
|
let data:Vec<u8>=(first..first+count).flat_map(|i|pending.blocks[&i].iter().copied()).collect();
|
||||||
self.pending=None;decode_windows(&data).map(Some)
|
let format=pending.format;self.pending=None;format.decode(&data).map(Some)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests{
|
mod tests{
|
||||||
use super::*;
|
use super::*;
|
||||||
|
#[test] fn mac_utf8_text_round_trips_both_directions(){
|
||||||
|
// Mac host offer: format list {1 id 0, 2 "public.utf8-plain-text"} (observed live).
|
||||||
|
let mut mac=Vec::new();int(1,0,&mut mac);string(2,MAC_TEXT,&mut mac);
|
||||||
|
let mut list=Vec::new();nested(1,&mac,&mut list);
|
||||||
|
let mut viewer=State::default();let mut id=200;let mut next=||{id+=1;id};
|
||||||
|
let asked=viewer.request(&request(7,1,&list),&mut next).unwrap();
|
||||||
|
assert_eq!(asked.messages.len(),2);
|
||||||
|
let ask_rpc=&asked.messages[1].1;let clip=bytes(ask_rpc,9).unwrap().unwrap();let ask=bytes(clip,2).unwrap().unwrap();
|
||||||
|
assert_eq!(number(ask,1),Ok(0));assert_eq!(text_field(ask,3),Ok(MAC_TEXT));
|
||||||
|
let key=text_field(ask,2).unwrap().to_owned();
|
||||||
|
let mut confirm=Vec::new();int(1,1,&mut confirm);string(2,&key,&mut confirm);int(3,1,&mut confirm);
|
||||||
|
assert_eq!(viewer.response(&response(header(ask_rpc).unwrap(),2,&confirm)).unwrap(),None);
|
||||||
|
let mut block=Vec::new();string(1,&key,&mut block);int(2,0,&mut block);nested(3,"中文 text\n".as_bytes(),&mut block);
|
||||||
|
assert_eq!(viewer.request(&request(8,3,&block),&mut next).unwrap().text.as_deref(),Some("中文 text\n"));
|
||||||
|
// Viewer offer lists both formats; a Mac-style ask gets UTF-8 bytes back.
|
||||||
|
let offer=viewer.offer_any_host(9,"hi".into()).unwrap();
|
||||||
|
assert_eq!(format_ids(&offer),vec![13,0]);
|
||||||
|
let mut ask=Vec::new();int(1,0,&mut ask);string(2,"k",&mut ask);string(3,MAC_TEXT,&mut ask);
|
||||||
|
let out=viewer.request(&request(10,2,&ask),&mut next).unwrap();
|
||||||
|
let data=bytes(bytes(bytes(&out.messages[1].1,9).unwrap().unwrap(),3).unwrap().unwrap(),3).unwrap().unwrap();
|
||||||
|
assert_eq!(data,b"hi");
|
||||||
|
// Host-side offers are unchanged: CF_UNICODETEXT only.
|
||||||
|
assert_eq!(format_ids(&State::default().offer(1,"hi".into()).unwrap()),vec![13]);
|
||||||
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn desktop_clipboard_negotiates_and_buffers_unicode_until_confirmation(){
|
fn desktop_clipboard_negotiates_and_buffers_unicode_until_confirmation(){
|
||||||
let text="UU-test-中文🙂\n".repeat(900);
|
let text="UU-test-中文🙂\n".repeat(900);
|
||||||
|
|||||||
@@ -248,6 +248,14 @@ impl InputInjector {
|
|||||||
if AUDIT.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 8 {
|
if AUDIT.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 8 {
|
||||||
log::info!("Desktop keyboard injection outcome: result={result}");
|
log::info!("Desktop keyboard injection outcome: result={result}");
|
||||||
}
|
}
|
||||||
|
// KP_0..KP_9 type digits only with NumLock on (#46); record the server's NumLock state, not the key.
|
||||||
|
static NUMPAD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||||
|
if (0x60..=0x6f).contains(&key) && is_press && self.backend==crate::desktop_backend::DesktopBackend::X11
|
||||||
|
&& NUMPAD.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 4 {
|
||||||
|
let (mut x,mut y,mut mask)=(0,0,0u32);
|
||||||
|
let state=unsafe { x11_pointer_state(&mut x,&mut y,&mut mask) };
|
||||||
|
log::info!("Desktop numpad key: result={result} numlock={}", state==0 && mask & 0x10 != 0);
|
||||||
|
}
|
||||||
if result == 0 {
|
if result == 0 {
|
||||||
let mut held=self.held.lock().unwrap();
|
let mut held=self.held.lock().unwrap();
|
||||||
if is_press {held.keys.insert(symbol);} else {held.keys.remove(&symbol);}
|
if is_press {held.keys.insert(symbol);} else {held.keys.remove(&symbol);}
|
||||||
|
|||||||
+31
-4
@@ -42,6 +42,18 @@ impl std::fmt::Display for Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Mirrors Windows 0x140b77cd0 / 0x140b7a6d0, not host RoomData.
|
// Mirrors Windows 0x140b77cd0 / 0x140b7a6d0, not host RoomData.
|
||||||
|
/// Treat the caller's device string as one opaque path segment, never a URL/query.
|
||||||
|
fn path_segment(device: &str) -> Result<String, Error> {
|
||||||
|
if device.is_empty() || device=="." || device==".." { return Err(Error::InvalidDevice); }
|
||||||
|
Ok(device.bytes().map(|b|if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {(b as char).to_string()}else{format!("%{b:02X}")}).collect())
|
||||||
|
}
|
||||||
|
fn parse_ack(status: u16, body: Value) -> Result<(), Error> {
|
||||||
|
let code = body.get("code").and_then(Value::as_i64).unwrap_or(-1);
|
||||||
|
if code == 1120 { return Err(Error::AuthenticationExpired); }
|
||||||
|
if status == 200 && code == 0 { return Ok(()); }
|
||||||
|
let msg = body.get("msg").and_then(Value::as_str).unwrap_or("").chars().take(120).collect();
|
||||||
|
Err(Error::Api(i32::try_from(code).unwrap_or(-1), msg))
|
||||||
|
}
|
||||||
pub fn parse_join(status: u16, value: Value) -> Result<JoinData, Error> {
|
pub fn parse_join(status: u16, value: Value) -> Result<JoinData, Error> {
|
||||||
let code = value.get("code").and_then(Value::as_i64).and_then(|v| i32::try_from(v).ok()).ok_or(Error::InvalidResponse)?;
|
let code = value.get("code").and_then(Value::as_i64).and_then(|v| i32::try_from(v).ok()).ok_or(Error::InvalidResponse)?;
|
||||||
let msg = value.get("msg").and_then(Value::as_str).ok_or(Error::InvalidResponse)?.chars().take(120).collect::<String>();
|
let msg = value.get("msg").and_then(Value::as_str).ok_or(Error::InvalidResponse)?.chars().take(120).collect::<String>();
|
||||||
@@ -110,10 +122,7 @@ impl Api {
|
|||||||
Ok((status, response.json().await.map_err(|_| Error::InvalidResponse)?))
|
Ok((status, response.json().await.map_err(|_| Error::InvalidResponse)?))
|
||||||
}
|
}
|
||||||
pub async fn join(&self, device: &str, force_join: bool, retry: bool) -> Result<JoinData, Error> {
|
pub async fn join(&self, device: &str, force_join: bool, retry: bool) -> Result<JoinData, Error> {
|
||||||
// Treat the caller's device string as one opaque path segment, never a URL/query.
|
let path = format!("/api/v1/room/join/by_device/{}", path_segment(device)?);
|
||||||
if device.is_empty() || device=="." || device==".." { return Err(Error::InvalidDevice); }
|
|
||||||
let encoded=device.bytes().map(|b|if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {(b as char).to_string()}else{format!("%{b:02X}")}).collect::<String>();
|
|
||||||
let path = format!("/api/v1/room/join/by_device/{encoded}");
|
|
||||||
let mut retries = 0;
|
let mut retries = 0;
|
||||||
loop {
|
loop {
|
||||||
let result = match self.request(reqwest::Method::POST, &path, Some(json!({"force_join":force_join}))).await {
|
let result = match self.request(reqwest::Method::POST, &path, Some(json!({"force_join":force_join}))).await {
|
||||||
@@ -143,6 +152,15 @@ impl Api {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// Remove a device from the account (official 「删除设备」). Paths from the Windows host strings
|
||||||
|
/// `/api/v1/device/%s/unbind` and `/api/v1/device/share/%s/unbind` (own vs. shared-with-me device).
|
||||||
|
/// POST verified live against an own device; the shared-device path is from strings only.
|
||||||
|
pub async fn unbind(&self, device: &str, shared: bool) -> Result<(), Error> {
|
||||||
|
let segment = path_segment(device)?;
|
||||||
|
let path = if shared { format!("/api/v1/device/share/{segment}/unbind") } else { format!("/api/v1/device/{segment}/unbind") };
|
||||||
|
let (status, body) = self.request(reqwest::Method::POST, &path, None).await?;
|
||||||
|
parse_ack(status, body)
|
||||||
|
}
|
||||||
/// Structure-only probe of the device list (status, JSON keys/types/lengths, never values).
|
/// Structure-only probe of the device list (status, JSON keys/types/lengths, never values).
|
||||||
pub async fn devices_shape(&self, method: reqwest::Method) -> Result<String, Error> {
|
pub async fn devices_shape(&self, method: reqwest::Method) -> Result<String, Error> {
|
||||||
let path = "/api/v1/device/list";
|
let path = "/api/v1/device/list";
|
||||||
@@ -188,6 +206,15 @@ impl Api {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#[test] fn unbind_ack_and_device_segment(){
|
||||||
|
use super::*;
|
||||||
|
assert_eq!(parse_ack(200,json!({"code":0,"msg":"ok"})),Ok(()));
|
||||||
|
assert_eq!(parse_ack(422,json!({"code":1120})),Err(Error::AuthenticationExpired));
|
||||||
|
assert_eq!(parse_ack(200,json!({"code":5003,"msg":"no such device"})),Err(Error::Api(5003,"no such device".into())));
|
||||||
|
assert_eq!(parse_ack(404,json!({})),Err(Error::Api(-1,String::new())));
|
||||||
|
assert_eq!(path_segment("a/b?c").unwrap(),"a%2Fb%3Fc");
|
||||||
|
for bad in ["",".",".."]{assert_eq!(path_segment(bad),Err(Error::InvalidDevice));}
|
||||||
|
}
|
||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
fn target_platform_matches_only_the_selected_device(){
|
fn target_platform_matches_only_the_selected_device(){
|
||||||
|
|||||||
+97
-12
@@ -12,7 +12,19 @@ const POLL:Duration=Duration::from_millis(500);
|
|||||||
static WARNED:AtomicBool=AtomicBool::new(false);
|
static WARNED:AtomicBool=AtomicBool::new(false);
|
||||||
fn warn(){if !WARNED.swap(true,Ordering::Relaxed){log::warn!("Viewer text clipboard unavailable; synchronization disabled");}}
|
fn warn(){if !WARNED.swap(true,Ordering::Relaxed){log::warn!("Viewer text clipboard unavailable; synchronization disabled");}}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Backend {read:PathBuf,read_args:Vec<&'static str>,write:PathBuf,write_args:Vec<&'static str>}
|
struct CommandBackend {read:PathBuf,read_args:Vec<&'static str>,write:PathBuf,write_args:Vec<&'static str>}
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum Backend {
|
||||||
|
Command(CommandBackend),
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
Sdl(mpsc::Sender<ClipboardRequest>),
|
||||||
|
}
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
pub enum ClipboardRequest {
|
||||||
|
Read(tokio::sync::oneshot::Sender<Result<Option<String>,()>>),
|
||||||
|
// false means the unfocused window skipped the write.
|
||||||
|
Write(String,tokio::sync::oneshot::Sender<Result<bool,()>>),
|
||||||
|
}
|
||||||
fn executable(name:&str)->Option<PathBuf>{
|
fn executable(name:&str)->Option<PathBuf>{
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
std::env::var_os("PATH").and_then(|p|std::env::split_paths(&p).map(|d|d.join(name))
|
std::env::var_os("PATH").and_then(|p|std::env::split_paths(&p).map(|d|d.join(name))
|
||||||
@@ -23,9 +35,38 @@ impl Backend {
|
|||||||
if std::env::var("UU_VIEWER_CLIPBOARD").as_deref()==Ok("0"){return None}
|
if std::env::var("UU_VIEWER_CLIPBOARD").as_deref()==Ok("0"){return None}
|
||||||
// Unit sessions must never inspect or change the developer's real clipboard.
|
// Unit sessions must never inspect or change the developer's real clipboard.
|
||||||
if !cfg!(target_os="linux") || cfg!(test){return None}
|
if !cfg!(target_os="linux") || cfg!(test){return None}
|
||||||
let selected=Self::select(std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v|!v.is_empty()),executable);
|
let selected=CommandBackend::select(std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v|!v.is_empty()),executable).map(Self::Command);
|
||||||
if selected.is_none(){warn();}selected
|
if selected.is_none(){warn();}selected
|
||||||
}
|
}
|
||||||
|
async fn read(&self)->Result<Option<String>,()>{
|
||||||
|
match self {
|
||||||
|
Self::Command(backend)=>backend.read().await,
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
Self::Sdl(tx)=>{
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tokio::time::timeout(Duration::from_secs(2),async {
|
||||||
|
tx.send(ClipboardRequest::Read(reply)).await.map_err(|_|())?;
|
||||||
|
rx.await.map_err(|_|())?
|
||||||
|
}).await.map_err(|_|())?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn write(&self,value:&str)->Result<bool,()>{
|
||||||
|
if value.len()>MAX_TEXT || value.contains('\0'){return Err(())}
|
||||||
|
match self {
|
||||||
|
Self::Command(backend)=>backend.write(value).await.map(|()|true),
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
Self::Sdl(tx)=>{
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tokio::time::timeout(Duration::from_secs(2),async {
|
||||||
|
tx.send(ClipboardRequest::Write(value.into(),reply)).await.map_err(|_|())?;
|
||||||
|
rx.await.map_err(|_|())?
|
||||||
|
}).await.map_err(|_|())?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl CommandBackend {
|
||||||
fn select(wayland:bool,find:impl Fn(&str)->Option<PathBuf>)->Option<Self>{
|
fn select(wayland:bool,find:impl Fn(&str)->Option<PathBuf>)->Option<Self>{
|
||||||
let selected=if wayland{
|
let selected=if wayland{
|
||||||
find("wl-paste").zip(find("wl-copy")).map(|(read,write)|Self{read,write,read_args:vec!["--no-newline","--type","text"],write_args:vec!["--type","text/plain;charset=utf-8"]})
|
find("wl-paste").zip(find("wl-copy")).map(|(read,write)|Self{read,write,read_args:vec!["--no-newline","--type","text"],write_args:vec!["--type","text/plain;charset=utf-8"]})
|
||||||
@@ -45,7 +86,6 @@ impl Backend {
|
|||||||
tokio::time::timeout(Duration::from_secs(2),operation).await.map_err(|_|())?
|
tokio::time::timeout(Duration::from_secs(2),operation).await.map_err(|_|())?
|
||||||
}
|
}
|
||||||
async fn write(&self,value:&str)->Result<(),()>{
|
async fn write(&self,value:&str)->Result<(),()>{
|
||||||
if value.len()>MAX_TEXT{return Err(())}
|
|
||||||
let mut child=tokio::process::Command::new(&self.write).args(&self.write_args).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).spawn().map_err(|_|())?;
|
let mut child=tokio::process::Command::new(&self.write).args(&self.write_args).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).spawn().map_err(|_|())?;
|
||||||
let operation=async{
|
let operation=async{
|
||||||
let mut stdin=child.stdin.take().ok_or(())?;stdin.write_all(value.as_bytes()).await.map_err(|_|())?;drop(stdin);
|
let mut stdin=child.stdin.take().ok_or(())?;stdin.write_all(value.as_bytes()).await.map_err(|_|())?;drop(stdin);
|
||||||
@@ -58,9 +98,11 @@ impl Backend {
|
|||||||
struct SyncState {last:Option<String>,assembly:text::Assembly,rich:rich::State,seq:u64}
|
struct SyncState {last:Option<String>,assembly:text::Assembly,rich:rich::State,seq:u64}
|
||||||
impl SyncState {
|
impl SyncState {
|
||||||
async fn apply(&mut self,backend:&Backend,value:String)->Result<(),()>{
|
async fn apply(&mut self,backend:&Backend,value:String)->Result<(),()>{
|
||||||
backend.write(&value).await?;
|
if backend.write(&value).await? {
|
||||||
log::info!("Viewer remote clipboard applied: bytes={}",value.len());
|
log::info!("Viewer remote clipboard applied: bytes={}",value.len());
|
||||||
self.last=Some(value);Ok(())
|
self.last=Some(value);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
fn next(&mut self)->u64{self.seq=self.seq.wrapping_add(1).max(100);self.seq}
|
fn next(&mut self)->u64{self.seq=self.seq.wrapping_add(1).max(100);self.seq}
|
||||||
/// Two requests per change: the rich format-list offer (this project's host asks for the data) and
|
/// Two requests per change: the rich format-list offer (this project's host asks for the data) and
|
||||||
@@ -69,7 +111,7 @@ impl SyncState {
|
|||||||
/// ignores the other form.
|
/// ignores the other form.
|
||||||
fn local(&mut self,value:String)->Result<Option<Vec<Vec<u8>>>,&'static str>{
|
fn local(&mut self,value:String)->Result<Option<Vec<Vec<u8>>>,&'static str>{
|
||||||
if self.last.as_ref()==Some(&value){return Ok(None)}
|
if self.last.as_ref()==Some(&value){return Ok(None)}
|
||||||
let id=self.next();let payload=self.rich.offer(id,value.clone())?;
|
let id=self.next();let payload=self.rich.offer_any_host(id,value.clone())?;
|
||||||
let rich=wire::envelope(self.next(),21,&payload);
|
let rich=wire::envelope(self.next(),21,&payload);
|
||||||
let text=wire::envelope(self.next(),21,&crate::clipboard_protocol::text_request(self.next(),&value));
|
let text=wire::envelope(self.next(),21,&crate::clipboard_protocol::text_request(self.next(),&value));
|
||||||
self.last=Some(value);Ok(Some(vec![rich,text]))
|
self.last=Some(value);Ok(Some(vec![rich,text]))
|
||||||
@@ -102,19 +144,24 @@ impl SyncState {
|
|||||||
_=>{},
|
_=>{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if value.as_ref().is_some_and(|text|text.contains('\0')){return Err("clipboard text contains NUL")}
|
||||||
Ok((replies,value))
|
Ok((replies,value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async fn send(channel:&RTCDataChannel,message:Vec<u8>)->Result<(),()>{
|
async fn send(channel:&RTCDataChannel,message:Vec<u8>)->Result<(),()>{
|
||||||
tokio::time::timeout(Duration::from_secs(2),channel.send(&bytes::Bytes::from(message))).await.map_err(|_|())?.map_err(|_|())?;Ok(())
|
tokio::time::timeout(Duration::from_secs(2),channel.send(&bytes::Bytes::from(message))).await.map_err(|_|())?.map_err(|_|())?;Ok(())
|
||||||
}
|
}
|
||||||
pub fn available()->bool{Backend::detect().is_some()}
|
|
||||||
pub struct Bridge {backend:Option<Backend>,pub enabled:bool,tx:Option<mpsc::Sender<Vec<u8>>>,task:Option<tokio::task::JoinHandle<()>>}
|
pub struct Bridge {backend:Option<Backend>,pub enabled:bool,tx:Option<mpsc::Sender<Vec<u8>>>,task:Option<tokio::task::JoinHandle<()>>}
|
||||||
impl Bridge {
|
impl Bridge {
|
||||||
pub fn new(desktop:bool)->Self{
|
pub fn new(desktop:bool)->Self{
|
||||||
let backend=if desktop{Backend::detect()}else{None};let enabled=backend.is_some();
|
let backend=if desktop{Backend::detect()}else{None};let enabled=backend.is_some();
|
||||||
Self{backend,enabled,tx:None,task:None}
|
Self{backend,enabled,tx:None,task:None}
|
||||||
}
|
}
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
pub fn sdl(tx:mpsc::Sender<ClipboardRequest>)->Self{
|
||||||
|
let backend=(std::env::var("UU_VIEWER_CLIPBOARD").as_deref()!=Ok("0")).then_some(Backend::Sdl(tx));
|
||||||
|
Self{enabled:backend.is_some(),backend,tx:None,task:None}
|
||||||
|
}
|
||||||
pub fn start(&mut self,channel:&Arc<RTCDataChannel>,control:&Arc<RTCDataChannel>,observed:Arc<Observed>){
|
pub fn start(&mut self,channel:&Arc<RTCDataChannel>,control:&Arc<RTCDataChannel>,observed:Arc<Observed>){
|
||||||
let Some(backend)=self.backend.take() else{return};
|
let Some(backend)=self.backend.take() else{return};
|
||||||
let (tx,mut rx)=mpsc::channel::<Vec<u8>>(16);self.tx=Some(tx);
|
let (tx,mut rx)=mpsc::channel::<Vec<u8>>(16);self.tx=Some(tx);
|
||||||
@@ -173,8 +220,22 @@ impl Drop for Bridge{fn drop(&mut self){self.stop();}}
|
|||||||
|
|
||||||
#[cfg(test)] mod tests {
|
#[cfg(test)] mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
#[tokio::test] async fn sdl_backend_requests_and_invalid_text(){
|
||||||
|
let(tx,mut rx)=mpsc::channel(8);let backend=Backend::Sdl(tx);
|
||||||
|
let ui=tokio::spawn(async move{
|
||||||
|
let Some(ClipboardRequest::Write(text,reply))=rx.recv().await else{panic!()};
|
||||||
|
assert_eq!(text,"text\n");reply.send(Ok(true)).unwrap();
|
||||||
|
let Some(ClipboardRequest::Read(reply))=rx.recv().await else{panic!()};
|
||||||
|
reply.send(Ok(Some("text\n".into()))).unwrap();
|
||||||
|
});
|
||||||
|
assert!(backend.write("nul\0text").await.is_err());
|
||||||
|
assert!(backend.write(&"a".repeat(MAX_TEXT+1)).await.is_err());
|
||||||
|
backend.write("text\n").await.unwrap();assert_eq!(backend.read().await.unwrap().as_deref(),Some("text\n"));
|
||||||
|
ui.await.unwrap();assert!(backend.read().await.is_err());
|
||||||
|
}
|
||||||
#[test] fn backend_priority_requires_a_complete_wayland_pair_and_falls_back(){
|
#[test] fn backend_priority_requires_a_complete_wayland_pair_and_falls_back(){
|
||||||
let select=|wayland,names:&[&str]|Backend::select(wayland,|n|names.contains(&n).then(||PathBuf::from(n)));
|
let select=|wayland,names:&[&str]|CommandBackend::select(wayland,|n|names.contains(&n).then(||PathBuf::from(n)));
|
||||||
let all=["wl-copy","wl-paste","xclip","xsel"];
|
let all=["wl-copy","wl-paste","xclip","xsel"];
|
||||||
assert_eq!(select(true,&all).unwrap().write,PathBuf::from("wl-copy"));
|
assert_eq!(select(true,&all).unwrap().write,PathBuf::from("wl-copy"));
|
||||||
assert_eq!(select(false,&all).unwrap().write,PathBuf::from("xclip"));
|
assert_eq!(select(false,&all).unwrap().write,PathBuf::from("xclip"));
|
||||||
@@ -182,6 +243,17 @@ impl Drop for Bridge{fn drop(&mut self){self.stop();}}
|
|||||||
assert_eq!(select(true,&["xsel"]).unwrap().write,PathBuf::from("xsel"));
|
assert_eq!(select(true,&["xsel"]).unwrap().write,PathBuf::from("xsel"));
|
||||||
assert!(select(true,&[]).is_none());
|
assert!(select(true,&[]).is_none());
|
||||||
}
|
}
|
||||||
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
#[tokio::test] async fn unfocused_write_does_not_mark_remote_text_as_applied(){
|
||||||
|
let(tx,mut rx)=mpsc::channel(8);let backend=Backend::Sdl(tx);
|
||||||
|
let ui=tokio::spawn(async move{
|
||||||
|
let Some(ClipboardRequest::Write(_,reply))=rx.recv().await else{panic!()};
|
||||||
|
reply.send(Ok(false)).unwrap();
|
||||||
|
});
|
||||||
|
let mut state=SyncState::default();state.last=Some("local".into());
|
||||||
|
state.apply(&backend,"remote".into()).await.unwrap();
|
||||||
|
assert_eq!(state.last.as_deref(),Some("local"));ui.await.unwrap();
|
||||||
|
}
|
||||||
#[test] fn limits_match_host_and_unchanged_or_remote_text_is_not_reoffered(){
|
#[test] fn limits_match_host_and_unchanged_or_remote_text_is_not_reoffered(){
|
||||||
assert!(include_str!("../clipboard.rs").contains("pub const MAX_TEXT: usize = 30 * 1024;"));
|
assert!(include_str!("../clipboard.rs").contains("pub const MAX_TEXT: usize = 30 * 1024;"));
|
||||||
assert!(POLL>=Duration::from_millis(500));
|
assert!(POLL>=Duration::from_millis(500));
|
||||||
@@ -212,6 +284,15 @@ impl Drop for Bridge{fn drop(&mut self){self.stop();}}
|
|||||||
assert!(state.receive(&wire::envelope(1,17,&[18,1,255])).is_err());
|
assert!(state.receive(&wire::envelope(1,17,&[18,1,255])).is_err());
|
||||||
assert!(state.receive(&wire::envelope(1,17,&text::encode(1,&"a".repeat(MAX_TEXT+1),false))).is_err());
|
assert!(state.receive(&wire::envelope(1,17,&text::encode(1,&"a".repeat(MAX_TEXT+1),false))).is_err());
|
||||||
}
|
}
|
||||||
|
#[test] fn rejected_nul_does_not_stop_later_valid_updates(){
|
||||||
|
let mut state=SyncState::default();
|
||||||
|
for kind in [17,21]{
|
||||||
|
let payload=if kind==17{text::encode(1,"nul\0text",false)}else{text::text_request(73,"nul\0text")};
|
||||||
|
assert!(state.receive(&wire::envelope(1,kind,&payload)).is_err());
|
||||||
|
let(_,value)=state.receive(&wire::envelope(2,17,&text::encode(2,"valid",false))).unwrap();
|
||||||
|
assert_eq!(value.as_deref(),Some("valid"));
|
||||||
|
}
|
||||||
|
}
|
||||||
// Match webrtc.rs: CONTROL and TEXT have separate rich States, and only TEXT has a desktop sink.
|
// Match webrtc.rs: CONTROL and TEXT have separate rich States, and only TEXT has a desktop sink.
|
||||||
fn native_host_exchange(outbound:usize,reverse:bool)->(Option<String>,bool){
|
fn native_host_exchange(outbound:usize,reverse:bool)->(Option<String>,bool){
|
||||||
let mut viewer=SyncState::default();let mut host=[rich::State::default(),rich::State::default()];let mut id=1000;
|
let mut viewer=SyncState::default();let mut host=[rich::State::default(),rich::State::default()];let mut id=1000;
|
||||||
@@ -269,9 +350,12 @@ impl Drop for Bridge{fn drop(&mut self){self.stop();}}
|
|||||||
assert!(!Bridge::new(false).enabled);assert!(!Bridge::new(true).enabled);
|
assert!(!Bridge::new(false).enabled);assert!(!Bridge::new(true).enabled);
|
||||||
let mut shape:wire::Shape=serde_json::from_str(include_str!("../../tests/fixtures/viewer/shape.json")).unwrap();
|
let mut shape:wire::Shape=serde_json::from_str(include_str!("../../tests/fixtures/viewer/shape.json")).unwrap();
|
||||||
shape.feature_flag=vec![[8,99]];
|
shape.feature_flag=vec![[8,99]];
|
||||||
let options=shape.connect_options("synthetic-device").unwrap();
|
let options=shape.connect_options("synthetic-device",false).unwrap();
|
||||||
let WireValue::Bytes(flags)=decode_wire(&options).unwrap().into_iter().find(|f|f.number==11).unwrap().value else{panic!()};
|
let WireValue::Bytes(flags)=decode_wire(&options).unwrap().into_iter().find(|f|f.number==11).unwrap().value else{panic!()};
|
||||||
assert!(!decode_wire(flags).unwrap().iter().any(|f|f.number==8));
|
assert!(!decode_wire(flags).unwrap().iter().any(|f|f.number==8));
|
||||||
|
let options=shape.connect_options("synthetic-device",true).unwrap();
|
||||||
|
let WireValue::Bytes(flags)=decode_wire(&options).unwrap().into_iter().find(|f|f.number==11).unwrap().value else{panic!()};
|
||||||
|
assert!(decode_wire(flags).unwrap().iter().any(|f|f.number==8 && f.value==WireValue::Varint(3)));
|
||||||
}
|
}
|
||||||
#[tokio::test] async fn backend_uses_stdin_preserves_text_and_bounds_reads(){
|
#[tokio::test] async fn backend_uses_stdin_preserves_text_and_bounds_reads(){
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
@@ -279,14 +363,15 @@ impl Drop for Bridge{fn drop(&mut self){self.stop();}}
|
|||||||
let script=root.join("mock");
|
let script=root.join("mock");
|
||||||
std::fs::write(&script,b"#!/bin/sh\ncd -- \"${0%/*}\" || exit 1\ncase \"$1\" in read) cat data;; write) cat > data;; esac\n").unwrap();
|
std::fs::write(&script,b"#!/bin/sh\ncd -- \"${0%/*}\" || exit 1\ncase \"$1\" in read) cat data;; write) cat > data;; esac\n").unwrap();
|
||||||
std::fs::set_permissions(&script,std::fs::Permissions::from_mode(0o700)).unwrap();
|
std::fs::set_permissions(&script,std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||||
let backend=Backend{read:script.clone(),write:script,read_args:vec!["read"],write_args:vec!["write"]};
|
let command=CommandBackend{read:script.clone(),write:script,read_args:vec!["read"],write_args:vec!["write"]};
|
||||||
|
let backend=Backend::Command(command.clone());
|
||||||
let mut state=SyncState::default();
|
let mut state=SyncState::default();
|
||||||
for value in ["中文🙂\n", "", "literal $(echo secret) `echo secret`"]{
|
for value in ["中文🙂\n", "", "literal $(echo secret) `echo secret`"]{
|
||||||
state.apply(&backend,value.into()).await.unwrap();
|
state.apply(&backend,value.into()).await.unwrap();
|
||||||
let read=backend.read().await.unwrap().unwrap();assert_eq!(read,value);
|
let read=backend.read().await.unwrap().unwrap();assert_eq!(read,value);
|
||||||
assert!(state.local(read).unwrap().is_none());
|
assert!(state.local(read).unwrap().is_none());
|
||||||
}
|
}
|
||||||
let broken=Backend{write:root.join("missing"),..backend.clone()};
|
let broken=Backend::Command(CommandBackend{write:root.join("missing"),..command});
|
||||||
let previous=state.last.clone();assert!(state.apply(&broken,"failed".into()).await.is_err());assert_eq!(state.last,previous);
|
let previous=state.last.clone();assert!(state.apply(&broken,"failed".into()).await.is_err());assert_eq!(state.last,previous);
|
||||||
std::fs::write(root.join("data"),vec![b'a';MAX_TEXT+1]).unwrap();assert!(backend.read().await.unwrap().is_none());
|
std::fs::write(root.join("data"),vec![b'a';MAX_TEXT+1]).unwrap();assert!(backend.read().await.unwrap().is_none());
|
||||||
std::fs::write(root.join("data"),[255]).unwrap();assert!(backend.read().await.unwrap().is_none());
|
std::fs::write(root.join("data"),[255]).unwrap();assert!(backend.read().await.unwrap().is_none());
|
||||||
|
|||||||
@@ -21,14 +21,14 @@ impl Cli {
|
|||||||
fn with_codec(codec:Codec,width:u32,height:u32)->Result<Self,String> {
|
fn with_codec(codec:Codec,width:u32,height:u32)->Result<Self,String> {
|
||||||
let ffmpeg=std::env::var("UU_VIEWER_FFMPEG").unwrap_or_else(|_|"ffmpeg".into());
|
let ffmpeg=std::env::var("UU_VIEWER_FFMPEG").unwrap_or_else(|_|"ffmpeg".into());
|
||||||
let filter=format!("scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2");
|
let filter=format!("scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2");
|
||||||
let mut child=Command::new(ffmpeg)
|
let passthrough=passthrough_args(&ffmpeg);
|
||||||
|
let mut child=Command::new(&ffmpeg)
|
||||||
.args(["-hide_banner","-loglevel","error","-nostdin","-threads","1","-probesize","32","-analyzeduration","0",
|
.args(["-hide_banner","-loglevel","error","-nostdin","-threads","1","-probesize","32","-analyzeduration","0",
|
||||||
"-fflags","nobuffer","-flags","low_delay","-f",codec.demuxer(),"-i","pipe:0","-an","-vf",&filter,
|
"-fflags","nobuffer","-flags","low_delay","-f",codec.demuxer(),"-i","pipe:0","-an","-vf",&filter,
|
||||||
"-pix_fmt","rgb24",
|
"-pix_fmt","rgb24",
|
||||||
// Raw H.264/H.265 carries no timestamps; constant-rate output dropped almost every frame of
|
// Raw H.264/H.265 carries no timestamps; constant-rate output dropped almost every frame of
|
||||||
// the official Mac host's stream (270 → 2). Pass frames through unchanged.
|
// the official Mac host's stream (270 → 2). Pass frames through unchanged.
|
||||||
// -vsync 0 also supports Ubuntu 22.04's FFmpeg 4.4, which lacks -fps_mode.
|
passthrough.0,passthrough.1,"-f","rawvideo","pipe:1"])
|
||||||
"-vsync","0","-f","rawvideo","pipe:1"])
|
|
||||||
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
|
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
|
||||||
.spawn().map_err(|e|format!("Start ffmpeg decoder: {e}"))?;
|
.spawn().map_err(|e|format!("Start ffmpeg decoder: {e}"))?;
|
||||||
let input=child.stdin.take().ok_or("ffmpeg stdin missing")?;
|
let input=child.stdin.take().ok_or("ffmpeg stdin missing")?;
|
||||||
@@ -47,6 +47,23 @@ impl Cli {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// FFmpeg ≥ 5.1 has `-fps_mode`; FFmpeg 8+ removed `-vsync`, and Ubuntu 22.04's 4.4 lacks `-fps_mode`.
|
||||||
|
/// Probe once per binary with a one-frame null run instead of parsing version strings.
|
||||||
|
fn passthrough_args(ffmpeg:&str)->(&'static str,&'static str) {
|
||||||
|
static CACHE:std::sync::Mutex<Vec<(String,bool)>>=std::sync::Mutex::new(Vec::new());
|
||||||
|
let mut cache=CACHE.lock().unwrap_or_else(|e|e.into_inner());
|
||||||
|
let fps_mode=match cache.iter().find(|(name,_)|name==ffmpeg) {
|
||||||
|
Some(&(_,known))=>known,
|
||||||
|
None=>{
|
||||||
|
let ok=Command::new(ffmpeg).args(["-hide_banner","-loglevel","quiet","-nostdin","-f","lavfi","-i","color=s=16x16:d=0.04",
|
||||||
|
"-fps_mode","passthrough","-f","null","-"]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())
|
||||||
|
.status().is_ok_and(|s|s.success());
|
||||||
|
cache.push((ffmpeg.into(),ok));ok
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if fps_mode {("-fps_mode","passthrough")} else {("-vsync","0")}
|
||||||
|
}
|
||||||
|
|
||||||
impl Decoder for Cli {
|
impl Decoder for Cli {
|
||||||
fn set_codec(&mut self,codec:Codec)->Result<(),String>{
|
fn set_codec(&mut self,codec:Codec)->Result<(),String>{
|
||||||
if self.codec!=codec {*self=Self::with_codec(codec,self.width,self.height)?;}Ok(())
|
if self.codec!=codec {*self=Self::with_codec(codec,self.width,self.height)?;}Ok(())
|
||||||
@@ -72,6 +89,16 @@ impl Drop for Cli { fn drop(&mut self) { let _=self.child.kill(); let _=self.chi
|
|||||||
#[cfg(test)] mod tests {
|
#[cfg(test)] mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
// Six synthetic red IDRs per fixture; no captured desktop or external encoder dependency.
|
// Six synthetic red IDRs per fixture; no captured desktop or external encoder dependency.
|
||||||
|
#[cfg(unix)] #[test] fn passthrough_follows_ffmpeg_option_support(){
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let dir=std::env::temp_dir().join(format!("uu-ffprobe-{}",std::process::id()));std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
for (name,script,expected) in [("new","exit 0",("-fps_mode","passthrough")),("old","case \"$*\" in *-fps_mode*) exit 1;; esac",("-vsync","0"))]{
|
||||||
|
let path=dir.join(name);std::fs::write(&path,format!("#!/bin/sh\n{script}\n")).unwrap();
|
||||||
|
std::fs::set_permissions(&path,std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
assert_eq!(super::passthrough_args(path.to_str().unwrap()),expected);
|
||||||
|
}
|
||||||
|
std::fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
#[test] fn ffmpeg_decodes_h264_and_hevc_420_and_444_to_rgb24(){
|
#[test] fn ffmpeg_decodes_h264_and_hevc_420_and_444_to_rgb24(){
|
||||||
match Command::new("ffmpeg").arg("-version").stdout(Stdio::null()).stderr(Stdio::null()).status(){
|
match Command::new("ffmpeg").arg("-version").stdout(Stdio::null()).stderr(Stdio::null()).status(){
|
||||||
Err(e) if e.kind()==std::io::ErrorKind::NotFound=>{eprintln!("skip: ffmpeg is not on PATH");return},
|
Err(e) if e.kind()==std::io::ErrorKind::NotFound=>{eprintln!("skip: ffmpeg is not on PATH");return},
|
||||||
|
|||||||
+3
-3
@@ -63,7 +63,7 @@ fn media_engine(shape:&Shape)->Result<MediaEngine,String>{
|
|||||||
}Ok(engine)
|
}Ok(engine)
|
||||||
}
|
}
|
||||||
impl Peer {
|
impl Peer {
|
||||||
pub async fn new(config:RTCConfiguration, shape:&Shape, app_id:&str, ice_id:&str, remote_client:&str, outbound:mpsc::Sender<Value>, settings:SettingEngine)->Result<Self,String> {
|
pub async fn new(config:RTCConfiguration, shape:&Shape, app_id:&str, ice_id:&str, remote_client:&str, outbound:mpsc::Sender<Value>, settings:SettingEngine, mut clipboard:super::clipboard::Bridge)->Result<Self,String> {
|
||||||
shape.validate_session()?;
|
shape.validate_session()?;
|
||||||
let mut engine=media_engine(shape)?;
|
let mut engine=media_engine(shape)?;
|
||||||
// UU RTP metadata the official Mac viewer offers (src/rtp_metadata.rs on the host side).
|
// UU RTP metadata the official Mac viewer offers (src/rtp_metadata.rs on the host side).
|
||||||
@@ -155,7 +155,6 @@ impl Peer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut channels=Vec::new();
|
let mut channels=Vec::new();
|
||||||
let mut clipboard=super::clipboard::Bridge::new(shape.capture_type==1);
|
|
||||||
let clipboard_enabled=clipboard.enabled;
|
let clipboard_enabled=clipboard.enabled;
|
||||||
// Diagnostic: hosts may open their own channels; log the label and message count only.
|
// Diagnostic: hosts may open their own channels; log the label and message count only.
|
||||||
pc.on_data_channel(Box::new(|channel|Box::pin(async move {
|
pc.on_data_channel(Box::new(|channel|Box::pin(async move {
|
||||||
@@ -196,7 +195,8 @@ impl Peer {
|
|||||||
if state.chroma.swap(chroma,Ordering::AcqRel)!=chroma {log::info!("Viewer capture sync: chroma={chroma}");}
|
if state.chroma.swap(chroma,Ordering::AcqRel)!=chroma {log::info!("Viewer capture sync: chroma={chroma}");}
|
||||||
}
|
}
|
||||||
let count=state.control_messages.fetch_add(1,Ordering::Relaxed);
|
let count=state.control_messages.fetch_add(1,Ordering::Relaxed);
|
||||||
if wire::echo_matches(&message.data,1) {state.clipboard_supported.store(wire::echo_clipboard_supported(&message.data),Ordering::Release);state.echo_received.store(true,Ordering::Release);}
|
if wire::echo_matches(&message.data,1) {let supported=wire::echo_clipboard_supported(&message.data);
|
||||||
|
if state.clipboard_supported.swap(supported,Ordering::AcqRel)!=supported || !state.echo_received.load(Ordering::Acquire) {log::info!("Viewer echo: clipboard_supported={supported}");}state.echo_received.store(true,Ordering::Release);}
|
||||||
if let Some(request)=wire::echo_request_seq(&message.data) {
|
if let Some(request)=wire::echo_request_seq(&message.data) {
|
||||||
if let Some(control)=control_for_echo.upgrade() {let _=control.send(&bytes::Bytes::from(wire::echo_response_with_clipboard(1_000_000+request,request,clipboard_enabled))).await;}
|
if let Some(control)=control_for_echo.upgrade() {let _=control.send(&bytes::Bytes::from(wire::echo_response_with_clipboard(1_000_000+request,request,clipboard_enabled))).await;}
|
||||||
}
|
}
|
||||||
|
|||||||
+95
-3
@@ -1,18 +1,61 @@
|
|||||||
use super::{desktop::{Frame,FrameSink},input::{Input,Viewport},session::Session};
|
use super::{desktop::{Frame,FrameSink},input::{Input,Viewport},session::Session};
|
||||||
use sdl2::{event::{Event,WindowEvent},mouse::MouseButton,pixels::PixelFormatEnum,rect::Rect};
|
use sdl2::{event::{Event,WindowEvent},mouse::MouseButton,pixels::PixelFormatEnum,rect::Rect};
|
||||||
pub struct Window { canvas:sdl2::render::Canvas<sdl2::video::Window>, events:sdl2::EventPump, _sdl:sdl2::Sdl, frame:(u32,u32), focused:bool, files:bool, mac:bool }
|
pub struct Window { canvas:sdl2::render::Canvas<sdl2::video::Window>, events:sdl2::EventPump, _sdl:sdl2::Sdl, frame:(u32,u32), focused:bool, files:bool, mac:bool,
|
||||||
|
clipboard:sdl2::clipboard::ClipboardUtil, clipboard_dirty:bool, clipboard_tx:tokio::sync::mpsc::Sender<super::clipboard::ClipboardRequest>, clipboard_requests:tokio::sync::mpsc::Receiver<super::clipboard::ClipboardRequest> }
|
||||||
impl Window {
|
impl Window {
|
||||||
pub fn new()->Result<Self,String>{
|
pub fn new()->Result<Self,String>{
|
||||||
let sdl=sdl2::init()?;let video=sdl.video()?;
|
let sdl=sdl2::init()?;let video=sdl.video()?;
|
||||||
let window=video.window("Native viewer (experimental)",1280,720).position_centered().resizable().build().map_err(|_|"Window creation failed")?;
|
let window=video.window("Native viewer (experimental)",1280,720).position_centered().resizable().build().map_err(|_|"Window creation failed")?;
|
||||||
let canvas=window.into_canvas().build().map_err(|_|"Renderer creation failed")?;
|
let canvas=window.into_canvas().build().map_err(|_|"Renderer creation failed")?;
|
||||||
let events=sdl.event_pump()?;Ok(Self{canvas,events,_sdl:sdl,frame:(1920,1080),focused:true,files:false,mac:false})
|
let events=sdl.event_pump()?;let clipboard=video.clipboard();
|
||||||
|
let(clipboard_tx,clipboard_requests)=tokio::sync::mpsc::channel(16);
|
||||||
|
Ok(Self{canvas,events,_sdl:sdl,frame:(1920,1080),focused:true,files:false,mac:false,clipboard,clipboard_dirty:true,clipboard_tx,clipboard_requests})
|
||||||
}
|
}
|
||||||
|
pub fn clipboard_bridge(&self)->super::clipboard::Bridge{super::clipboard::Bridge::sdl(self.clipboard_tx.clone())}
|
||||||
pub fn set_mac(&mut self,mac:bool){self.mac=mac;}
|
pub fn set_mac(&mut self,mac:bool){self.mac=mac;}
|
||||||
fn viewport(&self)->Viewport {Viewport::fit(self.canvas.window().size(),self.frame)}
|
fn viewport(&self)->Viewport {Viewport::fit(self.canvas.window().size(),self.frame)}
|
||||||
|
fn poll_clipboard(&mut self){
|
||||||
|
// Use the existing SDL window; wl-paste creates a transient toplevel on GNOME every poll.
|
||||||
|
while let Ok(request)=self.clipboard_requests.try_recv(){
|
||||||
|
use super::clipboard::ClipboardRequest;
|
||||||
|
match request {
|
||||||
|
ClipboardRequest::Read(reply)=>{
|
||||||
|
if self.clipboard_dirty {log::debug!("Viewer clipboard read: focused={} has_text={}",self.focused,self.clipboard.has_clipboard_text());}
|
||||||
|
let result=if self.focused && std::mem::take(&mut self.clipboard_dirty) && self.clipboard.has_clipboard_text(){read_clipboard()}else{Ok(None)};
|
||||||
|
let _=reply.send(result);
|
||||||
|
},
|
||||||
|
ClipboardRequest::Write(text,reply)=>{
|
||||||
|
let result=if self.focused {
|
||||||
|
self.clipboard_dirty=true;
|
||||||
|
self.clipboard.set_clipboard_text(&text).map(|()|true).map_err(|_|())
|
||||||
|
}else{Ok(false)};
|
||||||
|
let _=reply.send(result);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn poll(&mut self,input:&mut Input)->(bool,Vec<serde_json::Value>){
|
pub fn poll(&mut self,input:&mut Input)->(bool,Vec<serde_json::Value>){
|
||||||
let viewport=self.viewport();
|
let viewport=self.viewport();
|
||||||
translate_actions(self.events.poll_iter(),input,viewport,&mut self.focused,&mut self.files)
|
let dirty=&mut self.clipboard_dirty;
|
||||||
|
let events=self.events.poll_iter().inspect(|event|{
|
||||||
|
if matches!(event,Event::ClipboardUpdate{..}|Event::Window{win_event:WindowEvent::FocusGained,..}){*dirty=true;}
|
||||||
|
});
|
||||||
|
translate_actions(events,input,viewport,&mut self.focused,&mut self.files)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn clipboard_text(bytes:&[u8])->Option<String>{
|
||||||
|
if bytes.len()>super::clipboard::MAX_TEXT{return None}
|
||||||
|
std::str::from_utf8(bytes).ok().map(str::to_owned)
|
||||||
|
}
|
||||||
|
fn read_clipboard()->Result<Option<String>,()>{
|
||||||
|
// SDL2 0.37's String wrapper panics on invalid UTF-8; validate native bytes before copying.
|
||||||
|
// SDL still acquires the selection synchronously; the bridge timeout cannot interrupt it.
|
||||||
|
unsafe{
|
||||||
|
let data=sdl2::sys::SDL_GetClipboardText();
|
||||||
|
if data.is_null(){return Err(())}
|
||||||
|
let length=libc::strnlen(data,super::clipboard::MAX_TEXT+1);
|
||||||
|
let text=clipboard_text(std::slice::from_raw_parts(data.cast::<u8>(),length));
|
||||||
|
sdl2::sys::SDL_free(data.cast());Ok(text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn translate(events:impl IntoIterator<Item=Event>,input:&mut Input,viewport:Viewport,focused:&mut bool)->(bool,Vec<serde_json::Value>){
|
fn translate(events:impl IntoIterator<Item=Event>,input:&mut Input,viewport:Viewport,focused:&mut bool)->(bool,Vec<serde_json::Value>){
|
||||||
@@ -87,6 +130,7 @@ pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super:
|
|||||||
_=tick.tick()=>{
|
_=tick.tick()=>{
|
||||||
if let Some(playback)=audio.as_mut(){if playback.pump().is_err(){log::warn!("Viewer audio playback stopped");audio=None;}}
|
if let Some(playback)=audio.as_mut(){if playback.pump().is_err(){log::warn!("Viewer audio playback stopped");audio=None;}}
|
||||||
let (quit,messages)=window.poll(&mut input);
|
let (quit,messages)=window.poll(&mut input);
|
||||||
|
window.poll_clipboard();
|
||||||
requested|=std::mem::take(&mut window.files);
|
requested|=std::mem::take(&mut window.files);
|
||||||
#[cfg(uu_gtk)] {
|
#[cfg(uu_gtk)] {
|
||||||
if files.as_ref().is_some_and(|f|f.is_finished()){
|
if files.as_ref().is_some_and(|f|f.is_finished()){
|
||||||
@@ -119,6 +163,54 @@ pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super:
|
|||||||
|
|
||||||
#[cfg(test)] mod tests {
|
#[cfg(test)] mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
// macOS: SDL video must start on the main thread, which the test harness does not use; CI runs it on Linux.
|
||||||
|
#[cfg_attr(target_os="macos",ignore)]
|
||||||
|
#[tokio::test] async fn clipboard_requests_use_existing_window(){
|
||||||
|
if std::env::var_os("UU_VIEWER_CLIPBOARD_TEST_CHILD").is_none(){
|
||||||
|
let output=std::process::Command::new(std::env::current_exe().unwrap())
|
||||||
|
.args(["--exact","viewer::sdl::tests::clipboard_requests_use_existing_window","--test-threads=1"])
|
||||||
|
.env("SDL_VIDEODRIVER","dummy").env("UU_VIEWER_CLIPBOARD_TEST_CHILD","1").output().unwrap();
|
||||||
|
assert!(output.status.success(),"{}{}",String::from_utf8_lossy(&output.stdout),String::from_utf8_lossy(&output.stderr));return
|
||||||
|
}
|
||||||
|
let mut window=Window::new().unwrap();
|
||||||
|
let tx=window.clipboard_tx.clone();
|
||||||
|
use super::super::clipboard::ClipboardRequest;
|
||||||
|
for text in ["clipboard text\n",""]{
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tx.send(ClipboardRequest::Write(text.into(),reply)).await.unwrap();
|
||||||
|
window.poll_clipboard();assert_eq!(rx.await.unwrap(),Ok(true));
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tx.send(ClipboardRequest::Read(reply)).await.unwrap();
|
||||||
|
window.poll_clipboard();assert_eq!(rx.await.unwrap(),Ok((!text.is_empty()).then(||text.to_owned())));
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tx.send(ClipboardRequest::Read(reply)).await.unwrap();
|
||||||
|
window.poll_clipboard();assert_eq!(rx.await.unwrap(),Ok(None));
|
||||||
|
}
|
||||||
|
window.focused=false;window.clipboard_dirty=true;
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tx.send(ClipboardRequest::Read(reply)).await.unwrap();
|
||||||
|
window.poll_clipboard();assert_eq!(rx.await.unwrap(),Ok(None));assert!(window.clipboard_dirty);
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tx.send(ClipboardRequest::Write("background".into(),reply)).await.unwrap();
|
||||||
|
window.poll_clipboard();assert_eq!(rx.await.unwrap(),Ok(false));
|
||||||
|
window.focused=true;
|
||||||
|
let(reply,rx)=tokio::sync::oneshot::channel();
|
||||||
|
tx.send(ClipboardRequest::Read(reply)).await.unwrap();
|
||||||
|
window.poll_clipboard();assert_eq!(rx.await.unwrap(),Ok(None));
|
||||||
|
window.clipboard_dirty=false;
|
||||||
|
window._sdl.event().unwrap().push_event(Event::Window{timestamp:0,window_id:window.canvas.window().id(),win_event:WindowEvent::FocusGained}).unwrap();
|
||||||
|
window.poll(&mut Input::new(true));assert!(window.clipboard_dirty);
|
||||||
|
let bridge=window.clipboard_bridge();assert!(bridge.enabled);
|
||||||
|
drop(window);
|
||||||
|
assert!(tx.is_closed());drop(bridge);
|
||||||
|
let window=Window::new().unwrap();assert!(window.clipboard_bridge().enabled);
|
||||||
|
}
|
||||||
|
#[test] fn clipboard_text_rejects_invalid_or_large_data_and_keeps_empty_text(){
|
||||||
|
assert_eq!(clipboard_text(b""),Some(String::new()));
|
||||||
|
assert_eq!(clipboard_text(b"text\n"),Some("text\n".into()));
|
||||||
|
assert_eq!(clipboard_text(&[255]),None);
|
||||||
|
assert_eq!(clipboard_text(&vec![b'a';super::super::clipboard::MAX_TEXT+1]),None);
|
||||||
|
}
|
||||||
#[test] fn file_shortcut_is_local_in_control_and_watch_modes(){
|
#[test] fn file_shortcut_is_local_in_control_and_watch_modes(){
|
||||||
use sdl2::keyboard::{Scancode as S,Mod as M};
|
use sdl2::keyboard::{Scancode as S,Mod as M};
|
||||||
for watch in [false,true]{
|
for watch in [false,true]{
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::{sync::atomic::Ordering,time::Duration};
|
|||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use webrtc::api::setting_engine::SettingEngine;
|
use webrtc::api::setting_engine::SettingEngine;
|
||||||
|
|
||||||
pub struct Options {pub timeout:Duration,pub legacy_prefix:bool,pub ready_policy:ReadyPolicy}
|
pub struct Options {pub timeout:Duration,pub legacy_prefix:bool,pub ready_policy:ReadyPolicy,pub clipboard:super::clipboard::Bridge}
|
||||||
pub struct Session {pub peer:Peer,signal:Signal,candidates:mpsc::Receiver<Value>,policy:ReadyPolicy}
|
pub struct Session {pub peer:Peer,signal:Signal,candidates:mpsc::Receiver<Value>,policy:ReadyPolicy}
|
||||||
impl Session {
|
impl Session {
|
||||||
pub async fn open(room:&JoinData,shape:&Shape,device:&str,client:&str,options:Options,settings:SettingEngine)->Result<Self,String> {
|
pub async fn open(room:&JoinData,shape:&Shape,device:&str,client:&str,options:Options,settings:SettingEngine)->Result<Self,String> {
|
||||||
@@ -15,7 +15,7 @@ impl Session {
|
|||||||
let timeout=if room.ws_connect_timeout_ms>0 {Duration::from_millis(room.ws_connect_timeout_ms as u64)}else{options.timeout};
|
let timeout=if room.ws_connect_timeout_ms>0 {Duration::from_millis(room.ws_connect_timeout_ms as u64)}else{options.timeout};
|
||||||
let mut signal=Signal::connect(&room.signaling_list,&room.token,timeout,options.legacy_prefix).await?;
|
let mut signal=Signal::connect(&room.signaling_list,&room.token,timeout,options.legacy_prefix).await?;
|
||||||
let result=async {
|
let result=async {
|
||||||
let result=signal.control(shape.control(client,&app,&ice)?,shape.connect_options(device)?,options.timeout).await?;
|
let result=signal.control(shape.control(client,&app,&ice)?,shape.connect_options(device,options.clipboard.enabled)?,options.timeout).await?;
|
||||||
// Key names per ICE entry and URL scheme only (no values) to see where TURN credentials live.
|
// Key names per ICE entry and URL scheme only (no values) to see where TURN credentials live.
|
||||||
if let Some(list)=result.get("iceServers").and_then(Value::as_array) {
|
if let Some(list)=result.get("iceServers").and_then(Value::as_array) {
|
||||||
let summary:Vec<String>=list.iter().map(|s|{
|
let summary:Vec<String>=list.iter().map(|s|{
|
||||||
@@ -33,7 +33,7 @@ impl Session {
|
|||||||
let remote=result.get("client_id").and_then(Value::as_str).filter(|s|!s.is_empty()).ok_or("Control acknowledgement missing peer route")?;
|
let remote=result.get("client_id").and_then(Value::as_str).filter(|s|!s.is_empty()).ok_or("Control acknowledgement missing peer route")?;
|
||||||
let config=rtc::configuration(&result)?;
|
let config=rtc::configuration(&result)?;
|
||||||
let(tx,rx)=mpsc::channel(256);
|
let(tx,rx)=mpsc::channel(256);
|
||||||
let peer=Peer::new(config,&shape,&app,&ice,remote,tx,settings).await?;
|
let peer=Peer::new(config,&shape,&app,&ice,remote,tx,settings,options.clipboard).await?;
|
||||||
// The official host drops an offer whose ice_id is not yet in its connection table
|
// The official host drops an offer whose ice_id is not yet in its connection table
|
||||||
// (libstreamer 0xc3080); give it time to process be-controlled first.
|
// (libstreamer 0xc3080); give it time to process be-controlled first.
|
||||||
let delay=std::env::var("UU_VIEWER_OFFER_DELAY_MS").ok().and_then(|v|v.parse().ok()).unwrap_or(0u64).min(10_000);
|
let delay=std::env::var("UU_VIEWER_OFFER_DELAY_MS").ok().and_then(|v|v.parse().ok()).unwrap_or(0u64).min(10_000);
|
||||||
|
|||||||
+7
-7
@@ -148,7 +148,7 @@ async fn complete_session_uses_loopback_signaling_and_virtual_rtc_through_echo()
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
let room:JoinData=serde_json::from_value(json!({"token":"synthetic-room-ticket","signaling_list":[url],"report_token":"synthetic-report","report_url":""})).unwrap();
|
let room:JoinData=serde_json::from_value(json!({"token":"synthetic-room-ticket","signaling_list":[url],"report_token":"synthetic-report","report_url":""})).unwrap();
|
||||||
let options=Options{timeout:Duration::from_secs(3),legacy_prefix:false,ready_policy:ReadyPolicy::Explicit};
|
let options=Options{timeout:Duration::from_secs(3),legacy_prefix:false,ready_policy:ReadyPolicy::Explicit,clipboard:super::clipboard::Bridge::new(false)};
|
||||||
let mut session=Session::open(&room,&shape(),"synthetic-device","synthetic-client",options,viewer_settings).await.unwrap();
|
let mut session=Session::open(&room,&shape(),"synthetic-device","synthetic-client",options,viewer_settings).await.unwrap();
|
||||||
assert_eq!(session.peer.channels.len(),5);
|
assert_eq!(session.peer.channels.len(),5);
|
||||||
let(tool_io,mut tool_rx)=super::tools::attach(&session.peer).unwrap();
|
let(tool_io,mut tool_rx)=super::tools::attach(&session.peer).unwrap();
|
||||||
@@ -188,7 +188,7 @@ async fn complete_session_uses_loopback_signaling_and_virtual_rtc_through_echo()
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn early_candidates_and_foreign_session_messages_are_scoped() {
|
async fn early_candidates_and_foreign_session_messages_are_scoped() {
|
||||||
let(settings,_,router)=virtual_network().await;let(tx,_rx)=mpsc::channel(256);
|
let(settings,_,router)=virtual_network().await;let(tx,_rx)=mpsc::channel(256);
|
||||||
let mut peer=Peer::new(RTCConfiguration::default(),&shape(),"synthetic-app","synthetic-ice","synthetic-host",tx,settings).await.unwrap();
|
let mut peer=Peer::new(RTCConfiguration::default(),&shape(),"synthetic-app","synthetic-ice","synthetic-host",tx,settings,super::clipboard::Bridge::new(false)).await.unwrap();
|
||||||
assert!(!peer.matches_route(&json!({"ice_id":"foreign"})));
|
assert!(!peer.matches_route(&json!({"ice_id":"foreign"})));
|
||||||
assert!(!peer.matches_route(&json!({"app_control_id":"foreign"})));
|
assert!(!peer.matches_route(&json!({"app_control_id":"foreign"})));
|
||||||
peer.receive(&json!({"type":"answer","ice_id":"foreign","sdp":"invalid"})).await.unwrap();
|
peer.receive(&json!({"type":"answer","ice_id":"foreign","sdp":"invalid"})).await.unwrap();
|
||||||
@@ -201,8 +201,8 @@ async fn early_candidates_and_foreign_session_messages_are_scoped() {
|
|||||||
async fn closing_one_peer_preserves_another_peer() {
|
async fn closing_one_peer_preserves_another_peer() {
|
||||||
let(a,b,router)=virtual_network().await;
|
let(a,b,router)=virtual_network().await;
|
||||||
let(tx1,_rx1)=mpsc::channel(256);let(tx2,_rx2)=mpsc::channel(256);
|
let(tx1,_rx1)=mpsc::channel(256);let(tx2,_rx2)=mpsc::channel(256);
|
||||||
let first=Peer::new(RTCConfiguration::default(),&shape(),"synthetic-first","synthetic-first-ice","synthetic-host",tx1,a).await.unwrap();
|
let first=Peer::new(RTCConfiguration::default(),&shape(),"synthetic-first","synthetic-first-ice","synthetic-host",tx1,a,super::clipboard::Bridge::new(false)).await.unwrap();
|
||||||
let second=Peer::new(RTCConfiguration::default(),&shape(),"synthetic-second","synthetic-second-ice","synthetic-host",tx2,b).await.unwrap();
|
let second=Peer::new(RTCConfiguration::default(),&shape(),"synthetic-second","synthetic-second-ice","synthetic-host",tx2,b,super::clipboard::Bridge::new(false)).await.unwrap();
|
||||||
first.close().await;
|
first.close().await;
|
||||||
assert_ne!(second.pc.connection_state(),webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Closed);
|
assert_ne!(second.pc.connection_state(),webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Closed);
|
||||||
assert_eq!(second.channels.len(),5);
|
assert_eq!(second.channels.len(),5);
|
||||||
@@ -220,7 +220,7 @@ async fn opus_and_video_tracks_are_received_independently_in_memory() {
|
|||||||
let video=Arc::new(TrackLocalStaticRTP::new(RTCRtpCodecCapability{mime_type:"video/H264".into(),clock_rate:90000,sdp_fmtp_line:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f".into(),..Default::default()},"video".into(),"test".into()));
|
let video=Arc::new(TrackLocalStaticRTP::new(RTCRtpCodecCapability{mime_type:"video/H264".into(),clock_rate:90000,sdp_fmtp_line:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f".into(),..Default::default()},"video".into(),"test".into()));
|
||||||
host.add_track(audio.clone() as Arc<dyn TrackLocal+Send+Sync>).await.unwrap();host.add_track(video.clone() as Arc<dyn TrackLocal+Send+Sync>).await.unwrap();
|
host.add_track(audio.clone() as Arc<dyn TrackLocal+Send+Sync>).await.unwrap();host.add_track(video.clone() as Arc<dyn TrackLocal+Send+Sync>).await.unwrap();
|
||||||
let(tx,_rx)=mpsc::channel(256);
|
let(tx,_rx)=mpsc::channel(256);
|
||||||
let peer=Peer::new(RTCConfiguration::default(),&shape().video_preferences(false),"app","ice","host",tx,viewer_settings).await.unwrap();
|
let peer=Peer::new(RTCConfiguration::default(),&shape().video_preferences(false),"app","ice","host",tx,viewer_settings,super::clipboard::Bridge::new(false)).await.unwrap();
|
||||||
let mut gathered=peer.pc.gathering_complete_promise().await;peer.offer().await.unwrap();gathered.recv().await;
|
let mut gathered=peer.pc.gathering_complete_promise().await;peer.offer().await.unwrap();gathered.recv().await;
|
||||||
let offer=peer.pc.local_description().await.unwrap();assert!(offer.sdp.contains("m=audio") && offer.sdp.contains("opus/48000/2"));
|
let offer=peer.pc.local_description().await.unwrap();assert!(offer.sdp.contains("m=audio") && offer.sdp.contains("opus/48000/2"));
|
||||||
host.set_remote_description(offer).await.unwrap();let answer=host.create_answer(None).await.unwrap();
|
host.set_remote_description(offer).await.unwrap();let answer=host.create_answer(None).await.unwrap();
|
||||||
@@ -267,7 +267,7 @@ async fn desktop_file_window_reattaches_without_replacing_peer(){
|
|||||||
}));}
|
}));}
|
||||||
})}));
|
})}));
|
||||||
let(tx,_rx)=mpsc::channel(256);
|
let(tx,_rx)=mpsc::channel(256);
|
||||||
let peer=Peer::new(RTCConfiguration::default(),&shape(),"app","ice","host",tx,viewer_settings).await.unwrap();
|
let peer=Peer::new(RTCConfiguration::default(),&shape(),"app","ice","host",tx,viewer_settings,super::clipboard::Bridge::new(false)).await.unwrap();
|
||||||
let mut gathered=peer.pc.gathering_complete_promise().await;peer.offer().await.unwrap();gathered.recv().await;
|
let mut gathered=peer.pc.gathering_complete_promise().await;peer.offer().await.unwrap();gathered.recv().await;
|
||||||
host.set_remote_description(peer.pc.local_description().await.unwrap()).await.unwrap();
|
host.set_remote_description(peer.pc.local_description().await.unwrap()).await.unwrap();
|
||||||
let answer=host.create_answer(None).await.unwrap();let mut gathered=host.gathering_complete_promise().await;
|
let answer=host.create_answer(None).await.unwrap();let mut gathered=host.gathering_complete_promise().await;
|
||||||
@@ -316,7 +316,7 @@ async fn hevc_track_uses_negotiated_payload_type_in_memory(){
|
|||||||
}
|
}
|
||||||
})));
|
})));
|
||||||
let(tx,_rx)=mpsc::channel(256);
|
let(tx,_rx)=mpsc::channel(256);
|
||||||
let peer=Peer::new(RTCConfiguration::default(),&shape().video_preferences(false),"app","ice","host",tx,viewer_settings).await.unwrap();
|
let peer=Peer::new(RTCConfiguration::default(),&shape().video_preferences(false),"app","ice","host",tx,viewer_settings,super::clipboard::Bridge::new(false)).await.unwrap();
|
||||||
let mut gathered=peer.pc.gathering_complete_promise().await;peer.offer().await.unwrap();gathered.recv().await;
|
let mut gathered=peer.pc.gathering_complete_promise().await;peer.offer().await.unwrap();gathered.recv().await;
|
||||||
host.set_remote_description(peer.pc.local_description().await.unwrap()).await.unwrap();
|
host.set_remote_description(peer.pc.local_description().await.unwrap()).await.unwrap();
|
||||||
let answer=host.create_answer(None).await.unwrap();
|
let answer=host.create_answer(None).await.unwrap();
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ impl Terminal {
|
|||||||
let worker=tokio::spawn(async move {
|
let worker=tokio::spawn(async move {
|
||||||
let mut decoder=Decoder::default();
|
let mut decoder=Decoder::default();
|
||||||
while let Some((channel,data))=rx.recv().await {
|
while let Some((channel,data))=rx.recv().await {
|
||||||
if channel==CONTROL {
|
// Terminal RPC answers (check_env) come on CONTROL or, from the official Mac host, on BINARY
|
||||||
|
// next to TERM frames (as this project's host does).
|
||||||
|
if channel==CONTROL || (channel==BINARY && !data.starts_with(b"TERM")) {
|
||||||
if let Some(r)=blob(&data,22) {if let (Some(h),Some(body))=(blob(r,1),blob(r,24)) {
|
if let Some(r)=blob(&data,22) {if let (Some(h),Some(body))=(blob(r,1),blob(r,24)) {
|
||||||
if let Some(t)=p.lock().unwrap().remove(&(24,uint(h,1))) {let _=t.send(Ok(body.to_vec()));}
|
if let Some(t)=p.lock().unwrap().remove(&(24,uint(h,1))) {let _=t.send(Ok(body.to_vec()));}
|
||||||
}}continue
|
}}continue
|
||||||
@@ -85,7 +87,12 @@ impl Terminal {
|
|||||||
// "not implemented", not "unavailable"; go on and let OPEN report availability.
|
// "not implemented", not "unavailable"; go on and let OPEN report availability.
|
||||||
match tokio::time::timeout(std::time::Duration::from_secs(3),self.request((24,id),CONTROL,wire::envelope(id,21,&r))).await{
|
match tokio::time::timeout(std::time::Duration::from_secs(3),self.request((24,id),CONTROL,wire::envelope(id,21,&r))).await{
|
||||||
Err(_)=>Ok(()),
|
Err(_)=>Ok(()),
|
||||||
Ok(b)=>{let b=b?;if uint(&b,1)!=0 {return Err("Terminal environment unavailable".into())}Ok(())}
|
Ok(b)=>{let b=b?;let code=uint(&b,1);
|
||||||
|
if code!=0 {
|
||||||
|
let message=blob(&b,2).map(|m|String::from_utf8_lossy(m).chars().take(80).collect::<String>()).unwrap_or_default();
|
||||||
|
log::info!("Terminal check_env: code={code} message={message:?}");
|
||||||
|
return Err("Terminal environment unavailable".into())
|
||||||
|
}Ok(())}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub async fn list_sessions(&self)->Result<Vec<Value>,String>{
|
pub async fn list_sessions(&self)->Result<Vec<Value>,String>{
|
||||||
|
|||||||
@@ -195,6 +195,15 @@ pub async fn run(credentials: impl Fn() -> Result<crate::auth::Credentials, Stri
|
|||||||
Err(_) => toast("电源指令失败:无法启动会话进程"),
|
Err(_) => toast("电源指令失败:无法启动会话进程"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
["connect", id, "unbind"] => {
|
||||||
|
if let Some(s)=sessions.remove(*id){s.stop().await;}
|
||||||
|
let result=match credentials(){
|
||||||
|
Ok(creds)=>super::api::Api::new(crate::auth::UUAuthClient::new(creds),crate::auth::BASE_URL).unbind(id,false).await.map_err(|e|e.to_string()),
|
||||||
|
Err(e)=>Err(e),
|
||||||
|
};
|
||||||
|
match result {Ok(())=>toast("设备已从账号删除"),Err(e)=>toast(&format!("删除设备失败:{e}"))}
|
||||||
|
next_refresh=Instant::now();
|
||||||
|
}
|
||||||
["connect", _, kind] => log::info!("Viewer UI: {kind} is not supported yet"),
|
["connect", _, kind] => log::info!("Viewer UI: {kind} is not supported yet"),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -75,7 +75,7 @@ impl Shape {
|
|||||||
if h264_only {shape.decoders.retain(|d|d.codec==1);shape.codecs.retain(|c|c.video_codec==1);}
|
if h264_only {shape.decoders.retain(|d|d.codec==1);shape.codecs.retain(|c|c.video_codec==1);}
|
||||||
shape
|
shape
|
||||||
}
|
}
|
||||||
pub fn connect_options(&self, device:&str) -> Result<Vec<u8>,String> {
|
pub fn connect_options(&self, device:&str, clipboard:bool) -> Result<Vec<u8>,String> {
|
||||||
self.validate()?;
|
self.validate()?;
|
||||||
let mut out=Vec::new(); int(1,self.capture_type.into(),&mut out);
|
let mut out=Vec::new(); int(1,self.capture_type.into(),&mut out);
|
||||||
if [1,8].contains(&self.capture_type) { int(2,u64::MAX,&mut out); }
|
if [1,8].contains(&self.capture_type) { int(2,u64::MAX,&mut out); }
|
||||||
@@ -100,7 +100,7 @@ impl Shape {
|
|||||||
int(8,self.platform.into(),&mut out); bytes(9,device.as_bytes(),&mut out); int(10,1,&mut out);
|
int(8,self.platform.into(),&mut out); bytes(9,device.as_bytes(),&mut out); int(10,1,&mut out);
|
||||||
if self.capture_type==1 {
|
if self.capture_type==1 {
|
||||||
let mut flags=Vec::new(); for [field,version] in &self.feature_flag { if *field!=8 {int((*field).into(),(*version).into(),&mut flags);} }
|
let mut flags=Vec::new(); for [field,version] in &self.feature_flag { if *field!=8 {int((*field).into(),(*version).into(),&mut flags);} }
|
||||||
if super::clipboard::available(){int(8,3,&mut flags);}
|
if clipboard{int(8,3,&mut flags);}
|
||||||
bytes(11,&flags,&mut out);
|
bytes(11,&flags,&mut out);
|
||||||
}
|
}
|
||||||
if self.capture_type!=5 { bytes(12,self.client_version.as_bytes(),&mut out); }
|
if self.capture_type!=5 { bytes(12,self.client_version.as_bytes(),&mut out); }
|
||||||
@@ -176,7 +176,7 @@ mod tests {
|
|||||||
let mut s=shape();
|
let mut s=shape();
|
||||||
for capture in [1,5,8,9] {
|
for capture in [1,5,8,9] {
|
||||||
s.capture_type=capture;
|
s.capture_type=capture;
|
||||||
let b=s.connect_options("synthetic-device").unwrap(); let f=decode_wire(&b).unwrap();
|
let b=s.connect_options("synthetic-device",false).unwrap(); let f=decode_wire(&b).unwrap();
|
||||||
let numbers:Vec<u32>=f.iter().map(|f|f.number).collect();
|
let numbers:Vec<u32>=f.iter().map(|f|f.number).collect();
|
||||||
let expected=match capture {1=>vec![1,2,3,4,4,4,4,6,6,7,8,9,10,11,12],5=>vec![1,3,4,4,4,4,6,6,7,8,9,10],8=>vec![1,2,8,9,10,12],_=>vec![1,8,9,10,12]};
|
let expected=match capture {1=>vec![1,2,3,4,4,4,4,6,6,7,8,9,10,11,12],5=>vec![1,3,4,4,4,4,6,6,7,8,9,10],8=>vec![1,2,8,9,10,12],_=>vec![1,8,9,10,12]};
|
||||||
assert_eq!(numbers,expected);
|
assert_eq!(numbers,expected);
|
||||||
@@ -226,7 +226,7 @@ pub fn media_control(data:&[u8])->(Option<u32>,Option<u32>){
|
|||||||
let original:Shape=serde_json::from_str(include_str!("../../tests/fixtures/viewer/session-shape.json")).unwrap();
|
let original:Shape=serde_json::from_str(include_str!("../../tests/fixtures/viewer/session-shape.json")).unwrap();
|
||||||
for force in [false,true] {
|
for force in [false,true] {
|
||||||
let s=original.video_preferences(force);s.validate_session().unwrap();assert_eq!(s.chroma,1);
|
let s=original.video_preferences(force);s.validate_session().unwrap();assert_eq!(s.chroma,1);
|
||||||
let options=s.connect_options("synthetic-device").unwrap();
|
let options=s.connect_options("synthetic-device",false).unwrap();
|
||||||
let mut caps=Vec::new();
|
let mut caps=Vec::new();
|
||||||
for f in decode_wire(&options).unwrap(){if let (4,WireValue::Bytes(cap))=(f.number,f.value){
|
for f in decode_wire(&options).unwrap(){if let (4,WireValue::Bytes(cap))=(f.number,f.value){
|
||||||
assert_eq!(super::super::tools::uint(cap,1),30);
|
assert_eq!(super::super::tools::uint(cap,1),30);
|
||||||
@@ -234,7 +234,7 @@ pub fn media_control(data:&[u8])->(Option<u32>,Option<u32>){
|
|||||||
caps.push((super::super::tools::uint(cap,2),super::super::tools::uint(cap,5)));
|
caps.push((super::super::tools::uint(cap,2),super::super::tools::uint(cap,5)));
|
||||||
}}
|
}}
|
||||||
assert_eq!(caps,if force{vec![(1,1),(1,3)]}else{vec![(2,1),(2,3),(1,1),(1,3)]});
|
assert_eq!(caps,if force{vec![(1,1),(1,3)]}else{vec![(2,1),(2,3),(1,1),(1,3)]});
|
||||||
assert!(s.video_preferences(force).connect_options("synthetic-device").unwrap()==options);
|
assert!(s.video_preferences(force).connect_options("synthetic-device",false).unwrap()==options);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[test] fn chroma_request_and_actual_sync_are_independent_of_encoder_list(){
|
#[test] fn chroma_request_and_actual_sync_are_independent_of_encoder_list(){
|
||||||
|
|||||||
+13
-5
@@ -13,7 +13,7 @@ use viewer::clipboard;
|
|||||||
#[cfg(test)] #[path="initialization.rs"] mod initialization;
|
#[cfg(test)] #[path="initialization.rs"] mod initialization;
|
||||||
use viewer::{api::Api,rtc::ReadyPolicy,session::{Options,Session},wire::Shape};
|
use viewer::{api::Api,rtc::ReadyPolicy,session::{Options,Session},wire::Shape};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
const HELP:&str="Experimental native viewer.\n uuremote-viewer ui (GTK window: sign-in, devices, sessions) Desktop UI requires viewer-sdl (decodes with the ffmpeg CLI, or FFmpeg 6.x libraries with viewer-ffmpeg).\n uuremote-viewer power DEVICE reboot|shutdown\n uuremote-viewer terminal DEVICE [SESSION]\n uuremote-viewer files DEVICE ls PATH | get REMOTE LOCAL | put LOCAL REMOTE\n uuremote-viewer portmap DEVICE LOCAL_PORT HOST PORT\n uuremote-viewer files-ui|portmap-ui|terminal-ui DEVICE NAME (GTK tool windows)\n uuremote-viewer login [--no-gui]\n uuremote-viewer devices METHOD ARRAY_POINTER ID_POINTER NAME_POINTER\n uuremote-viewer assist CONNECT_ID (验证码从 stdin 读取一行)\n uuremote-viewer connect DEVICE true|false SHAPE_JSON echo|manual raw|legacy [--view-only]\nVideo: UU_VIEWER_CODEC=h264 forces H.264; UU_VIEWER_CHROMA=444 requests true color (default 4:2:0).\nAudio: UU_VIEWER_AUDIO=0 disables playback. UU_VIEWER_VIEW_ONLY=1 disables desktop input.\nDevice-list method/JSON pointers and compatibility shape require verified operator configuration.\nQR login reuses the sibling uuremote-server login command. Never run login in a captured log.\nEcho readiness is transport observation only; no sendVideoTrack RPC is emitted.";
|
const HELP:&str="Experimental native viewer.\n uuremote-viewer ui (GTK window: sign-in, devices, sessions) Desktop UI requires viewer-sdl (decodes with the ffmpeg CLI, or FFmpeg 6.x libraries with viewer-ffmpeg).\n uuremote-viewer power DEVICE reboot|shutdown\n uuremote-viewer unbind DEVICE [--shared] (从账号删除设备 / remove a device from the account)\n uuremote-viewer terminal DEVICE [SESSION]\n uuremote-viewer files DEVICE ls PATH | get REMOTE LOCAL | put LOCAL REMOTE\n uuremote-viewer portmap DEVICE LOCAL_PORT HOST PORT\n uuremote-viewer files-ui|portmap-ui|terminal-ui DEVICE NAME (GTK tool windows)\n uuremote-viewer login [--no-gui]\n uuremote-viewer devices METHOD ARRAY_POINTER ID_POINTER NAME_POINTER\n uuremote-viewer assist CONNECT_ID (验证码从 stdin 读取一行)\n uuremote-viewer connect DEVICE true|false SHAPE_JSON echo|manual raw|legacy [--view-only]\nVideo: UU_VIEWER_CODEC=h264 forces H.264; UU_VIEWER_CHROMA=444 requests true color (default 4:2:0).\nAudio: UU_VIEWER_AUDIO=0 disables playback. UU_VIEWER_VIEW_ONLY=1 disables desktop input.\nDevice-list method/JSON pointers and compatibility shape require verified operator configuration.\nQR login reuses the sibling uuremote-server login command. Never run login in a captured log.\nEcho readiness is transport observation only; no sendVideoTrack RPC is emitted.";
|
||||||
const DEFAULT_SHAPE:&str=r#"{"capture_type":1,"platform":3,"client_version":"4.42.0","width":1920,"height":1080,"fps":60,"chroma":1,
|
const DEFAULT_SHAPE:&str=r#"{"capture_type":1,"platform":3,"client_version":"4.42.0","width":1920,"height":1080,"fps":60,"chroma":1,
|
||||||
"decoders":[{"fps":60,"codec":1,"width":3840,"height":2160,"chroma":1}],"display_modes":[[1920,1080,60]],
|
"decoders":[{"fps":60,"codec":1,"width":3840,"height":2160,"chroma":1}],"display_modes":[[1920,1080,60]],
|
||||||
"displays":[{"id":1,"fps":60,"type":0,"hdr":0}],
|
"displays":[{"id":1,"fps":60,"type":0,"hdr":0}],
|
||||||
@@ -55,6 +55,10 @@ async fn run(args:&[String])->Result<(),String> {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Some("unbind") if (args.len()==2 || (args.len()==3 && args[2]=="--shared")) && !args[1].is_empty() => {
|
||||||
|
api()?.unbind(&args[1],args.len()==3).await.map_err(|e|format!("删除设备失败:{e}"))?;
|
||||||
|
println!("已从账号删除设备");Ok(())
|
||||||
|
}
|
||||||
Some("power")=>power_command(args).await,
|
Some("power")=>power_command(args).await,
|
||||||
Some("terminal-local") if args.len()==2 || args.len()==3=>{
|
Some("terminal-local") if args.len()==2 || args.len()==3=>{
|
||||||
let session=if args.len()==3{Some(args[2].parse::<u32>().ok().filter(|n|*n!=0).ok_or("Invalid terminal session id")?)}else{None};
|
let session=if args.len()==3{Some(args[2].parse::<u32>().ok().filter(|n|*n!=0).ok_or("Invalid terminal session id")?)}else{None};
|
||||||
@@ -100,7 +104,11 @@ async fn desktop_command(args:&[String],code:Option<String>)->Result<(),String>
|
|||||||
let device=account_connection.then_some(args[1].as_str());
|
let device=account_connection.then_some(args[1].as_str());
|
||||||
window.set_mac(api.target_is_mac(&room,device).await.map_err(|e|e.to_string())?);
|
window.set_mac(api.target_is_mac(&room,device).await.map_err(|e|e.to_string())?);
|
||||||
}
|
}
|
||||||
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:legacy,ready_policy:policy};
|
#[cfg(feature="viewer-sdl")]
|
||||||
|
let clipboard=desktop.as_ref().map(|(window,_)|window.clipboard_bridge()).unwrap_or_else(||clipboard::Bridge::new(false));
|
||||||
|
#[cfg(not(feature="viewer-sdl"))]
|
||||||
|
let clipboard=clipboard::Bridge::new(shape.capture_type==1);
|
||||||
|
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:legacy,ready_policy:policy,clipboard};
|
||||||
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
||||||
#[cfg(feature="viewer-sdl")]
|
#[cfg(feature="viewer-sdl")]
|
||||||
let result=if let Some((window,decoder))=desktop.as_mut(){viewer::sdl::run(&mut session,window,decoder.as_mut(),view_only).await}else{session.run().await};
|
let result=if let Some((window,decoder))=desktop.as_mut(){viewer::sdl::run(&mut session,window,decoder.as_mut(),view_only).await}else{session.run().await};
|
||||||
@@ -120,7 +128,7 @@ mod cli_tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn invalid_commands_never_fall_through_to_login_or_host_service() {
|
async fn invalid_commands_never_fall_through_to_login_or_host_service() {
|
||||||
for args in [vec!["invalid"],vec!["power"],vec!["power","device","logout"],vec!["power","device","reboot","extra"],vec!["login","--invalid"],vec!["connect"],vec!["assist"],vec!["assist","id","forbidden-code-argument"],vec!["terminal"],vec!["terminal","device","extra"],vec!["terminal","device","0"],vec!["terminal","device","4294967296"],vec!["terminal-ui","device"],vec!["files","device","bad","path"],vec!["portmap","device","bad","host","80"],vec!["portmap","device","8000","host","0"],vec!["devices","DELETE","/data","/id","/name"]] {
|
for args in [vec!["invalid"],vec!["power"],vec!["power","device","logout"],vec!["power","device","reboot","extra"],vec!["login","--invalid"],vec!["connect"],vec!["assist"],vec!["assist","id","forbidden-code-argument"],vec!["terminal"],vec!["terminal","device","extra"],vec!["terminal","device","0"],vec!["terminal","device","4294967296"],vec!["terminal-ui","device"],vec!["files","device","bad","path"],vec!["portmap","device","bad","host","80"],vec!["portmap","device","8000","host","0"],vec!["devices","DELETE","/data","/id","/name"],vec!["unbind"],vec!["unbind",""],vec!["unbind","device","--other"],vec!["unbind","device","--shared","extra"]] {
|
||||||
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).await.is_err());
|
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).await.is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,7 +155,7 @@ async fn tool_command(args:&[String])->Result<(),String>{
|
|||||||
let creds=credentials()?;let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL);
|
let creds=credentials()?;let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL);
|
||||||
let room=api.join(&args[1],false,true).await.map_err(|e|e.to_string())?;
|
let room=api.join(&args[1],false,true).await.map_err(|e|e.to_string())?;
|
||||||
// Match the existing UI connection framing (9bb42d5); the host tolerates this prefix.
|
// Match the existing UI connection framing (9bb42d5); the host tolerates this prefix.
|
||||||
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:true,ready_policy:ReadyPolicy::EchoOnly};
|
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:true,ready_policy:ReadyPolicy::EchoOnly,clipboard:clipboard::Bridge::new(false)};
|
||||||
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
||||||
let result=async{
|
let result=async{
|
||||||
let(io,rx)=viewer::tools::attach(&session.peer)?;
|
let(io,rx)=viewer::tools::attach(&session.peer)?;
|
||||||
@@ -176,7 +184,7 @@ async fn power_command(args:&[String])->Result<(),String>{
|
|||||||
shape.capture_type=5;shape.feature_flag.clear();
|
shape.capture_type=5;shape.feature_flag.clear();
|
||||||
let creds=credentials()?;let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL);
|
let creds=credentials()?;let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL);
|
||||||
let room=api.join(&args[1],false,true).await.map_err(|e|e.to_string())?;
|
let room=api.join(&args[1],false,true).await.map_err(|e|e.to_string())?;
|
||||||
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:true,ready_policy:ReadyPolicy::EchoOnly};
|
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:true,ready_policy:ReadyPolicy::EchoOnly,clipboard:clipboard::Bridge::new(false)};
|
||||||
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
||||||
let result=viewer::power::run(&mut session,action).await;
|
let result=viewer::power::run(&mut session,action).await;
|
||||||
session.close().await;
|
session.close().await;
|
||||||
|
|||||||
@@ -1071,6 +1071,16 @@ impl WebRtcSession {
|
|||||||
});}
|
});}
|
||||||
|
|
||||||
},
|
},
|
||||||
|
Ok(crate::control_protocol::ControlMessage::Unsupported(v)) => {
|
||||||
|
// Action name and key names only, never values (an IME text event would carry typed text).
|
||||||
|
static UNSUPPORTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||||
|
if UNSUPPORTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
|
||||||
|
let action = v.get("action").and_then(serde_json::Value::as_str)
|
||||||
|
.filter(|a| a.len() <= 40 && a.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')).unwrap_or("?");
|
||||||
|
let keys: Vec<&str> = v.as_object().map(|o| o.keys().map(String::as_str).take(12).collect()).unwrap_or_default();
|
||||||
|
log::info!("Unsupported CONTROL input: action={action} keys={keys:?}");
|
||||||
|
}
|
||||||
|
},
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
} else if channel_name.contains("STREAMER") {
|
} else if channel_name.contains("STREAMER") {
|
||||||
|
|||||||
Reference in new issue
Block a user