AnimationFrameCallbackDriver.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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/HashMap.h>
  9. #include <AK/IDAllocator.h>
  10. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  11. #include <LibWeb/Platform/Timer.h>
  12. namespace Web::HTML {
  13. struct AnimationFrameCallbackDriver {
  14. using Callback = Function<void(i32)>;
  15. AnimationFrameCallbackDriver()
  16. {
  17. m_timer = Platform::Timer::create_single_shot(16, [] {
  18. HTML::main_thread_event_loop().schedule();
  19. });
  20. }
  21. i32 add(Callback handler)
  22. {
  23. auto id = m_id_allocator.allocate();
  24. m_callbacks.set(id, move(handler));
  25. if (!m_timer->is_active())
  26. m_timer->start();
  27. return id;
  28. }
  29. bool remove(i32 id)
  30. {
  31. auto it = m_callbacks.find(id);
  32. if (it == m_callbacks.end())
  33. return false;
  34. m_callbacks.remove(it);
  35. m_id_allocator.deallocate(id);
  36. return true;
  37. }
  38. void run()
  39. {
  40. auto taken_callbacks = move(m_callbacks);
  41. for (auto& [id, callback] : taken_callbacks)
  42. callback(id);
  43. }
  44. bool has_callbacks() const
  45. {
  46. return !m_callbacks.is_empty();
  47. }
  48. private:
  49. HashMap<i32, Callback> m_callbacks;
  50. IDAllocator m_id_allocator;
  51. RefPtr<Platform::Timer> m_timer;
  52. };
  53. }