diff --git a/openVulkanoCpp/Base/ThreadBackgroundSleep.cpp b/openVulkanoCpp/Base/ThreadBackgroundSleep.cpp new file mode 100644 index 0000000..98d8683 --- /dev/null +++ b/openVulkanoCpp/Base/ThreadBackgroundSleep.cpp @@ -0,0 +1,47 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +#include "ThreadBackgroundSleep.hpp" +#include "Logger.hpp" +#include "AppEvents.hpp" + +namespace openVulkanoCpp +{ + ThreadBackgroundSleep ThreadBackgroundSleep::INSTANCE; + + ThreadBackgroundSleep::ThreadBackgroundSleep() + { + m_resignHandler = AppEvents::OnWillResignActive += [this]() { m_inBackground = true; }; + m_resumeHandler = AppEvents::OnDidBecomeActive += [this]() { Resume(); }; + } + + ThreadBackgroundSleep::~ThreadBackgroundSleep() + { + AppEvents::OnWillResignActive -= m_resignHandler; + AppEvents::OnDidBecomeActive -= m_resumeHandler; + Resume(); + } + + void ThreadBackgroundSleep::Resume() + { + { + std::unique_lock lock(m_mutex); + m_inBackground = false; + } + m_condVar.notify_all(); + } + + void ThreadBackgroundSleep::CheckForBackground(std::string_view taskName) + { + if (m_inBackground) + { + Logger::MANAGER->info("Sleep {}, because app has been sent to background.", taskName); + std::unique_lock l(m_mutex); + m_condVar.wait(l, [this]{ return !m_inBackground; }); + Logger::MANAGER->info("Resume {}, app is no longer in background.", taskName); + } + } +} \ No newline at end of file diff --git a/openVulkanoCpp/Base/ThreadBackgroundSleep.hpp b/openVulkanoCpp/Base/ThreadBackgroundSleep.hpp new file mode 100644 index 0000000..6d81d0d --- /dev/null +++ b/openVulkanoCpp/Base/ThreadBackgroundSleep.hpp @@ -0,0 +1,34 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +#include +#include +#include + +namespace openVulkanoCpp +{ + class IEventHandler; + + class ThreadBackgroundSleep final + { + std::mutex m_mutex; + std::condition_variable m_condVar; + bool m_inBackground = false; + IEventHandler* m_resignHandler = nullptr; + IEventHandler* m_resumeHandler = nullptr; + + public: + static ThreadBackgroundSleep INSTANCE; + + ThreadBackgroundSleep(); + + ~ThreadBackgroundSleep(); + + void Resume(); + + void CheckForBackground(std::string_view taskName); + }; +}