diff --git a/Common/UI/IconCache.cpp b/Common/UI/IconCache.cpp index 3c8747d4e6..0dfb2615b9 100644 --- a/Common/UI/IconCache.cpp +++ b/Common/UI/IconCache.cpp @@ -196,7 +196,7 @@ void IconCache::Decimate(int64_t maxSize) { } } -bool IconCache::GetDimensions(const std::string &key, int *width, int *height) { +bool IconCache::GetDimensions(std::string_view key, int *width, int *height) { std::unique_lock lock(lock_); auto iter = cache_.find(key); if (iter == cache_.end()) { @@ -214,12 +214,12 @@ bool IconCache::GetDimensions(const std::string &key, int *width, int *height) { } } -bool IconCache::Contains(const std::string &key) { +bool IconCache::Contains(std::string_view key) { std::unique_lock lock(lock_); return cache_.find(key) != cache_.end(); } -bool IconCache::MarkPending(const std::string &key) { +bool IconCache::MarkPending(std::string_view key) { std::unique_lock lock(lock_); if (cache_.find(key) != cache_.end()) { return false; @@ -227,16 +227,21 @@ bool IconCache::MarkPending(const std::string &key) { if (pending_.find(key) != pending_.end()) { return false; } - pending_.insert(key); + pending_.emplace(key); return true; } -void IconCache::CancelPending(const std::string &key) { +void IconCache::CancelPending(std::string_view key) { std::unique_lock lock(lock_); - pending_.erase(key); + auto iter = pending_.find(key); + if (iter == pending_.end()) { + ERROR_LOG(Log::System, "IconCache: CancelPending called for non-pending key: %.*s", STR_VIEW(key)); + return; + } + pending_.erase(iter); } -bool IconCache::InsertIcon(const std::string &key, IconFormat format, std::string &&data) { +bool IconCache::InsertIcon(std::string_view key, IconFormat format, std::string &&data) { if (key.empty()) { return false; } @@ -248,23 +253,27 @@ bool IconCache::InsertIcon(const std::string &key, IconFormat format, std::strin } std::unique_lock lock(lock_); + if (cache_.find(key) != cache_.end()) { // Already have this entry. return false; } if (data.size() > 1024 * 512) { - WARN_LOG(Log::G3D, "Unusually large icon inserted in icon cache: %s (%d bytes)", key.c_str(), (int)data.size()); + WARN_LOG(Log::G3D, "Unusually large icon inserted in icon cache: %.*s (%d bytes)", STR_VIEW(key), (int)data.size()); } - pending_.erase(key); + auto iter = pending_.find(key); + if (iter != pending_.end()) { + pending_.erase(iter); + } double now = time_now_d(); cache_.emplace(key, Entry{ std::move(data), format, nullptr, now, now, false }); return true; } -Draw::Texture *IconCache::BindIconTexture(UIContext *context, const std::string &key) { +Draw::Texture *IconCache::BindIconTexture(UIContext *context, std::string_view key) { if (key.empty()) { return nullptr; } @@ -300,7 +309,7 @@ Draw::Texture *IconCache::BindIconTexture(UIContext *context, const std::string &height, &buffer); if (result != 1) { - ERROR_LOG(Log::G3D, "IconCache: Failed to load png (%d bytes) for key %s", (int)iter->second.data.size(), key.c_str()); + ERROR_LOG(Log::G3D, "IconCache: Failed to load png (%d bytes) for key %.*s", (int)iter->second.data.size(), STR_VIEW(key)); iter->second.badData = true; return nullptr; } @@ -319,7 +328,7 @@ Draw::Texture *IconCache::BindIconTexture(UIContext *context, const std::string iconDesc.mipLevels = 1; iconDesc.swizzle = Draw::TextureSwizzle::DEFAULT; iconDesc.generateMips = false; - iconDesc.tag = key.c_str(); + iconDesc.tag = "icon"; iconDesc.format = dataFormat; iconDesc.type = Draw::TextureType::LINEAR2D; diff --git a/Common/UI/IconCache.h b/Common/UI/IconCache.h index c93483a95b..e631f77ca6 100644 --- a/Common/UI/IconCache.h +++ b/Common/UI/IconCache.h @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include @@ -32,14 +32,14 @@ class IconCache { public: // NOTE: Don't store the returned texture. Only use it to look up dimensions or other properties, // instead call BindIconTexture every time you want to use it. - Draw::Texture *BindIconTexture(UIContext *context, const std::string &key); + Draw::Texture *BindIconTexture(UIContext *context, std::string_view key); // It's okay to call these from any thread. - bool MarkPending(const std::string &key); // returns false if already pending or loaded - void CancelPending(const std::string &key); - bool InsertIcon(const std::string &key, IconFormat format, std::string &&pngData); - bool GetDimensions(const std::string &key, int *width, int *height); - bool Contains(const std::string &key); + bool MarkPending(std::string_view key); // returns false if already pending or loaded + void CancelPending(std::string_view key); + bool InsertIcon(std::string_view key, IconFormat format, std::string &&pngData); + bool GetDimensions(std::string_view key, int *width, int *height); + bool Contains(std::string_view key); void SaveToFile(FILE *file); bool LoadFromFile(FILE *file); @@ -63,8 +63,8 @@ private: bool badData; }; - std::map cache_; - std::set pending_; + std::map> cache_; + std::set> pending_; std::mutex lock_; diff --git a/Core/RetroAchievements.cpp b/Core/RetroAchievements.cpp index 7b74f45013..c4365c4c3f 100644 --- a/Core/RetroAchievements.cpp +++ b/Core/RetroAchievements.cpp @@ -287,7 +287,8 @@ static void server_call_callback(const rc_api_request_t *request, // If post data is provided, we need to make a POST request, otherwise, a GET request will suffice. auto ac = GetI18NCategory(I18NCat::ACHIEVEMENTS); if (request->post_data) { - std::shared_ptr download = g_DownloadManager.AsyncPostWithCallback(std::string(request->url), std::string(request->post_data), "application/x-www-form-urlencoded", http::RequestFlags::ProgressBar | http::RequestFlags::ProgressBarDelayed, [=](http::Request &download) { + std::shared_ptr download = g_DownloadManager.AsyncPostWithCallback(std::string(request->url), std::string(request->post_data), "application/x-www-form-urlencoded", http::RequestFlags::ProgressBar | http::RequestFlags::ProgressBarDelayed, + [callback, callback_data](http::Request &download) { std::string buffer; download.buffer().TakeAll(&buffer); rc_api_server_response_t response{}; @@ -297,7 +298,8 @@ static void server_call_callback(const rc_api_request_t *request, callback(&response, callback_data); }, ac->T("Contacting RetroAchievements server...")); } else { - std::shared_ptr download = g_DownloadManager.StartDownloadWithCallback(std::string(request->url), Path(), http::RequestFlags::ProgressBar | http::RequestFlags::ProgressBarDelayed, [=](http::Request &download) { + std::shared_ptr download = g_DownloadManager.StartDownloadWithCallback(std::string(request->url), Path(), http::RequestFlags::ProgressBar | http::RequestFlags::ProgressBarDelayed, + [callback, callback_data](http::Request &download) { std::string buffer; download.buffer().TakeAll(&buffer); rc_api_server_response_t response{}; @@ -882,15 +884,15 @@ bool HasAchievementsOrLeaderboards() { return IsActive(); } -void DownloadImageIfMissing(const std::string &cache_key, std::string_view url) { - if (g_iconCache.MarkPending(cache_key)) { - INFO_LOG(Log::Achievements, "Downloading image: %.*s (%s)", (int)url.size(), url.data(), cache_key.c_str()); - g_DownloadManager.StartDownloadWithCallback(url, Path(), http::RequestFlags::Default, [cache_key](http::Request &download) { +void DownloadImageIfMissing(std::string_view url) { + if (g_iconCache.MarkPending(url)) { + INFO_LOG(Log::Achievements, "Downloading image: %.*s", STR_VIEW(url)); + g_DownloadManager.StartDownloadWithCallback(url, Path(), http::RequestFlags::Default, [](http::Request &download) { if (download.ResultCode() != 200) return; std::string data; download.buffer().TakeAll(&data); - g_iconCache.InsertIcon(cache_key, IconFormat::PNG, std::move(data)); + g_iconCache.InsertIcon(download.url(), IconFormat::PNG, std::move(data)); }); } } @@ -945,13 +947,7 @@ void identify_and_load_callback(int result, const char *error_message, rc_client // Successful! Show a message that we're active. const rc_client_game_t *gameInfo = rc_client_get_game_info(client); - char cacheId[128]; - snprintf(cacheId, sizeof(cacheId), "gi:%s", gameInfo->badge_name); - - char temp[512]; - if (RC_OK == rc_client_game_get_image_url(gameInfo, temp, sizeof(temp))) { - Achievements::DownloadImageIfMissing(cacheId, temp); - } + DownloadImageIfMissing(gameInfo->badge_url); GameRegion region = DetectGameRegionFromID(g_paramSFO.GetDiscID()); auto ga = GetI18NCategory(I18NCat::GAME); @@ -962,7 +958,7 @@ void identify_and_load_callback(int result, const char *error_message, rc_client title += regionStr; title += ")"; } - g_OSD.Show(OSDType::MESSAGE_INFO, title, GetGameAchievementSummary(), cacheId, 5.0f); + g_OSD.Show(OSDType::MESSAGE_INFO, title, GetGameAchievementSummary(), gameInfo->badge_url, 5.0f); break; } case RC_NO_GAME_LOADED: diff --git a/Core/RetroAchievements.h b/Core/RetroAchievements.h index ee8495854d..23ba5f1013 100644 --- a/Core/RetroAchievements.h +++ b/Core/RetroAchievements.h @@ -79,7 +79,7 @@ bool HasToken(); /// Called when the system is being shut down. If Shutdown() returns false, the shutdown should be aborted if possible. bool Shutdown(); -void DownloadImageIfMissing(const std::string &cache_key, std::string_view url); +void DownloadImageIfMissing(std::string_view url); /// Called once a frame at vsync time on the CPU thread, during gameplay. void FrameUpdate(); diff --git a/UI/RetroAchievementScreens.cpp b/UI/RetroAchievementScreens.cpp index aee42197c9..65dd5efa2f 100644 --- a/UI/RetroAchievementScreens.cpp +++ b/UI/RetroAchievementScreens.cpp @@ -36,11 +36,11 @@ AudioFileChooser::AudioFileChooser(RequesterToken token, std::string *value, std layoutParams_->width = FILL_PARENT; layoutParams_->height = ITEM_HEIGHT; } - Add(new Choice(ImageID("I_PLAY"), new LinearLayoutParams(ITEM_HEIGHT, ITEM_HEIGHT)))->OnClick.Add([=](UI::EventParams &) { + Add(new Choice(ImageID("I_PLAY"), new LinearLayoutParams(ITEM_HEIGHT, ITEM_HEIGHT)))->OnClick.Add([this](UI::EventParams &) { float achievementVolume = Volume100ToMultiplier(g_Config.iAchievementVolume); g_BackgroundAudio.SFX().Play(sound_, achievementVolume); }); - Add(new FileChooserChoice(token, value, title, BrowseFileType::SOUND_EFFECT, new LinearLayoutParams(1.0f)))->OnChange.Add([=](UI::EventParams &e) { + Add(new FileChooserChoice(token, value, title, BrowseFileType::SOUND_EFFECT, new LinearLayoutParams(1.0f)))->OnChange.Add([this, sound, value](UI::EventParams &e) { std::string path = e.s; Sample *sample = Sample::Load(path); if (sample) { @@ -52,12 +52,12 @@ AudioFileChooser::AudioFileChooser(RequesterToken token, std::string *value, std } }); Choice *trash = new Choice(ImageID("I_TRASHCAN"), new LinearLayoutParams(ITEM_HEIGHT, ITEM_HEIGHT)); - trash->OnClick.Add([=](UI::EventParams &) { + trash->OnClick.Add([sound, value](UI::EventParams &) { g_BackgroundAudio.SFX().UpdateSample(sound, nullptr); value->clear(); }); Add(trash); - trash->SetEnabledFunc([=]() { + trash->SetEnabledFunc([value]() { return !value->empty(); }); } @@ -161,7 +161,7 @@ void RetroAchievementsListScreen::CreateLeaderboardsTab(UI::ViewGroup *viewGroup for (auto &leaderboard : leaderboards) { int leaderboardID = leaderboard->id; - viewGroup->Add(new LeaderboardSummaryView(leaderboard))->OnClick.Add([=](UI::EventParams &e) -> void { + viewGroup->Add(new LeaderboardSummaryView(leaderboard))->OnClick.Add([this, leaderboardID](UI::EventParams &e) -> void { screenManager()->push(new RetroAchievementsLeaderboardScreen(gamePath_, leaderboardID)); }); } @@ -231,7 +231,7 @@ void RetroAchievementsLeaderboardScreen::CreateLeaderboardTab(UI::LinearLayout * auto strip = layout->Add(new ChoiceStrip(ORIENT_HORIZONTAL)); strip->AddChoice(ac->T("Top players")); strip->AddChoice(ac->T("Around me")); - strip->OnChoice.Add([=](UI::EventParams &e) { + strip->OnChoice.Add([this, strip](UI::EventParams &e) { strip->SetSelection(e.a, false); nearMe_ = e.a != 0; FetchEntries(); @@ -317,18 +317,19 @@ void RetroAchievementsSettingsScreen::CreateAccountTab(UI::ViewGroup *viewGroup) } viewGroup->Add(new InfoItem(di->T("Username"), info->username)); // viewGroup->Add(new InfoItem(ac->T("Unread messages"), info.numUnreadMessages)); - viewGroup->Add(new Choice(di->T("Log out")))->OnClick.Add([=](UI::EventParams &) -> void { + viewGroup->Add(new Choice(di->T("Log out")))->OnClick.Add([](UI::EventParams &) -> void { Achievements::Logout(); }); } else { std::string errorMessage; if (Achievements::LoginProblems(&errorMessage)) { viewGroup->Add(new NoticeView(NoticeLevel::WARN, ac->T("Failed logging in to RetroAchievements"), errorMessage)); - viewGroup->Add(new Choice(di->T("Log out")))->OnClick.Add([=](UI::EventParams &) -> void { + viewGroup->Add(new Choice(di->T("Log out")))->OnClick.Add([](UI::EventParams &) -> void { Achievements::Logout(); }); } else if (System_GetPropertyBool(SYSPROP_HAS_LOGIN_DIALOG)) { - viewGroup->Add(new Choice(di->T("Log in")))->OnClick.Add([=](UI::EventParams &) -> void { + viewGroup->Add(new Choice(di->T("Log in")))->OnClick.Add([this](UI::EventParams &) -> void { + auto di = GetI18NCategory(I18NCat::DIALOG); std::string title = StringFromFormat("RetroAchievements: %s", di->T_cstr("Log in")); System_AskUsernamePassword(GetRequesterToken(), title, g_Config.sAchievementsUserName, [](const std::string &value, int) { std::vector parts; @@ -343,25 +344,25 @@ void RetroAchievementsSettingsScreen::CreateAccountTab(UI::ViewGroup *viewGroup) viewGroup->Add(new PopupTextInputChoice(GetRequesterToken(), &g_Config.sAchievementsUserName, di->T("Username"), "", 128, screenManager())); viewGroup->Add(new PopupTextInputChoice(GetRequesterToken(), &password_, di->T("Password"), "", 128, screenManager()))->SetPasswordDisplay(); Choice *loginButton = viewGroup->Add(new Choice(di->T("Log in"))); - loginButton->OnClick.Add([=](UI::EventParams &) -> void { + loginButton->OnClick.Add([this](UI::EventParams &) -> void { if (!g_Config.sAchievementsUserName.empty() && !password_.empty()) { Achievements::LoginAsync(g_Config.sAchievementsUserName.c_str(), password_.c_str()); memset(&password_[0], 0, password_.size()); password_.clear(); } }); - loginButton->SetEnabledFunc([&]() { + loginButton->SetEnabledFunc([this]() { return !g_Config.sAchievementsUserName.empty() && !password_.empty(); }); } - viewGroup->Add(new Choice(ac->T("Register on www.retroachievements.org")))->OnClick.Add([&](UI::EventParams &) -> void { + viewGroup->Add(new Choice(ac->T("Register on www.retroachievements.org")))->OnClick.Add([](UI::EventParams &) -> void { System_LaunchUrl(LaunchUrlType::BROWSER_URL, "https://retroachievements.org/createaccount.php"); }); } using namespace UI; viewGroup->Add(new ItemHeader(di->T("Settings"))); - viewGroup->Add(new CheckBox(&g_Config.bAchievementsEnable, ac->T("Achievements enabled")))->OnClick.Add([&](UI::EventParams &e) -> void { + viewGroup->Add(new CheckBox(&g_Config.bAchievementsEnable, ac->T("Achievements enabled")))->OnClick.Add([this](UI::EventParams &e) -> void { Achievements::UpdateSettings(); RecreateViews(); }); @@ -369,10 +370,10 @@ void RetroAchievementsSettingsScreen::CreateAccountTab(UI::ViewGroup *viewGroup) viewGroup->Add(new CheckBox(&g_Config.bAchievementsSoundEffects, ac->T("Sound Effects")))->SetEnabledPtr(&g_Config.bAchievementsEnable); viewGroup->Add(new ItemHeader(di->T("Links"))); - viewGroup->Add(new Choice(ac->T("RetroAchievements website"), ImageID("I_LINK_OUT")))->OnClick.Add([&](UI::EventParams &) -> void { + viewGroup->Add(new Choice(ac->T("RetroAchievements website"), ImageID("I_LINK_OUT")))->OnClick.Add([](UI::EventParams &) -> void { System_LaunchUrl(LaunchUrlType::BROWSER_URL, "https://www.retroachievements.org/"); }); - viewGroup->Add(new Choice(ac->T("How to use RetroAchievements"), ImageID("I_LINK_OUT")))->OnClick.Add([&](UI::EventParams &) -> void { + viewGroup->Add(new Choice(ac->T("How to use RetroAchievements"), ImageID("I_LINK_OUT")))->OnClick.Add([](UI::EventParams &) -> void { System_LaunchUrl(LaunchUrlType::BROWSER_URL, "https://www.ppsspp.org/docs/reference/retro-achievements"); }); } @@ -560,18 +561,13 @@ void RenderAchievement(UIContext &dc, const rc_client_achievement_t *achievement } // Download and display the image. - char cacheKey[256]; - snprintf(cacheKey, sizeof(cacheKey), "ai:%s:%s", achievement->badge_name, iconState == RC_CLIENT_ACHIEVEMENT_STATE_UNLOCKED ? "unlocked" : "locked"); - if (RC_OK == rc_client_achievement_get_image_url(achievement, iconState, temp, sizeof(temp))) { - Achievements::DownloadImageIfMissing(cacheKey, temp); - if (g_iconCache.BindIconTexture(&dc, cacheKey)) { - dc.Draw()->DrawTexRect(Bounds(bounds.x + padding, bounds.y + padding, iconSpace, iconSpace), 0.0f, 0.0f, 1.0f, 1.0f, whiteAlpha(alpha)); - } - dc.Flush(); - dc.RebindTexture(); + const char *url = iconState == RC_CLIENT_ACHIEVEMENT_STATE_UNLOCKED ? achievement->badge_url : achievement->badge_locked_url; + Achievements::DownloadImageIfMissing(url); + if (g_iconCache.BindIconTexture(&dc, url)) { + dc.Draw()->DrawTexRect(Bounds(bounds.x + padding, bounds.y + padding, iconSpace, iconSpace), 0.0f, 0.0f, 1.0f, 1.0f, whiteAlpha(alpha)); } - dc.Flush(); + dc.RebindTexture(); dc.PopScissor(); } @@ -614,14 +610,9 @@ static void RenderGameAchievementSummary(UIContext &dc, const Bounds &bounds, fl dc.SetFontScale(1.0f, 1.0f); dc.Flush(); - char url[512]; - char cacheKey[256]; - snprintf(cacheKey, sizeof(cacheKey), "gi:%s", gameInfo->badge_name); - if (RC_OK == rc_client_game_get_image_url(gameInfo, url, sizeof(url))) { - Achievements::DownloadImageIfMissing(cacheKey, url); - if (g_iconCache.BindIconTexture(&dc, cacheKey)) { - dc.Draw()->DrawTexRect(Bounds(bounds.x, bounds.y + (bounds.h - iconSpace) * 0.5f, iconSpace, iconSpace), 0.0f, 0.0f, 1.0f, 1.0f, whiteAlpha(alpha)); - } + Achievements::DownloadImageIfMissing(gameInfo->badge_url); + if (g_iconCache.BindIconTexture(&dc, gameInfo->badge_url)) { + dc.Draw()->DrawTexRect(Bounds(bounds.x, bounds.y + (bounds.h - iconSpace) * 0.5f, iconSpace, iconSpace), 0.0f, 0.0f, 1.0f, 1.0f, whiteAlpha(alpha)); } dc.Flush(); @@ -714,12 +705,10 @@ static void RenderLeaderboardEntry(UIContext &dc, const rc_client_leaderboard_en dc.Flush(); // Come up with a unique name for the icon entry. - char cacheKey[256]; - snprintf(cacheKey, sizeof(cacheKey), "lbe:%s", entry->user); - char temp[512]; - if (RC_OK == rc_client_leaderboard_entry_get_user_image_url(entry, temp, sizeof(temp))) { - Achievements::DownloadImageIfMissing(cacheKey, temp); - if (g_iconCache.BindIconTexture(&dc, cacheKey)) { + char userImageUrl[512]; + if (RC_OK == rc_client_leaderboard_entry_get_user_image_url(entry, userImageUrl, sizeof(userImageUrl))) { + Achievements::DownloadImageIfMissing(userImageUrl); + if (g_iconCache.BindIconTexture(&dc, userImageUrl)) { dc.Draw()->DrawTexRect(Bounds(bounds.x + iconLeft, bounds.y + 4.0f, 64.0f, 64.0f), 0.0f, 0.0f, 1.0f, 1.0f, whiteAlpha(alpha)); } }