AnimationFrameCallbackDriver.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2022, the SerenityOS developers.
  3. * Copyright (c) 2024, Andreas Kling <andreas@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Function.h>
  9. #include <AK/HashMap.h>
  10. #include <LibCore/Timer.h>
  11. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  12. #include <LibWeb/WebIDL/Types.h>
  13. namespace Web::HTML {
  14. struct AnimationFrameCallbackDriver {
  15. using Callback = Function<void(double)>;
  16. AnimationFrameCallbackDriver()
  17. {
  18. m_timer = Core::Timer::create_single_shot(16, [] {
  19. HTML::main_thread_event_loop().schedule();
  20. });
  21. }
  22. [[nodiscard]] WebIDL::UnsignedLong add(Callback handler)
  23. {
  24. auto id = ++m_animation_frame_callback_identifier;
  25. m_callbacks.set(id, move(handler));
  26. if (!m_timer->is_active())
  27. m_timer->start();
  28. return id;
  29. }
  30. bool remove(WebIDL::UnsignedLong id)
  31. {
  32. auto it = m_callbacks.find(id);
  33. if (it == m_callbacks.end())
  34. return false;
  35. m_callbacks.remove(it);
  36. return true;
  37. }
  38. void run(double now)
  39. {
  40. auto taken_callbacks = move(m_callbacks);
  41. for (auto& [id, callback] : taken_callbacks)
  42. callback(now);
  43. }
  44. bool has_callbacks() const
  45. {
  46. return !m_callbacks.is_empty();
  47. }
  48. private:
  49. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animation-frame-callback-identifier
  50. WebIDL::UnsignedLong m_animation_frame_callback_identifier { 0 };
  51. OrderedHashMap<WebIDL::UnsignedLong, Callback> m_callbacks;
  52. RefPtr<Core::Timer> m_timer;
  53. };
  54. }