forked from roytam1/UXP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyframeUtils.cpp
1616 lines (1448 loc) · 56.1 KB
/
KeyframeUtils.cpp
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
/* 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 "mozilla/KeyframeUtils.h"
#include "mozilla/AnimationUtils.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Move.h"
#include "mozilla/Preferences.h"
#include "mozilla/RangedArray.h"
#include "mozilla/StyleAnimationValue.h"
#include "mozilla/TimingParams.h"
#include "mozilla/dom/BaseKeyframeTypesBinding.h" // For FastBaseKeyframe etc.
#include "mozilla/dom/Element.h"
#include "mozilla/dom/KeyframeEffectBinding.h"
#include "mozilla/dom/KeyframeEffectReadOnly.h" // For PropertyValuesPair etc.
#include "jsapi.h" // For ForOfIterator etc.
#include "nsClassHashtable.h"
#include "nsCSSParser.h"
#include "nsCSSPropertyIDSet.h"
#include "nsCSSProps.h"
#include "nsCSSPseudoElements.h" // For CSSPseudoElementType
#include "nsDocument.h"
#include "nsTArray.h"
#include <algorithm> // For std::stable_sort
namespace mozilla {
// ------------------------------------------------------------------
//
// Internal data types
//
// ------------------------------------------------------------------
// This is used while calculating paced spacing. If the keyframe is not pacable,
// we set its cumulative distance to kNotPaceable, so we can use this to check.
const double kNotPaceable = -1.0;
// For the aAllowList parameter of AppendStringOrStringSequence and
// GetPropertyValuesPairs.
enum class ListAllowance { eDisallow, eAllow };
/**
* A comparator to sort nsCSSPropertyID values such that longhands are sorted
* before shorthands, and shorthands with fewer components are sorted before
* shorthands with more components.
*
* Using this allows us to prioritize values specified by longhands (or smaller
* shorthand subsets) when longhands and shorthands are both specified
* on the one keyframe.
*
* Example orderings that result from this:
*
* margin-left, margin
*
* and:
*
* border-top-color, border-color, border-top, border
*/
class PropertyPriorityComparator
{
public:
PropertyPriorityComparator()
: mSubpropertyCountInitialized(false) {}
bool Equals(nsCSSPropertyID aLhs, nsCSSPropertyID aRhs) const
{
return aLhs == aRhs;
}
bool LessThan(nsCSSPropertyID aLhs,
nsCSSPropertyID aRhs) const
{
bool isShorthandLhs = nsCSSProps::IsShorthand(aLhs);
bool isShorthandRhs = nsCSSProps::IsShorthand(aRhs);
if (isShorthandLhs) {
if (isShorthandRhs) {
// First, sort shorthands by the number of longhands they have.
uint32_t subpropCountLhs = SubpropertyCount(aLhs);
uint32_t subpropCountRhs = SubpropertyCount(aRhs);
if (subpropCountLhs != subpropCountRhs) {
return subpropCountLhs < subpropCountRhs;
}
// Otherwise, sort by IDL name below.
} else {
// Put longhands before shorthands.
return false;
}
} else {
if (isShorthandRhs) {
// Put longhands before shorthands.
return true;
}
}
// For two longhand properties, or two shorthand with the same number
// of longhand components, sort by IDL name.
return nsCSSProps::PropertyIDLNameSortPosition(aLhs) <
nsCSSProps::PropertyIDLNameSortPosition(aRhs);
}
uint32_t SubpropertyCount(nsCSSPropertyID aProperty) const
{
if (!mSubpropertyCountInitialized) {
PodZero(&mSubpropertyCount);
mSubpropertyCountInitialized = true;
}
if (mSubpropertyCount[aProperty] == 0) {
uint32_t count = 0;
CSSPROPS_FOR_SHORTHAND_SUBPROPERTIES(
p, aProperty, CSSEnabledState::eForAllContent) {
++count;
}
mSubpropertyCount[aProperty] = count;
}
return mSubpropertyCount[aProperty];
}
private:
// Cache of shorthand subproperty counts.
mutable RangedArray<
uint32_t,
eCSSProperty_COUNT_no_shorthands,
eCSSProperty_COUNT - eCSSProperty_COUNT_no_shorthands> mSubpropertyCount;
mutable bool mSubpropertyCountInitialized;
};
/**
* Adaptor for PropertyPriorityComparator to sort objects which have
* a mProperty member.
*/
template <typename T>
class TPropertyPriorityComparator : PropertyPriorityComparator
{
public:
bool Equals(const T& aLhs, const T& aRhs) const
{
return PropertyPriorityComparator::Equals(aLhs.mProperty, aRhs.mProperty);
}
bool LessThan(const T& aLhs, const T& aRhs) const
{
return PropertyPriorityComparator::LessThan(aLhs.mProperty, aRhs.mProperty);
}
};
/**
* Iterator to walk through a PropertyValuePair array using the ordering
* provided by PropertyPriorityComparator.
*/
class PropertyPriorityIterator
{
public:
explicit PropertyPriorityIterator(
const nsTArray<PropertyValuePair>& aProperties)
: mProperties(aProperties)
{
mSortedPropertyIndices.SetCapacity(mProperties.Length());
for (size_t i = 0, len = mProperties.Length(); i < len; ++i) {
PropertyAndIndex propertyIndex = { mProperties[i].mProperty, i };
mSortedPropertyIndices.AppendElement(propertyIndex);
}
mSortedPropertyIndices.Sort(PropertyAndIndex::Comparator());
}
class Iter
{
public:
explicit Iter(const PropertyPriorityIterator& aParent)
: mParent(aParent)
, mIndex(0) { }
static Iter EndIter(const PropertyPriorityIterator &aParent)
{
Iter iter(aParent);
iter.mIndex = aParent.mSortedPropertyIndices.Length();
return iter;
}
bool operator!=(const Iter& aOther) const
{
return mIndex != aOther.mIndex;
}
Iter& operator++()
{
MOZ_ASSERT(mIndex + 1 <= mParent.mSortedPropertyIndices.Length(),
"Should not seek past end iterator");
mIndex++;
return *this;
}
const PropertyValuePair& operator*()
{
MOZ_ASSERT(mIndex < mParent.mSortedPropertyIndices.Length(),
"Should not try to dereference an end iterator");
return mParent.mProperties[mParent.mSortedPropertyIndices[mIndex].mIndex];
}
private:
const PropertyPriorityIterator& mParent;
size_t mIndex;
};
Iter begin() { return Iter(*this); }
Iter end() { return Iter::EndIter(*this); }
private:
struct PropertyAndIndex
{
nsCSSPropertyID mProperty;
size_t mIndex; // Index of mProperty within mProperties
typedef TPropertyPriorityComparator<PropertyAndIndex> Comparator;
};
const nsTArray<PropertyValuePair>& mProperties;
nsTArray<PropertyAndIndex> mSortedPropertyIndices;
};
/**
* A property-values pair obtained from the open-ended properties
* discovered on a regular keyframe or property-indexed keyframe object.
*
* Single values (as required by a regular keyframe, and as also supported
* on property-indexed keyframes) are stored as the only element in
* mValues.
*/
struct PropertyValuesPair
{
nsCSSPropertyID mProperty;
nsTArray<nsString> mValues;
typedef TPropertyPriorityComparator<PropertyValuesPair> Comparator;
};
/**
* An additional property (for a property-values pair) found on a
* BaseKeyframe or BasePropertyIndexedKeyframe object.
*/
struct AdditionalProperty
{
nsCSSPropertyID mProperty;
size_t mJsidIndex; // Index into |ids| in GetPropertyValuesPairs.
struct PropertyComparator
{
bool Equals(const AdditionalProperty& aLhs,
const AdditionalProperty& aRhs) const
{
return aLhs.mProperty == aRhs.mProperty;
}
bool LessThan(const AdditionalProperty& aLhs,
const AdditionalProperty& aRhs) const
{
return nsCSSProps::PropertyIDLNameSortPosition(aLhs.mProperty) <
nsCSSProps::PropertyIDLNameSortPosition(aRhs.mProperty);
}
};
};
/**
* Data for a segment in a keyframe animation of a given property
* whose value is a StyleAnimationValue.
*
* KeyframeValueEntry is used in GetAnimationPropertiesFromKeyframes
* to gather data for each individual segment.
*/
struct KeyframeValueEntry
{
nsCSSPropertyID mProperty;
StyleAnimationValue mValue;
float mOffset;
Maybe<ComputedTimingFunction> mTimingFunction;
struct PropertyOffsetComparator
{
static bool Equals(const KeyframeValueEntry& aLhs,
const KeyframeValueEntry& aRhs)
{
return aLhs.mProperty == aRhs.mProperty &&
aLhs.mOffset == aRhs.mOffset;
}
static bool LessThan(const KeyframeValueEntry& aLhs,
const KeyframeValueEntry& aRhs)
{
// First, sort by property IDL name.
int32_t order = nsCSSProps::PropertyIDLNameSortPosition(aLhs.mProperty) -
nsCSSProps::PropertyIDLNameSortPosition(aRhs.mProperty);
if (order != 0) {
return order < 0;
}
// Then, by offset.
return aLhs.mOffset < aRhs.mOffset;
}
};
};
class ComputedOffsetComparator
{
public:
static bool Equals(const Keyframe& aLhs, const Keyframe& aRhs)
{
return aLhs.mComputedOffset == aRhs.mComputedOffset;
}
static bool LessThan(const Keyframe& aLhs, const Keyframe& aRhs)
{
return aLhs.mComputedOffset < aRhs.mComputedOffset;
}
};
// ------------------------------------------------------------------
//
// Inlined helper methods
//
// ------------------------------------------------------------------
inline bool
IsInvalidValuePair(const PropertyValuePair& aPair)
{
// There are three types of values we store as token streams:
//
// * Shorthand values (where we manually extract the token stream's string
// value) and pass that along to various parsing methods
// * Longhand values with variable references
// * Invalid values
//
// We can distinguish between the last two cases because for invalid values
// we leave the token stream's mPropertyID as eCSSProperty_UNKNOWN.
return !nsCSSProps::IsShorthand(aPair.mProperty) &&
aPair.mValue.GetUnit() == eCSSUnit_TokenStream &&
aPair.mValue.GetTokenStreamValue()->mPropertyID
== eCSSProperty_UNKNOWN;
}
// ------------------------------------------------------------------
//
// Internal helper method declarations
//
// ------------------------------------------------------------------
static void
GetKeyframeListFromKeyframeSequence(JSContext* aCx,
nsIDocument* aDocument,
JS::ForOfIterator& aIterator,
nsTArray<Keyframe>& aResult,
ErrorResult& aRv);
static bool
ConvertKeyframeSequence(JSContext* aCx,
nsIDocument* aDocument,
JS::ForOfIterator& aIterator,
nsTArray<Keyframe>& aResult);
static bool
GetPropertyValuesPairs(JSContext* aCx,
JS::Handle<JSObject*> aObject,
ListAllowance aAllowLists,
nsTArray<PropertyValuesPair>& aResult);
static bool
AppendStringOrStringSequenceToArray(JSContext* aCx,
JS::Handle<JS::Value> aValue,
ListAllowance aAllowLists,
nsTArray<nsString>& aValues);
static bool
AppendValueAsString(JSContext* aCx,
nsTArray<nsString>& aValues,
JS::Handle<JS::Value> aValue);
static PropertyValuePair
MakePropertyValuePair(nsCSSPropertyID aProperty, const nsAString& aStringValue,
nsCSSParser& aParser, nsIDocument* aDocument);
static bool
HasValidOffsets(const nsTArray<Keyframe>& aKeyframes);
static void
MarkAsComputeValuesFailureKey(PropertyValuePair& aPair);
static bool
IsComputeValuesFailureKey(const PropertyValuePair& aPair);
static void
BuildSegmentsFromValueEntries(nsTArray<KeyframeValueEntry>& aEntries,
nsTArray<AnimationProperty>& aResult);
static void
GetKeyframeListFromPropertyIndexedKeyframe(JSContext* aCx,
nsIDocument* aDocument,
JS::Handle<JS::Value> aValue,
nsTArray<Keyframe>& aResult,
ErrorResult& aRv);
static bool
HasImplicitKeyframeValues(const nsTArray<Keyframe>& aKeyframes,
nsIDocument* aDocument);
static void
DistributeRange(const Range<Keyframe>& aSpacingRange,
const Range<Keyframe>& aRangeToAdjust);
static void
DistributeRange(const Range<Keyframe>& aSpacingRange);
static void
PaceRange(const Range<Keyframe>& aKeyframes,
const Range<double>& aCumulativeDistances);
static nsTArray<double>
GetCumulativeDistances(const nsTArray<ComputedKeyframeValues>& aValues,
nsCSSPropertyID aProperty,
nsStyleContext* aStyleContext);
// ------------------------------------------------------------------
//
// Public API
//
// ------------------------------------------------------------------
/* static */ nsTArray<Keyframe>
KeyframeUtils::GetKeyframesFromObject(JSContext* aCx,
nsIDocument* aDocument,
JS::Handle<JSObject*> aFrames,
ErrorResult& aRv)
{
MOZ_ASSERT(!aRv.Failed());
nsTArray<Keyframe> keyframes;
if (!aFrames) {
// The argument was explicitly null meaning no keyframes.
return keyframes;
}
// At this point we know we have an object. We try to convert it to a
// sequence of keyframes first, and if that fails due to not being iterable,
// we try to convert it to a property-indexed keyframe.
JS::Rooted<JS::Value> objectValue(aCx, JS::ObjectValue(*aFrames));
JS::ForOfIterator iter(aCx);
if (!iter.init(objectValue, JS::ForOfIterator::AllowNonIterable)) {
aRv.Throw(NS_ERROR_FAILURE);
return keyframes;
}
if (iter.valueIsIterable()) {
GetKeyframeListFromKeyframeSequence(aCx, aDocument, iter, keyframes, aRv);
} else {
GetKeyframeListFromPropertyIndexedKeyframe(aCx, aDocument, objectValue,
keyframes, aRv);
}
if (aRv.Failed()) {
MOZ_ASSERT(keyframes.IsEmpty(),
"Should not set any keyframes when there is an error");
return keyframes;
}
// We currently don't support additive animation. However, Web Animations
// says that if you don't have a keyframe at offset 0 or 1, then you should
// synthesize one using an additive zero value when you go to compose style.
// Until we implement additive animations we just throw if we encounter any
// set of keyframes that would put us in that situation and keyframes aren't
// explicitly force-enabled.
if (!nsDocument::AreWebAnimationsImplicitKeyframesEnabled(aCx, nullptr) &&
HasImplicitKeyframeValues(keyframes, aDocument)) {
keyframes.Clear();
aRv.Throw(NS_ERROR_DOM_ANIM_MISSING_PROPS_ERR);
}
return keyframes;
}
/* static */ void
KeyframeUtils::ApplySpacing(nsTArray<Keyframe>& aKeyframes,
SpacingMode aSpacingMode,
nsCSSPropertyID aProperty,
nsTArray<ComputedKeyframeValues>& aComputedValues,
nsStyleContext* aStyleContext)
{
if (aKeyframes.IsEmpty()) {
return;
}
nsTArray<double> cumulativeDistances;
if (aSpacingMode == SpacingMode::paced) {
MOZ_ASSERT(IsAnimatableProperty(aProperty),
"Paced property should be animatable");
cumulativeDistances = GetCumulativeDistances(aComputedValues, aProperty,
aStyleContext);
// Reset the computed offsets if using paced spacing.
for (Keyframe& keyframe : aKeyframes) {
keyframe.mComputedOffset = Keyframe::kComputedOffsetNotSet;
}
}
// If the first keyframe has an unspecified offset, fill it in with 0%.
// If there is only a single keyframe, then it gets 100%.
if (aKeyframes.Length() > 1) {
Keyframe& firstElement = aKeyframes[0];
firstElement.mComputedOffset = firstElement.mOffset.valueOr(0.0);
// We will fill in the last keyframe's offset below
} else {
Keyframe& lastElement = aKeyframes.LastElement();
lastElement.mComputedOffset = lastElement.mOffset.valueOr(1.0);
}
// Fill in remaining missing offsets.
const Keyframe* const last = aKeyframes.cend() - 1;
const RangedPtr<Keyframe> begin(aKeyframes.begin(), aKeyframes.Length());
RangedPtr<Keyframe> keyframeA = begin;
while (keyframeA != last) {
// Find keyframe A and keyframe B *between* which we will apply spacing.
RangedPtr<Keyframe> keyframeB = keyframeA + 1;
while (keyframeB->mOffset.isNothing() && keyframeB != last) {
++keyframeB;
}
keyframeB->mComputedOffset = keyframeB->mOffset.valueOr(1.0);
// Fill computed offsets in (keyframe A, keyframe B).
if (aSpacingMode == SpacingMode::distribute) {
DistributeRange(Range<Keyframe>(keyframeA, keyframeB + 1));
} else {
// a) Find Paced A (first paceable keyframe) and
// Paced B (last paceable keyframe) in [keyframe A, keyframe B].
RangedPtr<Keyframe> pacedA = keyframeA;
while (pacedA < keyframeB &&
cumulativeDistances[pacedA - begin] == kNotPaceable) {
++pacedA;
}
RangedPtr<Keyframe> pacedB = keyframeB;
while (pacedB > keyframeA &&
cumulativeDistances[pacedB - begin] == kNotPaceable) {
--pacedB;
}
// As spec says, if there is no paceable keyframe
// in [keyframe A, keyframe B], we let Paced A and Paced B refer to
// keyframe B.
if (pacedA > pacedB) {
pacedA = pacedB = keyframeB;
}
// b) Apply distributing offsets in (keyframe A, Paced A] and
// [Paced B, keyframe B).
DistributeRange(Range<Keyframe>(keyframeA, keyframeB + 1),
Range<Keyframe>(keyframeA + 1, pacedA + 1));
DistributeRange(Range<Keyframe>(keyframeA, keyframeB + 1),
Range<Keyframe>(pacedB, keyframeB));
// c) Apply paced offsets to each paceable keyframe in (Paced A, Paced B).
// We pass the range [Paced A, Paced B] since PaceRange needs the end
// points of the range in order to calculate the correct offset.
PaceRange(Range<Keyframe>(pacedA, pacedB + 1),
Range<double>(&cumulativeDistances[pacedA - begin],
pacedB - pacedA + 1));
// d) Fill in any computed offsets in (Paced A, Paced B) that are still
// not set (e.g. because the keyframe was not paceable, or because the
// cumulative distance between paceable properties was zero).
for (RangedPtr<Keyframe> frame = pacedA + 1; frame < pacedB; ++frame) {
if (frame->mComputedOffset != Keyframe::kComputedOffsetNotSet) {
continue;
}
RangedPtr<Keyframe> start = frame - 1;
RangedPtr<Keyframe> end = frame + 1;
while (end < pacedB &&
end->mComputedOffset == Keyframe::kComputedOffsetNotSet) {
++end;
}
DistributeRange(Range<Keyframe>(start, end + 1));
frame = end;
}
}
keyframeA = keyframeB;
}
}
/* static */ void
KeyframeUtils::ApplyDistributeSpacing(nsTArray<Keyframe>& aKeyframes)
{
nsTArray<ComputedKeyframeValues> emptyArray;
ApplySpacing(aKeyframes, SpacingMode::distribute, eCSSProperty_UNKNOWN,
emptyArray, nullptr);
}
/* static */ nsTArray<ComputedKeyframeValues>
KeyframeUtils::GetComputedKeyframeValues(const nsTArray<Keyframe>& aKeyframes,
dom::Element* aElement,
nsStyleContext* aStyleContext)
{
MOZ_ASSERT(aStyleContext);
MOZ_ASSERT(aElement);
const size_t len = aKeyframes.Length();
nsTArray<ComputedKeyframeValues> result(len);
for (const Keyframe& frame : aKeyframes) {
nsCSSPropertyIDSet propertiesOnThisKeyframe;
ComputedKeyframeValues* computedValues = result.AppendElement();
for (const PropertyValuePair& pair :
PropertyPriorityIterator(frame.mPropertyValues)) {
if (IsInvalidValuePair(pair)) {
continue;
}
// Expand each value into the set of longhands and produce
// a KeyframeValueEntry for each value.
nsTArray<PropertyStyleAnimationValuePair> values;
// For shorthands, we store the string as a token stream so we need to
// extract that first.
if (nsCSSProps::IsShorthand(pair.mProperty)) {
nsCSSValueTokenStream* tokenStream = pair.mValue.GetTokenStreamValue();
if (!StyleAnimationValue::ComputeValues(pair.mProperty,
CSSEnabledState::eForAllContent, aElement, aStyleContext,
tokenStream->mTokenStream, /* aUseSVGMode */ false, values) ||
IsComputeValuesFailureKey(pair)) {
continue;
}
} else {
if (!StyleAnimationValue::ComputeValues(pair.mProperty,
CSSEnabledState::eForAllContent, aElement, aStyleContext,
pair.mValue, /* aUseSVGMode */ false, values)) {
continue;
}
MOZ_ASSERT(values.Length() == 1,
"Longhand properties should produce a single"
" StyleAnimationValue");
}
for (auto& value : values) {
// If we already got a value for this property on the keyframe,
// skip this one.
if (propertiesOnThisKeyframe.HasProperty(value.mProperty)) {
continue;
}
computedValues->AppendElement(value);
propertiesOnThisKeyframe.AddProperty(value.mProperty);
}
}
}
MOZ_ASSERT(result.Length() == aKeyframes.Length(), "Array length mismatch");
return result;
}
/* static */ nsTArray<AnimationProperty>
KeyframeUtils::GetAnimationPropertiesFromKeyframes(
const nsTArray<Keyframe>& aKeyframes,
const nsTArray<ComputedKeyframeValues>& aComputedValues,
nsStyleContext* aStyleContext)
{
MOZ_ASSERT(aKeyframes.Length() == aComputedValues.Length(),
"Array length mismatch");
nsTArray<KeyframeValueEntry> entries(aKeyframes.Length());
const size_t len = aKeyframes.Length();
for (size_t i = 0; i < len; ++i) {
const Keyframe& frame = aKeyframes[i];
for (auto& value : aComputedValues[i]) {
MOZ_ASSERT(frame.mComputedOffset != Keyframe::kComputedOffsetNotSet,
"Invalid computed offset");
KeyframeValueEntry* entry = entries.AppendElement();
entry->mOffset = frame.mComputedOffset;
entry->mProperty = value.mProperty;
entry->mValue = value.mValue;
entry->mTimingFunction = frame.mTimingFunction;
}
}
nsTArray<AnimationProperty> result;
BuildSegmentsFromValueEntries(entries, result);
return result;
}
/* static */ bool
KeyframeUtils::IsAnimatableProperty(nsCSSPropertyID aProperty)
{
if (aProperty == eCSSProperty_UNKNOWN) {
return false;
}
if (!nsCSSProps::IsShorthand(aProperty)) {
return nsCSSProps::kAnimTypeTable[aProperty] != eStyleAnimType_None;
}
CSSPROPS_FOR_SHORTHAND_SUBPROPERTIES(subprop, aProperty,
CSSEnabledState::eForAllContent) {
if (nsCSSProps::kAnimTypeTable[*subprop] != eStyleAnimType_None) {
return true;
}
}
return false;
}
// ------------------------------------------------------------------
//
// Internal helpers
//
// ------------------------------------------------------------------
/**
* Converts a JS object to an IDL sequence<Keyframe>.
*
* @param aCx The JSContext corresponding to |aIterator|.
* @param aDocument The document to use when parsing CSS properties.
* @param aIterator An already-initialized ForOfIterator for the JS
* object to iterate over as a sequence.
* @param aResult The array into which the resulting Keyframe objects will be
* appended.
* @param aRv Out param to store any errors thrown by this function.
*/
static void
GetKeyframeListFromKeyframeSequence(JSContext* aCx,
nsIDocument* aDocument,
JS::ForOfIterator& aIterator,
nsTArray<Keyframe>& aResult,
ErrorResult& aRv)
{
MOZ_ASSERT(!aRv.Failed());
MOZ_ASSERT(aResult.IsEmpty());
// Convert the object in aIterator to a sequence of keyframes producing
// an array of Keyframe objects.
if (!ConvertKeyframeSequence(aCx, aDocument, aIterator, aResult)) {
aRv.Throw(NS_ERROR_FAILURE);
aResult.Clear();
return;
}
// If the sequence<> had zero elements, we won't generate any
// keyframes.
if (aResult.IsEmpty()) {
return;
}
// Check that the keyframes are loosely sorted and with values all
// between 0% and 100%.
if (!HasValidOffsets(aResult)) {
aRv.ThrowTypeError<dom::MSG_INVALID_KEYFRAME_OFFSETS>();
aResult.Clear();
return;
}
}
/**
* Converts a JS object wrapped by the given JS::ForIfIterator to an
* IDL sequence<Keyframe> and stores the resulting Keyframe objects in
* aResult.
*/
static bool
ConvertKeyframeSequence(JSContext* aCx,
nsIDocument* aDocument,
JS::ForOfIterator& aIterator,
nsTArray<Keyframe>& aResult)
{
JS::Rooted<JS::Value> value(aCx);
nsCSSParser parser(aDocument->CSSLoader());
for (;;) {
bool done;
if (!aIterator.next(&value, &done)) {
return false;
}
if (done) {
break;
}
// Each value found when iterating the object must be an object
// or null/undefined (which gets treated as a default {} dictionary
// value).
if (!value.isObject() && !value.isNullOrUndefined()) {
dom::ThrowErrorMessage(aCx, dom::MSG_NOT_OBJECT,
"Element of sequence<Keyframe> argument");
return false;
}
// Convert the JS value into a BaseKeyframe dictionary value.
dom::binding_detail::FastBaseKeyframe keyframeDict;
if (!keyframeDict.Init(aCx, value,
"Element of sequence<Keyframe> argument")) {
return false;
}
Keyframe* keyframe = aResult.AppendElement(fallible);
if (!keyframe) {
return false;
}
if (!keyframeDict.mOffset.IsNull()) {
keyframe->mOffset.emplace(keyframeDict.mOffset.Value());
}
ErrorResult rv;
keyframe->mTimingFunction =
TimingParams::ParseEasing(keyframeDict.mEasing, aDocument, rv);
if (rv.MaybeSetPendingException(aCx)) {
return false;
}
// Look for additional property-values pairs on the object.
nsTArray<PropertyValuesPair> propertyValuePairs;
if (value.isObject()) {
JS::Rooted<JSObject*> object(aCx, &value.toObject());
if (!GetPropertyValuesPairs(aCx, object,
ListAllowance::eDisallow,
propertyValuePairs)) {
return false;
}
}
for (PropertyValuesPair& pair : propertyValuePairs) {
MOZ_ASSERT(pair.mValues.Length() == 1);
keyframe->mPropertyValues.AppendElement(
MakePropertyValuePair(pair.mProperty, pair.mValues[0], parser,
aDocument));
// When we go to convert keyframes into arrays of property values we
// call StyleAnimation::ComputeValues. This should normally return true
// but in order to test the case where it does not, BaseKeyframeDict
// includes a chrome-only member that can be set to indicate that
// ComputeValues should fail for shorthand property values on that
// keyframe.
if (nsCSSProps::IsShorthand(pair.mProperty) &&
keyframeDict.mSimulateComputeValuesFailure) {
MarkAsComputeValuesFailureKey(keyframe->mPropertyValues.LastElement());
}
}
}
return true;
}
/**
* Reads the property-values pairs from the specified JS object.
*
* @param aObject The JS object to look at.
* @param aAllowLists If eAllow, values will be converted to
* (DOMString or sequence<DOMString); if eDisallow, values
* will be converted to DOMString.
* @param aResult The array into which the enumerated property-values
* pairs will be stored.
* @return false on failure or JS exception thrown while interacting
* with aObject; true otherwise.
*/
static bool
GetPropertyValuesPairs(JSContext* aCx,
JS::Handle<JSObject*> aObject,
ListAllowance aAllowLists,
nsTArray<PropertyValuesPair>& aResult)
{
nsTArray<AdditionalProperty> properties;
// Iterate over all the properties on aObject and append an
// entry to properties for them.
//
// We don't compare the jsids that we encounter with those for
// the explicit dictionary members, since we know that none
// of the CSS property IDL names clash with them.
JS::Rooted<JS::IdVector> ids(aCx, JS::IdVector(aCx));
if (!JS_Enumerate(aCx, aObject, &ids)) {
return false;
}
for (size_t i = 0, n = ids.length(); i < n; i++) {
nsAutoJSString propName;
if (!propName.init(aCx, ids[i])) {
return false;
}
nsCSSPropertyID property =
nsCSSProps::LookupPropertyByIDLName(propName,
CSSEnabledState::eForAllContent);
if (KeyframeUtils::IsAnimatableProperty(property)) {
AdditionalProperty* p = properties.AppendElement();
p->mProperty = property;
p->mJsidIndex = i;
}
}
// Sort the entries by IDL name and then get each value and
// convert it either to a DOMString or to a
// (DOMString or sequence<DOMString>), depending on aAllowLists,
// and build up aResult.
properties.Sort(AdditionalProperty::PropertyComparator());
for (AdditionalProperty& p : properties) {
JS::Rooted<JS::Value> value(aCx);
if (!JS_GetPropertyById(aCx, aObject, ids[p.mJsidIndex], &value)) {
return false;
}
PropertyValuesPair* pair = aResult.AppendElement();
pair->mProperty = p.mProperty;
if (!AppendStringOrStringSequenceToArray(aCx, value, aAllowLists,
pair->mValues)) {
return false;
}
}
return true;
}
/**
* Converts aValue to DOMString, if aAllowLists is eDisallow, or
* to (DOMString or sequence<DOMString>) if aAllowLists is aAllow.
* The resulting strings are appended to aValues.
*/
static bool
AppendStringOrStringSequenceToArray(JSContext* aCx,
JS::Handle<JS::Value> aValue,
ListAllowance aAllowLists,
nsTArray<nsString>& aValues)
{
if (aAllowLists == ListAllowance::eAllow && aValue.isObject()) {
// The value is an object, and we want to allow lists; convert
// aValue to (DOMString or sequence<DOMString>).
JS::ForOfIterator iter(aCx);
if (!iter.init(aValue, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (iter.valueIsIterable()) {
// If the object is iterable, convert it to sequence<DOMString>.
JS::Rooted<JS::Value> element(aCx);
for (;;) {
bool done;
if (!iter.next(&element, &done)) {
return false;
}
if (done) {
break;
}
if (!AppendValueAsString(aCx, aValues, element)) {
return false;
}
}
return true;
}
}
// Either the object is not iterable, or aAllowLists doesn't want
// a list; convert it to DOMString.
if (!AppendValueAsString(aCx, aValues, aValue)) {
return false;
}
return true;
}
/**
* Converts aValue to DOMString and appends it to aValues.
*/
static bool
AppendValueAsString(JSContext* aCx,
nsTArray<nsString>& aValues,
JS::Handle<JS::Value> aValue)
{
return ConvertJSValueToString(aCx, aValue, dom::eStringify, dom::eStringify,
*aValues.AppendElement());
}
/**
* Construct a PropertyValuePair parsing the given string into a suitable
* nsCSSValue object.
*
* @param aProperty The CSS property.
* @param aStringValue The property value to parse.
* @param aParser The CSS parser object to use.
* @param aDocument The document to use when parsing.
* @return The constructed PropertyValuePair object.
*/
static PropertyValuePair
MakePropertyValuePair(nsCSSPropertyID aProperty, const nsAString& aStringValue,
nsCSSParser& aParser, nsIDocument* aDocument)
{
MOZ_ASSERT(aDocument);
PropertyValuePair result;
result.mProperty = aProperty;
nsCSSValue value;
if (!nsCSSProps::IsShorthand(aProperty)) {
aParser.ParseLonghandProperty(aProperty,
aStringValue,
aDocument->GetDocumentURI(),
aDocument->GetDocumentURI(),
aDocument->NodePrincipal(),
value);
}
if (value.GetUnit() == eCSSUnit_Null) {
// Either we have a shorthand, or we failed to parse a longhand.
// In either case, store the string value as a token stream.
nsCSSValueTokenStream* tokenStream = new nsCSSValueTokenStream;
tokenStream->mTokenStream = aStringValue;
// We are about to convert a null value to a token stream value but
// by leaving the mPropertyID as unknown, we will be able to
// distinguish between invalid values and valid token stream values