Skip to content
Repos

DevPlaceApp

C++ 1.2 KB40 lines Opens in site

Directory Raw Download

#include "screens/conversation/WindowFocusWatcher.hpp"

#include <SDL3/SDL.h>

#include <atomic>
#include <memory>

#include "core/UiQueue.hpp"

namespace dp {

struct WindowFocusWatcher::State {
  Handler handler;
  std::shared_ptr<std::atomic<bool>> alive = std::make_shared<std::atomic<bool>>(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<WindowFocusWatcher::State*>(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
29.8ms