2 * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "AnimationController.h"
32 #include "AnimationBase.h"
33 #include "AnimationControllerPrivate.h"
34 #include "CSSParser.h"
35 #include "CSSPropertyAnimation.h"
36 #include "CompositeAnimation.h"
37 #include "EventNames.h"
39 #include "FrameView.h"
41 #include "PseudoElement.h"
42 #include "RenderView.h"
43 #include "TransitionEvent.h"
44 #include "WebKitAnimationEvent.h"
45 #include "WebKitTransitionEvent.h"
46 #include <wtf/CurrentTime.h>
50 static const double cAnimationTimerDelay = 0.025;
51 static const double cBeginAnimationUpdateTimeNotSet = -1;
53 AnimationControllerPrivate::AnimationControllerPrivate(Frame& frame)
54 : m_animationTimer(this, &AnimationControllerPrivate::animationTimerFired)
55 , m_updateStyleIfNeededDispatcher(this, &AnimationControllerPrivate::updateStyleIfNeededDispatcherFired)
57 , m_beginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet)
58 , m_animationsWaitingForStyle()
59 , m_animationsWaitingForStartTimeResponse()
60 , m_waitingForAsyncStartNotification(false)
61 , m_isSuspended(false)
62 , m_allowsNewAnimationsWhileSuspended(false)
66 AnimationControllerPrivate::~AnimationControllerPrivate()
70 CompositeAnimation& AnimationControllerPrivate::ensureCompositeAnimation(RenderObject* renderer)
72 RenderObjectAnimationMap::AddResult result = m_compositeAnimations.add(renderer, 0);
73 if (result.isNewEntry)
74 result.iterator->value = CompositeAnimation::create(this);
75 return *result.iterator->value;
78 bool AnimationControllerPrivate::clear(RenderObject* renderer)
80 // Return false if we didn't do anything OR we are suspended (so we don't try to
81 // do a setNeedsStyleRecalc() when suspended).
82 RefPtr<CompositeAnimation> animation = m_compositeAnimations.take(renderer);
85 animation->clearRenderer();
86 return animation->isSuspended();
89 double AnimationControllerPrivate::updateAnimations(SetChanged callSetChanged/* = DoNotCallSetChanged*/)
91 double timeToNextService = -1;
92 bool calledSetChanged = false;
94 RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
95 for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
96 CompositeAnimation* compAnim = it->value.get();
97 if (!compAnim->isSuspended() && compAnim->hasAnimations()) {
98 double t = compAnim->timeToNextService();
99 if (t != -1 && (t < timeToNextService || timeToNextService == -1))
100 timeToNextService = t;
101 if (!timeToNextService) {
102 if (callSetChanged == CallSetChanged) {
103 Node* node = it->key->node();
104 ASSERT(!node || !node->document().inPageCache());
105 node->setNeedsStyleRecalc(SyntheticStyleChange);
106 calledSetChanged = true;
114 if (calledSetChanged)
115 m_frame.document()->updateStyleIfNeeded();
117 return timeToNextService;
120 void AnimationControllerPrivate::updateAnimationTimerForRenderer(RenderObject* renderer)
122 double timeToNextService = 0;
124 const CompositeAnimation* compositeAnimation = m_compositeAnimations.get(renderer);
125 if (!compositeAnimation->isSuspended() && compositeAnimation->hasAnimations())
126 timeToNextService = compositeAnimation->timeToNextService();
128 if (m_animationTimer.isActive() && (m_animationTimer.repeatInterval() || m_animationTimer.nextFireInterval() <= timeToNextService))
131 m_animationTimer.startOneShot(timeToNextService);
134 void AnimationControllerPrivate::updateAnimationTimer(SetChanged callSetChanged/* = DoNotCallSetChanged*/)
136 double timeToNextService = updateAnimations(callSetChanged);
138 LOG(Animations, "updateAnimationTimer: timeToNextService is %.2f", timeToNextService);
140 // If we want service immediately, we start a repeating timer to reduce the overhead of starting
141 if (!timeToNextService) {
142 if (!m_animationTimer.isActive() || m_animationTimer.repeatInterval() == 0)
143 m_animationTimer.startRepeating(cAnimationTimerDelay);
147 // If we don't need service, we want to make sure the timer is no longer running
148 if (timeToNextService < 0) {
149 if (m_animationTimer.isActive())
150 m_animationTimer.stop();
154 // Otherwise, we want to start a one-shot timer so we get here again
155 m_animationTimer.startOneShot(timeToNextService);
158 void AnimationControllerPrivate::updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*)
160 fireEventsAndUpdateStyle();
163 void AnimationControllerPrivate::fireEventsAndUpdateStyle()
165 // Protect the frame from getting destroyed in the event handler
166 Ref<Frame> protector(m_frame);
168 bool updateStyle = !m_eventsToDispatch.isEmpty() || !m_nodeChangesToDispatch.isEmpty();
170 // fire all the events
171 Vector<EventToDispatch> eventsToDispatch = m_eventsToDispatch;
172 m_eventsToDispatch.clear();
173 Vector<EventToDispatch>::const_iterator eventsToDispatchEnd = eventsToDispatch.end();
174 for (Vector<EventToDispatch>::const_iterator it = eventsToDispatch.begin(); it != eventsToDispatchEnd; ++it) {
175 Element* element = it->element.get();
176 if (it->eventType == eventNames().transitionendEvent)
177 element->dispatchEvent(TransitionEvent::create(it->eventType, it->name, it->elapsedTime, PseudoElement::pseudoElementNameForEvents(element->pseudoId())));
179 element->dispatchEvent(WebKitAnimationEvent::create(it->eventType, it->name, it->elapsedTime));
182 // call setChanged on all the elements
183 Vector<RefPtr<Node> >::const_iterator nodeChangesToDispatchEnd = m_nodeChangesToDispatch.end();
184 for (Vector<RefPtr<Node> >::const_iterator it = m_nodeChangesToDispatch.begin(); it != nodeChangesToDispatchEnd; ++it)
185 (*it)->setNeedsStyleRecalc(SyntheticStyleChange);
187 m_nodeChangesToDispatch.clear();
190 m_frame.document()->updateStyleIfNeeded();
193 void AnimationControllerPrivate::startUpdateStyleIfNeededDispatcher()
195 if (!m_updateStyleIfNeededDispatcher.isActive())
196 m_updateStyleIfNeededDispatcher.startOneShot(0);
199 void AnimationControllerPrivate::addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime)
201 m_eventsToDispatch.grow(m_eventsToDispatch.size()+1);
202 EventToDispatch& event = m_eventsToDispatch[m_eventsToDispatch.size()-1];
203 event.element = element;
204 event.eventType = eventType;
206 event.elapsedTime = elapsedTime;
208 startUpdateStyleIfNeededDispatcher();
211 void AnimationControllerPrivate::addNodeChangeToDispatch(PassRefPtr<Node> node)
213 ASSERT(!node || !node->document().inPageCache());
217 m_nodeChangesToDispatch.append(node);
218 startUpdateStyleIfNeededDispatcher();
221 #if ENABLE(REQUEST_ANIMATION_FRAME)
222 void AnimationControllerPrivate::animationFrameCallbackFired()
224 double timeToNextService = updateAnimations(CallSetChanged);
226 if (timeToNextService >= 0)
227 m_frame.document()->view()->scheduleAnimation();
231 void AnimationControllerPrivate::animationTimerFired(Timer<AnimationControllerPrivate>*)
233 // Make sure animationUpdateTime is updated, so that it is current even if no
234 // styleChange has happened (e.g. accelerated animations)
235 setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
237 // When the timer fires, all we do is call setChanged on all DOM nodes with running animations and then do an immediate
238 // updateStyleIfNeeded. It will then call back to us with new information.
239 updateAnimationTimer(CallSetChanged);
241 // Fire events right away, to avoid a flash of unanimated style after an animation completes, and before
242 // the 'end' event fires.
243 fireEventsAndUpdateStyle();
246 bool AnimationControllerPrivate::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
248 const CompositeAnimation* animation = m_compositeAnimations.get(renderer);
252 return animation->isAnimatingProperty(property, false, isRunningNow);
255 bool AnimationControllerPrivate::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
257 const CompositeAnimation* animation = m_compositeAnimations.get(renderer);
261 return animation->isAnimatingProperty(property, true, isRunningNow);
264 void AnimationControllerPrivate::suspendAnimations()
269 suspendAnimationsForDocument(m_frame.document());
271 // Traverse subframes
272 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
273 child->animation().suspendAnimations();
275 m_isSuspended = true;
278 void AnimationControllerPrivate::resumeAnimations()
283 resumeAnimationsForDocument(m_frame.document());
285 // Traverse subframes
286 for (Frame* child = m_frame.tree().firstChild(); child; child = child->tree().nextSibling())
287 child->animation().resumeAnimations();
289 m_isSuspended = false;
292 void AnimationControllerPrivate::suspendAnimationsForDocument(Document* document)
294 setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
296 RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
297 for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
298 RenderObject* renderer = it->key;
299 if (&renderer->document() == document) {
300 CompositeAnimation* compAnim = it->value.get();
301 compAnim->suspendAnimations();
305 updateAnimationTimer();
308 void AnimationControllerPrivate::resumeAnimationsForDocument(Document* document)
310 setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
312 RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
313 for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
314 RenderObject* renderer = it->key;
315 if (&renderer->document() == document) {
316 CompositeAnimation* compAnim = it->value.get();
317 compAnim->resumeAnimations();
321 updateAnimationTimer();
324 void AnimationControllerPrivate::startAnimationsIfNotSuspended(Document* document)
326 if (!isSuspended() || allowsNewAnimationsWhileSuspended())
327 resumeAnimationsForDocument(document);
330 void AnimationControllerPrivate::setAllowsNewAnimationsWhileSuspended(bool allowed)
332 m_allowsNewAnimationsWhileSuspended = allowed;
335 bool AnimationControllerPrivate::pauseAnimationAtTime(RenderObject* renderer, const AtomicString& name, double t)
340 CompositeAnimation& compositeAnimation = ensureCompositeAnimation(renderer);
341 if (compositeAnimation.pauseAnimationAtTime(name, t)) {
342 renderer->node()->setNeedsStyleRecalc(SyntheticStyleChange);
343 startUpdateStyleIfNeededDispatcher();
350 bool AnimationControllerPrivate::pauseTransitionAtTime(RenderObject* renderer, const String& property, double t)
355 CompositeAnimation& compositeAnimation = ensureCompositeAnimation(renderer);
356 if (compositeAnimation.pauseTransitionAtTime(cssPropertyID(property), t)) {
357 renderer->node()->setNeedsStyleRecalc(SyntheticStyleChange);
358 startUpdateStyleIfNeededDispatcher();
365 double AnimationControllerPrivate::beginAnimationUpdateTime()
367 if (m_beginAnimationUpdateTime == cBeginAnimationUpdateTimeNotSet)
368 m_beginAnimationUpdateTime = monotonicallyIncreasingTime();
369 return m_beginAnimationUpdateTime;
372 void AnimationControllerPrivate::endAnimationUpdate()
375 if (!m_waitingForAsyncStartNotification)
376 startTimeResponse(beginAnimationUpdateTime());
379 void AnimationControllerPrivate::receivedStartTimeResponse(double time)
381 m_waitingForAsyncStartNotification = false;
382 startTimeResponse(time);
385 PassRefPtr<RenderStyle> AnimationControllerPrivate::getAnimatedStyleForRenderer(RenderObject* renderer)
390 const CompositeAnimation* rendererAnimations = m_compositeAnimations.get(renderer);
391 if (!rendererAnimations)
392 return renderer->style();
394 RefPtr<RenderStyle> animatingStyle = rendererAnimations->getAnimatedStyle();
396 animatingStyle = renderer->style();
398 return animatingStyle.release();
401 unsigned AnimationControllerPrivate::numberOfActiveAnimations(Document* document) const
405 RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
406 for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
407 RenderObject* renderer = it->key;
408 CompositeAnimation* compAnim = it->value.get();
409 if (&renderer->document() == document)
410 count += compAnim->numberOfActiveAnimations();
416 void AnimationControllerPrivate::addToAnimationsWaitingForStyle(AnimationBase* animation)
418 // Make sure this animation is not in the start time waiters
419 m_animationsWaitingForStartTimeResponse.remove(animation);
421 m_animationsWaitingForStyle.add(animation);
424 void AnimationControllerPrivate::removeFromAnimationsWaitingForStyle(AnimationBase* animationToRemove)
426 m_animationsWaitingForStyle.remove(animationToRemove);
429 void AnimationControllerPrivate::styleAvailable()
431 // Go through list of waiters and send them on their way
432 WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStyle.begin();
433 WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStyle.end();
434 for (; it != end; ++it)
435 (*it)->styleAvailable();
437 m_animationsWaitingForStyle.clear();
440 void AnimationControllerPrivate::addToAnimationsWaitingForStartTimeResponse(AnimationBase* animation, bool willGetResponse)
442 // If willGetResponse is true, it means this animation is actually waiting for a response
443 // (which will come in as a call to notifyAnimationStarted()).
444 // In that case we don't need to add it to this list. We just set a waitingForAResponse flag
445 // which says we are waiting for the response. If willGetResponse is false, this animation
446 // is not waiting for a response for itself, but rather for a notifyXXXStarted() call for
447 // another animation to which it will sync.
449 // When endAnimationUpdate() is called we check to see if the waitingForAResponse flag is
450 // true. If so, we just return and will do our work when the first notifyXXXStarted() call
451 // comes in. If it is false, we will not be getting a notifyXXXStarted() call, so we will
452 // do our work right away. In both cases we call the onAnimationStartResponse() method
453 // on each animation. In the first case we send in the time we got from notifyXXXStarted().
454 // In the second case, we just pass in the beginAnimationUpdateTime().
456 // This will synchronize all software and accelerated animations started in the same
457 // updateStyleIfNeeded cycle.
461 m_waitingForAsyncStartNotification = true;
463 m_animationsWaitingForStartTimeResponse.add(animation);
466 void AnimationControllerPrivate::removeFromAnimationsWaitingForStartTimeResponse(AnimationBase* animationToRemove)
468 m_animationsWaitingForStartTimeResponse.remove(animationToRemove);
470 if (m_animationsWaitingForStartTimeResponse.isEmpty())
471 m_waitingForAsyncStartNotification = false;
474 void AnimationControllerPrivate::startTimeResponse(double time)
476 // Go through list of waiters and send them on their way
478 WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStartTimeResponse.begin();
479 WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStartTimeResponse.end();
480 for (; it != end; ++it)
481 (*it)->onAnimationStartResponse(time);
483 m_animationsWaitingForStartTimeResponse.clear();
484 m_waitingForAsyncStartNotification = false;
487 void AnimationControllerPrivate::animationWillBeRemoved(AnimationBase* animation)
489 removeFromAnimationsWaitingForStyle(animation);
490 removeFromAnimationsWaitingForStartTimeResponse(animation);
493 AnimationController::AnimationController(Frame& frame)
494 : m_data(createOwned<AnimationControllerPrivate>(frame))
495 , m_beginAnimationUpdateCount(0)
499 AnimationController::~AnimationController()
503 void AnimationController::cancelAnimations(RenderObject* renderer)
505 if (!m_data->hasAnimations())
508 if (m_data->clear(renderer)) {
509 Node* node = renderer->node();
510 ASSERT(!node || !node->document().inPageCache());
512 node->setNeedsStyleRecalc(SyntheticStyleChange);
516 PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject* renderer, RenderStyle* newStyle)
518 // Don't do anything if we're in the cache
519 if (renderer->document().inPageCache())
522 RenderStyle* oldStyle = renderer->style();
524 if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle->animations() && !newStyle->transitions()))
527 // Don't run transitions when printing.
528 if (renderer->view().printing())
531 // Fetch our current set of implicit animations from a hashtable. We then compare them
532 // against the animations in the style and make sure we're in sync. If destination values
533 // have changed, we reset the animation. We then do a blend to get new values and we return
536 // We don't support anonymous pseudo elements like :first-line or :first-letter.
537 ASSERT(renderer->node());
539 CompositeAnimation& rendererAnimations = m_data->ensureCompositeAnimation(renderer);
540 RefPtr<RenderStyle> blendedStyle = rendererAnimations.animate(renderer, oldStyle, newStyle);
542 if (renderer->parent() || newStyle->animations() || (oldStyle && oldStyle->animations())) {
543 m_data->updateAnimationTimerForRenderer(renderer);
544 #if ENABLE(REQUEST_ANIMATION_FRAME)
545 renderer->view().frameView().scheduleAnimation();
549 if (blendedStyle != newStyle) {
550 // If the animations/transitions change opacity or transform, we need to update
551 // the style to impose the stacking rules. Note that this is also
552 // done in StyleResolver::adjustRenderStyle().
553 if (blendedStyle->hasAutoZIndex() && (blendedStyle->opacity() < 1.0f || blendedStyle->hasTransform()))
554 blendedStyle->setZIndex(0);
556 return blendedStyle.release();
559 PassRefPtr<RenderStyle> AnimationController::getAnimatedStyleForRenderer(RenderObject* renderer)
561 return m_data->getAnimatedStyleForRenderer(renderer);
564 void AnimationController::notifyAnimationStarted(RenderObject*, double startTime)
566 m_data->receivedStartTimeResponse(startTime);
569 bool AnimationController::pauseAnimationAtTime(RenderObject* renderer, const AtomicString& name, double t)
571 return m_data->pauseAnimationAtTime(renderer, name, t);
574 unsigned AnimationController::numberOfActiveAnimations(Document* document) const
576 return m_data->numberOfActiveAnimations(document);
579 bool AnimationController::pauseTransitionAtTime(RenderObject* renderer, const String& property, double t)
581 return m_data->pauseTransitionAtTime(renderer, property, t);
584 bool AnimationController::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
586 return m_data->isRunningAnimationOnRenderer(renderer, property, isRunningNow);
589 bool AnimationController::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
591 return m_data->isRunningAcceleratedAnimationOnRenderer(renderer, property, isRunningNow);
594 bool AnimationController::isSuspended() const
596 return m_data->isSuspended();
599 void AnimationController::suspendAnimations()
601 LOG(Animations, "controller is suspending animations");
602 m_data->suspendAnimations();
605 void AnimationController::resumeAnimations()
607 LOG(Animations, "controller is resuming animations");
608 m_data->resumeAnimations();
611 bool AnimationController::allowsNewAnimationsWhileSuspended() const
613 return m_data->allowsNewAnimationsWhileSuspended();
616 void AnimationController::setAllowsNewAnimationsWhileSuspended(bool allowed)
618 m_data->setAllowsNewAnimationsWhileSuspended(allowed);
621 #if ENABLE(REQUEST_ANIMATION_FRAME)
622 void AnimationController::serviceAnimations()
624 m_data->animationFrameCallbackFired();
628 void AnimationController::suspendAnimationsForDocument(Document* document)
630 LOG(Animations, "suspending animations for document %p", document);
631 m_data->suspendAnimationsForDocument(document);
634 void AnimationController::resumeAnimationsForDocument(Document* document)
636 LOG(Animations, "resuming animations for document %p", document);
637 m_data->resumeAnimationsForDocument(document);
640 void AnimationController::startAnimationsIfNotSuspended(Document* document)
642 LOG(Animations, "animations may start for document %p", document);
643 m_data->startAnimationsIfNotSuspended(document);
646 void AnimationController::beginAnimationUpdate()
648 if (!m_beginAnimationUpdateCount)
649 m_data->setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
650 ++m_beginAnimationUpdateCount;
653 void AnimationController::endAnimationUpdate()
655 ASSERT(m_beginAnimationUpdateCount > 0);
656 --m_beginAnimationUpdateCount;
657 if (!m_beginAnimationUpdateCount)
658 m_data->endAnimationUpdate();
661 bool AnimationController::supportsAcceleratedAnimationOfProperty(CSSPropertyID property)
663 #if USE(ACCELERATED_COMPOSITING)
664 return CSSPropertyAnimation::animationOfPropertyIsAccelerated(property);
666 UNUSED_PARAM(property);
671 } // namespace WebCore