summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/HTML/AnimationFrameCallbackDriver.h
blob: 397ab1f3e65fadc30f6fff7f4a748158dc2e12a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * Copyright (c) 2022, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Function.h>
#include <AK/IDAllocator.h>
#include <LibCore/Timer.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>

namespace Web::HTML {

struct AnimationFrameCallbackDriver {
    using Callback = Function<void(i32)>;

    AnimationFrameCallbackDriver()
    {
        m_timer = Core::Timer::create_single_shot(16, [] {
            HTML::main_thread_event_loop().schedule();
        });
    }

    i32 add(Callback handler)
    {
        auto id = m_id_allocator.allocate();
        m_callbacks.set(id, move(handler));
        if (!m_timer->is_active())
            m_timer->start();
        return id;
    }

    bool remove(i32 id)
    {
        auto it = m_callbacks.find(id);
        if (it == m_callbacks.end())
            return false;
        m_callbacks.remove(it);
        m_id_allocator.deallocate(id);
        return true;
    }

    void run()
    {
        auto taken_callbacks = move(m_callbacks);
        for (auto& [id, callback] : taken_callbacks)
            callback(id);
    }

    bool has_callbacks() const
    {
        return !m_callbacks.is_empty();
    }

private:
    HashMap<i32, Callback> m_callbacks;
    IDAllocator m_id_allocator;
    RefPtr<Core::Timer> m_timer;
};

}