MainThreadSharedTimerCF.cpp [plain text]
#import "config.h"
#import "MainThreadSharedTimer.h"
#include <wtf/AutodrainedPool.h>
#if PLATFORM(MAC)
#import "PowerObserverMac.h"
#elif PLATFORM(IOS)
#import "WebCoreThread.h"
#import "WebCoreThreadRun.h"
#endif
namespace WebCore {
static CFRunLoopTimerRef sharedTimer;
static void timerFired(CFRunLoopTimerRef, void*);
static void restartSharedTimer();
static const CFTimeInterval kCFTimeIntervalDistantFuture = std::numeric_limits<CFTimeInterval>::max();
#if PLATFORM(IOS)
static void applicationDidBecomeActive(CFNotificationCenterRef, void*, CFStringRef, const void*, CFDictionaryRef)
{
WebThreadRun(^{
restartSharedTimer();
});
}
#endif
static void setupPowerObserver()
{
#if PLATFORM(MAC)
static PowerObserver* powerObserver;
if (!powerObserver)
powerObserver = std::make_unique<PowerObserver>(restartSharedTimer).release();
#elif PLATFORM(IOS)
static bool registeredForApplicationNotification = false;
if (!registeredForApplicationNotification) {
registeredForApplicationNotification = true;
CFNotificationCenterRef notificationCenter = CFNotificationCenterGetLocalCenter();
CFNotificationCenterAddObserver(notificationCenter, nullptr, applicationDidBecomeActive, CFSTR("UIApplicationDidBecomeActiveNotification"), nullptr, CFNotificationSuspensionBehaviorCoalesce);
}
#endif
}
static void timerFired(CFRunLoopTimerRef, void*)
{
AutodrainedPool pool;
MainThreadSharedTimer::singleton().fired();
}
static void restartSharedTimer()
{
if (!sharedTimer)
return;
MainThreadSharedTimer::singleton().stop();
timerFired(0, 0);
}
void MainThreadSharedTimer::invalidate()
{
if (!sharedTimer)
return;
CFRunLoopTimerInvalidate(sharedTimer);
CFRelease(sharedTimer);
sharedTimer = nullptr;
}
void MainThreadSharedTimer::setFireInterval(double interval)
{
ASSERT(m_firedFunction);
CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent() + interval;
if (!sharedTimer) {
sharedTimer = CFRunLoopTimerCreate(nullptr, fireDate, kCFTimeIntervalDistantFuture, 0, 0, timerFired, nullptr);
#if PLATFORM(IOS)
CFRunLoopAddTimer(WebThreadRunLoop(), sharedTimer, kCFRunLoopCommonModes);
#else
CFRunLoopAddTimer(CFRunLoopGetCurrent(), sharedTimer, kCFRunLoopCommonModes);
#endif
setupPowerObserver();
return;
}
CFRunLoopTimerSetNextFireDate(sharedTimer, fireDate);
}
void MainThreadSharedTimer::stop()
{
if (!sharedTimer)
return;
CFRunLoopTimerSetNextFireDate(sharedTimer, kCFTimeIntervalDistantFuture);
}
}