AnimationFrameCallbackDriver.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2022, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Function.h>
  8. #include <AK/IDAllocator.h>
  9. #include <LibCore/Timer.h>
  10. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  11. namespace Web::HTML {
  12. struct AnimationFrameCallbackDriver {
  13. using Callback = Function<void(i32)>;
  14. AnimationFrameCallbackDriver()
  15. {
  16. m_timer = Core::Timer::create_single_shot(16, [] {
  17. HTML::main_thread_event_loop().schedule();
  18. });
  19. }
  20. i32 add(Callback handler)
  21. {
  22. auto id = m_id_allocator.allocate();
  23. m_callbacks.set(id, move(handler));
  24. if (!m_timer->is_active())
  25. m_timer->start();
  26. return id;
  27. }
  28. bool remove(i32 id)
  29. {
  30. auto it = m_callbacks.find(id);
  31. if (it == m_callbacks.end())
  32. return false;
  33. m_callbacks.remove(it);
  34. m_id_allocator.deallocate(id);
  35. return true;
  36. }
  37. void run()
  38. {
  39. auto taken_callbacks = move(m_callbacks);
  40. for (auto& [id, callback] : taken_callbacks)
  41. callback(id);
  42. }
  43. bool has_callbacks() const
  44. {
  45. return !m_callbacks.is_empty();
  46. }
  47. private:
  48. HashMap<i32, Callback> m_callbacks;
  49. IDAllocator m_id_allocator;
  50. RefPtr<Core::Timer> m_timer;
  51. };
  52. }