game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
recommendations_widget.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// recommendations_widget.cpp
4// ==============================================================================
5// Unified game recommendations panel implementation
6// ==============================================================================
7
9#include "theme_manager.h"
10
11#include <QApplication>
12#include <QDesktopServices>
13#include <QGroupBox>
14#include <QHBoxLayout>
15#include <QUrl>
16#include <QVBoxLayout>
17#include <QtConcurrent/QtConcurrent>
18
19// ==============================================================================
20// Constructor / Destructor
21// ==============================================================================
22
24 : QFrame(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
25{
26 setupUI();
27 applyTheme();
28
29 // Initialize async fetch watcher (finished connection is set per-request
30 // in loadRecommendations to avoid stale signals from a previous game's fetch)
31 fetchWatcher_ = new QFutureWatcher<GameSuggestions>(this);
32
33 connect(themeManager_, &ThemeManager::themeChanged, this, &RecommendationsWidget::applyTheme);
34}
35
37{
38 // Cancel any pending async operation before destruction
39 if (fetchWatcher_ && fetchWatcher_->isRunning())
40 {
41 fetchWatcher_->cancel();
42 fetchWatcher_->waitForFinished();
43 }
44}
45
46// ==============================================================================
47// Public Methods
48// ==============================================================================
49
50void RecommendationsWidget::loadRecommendations(int steamAppId, const QString& gameName)
51{
52 currentSteamAppId_ = steamAppId;
53
54 // Cancel any pending fetch before starting a new one
55 if (fetchWatcher_->isRunning())
56 {
57 fetchWatcher_->cancel();
58 fetchWatcher_->waitForFinished();
59 }
60
61 const ThemeColors& c = themeManager_->colors();
62
63 // Show loading state
64 confidenceBadge_->setText("...");
65 confidenceBadge_->setStyleSheet(QString("background-color: %1; color: %2; padding: 4px 12px; "
66 "border-radius: 4px; font-weight: bold;")
67 .arg(c.inputBackground.name(), c.textMuted.name()));
68 confidenceSummary_->setText("Loading recommendations...");
69 suggestionsText_->setPlainText("Fetching data from ProtonDB and other sources...");
70 applyBtn_->setEnabled(false);
71
72 // Fetch async using Qt's thread pool - safely cancellable and properly managed
73 std::string gameNameStd = gameName.toStdString();
74 QFuture<GameSuggestions> future = QtConcurrent::run(
75 [steamAppId, gameNameStd]()
76 { return GameSuggestionService::getSuggestions(steamAppId, gameNameStd); });
77
78 // Reconnect finished signal capturing this request's steamAppId.
79 // This prevents a stale queued finished signal (from a completed-but-not-yet-delivered
80 // previous fetch) from displaying recommendations for the wrong game.
81 disconnect(fetchWatcher_, &QFutureWatcher<GameSuggestions>::finished, this, nullptr);
82 connect(fetchWatcher_, &QFutureWatcher<GameSuggestions>::finished, this,
83 [this, steamAppId]()
84 {
85 if (fetchWatcher_->isCanceled())
86 {
87 return;
88 }
89 // Guard against stale signals: if the user switched games again between
90 // this future completing and the event loop delivering finished, discard.
91 if (currentSteamAppId_ != steamAppId)
92 {
93 return;
94 }
95 GameSuggestions suggestions = fetchWatcher_->result();
96 setRecommendations(suggestions);
97 emit loadingComplete(suggestions.hasRecommendations());
98 });
99
100 fetchWatcher_->setFuture(future);
101}
102
104{
105 currentSuggestions_ = suggestions;
106 updateDisplay();
107}
108
110{
111 currentSuggestions_ = GameSuggestions{};
112 currentSteamAppId_ = 0;
113
114 const ThemeColors& c = themeManager_->colors();
115
116 confidenceBadge_->setText("—");
117 confidenceBadge_->setStyleSheet(QString("background-color: %1; color: %2; padding: 4px 12px; "
118 "border-radius: 4px; font-weight: bold;")
119 .arg(c.inputBackground.name(), c.textMuted.name()));
120 confidenceSummary_->setText("No game selected");
121
122 protondbLabel_->setText("—");
123 steamDeckLabel_->setText("—");
124 lutrisLabel_->setText("—");
125 nativeLabel_->setText("—");
126
127 suggestionsText_->clear();
128 applyBtn_->setEnabled(false);
129 viewProtonDBBtn_->setEnabled(false);
130}
131
132// ==============================================================================
133// Private Slots
134// ==============================================================================
135
136void RecommendationsWidget::onApplyClicked()
137{
138 if (hasRecommendations())
139 {
140 emit applyRequested(currentSuggestions_);
141 }
142}
143
144void RecommendationsWidget::onViewProtonDBClicked()
145{
146 if (currentSteamAppId_ > 0)
147 {
148 QString url = QString("https://www.protondb.com/app/%1").arg(currentSteamAppId_);
149 QDesktopServices::openUrl(QUrl(url));
150 }
151}
152
153// ==============================================================================
154// UI Setup
155// ==============================================================================
156
157void RecommendationsWidget::setupUI()
158{
159 setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
160
161 auto* mainLayout = new QVBoxLayout(this);
162 mainLayout->setSpacing(12);
163 mainLayout->setContentsMargins(12, 12, 12, 12);
164
165 // --- Confidence Header ---
166 auto* headerLayout = new QHBoxLayout();
167
168 confidenceBadge_ = new QLabel("—");
169 confidenceBadge_->setFixedHeight(28);
170 headerLayout->addWidget(confidenceBadge_);
171
172 confidenceSummary_ = new QLabel("No game selected");
173 confidenceSummary_->setWordWrap(true);
174 headerLayout->addWidget(confidenceSummary_, 1);
175
176 mainLayout->addLayout(headerLayout);
177
178 // --- Data Sources Grid ---
179 auto* sourcesGroup = new QGroupBox("Data Sources");
180 auto* sourcesLayout = new QHBoxLayout(sourcesGroup);
181 sourcesLayout->setSpacing(20);
182
183 // Helper lambda for creating data source columns with themed titles
184 auto createSourceColumn = [&](const QString& title, QLabel*& valueLabel)
185 {
186 auto* col = new QVBoxLayout();
187 auto* titleLabel = new QLabel(title);
188 titleLabel->setProperty("sourceTitle", true); // For theme targeting
189 valueLabel = new QLabel("—");
190 col->addWidget(titleLabel);
191 col->addWidget(valueLabel);
192 sourcesLayout->addLayout(col);
193 };
194
195 createSourceColumn("ProtonDB", protondbLabel_);
196 createSourceColumn("Steam Deck", steamDeckLabel_);
197 createSourceColumn("Lutris", lutrisLabel_);
198 createSourceColumn("Native", nativeLabel_);
199
200 sourcesLayout->addStretch();
201 mainLayout->addWidget(sourcesGroup);
202
203 // --- Suggestions List ---
204 auto* suggestionsGroup = new QGroupBox("Recommended Settings");
205 auto* suggestionsLayout = new QVBoxLayout(suggestionsGroup);
206
207 suggestionsText_ = new QTextEdit();
208 suggestionsText_->setReadOnly(true);
209 suggestionsText_->setMaximumHeight(150);
210 suggestionsLayout->addWidget(suggestionsText_);
211
212 mainLayout->addWidget(suggestionsGroup);
213
214 // --- Action Buttons ---
215 auto* buttonLayout = new QHBoxLayout();
216
217 viewProtonDBBtn_ = new QPushButton("View on ProtonDB");
218 viewProtonDBBtn_->setEnabled(false);
219 connect(viewProtonDBBtn_, &QPushButton::clicked, this,
220 &RecommendationsWidget::onViewProtonDBClicked);
221 buttonLayout->addWidget(viewProtonDBBtn_);
222
223 buttonLayout->addStretch();
224
225 applyBtn_ = new QPushButton("Apply Recommendations");
226 applyBtn_->setEnabled(false);
227 connect(applyBtn_, &QPushButton::clicked, this, &RecommendationsWidget::onApplyClicked);
228 buttonLayout->addWidget(applyBtn_);
229
230 mainLayout->addLayout(buttonLayout);
231}
232
233// ==============================================================================
234// Display Update Methods
235// ==============================================================================
236
237void RecommendationsWidget::updateDisplay()
238{
239 updateConfidenceBadge();
240 updateDataSources();
241 updateSuggestionsList();
242
243 applyBtn_->setEnabled(hasRecommendations());
244 viewProtonDBBtn_->setEnabled(currentSteamAppId_ > 0);
245}
246
247void RecommendationsWidget::updateConfidenceBadge()
248{
249 const ThemeColors& c = themeManager_->colors();
250
251 auto level = currentSuggestions_.getConfidenceLevel();
252 float score = currentSuggestions_.getConfidenceScore();
253 int percent = static_cast<int>(score * 100);
254
255 QString badgeText = QString("%1%").arg(percent);
256 QColor bgColor;
257 QString summary = QString::fromStdString(currentSuggestions_.getConfidenceSummary());
258
259 switch (level)
260 {
262 bgColor = c.success;
263 break;
265 bgColor = ThemeManager::lightenColor(c.success, 15);
266 break;
268 bgColor = c.warning;
269 break;
271 bgColor = ThemeManager::darkenColor(c.warning, 20);
272 break;
274 default:
275 bgColor = c.inputBackground;
276 badgeText = "?";
277 break;
278 }
279
280 confidenceBadge_->setText(badgeText);
281 confidenceBadge_->setStyleSheet(
282 QString("background-color: %1; color: %2; padding: 4px 12px; "
283 "border-radius: 4px; font-weight: bold; font-size: 14px;")
284 .arg(bgColor.name(), c.textOnAccent.name()));
285
286 confidenceSummary_->setText(summary);
287 QPalette summaryPal = confidenceSummary_->palette();
288 summaryPal.setColor(QPalette::WindowText, c.textSecondary);
289 confidenceSummary_->setPalette(summaryPal);
290}
291
292void RecommendationsWidget::updateDataSources()
293{
294 const ThemeColors& c = themeManager_->colors();
295 QString mutedColor = c.textMuted.name();
296 QString successColor = c.success.name();
297 QString warningColor = c.warning.name();
298 QString errorColor = c.error.name();
299
300 // ProtonDB - tier colors are intentionally specific branding colors
301 if (!currentSuggestions_.protondbTier.empty())
302 {
303 QString tier = QString::fromStdString(currentSuggestions_.protondbTier).toUpper();
304 QString tierColor;
305
306 // ProtonDB tier colors are well-known branding, keep them
307 if (tier == "PLATINUM")
308 tierColor = "#b4c7dc";
309 else if (tier == "GOLD")
310 tierColor = "#cfb53b";
311 else if (tier == "SILVER")
312 tierColor = "#a8a8a8";
313 else if (tier == "BRONZE")
314 tierColor = "#cd7f32";
315 else if (tier == "BORKED")
316 tierColor = errorColor;
317 else
318 tierColor = mutedColor;
319
320 QString text =
321 QString("<span style='color: %1; font-weight: bold;'>%2</span>").arg(tierColor, tier);
322 if (currentSuggestions_.protondbReportCount > 0)
323 {
324 text += QString(" <span style='color: %1;'>(%2 reports)</span>")
325 .arg(mutedColor)
326 .arg(currentSuggestions_.protondbReportCount);
327 }
328 protondbLabel_->setText(text);
329 protondbLabel_->setTextFormat(Qt::RichText);
330 protondbLabel_->setStyleSheet("");
331 }
332 else
333 {
334 protondbLabel_->setText("No data");
335 protondbLabel_->setStyleSheet(QString("color: %1;").arg(mutedColor));
336 }
337
338 // Steam Deck
339 if (!currentSuggestions_.steamDeckStatus.empty())
340 {
341 QString status = QString::fromStdString(currentSuggestions_.steamDeckStatus);
342 QString statusColor;
343
344 if (status == "Verified")
345 statusColor = successColor;
346 else if (status == "Playable")
347 statusColor = warningColor;
348 else if (status == "Unsupported")
349 statusColor = errorColor;
350 else
351 statusColor = mutedColor;
352
353 steamDeckLabel_->setText(QString("<span style='color: %1; font-weight: bold;'>%2</span>")
354 .arg(statusColor, status));
355 steamDeckLabel_->setTextFormat(Qt::RichText);
356 steamDeckLabel_->setStyleSheet("");
357 }
358 else
359 {
360 steamDeckLabel_->setText("Unknown");
361 steamDeckLabel_->setStyleSheet(QString("color: %1;").arg(mutedColor));
362 }
363
364 // Lutris
365 if (currentSuggestions_.hasLutrisInstaller)
366 {
367 QString text = QString("<span style='color: %1;'>Available</span>").arg(successColor);
368 if (currentSuggestions_.lutrisDownloadCount > 0)
369 {
370 text += QString(" <span style='color: %1;'>(%2 installs)</span>")
371 .arg(mutedColor)
372 .arg(currentSuggestions_.lutrisDownloadCount);
373 }
374 lutrisLabel_->setText(text);
375 lutrisLabel_->setTextFormat(Qt::RichText);
376 lutrisLabel_->setStyleSheet("");
377 }
378 else
379 {
380 lutrisLabel_->setText("No installer");
381 lutrisLabel_->setStyleSheet(QString("color: %1;").arg(mutedColor));
382 }
383
384 // Native Linux
385 if (currentSuggestions_.hasNativeLinux)
386 {
387 nativeLabel_->setText(
388 QString("<span style='color: %1; font-weight: bold;'>Yes</span>").arg(successColor));
389 nativeLabel_->setTextFormat(Qt::RichText);
390 nativeLabel_->setStyleSheet("");
391 }
392 else
393 {
394 nativeLabel_->setText("No");
395 nativeLabel_->setStyleSheet(QString("color: %1;").arg(mutedColor));
396 }
397}
398
399void RecommendationsWidget::updateSuggestionsList()
400{
401 if (currentSuggestions_.suggestions.empty())
402 {
403 suggestionsText_->setPlainText("No specific recommendations available.");
404 return;
405 }
406
407 const ThemeColors& c = themeManager_->colors();
408
409 QString html;
410 html += QString("<style>"
411 "body { font-family: monospace; font-size: 12px; color: %1; }"
412 ".critical { color: %2; }"
413 ".recommended { color: %3; }"
414 ".optional { color: %4; }"
415 ".source { color: %5; font-size: 10px; }"
416 "</style>")
417 .arg(c.textPrimary.name(), c.error.name(), c.info.name(), c.textSecondary.name(),
418 c.textMuted.name());
419
420 // Group by priority
421 std::vector<const GameSuggestion*> critical, recommended, optional;
422 for (const auto& s : currentSuggestions_.suggestions)
423 {
424 switch (s.priority)
425 {
427 critical.push_back(&s);
428 break;
430 recommended.push_back(&s);
431 break;
432 default:
433 optional.push_back(&s);
434 break;
435 }
436 }
437
438 auto formatSuggestion = [](const GameSuggestion* s, const QString& cssClass) -> QString
439 {
440 QString line = QString("<div class='%1'>• %2")
441 .arg(cssClass, QString::fromStdString(s->title).toHtmlEscaped());
442
443 if (!s->envKey.empty())
444 {
445 line += QString(" <code>%1=%2</code>")
446 .arg(QString::fromStdString(s->envKey).toHtmlEscaped(),
447 QString::fromStdString(s->envValue).toHtmlEscaped());
448 }
449 if (!s->recommendedRunner.empty())
450 {
451 line +=
452 QString(" → %1").arg(QString::fromStdString(s->recommendedRunner).toHtmlEscaped());
453 }
454 if (!s->source.empty())
455 {
456 line += QString(" <span class='source'>[%1]</span>")
457 .arg(QString::fromStdString(s->source).toHtmlEscaped());
458 }
459 line += "</div>";
460 return line;
461 };
462
463 if (!critical.empty())
464 {
465 html += "<div><b>⚠ Critical:</b></div>";
466 for (const auto* s : critical)
467 {
468 html += formatSuggestion(s, "critical");
469 }
470 }
471
472 if (!recommended.empty())
473 {
474 html += "<div><b>Recommended:</b></div>";
475 for (const auto* s : recommended)
476 {
477 html += formatSuggestion(s, "recommended");
478 }
479 }
480
481 if (!optional.empty())
482 {
483 html += "<div><b>Optional:</b></div>";
484 for (const auto* s : optional)
485 {
486 html += formatSuggestion(s, "optional");
487 }
488 }
489
490 suggestionsText_->setHtml(html);
491}
492
493// ==============================================================================
494// Theme Support
495// ==============================================================================
496
497void RecommendationsWidget::applyTheme()
498{
499 const ThemeColors& c = themeManager_->colors();
500
501 // Frame styling
502 setStyleSheet(
503 QString("RecommendationsWidget { background-color: %1; border: 1px solid %2; "
504 "border-radius: 6px; }"
505 "QGroupBox { color: %3; border: 1px solid %4; border-radius: 4px; margin-top: 8px; "
506 "padding-top: 8px; }"
507 "QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 5px; }"
508 "QLabel[sourceTitle=\"true\"] { font-weight: bold; color: %5; }")
509 .arg(c.cardBackground.name(), c.border.name(), c.textPrimary.name(),
510 c.borderLight.name(), c.textMuted.name()));
511
512 // Suggestions text area
513 if (suggestionsText_)
514 {
515 suggestionsText_->setStyleSheet(
516 QString("QTextEdit { background-color: %1; border: 1px solid %2; color: %3; }")
517 .arg(c.inputBackground.name(), c.border.name(), c.textPrimary.name()));
518 }
519
520 // Apply button - use success color for primary action
521 if (applyBtn_)
522 {
523 applyBtn_->setStyleSheet(
524 QString("QPushButton { background-color: %1; color: %2; padding: 8px 16px; "
525 "font-weight: bold; border-radius: 4px; } "
526 "QPushButton:hover { background-color: %3; } "
527 "QPushButton:disabled { background-color: %4; color: %5; }")
528 .arg(c.success.name(), c.textOnAccent.name(),
529 ThemeManager::lightenColor(c.success, 15).name(), c.inputBackground.name(),
530 c.textMuted.name()));
531 }
532
533 // View ProtonDB button - secondary style
534 if (viewProtonDBBtn_)
535 {
536 viewProtonDBBtn_->setStyleSheet(
537 QString("QPushButton { background-color: %1; color: %2; padding: 8px 16px; border: 1px "
538 "solid %3; border-radius: 4px; } "
539 "QPushButton:hover { background-color: %4; } "
540 "QPushButton:disabled { background-color: %5; color: %6; border-color: %5; }")
541 .arg(c.cardBackground.name(), c.textPrimary.name(), c.border.name(),
542 c.hoverBackground.name(), c.inputBackground.name(), c.textMuted.name()));
543 }
544
545 // Confidence summary label
546 if (confidenceSummary_)
547 {
548 QPalette p = confidenceSummary_->palette();
549 p.setColor(QPalette::WindowText, c.textSecondary);
550 confidenceSummary_->setPalette(p);
551 }
552
553 // Update data sources and badge if we have data
554 if (hasRecommendations())
555 {
556 updateDisplay();
557 }
558 else
559 {
560 // Reset badge to themed neutral state
561 if (confidenceBadge_)
562 {
563 confidenceBadge_->setStyleSheet(
564 QString("background-color: %1; color: %2; padding: 4px 12px; "
565 "border-radius: 4px; font-weight: bold; font-size: 14px;")
566 .arg(c.inputBackground.name(), c.textMuted.name()));
567 }
568 }
569}
static GameSuggestions getSuggestions(const Game &game)
Get suggestions for a game.
bool hasRecommendations() const
Check if recommendations are available.
RecommendationsWidget(QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void setRecommendations(const GameSuggestions &suggestions)
Set recommendations directly (for when already fetched).
void loadRecommendations(int steamAppId, const QString &gameName)
Load recommendations for a game by Steam App ID.
void applyRequested(const GameSuggestions &suggestions)
Emitted when user clicks "Apply Recommendations".
void clear()
Clear all displayed data.
void loadingComplete(bool success)
Emitted when loading completes (async).
static QColor darkenColor(const QColor &color, int amount)
Darken a color by decreasing its lightness.
void themeChanged()
Emitted when theme or accent color changes.
static QColor lightenColor(const QColor &color, int amount)
Lighten a color by increasing its lightness.
Collection of suggestions for a game.
QColor inputBackground
QColor borderLight
QColor cardBackground
QColor textSecondary
QColor textPrimary
QColor textMuted
QColor hoverBackground
QColor textOnAccent