#include "ui/RemoteImages.hpp" #include #include "core/UiQueue.hpp" #include "net/NetworkService.hpp" #include "spec/ImageLimits.hpp" namespace dp::ui { using L = spec::ImageLimits; namespace { // Box-average downscale so that the longest side is at most maxDim. BitmapPtr downscale(const BitmapPtr& src, int maxDim) { const int w = src->width(), h = src->height(); if (std::max(w, h) <= maxDim) return src; const double s = static_cast(maxDim) / std::max(w, h); const int nw = std::max(1, static_cast(w * s)), nh = std::max(1, static_cast(h * s)); auto out = std::make_shared(nw, nh); for (int y = 0; y < nh; ++y) { const int y0 = static_cast(static_cast(y) * h / nh); const int y1 = std::max(y0 + 1, static_cast(static_cast(y + 1) * h / nh)); for (int x = 0; x < nw; ++x) { const int x0 = static_cast(static_cast(x) * w / nw); const int x1 = std::max(x0 + 1, static_cast(static_cast(x + 1) * w / nw)); double a = 0, r = 0, g = 0, b = 0; for (int yy = y0; yy < y1; ++yy) { for (int xx = x0; xx < x1; ++xx) { const std::uint32_t p = src->at(xx, yy); const double pa = (p >> 24) & 0xFF; a += pa; r += pa * ((p >> 16) & 0xFF); g += pa * ((p >> 8) & 0xFF); b += pa * (p & 0xFF); } } const double n = static_cast((y1 - y0) * (x1 - x0)); std::uint32_t oa = static_cast(a / n + 0.5), orr = 0, og = 0, ob = 0; if (a > 0) { orr = static_cast(r / a + 0.5); og = static_cast(g / a + 0.5); ob = static_cast(b / a + 0.5); } out->data()[static_cast(y) * static_cast(nw) + static_cast(x)] = (std::min(oa, 255u) << 24) | (std::min(orr, 255u) << 16) | (std::min(og, 255u) << 8) | std::min(ob, 255u); } } return out; } bool looksLikeSvg(const std::string& body) { return body.substr(0, 2048).find(" lock(mutex_); stop_ = true; } cv_.notify_all(); for (auto& t : workers_) t.join(); } int RemoteImages::bucket(int rasterPx) { const int c = std::clamp(rasterPx, L::kMinRasterPx, L::kMaxRasterPx); return std::min(L::kMaxRasterPx, (c + L::kRasterBucketPx - 1) / L::kRasterBucketPx * L::kRasterBucketPx); } void RemoteImages::configure(Config config) { config_ = std::move(config); } void RemoteImages::clear() { entries_.clear(); lru_.clear(); waiting_.clear(); bytes_ = 0; inFlight_ = 0; ++generation_; std::lock_guard lock(mutex_); jobs_.clear(); } RemoteImages::Entry& RemoteImages::touch(const std::string& url, bool& created) { auto it = entries_.find(url); created = it == entries_.end(); if (created) { evict(1); lru_.push_front(url); it = entries_.emplace(url, Entry{}).first; it->second.lru = lru_.begin(); } else { lru_.splice(lru_.begin(), lru_, it->second.lru); } return it->second; } BitmapPtr RemoteImages::get(const std::string& url, int rasterPx) { if (url.empty() || url.size() > L::kMaxUrlLength) return nullptr; const int raster = bucket(rasterPx); bool created = false; Entry& e = touch(url, created); if (created) { e.raster = raster; if (!start(url, e)) { // queue full: loud skip, the next get() tries again lru_.erase(e.lru); entries_.erase(url); } return nullptr; } const double cooldown = config_.cooldownSeconds >= 0 ? config_.cooldownSeconds : L::kFailureCooldownSeconds; if (e.state == State::Failed) { const std::chrono::duration since = std::chrono::steady_clock::now() - e.failedAt; if (since.count() >= cooldown) { e.raster = raster; start(url, e); } return nullptr; } if (e.state == State::Ready && e.vector && raster > e.raster) { e.raster = raster; // re-rasterize at the larger size, the old bitmap stays visible meanwhile start(url, e); } return e.bitmap; } bool RemoteImages::isLoading(const std::string& url) const { auto it = entries_.find(url); return it != entries_.end() && (it->second.state == State::Queued || it->second.state == State::Loading); } bool RemoteImages::failed(const std::string& url) const { auto it = entries_.find(url); return it != entries_.end() && it->second.state == State::Failed; } void RemoteImages::retry(const std::string& url) { auto it = entries_.find(url); if (it == entries_.end() || it->second.state != State::Failed) return; start(url, it->second); } bool RemoteImages::start(const std::string& url, Entry& e) { if (waiting_.size() >= L::kMaxQueuedLoads) return false; e.state = State::Queued; e.generation = generation_; waiting_.push_back(url); pump(); return true; } void RemoteImages::pump() { while (inFlight_ < L::kMaxConcurrentLoads && !waiting_.empty()) { const std::string url = waiting_.front(); waiting_.pop_front(); auto it = entries_.find(url); if (it == entries_.end() || it->second.state != State::Queued) continue; it->second.state = State::Loading; ++inFlight_; const std::uint64_t gen = generation_; auto done = [this, url, gen](Result r) { onFetched(url, gen, std::move(r)); }; if (config_.fetcher) { config_.fetcher(url, std::move(done)); } else { HttpRequest req; req.path = url; req.timeoutSeconds = L::kRequestTimeoutSeconds; req.maxResponseBytes = L::kMaxDownloadBytes; NetworkService::instance().send(std::move(req), std::move(done)); } } } void RemoteImages::onFetched(const std::string& url, std::uint64_t generation, Result r) { if (generation != generation_) return; // cleared meanwhile, inFlight_ was reset auto it = entries_.find(url); if (it == entries_.end()) return; if (!r.ok() || r.value().status < 200 || r.value().status >= 300 || r.value().body.empty() || r.value().body.size() > L::kMaxDownloadBytes) { fail(url, it->second); return; } Job job{url, std::move(r.value().body), it->second.raster, generation}; { std::lock_guard lock(mutex_); jobs_.push_back(std::move(job)); } cv_.notify_one(); } void RemoteImages::workerLoop() { for (;;) { Job job; { std::unique_lock lock(mutex_); cv_.wait(lock, [this] { return stop_ || !jobs_.empty(); }); if (stop_) return; job = std::move(jobs_.front()); jobs_.pop_front(); } const bool vector = looksLikeSvg(job.body); BitmapPtr bmp = Bitmap::decode(job.body, job.raster); if (bmp) bmp = downscale(bmp, L::kMaxDecodedDimension); UiQueue::instance().post([this, url = std::move(job.url), gen = job.generation, bmp = std::move(bmp), vector] { finish(url, gen, bmp, vector); }); } } void RemoteImages::finish(const std::string& url, std::uint64_t generation, BitmapPtr bmp, bool vector) { if (generation != generation_) return; auto it = entries_.find(url); if (it == entries_.end()) return; Entry& e = it->second; if (!bmp || bmp->bytes() > byteCap()) { fail(url, e); return; } bytes_ -= e.bytes; e.bitmap = std::move(bmp); e.bytes = e.bitmap->bytes(); bytes_ += e.bytes; e.vector = vector; e.state = State::Ready; --inFlight_; ++version_; evict(); pump(); } void RemoteImages::fail(const std::string& url, Entry& e) { (void)url; bytes_ -= e.bytes; e.bitmap.reset(); e.bytes = 0; e.state = State::Failed; e.failedAt = std::chrono::steady_clock::now(); --inFlight_; ++version_; pump(); } std::size_t RemoteImages::byteCap() const { return std::min(config_.cacheBytes ? config_.cacheBytes : L::kMaxCacheBytes, L::kMaxCacheBytes); } void RemoteImages::evict(std::size_t reserve) { const std::size_t entryCap = std::min(config_.maxEntries ? config_.maxEntries : L::kMaxEntries, L::kMaxEntries); auto over = [&] { return bytes_ > byteCap() || entries_.size() + reserve > entryCap; }; auto it = lru_.end(); while (over() && it != lru_.begin()) { --it; auto e = entries_.find(*it); if (e == entries_.end() || e->second.state == State::Queued || e->second.state == State::Loading) continue; bytes_ -= e->second.bytes; entries_.erase(e); it = lru_.erase(it); } } } // namespace dp::ui