From 0e8cc9c3b7442d23a0896cd10f420e3b7b9f314c Mon Sep 17 00:00:00 2001 From: Cvolton Date: Thu, 15 Aug 2024 15:56:06 +0200 Subject: [PATCH] avoid memory leak with notifications --- src/main.cpp | 9 +++++++++ src/utils.cpp | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 4d2be97..fff34fd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -60,6 +60,15 @@ class BI_DLL $modify(MenuLayer) { fixLevelLists(); } + Notification::create("important notification")->show(); + BetterInfo::showUnimportantNotification("unimportant 1", NotificationIcon::Success); + BetterInfo::showUnimportantNotification("unimportant 2", NotificationIcon::Success); + BetterInfo::showUnimportantNotification("unimportant 3", NotificationIcon::Success); + BetterInfo::showUnimportantNotification("unimportant 4", NotificationIcon::Success); + BetterInfo::showUnimportantNotification("unimportant 5", NotificationIcon::Success); + BetterInfo::showUnimportantNotification("unimportant 6", NotificationIcon::Success); + Notification::create("important notification 2")->show(); + return true; } }; diff --git a/src/utils.cpp b/src/utils.cpp index 35c3db2..2c85566 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -887,18 +887,26 @@ long long BetterInfo::strtol(std::string_view str) { return result; } -static std::vector> notifications; +static std::vector> s_notifications; void BetterInfo::showUnimportantNotification(const std::string& content, NotificationIcon icon, float time) { if(GJBaseGameLayer::get()) return; auto notif = Notification::create(content, icon, time); - notifications.push_back(notif); + s_notifications.push_back(notif); notif->show(); + + std::thread([notif, time] { + //assume up to 2 notifications are scheduled outside of this - if this fails nothing much really happens, they just wont be removed immediately + std::this_thread::sleep_for(std::chrono::seconds((int) (time + (s_notifications.size() + 2)))); + Loader::get()->queueInMainThread([notif] { + s_notifications.erase(std::remove(s_notifications.begin(), s_notifications.end(), notif), s_notifications.end()); + }); + }).detach(); } void BetterInfo::cancelUnimportantNotifications() { - for(auto& notification : notifications) { + for(auto& notification : s_notifications) { notification->cancel(); } - notifications.clear(); + s_notifications.clear(); } \ No newline at end of file