game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_statistics_dialog.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// qt/game_statistics_dialog.cpp
4// ==============================================================================
5// Dialog showing game library statistics and visualizations
6// ==============================================================================
7
9#include "theme_manager.h"
10
11#include <QDateTime>
12#include <QDialogButtonBox>
13#include <QGridLayout>
14#include <QGroupBox>
15#include <QHBoxLayout>
16#include <QPainter>
17#include <QScrollArea>
18#include <QVBoxLayout>
19#include <algorithm>
20#include <cmath>
21
22// ==============================================================================
23// StatCard Implementation
24// ==============================================================================
25
26StatCard::StatCard(const QString& label, const QString& value, const QString& icon, QWidget* parent,
27 ThemeManager* themeManager)
28 : QFrame(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
29{
30 setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
31 setMinimumSize(150, 100);
32
33 auto* layout = new QVBoxLayout(this);
34 layout->setContentsMargins(16, 12, 16, 12);
35
36 // Top row: icon + value
37 auto* topLayout = new QHBoxLayout;
38 topLayout->setSpacing(8);
39
40 if (!icon.isEmpty())
41 {
42 iconLabel_ = new QLabel(icon);
43 iconLabel_->setStyleSheet("font-size: 24px;");
44 topLayout->addWidget(iconLabel_);
45 }
46
47 valueLabel_ = new QLabel(value);
48 valueLabel_->setStyleSheet("font-size: 28px; font-weight: bold;");
49 topLayout->addWidget(valueLabel_);
50 topLayout->addStretch();
51
52 layout->addLayout(topLayout);
53
54 // Label
55 labelLabel_ = new QLabel(label);
56 labelLabel_->setStyleSheet("font-size: 13px;");
57 layout->addWidget(labelLabel_);
58
59 // Optional subtext
60 subtextLabel_ = new QLabel;
61 subtextLabel_->setStyleSheet("font-size: 11px;");
62 subtextLabel_->hide();
63 layout->addWidget(subtextLabel_);
64
65 layout->addStretch();
66
67 applyTheme();
68 connect(themeManager_, &ThemeManager::themeChanged, this, &StatCard::applyTheme);
69}
70
71void StatCard::setValue(const QString& value)
72{
73 valueLabel_->setText(value);
74}
75
76void StatCard::setSubtext(const QString& subtext)
77{
78 subtextLabel_->setText(subtext);
79 subtextLabel_->setVisible(!subtext.isEmpty());
80}
81
83{
84 const auto& c = themeManager_->colors();
85
86 setStyleSheet(QString("StatCard {"
87 " background-color: %1;"
88 " border: 1px solid %2;"
89 " border-radius: 8px;"
90 "}")
91 .arg(c.cardBackground.name())
92 .arg(c.border.name()));
93
94 if (valueLabel_)
95 {
96 valueLabel_->setStyleSheet(
97 QString("font-size: 28px; font-weight: bold; color: %1;").arg(c.textPrimary.name()));
98 }
99 if (labelLabel_)
100 {
101 labelLabel_->setStyleSheet(
102 QString("font-size: 13px; color: %1;").arg(c.textSecondary.name()));
103 }
104 if (subtextLabel_)
105 {
106 subtextLabel_->setStyleSheet(
107 QString("font-size: 11px; color: %1;").arg(c.textSecondary.name()));
108 }
109}
110
111// ==============================================================================
112// PieChartWidget Implementation
113// ==============================================================================
114
115PieChartWidget::PieChartWidget(QWidget* parent, ThemeManager* themeManager)
116 : QWidget(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
117{
118 setMinimumSize(200, 200);
119 applyTheme();
120 connect(themeManager_, &ThemeManager::themeChanged, this, &PieChartWidget::applyTheme);
121}
122
123void PieChartWidget::setData(const std::vector<Slice>& slices)
124{
125 slices_ = slices;
126 update();
127}
128
129void PieChartWidget::setTitle(const QString& title)
130{
131 title_ = title;
132 update();
133}
134
136{
137 const auto& c = themeManager_->colors();
138 textColor_ = c.textPrimary;
139 backgroundColor_ = c.cardBackground;
140 update();
141}
142
144{
145 QPainter painter(this);
146 painter.setRenderHint(QPainter::Antialiasing);
147
148 // Background
149 painter.fillRect(rect(), backgroundColor_);
150
151 // Calculate total
152 double total = 0;
153 for (const auto& slice : slices_)
154 {
155 total += slice.value;
156 }
157
158 if (total <= 0 || slices_.empty())
159 {
160 painter.setPen(textColor_);
161 painter.drawText(rect(), Qt::AlignCenter, "No data");
162 return;
163 }
164
165 // Draw title
166 int yOffset = 0;
167 if (!title_.isEmpty())
168 {
169 painter.setPen(textColor_);
170 painter.setFont(QFont(font().family(), 12, QFont::Bold));
171 painter.drawText(QRect(0, 5, width(), 20), Qt::AlignCenter, title_);
172 yOffset = 25;
173 }
174
175 // Calculate pie dimensions
176 int pieSize = qMin(width(), height() - yOffset - 80);
177 int pieX = (width() - pieSize) / 2;
178 int pieY = yOffset + 10;
179 QRectF pieRect(pieX, pieY, pieSize, pieSize);
180
181 // Draw slices
182 int startAngle = 90 * 16; // Start at top (12 o'clock)
183 for (const auto& slice : slices_)
184 {
185 if (slice.value <= 0)
186 continue;
187
188 int spanAngle = static_cast<int>((slice.value / total) * 360 * 16);
189 painter.setBrush(slice.color);
190 painter.setPen(QPen(backgroundColor_, 2));
191 painter.drawPie(pieRect, startAngle, -spanAngle);
192 startAngle -= spanAngle;
193 }
194
195 // Draw legend
196 painter.setFont(QFont(font().family(), 10));
197 int legendY = pieY + pieSize + 10;
198 int legendX = 10;
199 int legendItemWidth = width() / 2 - 15;
200
201 int col = 0;
202 for (const auto& slice : slices_)
203 {
204 if (slice.value <= 0)
205 continue;
206
207 int x = legendX + (col % 2) * legendItemWidth;
208 int y = legendY + (col / 2) * 18;
209
210 // Color box
211 painter.fillRect(x, y + 2, 12, 12, slice.color);
212 painter.setPen(textColor_);
213
214 // Label with percentage
215 double percent = (slice.value / total) * 100;
216 QString text = QString("%1 (%2%)").arg(slice.label).arg(percent, 0, 'f', 1);
217 painter.drawText(x + 16, y, legendItemWidth - 20, 16, Qt::AlignLeft | Qt::AlignVCenter,
218 text);
219
220 col++;
221 }
222}
223
224// ==============================================================================
225// BarChartWidget Implementation
226// ==============================================================================
227
228BarChartWidget::BarChartWidget(QWidget* parent, ThemeManager* themeManager)
229 : QWidget(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
230{
231 setMinimumSize(300, 200);
232 applyTheme();
233 connect(themeManager_, &ThemeManager::themeChanged, this, &BarChartWidget::applyTheme);
234}
235
236void BarChartWidget::setData(const std::vector<Bar>& bars)
237{
238 bars_ = bars;
239 update();
240}
241
242void BarChartWidget::setTitle(const QString& title)
243{
244 title_ = title;
245 update();
246}
247
249{
250 const auto& c = themeManager_->colors();
251 textColor_ = c.textPrimary;
252 barColor_ = c.accent;
253 backgroundColor_ = c.cardBackground;
254 update();
255}
256
258{
259 int barCount = qMin(static_cast<int>(bars_.size()), maxBars_);
260 return QSize(400, qMax(200, barCount * 35 + 50));
261}
262
264{
265 return QSize(300, 150);
266}
267
269{
270 QPainter painter(this);
271 painter.setRenderHint(QPainter::Antialiasing);
272
273 // Background
274 painter.fillRect(rect(), backgroundColor_);
275
276 // Draw title
277 int yOffset = 0;
278 if (!title_.isEmpty())
279 {
280 painter.setPen(textColor_);
281 painter.setFont(QFont(font().family(), 12, QFont::Bold));
282 painter.drawText(QRect(0, 5, width(), 20), Qt::AlignCenter, title_);
283 yOffset = 30;
284 }
285
286 if (bars_.empty())
287 {
288 painter.setPen(textColor_);
289 painter.drawText(rect(), Qt::AlignCenter, "No data");
290 return;
291 }
292
293 // Find max value
294 double maxValue = 0;
295 for (const auto& bar : bars_)
296 {
297 maxValue = qMax(maxValue, bar.value);
298 }
299
300 if (maxValue <= 0)
301 {
302 maxValue = 1;
303 }
304
305 // Calculate dimensions
306 int barCount = qMin(static_cast<int>(bars_.size()), maxBars_);
307 int labelWidth = 120;
308 int valueWidth = 60;
309 int barAreaWidth = width() - labelWidth - valueWidth - 20;
310 int barHeight = 20;
311 int barSpacing = 8;
312
313 painter.setFont(QFont(font().family(), 10));
314
315 for (int i = 0; i < barCount; ++i)
316 {
317 const auto& bar = bars_[static_cast<size_t>(i)];
318 int y = yOffset + i * (barHeight + barSpacing);
319
320 // Label (truncated if too long)
321 painter.setPen(textColor_);
322 QRect labelRect(5, y, labelWidth - 10, barHeight);
323 QString elidedLabel =
324 painter.fontMetrics().elidedText(bar.label, Qt::ElideRight, labelWidth - 15);
325 painter.drawText(labelRect, Qt::AlignLeft | Qt::AlignVCenter, elidedLabel);
326
327 // Bar
328 int barWidth = static_cast<int>((bar.value / maxValue) * barAreaWidth);
329 QRect barRect(labelWidth, y + 2, barWidth, barHeight - 4);
330 painter.fillRect(barRect, barColor_);
331
332 // Value
333 painter.setPen(textColor_);
334 QRect valueRect(labelWidth + barAreaWidth + 5, y, valueWidth, barHeight);
335 painter.drawText(valueRect, Qt::AlignLeft | Qt::AlignVCenter, bar.formattedValue);
336 }
337}
338
339// ==============================================================================
340// ActivityHeatmapWidget Implementation
341// ==============================================================================
342
344 : QWidget(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
345{
346 setMinimumSize(500, 100);
347 applyTheme();
348 connect(themeManager_, &ThemeManager::themeChanged, this, &ActivityHeatmapWidget::applyTheme);
349}
350
351void ActivityHeatmapWidget::setActivityData(const std::map<int, double>& dailyHours)
352{
353 activityData_ = dailyHours;
354 maxActivity_ = 0;
355 for (const auto& [day, hours] : activityData_)
356 {
357 maxActivity_ = qMax(maxActivity_, hours);
358 }
359 update();
360}
361
362void ActivityHeatmapWidget::setTitle(const QString& title)
363{
364 title_ = title;
365 update();
366}
367
369{
370 const auto& c = themeManager_->colors();
371 textColor_ = c.textPrimary;
372 backgroundColor_ = c.cardBackground;
373 lowActivityColor_ = c.inputBackground;
374 highActivityColor_ = c.accent;
375 update();
376}
377
379{
380 QPainter painter(this);
381 painter.setRenderHint(QPainter::Antialiasing);
382
383 // Background
384 painter.fillRect(rect(), backgroundColor_);
385
386 // Draw title
387 int yOffset = 0;
388 if (!title_.isEmpty())
389 {
390 painter.setPen(textColor_);
391 painter.setFont(QFont(font().family(), 12, QFont::Bold));
392 painter.drawText(QRect(0, 5, width(), 20), Qt::AlignCenter, title_);
393 yOffset = 30;
394 }
395
396 // Draw 52 weeks (1 year) of activity
397 int weeks = 52;
398 int cellSize = qMin((width() - 50) / weeks, 15);
399 int startX = (width() - weeks * cellSize) / 2;
400 int startY = yOffset + 5;
401
402 // Day labels
403 painter.setFont(QFont(font().family(), 8));
404 painter.setPen(textColor_);
405 QStringList days = {"Mon", "Wed", "Fri", "Sun"};
406 for (int i = 0; i < 4; ++i)
407 {
408 painter.drawText(5, startY + i * 2 * cellSize + cellSize, days[i]);
409 }
410
411 // Draw cells
412 QDate today = QDate::currentDate();
413
414 for (int week = 0; week < weeks; ++week)
415 {
416 for (int day = 0; day < 7; ++day)
417 {
418 int daysAgo = (weeks - 1 - week) * 7 + (6 - day);
419 QDate cellDate = today.addDays(-daysAgo);
420
421 // Skip future dates
422 if (cellDate > today)
423 continue;
424
425 double hours = 0;
426 auto it = activityData_.find(daysAgo);
427 if (it != activityData_.end())
428 {
429 hours = it->second;
430 }
431
432 // Calculate color based on activity
433 QColor cellColor;
434 if (hours <= 0)
435 {
436 cellColor = lowActivityColor_;
437 }
438 else if (maxActivity_ > 0)
439 {
440 double intensity = qMin(hours / maxActivity_, 1.0);
441 int r = static_cast<int>(lowActivityColor_.red() +
442 intensity *
443 (highActivityColor_.red() - lowActivityColor_.red()));
444 int g = static_cast<int>(
445 lowActivityColor_.green() +
446 intensity * (highActivityColor_.green() - lowActivityColor_.green()));
447 int b = static_cast<int>(
448 lowActivityColor_.blue() +
449 intensity * (highActivityColor_.blue() - lowActivityColor_.blue()));
450 cellColor = QColor(r, g, b);
451 }
452 else
453 {
454 cellColor = lowActivityColor_;
455 }
456
457 int x = startX + week * cellSize;
458 int y = startY + day * cellSize;
459
460 painter.fillRect(x + 1, y + 1, cellSize - 2, cellSize - 2, cellColor);
461 }
462 }
463
464 // Month labels
465 painter.setPen(textColor_);
466 int labelY = startY + 7 * cellSize + 12;
467 QDate monthStart = today.addMonths(-11);
468 monthStart = QDate(monthStart.year(), monthStart.month(), 1);
469
470 for (int m = 0; m < 12; ++m)
471 {
472 QDate month = monthStart.addMonths(m);
473 int daysFromToday = static_cast<int>(today.toJulianDay() - month.toJulianDay());
474 int weekIndex = weeks - 1 - daysFromToday / 7;
475
476 if (weekIndex >= 0 && weekIndex < weeks)
477 {
478 int x = startX + weekIndex * cellSize;
479 painter.drawText(x, labelY, month.toString("MMM"));
480 }
481 }
482
483 // Legend
484 int legendX = width() - 150;
485 int legendY = labelY;
486 painter.drawText(legendX, legendY, "Less");
487 for (int i = 0; i < 5; ++i)
488 {
489 double intensity = i / 4.0;
490 int r = static_cast<int>(lowActivityColor_.red() +
491 intensity * (highActivityColor_.red() - lowActivityColor_.red()));
492 int g =
493 static_cast<int>(lowActivityColor_.green() +
494 intensity * (highActivityColor_.green() - lowActivityColor_.green()));
495 int b = static_cast<int>(lowActivityColor_.blue() + intensity * (highActivityColor_.blue() -
496 lowActivityColor_.blue()));
497 painter.fillRect(legendX + 30 + i * 14, legendY - 10, 12, 12, QColor(r, g, b));
498 }
499 painter.drawText(legendX + 105, legendY, "More");
500}
501
502// ==============================================================================
503// GameStatisticsDialog Implementation
504// ==============================================================================
505
507 : QDialog(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
508{
509 setWindowTitle("Library Statistics");
510 setMinimumSize(900, 700);
511 resize(1000, 750);
512
513 setupUI();
514 applyTheme();
515
516 connect(themeManager_, &ThemeManager::themeChanged, this, &GameStatisticsDialog::applyTheme);
517}
518
519void GameStatisticsDialog::setGames(const std::vector<Game*>& games)
520{
521 games_ = games;
522 refreshStatistics();
523}
524
525void GameStatisticsDialog::setupUI()
526{
527 auto* mainLayout = new QVBoxLayout(this);
528 mainLayout->setSpacing(12);
529
530 // Time range filter
531 auto* filterLayout = new QHBoxLayout;
532 filterLayout->addWidget(new QLabel("Time Range:"));
533
534 timeRangeCombo_ = new QComboBox;
535 timeRangeCombo_->addItem("All Time", 0);
536 timeRangeCombo_->addItem("Last 7 Days", 7);
537 timeRangeCombo_->addItem("Last 30 Days", 30);
538 timeRangeCombo_->addItem("Last 90 Days", 90);
539 timeRangeCombo_->addItem("Last Year", 365);
540 filterLayout->addWidget(timeRangeCombo_);
541 filterLayout->addStretch();
542
543 connect(timeRangeCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
544 &GameStatisticsDialog::onTimeRangeChanged);
545
546 mainLayout->addLayout(filterLayout);
547
548 // Tab widget
549 tabWidget_ = new QTabWidget;
550
551 // Overview tab
552 auto* overviewTab = new QWidget;
553 setupOverviewTab(overviewTab);
554 tabWidget_->addTab(overviewTab, "Overview");
555
556 // Playtime tab
557 auto* playtimeTab = new QWidget;
558 setupPlaytimeTab(playtimeTab);
559 tabWidget_->addTab(playtimeTab, "Playtime");
560
561 // Library tab
562 auto* libraryTab = new QWidget;
563 setupLibraryTab(libraryTab);
564 tabWidget_->addTab(libraryTab, "Library");
565
566 mainLayout->addWidget(tabWidget_, 1);
567
568 // Close button
569 auto* buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
570 connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
571 mainLayout->addWidget(buttonBox);
572}
573
574void GameStatisticsDialog::setupOverviewTab(QWidget* tab)
575{
576 auto* layout = new QVBoxLayout(tab);
577
578 // Stats cards row
579 auto* cardsLayout = new QHBoxLayout;
580
581 totalGamesCard_ = new StatCard("Total Games", "0", "\u25B6", this, themeManager_);
582 cardsLayout->addWidget(totalGamesCard_);
583
584 totalPlaytimeCard_ = new StatCard("Total Playtime", "0h", "\u23F1", this, themeManager_);
585 cardsLayout->addWidget(totalPlaytimeCard_);
586
587 avgSessionCard_ = new StatCard("Avg Session", "0m", "\u25B2", this, themeManager_);
588 cardsLayout->addWidget(avgSessionCard_);
589
590 mostPlayedCard_ = new StatCard("Most Played", "-", "\u2605", this, themeManager_);
591 cardsLayout->addWidget(mostPlayedCard_);
592
593 layout->addLayout(cardsLayout);
594
595 // Charts row
596 auto* chartsLayout = new QHBoxLayout;
597
598 auto* genreGroup = new QGroupBox("By Genre");
599 auto* genreLayout = new QVBoxLayout(genreGroup);
600 genreChart_ = new PieChartWidget(this, themeManager_);
601 genreLayout->addWidget(genreChart_);
602 chartsLayout->addWidget(genreGroup);
603
604 auto* sourceGroup = new QGroupBox("By Source");
605 auto* sourceLayout = new QVBoxLayout(sourceGroup);
606 sourceChart_ = new PieChartWidget(this, themeManager_);
607 sourceLayout->addWidget(sourceChart_);
608 chartsLayout->addWidget(sourceGroup);
609
610 layout->addLayout(chartsLayout, 1);
611}
612
613void GameStatisticsDialog::setupPlaytimeTab(QWidget* tab)
614{
615 auto* layout = new QVBoxLayout(tab);
616
617 // Stats cards
618 auto* cardsLayout = new QHBoxLayout;
619
620 weeklyPlaytimeCard_ = new StatCard("This Week", "0h", "\u25A0", this, themeManager_);
621 cardsLayout->addWidget(weeklyPlaytimeCard_);
622
623 monthlyPlaytimeCard_ = new StatCard("This Month", "0h", "\u25A1", this, themeManager_);
624 cardsLayout->addWidget(monthlyPlaytimeCard_);
625
626 longestSessionCard_ = new StatCard("Longest Session", "0h", "\u2605", this, themeManager_);
627 cardsLayout->addWidget(longestSessionCard_);
628
629 layout->addLayout(cardsLayout);
630
631 // Activity heatmap
632 auto* heatmapGroup = new QGroupBox("Activity (Last 12 Months)");
633 auto* heatmapLayout = new QVBoxLayout(heatmapGroup);
634 activityHeatmap_ = new ActivityHeatmapWidget(this, themeManager_);
635 heatmapLayout->addWidget(activityHeatmap_);
636 layout->addWidget(heatmapGroup);
637
638 // Top games bar chart
639 auto* topGamesGroup = new QGroupBox("Top 10 Most Played");
640 auto* topGamesLayout = new QVBoxLayout(topGamesGroup);
641 topGamesChart_ = new BarChartWidget(this, themeManager_);
642 topGamesChart_->setMaxBars(10);
643 topGamesLayout->addWidget(topGamesChart_);
644 layout->addWidget(topGamesGroup, 1);
645}
646
647void GameStatisticsDialog::setupLibraryTab(QWidget* tab)
648{
649 auto* layout = new QVBoxLayout(tab);
650
651 // Stats cards
652 auto* cardsLayout = new QHBoxLayout;
653
654 installedGamesCard_ = new StatCard("Installed", "0", "\u25CF", this, themeManager_);
655 cardsLayout->addWidget(installedGamesCard_);
656
657 favoriteGamesCard_ = new StatCard("Favorites", "0", "\u2605", this, themeManager_);
658 cardsLayout->addWidget(favoriteGamesCard_);
659
660 completedGamesCard_ = new StatCard("Completed", "0", "\xE2\x9C\x93");
661 cardsLayout->addWidget(completedGamesCard_);
662
663 notPlayedCard_ = new StatCard("Never Played", "0", "\u25CB", this, themeManager_);
664 cardsLayout->addWidget(notPlayedCard_);
665
666 layout->addLayout(cardsLayout);
667
668 // Charts and lists
669 auto* bottomLayout = new QHBoxLayout;
670
671 // Charts column
672 auto* chartsColumn = new QVBoxLayout;
673
674 auto* completionGroup = new QGroupBox("Completion Status");
675 auto* completionLayout = new QVBoxLayout(completionGroup);
676 completionChart_ = new PieChartWidget(this, themeManager_);
677 completionLayout->addWidget(completionChart_);
678 chartsColumn->addWidget(completionGroup);
679
680 auto* installGroup = new QGroupBox("Installation Status");
681 auto* installLayout = new QVBoxLayout(installGroup);
682 installStatusChart_ = new PieChartWidget(this, themeManager_);
683 installLayout->addWidget(installStatusChart_);
684 chartsColumn->addWidget(installGroup);
685
686 bottomLayout->addLayout(chartsColumn);
687
688 // Lists column
689 auto* listsColumn = new QVBoxLayout;
690
691 auto* recentlyAddedGroup = new QGroupBox("Recently Added");
692 auto* recentlyAddedLayout = new QVBoxLayout(recentlyAddedGroup);
693 recentlyAddedList_ = new QListWidget;
694 recentlyAddedList_->setMaximumHeight(150);
695 connect(recentlyAddedList_, &QListWidget::itemDoubleClicked, this,
696 &GameStatisticsDialog::onGameDoubleClicked);
697 recentlyAddedLayout->addWidget(recentlyAddedList_);
698 listsColumn->addWidget(recentlyAddedGroup);
699
700 auto* recentlyPlayedGroup = new QGroupBox("Recently Played");
701 auto* recentlyPlayedLayout = new QVBoxLayout(recentlyPlayedGroup);
702 recentlyPlayedList_ = new QListWidget;
703 recentlyPlayedList_->setMaximumHeight(150);
704 connect(recentlyPlayedList_, &QListWidget::itemDoubleClicked, this,
705 &GameStatisticsDialog::onGameDoubleClicked);
706 recentlyPlayedLayout->addWidget(recentlyPlayedList_);
707 listsColumn->addWidget(recentlyPlayedGroup);
708
709 bottomLayout->addLayout(listsColumn);
710
711 layout->addLayout(bottomLayout, 1);
712}
713
714void GameStatisticsDialog::onTimeRangeChanged(int index)
715{
716 daysFilter_ = timeRangeCombo_->itemData(index).toInt();
717 refreshStatistics();
718}
719
720void GameStatisticsDialog::onGameDoubleClicked(QListWidgetItem* item)
721{
722 // Could emit a signal to navigate to the game in the main window
723 Q_UNUSED(item);
724}
725
726void GameStatisticsDialog::refreshStatistics()
727{
728 calculateOverviewStats();
729 calculatePlaytimeStats();
730 calculateLibraryStats();
731}
732
733void GameStatisticsDialog::calculateOverviewStats()
734{
735 time_t now = time(nullptr);
736 time_t cutoff = (daysFilter_ > 0) ? now - daysFilter_ * 86400 : 0;
737
738 int totalGames = 0;
739 double totalPlaytime = 0;
740 int totalSessions = 0;
741 std::map<std::string, int> genreCounts;
742 std::map<GameSource, int> sourceCounts;
743 std::string mostPlayedName;
744 double mostPlayedTime = 0;
745
746 for (const auto* game : games_)
747 {
748 if (!game)
749 continue;
750
751 // Filter by time if needed
752 if (daysFilter_ > 0 && game->statistics.lastPlayed > 0 &&
753 game->statistics.lastPlayed < cutoff)
754 {
755 continue;
756 }
757
758 totalGames++;
759 totalPlaytime += game->statistics.totalPlayTimeSeconds;
760 totalSessions += game->statistics.timesLaunched;
761
762 if (game->statistics.totalPlayTimeSeconds > mostPlayedTime)
763 {
764 mostPlayedTime = game->statistics.totalPlayTimeSeconds;
765 mostPlayedName = game->name;
766 }
767
768 // Count genres
769 for (const auto& genre : game->metadata.genres)
770 {
771 genreCounts[genre]++;
772 }
773
774 // Count sources
775 sourceCounts[game->source]++;
776 }
777
778 // Update stat cards
779 totalGamesCard_->setValue(QString::number(totalGames));
780
781 totalPlaytimeCard_->setValue(formatPlaytime(totalPlaytime));
782
783 if (totalSessions > 0)
784 {
785 double avgSession = totalPlaytime / totalSessions;
786 avgSessionCard_->setValue(formatPlaytime(avgSession));
787 }
788 else
789 {
790 avgSessionCard_->setValue("0m");
791 }
792
793 if (!mostPlayedName.empty())
794 {
795 QString truncated = QString::fromStdString(mostPlayedName);
796 if (truncated.length() > 15)
797 {
798 truncated = truncated.left(12) + "...";
799 }
800 mostPlayedCard_->setValue(truncated);
801 mostPlayedCard_->setSubtext(formatPlaytime(mostPlayedTime));
802 }
803 else
804 {
805 mostPlayedCard_->setValue("-");
806 }
807
808 // Build genre chart data
809 std::vector<PieChartWidget::Slice> genreSlices;
810 std::vector<std::pair<std::string, int>> sortedGenres(genreCounts.begin(), genreCounts.end());
811 std::sort(sortedGenres.begin(), sortedGenres.end(),
812 [](const auto& a, const auto& b) { return a.second > b.second; });
813
814 QList<QColor> colors = {QColor("#6366f1"), QColor("#8b5cf6"), QColor("#a855f7"),
815 QColor("#d946ef"), QColor("#ec4899"), QColor("#f43f5e"),
816 QColor("#ef4444"), QColor("#f97316"), QColor("#f59e0b")};
817
818 int colorIdx = 0;
819 for (size_t i = 0; i < qMin(sortedGenres.size(), size_t(8)); ++i)
820 {
821 genreSlices.push_back({QString::fromStdString(sortedGenres[i].first),
822 static_cast<double>(sortedGenres[i].second),
823 colors[colorIdx++ % colors.size()]});
824 }
825 genreChart_->setData(genreSlices);
826
827 // Build source chart data
828 std::vector<PieChartWidget::Slice> sourceSlices;
829 sourceSlices.reserve(sourceCounts.size());
830 auto sourceColor = [](GameSource src) -> QColor
831 {
832 switch (src)
833 {
835 return QColor("#1b2838");
836 case GameSource::GOG:
837 return QColor("#86328a");
838 case GameSource::Epic:
839 return QColor("#2a2a2a");
840 case GameSource::Itch:
841 return QColor("#fa5c5c");
843 return QColor("#ff9900");
845 return QColor("#4ade80");
847 return QColor("#4a86cf");
848 default:
849 return QColor("#6b7280");
850 }
851 };
852 auto sourceName = [](GameSource src) -> QString
853 {
854 switch (src)
855 {
857 return "Steam";
858 case GameSource::GOG:
859 return "GOG";
860 case GameSource::Epic:
861 return "Epic";
862 case GameSource::Itch:
863 return "itch.io";
865 return "Lutris";
867 return "Local";
869 return "Flatpak";
870 default:
871 return "Other";
872 }
873 };
874
875 for (const auto& [source, count] : sourceCounts)
876 {
877 sourceSlices.push_back(
878 {sourceName(source), static_cast<double>(count), sourceColor(source)});
879 }
880 sourceChart_->setData(sourceSlices);
881}
882
883void GameStatisticsDialog::calculatePlaytimeStats()
884{
885 time_t now = time(nullptr);
886 time_t weekAgo = now - 7 * 86400;
887 time_t monthAgo = now - 30 * 86400;
888
889 double weeklyPlaytime = 0;
890 double monthlyPlaytime = 0;
891 double longestSession = 0;
892 std::map<int, double> dailyActivity;
893
894 // Collect top games
895 std::vector<std::pair<std::string, double>> gamePlaytimes;
896
897 for (const auto* game : games_)
898 {
899 if (!game)
900 continue;
901
902 gamePlaytimes.push_back({game->name, game->statistics.totalPlayTimeSeconds});
903
904 // Calculate weekly/monthly (simplified - using total if played recently)
905 if (game->statistics.lastPlayed >= weekAgo)
906 {
907 weeklyPlaytime += game->statistics.totalPlayTimeSeconds / 10; // Estimate
908 }
909 if (game->statistics.lastPlayed >= monthAgo)
910 {
911 monthlyPlaytime += game->statistics.totalPlayTimeSeconds / 30;
912 }
913
914 // Track longest average session
915 if (game->statistics.timesLaunched > 0)
916 {
917 double avgSession = game->statistics.totalPlayTimeSeconds /
918 static_cast<double>(game->statistics.timesLaunched);
919 if (avgSession > longestSession)
920 longestSession = avgSession;
921 }
922
923 // Simulate daily activity based on last played
924 if (game->statistics.lastPlayed > 0)
925 {
926 int daysAgo = static_cast<int>((now - game->statistics.lastPlayed) / 86400);
927 if (daysAgo < 365)
928 {
929 double estimatedDaily = game->statistics.totalPlayTimeSeconds / 3600.0 /
930 qMax(1, game->statistics.timesLaunched);
931 dailyActivity[daysAgo] += estimatedDaily;
932 }
933 }
934 }
935
936 // Update cards
937 weeklyPlaytimeCard_->setValue(formatPlaytime(weeklyPlaytime));
938 monthlyPlaytimeCard_->setValue(formatPlaytime(monthlyPlaytime));
939 longestSessionCard_->setValue(formatPlaytime(longestSession));
940
941 // Update heatmap
942 activityHeatmap_->setActivityData(dailyActivity);
943
944 // Sort and build top games chart
945 std::sort(gamePlaytimes.begin(), gamePlaytimes.end(),
946 [](const auto& a, const auto& b) { return a.second > b.second; });
947
948 std::vector<BarChartWidget::Bar> bars;
949 for (size_t i = 0; i < qMin(gamePlaytimes.size(), size_t(10)); ++i)
950 {
951 if (gamePlaytimes[i].second > 0)
952 {
953 bars.push_back({QString::fromStdString(gamePlaytimes[i].first), gamePlaytimes[i].second,
954 formatPlaytime(gamePlaytimes[i].second)});
955 }
956 }
957 topGamesChart_->setData(bars);
958}
959
960void GameStatisticsDialog::calculateLibraryStats()
961{
962 int installed = 0;
963 int favorites = 0;
964 int completed = 0;
965 int notPlayed = 0;
966
967 std::map<CompletionStatus, int> completionCounts;
968 std::map<GameStatus, int> statusCounts;
969
970 std::vector<std::pair<time_t, const Game*>> recentlyAdded;
971 std::vector<std::pair<time_t, const Game*>> recentlyPlayed;
972
973 for (const auto* game : games_)
974 {
975 if (!game)
976 continue;
977
978 if (game->isInstalled())
979 {
980 installed++;
981 }
982 if (game->isFavorite)
983 {
984 favorites++;
985 }
986 if (game->completionStatus == CompletionStatus::Completed)
987 {
988 completed++;
989 }
990 if (game->statistics.timesLaunched == 0)
991 {
992 notPlayed++;
993 }
994
995 completionCounts[game->completionStatus]++;
996 statusCounts[game->status]++;
997
998 if (game->statistics.dateAdded > 0)
999 {
1000 recentlyAdded.push_back({game->statistics.dateAdded, game});
1001 }
1002 if (game->statistics.lastPlayed > 0)
1003 {
1004 recentlyPlayed.push_back({game->statistics.lastPlayed, game});
1005 }
1006 }
1007
1008 // Update cards
1009 installedGamesCard_->setValue(QString::number(installed));
1010 favoriteGamesCard_->setValue(QString::number(favorites));
1011 completedGamesCard_->setValue(QString::number(completed));
1012 notPlayedCard_->setValue(QString::number(notPlayed));
1013
1014 // Completion chart
1015 auto completionColor = [](CompletionStatus status) -> QColor
1016 {
1017 switch (status)
1018 {
1020 return QColor("#6b7280");
1022 return QColor("#3b82f6");
1024 return QColor("#10b981");
1026 return QColor("#22c55e");
1028 return QColor("#f59e0b");
1030 return QColor("#ef4444");
1032 return QColor("#8b5cf6");
1033 default:
1034 return QColor("#9ca3af");
1035 }
1036 };
1037 auto completionName = [](CompletionStatus status) -> QString
1038 {
1039 switch (status)
1040 {
1042 return "Not Played";
1044 return "Playing";
1046 return "Beaten";
1048 return "Completed";
1050 return "On Hold";
1052 return "Abandoned";
1054 return "Played";
1055 default:
1056 return "Unknown";
1057 }
1058 };
1059
1060 std::vector<PieChartWidget::Slice> completionSlices;
1061 completionSlices.reserve(completionCounts.size());
1062 for (const auto& [status, count] : completionCounts)
1063 {
1064 completionSlices.push_back(
1065 {completionName(status), static_cast<double>(count), completionColor(status)});
1066 }
1067 completionChart_->setData(completionSlices);
1068
1069 // Game status chart
1070 auto statusColor = [](GameStatus status) -> QColor
1071 {
1072 switch (status)
1073 {
1075 return QColor("#6b7280");
1077 return QColor("#22c55e");
1079 return QColor("#fbbf24");
1081 return QColor("#3b82f6");
1083 return QColor("#f59e0b");
1085 return QColor("#8b5cf6");
1087 return QColor("#ec4899");
1088 default:
1089 return QColor("#9ca3af");
1090 }
1091 };
1092 auto statusName = [](GameStatus status) -> QString
1093 {
1094 switch (status)
1095 {
1097 return "Not Installed";
1099 return "Installed";
1101 return "Launching";
1103 return "Running";
1105 return "Closing";
1107 return "Installing";
1109 return "Updating";
1110 default:
1111 return "Unknown";
1112 }
1113 };
1114
1115 std::vector<PieChartWidget::Slice> statusSlices;
1116 statusSlices.reserve(statusCounts.size());
1117 for (const auto& [status, count] : statusCounts)
1118 {
1119 statusSlices.push_back(
1120 {statusName(status), static_cast<double>(count), statusColor(status)});
1121 }
1122 installStatusChart_->setData(statusSlices);
1123
1124 // Recently added list
1125 std::sort(recentlyAdded.begin(), recentlyAdded.end(),
1126 [](const auto& a, const auto& b) { return a.first > b.first; });
1127 recentlyAddedList_->clear();
1128 for (size_t i = 0; i < qMin(recentlyAdded.size(), size_t(10)); ++i)
1129 {
1130 auto* item = new QListWidgetItem(QString::fromStdString(recentlyAdded[i].second->name));
1131 item->setData(Qt::UserRole, QString::fromStdString(recentlyAdded[i].second->id));
1132 item->setToolTip(QString("Added: %1").arg(formatDate(recentlyAdded[i].first)));
1133 recentlyAddedList_->addItem(item);
1134 }
1135
1136 // Recently played list
1137 std::sort(recentlyPlayed.begin(), recentlyPlayed.end(),
1138 [](const auto& a, const auto& b) { return a.first > b.first; });
1139 recentlyPlayedList_->clear();
1140 for (size_t i = 0; i < qMin(recentlyPlayed.size(), size_t(10)); ++i)
1141 {
1142 auto* item = new QListWidgetItem(QString::fromStdString(recentlyPlayed[i].second->name));
1143 item->setData(Qt::UserRole, QString::fromStdString(recentlyPlayed[i].second->id));
1144 item->setToolTip(QString("Last played: %1").arg(formatDate(recentlyPlayed[i].first)));
1145 recentlyPlayedList_->addItem(item);
1146 }
1147}
1148
1149QString GameStatisticsDialog::formatPlaytime(double seconds) const
1150{
1151 if (seconds < 60)
1152 {
1153 return QString("%1s").arg(static_cast<int>(seconds));
1154 }
1155 else if (seconds < 3600)
1156 {
1157 return QString("%1m").arg(static_cast<int>(seconds / 60));
1158 }
1159 else
1160 {
1161 double hours = seconds / 3600;
1162 if (hours >= 100)
1163 {
1164 return QString("%1h").arg(static_cast<int>(hours));
1165 }
1166 return QString("%1h").arg(hours, 0, 'f', 1);
1167 }
1168}
1169
1170QString GameStatisticsDialog::formatDate(time_t timestamp) const
1171{
1172 if (timestamp == 0)
1173 return "Unknown";
1174 return QDateTime::fromSecsSinceEpoch(timestamp).toString("yyyy-MM-dd");
1175}
1176
1177void GameStatisticsDialog::applyTheme()
1178{
1179 const auto& c = themeManager_->colors();
1180
1181 setStyleSheet(QString("QDialog { background-color: %1; }").arg(c.windowBackground.name()));
1182
1183 // Tab widget styling
1184 tabWidget_->setStyleSheet(QString("QTabWidget::pane {"
1185 " border: 1px solid %1;"
1186 " border-radius: 6px;"
1187 " background: %2;"
1188 "}"
1189 "QTabBar::tab {"
1190 " background: %3;"
1191 " color: %4;"
1192 " padding: 8px 20px;"
1193 " border: 1px solid %1;"
1194 " border-bottom: none;"
1195 " border-top-left-radius: 4px;"
1196 " border-top-right-radius: 4px;"
1197 "}"
1198 "QTabBar::tab:selected {"
1199 " background: %2;"
1200 " color: %5;"
1201 "}"
1202 "QTabBar::tab:hover:!selected {"
1203 " background: %6;"
1204 "}")
1205 .arg(c.border.name())
1206 .arg(c.panelBackground.name())
1207 .arg(c.inputBackground.name())
1208 .arg(c.textSecondary.name())
1209 .arg(c.textPrimary.name())
1210 .arg(c.hoverBackground.name()));
1211
1212 // Group box styling
1213 QString groupStyle = QString("QGroupBox {"
1214 " font-weight: bold;"
1215 " color: %1;"
1216 " border: 1px solid %2;"
1217 " border-radius: 6px;"
1218 " margin-top: 8px;"
1219 " padding-top: 10px;"
1220 "}"
1221 "QGroupBox::title {"
1222 " subcontrol-origin: margin;"
1223 " left: 10px;"
1224 " padding: 0 5px;"
1225 "}")
1226 .arg(c.textPrimary.name())
1227 .arg(c.border.name());
1228
1229 for (auto* groupBox : findChildren<QGroupBox*>())
1230 {
1231 groupBox->setStyleSheet(groupStyle);
1232 }
1233
1234 // List widget styling
1235 QString listStyle = QString("QListWidget {"
1236 " background-color: %1;"
1237 " border: 1px solid %2;"
1238 " border-radius: 4px;"
1239 " color: %3;"
1240 "}"
1241 "QListWidget::item {"
1242 " padding: 4px;"
1243 "}"
1244 "QListWidget::item:selected {"
1245 " background-color: %4;"
1246 " color: %5;"
1247 "}"
1248 "QListWidget::item:hover:!selected {"
1249 " background-color: %6;"
1250 "}")
1251 .arg(c.inputBackground.name())
1252 .arg(c.border.name())
1253 .arg(c.textPrimary.name())
1254 .arg(c.accent.name())
1255 .arg(c.textOnAccent.name())
1256 .arg(c.hoverBackground.name());
1257
1258 recentlyAddedList_->setStyleSheet(listStyle);
1259 recentlyPlayedList_->setStyleSheet(listStyle);
1260
1261 // Combo box styling
1262 timeRangeCombo_->setStyleSheet(QString("QComboBox {"
1263 " background-color: %1;"
1264 " color: %2;"
1265 " border: 1px solid %3;"
1266 " border-radius: 4px;"
1267 " padding: 5px 10px;"
1268 "}"
1269 "QComboBox:hover {"
1270 " border-color: %4;"
1271 "}"
1272 "QComboBox::drop-down {"
1273 " border: none;"
1274 "}"
1275 "QComboBox QAbstractItemView {"
1276 " background-color: %1;"
1277 " color: %2;"
1278 " selection-background-color: %4;"
1279 "}")
1280 .arg(c.inputBackground.name())
1281 .arg(c.textPrimary.name())
1282 .arg(c.border.name())
1283 .arg(c.accent.name()));
1284}
void setTitle(const QString &title)
void paintEvent(QPaintEvent *event) override
void setActivityData(const std::map< int, double > &dailyHours)
ActivityHeatmapWidget(QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
QSize minimumSizeHint() const override
void paintEvent(QPaintEvent *event) override
QSize sizeHint() const override
void setData(const std::vector< Bar > &bars)
void setTitle(const QString &title)
BarChartWidget(QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void setGames(const std::vector< Game * > &games)
GameStatisticsDialog(QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void setTitle(const QString &title)
PieChartWidget(QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void setData(const std::vector< Slice > &slices)
void paintEvent(QPaintEvent *event) override
void setValue(const QString &value)
void setSubtext(const QString &subtext)
StatCard(const QString &label, const QString &value, const QString &icon="", QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void themeChanged()
Emitted when theme or accent color changes.
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
@ Itch
itch.io indie games
Definition game.h:44
@ Lutris
Lutris community scripts.
Definition game.h:45
@ GOG
GOG.com (DRM-free games).
Definition game.h:42
@ Flatpak
Flatpak package.
Definition game.h:46
@ Epic
Epic Games Store.
Definition game.h:43
GameStatus
Current installation and execution status of the game.
Definition game.h:97
@ Installing
Game is being installed.
Definition game.h:103
@ NotInstalled
Game is in library but not installed.
Definition game.h:98
@ Running
Game is currently running.
Definition game.h:101
@ Closing
Game is shutting down (waiting for process to terminate).
Definition game.h:102
@ Updating
Game is being updated.
Definition game.h:104
@ Installed
Game is installed and ready to play.
Definition game.h:99
@ Launching
Game is being launched (waiting for process to start).
Definition game.h:100
CompletionStatus
User's completion/play status for tracking backlog.
Definition game.h:115
@ Played
Played but no clear completion criteria (e.g., multiplayer).
Definition game.h:122
@ Completed
100% completion (achievements, side content, etc.)
Definition game.h:119
@ Abandoned
Stopped playing, unlikely to return.
Definition game.h:121
@ Beaten
Main story/campaign completed.
Definition game.h:118
@ OnHold
Temporarily paused.
Definition game.h:120
@ Playing
Currently playing.
Definition game.h:117
@ NotPlayed
Never played (backlog).
Definition game.h:116