DocumentTimeline.cpp [plain text]
#include "config.h"
#include "DocumentTimeline.h"
#include "AnimationPlaybackEvent.h"
#include "DOMWindow.h"
#include "DeclarativeAnimation.h"
#include "Document.h"
#include "KeyframeEffect.h"
#include "Microtasks.h"
#include "Page.h"
#include "RenderElement.h"
static const Seconds defaultAnimationInterval { 15_ms };
static const Seconds throttledAnimationInterval { 30_ms };
namespace WebCore {
Ref<DocumentTimeline> DocumentTimeline::create(Document& document)
{
return adoptRef(*new DocumentTimeline(document, 0_s));
}
Ref<DocumentTimeline> DocumentTimeline::create(Document& document, DocumentTimelineOptions&& options)
{
return adoptRef(*new DocumentTimeline(document, Seconds::fromMilliseconds(options.originTime)));
}
DocumentTimeline::DocumentTimeline(Document& document, Seconds originTime)
: AnimationTimeline(DocumentTimelineClass)
, m_document(&document)
, m_originTime(originTime)
, m_animationScheduleTimer(*this, &DocumentTimeline::animationScheduleTimerFired)
#if !USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
, m_animationResolutionTimer(*this, &DocumentTimeline::animationResolutionTimerFired)
#endif
{
}
DocumentTimeline::~DocumentTimeline() = default;
void DocumentTimeline::detachFromDocument()
{
m_invalidationTaskQueue.close();
m_eventDispatchTaskQueue.close();
m_animationScheduleTimer.stop();
auto& animationsToRemove = animations();
while (!animationsToRemove.isEmpty())
animationsToRemove.first()->remove();
m_document = nullptr;
}
void DocumentTimeline::updateThrottlingState()
{
m_needsUpdateAnimationSchedule = false;
timingModelDidChange();
}
Seconds DocumentTimeline::animationInterval() const
{
if (!m_document || !m_document->page())
return Seconds::infinity();
return m_document->page()->isLowPowerModeEnabled() ? throttledAnimationInterval : defaultAnimationInterval;
}
void DocumentTimeline::suspendAnimations()
{
if (animationsAreSuspended())
return;
m_isSuspended = true;
m_invalidationTaskQueue.cancelAllTasks();
if (m_animationScheduleTimer.isActive())
m_animationScheduleTimer.stop();
for (const auto& animation : animations())
animation->setSuspended(true);
applyPendingAcceleratedAnimations();
}
void DocumentTimeline::resumeAnimations()
{
if (!animationsAreSuspended())
return;
m_isSuspended = false;
for (const auto& animation : animations())
animation->setSuspended(false);
m_needsUpdateAnimationSchedule = false;
timingModelDidChange();
}
bool DocumentTimeline::animationsAreSuspended()
{
return m_isSuspended;
}
unsigned DocumentTimeline::numberOfActiveAnimationsForTesting() const
{
unsigned count = 0;
for (const auto& animation : animations()) {
if (!animation->isSuspended())
++count;
}
return count;
}
std::optional<Seconds> DocumentTimeline::currentTime()
{
if (m_paused || m_isSuspended || !m_document || !m_document->domWindow())
return AnimationTimeline::currentTime();
if (auto* mainDocumentTimeline = m_document->existingTimeline()) {
if (mainDocumentTimeline != this) {
if (auto mainDocumentTimelineCurrentTime = mainDocumentTimeline->currentTime())
return mainDocumentTimelineCurrentTime.value() - m_originTime;
return std::nullopt;
}
}
#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
if (m_document->animationScheduler().isFiring())
m_cachedCurrentTime = m_document->animationScheduler().lastTimestamp();
#endif
if (!m_cachedCurrentTime) {
#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
auto lastAnimationSchedulerTimestamp = m_document->animationScheduler().lastTimestamp();
auto delta = Seconds(m_document->domWindow()->nowTimestamp()) - lastAnimationSchedulerTimestamp;
int frames = std::floor(delta.seconds() / animationInterval().seconds());
m_cachedCurrentTime = lastAnimationSchedulerTimestamp + Seconds(frames * animationInterval().seconds());
#else
m_cachedCurrentTime = Seconds(m_document->domWindow()->nowTimestamp());
#endif
scheduleInvalidationTaskIfNeeded();
m_waitingOnVMIdle = true;
m_document->vm().whenIdle([this, protectedThis = makeRefPtr(this)]() {
m_waitingOnVMIdle = false;
maybeClearCachedCurrentTime();
});
}
return m_cachedCurrentTime.value() - m_originTime;
}
void DocumentTimeline::pause()
{
m_paused = true;
}
void DocumentTimeline::timingModelDidChange()
{
if (m_needsUpdateAnimationSchedule || m_isSuspended)
return;
m_needsUpdateAnimationSchedule = true;
if (m_animationScheduleTimer.isActive())
m_animationScheduleTimer.stop();
scheduleInvalidationTaskIfNeeded();
}
void DocumentTimeline::scheduleInvalidationTaskIfNeeded()
{
if (m_invalidationTaskQueue.hasPendingTasks())
return;
m_invalidationTaskQueue.enqueueTask(std::bind(&DocumentTimeline::performInvalidationTask, this));
}
void DocumentTimeline::performInvalidationTask()
{
for (auto& animation : animations()) {
if (is<DeclarativeAnimation>(animation))
downcast<DeclarativeAnimation>(*animation).invalidateDOMEvents();
}
applyPendingAcceleratedAnimations();
updateAnimationSchedule();
maybeClearCachedCurrentTime();
}
void DocumentTimeline::maybeClearCachedCurrentTime()
{
if (!m_waitingOnVMIdle && !m_invalidationTaskQueue.hasPendingTasks())
m_cachedCurrentTime = std::nullopt;
}
void DocumentTimeline::updateAnimationSchedule()
{
if (!m_needsUpdateAnimationSchedule)
return;
m_needsUpdateAnimationSchedule = false;
if (!m_acceleratedAnimationsPendingRunningStateChange.isEmpty()) {
scheduleAnimationResolution();
return;
}
Seconds scheduleDelay = Seconds::infinity();
for (const auto& animation : animations()) {
auto animationTimeToNextRequiredTick = animation->timeToNextRequiredTick();
if (animationTimeToNextRequiredTick < animationInterval()) {
scheduleAnimationResolution();
return;
}
scheduleDelay = std::min(scheduleDelay, animationTimeToNextRequiredTick);
}
if (scheduleDelay < Seconds::infinity())
m_animationScheduleTimer.startOneShot(scheduleDelay);
}
void DocumentTimeline::animationScheduleTimerFired()
{
scheduleAnimationResolution();
}
void DocumentTimeline::scheduleAnimationResolution()
{
#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
m_document->animationScheduler().scheduleWebAnimationsResolution();
#else
m_animationResolutionTimer.startOneShot(animationInterval());
#endif
}
#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
void DocumentTimeline::documentAnimationSchedulerDidFire()
#else
void DocumentTimeline::animationResolutionTimerFired()
#endif
{
updateAnimations();
}
void DocumentTimeline::updateAnimations()
{
for (const auto& animation : animations())
animation->runPendingTasks();
MicrotaskQueue::mainThreadQueue().performMicrotaskCheckpoint();
for (auto* animation : animationsWithoutTarget())
animation->resolve();
if (m_document && hasElementAnimations()) {
for (const auto& elementToAnimationsMapItem : elementToAnimationsMap())
elementToAnimationsMapItem.key->invalidateStyleAndLayerComposition();
for (const auto& elementToCSSAnimationsMapItem : elementToCSSAnimationsMap())
elementToCSSAnimationsMapItem.key->invalidateStyleAndLayerComposition();
for (const auto& elementToCSSTransitionsMapItem : elementToCSSTransitionsMap())
elementToCSSTransitionsMapItem.key->invalidateStyleAndLayerComposition();
m_document->updateStyleIfNeeded();
}
timingModelDidChange();
}
bool DocumentTimeline::computeExtentOfAnimation(RenderElement& renderer, LayoutRect& bounds) const
{
if (!renderer.element())
return true;
KeyframeEffectReadOnly* matchingEffect = nullptr;
for (const auto& animation : animationsForElement(*renderer.element())) {
auto* effect = animation->effect();
if (is<KeyframeEffectReadOnly>(effect)) {
auto* keyframeEffect = downcast<KeyframeEffectReadOnly>(effect);
if (keyframeEffect->animatedProperties().contains(CSSPropertyTransform))
matchingEffect = downcast<KeyframeEffectReadOnly>(effect);
}
}
if (matchingEffect)
return matchingEffect->computeExtentOfTransformAnimation(bounds);
return true;
}
bool DocumentTimeline::isRunningAnimationOnRenderer(RenderElement& renderer, CSSPropertyID property) const
{
if (!renderer.element())
return false;
for (const auto& animation : animationsForElement(*renderer.element())) {
auto playState = animation->playState();
if (playState != WebAnimation::PlayState::Running && playState != WebAnimation::PlayState::Paused)
continue;
auto* effect = animation->effect();
if (is<KeyframeEffectReadOnly>(effect) && downcast<KeyframeEffectReadOnly>(effect)->animatedProperties().contains(property))
return true;
}
return false;
}
bool DocumentTimeline::isRunningAcceleratedAnimationOnRenderer(RenderElement& renderer, CSSPropertyID property) const
{
if (!renderer.element())
return false;
for (const auto& animation : animationsForElement(*renderer.element())) {
auto playState = animation->playState();
if (playState != WebAnimation::PlayState::Running && playState != WebAnimation::PlayState::Paused)
continue;
auto* effect = animation->effect();
if (is<KeyframeEffectReadOnly>(effect)) {
auto* keyframeEffect = downcast<KeyframeEffectReadOnly>(effect);
if (keyframeEffect->isRunningAccelerated() && keyframeEffect->animatedProperties().contains(property))
return true;
}
}
return false;
}
std::unique_ptr<RenderStyle> DocumentTimeline::animatedStyleForRenderer(RenderElement& renderer)
{
std::unique_ptr<RenderStyle> result;
if (auto* element = renderer.element()) {
for (const auto& animation : animationsForElement(*element)) {
if (is<KeyframeEffectReadOnly>(animation->effect()))
downcast<KeyframeEffectReadOnly>(animation->effect())->getAnimatedStyle(result);
}
}
if (!result)
result = RenderStyle::clonePtr(renderer.style());
return result;
}
void DocumentTimeline::animationAcceleratedRunningStateDidChange(WebAnimation& animation)
{
m_acceleratedAnimationsPendingRunningStateChange.add(&animation);
}
void DocumentTimeline::applyPendingAcceleratedAnimations()
{
bool hasForcedLayout = false;
for (auto& animation : m_acceleratedAnimationsPendingRunningStateChange) {
if (!hasForcedLayout) {
auto* effect = animation->effect();
if (is<KeyframeEffectReadOnly>(effect))
hasForcedLayout |= downcast<KeyframeEffectReadOnly>(effect)->forceLayoutIfNeeded();
}
animation->applyPendingAcceleratedActions();
}
m_acceleratedAnimationsPendingRunningStateChange.clear();
}
bool DocumentTimeline::runningAnimationsForElementAreAllAccelerated(Element& element)
{
auto animations = animationsForElement(element);
for (const auto& animation : animations) {
if (is<KeyframeEffectReadOnly>(animation->effect()) && !downcast<KeyframeEffectReadOnly>(animation->effect())->isRunningAccelerated())
return false;
}
return !animations.isEmpty();
}
void DocumentTimeline::enqueueAnimationPlaybackEvent(AnimationPlaybackEvent& event)
{
m_pendingAnimationEvents.append(event);
if (!m_eventDispatchTaskQueue.hasPendingTasks())
m_eventDispatchTaskQueue.enqueueTask(std::bind(&DocumentTimeline::performEventDispatchTask, this));
}
static inline bool compareAnimationPlaybackEvents(const Ref<WebCore::AnimationPlaybackEvent>& lhs, const Ref<WebCore::AnimationPlaybackEvent>& rhs)
{
if (lhs->timelineTime() && !rhs->timelineTime())
return false;
if (!lhs->timelineTime() && rhs->timelineTime())
return true;
if (!lhs->timelineTime() && !rhs->timelineTime())
return true;
return lhs->timelineTime().value() < rhs->timelineTime().value();
}
void DocumentTimeline::performEventDispatchTask()
{
if (m_pendingAnimationEvents.isEmpty())
return;
auto pendingAnimationEvents = WTFMove(m_pendingAnimationEvents);
std::stable_sort(pendingAnimationEvents.begin(), pendingAnimationEvents.end(), compareAnimationPlaybackEvents);
for (auto& pendingEvent : pendingAnimationEvents)
pendingEvent->target()->dispatchEvent(pendingEvent);
}
}