#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 double maxDurationOfFiringTimers = 0.050;
ThreadTimers::ThreadTimers()
: m_sharedTimer(0)
, m_firingTimers(false)
, m_pendingSharedTimerFireTime(0)
{
if (isUIThread())
setSharedTimer(&MainThreadSharedTimer::singleton());
}
void ThreadTimers::setSharedTimer(SharedTimer* sharedTimer)
{
if (m_sharedTimer) {
m_sharedTimer->setFiredFunction(nullptr);
m_sharedTimer->stop();
m_pendingSharedTimerFireTime = 0;
}
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 = 0;
m_sharedTimer->stop();
} else {
double nextFireTime = m_timerHeap.first()->m_nextFireTime;
double currentMonotonicTime = monotonicallyIncreasingTime();
if (m_pendingSharedTimerFireTime) {
if (m_pendingSharedTimerFireTime <= currentMonotonicTime && nextFireTime <= currentMonotonicTime)
return;
}
m_pendingSharedTimerFireTime = nextFireTime;
m_sharedTimer->setFireInterval(Seconds(std::max(nextFireTime - currentMonotonicTime, 0.0)));
}
}
void ThreadTimers::sharedTimerFiredInternal()
{
ASSERT(isMainThread() || (!isWebThread() && !isUIThread()));
if (m_firingTimers)
return;
m_firingTimers = true;
m_pendingSharedTimerFireTime = 0;
double fireTime = monotonicallyIncreasingTime();
double timeToQuit = fireTime + maxDurationOfFiringTimers;
while (!m_timerHeap.isEmpty() && m_timerHeap.first()->m_nextFireTime <= fireTime) {
TimerBase* timer = m_timerHeap.first();
timer->m_nextFireTime = 0;
timer->m_unalignedNextFireTime = 0;
timer->heapDeleteMin();
double interval = timer->repeatInterval();
timer->setNextFireTime(interval ? fireTime + interval : 0);
timer->fired();
if (!m_firingTimers || timeToQuit < monotonicallyIncreasingTime())
break;
}
m_firingTimers = false;
updateSharedTimer();
}
void ThreadTimers::fireTimersInNestedEventLoop()
{
m_firingTimers = false;
if (m_sharedTimer) {
m_sharedTimer->invalidate();
m_pendingSharedTimerFireTime = 0;
}
updateSharedTimer();
}
}