File: AnimationEffect.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (462 lines) | stat: -rw-r--r-- 16,924 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
 * Copyright (C) 2017-2018 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "AnimationEffect.h"

#include "CSSAnimation.h"
#include "CSSNumericFactory.h"
#include "CSSNumericValue.h"
#include "CSSParserContext.h"
#include "CSSPropertyParserConsumer+Easing.h"
#include "CommonAtomStrings.h"
#include "FillMode.h"
#include "JSComputedEffectTiming.h"
#include "ScriptExecutionContext.h"
#include "ScrollTimeline.h"
#include "WebAnimation.h"
#include "WebAnimationUtilities.h"
#include <wtf/TZoneMallocInlines.h>

namespace WebCore {

WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(AnimationEffect);

AnimationEffect::AnimationEffect() = default;

AnimationEffect::~AnimationEffect() = default;

void AnimationEffect::setAnimation(WebAnimation* animation)
{
    if (m_animation == animation)
        return;

    m_animation = animation;
    m_timingDidMutate = true;
}

EffectTiming AnimationEffect::getBindingsTiming() const
{
    if (auto* styleOriginatedAnimation = dynamicDowncast<StyleOriginatedAnimation>(animation()))
        styleOriginatedAnimation->flushPendingStyleChanges();

    EffectTiming timing;
    timing.delay = secondsToWebAnimationsAPITime(m_timing.specifiedStartDelay);
    timing.endDelay = secondsToWebAnimationsAPITime(m_timing.specifiedEndDelay);
    timing.fill = m_timing.fill;
    timing.iterationStart = m_timing.iterationStart;
    timing.iterations = m_timing.iterations;
    if (auto specifiedDuration = m_timing.specifiedIterationDuration)
        timing.duration = secondsToWebAnimationsAPITime(*specifiedDuration);
    else
        timing.duration = autoAtom();
    timing.direction = m_timing.direction;
    timing.easing = m_timing.timingFunction->cssText();
    return timing;
}

AnimationEffectTiming::ResolutionData AnimationEffect::resolutionData(std::optional<WebAnimationTime> startTime) const
{
    if (!m_animation)
        return { };

    RefPtr animation = m_animation.get();
    RefPtr timeline = animation->timeline();
    return {
        timeline ? timeline->currentTime() : std::nullopt,
        timeline ? timeline->duration() : std::nullopt,
        startTime ? startTime : animation->startTime(),
        animation->currentTime(startTime),
        animation->playbackRate()
    };
}

BasicEffectTiming AnimationEffect::getBasicTiming(std::optional<WebAnimationTime> startTime)
{
    updateComputedTimingPropertiesIfNeeded();
    return m_timing.getBasicTiming(resolutionData(startTime));
}

ComputedEffectTiming AnimationEffect::getBindingsComputedTiming()
{
    if (auto* styleOriginatedAnimation = dynamicDowncast<StyleOriginatedAnimation>(animation()))
        styleOriginatedAnimation->flushPendingStyleChanges();
    return getComputedTiming();
}

ComputedEffectTiming AnimationEffect::getComputedTiming(std::optional<WebAnimationTime> startTime)
{
    updateComputedTimingPropertiesIfNeeded();

    auto data = resolutionData(startTime);
    auto resolvedTiming = m_timing.resolve(data);

    // https://drafts.csswg.org/web-animations-2/#dom-animationeffect-getcomputedtiming
    // The description of the duration attribute of the object needs to indicate that if timing.duration
    // is the string auto, this attribute will return the current calculated value of the intrinsic iteration
    // duration, which may be a expressed as a double representing the duration in milliseconds or a percentage
    // when the effect is associated with a progress-based timeline.
    auto computedDuration = [&]() -> DoubleOrCSSNumericValueOrString {
        auto& duration = m_timing.specifiedIterationDuration ? m_timing.iterationDuration : m_timing.intrinsicIterationDuration;
        if (auto percent = duration.percentage())
            return CSSNumericFactory::percent(*percent);
        ASSERT(duration.time());
        return secondsToWebAnimationsAPITime(*duration.time());
    }();

    ComputedEffectTiming computedTiming;
    computedTiming.delay = secondsToWebAnimationsAPITime(m_timing.specifiedStartDelay);
    computedTiming.endDelay = secondsToWebAnimationsAPITime(m_timing.specifiedEndDelay);
    computedTiming.fill = m_timing.fill == FillMode::Auto ? FillMode::None : m_timing.fill;
    computedTiming.iterationStart = m_timing.iterationStart;
    computedTiming.iterations = m_timing.iterations;
    computedTiming.duration = computedDuration;
    computedTiming.direction = m_timing.direction;
    computedTiming.easing = m_timing.timingFunction->cssText();
    computedTiming.endTime = m_timing.endTime;
    computedTiming.activeDuration = m_timing.activeDuration;
    computedTiming.localTime = data.localTime;
    computedTiming.simpleIterationProgress = resolvedTiming.simpleIterationProgress;
    computedTiming.progress = resolvedTiming.transformedProgress;
    computedTiming.currentIteration = resolvedTiming.currentIteration;
    computedTiming.phase = resolvedTiming.phase;
    computedTiming.before = resolvedTiming.before;
    return computedTiming;
}

ExceptionOr<void> AnimationEffect::bindingsUpdateTiming(Document& document, std::optional<OptionalEffectTiming> timing)
{
    auto retVal = updateTiming(document, timing);
    if (!retVal.hasException() && timing) {
        if (auto* cssAnimation = dynamicDowncast<CSSAnimation>(animation()))
            cssAnimation->effectTimingWasUpdatedUsingBindings(*timing);
    }
    return retVal;
}

ExceptionOr<void> AnimationEffect::updateTiming(Document& document, std::optional<OptionalEffectTiming> timing)
{
    // 6.5.4. Updating the timing of an AnimationEffect
    // https://drafts.csswg.org/web-animations/#updating-animationeffect-timing

    // To update the timing properties of an animation effect, effect, from an EffectTiming or OptionalEffectTiming object, input, perform the following steps:
    if (!timing)
        return { };

    // 1. If the iterationStart member of input is present and less than zero, throw a TypeError and abort this procedure.
    if (timing->iterationStart) {
        if (timing->iterationStart.value() < 0)
            return Exception { ExceptionCode::TypeError };
    }

    // 2. If the iterations member of input is present, and less than zero or is the value NaN, throw a TypeError and abort this procedure.
    if (timing->iterations) {
        if (timing->iterations.value() < 0 || std::isnan(timing->iterations.value()))
            return Exception { ExceptionCode::TypeError };
    }

    // 3. If the duration member of input is present, and less than zero or is the value NaN, throw a TypeError and abort this procedure.
    // FIXME: should it not throw an exception on a string other than "auto"?
    if (timing->duration) {
        if (std::holds_alternative<double>(timing->duration.value())) {
            auto durationAsDouble = std::get<double>(timing->duration.value());
            if (durationAsDouble < 0 || std::isnan(durationAsDouble))
                return Exception { ExceptionCode::TypeError };
        } else {
            if (std::get<String>(timing->duration.value()) != autoAtom())
                return Exception { ExceptionCode::TypeError };
        }
    }

    if (auto iterations = timing->iterations) {
        // https://github.com/w3c/csswg-drafts/issues/11343
        if (std::isinf(*iterations)) {
            if (RefPtr animation = m_animation.get()) {
                if (RefPtr timeline = animation->timeline()) {
                    if (timeline->isProgressBased())
                        return Exception { ExceptionCode::TypeError, "The number of iterations cannot be set to Infinity for progress-based animations"_s };
                }
            }
        }
    }

    // 4. If the easing member of input is present but cannot be parsed using the <timing-function> production [CSS-EASING-1], throw a TypeError and abort this procedure.
    if (!timing->easing.isNull()) {
        CSSParserContext parsingContext(document);
        // FIXME: Determine the how calc() and relative units should be resolved and switch to the non-deprecated parsing function.
        auto timingFunctionResult = CSSPropertyParserHelpers::parseEasingFunctionDeprecated(timing->easing, parsingContext);
        if (!timingFunctionResult)
            return Exception { ExceptionCode::TypeError };
        setTimingFunction(WTFMove(timingFunctionResult));
    }

    // 5. Assign each member present in input to the corresponding timing property of effect as follows:
    //
    //    delay → start delay
    //    endDelay → end delay
    //    fill → fill mode
    //    iterationStart → iteration start
    //    iterations → iteration count
    //    duration → iteration duration
    //    direction → playback direction
    //    easing → timing function

    if (auto delay = timing->delay)
        setDelay(Seconds::fromMilliseconds(*delay));

    if (auto endDelay = timing->endDelay)
        setEndDelay(Seconds::fromMilliseconds(*endDelay));

    if (auto fill = timing->fill)
        setFill(*fill);

    if (auto iterationStart = timing->iterationStart)
        setIterationStart(*iterationStart);

    if (auto iterations = timing->iterations)
        setIterations(*iterations);

    if (auto duration = timing->duration) {
        if (auto* durationDouble = std::get_if<double>(&*duration))
            setIterationDuration(Seconds::fromMilliseconds(*durationDouble));
        else
            setIterationDuration(std::nullopt);
    }

    if (auto direction = timing->direction)
        setDirection(*direction);

    if (m_animation)
        m_animation->effectTimingDidChange();

    return { };
}

ExceptionOr<void> AnimationEffect::setIterationStart(double iterationStart)
{
    // https://drafts.csswg.org/web-animations-1/#dom-animationeffecttiming-iterationstart
    // If an attempt is made to set this attribute to a value less than zero, a TypeError must
    // be thrown and the value of the iterationStart attribute left unchanged.
    if (iterationStart < 0)
        return Exception { ExceptionCode::TypeError };

    if (m_timing.iterationStart == iterationStart)
        return { };

    m_timing.iterationStart = iterationStart;

    return { };
}

ExceptionOr<void> AnimationEffect::setIterations(double iterations)
{
    // https://drafts.csswg.org/web-animations-1/#dom-animationeffecttiming-iterations
    // If an attempt is made to set this attribute to a value less than zero or a NaN value, a
    // TypeError must be thrown and the value of the iterations attribute left unchanged.
    if (iterations < 0 || std::isnan(iterations))
        return Exception { ExceptionCode::TypeError };

    if (m_timing.iterations == iterations)
        return { };
        
    m_timing.iterations = iterations;
    m_timingDidMutate = true;

    return { };
}

WebAnimationTime AnimationEffect::delay()
{
    updateComputedTimingPropertiesIfNeeded();
    return m_timing.startDelay;
}

void AnimationEffect::setDelay(const Seconds& delay)
{
    if (m_timing.specifiedStartDelay == delay)
        return;

    m_timing.specifiedStartDelay = delay;
    m_timingDidMutate = true;
}

WebAnimationTime AnimationEffect::endDelay()
{
    updateComputedTimingPropertiesIfNeeded();
    return m_timing.endDelay;
}

void AnimationEffect::setEndDelay(const Seconds& endDelay)
{
    if (m_timing.specifiedEndDelay == endDelay)
        return;

    m_timing.specifiedEndDelay = endDelay;
    m_timingDidMutate = true;
}

void AnimationEffect::setFill(FillMode fill)
{
    if (m_timing.fill == fill)
        return;

    m_timing.fill = fill;
}

WebAnimationTime AnimationEffect::iterationDuration()
{
    updateComputedTimingPropertiesIfNeeded();
    return m_timing.iterationDuration;
}

void AnimationEffect::setIterationDuration(const std::optional<Seconds>& duration)
{
    if (m_timing.specifiedIterationDuration == duration)
        return;

    m_timing.specifiedIterationDuration = duration;
    m_timingDidMutate = true;
}

void AnimationEffect::setDirection(PlaybackDirection direction)
{
    if (m_timing.direction == direction)
        return;

    m_timing.direction = direction;
}

void AnimationEffect::setTimingFunction(const RefPtr<TimingFunction>& timingFunction)
{
    m_timing.timingFunction = timingFunction;
}

WebAnimationTime AnimationEffect::activeDuration()
{
    updateComputedTimingPropertiesIfNeeded();
    return m_timing.activeDuration;
}

WebAnimationTime AnimationEffect::endTime()
{
    updateComputedTimingPropertiesIfNeeded();
    return m_timing.endTime;
}

std::optional<double> AnimationEffect::progressUntilNextStep(double iterationProgress) const
{
    RefPtr stepsTimingFunction = dynamicDowncast<StepsTimingFunction>(m_timing.timingFunction);
    if (!stepsTimingFunction)
        return std::nullopt;

    auto numberOfSteps = stepsTimingFunction->numberOfSteps();
    auto nextStepProgress = ceil(iterationProgress * numberOfSteps) / numberOfSteps;
    return nextStepProgress - iterationProgress;
}

Seconds AnimationEffect::timeToNextTick(const BasicEffectTiming& timing)
{
    switch (timing.phase) {
    case AnimationEffectPhase::Before:
        // The effect is in its "before" phase, in this case we can wait until it enters its "active" phase.
        return delay() - *timing.localTime;
    case AnimationEffectPhase::Active: {
        if (!ticksContinuouslyWhileActive())
            return endTime() - *timing.localTime;
        if (auto iterationProgress = getComputedTiming().simpleIterationProgress) {
            // In case we're in a range that uses a steps() timing function, we can compute the time until the next step starts.
            if (auto progressUntilNextStep = this->progressUntilNextStep(*iterationProgress))
                return iterationDuration() * *progressUntilNextStep;
        }
        // Other effects that continuously tick in the "active" phase will need to update their animated
        // progress at the immediate next opportunity.
        return 0_s;
    }
    case AnimationEffectPhase::After:
        // The effect is in its after phase, which means it will no longer update its progress, so it doens't need a tick.
        return Seconds::infinity();
    case AnimationEffectPhase::Idle:
        ASSERT_NOT_REACHED();
        return Seconds::infinity();
    }

    ASSERT_NOT_REACHED();
    return Seconds::infinity();
}

void AnimationEffect::animationTimelineDidChange(const AnimationTimeline*)
{
    m_timingDidMutate = true;
}

void AnimationEffect::animationPlaybackRateDidChange()
{
    m_timingDidMutate = true;
}

void AnimationEffect::animationProgressBasedTimelineSourceDidChangeMetrics(const TimelineRange& animationAttachmentRange)
{
    if (!animationAttachmentRange.isDefault())
        m_timingDidMutate = true;
}

void AnimationEffect::animationRangeDidChange()
{
    m_timingDidMutate = true;
}

void AnimationEffect::updateComputedTimingPropertiesIfNeeded()
{
    if (!m_timingDidMutate)
        return;

    m_timingDidMutate = false;

    auto playbackRate = [&] {
        if (m_animation)
            return m_animation->playbackRate();
        return 1.0;
    }();

    auto rangeDuration = [&] -> std::optional<WebAnimationTime> {
        if (!m_animation)
            return std::nullopt;

        RefPtr timeline = m_animation->timeline();
        if (!timeline)
            return std::nullopt;

        if (RefPtr scrollTimeline = dynamicDowncast<ScrollTimeline>(timeline)) {
            auto interval = scrollTimeline->intervalForAttachmentRange(m_animation->range());
            return interval.second - interval.first;
        }

        return timeline->duration();
    }();

    m_timing.updateComputedProperties(rangeDuration, playbackRate);
}

} // namespace WebCore