#pragma once
#include "Timer.h"
#include <wtf/Vector.h>
namespace WebCore {
class Page;
template<typename T> class EventSender {
WTF_MAKE_NONCOPYABLE(EventSender); WTF_MAKE_FAST_ALLOCATED;
public:
explicit EventSender(const AtomString& eventType);
const AtomString& eventType() const { return m_eventType; }
void dispatchEventSoon(T&);
void cancelEvent(T&);
void dispatchPendingEvents(Page*);
#if ASSERT_ENABLED
bool hasPendingEvents(T& sender) const
{
return m_dispatchSoonList.find(&sender) != notFound || m_dispatchingList.find(&sender) != notFound;
}
#endif
private:
void timerFired() { dispatchPendingEvents(nullptr); }
AtomString m_eventType;
Timer m_timer;
Vector<T*> m_dispatchSoonList;
Vector<T*> m_dispatchingList;
};
template<typename T> EventSender<T>::EventSender(const AtomString& eventType)
: m_eventType(eventType)
, m_timer(*this, &EventSender::timerFired)
{
}
template<typename T> void EventSender<T>::dispatchEventSoon(T& sender)
{
m_dispatchSoonList.append(&sender);
if (!m_timer.isActive())
m_timer.startOneShot(0_s);
}
template<typename T> void EventSender<T>::cancelEvent(T& sender)
{
for (auto& event : m_dispatchSoonList) {
if (event == &sender)
event = nullptr;
}
for (auto& event : m_dispatchingList) {
if (event == &sender)
event = nullptr;
}
}
template<typename T> void EventSender<T>::dispatchPendingEvents(Page* page)
{
if (!m_dispatchingList.isEmpty())
return;
m_timer.stop();
m_dispatchSoonList.checkConsistency();
m_dispatchingList.swap(m_dispatchSoonList);
for (auto& event : m_dispatchingList) {
if (T* sender = event) {
event = nullptr;
if (!page || sender->document().page() == page)
sender->dispatchPendingEvent(this);
else
dispatchEventSoon(*sender);
}
}
m_dispatchingList.clear();
}
}