game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_session_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_session_service.cpp
4// ==============================================================================
5// Implementation of game session management (screensaver, power profile)
6// ==============================================================================
7
9#include "logger.h"
10#include "process_executor.h"
11#include "shell_utils.h"
12
13#include <algorithm>
14#include <csignal>
15#include <vector>
16
17// ==============================================================================
18// Singleton Instance
19// ==============================================================================
20
26
28{
29 // Check which tools are available at startup
30 systemdInhibitAvailable_ = isCommandAvailable("systemd-inhibit");
31 powerProfilesAvailable_ = isCommandAvailable("powerprofilesctl");
32
33 Logger::info("GameSessionService: systemd-inhibit={}, powerprofilesctl={}",
34 systemdInhibitAvailable_ ? "available" : "not found",
35 powerProfilesAvailable_ ? "available" : "not found");
36}
37
38GameSessionService::~GameSessionService()
39{
40 // Clean up on destruction - release any held inhibitions
41 if (inhibitPid_ > 0)
42 {
43 uninhibitScreensaver();
44 }
45 if (!previousPowerProfile_.empty())
46 {
47 restorePowerProfile();
48 }
49}
50
51// ==============================================================================
52// Public Methods
53// ==============================================================================
54
56{
57 bool firstGame;
58 {
59 std::lock_guard<std::mutex> lock(mutex_);
60 activeGames_++;
61 Logger::info("GameSessionService: game started (active count: {})", activeGames_);
62 firstGame = (activeGames_ == 1);
63 }
64 // Call subprocess helpers outside the lock to avoid blocking all callers of
65 // isActive()/activeGameCount() for the duration of the subprocess.
66 if (firstGame)
67 {
68 inhibitScreensaver();
69 switchToPerformanceProfile();
70 }
71}
72
74{
75 bool lastGame;
76 {
77 std::lock_guard<std::mutex> lock(mutex_);
78
79 if (activeGames_ <= 0)
80 {
81 Logger::warn("GameSessionService: onGameStopped called but no games are active");
82 return;
83 }
84
85 activeGames_--;
86 Logger::info("GameSessionService: game stopped (active count: {})", activeGames_);
87 lastGame = (activeGames_ == 0);
88 }
89 if (lastGame)
90 {
91 uninhibitScreensaver();
92 restorePowerProfile();
93 }
94}
95
97{
98 std::lock_guard<std::mutex> lock(mutex_);
99 return activeGames_ > 0;
100}
101
103{
104 std::lock_guard<std::mutex> lock(mutex_);
105 return activeGames_;
106}
107
108// ==============================================================================
109// Screensaver Inhibition
110// ==============================================================================
111
112void GameSessionService::inhibitScreensaver()
113{
114 if (!systemdInhibitAvailable_)
115 {
117 "GameSessionService: systemd-inhibit not available, skipping screensaver inhibition");
118 return;
119 }
120
121 if (inhibitPid_ > 0)
122 {
123 Logger::debug("GameSessionService: screensaver already inhibited (pid: {})", inhibitPid_);
124 return;
125 }
126
127 // Launch systemd-inhibit in the background. It will hold the inhibit lock
128 // until the child process (sleep infinity) is killed.
129 // --what=idle inhibits idle detection (screensaver, suspend, etc.)
130 std::string cmd = "systemd-inhibit --what=idle --who='Game Launcher' "
131 "--why='Game is running' --mode=block sleep infinity &";
132
133 ProcessResult result = ProcessExecutor::executeBackground(cmd);
134 if (result.success)
135 {
136 // Find the PID of the sleep process we just launched
137 ProcessResult pidResult = ProcessExecutor::executeWithOutput(
138 "pgrep -n -f 'systemd-inhibit.*Game Launcher.*sleep infinity' 2>/dev/null");
139 if (pidResult.success && !pidResult.output.empty())
140 {
141 try
142 {
143 inhibitPid_ = std::stoi(pidResult.output);
144 Logger::info("GameSessionService: screensaver inhibited (pid: {})", inhibitPid_);
145 }
146 catch (...)
147 {
148 Logger::warn("GameSessionService: failed to parse inhibit PID from: {}",
149 pidResult.output);
150 }
151 }
152 else
153 {
154 Logger::warn("GameSessionService: inhibit command succeeded but could not find PID");
155 }
156 }
157 else
158 {
159 Logger::warn("GameSessionService: failed to inhibit screensaver");
160 }
161}
162
163void GameSessionService::uninhibitScreensaver()
164{
165 if (inhibitPid_ <= 0)
166 {
167 return;
168 }
169
170 Logger::info("GameSessionService: releasing screensaver inhibition (pid: {})", inhibitPid_);
171
172 // Kill the systemd-inhibit process, which releases the inhibit lock
173 if (kill(inhibitPid_, SIGTERM) != 0)
174 {
175 // Try SIGKILL as fallback
176 kill(inhibitPid_, SIGKILL);
177 }
178
179 inhibitPid_ = -1;
180}
181
182// ==============================================================================
183// Power Profile Management
184// ==============================================================================
185
186void GameSessionService::switchToPerformanceProfile()
187{
188 if (!powerProfilesAvailable_)
189 {
190 Logger::info("GameSessionService: powerprofilesctl not available, skipping profile switch");
191 return;
192 }
193
194 // Save current profile so we can restore it later
195 ProcessResult current = ProcessExecutor::executeWithOutput("powerprofilesctl get 2>/dev/null");
196 if (current.success && !current.output.empty())
197 {
198 // Trim whitespace/newlines from output
199 previousPowerProfile_ = current.output;
200 while (!previousPowerProfile_.empty() &&
201 (previousPowerProfile_.back() == '\n' || previousPowerProfile_.back() == '\r' ||
202 previousPowerProfile_.back() == ' '))
203 {
204 previousPowerProfile_.pop_back();
205 }
206 }
207 else
208 {
209 previousPowerProfile_ = "balanced"; // Safe default
210 }
211
212 // Already on performance? Nothing to do.
213 if (previousPowerProfile_ == "performance")
214 {
215 Logger::info("GameSessionService: already on performance profile, no switch needed");
216 previousPowerProfile_.clear(); // Don't restore since we didn't change it
217 return;
218 }
219
220 // Switch to performance
221 ProcessResult result = ProcessExecutor::execute("powerprofilesctl set performance 2>/dev/null");
222 if (result.success)
223 {
224 Logger::info("GameSessionService: switched power profile to performance (was: {})",
225 previousPowerProfile_);
226 }
227 else
228 {
229 Logger::warn("GameSessionService: failed to switch power profile to performance");
230 previousPowerProfile_.clear(); // Don't try to restore if switch failed
231 }
232}
233
234void GameSessionService::restorePowerProfile()
235{
236 if (!powerProfilesAvailable_ || previousPowerProfile_.empty())
237 {
238 return;
239 }
240
241 Logger::info("GameSessionService: restoring power profile to '{}'", previousPowerProfile_);
242
243 // Validate profile against known values to prevent command injection
244 static const std::vector<std::string> validProfiles = {"performance", "balanced",
245 "power-saver"};
246 if (std::find(validProfiles.begin(), validProfiles.end(), previousPowerProfile_) ==
247 validProfiles.end())
248 {
249 Logger::warn("GameSessionService: unknown power profile '{}', skipping restore",
250 previousPowerProfile_);
251 previousPowerProfile_.clear();
252 return;
253 }
254
255 ProcessResult result =
256 ProcessExecutor::execute("powerprofilesctl set " + previousPowerProfile_ + " 2>/dev/null");
257 if (result.success)
258 {
259 Logger::info("GameSessionService: power profile restored to {}", previousPowerProfile_);
260 }
261 else
262 {
263 Logger::warn("GameSessionService: failed to restore power profile to {}",
264 previousPowerProfile_);
265 }
266
267 previousPowerProfile_.clear();
268}
269
270// ==============================================================================
271// Helpers
272// ==============================================================================
273
274bool GameSessionService::isCommandAvailable(const std::string& cmd)
275{
276 ProcessResult result = ProcessExecutor::executeWithOutput(
277 "command -v " + ShellUtils::escapeArg(cmd) + " 2>/dev/null");
278 return result.success && !result.output.empty();
279}
static GameSessionService & instance()
Get singleton instance.
GameSessionService(const GameSessionService &)=delete
int activeGameCount() const
Get current number of running games being tracked.
void onGameStopped()
Called when a game stops running.
bool isActive() const
Check if any inhibitions are currently active.
void onGameStarted()
Called when a game starts running.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static ProcessResult executeWithOutput(const std::string &command, bool silent=false)
Execute command and capture stdout.
static ProcessResult executeBackground(const std::string &command)
Execute command in background (non-blocking).
static ProcessResult execute(const std::string &command, bool silent=false)
Execute command and check exit code.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
bool success
true if command executed successfully (exit code 0)
std::string output
Captured stdout (if requested).