game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// qt/main.cpp
4// ==============================================================================
5// Qt application entry point
6// ==============================================================================
7
9#include "game_process.h"
10#include "gamelauncher_version.h"
11#include "icon_font.h"
12#include "logger.h"
13#include "mainwindow.h"
18#include "steam_integration.h"
19#include "theme_manager.h"
20
21#include <QApplication>
22#include <QCommandLineParser>
23#include <QCoreApplication>
24#include <QDateTime>
25#include <QFile>
26#include <QIcon>
27#include <QLibraryInfo>
28#include <QLocale>
29#include <QSettings>
30#include <QSocketNotifier>
31#include <QStyleFactory>
32#include <QTranslator>
33#include <iomanip>
34#include <sstream>
35
36#ifndef _WIN32
37#include <fcntl.h>
38#include <signal.h>
39#include <unistd.h>
40#endif
41
42int main(int argc, char* argv[])
43{
44 // QtWebEngine Chromium flags. Must be set BEFORE QApplication so the
45 // Chromium subprocess (QtWebEngineProcess) inherits them at fork.
46 // --enable-features=VaapiVideoDecoder
47 // Hardware h264/h265 decode via VAAPI. Required for Frigate /
48 // go2rtc WebRTC live views to keep up with multi-camera streams
49 // without saturating CPU.
50 // --enable-features=WebRTCPipeWireCapturer
51 // Allows WebRTC media capture on Wayland sessions via xdg-desktop
52 // -portal + PipeWire (instead of the legacy X11 capturer).
53 // --ignore-gpu-blocklist
54 // Chromium maintains a per-driver blocklist that disables GPU
55 // acceleration on driver versions it doesn't trust. Bypassing is
56 // safe on a current AMDGPU/Mesa stack.
57 //
58 // KNOWN UNRESOLVED ISSUE: QtWebEngine 6.11 on Wayland + AMDGPU exhibits
59 // a SharedImageManager DMA-BUF mailbox lookup failure that prevents
60 // decoded video frames from compositing to screen (Frigate / go2rtc live
61 // views render as a black <video> element). Standard workaround
62 // --ozone-platform=x11 is unavailable because Arch's qt6-webengine is
63 // compiled with Wayland ozone only. Tracking this for a future fix that
64 // may require either (a) a custom qt6-webengine rebuild with X11 ozone
65 // enabled, (b) Chromium-side workaround flags as they emerge upstream,
66 // or (c) routing camera display through the system browser instead of
67 // the embedded one.
68 //
69 // References:
70 // https://doc.qt.io/qt-6/qtwebengine-debugging.html
71 // https://wiki.archlinux.org/title/Hardware_video_acceleration
72 qputenv("QTWEBENGINE_CHROMIUM_FLAGS",
73 "--enable-features=VaapiVideoDecoder,WebRTCPipeWireCapturer "
74 "--ignore-gpu-blocklist");
75
76 QApplication app(argc, argv);
77
78 // ----- CLI flags -----
79 //
80 // QCommandLineParser handles --help/--version automatically (calling
81 // ::exit() after printing) and lets us add launcher-specific options.
82 // Done immediately after QApplication so app.applicationName/version
83 // are set before parser.process() prints anything.
84 // Application metadata — set BEFORE the CLI parser (so --version prints the
85 // correct string) and before any QSettings access (which derives its path
86 // from the organization/application name). Version comes from the
87 // CMake-generated header, the single source of truth.
88 app.setApplicationName("Game Launcher");
89 app.setApplicationVersion(QStringLiteral(GAMELAUNCHER_VERSION_STRING));
90 app.setOrganizationName("GameLauncher");
91 app.setOrganizationDomain("gamelauncher.local");
92 // Wayland app_id / X11 WM_CLASS source: must match the .desktop file's
93 // basename (gamelauncher.desktop) and StartupWMClass so the compositor
94 // groups the window under the correct taskbar icon.
95 app.setDesktopFileName(QStringLiteral("gamelauncher"));
96
97 {
98 QCommandLineParser parser;
99 parser.setApplicationDescription(
100 QObject::tr("Linux game launcher with Steam, Lutris, GOG, and Epic integration"));
101 parser.addHelpOption();
102 parser.addVersionOption();
103 parser.addOption({{"l", "log-level"},
104 QObject::tr("Set log verbosity (debug, info, warn, error)."),
105 QObject::tr("level"),
106 "info"});
107 parser.addOption({"reset-settings",
108 QObject::tr("Discard saved window geometry and panel state on launch.")});
109 parser.process(app);
110
111 const QString lvl = parser.value("log-level").toLower();
112 if (lvl == "debug")
114 else if (lvl == "info")
116 else if (lvl == "warn" || lvl == "warning")
118 else if (lvl == "error")
120 else
121 {
122 Logger::warn("Unknown --log-level value '{}' — using info", lvl.toStdString());
123 }
124
125 if (parser.isSet("reset-settings"))
126 {
127 // Best-effort: rename rather than delete so the user can recover.
128 // SettingsController will fall through to defaults next load.
129 QString home = QString::fromUtf8(qgetenv("HOME"));
130 for (const QString& rel :
131 {QStringLiteral(".config/gamelauncher/settings.json"),
132 QStringLiteral(".local/state/gamelauncher/window-state.json")})
133 {
134 QString p = home + "/" + rel;
135 QFile f(p);
136 if (f.exists())
137 {
138 QString backup =
139 p + ".reset-" + QString::number(QDateTime::currentSecsSinceEpoch());
140 if (f.rename(backup))
141 Logger::info("--reset-settings: moved {} -> {}", p.toStdString(),
142 backup.toStdString());
143 }
144 }
145 // Also clear the QSettings store (org "GameLauncher" / app
146 // "Game Launcher"): keyboard-shortcut overrides, command-palette
147 // history, per-section collapsed state, theme choice, HA URL, the
148 // hamburger-menu preference, and crucially app/firstRunCompleted.
149 // Without this a "reset" left all UI/widget state and the wizard
150 // suppression in place.
151 QSettings().clear();
152 Logger::info("--reset-settings: cleared QSettings store");
153 }
154 }
155
156 // Log installation confirmation
157 Logger::info("=== Game Launcher Starting ===");
158 Logger::info("Executable path: {}", QCoreApplication::applicationFilePath().toStdString());
159 Logger::info("Application dir: {}", QCoreApplication::applicationDirPath().toStdString());
160
161 // Use Fusion style for consistent cross-platform look
162 app.setStyle(QStyleFactory::create("Fusion"));
163
164 // ----- i18n -----
165 //
166 // Per Qt 6 i18n best practice
167 // (https://doc.qt.io/qt-6/internationalization.html): every user-visible
168 // string is wrapped in tr(); a QTranslator loads the compiled .qm
169 // resource at startup; if no translation matches the system locale we
170 // fall back to en (the source language) which is implicitly correct.
171 //
172 // qt_add_translations(... TS_FILES ... gamelauncher_en.ts) compiles the
173 // .ts file to a .qm and embeds it under the `:/i18n/` resource prefix.
174 //
175 // The QTranslator must outlive app.exec() — make it static so its
176 // lifetime is tied to the process rather than to a stack frame in main().
177 static QTranslator appTranslator;
178 {
179 const QString locale = QLocale::system().name(); // e.g. "en_US"
180 // Try the locale-specific file first, then fall back to en.
181 if (appTranslator.load(QStringLiteral(":/i18n/gamelauncher_") + locale) ||
182 appTranslator.load(QStringLiteral(":/i18n/gamelauncher_en")))
183 {
184 QCoreApplication::installTranslator(&appTranslator);
185 Logger::info("i18n: loaded translation for locale {}", locale.toStdString());
186 }
187 else
188 {
189 // Not an error — until lupdate has been run and translations
190 // exist, this is the expected state. tr() returns the source
191 // string unchanged.
192 Logger::info("i18n: no translation file for locale {} — using source strings",
193 locale.toStdString());
194 }
195 }
196 // Qt's own widgets (QPushButton OK/Cancel, QFileDialog labels, etc.)
197 // ship qtbase_<locale>.qm under the standard translations path.
198 static QTranslator qtBaseTranslator;
199 {
200 const QString locale = QLocale::system().name();
201 if (qtBaseTranslator.load(QStringLiteral("qtbase_") + locale,
202 QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
203 {
204 QCoreApplication::installTranslator(&qtBaseTranslator);
205 }
206 }
207
208 // Load FontAwesome icon fonts from embedded resources
210
211 // Apply initial theme (default theme, settings will be loaded by MainWindow)
212 // This provides a themed appearance while the window is being constructed
214
215 // Set application icon
216 app.setWindowIcon(QIcon(":/icons/icon.png"));
217
218 // Initialize services for business logic
219 auto notificationService = std::make_shared<QtNotificationService>();
220 core::NotificationService::setInstance(notificationService);
221
222 auto imageService = std::make_shared<QtImageService>();
224
225 // Wire up GameProcessManager notification callback
226 // Uses NotificationService singleton which routes to QtNotificationService
228 [](GameProcess::NotificationType type, const std::string& message)
229 {
231 if (!service)
232 return;
233
234 switch (type)
235 {
237 service->info(message);
238 break;
240 service->warning(message);
241 break;
243 service->error(message);
244 break;
245 }
246 });
247
248 // Initialize Steam update monitor for real-time update notifications
249 auto& updateMonitor = SteamUpdateMonitor::instance();
250 updateMonitor.setOnUpdateAvailable(
251 [](const SteamGameUpdateInfo& info)
252 {
254 if (!service)
255 return;
256
257 std::string sizeStr;
258 if (info.updateSizeBytes > 0)
259 {
260 double sizeGB =
261 static_cast<double>(info.updateSizeBytes) / (1024.0 * 1024.0 * 1024.0);
262 if (sizeGB >= 1.0)
263 {
264 std::ostringstream oss;
265 oss << std::fixed << std::setprecision(1) << sizeGB;
266 sizeStr = " (" + oss.str() + " GB)";
267 }
268 else
269 {
270 double sizeMB = static_cast<double>(info.updateSizeBytes) / (1024.0 * 1024.0);
271 std::ostringstream oss;
272 oss << std::fixed << std::setprecision(0) << sizeMB;
273 sizeStr = " (" + oss.str() + " MB)";
274 }
275 }
276
277 service->info("Update available for " + info.gameName + sizeStr, 5.0f);
278 });
279
280 updateMonitor.setOnUpdateCompleted(
281 [](uint32_t /*appId*/, const std::string& gameName)
282 {
284 if (!service)
285 return;
286
287 service->success(gameName + " update completed", 3.0f);
288 });
289
290 // Start monitoring with 5 minute intervals (scans appmanifest files)
291 updateMonitor.start(300);
292
293 // Show first-run wizard on initial launch
295 {
296 FirstRunWizard wizard;
297 if (wizard.exec() == QDialog::Rejected)
298 {
299 // User cancelled - still mark completed so it doesn't show again
301 }
302 }
303
304 // Create and show main window
305 MainWindow mainWindow;
306 mainWindow.setNotificationService(notificationService);
307 mainWindow.show();
308
309 // ----- SIGTERM / SIGINT handling -----
310 //
311 // Without an explicit handler, systemctl reboot / shutdown sends the
312 // launcher straight to teardown without running MainWindow::closeEvent,
313 // which is where window geometry / panel state / splitter sizes are
314 // saved. The user-visible bug: rebooting while the launcher is open
315 // resets the layout on next start.
316 //
317 // The canonical Qt pattern (per https://doc.qt.io/qt-6/unix-signals.html)
318 // is to translate the POSIX signal into a Qt event via a self-pipe +
319 // QSocketNotifier, since calling QApplication::quit() directly from a
320 // signal handler is not async-signal-safe. The handler write()s a byte;
321 // QSocketNotifier wakes the GUI thread; the notifier's slot then calls
322 // QApplication::quit() which runs aboutToQuit and closeEvent normally.
323#ifndef _WIN32
324 static int sigPipe[2] = {-1, -1};
325 if (::pipe(sigPipe) != 0)
326 {
327 Logger::warn("Could not create signal pipe; SIGTERM/SIGINT will not save state");
328 }
329 else
330 {
331 // Make the read end non-blocking so the slot can drain the pipe in a
332 // tight loop without stalling the GUI thread.
333 ::fcntl(sigPipe[0], F_SETFL, ::fcntl(sigPipe[0], F_GETFL) | O_NONBLOCK);
334
335 struct SigHandler
336 {
337 static void handle(int /*signum*/)
338 {
339 // Strictly async-signal-safe operations only — no logging,
340 // no Qt calls, no malloc. write() is in POSIX's
341 // async-signal-safe list.
342 const char byte = 1;
343 [[maybe_unused]] ssize_t n = ::write(sigPipe[1], &byte, 1);
344 }
345 };
346
347 struct sigaction sa{};
348 sa.sa_handler = &SigHandler::handle;
349 sigemptyset(&sa.sa_mask);
350 sa.sa_flags = SA_RESTART;
351 ::sigaction(SIGTERM, &sa, nullptr);
352 ::sigaction(SIGINT, &sa, nullptr);
353
354 // QObject parent semantics: the QSocketNotifier is owned by `app`
355 // and is destroyed when QApplication is destroyed (Qt parent-child
356 // ownership, https://doc.qt.io/qt-6/qobject.html#QObject). The
357 // clang-static-analyzer can't model Qt's parent ownership and
358 // flags this as a leak (clang-analyzer-cplusplus.NewDeleteLeaks)
359 // - confirmed false positive. Path-sensitive checkers report at
360 // the function-exit site, so the suppression goes on `return
361 // app.exec()` below, not on this `new`.
362 auto* notifier = new QSocketNotifier(sigPipe[0], QSocketNotifier::Read, &app);
363 QObject::connect(notifier, &QSocketNotifier::activated, &app,
364 [notifier](QSocketDescriptor)
365 {
366 notifier->setEnabled(false);
368 "Received SIGTERM/SIGINT — saving state and exiting cleanly");
369 // Drain the pipe so re-arming doesn't immediately re-fire.
370 char buf[16];
371 while (::read(sigPipe[0], buf, sizeof(buf)) > 0)
372 {
373 }
374 // Triggers aboutToQuit, which lets MainWindow::closeEvent (and any
375 // other connected slots) persist their state via SettingsController.
376 QApplication::quit();
377 });
378 }
379#endif
380
381 // False positive on the QSocketNotifier owned by `app` (see comment
382 // above the `new QSocketNotifier(...)` call). Suppression placed at
383 // the function-exit point because that is where the path-sensitive
384 // analyzer reports the would-be leak.
385 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) - see comment above.
386 return app.exec();
387}
static bool hasBeenCompleted()
static void markCompleted()
void setOnNotification(std::function< void(GameProcess::NotificationType, const std::string &)> callback)
static GameProcessManager & instance()
NotificationType
Type of notification to display.
static bool init()
Load FontAwesome fonts from Qt resources. Call once at startup.
Definition icon_font.h:89
static void setLogLevel(LogLevel level)
Set minimum log level.
Definition logger.cpp:41
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
void setNotificationService(std::shared_ptr< QtNotificationService > service)
static SteamUpdateMonitor & instance()
static ThemeManager & instance()
void applyToApplication()
Apply current theme to the entire application.
static void setInstance(std::shared_ptr< IImageService > service)
Set the image service implementation.
static void setInstance(std::shared_ptr< INotificationService > service)
Set the notification service implementation UI layer calls this at startup with its implementation.
static std::shared_ptr< INotificationService > instance()
Get the current notification service instance.
@ WARN
Warning messages (non-critical issues).
Definition logger.h:40
@ INFO
General informational messages.
Definition logger.h:39
@ ERROR
Error messages (recoverable failures).
Definition logger.h:41
@ DEBUG
Verbose debugging information.
Definition logger.h:38
int main(int argc, char *argv[])
Definition main.cpp:42
Information about a game's update status.