dbus session support

This commit is contained in:
galister committed 2026-11-08 16:44:09 +09:00
1 parent 90fb181689
commit 2ee1d80ae5
16 files changed
+879 -65

No files matched your search

@@ -22,7 +22,7 @@ export LDAI_UPDATE_INFORMATION="gh-releases-zsync|wayvr-org|wayvr|latest|WayVR-*
echo "Packaging AppImage for ${APPIMAGE_ARCH}"
# linuxdeploy doesn't like multiple -d's being passed
install -Dm 0644 wayvr-headless.desktop "${APPDIR}/usr/share/applications/wayvr-headless.desktop"
install -Dm 0644 wayvr-session.desktop "${APPDIR}/usr/share/applications/wayvr-headless.desktop"
"./${LINUXDEPLOY}" \
-dwayvr.desktop \
+1
View File
@@ -38,4 +38,5 @@ pub struct RunParams {
pub wgui_globals: WguiGlobals,
pub config: GeneralConfig,
pub no_audio: bool,
pub session: bool,
}
+10 -4
View File
@@ -19,7 +19,10 @@ use std::{
},
path::{Path, PathBuf},
rc::Rc,
sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError},
sync::{
Arc,
mpsc::{self, Receiver, Sender, SyncSender, TryRecvError},
},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
@@ -88,14 +91,14 @@ pub struct InputCapture {
}
impl InputCapture {
pub fn new() -> io::Result<Self> {
pub fn new(dbus_session_address: Option<Arc<str>>) -> io::Result<Self> {
let (command_tx, command_rx) = mpsc::sync_channel(8);
let (event_tx, event_rx) = mpsc::channel();
let (init_tx, init_rx) = mpsc::sync_channel(1);
let worker = thread::Builder::new()
.name("wayvr-input-capture".into())
.spawn(move || worker_main(command_rx, event_tx, init_tx))?;
.spawn(move || worker_main(command_rx, event_tx, init_tx, dbus_session_address))?;
match init_rx.recv() {
Ok(Ok(())) => Ok(Self {
@@ -328,6 +331,7 @@ fn worker_main(
command_rx: Receiver<Command>,
event_tx: Sender<CapturedEvent>,
init_tx: SyncSender<io::Result<()>>,
dbus_session_address: Option<Arc<str>>,
) {
let restricted_state = Rc::new(RefCell::new(RestrictedState::default()));
let interface = RestrictedInterface {
@@ -346,6 +350,8 @@ fn worker_main(
log::debug!("input capture worker started");
let dbus = dbus_session_address.map_or_default(|s| DbusConnector::new(s));
let mut grabbed = false;
let mut pending_grab = false;
let mut watchdog = Instant::now() + WATCHDOG_TIMEOUT;
@@ -517,7 +523,7 @@ fn worker_main(
}
Err(error) => {
//TODO: we can't easily translate it at this stage, i18n lies on a separate thread
let _ = DbusConnector::notify_send(
let _ = dbus.notify_send(
"WayVR",
&format!(
"Could not capture input! Linux user must be in 'input' group!\n Error: \n{error}"
+10 -3
View File
@@ -169,6 +169,7 @@ pub struct WvrServerState {
pub manager: client::WayVRCompositor,
pub wm: window::WindowManager,
pub processes: DenseSlotMap<process::ProcessHandle, process::Process>,
pub dbus_address: Option<Arc<str>>,
pub tasks: SyncEventQueue<WayVRTask>,
ticks: u64,
cur_modifiers: u8,
@@ -357,6 +358,7 @@ impl WvrServerState {
Ok(Self {
manager: client::WayVRCompositor::new(state, display, seat_keyboard, seat_pointer)?,
processes: Default::default(),
dbus_address: None,
wm: window::WindowManager::new(),
ticks: 0,
tasks,
@@ -991,6 +993,7 @@ impl WvrServerState {
&mut app.audio,
&app.wgui_globals,
&app.session.config,
&app.dbus,
);
wvr_server.ticks += 1;
@@ -1180,6 +1183,7 @@ impl WvrServerState {
audio: &mut Box<dyn audio::AudioProvider>,
globals: &WguiGlobals,
config: &GeneralConfig,
dbus: &DbusConnector,
) {
let input_capture = match (self.input_capture.as_mut(), config.wvr_input_capture) {
(Some(cap), InputCaptureMethod::Evdev) => cap,
@@ -1188,7 +1192,7 @@ impl WvrServerState {
return;
}
(None, InputCaptureMethod::Evdev) if !self.input_capture_init_attempted => {
self.input_capture = InputCapture::new()
self.input_capture = InputCapture::new(dbus.address().cloned())
.log_err("Could not initialize evdev input capture")
.ok();
self.input_capture_init_attempted = true;
@@ -1198,7 +1202,7 @@ impl WvrServerState {
let text = &globals
.i18n()
.translate("NOTIFICATION.CANNOT_CAPTURE_KBD_MOUSE");
let _ = DbusConnector::notify_send("WayVR", text, 1, 5000, 0, true);
let _ = dbus.notify_send("WayVR", text, 1, 5000, 0, true);
return;
}
}
@@ -1330,7 +1334,7 @@ impl WvrServerState {
if !self.grab_toast_sent {
self.grab_toast_sent = true;
let text = &globals.i18n().translate("NOTIFICATION.WE_ARE_GRABBING");
let _ = DbusConnector::notify_send("WayVR", text, 1, 5000, 0, true);
let _ = dbus.notify_send("WayVR", text, 1, 5000, 0, true);
}
}
input_capture::CapturedEvent::Ungrabbed => {
@@ -1767,6 +1771,9 @@ impl WvrServerState {
// these go to env for flatpak as well
cmd.env("WAYLAND_DISPLAY", wayland_display);
cmd.env("DISPLAY", x11_display);
if let Some(address) = &self.dbus_address {
cmd.env("DBUS_SESSION_BUS_ADDRESS", address.as_ref());
}
if is_flatpak {
// need to inject --env after "run" because --env is a
+10 -5
View File
@@ -103,6 +103,10 @@ struct Args {
#[arg(long)]
headless: bool,
/// Start a XDG desktop session, for when you want WayVR to be your main desktop. Implies --headless.
#[arg(long)]
session: bool,
/// Do not auto-start registered apps
#[arg(long)]
no_autostart: bool,
@@ -122,7 +126,7 @@ fn load_config() -> GeneralConfig {
load_general_config()
}
fn init_run_params(no_audio: bool) -> backend::RunParams {
fn init_run_params(no_audio: bool, session: bool) -> backend::RunParams {
let assets = Box::new(gui::asset::GuiAsset {});
let config = load_config();
let lang_provider = WayVRLangProvider::from_config(&config);
@@ -141,6 +145,7 @@ fn init_run_params(no_audio: bool) -> backend::RunParams {
wgui_globals,
config,
no_audio,
session,
}
}
@@ -204,7 +209,7 @@ fn auto_run(args: &Args, out_backend: &mut Option<XrBackend>) {
if !args_get_openvr(args) {
use crate::backend::{BackendError, openxr::openxr_run};
tried_xr = true;
match openxr_run(args, init_run_params(args.no_audio)) {
match openxr_run(args, init_run_params(args.no_audio, args.session)) {
Ok(()) => {
out_backend.replace(XrBackend::OpenXR);
return;
@@ -222,7 +227,7 @@ fn auto_run(args: &Args, out_backend: &mut Option<XrBackend>) {
if !args_get_openxr(args) {
use crate::backend::{BackendError, openvr::openvr_run};
tried_vr = true;
match openvr_run(args, init_run_params(args.no_audio)) {
match openvr_run(args, init_run_params(args.no_audio, args.session)) {
Ok(()) => {
out_backend.replace(XrBackend::OpenVR);
return;
@@ -259,7 +264,7 @@ fn auto_run(args: &Args, out_backend: &mut Option<XrBackend>) {
_ => "NOTIFICATION.INVALID_ARGS",
};
let run_params = init_run_params(args.no_audio);
let run_params = init_run_params(args.no_audio, args.session);
let instructions_str = run_params.wgui_globals.i18n().translate(instructions_key);
@@ -270,7 +275,7 @@ fn auto_run(args: &Args, out_backend: &mut Option<XrBackend>) {
let instructions = format!("{instructions_title}\n{instructions_str}");
let _ = DbusConnector::notify_send("WayVR", &instructions, 1, 30000, 0, false);
let _ = DbusConnector::default().notify_send("WayVR", &instructions, 1, 30000, 0, false);
#[cfg(not(any(feature = "openvr", feature = "openxr")))]
compile_error!("No VR support! Enable either openvr or openxr features!");
+19 -20
View File
@@ -16,12 +16,9 @@ use crate::{
gui::panel::{GuiPanel, overlay_list::OverlayList, set_list::SetList},
overlays::keyboard::builder::create_keyboard_panel,
state::AppState,
subsystem::{
dbus::DbusConnector,
hid::{
ALT, ALTGR, CTRL, KeyModifier, SHIFT, SUPER, VirtualKey, WheelDelta, XkbKeymap,
get_keymap_wl, get_keymap_x11,
},
subsystem::hid::{
ALT, ALTGR, CTRL, KeyModifier, SHIFT, SUPER, VirtualKey, WheelDelta, XkbKeymap,
get_keymap_wl, get_keymap_x11,
},
windowing::{
backend::{FrameMeta, OverlayBackend, OverlayEventData, RenderResources, ShouldRender},
@@ -59,7 +56,13 @@ pub fn create_keyboard(app: &mut AppState) -> anyhow::Result<OverlayWindowConfig
let width = layout.row_size * 0.05 * app.session.config.keyboard_scale;
let mut maybe_keymap = KeyboardBackend::get_initial_keymap(app).ok();
let mut maybe_keymap = KeyboardBackend::get_initial_keymap(app).ok().or_else(|| {
app.session
.config
.keyboard_layouts
.first()
.and_then(|name| XkbKeymap::from_name(name.as_ref()).ok())
});
if let Some(keymap) = maybe_keymap.as_ref() {
app.hid_provider
@@ -90,7 +93,6 @@ pub fn create_keyboard(app: &mut AppState) -> anyhow::Result<OverlayWindowConfig
wlx_layout: layout,
wayland: app.feats.desktop_backend.is_wayland(),
re_fcitx: Regex::new(r"^keyboard-([^-]+)(?:-([^-]+))?$").unwrap(),
re_keymap: Regex::new(r"^([a-zA-Z][a-zA-Z0-9]*)(?:\(([^)]+)\))?$").unwrap(),
};
backend.active_layout = backend.add_new_keymap(maybe_keymap.as_ref(), app)?;
@@ -138,7 +140,6 @@ struct KeyboardBackend {
wlx_layout: layout::Layout,
wayland: bool,
re_fcitx: Regex,
re_keymap: Regex,
}
impl KeyboardBackend {
@@ -201,7 +202,7 @@ impl KeyboardBackend {
.state = state_from;
}
fn get_effective_keymap(&mut self) -> anyhow::Result<XkbKeymap> {
fn get_effective_keymap(&mut self, app: &AppState) -> anyhow::Result<XkbKeymap> {
fn get_system_keymap(wayland: bool) -> anyhow::Result<XkbKeymap> {
if wayland {
get_keymap_wl()
@@ -210,7 +211,9 @@ impl KeyboardBackend {
}
}
let Ok(fcitx_layout) = DbusConnector::fcitx_keymap()
let Ok(fcitx_layout) = app
.dbus
.fcitx_keymap()
.context("Could not keymap via fcitx5, falling back to wayland")
.inspect_err(|e| log::info!("{e:?}"))
else {
@@ -237,13 +240,7 @@ impl KeyboardBackend {
keymap_name: &str,
app: &mut AppState,
) -> anyhow::Result<bool> {
let Some(captures) = self.re_keymap.captures(keymap_name) else {
anyhow::bail!("invalid layout name for keymap switch: {keymap_name}");
};
let layout = captures.get(1).map_or("", |g| g.as_str());
let variant = captures.get(2).map_or("", |g| g.as_str());
let keymap = XkbKeymap::from_layout_variant(layout, variant)
.context("invalid layout/variant for keymap switch")?;
let keymap = XkbKeymap::from_name(keymap_name)?;
app.hid_provider
.keymap_changed(app.wvr_server.as_mut(), &keymap);
self.switch_keymap(&keymap, app)
@@ -258,7 +255,9 @@ impl KeyboardBackend {
}
}
let Ok(fcitx_layout) = DbusConnector::fcitx_keymap()
let Ok(fcitx_layout) = app
.dbus
.fcitx_keymap()
.context("Could not keymap via fcitx5, falling back to wayland")
.inspect_err(|e| log::info!("{e:?}"))
else {
@@ -282,7 +281,7 @@ impl KeyboardBackend {
}
fn auto_switch_keymap(&mut self, app: &mut AppState) -> anyhow::Result<bool> {
let keymap = self.get_effective_keymap()?;
let keymap = self.get_effective_keymap(app)?;
app.hid_provider
.keymap_changed(app.wvr_server.as_mut(), &keymap);
self.switch_keymap(&keymap, app)
+7 -5
View File
@@ -32,7 +32,6 @@ use crate::{
toast::Toast,
},
state::{AppState, save_pw_token_config},
subsystem::dbus::DbusConnector,
windowing::{
OverlaySelector,
backend::{DummyBackend, OverlayBackend},
@@ -322,7 +321,7 @@ fn check(mut par: CheckParams, finalize_fn: ScreenCastFinalizeFn) {
log::info!("{}: PipeWire node selected: {}", par.name, node_id);
if let Some(id) = par.notify_id.take() {
let _ = DbusConnector::notify_close(id);
let _ = par.app.dbus.notify_close(id);
}
let pw_tokens_copy = par.app.session.pw_tokens.clone();
@@ -370,8 +369,11 @@ fn check(mut par: CheckParams, finalize_fn: ScreenCastFinalizeFn) {
format!("{} {}", par.name, par.description).as_str(),
),
);
par.notify_id =
DbusConnector::notify_send("WayVR", &text, 1, 30000, 0, true).ok();
par.notify_id = par
.app
.dbus
.notify_send("WayVR", &text, 1, 30000, 0, true)
.ok();
}
1
} else {
@@ -412,7 +414,7 @@ fn check(mut par: CheckParams, finalize_fn: ScreenCastFinalizeFn) {
}
ScreenCastResult::Failed(ref e) => {
if let Some(id) = par.notify_id.take() {
let _ = DbusConnector::notify_close(id);
let _ = par.app.dbus.notify_close(id);
}
update_status_hack(&par.name, &par.description, &new_result, par.app);
+28 -4
View File
@@ -36,7 +36,10 @@ use crate::{
graphics::WGfxExtras,
ipc::{event_queue::SyncEventQueue, ipc_server, signal::WayVRSignal},
overlays::toast::{ToastQueue, toast_close, toast_tick},
subsystem::{dbus::DbusConnector, input::HidWrapper},
subsystem::{
dbus::{DbusConnector, session::XdgDesktopSession},
input::HidWrapper,
},
};
pub struct AppState {
@@ -77,6 +80,7 @@ pub struct AppState {
pub osc_sender: Option<OscSender>,
pub wvr_server: Option<WvrServerState>,
pub _desktop_session: Option<XdgDesktopSession>,
#[cfg(feature = "whisper")]
pub whisper_sst: Option<WhisperStt>,
@@ -104,7 +108,7 @@ impl AppState {
let session = AppSession::load(params.config);
let wvr_signals = SyncEventQueue::new();
let wvr_server = {
let mut wvr_server = {
let mut maybe_wvr = WvrServerState::new(gfx.clone(), &gfx_extras, &session.config)
.log_err("Could not initialize WayVR Server")
.ok();
@@ -114,6 +118,27 @@ impl AppState {
maybe_wvr
};
let dbus_session = if params.session
&& let Some(wvr) = &wvr_server
{
let wayland_display = wvr.manager.wayland_env.wayland_display_num_string();
let display = wvr.manager.wayland_env.display_num_string();
XdgDesktopSession::new(&wayland_display, &display)
.log_err("Could not initialize WayVR D-Bus session")
.ok()
.flatten()
} else {
None
};
let dbus = dbus_session
.as_ref()
.map_or_default(|session| DbusConnector::new(session.bus_address().clone()));
if let (Some(wvr), Some(dbus_session)) = (&mut wvr_server, &dbus_session) {
wvr.dbus_address = Some(dbus_session.bus_address().clone());
}
let (hid_provider, mut hid_error) = HidWrapper::new(session.config.input_emulation_method);
#[cfg(feature = "osc")]
@@ -175,8 +200,6 @@ impl AppState {
gradient_intensity: session.config.ui_gradient_intensity,
};
let dbus = DbusConnector::default();
let ipc_server = ipc_server::WayVRServer::new()?;
let mut desktop_finder = DesktopFinder::new(params.wgui_globals.i18n().get_locale());
@@ -223,6 +246,7 @@ impl AppState {
osc_sender,
wvr_server,
_desktop_session: dbus_session,
#[cfg(feature = "whisper")]
whisper_sst: None,
+30 -9
View File
@@ -1,4 +1,4 @@
use std::time::Duration;
use std::{sync::Arc, time::Duration};
use anyhow::Context;
use dbus::{
@@ -15,16 +15,36 @@ use crate::subsystem::dbus::{
mod fcitx5;
mod notifications;
pub mod session;
pub type DbusReceiveCallback = Box<dyn FnMut(Message, &Connection) -> bool + Send>;
pub type DbusMatchCallback = Box<dyn FnMut((), &Connection, &Message) -> bool + Send>;
#[derive(Default)]
pub struct DbusConnector {
pub connection: Option<Connection>,
connection: Option<Connection>,
session_address: Option<Arc<str>>,
}
impl DbusConnector {
pub fn new(session_address: Arc<str>) -> Self {
Self {
session_address: Some(session_address),
..Default::default()
}
}
pub const fn address(&self) -> Option<&Arc<str>> {
self.session_address.as_ref()
}
pub fn session_connection(&self) -> Result<Connection, dbus::Error> {
match self.session_address.as_ref() {
Some(address) => Connection::new_address(address),
None => Connection::new_session(),
}
}
pub fn tick(&self) {
if let Some(c) = self.connection.as_ref() {
let _ = c.process(Duration::ZERO);
@@ -40,7 +60,7 @@ impl DbusConnector {
.connection
.take()
.context("Not connected")
.or_else(|_| Connection::new_session())?;
.or_else(|_| self.session_connection())?;
let proxy = connection.with_proxy(
"org.freedesktop.DBus",
@@ -70,15 +90,15 @@ impl DbusConnector {
.connection
.take()
.context("Not connected")
.or_else(|_| Connection::new_session())?;
.or_else(|_| self.session_connection())?;
let _ = connection.add_match(rule, callback)?;
self.connection = Some(connection);
Ok(())
}
pub fn fcitx_keymap() -> anyhow::Result<String> {
let connection = Connection::new_session()?;
pub fn fcitx_keymap(&self) -> anyhow::Result<String> {
let connection = self.session_connection()?;
let proxy = connection.with_proxy(
"org.fcitx.Fcitx5",
"/controller",
@@ -91,6 +111,7 @@ impl DbusConnector {
}
pub fn notify_send(
&self,
summary: &str,
body: &str,
urgency: u8,
@@ -98,7 +119,7 @@ impl DbusConnector {
replaces_id: u32,
transient: bool,
) -> anyhow::Result<u32> {
let connection = Connection::new_session()?;
let connection = self.session_connection()?;
let proxy = connection.with_proxy(
"org.freedesktop.Notifications",
@@ -123,8 +144,8 @@ impl DbusConnector {
Ok(retval)
}
pub fn notify_close(id: u32) -> anyhow::Result<()> {
let connection = Connection::new_session()?;
pub fn notify_close(&self, id: u32) -> anyhow::Result<()> {
let connection = self.session_connection()?;
let proxy = connection.with_proxy(
"org.freedesktop.Notifications",
+725
View File
@@ -0,0 +1,725 @@
use std::{
collections::HashMap,
env,
ffi::{OsStr, OsString},
fs,
io::{BufRead, BufReader},
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
use anyhow::Context;
use dbus::blocking::Connection;
const ACTIVATION_VARS: &[&str] = &[
"DBUS_SESSION_BUS_ADDRESS",
"WAYLAND_DISPLAY",
"DISPLAY",
"XDG_CURRENT_DESKTOP",
"XDG_RUNTIME_DIR",
"XAUTHORITY",
"PATH",
"GDK_BACKEND",
"QT_QPA_PLATFORM",
];
const PORTAL_FRONTEND: Service = Service {
name: "xdg-desktop-portal",
bus_name: Some("org.freedesktop.portal.Desktop"),
units: &["xdg-desktop-portal.service"],
executables: &["xdg-desktop-portal"],
flatpak: None,
};
const PORTAL_GTK: Service = Service {
name: "xdg-desktop-portal-gtk",
bus_name: Some("org.freedesktop.impl.portal.desktop.gtk"),
units: &["xdg-desktop-portal-gtk.service"],
executables: &["xdg-desktop-portal-gtk"],
flatpak: None,
};
const PORTAL_KDE: Service = Service {
name: "xdg-desktop-portal-kde",
bus_name: Some("org.freedesktop.impl.portal.desktop.kde"),
units: &[
"xdg-desktop-portal-kde.service",
"plasma-xdg-desktop-portal-kde.service",
],
executables: &["xdg-desktop-portal-kde"],
flatpak: None,
};
const POLKIT_GNOME: Service = Service {
name: "polkit-gnome",
bus_name: None,
units: &[
"polkit-gnome-authentication-agent-1.service",
"polkit-gnome.service",
],
executables: &["polkit-gnome-authentication-agent-1"],
flatpak: None,
};
const POLKIT_KDE: Service = Service {
name: "polkit-kde",
bus_name: None,
units: &["plasma-polkit-agent.service", "polkit-kde-agent-1.service"],
executables: &["polkit-kde-authentication-agent-1"],
flatpak: None,
};
const FCITX5: Service = Service {
name: "fcitx5",
bus_name: None,
units: &[],
executables: &["fcitx5"],
flatpak: Some("org.fcitx.Fcitx5"),
};
struct Service {
name: &'static str,
bus_name: Option<&'static str>,
units: &'static [&'static str],
executables: &'static [&'static str],
flatpak: Option<&'static str>,
}
pub struct XdgDesktopSession {
bus_address: Arc<str>,
private_bus: Option<Child>,
worker: Option<JoinHandle<ServiceLauncher>>,
cancelled: Arc<AtomicBool>,
runtime_dir: Option<PathBuf>,
portal_config: Option<PathBuf>,
env: HashMap<String, OsString>,
saved_systemd_env: Option<HashMap<String, Option<String>>>,
saved_activation_env: Option<HashMap<String, Option<OsString>>>,
systemd: bool,
}
struct ServiceLauncher {
bus_address: Arc<str>,
children: Vec<Child>,
units: Vec<&'static str>,
env: HashMap<String, OsString>,
systemd: bool,
cancelled: Arc<AtomicBool>,
}
impl XdgDesktopSession {
pub fn new(wayland_display: &str, display: &str) -> anyhow::Result<Option<Self>> {
let existing = existing_session_bus();
if existing.is_some() && desktop_in_environment() {
log::info!(
"An existing desktop session is configured; leaving its D-Bus environment alone."
);
return Ok(None);
}
let (bus_address, private_bus, runtime_dir) = if let Some((_, address)) = existing {
(address, None, None)
} else {
// runnning without a display manager → start our own dbus session
let (address, process, runtime_dir) = start_private_bus()?;
(address, Some(process), Some(runtime_dir))
};
let systemd = private_bus.is_none() && user_systemd_available();
let mut session = Self {
bus_address: bus_address.into(),
private_bus,
worker: None,
cancelled: Arc::new(AtomicBool::new(false)),
runtime_dir,
portal_config: None,
env: HashMap::new(),
saved_systemd_env: None,
saved_activation_env: None,
systemd,
};
session.configure_environment(wayland_display, display);
session.update_activation_environment()?;
session.launch_services()?;
Ok(Some(session))
}
pub const fn bus_address(&self) -> &Arc<str> {
&self.bus_address
}
fn configure_environment(&mut self, wayland_display: &str, display: &str) {
self.env
.insert("XDG_CURRENT_DESKTOP".into(), "WayVR".into());
self.env.insert("DISPLAY".into(), display.into());
self.env
.insert("WAYLAND_DISPLAY".into(), wayland_display.into());
self.env.insert("GDK_BACKEND".into(), "wayland,x11".into());
self.env
.insert("QT_QPA_PLATFORM".into(), "wayland;xcb".into());
if let Some(runtime) = &self.runtime_dir {
self.env
.insert("XDG_RUNTIME_DIR".into(), runtime.as_os_str().to_os_string());
let host_runtime = original_runtime_dir();
let display_path = Path::new(wayland_display);
if !display_path.is_absolute() {
self.env.insert(
"WAYLAND_DISPLAY".into(),
host_runtime.join(display_path).into_os_string(),
);
}
}
if let Err(err) = self.create_portal_config() {
log::warn!("Could not create WayVR portal configuration: {err:#}");
}
}
fn create_portal_config(&mut self) -> anyhow::Result<()> {
let config_home = xdg::BaseDirectories::new()
.get_config_home()
.context("HOME is not set.")?;
let portal_dir = config_home.join("xdg-desktop-portal");
fs::create_dir_all(&portal_dir)?;
let config = portal_dir.join("wayvr-portals.conf");
if !config.exists() {
fs::write(
&config,
"[preferred]\ndefault=none\norg.freedesktop.impl.portal.AppChooser=gtk;kde;\norg.freedesktop.impl.portal.FileChooser=gtk;kde;\n",
)?;
log::debug!("Wrote portal config to {}", config.display());
self.portal_config = Some(config);
}
Ok(())
}
fn update_activation_environment(&mut self) -> anyhow::Result<()> {
log::debug!("Update activation env: {:?}", self.env);
if self.systemd {
self.saved_systemd_env = Some(read_systemd_environment()?);
} else if self.private_bus.is_none() {
self.saved_activation_env = Some(
ACTIVATION_VARS
.iter()
.map(|name| ((*name).to_string(), env::var_os(name)))
.collect(),
);
}
let mut command = Command::new("dbus-update-activation-environment");
if self.systemd {
command.arg("--systemd");
}
for name in ACTIVATION_VARS {
if let Some(value) = self.env.get(*name) {
command.arg(format!("{name}={}", value.to_string_lossy()));
} else if env::var_os(name).is_some() {
command.arg(name);
}
}
self.apply_environment(&mut command);
if command.status().is_ok_and(|status| status.success()) {
return Ok(());
}
let mut variables = HashMap::new();
for name in ACTIVATION_VARS {
if let Some(value) = self.env.get(*name).cloned().or_else(|| env::var_os(name)) {
variables.insert((*name).to_string(), value.to_string_lossy().into_owned());
}
}
update_bus_environment(&self.bus_address, variables.clone())?;
if self.systemd && !variables.is_empty() {
let assignments = variables
.iter()
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>();
let status = Command::new("systemctl")
.args(["--user", "set-environment"])
.args(&assignments)
.status()?;
if !status.success() {
anyhow::bail!("Could not update systemd user environment: {status}");
}
}
Ok(())
}
fn apply_environment(&self, command: &mut Command) {
command.envs(&self.env);
}
fn launch_services(&mut self) -> anyhow::Result<()> {
let launcher = ServiceLauncher {
bus_address: self.bus_address.clone(),
children: Vec::new(),
units: Vec::new(),
env: self.env.clone(),
systemd: self.systemd,
cancelled: self.cancelled.clone(),
};
self.worker = Some(
thread::Builder::new()
.name("wayvr-dbus-services".to_string())
.spawn(move || launcher.run())?,
);
Ok(())
}
}
impl ServiceLauncher {
fn apply_environment(&self, command: &mut Command) {
command.envs(&self.env);
}
fn run(mut self) -> Self {
self.restart_services();
self
}
fn restart_services(&mut self) {
let connection = match Connection::new_address(&self.bus_address) {
Ok(connection) => connection,
Err(err) => {
log::warn!("Cannot connect to WayVR D-Bus session: {err}");
return;
}
};
let paths_to_scan = paths_to_scan();
let backend = [PORTAL_GTK, PORTAL_KDE]
.iter()
.find(|service| self.restart_service(&paths_to_scan, service, &connection))
.map(|service| service.name);
if let Some(name) = backend {
log::info!("Using {name} as the preferred portal backend");
} else {
log::warn!(
"No GTK or KDE desktop portal backend could be started. Install either for proper desktop support."
);
}
if !self.restart_service(&paths_to_scan, &PORTAL_FRONTEND, &connection) {
log::warn!("Could not start xdg-desktop-portal");
} else if let Ok((xml,)) = connection
.with_proxy(
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
Duration::from_millis(1500),
)
.method_call::<(String,), _, _, _>(
"org.freedesktop.DBus.Introspectable",
"Introspect",
(),
)
&& !xml.contains("org.freedesktop.portal.FileChooser")
{
log::warn!("xdg-desktop-portal started without a FileChooser interface");
}
if self.cancelled.load(Ordering::Relaxed) {
return;
}
if !polkit_available() {
log::debug!("polkit authority is unavailable; skipping authentication agent");
return;
}
if !self.restart_service(&paths_to_scan, &POLKIT_GNOME, &connection)
&& !self.restart_service(&paths_to_scan, &POLKIT_KDE, &connection)
{
log::warn!("Could not start a GNOME or KDE polkit authentication agent");
}
let _ = self.restart_service(&paths_to_scan, &FCITX5, &connection);
}
fn restart_service(
&mut self,
paths_to_scan: &[PathBuf],
service: &Service,
connection: &Connection,
) -> bool {
if self.cancelled.load(Ordering::Relaxed) {
return false;
}
// if we're on systemd and there's a known systemd unit, try that first
if self.systemd {
for unit in service.units {
let was_active = systemctl(&["is-active", "--quiet", unit]);
if systemctl(&["--no-block", "restart", unit]) {
if !was_active {
self.units.push(*unit);
}
if service.bus_name.map_or_else(
|| wait_for_unit(unit, &self.cancelled),
|name| wait_for_owner(connection, name, &self.cancelled),
) {
log::debug!("{unit}: Restarted successfully");
return true;
}
log::warn!(
"{unit} started but {} did not become available.",
service.name
);
}
}
}
// wouldn't be able to restore a non-systemd service after shutdown, so just skip it
if service
.bus_name
.is_some_and(|name| name_has_owner(connection, name))
{
log::debug!(
"Cannot start {:?}: Already owned",
service.bus_name.unwrap()
);
return true;
}
// launch executable directly
for executable in service.executables {
if self.cancelled.load(Ordering::Relaxed) {
return false;
}
let Some(path) = find_executable(paths_to_scan, executable) else {
log::trace!("{executable}: Not found");
continue;
};
let mut command = Command::new(path);
self.apply_environment(&mut command);
command.stdin(Stdio::null()).stdout(Stdio::null());
match command.spawn() {
Ok(mut child) => {
if let Some(name) = service.bus_name {
if wait_for_owner(connection, name, &self.cancelled) {
log::debug!("{executable}: Started successfully, PID {}", child.id());
self.children.push(child);
return true;
}
} else {
thread::sleep(Duration::from_millis(250));
if matches!(child.try_wait(), Ok(None)) {
log::debug!("{executable}: Started successfully, PID {}", child.id());
self.children.push(child);
return true;
}
}
let _ = child.kill();
let _ = child.wait();
}
Err(err) => log::warn!("Could not launch {}: {err}", service.name),
}
}
if let Some(flatpak) = service.flatpak.as_ref() {
if self.cancelled.load(Ordering::Relaxed) {
return false;
}
let mut command = Command::new("/usr/bin/flatpak");
self.apply_environment(&mut command);
command.arg("run");
command.arg(flatpak);
command.stdin(Stdio::null()).stdout(Stdio::null());
match command.spawn() {
Ok(mut child) => {
if let Some(name) = service.bus_name {
if wait_for_owner(connection, name, &self.cancelled) {
log::debug!("{flatpak}: Started successfully, PID {}", child.id());
self.children.push(child);
return true;
}
} else {
thread::sleep(Duration::from_millis(250));
if matches!(child.try_wait(), Ok(None)) {
log::debug!("{flatpak}: Started successfully, PID {}", child.id());
self.children.push(child);
return true;
}
}
let _ = child.kill();
let _ = child.wait();
}
Err(err) => log::warn!("Could not launch {}: {err}", service.name),
}
}
false
}
}
impl Drop for ServiceLauncher {
fn drop(&mut self) {
for unit in self.units.iter().rev() {
let _ = systemctl(&["--no-block", "restart", unit]);
}
for child in self.children.iter_mut().rev() {
let _ = child.kill();
let _ = child.wait();
}
}
}
impl Drop for XdgDesktopSession {
fn drop(&mut self) {
if let Some(saved) = &self.saved_systemd_env {
restore_systemd_environment(saved, &self.bus_address);
} else if let Some(saved) = &self.saved_activation_env {
let variables = saved
.iter()
.filter_map(|(name, value)| {
value
.as_ref()
.map(|value| (name.clone(), value.to_string_lossy().into_owned()))
})
.collect();
let _ = update_bus_environment(&self.bus_address, variables);
}
self.cancelled.store(true, Ordering::Relaxed);
// this dropping the worker restarts systemd units in their og env
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
if let Some(bus) = &mut self.private_bus {
let _ = bus.kill();
let _ = bus.wait();
}
if let Some(config) = &self.portal_config {
let _ = fs::remove_file(config);
}
if let Some(runtime) = &self.runtime_dir {
let _ = fs::remove_dir_all(runtime);
}
}
}
fn desktop_in_environment() -> bool {
const DESKTOPS: &[&str] = &[
"gnome", "kde", "plasma", "xfce", "mate", "cinnamon", "lxqt", "budgie", "cosmic", "niri",
"sway", "hyprland", "deepin", "unity", "pantheon",
];
env::var("XDG_CURRENT_DESKTOP").is_ok_and(|desktop| {
desktop
.split(':')
.any(|name| DESKTOPS.contains(&name.to_ascii_lowercase().as_str()))
})
}
fn name_has_owner(connection: &Connection, name: &str) -> bool {
let proxy = connection.with_proxy(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
Duration::from_millis(700),
);
let result: Result<(bool,), dbus::Error> =
proxy.method_call("org.freedesktop.DBus", "NameHasOwner", (name,));
result.is_ok_and(|(owned,)| owned)
}
fn wait_for_owner(connection: &Connection, name: &str, cancelled: &AtomicBool) -> bool {
log::info!("Waiting for {name} to be disowned...");
let deadline = Instant::now() + Duration::from_secs(8);
loop {
if cancelled.load(Ordering::Relaxed) {
return false;
}
if name_has_owner(connection, name) {
return true;
}
if Instant::now() >= deadline {
return false;
}
thread::sleep(Duration::from_millis(80));
}
}
fn wait_for_unit(unit: &str, cancelled: &AtomicBool) -> bool {
let deadline = Instant::now() + Duration::from_secs(3);
loop {
if cancelled.load(Ordering::Relaxed) {
return false;
}
if systemctl(&["is-active", "--quiet", unit]) {
return true;
}
if Instant::now() >= deadline {
return false;
}
thread::sleep(Duration::from_millis(80));
}
}
fn existing_session_bus() -> Option<(Connection, String)> {
let mut addresses = Vec::new();
if let Some(address) = env::var_os("DBUS_SESSION_BUS_ADDRESS") {
addresses.push(address.to_string_lossy().into_owned());
}
let runtime_bus = original_runtime_dir().join("bus");
if runtime_bus.exists() {
addresses.push(format!("unix:path={}", runtime_bus.display()));
}
for address in addresses {
if let Ok(connection) = Connection::new_address(&address) {
return Some((connection, address));
}
}
None
}
fn original_runtime_dir() -> PathBuf {
env::var_os("XDG_RUNTIME_DIR").map_or_else(|| PathBuf::from("/tmp"), PathBuf::from)
}
fn start_private_bus() -> anyhow::Result<(String, Child, PathBuf)> {
let runtime = original_runtime_dir().join(format!("wayvr-dbus-{}", uuid::Uuid::new_v4()));
fs::create_dir(&runtime).with_context(|| format!("Creating {}", runtime.display()))?;
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700))?;
let socket = runtime.join("bus");
let mut command = Command::new("dbus-daemon");
command.args(["--session", "--nofork", "--print-address=1"]);
command.arg(format!("--address=unix:path={}", socket.display()));
command.stdin(Stdio::null()).stdout(Stdio::piped());
let mut child = match command.spawn() {
Ok(child) => child,
Err(err) => {
let _ = fs::remove_dir_all(&runtime);
return Err(err).context("Starting private D-Bus session");
}
};
let mut address = String::new();
let result = child
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("No D-Bus address pipe"))
.and_then(|stdout| {
BufReader::new(stdout)
.read_line(&mut address)
.map_err(Into::into)
});
if result.is_err() || address.trim().is_empty() {
let _ = child.kill();
let _ = child.wait();
let _ = fs::remove_dir_all(&runtime);
anyhow::bail!("Private D-Bus failed");
}
Ok((address.trim().to_string(), child, runtime))
}
fn user_systemd_available() -> bool {
systemctl(&["show-environment"])
}
fn systemctl(args: &[&str]) -> bool {
Command::new("systemctl")
.arg("--user")
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
fn read_systemd_environment() -> anyhow::Result<HashMap<String, Option<String>>> {
let output = Command::new("systemctl")
.args(["--user", "show-environment"])
.output()?;
if !output.status.success() {
anyhow::bail!("Could not read systemd activation environment");
}
let text = String::from_utf8(output.stdout)?;
let mut saved = ACTIVATION_VARS
.iter()
.map(|name| ((*name).to_string(), None))
.collect::<HashMap<_, _>>();
for line in text.lines() {
if let Some((name, value)) = line.split_once('=')
&& let Some(slot) = saved.get_mut(name)
{
*slot = Some(value.to_string());
}
}
Ok(saved)
}
fn restore_systemd_environment(saved: &HashMap<String, Option<String>>, address: &str) {
let mut update = Command::new("dbus-update-activation-environment");
update
.arg("--systemd")
.env("DBUS_SESSION_BUS_ADDRESS", address);
for (name, value) in saved {
if let Some(value) = value {
update.arg(format!("{name}={value}"));
} else {
let _ = systemctl(&["unset-environment", name]);
}
}
let _ = update.stdout(Stdio::null()).stderr(Stdio::null()).status();
}
fn update_bus_environment(address: &str, variables: HashMap<String, String>) -> anyhow::Result<()> {
let connection = Connection::new_address(address)?;
connection
.with_proxy(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
Duration::from_secs(2),
)
.method_call::<(), _, _, _>(
"org.freedesktop.DBus",
"UpdateActivationEnvironment",
(variables,),
)?;
Ok(())
}
fn polkit_available() -> bool {
Connection::new_system().is_ok()
}
fn paths_to_scan() -> Vec<PathBuf> {
let mut roots = Vec::with_capacity(64);
let path_var = env::var_os("PATH").unwrap_or_default();
roots.extend(env::split_paths(&path_var));
roots.extend([
PathBuf::from("/usr/libexec"),
PathBuf::from("/usr/local/libexec"),
PathBuf::from("/usr/lib"),
PathBuf::from("/usr/lib64"),
PathBuf::from("/usr/local/lib"),
PathBuf::from("/usr/bin"),
PathBuf::from("/bin"),
PathBuf::from("/usr/lib/polkit-gnome"),
PathBuf::from("/usr/libexec/polkit-gnome"),
PathBuf::from("/usr/libexec/kf6"),
PathBuf::from("/usr/lib/kf6"),
]);
if let Ok(entries) = fs::read_dir("/usr/lib") {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() && entry.file_name().to_string_lossy().contains("-linux-gnu") {
roots.push(path.join("libexec"));
}
}
}
roots
}
fn find_executable(paths_to_scan: &[PathBuf], executable: &str) -> Option<PathBuf> {
paths_to_scan
.iter()
.map(|dir| dir.join(OsStr::new(executable)))
.find(|path| {
path.metadata()
.is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
})
}
+25 -1
View File
@@ -1,9 +1,11 @@
use anyhow::Context;
use glam::DVec2;
use idmap::{IdMap, idmap};
use idmap_derive::IntegerId;
use libc::{input_event, timeval};
use regex::Regex;
use serde::Deserialize;
use std::sync::LazyLock;
use std::{cell::LazyCell, sync::LazyLock};
use strum::{EnumIter, EnumString, FromRepr};
use xkbcommon::xkb;
@@ -315,12 +317,34 @@ pub const fn get_key_type(key: VirtualKey) -> KeyType {
}
}
thread_local! {
static KEYMAP_NAME_REGEX: LazyCell<Regex> = const { LazyCell::new(||
Regex::new(r"^([a-zA-Z][a-zA-Z0-9]*)(?:\(([^)]+)\))?$").unwrap()
)};
}
#[derive(Clone)]
pub struct XkbKeymap {
pub inner: xkb::Keymap,
}
impl Default for XkbKeymap {
fn default() -> Self {
Self::from_layout_variant("us", "").unwrap()
}
}
impl XkbKeymap {
pub fn from_name(name: &str) -> anyhow::Result<Self> {
let Some(captures) = KEYMAP_NAME_REGEX.with(|rx| rx.captures(name)) else {
anyhow::bail!("invalid layout name for keymap switch: {name}");
};
let layout = captures.get(1).map_or("", |g| g.as_str());
let variant = captures.get(2).map_or("", |g| g.as_str());
Self::from_layout_variant(layout, variant).context("Invalid keymap layout or variant")
}
pub fn from_layout_variant(layout: &str, variant: &str) -> Option<Self> {
let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
xkb::Keymap::new_from_names(
@@ -224,7 +224,7 @@ impl WlVirtualProvider {
let virtual_keyboard = keyboard_manager.create_virtual_keyboard(&seat, &qh, ());
let keymap = hid::get_keymap_wl()
let keymap = hid::get_keymap_wl() // not expected to fail
.unwrap_or_else(|_| hid::XkbKeymap::from_layout_variant("us", "").unwrap());
let mut result = Self {
+1 -1
View File
@@ -75,7 +75,7 @@ impl NotificationManager {
}
pub fn run_dbus(&mut self, dbus: &mut DbusConnector) {
match Connection::new_session() {
match dbus.session_connection() {
Ok(connection) => {
match connection.request_name("org.freedesktop.Notifications", false, false, true) {
Ok(RequestNameReply::PrimaryOwner | RequestNameReply::AlreadyOwner) => {
+1 -1
View File
@@ -89,7 +89,7 @@ where
if headless {
app.screens.clear();
app.feats.desktop_backend = DesktopBackend::Headless;
log::info!("Running in headless mode; keyboard will be en-US");
log::info!("Running in headless mode; keyboard layout is read from config.");
} else {
// create one window set for each screen.
// this is the default and would be overwritten by
-10
View File
@@ -1,10 +0,0 @@
[Desktop Entry]
Type=Application
Name=WayVR (Headless)
Comment=Your way to enjoy VR on Linux
Exec=wayvr --headless
Icon=wayvr
Terminal=false
Categories=Utility;X-WiVRn-VR;
X-XR-Plugin=true
X-XR-Plugin-Exec=wayvr --openxr --headless
+10
View File
@@ -0,0 +1,10 @@
[Desktop Entry]
Type=Application
Name=WayVR (Session)
Comment=Start WayVR as a full desktop environment.
Exec=wayvr --session
Icon=wayvr
Terminal=false
Categories=Utility;X-WiVRn-VR;
X-XR-Plugin=true
X-XR-Plugin-Exec=wayvr --openxr --session