game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
steam_monitor.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#include "steam_monitor.h"
3#include "logger.h"
4#include "process_executor.h"
5#include "steam_constants.h"
6#include "steam_paths.h"
7#include <chrono>
8#include <filesystem>
9
10// ==============================================================================
11// Singleton
12// ==============================================================================
13
14SteamProcessMonitor& SteamProcessMonitor::instance()
15{
16 static SteamProcessMonitor instance;
17 return instance;
18}
19
20// ==============================================================================
21// Constructor / Destructor
22// ==============================================================================
23
24SteamProcessMonitor::SteamProcessMonitor()
25 : currentState_(State::NOT_RUNNING), shouldStop_(false),
26 transitionTime_(std::chrono::steady_clock::now())
27{
28 Logger::info("[SteamMonitor] Initialized");
29}
30
31SteamProcessMonitor::~SteamProcessMonitor()
32{
34}
35
36// ==============================================================================
37// Control Methods
38// ==============================================================================
39
41{
42 if (monitorThread_.joinable())
43 {
44 Logger::info("[SteamMonitor] Already monitoring");
45 return;
46 }
47
48 Logger::info("[SteamMonitor] Starting monitor thread");
49 shouldStop_ = false;
50
51 // Check initial state
52 if (checkSteamProcess())
53 {
54 transitionTo(State::RUNNING);
55 }
56 else
57 {
58 transitionTo(State::NOT_RUNNING);
59 }
60
61 monitorThread_ = std::thread(&SteamProcessMonitor::monitorThread, this);
62}
63
65{
66 if (!monitorThread_.joinable())
67 {
68 return;
69 }
70
71 Logger::info("[SteamMonitor] Stopping monitor thread");
72 // Set the stop flag under stateMutex_ (the CV's mutex) before notifying so
73 // the monitor thread's wait_for predicate cannot miss the wakeup.
74 {
75 std::lock_guard<std::mutex> lock(stateMutex_);
76 shouldStop_ = true;
77 }
78 stateCV_.notify_all();
79
80 if (monitorThread_.joinable())
81 {
82 monitorThread_.join();
83 }
84
85 // SteamProcessMonitor is a process-lifetime singleton. Without
86 // explicitly clearing the callback, any captured `this` / lambda
87 // closure passed via setStateCallback() lives until program exit
88 // — even if the calling MainWindow has been destroyed. The next
89 // setStateCallback (or the destructor itself) would then invoke
90 // a closure pointing at freed memory. Clear after the join so no
91 // monitor-thread invocation can race with the reset.
92 {
93 std::lock_guard<std::mutex> lock(stateMutex_);
94 stateCallback_ = nullptr;
95 }
96}
97
99{
100 {
101 std::lock_guard<std::mutex> lock(stateMutex_);
102 State current = currentState_.load();
103
104 if (current == State::RUNNING)
105 {
106 Logger::info("[SteamMonitor] Steam already running");
107 return;
108 }
109
110 if (current == State::STARTING)
111 {
112 Logger::info("[SteamMonitor] Steam already starting");
113 return;
114 }
115
116 Logger::info("[SteamMonitor] Requesting Steam start");
117 currentState_.store(State::STARTING);
118 transitionTime_ = std::chrono::steady_clock::now();
119 stateCV_.notify_all();
120 }
121
122 // Launch Steam in background (outside lock)
123 ProcessExecutor::executeBackground("steam -silent");
124}
125
127{
128 {
129 std::lock_guard<std::mutex> lock(stateMutex_);
130 State current = currentState_.load();
131
132 if (current == State::NOT_RUNNING)
133 {
134 Logger::info("[SteamMonitor] Steam already stopped");
135 return;
136 }
137
138 if (current == State::STOPPING)
139 {
140 Logger::info("[SteamMonitor] Steam already stopping");
141 return;
142 }
143
144 Logger::info("[SteamMonitor] Requesting Steam shutdown");
145 currentState_.store(State::STOPPING);
146 transitionTime_ = std::chrono::steady_clock::now();
147 stateCV_.notify_all();
148 }
149
150 // Request Steam shutdown outside lock (silent - no window shown)
151 ProcessExecutor::execute("steam -shutdown");
152}
153
154bool SteamProcessMonitor::waitForState(State targetState, int timeoutMs)
155{
156 std::unique_lock<std::mutex> lock(stateMutex_);
157
158 return stateCV_.wait_for(lock, std::chrono::milliseconds(timeoutMs),
159 [this, targetState]() { return currentState_.load() == targetState; });
160}
161
162// ==============================================================================
163// State Query
164// ==============================================================================
165
167{
168 return currentState_.load();
169}
170
172{
173 return currentState_.load() == State::RUNNING;
174}
175
177{
178 // First check if the process is running
179 if (currentState_.load() != State::RUNNING)
180 {
181 return false;
182 }
183
184 // Check for Steam's IPC socket which indicates Steam is ready for commands
185 // Steam creates this socket when it's fully initialized
186 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
187 if (steamRoot.empty())
188 {
189 return false;
190 }
191
192 // Check for steam.pipe (IPC socket) - indicates Steam is accepting commands
193 std::filesystem::path pipePath = steamRoot / "steam.pipe";
194 if (std::filesystem::exists(pipePath))
195 {
196 return true;
197 }
198
199 // Alternative: Check for the registry.vdf lock which Steam holds while running
200 std::filesystem::path registryPath = steamRoot / "registry.vdf";
201 if (std::filesystem::exists(registryPath))
202 {
203 // If registry.vdf exists and we can't get exclusive access, Steam has it locked
204 // This is a reasonable indicator that Steam is fully initialized
205 return true;
206 }
207
208 // Check for steamwebhelper process which starts after Steam UI is ready
209 if (ProcessExecutor::isProcessRunning("steamwebhelper"))
210 {
211 return true;
212 }
213
214 return false;
215}
216
218{
219 Logger::info("[SteamMonitor] Waiting for Steam to be fully initialized...");
220
221 auto startTime = std::chrono::steady_clock::now();
222 int pollIntervalMs = 250;
223
224 while (true)
225 {
227 {
228 Logger::info("[SteamMonitor] Steam is fully initialized");
229 return true;
230 }
231
232 auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
233 std::chrono::steady_clock::now() - startTime)
234 .count();
235
236 if (elapsed >= timeoutMs)
237 {
238 Logger::warn("[SteamMonitor] Timeout waiting for Steam initialization after {}ms",
239 timeoutMs);
240 return false;
241 }
242
243 std::this_thread::sleep_for(std::chrono::milliseconds(pollIntervalMs));
244 }
245}
246
247// ==============================================================================
248// Callbacks
249// ==============================================================================
250
252{
253 // Value param + std::move into storage: lets a caller passing
254 // an rvalue (e.g. lambda literal or std::move(myCb)) skip a copy.
255 std::lock_guard<std::mutex> lock(stateMutex_);
256 stateCallback_ = std::move(callback);
257}
258
259// ==============================================================================
260// Internal Methods
261// ==============================================================================
262
263void SteamProcessMonitor::monitorThread()
264{
265 Logger::info("[SteamMonitor] Monitor thread started");
266
267 while (!shouldStop_)
268 {
269 State current = currentState_.load();
270 bool processExists = checkSteamProcess();
271
272 // State machine logic
273 switch (current)
274 {
276 if (processExists)
277 {
278 // Steam started externally
279 transitionTo(State::RUNNING);
280 }
281 break;
282
283 case State::STARTING:
284 if (processExists)
285 {
286 // Steam has started successfully
287 Logger::info("[SteamMonitor] Steam started successfully");
288 transitionTo(State::RUNNING);
289 }
290 else
291 {
292 // Check for timeout
293 handleStartingTimeout();
294 }
295 break;
296
297 case State::RUNNING:
298 if (!processExists)
299 {
300 // Steam stopped unexpectedly or was closed
301 Logger::info("[SteamMonitor] Steam stopped");
302 transitionTo(State::NOT_RUNNING);
303 }
304 break;
305
306 case State::STOPPING:
307 if (!processExists)
308 {
309 // Steam has shut down successfully
310 Logger::info("[SteamMonitor] Steam shut down successfully");
311 transitionTo(State::NOT_RUNNING);
312 }
313 else
314 {
315 // Check for timeout
316 handleStoppingTimeout();
317 }
318 break;
319
320 case State::ERROR:
321 // Stay in error state until external reset
322 break;
323 }
324
325 // Poll every 500ms, but wake immediately when stopMonitoring() sets
326 // shouldStop_ and notifies — the old sleep_for ignored the CV, so the
327 // notify_all() in stopMonitoring() was dead and shutdown always waited
328 // out the full 500ms. The predicate re-check makes this lost-wakeup
329 // safe. transitionTo() takes stateMutex_ internally, so only hold it
330 // here for the wait, not across the state machine above.
331 {
332 std::unique_lock<std::mutex> lock(stateMutex_);
333 stateCV_.wait_for(lock, std::chrono::milliseconds(500),
334 [this] { return shouldStop_.load(); });
335 }
336 }
337
338 Logger::info("[SteamMonitor] Monitor thread stopped");
339}
340
341bool SteamProcessMonitor::checkSteamProcess()
342{
343 return ProcessExecutor::isProcessRunning("steam");
344}
345
346void SteamProcessMonitor::transitionTo(State newState)
347{
348 State oldState = currentState_.exchange(newState);
349
350 if (oldState == newState)
351 {
352 return; // No change
353 }
354
355 // Copy callback under lock, invoke outside
356 StateCallback callbackCopy;
357 {
358 std::lock_guard<std::mutex> lock(stateMutex_);
359 transitionTime_ = std::chrono::steady_clock::now();
360
361 Logger::info("[SteamMonitor] State transition: {} -> {}", static_cast<int>(oldState),
362 static_cast<int>(newState));
363
364 // Notify waiting threads
365 stateCV_.notify_all();
366
367 callbackCopy = stateCallback_;
368 }
369
370 if (callbackCopy)
371 {
372 callbackCopy(oldState, newState);
373 }
374}
375
376void SteamProcessMonitor::handleStartingTimeout()
377{
378 // Snap transitionTime_ under lock to avoid data race with requestSteamStart().
379 std::chrono::steady_clock::time_point t;
380 {
381 std::lock_guard<std::mutex> lock(stateMutex_);
382 t = transitionTime_;
383 }
384 auto now = std::chrono::steady_clock::now();
385 auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - t).count();
386
388 {
389 Logger::error("[SteamMonitor] Timeout waiting for Steam to start");
390 transitionTo(State::ERROR);
391 }
392}
393
394void SteamProcessMonitor::handleStoppingTimeout()
395{
396 std::chrono::steady_clock::time_point t;
397 {
398 std::lock_guard<std::mutex> lock(stateMutex_);
399 t = transitionTime_;
400 }
401 auto now = std::chrono::steady_clock::now();
402 auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - t).count();
403
405 {
406 Logger::error("[SteamMonitor] Timeout waiting for Steam to shut down");
407 transitionTo(State::ERROR);
408 }
409}
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
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 bool isProcessRunning(const std::string &processName)
Check if process is running by name.
static std::filesystem::path getPrimarySteamRoot()
Get primary Steam installation directory.
void setStateCallback(StateCallback callback)
State getCurrentState() const
bool isSteamRunning() const
static SteamProcessMonitor & instance()
bool waitForSteamInitialized(int timeoutMs=10000)
bool isSteamFullyInitialized() const
bool waitForState(State targetState, int timeoutMs=10000)
std::function< void(State oldState, State newState)> StateCallback
constexpr int START_TIMEOUT_SEC
Maximum time to wait for Steam to start before timeout.
constexpr int SHUTDOWN_TIMEOUT_SEC
Maximum time to wait for Steam to shutdown before timeout.