game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
async_image_loader.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// async_image_loader.cpp
4// ==============================================================================
5// Thread-safe async image loading implementation
6// ==============================================================================
7
9
10#include <QCoreApplication>
11#include <QFile>
12#include <QImageReader>
13#include <QMetaObject>
14#include <QPointer>
15
16// ==============================================================================
17// ImageCache Implementation
18// ==============================================================================
19
20ImageCache::ImageCache(size_t maxSize) : maxSize_(maxSize) {}
21
22bool ImageCache::contains(const QString& key) const
23{
24 QMutexLocker lock(&mutex_);
25 return cache_.find(key) != cache_.end();
26}
27
28QPixmap ImageCache::get(const QString& key)
29{
30 QMutexLocker lock(&mutex_);
31
32 auto it = cache_.find(key);
33 if (it == cache_.end())
34 {
35 missCount_++;
36 return QPixmap();
37 }
38
39 hitCount_++;
40 // Move to front of LRU (most recently used)
41 touchEntry(key);
42 return it->second;
43}
44
45void ImageCache::insert(const QString& key, const QPixmap& pixmap)
46{
47 QMutexLocker lock(&mutex_);
48
49 // If already exists, just update and touch
50 auto it = cache_.find(key);
51 if (it != cache_.end())
52 {
53 it->second = pixmap;
54 touchEntry(key);
55 return;
56 }
57
58 // Evict if at capacity
59 while (cache_.size() >= maxSize_ && !lruOrder_.empty())
60 {
61 evictOldest();
62 }
63
64 // Insert new entry
65 cache_[key] = pixmap;
66 lruOrder_.push_front(key);
67}
68
70{
71 QMutexLocker lock(&mutex_);
72 cache_.clear();
73 lruOrder_.clear();
74}
75
76size_t ImageCache::size() const
77{
78 QMutexLocker lock(&mutex_);
79 return cache_.size();
80}
81
82void ImageCache::evictOldest()
83{
84 // Must be called with mutex held
85 if (lruOrder_.empty())
86 return;
87
88 QString oldest = lruOrder_.back();
89 lruOrder_.pop_back();
90 cache_.erase(oldest);
91}
92
93void ImageCache::touchEntry(const QString& key)
94{
95 // Must be called with mutex held
96 // Remove from current position and move to front
97 auto it = std::find(lruOrder_.begin(), lruOrder_.end(), key);
98 if (it != lruOrder_.end())
99 {
100 lruOrder_.erase(it);
101 }
102 lruOrder_.push_front(key);
103}
104
105// ==============================================================================
106// ImageLoadTask - Runnable for thread pool
107// ==============================================================================
108
109class AsyncImageLoader::ImageLoadTask : public QRunnable
110{
111 public:
112 ImageLoadTask(AsyncImageLoader* loader, const ImageLoadRequest& request, uint64_t generation)
113 : loader_(loader) // QPointer — nulls atomically on QObject destruction
114 ,
115 request_(request), generation_(generation)
116 {
117 setAutoDelete(true);
118 }
119
120 void run() override
121 {
122 // Load-time null check: loader still alive?
123 AsyncImageLoader* loader = loader_.data();
124 if (!loader)
125 return;
126
127 // Check if cancelled (generation changed). The generation atomic is a
128 // member of AsyncImageLoader, so accessing it after the null-check is
129 // safe for the duration of this function (Qt guarantees QObject
130 // destruction is serialised with QPointer updates).
131 if (loader->generation_.load() != generation_)
132 return;
133
134 ImageLoadResult result;
135 result.cacheKey = request_.cacheKey;
136 result.success = false;
137
138 // Load image from disk
139 if (QFile::exists(request_.imagePath))
140 {
141 // Use QImageReader for better memory efficiency with large images
142 QImageReader reader(request_.imagePath);
143 reader.setAutoTransform(true);
144
145 // For thumbnails, we can set a scaled size hint to reduce memory
146 // This makes the decoder skip unnecessary pixels
147 if (request_.targetSize.isValid())
148 {
149 QSize originalSize = reader.size();
150 if (originalSize.isValid() &&
151 (originalSize.width() > request_.targetSize.width() * 2 ||
152 originalSize.height() > request_.targetSize.height() * 2))
153 {
154 // Set scale hint for decoder (much faster than post-scale)
155 reader.setScaledSize(request_.targetSize);
156 }
157 }
158
159 QImage image = reader.read();
160 if (!image.isNull())
161 {
162 // Check cancellation again after potentially slow I/O
163 loader = loader_.data();
164 if (!loader || loader->generation_.load() != generation_)
165 return;
166
167 // Scale if needed (if decoder didn't already scale)
168 if (request_.targetSize.isValid() && image.size() != request_.targetSize)
169 {
170 Qt::TransformationMode mode =
171 request_.useFastScaling ? Qt::FastTransformation : Qt::SmoothTransformation;
172
173 image = image.scaled(request_.targetSize, Qt::KeepAspectRatio, mode);
174 }
175
176 // Keep as QImage — QPixmap must only be created on the GUI thread.
177 // Conversion happens in onImageLoadComplete() on the main thread.
178 result.image = std::move(image);
179 result.success = !result.image.isNull();
180 }
181 }
182
183 // Final cancellation + liveness check. If the loader was destroyed
184 // during I/O, bail without posting an invokeMethod at a dead pointer.
185 loader = loader_.data();
186 if (!loader || loader->generation_.load() != generation_)
187 return;
188
189 // Deliver result on main thread. QMetaObject::invokeMethod on a
190 // QPointer-tracked object is still not automatic — we need the
191 // raw pointer here; the null-check above guards the narrow race.
192 QMetaObject::invokeMethod(loader, "onImageLoadComplete", Qt::QueuedConnection,
193 Q_ARG(ImageLoadResult, result));
194 }
195
196 private:
197 QPointer<AsyncImageLoader> loader_;
198 ImageLoadRequest request_;
199 uint64_t generation_;
200};
201
202// ==============================================================================
203// AsyncImageLoader Implementation
204// ==============================================================================
205
207 : QObject(parent), cache_(std::make_unique<ImageCache>(300)),
208 threadPool_(QThreadPool::globalInstance())
209{
210 // Register metatype for cross-thread signal
211 qRegisterMetaType<ImageLoadResult>("ImageLoadResult");
212}
213
218
219void AsyncImageLoader::requestImage(const QString& cacheKey, const QString& imagePath,
220 const QSize& targetSize, bool useFastScaling, int priority)
221{
222 // Fast path: check cache first
223 if (cache_->contains(cacheKey))
224 {
225 QPixmap cached = cache_->get(cacheKey);
226 // Emit on next event loop iteration to maintain async behavior
227 QMetaObject::invokeMethod(
228 this, [this, cacheKey, cached]() { emit imageLoaded(cacheKey, cached); },
229 Qt::QueuedConnection);
230 return;
231 }
232
233 // Check if already pending
234 {
235 QMutexLocker lock(&pendingMutex_);
236 if (pendingRequests_.find(cacheKey) != pendingRequests_.end())
237 {
238 // Already loading, don't duplicate
239 return;
240 }
241 pendingRequests_[cacheKey] = true;
242 }
243
244 // Create and queue load task
245 ImageLoadRequest request;
246 request.imagePath = imagePath;
247 request.targetSize = targetSize;
248 request.cacheKey = cacheKey;
249 request.useFastScaling = useFastScaling;
250
251 auto* task = new ImageLoadTask(this, request, generation_.load());
252 threadPool_->start(task, priority);
253}
254
256{
257 // Increment generation to invalidate all pending tasks
258 generation_++;
259
260 // Clear pending requests
261 QMutexLocker lock(&pendingMutex_);
262 pendingRequests_.clear();
263
264 // Note: Tasks already running will check generation and abort
265 // We don't call threadPool_->clear() because that would affect other users
266}
267
269{
270 cache_->clear();
271}
272
273bool AsyncImageLoader::isCached(const QString& cacheKey) const
274{
275 return cache_->contains(cacheKey);
276}
277
278QPixmap AsyncImageLoader::getCached(const QString& cacheKey)
279{
280 return cache_->get(cacheKey);
281}
282
284{
285 // Create new cache with new size (simple approach)
286 auto newCache = std::make_unique<ImageCache>(maxSize);
287 cache_ = std::move(newCache);
288}
289
290void AsyncImageLoader::getCacheStats(size_t& size, size_t& hits, size_t& misses) const
291{
292 size = cache_->size();
293 hits = cache_->hitCount();
294 misses = cache_->missCount();
295}
296
297void AsyncImageLoader::onImageLoadComplete(const ImageLoadResult& result)
298{
299 // Remove from pending
300 {
301 QMutexLocker lock(&pendingMutex_);
302 pendingRequests_.erase(result.cacheKey);
303 }
304
305 // Convert QImage → QPixmap here on the main thread (QPixmap is not thread-safe).
306 // result is const, so std::move(result.image) yields a const QImage&& —
307 // QPixmap::fromImage's overload set picks the const& version anyway,
308 // making the std::move a no-op. Drop it; clang-tidy
309 // performance-move-const-arg flags the misleading shape.
310 QPixmap pixmap;
311 if (result.success)
312 {
313 pixmap = QPixmap::fromImage(result.image);
314 cache_->insert(result.cacheKey, pixmap);
315 }
316
317 // Emit signal for UI update
318 emit imageLoaded(result.cacheKey, pixmap);
319}
ImageLoadTask(AsyncImageLoader *loader, const ImageLoadRequest &request, uint64_t generation)
void imageLoaded(const QString &cacheKey, const QPixmap &pixmap)
Emitted when an image has been loaded (on main thread).
QPixmap getCached(const QString &cacheKey)
Get cached image directly (for synchronous fallback).
bool isCached(const QString &cacheKey) const
Check if an image is already cached.
void requestImage(const QString &cacheKey, const QString &imagePath, const QSize &targetSize, bool useFastScaling=true, int priority=0)
Request an image to be loaded asynchronously.
void clearCache()
Clear the image cache.
AsyncImageLoader(QObject *parent=nullptr)
void getCacheStats(size_t &size, size_t &hits, size_t &misses) const
Get cache statistics.
void cancelAll()
Cancel all pending requests (useful when changing views).
void setMaxCacheSize(size_t maxSize)
Set maximum cache size.
Thread-safe LRU cache for scaled images.
bool contains(const QString &key) const
ImageCache(size_t maxSize=300)
QPixmap get(const QString &key)
void insert(const QString &key, const QPixmap &pixmap)
size_t size() const
Request for loading an image asynchronously.
Result of an async image load operation.