#include "screens/conversation/WindowFocusWatcher.hpp" #include #include #include #include "core/UiQueue.hpp" namespace dp { struct WindowFocusWatcher::State { Handler handler; std::shared_ptr> alive = std::make_shared>(true); }; namespace { bool onSdlEvent(void* userdata, SDL_Event* e) { if (e->type != SDL_EVENT_WINDOW_FOCUS_GAINED && e->type != SDL_EVENT_WINDOW_FOCUS_LOST) return true; auto* state = static_cast(userdata); const bool active = e->type == SDL_EVENT_WINDOW_FOCUS_GAINED; UiQueue::instance().post([alive = state->alive, state, active] { if (alive->load() && state->handler) state->handler(active); }); return true; } } // namespace WindowFocusWatcher::WindowFocusWatcher(Handler handler) : state_(new State{std::move(handler)}) { SDL_AddEventWatch(onSdlEvent, state_); } WindowFocusWatcher::~WindowFocusWatcher() { SDL_RemoveEventWatch(onSdlEvent, state_); state_->alive->store(false); // The state outlives queued closures only through `alive`; closures check it before touching `state`. UiQueue::instance().post([s = state_] { delete s; }); } } // namespace dp