Add onError callback to load pixmap code

This commit is contained in:
Mm2PL 2024-05-14 14:49:59 +02:00
parent 2e60142a47
commit 6c11b2400a
No known key found for this signature in database
GPG key ID: 94AC9B80EFA15ED9
2 changed files with 40 additions and 22 deletions

View file

@ -11,13 +11,20 @@
namespace chatterino {
void loadPixmapFromUrl(const Url &url, std::function<void(QPixmap)> &&callback)
void loadPixmapFromUrl(const Url &url, std::function<void(QPixmap)> &&onSuccess,
const std::optional<std::function<void()>> &onError)
{
NetworkRequest(url.string)
.concurrent()
.cache()
.onSuccess(
[callback = std::move(callback), url](const NetworkResult &result) {
.onError([onError](const NetworkResult & /*result*/) {
if (onError.has_value())
{
(*onError)();
}
})
.onSuccess([callback = std::move(onSuccess), onError,
url](const NetworkResult &result) {
auto data = result.getData();
QBuffer buffer(&data);
buffer.open(QIODevice::ReadOnly);
@ -28,6 +35,10 @@ void loadPixmapFromUrl(const Url &url, std::function<void(QPixmap)> &&callback)
qCWarning(chatterinoImage)
<< "Can't read image file at" << url.string << ":"
<< reader.errorString();
if (onError.has_value())
{
(*onError)();
}
return;
}
@ -37,6 +48,10 @@ void loadPixmapFromUrl(const Url &url, std::function<void(QPixmap)> &&callback)
qCWarning(chatterinoImage)
<< "Failed reading image at" << url.string << ":"
<< reader.errorString();
if (onError.has_value())
{
(*onError)();
}
return;
}

View file

@ -8,8 +8,11 @@ namespace chatterino {
/**
* Loads an image from url into a QPixmap. Allows for file:// protocol links. Uses cacheing.
*
* @param callback The callback you will get the pixmap by. It will be invoked concurrently with no guarantees on which thread.
* @param onSuccess The callback you will get the pixmap by. It will be invoked concurrently with no guarantees on which thread.
* @param onError The callback that will be called if the request fails or the image cannot be loaded.
*/
void loadPixmapFromUrl(const Url &url, std::function<void(QPixmap)> &&callback);
void loadPixmapFromUrl(
const Url &url, std::function<void(QPixmap)> &&onSuccess,
const std::optional<std::function<void()>> &onError = {});
} // namespace chatterino