game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_thumbnail_cache.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// ui/qt/game_thumbnail_cache.cpp
4// ==============================================================================
5// Extracted from MainWindow in the MED-7 pass.
6// ==============================================================================
7
9
10#include "dpr_utils.h"
11#include "models/game.h"
12
13#include <QFile>
14#include <QMetaObject>
15#include <QRunnable>
16#include <QThreadPool>
17#include <QtGlobal>
18#include <algorithm>
19
20// ==============================================================================
21// Construction
22// ==============================================================================
23
24GameThumbnailCache::GameThumbnailCache(size_t maxThumbnails, size_t maxHeroImages, QObject* parent)
25 : QObject(parent), maxThumbnails_(maxThumbnails), maxHeroImages_(maxHeroImages)
26{
27}
28
30
31// ==============================================================================
32// Invalidation
33// ==============================================================================
34
36{
37 thumbnailCache_.clear();
38 thumbnailLRU_.clear();
39 heroCache_.clear();
40 heroLRU_.clear();
41 imagePathCache_.clear();
42}
43
44// ==============================================================================
45// Path resolution
46// ==============================================================================
47
48QString GameThumbnailCache::findBestImage(const Game* game, ImageType preferred) const
49{
50 if (!game)
51 return {};
52
53 // Type-specific fallback chain. Lifted verbatim from MainWindow::findBestImage
54 // to preserve the previous behaviour exactly.
55 std::vector<ImageType> fallbackChain;
56 switch (preferred)
57 {
60 break;
64 break;
67 break;
71 break;
72 case ImageType::Icon:
74 break;
75 default:
76 fallbackChain = {preferred};
77 break;
78 }
79
80 for (ImageType type : fallbackChain)
81 {
82 // Cache key: "<gameId>_<typeEnum>"
83 const std::string cacheKey = game->id + "_" + std::to_string(static_cast<int>(type));
84 auto cacheIt = imagePathCache_.find(cacheKey);
85
86 if (cacheIt != imagePathCache_.end())
87 {
88 // Cache hit — empty value means "we checked and it doesn't exist"
89 if (!cacheIt->second.isEmpty())
90 return cacheIt->second;
91 continue;
92 }
93
94 const std::string path = game->getImagePath(type);
95 const QString qpath = QString::fromStdString(path);
96
97 if (!path.empty() && QFile::exists(qpath))
98 {
99 imagePathCache_[cacheKey] = qpath;
100 return qpath;
101 }
102 // Negative cache so we don't re-stat on every paint.
103 imagePathCache_[cacheKey] = QString();
104 }
105
106 return {};
107}
108
109// ==============================================================================
110// Thumbnail cache
111// ==============================================================================
112
113void GameThumbnailCache::touchThumbEntry(const std::string& key)
114{
115 auto it = std::find(thumbnailLRU_.begin(), thumbnailLRU_.end(), key);
116 if (it != thumbnailLRU_.end())
117 thumbnailLRU_.erase(it);
118 thumbnailLRU_.push_front(key);
119}
120
121QPixmap GameThumbnailCache::getGameThumbnail(const Game* game, const QSize& logicalSize,
122 ImageType preferred)
123{
124 if (!game)
125 return {};
126
127 // Quantise logical size to 16-px boundaries so near-size requests
128 // (during zoom/resize) share a cache entry.
129 auto quantize = [](int v) { return ((v + 8) / 16) * 16; };
130 const QSize qSize(quantize(logicalSize.width()), quantize(logicalSize.height()));
131
132 // DPR-aware physical resolution so HiDPI displays render crisply.
133 const qreal devicePixelRatio = dpr::primaryRatio();
134 const QSize physicalSize(static_cast<int>(qRound(qSize.width() * devicePixelRatio)),
135 static_cast<int>(qRound(qSize.height() * devicePixelRatio)));
136
137 const std::string cacheKey = game->id + "_" + std::to_string(qSize.width()) + "x" +
138 std::to_string(qSize.height()) + "_" +
139 std::to_string(static_cast<int>(preferred));
140
141 auto it = thumbnailCache_.find(cacheKey);
142 if (it != thumbnailCache_.end())
143 {
144 touchThumbEntry(cacheKey);
145 return it->second;
146 }
147
148 const QString imagePath = findBestImage(game, preferred);
149 if (imagePath.isEmpty())
150 return {};
151
152 QPixmap original(imagePath);
153 if (original.isNull())
154 return {};
155
156 // Scale to physical pixels then set DPR so layouts treat it as logical size.
157 QPixmap scaled = original.scaled(physicalSize, Qt::KeepAspectRatio, Qt::FastTransformation);
158 scaled.setDevicePixelRatio(devicePixelRatio);
159
160 // LRU eviction before insert.
161 while (thumbnailCache_.size() >= maxThumbnails_ && !thumbnailLRU_.empty())
162 {
163 const std::string& lruKey = thumbnailLRU_.back();
164 thumbnailCache_.erase(lruKey);
165 thumbnailLRU_.pop_back();
166 }
167
168 thumbnailCache_[cacheKey] = scaled;
169 thumbnailLRU_.push_front(cacheKey);
170 return scaled;
171}
172
173// ==============================================================================
174// Hero image cache
175// ==============================================================================
176
177void GameThumbnailCache::touchHeroEntry(const std::string& key)
178{
179 auto it = std::find(heroLRU_.begin(), heroLRU_.end(), key);
180 if (it != heroLRU_.end())
181 heroLRU_.erase(it);
182 heroLRU_.push_front(key);
183}
184
185QPixmap GameThumbnailCache::getHeroImage(const Game* game, int targetWidth)
186{
187 if (!game)
188 return {};
189
190 // Round width to 100-px boundaries for cache-friendliness during resize.
191 int roundedWidth = ((targetWidth + 50) / 100) * 100;
192 roundedWidth = qMax(roundedWidth, 300); // minimum 300 px
193
194 const std::string cacheKey = game->id + "_" + std::to_string(roundedWidth);
195
196 auto it = heroCache_.find(cacheKey);
197 if (it != heroCache_.end())
198 {
199 touchHeroEntry(cacheKey);
200 return it->second; // may be null (negative cache)
201 }
202
203 // Cache miss — load and scale.
204 const QString heroPath = findBestImage(game, ImageType::HeroImage);
205 QPixmap scaledHero;
206 if (!heroPath.isEmpty())
207 {
208 QPixmap heroPixmap(heroPath);
209 if (!heroPixmap.isNull())
210 {
211 // DPR-aware: scale to physical pixels then flag DPR.
212 const qreal devicePixelRatio = dpr::primaryRatio();
213 const int physicalWidth = static_cast<int>(qRound(roundedWidth * devicePixelRatio));
214 scaledHero = heroPixmap.scaledToWidth(physicalWidth, Qt::FastTransformation);
215 scaledHero.setDevicePixelRatio(devicePixelRatio);
216 }
217 }
218
219 // LRU eviction before insert. Always insert (even null) so we don't
220 // re-stat the file on every details-panel repaint.
221 if (heroCache_.size() >= maxHeroImages_)
222 {
223 if (!heroLRU_.empty())
224 {
225 heroCache_.erase(heroLRU_.back());
226 heroLRU_.pop_back();
227 }
228 }
229 heroCache_[cacheKey] = scaledHero;
230 heroLRU_.push_front(cacheKey);
231 return scaledHero;
232}
233
234// ==============================================================================
235// Background pre-population
236// ==============================================================================
237
238void GameThumbnailCache::buildImagePathCache(const std::vector<const Game*>& games)
239{
240 if (shuttingDown_.load())
241 return;
242
243 // Copy game pointers into the lambda; Game lifetimes are managed by the
244 // library controller and outlive the launcher's startup window.
245 std::vector<const Game*> gamesCopy = games;
246
247 QThreadPool::globalInstance()->start(
248 [this, gamesCopy = std::move(gamesCopy)]() mutable
249 {
250 if (shuttingDown_.load())
251 return;
252
253 static const std::vector<ImageType> allTypes = {ImageType::VerticalCover,
256
257 std::unordered_map<std::string, QString> localCache;
258 for (const Game* game : gamesCopy)
259 {
260 if (shuttingDown_.load())
261 return;
262 if (!game)
263 continue;
264
265 for (ImageType type : allTypes)
266 {
267 const std::string cacheKey =
268 game->id + "_" + std::to_string(static_cast<int>(type));
269 const std::string path = game->getImagePath(type);
270 const QString qpath = QString::fromStdString(path);
271 if (!path.empty() && QFile::exists(qpath))
272 localCache[cacheKey] = qpath;
273 else
274 localCache[cacheKey] = QString();
275 }
276 }
277
278 if (shuttingDown_.load())
279 return;
280
281 // Merge into the GUI-thread-owned imagePathCache_ via a queued call.
282 // unordered_map::merge transplants nodes from `local`, leaving any
283 // pre-existing entry in imagePathCache_ untouched (matches the
284 // prior `emplace` insertion-only semantics) and avoids the
285 // `std::move` of the const-qualified key that structured-binding
286 // iteration would have produced.
287 QMetaObject::invokeMethod(
288 this, [this, local = std::move(localCache)]() mutable
289 { imagePathCache_.merge(local); }, Qt::QueuedConnection);
290 });
291}
QPixmap getGameThumbnail(const Game *game, const QSize &logicalSize, ImageType preferred)
Get a logical-size thumbnail with DPR-aware backing store.
~GameThumbnailCache() override
QPixmap getHeroImage(const Game *game, int targetWidth)
Get a hero image scaled to targetWidth logical pixels (preserving aspect ratio).
void clearAll()
Clear all caches (thumbnails, hero images, path validation).
GameThumbnailCache(size_t maxThumbnails=300, size_t maxHeroImages=30, QObject *parent=nullptr)
void buildImagePathCache(const std::vector< const Game * > &games)
Pre-populate the image-path validation cache by stat-ing every image file for every game.
QString findBestImage(const Game *game, ImageType preferred) const
Return the best-available image file path for game, falling back through a type-specific chain when t...
Complete representation of a game in the library.
Definition game.h:767
std::string id
Unique identifier (auto-generated or user-specified).
Definition game.h:773
std::string getImagePath(ImageType type) const
Get path for a specific image type.
Definition game.cpp:221
ImageType
Types of game images available.
Definition game.h:478
@ HeroImage
Wide banner/hero image (landscape).
Definition game.h:480
@ Capsule
Store capsule image (616x353).
Definition game.h:483
@ VerticalCover
Vertical cover art (600x900, portrait).
Definition game.h:479
@ Icon
Small square icon.
Definition game.h:484
@ Header
Small header image (460x215).
Definition game.h:482
qreal primaryRatio()
The primary screen's device pixel ratio.
Definition dpr_utils.h:36