ProcessThrottler.cpp [plain text]
#include "config.h"
#include "ProcessThrottler.h"
#include "WebProcessProxy.h"
namespace WebKit {
static const unsigned processSuspensionTimeout = 30;
ProcessThrottler::ForegroundActivityToken::ForegroundActivityToken(ProcessThrottler& throttler)
: m_throttler(throttler.weakPtr())
{
throttler.m_foregroundCount++;
throttler.updateAssertion();
}
ProcessThrottler::ForegroundActivityToken::~ForegroundActivityToken()
{
if (ProcessThrottler* throttler = m_throttler.get()) {
throttler->m_foregroundCount--;
throttler->updateAssertion();
}
}
ProcessThrottler::BackgroundActivityToken::BackgroundActivityToken(ProcessThrottler& throttler)
: m_throttler(throttler.weakPtr())
{
throttler.m_backgroundCount++;
throttler.updateAssertion();
}
ProcessThrottler::BackgroundActivityToken::~BackgroundActivityToken()
{
if (ProcessThrottler* throttler = m_throttler.get()) {
throttler->m_backgroundCount--;
throttler->updateAssertion();
}
}
ProcessThrottler::ProcessThrottler(WebProcessProxy* process)
: m_process(process)
, m_weakPtrFactory(this)
, m_suspendTimer(RunLoop::main(), this, &ProcessThrottler::suspendTimerFired)
, m_foregroundCount(0)
, m_backgroundCount(0)
, m_suspendMessageCount(0)
{
}
AssertionState ProcessThrottler::assertionState()
{
ASSERT(!m_suspendTimer.isActive());
if (m_foregroundCount)
return AssertionState::Foreground;
if (m_backgroundCount)
return AssertionState::Background;
return AssertionState::Suspended;
}
void ProcessThrottler::updateAssertionNow()
{
m_suspendTimer.stop();
if (m_assertion)
m_assertion->setState(assertionState());
}
void ProcessThrottler::updateAssertion()
{
if (m_assertion && m_assertion->state() != AssertionState::Suspended && !m_foregroundCount && !m_backgroundCount) {
++m_suspendMessageCount;
m_process->sendProcessWillSuspend();
m_suspendTimer.startOneShot(processSuspensionTimeout);
m_assertion->setState(AssertionState::Background);
return;
}
if (m_suspendTimer.isActive() && (m_foregroundCount || m_backgroundCount))
m_process->sendCancelProcessWillSuspend();
updateAssertionNow();
}
void ProcessThrottler::didConnnectToProcess(pid_t pid)
{
m_suspendTimer.stop();
m_assertion = std::make_unique<ProcessAndUIAssertion>(pid, assertionState());
}
void ProcessThrottler::suspendTimerFired()
{
updateAssertionNow();
}
void ProcessThrottler::processReadyToSuspend()
{
if (!--m_suspendMessageCount)
updateAssertionNow();
ASSERT(m_suspendMessageCount >= 0);
}
void ProcessThrottler::didCancelProcessSuspension()
{
if (!--m_suspendMessageCount)
updateAssertionNow();
ASSERT(m_suspendMessageCount >= 0);
}
}