#ifndef EventSender_h
#define EventSender_h
#include "Timer.h"
#include <wtf/Vector.h>
namespace WebCore {
template<typename T> class EventSender {
WTF_MAKE_NONCOPYABLE(EventSender); WTF_MAKE_FAST_ALLOCATED;
public:
explicit EventSender(const AtomicString& eventType);
const AtomicString& eventType() const { return m_eventType; }
void dispatchEventSoon(T&);
void cancelEvent(T&);
void dispatchPendingEvents();
#ifndef NDEBUG
bool hasPendingEvents(T& sender) const
{
return m_dispatchSoonList.find(&sender) != notFound || m_dispatchingList.find(&sender) != notFound;
}
#endif
private:
void timerFired() { dispatchPendingEvents(); }
AtomicString m_eventType;
Timer m_timer;
Vector<T*> m_dispatchSoonList;
Vector<T*> m_dispatchingList;
};
template<typename T> EventSender<T>::EventSender(const AtomicString& 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);
}
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()
{
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;
sender->dispatchPendingEvent(this);
}
}
m_dispatchingList.clear();
}
}
#endif // EventSender_h