2 * Copyright (C) 2008 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
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.
13 * THIS SOFTWARE IS PROVIDED BY APPLE 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 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.
27 #include "SMILTimeContainer.h"
30 #include "CSSComputedStyleDeclaration.h"
31 #include "CSSParser.h"
33 #include "SVGAnimationElement.h"
35 #include "SVGSMILElement.h"
36 #include "SVGSVGElement.h"
37 #include <wtf/CurrentTime.h>
43 static const double animationFrameDelay = 0.025;
45 SMILTimeContainer::SMILTimeContainer(SVGSVGElement* owner)
48 , m_accumulatedPauseTime(0)
49 , m_documentOrderIndexesDirty(false)
50 , m_timer(this, &SMILTimeContainer::timerFired)
51 , m_ownerSVGElement(owner)
55 #if !ENABLE(SVG_ANIMATION)
56 void SMILTimeContainer::begin() {}
57 void SMILTimeContainer::pause() {}
58 void SMILTimeContainer::resume() {}
59 SMILTime SMILTimeContainer::elapsed() const { return 0; }
60 bool SMILTimeContainer::isPaused() const { return false; }
61 void SMILTimeContainer::timerFired(Timer<SMILTimeContainer>*) {}
64 void SMILTimeContainer::schedule(SVGSMILElement* animation)
66 ASSERT(animation->timeContainer() == this);
67 SMILTime nextFireTime = animation->nextProgressTime();
68 if (!nextFireTime.isFinite())
70 m_scheduledAnimations.add(animation);
74 void SMILTimeContainer::unschedule(SVGSMILElement* animation)
76 ASSERT(animation->timeContainer() == this);
78 m_scheduledAnimations.remove(animation);
81 SMILTime SMILTimeContainer::elapsed() const
85 return currentTime() - m_beginTime - m_accumulatedPauseTime;
88 bool SMILTimeContainer::isActive() const
90 return m_beginTime && !isPaused();
93 bool SMILTimeContainer::isPaused() const
98 void SMILTimeContainer::begin()
100 ASSERT(!m_beginTime);
101 m_beginTime = currentTime();
105 void SMILTimeContainer::pause()
110 m_pauseTime = currentTime();
114 void SMILTimeContainer::resume()
119 m_accumulatedPauseTime += currentTime() - m_pauseTime;
124 void SMILTimeContainer::startTimer(SMILTime fireTime, SMILTime minimumDelay)
126 if (!m_beginTime || isPaused())
129 if (!fireTime.isFinite())
132 SMILTime delay = max(fireTime - elapsed(), minimumDelay);
133 m_timer.startOneShot(delay.value());
136 void SMILTimeContainer::timerFired(Timer<SMILTimeContainer>*)
139 ASSERT(!m_pauseTime);
140 SMILTime elapsed = this->elapsed();
141 updateAnimations(elapsed);
144 void SMILTimeContainer::updateDocumentOrderIndexes()
146 unsigned timingElementCount = 0;
147 for (Node* node = m_ownerSVGElement; node; node = node->traverseNextNode(m_ownerSVGElement)) {
148 if (SVGSMILElement::isSMILElement(node))
149 static_cast<SVGSMILElement*>(node)->setDocumentOrderIndex(timingElementCount++);
151 m_documentOrderIndexesDirty = false;
154 struct PriorityCompare {
155 PriorityCompare(SMILTime elapsed) : m_elapsed(elapsed) {}
156 bool operator()(SVGSMILElement* a, SVGSMILElement* b)
158 // FIXME: This should also consider possible timing relations between the elements.
159 SMILTime aBegin = a->intervalBegin();
160 SMILTime bBegin = b->intervalBegin();
161 // Frozen elements need to be prioritized based on their previous interval.
162 aBegin = a->isFrozen() && m_elapsed < aBegin ? a->previousIntervalBegin() : aBegin;
163 bBegin = b->isFrozen() && m_elapsed < bBegin ? b->previousIntervalBegin() : bBegin;
164 if (aBegin == bBegin)
165 return a->documentOrderIndex() < b->documentOrderIndex();
166 return aBegin < bBegin;
171 void SMILTimeContainer::sortByPriority(Vector<SVGSMILElement*>& smilElements, SMILTime elapsed)
173 if (m_documentOrderIndexesDirty)
174 updateDocumentOrderIndexes();
175 std::sort(smilElements.begin(), smilElements.end(), PriorityCompare(elapsed));
178 static bool applyOrderSortFunction(SVGSMILElement* a, SVGSMILElement* b)
180 if (!a->hasTagName(SVGNames::animateTransformTag) && b->hasTagName(SVGNames::animateTransformTag))
185 static void sortByApplyOrder(Vector<SVGSMILElement*>& smilElements)
187 std::sort(smilElements.begin(), smilElements.end(), applyOrderSortFunction);
190 String SMILTimeContainer::baseValueFor(ElementAttributePair key)
192 // FIXME: We wouldn't need to do this if we were keeping base values around properly in DOM.
193 // Currently animation overwrites them so we need to save them somewhere.
194 BaseValueMap::iterator it = m_savedBaseValues.find(key);
195 if (it != m_savedBaseValues.end())
198 SVGElement* targetElement = key.first;
199 QualifiedName attributeName = key.second;
200 ASSERT(targetElement);
201 ASSERT(attributeName != anyQName());
203 if (SVGAnimationElement::isTargetAttributeCSSProperty(targetElement, attributeName))
204 baseValue = computedStyle(targetElement)->getPropertyValue(cssPropertyID(attributeName.localName()));
206 baseValue = targetElement->getAttribute(attributeName);
207 m_savedBaseValues.add(key, baseValue);
211 void SMILTimeContainer::sampleAnimationAtTime(const String& elementId, double newTime)
216 // Fast-forward to the time DRT wants to sample
219 updateAnimations(elapsed(), newTime, elementId);
222 void SMILTimeContainer::updateAnimations(SMILTime elapsed, double nextManualSampleTime, const String& nextSamplingTarget)
224 SMILTime earliersFireTime = SMILTime::unresolved();
226 Vector<SVGSMILElement*> toAnimate;
227 copyToVector(m_scheduledAnimations, toAnimate);
229 if (nextManualSampleTime) {
230 SMILTime samplingDiff;
231 for (unsigned n = 0; n < toAnimate.size(); ++n) {
232 SVGSMILElement* animation = toAnimate[n];
233 ASSERT(animation->timeContainer() == this);
235 SVGElement* targetElement = animation->targetElement();
236 // FIXME: This should probably be using getIdAttribute instead of idForStyleResolution.
237 if (!targetElement || !targetElement->hasID() || targetElement->idForStyleResolution() != nextSamplingTarget)
240 samplingDiff = animation->intervalBegin();
244 elapsed = SMILTime(nextManualSampleTime) + samplingDiff;
247 // Sort according to priority. Elements with later begin time have higher priority.
248 // In case of a tie, document order decides.
249 // FIXME: This should also consider timing relationships between the elements. Dependents
250 // have higher priority.
251 sortByPriority(toAnimate, elapsed);
253 // Calculate animation contributions.
254 typedef HashMap<ElementAttributePair, RefPtr<SVGSMILElement> > ResultElementMap;
255 ResultElementMap resultsElements;
256 for (unsigned n = 0; n < toAnimate.size(); ++n) {
257 SVGSMILElement* animation = toAnimate[n];
258 ASSERT(animation->timeContainer() == this);
260 SVGElement* targetElement = animation->targetElement();
264 QualifiedName attributeName = animation->attributeName();
265 if (attributeName == anyQName()) {
266 if (animation->hasTagName(SVGNames::animateMotionTag))
267 attributeName = SVGNames::animateMotionTag;
272 // Results are accumulated to the first animation that animates a particular element/attribute pair.
273 ElementAttributePair key(targetElement, attributeName);
274 SVGSMILElement* resultElement = resultsElements.get(key).get();
275 if (!resultElement) {
276 if (!animation->hasValidAttributeType())
278 resultElement = animation;
279 resultElement->resetToBaseValue(baseValueFor(key));
280 resultsElements.add(key, resultElement);
283 // This will calculate the contribution from the animation and add it to the resultsElement.
284 animation->progress(elapsed, resultElement);
286 SMILTime nextFireTime = animation->nextProgressTime();
287 if (nextFireTime.isFinite())
288 earliersFireTime = min(nextFireTime, earliersFireTime);
289 else if (!animation->isContributing(elapsed)) {
290 m_scheduledAnimations.remove(animation);
291 if (m_scheduledAnimations.isEmpty())
292 m_savedBaseValues.clear();
296 Vector<SVGSMILElement*> animationsToApply;
297 ResultElementMap::iterator end = resultsElements.end();
298 for (ResultElementMap::iterator it = resultsElements.begin(); it != end; ++it)
299 animationsToApply.append(it->second.get());
301 // Sort <animateTranform> to be the last one to be applied. <animate> may change transform attribute as
302 // well (directly or indirectly by modifying <use> x/y) and this way transforms combine properly.
303 sortByApplyOrder(animationsToApply);
305 // Apply results to target elements.
306 for (unsigned n = 0; n < animationsToApply.size(); ++n)
307 animationsToApply[n]->applyResultsToTarget();
309 startTimer(earliersFireTime, animationFrameDelay);
311 Document::updateStyleForAllDocuments();
318 #endif // ENABLE(SVG)