#include "config.h"
#include "DOMTimer.h"
#include "HTMLPlugInElement.h"
#include "InspectorInstrumentation.h"
#include "Logging.h"
#include "Page.h"
#include "PluginViewBase.h"
#include "ScheduledAction.h"
#include "ScriptExecutionContext.h"
#include "Settings.h"
#include "UserGestureIndicator.h"
#include <wtf/CurrentTime.h>
#include <wtf/HashMap.h>
#include <wtf/MathExtras.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#if PLATFORM(IOS)
#include "Chrome.h"
#include "ChromeClient.h"
#include "Frame.h"
#include "WKContentObservation.h"
#endif
namespace WebCore {
static const int maxIntervalForUserGestureForwarding = 1000; static const int minIntervalForNonUserObservableChangeTimers = 1000; static const int maxTimerNestingLevel = 5;
static const double oneMillisecond = 0.001;
class DOMTimerFireState {
public:
explicit DOMTimerFireState(ScriptExecutionContext& context)
: m_context(context)
, m_contextIsDocument(is<Document>(m_context))
{
if (m_contextIsDocument) {
m_initialDOMTreeVersion = downcast<Document>(context).domTreeVersion();
m_previous = current;
current = this;
}
}
~DOMTimerFireState()
{
if (m_contextIsDocument)
current = m_previous;
}
Document* contextDocument() const { return m_contextIsDocument ? &downcast<Document>(m_context) : nullptr; }
void setScriptMadeUserObservableChanges() { m_scriptMadeUserObservableChanges = true; }
void setScriptMadeNonUserObservableChanges() { m_scriptMadeNonUserObservableChanges = true; }
bool scriptMadeNonUserObservableChanges() const { return m_scriptMadeNonUserObservableChanges; }
bool scriptMadeUserObservableChanges() const
{
if (m_scriptMadeUserObservableChanges)
return true;
Document* document = contextDocument();
return document && document->domTreeVersion() != m_initialDOMTreeVersion;
}
static DOMTimerFireState* current;
private:
ScriptExecutionContext& m_context;
uint64_t m_initialDOMTreeVersion;
DOMTimerFireState* m_previous;
bool m_contextIsDocument;
bool m_scriptMadeNonUserObservableChanges { false };
bool m_scriptMadeUserObservableChanges { false };
};
DOMTimerFireState* DOMTimerFireState::current = nullptr;
struct NestedTimersMap {
typedef HashMap<int, DOMTimer*>::const_iterator const_iterator;
static NestedTimersMap* instanceForContext(ScriptExecutionContext& context)
{
if (is<Document>(context))
return &instance();
return nullptr;
}
void startTracking()
{
nestedTimers.clear();
isTrackingNestedTimers = true;
}
void stopTracking()
{
isTrackingNestedTimers = false;
nestedTimers.clear();
}
void add(int timeoutId, DOMTimer* timer)
{
if (isTrackingNestedTimers)
nestedTimers.add(timeoutId, timer);
}
void remove(int timeoutId)
{
if (isTrackingNestedTimers)
nestedTimers.remove(timeoutId);
}
const_iterator begin() const { return nestedTimers.begin(); }
const_iterator end() const { return nestedTimers.end(); }
private:
static NestedTimersMap& instance()
{
static NeverDestroyed<NestedTimersMap> map;
return map;
}
static bool isTrackingNestedTimers;
HashMap<int , DOMTimer*> nestedTimers;
};
bool NestedTimersMap::isTrackingNestedTimers = false;
static inline bool shouldForwardUserGesture(int interval, int nestingLevel)
{
return UserGestureIndicator::processingUserGesture()
&& interval <= maxIntervalForUserGestureForwarding
&& !nestingLevel; }
DOMTimer::DOMTimer(ScriptExecutionContext& context, std::unique_ptr<ScheduledAction> action, int interval, bool singleShot)
: SuspendableTimer(context)
, m_nestingLevel(context.timerNestingLevel())
, m_action(WTF::move(action))
, m_originalInterval(interval)
, m_throttleState(Undetermined)
, m_currentTimerInterval(intervalClampedToMinimum())
, m_shouldForwardUserGesture(shouldForwardUserGesture(interval, m_nestingLevel))
{
RefPtr<DOMTimer> reference = adoptRef(this);
do {
m_timeoutId = context.circularSequentialID();
} while (!context.addTimeout(m_timeoutId, reference));
if (singleShot)
startOneShot(m_currentTimerInterval);
else
startRepeating(m_currentTimerInterval);
}
DOMTimer::~DOMTimer()
{
}
int DOMTimer::install(ScriptExecutionContext& context, std::unique_ptr<ScheduledAction> action, int timeout, bool singleShot)
{
DOMTimer* timer = new DOMTimer(context, WTF::move(action), timeout, singleShot);
#if PLATFORM(IOS)
if (is<Document>(context)) {
Document& document = downcast<Document>(context);
bool didDeferTimeout = document.frame() && document.frame()->timersPaused();
if (!didDeferTimeout && timeout <= 100 && singleShot) {
WKSetObservedContentChange(WKContentIndeterminateChange);
WebThreadAddObservedContentModifier(timer); }
}
#endif
timer->suspendIfNeeded();
InspectorInstrumentation::didInstallTimer(&context, timer->m_timeoutId, timeout, singleShot);
if (NestedTimersMap* nestedTimers = NestedTimersMap::instanceForContext(context))
nestedTimers->add(timer->m_timeoutId, timer);
return timer->m_timeoutId;
}
void DOMTimer::removeById(ScriptExecutionContext& context, int timeoutId)
{
if (timeoutId <= 0)
return;
if (NestedTimersMap* nestedTimers = NestedTimersMap::instanceForContext(context))
nestedTimers->remove(timeoutId);
InspectorInstrumentation::didRemoveTimer(&context, timeoutId);
context.removeTimeout(timeoutId);
}
inline bool DOMTimer::isDOMTimersThrottlingEnabled(Document& document) const
{
auto* page = document.page();
if (!page)
return true;
return page->settings().domTimersThrottlingEnabled();
}
void DOMTimer::updateThrottlingStateIfNecessary(const DOMTimerFireState& fireState)
{
Document* contextDocument = fireState.contextDocument();
if (!contextDocument)
return;
if (UNLIKELY(!isDOMTimersThrottlingEnabled(*contextDocument))) {
if (m_throttleState == ShouldThrottle) {
LOG(DOMTimers, "%p - Unthrottling DOM timer because throttling was disabled via settings.", this);
m_throttleState = ShouldNotThrottle;
updateTimerIntervalIfNecessary();
}
return;
}
if (fireState.scriptMadeUserObservableChanges()) {
if (m_throttleState != ShouldNotThrottle) {
m_throttleState = ShouldNotThrottle;
updateTimerIntervalIfNecessary();
}
} else if (fireState.scriptMadeNonUserObservableChanges()) {
if (m_throttleState != ShouldThrottle) {
m_throttleState = ShouldThrottle;
updateTimerIntervalIfNecessary();
}
}
}
void DOMTimer::scriptDidInteractWithPlugin(HTMLPlugInElement& pluginElement)
{
if (!DOMTimerFireState::current)
return;
if (pluginElement.isUserObservable())
DOMTimerFireState::current->setScriptMadeUserObservableChanges();
else
DOMTimerFireState::current->setScriptMadeNonUserObservableChanges();
}
void DOMTimer::fired()
{
RefPtr<DOMTimer> reference = this;
ASSERT(scriptExecutionContext());
ScriptExecutionContext& context = *scriptExecutionContext();
DOMTimerFireState fireState(context);
#if PLATFORM(IOS)
Document* document = nullptr;
if (is<Document>(context)) {
document = &downcast<Document>(context);
ASSERT(!document->frame()->timersPaused());
}
#endif
context.setTimerNestingLevel(std::min(m_nestingLevel + 1, maxTimerNestingLevel));
ASSERT(!isSuspended());
ASSERT(!context.activeDOMObjectsAreSuspended());
UserGestureIndicator gestureIndicator(m_shouldForwardUserGesture ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
m_shouldForwardUserGesture = false;
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireTimer(&context, m_timeoutId);
if (isActive()) {
if (m_nestingLevel < maxTimerNestingLevel) {
m_nestingLevel++;
updateTimerIntervalIfNecessary();
}
m_action->execute(context);
InspectorInstrumentation::didFireTimer(cookie);
updateThrottlingStateIfNecessary(fireState);
return;
}
context.removeTimeout(m_timeoutId);
#if PLATFORM(IOS)
bool shouldReportLackOfChanges;
bool shouldBeginObservingChanges;
if (document) {
shouldReportLackOfChanges = WebThreadCountOfObservedContentModifiers() == 1;
shouldBeginObservingChanges = WebThreadContainsObservedContentModifier(this);
} else {
shouldReportLackOfChanges = false;
shouldBeginObservingChanges = false;
}
if (shouldBeginObservingChanges) {
WKBeginObservingContentChanges(false);
WebThreadRemoveObservedContentModifier(this);
}
#endif
NestedTimersMap* nestedTimers = NestedTimersMap::instanceForContext(context);
if (nestedTimers)
nestedTimers->startTracking();
m_action->execute(context);
#if PLATFORM(IOS)
if (shouldBeginObservingChanges) {
WKStopObservingContentChanges();
if (WKObservedContentChange() == WKContentVisibilityChange || shouldReportLackOfChanges)
if (document && document->page())
document->page()->chrome().client().observedContentChange(document->frame());
}
#endif
InspectorInstrumentation::didFireTimer(cookie);
if (nestedTimers) {
for (auto& keyValue : *nestedTimers) {
auto* timer = keyValue.value;
if (timer->isActive() && !timer->repeatInterval())
timer->updateThrottlingStateIfNecessary(fireState);
}
nestedTimers->stopTracking();
}
context.setTimerNestingLevel(0);
}
void DOMTimer::didStop()
{
m_action = nullptr;
}
void DOMTimer::updateTimerIntervalIfNecessary()
{
ASSERT(m_nestingLevel <= maxTimerNestingLevel);
double previousInterval = m_currentTimerInterval;
m_currentTimerInterval = intervalClampedToMinimum();
if (WTF::areEssentiallyEqual(previousInterval, m_currentTimerInterval, oneMillisecond))
return;
if (repeatInterval()) {
ASSERT(WTF::areEssentiallyEqual(repeatInterval(), previousInterval, oneMillisecond));
LOG(DOMTimers, "%p - Updating DOMTimer's repeat interval from %g ms to %g ms due to throttling.", this, previousInterval * 1000., m_currentTimerInterval * 1000.);
augmentRepeatInterval(m_currentTimerInterval - previousInterval);
} else {
LOG(DOMTimers, "%p - Updating DOMTimer's fire interval from %g ms to %g ms due to throttling.", this, previousInterval * 1000., m_currentTimerInterval * 1000.);
augmentFireInterval(m_currentTimerInterval - previousInterval);
}
}
double DOMTimer::intervalClampedToMinimum() const
{
ASSERT(scriptExecutionContext());
ASSERT(m_nestingLevel <= maxTimerNestingLevel);
double intervalInSeconds = std::max(oneMillisecond, m_originalInterval * oneMillisecond);
if (m_nestingLevel < maxTimerNestingLevel)
return intervalInSeconds;
intervalInSeconds = std::max(intervalInSeconds, scriptExecutionContext()->minimumTimerInterval());
if (m_throttleState == ShouldThrottle)
intervalInSeconds = std::max(intervalInSeconds, minIntervalForNonUserObservableChangeTimers * oneMillisecond);
return intervalInSeconds;
}
double DOMTimer::alignedFireTime(double fireTime) const
{
if (double alignmentInterval = scriptExecutionContext()->timerAlignmentInterval(m_nestingLevel >= maxTimerNestingLevel))
return ceil(fireTime / alignmentInterval) * alignmentInterval;
return fireTime;
}
const char* DOMTimer::activeDOMObjectName() const
{
return "DOMTimer";
}
}