Initial commit
This commit is contained in:
commit
611383544b
91 files changed
+12958
No files matched your search
+120
@@ -0,0 +1,120 @@
|
||||
//! Capability-selected Wine audio backend.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Backend {
|
||||
PipeWirePulse,
|
||||
PulseAudio,
|
||||
PipeWireNative,
|
||||
Alsa,
|
||||
None,
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::PipeWirePulse => "PulseAudio protocol on PipeWire",
|
||||
Self::PulseAudio => "PulseAudio",
|
||||
Self::PipeWireNative => "PipeWire (no PulseAudio compatibility detected)",
|
||||
Self::Alsa => "ALSA",
|
||||
Self::None => "no audio server detected",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detect() -> Backend {
|
||||
if let Some(server) = pactl_server() {
|
||||
return if server.to_ascii_lowercase().contains("pipewire") {
|
||||
Backend::PipeWirePulse
|
||||
} else {
|
||||
Backend::PulseAudio
|
||||
};
|
||||
}
|
||||
if command_succeeds("wpctl", &["status"]) {
|
||||
return Backend::PipeWireNative;
|
||||
}
|
||||
if Path::new("/proc/asound/cards").is_file() {
|
||||
return Backend::Alsa;
|
||||
}
|
||||
Backend::None
|
||||
}
|
||||
|
||||
/// Select a Wine driver only when a usable host backend is observable. Wine's
|
||||
/// pulse driver works with both a real PulseAudio daemon and pipewire-pulse.
|
||||
pub fn sync_wine(prefix: &Path) -> Result<Backend> {
|
||||
let backend = detect();
|
||||
let driver = match backend {
|
||||
Backend::PipeWirePulse | Backend::PulseAudio => Some("pulse"),
|
||||
Backend::PipeWireNative | Backend::Alsa => Some("alsa"),
|
||||
Backend::None => None,
|
||||
};
|
||||
if let Some(driver) = driver {
|
||||
let status = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.args([
|
||||
"reg",
|
||||
"add",
|
||||
r"HKCU\Software\Wine\Drivers",
|
||||
"/v",
|
||||
"Audio",
|
||||
"/t",
|
||||
"REG_SZ",
|
||||
"/d",
|
||||
driver,
|
||||
"/f",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.context("selecting the Wine audio driver")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("Wine rejected the {driver} audio driver setting");
|
||||
}
|
||||
}
|
||||
Ok(backend)
|
||||
}
|
||||
|
||||
fn pactl_server() -> Option<String> {
|
||||
let output = Command::new("pactl")
|
||||
.arg("info")
|
||||
.env("LC_ALL", "C")
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
text.lines()
|
||||
.find_map(|line| {
|
||||
line.split_once(':')
|
||||
.filter(|(key, _)| key.trim() == "Server Name")
|
||||
})
|
||||
.map(|(_, value)| value.trim().to_string())
|
||||
}
|
||||
|
||||
fn command_succeeds(program: &str, arguments: &[&str]) -> bool {
|
||||
Command::new(program)
|
||||
.args(arguments)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|status| status.success())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Backend;
|
||||
|
||||
#[test]
|
||||
fn backend_labels_are_user_facing() {
|
||||
assert_eq!(Backend::PulseAudio.label(), "PulseAudio");
|
||||
assert!(Backend::PipeWirePulse.label().contains("PipeWire"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Optional XDG login autostart, independent of desktop environment.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn enable() -> Result<()> {
|
||||
let path = desktop_path()?;
|
||||
let parent = path.parent().context("autostart path has no parent")?;
|
||||
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());
|
||||
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"
|
||||
),
|
||||
)?;
|
||||
println!(
|
||||
"{}",
|
||||
t!("autostart.enabled", path = path.display().to_string())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn disable() -> Result<()> {
|
||||
let path = desktop_path()?;
|
||||
if path.exists() {
|
||||
std::fs::remove_file(&path)?;
|
||||
}
|
||||
println!("{}", t!("autostart.disabled"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn status() -> Result<()> {
|
||||
let path = desktop_path()?;
|
||||
println!(
|
||||
"{}",
|
||||
if path.is_file() {
|
||||
t!(
|
||||
"autostart.status_enabled",
|
||||
path = path.display().to_string()
|
||||
)
|
||||
} else {
|
||||
t!("autostart.status_disabled")
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn desktop_path() -> Result<PathBuf> {
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))
|
||||
.context("cannot determine XDG configuration directory")?;
|
||||
Ok(base.join("autostart/uur.desktop"))
|
||||
}
|
||||
|
||||
fn desktop_exec_argument(value: &str) -> String {
|
||||
if value.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'_' | b'-' | b'.' | b':')
|
||||
}) {
|
||||
return value.to_string();
|
||||
}
|
||||
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::desktop_exec_argument;
|
||||
|
||||
#[test]
|
||||
fn desktop_exec_paths_are_quoted_only_when_needed() {
|
||||
assert_eq!(desktop_exec_argument("/usr/bin/uur"), "/usr/bin/uur");
|
||||
assert_eq!(
|
||||
desktop_exec_argument("/opt/UU Remote/uur"),
|
||||
"\"/opt/UU Remote/uur\""
|
||||
);
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::io::Read;
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::thread;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::input;
|
||||
use crate::protocol::{self, RECORD_BYTES, RECORD_HELLO};
|
||||
|
||||
/// Print the X11 pointer position — the before/after observable for hook
|
||||
/// verification.
|
||||
pub fn print_pointer() -> Result<()> {
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::ConnectionExt;
|
||||
let (conn, screen) = x11rb::connect(None).context("connecting to X display")?;
|
||||
let root = conn.setup().roots[screen].root;
|
||||
let reply = conn.query_pointer(root)?.reply()?;
|
||||
println!("{} {}", reply.root_x, reply.root_y);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serve the in-client hook: one authenticated loopback connection at a
|
||||
/// time, records dispatched to the selected input backend.
|
||||
pub fn serve() -> Result<()> {
|
||||
let config = Config::load()?;
|
||||
let preferred =
|
||||
std::env::var("UUR_INPUT_BACKEND").unwrap_or_else(|_| config.input_backend.clone());
|
||||
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")?;
|
||||
}
|
||||
let backend = std::sync::Arc::new(std::sync::Mutex::new(selected));
|
||||
let backend_handle = backend.clone();
|
||||
let addr = format!("127.0.0.1:{}", config.bridge_port);
|
||||
let listener = TcpListener::bind(&addr).with_context(|| format!("binding {addr}"))?;
|
||||
println!("{}", t!("bridge.listening", port = config.bridge_port));
|
||||
|
||||
// The service process hooks itself too, so multiple authenticated
|
||||
// connections coexist; each gets its own thread. Injection is
|
||||
// serialized through the single backend.
|
||||
for stream in listener.incoming() {
|
||||
let stream = match stream {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let config = config.clone();
|
||||
let backend_handle = backend_handle.clone();
|
||||
thread::spawn(move || {
|
||||
let mut stream = stream;
|
||||
match authenticate(&mut stream, &config) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return,
|
||||
Err(_) => return,
|
||||
}
|
||||
let mut guard = backend_handle.lock().unwrap();
|
||||
println!("{}", t!("bridge.connected", backend = guard.name()));
|
||||
match pump(&mut stream, guard.as_mut()) {
|
||||
Ok(count) => {
|
||||
println!("{}", t!("bridge.session_summary", count = count));
|
||||
println!("{}", t!("bridge.disconnected_clean"));
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
t!("bridge.disconnected_error", error = error.to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = guard.release_all();
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn authenticate(stream: &mut TcpStream, config: &Config) -> Result<bool> {
|
||||
let mut header = [0u8; protocol::HEADER_BYTES];
|
||||
stream.read_exact(&mut header).context("reading header")?;
|
||||
let header = protocol::read_header(&header);
|
||||
if header.magic != protocol::MAGIC
|
||||
|| header.version != protocol::VERSION
|
||||
|| header.kind != RECORD_HELLO
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let expected: [u8; 32] = decode_token(&config.bridge_token);
|
||||
let mut token = [0u8; 32];
|
||||
stream.read_exact(&mut token)?;
|
||||
if tokens_differ(&token, &expected) {
|
||||
let shown: String = token[..4].iter().map(|b| format!("{b:02x}")).collect();
|
||||
eprintln!("{}", t!("bridge.bad_token_fingerprint", prefix = shown));
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn pump(stream: &mut TcpStream, backend: &mut dyn input::InputBackend) -> Result<u64> {
|
||||
let mut header = [0u8; protocol::HEADER_BYTES];
|
||||
let mut record = [0u8; RECORD_BYTES];
|
||||
let mut injected: u64 = 0;
|
||||
loop {
|
||||
// EOF is the hook exiting: a clean disconnect, not an error.
|
||||
match stream.read_exact(&mut header) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => {
|
||||
return Ok(injected);
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
let header = protocol::read_header(&header);
|
||||
if header.magic != protocol::MAGIC {
|
||||
anyhow::bail!("bad magic");
|
||||
}
|
||||
match header.kind {
|
||||
protocol::RECORD_MOUSE | protocol::RECORD_KEYBOARD => {
|
||||
stream.read_exact(&mut record)?;
|
||||
let record = protocol::read_record(&record);
|
||||
dispatch(backend, &record)?;
|
||||
injected += 1;
|
||||
}
|
||||
_ => {
|
||||
// Unknown record: skip its payload if any, stay in sync.
|
||||
for _ in 0..(header.length / RECORD_BYTES as u32) {
|
||||
stream.read_exact(&mut record)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch(backend: &mut dyn input::InputBackend, record: &protocol::Record) -> Result<()> {
|
||||
match record.kind {
|
||||
protocol::RECORD_KEYBOARD => backend.key(record.code, record.state == 1)?,
|
||||
protocol::RECORD_MOUSE => {
|
||||
// a/b carry motion deltas or absolute coordinates; the wheel
|
||||
// selector reuses `code`.
|
||||
const MOTION: u16 = 0xffff;
|
||||
const WHEEL: u16 = 0xfffe;
|
||||
match record.code {
|
||||
MOTION => backend.motion(record.state == 1, record.a, record.b)?,
|
||||
WHEEL => backend.wheel(record.a != 0, record.b)?,
|
||||
_ => backend.button(record.code, record.state == 1)?,
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_token(token: &str) -> [u8; 32] {
|
||||
let mut out = [0u8; 32];
|
||||
for (index, chunk) in token.as_bytes().chunks(2).take(32).enumerate() {
|
||||
if let Ok(value) = u8::from_str_radix(std::str::from_utf8(chunk).unwrap_or("0"), 16) {
|
||||
out[index] = value;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Branch-free comparison; the token never leaves loopback but avoid
|
||||
/// handing timing data to same-user processes anyway.
|
||||
fn tokens_differ(a: &[u8; 32], b: &[u8; 32]) -> bool {
|
||||
let mut diff = 0u8;
|
||||
for (x, y) in a.iter().zip(b.iter()) {
|
||||
diff |= x ^ y;
|
||||
}
|
||||
diff != 0
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
//! Portal side of the capture path.
|
||||
//!
|
||||
//! Negotiates an xdg-desktop-portal ScreenCast session, obtains a private
|
||||
//! PipeWire file descriptor and the video node id, then hands both to the
|
||||
//! C capture helper (`uur-pw-capture`) which runs the PipeWire stream and
|
||||
//! publishes frames into a private XDG runtime file (see
|
||||
//! docs/capture-protocol.md).
|
||||
//!
|
||||
//! Consent: the first run shows the compositor's share dialog once. The
|
||||
//! returned restore token is stored in uur's config; every later run hands
|
||||
//! it back with PersistMode::Persistent and the portal restores the choice
|
||||
//! silently — no dialog, no local interaction, which is the whole point on
|
||||
//! a headless remote host.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command};
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// Run the capture path until interrupted.
|
||||
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"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the native PipeWire consumer with a portal-owned descriptor. The
|
||||
/// descriptor remains private to the child and is never reopened by path.
|
||||
pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
|
||||
// The helper inherits this descriptor: strip close-on-exec and keep the
|
||||
// OwnedFd alive across the spawn (closing it would invalidate the number
|
||||
// the child receives).
|
||||
let raw = pw_fd.as_raw_fd();
|
||||
unsafe {
|
||||
let flags = libc::fcntl(raw, libc::F_GETFD);
|
||||
if flags < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("fcntl F_GETFD");
|
||||
}
|
||||
if libc::fcntl(raw, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("fcntl F_SETFD");
|
||||
}
|
||||
}
|
||||
|
||||
let helper = find_helper()?;
|
||||
let mut command = Command::new(&helper);
|
||||
command
|
||||
.env("UUR_PW_FD", raw.to_string())
|
||||
.env("UUR_PW_NODE", node.to_string())
|
||||
.env("UUR_FRAME_PATH", frame_path()?);
|
||||
if let Ok(debug) = std::env::var("UUR_PW_DEBUG") {
|
||||
command.env("PIPEWIRE_DEBUG", debug);
|
||||
}
|
||||
let child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("running {}", helper.display()))?;
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn frame_path() -> Result<PathBuf> {
|
||||
if let Some(path) = std::env::var_os("UUR_FRAME_PATH") {
|
||||
return Ok(PathBuf::from(path));
|
||||
}
|
||||
Ok(crate::config::runtime_dir()?.join("frames.v1"))
|
||||
}
|
||||
|
||||
/// Open the portal session and return (inherited fd number, node id).
|
||||
/// First attempt reuses the stored restore token; if that fails (stale
|
||||
/// 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)> {
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| anyhow!("portal session failed")))
|
||||
})
|
||||
}
|
||||
|
||||
/// One full portal handshake. Returns the PipeWire fd, the video node id
|
||||
/// and the restore token the portal issued for this selection.
|
||||
async fn negotiate(
|
||||
screencast: &ashpd::desktop::screencast::Screencast<'_>,
|
||||
source: ashpd::desktop::screencast::SourceType,
|
||||
restore_token: Option<&str>,
|
||||
) -> Result<(OwnedFd, u32, Option<String>)> {
|
||||
use ashpd::desktop::screencast::CursorMode;
|
||||
use ashpd::desktop::PersistMode;
|
||||
|
||||
let session = screencast.create_session().await?;
|
||||
|
||||
screencast
|
||||
.select_sources(
|
||||
&session,
|
||||
CursorMode::Embedded,
|
||||
source.into(),
|
||||
false,
|
||||
restore_token,
|
||||
PersistMode::ExplicitlyRevoked,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let response = screencast.start(&session, None).await?;
|
||||
let streams_response = response.response()?;
|
||||
let streams = streams_response.streams();
|
||||
let stream = streams.first().context("no monitor selected")?;
|
||||
let node = stream.pipe_wire_node_id();
|
||||
let fresh_token = streams_response.restore_token().map(String::from);
|
||||
|
||||
let fd = screencast
|
||||
.open_pipe_wire_remote(&session)
|
||||
.await
|
||||
.context("opening the PipeWire remote")?;
|
||||
Ok((fd, node, fresh_token))
|
||||
}
|
||||
|
||||
pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType {
|
||||
use ashpd::desktop::screencast::SourceType;
|
||||
match value {
|
||||
"window" => SourceType::Window,
|
||||
"virtual" => SourceType::Virtual,
|
||||
_ => SourceType::Monitor,
|
||||
}
|
||||
}
|
||||
|
||||
fn find_helper() -> Result<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
PathBuf::from("/usr/lib/uur/uur-pw-capture"),
|
||||
PathBuf::from("/usr/local/lib/uur/uur-pw-capture"),
|
||||
];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/uur-pw-capture"));
|
||||
}
|
||||
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"));
|
||||
}
|
||||
}
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
candidates.push(cwd.join("capture/uur-pw-capture"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| {
|
||||
anyhow!("capture helper uur-pw-capture not found (build with capture/build.sh)")
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::source_type;
|
||||
use ashpd::desktop::screencast::SourceType;
|
||||
|
||||
#[test]
|
||||
fn configured_portal_source_is_mapped() {
|
||||
assert_eq!(source_type("monitor"), SourceType::Monitor);
|
||||
assert_eq!(source_type("window"), SourceType::Window);
|
||||
assert_eq!(source_type("virtual"), SourceType::Virtual);
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Persistent user configuration. Everything lives under the XDG state and
|
||||
/// config directories; the managed Wine prefix lives under data.
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
#[serde(default)]
|
||||
pub struct Config {
|
||||
/// EULA acceptance recorded during `uur setup`.
|
||||
pub eula_accepted: bool,
|
||||
/// Loopback port the in-client hook connects to.
|
||||
pub bridge_port: u16,
|
||||
/// Random per-install token the hook must present on HELLO.
|
||||
pub bridge_token: String,
|
||||
/// Preferred input backend: "auto" | "xtest" | "portal".
|
||||
pub input_backend: String,
|
||||
/// Release channel pinned for provisioning.
|
||||
pub pinned_version: Option<String>,
|
||||
/// ScreenCast portal restore token: after the first consent the portal
|
||||
/// restores the monitor selection silently.
|
||||
pub capture_restore_token: Option<String>,
|
||||
/// Persistent permission for the standard RemoteDesktop input portal.
|
||||
pub remote_desktop_restore_token: Option<String>,
|
||||
/// Portal source type: monitor, window, or virtual.
|
||||
pub capture_source: String,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
eula_accepted: false,
|
||||
bridge_port: 47010,
|
||||
bridge_token: generate_token(),
|
||||
input_backend: "auto".into(),
|
||||
pinned_version: None,
|
||||
capture_restore_token: None,
|
||||
remote_desktop_restore_token: None,
|
||||
capture_source: "monitor".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_token() -> String {
|
||||
let mut bytes = [0u8; 32];
|
||||
// Read EXACTLY 32 bytes. Never `fs::read` a character device like
|
||||
// /dev/urandom: it has no EOF, so fs::read would loop forever and
|
||||
// consume all memory (this actually caused an OOM once).
|
||||
let filled = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.open("/dev/urandom")
|
||||
.and_then(|mut f| {
|
||||
use std::io::Read;
|
||||
f.read_exact(&mut bytes)
|
||||
})
|
||||
.is_ok();
|
||||
if !filled {
|
||||
// No OS entropy available: derive a weak token from the clock so
|
||||
// the tool still functions on loopback. Logged as a condition,
|
||||
// not a crash.
|
||||
let t = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let mut state = t as u64 | 1;
|
||||
for byte in bytes.iter_mut() {
|
||||
// xorshift64 — not cryptographic, only a stopgap.
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
*byte = state as u8;
|
||||
}
|
||||
}
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn config_path() -> Result<PathBuf> {
|
||||
let base = std::env::var("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.context("cannot determine config directory")?;
|
||||
Ok(base.join("uur").join("config.toml"))
|
||||
}
|
||||
|
||||
pub fn data_dir() -> Result<PathBuf> {
|
||||
let base = std::env::var("XDG_DATA_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".local/share")))
|
||||
.context("cannot determine data directory")?;
|
||||
Ok(base.join("uur"))
|
||||
}
|
||||
|
||||
/// Private per-login runtime state. Capture frames are sensitive and must not
|
||||
/// live in a world-readable global /dev/shm name shared by every user.
|
||||
pub fn runtime_dir() -> Result<PathBuf> {
|
||||
let base = std::env::var("XDG_RUNTIME_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| PathBuf::from(format!("/tmp/uur-{}", unsafe { libc::geteuid() })));
|
||||
let dir = base.join("uur");
|
||||
std::fs::create_dir_all(&dir)
|
||||
.with_context(|| format!("creating runtime directory {}", dir.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> Result<Self> {
|
||||
let path = config_path()?;
|
||||
if !path.exists() {
|
||||
let config = Self::default();
|
||||
config.store()?;
|
||||
return Ok(config);
|
||||
}
|
||||
let raw = std::fs::read_to_string(&path)
|
||||
.with_context(|| format!("reading {}", path.display()))?;
|
||||
toml::from_str(&raw).context("parsing config.toml")
|
||||
}
|
||||
|
||||
pub fn store(&self) -> Result<()> {
|
||||
let path = config_path()?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("creating {}", parent.display()))?;
|
||||
}
|
||||
std::fs::write(&path, toml::to_string_pretty(self)?)
|
||||
.with_context(|| format!("writing {}", path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn token_generation_terminates_and_is_wellformed() {
|
||||
// Regression: generate_token once used fs::read on /dev/urandom,
|
||||
// which never returns EOF and consumed all memory.
|
||||
let token = generate_token();
|
||||
assert_eq!(token.len(), 64);
|
||||
assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_configuration_gets_new_defaults() {
|
||||
let config: Config = toml::from_str(
|
||||
r#"
|
||||
eula_accepted = true
|
||||
bridge_port = 47010
|
||||
bridge_token = "00"
|
||||
input_backend = "auto"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(config.remote_desktop_restore_token.is_none());
|
||||
assert!(config.capture_restore_token.is_none());
|
||||
assert_eq!(config.capture_source, "monitor");
|
||||
}
|
||||
}
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
use anyhow::Result;
|
||||
|
||||
fn line(status: &str, label: &str, detail: &str) {
|
||||
println!("{status:<8} {label:<28} {detail}");
|
||||
}
|
||||
|
||||
fn ok(missing: bool) -> &'static str {
|
||||
if missing {
|
||||
"MISS"
|
||||
} else {
|
||||
"ok"
|
||||
}
|
||||
}
|
||||
|
||||
fn command_present(name: &str) -> bool {
|
||||
std::env::var("PATH")
|
||||
.map(|path| {
|
||||
path.split(':')
|
||||
.any(|dir| std::path::Path::new(dir).join(name).exists())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn wine_version() -> Option<String> {
|
||||
let output = std::process::Command::new("wine")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()?;
|
||||
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
Some(text)
|
||||
}
|
||||
|
||||
fn distro() -> String {
|
||||
let raw = std::fs::read_to_string("/etc/os-release").unwrap_or_default();
|
||||
let field = |key: &str| {
|
||||
raw.lines().find(|l| l.starts_with(key)).map(|l| {
|
||||
l.split('=')
|
||||
.nth(1)
|
||||
.unwrap_or("")
|
||||
.trim_matches('"')
|
||||
.to_string()
|
||||
})
|
||||
};
|
||||
match (field("PRETTY_NAME"), field("ID")) {
|
||||
(Some(pretty), _) => pretty,
|
||||
(None, Some(id)) => id,
|
||||
_ => "unknown".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn portal_backends() -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let mut directories = vec![
|
||||
std::path::PathBuf::from("/usr/lib/xdg-desktop-portal/portals"),
|
||||
std::path::PathBuf::from("/usr/share/xdg-desktop-portal/portals"),
|
||||
];
|
||||
directories.extend(
|
||||
std::env::var("XDG_DATA_DIRS")
|
||||
.unwrap_or_else(|_| "/usr/local/share:/usr/share".into())
|
||||
.split(':')
|
||||
.filter(|entry| !entry.is_empty())
|
||||
.map(|entry| std::path::Path::new(entry).join("xdg-desktop-portal/portals")),
|
||||
);
|
||||
for dir in directories {
|
||||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let short = name
|
||||
.trim_end_matches(".portal")
|
||||
.trim_start_matches("portal-")
|
||||
.to_string();
|
||||
if !found.contains(&short) {
|
||||
found.push(short);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
fn library_present(soname: &str) -> bool {
|
||||
// `ldconfig -p` output is small; capture fully to avoid SIGPIPE races.
|
||||
let cache = std::process::Command::new("ldconfig")
|
||||
.arg("-p")
|
||||
.output()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
|
||||
.unwrap_or_default();
|
||||
cache.contains(soname)
|
||||
|| ["/lib", "/usr/lib", "/usr/local/lib"]
|
||||
.iter()
|
||||
.any(|directory| {
|
||||
std::fs::read_dir(directory)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.any(|entry| entry.file_name().to_string_lossy().contains(soname))
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_component_present(name: &str) -> bool {
|
||||
let mut candidates = vec![
|
||||
std::path::PathBuf::from("/usr/lib/uur/hook").join(name),
|
||||
std::path::PathBuf::from("/usr/local/lib/uur/hook").join(name),
|
||||
];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(
|
||||
std::path::PathBuf::from(home)
|
||||
.join(".local/lib/uur/hook")
|
||||
.join(name),
|
||||
);
|
||||
}
|
||||
if let Ok(executable) = std::env::current_exe() {
|
||||
if let Some(directory) = executable.parent() {
|
||||
candidates.push(directory.join("../lib/uur/hook").join(name));
|
||||
candidates.push(directory.join("../../build/hook").join(name));
|
||||
}
|
||||
}
|
||||
if let Ok(directory) = std::env::current_dir() {
|
||||
candidates.push(directory.join("build/hook").join(name));
|
||||
}
|
||||
candidates.into_iter().any(|path| path.is_file())
|
||||
}
|
||||
|
||||
fn portal_capabilities() -> (bool, bool, String) {
|
||||
let Ok(runtime) = tokio::runtime::Runtime::new() else {
|
||||
return (false, false, "unavailable".into());
|
||||
};
|
||||
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:?}")),
|
||||
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(),
|
||||
Err(_) => false,
|
||||
};
|
||||
(capture, input, sources)
|
||||
})
|
||||
}
|
||||
|
||||
/// Environment report. Everything is advisory: doctor never gates.
|
||||
pub fn report() -> Result<()> {
|
||||
println!("{}", t!("doctor.header"));
|
||||
println!();
|
||||
|
||||
line("info", "distro", &distro());
|
||||
line(
|
||||
"info",
|
||||
"session",
|
||||
&format!(
|
||||
"type={} desktop={}",
|
||||
std::env::var("XDG_SESSION_TYPE").unwrap_or_else(|_| "unknown".into()),
|
||||
std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_else(|_| "unknown".into()),
|
||||
),
|
||||
);
|
||||
line(
|
||||
"info",
|
||||
"display",
|
||||
&format!(
|
||||
"DISPLAY={} WAYLAND_DISPLAY={}",
|
||||
std::env::var("DISPLAY").unwrap_or_else(|_| "-".into()),
|
||||
std::env::var("WAYLAND_DISPLAY").unwrap_or_else(|_| "-".into()),
|
||||
),
|
||||
);
|
||||
println!();
|
||||
|
||||
let missing_wine = !command_present("wine");
|
||||
let wine_detail: String = match (!missing_wine).then(wine_version).flatten() {
|
||||
Some(version) => version,
|
||||
None => t!("doctor.install_hint").to_string(),
|
||||
};
|
||||
line(ok(missing_wine), "wine", &wine_detail);
|
||||
|
||||
let backends = portal_backends();
|
||||
let has_portal_impl = !backends.is_empty();
|
||||
let portal_detail = if backends.is_empty() {
|
||||
t!("doctor.no_portal_backend").to_string()
|
||||
} else {
|
||||
backends.join(", ")
|
||||
};
|
||||
line(ok(!has_portal_impl), "xdg-desktop-portal", &portal_detail);
|
||||
|
||||
let (portal_capture, portal_input, portal_sources) = portal_capabilities();
|
||||
let portal_capture_detail = if portal_capture {
|
||||
t!("doctor.present").to_string()
|
||||
} else {
|
||||
t!("doctor.portal_capture_missing").to_string()
|
||||
};
|
||||
line(
|
||||
ok(!portal_capture),
|
||||
"portal ScreenCast",
|
||||
&portal_capture_detail,
|
||||
);
|
||||
line("info", "portal source types", &portal_sources);
|
||||
let portal_input_detail = if portal_input {
|
||||
t!("doctor.present").to_string()
|
||||
} else {
|
||||
t!("doctor.portal_input_missing").to_string()
|
||||
};
|
||||
line(
|
||||
ok(!portal_input),
|
||||
"portal RemoteDesktop",
|
||||
&portal_input_detail,
|
||||
);
|
||||
|
||||
let missing_pw = !library_present("libpipewire");
|
||||
let pw_detail = if missing_pw {
|
||||
t!("doctor.install_hint").to_string()
|
||||
} else {
|
||||
t!("doctor.present").to_string()
|
||||
};
|
||||
line(ok(missing_pw), "PipeWire", &pw_detail);
|
||||
|
||||
let audio = crate::audio::detect();
|
||||
line("info", "audio backend", audio.label());
|
||||
|
||||
let video = crate::video::detect();
|
||||
line(
|
||||
"info",
|
||||
"DRM render node",
|
||||
crate::video::describe(video.render_node, "present", "not detected"),
|
||||
);
|
||||
line(
|
||||
"info",
|
||||
"VA-API capability",
|
||||
crate::video::describe(video.va_api, "available", "not probed; install vainfo"),
|
||||
);
|
||||
line(
|
||||
"info",
|
||||
"Vulkan capability",
|
||||
crate::video::describe(video.vulkan, "available", "not probed; install vulkaninfo"),
|
||||
);
|
||||
line(
|
||||
"info",
|
||||
"Vulkan Video",
|
||||
crate::video::describe(video.vulkan_video, "video queue available", "not detected"),
|
||||
);
|
||||
line(
|
||||
"info",
|
||||
"NVENC / NVDEC",
|
||||
&format!(
|
||||
"encode={} decode={}",
|
||||
crate::video::describe(video.nvenc, "available", "missing"),
|
||||
crate::video::describe(video.nvdec, "available", "missing")
|
||||
),
|
||||
);
|
||||
|
||||
let terminal_proxy = runtime_component_present("uur-terminal-proxy.exe");
|
||||
let terminal_detail = if terminal_proxy {
|
||||
t!("doctor.present").to_string()
|
||||
} else {
|
||||
t!("doctor.terminal_missing").to_string()
|
||||
};
|
||||
line(
|
||||
ok(!terminal_proxy),
|
||||
"native terminal adapter",
|
||||
&terminal_detail,
|
||||
);
|
||||
|
||||
let mux_proxy = runtime_component_present("uur-mux-proxy.exe");
|
||||
let mux_detail = if mux_proxy {
|
||||
t!("doctor.present").to_string()
|
||||
} else {
|
||||
t!("doctor.terminal_missing").to_string()
|
||||
};
|
||||
line(ok(!mux_proxy), "terminal session adapter", &mux_detail);
|
||||
|
||||
let launch_proxy = runtime_component_present("uur-launch-proxy.exe");
|
||||
let launch_detail = if launch_proxy {
|
||||
t!("doctor.present").to_string()
|
||||
} else {
|
||||
t!("doctor.launcher_missing").to_string()
|
||||
};
|
||||
line(ok(!launch_proxy), "UU Quick Launch adapter", &launch_detail);
|
||||
let has_application_launcher = command_present("gio") || command_present("gtk-launch");
|
||||
let application_launcher_detail = if has_application_launcher {
|
||||
t!("doctor.present").to_string()
|
||||
} else {
|
||||
t!("doctor.xdg_launcher_missing").to_string()
|
||||
};
|
||||
line(
|
||||
ok(!has_application_launcher),
|
||||
"XDG application launcher",
|
||||
&application_launcher_detail,
|
||||
);
|
||||
|
||||
let wallpaper = crate::wallpaper::detect();
|
||||
let wallpaper_detail = wallpaper
|
||||
.as_ref()
|
||||
.map(|wallpaper| format!("{} ({})", wallpaper.path.display(), wallpaper.provider))
|
||||
.unwrap_or_else(|| t!("doctor.wallpaper_missing").to_string());
|
||||
line(
|
||||
ok(wallpaper.is_none()),
|
||||
"desktop wallpaper",
|
||||
&wallpaper_detail,
|
||||
);
|
||||
|
||||
// /dev/uinput: the Wayland injection path. Three states matter:
|
||||
// missing file, module not loaded (ENODEV), and permission (EACCES).
|
||||
let uinput_detail = match std::fs::OpenOptions::new().write(true).open("/dev/uinput") {
|
||||
Ok(_) => t!("doctor.present").to_string(),
|
||||
Err(error) => match error.raw_os_error() {
|
||||
Some(19) => t!("doctor.uinput_module").to_string(),
|
||||
Some(13) => t!("doctor.uinput_permission").to_string(),
|
||||
_ => t!("doctor.uinput_missing").to_string(),
|
||||
},
|
||||
};
|
||||
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.
|
||||
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())
|
||||
};
|
||||
line(
|
||||
"info",
|
||||
"input backend",
|
||||
&format!("{backend} ({backend_note})"),
|
||||
);
|
||||
|
||||
match crate::wol::inspect(None) {
|
||||
Ok(state) => line(
|
||||
"info",
|
||||
"Wake-on-LAN",
|
||||
&format!(
|
||||
"{} {} ({})",
|
||||
state.interface,
|
||||
state.mac,
|
||||
match state.enabled {
|
||||
Some(true) => "enabled",
|
||||
Some(false) => "disabled",
|
||||
None => "unknown; install ethtool",
|
||||
}
|
||||
),
|
||||
),
|
||||
Err(error) => line("info", "Wake-on-LAN", &error.to_string()),
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", t!("doctor.footer"));
|
||||
Ok(())
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/// Locale support. English is the source language; catalogs live in
|
||||
/// `locales/`. Set `LANG`/`LC_ALL` or `UUR_LANG` to switch. The
|
||||
/// `i18n!` macro itself lives at the crate root.
|
||||
pub fn init() {
|
||||
let requested = std::env::var("UUR_LANG")
|
||||
.or_else(|_| std::env::var("LC_ALL"))
|
||||
.or_else(|_| std::env::var("LANG"))
|
||||
.unwrap_or_else(|_| "en".into());
|
||||
let code = requested.split('.').next().unwrap_or("en").to_string();
|
||||
let best = available()
|
||||
.into_iter()
|
||||
.find(|available| code.starts_with(available.as_str()))
|
||||
.unwrap_or_else(|| "en".into());
|
||||
rust_i18n::set_locale(&best);
|
||||
}
|
||||
|
||||
fn available() -> Vec<String> {
|
||||
vec!["en".into(), "zh-CN".into()]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Keep the desktop session awake only while the managed UU session is alive.
|
||||
|
||||
use anyhow::Result;
|
||||
use ashpd::desktop::inhibit::{InhibitFlags, InhibitProxy};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
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())?;
|
||||
signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?;
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(async move {
|
||||
let proxy = InhibitProxy::new().await?;
|
||||
let request = proxy
|
||||
.inhibit(
|
||||
None,
|
||||
InhibitFlags::Suspend | InhibitFlags::Idle,
|
||||
"An active UU Remote session is running",
|
||||
)
|
||||
.await?;
|
||||
request.response()?;
|
||||
println!("desktop suspend and idle inhibition active");
|
||||
while !stopping.load(Ordering::Relaxed) {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
pub mod portal;
|
||||
pub mod uinput;
|
||||
pub mod xtest;
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
/// A desktop input sink. Records arrive already normalized by `protocol`.
|
||||
pub trait InputBackend: Send {
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
fn key(&mut self, vkey: u16, down: bool) -> Result<()>;
|
||||
fn button(&mut self, button: u16, down: bool) -> Result<()>;
|
||||
/// Absolute (normalized 0..65535) or relative pointer motion.
|
||||
fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()>;
|
||||
fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()>;
|
||||
|
||||
/// Release everything currently held (called when the hook disconnects).
|
||||
fn release_all(&mut self) -> Result<()>;
|
||||
}
|
||||
|
||||
/// Choose the backend for this session:
|
||||
///
|
||||
/// - Wayland sessions prefer the standard RemoteDesktop portal, then use the
|
||||
/// 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();
|
||||
|
||||
if preferred == "portal" || (preferred == "auto" && on_wayland) {
|
||||
match portal::PortalBackend::connect() {
|
||||
Ok(backend) => return Ok(Box::new(backend)),
|
||||
Err(error) if preferred == "portal" => return Err(error),
|
||||
Err(error) => eprintln!("{}: {error}", t!("input.portal_unavailable")),
|
||||
}
|
||||
}
|
||||
if preferred == "uinput" || (preferred == "auto" && on_wayland) {
|
||||
match uinput::UinputBackend::connect() {
|
||||
Ok(backend) => return Ok(Box::new(backend)),
|
||||
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 std::env::var("DISPLAY").is_ok() {
|
||||
return Ok(Box::new(xtest::XtestBackend::connect()?));
|
||||
}
|
||||
anyhow::bail!("{}", t!("input.no_display"));
|
||||
}
|
||||
|
||||
pub(crate) fn wheel_steps(delta: i32) -> i32 {
|
||||
if delta.abs() >= 120 {
|
||||
(delta / 120).clamp(-16, 16)
|
||||
} else {
|
||||
delta.signum()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::wheel_steps;
|
||||
|
||||
#[test]
|
||||
fn windows_wheel_units_are_normalized() {
|
||||
assert_eq!(wheel_steps(120), 1);
|
||||
assert_eq!(wheel_steps(-240), -2);
|
||||
assert_eq!(wheel_steps(1), 1);
|
||||
assert_eq!(wheel_steps(0), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use ashpd::desktop::remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop};
|
||||
use ashpd::desktop::screencast::{CursorMode, Screencast};
|
||||
use ashpd::desktop::PersistMode;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, SyncSender};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
||||
|
||||
use super::InputBackend;
|
||||
|
||||
type Reply = SyncSender<std::result::Result<(), String>>;
|
||||
|
||||
enum Event {
|
||||
Key(i32, bool, Reply),
|
||||
Button(i32, bool, Reply),
|
||||
FlushMotion,
|
||||
Wheel(Axis, i32, Reply),
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Motion {
|
||||
absolute: bool,
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
struct CaptureGuard(std::process::Child);
|
||||
|
||||
impl Drop for CaptureGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Wayland input through the freedesktop RemoteDesktop portal. The actual
|
||||
/// backend can be GNOME, KDE, COSMIC, or any future implementation; uur never
|
||||
/// branches on a desktop name.
|
||||
pub struct PortalBackend {
|
||||
sender: UnboundedSender<Event>,
|
||||
pending_motion: Arc<Mutex<Option<Motion>>>,
|
||||
motion_queued: Arc<AtomicBool>,
|
||||
held_keys: HashSet<i32>,
|
||||
held_buttons: HashSet<i32>,
|
||||
}
|
||||
|
||||
impl PortalBackend {
|
||||
pub fn connect() -> Result<Self> {
|
||||
let mut config = crate::config::Config::load()?;
|
||||
let restore_token = config.remote_desktop_restore_token.clone();
|
||||
let (sender, receiver) = unbounded_channel();
|
||||
let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
|
||||
let pending_motion = Arc::new(Mutex::new(None));
|
||||
let motion_queued = Arc::new(AtomicBool::new(false));
|
||||
let worker_motion = pending_motion.clone();
|
||||
let worker_queued = motion_queued.clone();
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("uur-portal-input".into())
|
||||
.spawn(move || {
|
||||
let result = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|runtime| {
|
||||
runtime.block_on(portal_worker(
|
||||
receiver,
|
||||
ready_sender.clone(),
|
||||
restore_token,
|
||||
worker_motion,
|
||||
worker_queued,
|
||||
))
|
||||
});
|
||||
if let Err(error) = result {
|
||||
let _ = ready_sender.send(Err(error.to_string()));
|
||||
}
|
||||
})
|
||||
.context("starting portal input worker")?;
|
||||
|
||||
let fresh_token = ready_receiver
|
||||
.recv()
|
||||
.context("portal input worker stopped during setup")?
|
||||
.map_err(|error| anyhow!(error))?;
|
||||
if fresh_token != config.remote_desktop_restore_token {
|
||||
config.remote_desktop_restore_token = fresh_token;
|
||||
config.store()?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
sender,
|
||||
pending_motion,
|
||||
motion_queued,
|
||||
held_keys: HashSet::new(),
|
||||
held_buttons: HashSet::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn submit(&self, event: impl FnOnce(Reply) -> Event) -> Result<()> {
|
||||
let (reply_sender, reply_receiver) = mpsc::sync_channel(1);
|
||||
self.sender
|
||||
.send(event(reply_sender))
|
||||
.map_err(|_| anyhow!("portal input session closed"))?;
|
||||
reply_receiver
|
||||
.recv_timeout(Duration::from_secs(3))
|
||||
.context("portal input request timed out")?
|
||||
.map_err(|error| anyhow!(error))
|
||||
}
|
||||
}
|
||||
|
||||
async fn portal_worker(
|
||||
mut receiver: UnboundedReceiver<Event>,
|
||||
ready: SyncSender<std::result::Result<Option<String>, String>>,
|
||||
restore_token: Option<String>,
|
||||
pending_motion: Arc<Mutex<Option<Motion>>>,
|
||||
motion_queued: Arc<AtomicBool>,
|
||||
) -> Result<()> {
|
||||
let portal = RemoteDesktop::new().await?;
|
||||
let screencast = Screencast::new().await?;
|
||||
let configured = crate::config::Config::load()?;
|
||||
let source = crate::capture::source_type(&configured.capture_source);
|
||||
let available = portal.available_device_types().await?;
|
||||
if !available.contains(DeviceType::Keyboard) || !available.contains(DeviceType::Pointer) {
|
||||
anyhow::bail!("RemoteDesktop portal does not provide keyboard and pointer devices");
|
||||
}
|
||||
|
||||
let session = portal.create_session().await?;
|
||||
portal
|
||||
.select_devices(
|
||||
&session,
|
||||
DeviceType::Keyboard | DeviceType::Pointer,
|
||||
restore_token.as_deref(),
|
||||
PersistMode::ExplicitlyRevoked,
|
||||
)
|
||||
.await?
|
||||
.response()?;
|
||||
screencast
|
||||
.select_sources(
|
||||
&session,
|
||||
CursorMode::Embedded,
|
||||
source.into(),
|
||||
false,
|
||||
None,
|
||||
PersistMode::DoNot,
|
||||
)
|
||||
.await?
|
||||
.response()?;
|
||||
let selection = portal.start(&session, None).await?.response()?;
|
||||
let stream = selection
|
||||
.streams()
|
||||
.and_then(|streams| streams.first())
|
||||
.context("RemoteDesktop portal returned no screen stream")?;
|
||||
let stream_id = stream.pipe_wire_node_id();
|
||||
let (logical_width, logical_height) = stream.size().unwrap_or((65535, 65535));
|
||||
let pipewire = screencast.open_pipe_wire_remote(&session).await?;
|
||||
let _capture = CaptureGuard(crate::capture::spawn_helper(pipewire, stream_id)?);
|
||||
let token = selection.restore_token().map(ToOwned::to_owned);
|
||||
ready
|
||||
.send(Ok(token))
|
||||
.map_err(|_| anyhow!("portal setup receiver closed"))?;
|
||||
|
||||
while let Some(event) = receiver.recv().await {
|
||||
match event {
|
||||
Event::Key(code, down, reply) => {
|
||||
let result = portal
|
||||
.notify_keyboard_keycode(
|
||||
&session,
|
||||
code,
|
||||
if down {
|
||||
KeyState::Pressed
|
||||
} else {
|
||||
KeyState::Released
|
||||
},
|
||||
)
|
||||
.await;
|
||||
answer(reply, result)?;
|
||||
}
|
||||
Event::Button(button, down, reply) => {
|
||||
let result = portal
|
||||
.notify_pointer_button(
|
||||
&session,
|
||||
button,
|
||||
if down {
|
||||
KeyState::Pressed
|
||||
} else {
|
||||
KeyState::Released
|
||||
},
|
||||
)
|
||||
.await;
|
||||
answer(reply, result)?;
|
||||
}
|
||||
Event::FlushMotion => loop {
|
||||
let motion = pending_motion.lock().unwrap().take();
|
||||
let Some(motion) = motion else {
|
||||
motion_queued.store(false, Ordering::Release);
|
||||
let has_new_motion = pending_motion.lock().unwrap().is_some();
|
||||
if has_new_motion
|
||||
&& motion_queued
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
};
|
||||
let result = if motion.absolute {
|
||||
let logical_x = motion.x.clamp(0.0, 65535.0) * logical_width as f64 / 65535.0;
|
||||
let logical_y = motion.y.clamp(0.0, 65535.0) * logical_height as f64 / 65535.0;
|
||||
portal
|
||||
.notify_pointer_motion_absolute(&session, stream_id, logical_x, logical_y)
|
||||
.await
|
||||
} else {
|
||||
portal
|
||||
.notify_pointer_motion(&session, motion.x, motion.y)
|
||||
.await
|
||||
};
|
||||
if let Err(error) = result {
|
||||
eprintln!("portal pointer motion failed: {error}");
|
||||
}
|
||||
},
|
||||
Event::Wheel(axis, steps, reply) => {
|
||||
answer(
|
||||
reply,
|
||||
portal
|
||||
.notify_pointer_axis_discrete(&session, axis, steps)
|
||||
.await,
|
||||
)?;
|
||||
}
|
||||
Event::Shutdown => break,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn answer<T>(reply: Reply, result: std::result::Result<T, ashpd::Error>) -> Result<()> {
|
||||
let failure = result.as_ref().err().map(ToString::to_string);
|
||||
let _ = reply.send(result.map(|_| ()).map_err(|error| error.to_string()));
|
||||
failure.map_or(Ok(()), |error| Err(anyhow!(error)))
|
||||
}
|
||||
|
||||
impl InputBackend for PortalBackend {
|
||||
fn name(&self) -> &'static str {
|
||||
"portal"
|
||||
}
|
||||
|
||||
fn key(&mut self, vkey: u16, down: bool) -> Result<()> {
|
||||
let code = super::uinput::vk_to_linux_key(vkey) as i32;
|
||||
if code == 0 {
|
||||
anyhow::bail!("Windows virtual key 0x{vkey:02x} has no evdev mapping");
|
||||
}
|
||||
self.submit(|reply| Event::Key(code, down, reply))?;
|
||||
if down {
|
||||
self.held_keys.insert(code);
|
||||
} else {
|
||||
self.held_keys.remove(&code);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn button(&mut self, button: u16, down: bool) -> Result<()> {
|
||||
let evdev = match button {
|
||||
1 => input_linux_sys::BTN_LEFT,
|
||||
2 => input_linux_sys::BTN_RIGHT,
|
||||
3 => input_linux_sys::BTN_MIDDLE,
|
||||
8 => input_linux_sys::BTN_SIDE,
|
||||
9 => input_linux_sys::BTN_EXTRA,
|
||||
_ => anyhow::bail!("unsupported pointer button {button}"),
|
||||
} as i32;
|
||||
self.submit(|reply| Event::Button(evdev, down, reply))?;
|
||||
if down {
|
||||
self.held_buttons.insert(evdev);
|
||||
} else {
|
||||
self.held_buttons.remove(&evdev);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> {
|
||||
let mut pending = self.pending_motion.lock().unwrap();
|
||||
merge_motion(
|
||||
&mut pending,
|
||||
Motion {
|
||||
absolute,
|
||||
x: x as f64,
|
||||
y: y as f64,
|
||||
},
|
||||
);
|
||||
drop(pending);
|
||||
if !self.motion_queued.swap(true, Ordering::AcqRel)
|
||||
&& self.sender.send(Event::FlushMotion).is_err()
|
||||
{
|
||||
self.motion_queued.store(false, Ordering::Release);
|
||||
anyhow::bail!("portal input session closed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> {
|
||||
let axis = if horizontal {
|
||||
Axis::Horizontal
|
||||
} else {
|
||||
Axis::Vertical
|
||||
};
|
||||
let steps = super::wheel_steps(delta);
|
||||
self.submit(|reply| Event::Wheel(axis, steps, reply))
|
||||
}
|
||||
|
||||
fn release_all(&mut self) -> Result<()> {
|
||||
self.pending_motion.lock().unwrap().take();
|
||||
for key in self.held_keys.clone() {
|
||||
let _ = self.submit(|reply| Event::Key(key, false, reply));
|
||||
}
|
||||
self.held_keys.clear();
|
||||
for button in self.held_buttons.clone() {
|
||||
let _ = self.submit(|reply| Event::Button(button, false, reply));
|
||||
}
|
||||
self.held_buttons.clear();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_motion(pending: &mut Option<Motion>, next: Motion) {
|
||||
if !next.absolute {
|
||||
if let Some(current) = pending.as_mut().filter(|motion| !motion.absolute) {
|
||||
current.x += next.x;
|
||||
current.y += next.y;
|
||||
return;
|
||||
}
|
||||
}
|
||||
*pending = Some(next);
|
||||
}
|
||||
|
||||
impl Drop for PortalBackend {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.release_all();
|
||||
let _ = self.sender.send(Event::Shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{merge_motion, Motion};
|
||||
|
||||
#[test]
|
||||
fn absolute_motion_keeps_only_the_latest_position() {
|
||||
let mut pending = Some(Motion {
|
||||
absolute: true,
|
||||
x: 10.0,
|
||||
y: 20.0,
|
||||
});
|
||||
let latest = Motion {
|
||||
absolute: true,
|
||||
x: 30.0,
|
||||
y: 40.0,
|
||||
};
|
||||
merge_motion(&mut pending, latest);
|
||||
assert_eq!(pending, Some(latest));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_motion_accumulates_without_building_a_queue() {
|
||||
let mut pending = Some(Motion {
|
||||
absolute: false,
|
||||
x: 3.0,
|
||||
y: -2.0,
|
||||
});
|
||||
merge_motion(
|
||||
&mut pending,
|
||||
Motion {
|
||||
absolute: false,
|
||||
x: 4.0,
|
||||
y: 5.0,
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
pending,
|
||||
Some(Motion {
|
||||
absolute: false,
|
||||
x: 7.0,
|
||||
y: 3.0,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
use anyhow::{Context, Result};
|
||||
use input_linux_sys as linux;
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::os::unix::io::AsRawFd;
|
||||
|
||||
use super::InputBackend;
|
||||
|
||||
// /dev/uinput interface constants (linux/uinput.h, linux/input-event-codes.h)
|
||||
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
|
||||
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;
|
||||
const UI_DEV_CREATE: libc::Ioctl = 0x5501_u64 as libc::Ioctl;
|
||||
const UI_DEV_DESTROY: libc::Ioctl = 0x5502_u64 as libc::Ioctl;
|
||||
|
||||
const EV_SYN: u16 = 0x00;
|
||||
const EV_KEY: u16 = 0x01;
|
||||
const EV_REL: u16 = 0x02;
|
||||
const EV_ABS: u16 = 0x03;
|
||||
|
||||
const SYN_REPORT: u16 = 0;
|
||||
|
||||
const REL_X: u16 = 0x00;
|
||||
const REL_Y: u16 = 0x01;
|
||||
const REL_WHEEL: u16 = 0x08;
|
||||
const REL_HWHEEL: u16 = 0x09;
|
||||
|
||||
const ABS_X: u16 = 0x00;
|
||||
const ABS_Y: u16 = 0x01;
|
||||
|
||||
const BTN_LEFT: u16 = 0x110;
|
||||
const BTN_RIGHT: u16 = 0x111;
|
||||
const BTN_MIDDLE: u16 = 0x112;
|
||||
const BTN_SIDE: u16 = 0x116;
|
||||
const BTN_EXTRA: u16 = 0x117;
|
||||
const BTN_TOOL_PEN: u16 = 0x140;
|
||||
|
||||
const BUS_VIRTUAL: u16 = 0x06;
|
||||
|
||||
/// struct input_event, 64-bit time_t layout.
|
||||
#[repr(C)]
|
||||
struct InputEvent {
|
||||
tv_sec: i64,
|
||||
tv_usec: i64,
|
||||
type_: u16,
|
||||
code: u16,
|
||||
value: i32,
|
||||
}
|
||||
|
||||
/// struct uinput_setup: name[80] + input_id(4×u16) + ff_effects_max(u32).
|
||||
#[repr(C)]
|
||||
struct UinputSetup {
|
||||
name: [u8; 80],
|
||||
bustype: u16,
|
||||
vendor: u16,
|
||||
product: u16,
|
||||
version: u16,
|
||||
ff_effects_max: u32,
|
||||
}
|
||||
|
||||
/// struct uinput_abs_setup: u16 code (+padding) + input_absinfo (6×i32).
|
||||
#[repr(C)]
|
||||
struct UinputAbsSetup {
|
||||
code: u16,
|
||||
pad: u16,
|
||||
value: i32,
|
||||
minimum: i32,
|
||||
maximum: i32,
|
||||
fuzz: i32,
|
||||
flat: i32,
|
||||
resolution: i32,
|
||||
}
|
||||
|
||||
fn open_device() -> Result<File> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open("/dev/uinput")
|
||||
.context("opening /dev/uinput")
|
||||
}
|
||||
|
||||
fn ioctl_u32(file: &File, request: libc::Ioctl, value: u32) -> Result<()> {
|
||||
let rc = unsafe { libc::ioctl(file.as_raw_fd(), request, value) };
|
||||
if rc < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("uinput ioctl");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One kernel virtual input device.
|
||||
struct UinputDevice {
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl UinputDevice {
|
||||
fn create(name: &'static str, product: u16) -> Result<Self> {
|
||||
let file = open_device()?;
|
||||
unsafe {
|
||||
let mut setup_name = [0u8; 80];
|
||||
let label = name.as_bytes();
|
||||
let len = label.len().min(79);
|
||||
setup_name[..len].copy_from_slice(&label[..len]);
|
||||
let rc = libc::ioctl(
|
||||
file.as_raw_fd(),
|
||||
UI_DEV_SETUP,
|
||||
&UinputSetup {
|
||||
name: setup_name,
|
||||
bustype: BUS_VIRTUAL,
|
||||
vendor: 0x1,
|
||||
product,
|
||||
version: 1,
|
||||
ff_effects_max: 0,
|
||||
},
|
||||
);
|
||||
if rc < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("uinput UI_DEV_SETUP");
|
||||
}
|
||||
}
|
||||
Ok(Self { file })
|
||||
}
|
||||
|
||||
fn keybit(&self, code: u16) -> Result<()> {
|
||||
ioctl_u32(&self.file, UI_SET_KEYBIT, code as u32)
|
||||
}
|
||||
|
||||
fn relbit(&self, code: u16) -> Result<()> {
|
||||
ioctl_u32(&self.file, UI_SET_RELBIT, code as u32)
|
||||
}
|
||||
|
||||
fn absbit(&self, code: u16, maximum: i32) -> Result<()> {
|
||||
ioctl_u32(&self.file, UI_SET_ABSBIT, code as u32)?;
|
||||
let setup = UinputAbsSetup {
|
||||
code,
|
||||
pad: 0,
|
||||
value: 0,
|
||||
minimum: 0,
|
||||
maximum,
|
||||
fuzz: 0,
|
||||
flat: 0,
|
||||
resolution: 0,
|
||||
};
|
||||
let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_ABS_SETUP, &setup) };
|
||||
if rc < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("uinput UI_ABS_SETUP");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(&self) -> Result<()> {
|
||||
let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_DEV_CREATE) };
|
||||
if rc < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("uinput UI_DEV_CREATE");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit(&self, type_: u16, code: u16, value: i32) -> Result<()> {
|
||||
let event = InputEvent {
|
||||
tv_sec: 0,
|
||||
tv_usec: 0,
|
||||
type_,
|
||||
code,
|
||||
value,
|
||||
};
|
||||
let bytes = unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
&event as *const InputEvent as *const u8,
|
||||
std::mem::size_of::<InputEvent>(),
|
||||
)
|
||||
};
|
||||
// File implements Write through a shared reference.
|
||||
let mut file = &self.file;
|
||||
file.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn syn(&self) -> Result<()> {
|
||||
self.emit(EV_SYN, SYN_REPORT, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UinputDevice {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
libc::ioctl(self.file.as_raw_fd(), UI_DEV_DESTROY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kernel-level input injection through /dev/uinput. Works identically on
|
||||
/// every Wayland compositor and every X11 session, because the events enter
|
||||
/// the input stack like real hardware. Requires write access to
|
||||
/// /dev/uinput (udev `uaccess` tag or the `input` group).
|
||||
///
|
||||
/// Devices are deliberately split so libinput classifies each one cleanly:
|
||||
/// mixing REL and ABS axes on one device makes compositors treat it as a
|
||||
/// mouse and silently drop its absolute events (verified on KWin).
|
||||
struct Devices {
|
||||
keyboard: UinputDevice,
|
||||
pointer: UinputDevice,
|
||||
tablet: UinputDevice,
|
||||
}
|
||||
|
||||
impl Devices {
|
||||
fn create() -> Result<Self> {
|
||||
let keyboard = UinputDevice::create("uur virtual keyboard", 1)?;
|
||||
ioctl_u32(&keyboard.file, UI_SET_EVBIT, EV_KEY as u32)?;
|
||||
ioctl_u32(&keyboard.file, UI_SET_EVBIT, EV_SYN as u32)?;
|
||||
for code in 1..=0xffu16 {
|
||||
keyboard.keybit(code)?;
|
||||
}
|
||||
keyboard.finish()?;
|
||||
|
||||
let pointer = UinputDevice::create("uur virtual pointer", 2)?;
|
||||
ioctl_u32(&pointer.file, UI_SET_EVBIT, EV_KEY as u32)?;
|
||||
ioctl_u32(&pointer.file, UI_SET_EVBIT, EV_REL as u32)?;
|
||||
ioctl_u32(&pointer.file, UI_SET_EVBIT, EV_SYN as u32)?;
|
||||
for button in [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_SIDE, BTN_EXTRA] {
|
||||
pointer.keybit(button)?;
|
||||
}
|
||||
for rel in [REL_X, REL_Y, REL_WHEEL, REL_HWHEEL] {
|
||||
pointer.relbit(rel)?;
|
||||
}
|
||||
pointer.finish()?;
|
||||
|
||||
// An absolute pointer must look like a pen tablet, otherwise
|
||||
// libinput treats it as a mouse and ignores absolute motion.
|
||||
let tablet = UinputDevice::create("uur virtual tablet", 3)?;
|
||||
ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_KEY as u32)?;
|
||||
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.absbit(ABS_X, 65535)?;
|
||||
tablet.absbit(ABS_Y, 65535)?;
|
||||
tablet.finish()?;
|
||||
// Stay in proximity so hover motion keeps updating the cursor.
|
||||
tablet.emit(EV_KEY, BTN_TOOL_PEN, 1)?;
|
||||
tablet.syn()?;
|
||||
|
||||
Ok(Self {
|
||||
keyboard,
|
||||
pointer,
|
||||
tablet,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UinputBackend {
|
||||
devices: Devices,
|
||||
held_keys: HashSet<u16>,
|
||||
held_buttons: HashSet<u16>,
|
||||
}
|
||||
|
||||
impl UinputBackend {
|
||||
pub fn connect() -> Result<Self> {
|
||||
let devices = Devices::create()?;
|
||||
Ok(Self {
|
||||
devices,
|
||||
held_keys: HashSet::new(),
|
||||
held_buttons: HashSet::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl InputBackend for UinputBackend {
|
||||
fn name(&self) -> &'static str {
|
||||
"uinput"
|
||||
}
|
||||
|
||||
fn key(&mut self, vkey: u16, down: bool) -> Result<()> {
|
||||
let code = vk_to_linux_key(vkey);
|
||||
if code == 0 {
|
||||
return Ok(()); // not representable on this layout; drop quietly
|
||||
}
|
||||
let value = if down { 1 } else { 0 };
|
||||
self.devices.keyboard.emit(EV_KEY, code, value)?;
|
||||
self.devices.keyboard.syn()?;
|
||||
if down {
|
||||
self.held_keys.insert(code);
|
||||
} else {
|
||||
self.held_keys.remove(&code);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn button(&mut self, button: u16, down: bool) -> Result<()> {
|
||||
let code = match button {
|
||||
1 => BTN_LEFT,
|
||||
2 => BTN_RIGHT,
|
||||
3 => BTN_MIDDLE,
|
||||
8 => BTN_SIDE,
|
||||
9 => BTN_EXTRA,
|
||||
_ => return Ok(()), // unknown buttons are dropped, not fatal
|
||||
};
|
||||
let value = if down { 1 } else { 0 };
|
||||
self.devices.pointer.emit(EV_KEY, code, value)?;
|
||||
self.devices.pointer.syn()?;
|
||||
if down {
|
||||
self.held_buttons.insert(code);
|
||||
} else {
|
||||
self.held_buttons.remove(&code);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> {
|
||||
if absolute {
|
||||
self.devices.tablet.emit(EV_ABS, ABS_X, x.clamp(0, 65535))?;
|
||||
self.devices.tablet.emit(EV_ABS, ABS_Y, y.clamp(0, 65535))?;
|
||||
self.devices.tablet.syn()?;
|
||||
} else {
|
||||
self.devices.pointer.emit(EV_REL, REL_X, x)?;
|
||||
self.devices.pointer.emit(EV_REL, REL_Y, y)?;
|
||||
self.devices.pointer.syn()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> {
|
||||
self.devices.pointer.emit(
|
||||
EV_REL,
|
||||
if horizontal { REL_HWHEEL } else { REL_WHEEL },
|
||||
super::wheel_steps(delta),
|
||||
)?;
|
||||
self.devices.pointer.syn()
|
||||
}
|
||||
|
||||
fn release_all(&mut self) -> Result<()> {
|
||||
for code in self.held_keys.clone() {
|
||||
self.devices.keyboard.emit(EV_KEY, code, 0)?;
|
||||
}
|
||||
self.held_keys.clear();
|
||||
for code in self.held_buttons.clone() {
|
||||
self.devices.pointer.emit(EV_KEY, code, 0)?;
|
||||
}
|
||||
self.held_buttons.clear();
|
||||
self.devices.keyboard.syn()?;
|
||||
self.devices.pointer.syn()
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows virtual-key code -> Linux input keycode, invariant subset.
|
||||
/// The layout-aware remainder arrives with the Phase 2 semantic text path.
|
||||
pub(crate) fn vk_to_linux_key(vkey: u16) -> u16 {
|
||||
let base = vkey & 0xff;
|
||||
let extended = vkey & 0x100 != 0;
|
||||
let code = match base {
|
||||
0x08 => linux::KEY_BACKSPACE,
|
||||
0x09 => linux::KEY_TAB,
|
||||
0x0d if extended => linux::KEY_KPENTER,
|
||||
0x0d => linux::KEY_ENTER,
|
||||
0x10 | 0xa0 => linux::KEY_LEFTSHIFT,
|
||||
0xa1 => linux::KEY_RIGHTSHIFT,
|
||||
0x11 | 0xa2 if extended => linux::KEY_RIGHTCTRL,
|
||||
0x11 | 0xa2 => linux::KEY_LEFTCTRL,
|
||||
0xa3 => linux::KEY_RIGHTCTRL,
|
||||
0x12 | 0xa4 if extended => linux::KEY_RIGHTALT,
|
||||
0x12 | 0xa4 => linux::KEY_LEFTALT,
|
||||
0xa5 => linux::KEY_RIGHTALT,
|
||||
0x13 => linux::KEY_PAUSE,
|
||||
0x14 => linux::KEY_CAPSLOCK,
|
||||
0x1b => linux::KEY_ESC,
|
||||
0x20 => linux::KEY_SPACE,
|
||||
0x21 => linux::KEY_PAGEUP,
|
||||
0x22 => linux::KEY_PAGEDOWN,
|
||||
0x23 => linux::KEY_END,
|
||||
0x24 => linux::KEY_HOME,
|
||||
0x25 => linux::KEY_LEFT,
|
||||
0x26 => linux::KEY_UP,
|
||||
0x27 => linux::KEY_RIGHT,
|
||||
0x28 => linux::KEY_DOWN,
|
||||
0x2d => linux::KEY_INSERT,
|
||||
0x2e => linux::KEY_DELETE,
|
||||
0x30 => linux::KEY_0,
|
||||
0x31 => linux::KEY_1,
|
||||
0x32 => linux::KEY_2,
|
||||
0x33 => linux::KEY_3,
|
||||
0x34 => linux::KEY_4,
|
||||
0x35 => linux::KEY_5,
|
||||
0x36 => linux::KEY_6,
|
||||
0x37 => linux::KEY_7,
|
||||
0x38 => linux::KEY_8,
|
||||
0x39 => linux::KEY_9,
|
||||
0x41 => linux::KEY_A,
|
||||
0x42 => linux::KEY_B,
|
||||
0x43 => linux::KEY_C,
|
||||
0x44 => linux::KEY_D,
|
||||
0x45 => linux::KEY_E,
|
||||
0x46 => linux::KEY_F,
|
||||
0x47 => linux::KEY_G,
|
||||
0x48 => linux::KEY_H,
|
||||
0x49 => linux::KEY_I,
|
||||
0x4a => linux::KEY_J,
|
||||
0x4b => linux::KEY_K,
|
||||
0x4c => linux::KEY_L,
|
||||
0x4d => linux::KEY_M,
|
||||
0x4e => linux::KEY_N,
|
||||
0x4f => linux::KEY_O,
|
||||
0x50 => linux::KEY_P,
|
||||
0x51 => linux::KEY_Q,
|
||||
0x52 => linux::KEY_R,
|
||||
0x53 => linux::KEY_S,
|
||||
0x54 => linux::KEY_T,
|
||||
0x55 => linux::KEY_U,
|
||||
0x56 => linux::KEY_V,
|
||||
0x57 => linux::KEY_W,
|
||||
0x58 => linux::KEY_X,
|
||||
0x59 => linux::KEY_Y,
|
||||
0x5a => linux::KEY_Z,
|
||||
0x5b => linux::KEY_LEFTMETA,
|
||||
0x5c => linux::KEY_RIGHTMETA,
|
||||
0x60 => linux::KEY_KP0,
|
||||
0x61 => linux::KEY_KP1,
|
||||
0x62 => linux::KEY_KP2,
|
||||
0x63 => linux::KEY_KP3,
|
||||
0x64 => linux::KEY_KP4,
|
||||
0x65 => linux::KEY_KP5,
|
||||
0x66 => linux::KEY_KP6,
|
||||
0x67 => linux::KEY_KP7,
|
||||
0x68 => linux::KEY_KP8,
|
||||
0x69 => linux::KEY_KP9,
|
||||
0x6a => linux::KEY_KPASTERISK,
|
||||
0x6b => linux::KEY_KPPLUS,
|
||||
0x6d => linux::KEY_KPMINUS,
|
||||
0x6e => linux::KEY_KPDOT,
|
||||
0x6f => linux::KEY_KPSLASH,
|
||||
0x70 => linux::KEY_F1,
|
||||
0x71 => linux::KEY_F2,
|
||||
0x72 => linux::KEY_F3,
|
||||
0x73 => linux::KEY_F4,
|
||||
0x74 => linux::KEY_F5,
|
||||
0x75 => linux::KEY_F6,
|
||||
0x76 => linux::KEY_F7,
|
||||
0x77 => linux::KEY_F8,
|
||||
0x78 => linux::KEY_F9,
|
||||
0x79 => linux::KEY_F10,
|
||||
0x7a => linux::KEY_F11,
|
||||
0x7b => linux::KEY_F12,
|
||||
0xba => linux::KEY_SEMICOLON,
|
||||
0xbb => linux::KEY_EQUAL,
|
||||
0xbc => linux::KEY_COMMA,
|
||||
0xbd => linux::KEY_MINUS,
|
||||
0xbe => linux::KEY_DOT,
|
||||
0xbf => linux::KEY_SLASH,
|
||||
0xc0 => linux::KEY_GRAVE,
|
||||
0xdb => linux::KEY_LEFTBRACE,
|
||||
0xdc => linux::KEY_BACKSLASH,
|
||||
0xdd => linux::KEY_RIGHTBRACE,
|
||||
0xde => linux::KEY_APOSTROPHE,
|
||||
_ => return 0,
|
||||
};
|
||||
code as u16
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::vk_to_linux_key;
|
||||
use input_linux_sys as linux;
|
||||
|
||||
#[test]
|
||||
fn qwerty_row_uses_evdev_physical_positions() {
|
||||
let mapped: Vec<u16> = "QWERTYUIOP"
|
||||
.bytes()
|
||||
.map(|key| vk_to_linux_key(key.into()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
mapped,
|
||||
[
|
||||
linux::KEY_Q,
|
||||
linux::KEY_W,
|
||||
linux::KEY_E,
|
||||
linux::KEY_R,
|
||||
linux::KEY_T,
|
||||
linux::KEY_Y,
|
||||
linux::KEY_U,
|
||||
linux::KEY_I,
|
||||
linux::KEY_O,
|
||||
linux::KEY_P,
|
||||
]
|
||||
.map(|code| code as u16)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alphabet_is_not_assumed_contiguous() {
|
||||
let mapped: Vec<u16> = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
.bytes()
|
||||
.map(|key| vk_to_linux_key(key.into()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
mapped,
|
||||
[
|
||||
linux::KEY_A,
|
||||
linux::KEY_B,
|
||||
linux::KEY_C,
|
||||
linux::KEY_D,
|
||||
linux::KEY_E,
|
||||
linux::KEY_F,
|
||||
linux::KEY_G,
|
||||
linux::KEY_H,
|
||||
linux::KEY_I,
|
||||
linux::KEY_J,
|
||||
linux::KEY_K,
|
||||
linux::KEY_L,
|
||||
linux::KEY_M,
|
||||
linux::KEY_N,
|
||||
linux::KEY_O,
|
||||
linux::KEY_P,
|
||||
linux::KEY_Q,
|
||||
linux::KEY_R,
|
||||
linux::KEY_S,
|
||||
linux::KEY_T,
|
||||
linux::KEY_U,
|
||||
linux::KEY_V,
|
||||
linux::KEY_W,
|
||||
linux::KEY_X,
|
||||
linux::KEY_Y,
|
||||
linux::KEY_Z,
|
||||
]
|
||||
.map(|code| code as u16)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_contiguous_function_keys_and_extended_modifiers_are_preserved() {
|
||||
assert_eq!(vk_to_linux_key(0x7a), linux::KEY_F11 as u16);
|
||||
assert_eq!(vk_to_linux_key(0x7b), linux::KEY_F12 as u16);
|
||||
assert_eq!(vk_to_linux_key(0x111), linux::KEY_RIGHTCTRL as u16);
|
||||
assert_eq!(vk_to_linux_key(0x112), linux::KEY_RIGHTALT as u16);
|
||||
assert_eq!(vk_to_linux_key(0x10d), linux::KEY_KPENTER as u16);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashSet;
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::{ConnectionExt, Keycode};
|
||||
use x11rb::protocol::xtest::ConnectionExt as XtestExt;
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
|
||||
use super::InputBackend;
|
||||
|
||||
const FAKE_KEY_PRESS: u8 = 2;
|
||||
const FAKE_KEY_RELEASE: u8 = 3;
|
||||
const FAKE_BUTTON_PRESS: u8 = 4;
|
||||
const FAKE_BUTTON_RELEASE: u8 = 5;
|
||||
const FAKE_MOTION: u8 = 6;
|
||||
/// XTEST detail for motion: 0 = absolute, 1 = relative.
|
||||
const MOTION_RELATIVE: u8 = 1;
|
||||
|
||||
/// X11 XTest injection. Works on every X11 session; on XWayland it reaches
|
||||
/// XWayland-native windows only, which is why the portal backend is
|
||||
/// preferred on Wayland-only sessions.
|
||||
pub struct XtestBackend {
|
||||
conn: RustConnection,
|
||||
screen: usize,
|
||||
held_keys: HashSet<Keycode>,
|
||||
held_buttons: HashSet<u8>,
|
||||
}
|
||||
|
||||
impl XtestBackend {
|
||||
pub fn connect() -> Result<Self> {
|
||||
let (conn, screen) = x11rb::connect(None).context("connecting to X display")?;
|
||||
Ok(Self {
|
||||
conn,
|
||||
screen,
|
||||
held_keys: HashSet::new(),
|
||||
held_buttons: HashSet::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn root(&self) -> x11rb::protocol::xproto::Window {
|
||||
self.conn.setup().roots[self.screen].root
|
||||
}
|
||||
|
||||
fn screen_size(&self) -> (i16, i16) {
|
||||
let root = &self.conn.setup().roots[self.screen];
|
||||
(root.width_in_pixels as i16, root.height_in_pixels as i16)
|
||||
}
|
||||
|
||||
fn fake(&self, kind: u8, detail: u8, x: i16, y: i16) -> Result<()> {
|
||||
self.conn
|
||||
.xtest_fake_input(kind, detail, 0, self.root(), x, y, 0)
|
||||
.context("XTestFakeInput")?;
|
||||
self.conn.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl InputBackend for XtestBackend {
|
||||
fn name(&self) -> &'static str {
|
||||
"xtest"
|
||||
}
|
||||
|
||||
fn key(&mut self, vkey: u16, down: bool) -> Result<()> {
|
||||
let keycode = self.vkey_to_keycode(vkey)?;
|
||||
self.fake(
|
||||
if down {
|
||||
FAKE_KEY_PRESS
|
||||
} else {
|
||||
FAKE_KEY_RELEASE
|
||||
},
|
||||
keycode,
|
||||
0,
|
||||
0,
|
||||
)?;
|
||||
if down {
|
||||
self.held_keys.insert(keycode);
|
||||
} else {
|
||||
self.held_keys.remove(&keycode);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn button(&mut self, button: u16, down: bool) -> Result<()> {
|
||||
// Windows and X11 agree on 1-based button numbering.
|
||||
self.fake(
|
||||
if down {
|
||||
FAKE_BUTTON_PRESS
|
||||
} else {
|
||||
FAKE_BUTTON_RELEASE
|
||||
},
|
||||
button as u8,
|
||||
0,
|
||||
0,
|
||||
)?;
|
||||
if down {
|
||||
self.held_buttons.insert(button as u8);
|
||||
} else {
|
||||
self.held_buttons.remove(&(button as u8));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> {
|
||||
if absolute {
|
||||
let (width, height) = self.screen_size();
|
||||
let clamped_x = ((x.clamp(0, 65535) as i64 * (width as i64 - 1)) / 65535) as i16;
|
||||
let clamped_y = ((y.clamp(0, 65535) as i64 * (height as i64 - 1)) / 65535) as i16;
|
||||
self.fake(FAKE_MOTION, 0, clamped_x, clamped_y)?;
|
||||
} else {
|
||||
self.fake(FAKE_MOTION, MOTION_RELATIVE, x as i16, y as i16)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> {
|
||||
// X11 has no wheel concept: synthesize button 4/5 (vertical) and
|
||||
// 6/7 (horizontal) presses, one per notch.
|
||||
let (up_button, down_button) = if horizontal { (7u8, 6u8) } else { (4u8, 5u8) };
|
||||
let steps = super::wheel_steps(delta);
|
||||
for _ in 0..steps.unsigned_abs() {
|
||||
let button = if steps > 0 { up_button } else { down_button };
|
||||
self.fake(FAKE_BUTTON_PRESS, button, 0, 0)?;
|
||||
self.fake(FAKE_BUTTON_RELEASE, button, 0, 0)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn release_all(&mut self) -> Result<()> {
|
||||
for keycode in self.held_keys.clone() {
|
||||
self.fake(FAKE_KEY_RELEASE, keycode, 0, 0)?;
|
||||
}
|
||||
self.held_keys.clear();
|
||||
for button in self.held_buttons.clone() {
|
||||
self.fake(FAKE_BUTTON_RELEASE, button, 0, 0)?;
|
||||
}
|
||||
self.held_buttons.clear();
|
||||
self.conn.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl XtestBackend {
|
||||
/// Map a Windows virtual-key code onto this server's keymap via the
|
||||
/// invariant keysym subset. Layout-aware remapping for non-representable
|
||||
/// keys is Phase 2 together with the semantic text path.
|
||||
fn vkey_to_keycode(&self, vkey: u16) -> Result<Keycode> {
|
||||
let base = (vkey & 0xff) as u32;
|
||||
|
||||
let keysym: u32 = match base {
|
||||
0x08 => 0xff08, // BackSpace
|
||||
0x09 => 0xff09, // Tab
|
||||
0x0d => 0xff0d, // Return
|
||||
0x13 => 0xff13, // Pause
|
||||
0x14 => 0xffe5, // Caps Lock
|
||||
0x1b => 0xff1b, // Escape
|
||||
0x20 => 0x0020, // Space
|
||||
0x21 => 0xff55, // Prior
|
||||
0x22 => 0xff56, // Next
|
||||
0x23 => 0xff57, // End
|
||||
0x24 => 0xff50, // Home
|
||||
0x25 => 0xff51, // Left
|
||||
0x26 => 0xff52, // Up
|
||||
0x27 => 0xff53, // Right
|
||||
0x28 => 0xff54, // Down
|
||||
0x2d => 0xffff, // Insert
|
||||
0x2e => 0xff9f, // Delete (keypad-style)
|
||||
0x30..=0x39 => base, // 0-9
|
||||
0x41..=0x5a => base + 0x20, // A-Z -> lowercase keysyms
|
||||
0x60..=0x69 => 0xffb0 + (base - 0x60), // KP_0..KP_9
|
||||
0x6a => 0xffaa, // KP multiply
|
||||
0x6b => 0xffab, // KP add
|
||||
0x6d => 0xffad, // KP subtract
|
||||
0x6e => 0xffae, // KP decimal
|
||||
0x6f => 0xffaf, // KP divide
|
||||
0x70..=0x87 => 0xffbe + (base - 0x70), // F1..F24
|
||||
0xa0 => 0xffe1, // Shift L
|
||||
0xa1 => 0xffe2, // Shift R
|
||||
0xa2 => 0xffe3, // Control L
|
||||
0xa3 => 0xffe4, // Control R
|
||||
0xa4 => 0xffe9, // Alt L
|
||||
0xa5 => 0xffea, // Alt R
|
||||
0x5b => 0xffeb, // Meta L
|
||||
0x5c => 0xffec, // Meta R
|
||||
0xba => 0x3b, // ;
|
||||
0xbb => 0x3d, // =
|
||||
0xbc => 0x2c, // ,
|
||||
0xbd => 0x2d, // -
|
||||
0xbe => 0x2e, // .
|
||||
0xbf => 0x2f, // /
|
||||
0xc0 => 0x60, // `
|
||||
0xdb => 0x5b, // [
|
||||
0xdc => 0x5c, // backslash
|
||||
0xdd => 0x5d, // ]
|
||||
0xde => 0x27, // '
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
let setup = self.conn.setup();
|
||||
let min = setup.min_keycode;
|
||||
let max = setup.max_keycode;
|
||||
let map = self
|
||||
.conn
|
||||
.get_keyboard_mapping(min, max - min + 1)?
|
||||
.reply()?;
|
||||
|
||||
if keysym != 0 {
|
||||
let per = map.keysyms_per_keycode.max(1) as usize;
|
||||
for (index, chunk) in map.keysyms.chunks(per).enumerate() {
|
||||
if chunk.contains(&keysym) {
|
||||
return Ok(min + index as Keycode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layout does not represent this key: nearest identity fallback
|
||||
// keeps events flowing instead of dropping them silently.
|
||||
Ok(base as Keycode)
|
||||
}
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
//! XDG desktop application bridge for UU's Windows quick-launch scanner.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
|
||||
const MAGIC: u32 = 0x5555_4c41;
|
||||
const TOKEN_BYTES: usize = 64;
|
||||
const MAX_APPS: usize = 128;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DesktopApp {
|
||||
id: String,
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
pub fn prepare(prefix: &Path, proxy: &Path) -> Result<usize> {
|
||||
let apps = catalog();
|
||||
let root = prefix.join("drive_c/uur-linux-apps");
|
||||
if root.exists() {
|
||||
std::fs::remove_dir_all(&root).context("replacing Linux quick-launch staging")?;
|
||||
}
|
||||
std::fs::create_dir_all(&root)?;
|
||||
|
||||
let old_keys = std::fs::read_to_string(root.with_extension("keys")).unwrap_or_default();
|
||||
let mut registry = String::from("Windows Registry Editor Version 5.00\r\n\r\n");
|
||||
for key in old_keys.lines().filter(|key| !key.is_empty()) {
|
||||
registry.push_str(&format!("[-HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{key}]\r\n\r\n"));
|
||||
}
|
||||
|
||||
let mut keys = Vec::new();
|
||||
for app in apps.values().take(MAX_APPS) {
|
||||
let hash = fnv1a(app.id.as_bytes());
|
||||
let key = format!("UURLinux_{hash:016x}");
|
||||
let directory = root.join(format!("{hash:016x}"));
|
||||
std::fs::create_dir_all(&directory)?;
|
||||
std::fs::copy(proxy, directory.join("launcher.exe"))?;
|
||||
std::fs::write(directory.join("app-id.txt"), format!("{}\n", app.id))?;
|
||||
let windows_directory = format!(r"C:\uur-linux-apps\{hash:016x}");
|
||||
let executable = format!(r"{windows_directory}\launcher.exe");
|
||||
registry.push_str(&format!(
|
||||
"[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{key}]\r\n\
|
||||
\"DisplayName\"=\"{}\"\r\n\
|
||||
\"DisplayVersion\"=\"1\"\r\n\
|
||||
\"Publisher\"=\"Linux desktop\"\r\n\
|
||||
\"InstallLocation\"=\"{}\"\r\n\
|
||||
\"InstallSource\"=\"XDG Desktop Entry\"\r\n\
|
||||
\"DisplayIcon\"=\"{}\"\r\n\
|
||||
\"UninstallString\"=\"{}\"\r\n\
|
||||
\"NoModify\"=dword:00000001\r\n\
|
||||
\"NoRepair\"=dword:00000001\r\n\r\n",
|
||||
reg_escape(&app.name),
|
||||
reg_escape(&windows_directory),
|
||||
reg_escape(&executable),
|
||||
reg_escape(&executable),
|
||||
));
|
||||
keys.push(key);
|
||||
}
|
||||
std::fs::write(root.with_extension("keys"), keys.join("\n") + "\n")?;
|
||||
let registry_path = prefix.join("drive_c/uur-linux-apps.reg");
|
||||
write_utf16_registry(®istry_path, ®istry)?;
|
||||
let status = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.args(["reg", "import"])
|
||||
.arg(®istry_path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.context("importing Linux quick-launch applications")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("Wine rejected the Linux quick-launch registry");
|
||||
}
|
||||
Ok(keys.len())
|
||||
}
|
||||
|
||||
pub fn serve() -> Result<()> {
|
||||
let prefix = crate::config::data_dir()?.join("wine");
|
||||
let config_path = runtime_config(&prefix);
|
||||
let apps = Arc::new(catalog());
|
||||
let token = random_token()?;
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0))?;
|
||||
write_config(&config_path, listener.local_addr()?.port(), &token)?;
|
||||
println!(
|
||||
"native quick-launch service ready with {} applications",
|
||||
apps.len()
|
||||
);
|
||||
for stream in listener.incoming().flatten() {
|
||||
let apps = apps.clone();
|
||||
let token = token.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = handle(stream, &token, &apps) {
|
||||
eprintln!("quick-launch request failed: {error:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn runtime_config(prefix: &Path) -> PathBuf {
|
||||
prefix.join("drive_c/uur-launcher.runtime")
|
||||
}
|
||||
|
||||
fn handle(
|
||||
mut stream: TcpStream,
|
||||
expected_token: &str,
|
||||
apps: &BTreeMap<String, DesktopApp>,
|
||||
) -> Result<()> {
|
||||
let mut header = [0u8; 12];
|
||||
stream.read_exact(&mut header)?;
|
||||
let magic = u32::from_be_bytes(header[0..4].try_into().unwrap());
|
||||
let version = u16::from_be_bytes(header[4..6].try_into().unwrap());
|
||||
let token_length = u16::from_be_bytes(header[6..8].try_into().unwrap()) as usize;
|
||||
let id_length = u16::from_be_bytes(header[8..10].try_into().unwrap()) as usize;
|
||||
if magic != MAGIC
|
||||
|| version != 1
|
||||
|| token_length != TOKEN_BYTES
|
||||
|| id_length == 0
|
||||
|| id_length > 500
|
||||
{
|
||||
anyhow::bail!("invalid quick-launch handshake");
|
||||
}
|
||||
let mut token = [0u8; TOKEN_BYTES];
|
||||
stream.read_exact(&mut token)?;
|
||||
if !constant_time_equal(&token, expected_token.as_bytes()) {
|
||||
anyhow::bail!("quick-launch authentication failed");
|
||||
}
|
||||
let mut id = vec![0u8; id_length];
|
||||
stream.read_exact(&mut id)?;
|
||||
let id = std::str::from_utf8(&id)?;
|
||||
let accepted = apps.get(id).is_some_and(launch);
|
||||
stream.write_all(&[accepted as u8])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn launch(app: &DesktopApp) -> bool {
|
||||
let gio = Command::new("gio")
|
||||
.arg("launch")
|
||||
.arg(&app.path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn();
|
||||
if gio.is_ok() {
|
||||
return true;
|
||||
}
|
||||
Command::new("gtk-launch")
|
||||
.arg(app.id.trim_end_matches(".desktop"))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn catalog() -> BTreeMap<String, DesktopApp> {
|
||||
let mut apps = BTreeMap::new();
|
||||
for directory in data_directories() {
|
||||
collect_desktop_entries(&directory.join("applications"), &mut apps);
|
||||
}
|
||||
apps
|
||||
}
|
||||
|
||||
fn data_directories() -> Vec<PathBuf> {
|
||||
let mut directories: Vec<PathBuf> = std::env::var("XDG_DATA_DIRS")
|
||||
.unwrap_or_else(|_| "/usr/local/share:/usr/share".into())
|
||||
.split(':')
|
||||
.filter(|entry| !entry.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.collect();
|
||||
if let Some(user) = std::env::var_os("XDG_DATA_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share")))
|
||||
{
|
||||
directories.push(user);
|
||||
}
|
||||
directories
|
||||
}
|
||||
|
||||
fn collect_desktop_entries(directory: &Path, apps: &mut BTreeMap<String, DesktopApp>) {
|
||||
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_desktop_entries(&path, apps);
|
||||
continue;
|
||||
}
|
||||
if path.extension().and_then(|extension| extension.to_str()) != Some("desktop")
|
||||
|| path
|
||||
.components()
|
||||
.any(|component| component.as_os_str() == "wine")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(id) = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.map(str::to_string)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(content) = std::fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
let mut in_desktop = false;
|
||||
let mut kind = "";
|
||||
let mut name = None;
|
||||
let mut hidden = false;
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.starts_with('[') {
|
||||
in_desktop = line == "[Desktop Entry]";
|
||||
continue;
|
||||
}
|
||||
if !in_desktop {
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("Type=") {
|
||||
kind = value;
|
||||
} else if let Some(value) = line.strip_prefix("Name=") {
|
||||
name = Some(value.trim().to_string());
|
||||
} else if line == "Hidden=true" || line == "NoDisplay=true" {
|
||||
hidden = true;
|
||||
}
|
||||
}
|
||||
if kind == "Application" && !hidden {
|
||||
if let Some(name) = name.filter(|name| !name.is_empty()) {
|
||||
apps.insert(id.clone(), DesktopApp { id, name, path });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_config(path: &Path, port: u16, token: &str) -> Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(path)?;
|
||||
writeln!(file, "version=1")?;
|
||||
writeln!(file, "port={port}")?;
|
||||
writeln!(file, "token={token}")?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn random_token() -> Result<String> {
|
||||
let mut bytes = [0u8; 32];
|
||||
File::open("/dev/urandom")?.read_exact(&mut bytes)?;
|
||||
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
|
||||
}
|
||||
|
||||
fn constant_time_equal(left: &[u8], right: &[u8]) -> bool {
|
||||
if left.len() != right.len() {
|
||||
return false;
|
||||
}
|
||||
left.iter()
|
||||
.zip(right)
|
||||
.fold(0u8, |difference, (left, right)| difference | (left ^ right))
|
||||
== 0
|
||||
}
|
||||
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
|
||||
(hash ^ u64::from(*byte)).wrapping_mul(0x100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
fn reg_escape(value: &str) -> String {
|
||||
value.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
|
||||
fn write_utf16_registry(path: &Path, content: &str) -> Result<()> {
|
||||
let mut bytes = vec![0xff, 0xfe];
|
||||
for unit in content.encode_utf16() {
|
||||
bytes.extend_from_slice(&unit.to_le_bytes());
|
||||
}
|
||||
std::fs::write(path, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{fnv1a, reg_escape};
|
||||
|
||||
#[test]
|
||||
fn registry_values_are_escaped() {
|
||||
assert_eq!(reg_escape(r#"A\B"C"#), r#"A\\B\"C"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_hash_is_stable() {
|
||||
let first = fnv1a(b"org.example.App.desktop");
|
||||
assert_eq!(first, fnv1a(b"org.example.App.desktop"));
|
||||
assert_ne!(first, fnv1a(b"org.example.Other.desktop"));
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#[macro_use]
|
||||
extern crate rust_i18n;
|
||||
|
||||
mod audio;
|
||||
mod autostart;
|
||||
mod bridge;
|
||||
mod capture;
|
||||
mod config;
|
||||
mod doctor;
|
||||
mod i18n;
|
||||
mod inhibit;
|
||||
mod input;
|
||||
mod launcher;
|
||||
mod protocol;
|
||||
mod proxy;
|
||||
mod session;
|
||||
mod terminal;
|
||||
mod upstream;
|
||||
mod video;
|
||||
mod wallpaper;
|
||||
mod wine;
|
||||
mod wol;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
|
||||
// Locale catalogs are embedded from `locales/` at the crate root.
|
||||
i18n!("locales", fallback = "en");
|
||||
|
||||
/// Native Linux companion for NetEase UU Remote.
|
||||
///
|
||||
/// uur runs the official Windows client inside a managed Wine prefix and
|
||||
/// bridges its input and screen capture onto the real Linux desktop through
|
||||
/// X11 XTest or the Wayland RemoteDesktop portal.
|
||||
#[derive(Parser)]
|
||||
#[command(name = "uur", version, about, arg_required_else_help = true)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// One-time provisioning: EULA gate, Wine prefix, official client download.
|
||||
Setup {
|
||||
/// Accept the NetEase UU Remote EULA non-interactively.
|
||||
#[arg(long)]
|
||||
accept_eula: bool,
|
||||
},
|
||||
/// Print the live environment report (sessions, wine, portals, backends).
|
||||
Doctor,
|
||||
/// Print the current X11 pointer position (verification helper).
|
||||
Pointer,
|
||||
/// Capture the desktop through the ScreenCast portal (video path).
|
||||
Capture,
|
||||
/// Start a full session: capture + bridge + the managed client.
|
||||
Run,
|
||||
/// Stop every uur-owned process and the managed Wine prefix.
|
||||
Stop,
|
||||
/// Manage optional XDG login autostart.
|
||||
Autostart {
|
||||
#[command(subcommand)]
|
||||
action: AutostartAction,
|
||||
},
|
||||
/// Inspect or configure host Wake-on-LAN.
|
||||
Wol {
|
||||
#[command(subcommand)]
|
||||
action: WolAction,
|
||||
},
|
||||
/// Select the portal capture source used on Wayland.
|
||||
Display {
|
||||
#[command(subcommand)]
|
||||
action: DisplayAction,
|
||||
},
|
||||
/// Internal input bridge process. Not part of the public CLI.
|
||||
#[command(hide = true, name = "__bridge")]
|
||||
InternalBridge,
|
||||
/// Internal capture process. Not part of the public CLI.
|
||||
#[command(hide = true, name = "__capture")]
|
||||
InternalCapture,
|
||||
/// Internal native PTY bridge. Not part of the public CLI.
|
||||
#[command(hide = true, name = "__terminal")]
|
||||
InternalTerminal,
|
||||
/// Internal Linux wallpaper synchronizer. Not part of the public CLI.
|
||||
#[command(hide = true, name = "__wallpaper")]
|
||||
InternalWallpaper,
|
||||
/// Internal desktop suspend/idle inhibitor. Not part of the public CLI.
|
||||
#[command(hide = true, name = "__inhibit")]
|
||||
InternalInhibit,
|
||||
/// Internal authenticated XDG application launcher.
|
||||
#[command(hide = true, name = "__launcher")]
|
||||
InternalLauncher,
|
||||
/// Query NetEase's official release feed.
|
||||
Upstream {
|
||||
#[command(subcommand)]
|
||||
action: UpstreamAction,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum UpstreamAction {
|
||||
/// Print the latest official UU Remote release known to NetEase.
|
||||
Check,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum AutostartAction {
|
||||
/// Start the managed session after graphical login.
|
||||
Enable,
|
||||
/// Remove the login autostart entry.
|
||||
Disable,
|
||||
/// Report whether login autostart is enabled.
|
||||
Status,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum WolAction {
|
||||
/// Report the selected physical wired adapter and Magic Packet state.
|
||||
Status {
|
||||
#[arg(long)]
|
||||
interface: Option<String>,
|
||||
},
|
||||
/// Enable Magic Packet wake for the adapter and its NetworkManager profile.
|
||||
Enable {
|
||||
#[arg(long)]
|
||||
interface: Option<String>,
|
||||
},
|
||||
/// Disable Magic Packet wake for the adapter and its NetworkManager profile.
|
||||
Disable {
|
||||
#[arg(long)]
|
||||
interface: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum DisplayAction {
|
||||
/// Show the configured source type.
|
||||
Status,
|
||||
/// Use a monitor, one window, or a portal-provided virtual display.
|
||||
Source { source: DisplaySource },
|
||||
}
|
||||
|
||||
#[derive(Clone, ValueEnum)]
|
||||
enum DisplaySource {
|
||||
Monitor,
|
||||
Window,
|
||||
Virtual,
|
||||
}
|
||||
|
||||
impl DisplaySource {
|
||||
fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Monitor => "monitor",
|
||||
Self::Window => "window",
|
||||
Self::Virtual => "virtual",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// CLI output is routinely piped; a closed pipe is not an error.
|
||||
unsafe {
|
||||
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
||||
}
|
||||
i18n::init();
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Command::Setup { accept_eula } => wine::setup(accept_eula),
|
||||
Command::Doctor => doctor::report(),
|
||||
Command::Pointer => bridge::print_pointer(),
|
||||
Command::Capture => capture::run(),
|
||||
Command::Run => session::start(),
|
||||
Command::Stop => session::stop(),
|
||||
Command::Autostart { action } => match action {
|
||||
AutostartAction::Enable => autostart::enable(),
|
||||
AutostartAction::Disable => autostart::disable(),
|
||||
AutostartAction::Status => autostart::status(),
|
||||
},
|
||||
Command::Wol { action } => match action {
|
||||
WolAction::Status { interface } => wol::status(interface.as_deref()),
|
||||
WolAction::Enable { interface } => wol::configure(interface.as_deref(), true),
|
||||
WolAction::Disable { interface } => wol::configure(interface.as_deref(), false),
|
||||
},
|
||||
Command::Display { action } => {
|
||||
let mut config = config::Config::load()?;
|
||||
match action {
|
||||
DisplayAction::Status => {
|
||||
println!("{}", t!("display.status", source = config.capture_source));
|
||||
Ok(())
|
||||
}
|
||||
DisplayAction::Source { source } => {
|
||||
config.capture_source = source.as_str().to_string();
|
||||
config.capture_restore_token = None;
|
||||
config.remote_desktop_restore_token = None;
|
||||
config.store()?;
|
||||
println!("{}", t!("display.changed", source = source.as_str()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::InternalBridge => bridge::serve(),
|
||||
Command::InternalCapture => capture::run(),
|
||||
Command::InternalTerminal => terminal::serve(),
|
||||
Command::InternalWallpaper => wallpaper::serve(),
|
||||
Command::InternalInhibit => inhibit::serve(),
|
||||
Command::InternalLauncher => launcher::serve(),
|
||||
Command::Upstream {
|
||||
action: UpstreamAction::Check,
|
||||
} => upstream::check(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Wire protocol spoken between the in-client PE hook (`hook/`) and the host
|
||||
//! bridge. Kept in one place so both sides stay in lock-step.
|
||||
|
||||
pub const MAGIC: u32 = 0x50495555; // "UUIP" little-endian
|
||||
pub const VERSION: u32 = 1;
|
||||
|
||||
pub const RECORD_HELLO: u32 = 1;
|
||||
pub const RECORD_MOUSE: u32 = 2;
|
||||
pub const RECORD_KEYBOARD: u32 = 3;
|
||||
|
||||
/// One input record. Fixed 16-byte payload after the 16-byte header keeps
|
||||
/// parsing trivial on both sides.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Record {
|
||||
pub kind: u32,
|
||||
/// Keyboard: Windows virtual-key code (as sent by SendInput).
|
||||
/// Mouse: button number for press/release, axis selector for motion.
|
||||
pub code: u16,
|
||||
/// Keyboard: 1 = key-down, 0 = key-up.
|
||||
/// Mouse motion: 1 = absolute, 0 = relative.
|
||||
pub state: u16,
|
||||
pub a: i32,
|
||||
pub b: i32,
|
||||
}
|
||||
|
||||
pub const HEADER_BYTES: usize = 16;
|
||||
pub const RECORD_BYTES: usize = 16;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Header {
|
||||
pub magic: u32,
|
||||
pub version: u32,
|
||||
pub kind: u32,
|
||||
pub length: u32,
|
||||
}
|
||||
|
||||
pub fn read_header(buf: &[u8; HEADER_BYTES]) -> Header {
|
||||
Header {
|
||||
magic: u32::from_le_bytes(buf[0..4].try_into().unwrap()),
|
||||
version: u32::from_le_bytes(buf[4..8].try_into().unwrap()),
|
||||
kind: u32::from_le_bytes(buf[8..12].try_into().unwrap()),
|
||||
length: u32::from_le_bytes(buf[12..16].try_into().unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_record(buf: &[u8; RECORD_BYTES]) -> Record {
|
||||
Record {
|
||||
kind: u32::from_le_bytes(buf[0..4].try_into().unwrap()),
|
||||
code: u16::from_le_bytes(buf[4..6].try_into().unwrap()),
|
||||
state: u16::from_le_bytes(buf[6..8].try_into().unwrap()),
|
||||
a: i32::from_le_bytes(buf[8..12].try_into().unwrap()),
|
||||
b: i32::from_le_bytes(buf[12..16].try_into().unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn header_roundtrip() {
|
||||
let mut buf = [0u8; HEADER_BYTES];
|
||||
buf[0..4].copy_from_slice(&MAGIC.to_le_bytes());
|
||||
buf[4..8].copy_from_slice(&VERSION.to_le_bytes());
|
||||
buf[8..12].copy_from_slice(&RECORD_MOUSE.to_le_bytes());
|
||||
buf[12..16].copy_from_slice(&16u32.to_le_bytes());
|
||||
let header = read_header(&buf);
|
||||
assert_eq!(header.magic, MAGIC);
|
||||
assert_eq!(header.kind, RECORD_MOUSE);
|
||||
assert_eq!(header.length, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_roundtrip() {
|
||||
let mut buf = [0u8; RECORD_BYTES];
|
||||
buf[0..4].copy_from_slice(&RECORD_KEYBOARD.to_le_bytes());
|
||||
buf[4..6].copy_from_slice(&0x41u16.to_le_bytes());
|
||||
buf[6..8].copy_from_slice(&1u16.to_le_bytes());
|
||||
buf[8..12].copy_from_slice(&(-5i32).to_le_bytes());
|
||||
buf[12..16].copy_from_slice(&(7i32).to_le_bytes());
|
||||
let record = read_record(&buf);
|
||||
assert_eq!(record.kind, RECORD_KEYBOARD);
|
||||
assert_eq!(record.code, 0x41);
|
||||
assert_eq!(record.state, 1);
|
||||
assert_eq!(record.a, -5);
|
||||
assert_eq!(record.b, 7);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
//! Import standard Linux proxy environment into Wine's WinINet settings.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
pub fn sync(prefix: &Path) -> Result<Option<String>> {
|
||||
let http = environment_proxy("HTTP_PROXY", "http_proxy");
|
||||
let https = environment_proxy("HTTPS_PROXY", "https_proxy");
|
||||
if http.is_none() && https.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
if let Some(endpoint) = http {
|
||||
entries.push(format!("http={endpoint}"));
|
||||
}
|
||||
if let Some(endpoint) = https {
|
||||
entries.push(format!("https={endpoint}"));
|
||||
}
|
||||
let server = entries.join(";");
|
||||
reg_add(prefix, "ProxyEnable", "REG_DWORD", "1")?;
|
||||
reg_add(prefix, "ProxyServer", "REG_SZ", &server)?;
|
||||
if let Some(no_proxy) = std::env::var("NO_PROXY")
|
||||
.ok()
|
||||
.or_else(|| std::env::var("no_proxy").ok())
|
||||
{
|
||||
let bypass = no_proxy
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|entry| !entry.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(";");
|
||||
if !bypass.is_empty() {
|
||||
reg_add(prefix, "ProxyOverride", "REG_SZ", &bypass)?;
|
||||
}
|
||||
}
|
||||
Ok(Some(server))
|
||||
}
|
||||
|
||||
fn environment_proxy(upper: &str, lower: &str) -> Option<String> {
|
||||
std::env::var(upper)
|
||||
.ok()
|
||||
.or_else(|| std::env::var(lower).ok())
|
||||
.and_then(|value| proxy_endpoint(&value))
|
||||
}
|
||||
|
||||
fn proxy_endpoint(value: &str) -> Option<String> {
|
||||
let value = value.trim();
|
||||
let authority = value
|
||||
.split_once("://")
|
||||
.map(|(_, rest)| rest)
|
||||
.unwrap_or(value)
|
||||
.split('/')
|
||||
.next()?;
|
||||
let endpoint = authority
|
||||
.rsplit_once('@')
|
||||
.map(|(_, host)| host)
|
||||
.unwrap_or(authority);
|
||||
(!endpoint.is_empty()).then(|| endpoint.to_string())
|
||||
}
|
||||
|
||||
fn reg_add(prefix: &Path, value: &str, kind: &str, data: &str) -> Result<()> {
|
||||
let status = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.args([
|
||||
"reg",
|
||||
"add",
|
||||
r"HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings",
|
||||
"/v",
|
||||
value,
|
||||
"/t",
|
||||
kind,
|
||||
"/d",
|
||||
data,
|
||||
"/f",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.with_context(|| format!("writing WinINet proxy value {value}"))?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("Wine rejected WinINet proxy value {value}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::proxy_endpoint;
|
||||
|
||||
#[test]
|
||||
fn proxy_url_is_reduced_without_leaking_credentials() {
|
||||
assert_eq!(
|
||||
proxy_endpoint("http://user:[email protected]:7890/path"),
|
||||
Some("127.0.0.1:7890".into())
|
||||
);
|
||||
assert_eq!(
|
||||
proxy_endpoint("proxy.local:8080"),
|
||||
Some("proxy.local:8080".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
+740
@@ -0,0 +1,740 @@
|
||||
//! Session orchestration: one command starts everything for a remote
|
||||
//! session — desktop capture (portal, silent after first consent), the
|
||||
//! input bridge, and the managed UU client. When the client exits, the
|
||||
//! session ends.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use crate::config::{data_dir, Config};
|
||||
|
||||
fn rotate_session_log() {
|
||||
let state = std::env::var("XDG_STATE_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".local/state")))
|
||||
.unwrap_or_else(|_| PathBuf::from("/tmp"));
|
||||
let _ = std::fs::create_dir_all(state.join("uur"));
|
||||
let _ = std::fs::rename(
|
||||
state.join("uur/session.log"),
|
||||
state.join("uur/session.log.1"),
|
||||
);
|
||||
}
|
||||
|
||||
/// Locate the packaged hook DLLs. Packaged installs use /usr/lib/uur/hook;
|
||||
/// a dev checkout falls back to build/hook next to the sources.
|
||||
const HOOK_COMPONENTS: &[&str] = &[
|
||||
"winlogon.exe",
|
||||
"wevtapi.dll",
|
||||
"uur-hook.dll",
|
||||
"wtsapi32.dll",
|
||||
"uur-terminal-proxy.exe",
|
||||
"uur-mux-proxy.exe",
|
||||
"uur-launch-proxy.exe",
|
||||
];
|
||||
|
||||
fn complete_hook_directory(dir: &Path) -> bool {
|
||||
HOOK_COMPONENTS
|
||||
.iter()
|
||||
.all(|component| dir.join(component).is_file())
|
||||
}
|
||||
|
||||
fn hook_dir() -> Result<PathBuf> {
|
||||
let mut candidates = vec![
|
||||
PathBuf::from("/usr/lib/uur/hook"),
|
||||
PathBuf::from("/usr/local/lib/uur/hook"),
|
||||
];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
candidates.push(dir.join("../lib/uur/hook"));
|
||||
candidates.push(dir.join("../../build/hook"));
|
||||
candidates.push(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|dir| complete_hook_directory(dir))
|
||||
.context("complete hook runtime not found (run the build first)")
|
||||
}
|
||||
|
||||
fn hook_source_dir() -> Result<PathBuf> {
|
||||
let mut candidates = vec![PathBuf::from("/usr/lib/uur/hook")];
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".local/lib/uur/hook"));
|
||||
}
|
||||
candidates.push(
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(|d| d.join("../lib/uur/hook")))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
candidates.push(
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(|d| d.join("../../build/hook")))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
candidates.push(
|
||||
std::env::current_dir()
|
||||
.ok()
|
||||
.map(|dir| dir.join("build/hook"))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|dir| complete_hook_directory(dir))
|
||||
.context("hook DLLs not found (run the build first)")
|
||||
}
|
||||
|
||||
/// Install the native preload DLLs in the managed prefix, outside the
|
||||
/// proprietary application directory. Wine's native override resolves them
|
||||
/// from system32, so client updates never overwrite uur and uur never edits an
|
||||
/// official executable or DLL.
|
||||
fn deploy_hooks(prefix: &Path) -> Result<()> {
|
||||
let source = hook_source_dir()?;
|
||||
let target = prefix.join("drive_c/windows/system32");
|
||||
std::fs::create_dir_all(&target)?;
|
||||
for dll in ["wevtapi.dll", "uur-hook.dll", "wtsapi32.dll"] {
|
||||
let from = source.join(dll);
|
||||
let to = target.join(dll);
|
||||
std::fs::copy(&from, &to)
|
||||
.with_context(|| format!("deploying {} to {}", dll, target.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace UU's Windows ConPTY transport at its documented command-line ABI.
|
||||
/// The adapter receives UU's inherited stdin/stdout handles and forwards them
|
||||
/// to the native Linux PTY service. The official binary is retained for
|
||||
/// recovery, and an obsolete powershell-level adapter is removed on upgrade.
|
||||
fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
|
||||
let source_dir = hook_source_dir()?;
|
||||
let source = source_dir.join("uur-terminal-proxy.exe");
|
||||
let mux_source = source_dir.join("uur-mux-proxy.exe");
|
||||
let bin = install_dir.join("bin");
|
||||
std::fs::create_dir_all(&bin)?;
|
||||
for status in ["uur-terminal-adapter.status", "uur-mux-adapter.status"] {
|
||||
let _ = std::fs::remove_file(bin.join(status));
|
||||
}
|
||||
if let Ok(entries) = std::fs::read_dir(&bin) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.starts_with("uur-terminal-session-") && name.ends_with(".active") {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let legacy_target = bin.join("powershell.exe");
|
||||
let legacy_backup = bin.join("powershell.exe.uur-original");
|
||||
let legacy_marker = bin.join("powershell.exe.uur-managed");
|
||||
if legacy_marker.exists() {
|
||||
let _ = std::fs::remove_file(&legacy_target);
|
||||
if legacy_backup.exists() {
|
||||
std::fs::rename(&legacy_backup, &legacy_target)
|
||||
.with_context(|| format!("restoring {}", legacy_target.display()))?;
|
||||
}
|
||||
let _ = std::fs::remove_file(&legacy_marker);
|
||||
}
|
||||
|
||||
let target = bin.join("conpty_bridge.exe");
|
||||
let backup = bin.join("conpty_bridge.exe.uur-original");
|
||||
let marker = bin.join("conpty_bridge.exe.uur-managed");
|
||||
if target.exists() && !marker.exists() && !backup.exists() {
|
||||
std::fs::copy(&target, &backup)
|
||||
.with_context(|| format!("backing up {}", target.display()))?;
|
||||
}
|
||||
std::fs::copy(&source, &target)
|
||||
.with_context(|| format!("deploying native terminal proxy to {}", target.display()))?;
|
||||
std::fs::write(marker, b"managed by uur\n")?;
|
||||
|
||||
let mux_target = bin.join("uuyc-mux.exe");
|
||||
let mux_backup = bin.join("uuyc-mux.exe.uur-original");
|
||||
let mux_marker = bin.join("uuyc-mux.exe.uur-managed");
|
||||
if mux_target.exists() && !mux_marker.exists() && !mux_backup.exists() {
|
||||
std::fs::copy(&mux_target, &mux_backup)
|
||||
.with_context(|| format!("backing up {}", mux_target.display()))?;
|
||||
}
|
||||
std::fs::copy(&mux_source, &mux_target)
|
||||
.with_context(|| format!("deploying native mux proxy to {}", mux_target.display()))?;
|
||||
std::fs::write(mux_marker, b"managed by uur\n")?;
|
||||
Ok(bin.join("uu-terminal-bridge.runtime"))
|
||||
}
|
||||
|
||||
/// The client UI needs the Evergreen WebView2 runtime; the official
|
||||
/// bootstrapper ships inside the client's bin directory.
|
||||
fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> {
|
||||
let marker = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application");
|
||||
if marker.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let bootstrapper = install_dir
|
||||
.join("bin")
|
||||
.join("MicrosoftEdgeWebview2Setup.exe");
|
||||
if !bootstrapper.is_file() {
|
||||
anyhow::bail!("{}", t!("session.webview_missing"));
|
||||
}
|
||||
println!("{}", t!("session.installing_webview"));
|
||||
let status = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.arg(bootstrapper.to_string_lossy().as_ref())
|
||||
.args(["/silent", "/install"])
|
||||
.status()
|
||||
.context("running the WebView2 bootstrapper")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("{}", t!("session.webview_failed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
use std::os::unix::io::AsRawFd;
|
||||
let state = std::env::var("XDG_STATE_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".local/state")))
|
||||
.unwrap_or_else(|_| PathBuf::from("/tmp"));
|
||||
let dir = state.join("uur");
|
||||
std::fs::create_dir_all(&dir).context("creating state directory")?;
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(dir.join("session.lock"))
|
||||
.context("opening session.lock")?;
|
||||
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
|
||||
if rc != 0 {
|
||||
anyhow::bail!("{}", t!("session.already_running"));
|
||||
}
|
||||
let mut file = file;
|
||||
file.set_len(0)?;
|
||||
writeln!(
|
||||
file,
|
||||
"{} {}",
|
||||
std::process::id(),
|
||||
process_start_time(std::process::id())?
|
||||
)?;
|
||||
file.sync_data()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
struct ManagedChild {
|
||||
child: Child,
|
||||
terminated: bool,
|
||||
}
|
||||
|
||||
impl ManagedChild {
|
||||
fn spawn_internal(argument: &str, log: &std::fs::File) -> Result<Self> {
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
let executable = std::env::current_exe().context("resolving uur executable")?;
|
||||
let mut command = Command::new(executable);
|
||||
command
|
||||
.arg(argument)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.stderr(Stdio::from(log.try_clone()?))
|
||||
.process_group(0);
|
||||
let child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("starting internal helper {argument}"))?;
|
||||
Ok(Self {
|
||||
child,
|
||||
terminated: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn terminate(&mut self) {
|
||||
if self.terminated {
|
||||
return;
|
||||
}
|
||||
self.terminated = true;
|
||||
let group = -(self.child.id() as i32);
|
||||
unsafe {
|
||||
libc::kill(group, libc::SIGTERM);
|
||||
}
|
||||
for _ in 0..20 {
|
||||
if self.child.try_wait().ok().flatten().is_some() {
|
||||
return;
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
unsafe {
|
||||
libc::kill(group, libc::SIGKILL);
|
||||
}
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ManagedChild {
|
||||
fn drop(&mut self) {
|
||||
self.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionResources {
|
||||
prefix: PathBuf,
|
||||
helpers: Vec<ManagedChild>,
|
||||
cleanup_files: Vec<PathBuf>,
|
||||
cleaned: bool,
|
||||
}
|
||||
|
||||
impl SessionResources {
|
||||
fn new(prefix: PathBuf) -> Self {
|
||||
Self {
|
||||
prefix,
|
||||
helpers: Vec::new(),
|
||||
cleanup_files: Vec::new(),
|
||||
cleaned: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn shutdown(&mut self) {
|
||||
if self.cleaned {
|
||||
return;
|
||||
}
|
||||
self.cleaned = true;
|
||||
for helper in self.helpers.iter_mut().rev() {
|
||||
helper.terminate();
|
||||
}
|
||||
self.helpers.clear();
|
||||
for path in self.cleanup_files.drain(..) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
stop_wineserver(&self.prefix);
|
||||
if let Ok(path) = frame_path() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SessionResources {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
/// Start everything and block until the client exits.
|
||||
pub fn start() -> Result<()> {
|
||||
let _session_lock = acquire_session_lock()?;
|
||||
rotate_session_log();
|
||||
let config = Config::load()?;
|
||||
let prefix = data_dir()?.join("wine");
|
||||
let install_dir = crate::wine::find_client_dir(&prefix)
|
||||
.context("client not provisioned; run `uur setup` first")?;
|
||||
deploy_hooks(&prefix)?;
|
||||
crate::wine::set_dll_override(&prefix, "wtsapi32", "native")?;
|
||||
// Re-apply migrations on every launch so an updated uur package repairs
|
||||
// an existing prefix without requiring destructive reprovisioning.
|
||||
crate::wine::apply_registry_compat(&prefix)?;
|
||||
if let Some(proxy) = crate::proxy::sync(&prefix)? {
|
||||
println!("WinINet proxy synchronized: {proxy}");
|
||||
}
|
||||
let audio = crate::audio::sync_wine(&prefix)?;
|
||||
println!("{}", t!("session.audio_backend", backend = audio.label()));
|
||||
|
||||
// Bridge configuration as a file inside the prefix: any process the
|
||||
// Wine service manager respawns reads it, env or not.
|
||||
let frames = frame_path()?;
|
||||
let backend_status = crate::config::runtime_dir()?.join("backend");
|
||||
let _ = std::fs::remove_file(&backend_status);
|
||||
std::env::set_var("UUR_FRAME_PATH", &frames);
|
||||
std::env::set_var("UUR_BACKEND_STATUS", &backend_status);
|
||||
std::fs::write(
|
||||
prefix.join("drive_c/uur-bridge.ini"),
|
||||
format!(
|
||||
"[bridge]\nport={}\ntoken={}\nframe_path={}\n",
|
||||
config.bridge_port,
|
||||
config.bridge_token,
|
||||
unix_path_to_wine(&frames)
|
||||
),
|
||||
)
|
||||
.context("writing uur-bridge.ini")?;
|
||||
|
||||
let terminal_config = deploy_terminal_proxy(&install_dir)?;
|
||||
let launch_proxy = hook_source_dir()?.join("uur-launch-proxy.exe");
|
||||
let application_count = crate::launcher::prepare(&prefix, &launch_proxy)?;
|
||||
println!(
|
||||
"{}",
|
||||
t!("session.quick_launch_ready", count = application_count)
|
||||
);
|
||||
// Keep the start-menu entry pointing at the full session even if the
|
||||
// installer or an update regenerated it meanwhile.
|
||||
let _ = crate::wine::adopt_shortcut(
|
||||
&prefix,
|
||||
&std::env::current_exe().unwrap_or_else(|_| PathBuf::from("uur")),
|
||||
);
|
||||
ensure_webview2(&prefix, &install_dir)?;
|
||||
|
||||
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())?;
|
||||
signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?;
|
||||
|
||||
let log = open_session_log()?;
|
||||
let mut resources = SessionResources::new(prefix.clone());
|
||||
let _ = std::fs::remove_file(&terminal_config);
|
||||
std::env::set_var("UUR_TERMINAL_CONFIG", &terminal_config);
|
||||
resources.cleanup_files.push(terminal_config.clone());
|
||||
resources
|
||||
.helpers
|
||||
.push(ManagedChild::spawn_internal("__terminal", &log)?);
|
||||
wait_for_runtime_file(&terminal_config, &stopping)?;
|
||||
let launcher_config = crate::launcher::runtime_config(&prefix);
|
||||
let _ = std::fs::remove_file(&launcher_config);
|
||||
resources.cleanup_files.push(launcher_config.clone());
|
||||
resources
|
||||
.helpers
|
||||
.push(ManagedChild::spawn_internal("__launcher", &log)?);
|
||||
wait_for_runtime_file(&launcher_config, &stopping)?;
|
||||
resources
|
||||
.helpers
|
||||
.push(ManagedChild::spawn_internal("__wallpaper", &log)?);
|
||||
match ManagedChild::spawn_internal("__inhibit", &log) {
|
||||
Ok(helper) => resources.helpers.push(helper),
|
||||
Err(error) => eprintln!("desktop inhibition unavailable: {error}"),
|
||||
}
|
||||
resources
|
||||
.helpers
|
||||
.push(ManagedChild::spawn_internal("__bridge", &log)?);
|
||||
wait_for_bridge(config.bridge_port, &stopping)?;
|
||||
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" {
|
||||
resources
|
||||
.helpers
|
||||
.push(ManagedChild::spawn_internal("__capture", &log)?);
|
||||
}
|
||||
|
||||
// The service enumerates processes for a winlogon session token source
|
||||
// before it initialises; under plain Wine none exists. A sleeping
|
||||
// process with that name satisfies the check.
|
||||
let marker = hook_dir()?.join("winlogon.exe");
|
||||
let _ = Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
|
||||
.env("UUR_HOOK_LOG", log_path()?)
|
||||
.env("UUR_BRIDGE_PORT", config.bridge_port.to_string())
|
||||
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.stderr(Stdio::from(log.try_clone()?))
|
||||
.arg(marker.to_string_lossy().as_ref())
|
||||
.spawn();
|
||||
|
||||
// The launcher talks to the service through the Windows Service Control
|
||||
// Manager, so the service must be started through `sc start` — a
|
||||
// directly spawned --service process is invisible to it and the UI
|
||||
// waits forever.
|
||||
if !service_running(&prefix) {
|
||||
let _ = Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.stderr(Stdio::from(log.try_clone()?))
|
||||
.args(["sc", "start", "GameViewerService"])
|
||||
.status();
|
||||
}
|
||||
for _ in 0..150 {
|
||||
if service_running(&prefix) {
|
||||
break;
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(200));
|
||||
}
|
||||
|
||||
println!("{}", t!("session.launching_client"));
|
||||
let ui = install_dir.join("GameViewer.exe");
|
||||
let launch = || -> Result<Child> {
|
||||
Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.current_dir(&install_dir)
|
||||
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
|
||||
.env("UUR_HOOK_LOG", log_path().unwrap_or_default())
|
||||
.env("UUR_BRIDGE_PORT", config.bridge_port.to_string())
|
||||
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone())
|
||||
.stdout(Stdio::from(log.try_clone()?))
|
||||
.stderr(Stdio::from(log.try_clone()?))
|
||||
.arg(ui.to_string_lossy().as_ref())
|
||||
.spawn()
|
||||
.context("launching the managed client")
|
||||
};
|
||||
|
||||
// Start the client detached: it IS the session's lifetime anchor.
|
||||
let mut client = launch()?;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(45);
|
||||
let mut seen_client = false;
|
||||
let mut missing_checks = 0u8;
|
||||
let mut relaunches = 0;
|
||||
while !stopping.load(Ordering::Relaxed) {
|
||||
let running = wine_client_process_exists(&prefix);
|
||||
if running {
|
||||
seen_client = true;
|
||||
missing_checks = 0;
|
||||
} else if seen_client {
|
||||
missing_checks = missing_checks.saturating_add(1);
|
||||
// UU hands off between short-lived launchers and its real Qt
|
||||
// process. Require a sustained absence before treating it as a
|
||||
// user-requested exit.
|
||||
if missing_checks >= 6 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !seen_client && std::time::Instant::now() >= deadline {
|
||||
anyhow::bail!("UU Remote did not create its client process within 45 seconds");
|
||||
}
|
||||
if !seen_client && client.try_wait()?.is_some() && relaunches < 2 {
|
||||
relaunches += 1;
|
||||
thread::sleep(std::time::Duration::from_secs(2));
|
||||
client = launch()?;
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(500));
|
||||
}
|
||||
|
||||
println!("{}", t!("session.client_exited", code = 0));
|
||||
|
||||
resources.shutdown();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Query the Windows process table belonging to this exact Wine prefix.
|
||||
/// Modern Wine may host a Windows process in a Linux process whose `/proc`
|
||||
/// cmdline names another image, so Linux process-name matching is not a valid
|
||||
/// lifecycle boundary.
|
||||
fn wine_client_process_exists(prefix: &Path) -> bool {
|
||||
let output = run_with_timeout(
|
||||
Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.args([
|
||||
"tasklist",
|
||||
"/NH",
|
||||
"/FO",
|
||||
"CSV",
|
||||
"/FI",
|
||||
"IMAGENAME eq GameViewer.exe",
|
||||
]),
|
||||
std::time::Duration::from_secs(5),
|
||||
);
|
||||
output.is_some_and(|text| tasklist_contains_image(&text, "GameViewer.exe"))
|
||||
}
|
||||
|
||||
/// Run a command with a hard timeout, returning its stdout (None on
|
||||
/// timeout or failure). `wine sc query` has been observed to hang
|
||||
/// indefinitely against a freshly booted wineserver; without a deadline
|
||||
/// the whole session startup would block forever.
|
||||
fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Option<String> {
|
||||
use std::process::Stdio;
|
||||
|
||||
let mut child = command
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) => {
|
||||
if std::time::Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Err(_) => return None,
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
let mut stdout = String::new();
|
||||
if let Some(mut pipe) = child.stdout.take() {
|
||||
let _ = pipe.read_to_string(&mut stdout);
|
||||
}
|
||||
Some(stdout)
|
||||
}
|
||||
|
||||
/// True when the Windows service reports STATE 4 (RUNNING) via `sc query`.
|
||||
fn service_running(prefix: &Path) -> bool {
|
||||
let output = run_with_timeout(
|
||||
Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.args(["sc", "query", "GameViewerService"]),
|
||||
std::time::Duration::from_secs(10),
|
||||
);
|
||||
match output {
|
||||
Some(text) => text.lines().any(|line| {
|
||||
let line = line.trim();
|
||||
line.starts_with("STATE") && line.contains("RUNNING")
|
||||
}),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn tasklist_contains_image(output: &str, image: &str) -> bool {
|
||||
output.lines().any(|line| {
|
||||
line.split(',')
|
||||
.next()
|
||||
.map(|field| field.trim().trim_matches('"').eq_ignore_ascii_case(image))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
|
||||
fn log_path() -> Result<PathBuf> {
|
||||
Ok(data_dir()?.join("hook.log"))
|
||||
}
|
||||
|
||||
/// End the session: stop the capture helper, terminate the managed prefix's
|
||||
/// Wine processes, and drop the bridge connection.
|
||||
pub fn stop() -> Result<()> {
|
||||
let prefix = data_dir()?.join("wine");
|
||||
if let Some((pid, start)) = read_session_identity()? {
|
||||
if process_start_time(pid).ok() == Some(start) {
|
||||
unsafe {
|
||||
libc::kill(pid as i32, libc::SIGTERM);
|
||||
}
|
||||
for _ in 0..100 {
|
||||
if process_start_time(pid).is_err() {
|
||||
println!("{}", t!("bridge.stop_requested"));
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
}
|
||||
stop_wineserver(&prefix);
|
||||
if let Ok(path) = frame_path() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
println!("{}", t!("bridge.stop_requested"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn state_dir() -> PathBuf {
|
||||
std::env::var("XDG_STATE_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|_| std::env::var("HOME").map(|home| PathBuf::from(home).join(".local/state")))
|
||||
.unwrap_or_else(|_| PathBuf::from("/tmp"))
|
||||
.join("uur")
|
||||
}
|
||||
|
||||
fn open_session_log() -> Result<std::fs::File> {
|
||||
let dir = state_dir();
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(dir.join("session.log"))
|
||||
.context("opening session log")
|
||||
}
|
||||
|
||||
fn read_session_identity() -> Result<Option<(u32, u64)>> {
|
||||
let path = state_dir().join("session.lock");
|
||||
let Ok(contents) = std::fs::read_to_string(path) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut fields = contents.split_whitespace();
|
||||
let Some(pid) = fields.next().and_then(|value| value.parse().ok()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(start) = fields.next().and_then(|value| value.parse().ok()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some((pid, start)))
|
||||
}
|
||||
|
||||
fn process_start_time(pid: u32) -> Result<u64> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat"))?;
|
||||
let end = stat.rfind(") ").context("malformed /proc stat")?;
|
||||
stat[end + 2..]
|
||||
.split_whitespace()
|
||||
.nth(19)
|
||||
.context("missing process start time")?
|
||||
.parse()
|
||||
.context("invalid process start time")
|
||||
}
|
||||
|
||||
fn frame_path() -> Result<PathBuf> {
|
||||
Ok(crate::config::runtime_dir()?.join("frames.v1"))
|
||||
}
|
||||
|
||||
fn unix_path_to_wine(path: &Path) -> String {
|
||||
format!("Z:{}", path.display()).replace('/', "\\")
|
||||
}
|
||||
|
||||
fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> 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.
|
||||
for _ in 0..6000 {
|
||||
if stopping.load(Ordering::Relaxed) {
|
||||
anyhow::bail!("session startup cancelled");
|
||||
}
|
||||
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
anyhow::bail!("input bridge did not become ready")
|
||||
}
|
||||
|
||||
fn wait_for_runtime_file(path: &Path, stopping: &AtomicBool) -> Result<()> {
|
||||
for _ in 0..250 {
|
||||
if stopping.load(Ordering::Relaxed) {
|
||||
anyhow::bail!("session startup cancelled");
|
||||
}
|
||||
if std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0) {
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
anyhow::bail!("native terminal bridge did not become ready")
|
||||
}
|
||||
|
||||
fn stop_wineserver(prefix: &Path) {
|
||||
let _ = Command::new("wineserver")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.arg("-k")
|
||||
.status();
|
||||
}
|
||||
|
||||
fn wine_debug() -> String {
|
||||
std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tasklist_parser_matches_the_exact_image() {
|
||||
let output = "\"GameViewer.exe\",\"456\",\"Console\",\"1\"\n\
|
||||
\"GameViewerServer.exe\",\"464\",\"Console\",\"1\"\n";
|
||||
assert!(tasklist_contains_image(output, "GameViewer.exe"));
|
||||
assert!(!tasklist_contains_image(output, "GameViewerService.exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_process_identity_is_readable() {
|
||||
assert!(process_start_time(std::process::id()).unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_path_converts_to_a_wine_z_path() {
|
||||
assert_eq!(
|
||||
unix_path_to_wine(Path::new("/run/user/1000/uur/frames.v1")),
|
||||
r"Z:\run\user\1000\uur\frames.v1"
|
||||
);
|
||||
}
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
//! Native PTY service for UU Remote's terminal feature.
|
||||
//!
|
||||
//! The Windows compatibility proxy keeps UU's existing ConPTY-facing stdio
|
||||
//! contract. This service authenticates that proxy and attaches it to the
|
||||
//! current Linux user's login shell through a real pseudoterminal.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||
use std::os::fd::{AsRawFd, FromRawFd};
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAGIC: u32 = 0x5555_5242;
|
||||
const VERSION: u16 = 1;
|
||||
const TOKEN_BYTES: usize = 64;
|
||||
const MAX_FRAME: usize = 64 * 1024;
|
||||
const MAX_SESSIONS: usize = 4;
|
||||
const ACCEPTED: u8 = 0x06;
|
||||
const FRAME_DATA: u8 = 1;
|
||||
const FRAME_RESIZE: u8 = 2;
|
||||
const FRAME_EOF: u8 = 3;
|
||||
|
||||
#[link(name = "util")]
|
||||
unsafe extern "C" {
|
||||
fn openpty(
|
||||
master: *mut libc::c_int,
|
||||
slave: *mut libc::c_int,
|
||||
name: *mut libc::c_char,
|
||||
termios: *const libc::termios,
|
||||
winsize: *const libc::winsize,
|
||||
) -> libc::c_int;
|
||||
}
|
||||
|
||||
pub fn serve() -> Result<()> {
|
||||
let config_path = std::env::var_os("UUR_TERMINAL_CONFIG")
|
||||
.map(PathBuf::from)
|
||||
.context("UUR_TERMINAL_CONFIG is not set")?;
|
||||
let token = random_token()?;
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).context("binding terminal bridge")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
write_runtime_config(&config_path, port, &token)?;
|
||||
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
for connection in listener.incoming() {
|
||||
let Ok(stream) = connection else {
|
||||
continue;
|
||||
};
|
||||
if active.fetch_add(1, Ordering::AcqRel) >= MAX_SESSIONS {
|
||||
active.fetch_sub(1, Ordering::AcqRel);
|
||||
continue;
|
||||
}
|
||||
let token = token.clone();
|
||||
let active = active.clone();
|
||||
thread::spawn(move || {
|
||||
let _guard = SessionCount(active);
|
||||
if let Err(error) = handle_connection(stream, &token) {
|
||||
eprintln!("terminal adapter connection failed: {error:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct SessionCount(Arc<AtomicUsize>);
|
||||
|
||||
impl Drop for SessionCount {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_connection(mut stream: TcpStream, expected_token: &str) -> Result<()> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
let mut hello = [0u8; 12];
|
||||
stream.read_exact(&mut hello)?;
|
||||
if u32::from_be_bytes(hello[0..4].try_into().unwrap()) != MAGIC
|
||||
|| u16::from_be_bytes(hello[4..6].try_into().unwrap()) != VERSION
|
||||
|| u16::from_be_bytes(hello[6..8].try_into().unwrap()) as usize != TOKEN_BYTES
|
||||
{
|
||||
anyhow::bail!("invalid terminal handshake");
|
||||
}
|
||||
let columns = u16::from_be_bytes(hello[8..10].try_into().unwrap()).clamp(20, 1000);
|
||||
let rows = u16::from_be_bytes(hello[10..12].try_into().unwrap()).clamp(5, 500);
|
||||
let mut supplied = [0u8; TOKEN_BYTES];
|
||||
stream.read_exact(&mut supplied)?;
|
||||
if !constant_time_equal(&supplied, expected_token.as_bytes()) {
|
||||
anyhow::bail!("terminal authentication failed");
|
||||
}
|
||||
stream.write_all(&[ACCEPTED])?;
|
||||
stream.set_read_timeout(Some(Duration::from_millis(500)))?;
|
||||
|
||||
let (mut master, mut child) = spawn_shell(columns, rows)?;
|
||||
let mut output = master.try_clone()?;
|
||||
let mut output_socket = stream.try_clone()?;
|
||||
let output_thread = thread::spawn(move || {
|
||||
let mut buffer = [0u8; 16 * 1024];
|
||||
while let Ok(count) = output.read(&mut buffer) {
|
||||
if count == 0 || output_socket.write_all(&buffer[..count]).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = output_socket.shutdown(Shutdown::Write);
|
||||
});
|
||||
|
||||
loop {
|
||||
let mut header = [0u8; 8];
|
||||
match stream.read_exact(&mut header) {
|
||||
Ok(()) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
if child.try_wait()?.is_some() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
let frame_type = header[0];
|
||||
let length = u32::from_be_bytes(header[4..8].try_into().unwrap()) as usize;
|
||||
if length > MAX_FRAME {
|
||||
anyhow::bail!("terminal frame exceeds limit");
|
||||
}
|
||||
let mut payload = vec![0u8; length];
|
||||
stream.read_exact(&mut payload)?;
|
||||
match frame_type {
|
||||
FRAME_DATA => master.write_all(&payload)?,
|
||||
FRAME_RESIZE if payload.len() == 4 => {
|
||||
let columns = u16::from_be_bytes(payload[0..2].try_into().unwrap());
|
||||
let rows = u16::from_be_bytes(payload[2..4].try_into().unwrap());
|
||||
resize_pty(&master, columns, rows)?;
|
||||
}
|
||||
FRAME_EOF => break,
|
||||
_ => anyhow::bail!("invalid terminal frame"),
|
||||
}
|
||||
}
|
||||
|
||||
unsafe {
|
||||
libc::kill(child.id() as i32, libc::SIGHUP);
|
||||
}
|
||||
let _ = child.wait();
|
||||
drop(master);
|
||||
let _ = output_thread.join();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_shell(columns: u16, rows: u16) -> Result<(File, std::process::Child)> {
|
||||
let size = libc::winsize {
|
||||
ws_row: rows,
|
||||
ws_col: columns,
|
||||
ws_xpixel: 0,
|
||||
ws_ypixel: 0,
|
||||
};
|
||||
let mut master_fd = -1;
|
||||
let mut slave_fd = -1;
|
||||
let result = unsafe {
|
||||
openpty(
|
||||
&mut master_fd,
|
||||
&mut slave_fd,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null(),
|
||||
&size,
|
||||
)
|
||||
};
|
||||
if result != 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("openpty");
|
||||
}
|
||||
|
||||
let master = unsafe { File::from_raw_fd(master_fd) };
|
||||
let slave = unsafe { File::from_raw_fd(slave_fd) };
|
||||
let shell = std::env::var("SHELL")
|
||||
.ok()
|
||||
.filter(|path| Path::new(path).is_absolute() && Path::new(path).is_file())
|
||||
.or_else(|| {
|
||||
option_env!("UUR_BUILD_SHELL")
|
||||
.filter(|path| Path::new(path).is_file())
|
||||
.map(ToOwned::to_owned)
|
||||
})
|
||||
.unwrap_or_else(|| "bash".to_string());
|
||||
let mut command = Command::new(shell);
|
||||
command
|
||||
.arg("-l")
|
||||
.env("TERM", "xterm-256color")
|
||||
.stdin(Stdio::from(slave.try_clone()?))
|
||||
.stdout(Stdio::from(slave.try_clone()?))
|
||||
.stderr(Stdio::from(slave.try_clone()?));
|
||||
if let Some(home) = std::env::var_os("HOME").filter(|path| Path::new(path).is_absolute()) {
|
||||
command.current_dir(home);
|
||||
}
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if libc::setsid() < 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
if libc::ioctl(0, libc::TIOCSCTTY, 0) < 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let child = command.spawn().context("starting login shell")?;
|
||||
drop(slave);
|
||||
Ok((master, child))
|
||||
}
|
||||
|
||||
fn resize_pty(master: &File, columns: u16, rows: u16) -> Result<()> {
|
||||
let size = libc::winsize {
|
||||
ws_row: rows.clamp(5, 500),
|
||||
ws_col: columns.clamp(20, 1000),
|
||||
ws_xpixel: 0,
|
||||
ws_ypixel: 0,
|
||||
};
|
||||
let result = unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCSWINSZ, &size) };
|
||||
if result < 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("resizing PTY");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_runtime_config(path: &Path, port: u16, token: &str) -> Result<()> {
|
||||
let parent = path.parent().context("terminal config has no parent")?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let temporary = path.with_extension(format!("tmp.{}", std::process::id()));
|
||||
let mut file = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(&temporary)?;
|
||||
writeln!(file, "version=1")?;
|
||||
writeln!(file, "port={port}")?;
|
||||
writeln!(file, "token={token}")?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(temporary, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn random_token() -> Result<String> {
|
||||
let mut random = [0u8; 32];
|
||||
File::open("/dev/urandom")?.read_exact(&mut random)?;
|
||||
Ok(random.iter().map(|byte| format!("{byte:02x}")).collect())
|
||||
}
|
||||
|
||||
fn constant_time_equal(left: &[u8], right: &[u8]) -> bool {
|
||||
if left.len() != right.len() {
|
||||
return false;
|
||||
}
|
||||
let mut difference = 0u8;
|
||||
for (left, right) in left.iter().zip(right) {
|
||||
difference |= left ^ right;
|
||||
}
|
||||
difference == 0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn token_shape_and_comparison() {
|
||||
let token = random_token().unwrap();
|
||||
assert_eq!(token.len(), TOKEN_BYTES);
|
||||
assert!(token.bytes().all(|byte| byte.is_ascii_hexdigit()));
|
||||
assert!(constant_time_equal(token.as_bytes(), token.as_bytes()));
|
||||
assert!(!constant_time_equal(token.as_bytes(), &[b'0'; TOKEN_BYTES]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pty_starts_a_real_shell() {
|
||||
let (mut pty, mut child) = spawn_shell(80, 24).unwrap();
|
||||
pty.write_all(b"printf UUR_PTY_OK\\n\nexit\n").unwrap();
|
||||
let mut output = Vec::new();
|
||||
pty.read_to_end(&mut output).ok();
|
||||
let _ = child.wait();
|
||||
assert!(String::from_utf8_lossy(&output).contains("UUR_PTY_OK"));
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::process::Command;
|
||||
|
||||
const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd";
|
||||
|
||||
/// The latest official release filename, e.g. `uuyc_4.38.3.exe`, resolved
|
||||
/// from the same feed the official client uses. `uur` never mirrors the
|
||||
/// binary; it only learns what upstream shipped.
|
||||
fn latest_filename() -> Result<String> {
|
||||
// Follow redirects and stop at the headers: the feed answers with a
|
||||
// Location carrying the signed CDN path whose final component names the
|
||||
// installer version.
|
||||
let output = Command::new("curl")
|
||||
.args([
|
||||
"-fsIL",
|
||||
"--max-time",
|
||||
"20",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{url_effective}",
|
||||
OFFICIAL_DOWNLOAD_URL,
|
||||
])
|
||||
.output()
|
||||
.context("running curl")?;
|
||||
if !output.status.success() {
|
||||
anyhow::bail!("{}", t!("upstream.unreachable"));
|
||||
}
|
||||
let url = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
let filename = url
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.split('?')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if filename.is_empty() {
|
||||
anyhow::bail!("{}", t!("upstream.unparsable", url = url));
|
||||
}
|
||||
Ok(filename)
|
||||
}
|
||||
|
||||
fn extract_version(filename: &str) -> Option<String> {
|
||||
let stem = filename.trim_end_matches(".exe");
|
||||
let bytes = stem.as_bytes();
|
||||
let mut start = None;
|
||||
let mut end = 0usize;
|
||||
let mut in_run = false;
|
||||
let mut run_start = 0usize;
|
||||
for (index, byte) in bytes.iter().enumerate() {
|
||||
let is_part = byte.is_ascii_digit() || *byte == b'.';
|
||||
if is_part && !in_run {
|
||||
in_run = true;
|
||||
run_start = index;
|
||||
} else if !is_part && in_run {
|
||||
in_run = false;
|
||||
if stem[run_start..index].contains('.') {
|
||||
start = Some(run_start);
|
||||
end = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if in_run && start.is_none() && stem[run_start..].contains('.') {
|
||||
return Some(stem[run_start..].to_string());
|
||||
}
|
||||
start.map(|s| stem[s..end].to_string())
|
||||
}
|
||||
|
||||
fn installed_version() -> Option<String> {
|
||||
let prefix = crate::config::data_dir().ok()?.join("wine");
|
||||
crate::wine::find_client_dir(&prefix)?;
|
||||
let output = Command::new("wine")
|
||||
.env("WINEPREFIX", &prefix)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.args([
|
||||
"reg",
|
||||
"query",
|
||||
r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\GameViewer",
|
||||
"/v",
|
||||
"DisplayVersion",
|
||||
])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.find(|line| line.contains("DisplayVersion") && line.contains("REG_SZ"))
|
||||
.and_then(|line| line.split("REG_SZ").nth(1))
|
||||
.map(str::trim)
|
||||
.filter(|version| !version.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub fn check() -> Result<()> {
|
||||
let filename = latest_filename()?;
|
||||
// Filenames observed upstream: `uuyc_4.33.0.exe`,
|
||||
// `UURemote_Setup_4.39.1.1375_<build>_gwqd.exe`. Take the first
|
||||
// dotted-numeric run as the version.
|
||||
let upstream =
|
||||
extract_version(&filename).with_context(|| format!("no version in {}", filename))?;
|
||||
|
||||
println!(
|
||||
"{}",
|
||||
t!("upstream.latest", version = upstream, filename = filename)
|
||||
);
|
||||
match installed_version() {
|
||||
Some(local) if local == upstream => println!("{}", t!("upstream.up_to_date")),
|
||||
Some(local) => println!(
|
||||
"{}",
|
||||
t!(
|
||||
"upstream.newer_available",
|
||||
local = local,
|
||||
upstream = upstream
|
||||
)
|
||||
),
|
||||
None => println!("{}", t!("upstream.not_provisioned")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
//! Native video acceleration capability inventory.
|
||||
//!
|
||||
//! This module reports host APIs independently from UU's Windows encoder.
|
||||
//! It is the selection boundary for future native frame encoders and decoders.
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Capabilities {
|
||||
pub render_node: bool,
|
||||
pub va_api: bool,
|
||||
pub vulkan: bool,
|
||||
pub vulkan_video: bool,
|
||||
pub nvenc: bool,
|
||||
pub nvdec: bool,
|
||||
}
|
||||
|
||||
pub fn detect() -> Capabilities {
|
||||
let vulkan = command_output("vulkaninfo", &[]);
|
||||
Capabilities {
|
||||
render_node: render_node_present(),
|
||||
va_api: command_succeeds("vainfo", &["--display", "drm"]),
|
||||
vulkan: vulkan.is_some(),
|
||||
vulkan_video: vulkan
|
||||
.as_deref()
|
||||
.is_some_and(|text| text.contains("VK_KHR_video_queue")),
|
||||
nvenc: library_present("libnvidia-encode.so"),
|
||||
nvdec: library_present("libnvcuvid.so"),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_output(program: &str, arguments: &[&str]) -> Option<String> {
|
||||
let output = Command::new(program)
|
||||
.args(arguments)
|
||||
.env("DISPLAY", std::env::var("DISPLAY").unwrap_or_default())
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
output
|
||||
.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
}
|
||||
|
||||
pub fn describe<'a>(value: bool, available: &'a str, unavailable: &'a str) -> &'a str {
|
||||
if value {
|
||||
available
|
||||
} else {
|
||||
unavailable
|
||||
}
|
||||
}
|
||||
|
||||
fn render_node_present() -> bool {
|
||||
std::fs::read_dir("/dev/dri")
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.any(|entry| entry.file_name().to_string_lossy().starts_with("renderD"))
|
||||
}
|
||||
|
||||
fn command_succeeds(program: &str, arguments: &[&str]) -> bool {
|
||||
Command::new(program)
|
||||
.args(arguments)
|
||||
.env("DISPLAY", std::env::var("DISPLAY").unwrap_or_default())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|status| status.success())
|
||||
}
|
||||
|
||||
fn library_present(needle: &str) -> bool {
|
||||
let cache = Command::new("ldconfig")
|
||||
.arg("-p")
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.ok()
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
.unwrap_or_default();
|
||||
if cache.contains(needle) {
|
||||
return true;
|
||||
}
|
||||
["/usr/lib", "/usr/local/lib", "/lib"]
|
||||
.iter()
|
||||
.any(|directory| {
|
||||
std::fs::read_dir(directory)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.any(|entry| entry.file_name().to_string_lossy().starts_with(needle))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::describe;
|
||||
|
||||
#[test]
|
||||
fn capability_description_selects_the_correct_branch() {
|
||||
assert_eq!(describe(true, "available", "missing"), "available");
|
||||
assert_eq!(describe(false, "available", "missing"), "missing");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Desktop-neutral wallpaper discovery and Wine registry synchronization.
|
||||
//!
|
||||
//! UU reads the standard Windows `Control Panel\\Desktop\\Wallpaper` value.
|
||||
//! Providers below discover the active Linux wallpaper without making the
|
||||
//! session supervisor depend on a particular desktop environment.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::cmp::Ordering;
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Wallpaper {
|
||||
pub path: PathBuf,
|
||||
pub provider: &'static str,
|
||||
}
|
||||
|
||||
pub fn detect() -> Option<Wallpaper> {
|
||||
if let Some(value) = std::env::var_os("UUR_WALLPAPER") {
|
||||
if let Some(path) = resolve_candidate(PathBuf::from(value)) {
|
||||
return Some(Wallpaper {
|
||||
path,
|
||||
provider: "environment",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = detect_runtime_provider() {
|
||||
return Some(Wallpaper {
|
||||
path,
|
||||
provider: "wallpaper daemon",
|
||||
});
|
||||
}
|
||||
|
||||
let desktop = std::env::var("XDG_CURRENT_DESKTOP")
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let mut providers: Vec<fn() -> Option<Wallpaper>> = Vec::new();
|
||||
if desktop.contains("kde") || desktop.contains("plasma") {
|
||||
providers.push(detect_kde);
|
||||
}
|
||||
if desktop.contains("gnome")
|
||||
|| desktop.contains("unity")
|
||||
|| desktop.contains("budgie")
|
||||
|| desktop.contains("pantheon")
|
||||
{
|
||||
providers.push(detect_gnome_family);
|
||||
}
|
||||
if desktop.contains("cinnamon") {
|
||||
providers.push(detect_cinnamon);
|
||||
}
|
||||
if desktop.contains("mate") {
|
||||
providers.push(detect_mate);
|
||||
}
|
||||
if desktop.contains("xfce") {
|
||||
providers.push(detect_xfce);
|
||||
}
|
||||
if desktop.contains("lxqt") || desktop.contains("lxde") {
|
||||
providers.push(detect_pcmanfm);
|
||||
}
|
||||
|
||||
for fallback in [
|
||||
detect_kde as fn() -> Option<Wallpaper>,
|
||||
detect_gnome_family,
|
||||
detect_cinnamon,
|
||||
detect_mate,
|
||||
detect_xfce,
|
||||
detect_pcmanfm,
|
||||
detect_nitrogen,
|
||||
detect_feh,
|
||||
] {
|
||||
if !providers
|
||||
.iter()
|
||||
.any(|provider| std::ptr::fn_addr_eq(*provider, fallback))
|
||||
{
|
||||
providers.push(fallback);
|
||||
}
|
||||
}
|
||||
providers.into_iter().find_map(|provider| provider())
|
||||
}
|
||||
|
||||
pub fn sync(prefix: &Path) -> Result<Option<Wallpaper>> {
|
||||
let Some(wallpaper) = detect() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let compatible = windows_compatible_path(&wallpaper.path)?;
|
||||
let windows_path = format!("Z:{}", compatible.display()).replace('/', "\\");
|
||||
let status = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.args([
|
||||
"reg",
|
||||
"add",
|
||||
r"HKCU\Control Panel\Desktop",
|
||||
"/v",
|
||||
"Wallpaper",
|
||||
"/t",
|
||||
"REG_SZ",
|
||||
"/d",
|
||||
&windows_path,
|
||||
"/f",
|
||||
])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.context("updating Wine wallpaper registry value")?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("Wine rejected the wallpaper registry update");
|
||||
}
|
||||
Ok(Some(wallpaper))
|
||||
}
|
||||
|
||||
pub fn serve() -> Result<()> {
|
||||
let prefix = crate::config::data_dir()?.join("wine");
|
||||
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())?;
|
||||
signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?;
|
||||
|
||||
let mut previous: Option<(PathBuf, Option<SystemTime>)> = None;
|
||||
while !stopping.load(AtomicOrdering::Relaxed) {
|
||||
if let Some(current) = detect() {
|
||||
let modified = current
|
||||
.path
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|metadata| metadata.modified().ok());
|
||||
let fingerprint = (current.path.clone(), modified);
|
||||
if previous.as_ref() != Some(&fingerprint) {
|
||||
if let Err(error) = sync(&prefix) {
|
||||
eprintln!("wallpaper synchronization failed: {error:#}");
|
||||
} else {
|
||||
println!(
|
||||
"wallpaper synchronized via {}: {}",
|
||||
current.provider,
|
||||
current.path.display()
|
||||
);
|
||||
previous = Some(fingerprint);
|
||||
}
|
||||
}
|
||||
}
|
||||
for _ in 0..20 {
|
||||
if stopping.load(AtomicOrdering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn detect_kde() -> Option<Wallpaper> {
|
||||
let content =
|
||||
std::fs::read_to_string(config_home().join("plasma-org.kde.plasma.desktop-appletsrc"))
|
||||
.ok()?;
|
||||
let value = content
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("Image="))?;
|
||||
wallpaper_from_value(value, "KDE Plasma")
|
||||
}
|
||||
|
||||
fn detect_gnome_family() -> Option<Wallpaper> {
|
||||
let dark = command_value(
|
||||
"gsettings",
|
||||
&["get", "org.gnome.desktop.background", "picture-uri-dark"],
|
||||
);
|
||||
let regular = command_value(
|
||||
"gsettings",
|
||||
&["get", "org.gnome.desktop.background", "picture-uri"],
|
||||
);
|
||||
dark.or(regular)
|
||||
.and_then(|value| wallpaper_from_value(&value, "GNOME settings"))
|
||||
}
|
||||
|
||||
fn detect_cinnamon() -> Option<Wallpaper> {
|
||||
command_value(
|
||||
"gsettings",
|
||||
&["get", "org.cinnamon.desktop.background", "picture-uri"],
|
||||
)
|
||||
.and_then(|value| wallpaper_from_value(&value, "Cinnamon settings"))
|
||||
}
|
||||
|
||||
fn detect_mate() -> Option<Wallpaper> {
|
||||
command_value(
|
||||
"gsettings",
|
||||
&["get", "org.mate.background", "picture-filename"],
|
||||
)
|
||||
.and_then(|value| wallpaper_from_value(&value, "MATE settings"))
|
||||
}
|
||||
|
||||
fn detect_xfce() -> Option<Wallpaper> {
|
||||
let output = command_value("xfconf-query", &["-c", "xfce4-desktop", "-l", "-v"])?;
|
||||
output
|
||||
.lines()
|
||||
.filter(|line| line.contains("last-image"))
|
||||
.filter_map(|line| line.split_whitespace().last())
|
||||
.find_map(|value| wallpaper_from_value(value, "Xfce settings"))
|
||||
}
|
||||
|
||||
fn detect_pcmanfm() -> Option<Wallpaper> {
|
||||
for relative in [
|
||||
"pcmanfm-qt/lxqt/settings.conf",
|
||||
"pcmanfm/LXDE/desktop-items-0.conf",
|
||||
"pcmanfm/default/desktop-items-0.conf",
|
||||
] {
|
||||
let Ok(content) = std::fs::read_to_string(config_home().join(relative)) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(value) = content.lines().find_map(|line| {
|
||||
line.strip_prefix("Wallpaper=")
|
||||
.or_else(|| line.strip_prefix("wallpaper="))
|
||||
}) {
|
||||
if let Some(found) = wallpaper_from_value(value, "PCManFM settings") {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn detect_nitrogen() -> Option<Wallpaper> {
|
||||
let content = std::fs::read_to_string(config_home().join("nitrogen/bg-saved.cfg")).ok()?;
|
||||
let value = content
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("file="))?;
|
||||
wallpaper_from_value(value, "Nitrogen settings")
|
||||
}
|
||||
|
||||
fn detect_feh() -> Option<Wallpaper> {
|
||||
let content = std::fs::read_to_string(home_dir().join(".fehbg")).ok()?;
|
||||
content
|
||||
.split(['\'', '"'])
|
||||
.find_map(|part| wallpaper_from_value(part, "feh configuration"))
|
||||
}
|
||||
|
||||
fn detect_runtime_provider() -> Option<PathBuf> {
|
||||
for (command, arguments) in [
|
||||
("swww", &["query"][..]),
|
||||
("hyprctl", &["hyprpaper", "listactive"][..]),
|
||||
] {
|
||||
if let Some(output) = command_value(command, arguments) {
|
||||
if let Some(path) = output.lines().find_map(path_from_runtime_line) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for entry in std::fs::read_dir("/proc").ok()? {
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
if !entry
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(entry.path().join("cmdline")) else {
|
||||
continue;
|
||||
};
|
||||
let arguments: Vec<_> = bytes
|
||||
.split(|byte| *byte == 0)
|
||||
.filter(|part| !part.is_empty())
|
||||
.map(|part| String::from_utf8_lossy(part).into_owned())
|
||||
.collect();
|
||||
let executable = arguments
|
||||
.first()
|
||||
.and_then(|path| Path::new(path).file_name())
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or_default();
|
||||
let candidate = match executable {
|
||||
"swaybg" => argument_after(&arguments, "-i"),
|
||||
"xwallpaper" => arguments.last().cloned(),
|
||||
"mpvpaper" => arguments.last().cloned(),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(path) = candidate.and_then(|value| resolve_candidate(PathBuf::from(value))) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn path_from_runtime_line(line: &str) -> Option<PathBuf> {
|
||||
let value = line
|
||||
.split_once("image:")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| line.rsplit_once(" = ").map(|(_, value)| value))?;
|
||||
resolve_candidate(PathBuf::from(value.trim()))
|
||||
}
|
||||
|
||||
fn argument_after(arguments: &[String], option: &str) -> Option<String> {
|
||||
arguments
|
||||
.windows(2)
|
||||
.find(|pair| pair[0] == option)
|
||||
.map(|pair| pair[1].clone())
|
||||
}
|
||||
|
||||
fn wallpaper_from_value(value: &str, provider: &'static str) -> Option<Wallpaper> {
|
||||
let value = value.trim().trim_matches(['\'', '"']);
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let decoded = value
|
||||
.strip_prefix("file://")
|
||||
.map(percent_decode)
|
||||
.unwrap_or_else(|| value.to_string());
|
||||
resolve_candidate(PathBuf::from(decoded)).map(|path| Wallpaper { path, provider })
|
||||
}
|
||||
|
||||
fn resolve_candidate(path: PathBuf) -> Option<PathBuf> {
|
||||
let path = path.canonicalize().ok()?;
|
||||
if path.is_file() {
|
||||
return Some(path);
|
||||
}
|
||||
if !path.is_dir() {
|
||||
return None;
|
||||
}
|
||||
best_image_in_directory(&path, 4)
|
||||
}
|
||||
|
||||
fn best_image_in_directory(root: &Path, depth: usize) -> Option<PathBuf> {
|
||||
let mut files = Vec::new();
|
||||
collect_images(root, depth, &mut files);
|
||||
let target_ratio = display_ratio().unwrap_or(16.0 / 9.0);
|
||||
files.into_iter().max_by(|left, right| {
|
||||
image_score(left, target_ratio)
|
||||
.partial_cmp(&image_score(right, target_ratio))
|
||||
.unwrap_or(Ordering::Equal)
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_images(directory: &Path, depth: usize, output: &mut Vec<PathBuf>) {
|
||||
if depth == 0 {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_images(&path, depth - 1, output);
|
||||
} else if supported_image(&path) {
|
||||
output.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn supported_image(path: &Path) -> bool {
|
||||
matches!(
|
||||
path.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase()
|
||||
.as_str(),
|
||||
"jpg" | "jpeg" | "png" | "bmp" | "webp" | "jxl"
|
||||
)
|
||||
}
|
||||
|
||||
fn image_score(path: &Path, target_ratio: f64) -> f64 {
|
||||
let dimensions = path
|
||||
.file_stem()
|
||||
.and_then(OsStr::to_str)
|
||||
.and_then(parse_dimensions);
|
||||
if let Some((width, height)) = dimensions {
|
||||
let ratio_error = (width as f64 / height as f64 - target_ratio).abs();
|
||||
return 1_000_000_000.0 - ratio_error * 100_000_000.0
|
||||
+ (width as f64 * height as f64).sqrt();
|
||||
}
|
||||
path.metadata()
|
||||
.map(|metadata| metadata.len() as f64)
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn parse_dimensions(value: &str) -> Option<(u32, u32)> {
|
||||
let (width, height) = value.split_once('x')?;
|
||||
Some((width.parse().ok()?, height.parse().ok()?))
|
||||
}
|
||||
|
||||
fn display_ratio() -> Option<f64> {
|
||||
let output = command_value("xrandr", &["--current"])?;
|
||||
let current = output.split("current ").nth(1)?;
|
||||
let mut words = current.split_whitespace();
|
||||
let width: f64 = words.next()?.parse().ok()?;
|
||||
if words.next()? != "x" {
|
||||
return None;
|
||||
}
|
||||
let height: f64 = words.next()?.trim_end_matches(',').parse().ok()?;
|
||||
(height > 0.0).then_some(width / height)
|
||||
}
|
||||
|
||||
fn command_value(program: &str, arguments: &[&str]) -> Option<String> {
|
||||
let mut child = Command::new(program)
|
||||
.args(arguments)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(2);
|
||||
let status = loop {
|
||||
match child.try_wait().ok()? {
|
||||
Some(status) => break status,
|
||||
None if std::time::Instant::now() < deadline => {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
None => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
};
|
||||
if !status.success() {
|
||||
return None;
|
||||
}
|
||||
let mut output = String::new();
|
||||
child.stdout.take()?.read_to_string(&mut output).ok()?;
|
||||
let output = output.trim().to_string();
|
||||
(!output.is_empty()).then_some(output)
|
||||
}
|
||||
|
||||
fn windows_compatible_path(source: &Path) -> Result<PathBuf> {
|
||||
let metadata = source
|
||||
.metadata()
|
||||
.with_context(|| format!("reading wallpaper metadata for {}", source.display()))?;
|
||||
let extension = source
|
||||
.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
if matches!(extension.as_str(), "jpg" | "jpeg" | "png" | "bmp")
|
||||
&& metadata.len() <= 5 * 1024 * 1024
|
||||
{
|
||||
return Ok(source.to_path_buf());
|
||||
}
|
||||
|
||||
let modified = metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(SystemTime::UNIX_EPOCH).ok())
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or(0);
|
||||
let cache = crate::config::data_dir()?.join("wallpaper-cache");
|
||||
std::fs::create_dir_all(&cache)?;
|
||||
let stem = format!("wallpaper-{}-{modified}", metadata.len());
|
||||
let jpeg = cache.join(format!("{stem}.jpg"));
|
||||
if jpeg.is_file() {
|
||||
return Ok(jpeg);
|
||||
}
|
||||
|
||||
let temporary_jpeg = cache.join(format!("{stem}.tmp.jpg"));
|
||||
let converted = Command::new("magick")
|
||||
.arg(source)
|
||||
.args([
|
||||
"-auto-orient",
|
||||
"-resize",
|
||||
"3840x2160>",
|
||||
"-strip",
|
||||
"-quality",
|
||||
"88",
|
||||
])
|
||||
.arg(&temporary_jpeg)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|status| status.success() && temporary_jpeg.is_file());
|
||||
if converted {
|
||||
std::fs::rename(&temporary_jpeg, &jpeg)?;
|
||||
remove_old_cache_files(&cache, &jpeg);
|
||||
return Ok(jpeg);
|
||||
}
|
||||
let _ = std::fs::remove_file(&temporary_jpeg);
|
||||
|
||||
let png = cache.join(format!("{stem}.png"));
|
||||
let temporary_png = cache.join(format!("{stem}.tmp.png"));
|
||||
let input_uri = format!("file://{}", source.display());
|
||||
let converted = Command::new("glycin-thumbnailer")
|
||||
.args(["--input", &input_uri, "--size", "3840", "--output"])
|
||||
.arg(&temporary_png)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|status| status.success() && temporary_png.is_file());
|
||||
if converted {
|
||||
std::fs::rename(&temporary_png, &png)?;
|
||||
remove_old_cache_files(&cache, &png);
|
||||
return Ok(png);
|
||||
}
|
||||
let _ = std::fs::remove_file(&temporary_png);
|
||||
|
||||
// UU may support the source codec through its own image stack. Returning
|
||||
// the original is more useful than suppressing wallpaper publication.
|
||||
Ok(source.to_path_buf())
|
||||
}
|
||||
|
||||
fn remove_old_cache_files(directory: &Path, keep: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path != keep
|
||||
&& path
|
||||
.file_name()
|
||||
.and_then(OsStr::to_str)
|
||||
.is_some_and(|name| name.starts_with("wallpaper-"))
|
||||
{
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode(value: &str) -> String {
|
||||
let bytes = value.as_bytes();
|
||||
let mut decoded = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
if bytes[index] == b'%' && index + 2 < bytes.len() {
|
||||
if let Ok(byte) = u8::from_str_radix(&value[index + 1..index + 3], 16) {
|
||||
decoded.push(byte);
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
decoded.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&decoded).into_owned()
|
||||
}
|
||||
|
||||
fn config_home() -> PathBuf {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| home_dir().join(".config"))
|
||||
}
|
||||
|
||||
fn home_dir() -> PathBuf {
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{parse_dimensions, percent_decode};
|
||||
|
||||
#[test]
|
||||
fn file_uri_percent_encoding_is_decoded() {
|
||||
assert_eq!(
|
||||
percent_decode("/Pictures/My%20Wallpaper%23one.png"),
|
||||
"/Pictures/My Wallpaper#one.png"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_image_dimensions_are_recognized() {
|
||||
assert_eq!(parse_dimensions("5120x2880"), Some((5120, 2880)));
|
||||
assert_eq!(parse_dimensions("wallpaper"), None);
|
||||
}
|
||||
}
|
||||
+409
@@ -0,0 +1,409 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
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";
|
||||
|
||||
/// 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<()> {
|
||||
let mut config = Config::load()?;
|
||||
|
||||
if !config.eula_accepted {
|
||||
if !accept_eula {
|
||||
println!("{}", t!("setup.eula_prompt", url = EULA_URL));
|
||||
anyhow::bail!("{}", t!("setup.eula_required"));
|
||||
}
|
||||
config.eula_accepted = true;
|
||||
config.store()?;
|
||||
println!("{}", t!("setup.eula_recorded"));
|
||||
}
|
||||
|
||||
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")?;
|
||||
|
||||
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);
|
||||
println!("{}", t!("setup.already_provisioned"));
|
||||
stop_wineserver(&prefix);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{}", t!("setup.downloading", url = OFFICIAL_DOWNLOAD_URL));
|
||||
let installer = cache.join("uu-remote-setup.exe");
|
||||
let status = Command::new("curl")
|
||||
.args([
|
||||
"-fL",
|
||||
"--retry",
|
||||
"3",
|
||||
"--progress-bar",
|
||||
"-o",
|
||||
installer.to_string_lossy().as_ref(),
|
||||
OFFICIAL_DOWNLOAD_URL,
|
||||
])
|
||||
.status()
|
||||
.context("running curl")?;
|
||||
if !status.success() {
|
||||
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())
|
||||
.arg(installer.to_string_lossy().as_ref())
|
||||
.arg("/S")
|
||||
.status()
|
||||
.context("launching installer")?;
|
||||
if !status.success() {
|
||||
println!("{}", t!("setup.silent_install_unavailable"));
|
||||
}
|
||||
|
||||
// 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)?;
|
||||
let uur_bin = std::env::current_exe().unwrap_or_default();
|
||||
let _ = adopt_shortcut(&prefix, &uur_bin);
|
||||
purge_wine_shortcuts();
|
||||
|
||||
println!("{}", t!("setup.done", path = prefix.display().to_string()));
|
||||
stop_wineserver(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Registry compatibility profile, ported from the field-tested reference
|
||||
/// implementation:
|
||||
///
|
||||
/// - msedgewebview2.exe runs under Wine only with a win8 app-compat
|
||||
/// override — without it the WebView2 process never spawns;
|
||||
/// - GameViewerServer.exe sees Windows 10 because current UU terminal builds
|
||||
/// gate their ConPTY transport on the OS version. Native input and display
|
||||
/// adapters handle the hardware capabilities separately;
|
||||
/// - the service must auto-start;
|
||||
/// - X11 focus/XIM tuning and CJK font substitution keep the controller
|
||||
/// usable.
|
||||
type RegistryEntry = (String, Vec<(&'static str, &'static str, &'static str)>);
|
||||
|
||||
pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
|
||||
let entries: Vec<RegistryEntry> = vec![
|
||||
(
|
||||
r#"Software\Wine\AppDefaults\msedgewebview2.exe"#.to_string(),
|
||||
vec![("Version", "REG_SZ", "win8")],
|
||||
),
|
||||
(
|
||||
r#"Software\Wine\AppDefaults\GameViewerServer.exe"#.to_string(),
|
||||
vec![("Version", "REG_SZ", "win10")],
|
||||
),
|
||||
(
|
||||
r"System\CurrentControlSet\Services\GameViewerService".to_string(),
|
||||
vec![("Start", "REG_DWORD", "2")],
|
||||
),
|
||||
(
|
||||
r"Software\Wine\X11 Driver".to_string(),
|
||||
vec![("UseTakeFocus", "REG_SZ", "N")],
|
||||
),
|
||||
(
|
||||
r"Software\Wine\AppDefaults\gameviewer.exe\X11 Driver".to_string(),
|
||||
vec![("UseXIM", "REG_SZ", "N"), ("UseTakeFocus", "REG_SZ", "Y")],
|
||||
),
|
||||
(
|
||||
r"Software\Microsoft\Windows NT\CurrentVersion\FontSubstitutes".to_string(),
|
||||
vec![
|
||||
("MS Shell Dlg", "REG_SZ", "Noto Sans CJK SC"),
|
||||
("MS Shell Dlg 2", "REG_SZ", "Noto Sans CJK SC"),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
for (key, values) in &entries {
|
||||
let full = if key.starts_with("System") {
|
||||
format!("HKLM\\{key}")
|
||||
} else {
|
||||
format!("HKCU\\{key}")
|
||||
};
|
||||
for (value, reg_type, data) in values {
|
||||
let _ = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.args([
|
||||
"reg", "add", &full, "/v", value, "/t", reg_type, "/d", data, "/f",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.with_context(|| format!("reg add {full} /v {value}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
|
||||
let status = Command::new("wine")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDEBUG", wine_debug())
|
||||
.args([
|
||||
"reg",
|
||||
"add",
|
||||
r"HKCU\Software\Wine\DllOverrides",
|
||||
"/v",
|
||||
name,
|
||||
"/t",
|
||||
"REG_SZ",
|
||||
"/d",
|
||||
mode,
|
||||
"/f",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.with_context(|| format!("registering {name} dll override"))?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("Wine rejected the {name} DLL override");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wine_debug() -> String {
|
||||
std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string())
|
||||
}
|
||||
|
||||
fn stop_wineserver(prefix: &Path) {
|
||||
let _ = Command::new("wineserver")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.arg("-k")
|
||||
.status();
|
||||
}
|
||||
|
||||
/// Locate the installed client directory regardless of how NetEase spells
|
||||
/// the vendor folder ("Netease", "NetEase", ...). Case matters on Linux.
|
||||
pub fn find_client_dir(prefix: &Path) -> Option<PathBuf> {
|
||||
let program_files = prefix.join("drive_c").join("Program Files");
|
||||
let entries = std::fs::read_dir(&program_files).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
if name.to_string_lossy().eq_ignore_ascii_case("netease") {
|
||||
let vendor = entry.path();
|
||||
if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) {
|
||||
let bin = found.parent()?;
|
||||
if bin
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("bin"))
|
||||
{
|
||||
return bin.parent().map(Path::to_path_buf);
|
||||
}
|
||||
return Some(bin.to_path_buf());
|
||||
}
|
||||
return Some(vendor);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option<PathBuf> {
|
||||
if depth == 0 {
|
||||
return None;
|
||||
}
|
||||
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) {
|
||||
return Some(path);
|
||||
}
|
||||
if path.is_dir() {
|
||||
if let Some(found) = find_dir_recursive(&path, needle, depth - 1) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Preserve an existing Wine-generated launcher as a hidden compatibility
|
||||
/// alias. Previously pinned desktop icons keep working, but the packaged
|
||||
/// `uur.desktop` remains the one visible menu entry.
|
||||
pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> {
|
||||
use std::fs;
|
||||
|
||||
let mut name = None;
|
||||
let users = prefix.join("drive_c/users");
|
||||
if let Ok(entries) = fs::read_dir(&users) {
|
||||
'outer: for user in entries.flatten() {
|
||||
let programs = user
|
||||
.path()
|
||||
.join("AppData/Roaming/Microsoft/Windows/Start Menu/Programs");
|
||||
let Ok(items) = fs::read_dir(&programs) else {
|
||||
continue;
|
||||
};
|
||||
for item in items.flatten() {
|
||||
let file_name = item.file_name().to_string_lossy().into_owned();
|
||||
if file_name.ends_with(".lnk") && shortcut_targets_gameviewer(&item.path()) {
|
||||
name = Some(file_name.trim_end_matches(".lnk").to_string());
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(name) = name else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
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 mut best = 0u32;
|
||||
if let Ok(sizes) = fs::read_dir(icons.join("hicolor")) {
|
||||
for size in sizes.flatten() {
|
||||
let size_name = size.file_name().to_string_lossy().into_owned();
|
||||
let Ok(width) = size_name.split('x').next().unwrap_or("").parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(apps) = fs::read_dir(size.path().join("apps")) else {
|
||||
continue;
|
||||
};
|
||||
for app in apps.flatten() {
|
||||
let file_name = app.file_name().to_string_lossy().into_owned();
|
||||
if file_name.contains("GameViewer") && width > best {
|
||||
best = width;
|
||||
icon_name = file_name
|
||||
.trim_end_matches(".png")
|
||||
.trim_end_matches(".0")
|
||||
.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let applications = std::env::var("HOME")
|
||||
.map(|h| PathBuf::from(h).join(".local/share/applications"))
|
||||
.context("no home")?;
|
||||
std::fs::create_dir_all(&applications)?;
|
||||
let entry = applications.join(format!("{name}.desktop"));
|
||||
let exec = uur_bin.display();
|
||||
let icon_line = if icon_name.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("Icon={icon_name}\n")
|
||||
};
|
||||
std::fs::write(
|
||||
&entry,
|
||||
format!(
|
||||
"[Desktop Entry]\n\
|
||||
Type=Application\n\
|
||||
Name={name}\n\
|
||||
Comment=UU Remote for Linux (uur)\n\
|
||||
Exec={exec} run\n\
|
||||
TryExec={exec}\n\
|
||||
{icon_line}Terminal=false\n\
|
||||
NoDisplay=true\n\
|
||||
X-UUR-Managed=true\n\
|
||||
Categories=Network;RemoteAccess;\n"
|
||||
),
|
||||
)
|
||||
.with_context(|| format!("writing {}", entry.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = fs::set_permissions(&entry, fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn shortcut_targets_gameviewer(path: &Path) -> bool {
|
||||
let Ok(bytes) = std::fs::read(path) else {
|
||||
return false;
|
||||
};
|
||||
let searchable: String = bytes
|
||||
.into_iter()
|
||||
.filter(|byte| *byte != 0)
|
||||
.map(|byte| byte as char)
|
||||
.collect::<String>()
|
||||
.to_ascii_lowercase();
|
||||
searchable.contains("gameviewer")
|
||||
}
|
||||
|
||||
/// Remove Wine-generated desktop copies of the client. The start-menu
|
||||
/// entry is ours and correct; only Desktop copies are swept.
|
||||
fn purge_wine_shortcuts() {
|
||||
let home = match std::env::var("HOME") {
|
||||
Ok(home) => PathBuf::from(home),
|
||||
Err(_) => return,
|
||||
};
|
||||
let matches = |name: &str| {
|
||||
let lower = name.to_lowercase();
|
||||
lower.contains("uuremote") || lower.contains("gameviewer") || lower.contains("uu remote")
|
||||
};
|
||||
let dir = home.join("Desktop");
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if matches(&name) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
//! Host Wake-on-LAN configuration without a desktop- or distro-specific policy.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct State {
|
||||
pub interface: String,
|
||||
pub mac: String,
|
||||
pub supported: Option<bool>,
|
||||
pub enabled: Option<bool>,
|
||||
pub connection: Option<String>,
|
||||
}
|
||||
|
||||
pub fn status(requested: Option<&str>) -> Result<()> {
|
||||
let state = inspect(requested)?;
|
||||
println!("{}", t!("wol.interface", interface = state.interface));
|
||||
println!("{}", t!("wol.mac", mac = state.mac));
|
||||
println!(
|
||||
"{}",
|
||||
t!("wol.magic_support", state = tri_state(state.supported))
|
||||
);
|
||||
println!(
|
||||
"{}",
|
||||
t!("wol.magic_enabled", state = tri_state(state.enabled))
|
||||
);
|
||||
println!(
|
||||
"{}",
|
||||
t!(
|
||||
"wol.connection",
|
||||
connection = state.connection.as_deref().unwrap_or("-")
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn configure(requested: Option<&str>, enabled: bool) -> Result<()> {
|
||||
let before = inspect(requested)?;
|
||||
if enabled && before.supported == Some(false) {
|
||||
anyhow::bail!("{}", t!("wol.unsupported", interface = before.interface));
|
||||
}
|
||||
|
||||
if let Some(connection) = &before.connection {
|
||||
let value = if enabled { "magic" } else { "0" };
|
||||
checked(
|
||||
Command::new("nmcli")
|
||||
.args([
|
||||
"connection",
|
||||
"modify",
|
||||
connection,
|
||||
"802-3-ethernet.wake-on-lan",
|
||||
value,
|
||||
])
|
||||
.stdin(Stdio::null()),
|
||||
"updating the NetworkManager Wake-on-LAN profile",
|
||||
)?;
|
||||
}
|
||||
|
||||
let mode = if enabled { "g" } else { "d" };
|
||||
checked(
|
||||
Command::new("ethtool")
|
||||
.args(["-s", &before.interface, "wol", mode])
|
||||
.stdin(Stdio::null()),
|
||||
&format!(
|
||||
"setting Wake-on-LAN on {} (run this command as root or through an authorized Polkit session)",
|
||||
before.interface
|
||||
),
|
||||
)?;
|
||||
|
||||
let after = inspect(Some(&before.interface))?;
|
||||
if after.enabled != Some(enabled) {
|
||||
anyhow::bail!("{}", t!("wol.verify_failed", interface = before.interface));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
if enabled {
|
||||
t!("wol.enabled", interface = before.interface)
|
||||
} else {
|
||||
t!("wol.disabled", interface = before.interface)
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn inspect(requested: Option<&str>) -> Result<State> {
|
||||
let interface = select_interface(requested)?;
|
||||
let base = Path::new("/sys/class/net").join(&interface);
|
||||
let mac = std::fs::read_to_string(base.join("address"))
|
||||
.unwrap_or_else(|_| "unknown".into())
|
||||
.trim()
|
||||
.to_string();
|
||||
let properties = Command::new("ethtool")
|
||||
.arg(&interface)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned());
|
||||
let supported = properties
|
||||
.as_deref()
|
||||
.and_then(|text| property(text, "Supports Wake-on:").map(|value| value.contains('g')));
|
||||
let enabled = properties
|
||||
.as_deref()
|
||||
.and_then(|text| property(text, "Wake-on:").map(|value| value.contains('g')));
|
||||
Ok(State {
|
||||
interface: interface.clone(),
|
||||
mac,
|
||||
supported,
|
||||
enabled,
|
||||
connection: active_connection(&interface),
|
||||
})
|
||||
}
|
||||
|
||||
fn select_interface(requested: Option<&str>) -> Result<String> {
|
||||
if let Some(interface) = requested {
|
||||
validate_interface(interface)?;
|
||||
return Ok(interface.to_string());
|
||||
}
|
||||
if let Some(interface) = default_route_interface().filter(|name| is_wired_physical(name)) {
|
||||
return Ok(interface);
|
||||
}
|
||||
let mut candidates = std::fs::read_dir("/sys/class/net")
|
||||
.context("enumerating network interfaces")?
|
||||
.flatten()
|
||||
.filter_map(|entry| entry.file_name().into_string().ok())
|
||||
.filter(|name| is_wired_physical(name))
|
||||
.collect::<Vec<_>>();
|
||||
candidates.sort();
|
||||
candidates
|
||||
.into_iter()
|
||||
.next()
|
||||
.context("no physical wired network interface found")
|
||||
}
|
||||
|
||||
fn validate_interface(interface: &str) -> Result<()> {
|
||||
if interface.is_empty()
|
||||
|| !interface
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':'))
|
||||
|| !is_wired_physical(interface)
|
||||
{
|
||||
anyhow::bail!("invalid or non-wired physical interface: {interface}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_wired_physical(interface: &str) -> bool {
|
||||
let base = PathBuf::from("/sys/class/net").join(interface);
|
||||
base.join("device").exists() && !base.join("wireless").exists()
|
||||
}
|
||||
|
||||
fn default_route_interface() -> Option<String> {
|
||||
let output = Command::new("ip")
|
||||
.args(["-o", "route", "show", "default"])
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let fields = text.split_whitespace().collect::<Vec<_>>();
|
||||
let index = fields.iter().position(|field| *field == "dev")?;
|
||||
fields.get(index + 1).map(|value| value.to_string())
|
||||
}
|
||||
|
||||
fn active_connection(interface: &str) -> Option<String> {
|
||||
let output = Command::new("nmcli")
|
||||
.args(["-g", "GENERAL.CONNECTION", "device", "show", interface])
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(!value.is_empty() && value != "--").then_some(value)
|
||||
}
|
||||
|
||||
fn property<'a>(text: &'a str, name: &str) -> Option<&'a str> {
|
||||
text.lines()
|
||||
.map(str::trim)
|
||||
.find_map(|line| line.strip_prefix(name).map(str::trim))
|
||||
}
|
||||
|
||||
fn checked(command: &mut Command, context: &str) -> Result<()> {
|
||||
let output = command.output().with_context(|| context.to_string())?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let detail = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
anyhow::bail!("{context}: {detail}")
|
||||
}
|
||||
|
||||
fn tri_state(value: Option<bool>) -> String {
|
||||
match value {
|
||||
Some(true) => t!("wol.yes").to_string(),
|
||||
Some(false) => t!("wol.no").to_string(),
|
||||
None => t!("wol.unknown_ethtool").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::property;
|
||||
|
||||
#[test]
|
||||
fn parses_ethtool_wake_properties_without_confusing_them() {
|
||||
let sample = "Supports Wake-on: pumbg\nWake-on: g\n";
|
||||
assert_eq!(property(sample, "Supports Wake-on:"), Some("pumbg"));
|
||||
assert_eq!(property(sample, "Wake-on:"), Some("g"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user