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