Home | History | Annotate | Download | only in page
      1 /*
      2  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
      3  *
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions
      6  * are met:
      7  * 1. Redistributions of source code must retain the above copyright
      8  *    notice, this list of conditions and the following disclaimer.
      9  * 2. Redistributions in binary form must reproduce the above copyright
     10  *    notice, this list of conditions and the following disclaimer in the
     11  *    documentation and/or other materials provided with the distribution.
     12  *
     13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
     14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
     17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     24  *
     25  */
     26 
     27 #include "config.h"
     28 #include "core/page/DOMTimer.h"
     29 
     30 #include "bindings/v8/ScheduledAction.h"
     31 #include "core/dom/ScriptExecutionContext.h"
     32 #include "core/inspector/InspectorInstrumentation.h"
     33 #include "wtf/CurrentTime.h"
     34 
     35 using namespace std;
     36 
     37 namespace WebCore {
     38 
     39 static const int maxIntervalForUserGestureForwarding = 1000; // One second matches Gecko.
     40 static const int maxTimerNestingLevel = 5;
     41 static const double oneMillisecond = 0.001;
     42 // Chromium uses a minimum timer interval of 4ms. We'd like to go
     43 // lower; however, there are poorly coded websites out there which do
     44 // create CPU-spinning loops.  Using 4ms prevents the CPU from
     45 // spinning too busily and provides a balance between CPU spinning and
     46 // the smallest possible interval timer.
     47 static const double minimumInterval = 0.004;
     48 
     49 static int timerNestingLevel = 0;
     50 
     51 static inline bool shouldForwardUserGesture(int interval, int nestingLevel)
     52 {
     53     return UserGestureIndicator::processingUserGesture()
     54         && interval <= maxIntervalForUserGestureForwarding
     55         && nestingLevel == 1; // Gestures should not be forwarded to nested timers.
     56 }
     57 
     58 double DOMTimer::hiddenPageAlignmentInterval()
     59 {
     60     // Timers on hidden pages are aligned so that they fire once per
     61     // second at most.
     62     return 1.0;
     63 }
     64 
     65 double DOMTimer::visiblePageAlignmentInterval()
     66 {
     67     // Alignment does not apply to timers on visible pages.
     68     return 0;
     69 }
     70 
     71 int DOMTimer::install(ScriptExecutionContext* context, PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot)
     72 {
     73     int timeoutID = context->installNewTimeout(action, timeout, singleShot);
     74     InspectorInstrumentation::didInstallTimer(context, timeoutID, timeout, singleShot);
     75     return timeoutID;
     76 }
     77 
     78 void DOMTimer::removeByID(ScriptExecutionContext* context, int timeoutID)
     79 {
     80     context->removeTimeoutByID(timeoutID);
     81     InspectorInstrumentation::didRemoveTimer(context, timeoutID);
     82 }
     83 
     84 DOMTimer::DOMTimer(ScriptExecutionContext* context, PassOwnPtr<ScheduledAction> action, int interval, bool singleShot, int timeoutID)
     85     : SuspendableTimer(context)
     86     , m_timeoutID(timeoutID)
     87     , m_nestingLevel(timerNestingLevel + 1)
     88     , m_action(action)
     89 {
     90     ASSERT(timeoutID > 0);
     91     if (shouldForwardUserGesture(interval, m_nestingLevel))
     92         m_userGestureToken = UserGestureIndicator::currentToken();
     93 
     94     double intervalMilliseconds = max(oneMillisecond, interval * oneMillisecond);
     95     if (intervalMilliseconds < minimumInterval && m_nestingLevel >= maxTimerNestingLevel)
     96         intervalMilliseconds = minimumInterval;
     97     if (singleShot)
     98         startOneShot(intervalMilliseconds);
     99     else
    100         startRepeating(intervalMilliseconds);
    101 }
    102 
    103 DOMTimer::~DOMTimer()
    104 {
    105 }
    106 
    107 int DOMTimer::timeoutID() const
    108 {
    109     return m_timeoutID;
    110 }
    111 
    112 void DOMTimer::fired()
    113 {
    114     ScriptExecutionContext* context = scriptExecutionContext();
    115     timerNestingLevel = m_nestingLevel;
    116     ASSERT(!context->activeDOMObjectsAreSuspended());
    117     // Only the first execution of a multi-shot timer should get an affirmative user gesture indicator.
    118     UserGestureIndicator gestureIndicator(m_userGestureToken.release());
    119 
    120     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireTimer(context, m_timeoutID);
    121 
    122     // Simple case for non-one-shot timers.
    123     if (isActive()) {
    124         if (repeatInterval() && repeatInterval() < minimumInterval) {
    125             m_nestingLevel++;
    126             if (m_nestingLevel >= maxTimerNestingLevel)
    127                 augmentRepeatInterval(minimumInterval - repeatInterval());
    128         }
    129 
    130         // No access to member variables after this point, it can delete the timer.
    131         m_action->execute(context);
    132 
    133         InspectorInstrumentation::didFireTimer(cookie);
    134 
    135         return;
    136     }
    137 
    138     // Delete timer before executing the action for one-shot timers.
    139     OwnPtr<ScheduledAction> action = m_action.release();
    140 
    141     // This timer is being deleted; no access to member variables allowed after this point.
    142     context->removeTimeoutByID(m_timeoutID);
    143 
    144     action->execute(context);
    145 
    146     InspectorInstrumentation::didFireTimer(cookie);
    147 
    148     timerNestingLevel = 0;
    149 }
    150 
    151 void DOMTimer::contextDestroyed()
    152 {
    153     SuspendableTimer::contextDestroyed();
    154 }
    155 
    156 void DOMTimer::stop()
    157 {
    158     SuspendableTimer::stop();
    159     // Need to release JS objects potentially protected by ScheduledAction
    160     // because they can form circular references back to the ScriptExecutionContext
    161     // which will cause a memory leak.
    162     m_action.clear();
    163 }
    164 
    165 double DOMTimer::alignedFireTime(double fireTime) const
    166 {
    167     double alignmentInterval = scriptExecutionContext()->timerAlignmentInterval();
    168     if (alignmentInterval) {
    169         double currentTime = monotonicallyIncreasingTime();
    170         if (fireTime <= currentTime)
    171             return fireTime;
    172 
    173         // When a repeating timer is scheduled for exactly the
    174         // background page alignment interval, because it's impossible
    175         // for the timer to be rescheduled instantaneously, it misses
    176         // every other fire time. Avoid this by looking at the next
    177         // fire time rounded both down and up.
    178 
    179         double alignedTimeRoundedDown = floor(fireTime / alignmentInterval) * alignmentInterval;
    180         double alignedTimeRoundedUp = ceil(fireTime / alignmentInterval) * alignmentInterval;
    181 
    182         // If the version rounded down is in the past, discard it
    183         // immediately.
    184 
    185         if (alignedTimeRoundedDown <= currentTime)
    186             return alignedTimeRoundedUp;
    187 
    188         // Only use the rounded-down time if it's within a certain
    189         // tolerance of the fire time. This avoids speeding up timers
    190         // on background pages in the common case.
    191 
    192         if (fireTime - alignedTimeRoundedDown < minimumInterval)
    193             return alignedTimeRoundedDown;
    194 
    195         return alignedTimeRoundedUp;
    196     }
    197 
    198     return fireTime;
    199 }
    200 
    201 } // namespace WebCore
    202