#include "ImageRegistry.h" ImageRegistry::ImageRegistry() { this->loaded_images = std::unordered_map(); this->loader_queue = std::queue>(); this->binding_queue = std::queue>(); 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([&] { 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)); } }