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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Animation.h"
#include "AnimationUtils.h"
#include "mozAutoDocUpdate.h"
#include "mozilla/dom/AnimationBinding.h"
#include "mozilla/dom/AnimationPlaybackEvent.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/DocumentTimeline.h"
#include "mozilla/dom/MutationObservers.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/AnimationEventDispatcher.h"
#include "mozilla/AnimationTarget.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/DeclarationBlock.h"
#include "mozilla/Maybe.h" // For Maybe
#include "mozilla/StaticPrefs_dom.h"
#include "nsAnimationManager.h" // For CSSAnimation
#include "nsComputedDOMStyle.h"
#include "nsDOMMutationObserver.h" // For nsAutoAnimationMutationBatch
#include "nsDOMCSSAttrDeclaration.h" // For nsDOMCSSAttributeDeclaration
#include "nsThreadUtils.h" // For nsRunnableMethod and nsRevocableEventPtr
#include "nsTransitionManager.h" // For CSSTransition
#include "PendingAnimationTracker.h" // For PendingAnimationTracker
#include "ScrollTimelineAnimationTracker.h"
namespace mozilla::dom {
// Static members
uint64_t Animation::sNextAnimationIndex = 0;
NS_IMPL_CYCLE_COLLECTION_INHERITED(Animation, DOMEventTargetHelper, mTimeline,
mEffect, mReady, mFinished)
NS_IMPL_ADDREF_INHERITED(Animation, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(Animation, DOMEventTargetHelper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Animation)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
JSObject* Animation::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return dom::Animation_Binding::Wrap(aCx, this, aGivenProto);
}
// ---------------------------------------------------------------------------
//
// Utility methods
//
// ---------------------------------------------------------------------------
namespace {
// A wrapper around nsAutoAnimationMutationBatch that looks up the
// appropriate document from the supplied animation.
class MOZ_RAII AutoMutationBatchForAnimation {
public:
explicit AutoMutationBatchForAnimation(const Animation& aAnimation) {
NonOwningAnimationTarget target = aAnimation.GetTargetForAnimation();
if (!target) {
return;
}
// For mutation observers, we use the OwnerDoc.
mAutoBatch.emplace(target.mElement->OwnerDoc());
}
private:
Maybe<nsAutoAnimationMutationBatch> mAutoBatch;
};
} // namespace
// ---------------------------------------------------------------------------
//
// Animation interface:
//
// ---------------------------------------------------------------------------
Animation::Animation(nsIGlobalObject* aGlobal)
: DOMEventTargetHelper(aGlobal),
mAnimationIndex(sNextAnimationIndex++),
mRTPCallerType(aGlobal->GetRTPCallerType()) {}
Animation::~Animation() = default;
/* static */
already_AddRefed<Animation> Animation::ClonePausedAnimation(
nsIGlobalObject* aGlobal, const Animation& aOther, AnimationEffect& aEffect,
AnimationTimeline& aTimeline) {
// FIXME: Bug 1805950: Support printing for scroll-timeline once we resolve
// the spec issue.
if (aOther.UsingScrollTimeline()) {
return nullptr;
}
RefPtr<Animation> animation = new Animation(aGlobal);
// Setup the timeline. We always use document-timeline of the new document,
// even if the timeline of |aOther| is null.
animation->mTimeline = &aTimeline;
// Setup the playback rate.
animation->mPlaybackRate = aOther.mPlaybackRate;
// Setup the timing.
const Nullable<TimeDuration> currentTime = aOther.GetCurrentTimeAsDuration();
if (!aOther.GetTimeline()) {
// This simulates what we do in SetTimelineNoUpdate(). It's possible to
// preserve the progress if the previous timeline is a scroll-timeline.
// So for null timeline, it may have a progress and the non-null current
// time.
if (!currentTime.IsNull()) {
animation->SilentlySetCurrentTime(currentTime.Value());
}
animation->mPreviousCurrentTime = animation->GetCurrentTimeAsDuration();
} else {
animation->mHoldTime = currentTime;
if (!currentTime.IsNull()) {
// FIXME: Should we use |timelineTime| as previous current time here? It
// seems we should use animation->GetCurrentTimeAsDuration(), per
// UpdateFinishedState().
const Nullable<TimeDuration> timelineTime =
aTimeline.GetCurrentTimeAsDuration();
MOZ_ASSERT(!timelineTime.IsNull(), "Timeline not yet set");
animation->mPreviousCurrentTime = timelineTime;
}
}
// Setup the effect's link to this.
animation->mEffect = &aEffect;
animation->mEffect->SetAnimation(animation);
animation->mPendingState = PendingState::PausePending;
Document* doc = animation->GetRenderedDocument();
MOZ_ASSERT(doc,
"Cloning animation should already have the rendered document");
PendingAnimationTracker* tracker = doc->GetOrCreatePendingAnimationTracker();
tracker->AddPausePending(*animation);
// We expect our relevance to be the same as the orginal.
animation->mIsRelevant = aOther.mIsRelevant;
animation->PostUpdate();
animation->mTimeline->NotifyAnimationUpdated(*animation);
return animation.forget();
}
NonOwningAnimationTarget Animation::GetTargetForAnimation() const {
AnimationEffect* effect = GetEffect();
NonOwningAnimationTarget target;
if (!effect || !effect->AsKeyframeEffect()) {
return target;
}
return effect->AsKeyframeEffect()->GetAnimationTarget();
}
/* static */
already_AddRefed<Animation> Animation::Constructor(
const GlobalObject& aGlobal, AnimationEffect* aEffect,
const Optional<AnimationTimeline*>& aTimeline, ErrorResult& aRv) {
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
AnimationTimeline* timeline;
Document* document =
AnimationUtils::GetCurrentRealmDocument(aGlobal.Context());
if (aTimeline.WasPassed()) {
timeline = aTimeline.Value();
} else {
if (!document) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
timeline = document->Timeline();
}
RefPtr<Animation> animation = new Animation(global);
animation->SetTimelineNoUpdate(timeline);
animation->SetEffectNoUpdate(aEffect);
return animation.forget();
}
void Animation::SetId(const nsAString& aId) {
if (mId == aId) {
return;
}
mId = aId;
MutationObservers::NotifyAnimationChanged(this);
}
void Animation::SetEffect(AnimationEffect* aEffect) {
SetEffectNoUpdate(aEffect);
PostUpdate();
}
// https://drafts.csswg.org/web-animations/#setting-the-target-effect
void Animation::SetEffectNoUpdate(AnimationEffect* aEffect) {
RefPtr<Animation> kungFuDeathGrip(this);
if (mEffect == aEffect) {
return;
}
AutoMutationBatchForAnimation mb(*this);
bool wasRelevant = mIsRelevant;
if (mEffect) {
// We need to notify observers now because once we set mEffect to null
// we won't be able to find the target element to notify.
if (mIsRelevant) {
MutationObservers::NotifyAnimationRemoved(this);
}
// Break links with the old effect and then drop it.
RefPtr<AnimationEffect> oldEffect = mEffect;
mEffect = nullptr;
if (IsPartialPrerendered()) {
if (KeyframeEffect* oldKeyframeEffect = oldEffect->AsKeyframeEffect()) {
oldKeyframeEffect->ResetPartialPrerendered();
}
}
oldEffect->SetAnimation(nullptr);
// The following will not do any notification because mEffect is null.
UpdateRelevance();
}
if (aEffect) {
// Break links from the new effect to its previous animation, if any.
RefPtr<AnimationEffect> newEffect = aEffect;
Animation* prevAnim = aEffect->GetAnimation();
if (prevAnim) {
prevAnim->SetEffect(nullptr);
}
// Create links with the new effect. SetAnimation(this) will also update
// mIsRelevant of this animation, and then notify mutation observer if
// needed by calling Animation::UpdateRelevance(), so we don't need to
// call it again.
mEffect = newEffect;
mEffect->SetAnimation(this);
// Notify possible add or change.
// If the target is different, the change notification will be ignored by
// AutoMutationBatchForAnimation.
if (wasRelevant && mIsRelevant) {
MutationObservers::NotifyAnimationChanged(this);
}
ReschedulePendingTasks();
}
MaybeScheduleReplacementCheck();
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
}
void Animation::SetTimeline(AnimationTimeline* aTimeline) {
SetTimelineNoUpdate(aTimeline);
PostUpdate();
}
// https://drafts.csswg.org/web-animations/#setting-the-timeline
void Animation::SetTimelineNoUpdate(AnimationTimeline* aTimeline) {
if (mTimeline == aTimeline) {
return;
}
StickyTimeDuration activeTime =
mEffect ? mEffect->GetComputedTiming().mActiveTime : StickyTimeDuration();
const AnimationPlayState previousPlayState = PlayState();
const Nullable<TimeDuration> previousCurrentTime = GetCurrentTimeAsDuration();
// FIXME: The definition of end time in web-animation-1 is different from that
// in web-animation-2, which includes the start time. We are still using the
// definition in web-animation-1 here for now.
const TimeDuration endTime = TimeDuration(EffectEnd());
double previousProgress = 0.0;
if (!previousCurrentTime.IsNull() && !endTime.IsZero()) {
previousProgress =
previousCurrentTime.Value().ToSeconds() / endTime.ToSeconds();
}
RefPtr<AnimationTimeline> oldTimeline = mTimeline;
if (oldTimeline) {
oldTimeline->RemoveAnimation(this);
}
mTimeline = aTimeline;
mResetCurrentTimeOnResume = false;
if (mEffect) {
mEffect->UpdateNormalizedTiming();
}
if (mTimeline && !mTimeline->IsMonotonicallyIncreasing()) {
// If "to finite timeline" is true.
ApplyPendingPlaybackRate();
Nullable<TimeDuration> seekTime;
if (mPlaybackRate >= 0.0) {
seekTime.SetValue(TimeDuration());
} else {
seekTime.SetValue(TimeDuration(EffectEnd()));
}
switch (previousPlayState) {
case AnimationPlayState::Running:
case AnimationPlayState::Finished:
mStartTime = seekTime;
break;
case AnimationPlayState::Paused:
if (!previousCurrentTime.IsNull()) {
mResetCurrentTimeOnResume = true;
mStartTime.SetNull();
mHoldTime.SetValue(
TimeDuration(EffectEnd().MultDouble(previousProgress)));
} else {
mStartTime = seekTime;
}
break;
case AnimationPlayState::Idle:
default:
break;
}
} else if (oldTimeline && !oldTimeline->IsMonotonicallyIncreasing() &&
!previousCurrentTime.IsNull()) {
// If "from finite timeline" and previous progress is resolved.
SetCurrentTimeNoUpdate(
TimeDuration(EffectEnd().MultDouble(previousProgress)));
}
if (!mStartTime.IsNull()) {
mHoldTime.SetNull();
}
if (!aTimeline) {
MaybeQueueCancelEvent(activeTime);
}
UpdatePendingAnimationTracker(oldTimeline, aTimeline);
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
// FIXME: Bug 1799071: Check if we need to add
// MutationObservers::NotifyAnimationChanged(this) here.
}
// https://drafts.csswg.org/web-animations/#set-the-animation-start-time
void Animation::SetStartTime(const Nullable<TimeDuration>& aNewStartTime) {
// Return early if the start time will not change. However, if we
// are pending, then setting the start time to any value
// including the current value has the effect of aborting
// pending tasks so we should not return early in that case.
if (!Pending() && aNewStartTime == mStartTime) {
return;
}
AutoMutationBatchForAnimation mb(*this);
Nullable<TimeDuration> timelineTime;
if (mTimeline) {
// The spec says to check if the timeline is active (has a resolved time)
// before using it here, but we don't need to since it's harmless to set
// the already null time to null.
timelineTime = mTimeline->GetCurrentTimeAsDuration();
}
if (timelineTime.IsNull() && !aNewStartTime.IsNull()) {
mHoldTime.SetNull();
}
Nullable<TimeDuration> previousCurrentTime = GetCurrentTimeAsDuration();
ApplyPendingPlaybackRate();
mStartTime = aNewStartTime;
mResetCurrentTimeOnResume = false;
if (!aNewStartTime.IsNull()) {
if (mPlaybackRate != 0.0) {
mHoldTime.SetNull();
}
} else {
mHoldTime = previousCurrentTime;
}
CancelPendingTasks();
if (mReady) {
// We may have already resolved mReady, but in that case calling
// MaybeResolve is a no-op, so that's okay.
mReady->MaybeResolve(this);
}
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
PostUpdate();
}
// https://drafts.csswg.org/web-animations/#current-time
Nullable<TimeDuration> Animation::GetCurrentTimeForHoldTime(
const Nullable<TimeDuration>& aHoldTime) const {
Nullable<TimeDuration> result;
if (!aHoldTime.IsNull()) {
result = aHoldTime;
return result;
}
if (mTimeline && !mStartTime.IsNull()) {
Nullable<TimeDuration> timelineTime = mTimeline->GetCurrentTimeAsDuration();
if (!timelineTime.IsNull()) {
result = CurrentTimeFromTimelineTime(timelineTime.Value(),
mStartTime.Value(), mPlaybackRate);
}
}
return result;
}
// https://drafts.csswg.org/web-animations/#set-the-current-time
void Animation::SetCurrentTime(const TimeDuration& aSeekTime) {
// Return early if the current time has not changed. However, if we
// are pause-pending, then setting the current time to any value
// including the current value has the effect of aborting the
// pause so we should not return early in that case.
if (mPendingState != PendingState::PausePending &&
Nullable<TimeDuration>(aSeekTime) == GetCurrentTimeAsDuration()) {
return;
}
AutoMutationBatchForAnimation mb(*this);
SetCurrentTimeNoUpdate(aSeekTime);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
PostUpdate();
}
void Animation::SetCurrentTimeNoUpdate(const TimeDuration& aSeekTime) {
SilentlySetCurrentTime(aSeekTime);
if (mPendingState == PendingState::PausePending) {
// Finish the pause operation
mHoldTime.SetValue(aSeekTime);
ApplyPendingPlaybackRate();
mStartTime.SetNull();
if (mReady) {
mReady->MaybeResolve(this);
}
CancelPendingTasks();
}
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Async);
}
// https://drafts.csswg.org/web-animations/#set-the-playback-rate
void Animation::SetPlaybackRate(double aPlaybackRate) {
mPendingPlaybackRate.reset();
if (aPlaybackRate == mPlaybackRate) {
return;
}
AutoMutationBatchForAnimation mb(*this);
Nullable<TimeDuration> previousTime = GetCurrentTimeAsDuration();
mPlaybackRate = aPlaybackRate;
if (!previousTime.IsNull()) {
SetCurrentTime(previousTime.Value());
}
// In the case where GetCurrentTimeAsDuration() returns the same result before
// and after updating mPlaybackRate, SetCurrentTime will return early since,
// as far as it can tell, nothing has changed.
// As a result, we need to perform the following updates here:
// - update timing (since, if the sign of the playback rate has changed, our
// finished state may have changed),
// - dispatch a change notification for the changed playback rate, and
// - update the playback rate on animations on layers.
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
PostUpdate();
}
// https://drafts.csswg.org/web-animations/#seamlessly-update-the-playback-rate
void Animation::UpdatePlaybackRate(double aPlaybackRate) {
if (mPendingPlaybackRate && mPendingPlaybackRate.value() == aPlaybackRate) {
return;
}
// Calculate the play state using the existing playback rate since below we
// want to know if the animation is _currently_ finished or not, not whether
// it _will_ be finished.
AnimationPlayState playState = PlayState();
mPendingPlaybackRate = Some(aPlaybackRate);
if (Pending()) {
// If we already have a pending task, there is nothing more to do since the
// playback rate will be applied then.
//
// However, as with the idle/paused case below, we still need to update the
// relevance (and effect set to make sure it only contains relevant
// animations) since the relevance is based on the Animation play state
// which incorporates the _pending_ playback rate.
UpdateEffect(PostRestyleMode::Never);
return;
}
AutoMutationBatchForAnimation mb(*this);
if (playState == AnimationPlayState::Idle ||
playState == AnimationPlayState::Paused ||
GetCurrentTimeAsDuration().IsNull()) {
// If |previous play state| is idle or paused, or the current time is
// unresolved, we apply any pending playback rate on animation immediately.
ApplyPendingPlaybackRate();
// We don't need to update timing or post an update here because:
//
// * the current time hasn't changed -- it's either unresolved or fixed
// with a hold time -- so the output won't have changed
// * the finished state won't have changed even if the sign of the
// playback rate changed since we're not finished (we're paused or idle)
// * the playback rate on layers doesn't need to be updated since we're not
// moving. Once we get a start time etc. we'll update the playback rate
// then.
//
// However we still need to update the relevance and effect set as well as
// notifying observers.
UpdateEffect(PostRestyleMode::Never);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
} else if (playState == AnimationPlayState::Finished) {
MOZ_ASSERT(mTimeline && !mTimeline->GetCurrentTimeAsDuration().IsNull(),
"If we have no active timeline, we should be idle or paused");
if (aPlaybackRate != 0) {
// The unconstrained current time can only be unresolved if either we
// don't have an active timeline (and we already asserted that is not
// true) or we have an unresolved start time (in which case we should be
// paused).
MOZ_ASSERT(!GetUnconstrainedCurrentTime().IsNull(),
"Unconstrained current time should be resolved");
TimeDuration unconstrainedCurrentTime =
GetUnconstrainedCurrentTime().Value();
TimeDuration timelineTime = mTimeline->GetCurrentTimeAsDuration().Value();
mStartTime = StartTimeFromTimelineTime(
timelineTime, unconstrainedCurrentTime, aPlaybackRate);
} else {
mStartTime = mTimeline->GetCurrentTimeAsDuration();
}
ApplyPendingPlaybackRate();
// Even though we preserve the current time, we might now leave the finished
// state (e.g. if the playback rate changes sign) so we need to update
// timing.
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
PostUpdate();
} else {
ErrorResult rv;
Play(rv, LimitBehavior::Continue);
MOZ_ASSERT(!rv.Failed(),
"We should only fail to play when using auto-rewind behavior");
}
}
// https://drafts.csswg.org/web-animations/#play-state
AnimationPlayState Animation::PlayState() const {
Nullable<TimeDuration> currentTime = GetCurrentTimeAsDuration();
if (currentTime.IsNull() && mStartTime.IsNull() && !Pending()) {
return AnimationPlayState::Idle;
}
if (mPendingState == PendingState::PausePending ||
(mStartTime.IsNull() && !Pending())) {
return AnimationPlayState::Paused;
}
double playbackRate = CurrentOrPendingPlaybackRate();
if (!currentTime.IsNull() &&
((playbackRate > 0.0 && currentTime.Value() >= EffectEnd()) ||
(playbackRate < 0.0 && currentTime.Value() <= TimeDuration()))) {
return AnimationPlayState::Finished;
}
return AnimationPlayState::Running;
}
Promise* Animation::GetReady(ErrorResult& aRv) {
nsCOMPtr<nsIGlobalObject> global = GetOwnerGlobal();
if (!mReady && global) {
mReady = Promise::Create(global, aRv); // Lazily create on demand
}
if (!mReady) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
if (!Pending()) {
mReady->MaybeResolve(this);
}
return mReady;
}
Promise* Animation::GetFinished(ErrorResult& aRv) {
nsCOMPtr<nsIGlobalObject> global = GetOwnerGlobal();
if (!mFinished && global) {
mFinished = Promise::Create(global, aRv); // Lazily create on demand
}
if (!mFinished) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
if (mFinishedIsResolved) {
MaybeResolveFinishedPromise();
}
return mFinished;
}
// https://drafts.csswg.org/web-animations/#cancel-an-animation
void Animation::Cancel(PostRestyleMode aPostRestyle) {
bool newlyIdle = false;
if (PlayState() != AnimationPlayState::Idle) {
newlyIdle = true;
ResetPendingTasks();
if (mFinished) {
mFinished->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
// mFinished can already be resolved.
MOZ_ALWAYS_TRUE(mFinished->SetAnyPromiseIsHandled());
}
ResetFinishedPromise();
QueuePlaybackEvent(u"cancel"_ns, GetTimelineCurrentTimeAsTimeStamp());
}
StickyTimeDuration activeTime =
mEffect ? mEffect->GetComputedTiming().mActiveTime : StickyTimeDuration();
mHoldTime.SetNull();
mStartTime.SetNull();
// Allow our effect to remove itself from the its target element's EffectSet.
UpdateEffect(aPostRestyle);
if (mTimeline) {
mTimeline->RemoveAnimation(this);
}
MaybeQueueCancelEvent(activeTime);
if (newlyIdle && aPostRestyle == PostRestyleMode::IfNeeded) {
PostUpdate();
}
}
// https://drafts.csswg.org/web-animations/#finish-an-animation
void Animation::Finish(ErrorResult& aRv) {
double effectivePlaybackRate = CurrentOrPendingPlaybackRate();
if (effectivePlaybackRate == 0) {
return aRv.ThrowInvalidStateError(
"Can't finish animation with zero playback rate");
}
if (effectivePlaybackRate > 0 && EffectEnd() == TimeDuration::Forever()) {
return aRv.ThrowInvalidStateError("Can't finish infinite animation");
}
AutoMutationBatchForAnimation mb(*this);
ApplyPendingPlaybackRate();
// Seek to the end
TimeDuration limit =
mPlaybackRate > 0 ? TimeDuration(EffectEnd()) : TimeDuration(0);
bool didChange = GetCurrentTimeAsDuration() != Nullable<TimeDuration>(limit);
SilentlySetCurrentTime(limit);
// If we are paused or play-pending we need to fill in the start time in
// order to transition to the finished state.
//
// We only do this, however, if we have an active timeline. If we have an
// inactive timeline we can't transition into the finished state just like
// we can't transition to the running state (this finished state is really
// a substate of the running state).
if (mStartTime.IsNull() && mTimeline &&
!mTimeline->GetCurrentTimeAsDuration().IsNull()) {
mStartTime = StartTimeFromTimelineTime(
mTimeline->GetCurrentTimeAsDuration().Value(), limit, mPlaybackRate);
didChange = true;
}
// If we just resolved the start time for a pause or play-pending
// animation, we need to clear the task. We don't do this as a branch of
// the above however since we can have a play-pending animation with a
// resolved start time if we aborted a pause operation.
if (!mStartTime.IsNull() && (mPendingState == PendingState::PlayPending ||
mPendingState == PendingState::PausePending)) {
if (mPendingState == PendingState::PausePending) {
mHoldTime.SetNull();
}
CancelPendingTasks();
didChange = true;
if (mReady) {
mReady->MaybeResolve(this);
}
}
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Sync);
if (didChange && IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
PostUpdate();
}
void Animation::Play(ErrorResult& aRv, LimitBehavior aLimitBehavior) {
PlayNoUpdate(aRv, aLimitBehavior);
PostUpdate();
}
// https://drafts.csswg.org/web-animations/#reverse-an-animation
void Animation::Reverse(ErrorResult& aRv) {
if (!mTimeline) {
return aRv.ThrowInvalidStateError(
"Can't reverse an animation with no associated timeline");
}
if (mTimeline->GetCurrentTimeAsDuration().IsNull()) {
return aRv.ThrowInvalidStateError(
"Can't reverse an animation associated with an inactive timeline");
}
double effectivePlaybackRate = CurrentOrPendingPlaybackRate();
if (effectivePlaybackRate == 0.0) {
return;
}
Maybe<double> originalPendingPlaybackRate = mPendingPlaybackRate;
mPendingPlaybackRate = Some(-effectivePlaybackRate);
Play(aRv, LimitBehavior::AutoRewind);
// If Play() threw, restore state and don't report anything to mutation
// observers.
if (aRv.Failed()) {
mPendingPlaybackRate = originalPendingPlaybackRate;
}
// Play(), above, unconditionally calls PostUpdate so we don't need to do
// it here.
}
void Animation::Persist() {
if (mReplaceState == AnimationReplaceState::Persisted) {
return;
}
bool wasRemoved = mReplaceState == AnimationReplaceState::Removed;
mReplaceState = AnimationReplaceState::Persisted;
// If the animation is not (yet) removed, there should be no side effects of
// persisting it.
if (wasRemoved) {
UpdateEffect(PostRestyleMode::IfNeeded);
PostUpdate();
}
}
// https://drafts.csswg.org/web-animations/#dom-animation-commitstyles
void Animation::CommitStyles(ErrorResult& aRv) {
if (!mEffect) {
return;
}
// Take an owning reference to the keyframe effect. This will ensure that
// this Animation and the target element remain alive after flushing style.
RefPtr<KeyframeEffect> keyframeEffect = mEffect->AsKeyframeEffect();
if (!keyframeEffect) {
return;
}
NonOwningAnimationTarget target = keyframeEffect->GetAnimationTarget();
if (!target) {
return;
}
if (target.mPseudoType != PseudoStyleType::NotPseudo) {
return aRv.ThrowNoModificationAllowedError(
"Can't commit styles of a pseudo-element");
}
// Check it is an element with a style attribute
RefPtr<nsStyledElement> styledElement =
nsStyledElement::FromNodeOrNull(target.mElement);
if (!styledElement) {
return aRv.ThrowNoModificationAllowedError(
"Target is not capable of having a style attribute");
}
// Hold onto a strong reference to the doc in case the flush destroys it.
RefPtr<Document> doc = target.mElement->GetComposedDoc();
// Flush frames before checking if the target element is rendered since the
// result could depend on pending style changes, and IsRendered() looks at the
// primary frame.
if (doc) {
doc->FlushPendingNotifications(FlushType::Frames);
}
if (!target.mElement->IsRendered()) {
return aRv.ThrowInvalidStateError("Target is not rendered");
}
nsPresContext* presContext =
nsContentUtils::GetContextForContent(target.mElement);
if (!presContext) {
return aRv.ThrowInvalidStateError("Target is not rendered");
}
// Get the computed animation values
UniquePtr<RawServoAnimationValueMap> animationValues =
Servo_AnimationValueMap_Create().Consume();
if (!presContext->EffectCompositor()->ComposeServoAnimationRuleForEffect(
*keyframeEffect, CascadeLevel(), animationValues.get())) {
NS_WARNING("Failed to compose animation style to commit");
return;
}
// Calling SetCSSDeclaration will trigger attribute setting code.
// Start the update now so that the old rule doesn't get used
// between when we mutate the declaration and when we set the new
// rule.
mozAutoDocUpdate autoUpdate(target.mElement->OwnerDoc(), true);
// Get the inline style to append to
RefPtr<DeclarationBlock> declarationBlock;
if (auto* existing = target.mElement->GetInlineStyleDeclaration()) {
declarationBlock = existing->EnsureMutable();
} else {
declarationBlock = new DeclarationBlock();
declarationBlock->SetDirty();
}
// Prepare the callback
MutationClosureData closureData;
closureData.mShouldBeCalled = true;
closureData.mElement = target.mElement;
DeclarationBlockMutationClosure beforeChangeClosure = {
nsDOMCSSAttributeDeclaration::MutationClosureFunction,
&closureData,
};
// Set the animated styles
bool changed = false;
nsCSSPropertyIDSet properties = keyframeEffect->GetPropertySet();
for (nsCSSPropertyID property : properties) {
RefPtr<RawServoAnimationValue> computedValue =
Servo_AnimationValueMap_GetValue(animationValues.get(), property)
.Consume();
if (computedValue) {
changed |= Servo_DeclarationBlock_SetPropertyToAnimationValue(
declarationBlock->Raw(), computedValue, beforeChangeClosure);
}
}
if (!changed) {
MOZ_ASSERT(!closureData.mWasCalled);
return;
}
MOZ_ASSERT(closureData.mWasCalled);
// Update inline style declaration
target.mElement->SetInlineStyleDeclaration(*declarationBlock, closureData);
}
// ---------------------------------------------------------------------------
//
// JS wrappers for Animation interface:
//
// ---------------------------------------------------------------------------
Nullable<double> Animation::GetStartTimeAsDouble() const {
return AnimationUtils::TimeDurationToDouble(mStartTime, mRTPCallerType);
}
void Animation::SetStartTimeAsDouble(const Nullable<double>& aStartTime) {
return SetStartTime(AnimationUtils::DoubleToTimeDuration(aStartTime));
}
Nullable<double> Animation::GetCurrentTimeAsDouble() const {
return AnimationUtils::TimeDurationToDouble(GetCurrentTimeAsDuration(),
mRTPCallerType);
}
void Animation::SetCurrentTimeAsDouble(const Nullable<double>& aCurrentTime,
ErrorResult& aRv) {
if (aCurrentTime.IsNull()) {
if (!GetCurrentTimeAsDuration().IsNull()) {
aRv.ThrowTypeError(
"Current time is resolved but trying to set it to an unresolved "
"time");
}
return;
}
return SetCurrentTime(TimeDuration::FromMilliseconds(aCurrentTime.Value()));
}
// ---------------------------------------------------------------------------
void Animation::Tick() {
// Finish pending if we have a pending ready time, but only if we also
// have an active timeline.
if (mPendingState != PendingState::NotPending &&
!mPendingReadyTime.IsNull() && mTimeline &&
!mTimeline->GetCurrentTimeAsDuration().IsNull()) {
// Even though mPendingReadyTime is initialized using TimeStamp::Now()
// during the *previous* tick of the refresh driver, it can still be
// ahead of the *current* timeline time when we are using the
// vsync timer so we need to clamp it to the timeline time.
TimeDuration currentTime = mTimeline->GetCurrentTimeAsDuration().Value();
if (currentTime < mPendingReadyTime.Value()) {
mPendingReadyTime.SetValue(currentTime);
}
FinishPendingAt(mPendingReadyTime.Value());
mPendingReadyTime.SetNull();
}
if (IsPossiblyOrphanedPendingAnimation()) {
MOZ_ASSERT(mTimeline && !mTimeline->GetCurrentTimeAsDuration().IsNull(),
"Orphaned pending animations should have an active timeline");
FinishPendingAt(mTimeline->GetCurrentTimeAsDuration().Value());
}
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Sync);
// Check for changes to whether or not this animation is replaceable.
bool isReplaceable = IsReplaceable();
if (isReplaceable && !mWasReplaceableAtLastTick) {
ScheduleReplacementCheck();
}
mWasReplaceableAtLastTick = isReplaceable;
if (!mEffect) {
return;
}
// Update layers if we are newly finished.
KeyframeEffect* keyframeEffect = mEffect->AsKeyframeEffect();
if (keyframeEffect && !keyframeEffect->Properties().IsEmpty() &&
!mFinishedAtLastComposeStyle &&
PlayState() == AnimationPlayState::Finished) {
PostUpdate();
}
}
void Animation::TriggerOnNextTick(const Nullable<TimeDuration>& aReadyTime) {
// Normally we expect the play state to be pending but it's possible that,
// due to the handling of possibly orphaned animations in Tick(), this
// animation got started whilst still being in another document's pending
// animation map.
if (!Pending()) {
return;
}
// If aReadyTime.IsNull() we'll detect this in Tick() where we check for
// orphaned animations and trigger this animation anyway
mPendingReadyTime = aReadyTime;
}
void Animation::TriggerNow() {
// Normally we expect the play state to be pending but when an animation
// is cancelled and its rendered document can't be reached, we can end up
// with the animation still in a pending player tracker even after it is
// no longer pending.
if (!Pending()) {
return;
}
// If we don't have an active timeline we can't trigger the animation.
// However, this is a test-only method that we don't expect to be used in
// conjunction with animations without an active timeline so generate
// a warning if we do find ourselves in that situation.
if (!mTimeline || mTimeline->GetCurrentTimeAsDuration().IsNull()) {
NS_WARNING("Failed to trigger an animation with an active timeline");
return;
}
FinishPendingAt(mTimeline->GetCurrentTimeAsDuration().Value());
}
bool Animation::TryTriggerNowForFiniteTimeline() {
// Normally we expect the play state to be pending but when an animation
// is cancelled and its rendered document can't be reached, we can end up
// with the animation still in a pending player tracker even after it is
// no longer pending.
if (!Pending()) {
return true;
}
MOZ_ASSERT(mTimeline && !mTimeline->IsMonotonicallyIncreasing());
// It's possible that the primary frame or the scrollable frame is not ready
// when setting up this animation. So we don't finish pending right now. In
// this case, the timeline is inactive so it is still pending. The caller
// should handle this case by trying this later once the scrollable frame is
// ready.
const auto currentTime = mTimeline->GetCurrentTimeAsDuration();
if (currentTime.IsNull()) {
return false;
}
FinishPendingAt(currentTime.Value());
return true;
}
Nullable<TimeDuration> Animation::GetCurrentOrPendingStartTime() const {
Nullable<TimeDuration> result;
// If we have a pending playback rate, work out what start time we will use
// when we come to updating that playback rate.
//
// This logic roughly shadows that in ResumeAt but is just different enough
// that it is difficult to extract out the common functionality (and
// extracting that functionality out would make it harder to match ResumeAt up
// against the spec).
if (mPendingPlaybackRate && !mPendingReadyTime.IsNull() &&
!mStartTime.IsNull()) {
// If we have a hold time, use it as the current time to match.
TimeDuration currentTimeToMatch =
!mHoldTime.IsNull()
? mHoldTime.Value()
: CurrentTimeFromTimelineTime(mPendingReadyTime.Value(),
mStartTime.Value(), mPlaybackRate);
result = StartTimeFromTimelineTime(
mPendingReadyTime.Value(), currentTimeToMatch, *mPendingPlaybackRate);
return result;
}
if (!mStartTime.IsNull()) {
result = mStartTime;
return result;
}
if (mPendingReadyTime.IsNull() || mHoldTime.IsNull()) {
return result;
}
// Calculate the equivalent start time from the pending ready time.
result = StartTimeFromTimelineTime(mPendingReadyTime.Value(),
mHoldTime.Value(), mPlaybackRate);
return result;
}
TimeStamp Animation::AnimationTimeToTimeStamp(
const StickyTimeDuration& aTime) const {
// Initializes to null. Return the same object every time to benefit from
// return-value-optimization.
TimeStamp result;
// We *don't* check for mTimeline->TracksWallclockTime() here because that
// method only tells us if the timeline times can be converted to
// TimeStamps that can be compared to TimeStamp::Now() or not, *not*
// whether the timelines can be converted to TimeStamp values at all.
//
// Furthermore, we want to be able to use this method when the refresh driver
// is under test control (in which case TracksWallclockTime() will return
// false).
//
// Once we introduce timelines that are not time-based we will need to
// differentiate between them here and determine how to sort their events.
if (!mTimeline) {
return result;
}
// Check the time is convertible to a timestamp
if (aTime == TimeDuration::Forever() || mPlaybackRate == 0.0 ||
mStartTime.IsNull()) {
return result;
}
// Invert the standard relation:
// current time = (timeline time - start time) * playback rate
TimeDuration timelineTime =
TimeDuration(aTime).MultDouble(1.0 / mPlaybackRate) + mStartTime.Value();
result = mTimeline->ToTimeStamp(timelineTime);
return result;
}
TimeStamp Animation::ElapsedTimeToTimeStamp(
const StickyTimeDuration& aElapsedTime) const {
TimeDuration delay =
mEffect ? mEffect->NormalizedTiming().Delay() : TimeDuration();
return AnimationTimeToTimeStamp(aElapsedTime + delay);
}
// https://drafts.csswg.org/web-animations/#silently-set-the-current-time
void Animation::SilentlySetCurrentTime(const TimeDuration& aSeekTime) {
// TODO: Bug 1762238: Introduce "valid seek time" after introducing
// CSSNumberish time values.
// https://drafts.csswg.org/web-animations-2/#silently-set-the-current-time
if (!mHoldTime.IsNull() || mStartTime.IsNull() || !mTimeline ||
mTimeline->GetCurrentTimeAsDuration().IsNull() || mPlaybackRate == 0.0) {
mHoldTime.SetValue(aSeekTime);
} else {
mStartTime =
StartTimeFromTimelineTime(mTimeline->GetCurrentTimeAsDuration().Value(),
aSeekTime, mPlaybackRate);
}
if (!mTimeline || mTimeline->GetCurrentTimeAsDuration().IsNull()) {
mStartTime.SetNull();
}
mPreviousCurrentTime.SetNull();
mResetCurrentTimeOnResume = false;
}
bool Animation::ShouldBeSynchronizedWithMainThread(
const nsCSSPropertyIDSet& aPropertySet, const nsIFrame* aFrame,
AnimationPerformanceWarning::Type& aPerformanceWarning) const {
// Only synchronize playing animations
if (!IsPlaying()) {
return false;
}
// Currently only transform animations need to be synchronized
if (!aPropertySet.Intersects(nsCSSPropertyIDSet::TransformLikeProperties())) {
return false;
}
KeyframeEffect* keyframeEffect =
mEffect ? mEffect->AsKeyframeEffect() : nullptr;
if (!keyframeEffect) {
return false;
}
// Are we starting at the same time as other geometric animations?
// We check this before calling ShouldBlockAsyncTransformAnimations, partly
// because it's cheaper, but also because it's often the most useful thing
// to know when you're debugging performance.
// Note: |mSyncWithGeometricAnimations| wouldn't be set if the geometric
// animations use scroll-timeline.
if (StaticPrefs::
dom_animations_mainthread_synchronization_with_geometric_animations() &&
mSyncWithGeometricAnimations &&
keyframeEffect->HasAnimationOfPropertySet(
nsCSSPropertyIDSet::TransformLikeProperties())) {
aPerformanceWarning =
AnimationPerformanceWarning::Type::TransformWithSyncGeometricAnimations;
return true;
}
return keyframeEffect->ShouldBlockAsyncTransformAnimations(
aFrame, aPropertySet, aPerformanceWarning);
}
void Animation::UpdateRelevance() {
bool wasRelevant = mIsRelevant;
mIsRelevant = mReplaceState != AnimationReplaceState::Removed &&
(HasCurrentEffect() || IsInEffect());
// Notify animation observers.
if (wasRelevant && !mIsRelevant) {
MutationObservers::NotifyAnimationRemoved(this);
} else if (!wasRelevant && mIsRelevant) {
MutationObservers::NotifyAnimationAdded(this);
}
}
template <class T>
bool IsMarkupAnimation(T* aAnimation) {
return aAnimation && aAnimation->IsTiedToMarkup();
}
// https://drafts.csswg.org/web-animations/#replaceable-animation
bool Animation::IsReplaceable() const {
// We never replace CSS animations or CSS transitions since they are managed
// by CSS.
if (IsMarkupAnimation(AsCSSAnimation()) ||
IsMarkupAnimation(AsCSSTransition())) {
return false;
}
// Only finished animations can be replaced.
if (PlayState() != AnimationPlayState::Finished) {
return false;
}
// Already removed animations cannot be replaced.
if (ReplaceState() == AnimationReplaceState::Removed) {
return false;
}
// We can only replace an animation if we know that, uninterfered, it would
// never start playing again. That excludes any animations on timelines that
// aren't monotonically increasing.
//
// If we don't have any timeline at all, then we can't be in the finished
// state (since we need both a resolved start time and current time for that)
// and will have already returned false above.
//
// (However, if it ever does become possible to be finished without a timeline
// then we will want to return false here since it probably suggests an
// animation being driven directly by script, in which case we can't assume
// anything about how they will behave.)
if (!GetTimeline() || !GetTimeline()->TracksWallclockTime()) {
return false;
}
// If the animation doesn't have an effect then we can't determine if it is
// filling or not so just leave it alone.
if (!GetEffect()) {
return false;
}
// At the time of writing we only know about KeyframeEffects. If we introduce
// other types of effects we will need to decide if they are replaceable or
// not.
MOZ_ASSERT(GetEffect()->AsKeyframeEffect(),
"Effect should be a keyframe effect");
// We only replace animations that are filling.
if (GetEffect()->GetComputedTiming().mProgress.IsNull()) {
return false;
}
// We should only replace animations with a target element (since otherwise
// what other effects would we consider when determining if they are covered
// or not?).
if (!GetEffect()->AsKeyframeEffect()->GetAnimationTarget()) {
return false;
}
return true;
}
bool Animation::IsRemovable() const {
return ReplaceState() == AnimationReplaceState::Active && IsReplaceable();
}
void Animation::ScheduleReplacementCheck() {
MOZ_ASSERT(
IsReplaceable(),
"Should only schedule a replacement check for a replaceable animation");
// If IsReplaceable() is true, the following should also hold
MOZ_ASSERT(GetEffect());
MOZ_ASSERT(GetEffect()->AsKeyframeEffect());
NonOwningAnimationTarget target =
GetEffect()->AsKeyframeEffect()->GetAnimationTarget();
MOZ_ASSERT(target);
nsPresContext* presContext =
nsContentUtils::GetContextForContent(target.mElement);
if (presContext) {
presContext->EffectCompositor()->NoteElementForReducing(target);
}
}
void Animation::MaybeScheduleReplacementCheck() {
if (!IsReplaceable()) {
return;
}
ScheduleReplacementCheck();
}
void Animation::Remove() {
MOZ_ASSERT(IsRemovable(),
"Should not be trying to remove an effect that is not removable");
mReplaceState = AnimationReplaceState::Removed;
UpdateEffect(PostRestyleMode::IfNeeded);
PostUpdate();
QueuePlaybackEvent(u"remove"_ns, GetTimelineCurrentTimeAsTimeStamp());
}
bool Animation::HasLowerCompositeOrderThan(const Animation& aOther) const {
// 0. Object-equality case
if (&aOther == this) {
return false;
}
// 1. CSS Transitions sort lowest
{
auto asCSSTransitionForSorting =
[](const Animation& anim) -> const CSSTransition* {
const CSSTransition* transition = anim.AsCSSTransition();
return transition && transition->IsTiedToMarkup() ? transition : nullptr;
};
auto thisTransition = asCSSTransitionForSorting(*this);
auto otherTransition = asCSSTransitionForSorting(aOther);
if (thisTransition && otherTransition) {
return thisTransition->HasLowerCompositeOrderThan(*otherTransition);
}
if (thisTransition || otherTransition) {
// Cancelled transitions no longer have an owning element. To be strictly
// correct we should store a strong reference to the owning element
// so that if we arrive here while sorting cancel events, we can sort
// them in the correct order.
//
// However, given that cancel events are almost always queued
// synchronously in some deterministic manner, we can be fairly sure
// that cancel events will be dispatched in a deterministic order
// (which is our only hard requirement until specs say otherwise).
// Furthermore, we only reach here when we have events with equal
// timestamps so this is an edge case we can probably ignore for now.
return thisTransition;
}
}
// 2. CSS Animations sort next
{
auto asCSSAnimationForSorting =
[](const Animation& anim) -> const CSSAnimation* {
const CSSAnimation* animation = anim.AsCSSAnimation();
return animation && animation->IsTiedToMarkup() ? animation : nullptr;
};
auto thisAnimation = asCSSAnimationForSorting(*this);
auto otherAnimation = asCSSAnimationForSorting(aOther);
if (thisAnimation && otherAnimation) {
return thisAnimation->HasLowerCompositeOrderThan(*otherAnimation);
}
if (thisAnimation || otherAnimation) {
return thisAnimation;
}
}
// Subclasses of Animation repurpose mAnimationIndex to implement their
// own brand of composite ordering. However, by this point we should have
// handled any such custom composite ordering so we should now have unique
// animation indices.
MOZ_ASSERT(mAnimationIndex != aOther.mAnimationIndex,
"Animation indices should be unique");
// 3. Finally, generic animations sort by their position in the global
// animation array.
return mAnimationIndex < aOther.mAnimationIndex;
}
void Animation::WillComposeStyle() {
mFinishedAtLastComposeStyle = (PlayState() == AnimationPlayState::Finished);
MOZ_ASSERT(mEffect);
KeyframeEffect* keyframeEffect = mEffect->AsKeyframeEffect();
if (keyframeEffect) {
keyframeEffect->WillComposeStyle();
}
}
void Animation::ComposeStyle(RawServoAnimationValueMap& aComposeResult,
const nsCSSPropertyIDSet& aPropertiesToSkip) {
if (!mEffect) {
return;
}
// In order to prevent flicker, there are a few cases where we want to use
// a different time for rendering that would otherwise be returned by
// GetCurrentTimeAsDuration. These are:
//
// (a) For animations that are pausing but which are still running on the
// compositor. In this case we send a layer transaction that removes the
// animation but which also contains the animation values calculated on
// the main thread. To prevent flicker when this occurs we want to ensure
// the timeline time used to calculate the main thread animation values
// does not lag far behind the time used on the compositor. Ideally we
// would like to use the "animation ready time" calculated at the end of
// the layer transaction as the timeline time but it will be too late to
// update the style rule at that point so instead we just use the current
// wallclock time.
//
// (b) For animations that are pausing that we have already taken off the
// compositor. In this case we record a pending ready time but we don't
// apply it until the next tick. However, while waiting for the next tick,
// we should still use the pending ready time as the timeline time. If we
// use the regular timeline time the animation may appear jump backwards
// if the main thread's timeline time lags behind the compositor.
//
// (c) For animations that are play-pending due to an aborted pause operation
// (i.e. a pause operation that was interrupted before we entered the
// paused state). When we cancel a pending pause we might momentarily take
// the animation off the compositor, only to re-add it moments later. In
// that case the compositor might have been ahead of the main thread so we
// should use the current wallclock time to ensure the animation doesn't
// temporarily jump backwards.
//
// To address each of these cases we temporarily tweak the hold time
// immediately before updating the style rule and then restore it immediately
// afterwards. This is purely to prevent visual flicker. Other behavior
// such as dispatching events continues to rely on the regular timeline time.
bool pending = Pending();
{
AutoRestore<Nullable<TimeDuration>> restoreHoldTime(mHoldTime);
if (pending && mHoldTime.IsNull() && !mStartTime.IsNull()) {
Nullable<TimeDuration> timeToUse = mPendingReadyTime;
if (timeToUse.IsNull() && mTimeline && mTimeline->TracksWallclockTime()) {
timeToUse = mTimeline->ToTimelineTime(TimeStamp::Now());
}
if (!timeToUse.IsNull()) {
mHoldTime = CurrentTimeFromTimelineTime(
timeToUse.Value(), mStartTime.Value(), mPlaybackRate);
}
}
KeyframeEffect* keyframeEffect = mEffect->AsKeyframeEffect();
if (keyframeEffect) {
keyframeEffect->ComposeStyle(aComposeResult, aPropertiesToSkip);
}
}
MOZ_ASSERT(
pending == Pending(),
"Pending state should not change during the course of compositing");
}
void Animation::NotifyEffectTimingUpdated() {
MOZ_ASSERT(mEffect,
"We should only update effect timing when we have a target "
"effect");
UpdateTiming(Animation::SeekFlag::NoSeek, Animation::SyncNotifyFlag::Async);
}
void Animation::NotifyEffectPropertiesUpdated() {
MOZ_ASSERT(mEffect,
"We should only update effect properties when we have a target "
"effect");
MaybeScheduleReplacementCheck();
}
void Animation::NotifyEffectTargetUpdated() {
MOZ_ASSERT(mEffect,
"We should only update the effect target when we have a target "
"effect");
MaybeScheduleReplacementCheck();
}
void Animation::NotifyGeometricAnimationsStartingThisFrame() {
if (!IsNewlyStarted() || !mEffect) {
return;
}
mSyncWithGeometricAnimations = true;
}
// https://drafts.csswg.org/web-animations/#play-an-animation
void Animation::PlayNoUpdate(ErrorResult& aRv, LimitBehavior aLimitBehavior) {
AutoMutationBatchForAnimation mb(*this);
const bool isAutoRewind = aLimitBehavior == LimitBehavior::AutoRewind;
const bool abortedPause = mPendingState == PendingState::PausePending;
double effectivePlaybackRate = CurrentOrPendingPlaybackRate();
Nullable<TimeDuration> currentTime = GetCurrentTimeAsDuration();
if (mResetCurrentTimeOnResume) {
currentTime.SetNull();
mResetCurrentTimeOnResume = false;
}
Nullable<TimeDuration> seekTime;
if (isAutoRewind) {
if (effectivePlaybackRate >= 0.0 &&
(currentTime.IsNull() || currentTime.Value() < TimeDuration() ||
currentTime.Value() >= EffectEnd())) {
seekTime.SetValue(TimeDuration());
} else if (effectivePlaybackRate < 0.0 &&
(currentTime.IsNull() || currentTime.Value() <= TimeDuration() ||
currentTime.Value() > EffectEnd())) {
if (EffectEnd() == TimeDuration::Forever()) {
return aRv.ThrowInvalidStateError(
"Can't rewind animation with infinite effect end");
}
seekTime.SetValue(TimeDuration(EffectEnd()));
}
}
if (seekTime.IsNull() && mStartTime.IsNull() && currentTime.IsNull()) {
seekTime.SetValue(TimeDuration());
}
if (!seekTime.IsNull()) {
if (HasFiniteTimeline()) {
mStartTime = seekTime;
mHoldTime.SetNull();
ApplyPendingPlaybackRate();
} else {
mHoldTime = seekTime;
}
}
bool reuseReadyPromise = false;
if (mPendingState != PendingState::NotPending) {
CancelPendingTasks();
reuseReadyPromise = true;
}
// If the hold time is null then we're already playing normally and,
// typically, we can bail out here.
//
// However, there are two cases where we can't do that:
//
// (a) If we just aborted a pause. In this case, for consistency, we need to
// go through the motions of doing an asynchronous start.
//
// (b) If we have timing changes (specifically a change to the playbackRate)
// that should be applied asynchronously.
//
if (mHoldTime.IsNull() && seekTime.IsNull() && !abortedPause &&
!mPendingPlaybackRate) {
return;
}
// Clear the start time until we resolve a new one. We do this except
// for the case where we are aborting a pause and don't have a hold time.
//
// If we're aborting a pause and *do* have a hold time (e.g. because
// the animation is finished or we just applied the auto-rewind behavior
// above) we should respect it by clearing the start time. If we *don't*
// have a hold time we should keep the current start time so that the
// the animation continues moving uninterrupted by the aborted pause.
//
// (If we're not aborting a pause, mHoldTime must be resolved by now
// or else we would have returned above.)
if (!mHoldTime.IsNull()) {
mStartTime.SetNull();
}
if (!reuseReadyPromise) {
// Clear ready promise. We'll create a new one lazily.
mReady = nullptr;
}
mPendingState = PendingState::PlayPending;
// Clear flag that causes us to sync transform animations with the main
// thread for now. We'll set this when we go to set up compositor
// animations if it applies.
mSyncWithGeometricAnimations = false;
if (HasFiniteTimeline()) {
// Always schedule a task even if we would like to let this animation
// immedidately ready, per spec.
// https://drafts.csswg.org/web-animations/#playing-an-animation-section
if (Document* doc = GetRenderedDocument()) {
doc->GetOrCreateScrollTimelineAnimationTracker()->AddPending(*this);
} // else: we fail to track this animation, so let the scroll frame to
// trigger it when ticking.
} else {
if (Document* doc = GetRenderedDocument()) {
PendingAnimationTracker* tracker =
doc->GetOrCreatePendingAnimationTracker();
tracker->AddPlayPending(*this);
} else {
TriggerOnNextTick(Nullable<TimeDuration>());
}
}
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
}
// https://drafts.csswg.org/web-animations/#pause-an-animation
void Animation::Pause(ErrorResult& aRv) {
if (IsPausedOrPausing()) {
return;
}
AutoMutationBatchForAnimation mb(*this);
Nullable<TimeDuration> seekTime;
// If we are transitioning from idle, fill in the current time
if (GetCurrentTimeAsDuration().IsNull()) {
if (mPlaybackRate >= 0.0) {
seekTime.SetValue(TimeDuration(0));
} else {
if (EffectEnd() == TimeDuration::Forever()) {
return aRv.ThrowInvalidStateError("Can't seek to infinite effect end");
}
seekTime.SetValue(TimeDuration(EffectEnd()));
}
}
if (!seekTime.IsNull()) {
if (HasFiniteTimeline()) {
mStartTime = seekTime;
} else {
mHoldTime = seekTime;
}
}
bool reuseReadyPromise = false;
if (mPendingState == PendingState::PlayPending) {
CancelPendingTasks();
reuseReadyPromise = true;
}
if (!reuseReadyPromise) {
// Clear ready promise. We'll create a new one lazily.
mReady = nullptr;
}
mPendingState = PendingState::PausePending;
if (HasFiniteTimeline()) {
// Always schedule a task even if we would like to let this animation
// immedidately ready, per spec.
// https://drafts.csswg.org/web-animations/#playing-an-animation-section
if (Document* doc = GetRenderedDocument()) {
doc->GetOrCreateScrollTimelineAnimationTracker()->AddPending(*this);
} // else: we fail to track this animation, so let the scroll frame to
// trigger it when ticking.
} else {
if (Document* doc = GetRenderedDocument()) {
PendingAnimationTracker* tracker =
doc->GetOrCreatePendingAnimationTracker();
tracker->AddPausePending(*this);
} else {
TriggerOnNextTick(Nullable<TimeDuration>());
}
}
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
PostUpdate();
}
// https://drafts.csswg.org/web-animations/#play-an-animation
void Animation::ResumeAt(const TimeDuration& aReadyTime) {
// This method is only expected to be called for an animation that is
// waiting to play. We can easily adapt it to handle other states
// but it's currently not necessary.
MOZ_ASSERT(mPendingState == PendingState::PlayPending,
"Expected to resume a play-pending animation");
MOZ_ASSERT(!mHoldTime.IsNull() || !mStartTime.IsNull(),
"An animation in the play-pending state should have either a"
" resolved hold time or resolved start time");
AutoMutationBatchForAnimation mb(*this);
bool hadPendingPlaybackRate = mPendingPlaybackRate.isSome();
if (!mHoldTime.IsNull()) {
// The hold time is set, so we don't need any special handling to preserve
// the current time.
ApplyPendingPlaybackRate();
mStartTime =
StartTimeFromTimelineTime(aReadyTime, mHoldTime.Value(), mPlaybackRate);
if (mPlaybackRate != 0) {
mHoldTime.SetNull();
}
} else if (!mStartTime.IsNull() && mPendingPlaybackRate) {
// Apply any pending playback rate, preserving the current time.
TimeDuration currentTimeToMatch = CurrentTimeFromTimelineTime(
aReadyTime, mStartTime.Value(), mPlaybackRate);
ApplyPendingPlaybackRate();
mStartTime = StartTimeFromTimelineTime(aReadyTime, currentTimeToMatch,
mPlaybackRate);
if (mPlaybackRate == 0) {
mHoldTime.SetValue(currentTimeToMatch);
}
}
mPendingState = PendingState::NotPending;
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Sync);
// If we had a pending playback rate, we will have now applied it so we need
// to notify observers.
if (hadPendingPlaybackRate && IsRelevant()) {
MutationObservers::NotifyAnimationChanged(this);
}
if (mReady) {
mReady->MaybeResolve(this);
}
}
void Animation::PauseAt(const TimeDuration& aReadyTime) {
MOZ_ASSERT(mPendingState == PendingState::PausePending,
"Expected to pause a pause-pending animation");
if (!mStartTime.IsNull() && mHoldTime.IsNull()) {
mHoldTime = CurrentTimeFromTimelineTime(aReadyTime, mStartTime.Value(),
mPlaybackRate);
}
ApplyPendingPlaybackRate();
mStartTime.SetNull();
mPendingState = PendingState::NotPending;
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
if (mReady) {
mReady->MaybeResolve(this);
}
}
void Animation::UpdateTiming(SeekFlag aSeekFlag,
SyncNotifyFlag aSyncNotifyFlag) {
// We call UpdateFinishedState before UpdateEffect because the former
// can change the current time, which is used by the latter.
UpdateFinishedState(aSeekFlag, aSyncNotifyFlag);
UpdateEffect(PostRestyleMode::IfNeeded);
if (mTimeline) {
mTimeline->NotifyAnimationUpdated(*this);
}
}
// https://drafts.csswg.org/web-animations/#update-an-animations-finished-state
void Animation::UpdateFinishedState(SeekFlag aSeekFlag,
SyncNotifyFlag aSyncNotifyFlag) {
Nullable<TimeDuration> unconstrainedCurrentTime =
aSeekFlag == SeekFlag::NoSeek ? GetUnconstrainedCurrentTime()
: GetCurrentTimeAsDuration();
TimeDuration effectEnd = TimeDuration(EffectEnd());
if (!unconstrainedCurrentTime.IsNull() && !mStartTime.IsNull() &&
mPendingState == PendingState::NotPending) {
if (mPlaybackRate > 0.0 && unconstrainedCurrentTime.Value() >= effectEnd) {
if (aSeekFlag == SeekFlag::DidSeek) {
mHoldTime = unconstrainedCurrentTime;
} else if (!mPreviousCurrentTime.IsNull()) {
mHoldTime.SetValue(std::max(mPreviousCurrentTime.Value(), effectEnd));
} else {
mHoldTime.SetValue(effectEnd);
}
} else if (mPlaybackRate < 0.0 &&
unconstrainedCurrentTime.Value() <= TimeDuration()) {
if (aSeekFlag == SeekFlag::DidSeek) {
mHoldTime = unconstrainedCurrentTime;
} else if (!mPreviousCurrentTime.IsNull()) {
mHoldTime.SetValue(
std::min(mPreviousCurrentTime.Value(), TimeDuration(0)));
} else {
mHoldTime.SetValue(0);
}
} else if (mPlaybackRate != 0.0 && mTimeline &&
!mTimeline->GetCurrentTimeAsDuration().IsNull()) {
if (aSeekFlag == SeekFlag::DidSeek && !mHoldTime.IsNull()) {
mStartTime = StartTimeFromTimelineTime(
mTimeline->GetCurrentTimeAsDuration().Value(), mHoldTime.Value(),
mPlaybackRate);
}
mHoldTime.SetNull();
}
}
// We must recalculate the current time to take account of any mHoldTime
// changes the code above made.
mPreviousCurrentTime = GetCurrentTimeAsDuration();
bool currentFinishedState = PlayState() == AnimationPlayState::Finished;
if (currentFinishedState && !mFinishedIsResolved) {
DoFinishNotification(aSyncNotifyFlag);
} else if (!currentFinishedState && mFinishedIsResolved) {
ResetFinishedPromise();
}
}
void Animation::UpdateEffect(PostRestyleMode aPostRestyle) {
if (mEffect) {
UpdateRelevance();
KeyframeEffect* keyframeEffect = mEffect->AsKeyframeEffect();
if (keyframeEffect) {
keyframeEffect->NotifyAnimationTimingUpdated(aPostRestyle);
}
}
}
void Animation::FlushUnanimatedStyle() const {
if (Document* doc = GetRenderedDocument()) {
doc->FlushPendingNotifications(
ChangesToFlush(FlushType::Style, false /* flush animations */));
}
}
void Animation::PostUpdate() {
if (!mEffect) {
return;
}
KeyframeEffect* keyframeEffect = mEffect->AsKeyframeEffect();
if (!keyframeEffect) {
return;
}
keyframeEffect->RequestRestyle(EffectCompositor::RestyleType::Layer);
}
void Animation::CancelPendingTasks() {
if (mPendingState == PendingState::NotPending) {
return;
}
if (Document* doc = GetRenderedDocument()) {
PendingAnimationTracker* tracker = doc->GetPendingAnimationTracker();
if (tracker) {
if (mPendingState == PendingState::PlayPending) {
tracker->RemovePlayPending(*this);
} else {
tracker->RemovePausePending(*this);
}
}
}
mPendingState = PendingState::NotPending;
mPendingReadyTime.SetNull();
}
// https://drafts.csswg.org/web-animations/#reset-an-animations-pending-tasks
void Animation::ResetPendingTasks() {
if (mPendingState == PendingState::NotPending) {
return;
}
CancelPendingTasks();
ApplyPendingPlaybackRate();
if (mReady) {
mReady->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
MOZ_ALWAYS_TRUE(mReady->SetAnyPromiseIsHandled());
mReady = nullptr;
}
}
void Animation::ReschedulePendingTasks() {
if (mPendingState == PendingState::NotPending) {
return;
}
mPendingReadyTime.SetNull();
if (Document* doc = GetRenderedDocument()) {
PendingAnimationTracker* tracker =
doc->GetOrCreatePendingAnimationTracker();
if (mPendingState == PendingState::PlayPending &&
!tracker->IsWaitingToPlay(*this)) {
tracker->AddPlayPending(*this);
} else if (mPendingState == PendingState::PausePending &&
!tracker->IsWaitingToPause(*this)) {
tracker->AddPausePending(*this);
}
}
}
// https://drafts.csswg.org/web-animations-2/#at-progress-timeline-boundary
/* static*/ Animation::ProgressTimelinePosition
Animation::AtProgressTimelineBoundary(
const Nullable<TimeDuration>& aTimelineDuration,
const Nullable<TimeDuration>& aCurrentTime,
const TimeDuration& aEffectStartTime, const double aPlaybackRate) {
// Based on changed defined in: https://github.com/w3c/csswg-drafts/pull/6702
// 1. If any of the following conditions are true:
// * the associated animation's timeline is not a progress-based timeline,
// or
// * the associated animation's timeline duration is unresolved or zero,
// or
// * the animation's playback rate is zero
// return false
// Note: We can detect a progress-based timeline by relying on the fact that
// monotonic timelines (i.e. non-progress-based timelines) have an unresolved
// timeline duration.
if (aTimelineDuration.IsNull() || aTimelineDuration.Value().IsZero() ||
aPlaybackRate == 0.0) {
return ProgressTimelinePosition::NotBoundary;
}
// 2. Let effective start time be the animation's start time if resolved, or
// zero otherwise.
const TimeDuration& effectiveStartTime = aEffectStartTime;
// 3. Let effective timeline time be (animation's current time / animation's
// playback rate) + effective start time.
// Note: we use zero if the current time is unresolved. See the spec issue:
// https://github.com/w3c/csswg-drafts/issues/7458
const TimeDuration effectiveTimelineTime =
(aCurrentTime.IsNull()
? TimeDuration()
: aCurrentTime.Value().MultDouble(1.0 / aPlaybackRate)) +
effectiveStartTime;
// 4. Let effective timeline progress be (effective timeline time / timeline
// duration)
// 5. If effective timeline progress is 0 or 1, return true,
// We avoid the division here but it is effectively the same as 4 & 5 above.
return effectiveTimelineTime.IsZero() ||
(AnimationUtils::IsWithinAnimationTimeTolerance(
effectiveTimelineTime, aTimelineDuration.Value()))
? ProgressTimelinePosition::Boundary
: ProgressTimelinePosition::NotBoundary;
}
bool Animation::IsPossiblyOrphanedPendingAnimation() const {
// Check if we are pending but might never start because we are not being
// tracked.
//
// This covers the following cases:
//
// * We started playing but our effect's target element was orphaned
// or bound to a different document.
// (note that for the case of our effect changing we should handle
// that in SetEffect)
// * We started playing but our timeline became inactive.
// In this case the pending animation tracker will drop us from its hashmap
// when we have been painted.
// * When we started playing we couldn't find a
// PendingAnimationTracker/ScrollTimelineAnimationTracker to register with
// (perhaps the effect had no document) so we may
// 1. simply set mPendingState in PlayNoUpdate and relied on this method to
// catch us on the next tick, or
// 2. rely on the scroll frame to tick this animation and catch us in this
// method.
// If we're not pending we're ok.
if (mPendingState == PendingState::NotPending) {
return false;
}
// If we have a pending ready time then we will be started on the next
// tick.
if (!mPendingReadyTime.IsNull()) {
return false;
}
// If we don't have an active timeline then we shouldn't start until
// we do.
if (!mTimeline || mTimeline->GetCurrentTimeAsDuration().IsNull()) {
return false;
}
// If we have no rendered document, or we're not in our rendered document's
// PendingAnimationTracker then there's a good chance no one is tracking us.
//
// If we're wrong and another document is tracking us then, at worst, we'll
// simply start/pause the animation one tick too soon. That's better than
// never starting/pausing the animation and is unlikely.
Document* doc = GetRenderedDocument();
if (!doc) {
return true;
}
PendingAnimationTracker* tracker = doc->GetPendingAnimationTracker();
return !tracker || (!tracker->IsWaitingToPlay(*this) &&
!tracker->IsWaitingToPause(*this));
}
StickyTimeDuration Animation::EffectEnd() const {
if (!mEffect) {
return StickyTimeDuration(0);
}
return mEffect->NormalizedTiming().EndTime();
}
Document* Animation::GetRenderedDocument() const {
if (!mEffect || !mEffect->AsKeyframeEffect()) {
return nullptr;
}
return mEffect->AsKeyframeEffect()->GetRenderedDocument();
}
Document* Animation::GetTimelineDocument() const {
return mTimeline ? mTimeline->GetDocument() : nullptr;
}
void Animation::UpdatePendingAnimationTracker(AnimationTimeline* aOldTimeline,
AnimationTimeline* aNewTimeline) {
// If we are still in pending, we may have to move this animation into the
// correct animation tracker.
Document* doc = GetRenderedDocument();
if (!doc || !Pending()) {
return;
}
const bool fromFiniteTimeline =
aOldTimeline && !aOldTimeline->IsMonotonicallyIncreasing();
const bool toFiniteTimeline =
aNewTimeline && !aNewTimeline->IsMonotonicallyIncreasing();
if (fromFiniteTimeline == toFiniteTimeline) {
return;
}
const bool isPlayPending = mPendingState == PendingState::PlayPending;
if (toFiniteTimeline) {
// From null/document-timeline to scroll-timeline
if (auto* tracker = doc->GetPendingAnimationTracker()) {
if (isPlayPending) {
tracker->RemovePlayPending(*this);
} else {
tracker->RemovePausePending(*this);
}
}
doc->GetOrCreateScrollTimelineAnimationTracker()->AddPending(*this);
} else {
// From scroll-timeline to null/document-timeline
if (auto* tracker = doc->GetScrollTimelineAnimationTracker()) {
tracker->RemovePending(*this);
}
auto* tracker = doc->GetOrCreatePendingAnimationTracker();
if (isPlayPending) {
tracker->AddPlayPending(*this);
} else {
tracker->AddPausePending(*this);
}
}
}
class AsyncFinishNotification : public MicroTaskRunnable {
public:
explicit AsyncFinishNotification(Animation* aAnimation)
: MicroTaskRunnable(), mAnimation(aAnimation) {}
virtual void Run(AutoSlowOperation& aAso) override {
mAnimation->DoFinishNotificationImmediately(this);
mAnimation = nullptr;
}
virtual bool Suppressed() override {
nsIGlobalObject* global = mAnimation->GetOwnerGlobal();
return global && global->IsInSyncOperation();
}
private:
RefPtr<Animation> mAnimation;
};
void Animation::DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag) {
CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
if (aSyncNotifyFlag == SyncNotifyFlag::Sync) {
DoFinishNotificationImmediately();
} else if (!mFinishNotificationTask) {
RefPtr<MicroTaskRunnable> runnable = new AsyncFinishNotification(this);
context->DispatchToMicroTask(do_AddRef(runnable));
mFinishNotificationTask = std::move(runnable);
}
}
void Animation::ResetFinishedPromise() {
mFinishedIsResolved = false;
mFinished = nullptr;
}
void Animation::MaybeResolveFinishedPromise() {
if (mFinished) {
mFinished->MaybeResolve(this);
}
mFinishedIsResolved = true;
}
void Animation::DoFinishNotificationImmediately(MicroTaskRunnable* aAsync) {
if (aAsync && aAsync != mFinishNotificationTask) {
return;
}
mFinishNotificationTask = nullptr;
if (PlayState() != AnimationPlayState::Finished) {
return;
}
MaybeResolveFinishedPromise();
QueuePlaybackEvent(u"finish"_ns, AnimationTimeToTimeStamp(EffectEnd()));
}
void Animation::QueuePlaybackEvent(const nsAString& aName,
TimeStamp&& aScheduledEventTime) {
// Use document for timing.
// https://drafts.csswg.org/web-animations-1/#document-for-timing
Document* doc = GetTimelineDocument();
if (!doc) {
return;
}
nsPresContext* presContext = doc->GetPresContext();
if (!presContext) {
return;
}
AnimationPlaybackEventInit init;
if (aName.EqualsLiteral("finish") || aName.EqualsLiteral("remove")) {
init.mCurrentTime = GetCurrentTimeAsDouble();
}
if (mTimeline) {
init.mTimelineTime = mTimeline->GetCurrentTimeAsDouble();
}
RefPtr<AnimationPlaybackEvent> event =
AnimationPlaybackEvent::Constructor(this, aName, init);
event->SetTrusted(true);
presContext->AnimationEventDispatcher()->QueueEvent(AnimationEventInfo(
aName, std::move(event), std::move(aScheduledEventTime), this));
}
bool Animation::IsRunningOnCompositor() const {
return mEffect && mEffect->AsKeyframeEffect() &&
mEffect->AsKeyframeEffect()->IsRunningOnCompositor();
}
bool Animation::HasCurrentEffect() const {
return GetEffect() && GetEffect()->IsCurrent();
}
bool Animation::IsInEffect() const {
return GetEffect() && GetEffect()->IsInEffect();
}
void Animation::SetHiddenByContentVisibility(bool hidden) {
if (mHiddenByContentVisibility == hidden) {
return;
}
mHiddenByContentVisibility = hidden;
if (!GetTimeline()) {
return;
}
GetTimeline()->NotifyAnimationContentVisibilityChanged(this, !hidden);
}
StickyTimeDuration Animation::IntervalStartTime(
const StickyTimeDuration& aActiveDuration) const {
MOZ_ASSERT(AsCSSTransition() || AsCSSAnimation(),
"Should be called for CSS animations or transitions");
static constexpr StickyTimeDuration zeroDuration = StickyTimeDuration();
return std::max(
std::min(StickyTimeDuration(-mEffect->NormalizedTiming().Delay()),
aActiveDuration),
zeroDuration);
}
// Later side of the elapsed time range reported in CSS Animations and CSS
// Transitions events.
//
// https://drafts.csswg.org/css-animations-2/#interval-end
// https://drafts.csswg.org/css-transitions-2/#interval-end
StickyTimeDuration Animation::IntervalEndTime(
const StickyTimeDuration& aActiveDuration) const {
MOZ_ASSERT(AsCSSTransition() || AsCSSAnimation(),
"Should be called for CSS animations or transitions");
static constexpr StickyTimeDuration zeroDuration = StickyTimeDuration();
const StickyTimeDuration& effectEnd = EffectEnd();
// If both "associated effect end" and "start delay" are Infinity, we skip it
// because we will get NaN when computing "Infinity - Infinity", and
// using NaN in std::min or std::max is undefined.
if (MOZ_UNLIKELY(effectEnd == TimeDuration::Forever() &&
effectEnd == mEffect->NormalizedTiming().Delay())) {
// Note: If we use TimeDuration::Forever(), within our animation event
// handling, we'd end up turning that into a null TimeStamp which can causes
// errors if we try to do any arithmetic with it. Given that we should never
// end up _using_ the interval end time. So returning zeroDuration here is
// probably fine.
return zeroDuration;
}
return std::max(std::min(effectEnd - mEffect->NormalizedTiming().Delay(),
aActiveDuration),
zeroDuration);
}
} // namespace mozilla::dom
|