game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
mainwindow.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// qt/mainwindow.cpp
4// ==============================================================================
5// Main window implementation with list/grid view support
6// ==============================================================================
7
8#include "mainwindow.h"
9#include "a11y_utils.h"
10#include "command_palette.h"
26#include "dpr_utils.h"
27#include "icon_font.h"
38#include "models/game.h"
44#include "shortcut_manager.h"
46#include "theme_manager.h"
47#include "util/logger.h"
58#ifdef HAVE_QTERMWIDGET
60#endif
61#ifdef HAVE_WEBENGINE
63#endif
64
65#include <QAction>
66#include <QActionGroup>
67#include <QApplication>
68#include <QClipboard>
69#include <QCloseEvent>
70#include <QComboBox>
71#include <QDateTime>
72#include <QDesktopServices>
73#include <QFile>
74#include <QFileInfo>
75#include <QFrame>
76#include <QGuiApplication>
77#include <QHBoxLayout>
78#include <QInputDialog>
79#include <QItemSelectionModel>
80#include <QKeyEvent>
81#include <QLabel>
82#include <QLineEdit>
83#include <QListView>
84#include <QListWidget>
85#include <QMenu>
86#include <QMenuBar>
87#include <QMessageBox>
88#include <QMimeData>
89#include <QMouseEvent>
90#include <QPainter>
91#include <QPainterPath>
92#include <QProcess>
93#include <QProgressBar>
94#include <QPropertyAnimation>
95#include <QPushButton>
96#include <QScreen>
97#include <QScrollArea>
98#include <QScrollBar>
99#include <QSettings>
100#include <QShortcut>
101#include <QSplitter>
102#include <QStatusBar>
103#include <QStyledItemDelegate>
104#include <QTimer>
105#include <QToolBar>
106#include <QVBoxLayout>
107#include <QtConcurrent/QtConcurrent>
108#include <algorithm>
109#include <atomic>
110#include <chrono>
111#include <deque>
112#include <filesystem>
113#include <set>
114#include <thread>
115#include <unordered_map>
116
117// ==============================================================================
118// Helper Functions
119// ==============================================================================
120
121// Open a steam:// URL using the steam command directly (avoids KIO issues)
122static void openSteamUrl(const QString& steamUrl)
123{
124 // Use steam command directly to avoid KIO protocol handler issues
125 // steam:// URLs work when passed to the steam executable
126 QProcess::startDetached("steam", {steamUrl});
127}
128
130
131MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent)
132{
133 // Initialize controllers
134 libraryController_ = std::make_unique<core::GameLibraryController>();
135 launchController_ = std::make_unique<core::LaunchController>();
136 settingsController_ = std::make_unique<core::SettingsController>();
137 performanceProfileService_ = std::make_unique<PerformanceProfileService>();
138
139 // Image cache (thumbnails, heroes, path validation) — MED-7 extraction.
140 // Parented to `this` via QObject so it receives queued invokeMethod calls
141 // from the buildImagePathCache worker and cleans up with the window.
142 imageCache_ = std::make_unique<GameThumbnailCache>(
143 /*maxThumbnails=*/300, /*maxHeroImages=*/30, this);
144
145 // Load settings and library
146 settingsController_->loadSettings();
147 libraryController_->loadLibrary();
148
149 // Sync Steam installed status for all Steam games
150 // This ensures the database matches actual Steam state
151 syncSteamInstalledStatus();
152
153 // Pre-load Steam app name cache in background (needed for Steam import)
154 // This runs early so it's ready before user opens Steam import dialog
155 (void)QtConcurrent::run([]() { SteamLibraryScanner::loadAppNameCache(); });
156
157 // Initialize game process tracker with library games to detect already-running games
159 libraryController_->getAllGames(),
160 [this](const std::string& gameId, const std::function<void(Game&)>& updater)
161 { libraryController_->executeWithGame(gameId, updater); });
162
163 // Set up callback to persist game statistics when a game exits
164 // NOTE: This callback fires from the GameProcessManager background detection thread,
165 // so we must marshal all library/UI access to the Qt main thread.
166 // QPointer guard ensures we don't touch a destroyed MainWindow if the callback
167 // fires during or after destruction (cleared in ~MainWindow() as primary guard).
168 QPointer<MainWindow> statsGuard(this);
170 [statsGuard](const std::string& gameId)
171 {
172 if (!statsGuard)
173 return;
174 // Capture gameId by value into the queued lambda — the outer
175 // gameId is a reference into a transient call frame and may be
176 // destroyed before the queued slot fires on the GUI thread.
177 QMetaObject::invokeMethod(
178 statsGuard,
179 [statsGuard, gameId]()
180 {
181 if (!statsGuard || !statsGuard->libraryController_)
182 return;
183 statsGuard->libraryController_->saveLibrary();
184 Logger::info("Persisted game statistics for: {}", gameId);
185 },
186 Qt::QueuedConnection);
187 });
188
189 // Start Steam process monitor for launch management
191
192 // Clean up old MangoHud logs (older than 24 hours) to prevent disk space bloat
194
195 // Initialize theme manager with settings and load saved theme
196 ThemeManager::instance().initialize(settingsController_.get());
198
199 // Apply first-run wizard overrides (wizard runs before settings controller exists)
200 {
201 QSettings qSettings;
202 if (qSettings.contains("wizard/enableHomeAssistant"))
203 {
204 auto appSettings = settingsController_->getAppSettings();
205 appSettings.enableHomeAssistant =
206 qSettings.value("wizard/enableHomeAssistant").toBool();
207 if (qSettings.contains("wizard/homeAssistantUrl"))
208 appSettings.homeAssistantUrl =
209 qSettings.value("wizard/homeAssistantUrl").toString().toStdString();
210 settingsController_->setAppSettings(appSettings);
211 qSettings.remove("wizard/enableHomeAssistant");
212 qSettings.remove("wizard/homeAssistantUrl");
213 }
214 // Also persist the wizard theme choice to the settings controller
216 }
217
218 // Setup UI
219 setupUI();
220 setupMenuBar();
221 // ContextMenuManager needs both detailsPanelManager_ (created in
222 // setupUI) and gameActionFactory_ (created in setupMenuBar) — so
223 // construct it AFTER both. Constructing it inside setupGameList()
224 // was the original bug where both pointers were captured null.
225 setupGameListContextMenu();
226 setupToolBar();
227 setupStatusBar();
228 setupTrayIcon();
229 setupControllerCallbacks();
230 setupKeyboardShortcuts();
231 setupCommandPalette();
232 setupSteamDownloadMonitor();
233
234 // Initialize async image loader (offloads image I/O to background threads)
235 imageLoader_ = new AsyncImageLoader(this);
236 connect(imageLoader_, &AsyncImageLoader::imageLoaded, this, &MainWindow::onAsyncImageLoaded);
237
238 // Connect theme changes to UI refresh
239 connect(&ThemeManager::instance(), &ThemeManager::themeChanged, this, &MainWindow::applyTheme);
240
241 // Build image path cache in background. GameThumbnailCache owns the
242 // thread-pool task internally (with its own shutdown-flag coordination),
243 // so we just hand it the list of games from the library controller.
244 if (imageCache_ && libraryController_)
245 {
246 // getAllGames() returns std::vector<Game*>; the cache wants
247 // std::vector<const Game*> since it only reads. Convert here.
248 auto src = libraryController_->getAllGames();
249 std::vector<const Game*> games(src.begin(), src.end());
250 imageCache_->buildImagePathCache(games);
251 }
252
253 // Apply menu mode (menu bar vs hamburger) from settings
254 updateMenuMode();
255
256 // Initial refresh
257 refreshGameList();
258
259 // Set window properties
260 setWindowTitle("Game Launcher");
261 resize(1400, 900);
262
263 // Check if any games are already running and apply gaming layout if needed
264 // Deferred slightly to ensure all UI is fully initialized
265 QTimer::singleShot(500, this, &MainWindow::checkRunningGameOnStartup);
266
267 // Start periodic update timer for launch state monitoring
268 // Using 1000ms interval for better battery/CPU efficiency - 500ms is excessive
269 QTimer* updateTimer = new QTimer(this);
270 updateTimer->setObjectName("updateTimer"); // For start/stop on minimize
271 connect(updateTimer, &QTimer::timeout, this,
272 [this]()
273 {
274 launchController_->update();
275 detailsPanelManager_->updateLaunchButton(selectedGameId_);
276 // Update running count in sidebar (check every 5 seconds to reduce overhead)
277 static int timerTicks = 0;
278 if (++timerTicks >= 5) // 5 * 1000ms = 5 seconds
279 {
280 timerTicks = 0;
281 updateCategoryCounts();
282 }
283 // Note: Running game info is now updated by frameMetricsTimer_ using lightweight
284 // detailsPanelManager_->updateRunningInfo()
285 });
286 updateTimer->start(1000); // Update every 1000ms (was 500ms)
287
288 // Discover and refresh images for games (run once after startup)
289 QTimer::singleShot(
290 2000, this,
291 [this]()
292 {
293 // Show progress indicator
294 QMetaObject::invokeMethod(
295 this,
296 [this]()
297 {
298 if (statusProgressBar_)
299 {
300 statusProgressBar_->setVisible(true);
301 statusLabel_->setText(statusLabel_->text() + " | Updating images...");
302 }
303 },
304 Qt::QueuedConnection);
305
306 // Run in a separate thread to avoid blocking UI
307 // Use QPointer to safely handle MainWindow destruction during async operation
308 QPointer<MainWindow> self = this;
309 // libraryController_ is owned by MainWindow and initialized in its
310 // constructor; once `self` is non-null inside the lambda the
311 // controller pointer is also valid. The static analyzer can't see
312 // that ownership invariant, so it flags the .get() — suppress here.
313 // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage)
314 auto* libraryController = libraryController_.get();
315 (void)QtConcurrent::run(
316 [self, libraryController]()
317 {
318 if (!self)
319 return; // Abort if MainWindow was destroyed before task started
320 // First, refresh any stale images (paths that no longer exist)
321 int refreshed = libraryController->refreshStaleImages();
322
323 // Then discover images for games missing cover art
324 int discovered = libraryController->discoverMissingImages();
325
326 int total = refreshed + discovered;
327
328 // Hide progress indicator and refresh on main thread - check if window still
329 // exists
330 if (self)
331 {
332 QMetaObject::invokeMethod(
333 self.data(),
334 [self, total, refreshed, discovered]()
335 {
336 if (!self)
337 return; // Double-check in case destroyed between queue and
338 // execution
339
340 if (self->statusProgressBar_)
341 {
342 self->statusProgressBar_->setVisible(false);
343 }
344
345 if (total > 0)
346 {
347 // Clear all image caches so new images are loaded.
348 if (self->imageCache_)
349 self->imageCache_->clearAll();
350
351 self->refreshGameList();
352 if (self->notificationService_)
353 {
354 std::string msg;
355 if (refreshed > 0 && discovered > 0)
356 {
357 msg = "Updated images: " + std::to_string(refreshed) +
358 " refreshed, " + std::to_string(discovered) +
359 " discovered";
360 }
361 else if (refreshed > 0)
362 {
363 msg = "Refreshed images for " +
364 std::to_string(refreshed) + " game(s)";
365 }
366 else
367 {
368 msg = "Discovered images for " +
369 std::to_string(discovered) + " game(s)";
370 }
371 self->notificationService_->success(msg);
372 }
373 }
374 },
375 Qt::QueuedConnection);
376 }
377 });
378 });
379
380 // Fetch ProtonDB data for Steam games with stale/missing cache (run after startup)
381 QTimer::singleShot(5000, this, [this]() { fetchMissingProtonDB(); });
382
383 // Fetch Steam names for games with placeholder names (run after startup)
384 QTimer::singleShot(
385 3000, this,
386 [this]()
387 {
388 Logger::info("[MainWindow] Starting Steam name fetch task");
389 // Run in a separate thread to avoid blocking UI
390 // Use QPointer to safely handle MainWindow destruction during async operation
391 QPointer<MainWindow> self = this;
392 // libraryController_ ownership is tied to MainWindow's lifetime; the
393 // QPointer `self` check inside the lambda is the real guard.
394 // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage)
395 auto* libraryController = libraryController_.get();
396 (void)QtConcurrent::run(
397 [self, libraryController]()
398 {
399 if (!self)
400 return;
401
402 auto allGames = libraryController->getAllGames();
403 Logger::info("[MainWindow] Checking {} games for placeholder names",
404 allGames.size());
405
406 // Collect game IDs that have placeholder names (e.g., "Steam App XXXXX")
407 std::vector<std::pair<std::string, uint32_t>>
408 needsNameFetch; // (gameId, steamAppId)
409
410 for (const auto* game : allGames)
411 {
412 if (game->source == GameSource::Steam && game->metadata.steamAppId > 0)
413 {
414 // Check if name is a placeholder
415 if (game->name.find("Steam App ") == 0)
416 {
418 "[MainWindow] Found placeholder name: '{}' (AppID: {})",
419 game->name, game->metadata.steamAppId);
420 needsNameFetch.emplace_back(
421 game->id, static_cast<uint32_t>(game->metadata.steamAppId));
422 }
423 }
424 }
425
426 if (needsNameFetch.empty())
427 {
428 Logger::info("[MainWindow] No games with placeholder names found");
429 return;
430 }
431
432 Logger::info("[MainWindow] Found {} games needing name fetch",
433 needsNameFetch.size());
434
435 // Update status on main thread
436 if (self)
437 {
438 QMetaObject::invokeMethod(
439 self.data(),
440 [self, count = needsNameFetch.size()]()
441 {
442 if (!self)
443 return;
444 if (self->statusProgressBar_)
445 {
446 self->statusProgressBar_->setVisible(true);
447 self->statusLabel_->setText("Fetching Steam names for " +
448 QString::number(count) +
449 " game(s)...");
450 }
451 },
452 Qt::QueuedConnection);
453 }
454
455 int updated = 0;
456 for (const auto& entry : needsNameFetch)
457 {
458 if (!self)
459 break; // Stop if window was destroyed
460
461 const std::string& gameId = entry.first;
462 uint32_t steamAppId = entry.second;
463
464 Logger::info("[MainWindow] Fetching name for AppID {}", steamAppId);
465
466 // Try to get name from cache first, then API
467 std::string fetchedName =
469
470 if (fetchedName.empty())
471 {
472 Logger::info("[MainWindow] Cache miss for AppID {}, trying API",
473 steamAppId);
474 // Try the API
475 fetchedName =
477 }
478 else
479 {
480 Logger::info("[MainWindow] Cache hit for AppID {}: '{}'", steamAppId,
481 fetchedName);
482 }
483
484 if (!fetchedName.empty() && self)
485 {
486 Logger::info("[MainWindow] Got name for AppID {}: '{}'", steamAppId,
487 fetchedName);
488 // Update game name on main thread
489 // Use QueuedConnection to avoid deadlock on window destruction
490 QMetaObject::invokeMethod(
491 self.data(),
492 [self, libraryController, gameId, fetchedName]()
493 {
494 if (!self)
495 return;
496 Game* mutableGame = libraryController->getGameForEdit(gameId);
497 if (mutableGame && mutableGame->name.find("Steam App ") == 0)
498 {
499 Logger::info("[MainWindow] Updating game '{}' -> '{}'",
500 mutableGame->name, fetchedName);
501 mutableGame->name = fetchedName;
502 libraryController->updateGame(gameId, *mutableGame);
503 }
504 },
505 Qt::QueuedConnection);
506 updated++;
507 }
508 else if (fetchedName.empty())
509 {
510 Logger::warn("[MainWindow] Failed to fetch name for AppID {}",
511 steamAppId);
512 }
513
514 // Small delay to avoid hammering the Steam API
515 std::this_thread::sleep_for(std::chrono::milliseconds(100));
516 }
517
518 Logger::info("[MainWindow] Steam name fetch complete. Updated {} games",
519 updated);
520
521 // Save and update UI on main thread
522 if (self)
523 {
524 QMetaObject::invokeMethod(
525 self.data(),
526 [self, libraryController, updated]()
527 {
528 if (!self)
529 return;
530 if (self->statusProgressBar_)
531 {
532 self->statusProgressBar_->setVisible(false);
533 }
534
535 if (updated > 0)
536 {
537 libraryController->saveLibrary();
538 self->refreshGameList();
539 if (self->notificationService_)
540 {
541 self->notificationService_->success(
542 "Updated names for " + std::to_string(updated) +
543 " Steam game(s)");
544 }
545 }
546 },
547 Qt::QueuedConnection);
548 }
549 });
550 });
551}
552
554{
555 // Clear singleton callbacks before any members are destroyed.
556 // The GameProcessManager background thread can fire onGameStatsUpdated at any time;
557 // clearing it here prevents it from running with a dangling this pointer.
559
560 // Signal shutdown to all background tasks
561 isShuttingDown_.store(true);
562 if (imageCache_)
563 imageCache_->requestShutdown();
564
565 // Cancel async image loading operations
566 if (imageLoader_)
567 {
568 imageLoader_->cancelAll();
569 }
570
571 // Stop Steam monitor
573
574 // Save settings on exit
575 settingsController_->saveSettings();
576}
577
578void MainWindow::setNotificationService(std::shared_ptr<QtNotificationService> service)
579{
580 notificationService_ = std::move(service);
581 if (notificationService_)
582 {
583 notificationService_->setParentWidget(this);
584 }
585}
586
587void MainWindow::closeEvent(QCloseEvent* event)
588{
589 // Check if we should minimize to tray instead of closing
590 // (unless forceQuit_ is set from Exit menu action)
591 if (!forceQuit_ && settingsController_->isMinimizeToTrayEnabled() && trayIcon_ &&
592 trayIcon_->isVisible())
593 {
594 hide();
595 event->ignore();
596 return;
597 }
598
599 // Save panel visibility state before closing
600 if (settingsController_ && !isInGamingLayout_)
601 {
602 auto settings = settingsController_->getAppSettings();
603 settings.panelSidebarVisible = sidebarContainer_ && sidebarContainer_->isVisible();
604 settings.panelGamesVisible = gameListContainer_ && gameListContainer_->isVisible();
605 settings.panelDetailsVisible = detailsContainer_ && detailsContainer_->isVisible();
606#ifdef HAVE_QTERMWIDGET
607 settings.panelMonitorVisible = terminalContainer_ && terminalContainer_->isVisible();
608#endif
609#ifdef HAVE_WEBENGINE
610 settings.panelHAVisible = haContainer_ && haContainer_->isVisible();
611#endif
612 // Save splitter sizes
613 if (mainSplitter_)
614 {
615 QStringList sizeStrs;
616 for (int s : mainSplitter_->sizes())
617 sizeStrs.append(QString::number(s));
618 settings.splitterSizes = sizeStrs.join(",").toStdString();
619 }
620 settingsController_->setAppSettings(settings);
621 settingsController_->saveSettings();
622 }
623
624 // Just close the launcher - games will continue running independently
625 // No need to confirm or stop games, they run as separate processes
626 event->accept();
627 QApplication::quit();
628}
629
630void MainWindow::setupUI()
631{
632 QWidget* centralWidget = new QWidget(this);
633 setCentralWidget(centralWidget);
634
635 // Enable drag-and-drop of executable files onto the window to add games
636 setAcceptDrops(true);
637
638 QHBoxLayout* mainLayout = new QHBoxLayout(centralWidget);
639 mainLayout->setContentsMargins(0, 0, 0, 0);
640 mainLayout->setSpacing(0);
641
643
644 mainSplitter_ = new QSplitter(Qt::Horizontal, this);
645 mainSplitter_->setHandleWidth(6); // Wider handles for easier grabbing
646 mainSplitter_->setChildrenCollapsible(false); // Prevent panels from collapsing to 0
647 mainSplitter_->setOpaqueResize(false); // Use rubber band for smoother resizing
648 mainSplitter_->setStyleSheet(QString("QSplitter::handle { background-color: %1; }"
649 "QSplitter::handle:hover { background-color: %2; }"
650 "QSplitter::handle:pressed { background-color: %3; }")
651 .arg(c.border.name())
652 .arg(c.accent.darker(120).name())
653 .arg(c.accent.name()));
654 mainLayout->addWidget(mainSplitter_);
655
656 // Setup components (creates the raw content widgets)
657 setupSidebar();
658 setupGameList();
659
660 // Build the details panel via the dedicated manager (MED-7 extraction).
661 // Widget tree + rendering logic all live in DetailsPanelManager; the
662 // raw alias keeps splitter/layout wiring unchanged.
663 detailsPanelManager_ = std::make_unique<DetailsPanelManager>(
664 this, libraryController_.get(), launchController_.get(), imageCache_.get(),
665 &ThemeManager::instance(), this);
666 detailsPanel_ = detailsPanelManager_->widget();
667
668 // Wire manager signals to MainWindow slots / update paths
669 connect(detailsPanelManager_.get(), &DetailsPanelManager::launchRequested, this,
670 [this](const std::string& /*gameId*/) { onLaunchClicked(); });
671 connect(detailsPanelManager_.get(), &DetailsPanelManager::stopRequested, this,
672 [this](const std::string& /*gameId*/) { onStopClicked(); });
673 connect(detailsPanelManager_.get(), &DetailsPanelManager::configureRequested, this,
674 [this](const std::string& gameId)
675 {
676 if (gameId.empty())
677 return;
678 Game* game = libraryController_->getGameForEdit(gameId);
679 if (!game)
680 return;
681 GameConfigDialog dialog(game, this);
682 if (dialog.exec() == QDialog::Accepted)
683 {
684 libraryController_->updateGame(gameId, *game);
685 detailsPanelManager_->update(gameId);
686 }
687 });
688 connect(detailsPanelManager_.get(), &DetailsPanelManager::gameChanged, this,
689 [this](const std::string& gameId)
690 {
691 scheduleRefresh();
692 if (!gameId.empty())
693 updateGameRow(gameId);
694 });
695
696 // Wrap panels in containers with title bars for move/pop-out controls
697 sidebarContainer_ = createPanelContainer(sidebar_, "Sidebar", poppedSidebar_, 250, 600);
698 gameListContainer_ = createPanelContainer(gameList_, "Games", poppedGameList_, 400, 700);
699 detailsContainer_ = createPanelContainer(detailsPanel_, "Details", poppedDetails_, 450, 700);
700
701 // Set minimum sizes for containers to prevent over-shrinking
702 sidebarContainer_->setMinimumWidth(120);
703 gameListContainer_->setMinimumWidth(200);
704 detailsContainer_->setMinimumWidth(250);
705
706#ifdef HAVE_QTERMWIDGET
707 // Create terminal panel (hidden by default, can be shown alongside other panels)
708 terminalPanel_ = new TerminalPanel(this);
709 terminalContainer_ =
710 createPanelContainer(terminalPanel_, "System Monitor", poppedMonitor_, 800, 600);
711 terminalContainer_->setVisible(false);
712 terminalContainer_->setMinimumWidth(300); // Terminal needs more space
713#endif
714
715#ifdef HAVE_WEBENGINE
716 // Create Home Assistant panel (visibility restored from saved state below)
717 haPanel_ = new HomeAssistantPanel(this);
718 haContainer_ = createPanelContainer(haPanel_, "Home Assistant", poppedHA_, 900, 700);
719 haContainer_->setMinimumWidth(400); // Web content needs space
720 // Hide container title bar — HA panel has its own nav bar
721 if (auto* titleBar = haContainer_->findChild<QWidget*>("panelTitleBar"))
722 titleBar->setVisible(false);
723#endif
724
725 // Add all panel containers to the main splitter
726 mainSplitter_->addWidget(sidebarContainer_);
727 mainSplitter_->addWidget(gameListContainer_);
728 mainSplitter_->addWidget(detailsContainer_);
729#ifdef HAVE_QTERMWIDGET
730 mainSplitter_->addWidget(terminalContainer_);
731#endif
732#ifdef HAVE_WEBENGINE
733 mainSplitter_->addWidget(haContainer_);
734#endif
735
736 // Restore saved panel state or use defaults
737 {
738 auto appSettings = settingsController_->getAppSettings();
739
740 // Restore panel visibility
741 if (sidebarContainer_)
742 sidebarContainer_->setVisible(appSettings.panelSidebarVisible);
743 if (gameListContainer_)
744 gameListContainer_->setVisible(appSettings.panelGamesVisible);
745 if (detailsContainer_)
746 detailsContainer_->setVisible(appSettings.panelDetailsVisible);
747#ifdef HAVE_QTERMWIDGET
748 if (terminalContainer_)
749 {
750 terminalContainer_->setVisible(appSettings.panelMonitorVisible);
751 if (appSettings.panelMonitorVisible && terminalPanel_)
752 terminalPanel_->startCommand("btop");
753 }
754#endif
755#ifdef HAVE_WEBENGINE
756 if (haContainer_)
757 {
758 haContainer_->setVisible(appSettings.panelHAVisible);
759 if (appSettings.panelHAVisible && haPanel_)
760 haPanel_->loadDashboard();
761 }
762#endif
763
764 // Restore splitter sizes if saved, otherwise use defaults
765 if (!appSettings.splitterSizes.empty())
766 {
767 QList<int> sizes;
768 for (const auto& s : QString::fromStdString(appSettings.splitterSizes).split(","))
769 {
770 bool ok;
771 int val = s.toInt(&ok);
772 if (ok)
773 sizes.append(val);
774 }
775 if (sizes.size() == mainSplitter_->count())
776 mainSplitter_->setSizes(sizes);
777 else
778 mainSplitter_->setSizes({200, 700, 400});
779 }
780 else
781 {
782 mainSplitter_->setSizes({200, 700, 400});
783 }
784 }
785
786 // Debounce splitter moves to prevent expensive updates during drag
787 connect(mainSplitter_, &QSplitter::splitterMoved, this,
788 [this]()
789 {
790 // Only update details panel after splitter drag completes (debounced)
791 if (!resizeDebounceTimer_)
792 {
793 resizeDebounceTimer_ = new QTimer(this);
794 resizeDebounceTimer_->setSingleShot(true);
795 resizeDebounceTimer_->setInterval(150);
796 connect(resizeDebounceTimer_, &QTimer::timeout, this,
797 [this]()
798 {
799 // Update hero image when panel width changes (with caching)
800 if (!selectedGameId_.empty())
801 {
802 detailsPanelManager_->update(selectedGameId_);
803 }
804 });
805 }
806 resizeDebounceTimer_->start();
807 });
808}
809
810void MainWindow::setupMenuBar()
811{
812 // Shared per-game action factory — used by both the menu-bar Game
813 // menu (via MenuBarManager) and the game-list context menu (inline in
814 // setupGameList). Created before MenuBarManager so we can pass it in.
815 gameActionFactory_ = std::make_unique<GameActionFactory>(
816 this, libraryController_.get(), launchController_.get(), detailsPanelManager_.get(),
817 imageCache_.get(), &ThemeManager::instance());
818
819 // Menu construction lives in MenuBarManager (extracted 2026-04-19).
820 // MainWindow constructs the manager, connects its semantic signals to
821 // existing slots, and installs the small functors the dynamic menus
822 // need (panel visibility, selected game id).
823 menuBarManager_ = std::make_unique<MenuBarManager>(
824 this, libraryController_.get(), launchController_.get(), settingsController_.get(),
825 detailsPanelManager_.get(), imageCache_.get(), gameActionFactory_.get(),
827 menuBarManager_->setupMenus();
828
829 // Panel visibility query — used by the View menu's aboutToShow handler.
830 menuBarManager_->setPanelVisibilityQuery(
831 [this](const QString& name) -> bool
832 {
833 if (name == QLatin1String("sidebar"))
834 return sidebarContainer_ && sidebarContainer_->isVisible();
835 if (name == QLatin1String("games"))
836 return gameListContainer_ && gameListContainer_->isVisible();
837 if (name == QLatin1String("details"))
838 return detailsContainer_ && detailsContainer_->isVisible();
839#ifdef HAVE_QTERMWIDGET
840 if (name == QLatin1String("monitor"))
841 return terminalContainer_ && terminalContainer_->isVisible();
842#endif
843#ifdef HAVE_WEBENGINE
844 if (name == QLatin1String("ha"))
845 return haContainer_ && haContainer_->isVisible();
846#endif
847 return false;
848 });
849
850 MenuBarManager* mm = menuBarManager_.get();
851
852 // Shared signals (same semantic names ToolbarManager uses — MainWindow's
853 // existing slots already handle these).
854 connect(mm, &MenuBarManager::addGameRequested, this, &MainWindow::onAddGameClicked);
855 connect(mm, &MenuBarManager::settingsRequested, this, &MainWindow::onSettingsClicked);
856 connect(mm, &MenuBarManager::refreshLibraryRequested, this, &MainWindow::onRefreshLibrary);
857
858 connect(mm, &MenuBarManager::importGamesRequested, this,
859 [this]()
860 {
861 GameImportDialog dialog(libraryController_.get(), this);
862 if (dialog.exec() == QDialog::Accepted)
863 {
865 libraryController_->getAllGames(),
866 [this](const std::string& gameId, const std::function<void(Game&)>& updater)
867 { libraryController_->executeWithGame(gameId, updater); });
868 updateSourceFilters();
869 updateCategoryCounts();
870 refreshGameList();
871 QTimer::singleShot(500, this, [this]() { fetchMissingProtonDB(); });
872 }
873 });
874
876 [this]()
877 {
878 LutrisSearchDialog searchDialog(libraryController_.get(), this);
879 connect(&searchDialog, &LutrisSearchDialog::installRequested, this,
880 [this](const LutrisInstallerScript& script)
881 {
882 LutrisInstallPreviewDialog previewDialog(script, this);
883 if (previewDialog.exec() == QDialog::Accepted)
884 {
885 InstallConfig config = previewDialog.getInstallConfig();
886 LutrisInstallerScript scriptCopy = previewDialog.getScript();
887 LutrisInstallProgressDialog progressDialog(
888 scriptCopy, config, libraryController_.get(), this);
889 if (progressDialog.exec() == QDialog::Accepted)
890 {
892 libraryController_->getAllGames(),
893 [this](const std::string& gameId,
894 const std::function<void(Game&)>& updater)
895 { libraryController_->executeWithGame(gameId, updater); });
896 updateSourceFilters();
897 updateCategoryCounts();
898 refreshGameList();
899 }
900 }
901 });
902 searchDialog.exec();
903 });
904
905 connect(mm, &MenuBarManager::exportImportRequested, this,
906 [this]()
907 {
908 LibraryExportDialog dialog(this);
909 dialog.setController(libraryController_.get());
910 if (dialog.exec() == QDialog::Accepted)
911 {
912 refreshGameList();
913 updateSourceFilters();
914 updateCategoryCounts();
915 }
916 });
917
919 [this]()
920 {
921 RunnerManagerDialog dialog(this);
922 dialog.exec();
923 populateRunnerVersions();
924 });
925
927 [this]()
928 {
929 GameStatisticsDialog dialog(this);
930 auto filteredGames = libraryController_->getFilteredGames();
931 std::vector<Game*> games;
932 games.reserve(filteredGames.size());
933 for (const Game* g : filteredGames)
934 games.push_back(const_cast<Game*>(g));
935 dialog.setGames(games);
936 dialog.exec();
937 });
938
940 [this]()
941 {
942 DownloadQueueDialog dialog(steamDownloadMonitor_.get(), libraryController_.get(),
943 this);
944 dialog.exec();
945 });
946
947 connect(mm, &MenuBarManager::exitRequested, this,
948 [this]()
949 {
950 forceQuit_ = true;
951 close();
952 });
953
954 connect(mm, &MenuBarManager::themeSelected, this,
955 [this](const QString& themeId)
956 {
959 settingsController_->saveSettings();
960 });
961
962 // Game-menu per-selection actions. launchRequested/stopRequested are
963 // forwarded from the GameActionFactory which the MenuBarManager uses;
964 // the factory already mutates state for favoriteChanged, so MainWindow
965 // only needs to refresh.
966 connect(mm, &MenuBarManager::launchRequested, this,
967 [this](const std::string&) { onLaunchClicked(); });
968 connect(mm, &MenuBarManager::stopRequested, this,
969 [this](const std::string&) { onStopClicked(); });
970 connect(mm, &MenuBarManager::favoriteChanged, this,
971 [this](const std::string&) { refreshGameList(); });
972 connect(mm, &MenuBarManager::removeGameRequested, this,
973 [this](const std::string&) { deleteSelectedGame(); });
974 connect(mm, &MenuBarManager::artworkChanged, this,
975 [this](const std::string&)
976 {
977 invalidateGameItemCache();
978 refreshGameList();
979 });
980
981 // View-menu state propagation.
982 connect(mm, &MenuBarManager::viewModeSelected, this, &MainWindow::onViewModeChanged);
983 connect(mm, &MenuBarManager::sortSelected, this,
984 [this](SortOption opt)
985 {
986 // Route through the toolbar's sort combo so the UI stays
987 // consistent. ToolbarManager emits sortChanged which MainWindow
988 // forwards to onSortChanged.
989 if (sortCombo_)
990 {
991 for (int i = 0; i < sortCombo_->count(); ++i)
992 {
993 if (sortCombo_->itemData(i).toInt() == static_cast<int>(opt))
994 {
995 sortCombo_->setCurrentIndex(i);
996 break;
997 }
998 }
999 }
1000 });
1001
1002 // Panel toggles — reuse the name-based dispatch already connected for
1003 // ToolbarManager.
1004 connect(mm, &MenuBarManager::panelToggleRequested, this,
1005 [this](const QString& name)
1006 {
1007 if (name == QLatin1String("sidebar"))
1008 togglePanel(sidebarContainer_, panelSidebarBtn_, "Sidebar");
1009 else if (name == QLatin1String("games"))
1010 togglePanel(gameListContainer_, panelGamesBtn_, "Games");
1011 else if (name == QLatin1String("details"))
1012 togglePanel(detailsContainer_, panelDetailsBtn_, "Details");
1013#ifdef HAVE_QTERMWIDGET
1014 else if (name == QLatin1String("monitor"))
1015 {
1016 const bool willShow = terminalContainer_ && !terminalContainer_->isVisible();
1017 togglePanel(terminalContainer_, panelMonitorBtn_, "Monitor");
1018 if (willShow && terminalPanel_)
1019 terminalPanel_->startCommand("btop");
1020 }
1021#endif
1022#ifdef HAVE_WEBENGINE
1023 else if (name == QLatin1String("ha"))
1024 {
1025 const bool willShow = haContainer_ && !haContainer_->isVisible();
1026 togglePanel(haContainer_, panelHABtn_, "Home Assistant");
1027 if (willShow && haPanel_)
1028 haPanel_->loadDashboard();
1029 }
1030#endif
1031 });
1032
1033 // Zoom — drive the toolbar's slider.
1034 connect(mm, &MenuBarManager::zoomInRequested, this,
1035 [this]()
1036 {
1037 if (zoomSlider_)
1038 zoomSlider_->setValue(qMin(zoomSlider_->maximum(), zoomSlider_->value() + 10));
1039 });
1040 connect(mm, &MenuBarManager::zoomOutRequested, this,
1041 [this]()
1042 {
1043 if (zoomSlider_)
1044 zoomSlider_->setValue(qMax(zoomSlider_->minimum(), zoomSlider_->value() - 10));
1045 });
1046 connect(mm, &MenuBarManager::zoomResetRequested, this,
1047 [this]()
1048 {
1049 if (zoomSlider_)
1050 zoomSlider_->setValue(100);
1051 });
1052
1053 connect(mm, &MenuBarManager::menuModeToggled, this, [this](bool) { updateMenuMode(); });
1054
1055 // Refresh notifications from MenuBarManager-internal mutations.
1056 connect(mm, &MenuBarManager::gameConfigUpdated, this,
1057 [this](const std::string& gameId) { updateGameRow(gameId); });
1058 connect(mm, &MenuBarManager::gameListChanged, this,
1059 [this]()
1060 {
1061 updateCollectionsList();
1062 refreshGameList();
1063 });
1064 connect(mm, &MenuBarManager::runnersListChanged, this, &MainWindow::populateRunnerVersions);
1065 // artworkChanged is wired above in the per-selection block.
1066 connect(mm, &MenuBarManager::commandPaletteRequested, this,
1067 [this]()
1068 {
1069 if (commandPalette_)
1070 commandPalette_->showPalette();
1071 });
1072}
1073
1074// ==============================================================================
1075// Panel Management Helpers
1076// ==============================================================================
1077
1078void MainWindow::togglePanel(QWidget* panel, QPushButton* btn, const QString& /*name*/)
1079{
1080 if (!panel)
1081 return;
1082
1083 // If user manually toggles a panel while in gaming layout, mark as overridden
1084 // This prevents auto-restore when the game exits
1085 if (isInGamingLayout_)
1086 {
1087 Logger::info("[MainWindow] User manually toggled panel during gaming layout - marking as "
1088 "overridden");
1089 gamingLayoutOverridden_ = true;
1090 isInGamingLayout_ = false; // Exit gaming layout mode
1091
1092 // Reset min/max constraints on all panels so user can resize freely
1093 if (sidebarContainer_)
1094 {
1095 sidebarContainer_->setMinimumWidth(120);
1096 sidebarContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
1097 }
1098 if (gameListContainer_)
1099 {
1100 gameListContainer_->setMinimumWidth(200);
1101 gameListContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
1102 }
1103 if (detailsContainer_)
1104 {
1105 detailsContainer_->setMinimumWidth(250);
1106 detailsContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
1107 }
1108#ifdef HAVE_QTERMWIDGET
1109 if (terminalContainer_)
1110 {
1111 terminalContainer_->setMinimumWidth(300);
1112 terminalContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
1113 }
1114#endif
1115#ifdef HAVE_WEBENGINE
1116 if (haContainer_)
1117 {
1118 haContainer_->setMinimumWidth(400);
1119 haContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
1120 }
1121#endif
1122 }
1123
1124 bool newVisible = !panel->isVisible();
1125 panel->setVisible(newVisible);
1126 if (btn)
1127 btn->setChecked(newVisible);
1128
1129#ifdef HAVE_QTERMWIDGET
1130 // Pause/resume terminal process when panel visibility changes to save CPU
1131 if (terminalContainer_ && panel == terminalContainer_ && terminalPanel_)
1132 {
1133 if (newVisible)
1134 terminalPanel_->resumeProcess();
1135 else
1136 terminalPanel_->pauseProcess();
1137 }
1138#endif
1139
1140 // Defer toolbar update to ensure visibility state is fully applied
1141 QTimer::singleShot(0, this, &MainWindow::updateToolbarVisibility);
1142
1143 // When showing a panel, ensure it gets a reasonable size in the splitter
1144 if (newVisible && mainSplitter_)
1145 {
1146 int panelIndex = mainSplitter_->indexOf(panel);
1147 if (panelIndex >= 0)
1148 {
1149 QList<int> sizes = mainSplitter_->sizes();
1150 // If the panel has 0 or very small size, give it a reasonable default
1151 if (panelIndex < sizes.size() && sizes[panelIndex] < 50)
1152 {
1153 // Calculate a fair share - take space proportionally from visible panels
1154 int totalWidth = 0;
1155 int visibleCount = 0;
1156 for (int i = 0; i < mainSplitter_->count(); ++i)
1157 {
1158 if (mainSplitter_->widget(i)->isVisible())
1159 {
1160 totalWidth += sizes[i];
1161 visibleCount++;
1162 }
1163 }
1164
1165 // Give the new panel about 1/4 of the total width, min 300px
1166 int newPanelSize = qMax(300, totalWidth / 4);
1167
1168 // Reduce other visible panels proportionally
1169 if (totalWidth > newPanelSize && visibleCount > 1)
1170 {
1171 double scale = static_cast<double>(totalWidth - newPanelSize) / totalWidth;
1172 for (int i = 0; i < sizes.size(); ++i)
1173 {
1174 if (i == panelIndex)
1175 {
1176 sizes[i] = newPanelSize;
1177 }
1178 else if (mainSplitter_->widget(i)->isVisible())
1179 {
1180 sizes[i] = static_cast<int>(sizes[i] * scale);
1181 }
1182 }
1183 mainSplitter_->setSizes(sizes);
1184 }
1185 }
1186 }
1187 }
1188}
1189
1190void MainWindow::popOutPanel(QWidget* panel, QWidget*& poppedWindow, const QString& title,
1191 int width, int height)
1192{
1193 if (!panel)
1194 return;
1195
1196 // If already popped out, bring to front
1197 if (poppedWindow)
1198 {
1199 poppedWindow->raise();
1200 poppedWindow->activateWindow();
1201 return;
1202 }
1203
1204 // Find the container that holds this panel
1205 QWidget* container = nullptr;
1206 if (panel == sidebar_)
1207 container = sidebarContainer_;
1208 else if (panel == gameList_)
1209 container = gameListContainer_;
1210 else if (panel == detailsPanel_)
1211 container = detailsContainer_;
1212#ifdef HAVE_QTERMWIDGET
1213 else if (panel == terminalPanel_)
1214 container = terminalContainer_;
1215#endif
1216#ifdef HAVE_WEBENGINE
1217 else if (panel == haPanel_)
1218 container = haContainer_;
1219#endif
1220
1221 // Hide the container in the main splitter
1222 if (container)
1223 {
1224 container->setVisible(false);
1225 }
1226
1227 // Create pop-out window
1228 poppedWindow = new QWidget(nullptr, Qt::Window);
1229 poppedWindow->setWindowTitle(title + " - Game Launcher");
1230 poppedWindow->resize(width, height);
1231 poppedWindow->setAttribute(Qt::WA_DeleteOnClose);
1232
1233 QVBoxLayout* layout = new QVBoxLayout(poppedWindow);
1234 layout->setContentsMargins(0, 0, 0, 0);
1235
1236 // Reparent the panel to the pop-out window
1237 panel->setParent(poppedWindow);
1238 panel->setVisible(true);
1239 layout->addWidget(panel);
1240
1241 // When pop-out window closes, return panel to its container
1242 connect(poppedWindow, &QWidget::destroyed, this,
1243 [this, panel, container, &poppedWindow]()
1244 {
1245 poppedWindow = nullptr;
1246
1247 if (container)
1248 {
1249 // Return panel to its container
1250 QVBoxLayout* containerLayout = qobject_cast<QVBoxLayout*>(container->layout());
1251 if (containerLayout)
1252 {
1253 panel->setParent(container);
1254 containerLayout->addWidget(panel, 1); // Add with stretch factor
1255 panel->setVisible(true);
1256 container->setVisible(true);
1257 }
1258 }
1259 else
1260 {
1261 // Fallback: add directly to splitter
1262 panel->setParent(this);
1263 mainSplitter_->addWidget(panel);
1264 panel->setVisible(true);
1265 }
1266 updateToolbarVisibility();
1267 });
1268
1269 poppedWindow->show();
1270 updateToolbarVisibility();
1271}
1272
1273void MainWindow::updateMenuMode()
1274{
1275 QSettings settings;
1276 bool useHamburger = settings.value("ui/useHamburgerMenu", false).toBool();
1277
1278 // Toggle menu bar visibility
1279 menuBar()->setVisible(!useHamburger);
1280
1281 // Toggle hamburger button visibility
1282 if (toolbarManager_)
1283 {
1284 if (auto* btn = toolbarManager_->hamburgerButton())
1285 btn->setVisible(useHamburger);
1286 }
1287}
1288
1289void MainWindow::updateToolbarVisibility()
1290{
1291 // Game controls need games list visible (search, sort, view mode, zoom all apply to game list)
1292 bool gamesListVisible = gameListContainer_ && gameListContainer_->isVisible();
1293
1294 // Show/hide game controls section
1295 if (draggableToolbar_)
1296 {
1297 if (auto* gameControlsSection = draggableToolbar_->section("gameControls"))
1298 gameControlsSection->setVisible(gamesListVisible);
1299 }
1300
1301#ifdef HAVE_QTERMWIDGET
1302 // Show monitor controls only if monitor container is visible
1303 bool monitorVisible = terminalContainer_ && terminalContainer_->isVisible();
1304
1305 // Show/hide monitor section
1306 if (draggableToolbar_)
1307 {
1308 if (auto* monitorSection = draggableToolbar_->section("monitor"))
1309 monitorSection->setVisible(monitorVisible);
1310 }
1311
1312 // Update panel button states
1313 if (panelMonitorBtn_)
1314 panelMonitorBtn_->setChecked(monitorVisible);
1315#endif
1316
1317 // Update panel toggle button states
1318 if (panelSidebarBtn_)
1319 panelSidebarBtn_->setChecked(sidebarContainer_ && sidebarContainer_->isVisible());
1320 if (panelGamesBtn_)
1321 panelGamesBtn_->setChecked(gameListContainer_ && gameListContainer_->isVisible());
1322 if (panelDetailsBtn_)
1323 panelDetailsBtn_->setChecked(detailsContainer_ && detailsContainer_->isVisible());
1324#ifdef HAVE_WEBENGINE
1325 if (panelHABtn_)
1326 panelHABtn_->setChecked(haContainer_ && haContainer_->isVisible());
1327#endif
1328
1329 // Update status bar - only show game info if games list is visible
1330 if (statusLabel_)
1331 {
1332 if (gamesListVisible)
1333 {
1334 // Show game count and view mode
1335 QString viewName;
1336 switch (currentViewMode_)
1337 {
1338 case ViewMode::List:
1339 viewName = "List";
1340 break;
1341 case ViewMode::Grid:
1342 viewName = "Grid";
1343 break;
1344 case ViewMode::Compact:
1345 viewName = "Compact";
1346 break;
1347 }
1348 int totalGames =
1349 libraryController_ ? static_cast<int>(libraryController_->getGameCount()) : 0;
1350 int visibleGames = gameListProxy_ ? gameListProxy_->rowCount() : 0;
1351 statusLabel_->setText(QString("Games: %1 (showing %2) | %3 view")
1352 .arg(totalGames)
1353 .arg(visibleGames)
1354 .arg(viewName));
1355 }
1356 else
1357 {
1358 statusLabel_->setText("Ready");
1359 }
1360 }
1361}
1362
1363void MainWindow::updateRunningGameStatus()
1364{
1365 if (!runningGameStatusWidget_)
1366 {
1367 Logger::debug("[RunningStatus] Widget is null");
1368 return;
1369 }
1370
1371 // Check if feature is enabled in settings
1372 bool featureEnabled =
1373 settingsController_ && settingsController_->getAppSettings().showToolbarGameStatus;
1374
1375 // Find any running game
1376 std::string runningGameId;
1377 const Game* runningGame = nullptr;
1378
1379 // Check if selected game is running first
1380 if (!selectedGameId_.empty() && launchController_->isGameRunning(selectedGameId_))
1381 {
1382 runningGameId = selectedGameId_;
1383 runningGame = libraryController_->getGame(runningGameId);
1384 }
1385 else
1386 {
1387 // Find any running game from our library
1388 for (const auto* game : libraryController_->getAllGames())
1389 {
1390 if (launchController_->isGameRunning(game->id))
1391 {
1392 runningGameId = game->id;
1393 runningGame = game;
1394 break;
1395 }
1396 }
1397 }
1398
1399 // Detect game start/stop transitions for gaming layout management
1400 if (runningGameId != previousRunningGameId_)
1401 {
1402 if (!runningGameId.empty() && previousRunningGameId_.empty())
1403 {
1404 // Game just started
1405 onGameStarted(runningGameId);
1406 }
1407 else if (runningGameId.empty() && !previousRunningGameId_.empty())
1408 {
1409 // Game just stopped
1410 onGameStopped(previousRunningGameId_);
1411 }
1412 previousRunningGameId_ = runningGameId;
1413 }
1414
1415 // Show when enabled and a game is running
1416 bool shouldShow = featureEnabled && runningGame != nullptr;
1417
1418 // Debug: Log visibility decision
1419 static bool lastShouldShow = false;
1420 if (shouldShow != lastShouldShow)
1421 {
1422 Logger::info("[RunningStatus] featureEnabled={}, runningGame={}, shouldShow={}",
1423 featureEnabled, runningGame ? runningGame->name : "null", shouldShow);
1424 lastShouldShow = shouldShow;
1425 }
1426
1427 if (!shouldShow)
1428 {
1429 runningGameStatusWidget_->clear();
1430 runningGameStatusWidget_->setVisible(false);
1431 if (draggableToolbar_)
1432 {
1433 if (auto* runningSection = draggableToolbar_->section("running"))
1434 runningSection->setVisible(false);
1435 }
1436 return;
1437 }
1438
1439 // Get session duration
1440 auto duration = launchController_->getSessionDuration(runningGameId);
1441 int runningSeconds = static_cast<int>(duration.count());
1442
1443 // Get frame metrics
1444 auto frameMetrics = FrameMetricsService::instance().getMetrics(runningGameId);
1445
1446 // Get tracked process name (for launcher games like Battle.net → WoWClassic.exe)
1447 QString trackedProcessName;
1448 const auto* process = GameProcessManager::instance().getRunningProcess(runningGameId);
1449 if (process)
1450 {
1451 std::string trackedName = process->getTrackedProcessName();
1452 if (!trackedName.empty())
1453 {
1454 trackedProcessName = QString::fromStdString(trackedName);
1455 }
1456 }
1457
1458 // Update the widget
1459 runningGameStatusWidget_->updateStatus(
1460 QString::fromStdString(runningGameId), QString::fromStdString(runningGame->name),
1461 runningSeconds, frameMetrics.fps, frameMetrics.frametime_ms, frameMetrics.frametimeHistory,
1462 trackedProcessName);
1463
1464 // Build optimization list for tooltip
1465 QStringList optimizations;
1466 if (runningGame->runnerConfig.enableMangoHud)
1467 optimizations << "MangoHud";
1468 if (runningGame->runnerConfig.enableGameMode)
1469 optimizations << "GameMode";
1470 if (runningGame->runnerConfig.enableGamePerformance)
1471 optimizations << "game-performance";
1472 if (runningGame->runnerConfig.enableVkBasalt)
1473 optimizations << "VkBasalt";
1474 if (runningGame->runnerConfig.enableFsync)
1475 optimizations << "Fsync";
1476
1477 QString runner;
1478 switch (runningGame->runner)
1479 {
1480 case GameRunner::Native:
1481 runner = "Native";
1482 break;
1483 case GameRunner::Wine:
1484 runner = "Wine";
1485 break;
1486 case GameRunner::Proton:
1487 runner = "Proton";
1488 break;
1489 default:
1490 runner = "Unknown";
1491 break;
1492 }
1493
1494 QString protonVersion;
1495 if (runningGame->runner == GameRunner::Proton)
1496 {
1497 // Try to get the Proton version from the config first
1498 if (!runningGame->runnerConfig.protonVersion.empty() &&
1499 runningGame->runnerConfig.protonVersion != "Proton (Steam-managed)")
1500 {
1501 protonVersion = QString::fromStdString(runningGame->runnerConfig.protonVersion);
1502 }
1503 // If still empty/placeholder and it's a Steam game, try to read from Steam config
1504 else if (runningGame->metadata.isSteamGame && runningGame->metadata.steamAppId > 0)
1505 {
1506 std::string steamProtonVersion = SteamLibraryScanner::readSteamProtonVersion(
1507 static_cast<uint32_t>(runningGame->metadata.steamAppId));
1508 if (!steamProtonVersion.empty())
1509 {
1510 protonVersion = QString::fromStdString(steamProtonVersion);
1511 }
1512 }
1513 }
1514
1515 runningGameStatusWidget_->setLaunchInfo(optimizations, runner, protonVersion);
1516 runningGameStatusWidget_->setVisible(true);
1517 if (draggableToolbar_)
1518 {
1519 if (auto* runningSection = draggableToolbar_->section("running"))
1520 runningSection->setVisible(true);
1521 }
1522}
1523
1524// ==============================================================================
1525// Panel Container Helper (wraps panels with title bars)
1526// ==============================================================================
1527
1528QWidget* MainWindow::createPanelContainer(QWidget* content, const QString& title,
1529 QWidget*& poppedWindow, int popWidth, int popHeight)
1530{
1531 const ThemeColors& c = ThemeManager::instance().colors();
1532
1533 // Create container
1534 QWidget* container = new QWidget(this);
1535 QVBoxLayout* layout = new QVBoxLayout(container);
1536 layout->setContentsMargins(0, 0, 0, 0);
1537 layout->setSpacing(0);
1538
1539 // Create title bar
1540 QWidget* titleBar = new QWidget(container);
1541 titleBar->setObjectName("panelTitleBar"); // For theme updates
1542 titleBar->setFixedHeight(24);
1543 titleBar->setStyleSheet(
1544 QString("QWidget#panelTitleBar { background-color: %1; border-bottom: 1px solid %2; }")
1545 .arg(c.cardBackground.darker(105).name())
1546 .arg(c.border.name()));
1547
1548 QHBoxLayout* titleLayout = new QHBoxLayout(titleBar);
1549 titleLayout->setContentsMargins(8, 0, 4, 0);
1550 titleLayout->setSpacing(2);
1551
1552 // Title label
1553 QLabel* titleLabel = new QLabel(title, titleBar);
1554 titleLabel->setObjectName("panelTitleLabel"); // For theme updates
1555 titleLabel->setStyleSheet(QString("QLabel { color: %1; font-size: 11px; font-weight: bold; "
1556 "background: transparent; border: none; }")
1557 .arg(c.textSecondary.name()));
1558 titleLayout->addWidget(titleLabel);
1559
1560 titleLayout->addStretch();
1561
1562 // Button style - compact
1563 QString btnStyle =
1564 QString("QPushButton { background: transparent; color: %1; border: none; padding: 2px 4px; "
1565 "font-size: 11px; border-radius: 2px; }"
1566 "QPushButton:hover { background-color: %2; color: %3; }"
1567 "QPushButton:pressed { background-color: %4; color: %5; }")
1568 .arg(c.textSecondary.name())
1569 .arg(c.hoverBackground.name())
1570 .arg(c.textPrimary.name())
1571 .arg(c.accent.name())
1572 .arg(c.textOnAccent.name());
1573
1574 // Move left button
1575 QPushButton* moveLeftBtn = new QPushButton("◀", titleBar);
1576 moveLeftBtn->setObjectName("panelTitleBtn"); // For theme updates
1577 moveLeftBtn->setFixedSize(20, 18);
1578 moveLeftBtn->setToolTip("Move panel left");
1579 moveLeftBtn->setStyleSheet(btnStyle);
1580 connect(moveLeftBtn, &QPushButton::clicked, this,
1581 [this, container]() { movePanelLeft(container); });
1582 titleLayout->addWidget(moveLeftBtn);
1583
1584 // Move right button
1585 QPushButton* moveRightBtn = new QPushButton("▶", titleBar);
1586 moveRightBtn->setObjectName("panelTitleBtn"); // For theme updates
1587 moveRightBtn->setFixedSize(20, 18);
1588 moveRightBtn->setToolTip("Move panel right");
1589 moveRightBtn->setStyleSheet(btnStyle);
1590 connect(moveRightBtn, &QPushButton::clicked, this,
1591 [this, container]() { movePanelRight(container); });
1592 titleLayout->addWidget(moveRightBtn);
1593
1594 // Separator
1595 QFrame* sep = new QFrame(titleBar);
1596 sep->setObjectName("panelTitleSep"); // For theme updates
1597 sep->setFrameShape(QFrame::VLine);
1598 sep->setFixedWidth(1);
1599 sep->setStyleSheet(QString("background-color: %1;").arg(c.border.name()));
1600 titleLayout->addWidget(sep);
1601
1602 // Pop out button
1603 QPushButton* popOutBtn = new QPushButton("⧉", titleBar);
1604 popOutBtn->setObjectName("panelTitleBtn"); // For theme updates
1605 popOutBtn->setFixedSize(20, 18);
1606 popOutBtn->setToolTip("Pop out to separate window");
1607 popOutBtn->setStyleSheet(btnStyle);
1608 connect(popOutBtn, &QPushButton::clicked, this,
1609 [this, content, &poppedWindow, title, popWidth, popHeight]()
1610 { popOutPanel(content, poppedWindow, title, popWidth, popHeight); });
1611 titleLayout->addWidget(popOutBtn);
1612
1613 layout->addWidget(titleBar);
1614 layout->addWidget(content, 1); // Content takes remaining space
1615
1616 return container;
1617}
1618
1619void MainWindow::movePanelLeft(QWidget* container)
1620{
1621 if (!mainSplitter_ || !container)
1622 return;
1623
1624 int idx = mainSplitter_->indexOf(container);
1625 if (idx > 0)
1626 {
1627 // Find the previous visible panel
1628 for (int i = idx - 1; i >= 0; --i)
1629 {
1630 QWidget* w = mainSplitter_->widget(i);
1631 if (w && w->isVisible())
1632 {
1633 // Swap positions by reinserting
1634 mainSplitter_->insertWidget(i, container);
1635 break;
1636 }
1637 }
1638 }
1639}
1640
1641void MainWindow::movePanelRight(QWidget* container)
1642{
1643 if (!mainSplitter_ || !container)
1644 return;
1645
1646 int idx = mainSplitter_->indexOf(container);
1647 if (idx >= 0 && idx < mainSplitter_->count() - 1)
1648 {
1649 // Find the next visible panel
1650 for (int i = idx + 1; i < mainSplitter_->count(); ++i)
1651 {
1652 QWidget* w = mainSplitter_->widget(i);
1653 if (w && w->isVisible())
1654 {
1655 // Swap positions by reinserting after
1656 mainSplitter_->insertWidget(i + 1, container);
1657 break;
1658 }
1659 }
1660 }
1661}
1662
1663// ==============================================================================
1664// Toolbar Setup
1665// ==============================================================================
1666
1667void MainWindow::setupToolBar()
1668{
1669 // Toolbar construction + input plumbing lives in ToolbarManager (extracted
1670 // from this file 2026-04-19). MainWindow only sets the manager up, grabs
1671 // raw widget aliases for cross-module code (keyboard shortcuts, command
1672 // palette, gaming-layout state machine), and wires the manager's signals
1673 // to the handlers that mutate MainWindow state.
1674 toolbarManager_ =
1675 std::make_unique<ToolbarManager>(this, libraryController_.get(), launchController_.get(),
1676 settingsController_.get(), &ThemeManager::instance());
1677 toolbarManager_->setupToolbar();
1678
1679 // Raw alias pointers — owned by ToolbarManager, kept here so existing
1680 // call sites compile unchanged.
1681 draggableToolbar_ = toolbarManager_->draggableToolbar();
1682 searchEdit_ = toolbarManager_->searchEdit();
1683 sortCombo_ = toolbarManager_->sortCombo();
1684 zoomSlider_ = toolbarManager_->zoomSlider();
1685 zoomLabel_ = toolbarManager_->zoomLabel();
1686 listViewAction_ = toolbarManager_->listViewAction();
1687 gridViewAction_ = toolbarManager_->gridViewAction();
1688 compactViewAction_ = toolbarManager_->compactViewAction();
1689 viewModeGroup_ = toolbarManager_->viewModeGroup();
1690 panelSidebarBtn_ = toolbarManager_->panelSidebarButton();
1691 panelGamesBtn_ = toolbarManager_->panelGamesButton();
1692 panelDetailsBtn_ = toolbarManager_->panelDetailsButton();
1693#ifdef HAVE_QTERMWIDGET
1694 panelMonitorBtn_ = toolbarManager_->panelMonitorButton();
1695 monitorTypeCombo_ = toolbarManager_->monitorTypeCombo();
1696 monitorRestartBtn_ = toolbarManager_->monitorRestartButton();
1697#endif
1698#ifdef HAVE_WEBENGINE
1699 panelHABtn_ = toolbarManager_->panelHAButton();
1700#endif
1701 runningGameStatusWidget_ = toolbarManager_->runningGameStatusWidget();
1702
1703 // ------------------------------------------------------------------------
1704 // Signal wiring
1705 // ------------------------------------------------------------------------
1706 ToolbarManager* tm = toolbarManager_.get();
1707
1708 // Input events — directly forwarded to the pre-existing slots. The
1709 // debounce timers live inside the manager now, so the slots are simpler
1710 // (no re-debounce on this side).
1711 connect(tm, &ToolbarManager::searchTextChanged, this, &MainWindow::onSearchTextChanged);
1712 connect(tm, &ToolbarManager::sortChanged, this, &MainWindow::onSortChanged);
1713 connect(tm, &ToolbarManager::zoomChanged, this, &MainWindow::onZoomChanged);
1714 connect(tm, &ToolbarManager::viewModeChanged, this, &MainWindow::onViewModeChanged);
1715
1716 // Menu actions — most map to existing MainWindow slots; the rest open
1717 // dialogs that need MainWindow-private state.
1718 connect(tm, &ToolbarManager::addGameRequested, this, &MainWindow::onAddGameClicked);
1719 connect(tm, &ToolbarManager::refreshLibraryRequested, this, &MainWindow::onRefreshLibrary);
1720 connect(tm, &ToolbarManager::settingsRequested, this, &MainWindow::onSettingsClicked);
1721
1722 connect(tm, &ToolbarManager::importGamesRequested, this,
1723 [this]()
1724 {
1725 GameImportDialog dialog(libraryController_.get(), this);
1726 if (dialog.exec() == QDialog::Accepted)
1727 {
1729 libraryController_->getAllGames(),
1730 [this](const std::string& gameId, const std::function<void(Game&)>& updater)
1731 { libraryController_->executeWithGame(gameId, updater); });
1732 updateSourceFilters();
1733 updateCategoryCounts();
1734 refreshGameList();
1735 QTimer::singleShot(500, this, [this]() { fetchMissingProtonDB(); });
1736 }
1737 });
1738
1740 [this]()
1741 {
1742 LutrisSearchDialog searchDialog(libraryController_.get(), this);
1743 connect(&searchDialog, &LutrisSearchDialog::installRequested, this,
1744 [this](const LutrisInstallerScript& script)
1745 {
1746 LutrisInstallPreviewDialog previewDialog(script, this);
1747 if (previewDialog.exec() == QDialog::Accepted)
1748 {
1749 InstallConfig config = previewDialog.getInstallConfig();
1750 LutrisInstallerScript scriptCopy = previewDialog.getScript();
1751 LutrisInstallProgressDialog progressDialog(
1752 scriptCopy, config, libraryController_.get(), this);
1753 if (progressDialog.exec() == QDialog::Accepted)
1754 {
1756 libraryController_->getAllGames(),
1757 [this](const std::string& gameId,
1758 const std::function<void(Game&)>& updater)
1759 { libraryController_->executeWithGame(gameId, updater); });
1760 updateSourceFilters();
1761 updateCategoryCounts();
1762 refreshGameList();
1763 }
1764 }
1765 });
1766 searchDialog.exec();
1767 });
1768
1769 connect(tm, &ToolbarManager::manageRunnersRequested, this,
1770 [this]()
1771 {
1772 RunnerManagerDialog dialog(this);
1773 dialog.exec();
1774 populateRunnerVersions();
1775 });
1776
1778 [this]()
1779 {
1780 GameStatisticsDialog dialog(this);
1781 auto filteredGames = libraryController_->getFilteredGames();
1782 std::vector<Game*> games;
1783 games.reserve(filteredGames.size());
1784 for (const Game* g : filteredGames)
1785 {
1786 games.push_back(const_cast<Game*>(g));
1787 }
1788 dialog.setGames(games);
1789 dialog.exec();
1790 });
1791
1792 connect(tm, &ToolbarManager::exportImportRequested, this,
1793 [this]()
1794 {
1795 LibraryExportDialog dialog(this);
1796 dialog.setController(libraryController_.get());
1797 if (dialog.exec() == QDialog::Accepted)
1798 {
1799 refreshGameList();
1800 updateSourceFilters();
1801 updateCategoryCounts();
1802 }
1803 });
1804
1805 connect(tm, &ToolbarManager::downloadQueueRequested, this,
1806 [this]()
1807 {
1808 DownloadQueueDialog dialog(steamDownloadMonitor_.get(), libraryController_.get(),
1809 this);
1810 dialog.exec();
1811 });
1812
1813 connect(tm, &ToolbarManager::exitRequested, this,
1814 [this]()
1815 {
1816 forceQuit_ = true;
1817 close();
1818 });
1819
1820 connect(tm, &ToolbarManager::themeSelected, this,
1821 [this](const QString& themeId)
1822 {
1825 settingsController_->saveSettings();
1826 });
1827
1828 // Panel toggle — map the name back to the correct container / button pair.
1829 connect(tm, &ToolbarManager::panelToggleRequested, this,
1830 [this](const QString& name)
1831 {
1832 if (name == QLatin1String("sidebar"))
1833 {
1834 togglePanel(sidebarContainer_, panelSidebarBtn_, "Sidebar");
1835 if (panelSidebarBtn_)
1836 panelSidebarBtn_->setChecked(sidebarContainer_ &&
1837 sidebarContainer_->isVisible());
1838 }
1839 else if (name == QLatin1String("games"))
1840 {
1841 togglePanel(gameListContainer_, panelGamesBtn_, "Games");
1842 if (panelGamesBtn_)
1843 panelGamesBtn_->setChecked(gameListContainer_ &&
1844 gameListContainer_->isVisible());
1845 }
1846 else if (name == QLatin1String("details"))
1847 {
1848 togglePanel(detailsContainer_, panelDetailsBtn_, "Details");
1849 if (panelDetailsBtn_)
1850 panelDetailsBtn_->setChecked(detailsContainer_ &&
1851 detailsContainer_->isVisible());
1852 }
1853#ifdef HAVE_QTERMWIDGET
1854 else if (name == QLatin1String("monitor"))
1855 {
1856 bool willShow = terminalContainer_ && !terminalContainer_->isVisible();
1857 togglePanel(terminalContainer_, panelMonitorBtn_, "Monitor");
1858 if (panelMonitorBtn_)
1859 panelMonitorBtn_->setChecked(terminalContainer_ &&
1860 terminalContainer_->isVisible());
1861 if (willShow && terminalPanel_)
1862 {
1863 QString command = "btop";
1864 if (monitorTypeCombo_)
1865 {
1866 switch (monitorTypeCombo_->currentIndex())
1867 {
1868 case 0:
1869 command = "btop";
1870 break;
1871 case 1:
1872 command = "htop";
1873 break;
1874 case 2:
1875 command = "top";
1876 break;
1877 case 3:
1878 {
1879 QString s = QString::fromLocal8Bit(qgetenv("SHELL"));
1880 command = s.isEmpty() ? QStringLiteral("/bin/bash") : s;
1881 break;
1882 }
1883 default:
1884 break;
1885 }
1886 }
1887 terminalPanel_->startCommand(command);
1888 }
1889 }
1890#endif
1891#ifdef HAVE_WEBENGINE
1892 else if (name == QLatin1String("ha"))
1893 {
1894 bool willShow = haContainer_ && !haContainer_->isVisible();
1895 togglePanel(haContainer_, panelHABtn_, "Home Assistant");
1896 if (panelHABtn_)
1897 panelHABtn_->setChecked(haContainer_ && haContainer_->isVisible());
1898 if (willShow && haPanel_)
1899 haPanel_->loadDashboard();
1900 }
1901#endif
1902 });
1903
1905 [this]()
1906 {
1907 if (detailsContainer_ && !detailsContainer_->isVisible())
1908 {
1909 detailsContainer_->setVisible(true);
1910 if (panelDetailsBtn_)
1911 panelDetailsBtn_->setChecked(true);
1912 }
1913 });
1914
1915#ifdef HAVE_QTERMWIDGET
1916 // Monitor combo / restart — the actual terminal-panel interaction lives
1917 // here because terminalPanel_ is a MainWindow-owned widget.
1918 connect(tm, &ToolbarManager::monitorCommandRequested, this,
1919 [this](const QString& cmd)
1920 {
1921 if (terminalPanel_ && terminalPanel_->isVisible())
1922 {
1923 terminalPanel_->startCommand("exit");
1924 QTimer::singleShot(200, this,
1925 [this, cmd]()
1926 {
1927 if (terminalPanel_)
1928 terminalPanel_->startCommand(cmd);
1929 });
1930 }
1931 });
1932 connect(tm, &ToolbarManager::monitorRestartRequested, this,
1933 [this]()
1934 {
1935 if (terminalPanel_ && monitorTypeCombo_)
1936 {
1937 QString cmd;
1938 switch (monitorTypeCombo_->currentIndex())
1939 {
1940 case 0:
1941 cmd = "btop";
1942 break;
1943 case 1:
1944 cmd = "htop";
1945 break;
1946 case 2:
1947 cmd = "top";
1948 break;
1949 case 3:
1950 {
1951 QString s = QString::fromLocal8Bit(qgetenv("SHELL"));
1952 cmd = s.isEmpty() ? QStringLiteral("/bin/bash") : s;
1953 break;
1954 }
1955 default:
1956 cmd = "btop";
1957 }
1958 terminalPanel_->startCommand("\x03");
1959 QTimer::singleShot(100, this,
1960 [this, cmd]()
1961 {
1962 if (terminalPanel_)
1963 terminalPanel_->startCommand(cmd);
1964 });
1965 }
1966 });
1967#endif
1968}
1969
1970void MainWindow::applyTheme()
1971{
1972 const ThemeColors& c = ThemeManager::instance().colors();
1973
1974 // Disable updates during batch stylesheet changes to avoid multiple repaints
1975 setUpdatesEnabled(false);
1976
1977 // Update delegate's cached colors
1978 if (gameListDelegate_)
1979 {
1980 gameListDelegate_->updateCachedColors();
1981 }
1982
1983 // Sidebar theming — delegated to SidebarManager (extracted 2026-04-19).
1984 if (sidebarManager_)
1985 {
1986 sidebarManager_->applyTheme();
1987 }
1988
1989 // Update game list
1990 if (gameList_)
1991 {
1992 gameList_->setStyleSheet(QString("QListView { background-color: %1; border: none; }")
1993 .arg(c.panelBackground.name()));
1994 // Force repaint of delegate items
1995 gameList_->viewport()->update();
1996 }
1997
1998 // Details panel styling — delegated to the panel manager (MED-7 extraction)
1999 if (detailsPanelManager_)
2000 {
2001 detailsPanelManager_->applyTheme();
2002 }
2003
2004 // Update status bar
2005 if (statusProgressBar_)
2006 {
2007 statusProgressBar_->setStyleSheet(
2008 QString("QProgressBar { background-color: %1; border: none; border-radius: 3px; }"
2009 "QProgressBar::chunk { background-color: %2; border-radius: 3px; }")
2010 .arg(c.cardBackground.name())
2011 .arg(c.success.name()));
2012 }
2013
2014 // Toolbar theming (hamburger menu, theme submenu, search, zoom, draggable
2015 // toolbar styling) is owned by ToolbarManager post-extraction.
2016 if (toolbarManager_)
2017 {
2018 toolbarManager_->applyTheme();
2019 }
2020
2021 if (trayMenu_)
2022 ThemeManager::instance().styleMenu(trayMenu_);
2023
2024 // Menu bar + its top-level menus are re-themed by MenuBarManager.
2025 if (menuBarManager_)
2026 {
2027 menuBarManager_->applyTheme();
2028 }
2029
2030 // Re-enable updates and trigger single repaint
2031 setUpdatesEnabled(true);
2032 update();
2033
2034 // (Toolbar styling is re-applied above via toolbarManager_->applyTheme().)
2035
2036 // Update panel title bars (found by object name)
2037 QString titleBarStyle =
2038 QString("QWidget#panelTitleBar { background-color: %1; border-bottom: 1px solid %2; }")
2039 .arg(c.cardBackground.darker(105).name())
2040 .arg(c.border.name());
2041 QString titleLabelStyle = QString("QLabel { color: %1; font-size: 11px; font-weight: bold; "
2042 "background: transparent; border: none; }")
2043 .arg(c.textSecondary.name());
2044 QString titleBtnStyle =
2045 QString("QPushButton { background: transparent; color: %1; border: none; padding: 2px 4px; "
2046 "font-size: 11px; border-radius: 2px; }"
2047 "QPushButton:hover { background-color: %2; color: %3; }"
2048 "QPushButton:pressed { background-color: %4; }")
2049 .arg(c.textMuted.name())
2050 .arg(c.hoverBackground.name())
2051 .arg(c.textPrimary.name())
2052 .arg(c.accent.name());
2053 QString titleSepStyle = QString("background-color: %1;").arg(c.border.name());
2054
2055 // Find and update all panel title bars
2056 for (QWidget* titleBar : findChildren<QWidget*>("panelTitleBar"))
2057 {
2058 titleBar->setStyleSheet(titleBarStyle);
2059 }
2060 for (QLabel* label : findChildren<QLabel*>("panelTitleLabel"))
2061 {
2062 label->setStyleSheet(titleLabelStyle);
2063 }
2064 for (QPushButton* btn : findChildren<QPushButton*>("panelTitleBtn"))
2065 {
2066 btn->setStyleSheet(titleBtnStyle);
2067 }
2068 for (QFrame* sep : findChildren<QFrame*>("panelTitleSep"))
2069 {
2070 sep->setStyleSheet(titleSepStyle);
2071 }
2072
2073 // Update splitter handle accent color
2074 if (mainSplitter_)
2075 {
2076 mainSplitter_->setStyleSheet(QString("QSplitter::handle { background-color: %1; }"
2077 "QSplitter::handle:hover { background-color: %2; }"
2078 "QSplitter::handle:pressed { background-color: %3; }")
2079 .arg(c.border.name())
2080 .arg(c.accent.darker(120).name())
2081 .arg(c.accent.name()));
2082 }
2083
2084 // (search bar / zoom slider / zoom label styling now handled by
2085 // toolbarManager_->applyTheme() above.)
2086
2087 // Update status bar label
2088 if (statusLabel_)
2089 {
2090 statusLabel_->setStyleSheet(QString("color: %1; padding: 0 8px;").arg(c.textMuted.name()));
2091 }
2092
2093 // Force status bar indicators to repaint with new theme colors.
2094 // StatusIndicator::paintEvent reads ThemeManager dynamically, so update() is sufficient.
2095 statusBar()->setStyleSheet(
2096 QString("QStatusBar { background-color: %1; border-top: 1px solid %2; }")
2097 .arg(c.panelBackground.name(), c.border.name()));
2098 statusBar()->update();
2099
2100 // Re-render details panel to update HTML content with new theme colors
2101 if (!selectedGameId_.empty())
2102 {
2103 detailsPanelManager_->update(selectedGameId_);
2104 }
2105}
2106
2107void MainWindow::setupSidebar()
2108{
2109 // Sidebar construction + filter helper methods live in SidebarManager
2110 // (extracted 2026-04-19, migrated to QListView + QAbstractListModel the
2111 // same day). MainWindow stores a back-reference, grabs the root widget
2112 // for splitter wiring, and bridges the manager's semantic signals back
2113 // to refreshGameList() and existing MainWindow state. MainWindow no
2114 // longer holds raw pointers to the four filter lists — it queries the
2115 // manager via selectedCategoryIndex(), selectedSourceValue(), etc.
2116 sidebarManager_ = std::make_unique<SidebarManager>(
2117 libraryController_.get(), launchController_.get(), settingsController_.get(),
2118 notificationService_.get(), &ThemeManager::instance(), this);
2119 sidebarManager_->setupSidebar();
2120
2121 sidebar_ = sidebarManager_->widget();
2122
2123 SidebarManager* sm = sidebarManager_.get();
2124 connect(sm, &SidebarManager::categoryChanged, this,
2125 [this](int row)
2126 {
2127 currentCategory_ = row;
2128 refreshGameList();
2129 });
2130 connect(sm, &SidebarManager::sourceChanged, this, &MainWindow::refreshGameList);
2131 connect(sm, &SidebarManager::runnerChanged, this, &MainWindow::refreshGameList);
2132 connect(sm, &SidebarManager::collectionChanged, this,
2133 [this](const QString& name)
2134 {
2135 currentCollection_ = name.toStdString();
2136 refreshGameList();
2137 });
2138 connect(sm, &SidebarManager::collectionDeleted, this,
2139 [this](const QString& name)
2140 {
2141 if (currentCollection_ == name.toStdString())
2142 {
2143 currentCollection_.clear();
2144 refreshGameList();
2145 }
2146 });
2147}
2148
2149void MainWindow::setupGameList()
2150{
2151 gameList_ = new QListView(this);
2152 gameList_->setViewMode(QListView::ListMode);
2153 gameList_->setSpacing(2);
2154 gameList_->setSelectionMode(QAbstractItemView::ExtendedSelection);
2155 gameList_->setContextMenuPolicy(Qt::CustomContextMenu);
2156 gameList_->setMouseTracking(true);
2157 gameList_->setUniformItemSizes(false);
2158
2159 // Create model + proxy and wire them to the view (MED-6)
2160 gameListModel_ = new GameListModel(this);
2161 gameListProxy_ = new GameListProxyModel(this);
2162 gameListProxy_->setSourceModel(gameListModel_);
2163 gameList_->setModel(gameListProxy_);
2164
2165 // Route GameIsRunningRole queries through the launch controller.
2166 gameListModel_->setIsRunningAccessor(
2167 [this](const std::string& id)
2168 { return launchController_ && launchController_->isGameRunning(id); });
2169
2170 // Create and set custom delegate for rich item rendering
2171 gameListDelegate_ = new GameListDelegate(this);
2172 gameList_->setItemDelegate(gameListDelegate_);
2173
2174 // Minimal styling - delegate handles most rendering
2175 const ThemeColors& c = ThemeManager::instance().colors();
2176 gameList_->setStyleSheet(
2177 QString("QListView { background-color: %1; border: none; outline: none; }")
2178 .arg(c.panelBackground.name()));
2179
2180 // Empty-state overlay (first-run / no-search-results / no-filter-results)
2181 gameListEmptyOverlay_ = new QWidget(gameList_->viewport());
2182 gameListEmptyOverlay_->setObjectName("gameListEmptyOverlay");
2183 gameListEmptyOverlay_->setStyleSheet("background: transparent;");
2184 {
2185 auto* overlayLayout = new QVBoxLayout(gameListEmptyOverlay_);
2186 overlayLayout->setAlignment(Qt::AlignCenter);
2187 overlayLayout->setSpacing(12);
2188
2189 emptyStateLabel_ = new QLabel(gameListEmptyOverlay_);
2190 emptyStateLabel_->setAlignment(Qt::AlignCenter);
2191 emptyStateLabel_->setWordWrap(true);
2192 emptyStateLabel_->setStyleSheet(
2193 QString("color: %1; padding: 12px;").arg(c.textSecondary.name()));
2194 overlayLayout->addWidget(emptyStateLabel_);
2195
2196 auto* btnRow = new QHBoxLayout();
2197 btnRow->setAlignment(Qt::AlignCenter);
2198
2199 emptyStateAddButton_ = new QPushButton("Add Game", gameListEmptyOverlay_);
2200 emptyStateAddButton_->setStyleSheet(
2201 QString("QPushButton { background-color: %1; color: %2; border: none; border-radius: "
2202 "6px; padding: 9px 24px; font-weight: bold; }"
2203 "QPushButton:hover { background-color: %3; }"
2204 "QPushButton:pressed { background-color: %4; }")
2205 .arg(c.accent.name())
2206 .arg(c.textOnAccent.name())
2207 .arg(c.accentHover.name())
2208 .arg(c.accentPressed.name()));
2209 connect(emptyStateAddButton_, &QPushButton::clicked, this, &MainWindow::onAddGameClicked);
2210
2211 emptyStateImportButton_ = new QPushButton("Import Games", gameListEmptyOverlay_);
2212 emptyStateImportButton_->setStyleSheet(
2213 QString("QPushButton { background-color: %1; color: %2; border: 1px solid %3; "
2214 "border-radius: 6px; padding: 9px 24px; }"
2215 "QPushButton:hover { background-color: %4; border-color: %5; }")
2216 .arg(c.cardBackground.name())
2217 .arg(c.textPrimary.name())
2218 .arg(c.border.name())
2219 .arg(c.hoverBackground.name())
2220 .arg(c.accent.name()));
2221 connect(
2222 emptyStateImportButton_, &QPushButton::clicked, this,
2223 [this]()
2224 {
2225 GameImportDialog dialog(libraryController_.get(), this);
2226 if (dialog.exec() == QDialog::Accepted)
2227 {
2229 libraryController_->getAllGames(),
2230 [this](const std::string& gameId, const std::function<void(Game&)>& updater)
2231 { libraryController_->executeWithGame(gameId, updater); });
2232 updateSourceFilters();
2233 updateCategoryCounts();
2234 refreshGameList();
2235 QTimer::singleShot(500, this, [this]() { fetchMissingProtonDB(); });
2236 }
2237 });
2238
2239 emptyStateClearSearchButton_ = new QPushButton("Clear Search", gameListEmptyOverlay_);
2240 emptyStateClearSearchButton_->setStyleSheet(
2241 QString("QPushButton { background-color: %1; color: %2; border: 1px solid %3; "
2242 "border-radius: 4px; padding: 6px 16px; }"
2243 "QPushButton:hover { background-color: %4; }")
2244 .arg(c.cardBackground.name())
2245 .arg(c.textPrimary.name())
2246 .arg(c.border.name())
2247 .arg(c.hoverBackground.name()));
2248 connect(emptyStateClearSearchButton_, &QPushButton::clicked, this,
2249 [this]()
2250 {
2251 searchEdit_->clear();
2252 searchEdit_->setFocus();
2253 });
2254
2255 emptyStateShowAllButton_ = new QPushButton("Show All Games", gameListEmptyOverlay_);
2256 emptyStateShowAllButton_->setStyleSheet(
2257 QString("QPushButton { background-color: %1; color: %2; border: 1px solid %3; "
2258 "border-radius: 4px; padding: 6px 16px; }"
2259 "QPushButton:hover { background-color: %4; }")
2260 .arg(c.cardBackground.name())
2261 .arg(c.textPrimary.name())
2262 .arg(c.border.name())
2263 .arg(c.hoverBackground.name()));
2264 connect(emptyStateShowAllButton_, &QPushButton::clicked, this,
2265 [this]()
2266 {
2267 if (sidebarManager_)
2268 {
2269 sidebarManager_->selectCategoryByRow(0);
2270 sidebarManager_->clearCollectionsSelection();
2271 }
2272 currentCategory_ = 0;
2273 currentCollection_.clear();
2274 refreshGameList();
2275 });
2276
2277 btnRow->addWidget(emptyStateAddButton_);
2278 btnRow->addWidget(emptyStateImportButton_);
2279 btnRow->addWidget(emptyStateClearSearchButton_);
2280 btnRow->addWidget(emptyStateShowAllButton_);
2281 overlayLayout->addLayout(btnRow);
2282 }
2283 gameListEmptyOverlay_->hide();
2284 // Watch viewport resize so we can keep the overlay full-size.
2285 gameList_->viewport()->installEventFilter(this);
2286
2287 connect(gameList_->selectionModel(), &QItemSelectionModel::currentChanged, this,
2288 &MainWindow::onGameSelected);
2289 connect(gameList_, &QListView::doubleClicked, this,
2290 [this](const QModelIndex&) { onLaunchClicked(); });
2291}
2292
2293void MainWindow::setupGameListContextMenu()
2294{
2295 // Game-list right-click context menu lives in ContextMenuManager
2296 // (extracted 2026-04-19). This runs after setupUI() and setupMenuBar()
2297 // so that detailsPanelManager_ and gameActionFactory_ are live — if
2298 // constructed earlier (as in the initial extraction) the factory
2299 // pointer was captured null and right-click silently no-op'd.
2300 contextMenuManager_ = std::make_unique<ContextMenuManager>(
2301 this, libraryController_.get(), detailsPanelManager_.get(), gameActionFactory_.get(),
2302 notificationService_, &ThemeManager::instance());
2303 contextMenuManager_->install(gameList_);
2304
2305 connect(contextMenuManager_.get(), &ContextMenuManager::gamesBatchRemoveRequested, this,
2306 [this](const std::vector<std::string>& ids)
2307 {
2308 for (const auto& id : ids)
2309 libraryController_->removeGame(id);
2310 updateSourceFilters();
2311 updateCategoryCounts();
2312 refreshGameList();
2313 });
2314
2315 connect(contextMenuManager_.get(), &ContextMenuManager::steamUninstallCompleted, this,
2316 [this](const std::string& gameId, bool success, const std::string& gameName,
2317 std::uint32_t appId)
2318 {
2319 if (!success)
2320 {
2321 if (notificationService_)
2322 {
2323 notificationService_->error("Failed to uninstall " + gameName);
2324 }
2325 return;
2326 }
2327 if (notificationService_)
2328 {
2329 notificationService_->success(gameName + " has been uninstalled");
2330 }
2331 if (auto* gamePtr = libraryController_->getGameForEdit(gameId))
2332 {
2333 gamePtr->metadata.steamInstalled = false;
2334 libraryController_->updateGame(gameId, *gamePtr);
2335 }
2336 scheduleRefresh();
2337 detailsPanelManager_->update(gameId);
2338 QProcess::startDetached(
2339 "steam", {QStringLiteral("steam://nav/games/details/%1").arg(appId)});
2340 });
2341}
2342
2343void MainWindow::setupStatusBar()
2344{
2345 const ThemeColors& c = ThemeManager::instance().colors();
2346
2347 // Rich status indicators (library stats, running games, downloads)
2348 // Note: SteamDownloadMonitor is not a QObject - downloads are forwarded via callbacks
2349 auto* statusIndicators = new StatusBarContainer(
2350 launchController_.get(), libraryController_.get(),
2351 nullptr, // Download callbacks are set up in setupSteamDownloadMonitor()
2352 this, &ThemeManager::instance());
2353 statusIndicators->setObjectName("statusIndicators"); // For later access
2354 statusBar()->addWidget(statusIndicators, 1); // Stretch factor 1
2355
2356 // Connect status indicator signals
2357 connect(statusIndicators, &StatusBarContainer::stopGameRequested, this,
2358 [this](const std::string& gameId) { launchController_->stopGame(gameId); });
2359 connect(statusIndicators, &StatusBarContainer::showGameRequested, this,
2360 [this](const std::string& gameId)
2361 {
2362 // Find and select the game in the list
2363 QModelIndex idx = proxyIndexForGameId(gameId);
2364 if (idx.isValid())
2365 {
2366 gameList_->setCurrentIndex(idx);
2367 gameList_->scrollTo(idx);
2368 }
2369 });
2370
2371 // Progress indicator for async operations (hidden by default)
2372 statusProgressBar_ = new QProgressBar(this);
2373 statusProgressBar_->setMaximumWidth(150);
2374 statusProgressBar_->setMaximumHeight(16);
2375 statusProgressBar_->setTextVisible(false);
2376 statusProgressBar_->setRange(0, 0); // Indeterminate mode
2377 statusProgressBar_->setVisible(false);
2378 statusProgressBar_->setStyleSheet(
2379 QString("QProgressBar { background-color: %1; border: none; border-radius: 3px; }"
2380 "QProgressBar::chunk { background-color: %2; border-radius: 3px; }")
2381 .arg(c.cardBackground.name())
2382 .arg(c.success.name()));
2383 statusBar()->addPermanentWidget(statusProgressBar_);
2384
2385 // System readiness indicator (compact gaming readiness dashboard)
2386 auto* readinessWidget = new SystemReadinessWidget(this);
2387 readinessWidget->setMaximumHeight(28);
2388 connect(readinessWidget, &SystemReadinessWidget::detailsRequested, this,
2389 [this]()
2390 {
2391 // Open settings dialog to System Info tab
2392 SettingsDialog dialog(settingsController_.get(), this);
2393 dialog.exec();
2394 });
2395 statusBar()->addPermanentWidget(readinessWidget);
2396
2397 // Also keep the legacy status label for simple status messages
2398 statusLabel_ = new QLabel(this);
2399 statusLabel_->setStyleSheet(QString("color: %1; padding: 0 8px;").arg(c.textMuted.name()));
2400 statusBar()->addPermanentWidget(statusLabel_);
2401}
2402
2403void MainWindow::setupTrayIcon()
2404{
2405 trayIcon_ = new QSystemTrayIcon(this);
2406 trayIcon_->setIcon(QIcon::fromTheme("applications-games", QIcon(":/icons/icon.png")));
2407 trayIcon_->setToolTip("Game Launcher");
2408
2409 trayMenu_ = new QMenu(this);
2410 ThemeManager::instance().styleMenu(trayMenu_);
2411
2412 // Show/Hide actions
2413 trayMenu_->addAction("Show Window", this, &QMainWindow::show);
2414 trayMenu_->addAction("Hide Window", this, &QMainWindow::hide);
2415 trayMenu_->addSeparator();
2416
2417 // Running games submenu (dynamic)
2418 QMenu* runningMenu = trayMenu_->addMenu("Running Games");
2419 ThemeManager::instance().styleMenu(runningMenu);
2420 runningMenu->setEnabled(false);
2421
2422 // Recently played submenu (quick launch)
2423 QMenu* recentMenu = trayMenu_->addMenu("Quick Launch");
2424 ThemeManager::instance().styleMenu(recentMenu);
2425
2426 trayMenu_->addSeparator();
2427 trayMenu_->addAction("Exit", this,
2428 [this]()
2429 {
2430 forceQuit_ = true; // Bypass minimize-to-tray
2431 close();
2432 });
2433
2434 trayIcon_->setContextMenu(trayMenu_);
2435
2436 // Update the tray menu when it's about to show
2437 connect(trayMenu_, &QMenu::aboutToShow, this,
2438 [this, runningMenu, recentMenu]()
2439 {
2440 // Update running games submenu
2441 runningMenu->clear();
2442 auto runningGames = launchController_->getAllRunningGames();
2443 if (runningGames.empty())
2444 {
2445 runningMenu->setEnabled(false);
2446 runningMenu->setTitle("Running Games (none)");
2447 }
2448 else
2449 {
2450 runningMenu->setEnabled(true);
2451 runningMenu->setTitle(QString("Running Games (%1)").arg(runningGames.size()));
2452 for (const auto& info : runningGames)
2453 {
2454 QString gameName = QString::fromStdString(info.gameName);
2455 QMenu* gameMenu = runningMenu->addMenu(gameName);
2456 gameMenu->addAction("Stop", this, [this, gameId = info.gameId]()
2457 { launchController_->stopGame(gameId); });
2458 gameMenu->addAction("Show in Library", this,
2459 [this, gameId = info.gameId]()
2460 {
2461 show();
2462 raise();
2463 activateWindow();
2464 // Select the game in the list
2465 QModelIndex idx = proxyIndexForGameId(gameId);
2466 if (idx.isValid())
2467 {
2468 gameList_->setCurrentIndex(idx);
2469 }
2470 });
2471 }
2472 runningMenu->addSeparator();
2473 runningMenu->addAction("Stop All", this,
2474 [this]() { launchController_->stopAllGames(); });
2475 }
2476
2477 // Update recent games submenu
2478 recentMenu->clear();
2479 auto recentGames = libraryController_->getRecentlyPlayed(5);
2480 if (recentGames.empty())
2481 {
2482 recentMenu->addAction("No recent games")->setEnabled(false);
2483 }
2484 else
2485 {
2486 for (const auto* game : recentGames)
2487 {
2488 QString gameName = QString::fromStdString(game->name);
2489 std::string gameId = game->id;
2490 QAction* action = recentMenu->addAction(
2491 gameName, this,
2492 [this, gameId]()
2493 {
2494 if (auto recentGame = libraryController_->getGame(gameId))
2495 {
2496 launchController_->launchGame(gameId, *recentGame);
2497 }
2498 });
2499
2500 // Disable if already running
2501 if (launchController_->isGameRunning(gameId))
2502 {
2503 action->setEnabled(false);
2504 action->setText(gameName + " (running)");
2505 }
2506 }
2507 }
2508
2509 // Update tooltip with current status
2510 if (!runningGames.empty())
2511 {
2512 QString tooltip =
2513 QString("Game Launcher\n%1 game(s) running").arg(runningGames.size());
2514 trayIcon_->setToolTip(tooltip);
2515 }
2516 else
2517 {
2518 trayIcon_->setToolTip("Game Launcher");
2519 }
2520 });
2521
2522 connect(trayIcon_, &QSystemTrayIcon::activated, this, &MainWindow::onTrayIconActivated);
2523
2524 trayIcon_->show();
2525}
2526
2527void MainWindow::setupControllerCallbacks()
2528{
2529 // Every outer-lambda captures a QPointer<MainWindow> guard rather than a
2530 // raw `this`. The outer lambda runs on an arbitrary backend thread, so
2531 // dereferencing `this` after destruction is UB. QPointer nulls atomically
2532 // on QObject destruction and is safe to null-check from any thread; we
2533 // re-check inside the marshalled lambda to cover the narrow window between
2534 // queuing and dispatch.
2535
2536 // Game library callbacks
2537 libraryController_->setOnGameAdded(
2538 [guard = QPointer<MainWindow>(this)](const core::GameAddedEvent& event)
2539 {
2540 if (!guard)
2541 return;
2542 QMetaObject::invokeMethod(
2543 guard.data(),
2544 [guard, event]()
2545 {
2546 auto* self = guard.data();
2547 if (!self)
2548 return;
2549 // If this is a Steam game, add it to the download monitor watch list
2550 const Game* game = self->libraryController_->getGame(event.gameId);
2551 if (game && game->source == GameSource::Steam &&
2552 game->metadata.steamAppId > 0 && self->steamDownloadMonitor_)
2553 {
2554 self->steamDownloadMonitor_->watchGame(
2555 static_cast<uint32_t>(game->metadata.steamAppId));
2556 }
2557 self->scheduleRefresh(); // Debounced - multiple adds will consolidate
2558 },
2559 Qt::QueuedConnection);
2560 });
2561
2562 libraryController_->setOnGameRemoved(
2563 [guard = QPointer<MainWindow>(this)](const core::GameRemovedEvent&)
2564 {
2565 if (!guard)
2566 return;
2567 QMetaObject::invokeMethod(
2568 guard.data(),
2569 [guard]()
2570 {
2571 if (auto* self = guard.data())
2572 self->scheduleRefresh();
2573 },
2574 Qt::QueuedConnection);
2575 });
2576
2577 libraryController_->setOnGameUpdated(
2578 [guard = QPointer<MainWindow>(this)](const core::GameUpdatedEvent& event)
2579 {
2580 if (!guard)
2581 return;
2582 QMetaObject::invokeMethod(
2583 guard.data(),
2584 [guard, event]()
2585 {
2586 auto* self = guard.data();
2587 if (!self)
2588 return;
2589 if (event.gameId == self->selectedGameId_)
2590 self->detailsPanelManager_->update(self->selectedGameId_);
2591 },
2592 Qt::QueuedConnection);
2593 });
2594
2595 // Launch controller callbacks
2596 launchController_->setOnStateChanged(
2597 [guard = QPointer<MainWindow>(this)](const core::LaunchStateChangedEvent& event)
2598 {
2599 if (!guard)
2600 return;
2601 QMetaObject::invokeMethod(
2602 guard.data(),
2603 [guard, event]()
2604 {
2605 auto* self = guard.data();
2606 if (!self)
2607 return;
2608 self->detailsPanelManager_->updateLaunchButton(self->selectedGameId_);
2609
2610 // Update status bar with launch state
2611 QString statusMsg;
2612 switch (event.newState)
2613 {
2614 case core::LaunchState::PreparingLaunch:
2615 statusMsg = "Preparing to launch...";
2616 break;
2617 case core::LaunchState::WaitingForSteam:
2618 statusMsg = "Waiting for Steam...";
2619 break;
2620 case core::LaunchState::Launching:
2621 statusMsg = "Launching game...";
2622 break;
2623 case core::LaunchState::VerifyingStart:
2624 statusMsg = "Verifying game started...";
2625 break;
2626 case core::LaunchState::Running:
2627 statusMsg = "Game running";
2628 break;
2629 case core::LaunchState::Stopping:
2630 statusMsg = "Stopping game...";
2631 break;
2632 case core::LaunchState::Completed:
2633 statusMsg = "Ready";
2634 break;
2635 default:
2636 break;
2637 }
2638
2639 if (!statusMsg.isEmpty() && self->statusLabel_)
2640 {
2641 self->statusLabel_->setText(statusMsg);
2642 }
2643
2644 // Update game list item to show running state
2645 if (!event.gameId.empty())
2646 {
2647 self->updateGameRow(event.gameId);
2648 }
2649 },
2650 Qt::QueuedConnection);
2651 });
2652
2653 launchController_->setOnProcessStarted(
2654 [guard = QPointer<MainWindow>(this)](const core::ProcessStartedEvent& event)
2655 {
2656 if (!guard)
2657 return;
2658 QMetaObject::invokeMethod(
2659 guard.data(),
2660 [guard, event]()
2661 {
2662 auto* self = guard.data();
2663 if (!self)
2664 return;
2665 const Game* game = self->libraryController_->getGame(event.gameId);
2666 std::string gameName = game ? game->name : event.processName;
2667
2668 if (self->notificationService_)
2669 {
2670 self->notificationService_->success("▶ " + gameName + " is now running");
2671 }
2672
2673 // Update status bar
2674 if (self->statusLabel_)
2675 {
2676 self->statusLabel_->setText(QString::fromStdString(gameName) + " running");
2677 }
2678 },
2679 Qt::QueuedConnection);
2680 });
2681
2682 launchController_->setOnProcessExited(
2683 [guard = QPointer<MainWindow>(this)](const core::ProcessExitedEvent& event)
2684 {
2685 if (!guard)
2686 return;
2687 QMetaObject::invokeMethod(
2688 guard.data(),
2689 [guard, event]()
2690 {
2691 auto* self = guard.data();
2692 if (!self)
2693 return;
2694 const Game* game = self->libraryController_->getGame(event.gameId);
2695 std::string gameName = game ? game->name : "Game";
2696
2697 if (self->notificationService_)
2698 {
2699 auto duration = event.sessionDuration.count();
2700 auto hours = static_cast<int>(duration / 3600);
2701 auto minutes = static_cast<int>((duration % 3600) / 60);
2702 std::string msg = gameName + " closed";
2703 if (hours > 0)
2704 {
2705 msg += " • Played " + std::to_string(hours) + "h " +
2706 std::to_string(minutes) + "m";
2707 }
2708 else if (minutes > 0)
2709 {
2710 msg += " • Played " + std::to_string(minutes) + " minutes";
2711 }
2712 self->notificationService_->info(msg);
2713 }
2714
2715 // Update status bar
2716 if (self->statusLabel_)
2717 {
2718 self->statusLabel_->setText("Ready");
2719 }
2720
2721 // Update game statistics in the list
2722 if (game)
2723 {
2724 self->updateGameRow(event.gameId);
2725 }
2726
2727 // Clear frame metrics widget and update details panel if this game is selected
2728 if (event.gameId == self->selectedGameId_)
2729 {
2730 if (self->detailsPanelManager_->frameMetricsWidget())
2731 {
2732 self->detailsPanelManager_->frameMetricsWidget()->clear();
2733 self->detailsPanelManager_->frameMetricsWidget()->setVisible(false);
2734 }
2735 self->detailsPanelManager_->update(self->selectedGameId_);
2736 }
2737 },
2738 Qt::QueuedConnection);
2739 });
2740
2741 launchController_->setOnLaunchError(
2742 [guard = QPointer<MainWindow>(this)](const core::LaunchErrorEvent& event)
2743 {
2744 if (!guard)
2745 return;
2746 QMetaObject::invokeMethod(
2747 guard.data(),
2748 [guard, event]()
2749 {
2750 auto* self = guard.data();
2751 if (!self)
2752 return;
2753 const Game* game = self->libraryController_->getGame(event.gameId);
2754 std::string gameName = game ? game->name : "Game";
2755
2756 if (self->notificationService_)
2757 {
2758 self->notificationService_->error("Failed to launch " + gameName + ": " +
2759 event.errorMessage);
2760 }
2761
2762 // Update status bar
2763 if (self->statusLabel_)
2764 {
2765 self->statusLabel_->setText("Launch failed");
2766 }
2767 },
2768 Qt::QueuedConnection);
2769 });
2770}
2771
2772void MainWindow::setupSteamDownloadMonitor()
2773{
2774 steamDownloadMonitor_ = std::make_unique<SteamDownloadMonitor>();
2775
2776 // Set up progress callback. The monitor invokes this from its background
2777 // polling thread, so we capture a QPointer guard rather than raw `this`.
2778 steamDownloadMonitor_->setOnProgressUpdate(
2779 [guard = QPointer<MainWindow>(this)](uint32_t appId, const SteamDownloadProgress& progress)
2780 {
2781 if (!guard)
2782 return;
2783 QMetaObject::invokeMethod(
2784 guard.data(),
2785 [guard, appId, progress]()
2786 {
2787 if (auto* self = guard.data())
2788 self->onSteamDownloadProgress(
2789 appId, progress.overallProgress,
2790 QString::fromStdString(progress.stateDescription));
2791 },
2792 Qt::QueuedConnection);
2793 });
2794
2795 // Set up state change callback for completion detection.
2796 // Fires from SteamDownloadMonitor's background polling thread; guard with
2797 // QPointer and marshal to the Qt main thread for all library/UI access.
2798 steamDownloadMonitor_->setOnStateChange(
2799 [guard = QPointer<MainWindow>(this)](uint32_t appId, uint32_t oldState, uint32_t newState)
2800 {
2801 Logger::info("[MainWindow] Steam state change for app {}: {} -> {} ({})", appId,
2802 oldState, newState, SteamStateFlags::getStateDescription(newState));
2803
2804 if (!guard)
2805 return;
2806 QMetaObject::invokeMethod(
2807 guard.data(),
2808 [guard, appId, oldState, newState]()
2809 {
2810 auto* self = guard.data();
2811 if (!self)
2812 return;
2813 // Check if game transitioned to fully installed state
2814 if (SteamStateFlags::isFullyInstalled(newState))
2815 {
2816 // Skip if this is just initial state detection (oldState == 0)
2817 // and the game was already marked as installed in our database
2818 bool skipBecauseAlreadyKnown = (oldState == 0);
2819
2820 if (skipBecauseAlreadyKnown)
2821 {
2822 // Check if our database already knows this game is installed
2823 for (const auto* game : self->libraryController_->getAllGames())
2824 {
2825 if (game->source == GameSource::Steam &&
2826 static_cast<uint32_t>(game->metadata.steamAppId) == appId)
2827 {
2828 if (!game->metadata.steamInstalled)
2829 {
2830 // Database says not installed, but Steam says it is!
2831 // This is a sync issue - we should update our state
2832 skipBecauseAlreadyKnown = false;
2833 Logger::info("[MainWindow] App {} is installed in Steam "
2834 "but not in our database - syncing",
2835 appId);
2836 }
2837 break;
2838 }
2839 }
2840 }
2841
2842 if (!skipBecauseAlreadyKnown ||
2843 (oldState != 0 && !SteamStateFlags::isFullyInstalled(oldState)))
2844 {
2845 // Actual install/update complete
2846 self->onSteamInstallComplete(appId);
2847 }
2848 }
2849 else if (newState == 0 && oldState != 0)
2850 {
2851 // Uninstall complete (manifest disappeared)
2852 self->onSteamUninstallComplete(appId, oldState);
2853 }
2854 },
2855 Qt::QueuedConnection);
2856 });
2857
2858 // Start monitoring with 1 second poll interval
2859 steamDownloadMonitor_->start(1000);
2860
2861 // Auto-watch ALL Steam games in the library for accurate state tracking
2862 // This allows us to detect downloads, updates, and installation changes
2863 for (const auto* game : libraryController_->getAllGames())
2864 {
2865 if (game->source == GameSource::Steam && game->metadata.steamAppId > 0)
2866 {
2867 steamDownloadMonitor_->watchGame(static_cast<uint32_t>(game->metadata.steamAppId));
2868 }
2869 }
2870
2871 Logger::info("[MainWindow] Auto-watching {} Steam games for state changes",
2872 steamDownloadMonitor_->getWatchedGames().size());
2873}
2874
2875void MainWindow::onSteamDownloadProgress(uint32_t appId, double progress, const QString& status)
2876{
2877 // Find the game for this appId
2878 QString gameName;
2879 std::string gameId;
2880 const Game* targetGame = nullptr;
2881 for (const auto* game : libraryController_->getAllGames())
2882 {
2883 if (game->source == GameSource::Steam &&
2884 static_cast<uint32_t>(game->metadata.steamAppId) == appId)
2885 {
2886 gameName = QString::fromStdString(game->name);
2887 gameId = game->id;
2888 targetGame = game;
2889 break;
2890 }
2891 }
2892
2893 // Always update the status bar regardless of which game is selected
2894 if (statusLabel_ && !gameName.isEmpty())
2895 {
2896 statusLabel_->setText(
2897 QString("%1: %2 %3%").arg(gameName).arg(status).arg(static_cast<int>(progress * 100)));
2898 }
2899
2900 // Forward to status indicators in status bar
2901 auto* statusIndicators = findChild<StatusBarContainer*>("statusIndicators");
2902 if (statusIndicators && statusIndicators->downloadsIndicator())
2903 {
2904 statusIndicators->downloadsIndicator()->onDownloadProgress(appId, progress, status);
2905 }
2906
2907 // Update the game item in the list to show current status
2908 if (targetGame && !gameId.empty())
2909 {
2910 // Progress data now flows from the Game* via the model's roles;
2911 // just re-emit dataChanged so the delegate repaints.
2912 // TODO MED-6: per-row transient (Qt::UserRole + 100/101) payload no
2913 // longer survives the migration; delegate reads progress from
2914 // GameDownloadProgressRole computed from Game::metadata.steamBytes*.
2915 updateGameRow(gameId);
2916 if (gameList_)
2917 gameList_->viewport()->update();
2918 }
2919
2920 // Check if this is the currently selected game for details panel updates
2921 const Game* selectedGame =
2922 selectedGameId_.empty() ? nullptr : libraryController_->getGame(selectedGameId_);
2923 if (!selectedGame || selectedGame->source != GameSource::Steam ||
2924 static_cast<uint32_t>(selectedGame->metadata.steamAppId) != appId)
2925 {
2926 return;
2927 }
2928
2929 // Show progress widget if not visible
2930 if (detailsPanelManager_->downloadProgressWidget() &&
2931 !detailsPanelManager_->downloadProgressWidget()->isVisible())
2932 {
2933 detailsPanelManager_->downloadProgressWidget()->setVisible(true);
2934 }
2935
2936 // Update progress bar
2937 if (detailsPanelManager_->downloadProgressBar())
2938 {
2939 detailsPanelManager_->downloadProgressBar()->setValue(static_cast<int>(progress * 100));
2940 }
2941
2942 // Update status label
2943 if (detailsPanelManager_->downloadProgressLabel())
2944 {
2945 QString progressText =
2946 QString("%1 - %2%").arg(status).arg(static_cast<int>(progress * 100));
2947 detailsPanelManager_->downloadProgressLabel()->setText(progressText);
2948 }
2949
2950 // Update launch button text
2951 if (detailsPanelManager_->launchButton())
2952 {
2953 detailsPanelManager_->launchButton()->setEnabled(false);
2954 detailsPanelManager_->launchButton()->setText(
2955 QString("%1... %2%").arg(status).arg(static_cast<int>(progress * 100)));
2956 }
2957}
2958
2959void MainWindow::onSteamInstallComplete(uint32_t appId)
2960{
2961 // Notify status indicators of completion
2962 auto* statusIndicators = findChild<StatusBarContainer*>("statusIndicators");
2963 if (statusIndicators && statusIndicators->downloadsIndicator())
2964 {
2965 statusIndicators->downloadsIndicator()->onDownloadComplete(appId);
2966 }
2967
2968 // Hide progress widget
2969 if (detailsPanelManager_->downloadProgressWidget())
2970 {
2971 detailsPanelManager_->downloadProgressWidget()->setVisible(false);
2972 }
2973
2974 // Find the game and check if it was actually not installed before
2975 QString gameName = "Game";
2976 std::string gameIdToUpdate;
2977 bool wasAlreadyInstalled = false;
2978 for (const auto* game : libraryController_->getAllGames())
2979 {
2980 if (game->source == GameSource::Steam &&
2981 static_cast<uint32_t>(game->metadata.steamAppId) == appId)
2982 {
2983 gameName = QString::fromStdString(game->name);
2984 gameIdToUpdate = game->id;
2985 // Check if already marked as installed - skip notification if so
2986 wasAlreadyInstalled =
2987 game->metadata.steamInstalled && game->status == GameStatus::Installed;
2988 break;
2989 }
2990 }
2991
2992 // Skip if game was already installed (no actual state change)
2993 if (wasAlreadyInstalled)
2994 {
2995 Logger::debug("[MainWindow] Skipping install complete for {} - already marked installed",
2996 appId);
2997 return;
2998 }
2999
3000 // Update game's installed status in library
3001 if (!gameIdToUpdate.empty())
3002 {
3003 if (auto gamePtr = libraryController_->getGameForEdit(gameIdToUpdate))
3004 {
3005 gamePtr->metadata.steamInstalled = true;
3006 gamePtr->status = GameStatus::Installed;
3007 libraryController_->updateGame(gameIdToUpdate, *gamePtr);
3008 }
3009 }
3010
3011 // Show notification only for actual installs
3012 if (notificationService_)
3013 {
3014 notificationService_->success(gameName.toStdString() + " installation complete!");
3015 }
3016
3017 Logger::info("[MainWindow] Steam game {} ({}) installation complete", gameName.toStdString(),
3018 appId);
3019
3020 // Don't stop watching - keep monitoring for updates/uninstalls
3021 // steamDownloadMonitor_->unwatchGame(appId);
3022
3023 // Debounced refresh - multiple installs completing will consolidate
3024 scheduleRefresh();
3025
3026 // Update the details panel and launch button
3027 if (!selectedGameId_.empty())
3028 {
3029 detailsPanelManager_->update(selectedGameId_);
3030 detailsPanelManager_->updateLaunchButton(selectedGameId_);
3031 }
3032}
3033
3034void MainWindow::onSteamUninstallComplete(uint32_t appId, uint32_t previousState)
3035{
3036 Q_UNUSED(previousState);
3037
3038 // Hide progress widget
3039 if (detailsPanelManager_->downloadProgressWidget())
3040 {
3041 detailsPanelManager_->downloadProgressWidget()->setVisible(false);
3042 }
3043
3044 // Find the game and check if it was actually installed before
3045 QString gameName = "Game";
3046 std::string gameIdToUpdate;
3047 bool wasInstalled = false;
3048 for (const auto* game : libraryController_->getAllGames())
3049 {
3050 if (game->source == GameSource::Steam &&
3051 static_cast<uint32_t>(game->metadata.steamAppId) == appId)
3052 {
3053 gameName = QString::fromStdString(game->name);
3054 gameIdToUpdate = game->id;
3055 wasInstalled = game->metadata.steamInstalled;
3056 break;
3057 }
3058 }
3059
3060 // Skip if game wasn't installed (no actual state change)
3061 if (!wasInstalled)
3062 {
3063 Logger::debug("[MainWindow] Skipping uninstall complete for {} - wasn't marked installed",
3064 appId);
3065 return;
3066 }
3067
3068 // Update game's installed status in library
3069 if (!gameIdToUpdate.empty())
3070 {
3071 if (auto gamePtr = libraryController_->getGameForEdit(gameIdToUpdate))
3072 {
3073 gamePtr->metadata.steamInstalled = false;
3074 gamePtr->status = GameStatus::NotInstalled;
3075 libraryController_->updateGame(gameIdToUpdate, *gamePtr);
3076 }
3077 }
3078
3079 // Show notification only for actual uninstalls
3080 if (notificationService_)
3081 {
3082 notificationService_->info(gameName.toStdString() + " has been uninstalled.");
3083 }
3084
3085 Logger::info("[MainWindow] Steam game {} ({}) uninstalled", gameName.toStdString(), appId);
3086
3087 // Update status bar
3088 if (statusLabel_)
3089 {
3090 statusLabel_->setText("Ready");
3091 }
3092
3093 // Don't stop watching - game might be reinstalled later
3094 // steamDownloadMonitor_->unwatchGame(appId);
3095
3096 // Debounced refresh - multiple uninstalls completing will consolidate
3097 scheduleRefresh();
3098
3099 // Update the details panel and launch button
3100 if (!selectedGameId_.empty())
3101 {
3102 detailsPanelManager_->update(selectedGameId_);
3103 detailsPanelManager_->updateLaunchButton(selectedGameId_);
3104 }
3105}
3106
3107void MainWindow::onAsyncImageLoaded(const QString& cacheKey, const QPixmap& pixmap)
3108{
3109 if (pixmap.isNull())
3110 return;
3111
3112 // Check if this is for the hero image in details panel
3113 if (cacheKey.startsWith(QStringLiteral("hero_")))
3114 {
3115 // Hero image for details panel - format: "hero_gameId_width"
3116 QString remainder = cacheKey.mid(5); // Remove "hero_" prefix
3117 qsizetype lastUnderscore = remainder.lastIndexOf('_');
3118 if (lastUnderscore > 0)
3119 {
3120 QString gameId = remainder.left(lastUnderscore);
3121 if (gameId.toStdString() == selectedGameId_ && detailsPanelManager_->heroImageLabel())
3122 {
3123 detailsPanelManager_->heroImageLabel()->setPixmap(pixmap);
3124 detailsPanelManager_->heroImageLabel()->setFixedHeight(pixmap.height());
3125 detailsPanelManager_->heroImageLabel()->setVisible(true);
3126 }
3127 }
3128 return;
3129 }
3130
3131 // For thumbnail images, extract game ID from cache key
3132 // Format: gameId_WxH_type (from makeImageCacheKey)
3133 // We need to find the game ID which is before the size component
3134
3135 // Find the size pattern (_NNNxNNN_) by looking for "x" surrounded by digits
3136 qsizetype xPos = cacheKey.lastIndexOf('x');
3137 if (xPos < 0)
3138 return;
3139
3140 // Find underscore before width
3141 qsizetype widthStart = cacheKey.lastIndexOf('_', xPos - 1);
3142 if (widthStart < 0)
3143 return;
3144
3145 QString gameId = cacheKey.left(widthStart);
3146
3147 // Store icon in the model; the model emits dataChanged for DecorationRole.
3148 if (gameListModel_)
3149 {
3150 gameListModel_->setIcon(gameId.toStdString(), QIcon(pixmap));
3151 }
3152}
3153
3154void MainWindow::setupKeyboardShortcuts()
3155{
3156 // Registration lives in ShortcutsController (extracted 2026-04-19).
3157 if (!shortcutsController_)
3158 shortcutsController_ = std::make_unique<ShortcutsController>(this);
3159 shortcutsController_->setupKeyboardShortcuts();
3160}
3161
3162// ==============================================================================
3163// Command Palette Setup
3164// ==============================================================================
3165
3166void MainWindow::setupCommandPalette()
3167{
3168 commandPalette_ = new CommandPalette(this, &ThemeManager::instance());
3169 registerPaletteCommands();
3170}
3171
3172void MainWindow::registerPaletteCommands()
3173{
3174 // Registration lives in ShortcutsController (extracted 2026-04-19).
3175 if (!shortcutsController_)
3176 shortcutsController_ = std::make_unique<ShortcutsController>(this);
3177 shortcutsController_->registerPaletteCommands();
3178}
3179
3180void MainWindow::deleteSelectedGame()
3181{
3182 QModelIndexList selectedItems = gameList_ && gameList_->selectionModel()
3183 ? gameList_->selectionModel()->selectedIndexes()
3184 : QModelIndexList();
3185 if (selectedItems.isEmpty())
3186 return;
3187
3188 // Multi-selection delete
3189 if (selectedItems.size() > 1)
3190 {
3191 QMessageBox::StandardButton reply = QMessageBox::question(
3192 this, "Confirm Removal",
3193 QString("Are you sure you want to remove %1 games from the library?")
3194 .arg(selectedItems.size()),
3195 QMessageBox::Yes | QMessageBox::No);
3196
3197 if (reply == QMessageBox::Yes)
3198 {
3199 int removedCount = 0;
3200 for (const QModelIndex& idx : selectedItems)
3201 {
3202 std::string gameId = idx.data(GameIdRole).toString().toStdString();
3203 libraryController_->removeGame(gameId);
3204 removedCount++;
3205 }
3206 updateSourceFilters();
3207 updateCategoryCounts();
3208 refreshGameList();
3209
3210 if (notificationService_)
3211 {
3212 notificationService_->info("Removed " + std::to_string(removedCount) + " games");
3213 }
3214 }
3215 return;
3216 }
3217
3218 // Single selection delete
3219 if (selectedGameId_.empty())
3220 return;
3221
3222 const Game* game = libraryController_->getGame(selectedGameId_);
3223 if (!game)
3224 return;
3225
3226 QMessageBox::StandardButton reply =
3227 QMessageBox::question(this, "Confirm Removal",
3228 QString("Are you sure you want to remove '%1' from the library?")
3229 .arg(QString::fromStdString(game->name)),
3230 QMessageBox::Yes | QMessageBox::No);
3231
3232 if (reply == QMessageBox::Yes)
3233 {
3234 std::string removedName = game->name;
3235 libraryController_->removeGame(selectedGameId_);
3236 refreshGameList();
3237
3238 if (notificationService_)
3239 {
3240 notificationService_->info("Removed: " + removedName);
3241 }
3242 }
3243}
3244
3245void MainWindow::toggleSelectedFavorite()
3246{
3247 if (selectedGameId_.empty())
3248 return;
3249
3250 Game* game = libraryController_->getGameForEdit(selectedGameId_);
3251 if (!game)
3252 return;
3253
3254 game->isFavorite = !game->isFavorite;
3255 libraryController_->updateGame(selectedGameId_, *game);
3256
3257 // Update just the selected item instead of full refresh
3258 updateGameRow(selectedGameId_);
3259
3260 // Update details panel
3261 detailsPanelManager_->update(selectedGameId_);
3262
3263 if (notificationService_)
3264 {
3265 if (game->isFavorite)
3266 {
3267 notificationService_->success("Added to favorites: " + game->name);
3268 }
3269 else
3270 {
3271 notificationService_->info("Removed from favorites: " + game->name);
3272 }
3273 }
3274}
3275
3276int MainWindow::rowForGameId(const std::string& gameId) const
3277{
3278 return gameListModel_ ? gameListModel_->rowForGameId(gameId) : -1;
3279}
3280
3281QModelIndex MainWindow::proxyIndexForGameId(const std::string& gameId) const
3282{
3283 if (!gameListModel_ || !gameListProxy_)
3284 return {};
3285 const int srcRow = gameListModel_->rowForGameId(gameId);
3286 if (srcRow < 0)
3287 return {};
3288 return gameListProxy_->mapFromSource(gameListModel_->index(srcRow, 0));
3289}
3290
3291void MainWindow::updateGameRow(const std::string& gameId)
3292{
3293 if (gameListModel_)
3294 gameListModel_->updateGameById(gameId);
3295}
3296
3297void MainWindow::invalidateGameItemCache()
3298{
3299 // QListWidget-era gameItemCache_ no longer exists; GameListModel owns its
3300 // own id->row index. Kept as a no-op so existing callers compile. MED-6.
3301}
3302
3303// touchCacheEntry removed in MED-7 extraction — owned by GameThumbnailCache.
3304
3305void MainWindow::scheduleRefresh()
3306{
3307 // Debounced refresh - consolidates multiple rapid refreshGameList() calls
3308 // into a single actual refresh after 50ms of inactivity
3309 if (!refreshDebounceTimer_)
3310 {
3311 refreshDebounceTimer_ = new QTimer(this);
3312 refreshDebounceTimer_->setSingleShot(true);
3313 refreshDebounceTimer_->setInterval(50); // 50ms debounce
3314 connect(refreshDebounceTimer_, &QTimer::timeout, this, &MainWindow::refreshGameList);
3315 }
3316 refreshDebounceTimer_->start(); // Restart timer on each call
3317}
3318
3319void MainWindow::refreshGameList()
3320{
3321 // Save the currently selected game ID before replacing the list
3322 std::string previousSelection = selectedGameId_;
3323
3324 // Disable updates during batch operations to prevent unnecessary repaints
3325 gameList_->setUpdatesEnabled(false);
3326
3327 // Apply view mode settings
3328 applyViewMode();
3329
3330 // Apply category filter
3331 core::FilterOptions filter;
3332 switch (currentCategory_)
3333 {
3334 case 0: // All Games
3335 break;
3336 case 1: // Favorites
3337 filter.favoritesOnly = true;
3338 break;
3339 case 2: // Recently Played
3340 // Recently played - temporarily override sort
3341 if (currentSort_ != SortOption::LastPlayedDesc && currentSort_ != SortOption::LastPlayedAsc)
3342 {
3343 libraryController_->setSort({core::SortField::LastPlayed, core::SortOrder::Descending});
3344 }
3345 break;
3346 case 3: // Installed
3347 filter.installedOnly = true;
3348 break;
3349 case 4: // Not Installed
3350 filter.notInstalledOnly = true;
3351 break;
3352 case 5: // Updates Available
3353 // Special case - show only games with updates pending
3354 filter.installedOnly = true; // Updates only apply to installed games
3355 break;
3356 case 6: // Running
3357 // Special case - show only running games
3358 break;
3359 default:
3360 break;
3361 }
3362
3363 // Apply search filter
3364 if (!currentFilter_.empty())
3365 {
3366 filter.searchQuery = currentFilter_;
3367 }
3368
3369 // Apply source filter from the sidebar. selectedSourceValue() returns
3370 // the Qt::UserRole payload (GameSource enum int) or -1 for "All".
3371 if (sidebarManager_)
3372 {
3373 int sourceValue = sidebarManager_->selectedSourceValue();
3374 if (sourceValue >= 0)
3375 filter.source = static_cast<GameSource>(sourceValue);
3376 }
3377
3378 // Runner version filter from the sidebar — empty means "All".
3379 QString selectedRunnerVersion =
3380 sidebarManager_ ? sidebarManager_->selectedRunnerVersion() : QString();
3381
3382 // Apply collection filter
3383 if (!currentCollection_.empty())
3384 {
3385 filter.collection = currentCollection_;
3386 }
3387
3388 libraryController_->setFilter(filter);
3389
3390 // Get filtered games
3391 auto games = libraryController_->getFilteredGames();
3392
3393 std::vector<const Game*> filteredGames;
3394 filteredGames.reserve(games.size());
3395 for (const auto* game : games)
3396 {
3397 if (!game)
3398 continue;
3399
3400 // For "Updates Available" category (index 5), filter to games needing updates
3401 if (currentCategory_ == 5)
3402 {
3403 // Check if this Steam game needs an update
3404 if (game->source != GameSource::Steam || game->metadata.steamAppId <= 0)
3405 {
3406 continue; // Only Steam games can have detected updates
3407 }
3409 static_cast<uint32_t>(game->metadata.steamAppId));
3410 if (!SteamStateFlags::needsUpdate(progress.stateFlags))
3411 {
3412 continue;
3413 }
3414 }
3415
3416 // For "Running" category (index 6), filter manually
3417 if (currentCategory_ == 6 && !launchController_->isGameRunning(game->id))
3418 {
3419 continue;
3420 }
3421
3422 // Apply runner version filter manually
3423 if (!selectedRunnerVersion.isEmpty())
3424 {
3425 QString gameRunner = QString::fromStdString(game->runnerConfig.runnerVersion);
3426 // Also check runnerType if runnerVersion is empty
3427 if (gameRunner.isEmpty())
3428 {
3429 gameRunner = QString::fromStdString(game->runnerConfig.runnerType);
3430 }
3431 // For native games, use "native" as the version
3432 if (gameRunner.isEmpty() && game->runner == GameRunner::Native)
3433 {
3434 gameRunner = "native";
3435 }
3436 if (gameRunner != selectedRunnerVersion)
3437 continue;
3438 }
3439
3440 filteredGames.push_back(game);
3441 }
3442
3443 // Replace all rows in one shot (model emits modelReset).
3444 // Proxy is currently pass-through (filters already applied above in C++);
3445 // we still set an empty search text so a stale filter doesn't hide rows.
3446 if (gameListProxy_)
3447 {
3448 gameListProxy_->setSearchText(QString());
3449 gameListProxy_->setSourceFilter(QString());
3450 gameListProxy_->setRunnerFilter(QString());
3451 gameListProxy_->setCollectionFilter(QString());
3452 gameListProxy_->setShowRunningOnly(false);
3453 gameListProxy_->setShowUpdatesOnlyGame(false);
3454 gameListProxy_->setShowFavoritesOnly(false);
3455 }
3456 if (gameListModel_)
3457 {
3458 gameListModel_->setGames(filteredGames);
3459 // MED-6 regression fix: the pre-migration code baked icons into each
3460 // QListWidgetItem during createGameItem(). With the model-based list,
3461 // the model starts empty of icons and only refills via the async
3462 // pipeline. Kick the cache-warm pipeline now so rows have thumbnails
3463 // immediately after refresh (otherwise they stay blank until a zoom
3464 // or view-mode change triggers updateItemIcons()).
3465 updateItemIcons();
3466 }
3467
3468 // Update status bar with view mode info
3469 QString viewModeStr;
3470 switch (currentViewMode_)
3471 {
3472 case ViewMode::List:
3473 viewModeStr = "List";
3474 break;
3475 case ViewMode::Grid:
3476 viewModeStr = "Grid";
3477 break;
3478 case ViewMode::Compact:
3479 viewModeStr = "Compact";
3480 break;
3481 }
3482
3483 int totalCount = static_cast<int>(libraryController_->getGameCount());
3484 int showingCount = gameListProxy_ ? gameListProxy_->rowCount() : 0;
3485
3486 statusLabel_->setText(QString("Games: %1 (showing %2) | %3 view")
3487 .arg(totalCount)
3488 .arg(showingCount)
3489 .arg(viewModeStr));
3490
3491 // Update search field placeholder with result count
3492 if (!currentFilter_.empty())
3493 {
3494 searchEdit_->setPlaceholderText(
3495 QString("%1 of %2 games").arg(showingCount).arg(totalCount));
3496 }
3497 else
3498 {
3499 searchEdit_->setPlaceholderText(QString("Search %1 games...").arg(totalCount));
3500 }
3501
3502 // Show context-aware empty state when no games match
3503 if (gameListEmptyOverlay_)
3504 {
3505 if (showingCount == 0)
3506 {
3507 if (totalCount == 0)
3508 {
3509 // First launch - truly empty library
3510 emptyStateLabel_->setText(
3511 "Welcome to Game Launcher!\n\nGet started by importing your game library.");
3512 if (emptyStateAddButton_)
3513 emptyStateAddButton_->setVisible(true);
3514 if (emptyStateImportButton_)
3515 emptyStateImportButton_->setVisible(true);
3516 if (emptyStateClearSearchButton_)
3517 emptyStateClearSearchButton_->setVisible(false);
3518 if (emptyStateShowAllButton_)
3519 emptyStateShowAllButton_->setVisible(false);
3520 }
3521 else if (!currentFilter_.empty())
3522 {
3523 emptyStateLabel_->setText(
3524 QString("No games match \"%1\"").arg(QString::fromStdString(currentFilter_)));
3525 if (emptyStateAddButton_)
3526 emptyStateAddButton_->setVisible(false);
3527 if (emptyStateImportButton_)
3528 emptyStateImportButton_->setVisible(false);
3529 if (emptyStateClearSearchButton_)
3530 emptyStateClearSearchButton_->setVisible(true);
3531 if (emptyStateShowAllButton_)
3532 emptyStateShowAllButton_->setVisible(false);
3533 }
3534 else if (currentCategory_ > 0 || !currentCollection_.empty())
3535 {
3536 QString emptyMessage;
3537 if (currentCategory_ == 1)
3538 emptyMessage = "No favorite games yet\n\nPress F while a game is selected to "
3539 "add it to favorites";
3540 else if (currentCategory_ == 3)
3541 emptyMessage = "No installed games found";
3542 else if (currentCategory_ == 5)
3543 emptyMessage = "All games are up to date";
3544 else if (currentCategory_ == 6)
3545 emptyMessage = "No games currently running";
3546 else if (!currentCollection_.empty())
3547 emptyMessage = QString("No games in \"%1\" collection")
3548 .arg(QString::fromStdString(currentCollection_));
3549 else
3550 emptyMessage = "No games in this category";
3551
3552 emptyStateLabel_->setText(emptyMessage);
3553 if (emptyStateAddButton_)
3554 emptyStateAddButton_->setVisible(false);
3555 if (emptyStateImportButton_)
3556 emptyStateImportButton_->setVisible(false);
3557 if (emptyStateClearSearchButton_)
3558 emptyStateClearSearchButton_->setVisible(false);
3559 if (emptyStateShowAllButton_)
3560 emptyStateShowAllButton_->setVisible(true);
3561 }
3562 else
3563 {
3564 // Generic empty state (no filters, no library games but also no special case)
3565 emptyStateLabel_->setText("No games to show");
3566 if (emptyStateAddButton_)
3567 emptyStateAddButton_->setVisible(false);
3568 if (emptyStateImportButton_)
3569 emptyStateImportButton_->setVisible(false);
3570 if (emptyStateClearSearchButton_)
3571 emptyStateClearSearchButton_->setVisible(false);
3572 if (emptyStateShowAllButton_)
3573 emptyStateShowAllButton_->setVisible(false);
3574 }
3575
3576 gameListEmptyOverlay_->resize(gameList_->viewport()->size());
3577 gameListEmptyOverlay_->raise();
3578 gameListEmptyOverlay_->show();
3579 }
3580 else
3581 {
3582 gameListEmptyOverlay_->hide();
3583 }
3584 }
3585
3586 // Re-enable updates and trigger single repaint
3587 gameList_->setUpdatesEnabled(true);
3588
3589 // Restore previous selection if it still exists in the proxy model
3590 if (!previousSelection.empty())
3591 {
3592 QModelIndex idx = proxyIndexForGameId(previousSelection);
3593 if (idx.isValid())
3594 {
3595 // Use QSignalBlocker RAII to avoid triggering onGameSelected during restoration
3596 const QSignalBlocker blocker(gameList_->selectionModel());
3597 gameList_->setCurrentIndex(idx);
3598
3599 // Restore selectedGameId_ since we blocked the signal
3600 selectedGameId_ = previousSelection;
3601 if (menuBarManager_)
3602 menuBarManager_->setSelectedGameId(selectedGameId_);
3603
3604 // Update details panel to match the restored selection
3605 detailsPanelManager_->update(previousSelection);
3606 }
3607 }
3608}
3609
3610void MainWindow::onGameSelected(const QModelIndex& current, const QModelIndex& previous)
3611{
3612 Q_UNUSED(previous);
3613
3614 if (!current.isValid())
3615 {
3616 selectedGameId_.clear();
3617 detailsPanelManager_->update("");
3618 return;
3619 }
3620
3621 selectedGameId_ = current.data(GameIdRole).toString().toStdString();
3622 detailsPanelManager_->update(selectedGameId_);
3623 if (menuBarManager_)
3624 menuBarManager_->setSelectedGameId(selectedGameId_);
3625}
3626void MainWindow::onLaunchClicked()
3627{
3628 if (selectedGameId_.empty())
3629 return;
3630
3631 const Game* game = libraryController_->getGame(selectedGameId_);
3632 if (!game)
3633 return;
3634
3635 // Check if game needs to be installed or has a paused/partial download
3636 if (!game->isInstalled() && game->source == GameSource::Steam && game->metadata.steamAppId > 0)
3637 {
3638 uint32_t appId = static_cast<uint32_t>(game->metadata.steamAppId);
3639 QString steamUrl;
3640
3641 // Check current download state to determine the right Steam command
3642 // Read directly from appmanifest to detect partial downloads
3643 SteamDownloadProgress progress = SteamDownloadMonitor::readGameState(appId);
3644
3645 if (progress.stateFlags != 0 && !SteamStateFlags::isFullyInstalled(progress.stateFlags))
3646 {
3647 // Game has a partial download - use steam://install to resume
3648 // (steam://run would also launch the game after downloading)
3649 steamUrl = QString("steam://install/%1").arg(appId);
3651 "Resuming paused download with steam://install/{} (state: {}, progress: {}%)",
3652 appId, progress.stateDescription, static_cast<int>(progress.overallProgress * 100));
3653 }
3654 else
3655 {
3656 // Fresh install - use steam://install
3657 steamUrl = QString("steam://install/%1").arg(appId);
3658 Logger::info("Opening Steam install URL: {}", steamUrl.toStdString());
3659 }
3660
3661 // Use steam command directly to avoid KIO protocol handler issues
3662 openSteamUrl(steamUrl);
3663
3664 // Update button to show installing state
3665 detailsPanelManager_->launchButton()->setEnabled(false);
3666 detailsPanelManager_->launchButton()->setText("Opening Steam...");
3667
3668 // Mark game as installing so we track state properly
3669 if (auto gamePtr = libraryController_->getGameForEdit(selectedGameId_))
3670 {
3671 gamePtr->status = GameStatus::Installing;
3672 libraryController_->updateGame(selectedGameId_, *gamePtr);
3673 }
3674
3675 // Start monitoring this game for download progress
3676 if (steamDownloadMonitor_)
3677 {
3678 steamDownloadMonitor_->watchGame(appId);
3679 }
3680
3681 // Show progress widget
3682 if (detailsPanelManager_->downloadProgressWidget())
3683 {
3684 detailsPanelManager_->downloadProgressWidget()->setVisible(true);
3685 detailsPanelManager_->downloadProgressLabel()->setText("Waiting for Steam...");
3686 detailsPanelManager_->downloadProgressBar()->setValue(0);
3687 }
3688
3689 return;
3690 }
3691
3692 if (auto launchGame = libraryController_->getGame(selectedGameId_))
3693 {
3694 launchController_->launchGame(selectedGameId_, *launchGame);
3695 }
3696 else
3697 {
3698 // Fallback to const version
3699 launchController_->launchGame(selectedGameId_, *game);
3700 }
3701}
3702
3703void MainWindow::onStopClicked()
3704{
3705 if (selectedGameId_.empty())
3706 return;
3707
3708 // Use force kill — graceful SIGTERM is often ignored by game processes
3709 launchController_->killGame(selectedGameId_);
3710}
3711
3712void MainWindow::onSearchTextChanged(const QString& text)
3713{
3714 // ToolbarManager emits this signal with the already-debounced value.
3715 currentFilter_ = text.toStdString();
3716 refreshGameList();
3717}
3718
3719void MainWindow::onAddGameClicked()
3720{
3721 AddGameDialog dialog(this);
3722 if (dialog.exec() == QDialog::Accepted)
3723 {
3724 Game game = dialog.getGame();
3725 libraryController_->addGame(game);
3726 updateSourceFilters(); // Update sidebar source filters
3727 updateCategoryCounts(); // Update category counts
3728 refreshGameList();
3729
3730 if (notificationService_)
3731 {
3732 notificationService_->success("Game added: " + game.name);
3733 }
3734 }
3735}
3736
3737void MainWindow::onSettingsClicked()
3738{
3739 SettingsDialog dialog(settingsController_.get(), this);
3740 dialog.exec();
3741
3742 // Apply menu mode change (hamburger vs menu bar)
3743 updateMenuMode();
3744
3745#ifdef HAVE_WEBENGINE
3746 const auto& app = settingsController_->getAppSettings();
3747 if (panelHABtn_)
3748 panelHABtn_->setVisible(app.enableHomeAssistant);
3749 if (!app.enableHomeAssistant && haContainer_ && haContainer_->isVisible())
3750 togglePanel(haContainer_, nullptr, "Home Assistant");
3751 if (haPanel_ && !app.homeAssistantUrl.empty())
3752 haPanel_->setUrl(QString::fromStdString(app.homeAssistantUrl));
3753#endif
3754}
3755
3756void MainWindow::onRefreshLibrary()
3757{
3758 libraryController_->loadLibrary();
3759
3760 // Re-scan for running games with updated library
3762 libraryController_->getAllGames(),
3763 [this](const std::string& gameId, const std::function<void(Game&)>& updater)
3764 { libraryController_->executeWithGame(gameId, updater); });
3765
3766 // Update sidebar filters with current library data
3767 populateRunnerVersions();
3768 updateSourceFilters();
3769 updateCategoryCounts();
3770
3771 refreshGameList();
3772}
3773
3774void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
3775{
3776 if (reason == QSystemTrayIcon::DoubleClick)
3777 {
3778 if (isVisible())
3779 {
3780 hide();
3781 }
3782 else
3783 {
3784 show();
3785 activateWindow();
3786 }
3787 }
3788}
3789
3790// ==============================================================================
3791// View Mode Handling
3792// ==============================================================================
3793
3794void MainWindow::onViewModeChanged(ViewMode mode)
3795{
3796 if (currentViewMode_ == mode)
3797 return;
3798
3799 currentViewMode_ = mode;
3800 if (menuBarManager_)
3801 menuBarManager_->setViewMode(mode);
3802 applyViewMode();
3803 refreshGameList();
3804}
3805
3806void MainWindow::applyViewMode()
3807{
3808 // Update delegate's view mode and zoom level
3809 gameListDelegate_->setViewMode(currentViewMode_);
3810 gameListDelegate_->setZoomLevel(zoomLevel_);
3811
3812 // Apply zoom level (50-200%)
3813 double zoomFactor = zoomLevel_ / 100.0;
3814
3815 switch (currentViewMode_)
3816 {
3817 case ViewMode::List:
3818 {
3819 int iconW = static_cast<int>(64 * zoomFactor);
3820 int iconH = static_cast<int>(36 * zoomFactor);
3821 gameList_->setViewMode(QListView::ListMode);
3822 gameList_->setIconSize(QSize(iconW, iconH));
3823 gameList_->setSpacing(0); // Delegate handles spacing
3824 gameList_->setGridSize(QSize());
3825 gameList_->setWordWrap(false);
3826 gameList_->setUniformItemSizes(true);
3827 }
3828 break;
3829
3830 case ViewMode::Grid:
3831 {
3832 int gridIconW = static_cast<int>(GRID_ICON_WIDTH * zoomFactor);
3833 int gridIconH = static_cast<int>(GRID_ICON_HEIGHT * zoomFactor);
3834 int gridSpacing = static_cast<int>(12 * zoomFactor);
3835 int textSpace = static_cast<int>(40 * zoomFactor);
3836 gameList_->setViewMode(QListView::IconMode);
3837 gameList_->setIconSize(QSize(gridIconW, gridIconH));
3838 gameList_->setSpacing(gridSpacing);
3839 // Grid size needs extra height for game title text below the cover
3840 gameList_->setGridSize(QSize(gridIconW + 16, gridIconH + textSpace));
3841 gameList_->setWordWrap(true);
3842 gameList_->setUniformItemSizes(true);
3843 gameList_->setResizeMode(QListView::Adjust);
3844 gameList_->setMovement(QListView::Static);
3845 gameList_->verticalScrollBar()->setSingleStep(30);
3846 }
3847 break;
3848
3849 case ViewMode::Compact:
3850 {
3851 int compactIcon = static_cast<int>(28 * zoomFactor);
3852 gameList_->setViewMode(QListView::ListMode);
3853 gameList_->setIconSize(QSize(compactIcon, compactIcon));
3854 gameList_->setSpacing(0); // Delegate handles spacing
3855 gameList_->setGridSize(QSize());
3856 gameList_->setWordWrap(false);
3857 gameList_->setUniformItemSizes(true);
3858 }
3859 break;
3860 }
3861}
3862
3863void MainWindow::updateGridIconSize()
3864{
3865 if (currentViewMode_ == ViewMode::Grid)
3866 {
3867 double zoomFactor = ThemeManager::instance().zoomLevel() / 100.0;
3868 int spacing = static_cast<int>(8 * zoomFactor);
3869
3870 // Recalculate grid size based on available width
3871 int availableWidth = gameList_->viewport()->width();
3872 int baseItemWidth = static_cast<int>(GRID_ICON_WIDTH * zoomFactor) + spacing * 2;
3873 int columns = qMax(2, availableWidth / baseItemWidth);
3874
3875 // Calculate item width to fill available space evenly
3876 int itemWidth = (availableWidth - (columns + 1) * spacing) / columns;
3877 itemWidth = qMax(itemWidth, static_cast<int>(120 * zoomFactor));
3878
3879 // Maintain 2:3 aspect ratio for covers
3880 int iconWidth = itemWidth - 10;
3881 int iconHeight = static_cast<int>(iconWidth * 1.5);
3882 int textSpace = 32;
3883 int itemHeight = iconHeight + textSpace;
3884
3885 gameList_->setIconSize(QSize(iconWidth, iconHeight));
3886 gameList_->setGridSize(QSize(itemWidth, itemHeight));
3887 gameList_->setSpacing(spacing);
3888 }
3889}
3890
3891void MainWindow::resizeEvent(QResizeEvent* event)
3892{
3893 QMainWindow::resizeEvent(event);
3894
3895 // Debounce resize to prevent expensive layout recalculations during drag
3896 // Use longer interval (200ms) to batch resize events during splitter drag
3897 if (!resizeDebounceTimer_)
3898 {
3899 resizeDebounceTimer_ = new QTimer(this);
3900 resizeDebounceTimer_->setSingleShot(true);
3901 resizeDebounceTimer_->setInterval(200); // 200ms debounce (was 50ms)
3902 connect(resizeDebounceTimer_, &QTimer::timeout, this, &MainWindow::updateGridIconSize);
3903 }
3904 resizeDebounceTimer_->start();
3905}
3906
3907void MainWindow::changeEvent(QEvent* event)
3908{
3909 QMainWindow::changeEvent(event);
3910
3911 if (event->type() == QEvent::WindowStateChange)
3912 {
3913 // Stop/start timers based on window visibility to save CPU when minimized
3914 bool isMinimized = windowState() & Qt::WindowMinimized;
3915
3916 // Find and control named timers
3917 QTimer* updateTimer = findChild<QTimer*>("updateTimer");
3918 if (updateTimer)
3919 {
3920 if (isMinimized)
3921 updateTimer->stop();
3922 else
3923 updateTimer->start();
3924 }
3925
3926 if (frameMetricsTimer_)
3927 {
3928 if (isMinimized)
3929 frameMetricsTimer_->stop();
3930 else
3931 frameMetricsTimer_->start();
3932 }
3933
3934#ifdef HAVE_QTERMWIDGET
3935 // Pause/resume terminal process (btop/htop) to save CPU when minimized
3936 if (terminalPanel_)
3937 {
3938 if (isMinimized)
3939 terminalPanel_->pauseProcess();
3940 else
3941 terminalPanel_->resumeProcess();
3942 }
3943#endif
3944 }
3945}
3946
3947void MainWindow::dragEnterEvent(QDragEnterEvent* event)
3948{
3949 if (!event->mimeData()->hasUrls())
3950 {
3951 event->ignore();
3952 return;
3953 }
3954
3955 // Accept if any of the dropped files look like game executables
3956 const QList<QUrl> urls = event->mimeData()->urls();
3957 for (const QUrl& url : urls)
3958 {
3959 if (!url.isLocalFile())
3960 continue;
3961
3962 QString path = url.toLocalFile();
3963 QFileInfo fileInfo(path);
3964 if (!fileInfo.isFile())
3965 continue;
3966
3967 // Check for common game executable extensions or executable permission
3968 QString suffix = fileInfo.suffix().toLower();
3969 static const QStringList gameExtensions = {
3970 "exe", "msi", // Windows executables (Wine/Proton)
3971 "sh", "x86_64", "x86", "appimage", // Linux executables
3972 "jar", // Java games
3973 };
3974
3975 if (gameExtensions.contains(suffix) || fileInfo.isExecutable())
3976 {
3977 event->acceptProposedAction();
3978 return;
3979 }
3980 }
3981
3982 event->ignore();
3983}
3984
3985void MainWindow::dropEvent(QDropEvent* event)
3986{
3987 if (!event->mimeData()->hasUrls())
3988 {
3989 event->ignore();
3990 return;
3991 }
3992
3993 const QList<QUrl> urls = event->mimeData()->urls();
3994 for (const QUrl& url : urls)
3995 {
3996 if (!url.isLocalFile())
3997 continue;
3998
3999 QString filePath = url.toLocalFile();
4000 QFileInfo fileInfo(filePath);
4001 if (!fileInfo.isFile())
4002 continue;
4003
4004 // Check if it looks like an executable
4005 QString suffix = fileInfo.suffix().toLower();
4006 static const QStringList gameExtensions = {
4007 "exe", "msi", "sh", "x86_64", "x86", "appimage", "jar",
4008 };
4009
4010 if (!gameExtensions.contains(suffix) && !fileInfo.isExecutable())
4011 continue;
4012
4013 // Extract game name from filename:
4014 // Strip extension, replace underscores/dashes with spaces, title case
4015 QString baseName = fileInfo.completeBaseName();
4016 baseName.replace('_', ' ');
4017 baseName.replace('-', ' ');
4018
4019 // Title case: capitalize first letter of each word
4020 QStringList words = baseName.split(' ', Qt::SkipEmptyParts);
4021 for (QString& word : words)
4022 {
4023 if (!word.isEmpty())
4024 {
4025 word[0] = word[0].toUpper();
4026 }
4027 }
4028 QString gameName = words.join(' ');
4029
4030 // Create a pre-filled game and use the AddGameDialog
4031 Game game;
4032 game.name = gameName.toStdString();
4033 game.runnerConfig.executablePath = filePath.toStdString();
4034 game.runnerConfig.workingDirectory = fileInfo.absolutePath().toStdString();
4036
4037 // Detect runner based on file extension
4038 if (suffix == "exe" || suffix == "msi")
4039 {
4040 game.runner = GameRunner::Wine;
4041 }
4042 else
4043 {
4045 }
4046
4047 // Open AddGameDialog pre-filled with detected info
4048 AddGameDialog dialog(this);
4049 dialog.setGame(game);
4050 if (dialog.exec() == QDialog::Accepted)
4051 {
4052 Game resultGame = dialog.getGame();
4053 libraryController_->addGame(resultGame);
4054 updateSourceFilters();
4055 updateCategoryCounts();
4056 refreshGameList();
4057
4058 if (notificationService_)
4059 {
4060 notificationService_->success("Game added: " + resultGame.name);
4061 }
4062 }
4063
4064 // Only process the first valid file
4065 break;
4066 }
4067
4068 event->acceptProposedAction();
4069}
4070
4071bool MainWindow::eventFilter(QObject* obj, QEvent* event)
4072{
4073 // Keep the empty-state overlay sized to the game list viewport.
4074 if (gameList_ && obj == gameList_->viewport() && event->type() == QEvent::Resize)
4075 {
4076 if (gameListEmptyOverlay_ && gameListEmptyOverlay_->isVisible())
4077 {
4078 gameListEmptyOverlay_->resize(gameList_->viewport()->size());
4079 gameListEmptyOverlay_->raise();
4080 }
4081 // fall through — other filters may still need this event
4082 }
4083
4084 // Note: click-to-edit handler for userNotesLabel_ moved into
4085 // DetailsPanelManager (MED-7 extraction).
4086 return QMainWindow::eventFilter(obj, event);
4087}
4088
4089void MainWindow::updateItemIcons()
4090{
4091 // Populate the model's DecorationRole icons for every row. This path is
4092 // synchronous — each call to GameThumbnailCache::getGameThumbnail either
4093 // returns an already-cached pixmap in O(1) or loads+scales from disk
4094 // immediately. For a typical library size the total cost is a brief
4095 // GUI-thread hitch on first refresh; subsequent refreshes are cache hits.
4096 //
4097 // Called from refreshGameList() (after model reset) and applyZoomChange()
4098 // (after icon-size change).
4099
4100 double zoomFactor = zoomLevel_ / 100.0;
4101 QSize iconSize;
4102 ImageType preferredImageType;
4103
4104 switch (currentViewMode_)
4105 {
4106 case ViewMode::Grid:
4107 iconSize = QSize(static_cast<int>(GRID_ICON_WIDTH * zoomFactor),
4108 static_cast<int>(GRID_ICON_HEIGHT * zoomFactor));
4109 preferredImageType = ImageType::VerticalCover;
4110 break;
4111 case ViewMode::Compact:
4112 iconSize = QSize(static_cast<int>(48 * zoomFactor), static_cast<int>(27 * zoomFactor));
4113 preferredImageType = ImageType::Header;
4114 break;
4115 case ViewMode::List:
4116 default:
4117 iconSize = QSize(static_cast<int>(64 * zoomFactor), static_cast<int>(36 * zoomFactor));
4118 preferredImageType = ImageType::Header;
4119 break;
4120 }
4121
4122 if (!gameListProxy_ || !gameListModel_)
4123 return;
4124
4125 // Get visible rect for prioritization
4126 QRect visibleRect = gameList_->viewport()->rect();
4127
4128 // Process visible items first (high priority), then rest (low priority)
4129 for (int pass = 0; pass < 2; ++pass)
4130 {
4131 bool visiblePass = (pass == 0);
4132
4133 for (int i = 0; i < gameListProxy_->rowCount(); ++i)
4134 {
4135 QModelIndex idx = gameListProxy_->index(i, 0);
4136 if (!idx.isValid())
4137 continue;
4138
4139 // Check if item is visible
4140 QRect itemRect = gameList_->visualRect(idx);
4141 bool isVisible = visibleRect.intersects(itemRect);
4142
4143 // First pass = visible only, second pass = non-visible only
4144 if (visiblePass != isVisible)
4145 continue;
4146
4147 QString gameId = idx.data(GameIdRole).toString();
4148 const Game* game = libraryController_->getGame(gameId.toStdString());
4149 if (!game)
4150 continue;
4151
4152 // Request thumbnail - will return from cache or trigger async load
4153 QPixmap thumbnail =
4154 imageCache_ ? imageCache_->getGameThumbnail(game, iconSize, preferredImageType)
4155 : QPixmap();
4156 if (!thumbnail.isNull())
4157 {
4158 gameListModel_->setIcon(gameId.toStdString(), QIcon(thumbnail));
4159 }
4160 }
4161 }
4162}
4163
4164// ==============================================================================
4165// Sort Handling
4166// ==============================================================================
4167
4168void MainWindow::onSortChanged(int index)
4169{
4170 SortOption sort = static_cast<SortOption>(sortCombo_->itemData(index).toInt());
4171 if (currentSort_ == sort)
4172 return;
4173
4174 currentSort_ = sort;
4175 if (menuBarManager_)
4176 menuBarManager_->setSortOption(sort);
4177
4178 // Apply sort to library controller
4179 core::SortOptions sortOptions;
4180 switch (sort)
4181 {
4184 break;
4187 break;
4190 break;
4193 break;
4196 break;
4199 break;
4202 break;
4205 break;
4206 }
4207
4208 libraryController_->setSort(sortOptions);
4209 refreshGameList();
4210}
4211
4212void MainWindow::onZoomChanged(int value)
4213{
4214 // ToolbarManager emits this signal once the slider has settled (150ms
4215 // debounce). It also keeps the zoomLabel_ text in sync internally during
4216 // the drag, so we only need to apply the heavy layout work here.
4217 zoomLevel_ = value;
4218 applyZoomChange();
4219}
4220
4221void MainWindow::applyZoomChange()
4222{
4223 // Batch all updates - disable painting during changes
4224 gameList_->setUpdatesEnabled(false);
4225
4226 if (currentViewMode_ == ViewMode::Grid)
4227 {
4228 // For Grid view, switch to ListMode first to clear Qt's layout cache
4229 gameList_->setViewMode(QListView::ListMode);
4230 }
4231
4232 // Apply new grid/icon sizes
4233 applyViewMode();
4234
4235 // Update all item icons to match the new zoom level
4236 updateItemIcons();
4237
4238 // Re-enable updates and force single layout pass
4239 gameList_->setUpdatesEnabled(true);
4240 gameList_->doItemsLayout();
4241 gameList_->viewport()->update();
4242}
4243
4244// ==============================================================================
4245// Image Helper Methods — extracted to GameThumbnailCache in MED-7.
4246// See ui/qt/game_thumbnail_cache.{h,cpp}. MainWindow now owns an instance
4247// via imageCache_ and delegates findBestImage/getGameThumbnail/getHeroImage
4248// /buildImagePathCache through it.
4249// ==============================================================================
4250
4251void MainWindow::populateRunnerVersions()
4252{
4253 if (sidebarManager_)
4254 sidebarManager_->populateRunnerVersions();
4255}
4256
4257void MainWindow::updateSourceFilters()
4258{
4259 if (sidebarManager_)
4260 sidebarManager_->updateSourceFilters();
4261}
4262
4263void MainWindow::updateCategoryCounts()
4264{
4265 if (sidebarManager_)
4266 sidebarManager_->updateCategoryCounts();
4267}
4268
4269// ==============================================================================
4270// Collections Management
4271// ==============================================================================
4272
4273void MainWindow::updateCollectionsList()
4274{
4275 if (sidebarManager_)
4276 sidebarManager_->updateCollectionsList();
4277}
4278
4279void MainWindow::showCreateCollectionDialog()
4280{
4281 if (sidebarManager_)
4282 sidebarManager_->showCreateCollectionDialog(this);
4283}
4284
4285void MainWindow::fetchMissingProtonDB()
4286{
4287 QPointer<MainWindow> self = this;
4288 auto* libraryController = libraryController_.get();
4289 (void)QtConcurrent::run(
4290 [self, libraryController]()
4291 {
4292 if (!self)
4293 return;
4294
4295 auto allGames = libraryController->getAllGames();
4296
4297 std::vector<std::pair<std::string, int>> needsFetch; // (gameId, steamAppId)
4298 const time_t oneWeekAgo = time(nullptr) - (7 * 24 * 60 * 60);
4299 for (const auto* game : allGames)
4300 {
4301 if (game->source == GameSource::Steam && game->metadata.steamAppId > 0)
4302 {
4303 if (game->metadata.protondbLastUpdated == 0 ||
4304 game->metadata.protondbLastUpdated < oneWeekAgo)
4305 {
4306 needsFetch.emplace_back(game->id, game->metadata.steamAppId);
4307 }
4308 }
4309 }
4310
4311 if (needsFetch.empty())
4312 return;
4313
4314 if (self)
4315 {
4316 QMetaObject::invokeMethod(
4317 self.data(),
4318 [self, count = needsFetch.size()]()
4319 {
4320 if (!self)
4321 return;
4322 if (self->statusProgressBar_)
4323 {
4324 self->statusProgressBar_->setVisible(true);
4325 self->statusLabel_->setText("Fetching ProtonDB data for " +
4326 QString::number(count) + " game(s)...");
4327 }
4328 },
4329 Qt::QueuedConnection);
4330 }
4331
4332 int updated = 0;
4333 for (const auto& entry : needsFetch)
4334 {
4335 if (!self)
4336 break;
4337
4338 const std::string& gameId = entry.first;
4339 int steamAppId = entry.second;
4340
4341 auto info = ProtonDBService::getGameInfo(steamAppId);
4342 if (info.found && self)
4343 {
4344 QMetaObject::invokeMethod(
4345 self.data(),
4346 [self, libraryController, gameId, info]()
4347 {
4348 if (!self)
4349 return;
4350 Game* mutableGame = libraryController->getGameForEdit(gameId);
4351 if (mutableGame)
4352 {
4353 mutableGame->metadata.protondbTier = info.tier;
4354 mutableGame->metadata.protondbConfidence = info.confidence;
4355 mutableGame->metadata.protondbScore = info.score;
4356 mutableGame->metadata.protondbLastUpdated = time(nullptr);
4357 libraryController->updateGame(gameId, *mutableGame);
4358 }
4359 },
4360 Qt::QueuedConnection);
4361 updated++;
4362 }
4363 }
4364
4365 if (self)
4366 {
4367 QMetaObject::invokeMethod(
4368 self.data(),
4369 [self, libraryController, updated]()
4370 {
4371 if (!self)
4372 return;
4373 if (self->statusProgressBar_)
4374 self->statusProgressBar_->setVisible(false);
4375
4376 if (updated > 0)
4377 {
4378 libraryController->saveLibrary();
4379 self->refreshGameList();
4380 if (self->notificationService_)
4381 {
4382 self->notificationService_->success("Updated ProtonDB data for " +
4383 std::to_string(updated) +
4384 " game(s)");
4385 }
4386 }
4387 },
4388 Qt::QueuedConnection);
4389 }
4390 });
4391}
4392
4393void MainWindow::syncSteamInstalledStatus()
4394{
4395 // Scan Steam libraries to get current installed games
4396 SteamLibraryScanner scanner;
4397 auto installedGames = scanner.scanAllLibraries();
4398
4399 // Create a set of installed app IDs for quick lookup
4400 std::set<uint32_t> installedAppIds;
4401 for (const auto& steamGame : installedGames)
4402 {
4403 // Only count as installed if StateFlags indicates fully installed
4404 if (SteamStateFlags::isFullyInstalled(steamGame.stateFlags))
4405 {
4406 installedAppIds.insert(steamGame.appId);
4407 }
4408 }
4409
4410 // Update all Steam games in library to match actual installed status
4411 int updated = 0;
4412 for (const auto* game : libraryController_->getAllGames())
4413 {
4414 if (game->source != GameSource::Steam || game->metadata.steamAppId <= 0)
4415 {
4416 continue;
4417 }
4418
4419 uint32_t appId = static_cast<uint32_t>(game->metadata.steamAppId);
4420 bool actuallyInstalled = installedAppIds.count(appId) > 0;
4421
4422 // Check if we need to update
4423 if (game->metadata.steamInstalled != actuallyInstalled)
4424 {
4425 if (auto gamePtr = libraryController_->getGameForEdit(game->id))
4426 {
4427 gamePtr->metadata.steamInstalled = actuallyInstalled;
4428 gamePtr->status =
4429 actuallyInstalled ? GameStatus::Installed : GameStatus::NotInstalled;
4430 libraryController_->updateGame(game->id, *gamePtr);
4431 updated++;
4432
4433 Logger::info("[MainWindow] Synced Steam game {} ({}): installed={}", game->name,
4434 appId, actuallyInstalled);
4435 }
4436 }
4437 }
4438
4439 if (updated > 0)
4440 {
4441 Logger::info("[MainWindow] Synced installed status for {} Steam games", updated);
4442 }
4443}
4444
4445// ==============================================================================
4446// Gaming Layout Management
4447// ==============================================================================
4448
4449void MainWindow::onGameStarted(const std::string& gameId)
4450{
4451 Logger::info("[MainWindow] Game started: {}", gameId);
4452
4453 if (!settingsController_)
4454 return;
4455
4456 const auto& settings = settingsController_->getAppSettings();
4457
4458 Logger::info("[MainWindow] Settings: autoSwitch={}, autoGamingLayout={}, widthPercent={}, "
4459 "edge={}, fullHeight={}",
4460 settings.autoSwitchToRunningGame, settings.autoGamingLayout,
4461 settings.gamingLayoutWidthPercent, settings.gamingLayoutEdge,
4462 settings.gamingLayoutFullHeight);
4463
4464 // Auto-switch to the running game's details panel
4465 if (settings.autoSwitchToRunningGame)
4466 {
4467 // Select the game in the list
4468 QModelIndex idx = proxyIndexForGameId(gameId);
4469 if (idx.isValid())
4470 {
4471 gameList_->setCurrentIndex(idx);
4472 gameList_->scrollTo(idx);
4473 }
4474
4475 // Ensure details panel is visible
4476 if (detailsContainer_ && !detailsContainer_->isVisible())
4477 {
4478 togglePanel(detailsContainer_, panelDetailsBtn_, "Details");
4479 }
4480
4481 Logger::info("[MainWindow] Auto-switched to game details panel");
4482 }
4483
4484 // Auto-enter gaming layout if enabled
4485 if (settings.autoGamingLayout && !isInGamingLayout_)
4486 {
4487 Logger::info("[MainWindow] Entering gaming layout...");
4488 enterGamingLayout();
4489 }
4490 else
4491 {
4493 "[MainWindow] Gaming layout skipped: autoGamingLayout={}, isInGamingLayout_={}",
4494 settings.autoGamingLayout, isInGamingLayout_);
4495 }
4496}
4497
4498void MainWindow::onGameStopped(const std::string& gameId)
4499{
4500 Logger::info("[MainWindow] Game stopped: {}", gameId);
4501
4502 if (!settingsController_)
4503 return;
4504
4505 const auto& settings = settingsController_->getAppSettings();
4506
4507 // Restore layout if we were in gaming layout (and user didn't manually override)
4508 if (isInGamingLayout_ && settings.restoreLayoutOnExit)
4509 {
4510 exitGamingLayout();
4511 }
4512 else if (gamingLayoutOverridden_)
4513 {
4514 Logger::info("[MainWindow] Gaming layout was manually overridden - not restoring layout");
4515 }
4516
4517 // Reset override flag for next game session
4518 gamingLayoutOverridden_ = false;
4519}
4520
4521void MainWindow::enterGamingLayout()
4522{
4523 if (isInGamingLayout_)
4524 return;
4525
4526 Logger::info("[MainWindow] Entering gaming layout");
4527
4528 // Reset override flag when entering gaming layout
4529 gamingLayoutOverridden_ = false;
4530
4531 // Save current panel visibility state
4532 savedSidebarVisible_ = sidebarContainer_ && sidebarContainer_->isVisible();
4533 savedGameListVisible_ = gameListContainer_ && gameListContainer_->isVisible();
4534 savedDetailsVisible_ = detailsContainer_ && detailsContainer_->isVisible();
4535#ifdef HAVE_QTERMWIDGET
4536 savedMonitorVisible_ = terminalContainer_ && terminalContainer_->isVisible();
4537#endif
4538#ifdef HAVE_WEBENGINE
4539 savedHAVisible_ = haContainer_ && haContainer_->isVisible();
4540#endif
4541
4542 // Save current splitter sizes
4543 if (mainSplitter_)
4544 {
4545 savedSplitterSizes_ = mainSplitter_->sizes();
4546 }
4547
4548 // NOTE: Window geometry is NOT changed here - let window manager handle position/size
4549 // We only manage which panels are visible and their proportions within the window
4550
4551 // Configure panels for gaming layout:
4552 // - Hide sidebar (not needed during gaming)
4553 // - Hide games list (we already know what's running)
4554 // - Show details panel (for running game info/metrics)
4555 // - Show monitor panel (for btop/system monitoring)
4556
4557 // Hide sidebar - remove minimum width so splitter can collapse it
4558 if (sidebarContainer_)
4559 {
4560 sidebarContainer_->setMinimumWidth(0);
4561 sidebarContainer_->setMaximumWidth(0);
4562 sidebarContainer_->setVisible(false);
4563 if (panelSidebarBtn_)
4564 panelSidebarBtn_->setChecked(false);
4565 }
4566
4567 // Hide games list - remove minimum width so splitter can collapse it
4568 if (gameListContainer_)
4569 {
4570 gameListContainer_->setMinimumWidth(0);
4571 gameListContainer_->setMaximumWidth(0);
4572 gameListContainer_->setVisible(false);
4573 if (panelGamesBtn_)
4574 panelGamesBtn_->setChecked(false);
4575 }
4576
4577 // Ensure details panel is visible and can expand
4578 if (detailsContainer_)
4579 {
4580 detailsContainer_->setMinimumWidth(200);
4581 detailsContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4582 detailsContainer_->setVisible(true);
4583 if (panelDetailsBtn_)
4584 panelDetailsBtn_->setChecked(true);
4585 }
4586
4587#ifdef HAVE_QTERMWIDGET
4588 // Show and start the monitor panel (btop)
4589 if (terminalContainer_)
4590 {
4591 terminalContainer_->setMinimumWidth(200);
4592 terminalContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4593 terminalContainer_->setVisible(true);
4594 if (panelMonitorBtn_)
4595 panelMonitorBtn_->setChecked(true);
4596
4597 // Start btop if terminal is ready
4598 if (terminalPanel_)
4599 {
4600 terminalPanel_->resumeProcess();
4601 QString command = "btop";
4602 if (monitorTypeCombo_)
4603 {
4604 switch (monitorTypeCombo_->currentIndex())
4605 {
4606 case 0:
4607 command = "btop";
4608 break;
4609 case 1:
4610 command = "htop";
4611 break;
4612 case 2:
4613 command = "top";
4614 break;
4615 case 3:
4616 {
4617 QString s = QString::fromLocal8Bit(qgetenv("SHELL"));
4618 command = s.isEmpty() ? QStringLiteral("/bin/bash") : s;
4619 break;
4620 }
4621 default:
4622 break;
4623 }
4624 }
4625 terminalPanel_->startCommand(command);
4626 }
4627 }
4628#endif
4629
4630#ifdef HAVE_WEBENGINE
4631 // Hide HA panel during gaming layout
4632 if (haContainer_)
4633 {
4634 haContainer_->setMinimumWidth(0);
4635 haContainer_->setMaximumWidth(0);
4636 haContainer_->setVisible(false);
4637 if (panelHABtn_)
4638 panelHABtn_->setChecked(false);
4639 }
4640#endif
4641
4642 isInGamingLayout_ = true;
4643
4644 // Defer splitter adjustment to after layout is processed
4645 // This ensures the window geometry is fully applied first
4646 QTimer::singleShot(
4647 200, this,
4648 [this]()
4649 {
4650 if (!mainSplitter_ || !isInGamingLayout_)
4651 return;
4652
4653 // Flush pending layout events once so the splitter width read below
4654 // is accurate. (Calling processEvents() re-enters the event loop and
4655 // can deliver arbitrary events mid-slot, so avoid doing it more than
4656 // necessary — the redundant second call was removed.)
4657 QApplication::processEvents();
4658
4659 // Get actual splitter width after layout
4660 int splitterWidth = mainSplitter_->width();
4661 Logger::info("[MainWindow] Gaming layout: window width={}, splitter width={}", width(),
4662 splitterWidth);
4663
4664 // Calculate target sizes for visible panels
4665 QList<int> targetSizes;
4666#ifdef HAVE_QTERMWIDGET
4667 int detailsWidth = splitterWidth * 15 / 100;
4668 int monitorWidth = splitterWidth - detailsWidth;
4669 targetSizes << 0 << 0 << detailsWidth << monitorWidth;
4670 Logger::info("[MainWindow] Gaming layout target: 0, 0, {}, {}", detailsWidth,
4671 monitorWidth);
4672#else
4673 targetSizes << 0 << 0 << splitterWidth;
4674#endif
4675 // Animate splitter transition over ~300ms with ease-out curve
4676 QList<int> startSizes = mainSplitter_->sizes();
4677 const int animSteps = 15;
4678 const int animIntervalMs = 20;
4679 int* step = new int(0);
4680 QTimer* animTimer = new QTimer(this);
4681 animTimer->setInterval(animIntervalMs);
4682 connect(animTimer, &QTimer::timeout, this,
4683 [this, startSizes, targetSizes, step, animTimer]()
4684 {
4685 (*step)++;
4686 double t = static_cast<double>(*step) / animSteps;
4687 double ease = 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t);
4688 QList<int> interpolated;
4689 for (int i = 0; i < qMin(startSizes.size(), targetSizes.size()); ++i)
4690 interpolated
4691 << startSizes[i] +
4692 static_cast<int>((targetSizes[i] - startSizes[i]) * ease);
4693 mainSplitter_->setSizes(interpolated);
4694 if (*step >= animSteps)
4695 {
4696 mainSplitter_->setSizes(targetSizes);
4697 animTimer->stop();
4698 animTimer->deleteLater();
4699 delete step;
4700 }
4701 });
4702 animTimer->start();
4703 });
4704
4705 // Update toolbar visibility
4706 QTimer::singleShot(0, this, &MainWindow::updateToolbarVisibility);
4707
4708 Logger::info("[MainWindow] Gaming layout entered - panels configured");
4709}
4710
4711void MainWindow::exitGamingLayout()
4712{
4713 if (!isInGamingLayout_)
4714 return;
4715
4716 Logger::info("[MainWindow] Exiting gaming layout");
4717
4718 // NOTE: Window geometry is NOT restored - window manager handles that
4719 // We only restore panel visibility and their proportions
4720
4721 // Restore panel visibility and minimum widths
4722 if (sidebarContainer_)
4723 {
4724 sidebarContainer_->setMinimumWidth(120);
4725 sidebarContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4726 sidebarContainer_->setVisible(savedSidebarVisible_);
4727 if (panelSidebarBtn_)
4728 panelSidebarBtn_->setChecked(savedSidebarVisible_);
4729 }
4730
4731 if (gameListContainer_)
4732 {
4733 gameListContainer_->setMinimumWidth(200);
4734 gameListContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4735 gameListContainer_->setVisible(savedGameListVisible_);
4736 if (panelGamesBtn_)
4737 panelGamesBtn_->setChecked(savedGameListVisible_);
4738 }
4739
4740 if (detailsContainer_)
4741 {
4742 detailsContainer_->setMinimumWidth(250);
4743 detailsContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4744 detailsContainer_->setVisible(savedDetailsVisible_);
4745 if (panelDetailsBtn_)
4746 panelDetailsBtn_->setChecked(savedDetailsVisible_);
4747 }
4748
4749#ifdef HAVE_QTERMWIDGET
4750 if (terminalContainer_)
4751 {
4752 terminalContainer_->setMinimumWidth(300);
4753 terminalContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4754 terminalContainer_->setVisible(savedMonitorVisible_);
4755 if (panelMonitorBtn_)
4756 panelMonitorBtn_->setChecked(savedMonitorVisible_);
4757
4758 // If we're hiding the monitor, pause the terminal process
4759 if (!savedMonitorVisible_ && terminalPanel_)
4760 {
4761 terminalPanel_->pauseProcess();
4762 }
4763 }
4764#endif
4765
4766#ifdef HAVE_WEBENGINE
4767 if (haContainer_)
4768 {
4769 haContainer_->setMinimumWidth(400);
4770 haContainer_->setMaximumWidth(QWIDGETSIZE_MAX);
4771 haContainer_->setVisible(savedHAVisible_);
4772 if (panelHABtn_)
4773 panelHABtn_->setChecked(savedHAVisible_);
4774 }
4775#endif
4776
4777 // Animate splitter restoration over ~300ms with ease-out curve
4778 if (mainSplitter_ && !savedSplitterSizes_.isEmpty())
4779 {
4780 QList<int> startSizes = mainSplitter_->sizes();
4781 QList<int> targetSizes = savedSplitterSizes_;
4782 const int animSteps = 15;
4783 const int animIntervalMs = 20;
4784 int* step = new int(0);
4785 QTimer* animTimer = new QTimer(this);
4786 animTimer->setInterval(animIntervalMs);
4787 connect(animTimer, &QTimer::timeout, this,
4788 [this, startSizes, targetSizes, step, animTimer]()
4789 {
4790 (*step)++;
4791 double t = static_cast<double>(*step) / animSteps;
4792 double ease = 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t);
4793 QList<int> interpolated;
4794 for (int i = 0; i < qMin(startSizes.size(), targetSizes.size()); ++i)
4795 interpolated
4796 << startSizes[i] +
4797 static_cast<int>((targetSizes[i] - startSizes[i]) * ease);
4798 mainSplitter_->setSizes(interpolated);
4799 if (*step >= animSteps)
4800 {
4801 mainSplitter_->setSizes(targetSizes);
4802 animTimer->stop();
4803 animTimer->deleteLater();
4804 delete step;
4805 }
4806 });
4807 animTimer->start();
4808 }
4809
4810 isInGamingLayout_ = false;
4811
4812 // Update toolbar visibility
4813 QTimer::singleShot(0, this, &MainWindow::updateToolbarVisibility);
4814}
4815
4816void MainWindow::checkRunningGameOnStartup()
4817{
4818 Logger::info("[MainWindow] Checking for already-running games on startup");
4819
4820 if (!launchController_ || !libraryController_)
4821 {
4822 Logger::warn("[MainWindow] Controllers not ready for startup check");
4823 return;
4824 }
4825
4826 // Log settings state
4827 if (settingsController_)
4828 {
4829 const auto& settings = settingsController_->getAppSettings();
4830 Logger::info("[MainWindow] Startup check - autoSwitch={}, autoGamingLayout={}",
4831 settings.autoSwitchToRunningGame, settings.autoGamingLayout);
4832 }
4833
4834 // Find any running game from our library
4835 std::string runningGameId;
4836 int checkedCount = 0;
4837 for (const auto* game : libraryController_->getAllGames())
4838 {
4839 checkedCount++;
4840 if (launchController_->isGameRunning(game->id))
4841 {
4842 runningGameId = game->id;
4843 Logger::info("[MainWindow] Found running game on startup: {} (checked {} games)",
4844 game->name, checkedCount);
4845 break;
4846 }
4847 }
4848
4849 if (runningGameId.empty())
4850 {
4851 Logger::info("[MainWindow] No games running on startup (checked {} games)", checkedCount);
4852 return;
4853 }
4854
4855 // Initialize previousRunningGameId_ to current state so we don't re-trigger on first update
4856 previousRunningGameId_ = runningGameId;
4857
4858 // Trigger game started handler (same as if game just started)
4859 Logger::info("[MainWindow] Triggering onGameStarted for startup-detected game");
4860 onGameStarted(runningGameId);
4861}
Game getGame() const
void setGame(const Game &game)
Async image loader using QThreadPool.
void imageLoaded(const QString &cacheKey, const QPixmap &pixmap)
Emitted when an image has been loaded (on main thread).
void gamesBatchRemoveRequested(const std::vector< std::string > &gameIds)
Multi-select "Remove N Games" confirmed; caller should loop libraryController->removeGame + run updat...
void steamUninstallCompleted(const std::string &gameId, bool success, const std::string &gameName, std::uint32_t appId)
Steam Uninstall worker completed on the UI thread.
void gameChanged(const std::string &gameId)
void stopRequested(const std::string &gameId)
void configureRequested(const std::string &gameId)
void launchRequested(const std::string &gameId)
FrameMetrics getMetrics(const std::string &gameId) const
Get current metrics for a game.
static FrameMetricsService & instance()
Get the singleton instance.
int cleanupOldLogs(int maxAgeHours=24)
Clean up old MangoHud log files.
void setOnGameStatsUpdated(std::function< void(const std::string &gameId)> callback)
const GameProcess * getRunningProcess(const std::string &gameId) const
void scanForRunningGames(const std::vector< Game * > &games, GameAccessCallback gameAccessCallback)
static GameProcessManager & instance()
Complete representation of a game in the library.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
bool isFavorite
Is this marked as a favorite game?
Definition game.h:803
std::string name
Display name shown in UI.
Definition game.h:774
std::string id
Unique identifier (auto-generated or user-specified).
Definition game.h:773
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
bool isInstalled() const
Check if game is currently installed.
Definition game.h:944
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
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
void installRequested(const LutrisInstallerScript &script)
void closeEvent(QCloseEvent *event) override
~MainWindow() override
void changeEvent(QEvent *event) override
void dragEnterEvent(QDragEnterEvent *event) override
MainWindow(QWidget *parent=nullptr)
void resizeEvent(QResizeEvent *event) override
void setNotificationService(std::shared_ptr< QtNotificationService > service)
bool eventFilter(QObject *obj, QEvent *event) override
void dropEvent(QDropEvent *event) override
void libraryStatisticsRequested()
void installFromLutrisRequested()
void addGameRequested()
void gameListChanged()
void zoomInRequested()
void sortSelected(SortOption sort)
void commandPaletteRequested()
void favoriteChanged(const std::string &gameId)
void stopRequested(const std::string &gameId)
void manageRunnersRequested()
void refreshLibraryRequested()
void runnersListChanged()
void importGamesRequested()
void removeGameRequested(const std::string &gameId)
void launchRequested(const std::string &gameId)
void viewModeSelected(ViewMode mode)
void exportImportRequested()
void gameConfigUpdated(const std::string &gameId)
void zoomOutRequested()
void panelToggleRequested(const QString &name)
void exitRequested()
void themeSelected(const QString &themeId)
void downloadQueueRequested()
void settingsRequested()
void artworkChanged(const std::string &gameId)
void zoomResetRequested()
void menuModeToggled(bool useHamburger)
static ProtonDBGameInfo getGameInfo(int steamAppId)
Get game info by Steam App ID.
void runnerChanged()
void sourceChanged()
void collectionDeleted(const QString &collectionName)
void categoryChanged(int row)
void collectionChanged(const QString &collectionName)
void stopGameRequested(const std::string &gameId)
void showGameRequested(const std::string &gameId)
static SteamDownloadProgress readGameState(uint32_t appId)
Read current state of a game directly from its appmanifest.
static std::string fetchGameNameFromCache(uint32_t appId)
Get game name from pre-loaded cache (instant).
static bool loadAppNameCache()
Load Steam app name cache from GetAppList API.
static std::string fetchGameNameFromSteamAPI(uint32_t appId)
Fetch game name from Steam Web API.
std::vector< SteamGame > scanAllLibraries()
Scan all Steam libraries for installed games.
static std::string readSteamProtonVersion(uint32_t appId)
Read Proton compatibility tool mapping for a game from config.vdf.
static SteamProcessMonitor & instance()
void detailsRequested()
Emitted when user clicks to see more details.
Terminal panel widget that embeds a terminal emulator.
static ThemeManager & instance()
void applyToApplication()
Apply current theme to the entire application.
void styleMenu(QMenu *menu) const
Apply complete menu styling (stylesheet + palette) to a QMenu.
void initialize(core::SettingsController *settingsController)
void themeChanged()
Emitted when theme or accent color changes.
int zoomLevel() const
Get current zoom level (75-150, default 100).
void setTheme(const QString &themeId)
Set active theme by ID.
const ThemeColors & colors() const
Get effective colors (with accent customization applied).
void saveToSettings()
Save theme settings to settings controller.
void panelToggleRequested(const QString &panelName)
void viewModeChanged(ViewMode mode)
void themeSelected(const QString &themeId)
void downloadQueueRequested()
void addGameRequested()
void settingsRequested()
void installFromLutrisRequested()
void exitRequested()
void monitorCommandRequested(const QString &command)
void zoomChanged(int value)
void runningGameDetailsRequested()
void monitorRestartRequested()
void sortChanged(int index)
void searchTextChanged(const QString &text)
void exportImportRequested()
void importGamesRequested()
void libraryStatisticsRequested()
void manageRunnersRequested()
void refreshLibraryRequested()
GameSource
Where the game was acquired from (store/service/local).
Definition game.h:39
@ Steam
Steam store/platform.
Definition game.h:41
@ Local
Manually added game (not from a store).
Definition game.h:40
ImageType
Types of game images available.
Definition game.h:478
@ VerticalCover
Vertical cover art (600x900, portrait).
Definition game.h:479
@ Header
Small header image (460x215).
Definition game.h:482
@ Installing
Game is being installed.
Definition game.h:103
@ NotInstalled
Game is in library but not installed.
Definition game.h:98
@ Installed
Game is installed and ready to play.
Definition game.h:99
@ Proton
Proton (Steam's Wine fork).
Definition game.h:84
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:82
@ Wine
Wine compatibility layer.
Definition game.h:83
@ GameIdRole
static void openSteamUrl(const QString &steamUrl)
ViewMode
Definition mainwindow.h:75
SortOption
Definition mainwindow.h:86
@ RecentlyAddedAsc
Definition mainwindow.h:94
@ RecentlyAddedDesc
Definition mainwindow.h:93
std::string getStateDescription(uint32_t flags)
Get human-readable state description.
bool isFullyInstalled(uint32_t flags)
Check if a game is fully installed.
bool needsUpdate(uint32_t flags)
Check if a game needs an update.
bool isSteamGame
True if imported from Steam.
Definition game.h:574
bool steamInstalled
True if Steam game is installed (set during Steam import).
Definition game.h:576
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
time_t protondbLastUpdated
When ProtonDB data was last fetched.
Definition game.h:604
bool enableVkBasalt
Enable VkBasalt shader injection.
Definition game.h:188
std::string executablePath
Full path to game executable.
Definition game.h:141
std::string workingDirectory
Working directory for game execution.
Definition game.h:142
bool enableMangoHud
Enable MangoHud performance overlay.
Definition game.h:184
bool enableGamePerformance
Enable game-performance wrapper (CachyOS).
Definition game.h:187
bool enableFsync
Enable Fsync (kernel 5.16+, best performance).
Definition game.h:215
std::string runnerVersion
Runner version: "wine-8.0", "proton-8.0-5", etc.
Definition game.h:140
std::string runnerType
Runner type: "wine", "proton", "native", etc.
Definition game.h:139
bool enableGameMode
Enable GameMode CPU governor optimization.
Definition game.h:186
std::string protonVersion
Proton version (e.g., "proton-cachyos-slr").
Definition game.h:170
std::string stateDescription
Human-readable state.
uint32_t stateFlags
Current StateFlags.
double overallProgress
Combined progress (0.0 to 1.0).
QColor panelBackground
QColor cardBackground
QColor textSecondary
QColor textPrimary
QColor accentHover
QColor textMuted
QColor hoverBackground
QColor accentPressed
QColor textOnAccent
std::optional< std::string > collection
std::optional< GameSource > source
@ Game
Game-specific fixes.