From b63bedd4dcd5259b01662824c01aa0a2813c1577 Mon Sep 17 00:00:00 2001 From: VallierDev <24893073+VallierDev@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:30:09 +0800 Subject: [PATCH] Repaint full-screen terminal programs on reattach; ABR for libx265 bitrate presets Reattaching replays the scrollback tail, which starts mid-redraw for full-screen programs (tmux, vim, TUIs), and an unchanged size raises no SIGWINCH. Shrink the PTY by one row and restore the latest requested size after a pause so the program repaints (#17). Apply the #15 ABR change to the libx265 path as well, clarify the non-wayland build error, and document the Wayland systemd unit and uinput module autoload (#16). Co-Authored-By: Claude Opus 5.5 --- README.en.md | 6 +++++- README.md | 19 ++++++++++++++++++- src/terminal.rs | 44 ++++++++++++++++++++++++++++++++++++++++++-- src/video.rs | 12 +++++++++--- src/wayland.rs | 2 +- 5 files changed, 75 insertions(+), 8 deletions(-) diff --git a/README.en.md b/README.en.md index ac5992e..217a1c3 100644 --- a/README.en.md +++ b/README.en.md @@ -368,10 +368,14 @@ cargo build --release --features wayland Omarchy uses Hyprland: run in its user session, select `UU_DESKTOP_BACKEND=wayland`, and retain `WAYLAND_DISPLAY` / `XDG_RUNTIME_DIR`. This requires wlr-screencopy and the virtual input protocols supported by Hyprland; other compositors may need `--features wayland,portal`. -For uinput, load `uinput` and apply the uaccess rule above; seat ACLs require an active login. +For uinput, load `uinput` (at boot: `echo uinput | sudo tee /etc/modules-load.d/uinput.conf`) and apply the uaccess rule above; seat ACLs require an active login. For unattended accounts, explicitly restrict `/dev/uinput` access to a dedicated group. This permission can inject into the whole seat, including lock/greeter screens. `UU_INPUT_BACKEND=uinput` requests kernel devices; verify startup actually reports uinput. +In Hyprland / uwsm sessions `default.target` may start before the compositor exports `WAYLAND_DISPLAY`; +tie the unit to the graphical session instead (community-verified autostart on Omarchy): +`After=` and `PartOf=graphical-session.target`, `ConditionEnvironment=WAYLAND_DISPLAY`, +`Environment=UU_DESKTOP_BACKEND=wayland` (no `DISPLAY`), and `WantedBy=graphical-session.target`. Optional VAAPI: `intel-media-driver` (modern Intel) or `libva-mesa-driver` (AMD), `libva-utils` for `vainfo`. Optional KMS: `libdrm`. Virtual Xfce: `xorg-server-xvfb xorg-xauth xorg-xdpyinfo xfce4-session xfce4-panel xfdesktop xfwm4 gnome-terminal`. diff --git a/README.md b/README.md index 5c3fbbf..56f8711 100644 --- a/README.md +++ b/README.md @@ -323,10 +323,27 @@ cargo build --release --features wayland Omarchy 使用 Hyprland:在其用户会话中运行,设置 `UU_DESKTOP_BACKEND=wayland`,保留 `WAYLAND_DISPLAY` 和 `XDG_RUNTIME_DIR`。其他合成器可能需要 `--features wayland,portal`。 -uinput 需加载内核模块并应用上文 uaccess 规则;无人登录账号需要专用组的受限授权。 +uinput 需加载内核模块(开机自动加载:`echo uinput | sudo tee /etc/modules-load.d/uinput.conf`)并应用上文 uaccess 规则;无人登录账号需要专用组的受限授权。 该权限能向整个 seat(包括锁屏/登录界面)注入输入。设置 `UU_INPUT_BACKEND=uinput` 后, 仍须确认启动日志实际选择了 uinput。 +Hyprland / uwsm 等会话中,`default.target` 可能早于合成器导出 `WAYLAND_DISPLAY`。systemd 单元可改为随图形会话启动 +(社区在 Omarchy 上验证过开机自启): + +```ini +[Unit] +After=graphical-session.target +PartOf=graphical-session.target +ConditionEnvironment=WAYLAND_DISPLAY + +[Service] +Environment=UU_DESKTOP_BACKEND=wayland +# 其余同上文 X11 示例,去掉 DISPLAY + +[Install] +WantedBy=graphical-session.target +``` + VAAPI 可选包:Intel 新显卡用 `intel-media-driver`,AMD 用 `libva-mesa-driver`,`libva-utils` 提供 `vainfo`。KMS 依赖 `libdrm`。虚拟 Xfce 依赖 `xorg-server-xvfb xorg-xauth xorg-xdpyinfo xfce4-session xfce4-panel xfdesktop xfwm4 gnome-terminal`。 diff --git a/src/terminal.rs b/src/terminal.rs index 977cc88..40b49f1 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -71,6 +71,7 @@ struct Session { pid: i32, sink: Mutex>>>, scrollback: Mutex>, + size: Mutex<(u16, u16)>, } impl Session { @@ -83,9 +84,26 @@ impl Session { false } fn resize(&self, cols: u16, rows: u16) { + *self.size.lock().unwrap() = (cols, rows); + self.set_winsize(cols, rows); + } + fn set_winsize(&self, cols: u16, rows: u16) { let win = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 }; unsafe { libc::ioctl(self.master.as_raw_fd(), libc::TIOCSWINSZ as _, &win); } } + /// Full-screen programs repaint only on SIGWINCH, which an unchanged size never raises: + /// shrink by one row, then restore the latest requested size after a pause. + fn force_redraw(self: &Arc) { + let (cols, rows) = *self.size.lock().unwrap(); + if rows <= 1 { return; } + self.set_winsize(cols, rows - 1); + let s = self.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(150)); + let (cols, rows) = *s.size.lock().unwrap(); + s.set_winsize(cols, rows); + }); + } fn write(&self, data: &[u8]) { let mut off = 0; while off < data.len() { @@ -137,7 +155,7 @@ fn spawn(requested_id: u32, cols: u16, rows: u16, shell: Option<&str>) -> Result } }; let session = Arc::new(Session { id, shell: shell.clone(), created_ms: now_ms(), pid: child.id() as i32, - master: pty.master, sink: Mutex::new(None), scrollback: Mutex::new(VecDeque::new()) }); + master: pty.master, sink: Mutex::new(None), scrollback: Mutex::new(VecDeque::new()), size: Mutex::new((cols, rows)) }); let mut reader = std::fs::File::from(session.master.try_clone().map_err(|e| format!("pty dup failed: {e}"))?); let worker = session.clone(); std::thread::Builder::new().name(format!("uu-term-{id}")).spawn(move || { @@ -212,6 +230,7 @@ impl TerminalConn { OPEN => { let v = json(&frame.payload); let (cols, rows) = dims(&v); + let reattach = existing.is_some(); let session = match existing { Some(s) => { s.resize(cols, rows); Ok(s) } None => spawn(frame.session, cols, rows, v.get("shell").and_then(|s| s.as_str())), @@ -225,6 +244,9 @@ impl TerminalConn { let replay: Vec = s.scrollback.lock().unwrap().iter().copied().collect(); // A full scrollback exceeds SCTP's 64 KiB outbound message limit. for chunk in replay.chunks(OUTPUT_CHUNK) { self.send(STDOUT, s.id, chunk); } + drop(sink); + // The replay tail starts mid-redraw for full-screen programs. + if reattach { s.force_redraw(); } } Err(e) => { log::warn!("Terminal open failed: {}", e); self.send(OPEN_RESP, frame.session, &reply(1, &e)); } } @@ -291,13 +313,31 @@ mod tests { } } #[test] + fn force_redraw_shrinks_then_restores_latest_size() { + let pty = nix::pty::openpty(None, None).unwrap(); + let session = Arc::new(Session { id: u32::MAX - 2, shell: "/bin/sh".into(), created_ms: now_ms(), + master: pty.master, pid: 0, sink: Mutex::new(None), + scrollback: Mutex::new(VecDeque::new()), size: Mutex::new((80, 24)) }); + let rows = |s: &Session| { + let mut win = libc::winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0 }; + unsafe { libc::ioctl(s.master.as_raw_fd(), libc::TIOCGWINSZ as _, &mut win); } + (win.ws_col, win.ws_row) + }; + session.resize(100, 30); + session.force_redraw(); + assert_eq!(rows(&session), (100, 29)); + session.resize(120, 40); + std::thread::sleep(std::time::Duration::from_millis(400)); + assert_eq!(rows(&session), (120, 40), "restore must use the latest requested size"); + } + #[test] fn reconnect_replays_large_history_in_bounded_frames() { let pty = nix::pty::openpty(None, None).unwrap(); let id = u32::MAX - 1; let history: Vec = (0..SCROLLBACK).map(|n| (n % 251) as u8).collect(); let session = Arc::new(Session { id, shell: "/bin/sh".into(), created_ms: now_ms(), master: pty.master, pid: 0, sink: Mutex::new(None), - scrollback: Mutex::new(history.iter().copied().collect()) }); + scrollback: Mutex::new(history.iter().copied().collect()), size: Mutex::new((80, 24)) }); registry().lock().unwrap().insert(id, session.clone()); struct Cleanup(u32); impl Drop for Cleanup { fn drop(&mut self) { registry().lock().unwrap().remove(&self.0); } } diff --git a/src/video.rs b/src/video.rs index 93527a3..37682f9 100644 --- a/src/video.rs +++ b/src/video.rs @@ -136,10 +136,16 @@ pub(crate) fn x265_params(gop: &str) -> String { fn cpu_hevc_options(settings: &VideoSettings, gop: &str) -> Vec { let (maxrate, buffer) = rate_args(settings, Encoder::Cpu); let (profile, pix_fmt) = chroma_args(settings, Encoder::Cpu); - ["-c:v", "libx265", "-preset", "superfast", "-tune", "zerolatency", "-profile:v", profile, - "-pix_fmt", pix_fmt, "-g", gop, "-bf", "0", "-threads", "4", "-crf", &settings.cq().to_string(), + let mut options = ["-c:v", "libx265", "-preset", "superfast", "-tune", "zerolatency", "-profile:v", profile, + "-pix_fmt", pix_fmt, "-g", gop, "-bf", "0", "-threads", "4", "-maxrate", &maxrate, "-bufsize", &buffer, "-x265-params", &x265_params(gop)] - .into_iter().map(str::to_owned).collect() + .into_iter().map(str::to_owned).collect::>(); + // Same as libx264: capped CRF starves repeated keyframes, so bitrate presets use ABR. + match settings.max_kbps() { + Some(k) => options.extend(["-b:v".into(), format!("{}k", k * 3 / 4)]), + None => options.extend(["-crf".into(), settings.cq().to_string()]), + } + options } fn encoder_options(settings: &VideoSettings, encoder: Encoder, gop: &str) -> Vec { diff --git a/src/wayland.rs b/src/wayland.rs index 3d63672..a940831 100644 --- a/src/wayland.rs +++ b/src/wayland.rs @@ -26,7 +26,7 @@ pub fn init() -> Result<(u32,u32),String> { return Ok((w as u32,h as u32)); } #[cfg(not(all(target_os="linux", feature="wayland")))] - Err("Wayland backend requires Linux and a build with --features wayland".into()) + Err("this build was compiled without the wayland feature; rebuild with --features wayland".into()) } pub fn capture(buffer:&mut [u8]) -> Result<(),String> { #[cfg(all(target_os="linux", feature="wayland"))]