#include "config.h"
#include "ThreadTimers.h"
#include "MainThreadSharedTimer.h"
#include "SharedTimer.h"
#include "ThreadGlobalData.h"
#include "Timer.h"
#include <wtf/CurrentTime.h>
#include <wtf/MainThread.h>
#if PLATFORM(IOS)
#include "WebCoreThread.h"
#endif
namespace WebCore {
static const Seconds maxDurationOfFiringTimers { 50_ms };
ThreadTimers::ThreadTimers()
{
if (isUIThread())
setSharedTimer(&MainThreadSharedTimer::singleton());
}
void ThreadTimers::setSharedTimer(SharedTimer* sharedTimer)
{
if (m_sharedTimer) {
m_sharedTimer->setFiredFunction(nullptr);
m_sharedTimer->stop();
m_pendingSharedTimerFireTime = MonotonicTime { };
}
m_sharedTimer = sharedTimer;
if (sharedTimer) {
m_sharedTimer->setFiredFunction([] { threadGlobalData().threadTimers().sharedTimerFiredInternal(); });
updateSharedTimer();
}
}
void ThreadTimers::updateSharedTimer()
{
if (!m_sharedTimer)
return;
if (m_firingTimers || m_timerHeap.isEmpty()) {
m_pendingSharedTimerFireTime = MonotonicTime { };
m_sharedTimer->stop();
} else {
MonotonicTime nextFireTime = m_timerHeap.first()->m_nextFireTime;
MonotonicTime currentMonotonicTime = MonotonicTime::now();
if (m_pendingSharedTimerFireTime) {
if (m_pendingSharedTimerFireTime <= currentMonotonicTime && nextFireTime <= currentMonotonicTime)
return;
}
m_pendingSharedTimerFireTime = nextFireTime;
m_sharedTimer->setFireInterval(std::max(nextFireTime - currentMonotonicTime, 0_s));
}
}
void ThreadTimers::sharedTimerFiredInternal()
{
ASSERT(isMainThread() || (!isWebThread() && !isUIThread()));
if (m_firingTimers)
return;
m_firingTimers = true;
m_pendingSharedTimerFireTime = MonotonicTime { };
MonotonicTime fireTime = MonotonicTime::now();
MonotonicTime timeToQuit = fireTime + maxDurationOfFiringTimers;
while (!m_timerHeap.isEmpty() && m_timerHeap.first()->m_nextFireTime <= fireTime) {
TimerBase* timer = m_timerHeap.first();
timer->m_nextFireTime = MonotonicTime { };
timer->m_unalignedNextFireTime = MonotonicTime { };
timer->heapDeleteMin();
Seconds interval = timer->repeatInterval();
timer->setNextFireTime(interval ? fireTime + interval : MonotonicTime { });
timer->fired();
if (!m_firingTimers || timeToQuit < MonotonicTime::now())
break;
}
m_firingTimers = false;
updateSharedTimer();
}
void ThreadTimers::fireTimersInNestedEventLoop()
{
m_firingTimers = false;
if (m_sharedTimer) {
m_sharedTimer->invalidate();
m_pendingSharedTimerFireTime = MonotonicTime { };
}
updateSharedTimer();
}
}