game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
async_image_loader.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// async_image_loader.h
4// ==============================================================================
5// Thread-safe async image loading system for game thumbnails and hero images
6// ==============================================================================
7
8#pragma once
9
10#include <QMutex>
11#include <QObject>
12#include <QPixmap>
13#include <QRunnable>
14#include <QSize>
15#include <QString>
16#include <QThreadPool>
17
18#include <atomic>
19#include <deque>
20#include <functional>
21#include <memory>
22#include <unordered_map>
23
24/**
25 * @brief Request for loading an image asynchronously
26 */
28{
29 QString imagePath;
31 QString cacheKey;
32 bool useFastScaling = true; // FastTransformation vs SmoothTransformation
33};
34
35/**
36 * @brief Result of an async image load operation
37 */
39{
40 QString cacheKey;
41 QImage image; // populated by worker thread (QImage is thread-safe)
42 QPixmap pixmap; // populated on main thread in onImageLoadComplete
43 bool success = false;
44};
45
46/**
47 * @brief Thread-safe LRU cache for scaled images
48 *
49 * Provides O(1) lookup and bounded memory usage with LRU eviction.
50 */
52{
53 public:
54 explicit ImageCache(size_t maxSize = 300);
55
56 // Thread-safe cache operations
57 bool contains(const QString& key) const;
58 QPixmap get(const QString& key);
59 void insert(const QString& key, const QPixmap& pixmap);
60 void clear();
61
62 // Stats for debugging
63 size_t size() const;
64 size_t hitCount() const
65 {
66 return hitCount_.load();
67 }
68 size_t missCount() const
69 {
70 return missCount_.load();
71 }
72
73 private:
74 void evictOldest();
75 void touchEntry(const QString& key);
76
77 mutable QMutex mutex_;
78 std::unordered_map<QString, QPixmap> cache_;
79 std::deque<QString> lruOrder_;
80 size_t maxSize_;
81
82 // Statistics
83 mutable std::atomic<size_t> hitCount_{0};
84 mutable std::atomic<size_t> missCount_{0};
85};
86
87/**
88 * @brief Async image loader using QThreadPool
89 *
90 * Loads and scales images in background threads, emits signals when complete.
91 * Automatically manages a thread-safe LRU cache.
92 *
93 * Usage:
94 * auto* loader = new AsyncImageLoader(this);
95 * connect(loader, &AsyncImageLoader::imageLoaded, this, &MyWidget::onImageLoaded);
96 * loader->requestImage("game123", "/path/to/image.png", QSize(150, 225));
97 *
98 * The loader will:
99 * 1. Check cache first (fast path, no thread spawn)
100 * 2. If miss, queue load task to thread pool
101 * 3. Emit imageLoaded() on main thread when complete
102 */
103class AsyncImageLoader : public QObject
104{
105 Q_OBJECT
106
107 public:
108 explicit AsyncImageLoader(QObject* parent = nullptr);
109 ~AsyncImageLoader() override;
110
111 /**
112 * @brief Request an image to be loaded asynchronously
113 * @param cacheKey Unique key for caching (e.g., "gameId_width_height")
114 * @param imagePath Path to the image file
115 * @param targetSize Desired scaled size
116 * @param useFastScaling Use Qt::FastTransformation (true) or SmoothTransformation (false)
117 * @param priority Higher priority tasks run first (default 0)
118 *
119 * If image is already cached, emits imageLoaded immediately (on next event loop).
120 * Otherwise queues a background task.
121 */
122 void requestImage(const QString& cacheKey, const QString& imagePath, const QSize& targetSize,
123 bool useFastScaling = true, int priority = 0);
124
125 /**
126 * @brief Cancel all pending requests (useful when changing views)
127 */
128 void cancelAll();
129
130 /**
131 * @brief Clear the image cache
132 */
133 void clearCache();
134
135 /**
136 * @brief Check if an image is already cached
137 */
138 bool isCached(const QString& cacheKey) const;
139
140 /**
141 * @brief Get cached image directly (for synchronous fallback)
142 * @return Cached pixmap or null pixmap if not cached
143 */
144 QPixmap getCached(const QString& cacheKey);
145
146 /**
147 * @brief Set maximum cache size
148 */
149 void setMaxCacheSize(size_t maxSize);
150
151 /**
152 * @brief Get cache statistics
153 */
154 void getCacheStats(size_t& size, size_t& hits, size_t& misses) const;
155
156 signals:
157 /**
158 * @brief Emitted when an image has been loaded (on main thread)
159 * @param cacheKey The key used in requestImage()
160 * @param pixmap The loaded and scaled pixmap (null if failed)
161 */
162 void imageLoaded(const QString& cacheKey, const QPixmap& pixmap);
163
164 private slots:
165 void onImageLoadComplete(const ImageLoadResult& result);
166
167 private:
168 // Internal task for thread pool
169 class ImageLoadTask;
170
171 std::unique_ptr<ImageCache> cache_;
172 QThreadPool* threadPool_;
173
174 // Track pending requests to avoid duplicates
175 mutable QMutex pendingMutex_;
176 std::unordered_map<QString, bool> pendingRequests_;
177
178 // Generation counter for cancellation
179 std::atomic<uint64_t> generation_{0};
180};
181
182// ==============================================================================
183// Helper: Quantize size for better cache efficiency
184// ==============================================================================
185
186/**
187 * @brief Round size to nearest quantization step for cache efficiency
188 *
189 * E.g., with step=16: 147x223 → 144x224
190 * This increases cache hit rate during smooth resize operations.
191 */
192inline QSize quantizeSize(const QSize& size, int step = 16)
193{
194 return QSize(((size.width() + step / 2) / step) * step,
195 ((size.height() + step / 2) / step) * step);
196}
197
198/**
199 * @brief Generate cache key for an image at a specific size
200 */
201inline QString makeImageCacheKey(const QString& gameId, const QSize& size,
202 const QString& imageType = QString())
203{
204 QSize quantized = quantizeSize(size);
205 if (imageType.isEmpty())
206 return QStringLiteral("%1_%2x%3")
207 .arg(gameId)
208 .arg(quantized.width())
209 .arg(quantized.height());
210 else
211 return QStringLiteral("%1_%2_%3x%4")
212 .arg(gameId, imageType)
213 .arg(quantized.width())
214 .arg(quantized.height());
215}
QSize quantizeSize(const QSize &size, int step=16)
Round size to nearest quantization step for cache efficiency.
QString makeImageCacheKey(const QString &gameId, const QSize &size, const QString &imageType=QString())
Generate cache key for an image at a specific size.
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.
size_t missCount() const
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 hitCount() const
size_t size() const
Request for loading an image asynchronously.
Result of an async image load operation.