Something went wrong. Try again.
Youtube chat viewer inspired by chatterino
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485#include "ImageRegistry.h"
ImageRegistry::ImageRegistry() { this->loaded_images = std::unordered_map<std::string, RegistryResult>(); this->loader_queue = std::queue<std::pair<std::string, std::string>>(); this->binding_queue = std::queue<std::pair<std::string, PendingImage>>(); this->loader = nullptr;}
ImageRegistry::~ImageRegistry() { for (const auto& result : this->loaded_images) { this->Unload(result.first); }}
void ImageRegistry::ProcessBindingQueue() { while (!this->binding_queue.empty()) { auto pair = this->binding_queue.front(); this->binding_queue.pop();
auto id = pair.first; auto img = pair.second;
auto bound = RemoteImageLoader::BindPendingImage(img); auto result = &this->loaded_images[id]; result->img = bound; result->ready = true; }}
Image* ImageRegistry::Get(std::string id, std::string url) { // i can just hope that this always runs on the main thread // ...right? auto result = this->loaded_images.find(id); if (result != this->loaded_images.end()) { auto img = &result->second; if (!img->ready) return nullptr; return &img->img; }
this->loaded_images[id] = RegistryResult { false }; this->loader_queue.push(std::pair(id, url));
if (loader == nullptr) { auto thread = std::make_unique<std::thread>([&] { this->RunLoaderThread();
// doing this in the thread itself seems.. illogical? this->loader = nullptr; });
thread->detach(); this->loader = std::move(thread); }
return nullptr;}
void ImageRegistry::Unload(std::string id) { if (!this->loaded_images.contains(id)) return;
auto img = this->loaded_images[id]; RemoteImageLoader::UnloadImage(img.img); this->loaded_images.erase(id);}
void ImageRegistry::RunLoaderThread() { // this could be faster with async requests, but idk // if plain libcurl supports it.. and it'll probably // be fine for now while (!this->loader_queue.empty()) { auto pair = this->loader_queue.front(); this->loader_queue.pop();
auto id = pair.first; auto url = pair.second;
auto img = RemoteImageLoader::FetchRemoteImage(url); this->binding_queue.push(std::pair(id, img)); }}