Skip to content

Commit

Permalink
desktop: Add GameModeSession for managing gamemode
Browse files Browse the repository at this point in the history
  • Loading branch information
kjarosh authored and Dinnerbone committed Oct 6, 2024
1 parent 4544f86 commit 1e7e81a
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions desktop/src/dbus.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#![cfg(target_os = "linux")]
//! Types and methods utilized for communicating with D-Bus

use std::mem;
use std::sync::{Arc, Mutex};

use futures::StreamExt;
use zbus::export::futures_core::Stream;
use zbus::zvariant::{OwnedValue, Value};
Expand Down Expand Up @@ -80,3 +83,56 @@ impl<'p> FreedesktopSettings<'p> {
}
}
}

pub struct GameModeSession {
_guard: Arc<Mutex<Option<GameModeGuard>>>,
}

impl GameModeSession {
pub fn new(enabled: bool) -> Self {
let guard = Arc::new(Mutex::new(None));
let guard2 = guard.clone();
tokio::spawn(async move {
let game_mode_guard = GameModeGuard::new(enabled).await;
*guard2.lock().expect("Non-poisoned gamemode guard") = Some(game_mode_guard);
});
Self { _guard: guard }
}
}

struct GameModeGuard {
gamemode: Option<ashpd::desktop::game_mode::GameMode<'static>>,
}

impl GameModeGuard {
async fn new(enabled: bool) -> Self {
if !enabled {
return Self { gamemode: None };
}

let gamemode = ashpd::desktop::game_mode::GameMode::new()
.await
.inspect_err(|err| tracing::warn!("Failed to initialize gamemode controller: {}", err))
.ok();

if let Some(gamemode) = &gamemode {
if let Err(err) = gamemode.register(std::process::id()).await {
tracing::warn!("Failed to register a game with gamemode: {}", err)
}
}

Self { gamemode }
}
}

impl Drop for GameModeGuard {
fn drop(&mut self) {
if let Some(gamemode) = mem::take(&mut self.gamemode) {
tokio::spawn(async move {
if let Err(err) = gamemode.unregister(std::process::id()).await {
tracing::warn!("Failed to unregister a game with gamemode: {}", err)
}
});
}
}
}

0 comments on commit 1e7e81a

Please sign in to comment.