Backed out 4 changesets (bug 1825722) for causing reftest failures CLOSED TREE
[gecko.git] / layout / style / nsTransitionManager.cpp
blob66f1004354b5ff3c217813404a2d4b5731618d4f
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Code to start and animate CSS transitions. */
9 #include "nsTransitionManager.h"
10 #include "mozilla/dom/Document.h"
11 #include "nsAnimationManager.h"
13 #include "nsIContent.h"
14 #include "AnimatedPropertyID.h"
15 #include "AnimatedPropertyIDSet.h"
16 #include "mozilla/ComputedStyle.h"
17 #include "mozilla/MemoryReporting.h"
18 #include "nsCSSPropertyIDSet.h"
19 #include "mozilla/EffectSet.h"
20 #include "mozilla/ElementAnimationData.h"
21 #include "mozilla/EventDispatcher.h"
22 #include "mozilla/ServoBindings.h"
23 #include "mozilla/StyleAnimationValue.h"
24 #include "mozilla/dom/DocumentTimeline.h"
25 #include "mozilla/dom/Element.h"
26 #include "nsIFrame.h"
27 #include "nsCSSProps.h"
28 #include "nsCSSPseudoElements.h"
29 #include "nsDisplayList.h"
30 #include "nsRFPService.h"
31 #include "nsStyleChangeList.h"
32 #include "mozilla/RestyleManager.h"
34 using mozilla::dom::CSSTransition;
35 using mozilla::dom::DocumentTimeline;
36 using mozilla::dom::KeyframeEffect;
38 using namespace mozilla;
39 using namespace mozilla::css;
41 bool nsTransitionManager::UpdateTransitions(dom::Element* aElement,
42 PseudoStyleType aPseudoType,
43 const ComputedStyle& aOldStyle,
44 const ComputedStyle& aNewStyle) {
45 if (mPresContext->Medium() == nsGkAtoms::print) {
46 // For print or print preview, ignore transitions.
47 return false;
50 MOZ_ASSERT(mPresContext->IsDynamic());
51 if (aNewStyle.StyleDisplay()->mDisplay == StyleDisplay::None) {
52 StopAnimationsForElement(aElement, aPseudoType);
53 return false;
56 auto* collection = CSSTransitionCollection::Get(aElement, aPseudoType);
57 return DoUpdateTransitions(*aNewStyle.StyleUIReset(), aElement, aPseudoType,
58 collection, aOldStyle, aNewStyle);
61 // This function expands the shorthands and "all" keyword specified in
62 // transition-property, and then execute |aHandler| on the expanded longhand.
63 // |aHandler| should be a lamda function which accepts nsCSSPropertyID.
64 template <typename T>
65 static void ExpandTransitionProperty(const StyleTransitionProperty& aProperty,
66 T aHandler) {
67 switch (aProperty.tag) {
68 case StyleTransitionProperty::Tag::Unsupported:
69 break;
70 case StyleTransitionProperty::Tag::Custom: {
71 AnimatedPropertyID property(aProperty.AsCustom().AsAtom());
72 aHandler(property);
73 break;
75 case StyleTransitionProperty::Tag::NonCustom: {
76 nsCSSPropertyID id = nsCSSPropertyID(aProperty.AsNonCustom()._0);
77 if (nsCSSProps::IsShorthand(id)) {
78 CSSPROPS_FOR_SHORTHAND_SUBPROPERTIES(subprop, id,
79 CSSEnabledState::ForAllContent) {
80 AnimatedPropertyID property(*subprop);
81 aHandler(property);
83 } else {
84 AnimatedPropertyID property(id);
85 aHandler(property);
87 break;
92 bool nsTransitionManager::DoUpdateTransitions(
93 const nsStyleUIReset& aStyle, dom::Element* aElement,
94 PseudoStyleType aPseudoType, CSSTransitionCollection*& aElementTransitions,
95 const ComputedStyle& aOldStyle, const ComputedStyle& aNewStyle) {
96 MOZ_ASSERT(!aElementTransitions || &aElementTransitions->mElement == aElement,
97 "Element mismatch");
99 // Per http://lists.w3.org/Archives/Public/www-style/2009Aug/0109.html
100 // I'll consider only the transitions from the number of items in
101 // 'transition-property' on down, and later ones will override earlier
102 // ones (tracked using |propertiesChecked|).
103 bool startedAny = false;
104 AnimatedPropertyIDSet propertiesChecked;
105 for (uint32_t i = aStyle.mTransitionPropertyCount; i--;) {
106 const float delay = aStyle.GetTransitionDelay(i).ToMilliseconds();
108 // The spec says a negative duration is treated as zero.
109 const float duration =
110 std::max(aStyle.GetTransitionDuration(i).ToMilliseconds(), 0.0f);
112 // If the combined duration of this transition is 0 or less we won't start a
113 // transition, we can avoid even looking at transition-property if we're the
114 // last one.
115 if (i == 0 && delay + duration <= 0.0f) {
116 continue;
119 const auto behavior = aStyle.GetTransitionBehavior(i);
120 ExpandTransitionProperty(aStyle.GetTransitionProperty(i),
121 [&](const AnimatedPropertyID& aProperty) {
122 // We might have something to transition. See if
123 // any of the properties in question changed and
124 // are animatable.
125 startedAny |= ConsiderInitiatingTransition(
126 aProperty, aStyle, i, delay, duration,
127 behavior, aElement, aPseudoType,
128 aElementTransitions, aOldStyle, aNewStyle,
129 propertiesChecked);
133 // Stop any transitions for properties that are no longer in
134 // 'transition-property', including finished transitions.
135 // Also stop any transitions (and remove any finished transitions)
136 // for properties that just changed (and are still in the set of
137 // properties to transition), but for which we didn't just start the
138 // transition. This can happen delay and duration are both zero, or
139 // because the new value is not interpolable.
140 if (aElementTransitions) {
141 const bool checkProperties = !aStyle.GetTransitionProperty(0).IsAll();
142 AnimatedPropertyIDSet allTransitionProperties;
143 if (checkProperties) {
144 for (uint32_t i = aStyle.mTransitionPropertyCount; i-- != 0;) {
145 ExpandTransitionProperty(aStyle.GetTransitionProperty(i),
146 [&](const AnimatedPropertyID& aProperty) {
147 allTransitionProperties.AddProperty(
148 aProperty.ToPhysical(aNewStyle));
153 OwningCSSTransitionPtrArray& animations = aElementTransitions->mAnimations;
154 size_t i = animations.Length();
155 MOZ_ASSERT(i != 0, "empty transitions list?");
156 AnimationValue currentValue;
157 do {
158 --i;
159 CSSTransition* anim = animations[i];
160 const AnimatedPropertyID& property = anim->TransitionProperty();
161 if (
162 // Properties no longer in `transition-property`.
163 (checkProperties && !allTransitionProperties.HasProperty(property)) ||
164 // Properties whose computed values changed but for which we did not
165 // start a new transition (because delay and duration are both zero,
166 // or because the new value is not interpolable); a new transition
167 // would have anim->ToValue() matching currentValue.
168 !Servo_ComputedValues_TransitionValueMatches(
169 &aNewStyle, &property, anim->ToValue().mServo.get())) {
170 // Stop the transition.
171 DoCancelTransition(aElement, aPseudoType, aElementTransitions, i);
173 } while (i != 0);
176 return startedAny;
179 static Keyframe& AppendKeyframe(double aOffset,
180 const AnimatedPropertyID& aProperty,
181 AnimationValue&& aValue,
182 nsTArray<Keyframe>& aKeyframes) {
183 Keyframe& frame = *aKeyframes.AppendElement();
184 frame.mOffset.emplace(aOffset);
185 MOZ_ASSERT(aValue.mServo);
186 RefPtr<StyleLockedDeclarationBlock> decl =
187 Servo_AnimationValue_Uncompute(aValue.mServo).Consume();
188 frame.mPropertyValues.AppendElement(
189 PropertyValuePair(aProperty, std::move(decl)));
190 return frame;
193 static nsTArray<Keyframe> GetTransitionKeyframes(
194 const AnimatedPropertyID& aProperty, AnimationValue&& aStartValue,
195 AnimationValue&& aEndValue) {
196 nsTArray<Keyframe> keyframes(2);
198 AppendKeyframe(0.0, aProperty, std::move(aStartValue), keyframes);
199 AppendKeyframe(1.0, aProperty, std::move(aEndValue), keyframes);
201 return keyframes;
204 static Maybe<CSSTransition::ReplacedTransitionProperties>
205 GetReplacedTransitionProperties(const CSSTransition* aTransition,
206 const DocumentTimeline* aTimelineToMatch) {
207 Maybe<CSSTransition::ReplacedTransitionProperties> result;
209 // Transition needs to be currently running on the compositor to be
210 // replaceable.
211 if (!aTransition || !aTransition->HasCurrentEffect() ||
212 !aTransition->IsRunningOnCompositor() ||
213 aTransition->GetStartTime().IsNull()) {
214 return result;
217 // Transition needs to be running on the same timeline.
218 if (aTransition->GetTimeline() != aTimelineToMatch) {
219 return result;
222 // The transition needs to have a keyframe effect.
223 const KeyframeEffect* keyframeEffect =
224 aTransition->GetEffect() ? aTransition->GetEffect()->AsKeyframeEffect()
225 : nullptr;
226 if (!keyframeEffect) {
227 return result;
230 // The keyframe effect needs to be a simple transition of the original
231 // transition property (i.e. not replaced with something else).
232 if (keyframeEffect->Properties().Length() != 1 ||
233 keyframeEffect->Properties()[0].mSegments.Length() != 1 ||
234 keyframeEffect->Properties()[0].mProperty !=
235 aTransition->TransitionProperty()) {
236 return result;
239 const AnimationPropertySegment& segment =
240 keyframeEffect->Properties()[0].mSegments[0];
242 result.emplace(CSSTransition::ReplacedTransitionProperties(
243 {aTransition->GetStartTime().Value(), aTransition->PlaybackRate(),
244 keyframeEffect->SpecifiedTiming(), segment.mTimingFunction,
245 segment.mFromValue, segment.mToValue}));
247 return result;
250 bool nsTransitionManager::ConsiderInitiatingTransition(
251 const AnimatedPropertyID& aProperty, const nsStyleUIReset& aStyle,
252 uint32_t aTransitionIndex, float aDelay, float aDuration,
253 mozilla::StyleTransitionBehavior aBehavior, dom::Element* aElement,
254 PseudoStyleType aPseudoType, CSSTransitionCollection*& aElementTransitions,
255 const ComputedStyle& aOldStyle, const ComputedStyle& aNewStyle,
256 AnimatedPropertyIDSet& aPropertiesChecked) {
257 // IsShorthand itself will assert if aProperty is not a property.
258 MOZ_ASSERT(aProperty.IsCustom() || !nsCSSProps::IsShorthand(aProperty.mID),
259 "property out of range");
260 NS_ASSERTION(
261 !aElementTransitions || &aElementTransitions->mElement == aElement,
262 "Element mismatch");
264 AnimatedPropertyID property = aProperty.ToPhysical(aNewStyle);
266 // A later item in transition-property already specified a transition for
267 // this property, so we ignore this one.
269 // See http://lists.w3.org/Archives/Public/www-style/2009Aug/0109.html .
270 if (aPropertiesChecked.HasProperty(property)) {
271 return false;
274 aPropertiesChecked.AddProperty(property);
276 if (aDuration + aDelay <= 0.0f) {
277 return false;
280 size_t currentIndex = nsTArray<KeyframeEffect>::NoIndex;
281 const auto* oldTransition = [&]() -> const CSSTransition* {
282 if (!aElementTransitions) {
283 return nullptr;
285 const OwningCSSTransitionPtrArray& animations =
286 aElementTransitions->mAnimations;
287 for (size_t i = 0, i_end = animations.Length(); i < i_end; ++i) {
288 if (animations[i]->TransitionProperty() == property) {
289 currentIndex = i;
290 return animations[i];
293 return nullptr;
294 }();
296 AnimationValue startValue, endValue;
297 const StyleShouldTransitionResult result =
298 Servo_ComputedValues_ShouldTransition(
299 &aOldStyle, &aNewStyle, &property, aBehavior,
300 oldTransition ? oldTransition->ToValue().mServo.get() : nullptr,
301 &startValue.mServo, &endValue.mServo);
303 // If we got a style change that changed the value to the endpoint
304 // of the currently running transition, we don't want to interrupt
305 // its timing function.
306 // This needs to be before the !shouldAnimate && haveCurrentTransition
307 // case below because we might be close enough to the end of the
308 // transition that the current value rounds to the final value. In
309 // this case, we'll end up with shouldAnimate as false (because
310 // there's no value change), but we need to return early here rather
311 // than cancel the running transition because shouldAnimate is false!
313 // Likewise, if we got a style change that changed the value to the
314 // endpoint of our finished transition, we also don't want to start
315 // a new transition for the reasons described in
316 // https://lists.w3.org/Archives/Public/www-style/2015Jan/0444.html .
317 if (result.old_transition_value_matches) {
318 // GetAnimationRule already called RestyleForAnimation.
319 return false;
322 if (!result.should_animate) {
323 if (oldTransition) {
324 // We're in the middle of a transition, and just got a non-transition
325 // style change to something that we can't animate. This might happen
326 // because we got a non-transition style change changing to the current
327 // in-progress value (which is particularly easy to cause when we're
328 // currently in the 'transition-delay'). It also might happen because we
329 // just got a style change to a value that can't be interpolated.
330 DoCancelTransition(aElement, aPseudoType, aElementTransitions,
331 currentIndex);
333 return false;
336 AnimationValue startForReversingTest = startValue;
337 double reversePortion = 1.0;
339 // If the new transition reverses an existing one, we'll need to
340 // handle the timing differently.
341 if (oldTransition && oldTransition->HasCurrentEffect() &&
342 oldTransition->StartForReversingTest() == endValue) {
343 // Compute the appropriate negative transition-delay such that right
344 // now we'd end up at the current position.
345 double valuePortion =
346 oldTransition->CurrentValuePortion() * oldTransition->ReversePortion() +
347 (1.0 - oldTransition->ReversePortion());
348 // A timing function with negative y1 (or y2!) might make
349 // valuePortion negative. In this case, we still want to apply our
350 // reversing logic based on relative distances, not make duration
351 // negative.
352 if (valuePortion < 0.0) {
353 valuePortion = -valuePortion;
355 // A timing function with y2 (or y1!) greater than one might
356 // advance past its terminal value. It's probably a good idea to
357 // clamp valuePortion to be at most one to preserve the invariant
358 // that a transition will complete within at most its specified
359 // time.
360 if (valuePortion > 1.0) {
361 valuePortion = 1.0;
364 // Negative delays are essentially part of the transition
365 // function, so reduce them along with the duration, but don't
366 // reduce positive delays.
367 if (aDelay < 0.0f && std::isfinite(aDelay)) {
368 aDelay *= valuePortion;
371 if (std::isfinite(aDuration)) {
372 aDuration *= valuePortion;
375 startForReversingTest = oldTransition->ToValue();
376 reversePortion = valuePortion;
379 TimingParams timing = TimingParamsFromCSSParams(
380 aDuration, aDelay, 1.0 /* iteration count */,
381 StyleAnimationDirection::Normal, StyleAnimationFillMode::Backwards);
383 const StyleComputedTimingFunction& tf =
384 aStyle.GetTransitionTimingFunction(aTransitionIndex);
385 if (!tf.IsLinearKeyword()) {
386 timing.SetTimingFunction(Some(tf));
389 RefPtr<CSSTransition> transition = DoCreateTransition(
390 property, aElement, aPseudoType, aNewStyle, aElementTransitions,
391 std::move(timing), std::move(startValue), std::move(endValue),
392 std::move(startForReversingTest), reversePortion);
393 if (!transition) {
394 return false;
397 OwningCSSTransitionPtrArray& transitions = aElementTransitions->mAnimations;
398 #ifdef DEBUG
399 for (size_t i = 0, i_end = transitions.Length(); i < i_end; ++i) {
400 MOZ_ASSERT(
401 i == currentIndex || transitions[i]->TransitionProperty() != property,
402 "duplicate transitions for property");
404 #endif
405 if (oldTransition) {
406 // If this new transition is replacing an existing transition that is
407 // running on the compositor, we store select parameters from the replaced
408 // transition so that later, once all scripts have run, we can update the
409 // start value of the transition using TimeStamp::Now(). This allows us to
410 // avoid a large jump when starting a new transition when the main thread
411 // lags behind the compositor.
412 const dom::DocumentTimeline* timeline = aElement->OwnerDoc()->Timeline();
413 auto replacedTransitionProperties =
414 GetReplacedTransitionProperties(oldTransition, timeline);
415 if (replacedTransitionProperties) {
416 transition->SetReplacedTransition(
417 std::move(replacedTransitionProperties.ref()));
420 transitions[currentIndex]->CancelFromStyle(PostRestyleMode::IfNeeded);
421 oldTransition = nullptr; // Clear pointer so it doesn't dangle
422 transitions[currentIndex] = transition;
423 } else {
424 // XXX(Bug 1631371) Check if this should use a fallible operation as it
425 // pretended earlier.
426 transitions.AppendElement(transition);
429 if (auto* effectSet = EffectSet::Get(aElement, aPseudoType)) {
430 effectSet->UpdateAnimationGeneration(mPresContext);
433 return true;
436 already_AddRefed<CSSTransition> nsTransitionManager::DoCreateTransition(
437 const AnimatedPropertyID& aProperty, dom::Element* aElement,
438 PseudoStyleType aPseudoType, const mozilla::ComputedStyle& aNewStyle,
439 CSSTransitionCollection*& aElementTransitions, TimingParams&& aTiming,
440 AnimationValue&& aStartValue, AnimationValue&& aEndValue,
441 AnimationValue&& aStartForReversingTest, double aReversePortion) {
442 dom::DocumentTimeline* timeline = aElement->OwnerDoc()->Timeline();
443 KeyframeEffectParams effectOptions;
444 RefPtr<KeyframeEffect> keyframeEffect = new KeyframeEffect(
445 aElement->OwnerDoc(), OwningAnimationTarget(aElement, aPseudoType),
446 std::move(aTiming), effectOptions);
448 keyframeEffect->SetKeyframes(
449 GetTransitionKeyframes(aProperty, std::move(aStartValue),
450 std::move(aEndValue)),
451 &aNewStyle, timeline);
453 if (NS_WARN_IF(MOZ_UNLIKELY(!keyframeEffect->IsValidTransition()))) {
454 return nullptr;
457 RefPtr<CSSTransition> animation =
458 new CSSTransition(mPresContext->Document()->GetScopeObject(), aProperty);
459 animation->SetOwningElement(OwningElementRef(*aElement, aPseudoType));
460 animation->SetTimelineNoUpdate(timeline);
461 animation->SetCreationSequence(
462 mPresContext->RestyleManager()->GetAnimationGeneration());
463 animation->SetEffectFromStyle(keyframeEffect);
464 animation->SetReverseParameters(std::move(aStartForReversingTest),
465 aReversePortion);
466 animation->PlayFromStyle();
468 if (!aElementTransitions) {
469 aElementTransitions =
470 &aElement->EnsureAnimationData().EnsureTransitionCollection(
471 *aElement, aPseudoType);
472 if (!aElementTransitions->isInList()) {
473 AddElementCollection(aElementTransitions);
476 return animation.forget();
479 void nsTransitionManager::DoCancelTransition(
480 dom::Element* aElement, PseudoStyleType aPseudoType,
481 CSSTransitionCollection*& aElementTransitions, size_t aIndex) {
482 MOZ_ASSERT(aElementTransitions);
483 OwningCSSTransitionPtrArray& transitions = aElementTransitions->mAnimations;
484 CSSTransition* transition = transitions[aIndex];
486 if (transition->HasCurrentEffect()) {
487 if (auto* effectSet = EffectSet::Get(aElement, aPseudoType)) {
488 effectSet->UpdateAnimationGeneration(mPresContext);
491 transition->CancelFromStyle(PostRestyleMode::IfNeeded);
492 transitions.RemoveElementAt(aIndex);
494 if (transitions.IsEmpty()) {
495 aElementTransitions->Destroy();
496 // |aElementTransitions| is now a dangling pointer!
497 aElementTransitions = nullptr;