fix: repair Wine setup and niri capture, input and tray (#22)

* fix(setup): verify provisioning and runtime readiness

* feat: add explicit per-user uninstall and purge

* fix: restore niri input and provide native capture and tray

* fix(build): declare Wayland scanner and release dependencies
This commit is contained in:
Xuc Pan authored and GitHub committed 2026-10-13 15:26:06 +08:00
1 parent d349e6ff6a
commit 8c0589021f
38 files changed
+2409 -185

No files matched your search

+2 -1
View File
@@ -9,10 +9,11 @@ pub fn enable() -> Result<()> {
std::fs::create_dir_all(parent)?;
let executable = std::env::current_exe().context("resolving uur executable")?;
let exec = desktop_exec_argument(&executable.to_string_lossy());
let prefix = crate::config::data_dir()?.join("wine");
std::fs::write(
&path,
format!(
"[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"
"[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\nX-UUR-Managed=true\nX-UUR-Prefix={}\n", prefix.display()
),
)?;
println!(
+9 -1
View File
@@ -133,8 +133,16 @@ pub fn print_pointer() -> Result<()> {
/// input events without holding the backend lock while waiting for records.
pub fn serve() -> Result<()> {
let config = Config::load()?;
let preferred =
let mut preferred =
std::env::var("UUR_INPUT_BACKEND").unwrap_or_else(|_| config.input_backend.clone());
if config.capture_backend == "wayland" {
if preferred == "auto" {
preferred = "uinput".into();
}
if preferred == "portal" {
anyhow::bail!("direct Wayland capture uses uinput; choose UUR_INPUT_BACKEND=uinput or return to portal capture");
}
}
let selected = input::select(&preferred)?;
if let Some(path) = std::env::var_os("UUR_BACKEND_STATUS") {
std::fs::write(path, selected.name()).context("writing backend status")?;
+153 -43
View File
@@ -13,25 +13,123 @@
//! a headless remote host.
use anyhow::{anyhow, Context, Result};
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::fd::OwnedFd;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::config::Config;
/// Run the capture path until interrupted.
pub fn run_standalone() -> Result<()> {
// Public capture uses the same lifecycle lock as run/setup so stop and
// uninstall can also shut down a diagnostic ScreenCast session. Internal
// capture already runs under the supervisor's lock.
let _session_lock = crate::session::acquire_session_lock()?;
run()
}
pub fn run() -> Result<()> {
let mut config = Config::load()?;
let (pw_fd, node) = portal_session(&mut config)?;
println!("{}", t!("capture.session_ready", node = node));
let mut helper = spawn_helper(pw_fd, node)?;
let status = helper.wait().context("waiting for capture helper")?;
if !status.success() {
anyhow::bail!("{}", t!("capture.helper_failed"));
let stopping = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?;
signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?;
if config.capture_backend == "wayland" {
if config.capture_source != "monitor" {
anyhow::bail!("direct Wayland capture requires a monitor source");
}
let mut command = Command::new(find_helper("uur-wl-capture")?);
command.env("UUR_FRAME_PATH", frame_path()?);
if let Some(output) = &config.capture_output {
command.env("UUR_CAPTURE_OUTPUT", output);
}
let mut helper = CaptureHelper(command.spawn().context("starting direct Wayland capture")?);
println!("{}", t!("capture.direct_started"));
while !stopping.load(Ordering::Relaxed) {
if let Some(status) = helper.0.try_wait()? {
if !status.success() {
anyhow::bail!("direct Wayland capture failed ({status})");
}
return Ok(());
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
return Ok(());
}
Ok(())
if config.capture_backend != "portal" {
anyhow::bail!("unknown capture backend {:?}", config.capture_backend);
}
let runtime = tokio::runtime::Runtime::new().context("creating capture runtime")?;
// The portal's D-Bus connection runs on this runtime. Keep it running
// throughout capture, including on capture-only compositors such as niri.
runtime.block_on(async {
let (pw_fd, node) = tokio::select! {
result = portal_session(&mut config) => result?,
_ = wait_for_stop(&stopping) => return Ok(()),
};
println!("{}", t!("capture.session_ready", node = node));
let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?);
loop {
if stopping.load(Ordering::Relaxed) {
return Ok(());
}
if let Some(status) = helper.0.try_wait().context("waiting for capture helper")? {
if !status.success() {
anyhow::bail!("{}", t!("capture.helper_failed"));
}
return Ok(());
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
})
}
async fn wait_for_stop(stopping: &AtomicBool) {
while !stopping.load(Ordering::Relaxed) {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
}
struct CaptureHelper(Child);
impl Drop for CaptureHelper {
fn drop(&mut self) {
if self.0.try_wait().ok().flatten().is_some() {
return;
}
unsafe {
libc::kill(self.0.id() as i32, libc::SIGTERM);
}
for _ in 0..100 {
if self.0.try_wait().ok().flatten().is_some() {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let _ = self.0.kill();
let _ = self.0.wait();
}
}
pub(crate) fn has_frame(path: &Path) -> bool {
let mut header = [0u8; 64];
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
if file.read_exact(&mut header).is_err() {
return false;
}
let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap());
field(0) == 0x4652_5555
&& field(4) == 1
&& field(8) > 0
&& field(12) > 0
&& field(16) >= field(8).saturating_mul(4)
&& field(20) == 1
&& u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0
}
/// Start the native PipeWire consumer with a portal-owned descriptor. The
@@ -51,7 +149,7 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
}
}
let helper = find_helper()?;
let helper = find_helper("uur-pw-capture")?;
let mut command = Command::new(&helper);
command
.env("UUR_PW_FD", raw.to_string())
@@ -78,32 +176,34 @@ fn frame_path() -> Result<PathBuf> {
/// token, monitor changed, compositor restart) fall back to one
/// interactive attempt and store the fresh token.
#[allow(clippy::type_complexity)]
fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
async fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> {
let saved_token = config.capture_restore_token.clone();
let runtime = tokio::runtime::Runtime::new().context("creating tokio runtime")?;
runtime.block_on(async move {
let screencast = ashpd::desktop::screencast::Screencast::new()
.await
.context("connecting to the ScreenCast portal")?;
let screencast = ashpd::desktop::screencast::Screencast::new()
.await
.context("connecting to the ScreenCast portal")?;
let mut last_error = None;
let source = source_type(&config.capture_source);
for token in [saved_token.clone(), None] {
match negotiate(&screencast, source, token.as_deref()).await {
Ok((fd, node, fresh_token)) => {
if fresh_token != saved_token {
config.capture_restore_token = fresh_token;
config.store().context("storing the new restore token")?;
}
return Ok((fd, node));
}
Err(error) => {
last_error = Some(error);
let mut last_error = None;
let source = source_type(&config.capture_source);
for token in saved_token
.clone()
.map(Some)
.into_iter()
.chain(std::iter::once(None))
{
match negotiate(&screencast, source, token.as_deref()).await {
Ok((fd, node, fresh_token)) => {
if fresh_token != saved_token {
config.capture_restore_token = fresh_token;
config.store().context("storing the new restore token")?;
}
return Ok((fd, node));
}
Err(error) => {
last_error = Some(error);
}
}
Err(last_error.unwrap_or_else(|| anyhow!("portal session failed")))
})
}
Err(last_error.unwrap_or_else(|| anyhow!("portal session failed")))
}
/// One full portal handshake. Returns the PipeWire fd, the video node id
@@ -127,7 +227,8 @@ async fn negotiate(
restore_token,
PersistMode::ExplicitlyRevoked,
)
.await?;
.await?
.response()?;
let response = screencast.start(&session, None).await?;
let streams_response = response.response()?;
@@ -152,28 +253,37 @@ pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType
}
}
fn find_helper() -> Result<PathBuf> {
pub fn list_wayland_outputs() -> Result<()> {
let status = Command::new(find_helper("uur-wl-capture")?)
.arg("--list-outputs")
.status()?;
anyhow::ensure!(status.success(), "could not enumerate Wayland outputs");
Ok(())
}
fn find_helper(name: &str) -> Result<PathBuf> {
let mut candidates = vec![
PathBuf::from("/usr/lib/uur/uur-pw-capture"),
PathBuf::from("/usr/local/lib/uur/uur-pw-capture"),
PathBuf::from("/usr/lib/uur").join(name),
PathBuf::from("/usr/local/lib/uur").join(name),
];
if let Ok(home) = std::env::var("HOME") {
candidates.push(PathBuf::from(home).join(".local/lib/uur/uur-pw-capture"));
candidates.push(PathBuf::from(home).join(".local/lib/uur").join(name));
}
if let Ok(exe) = std::env::current_exe() {
// dev checkout: target/debug/uur -> capture/uur-pw-capture
if let Some(dir) = exe.parent() {
candidates.push(dir.join("../lib/uur/uur-pw-capture"));
candidates.push(dir.join("../../capture/uur-pw-capture"));
candidates.push(dir.join("uur-pw-capture"));
candidates.push(dir.join("../lib/uur").join(name));
candidates.push(dir.join("../../capture").join(name));
candidates.push(dir.join(name));
}
}
if let Ok(cwd) = std::env::current_dir() {
candidates.push(cwd.join("capture/uur-pw-capture"));
candidates.push(cwd.join("capture").join(name));
}
candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| {
anyhow!("capture helper uur-pw-capture not found (build with capture/build.sh)")
})
candidates
.into_iter()
.find(|p| p.is_file())
.ok_or_else(|| anyhow!("capture helper {name} not found (build with capture/build.sh)"))
}
#[cfg(test)]
+7 -1
View File
@@ -13,7 +13,7 @@ pub struct Config {
pub bridge_port: u16,
/// Random per-install token the hook must present on HELLO.
pub bridge_token: String,
/// Preferred input backend: "auto" | "xtest" | "portal".
/// Preferred input backend: "auto" | "xtest" | "portal" | "uinput".
pub input_backend: String,
/// Release channel pinned for provisioning.
pub pinned_version: Option<String>,
@@ -24,6 +24,10 @@ pub struct Config {
pub remote_desktop_restore_token: Option<String>,
/// Portal source type: monitor, window, or virtual.
pub capture_source: String,
/// "portal" uses system consent; "wayland" is explicitly enabled direct monitor capture.
pub capture_backend: String,
/// Named Wayland output for direct capture; a single-output session needs no name.
pub capture_output: Option<String>,
}
impl Default for Config {
@@ -37,6 +41,8 @@ impl Default for Config {
capture_restore_token: None,
remote_desktop_restore_token: None,
capture_source: "monitor".into(),
capture_backend: "portal".into(),
capture_output: None,
}
}
}
+86 -14
View File
@@ -130,13 +130,16 @@ fn portal_capabilities() -> (bool, bool, String) {
runtime.block_on(async {
let (capture, sources) = match ashpd::desktop::screencast::Screencast::new().await {
Ok(portal) => match portal.available_source_types().await {
Ok(types) => (true, format!("{types:?}")),
Ok(types) => (!types.is_empty(), format!("{types:?}")),
Err(_) => (false, "unavailable".into()),
},
Err(_) => (false, "unavailable".into()),
};
let input = match ashpd::desktop::remote_desktop::RemoteDesktop::new().await {
Ok(portal) => portal.available_device_types().await.is_ok(),
Ok(portal) => portal.available_device_types().await.is_ok_and(|types| {
types.contains(ashpd::desktop::remote_desktop::DeviceType::Keyboard)
&& types.contains(ashpd::desktop::remote_desktop::DeviceType::Pointer)
}),
Err(_) => false,
};
(capture, input, sources)
@@ -176,6 +179,32 @@ pub fn report() -> Result<()> {
};
line(ok(missing_wine), "wine", &wine_detail);
let prefix = crate::config::data_dir()?.join("wine");
line(
ok(!crate::wine::prefix_initialized(&prefix)),
"managed Wine prefix",
&prefix.display().to_string(),
);
let client = crate::wine::find_client_dir(&prefix);
let client_detail = client
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_else(|| t!("doctor.client_incomplete").to_string());
line(ok(client.is_none()), "UU client and server", &client_detail);
let service = crate::wine::client_service_registered(&prefix);
let service_detail = if service {
t!("doctor.service_registered").to_string()
} else {
t!("doctor.service_missing").to_string()
};
line(ok(!service), "GameViewerService", &service_detail);
let webview_detail = if crate::wine::webview2_installed(&prefix) {
t!("doctor.present").to_string()
} else {
t!("doctor.webview_pending").to_string()
};
line("info", "WebView2 runtime", &webview_detail);
let backends = portal_backends();
let has_portal_impl = !backends.is_empty();
let portal_detail = if backends.is_empty() {
@@ -187,7 +216,7 @@ pub fn report() -> Result<()> {
let (portal_capture, portal_input, portal_sources) = portal_capabilities();
let portal_capture_detail = if portal_capture {
t!("doctor.present").to_string()
t!("doctor.portal_capture_advertised").to_string()
} else {
t!("doctor.portal_capture_missing").to_string()
};
@@ -198,7 +227,7 @@ pub fn report() -> Result<()> {
);
line("info", "portal source types", &portal_sources);
let portal_input_detail = if portal_input {
t!("doctor.present").to_string()
t!("doctor.portal_input_advertised").to_string()
} else {
t!("doctor.portal_input_missing").to_string()
};
@@ -313,19 +342,62 @@ pub fn report() -> Result<()> {
let uinput_missing = uinput_detail != t!("doctor.present");
line(ok(uinput_missing), "uinput (/dev/uinput)", &uinput_detail);
// Mirror the real auto policy in input::select.
// Report the configured policy; portal properties do not validate that
// the compositor can successfully create an authorized session.
let session_type = std::env::var("XDG_SESSION_TYPE").unwrap_or_default();
let (backend, backend_note) = if session_type == "wayland" && portal_input {
("portal", t!("doctor.backend_portal").to_string())
} else if session_type == "wayland" && !uinput_missing {
("uinput", t!("doctor.backend_wayland").to_string())
} else if std::env::var("DISPLAY").is_ok() {
("xtest", t!("doctor.backend_x11").to_string())
} else {
("none", t!("doctor.backend_none").to_string())
};
let on_wayland = session_type == "wayland" || std::env::var_os("WAYLAND_DISPLAY").is_some();
let configured = crate::config::Config::load()?;
line(
"info",
"capture backend",
&format!(
"{} ({})",
configured.capture_backend,
configured
.capture_output
.as_deref()
.unwrap_or("selected/default output")
),
);
let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or(configured.input_backend);
if configured.capture_backend == "wayland" && preferred == "auto" {
preferred = "uinput".into();
}
let (status, backend, backend_note) = match preferred.as_str() {
"portal" => (
ok(!portal_input),
"portal",
t!("doctor.backend_portal").to_string(),
),
"uinput" => (
ok(uinput_missing),
"uinput",
t!("doctor.backend_wayland").to_string(),
),
"xtest" if on_wayland => ("WARN", "xtest", t!("doctor.backend_partial").to_string()),
"xtest" => (
ok(std::env::var_os("DISPLAY").is_none()),
"xtest",
t!("doctor.backend_x11").to_string(),
),
"auto" if on_wayland && portal_input => {
("info", "portal", t!("doctor.backend_portal").to_string())
}
"auto" if on_wayland && !uinput_missing => {
("info", "uinput", t!("doctor.backend_wayland").to_string())
}
"auto" if on_wayland => (
"MISS",
"none",
t!("doctor.backend_wayland_missing").to_string(),
),
"auto" if std::env::var_os("DISPLAY").is_some() => {
("info", "xtest", t!("doctor.backend_x11").to_string())
}
_ => ("MISS", "none", t!("doctor.backend_none").to_string()),
};
line(
status,
"input backend",
&format!("{backend} ({backend_note})"),
);
+8 -2
View File
@@ -24,7 +24,11 @@ pub trait InputBackend: Send {
/// kernel-level uinput device when the compositor only provides ScreenCast.
/// - X11 sessions use XTEST, which needs no extra privileges.
pub fn select(preferred: &str) -> Result<Box<dyn InputBackend>> {
let on_wayland = std::env::var("WAYLAND_DISPLAY").is_ok();
let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland");
if !matches!(preferred, "auto" | "portal" | "uinput" | "xtest") {
anyhow::bail!("unknown input backend {preferred:?}; use auto, portal, uinput, or xtest");
}
if preferred == "portal" || (preferred == "auto" && on_wayland) {
match portal::PortalBackend::connect() {
@@ -39,10 +43,12 @@ pub fn select(preferred: &str) -> Result<Box<dyn InputBackend>> {
Err(error) if preferred == "uinput" => return Err(error),
Err(error) => {
eprintln!("{}: {error}", t!("input.uinput_unavailable"));
// fall through to XTEST: partial reachability beats nothing
}
}
}
if on_wayland && preferred == "auto" {
anyhow::bail!("{}", t!("input.wayland_no_full_input"));
}
if std::env::var("DISPLAY").is_ok() {
return Ok(Box::new(xtest::XtestBackend::connect()?));
}
+10 -4
View File
@@ -12,7 +12,7 @@ const UI_SET_EVBIT: libc::Ioctl = 0x4004_5564_u64 as libc::Ioctl;
const UI_SET_KEYBIT: libc::Ioctl = 0x4004_5565_u64 as libc::Ioctl;
const UI_SET_RELBIT: libc::Ioctl = 0x4004_5566_u64 as libc::Ioctl;
const UI_SET_ABSBIT: libc::Ioctl = 0x4004_5567_u64 as libc::Ioctl;
// struct uinput_setup = name[80] + input_id(8) + ff_effects_max(4) = 92 bytes
// struct uinput_setup = input_id(8) + name[80] + ff_effects_max(4) = 92 bytes
const UI_DEV_SETUP: libc::Ioctl = 0x405C_5503_u64 as libc::Ioctl;
// struct uinput_abs_setup = u16 code + input_absinfo(24) = 28 bytes
const UI_ABS_SETUP: libc::Ioctl = 0x401C_5504_u64 as libc::Ioctl;
@@ -40,6 +40,8 @@ const BTN_MIDDLE: u16 = 0x112;
const BTN_SIDE: u16 = 0x116;
const BTN_EXTRA: u16 = 0x117;
const BTN_TOOL_PEN: u16 = 0x140;
const BTN_TOUCH: u16 = 0x14a;
const BTN_STYLUS: u16 = 0x14b;
const BUS_VIRTUAL: u16 = 0x06;
@@ -53,14 +55,14 @@ struct InputEvent {
value: i32,
}
/// struct uinput_setup: name[80] + input_id(4×u16) + ff_effects_max(u32).
/// Linux ABI: input_id(4×u16), then name[80], then ff_effects_max(u32).
#[repr(C)]
struct UinputSetup {
name: [u8; 80],
bustype: u16,
vendor: u16,
product: u16,
version: u16,
name: [u8; 80],
ff_effects_max: u32,
}
@@ -142,7 +144,9 @@ impl UinputDevice {
maximum,
fuzz: 0,
flat: 0,
resolution: 0,
// libinput requires physical axis resolution for tablets. A
// 65.535 mm virtual surface maps the full normalized range.
resolution: 1000,
};
let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_ABS_SETUP, &setup) };
if rc < 0 {
@@ -235,6 +239,8 @@ impl Devices {
ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_ABS as u32)?;
ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_SYN as u32)?;
tablet.keybit(BTN_TOOL_PEN)?;
tablet.keybit(BTN_TOUCH)?;
tablet.keybit(BTN_STYLUS)?;
tablet.absbit(ABS_X, 65535)?;
tablet.absbit(ABS_Y, 65535)?;
tablet.finish()?;
+77 -2
View File
@@ -15,6 +15,8 @@ mod protocol;
mod proxy;
mod session;
mod terminal;
mod tray;
mod uninstall;
mod upstream;
mod video;
mod wallpaper;
@@ -46,6 +48,9 @@ enum Command {
/// Accept the NetEase UU Remote EULA non-interactively.
#[arg(long)]
accept_eula: bool,
/// Update the existing Wine prefix, retry Wine components, and repair an incomplete client installation.
#[arg(long)]
repair: bool,
},
/// Print the live environment report (sessions, wine, portals, backends).
Doctor,
@@ -57,6 +62,18 @@ enum Command {
Run,
/// Stop every uur-owned process and the managed Wine prefix.
Stop,
/// Remove this user's integration and source installation; optionally erase all managed data.
Uninstall {
/// Delete the managed Wine prefix, account data, installer cache, configuration and logs.
#[arg(long)]
purge: bool,
/// Show the exact removal plan without stopping processes or changing files.
#[arg(long)]
dry_run: bool,
/// Confirm removal without an interactive prompt.
#[arg(long)]
yes: bool,
},
/// Manage optional XDG login autostart.
Autostart {
#[command(subcommand)]
@@ -87,6 +104,9 @@ enum Command {
/// Internal desktop suspend/idle inhibitor. Not part of the public CLI.
#[command(hide = true, name = "__inhibit")]
InternalInhibit,
/// Internal native desktop tray. Not part of the public CLI.
#[command(hide = true, name = "__tray")]
InternalTray,
/// Internal authenticated XDG application launcher.
#[command(hide = true, name = "__launcher")]
InternalLauncher,
@@ -138,6 +158,21 @@ enum DisplayAction {
Status,
/// Use a monitor, one window, or a portal-provided virtual display.
Source { source: DisplaySource },
/// Choose portal capture, or explicitly enable direct Wayland monitor capture.
Backend {
backend: CaptureBackend,
/// Name from `uur display outputs`; required if more than one output is present.
#[arg(long)]
output: Option<String>,
},
/// List native Wayland outputs without capturing their content.
Outputs,
}
#[derive(Clone, ValueEnum)]
enum CaptureBackend {
Portal,
Wayland,
}
#[derive(Clone, ValueEnum)]
@@ -165,12 +200,20 @@ fn main() -> Result<()> {
i18n::init();
let cli = Cli::parse();
match cli.command {
Command::Setup { accept_eula } => wine::setup(accept_eula),
Command::Setup {
accept_eula,
repair,
} => wine::setup(accept_eula, repair),
Command::Doctor => doctor::report(),
Command::Pointer => bridge::print_pointer(),
Command::Capture => capture::run(),
Command::Capture => capture::run_standalone(),
Command::Run => session::start(),
Command::Stop => session::stop(),
Command::Uninstall {
purge,
dry_run,
yes,
} => uninstall::run(purge, dry_run, yes),
Command::Autostart { action } => match action {
AutostartAction::Enable => autostart::enable(),
AutostartAction::Disable => autostart::disable(),
@@ -182,12 +225,43 @@ fn main() -> Result<()> {
WolAction::Disable { interface } => wol::configure(interface.as_deref(), false),
},
Command::Display { action } => {
if matches!(action, DisplayAction::Outputs) {
return capture::list_wayland_outputs();
}
let mut config = config::Config::load()?;
match action {
DisplayAction::Status => {
println!("{}", t!("display.status", source = config.capture_source));
println!("capture backend: {}", config.capture_backend);
if let Some(output) = &config.capture_output {
println!("output: {output}");
}
Ok(())
}
DisplayAction::Backend { backend, output } => {
config.capture_backend = match backend {
CaptureBackend::Portal => "portal",
CaptureBackend::Wayland => "wayland",
}
.into();
config.capture_output = output;
if config.capture_backend == "wayland" {
config.capture_source = "monitor".into();
}
config.capture_restore_token = None;
config.remote_desktop_restore_token = None;
config.store()?;
println!(
"{}",
if config.capture_backend == "wayland" {
t!("capture.direct_enabled").to_string()
} else {
t!("capture.portal_enabled").to_string()
}
);
Ok(())
}
DisplayAction::Outputs => unreachable!(),
DisplayAction::Source { source } => {
config.capture_source = source.as_str().to_string();
config.capture_restore_token = None;
@@ -203,6 +277,7 @@ fn main() -> Result<()> {
Command::InternalTerminal => terminal::serve(),
Command::InternalWallpaper => wallpaper::serve(),
Command::InternalInhibit => inhibit::serve(),
Command::InternalTray => tray::serve(),
Command::InternalLauncher => launcher::serve(),
Command::Upstream {
action: UpstreamAction::Check,
+123 -13
View File
@@ -251,8 +251,7 @@ fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command {
}
fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
let marker = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application");
if marker.exists() {
if crate::wine::webview2_installed(prefix) {
return Ok(());
}
let bootstrapper = install_dir
@@ -265,7 +264,7 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
let status = webview2_install_command(prefix, &bootstrapper)
.status()
.context("running the WebView2 bootstrapper")?;
if !status.success() {
if !status.success() || !crate::wine::webview2_installed(prefix) {
anyhow::bail!("{}", t!("session.webview_failed"));
}
Ok(())
@@ -274,7 +273,7 @@ fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
/// Single-instance guard: an flock held for the lifetime of the session.
/// A second click on the launcher exits with a clear message instead of
/// fighting over the bridge port.
fn acquire_session_lock() -> Result<std::fs::File> {
pub(crate) fn acquire_session_lock() -> Result<std::fs::File> {
use std::os::unix::io::AsRawFd;
let state = std::env::var("XDG_STATE_HOME")
.map(PathBuf::from)
@@ -306,6 +305,7 @@ fn acquire_session_lock() -> Result<std::fs::File> {
struct ManagedChild {
child: Child,
name: String,
terminated: bool,
}
@@ -326,10 +326,21 @@ impl ManagedChild {
.with_context(|| format!("starting internal helper {argument}"))?;
Ok(Self {
child,
name: argument.to_string(),
terminated: false,
})
}
fn ensure_running(&mut self) -> Result<()> {
if let Some(status) = self.child.try_wait()? {
anyhow::bail!(
"helper {} exited ({status}); see $XDG_STATE_HOME/uur/session.log (normally ~/.local/state/uur/session.log)",
self.name
);
}
Ok(())
}
fn terminate(&mut self) {
if self.terminated {
return;
@@ -392,6 +403,18 @@ impl SessionResources {
let _ = std::fs::remove_file(path);
}
}
fn check_required_helpers(&mut self) -> Result<()> {
for helper in &mut self.helpers {
if matches!(
helper.name.as_str(),
"__bridge" | "__capture" | "__terminal" | "__launcher"
) {
helper.ensure_running()?;
}
}
Ok(())
}
}
impl Drop for SessionResources {
@@ -405,9 +428,15 @@ pub fn start() -> Result<()> {
let _session_lock = acquire_session_lock()?;
rotate_session_log();
let config = Config::load()?;
let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland");
let prefix = data_dir()?.join("wine");
let install_dir = crate::wine::find_client_dir(&prefix)
.context("client not provisioned; run `uur setup` first")?;
.context("client installation incomplete; run `uur setup --repair` first")?;
if !crate::wine::client_service_registered(&prefix) {
anyhow::bail!("{}", t!("setup.service_incomplete"));
}
let mut resources = SessionResources::new(prefix.clone());
if let Some(dpi) = xft_dpi() {
match crate::wine::set_log_pixels(&prefix, dpi) {
Ok(()) => println!("{}", t!("session.wine_dpi", dpi = dpi)),
@@ -428,6 +457,11 @@ pub fn start() -> Result<()> {
// Bridge configuration as a file inside the prefix: any process the
// Wine service manager respawns reads it, env or not.
let frames = frame_path()?;
match std::fs::remove_file(&frames) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("removing the previous capture transport"),
}
let backend_status = crate::config::runtime_dir()?.join("backend");
let _ = std::fs::remove_file(&backend_status);
std::env::set_var("UUR_FRAME_PATH", &frames);
@@ -464,7 +498,10 @@ pub fn start() -> Result<()> {
signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?;
let log = open_session_log()?;
let mut resources = SessionResources::new(prefix.clone());
match ManagedChild::spawn_internal("__tray", &log) {
Ok(helper) => resources.helpers.push(helper),
Err(error) => eprintln!("native tray unavailable: {error}"),
}
let _ = std::fs::remove_file(&terminal_config);
std::env::set_var("UUR_TERMINAL_CONFIG", &terminal_config);
resources.cleanup_files.push(terminal_config.clone());
@@ -489,14 +526,29 @@ pub fn start() -> Result<()> {
resources
.helpers
.push(ManagedChild::spawn_internal("__bridge", &log)?);
wait_for_bridge(config.bridge_port, &stopping)?;
wait_for_bridge(
config.bridge_port,
&stopping,
resources.helpers.last_mut().unwrap(),
)?;
let selected_backend = std::fs::read_to_string(&backend_status).unwrap_or_default();
let _ = std::fs::remove_file(&backend_status);
if std::env::var_os("WAYLAND_DISPLAY").is_some() && selected_backend.trim() != "portal" {
if on_wayland && selected_backend.trim() != "portal" {
resources
.helpers
.push(ManagedChild::spawn_internal("__capture", &log)?);
}
if on_wayland {
println!(
"{}",
if config.capture_backend == "wayland" {
t!("session.waiting_direct_capture").to_string()
} else {
t!("session.waiting_capture").to_string()
}
);
wait_for_capture(&frames, &stopping, &mut resources)?;
}
// The service enumerates processes for a winlogon session token source
// before it initialises; under plain Wine none exists. A sleeping
@@ -527,12 +579,18 @@ pub fn start() -> Result<()> {
.args(["sc", "start", "GameViewerService"])
.status();
}
for _ in 0..150 {
if service_running(&prefix) {
break;
let service_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !service_running(&prefix) {
resources.check_required_helpers()?;
if stopping.load(Ordering::Relaxed) {
anyhow::bail!("session startup cancelled");
}
if std::time::Instant::now() >= service_deadline {
anyhow::bail!("{}", t!("session.service_failed"));
}
thread::sleep(std::time::Duration::from_millis(200));
}
println!("{}", t!("session.server_running"));
println!("{}", t!("session.launching_client"));
let ui = install_dir.join("GameViewer.exe");
@@ -559,6 +617,7 @@ pub fn start() -> Result<()> {
let mut missing_checks = 0u8;
let mut relaunches = 0;
while !stopping.load(Ordering::Relaxed) {
resources.check_required_helpers()?;
let running = wine_client_process_exists(&prefix);
if running {
seen_client = true;
@@ -652,7 +711,7 @@ fn service_running(prefix: &Path) -> bool {
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args(["sc", "query", "GameViewerService"]),
std::time::Duration::from_secs(10),
std::time::Duration::from_secs(3),
);
match output {
Some(text) => text.lines().any(|line| {
@@ -702,6 +761,35 @@ pub fn stop() -> Result<()> {
Ok(())
}
/// Activate the official client's existing single-instance UI from the
/// native tray without starting another capture/input supervisor.
pub(crate) fn show_client() -> Result<()> {
let prefix = data_dir()?.join("wine");
let install =
crate::wine::find_client_dir(&prefix).context("managed client is not installed")?;
let Some((pid, start)) = read_session_identity()? else {
anyhow::bail!("managed session is not running");
};
if process_start_time(pid).ok() != Some(start) {
anyhow::bail!("managed session is not running");
}
let mut child = Command::new("wine")
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
.current_dir(&install)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.arg(install.join("GameViewer.exe"))
.spawn()
.context("showing the managed client")?;
thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
fn state_dir() -> PathBuf {
std::env::var("XDG_STATE_HOME")
.map(PathBuf::from)
@@ -754,7 +842,7 @@ fn unix_path_to_wine(path: &Path) -> String {
format!("Z:{}", path.display()).replace('/', "\\")
}
fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> {
fn wait_for_bridge(port: u16, stopping: &AtomicBool, helper: &mut ManagedChild) -> Result<()> {
// The first RemoteDesktop portal grant is intentionally interactive.
// Keep the supervisor alive while the user chooses a monitor instead of
// treating a two-second consent delay as a bridge failure.
@@ -762,6 +850,7 @@ fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> {
if stopping.load(Ordering::Relaxed) {
anyhow::bail!("session startup cancelled");
}
helper.ensure_running()?;
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
return Ok(());
}
@@ -770,6 +859,27 @@ fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> {
anyhow::bail!("input bridge did not become ready")
}
fn wait_for_capture(
frames: &Path,
stopping: &AtomicBool,
resources: &mut SessionResources,
) -> Result<()> {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
loop {
if stopping.load(Ordering::Relaxed) {
anyhow::bail!("session startup cancelled");
}
resources.check_required_helpers()?;
if crate::capture::has_frame(frames) {
return Ok(());
}
if std::time::Instant::now() >= deadline {
anyhow::bail!("{}", t!("session.capture_not_ready"));
}
thread::sleep(std::time::Duration::from_millis(50));
}
}
fn wait_for_runtime_file(path: &Path, stopping: &AtomicBool) -> Result<()> {
for _ in 0..250 {
if stopping.load(Ordering::Relaxed) {
+316
View File
@@ -0,0 +1,316 @@
//! Native StatusNotifierItem and DBusMenu, independent of Wine's XEmbed tray.
//! The supervisor owns this helper, so closing the session removes the item.
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
type Pixmap = (i32, i32, Vec<u8>);
type Properties = HashMap<String, OwnedValue>;
type Layout = (i32, Properties, Vec<OwnedValue>);
#[derive(Clone, Copy)]
enum Action {
Show,
Stop,
}
struct Tray {
actions: UnboundedSender<Action>,
icon: Pixmap,
}
#[zbus::interface(name = "org.kde.StatusNotifierItem")]
impl Tray {
#[zbus(property)]
fn category(&self) -> &str {
"ApplicationStatus"
}
#[zbus(property)]
fn id(&self) -> &str {
"uur"
}
#[zbus(property)]
fn title(&self) -> String {
t!("tray.title").to_string()
}
#[zbus(property)]
fn status(&self) -> &str {
"Active"
}
#[zbus(property)]
fn window_id(&self) -> i32 {
0
}
#[zbus(property)]
fn icon_name(&self) -> &str {
"uur"
}
#[zbus(property)]
fn icon_theme_path(&self) -> &str {
""
}
#[zbus(property)]
fn icon_pixmap(&self) -> Vec<Pixmap> {
vec![self.icon.clone()]
}
#[zbus(property)]
fn attention_icon_name(&self) -> &str {
""
}
#[zbus(property)]
fn attention_icon_pixmap(&self) -> Vec<Pixmap> {
Vec::new()
}
#[zbus(property)]
fn attention_movie_name(&self) -> &str {
""
}
#[zbus(property)]
fn overlay_icon_name(&self) -> &str {
""
}
#[zbus(property)]
fn overlay_icon_pixmap(&self) -> Vec<Pixmap> {
Vec::new()
}
#[zbus(property)]
fn item_is_menu(&self) -> bool {
false
}
#[zbus(property)]
fn menu(&self) -> OwnedObjectPath {
OwnedObjectPath::try_from("/MenuBar").unwrap()
}
#[zbus(property)]
fn tool_tip(&self) -> (String, Vec<Pixmap>, String, String) {
(
"uur".into(),
vec![self.icon.clone()],
t!("tray.title").to_string(),
t!("tray.tooltip").to_string(),
)
}
fn activate(&self, _x: i32, _y: i32) {
let _ = self.actions.send(Action::Show);
}
fn secondary_activate(&self, _x: i32, _y: i32) {
let _ = self.actions.send(Action::Show);
}
// Hosts draw the menu returned by Menu; no X11 popup is necessary.
fn context_menu(&self, _x: i32, _y: i32) {}
fn scroll(&self, _delta: i32, _orientation: &str) {}
fn provide_xdg_activation_token(&self, _token: &str) {}
}
struct Menu {
actions: UnboundedSender<Action>,
}
#[zbus::interface(name = "com.canonical.dbusmenu")]
impl Menu {
#[zbus(property)]
fn version(&self) -> u32 {
3
}
#[zbus(property)]
fn text_direction(&self) -> &str {
"ltr"
}
#[zbus(property)]
fn status(&self) -> &str {
"normal"
}
#[zbus(property)]
fn icon_theme_path(&self) -> Vec<String> {
Vec::new()
}
fn get_layout(
&self,
parent_id: i32,
recursion_depth: i32,
property_names: Vec<String>,
) -> zbus::fdo::Result<(u32, Layout)> {
let properties = menu_properties(parent_id, &property_names)?;
let mut children = Vec::new();
if parent_id == 0 && recursion_depth != 0 {
for id in [1, 2] {
let child = (
id,
menu_properties(id, &property_names)?,
Vec::<OwnedValue>::new(),
);
children.push(
OwnedValue::try_from(Value::new(child))
.map_err(|error| zbus::fdo::Error::Failed(error.to_string()))?,
);
}
}
Ok((1, (parent_id, properties, children)))
}
fn get_group_properties(
&self,
ids: Vec<i32>,
property_names: Vec<String>,
) -> zbus::fdo::Result<Vec<(i32, Properties)>> {
let ids = if ids.is_empty() { vec![0, 1, 2] } else { ids };
ids.into_iter()
.map(|id| Ok((id, menu_properties(id, &property_names)?)))
.collect()
}
fn get_property(&self, id: i32, name: &str) -> zbus::fdo::Result<OwnedValue> {
menu_properties(id, &[])?
.remove(name)
.ok_or_else(|| zbus::fdo::Error::InvalidArgs(format!("unknown menu property {name}")))
}
fn event(
&self,
id: i32,
event_id: &str,
_data: OwnedValue,
_timestamp: u32,
) -> zbus::fdo::Result<()> {
let action = match id {
1 => Action::Show,
2 => Action::Stop,
0 => return Ok(()),
_ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())),
};
if event_id == "clicked" {
let _ = self.actions.send(action);
}
Ok(())
}
fn event_group(&self, events: Vec<(i32, String, OwnedValue, u32)>) -> Vec<i32> {
events
.into_iter()
.filter_map(|(id, event, data, timestamp)| {
self.event(id, &event, data, timestamp).err().map(|_| id)
})
.collect()
}
fn about_to_show(&self, id: i32) -> zbus::fdo::Result<bool> {
menu_properties(id, &[])?;
Ok(false)
}
fn about_to_show_group(&self, ids: Vec<i32>) -> (Vec<i32>, Vec<i32>) {
(
Vec::new(),
ids.into_iter().filter(|id| !(0..=2).contains(id)).collect(),
)
}
}
fn menu_properties(id: i32, requested: &[String]) -> zbus::fdo::Result<Properties> {
let mut properties = Properties::new();
let string = |value: String| OwnedValue::from(zbus::zvariant::Str::from(value));
match id {
0 => {
properties.insert("children-display".into(), string("submenu".into()));
}
1 | 2 => {
properties.insert(
"label".into(),
string(if id == 1 {
t!("tray.open").to_string()
} else {
t!("tray.quit").to_string()
}),
);
properties.insert("enabled".into(), OwnedValue::from(true));
properties.insert("visible".into(), OwnedValue::from(true));
}
_ => return Err(zbus::fdo::Error::InvalidArgs("unknown menu item".into())),
}
if !requested.is_empty() {
properties.retain(|key, _| requested.contains(key));
}
Ok(properties)
}
fn icon_pixmap() -> Result<Pixmap> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(include_bytes!(
"../packaging/uur-icon.png"
)));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().context("reading tray icon")?;
let mut pixels = vec![
0;
reader
.output_buffer_size()
.context("tray icon size overflow")?
];
let info = reader
.next_frame(&mut pixels)
.context("decoding tray icon")?;
anyhow::ensure!(
info.color_type == png::ColorType::Rgba,
"tray icon must be RGBA"
);
pixels.truncate(info.buffer_size());
// SNI requires network-byte-order ARGB32, not PNG's RGBA byte order.
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.rotate_right(1);
}
Ok((info.width.try_into()?, info.height.try_into()?, pixels))
}
pub fn serve() -> Result<()> {
let stopping = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?;
signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?;
tokio::runtime::Runtime::new()?.block_on(async {
let (actions, mut receiver) = unbounded_channel();
let connection = zbus::connection::Builder::session()?
.serve_at("/StatusNotifierItem", Tray { actions: actions.clone(), icon: icon_pixmap()? })?
.serve_at("/MenuBar", Menu { actions })?.build().await?;
let bus = zbus::fdo::DBusProxy::new(&connection).await?;
let mut watcher_owner = None;
let mut timer = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
tokio::select! {
action = receiver.recv() => match action {
Some(Action::Show) => {
tokio::task::spawn_blocking(|| {
if let Err(error) = crate::session::show_client() { eprintln!("tray: {error}"); }
});
}
Some(Action::Stop) => {
tokio::task::spawn_blocking(crate::session::stop).await??;
break;
}
None => break,
},
_ = timer.tick() => {
if stopping.load(Ordering::Relaxed) { break; }
let owner = bus.get_name_owner("org.kde.StatusNotifierWatcher".try_into()?).await.ok();
if owner != watcher_owner {
if owner.is_some() {
let watcher = zbus::Proxy::new(&connection, "org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher", "org.kde.StatusNotifierWatcher").await?;
match watcher.call::<_, _, ()>("RegisterStatusNotifierItem", &("/StatusNotifierItem",)).await {
Ok(()) => {
println!("{}", t!("tray.registered"));
watcher_owner = owner;
}
Err(error) => eprintln!("tray registration: {error}"),
}
} else { watcher_owner = None; }
}
}
}
}
Ok(())
})
}
+489
View File
@@ -0,0 +1,489 @@
//! Explicit per-user removal. Distribution-owned files stay with the package
//! manager; a source installation is identified by its installer receipt.
use anyhow::{Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{IsTerminal, Write};
use std::os::unix::fs::MetadataExt;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
#[derive(Clone, Copy)]
enum Removal {
File,
Tree,
EmptyDirectory,
}
struct Plan {
home: PathBuf,
data: PathBuf,
config: PathBuf,
state: PathBuf,
runtime: PathBuf,
entries: BTreeMap<PathBuf, Removal>,
source_install: bool,
}
pub fn run(purge: bool, dry_run: bool, yes: bool) -> Result<()> {
if unsafe { libc::geteuid() } == 0 {
anyhow::bail!("{}", t!("uninstall.no_root"));
}
let mut plan = Plan::build(purge)?;
println!("{}", t!("uninstall.plan"));
for (path, removal) in &plan.entries {
if !matches!(removal, Removal::EmptyDirectory) {
println!(" {}", path.display());
}
}
if purge {
println!("{}", t!("uninstall.purge_warning"));
} else {
println!("{}", t!("uninstall.keep_data"));
}
println!("{}", t!("uninstall.package_hint"));
if dry_run {
println!("{}", t!("uninstall.dry_run"));
return Ok(());
}
if !yes {
if !std::io::stdin().is_terminal() {
anyhow::bail!("{}", t!("uninstall.confirm_required"));
}
print!("{} ", t!("uninstall.confirm"));
std::io::stdout().flush()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer)?;
if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
println!("{}", t!("uninstall.cancelled"));
return Ok(());
}
}
crate::session::stop()?;
// Keep setup/run excluded until the directory cleanup has finished.
let _session_lock = crate::session::acquire_session_lock()?;
stop_prefix(&plan.data.join("wine"))?;
// Revalidate the displayed targets after stopping the session. Do not add
// newly discovered files to a plan the user has already confirmed.
plan.validate()?;
// Remove integrations first, then the trees; the running ELF can be
// unlinked on Linux, so source installs need no second helper process.
let trees: Vec<_> = plan
.entries
.iter()
.filter_map(|(path, removal)| matches!(removal, Removal::Tree).then_some(path.clone()))
.collect();
plan.entries.retain(|path, removal| {
!matches!(removal, Removal::File)
|| !trees
.iter()
.any(|root| path != root && path.starts_with(root))
});
let mut removals: Vec<_> = plan
.entries
.iter()
.filter(|(_, removal)| !matches!(removal, Removal::EmptyDirectory))
.collect();
// Keep the receipt until all installed files are removed, so a failed
// cleanup can be retried from another copy of uur.
removals.sort_by_key(
|(path, _)| match path.file_name().and_then(|name| name.to_str()) {
Some("user-install") => 2,
Some("uur") if path.parent().and_then(Path::file_name) == Some("bin".as_ref()) => 1,
_ => 0,
},
);
for (path, removal) in removals {
remove(path, *removal)?;
}
for (path, removal) in plan.entries.iter().rev() {
if matches!(removal, Removal::EmptyDirectory) {
remove(path, *removal)?;
}
}
println!("{}", t!("uninstall.done"));
if !plan.source_install {
println!("{}", t!("uninstall.package_hint"));
}
Ok(())
}
impl Plan {
fn build(purge: bool) -> Result<Self> {
let home = absolute(PathBuf::from(
std::env::var_os("HOME").context("HOME is unset")?,
))?;
let data_home = xdg_home("XDG_DATA_HOME", &home.join(".local/share"))?;
let config_home = xdg_home("XDG_CONFIG_HOME", &home.join(".config"))?;
let state_home = xdg_home("XDG_STATE_HOME", &home.join(".local/state"))?;
let runtime_home = xdg_home(
"XDG_RUNTIME_DIR",
&PathBuf::from(format!("/tmp/uur-{}", unsafe { libc::geteuid() })),
)?;
let mut plan = Self {
home: home.clone(),
data: data_home.join("uur"),
config: config_home.join("uur"),
state: state_home.join("uur"),
runtime: runtime_home.join("uur"),
entries: BTreeMap::new(),
source_install: false,
};
plan.entries.insert(plan.runtime.clone(), Removal::Tree);
if purge {
for path in [&plan.data, &plan.config, &plan.state] {
plan.entries.insert(path.clone(), Removal::Tree);
}
}
let default_scope = data_home == home.join(".local/share");
let mut desktops = BTreeSet::new();
scan_files(&data_home.join("applications"), 8, &mut desktops)?;
// Old releases placed compatibility aliases in ~/.local/share even
// when XDG_DATA_HOME was set. Only entries tied to this prefix qualify.
scan_files(&home.join(".local/share/applications"), 8, &mut desktops)?;
scan_files(&desktop_dir(&home, &config_home), 1, &mut desktops)?;
let autostart = config_home.join("autostart/uur.desktop");
if autostart.exists() {
desktops.insert(autostart);
}
let mut removed_icons = BTreeSet::new();
let mut kept_icons = BTreeSet::new();
let mut remove_default_icons = default_scope;
for path in desktops {
if path
.extension()
.is_none_or(|extension| extension != "desktop")
{
continue;
}
let content = std::fs::read_to_string(&path)
.with_context(|| format!("reading {}", path.display()))?;
let icon = desktop_value(&content, "Icon").unwrap_or_default();
if plan.owns_desktop(&content, default_scope) {
remove_default_icons |= path.starts_with(home.join(".local/share/applications"))
|| path.starts_with(desktop_dir(&home, &config_home));
plan.entries.insert(path, Removal::File);
removed_icons.insert(icon.to_string());
} else {
kept_icons.insert(icon.to_string());
}
}
let mut icon_roots = BTreeSet::from([data_home.join("icons")]);
if remove_default_icons {
icon_roots.insert(home.join(".local/share/icons"));
}
for icons in icon_roots {
let mut files = BTreeSet::new();
scan_files(&icons, 6, &mut files)?;
for path in files {
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let alias = stem.strip_suffix(".0").unwrap_or(stem);
if (removed_icons.contains(stem) || removed_icons.contains(alias))
&& !kept_icons.contains(stem)
&& !kept_icons.contains(alias)
{
plan.entries.insert(path, Removal::File);
}
}
}
plan.source_files()?;
plan.validate()?;
Ok(plan)
}
fn owns_desktop(&self, content: &str, default_scope: bool) -> bool {
let prefix = self.data.join("wine");
if let Some(recorded) = desktop_value(content, "X-UUR-Prefix") {
return desktop_value(content, "X-UUR-Managed") == Some("true")
&& recorded == prefix.to_string_lossy();
}
let managed = desktop_value(content, "X-UUR-Managed") == Some("true")
|| desktop_value(content, "Comment") == Some("Start the managed UU Remote session")
|| desktop_value(content, "Comment") == Some("UU Remote for Linux (uur)");
if managed && default_scope {
return true;
}
// Wine writes an explicit WINEPREFIX assignment in its launchers.
// Match the entire quoted/unquoted value, not a filename substring.
let exec = desktop_value(content, "Exec").unwrap_or_default();
let prefix = prefix.to_string_lossy();
let references_prefix = [
format!("WINEPREFIX=\"{prefix}\" "),
format!("WINEPREFIX='{prefix}' "),
format!("WINEPREFIX={prefix} "),
]
.iter()
.any(|assignment| exec.contains(assignment));
references_prefix && exec.to_ascii_lowercase().contains("gameviewer")
}
fn source_files(&mut self) -> Result<()> {
let executable = std::env::current_exe()?;
let mut prefixes = BTreeSet::from([self.home.join(".local")]);
if let Some(prefix) = executable.parent().and_then(Path::parent) {
if executable.parent().and_then(Path::file_name) == Some("bin".as_ref()) {
prefixes.insert(prefix.to_path_buf());
}
}
if let Some(prefix) = std::env::var_os("UUR_INSTALL_PREFIX") {
prefixes.insert(absolute(PathBuf::from(prefix))?);
}
for prefix in prefixes {
let receipt = prefix.join("lib/uur/user-install");
let marked = std::fs::read_to_string(&receipt).is_ok_and(|content| {
content == format!("uur-user-install-v1\n{}\n", self.data.display())
});
// Support the previous source installer, but only while executing
// its ~/.local/bin/uur and with the matching generated menu entry.
let legacy = prefix == self.home.join(".local")
&& std::fs::canonicalize(prefix.join("bin/uur")).ok() == Some(executable.clone())
&& std::fs::read_to_string(prefix.join("share/applications/uur.desktop"))
.is_ok_and(|content| {
desktop_value(&content, "TryExec")
== Some(prefix.join("bin/uur").to_string_lossy().as_ref())
});
if !marked && !legacy {
continue;
}
self.source_install = true;
for relative in [
"bin/uur",
"lib/uur/user-install",
"lib/uur/uur-pw-capture",
"lib/uur/uur-wl-capture",
"lib/uur/hook/wevtapi.dll",
"lib/uur/hook/uur-hook.dll",
"lib/uur/hook/wtsapi32.dll",
"lib/uur/hook/winlogon.exe",
"lib/uur/hook/uur-terminal-proxy.exe",
"lib/uur/hook/uur-mux-proxy.exe",
"lib/uur/hook/uur-launch-proxy.exe",
"share/applications/uur.desktop",
"share/icons/hicolor/256x256/apps/uur.png",
] {
let path = prefix.join(relative);
if std::fs::symlink_metadata(&path).is_ok() {
self.entries.insert(path, Removal::File);
}
}
for relative in ["lib/uur/hook", "lib/uur"] {
self.entries
.insert(prefix.join(relative), Removal::EmptyDirectory);
}
}
Ok(())
}
fn validate(&self) -> Result<()> {
// Session shutdown/locking access these paths before tree removal.
// Reject redirected state rather than following a link while writing
// the lock or stopping an unrelated Wine prefix.
for path in [
&self.data,
&self.state,
&self.runtime,
&self.state.join("session.lock"),
&self.data.join("wine"),
] {
if path.is_symlink() {
anyhow::bail!("refusing redirected session state: {}", path.display());
}
if std::fs::metadata(path)
.is_ok_and(|metadata| metadata.uid() != unsafe { libc::geteuid() })
{
anyhow::bail!("session state belongs to another user: {}", path.display());
}
}
for (path, removal) in &self.entries {
let path = absolute(path.clone())?;
// Resolve ancestor links, but never resolve the final link: remove
// symlink entries themselves, not the objects they point at.
let resolved = path
.parent()
.and_then(|parent| std::fs::canonicalize(parent).ok())
.map(|parent| parent.join(path.file_name().unwrap_or_default()))
.unwrap_or_else(|| path.clone());
if path == self.home || resolved == self.home || path.parent().is_none() {
anyhow::bail!("refusing to remove {}", path.display());
}
// Never allow a receipt or an XDG override to select system trees.
for system in [
"/usr", "/etc", "/opt", "/var", "/nix", "/bin", "/lib", "/sbin", "/boot", "/dev",
"/proc", "/sys",
] {
if path.starts_with(system) || resolved.starts_with(system) {
anyhow::bail!("refusing to remove system path {}", path.display());
}
}
match std::fs::symlink_metadata(&path) {
Ok(metadata) => {
if metadata.uid() != unsafe { libc::geteuid() } {
anyhow::bail!(
"refusing to remove a path owned by another user: {}",
path.display()
);
}
if matches!(removal, Removal::Tree)
&& !metadata.file_type().is_symlink()
&& (path.join(".git").exists() || path.join("Cargo.toml").exists())
{
anyhow::bail!("refusing to remove a source checkout: {}", path.display());
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(error).with_context(|| format!("checking {}", path.display()))
}
}
}
Ok(())
}
}
fn absolute(path: PathBuf) -> Result<PathBuf> {
if !path.is_absolute() {
anyhow::bail!(
"uninstall requires absolute XDG/install paths: {}",
path.display()
);
}
let mut normalized = PathBuf::from("/");
for component in path.components() {
match component {
Component::Normal(part) => normalized.push(part),
Component::ParentDir => {
normalized.pop();
}
_ => {}
}
}
Ok(normalized)
}
fn xdg_home(variable: &str, fallback: &Path) -> Result<PathBuf> {
absolute(
std::env::var_os(variable)
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| fallback.to_path_buf()),
)
}
fn desktop_value<'a>(content: &'a str, key: &str) -> Option<&'a str> {
let mut main_section = false;
for line in content.lines() {
if line.starts_with('[') {
main_section = line == "[Desktop Entry]";
} else if main_section {
if let Some((name, value)) = line.split_once('=') {
if name == key {
return Some(value);
}
}
}
}
None
}
fn desktop_dir(home: &Path, config_home: &Path) -> PathBuf {
// user-dirs.dirs is data, not a shell script: never source it.
std::fs::read_to_string(config_home.join("user-dirs.dirs"))
.ok()
.and_then(|content| {
content.lines().find_map(|line| {
let value = line.strip_prefix("XDG_DESKTOP_DIR=\"")?.strip_suffix('"')?;
let path = value
.strip_prefix("$HOME/")
.map(|suffix| home.join(suffix))
.unwrap_or_else(|| PathBuf::from(value));
(path.is_absolute() && path != home).then_some(path)
})
})
.unwrap_or_else(|| home.join("Desktop"))
}
fn scan_files(dir: &Path, depth: u8, files: &mut BTreeSet<PathBuf>) -> Result<()> {
if depth == 0 {
return Ok(());
}
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("listing {}", dir.display())),
};
for entry in entries {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_dir() {
scan_files(&entry.path(), depth - 1, files)?;
} else if kind.is_file() {
files.insert(entry.path());
}
}
Ok(())
}
fn stop_prefix(prefix: &Path) -> Result<()> {
if !prefix.is_dir() || prefix.is_symlink() {
return Ok(());
}
match Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-k")
.stdin(Stdio::null())
.status()
{
// -k exits 1 when stop already shut down this prefix's server. The
// following -w, with a deadline, is the actual shutdown check.
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).context("stopping the managed wineserver"),
}
let mut wait = Command::new("wineserver")
.env("WINEPREFIX", prefix)
.arg("-w")
.stdin(Stdio::null())
.spawn()?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
if let Some(status) = wait.try_wait()? {
if !status.success() {
anyhow::bail!("wineserver shutdown failed");
}
return Ok(());
}
if std::time::Instant::now() >= deadline {
let _ = wait.kill();
let _ = wait.wait();
anyhow::bail!("managed wineserver is still running; no files were removed");
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
fn remove(path: &Path, removal: Removal) -> Result<()> {
let metadata = match std::fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("checking {}", path.display())),
};
let result = match removal {
Removal::Tree if metadata.is_dir() && !metadata.file_type().is_symlink() => {
std::fs::remove_dir_all(path)
}
Removal::EmptyDirectory if metadata.is_dir() => std::fs::remove_dir(path),
_ => std::fs::remove_file(path),
};
match result {
Err(error)
if matches!(removal, Removal::EmptyDirectory)
&& error.kind() == std::io::ErrorKind::DirectoryNotEmpty =>
{
Ok(())
}
other => other.with_context(|| format!("removing {}", path.display())),
}
}
+134 -74
View File
@@ -6,11 +6,20 @@ use crate::config::Config;
const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd";
const EULA_URL: &str = "https://uuyc.163.com/contact/20240402/40294_1146065.html";
const SETUP_DLL_OVERRIDES: &str = "wevtapi=b,wtsapi32=b";
struct SetupPrefix(PathBuf);
impl Drop for SetupPrefix {
fn drop(&mut self) {
stop_wineserver(&self.0);
}
}
/// One-time provisioning. Deliberately quiet: progress on stdout, nothing
/// else. NetEase binaries are never redistributed — they are fetched from
/// the official feed into a per-user prefix.
pub fn setup(accept_eula: bool) -> Result<()> {
pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
let mut config = Config::load()?;
if !config.eula_accepted {
@@ -23,19 +32,40 @@ pub fn setup(accept_eula: bool) -> Result<()> {
println!("{}", t!("setup.eula_recorded"));
}
let _session_lock = crate::session::acquire_session_lock()?;
let data = crate::config::data_dir()?;
let prefix = data.join("wine");
std::fs::create_dir_all(&prefix).context("creating wine prefix directory")?;
let cache = data.join("cache");
std::fs::create_dir_all(&cache).context("creating cache directory")?;
let _prefix_cleanup = SetupPrefix(prefix.clone());
if find_client_dir(&prefix).is_some() {
apply_registry_compat(&prefix)?;
let uur_bin = std::env::current_exe().unwrap_or_default();
let _ = adopt_shortcut(&prefix, &uur_bin);
if !repair
&& prefix_initialized(&prefix)
&& find_client_dir(&prefix).is_some()
&& client_service_registered(&prefix)
{
finish_setup(&prefix)?;
println!("{}", t!("setup.already_provisioned"));
stop_wineserver(&prefix);
return Ok(());
}
println!("{}", t!("setup.initializing_prefix"));
let status = Command::new("wineboot")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
.arg(if repair { "--update" } else { "--init" })
.status()
.context("running wineboot")?;
if !status.success() || !prefix_initialized(&prefix) {
anyhow::bail!("{}", t!("setup.prefix_failed", status = status));
}
if find_client_dir(&prefix).is_some() && query_client_service(&prefix)? {
finish_setup(&prefix)?;
println!("{}", t!("setup.repaired", path = prefix.display()));
return Ok(());
}
@@ -57,82 +87,96 @@ pub fn setup(accept_eula: bool) -> Result<()> {
anyhow::bail!("{}", t!("setup.download_failed"));
}
println!("{}", t!("setup.initializing_prefix"));
let _ = Command::new("wineboot")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.arg("--init")
.status()
.context("running wineboot")?;
// The preload chain only works if Wine resolves wevtapi to the native
// shim in the application directory instead of its builtin.
let _ = Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.args([
"reg",
"add",
r"HKCU\Software\Wine\DllOverrides",
"/v",
"wevtapi",
"/t",
"REG_SZ",
"/d",
"native",
"/f",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("registering wevtapi dll override")?;
println!("{}", t!("setup.installing_client"));
let status = Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
.arg(installer.to_string_lossy().as_ref())
.arg("/S")
.status()
.context("launching installer")?;
if !status.success() {
println!("{}", t!("setup.silent_install_unavailable"));
anyhow::bail!("{}", t!("setup.install_failed", status = status));
}
find_client_dir(&prefix).context(t!("setup.client_incomplete").to_string())?;
if !query_client_service(&prefix)? {
anyhow::bail!("{}", t!("setup.service_incomplete"));
}
finish_setup(&prefix)?;
println!("{}", t!("setup.done", path = prefix.display().to_string()));
Ok(())
}
fn finish_setup(prefix: &Path) -> Result<()> {
// winemenubuilder generated its entries during the install: adopt the
// start-menu one for the full session, then stop it from producing raw
// shortcuts ever again, and sweep desktop copies.
let _ = Command::new("wine")
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.args([
"reg",
"add",
r"HKCU\Software\Wine\DllOverrides",
"/v",
"winemenubuilder",
"/t",
"REG_SZ",
"/d",
"",
"/f",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("disabling winemenubuilder")?;
apply_registry_compat(&prefix)?;
set_dll_override(prefix, "wevtapi", "native")?;
set_dll_override(prefix, "winemenubuilder", "")?;
apply_registry_compat(prefix)?;
let uur_bin = std::env::current_exe().unwrap_or_default();
let _ = adopt_shortcut(&prefix, &uur_bin);
let _ = adopt_shortcut(prefix, &uur_bin);
purge_wine_shortcuts();
println!("{}", t!("setup.done", path = prefix.display().to_string()));
stop_wineserver(&prefix);
Ok(())
}
pub fn prefix_initialized(prefix: &Path) -> bool {
["system.reg", "user.reg"]
.iter()
.all(|name| std::fs::metadata(prefix.join(name)).is_ok_and(|metadata| metadata.len() > 0))
}
pub fn webview2_installed(prefix: &Path) -> bool {
let application = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application");
find_dir_recursive(&application, "msedgewebview2.exe", 3)
.is_some_and(|path| std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0))
}
/// Read the persisted Wine service registration without starting Wine or
/// showing component installers from `uur doctor`.
pub fn client_service_registered(prefix: &Path) -> bool {
let Ok(registry) = std::fs::read_to_string(prefix.join("system.reg")) else {
return false;
};
let mut service_section = false;
for line in registry.lines() {
if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) {
service_section = section
.0
.to_ascii_lowercase()
.ends_with(r"\\services\\gameviewerservice");
} else if service_section && line.starts_with("\"ImagePath\"=") {
return line.to_ascii_lowercase().contains("gameviewerserver.exe");
}
}
false
}
fn query_client_service(prefix: &Path) -> Result<bool> {
let output = Command::new("wine")
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
.args([
"reg",
"query",
r"HKLM\System\CurrentControlSet\Services\GameViewerService",
"/v",
"ImagePath",
])
.stdin(Stdio::null())
.output()
.context("checking the UU Windows service registration")?;
Ok(output.status.success()
&& String::from_utf8_lossy(&output.stdout)
.to_ascii_lowercase()
.contains("gameviewerserver.exe"))
}
/// Registry compatibility profile, ported from the field-tested reference
/// implementation:
///
@@ -196,7 +240,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
format!("HKCU\\{key}")
};
for (value, reg_type, data) in &values {
let _ = Command::new("wine")
let status = Command::new("wine")
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
@@ -207,6 +251,9 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
.stderr(Stdio::null())
.status()
.with_context(|| format!("reg add {full} /v {value}"))?;
if !status.success() {
anyhow::bail!("Wine rejected registry compatibility setting {full} /v {value}");
}
}
}
Ok(())
@@ -294,15 +341,21 @@ pub fn find_client_dir(prefix: &Path) -> Option<PathBuf> {
let vendor = entry.path();
if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) {
let bin = found.parent()?;
if bin
let candidate = if bin
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("bin"))
{
return bin.parent().map(Path::to_path_buf);
bin.parent()?.to_path_buf()
} else {
bin.to_path_buf()
};
if std::fs::metadata(candidate.join("GameViewer.exe"))
.is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
&& std::fs::metadata(&found).is_ok_and(|metadata| metadata.len() > 0)
{
return Some(candidate);
}
return Some(bin.to_path_buf());
}
return Some(vendor);
}
}
None
@@ -315,7 +368,11 @@ fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf>
let entries = std::fs::read_dir(start).ok()?;
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && path.file_name().map(|n| n == needle).unwrap_or(false) {
if path.is_file()
&& path
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case(needle))
{
return Some(path);
}
if path.is_dir() {
@@ -357,8 +414,11 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
};
let mut icon_name = String::new();
let home = std::env::var("HOME").unwrap_or_default();
let icons = PathBuf::from(home).join(".local/share/icons");
let data_home = crate::config::data_dir()?
.parent()
.context("no data home")?
.to_path_buf();
let icons = data_home.join("icons");
let mut best = 0u32;
if let Ok(sizes) = fs::read_dir(icons.join("hicolor")) {
for size in sizes.flatten() {
@@ -382,9 +442,7 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
}
}
let applications = std::env::var("HOME")
.map(|h| PathBuf::from(h).join(".local/share/applications"))
.context("no home")?;
let applications = data_home.join("applications");
std::fs::create_dir_all(&applications)?;
let entry = applications.join(format!("{name}.desktop"));
let exec = uur_bin.display();
@@ -405,7 +463,9 @@ pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
{icon_line}Terminal=false\n\
NoDisplay=true\n\
X-UUR-Managed=true\n\
Categories=Network;RemoteAccess;\n"
X-UUR-Prefix={}\n\
Categories=Network;RemoteAccess;\n",
prefix.display()
),
)
.with_context(|| format!("writing {}", entry.display()))?;