xref: /aosp_15_r20/external/openscreen/cast/standalone_receiver/sdl_glue.cc (revision 3f982cf4871df8771c9d4abe6e9a6f8d829b2736)
1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "cast/standalone_receiver/sdl_glue.h"
6 
7 #include <utility>
8 
9 #include "platform/api/task_runner.h"
10 #include "platform/api/time.h"
11 #include "util/osp_logging.h"
12 
13 namespace openscreen {
14 namespace cast {
15 
SDLEventLoopProcessor(TaskRunner * task_runner,std::function<void ()> quit_callback)16 SDLEventLoopProcessor::SDLEventLoopProcessor(
17     TaskRunner* task_runner,
18     std::function<void()> quit_callback)
19     : alarm_(&Clock::now, task_runner),
20       quit_callback_(std::move(quit_callback)) {
21   alarm_.Schedule([this] { ProcessPendingEvents(); }, Alarm::kImmediately);
22 }
23 
24 SDLEventLoopProcessor::~SDLEventLoopProcessor() = default;
25 
RegisterForKeyboardEvent(SDLEventLoopProcessor::KeyboardEventCallback cb)26 void SDLEventLoopProcessor::RegisterForKeyboardEvent(
27     SDLEventLoopProcessor::KeyboardEventCallback cb) {
28   keyboard_callbacks_.push_back(std::move(cb));
29 }
30 
ProcessPendingEvents()31 void SDLEventLoopProcessor::ProcessPendingEvents() {
32   // Process all pending events.
33   SDL_Event event;
34   while (SDL_PollEvent(&event)) {
35     if (event.type == SDL_QUIT) {
36       OSP_VLOG << "SDL_QUIT received, invoking quit callback...";
37       if (quit_callback_) {
38         quit_callback_();
39       }
40     } else if (event.type == SDL_KEYUP) {
41       for (auto& cb : keyboard_callbacks_) {
42         cb(event.key);
43       }
44     }
45   }
46 
47   // Schedule a task to come back and process more pending events.
48   constexpr auto kEventPollPeriod = std::chrono::milliseconds(10);
49   alarm_.ScheduleFromNow([this] { ProcessPendingEvents(); }, kEventPollPeriod);
50 }
51 
52 }  // namespace cast
53 }  // namespace openscreen
54