HysteresisActivity.h [plain text]
#ifndef HysteresisActivity_h
#define HysteresisActivity_h
#include <wtf/RunLoop.h>
#include <wtf/Seconds.h>
namespace WebCore {
static const Seconds defaultHysteresisDuration { 5_s };
enum class HysteresisState {
Started,
Stopped
};
class HysteresisActivity {
public:
explicit HysteresisActivity(WTF::Function<void(HysteresisState)>&& callback = [](HysteresisState) { }, Seconds hysteresisSeconds = defaultHysteresisDuration)
: m_callback(WTFMove(callback))
, m_hysteresisSeconds(hysteresisSeconds)
, m_active(false)
, m_timer(RunLoop::main(), this, &HysteresisActivity::hysteresisTimerFired)
{
}
void start()
{
if (m_active)
return;
m_active = true;
if (m_timer.isActive())
m_timer.stop();
else
m_callback(HysteresisState::Started);
}
void stop()
{
if (!m_active)
return;
m_active = false;
m_timer.startOneShot(m_hysteresisSeconds);
}
void impulse()
{
if (!m_active) {
start();
stop();
}
}
HysteresisState state() const
{
return m_active || m_timer.isActive() ? HysteresisState::Started : HysteresisState::Stopped;
}
private:
void hysteresisTimerFired()
{
m_timer.stop();
m_callback(HysteresisState::Stopped);
}
WTF::Function<void(HysteresisState)> m_callback;
Seconds m_hysteresisSeconds;
bool m_active;
RunLoop::Timer<HysteresisActivity> m_timer;
};
}
#endif // HysteresisActivity_h