[Web Animations] Remove useless internals methods
[WebKit-https.git] / Source / WebCore / animation / DocumentTimeline.cpp
1 /*
2  * Copyright (C) 2017 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 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.
24  */
25
26 #include "config.h"
27 #include "DocumentTimeline.h"
28
29 #include "AnimationPlaybackEvent.h"
30 #include "CSSPropertyAnimation.h"
31 #include "DOMWindow.h"
32 #include "DeclarativeAnimation.h"
33 #include "Document.h"
34 #include "GraphicsLayer.h"
35 #include "KeyframeEffect.h"
36 #include "Microtasks.h"
37 #include "Page.h"
38 #include "RenderElement.h"
39 #include "RenderLayer.h"
40 #include "RenderLayerBacking.h"
41
42 static const Seconds defaultAnimationInterval { 15_ms };
43 static const Seconds throttledAnimationInterval { 30_ms };
44
45 namespace WebCore {
46
47 Ref<DocumentTimeline> DocumentTimeline::create(Document& document)
48 {
49     return adoptRef(*new DocumentTimeline(document, 0_s));
50 }
51
52 Ref<DocumentTimeline> DocumentTimeline::create(Document& document, DocumentTimelineOptions&& options)
53 {
54     return adoptRef(*new DocumentTimeline(document, Seconds::fromMilliseconds(options.originTime)));
55 }
56
57 DocumentTimeline::DocumentTimeline(Document& document, Seconds originTime)
58     : AnimationTimeline(DocumentTimelineClass)
59     , m_document(&document)
60     , m_originTime(originTime)
61     , m_animationScheduleTimer(*this, &DocumentTimeline::animationScheduleTimerFired)
62 #if !USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
63     , m_animationResolutionTimer(*this, &DocumentTimeline::animationResolutionTimerFired)
64 #endif
65 {
66     if (m_document && m_document->page() && !m_document->page()->isVisible())
67         suspendAnimations();
68 }
69
70 DocumentTimeline::~DocumentTimeline() = default;
71
72 void DocumentTimeline::detachFromDocument()
73 {
74     m_invalidationTaskQueue.close();
75     m_eventDispatchTaskQueue.close();
76     m_animationScheduleTimer.stop();
77     m_elementsWithRunningAcceleratedAnimations.clear();
78
79     auto& animationsToRemove = animations();
80     while (!animationsToRemove.isEmpty())
81         animationsToRemove.first()->remove();
82
83     m_document = nullptr;
84 }
85
86 void DocumentTimeline::updateThrottlingState()
87 {
88     m_needsUpdateAnimationSchedule = false;
89     timingModelDidChange();
90 }
91
92 Seconds DocumentTimeline::animationInterval() const
93 {
94     if (!m_document || !m_document->page())
95         return Seconds::infinity();
96     return m_document->page()->isLowPowerModeEnabled() ? throttledAnimationInterval : defaultAnimationInterval;
97 }
98
99 void DocumentTimeline::suspendAnimations()
100 {
101     if (animationsAreSuspended())
102         return;
103
104     m_invalidationTaskQueue.cancelAllTasks();
105     if (m_animationScheduleTimer.isActive())
106         m_animationScheduleTimer.stop();
107
108     for (const auto& animation : animations())
109         animation->setSuspended(true);
110
111     m_isSuspended = true;
112
113     applyPendingAcceleratedAnimations();
114 }
115
116 void DocumentTimeline::resumeAnimations()
117 {
118     if (!animationsAreSuspended())
119         return;
120
121     m_isSuspended = false;
122
123     for (const auto& animation : animations())
124         animation->setSuspended(false);
125
126     m_needsUpdateAnimationSchedule = false;
127     timingModelDidChange();
128 }
129
130 bool DocumentTimeline::animationsAreSuspended()
131 {
132     return m_isSuspended;
133 }
134
135 unsigned DocumentTimeline::numberOfActiveAnimationsForTesting() const
136 {
137     unsigned count = 0;
138     for (const auto& animation : animations()) {
139         if (!animation->isSuspended())
140             ++count;
141     }
142     return count;
143 }
144
145 std::optional<Seconds> DocumentTimeline::currentTime()
146 {
147     if (!m_document || !m_document->domWindow())
148         return AnimationTimeline::currentTime();
149
150     if (auto* mainDocumentTimeline = m_document->existingTimeline()) {
151         if (mainDocumentTimeline != this) {
152             if (auto mainDocumentTimelineCurrentTime = mainDocumentTimeline->currentTime())
153                 return mainDocumentTimelineCurrentTime.value() - m_originTime;
154             return std::nullopt;
155         }
156     }
157
158 #if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
159     // If we're in the middle of firing a frame, either due to a requestAnimationFrame callback
160     // or scheduling an animation update, we want to ensure we use the same time we're using as
161     // the timestamp for requestAnimationFrame() callbacks.
162     if (m_document->animationScheduler().isFiring())
163         m_cachedCurrentTime = m_document->animationScheduler().lastTimestamp();
164 #endif
165
166     if (!m_cachedCurrentTime) {
167 #if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
168         // If we're not in the middle of firing a frame, let's make our best guess at what the currentTime should
169         // be since the last time a frame fired by increment of our update interval. This way code using something
170         // like setTimeout() or handling events will get a time that's only updating at around 60fps, or less if
171         // we're throttled.
172         auto lastAnimationSchedulerTimestamp = m_document->animationScheduler().lastTimestamp();
173         auto delta = Seconds(m_document->domWindow()->nowTimestamp()) - lastAnimationSchedulerTimestamp;
174         int frames = std::floor(delta.seconds() / animationInterval().seconds());
175         m_cachedCurrentTime = lastAnimationSchedulerTimestamp + Seconds(frames * animationInterval().seconds());
176 #else
177         m_cachedCurrentTime = Seconds(m_document->domWindow()->nowTimestamp());
178 #endif
179         // We want to be sure to keep this time cached until we've both finished running JS and finished updating
180         // animations, so we schedule the invalidation task and register a whenIdle callback on the VM, which will
181         // fire syncronously if no JS is running.
182         scheduleInvalidationTaskIfNeeded();
183         m_waitingOnVMIdle = true;
184         m_document->vm().whenIdle([this, protectedThis = makeRefPtr(this)]() {
185             m_waitingOnVMIdle = false;
186             maybeClearCachedCurrentTime();
187         });
188     }
189     return m_cachedCurrentTime.value() - m_originTime;
190 }
191
192 void DocumentTimeline::timingModelDidChange()
193 {
194     if (m_needsUpdateAnimationSchedule || m_isSuspended)
195         return;
196
197     m_needsUpdateAnimationSchedule = true;
198
199     // We know that we will resolve animations again, so we can cancel the timer right away.
200     if (m_animationScheduleTimer.isActive())
201         m_animationScheduleTimer.stop();
202
203     scheduleInvalidationTaskIfNeeded();
204 }
205
206 void DocumentTimeline::scheduleInvalidationTaskIfNeeded()
207 {
208     if (m_invalidationTaskQueue.hasPendingTasks())
209         return;
210
211     m_invalidationTaskQueue.enqueueTask(std::bind(&DocumentTimeline::performInvalidationTask, this));
212 }
213
214 void DocumentTimeline::performInvalidationTask()
215 {
216     // Now that the timing model has changed we can see if there are DOM events to dispatch for declarative animations.
217     if (!m_isSuspended) {
218         for (auto& animation : animations()) {
219             if (is<DeclarativeAnimation>(animation))
220                 downcast<DeclarativeAnimation>(*animation).invalidateDOMEvents();
221         }
222     }
223
224     applyPendingAcceleratedAnimations();
225
226     updateAnimationSchedule();
227     maybeClearCachedCurrentTime();
228 }
229
230 void DocumentTimeline::maybeClearCachedCurrentTime()
231 {
232     // We want to make sure we only clear the cached current time if we're not currently running
233     // JS or waiting on all current animation updating code to have completed. This is so that
234     // we're guaranteed to have a consistent current time reported for all work happening in a given
235     // JS frame or throughout updating animations in WebCore.
236     if (!m_waitingOnVMIdle && !m_invalidationTaskQueue.hasPendingTasks())
237         m_cachedCurrentTime = std::nullopt;
238 }
239
240 void DocumentTimeline::updateAnimationSchedule()
241 {
242     if (!m_needsUpdateAnimationSchedule)
243         return;
244
245     m_needsUpdateAnimationSchedule = false;
246
247     if (!m_acceleratedAnimationsPendingRunningStateChange.isEmpty()) {
248         scheduleAnimationResolution();
249         return;
250     }
251
252     Seconds scheduleDelay = Seconds::infinity();
253
254     for (const auto& animation : animations()) {
255         auto animationTimeToNextRequiredTick = animation->timeToNextRequiredTick();
256         if (animationTimeToNextRequiredTick < animationInterval()) {
257             scheduleAnimationResolution();
258             return;
259         }
260         scheduleDelay = std::min(scheduleDelay, animationTimeToNextRequiredTick);
261     }
262
263     if (scheduleDelay < Seconds::infinity())
264         m_animationScheduleTimer.startOneShot(scheduleDelay);
265 }
266
267 void DocumentTimeline::animationScheduleTimerFired()
268 {
269     scheduleAnimationResolution();
270 }
271
272 void DocumentTimeline::scheduleAnimationResolution()
273 {
274 #if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
275     m_document->animationScheduler().scheduleWebAnimationsResolution();
276 #else
277     // FIXME: We need to use the same logic as ScriptedAnimationController here,
278     // which will be addressed by the refactor tracked by webkit.org/b/179293.
279     m_animationResolutionTimer.startOneShot(animationInterval());
280 #endif
281 }
282
283 #if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
284 void DocumentTimeline::documentAnimationSchedulerDidFire()
285 #else
286 void DocumentTimeline::animationResolutionTimerFired()
287 #endif
288 {
289     updateAnimations();
290 }
291
292 void DocumentTimeline::updateAnimations()
293 {
294     m_numberOfAnimationTimelineInvalidationsForTesting++;
295
296     for (const auto& animation : animations())
297         animation->runPendingTasks();
298
299     // Perform a microtask checkpoint such that all promises that may have resolved while
300     // running pending tasks can fire right away.
301     MicrotaskQueue::mainThreadQueue().performMicrotaskCheckpoint();
302
303     // Let's first resolve any animation that does not have a target.
304     for (auto* animation : animationsWithoutTarget())
305         animation->resolve();
306
307     // For the rest of the animations, we will resolve them via TreeResolver::createAnimatedElementUpdate()
308     // by invalidating their target element's style.
309     if (m_document && hasElementAnimations()) {
310         for (const auto& elementToAnimationsMapItem : elementToAnimationsMap())
311             elementToAnimationsMapItem.key->invalidateStyleAndLayerComposition();
312         for (const auto& elementToCSSAnimationsMapItem : elementToCSSAnimationsMap())
313             elementToCSSAnimationsMapItem.key->invalidateStyleAndLayerComposition();
314         for (const auto& elementToCSSTransitionsMapItem : elementToCSSTransitionsMap())
315             elementToCSSTransitionsMapItem.key->invalidateStyleAndLayerComposition();
316         m_document->updateStyleIfNeeded();
317     }
318
319     // Time has advanced, the timing model requires invalidation now.
320     timingModelDidChange();
321 }
322
323 bool DocumentTimeline::computeExtentOfAnimation(RenderElement& renderer, LayoutRect& bounds) const
324 {
325     if (!renderer.element())
326         return true;
327
328     KeyframeEffectReadOnly* matchingEffect = nullptr;
329     for (const auto& animation : animationsForElement(*renderer.element())) {
330         auto* effect = animation->effect();
331         if (is<KeyframeEffectReadOnly>(effect)) {
332             auto* keyframeEffect = downcast<KeyframeEffectReadOnly>(effect);
333             if (keyframeEffect->animatedProperties().contains(CSSPropertyTransform))
334                 matchingEffect = downcast<KeyframeEffectReadOnly>(effect);
335         }
336     }
337
338     if (matchingEffect)
339         return matchingEffect->computeExtentOfTransformAnimation(bounds);
340
341     return true;
342 }
343
344 bool DocumentTimeline::isRunningAnimationOnRenderer(RenderElement& renderer, CSSPropertyID property) const
345 {
346     if (!renderer.element())
347         return false;
348
349     for (const auto& animation : animationsForElement(*renderer.element())) {
350         auto playState = animation->playState();
351         if (playState != WebAnimation::PlayState::Running && playState != WebAnimation::PlayState::Paused)
352             continue;
353         auto* effect = animation->effect();
354         if (is<KeyframeEffectReadOnly>(effect) && downcast<KeyframeEffectReadOnly>(effect)->animatedProperties().contains(property))
355             return true;
356     }
357
358     return false;
359 }
360
361 bool DocumentTimeline::isRunningAcceleratedAnimationOnRenderer(RenderElement& renderer, CSSPropertyID property) const
362 {
363     if (!renderer.element())
364         return false;
365
366     for (const auto& animation : animationsForElement(*renderer.element())) {
367         auto playState = animation->playState();
368         if (playState != WebAnimation::PlayState::Running && playState != WebAnimation::PlayState::Paused)
369             continue;
370         auto* effect = animation->effect();
371         if (is<KeyframeEffectReadOnly>(effect)) {
372             auto* keyframeEffect = downcast<KeyframeEffectReadOnly>(effect);
373             if (keyframeEffect->isRunningAccelerated() && keyframeEffect->animatedProperties().contains(property))
374                 return true;
375         }
376     }
377
378     return false;
379 }
380
381 std::unique_ptr<RenderStyle> DocumentTimeline::animatedStyleForRenderer(RenderElement& renderer)
382 {
383     std::unique_ptr<RenderStyle> result;
384
385     if (auto* element = renderer.element()) {
386         for (const auto& animation : animationsForElement(*element)) {
387             if (is<KeyframeEffectReadOnly>(animation->effect()))
388                 downcast<KeyframeEffectReadOnly>(animation->effect())->getAnimatedStyle(result);
389         }
390     }
391
392     if (!result)
393         result = RenderStyle::clonePtr(renderer.style());
394
395     return result;
396 }
397
398 void DocumentTimeline::animationWasAddedToElement(WebAnimation& animation, Element& element)
399 {
400     AnimationTimeline::animationWasAddedToElement(animation, element);
401     updateListOfElementsWithRunningAcceleratedAnimationsForElement(element);
402 }
403
404 void DocumentTimeline::animationWasRemovedFromElement(WebAnimation& animation, Element& element)
405 {
406     AnimationTimeline::animationWasRemovedFromElement(animation, element);
407     updateListOfElementsWithRunningAcceleratedAnimationsForElement(element);
408 }
409
410 void DocumentTimeline::animationAcceleratedRunningStateDidChange(WebAnimation& animation)
411 {
412     m_acceleratedAnimationsPendingRunningStateChange.add(&animation);
413
414     if (is<KeyframeEffectReadOnly>(animation.effect())) {
415         if (auto* target = downcast<KeyframeEffectReadOnly>(animation.effect())->target())
416             updateListOfElementsWithRunningAcceleratedAnimationsForElement(*target);
417     }
418 }
419
420 void DocumentTimeline::updateListOfElementsWithRunningAcceleratedAnimationsForElement(Element& element)
421 {
422     auto animations = animationsForElement(element);
423     bool runningAnimationsForElementAreAllAccelerated = !animations.isEmpty();
424     for (const auto& animation : animations) {
425         if (is<KeyframeEffectReadOnly>(animation->effect()) && !downcast<KeyframeEffectReadOnly>(animation->effect())->isRunningAccelerated()) {
426             runningAnimationsForElementAreAllAccelerated = false;
427             break;
428         }
429     }
430
431     if (runningAnimationsForElementAreAllAccelerated)
432         m_elementsWithRunningAcceleratedAnimations.add(&element);
433     else
434         m_elementsWithRunningAcceleratedAnimations.remove(&element);
435 }
436
437 void DocumentTimeline::applyPendingAcceleratedAnimations()
438 {
439     auto acceleratedAnimationsPendingRunningStateChange = m_acceleratedAnimationsPendingRunningStateChange;
440     m_acceleratedAnimationsPendingRunningStateChange.clear();
441
442     bool hasForcedLayout = false;
443     for (auto& animation : acceleratedAnimationsPendingRunningStateChange) {
444         if (!hasForcedLayout) {
445             auto* effect = animation->effect();
446             if (is<KeyframeEffectReadOnly>(effect))
447                 hasForcedLayout |= downcast<KeyframeEffectReadOnly>(effect)->forceLayoutIfNeeded();
448         }
449         animation->applyPendingAcceleratedActions();
450     }
451 }
452
453 bool DocumentTimeline::resolveAnimationsForElement(Element& element, RenderStyle& targetStyle)
454 {
455     bool hasNonAcceleratedAnimations = false;
456     bool hasPendingAcceleratedAnimations = true;
457     for (const auto& animation : animationsForElement(element)) {
458         animation->resolve(targetStyle);
459         if (!hasNonAcceleratedAnimations) {
460             if (auto* effect = animation->effect()) {
461                 if (is<KeyframeEffectReadOnly>(effect)) {
462                     auto* keyframeEffect = downcast<KeyframeEffectReadOnly>(effect);
463                     for (auto cssPropertyId : keyframeEffect->animatedProperties()) {
464                         if (!CSSPropertyAnimation::animationOfPropertyIsAccelerated(cssPropertyId)) {
465                             hasNonAcceleratedAnimations = true;
466                             continue;
467                         }
468                         if (!hasPendingAcceleratedAnimations)
469                             hasPendingAcceleratedAnimations = keyframeEffect->hasPendingAcceleratedAction();
470                     }
471                 }
472             }
473         }
474     }
475
476     // If there are no non-accelerated animations and we've encountered at least one pending
477     // accelerated animation, we should recomposite this element's layer for animation purposes.
478     return !hasNonAcceleratedAnimations && hasPendingAcceleratedAnimations;
479 }
480
481 bool DocumentTimeline::runningAnimationsForElementAreAllAccelerated(Element& element) const
482 {
483     return m_elementsWithRunningAcceleratedAnimations.contains(&element);
484 }
485
486 void DocumentTimeline::enqueueAnimationPlaybackEvent(AnimationPlaybackEvent& event)
487 {
488     m_pendingAnimationEvents.append(event);
489
490     if (!m_eventDispatchTaskQueue.hasPendingTasks())
491         m_eventDispatchTaskQueue.enqueueTask(std::bind(&DocumentTimeline::performEventDispatchTask, this));
492 }
493
494 static inline bool compareAnimationPlaybackEvents(const Ref<WebCore::AnimationPlaybackEvent>& lhs, const Ref<WebCore::AnimationPlaybackEvent>& rhs)
495 {
496     // Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort before events scheduled to occur later
497     // and events whose scheduled event time is unresolved sort before events with a resolved scheduled event time.
498     if (lhs->timelineTime() && !rhs->timelineTime())
499         return false;
500     if (!lhs->timelineTime() && rhs->timelineTime())
501         return true;
502     if (!lhs->timelineTime() && !rhs->timelineTime())
503         return true;
504     return lhs->timelineTime().value() < rhs->timelineTime().value();
505 }
506
507 void DocumentTimeline::performEventDispatchTask()
508 {
509     if (m_pendingAnimationEvents.isEmpty())
510         return;
511
512     auto pendingAnimationEvents = WTFMove(m_pendingAnimationEvents);
513
514     std::stable_sort(pendingAnimationEvents.begin(), pendingAnimationEvents.end(), compareAnimationPlaybackEvents);
515     for (auto& pendingEvent : pendingAnimationEvents)
516         pendingEvent->target()->dispatchEvent(pendingEvent);
517 }
518
519 Vector<std::pair<String, double>> DocumentTimeline::acceleratedAnimationsForElement(Element& element) const
520 {
521     auto* renderer = element.renderer();
522     if (renderer && renderer->isComposited()) {
523         auto* compositedRenderer = downcast<RenderBoxModelObject>(renderer);
524         if (auto* graphicsLayer = compositedRenderer->layer()->backing()->graphicsLayer())
525             return graphicsLayer->acceleratedAnimationsForTesting();
526     }
527     return { };
528 }
529
530 unsigned DocumentTimeline::numberOfAnimationTimelineInvalidationsForTesting() const
531 {
532     return m_numberOfAnimationTimelineInvalidationsForTesting;
533 }
534
535 } // namespace WebCore