#pragma once
#include <wtf/HashSet.h>
#include <wtf/Lock.h>
#include <wtf/RefPtr.h>
#include <wtf/RetainPtr.h>
#include <wtf/RunLoop.h>
#include <wtf/SharedTask.h>
#include <wtf/ThreadSafeRefCounted.h>
namespace JSC {
class JSLock;
class VM;
class JSRunLoopTimer : public ThreadSafeRefCounted<JSRunLoopTimer> {
public:
typedef void TimerNotificationType();
using TimerNotificationCallback = RefPtr<WTF::SharedTask<TimerNotificationType>>;
class Manager {
WTF_MAKE_FAST_ALLOCATED;
WTF_MAKE_NONCOPYABLE(Manager);
void timerDidFireCallback();
Manager() = default;
void timerDidFire();
public:
using EpochTime = Seconds;
static Manager& shared();
void registerVM(VM&);
void unregisterVM(VM&);
void scheduleTimer(JSRunLoopTimer&, Seconds nextFireTime);
void cancelTimer(JSRunLoopTimer&);
Optional<Seconds> timeUntilFire(JSRunLoopTimer&);
private:
Lock m_lock;
class PerVMData {
WTF_MAKE_FAST_ALLOCATED;
WTF_MAKE_NONCOPYABLE(PerVMData);
public:
PerVMData(Manager&, WTF::RunLoop&);
~PerVMData();
Ref<WTF::RunLoop> runLoop;
std::unique_ptr<RunLoop::Timer<Manager>> timer;
Vector<std::pair<Ref<JSRunLoopTimer>, EpochTime>> timers;
};
HashMap<Ref<JSLock>, std::unique_ptr<PerVMData>> m_mapping;
};
JSRunLoopTimer(VM&);
JS_EXPORT_PRIVATE virtual ~JSRunLoopTimer();
virtual void doWork(VM&) = 0;
void setTimeUntilFire(Seconds intervalInSeconds);
void cancelTimer();
bool isScheduled() const { return m_isScheduled; }
JS_EXPORT_PRIVATE void addTimerSetNotification(TimerNotificationCallback);
JS_EXPORT_PRIVATE void removeTimerSetNotification(TimerNotificationCallback);
JS_EXPORT_PRIVATE Optional<Seconds> timeUntilFire();
protected:
static constexpr Seconds s_decade { 60 * 60 * 24 * 365 * 10 };
Ref<JSLock> m_apiLock;
private:
friend class Manager;
void timerDidFire();
HashSet<TimerNotificationCallback> m_timerSetCallbacks;
Lock m_timerCallbacksLock;
Lock m_lock;
bool m_isScheduled { false };
};
}