aboutsummaryrefslogtreecommitdiffstats
path: root/components/style/properties/helpers/animated_properties.mako.rs
blob: 1af4268b32d9b758a6d0bc452606843db2ff041f (plain) (blame)
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
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
/* 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/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

<% from data import SYSTEM_FONT_LONGHANDS %>

use app_units::Au;
use cssparser::{Parser, RGBA};
use euclid::{Point2D, Size2D};
#[cfg(feature = "gecko")] use gecko_bindings::bindings::RawServoAnimationValueMap;
#[cfg(feature = "gecko")] use gecko_bindings::structs::RawGeckoGfxMatrix4x4;
#[cfg(feature = "gecko")] use gecko_bindings::structs::nsCSSPropertyID;
#[cfg(feature = "gecko")] use gecko_bindings::sugar::ownership::{HasFFI, HasSimpleFFI};
#[cfg(feature = "gecko")] use gecko_string_cache::Atom;
use properties::{CSSWideKeyword, PropertyDeclaration};
use properties::longhands;
use properties::longhands::font_weight::computed_value::T as FontWeight;
use properties::longhands::font_stretch::computed_value::T as FontStretch;
use properties::longhands::transform::computed_value::ComputedMatrix;
use properties::longhands::transform::computed_value::ComputedOperation as TransformOperation;
use properties::longhands::transform::computed_value::T as TransformList;
use properties::longhands::vertical_align::computed_value::T as VerticalAlign;
use properties::longhands::visibility::computed_value::T as Visibility;
#[cfg(feature = "gecko")] use properties::{PropertyDeclarationId, LonghandId};
use selectors::parser::SelectorParseError;
use smallvec::SmallVec;
use std::cmp;
#[cfg(feature = "gecko")] use fnv::FnvHashMap;
use style_traits::ParseError;
use super::ComputedValues;
#[cfg(any(feature = "gecko", feature = "testing"))]
use values::Auto;
use values::{CSSFloat, CustomIdent, Either};
use values::animated::ToAnimatedValue;
use values::animated::effects::BoxShadowList as AnimatedBoxShadowList;
use values::animated::effects::Filter as AnimatedFilter;
use values::animated::effects::FilterList as AnimatedFilterList;
use values::animated::effects::TextShadowList as AnimatedTextShadowList;
use values::computed::{Angle, LengthOrPercentageOrAuto, LengthOrPercentageOrNone};
use values::computed::{BorderCornerRadius, ClipRect};
use values::computed::{CalcLengthOrPercentage, Color, Context, ComputedValueAsSpecified};
use values::computed::{LengthOrPercentage, MaxLength, MozLength, ToComputedValue};
use values::generics::{SVGPaint, SVGPaintKind};
use values::generics::border::BorderCornerRadius as GenericBorderCornerRadius;
use values::generics::effects::Filter;
use values::generics::position as generic_position;
use values::specified::length::Percentage;


/// A longhand property whose animation type is not "none".
///
/// NOTE: This includes the 'display' property since it is animatable from SMIL even though it is
/// not animatable from CSS animations or Web Animations. CSS transitions also does not allow
/// animating 'display', but for CSS transitions we have the separate TransitionProperty type.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum AnimatableLonghand {
    % for prop in data.longhands:
        % if prop.animatable:
            /// ${prop.name}
            ${prop.camel_case},
        % endif
    % endfor
}

impl AnimatableLonghand {
    /// Returns true if this AnimatableLonghand is one of the discretely animatable properties.
    pub fn is_discrete(&self) -> bool {
        match *self {
            % for prop in data.longhands:
                % if prop.animation_value_type == "discrete":
                    AnimatableLonghand::${prop.camel_case} => true,
                % endif
            % endfor
            _ => false
        }
    }

    /// Converts from an nsCSSPropertyID. Returns None if nsCSSPropertyID is not an animatable
    /// longhand in Servo.
    #[cfg(feature = "gecko")]
    pub fn from_nscsspropertyid(css_property: nsCSSPropertyID) -> Option<Self> {
        match css_property {
            % for prop in data.longhands:
                % if prop.animatable:
                    ${helpers.to_nscsspropertyid(prop.ident)}
                        => Some(AnimatableLonghand::${prop.camel_case}),
                % endif
            % endfor
            _ => None
        }
    }

    /// Converts from TransitionProperty. Returns None if the property is not an animatable
    /// longhand.
    pub fn from_transition_property(transition_property: &TransitionProperty) -> Option<Self> {
        match *transition_property {
            % for prop in data.longhands:
                % if prop.transitionable and prop.animatable:
                    TransitionProperty::${prop.camel_case}
                        => Some(AnimatableLonghand::${prop.camel_case}),
                % endif
            % endfor
            _ => None
        }
    }

    /// Get an animatable longhand property from a property declaration.
    pub fn from_declaration(declaration: &PropertyDeclaration) -> Option<Self> {
        use properties::LonghandId;
        match *declaration {
            % for prop in data.longhands:
                % if prop.animatable:
                    PropertyDeclaration::${prop.camel_case}(..)
                        => Some(AnimatableLonghand::${prop.camel_case}),
                % endif
            % endfor
            PropertyDeclaration::CSSWideKeyword(id, _) |
            PropertyDeclaration::WithVariables(id, _) => {
                match id {
                    % for prop in data.longhands:
                        % if prop.animatable:
                            LonghandId::${prop.camel_case} =>
                                Some(AnimatableLonghand::${prop.camel_case}),
                        % endif
                    % endfor
                    _ => None,
                }
            },
            _ => None,
        }
    }
}

/// Convert to nsCSSPropertyID.
#[cfg(feature = "gecko")]
#[allow(non_upper_case_globals)]
impl<'a> From< &'a AnimatableLonghand> for nsCSSPropertyID {
    fn from(property: &'a AnimatableLonghand) -> nsCSSPropertyID {
        match *property {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimatableLonghand::${prop.camel_case}
                        => ${helpers.to_nscsspropertyid(prop.ident)},
                % endif
            % endfor
        }
    }
}

/// Convert to PropertyDeclarationId.
#[cfg(feature = "gecko")]
#[allow(non_upper_case_globals)]
impl<'a> From<AnimatableLonghand> for PropertyDeclarationId<'a> {
    fn from(property: AnimatableLonghand) -> PropertyDeclarationId<'a> {
        match property {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimatableLonghand::${prop.camel_case}
                        => PropertyDeclarationId::Longhand(LonghandId::${prop.camel_case}),
                % endif
            % endfor
        }
    }
}

/// Returns true if this nsCSSPropertyID is one of the animatable properties.
#[cfg(feature = "gecko")]
pub fn nscsspropertyid_is_animatable(property: nsCSSPropertyID) -> bool {
    match property {
        % for prop in data.longhands + data.shorthands_except_all():
            % if prop.animatable:
                ${helpers.to_nscsspropertyid(prop.ident)} => true,
            % endif
        % endfor
        _ => false
    }
}

/// A given transition property, that is either `All`, a transitionable longhand property,
/// a shorthand with at least one transitionable longhand component, or an unsupported property.
// NB: This needs to be here because it needs all the longhands generated
// beforehand.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Debug, Eq, Hash, PartialEq, ToCss)]
pub enum TransitionProperty {
    /// All, any transitionable property changing should generate a transition.
    All,
    % for prop in data.longhands + data.shorthands_except_all():
        % if prop.transitionable:
            /// ${prop.name}
            ${prop.camel_case},
        % endif
    % endfor
    /// Unrecognized property which could be any non-transitionable, custom property, or
    /// unknown property.
    Unsupported(CustomIdent)
}

no_viewport_percentage!(TransitionProperty);

impl ComputedValueAsSpecified for TransitionProperty {}

impl TransitionProperty {
    /// Iterates over each longhand property.
    pub fn each<F: FnMut(&TransitionProperty) -> ()>(mut cb: F) {
        % for prop in data.longhands:
            % if prop.transitionable:
                cb(&TransitionProperty::${prop.camel_case});
            % endif
        % endfor
    }

    /// Iterates over every longhand property that is not TransitionProperty::All, stopping and
    /// returning true when the provided callback returns true for the first time.
    pub fn any<F: FnMut(&TransitionProperty) -> bool>(mut cb: F) -> bool {
        % for prop in data.longhands:
            % if prop.transitionable:
                if cb(&TransitionProperty::${prop.camel_case}) {
                    return true;
                }
            % endif
        % endfor
        false
    }

    /// Parse a transition-property value.
    pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
        let ident = input.expect_ident()?;
        let supported = match_ignore_ascii_case! { &ident,
            "all" => Ok(Some(TransitionProperty::All)),
            % for prop in data.longhands + data.shorthands_except_all():
                % if prop.transitionable:
                    "${prop.name}" => Ok(Some(TransitionProperty::${prop.camel_case})),
                % endif
            % endfor
            "none" => Err(()),
            _ => Ok(None),
        };

        match supported {
            Ok(Some(property)) => Ok(property),
            Ok(None) => CustomIdent::from_ident(ident, &[]).map(TransitionProperty::Unsupported),
            Err(()) => Err(SelectorParseError::UnexpectedIdent(ident).into()),
        }
    }

    /// Return transitionable longhands of this shorthand TransitionProperty, except for "all".
    pub fn longhands(&self) -> &'static [TransitionProperty] {
        % for prop in data.shorthands_except_all():
            % if prop.transitionable:
                static ${prop.ident.upper()}: &'static [TransitionProperty] = &[
                    % for sub in prop.sub_properties:
                        % if sub.transitionable:
                            TransitionProperty::${sub.camel_case},
                        % endif
                    % endfor
                ];
            % endif
        % endfor
        match *self {
            % for prop in data.shorthands_except_all():
                % if prop.transitionable:
                    TransitionProperty::${prop.camel_case} => ${prop.ident.upper()},
                % endif
            % endfor
            _ => panic!("Not allowed to call longhands() for this TransitionProperty")
        }
    }

    /// Returns true if this TransitionProperty is a shorthand.
    pub fn is_shorthand(&self) -> bool {
        match *self {
            % for prop in data.shorthands_except_all():
                % if prop.transitionable:
                    TransitionProperty::${prop.camel_case} => true,
                % endif
            % endfor
            _ => false
        }
    }
}

/// Convert to nsCSSPropertyID.
#[cfg(feature = "gecko")]
#[allow(non_upper_case_globals)]
impl<'a> From< &'a TransitionProperty> for nsCSSPropertyID {
    fn from(transition_property: &'a TransitionProperty) -> nsCSSPropertyID {
        match *transition_property {
            % for prop in data.longhands + data.shorthands_except_all():
                % if prop.transitionable:
                    TransitionProperty::${prop.camel_case}
                        => ${helpers.to_nscsspropertyid(prop.ident)},
                % endif
            % endfor
            TransitionProperty::All => nsCSSPropertyID::eCSSPropertyExtra_all_properties,
            _ => panic!("Unconvertable Servo transition property: {:?}", transition_property),
        }
    }
}

/// Convert nsCSSPropertyID to TransitionProperty
#[cfg(feature = "gecko")]
#[allow(non_upper_case_globals)]
impl From<nsCSSPropertyID> for TransitionProperty {
    fn from(property: nsCSSPropertyID) -> TransitionProperty {
        match property {
            % for prop in data.longhands + data.shorthands_except_all():
                % if prop.transitionable:
                    ${helpers.to_nscsspropertyid(prop.ident)}
                        => TransitionProperty::${prop.camel_case},
                % else:
                    ${helpers.to_nscsspropertyid(prop.ident)}
                        => TransitionProperty::Unsupported(CustomIdent(Atom::from("${prop.ident}"))),
                % endif
            % endfor
            nsCSSPropertyID::eCSSPropertyExtra_all_properties => TransitionProperty::All,
            _ => panic!("Unconvertable nsCSSPropertyID: {:?}", property),
        }
    }
}

/// Returns true if this nsCSSPropertyID is one of the transitionable properties.
#[cfg(feature = "gecko")]
pub fn nscsspropertyid_is_transitionable(property: nsCSSPropertyID) -> bool {
    match property {
        % for prop in data.longhands + data.shorthands_except_all():
            % if prop.transitionable:
                ${helpers.to_nscsspropertyid(prop.ident)} => true,
            % endif
        % endfor
        _ => false
    }
}

/// An animated property interpolation between two computed values for that
/// property.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum AnimatedProperty {
    % for prop in data.longhands:
        % if prop.animatable:
            <%
                if prop.is_animatable_with_computed_value:
                    value_type = "longhands::{}::computed_value::T".format(prop.ident)
                else:
                    value_type = prop.animation_value_type
            %>
            /// ${prop.name}
            ${prop.camel_case}(${value_type}, ${value_type}),
        % endif
    % endfor
}

impl AnimatedProperty {
    /// Get the name of this property.
    pub fn name(&self) -> &'static str {
        match *self {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimatedProperty::${prop.camel_case}(..) => "${prop.name}",
                % endif
            % endfor
        }
    }

    /// Whether this interpolation does animate, that is, whether the start and
    /// end values are different.
    pub fn does_animate(&self) -> bool {
        match *self {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimatedProperty::${prop.camel_case}(ref from, ref to) => from != to,
                % endif
            % endfor
        }
    }

    /// Whether an animated property has the same end value as another.
    pub fn has_the_same_end_value_as(&self, other: &Self) -> bool {
        match (self, other) {
            % for prop in data.longhands:
                % if prop.animatable:
                    (&AnimatedProperty::${prop.camel_case}(_, ref this_end_value),
                     &AnimatedProperty::${prop.camel_case}(_, ref other_end_value)) => {
                        this_end_value == other_end_value
                    }
                % endif
            % endfor
            _ => false,
        }
    }

    /// Update `style` with the proper computed style corresponding to this
    /// animation at `progress`.
    pub fn update(&self, style: &mut ComputedValues, progress: f64) {
        match *self {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimatedProperty::${prop.camel_case}(ref from, ref to) => {
                        // https://w3c.github.io/web-animations/#discrete-animation-type
                        % if prop.animation_value_type == "discrete":
                            let value = if progress < 0.5 { from.clone() } else { to.clone() };
                        % else:
                            let value = match from.interpolate(to, progress) {
                                Ok(value) => value,
                                Err(()) => return,
                            };
                        % endif
                        % if not prop.is_animatable_with_computed_value:
                            let value: longhands::${prop.ident}::computed_value::T =
                                ToAnimatedValue::from_animated_value(value);
                        % endif
                        <% method = "style.mutate_" + prop.style_struct.ident.strip("_") + "().set_" + prop.ident %>
                        % if prop.has_uncacheable_values is "True":
                            ${method}(value, &mut false);
                        % else:
                            ${method}(value);
                        % endif
                    }
                % endif
            % endfor
        }
    }

    /// Get an animatable value from a transition-property, an old style, and a
    /// new style.
    pub fn from_animatable_longhand(property: &AnimatableLonghand,
                                    old_style: &ComputedValues,
                                    new_style: &ComputedValues)
                                    -> AnimatedProperty {
        match *property {
            % for prop in data.longhands:
            % if prop.animatable:
                AnimatableLonghand::${prop.camel_case} => {
                    let old_computed = old_style.get_${prop.style_struct.ident.strip("_")}().clone_${prop.ident}();
                    let new_computed = new_style.get_${prop.style_struct.ident.strip("_")}().clone_${prop.ident}();
                    AnimatedProperty::${prop.camel_case}(
                    % if prop.is_animatable_with_computed_value:
                        old_computed,
                        new_computed,
                    % else:
                        old_computed.to_animated_value(),
                        new_computed.to_animated_value(),
                    % endif
                    )
                }
            % endif
            % endfor
        }
    }
}

/// A collection of AnimationValue that were composed on an element.
/// This HashMap stores the values that are the last AnimationValue to be
/// composed for each TransitionProperty.
#[cfg(feature = "gecko")]
pub type AnimationValueMap = FnvHashMap<AnimatableLonghand, AnimationValue>;
#[cfg(feature = "gecko")]
unsafe impl HasFFI for AnimationValueMap {
    type FFIType = RawServoAnimationValueMap;
}
#[cfg(feature = "gecko")]
unsafe impl HasSimpleFFI for AnimationValueMap {}

/// An enum to represent a single computed value belonging to an animated
/// property in order to be interpolated with another one. When interpolating,
/// both values need to belong to the same property.
///
/// This is different to AnimatedProperty in the sense that AnimatedProperty
/// also knows the final value to be used during the animation.
///
/// This is to be used in Gecko integration code.
///
/// FIXME: We need to add a path for custom properties, but that's trivial after
/// this (is a similar path to that of PropertyDeclaration).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum AnimationValue {
    % for prop in data.longhands:
        % if prop.animatable:
            /// ${prop.name}
            % if prop.is_animatable_with_computed_value:
                ${prop.camel_case}(longhands::${prop.ident}::computed_value::T),
            % else:
                ${prop.camel_case}(${prop.animation_value_type}),
            % endif
        % endif
    % endfor
}

impl AnimationValue {
    /// "Uncompute" this animation value in order to be used inside the CSS
    /// cascade.
    pub fn uncompute(&self) -> PropertyDeclaration {
        use properties::longhands;
        match *self {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimationValue::${prop.camel_case}(ref from) => {
                        PropertyDeclaration::${prop.camel_case}(
                            % if prop.boxed:
                            Box::new(
                            % endif
                                longhands::${prop.ident}::SpecifiedValue::from_computed_value(
                                % if prop.is_animatable_with_computed_value:
                                    from
                                % else:
                                    &ToAnimatedValue::from_animated_value(from.clone())
                                % endif
                                ))
                            % if prop.boxed:
                            )
                            % endif
                    }
                % endif
            % endfor
        }
    }

    /// Construct an AnimationValue from a property declaration
    pub fn from_declaration(decl: &PropertyDeclaration, context: &mut Context,
                            initial: &ComputedValues) -> Option<Self> {
        use error_reporting::create_error_reporter;
        use properties::LonghandId;
        use properties::DeclaredValue;

        match *decl {
            % for prop in data.longhands:
            % if prop.animatable:
            PropertyDeclaration::${prop.camel_case}(ref val) => {
            % if prop.ident in SYSTEM_FONT_LONGHANDS and product == "gecko":
                if let Some(sf) = val.get_system() {
                    longhands::system_font::resolve_system_font(sf, context);
                }
            % endif
            let computed = val.to_computed_value(context);
            Some(AnimationValue::${prop.camel_case}(
            % if prop.is_animatable_with_computed_value:
                computed
            % else:
                computed.to_animated_value()
            % endif
            ))
            },
            % endif
            % endfor
            PropertyDeclaration::CSSWideKeyword(id, keyword) => {
                match id {
                    // We put all the animatable properties first in the hopes
                    // that it might increase match locality.
                    % for prop in data.longhands:
                    % if prop.animatable:
                    LonghandId::${prop.camel_case} => {
                        let computed = match keyword {
                            % if not prop.style_struct.inherited:
                                CSSWideKeyword::Unset |
                            % endif
                            CSSWideKeyword::Initial => {
                                let initial_struct = initial.get_${prop.style_struct.name_lower}();
                                initial_struct.clone_${prop.ident}()
                            },
                            % if prop.style_struct.inherited:
                                CSSWideKeyword::Unset |
                            % endif
                            CSSWideKeyword::Inherit => {
                                let inherit_struct = context.inherited_style
                                                            .get_${prop.style_struct.name_lower}();
                                inherit_struct.clone_${prop.ident}()
                            },
                        };
                        % if not prop.is_animatable_with_computed_value:
                        let computed = computed.to_animated_value();
                        % endif
                        Some(AnimationValue::${prop.camel_case}(computed))
                    },
                    % endif
                    % endfor
                    % for prop in data.longhands:
                    % if not prop.animatable:
                    LonghandId::${prop.camel_case} => None,
                    % endif
                    % endfor
                }
            },
            PropertyDeclaration::WithVariables(id, ref variables) => {
                let custom_props = context.style().custom_properties();
                let reporter = create_error_reporter();
                match id {
                    % for prop in data.longhands:
                    % if prop.animatable:
                    LonghandId::${prop.camel_case} => {
                        let mut result = None;
                        let quirks_mode = context.quirks_mode;
                        ::properties::substitute_variables_${prop.ident}_slow(
                            &variables.css,
                            variables.first_token_type,
                            &variables.url_data,
                            variables.from_shorthand,
                            &custom_props,
                            &mut |v| {
                                let declaration = match *v {
                                    DeclaredValue::Value(value) => {
                                        PropertyDeclaration::${prop.camel_case}(value.clone())
                                    },
                                    DeclaredValue::CSSWideKeyword(keyword) => {
                                        PropertyDeclaration::CSSWideKeyword(id, keyword)
                                    },
                                    DeclaredValue::WithVariables(_) => unreachable!(),
                                };
                                result = AnimationValue::from_declaration(&declaration, context, initial);
                            },
                            &reporter,
                            quirks_mode);
                        result
                    },
                    % else:
                    LonghandId::${prop.camel_case} => None,
                    % endif
                    % endfor
                }
            },
            _ => None // non animatable properties will get included because of shorthands. ignore.
        }
    }

    /// Get an AnimationValue for an AnimatableLonghand from a given computed values.
    pub fn from_computed_values(property: &AnimatableLonghand,
                                computed_values: &ComputedValues)
                                -> Self {
        match *property {
            % for prop in data.longhands:
                % if prop.animatable:
                    AnimatableLonghand::${prop.camel_case} => {
                        let computed = computed_values
                            .get_${prop.style_struct.ident.strip("_")}()
                            .clone_${prop.ident}();
                        AnimationValue::${prop.camel_case}(
                        % if prop.is_animatable_with_computed_value:
                            computed
                        % else:
                            computed.to_animated_value()
                        % endif
                        )
                    }
                % endif
            % endfor
        }
    }
}

impl Animatable for AnimationValue {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
        -> Result<Self, ()> {
        match (self, other) {
            % for prop in data.longhands:
                % if prop.animatable:
                    (&AnimationValue::${prop.camel_case}(ref from),
                     &AnimationValue::${prop.camel_case}(ref to)) => {
                        % if prop.animation_value_type == "discrete":
                            if self_portion > other_portion {
                                Ok(AnimationValue::${prop.camel_case}(from.clone()))
                            } else {
                                Ok(AnimationValue::${prop.camel_case}(to.clone()))
                            }
                        % else:
                            from.add_weighted(to, self_portion, other_portion)
                                .map(AnimationValue::${prop.camel_case})
                        % endif
                    }
                % endif
            % endfor
            _ => {
                panic!("Expected weighted addition of computed values of the same \
                        property, got: {:?}, {:?}", self, other);
            }
        }
    }

    fn add(&self, other: &Self) -> Result<Self, ()> {
        match (self, other) {
            % for prop in data.longhands:
                % if prop.animatable:
                    % if prop.animation_value_type == "discrete":
                        (&AnimationValue::${prop.camel_case}(_),
                         &AnimationValue::${prop.camel_case}(_)) => {
                            Err(())
                        }
                    % else:
                        (&AnimationValue::${prop.camel_case}(ref from),
                         &AnimationValue::${prop.camel_case}(ref to)) => {
                            from.add(to).map(AnimationValue::${prop.camel_case})
                        }
                    % endif
                % endif
            % endfor
            _ => {
                panic!("Expected addition of computed values of the same \
                        property, got: {:?}, {:?}", self, other);
            }
        }
    }

    fn accumulate(&self, other: &Self, count: u64) -> Result<Self, ()> {
        match (self, other) {
            % for prop in data.longhands:
                % if prop.animatable:
                    % if prop.animation_value_type == "discrete":
                        (&AnimationValue::${prop.camel_case}(_),
                         &AnimationValue::${prop.camel_case}(_)) => {
                            Err(())
                        }
                    % else:
                        (&AnimationValue::${prop.camel_case}(ref from),
                         &AnimationValue::${prop.camel_case}(ref to)) => {
                            from.accumulate(to, count).map(AnimationValue::${prop.camel_case})
                        }
                    % endif
                % endif
            % endfor
            _ => {
                panic!("Expected accumulation of computed values of the same \
                        property, got: {:?}, {:?}", self, other);
            }
        }
    }

    fn get_zero_value(&self) -> Result<Self, ()> {
        match *self {
            % for prop in data.longhands:
            % if prop.animatable and prop.animation_value_type != "discrete":
            AnimationValue::${prop.camel_case}(ref base) => {
                Ok(AnimationValue::${prop.camel_case}(base.get_zero_value()?))
            },
            % endif
            % endfor
            _ => Err(()),
        }
    }

    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (self, other) {
            % for prop in data.longhands:
                % if prop.animatable:
                    % if prop.animation_value_type != "discrete":
                        (&AnimationValue::${prop.camel_case}(ref from),
                         &AnimationValue::${prop.camel_case}(ref to)) => {
                            from.compute_distance(to)
                        },
                    % else:
                        (&AnimationValue::${prop.camel_case}(ref _from),
                         &AnimationValue::${prop.camel_case}(ref _to)) => {
                            Err(())
                        },
                    % endif
                % endif
            % endfor
            _ => {
                panic!("Expected compute_distance of computed values of the same \
                        property, got: {:?}, {:?}", self, other);
            }
        }
    }
}


/// A trait used to implement various procedures used during animation.
pub trait Animatable: Sized {
    /// Performs a weighted sum of this value and |other|. This is used for
    /// interpolation and addition of animation values.
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
        -> Result<Self, ()>;

    /// [Interpolates][interpolation] a value with another for a given property.
    ///
    /// [interpolation]: https://w3c.github.io/web-animations/#animation-interpolation
    fn interpolate(&self, other: &Self, progress: f64) -> Result<Self, ()> {
        self.add_weighted(other, 1.0 - progress, progress)
    }

    /// Returns the [sum][animation-addition] of this value and |other|.
    ///
    /// [animation-addition]: https://w3c.github.io/web-animations/#animation-addition
    fn add(&self, other: &Self) -> Result<Self, ()> {
        self.add_weighted(other, 1.0, 1.0)
    }

    /// [Accumulates][animation-accumulation] this value onto itself (|count| - 1) times then
    /// accumulates |other| onto the result.
    /// If |count| is zero, the result will be |other|.
    ///
    /// [animation-accumulation]: https://w3c.github.io/web-animations/#animation-accumulation
    fn accumulate(&self, other: &Self, count: u64) -> Result<Self, ()> {
        self.add_weighted(other, count as f64, 1.0)
    }

    /// Returns a value that, when added with an underlying value, will produce the underlying
    /// value. This is used for SMIL animation's "by-animation" where SMIL first interpolates from
    /// the zero value to the 'by' value, and then adds the result to the underlying value.
    ///
    /// This is not the necessarily the same as the initial value of a property. For example, the
    /// initial value of 'stroke-width' is 1, but the zero value is 0, since adding 1 to the
    /// underlying value will not produce the underlying value.
    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Err(()) }

    /// Compute distance between a value and another for a given property.
    fn compute_distance(&self, _other: &Self) -> Result<f64, ()>  { Err(()) }

    /// In order to compute the Euclidean distance of a list or property value with multiple
    /// components, we need to compute squared distance for each element, so the vector can sum it
    /// and then get its squared root as the distance.
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_distance(other).map(|d| d * d)
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-repeatable-list
pub trait RepeatableListAnimatable: Animatable {}

impl RepeatableListAnimatable for LengthOrPercentage {}
impl RepeatableListAnimatable for Either<f32, LengthOrPercentage> {}

macro_rules! repeated_vec_impl {
    ($($ty:ty),*) => {
        $(impl<T: RepeatableListAnimatable> Animatable for $ty {
            fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
                -> Result<Self, ()> {
                // If the length of either list is zero, the least common multiple is undefined.
                if cmp::min(self.len(), other.len()) < 1 {
                    return Err(());
                }
                use num_integer::lcm;
                let len = lcm(self.len(), other.len());
                self.iter().cycle().zip(other.iter().cycle()).take(len).map(|(me, you)| {
                    me.add_weighted(you, self_portion, other_portion)
                }).collect()
            }

            #[inline]
            fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
                self.compute_squared_distance(other).map(|sd| sd.sqrt())
            }

            #[inline]
            fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
                // If the length of either list is zero, the least common multiple is undefined.
                if cmp::min(self.len(), other.len()) < 1 {
                    return Err(());
                }
                use num_integer::lcm;
                let len = lcm(self.len(), other.len());
                self.iter().cycle().zip(other.iter().cycle()).take(len).map(|(me, you)| {
                    me.compute_squared_distance(you)
                }).sum()
            }
        })*
    };
}

repeated_vec_impl!(SmallVec<[T; 1]>, Vec<T>);

/// https://drafts.csswg.org/css-transitions/#animtype-number
impl Animatable for Au {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Au((self.0 as f64 * self_portion + other.0 as f64 * other_portion).round() as i32))
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(Au(0)) }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.0.compute_distance(&other.0)
    }
}

impl <T> Animatable for Option<T>
    where T: Animatable,
{
    #[inline]
    fn add_weighted(&self, other: &Option<T>, self_portion: f64, other_portion: f64) -> Result<Option<T>, ()> {
        match (self, other) {
            (&Some(ref this), &Some(ref other)) => {
                Ok(this.add_weighted(other, self_portion, other_portion).ok())
            }
            (&None, &None) => Ok(None),
            _ => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (self, other) {
            (&Some(ref this), &Some(ref other)) => {
                this.compute_distance(other)
            },
            (&None, &None) => Ok(0.0),
            _ => Err(()),
        }
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        match (self, other) {
            (&Some(ref this), &Some(ref other)) => {
                this.compute_squared_distance(other)
            },
            (&None, &None) => Ok(0.0),
            _ => Err(()),
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-number
impl Animatable for f32 {
    #[inline]
    fn add_weighted(&self, other: &f32, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok((*self as f64 * self_portion + *other as f64 * other_portion) as f32)
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(0.) }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok((*self - *other).abs() as f64)
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-number
impl Animatable for f64 {
    #[inline]
    fn add_weighted(&self, other: &f64, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(*self * self_portion + *other * other_portion)
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(0.) }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok((*self - *other).abs())
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-integer
impl Animatable for i32 {
    #[inline]
    fn add_weighted(&self, other: &i32, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok((*self as f64 * self_portion + *other as f64 * other_portion).round() as i32)
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(0) }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok((*self - *other).abs() as f64)
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-number
impl Animatable for Angle {
    #[inline]
    fn add_weighted(&self, other: &Angle, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            % for angle_type in [ 'Degree', 'Gradian', 'Turn' ]:
            (Angle::${angle_type}(val1), Angle::${angle_type}(val2)) => {
                Ok(Angle::${angle_type}(
                    try!(val1.add_weighted(&val2, self_portion, other_portion))
                ))
            }
            % endfor
            _ => {
                self.radians()
                    .add_weighted(&other.radians(), self_portion, other_portion)
                    .map(Angle::from_radians)
            }
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-percentage
impl Animatable for Percentage {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Percentage((self.0 as f64 * self_portion + other.0 as f64 * other_portion) as f32))
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(Percentage(0.)) }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok((self.0 as f64 - other.0 as f64).abs())
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-visibility
impl Animatable for Visibility {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (Visibility::visible, _) => {
                Ok(if self_portion > 0.0 { *self } else { *other })
            },
            (_, Visibility::visible) => {
                Ok(if other_portion > 0.0 { *other } else { *self })
            },
            _ => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        if *self == *other {
            Ok(0.0)
        } else {
            Ok(1.0)
        }
    }
}

impl<T: Animatable + Copy> Animatable for Size2D<T> {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        let width = self.width.add_weighted(&other.width, self_portion, other_portion)?;
        let height = self.height.add_weighted(&other.height, self_portion, other_portion)?;

        Ok(Size2D::new(width, height))
    }
}

impl<T: Animatable + Copy> Animatable for Point2D<T> {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        let x = self.x.add_weighted(&other.x, self_portion, other_portion)?;
        let y = self.y.add_weighted(&other.y, self_portion, other_portion)?;

        Ok(Point2D::new(x, y))
    }
}

impl Animatable for BorderCornerRadius {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        self.0.add_weighted(&other.0, self_portion, other_portion).map(GenericBorderCornerRadius)
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sd| sd.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok(self.0.width.compute_squared_distance(&other.0.width)? +
           self.0.height.compute_squared_distance(&other.0.height)?)
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-length
impl Animatable for VerticalAlign {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (VerticalAlign::LengthOrPercentage(LengthOrPercentage::Length(ref this)),
             VerticalAlign::LengthOrPercentage(LengthOrPercentage::Length(ref other))) => {
                this.add_weighted(other, self_portion, other_portion).map(|value| {
                    VerticalAlign::LengthOrPercentage(LengthOrPercentage::Length(value))
                })
            }
            _ => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (VerticalAlign::LengthOrPercentage(ref this),
             VerticalAlign::LengthOrPercentage(ref other)) => {
                this.compute_distance(other)
            },
            _ => Err(()),
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-lpcalc
impl Animatable for CalcLengthOrPercentage {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        fn add_weighted_half<T>(this: Option<T>,
                                other: Option<T>,
                                self_portion: f64,
                                other_portion: f64)
                                -> Result<Option<T>, ()>
            where T: Default + Animatable,
        {
            match (this, other) {
                (None, None) => Ok(None),
                (this, other) => {
                    let this = this.unwrap_or(T::default());
                    let other = other.unwrap_or(T::default());
                    this.add_weighted(&other, self_portion, other_portion).map(Some)
                }
            }
        }

        let length = self.unclamped_length().add_weighted(&other.unclamped_length(), self_portion, other_portion)?;
        let percentage = add_weighted_half(self.percentage, other.percentage, self_portion, other_portion)?;
        Ok(CalcLengthOrPercentage::with_clamping_mode(length, percentage, self.clamping_mode))
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sq| sq.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        let length_diff = (self.unclamped_length().0 - other.unclamped_length().0) as f64;
        let percentage_diff = (self.percentage() - other.percentage()) as f64;
        Ok(length_diff * length_diff + percentage_diff * percentage_diff)
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-lpcalc
impl Animatable for LengthOrPercentage {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (LengthOrPercentage::Length(ref this),
             LengthOrPercentage::Length(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(LengthOrPercentage::Length)
            }
            (LengthOrPercentage::Percentage(ref this),
             LengthOrPercentage::Percentage(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(LengthOrPercentage::Percentage)
            }
            (this, other) => {
                // Special handling for zero values since these should not require calc().
                if this.is_definitely_zero() {
                    return other.add_weighted(&other, 0., other_portion)
                } else if other.is_definitely_zero() {
                    return this.add_weighted(self, self_portion, 0.)
                }

                let this: CalcLengthOrPercentage = From::from(this);
                let other: CalcLengthOrPercentage = From::from(other);
                this.add_weighted(&other, self_portion, other_portion)
                    .map(LengthOrPercentage::Calc)
            }
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        Ok(LengthOrPercentage::zero())
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (LengthOrPercentage::Length(ref this),
             LengthOrPercentage::Length(ref other)) => {
                this.compute_distance(other)
            },
            (LengthOrPercentage::Percentage(ref this),
             LengthOrPercentage::Percentage(ref other)) => {
                this.compute_distance(other)
            },
            (this, other) => {
                let this: CalcLengthOrPercentage = From::from(this);
                let other: CalcLengthOrPercentage = From::from(other);
                this.compute_distance(&other)
            }
        }
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (LengthOrPercentage::Length(ref this),
             LengthOrPercentage::Length(ref other)) => {
                let diff = (this.0 - other.0) as f64;
                Ok(diff * diff)
            },
            (LengthOrPercentage::Percentage(ref this),
             LengthOrPercentage::Percentage(ref other)) => {
                let diff = this.0 as f64 - other.0 as f64;
                Ok(diff * diff)
            },
            (this, other) => {
                let this: CalcLengthOrPercentage = From::from(this);
                let other: CalcLengthOrPercentage = From::from(other);
                let length_diff = (this.unclamped_length().0 - other.unclamped_length().0) as f64;
                let percentage_diff = (this.percentage() - other.percentage()) as f64;
                Ok(length_diff * length_diff + percentage_diff * percentage_diff)
            }
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-lpcalc
impl Animatable for LengthOrPercentageOrAuto {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (LengthOrPercentageOrAuto::Length(ref this),
             LengthOrPercentageOrAuto::Length(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(LengthOrPercentageOrAuto::Length)
            }
            (LengthOrPercentageOrAuto::Percentage(ref this),
             LengthOrPercentageOrAuto::Percentage(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(LengthOrPercentageOrAuto::Percentage)
            }
            (LengthOrPercentageOrAuto::Auto, LengthOrPercentageOrAuto::Auto) => {
                Ok(LengthOrPercentageOrAuto::Auto)
            }
            (this, other) => {
                let this: Option<CalcLengthOrPercentage> = From::from(this);
                let other: Option<CalcLengthOrPercentage> = From::from(other);
                match this.add_weighted(&other, self_portion, other_portion) {
                    Ok(Some(result)) => Ok(LengthOrPercentageOrAuto::Calc(result)),
                    _ => Err(()),
                }
            }
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        match *self {
            LengthOrPercentageOrAuto::Length(_) |
            LengthOrPercentageOrAuto::Percentage(_) |
            LengthOrPercentageOrAuto::Calc(_) => {
                Ok(LengthOrPercentageOrAuto::Length(Au(0)))
            },
            LengthOrPercentageOrAuto::Auto => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (LengthOrPercentageOrAuto::Length(ref this),
             LengthOrPercentageOrAuto::Length(ref other)) => {
                this.compute_distance(other)
            },
            (LengthOrPercentageOrAuto::Percentage(ref this),
             LengthOrPercentageOrAuto::Percentage(ref other)) => {
                this.compute_distance(other)
            },
            (this, other) => {
                // If one of the element is Auto, Option<> will be None, and the returned distance is Err(())
                let this: Option<CalcLengthOrPercentage> = From::from(this);
                let other: Option<CalcLengthOrPercentage> = From::from(other);
                this.compute_distance(&other)
            }
        }
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (LengthOrPercentageOrAuto::Length(ref this),
             LengthOrPercentageOrAuto::Length(ref other)) => {
                let diff = (this.0 - other.0) as f64;
                Ok(diff * diff)
            },
            (LengthOrPercentageOrAuto::Percentage(ref this),
             LengthOrPercentageOrAuto::Percentage(ref other)) => {
                let diff = this.0 as f64 - other.0 as f64;
                Ok(diff * diff)
            },
            (this, other) => {
                let this: Option<CalcLengthOrPercentage> = From::from(this);
                let other: Option<CalcLengthOrPercentage> = From::from(other);
                if let (Some(this), Some(other)) = (this, other) {
                    let length_diff = (this.unclamped_length().0 - other.unclamped_length().0) as f64;
                    let percentage_diff = (this.percentage() - other.percentage()) as f64;
                    Ok(length_diff * length_diff + percentage_diff * percentage_diff)
                } else {
                    Err(())
                }
            }
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-lpcalc
impl Animatable for LengthOrPercentageOrNone {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (LengthOrPercentageOrNone::Length(ref this),
             LengthOrPercentageOrNone::Length(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(LengthOrPercentageOrNone::Length)
            }
            (LengthOrPercentageOrNone::Percentage(ref this),
             LengthOrPercentageOrNone::Percentage(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(LengthOrPercentageOrNone::Percentage)
            }
            (LengthOrPercentageOrNone::None, LengthOrPercentageOrNone::None) => {
                Ok(LengthOrPercentageOrNone::None)
            }
            (this, other) => {
                let this = <Option<CalcLengthOrPercentage>>::from(this);
                let other = <Option<CalcLengthOrPercentage>>::from(other);
                match this.add_weighted(&other, self_portion, other_portion) {
                    Ok(Some(result)) => Ok(LengthOrPercentageOrNone::Calc(result)),
                    _ => Err(()),
                }
            },
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        match *self {
            LengthOrPercentageOrNone::Length(_) |
            LengthOrPercentageOrNone::Percentage(_) |
            LengthOrPercentageOrNone::Calc(_) => {
                Ok(LengthOrPercentageOrNone::Length(Au(0)))
            },
            LengthOrPercentageOrNone::None => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (LengthOrPercentageOrNone::Length(ref this),
             LengthOrPercentageOrNone::Length(ref other)) => {
                this.compute_distance(other)
            },
            (LengthOrPercentageOrNone::Percentage(ref this),
             LengthOrPercentageOrNone::Percentage(ref other)) => {
                this.compute_distance(other)
            },
            (this, other) => {
                // If one of the element is Auto, Option<> will be None, and the returned distance is Err(())
                let this = <Option<CalcLengthOrPercentage>>::from(this);
                let other = <Option<CalcLengthOrPercentage>>::from(other);
                this.compute_distance(&other)
            },
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-lpcalc
impl Animatable for MozLength {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (MozLength::LengthOrPercentageOrAuto(ref this),
             MozLength::LengthOrPercentageOrAuto(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(MozLength::LengthOrPercentageOrAuto)
            }
            _ => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (MozLength::LengthOrPercentageOrAuto(ref this),
             MozLength::LengthOrPercentageOrAuto(ref other)) => {
                this.compute_distance(other)
            },
            _ => Err(()),
        }
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-lpcalc
impl Animatable for MaxLength {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (MaxLength::LengthOrPercentageOrNone(ref this),
             MaxLength::LengthOrPercentageOrNone(ref other)) => {
                this.add_weighted(other, self_portion, other_portion)
                    .map(MaxLength::LengthOrPercentageOrNone)
            }
            _ => Err(()),
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (*self, *other) {
            (MaxLength::LengthOrPercentageOrNone(ref this),
             MaxLength::LengthOrPercentageOrNone(ref other)) => {
                this.compute_distance(other)
            },
            _ => Err(()),
        }
    }
}

/// http://dev.w3.org/csswg/css-transitions/#animtype-font-weight
impl Animatable for FontWeight {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        let a = self.0 as f64;
        let b = other.0 as f64;
        const NORMAL: f64 = 400.;
        let weight = (a - NORMAL) * self_portion + (b - NORMAL) * other_portion + NORMAL;
        let weight = (weight.min(100.).max(900.) / 100.).round() * 100.;
        Ok(FontWeight(weight as u16))
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(FontWeight::normal()) }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        let a = self.0 as f64;
        let b = other.0 as f64;
        a.compute_distance(&b)
    }
}

/// https://drafts.csswg.org/css-fonts/#font-stretch-prop
impl Animatable for FontStretch {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
        -> Result<Self, ()>
    {
        let from = f64::from(*self);
        let to = f64::from(*other);
        // FIXME: When `const fn` is available in release rust, make |normal|, below, const.
        let normal = f64::from(FontStretch::normal);
        let result = (from - normal) * self_portion + (to - normal) * other_portion + normal;

        Ok(result.into())
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        let from = f64::from(*self);
        let to   = f64::from(*other);
        from.compute_distance(&to)
    }
}

/// We should treat font stretch as real number in order to interpolate this property.
/// https://drafts.csswg.org/css-fonts-3/#font-stretch-animation
impl From<FontStretch> for f64 {
    fn from(stretch: FontStretch) -> f64 {
        use self::FontStretch::*;
        match stretch {
            ultra_condensed => 1.0,
            extra_condensed => 2.0,
            condensed       => 3.0,
            semi_condensed  => 4.0,
            normal          => 5.0,
            semi_expanded   => 6.0,
            expanded        => 7.0,
            extra_expanded  => 8.0,
            ultra_expanded  => 9.0,
        }
    }
}

impl Into<FontStretch> for f64 {
    fn into(self) -> FontStretch {
        use properties::longhands::font_stretch::computed_value::T::*;
        let index = (self + 0.5).floor().min(9.0).max(1.0);
        static FONT_STRETCH_ENUM_MAP: [FontStretch; 9] =
            [ ultra_condensed, extra_condensed, condensed, semi_condensed, normal,
              semi_expanded, expanded, extra_expanded, ultra_expanded ];
        FONT_STRETCH_ENUM_MAP[(index - 1.0) as usize]
    }
}

/// https://drafts.csswg.org/css-transitions/#animtype-simple-list
impl<H: Animatable, V: Animatable> Animatable for generic_position::Position<H, V> {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(generic_position::Position {
            horizontal: self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)?,
            vertical: self.vertical.add_weighted(&other.vertical, self_portion, other_portion)?,
        })
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        Ok(generic_position::Position {
            horizontal: self.horizontal.get_zero_value()?,
            vertical: self.vertical.get_zero_value()?,
        })
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sd| sd.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok(self.horizontal.compute_squared_distance(&other.horizontal)? +
           self.vertical.compute_squared_distance(&other.vertical)?)
    }
}

impl<H, V> RepeatableListAnimatable for generic_position::Position<H, V>
    where H: RepeatableListAnimatable, V: RepeatableListAnimatable {}

/// https://drafts.csswg.org/css-transitions/#animtype-rect
impl Animatable for ClipRect {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
        -> Result<Self, ()> {
        Ok(ClipRect {
            top: self.top.add_weighted(&other.top, self_portion, other_portion)?,
            right: self.right.add_weighted(&other.right, self_portion, other_portion)?,
            bottom: self.bottom.add_weighted(&other.bottom, self_portion, other_portion)?,
            left: self.left.add_weighted(&other.left, self_portion, other_portion)?,
        })
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sd| sd.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        let list = [
            self.top.compute_distance(&other.top)?,
            self.right.compute_distance(&other.right)?,
            self.bottom.compute_distance(&other.bottom)?,
            self.left.compute_distance(&other.left)?
        ];
        Ok(list.iter().fold(0.0f64, |sum, diff| sum + diff * diff))
    }
}

/// Check if it's possible to do a direct numerical interpolation
/// between these two transform lists.
/// http://dev.w3.org/csswg/css-transforms/#transform-transform-animation
fn can_interpolate_list(from_list: &[TransformOperation],
                        to_list: &[TransformOperation]) -> bool {
    // Lists must be equal length
    if from_list.len() != to_list.len() {
        return false;
    }

    // Each transform operation must match primitive type in other list
    for (from, to) in from_list.iter().zip(to_list) {
        match (from, to) {
            (&TransformOperation::Matrix(..), &TransformOperation::Matrix(..)) |
            (&TransformOperation::Skew(..), &TransformOperation::Skew(..)) |
            (&TransformOperation::Translate(..), &TransformOperation::Translate(..)) |
            (&TransformOperation::Scale(..), &TransformOperation::Scale(..)) |
            (&TransformOperation::Rotate(..), &TransformOperation::Rotate(..)) |
            (&TransformOperation::Perspective(..), &TransformOperation::Perspective(..)) => {}
            _ => {
                return false;
            }
        }
    }

    true
}

/// Build an equivalent 'identity transform function list' based
/// on an existing transform list.
/// http://dev.w3.org/csswg/css-transforms/#none-transform-animation
fn build_identity_transform_list(list: &[TransformOperation]) -> Vec<TransformOperation> {
    let mut result = vec!();

    for operation in list {
        match *operation {
            TransformOperation::Matrix(..) => {
                let identity = ComputedMatrix::identity();
                result.push(TransformOperation::Matrix(identity));
            }
            TransformOperation::MatrixWithPercents(..) => {}
            TransformOperation::Skew(..) => {
                result.push(TransformOperation::Skew(Angle::zero(), Angle::zero()))
            }
            TransformOperation::Translate(..) => {
                result.push(TransformOperation::Translate(LengthOrPercentage::zero(),
                                                          LengthOrPercentage::zero(),
                                                          Au(0)));
            }
            TransformOperation::Scale(..) => {
                result.push(TransformOperation::Scale(1.0, 1.0, 1.0));
            }
            TransformOperation::Rotate(..) => {
                result.push(TransformOperation::Rotate(0.0, 0.0, 1.0, Angle::zero()));
            }
            TransformOperation::Perspective(..) |
            TransformOperation::AccumulateMatrix { .. } |
            TransformOperation::InterpolateMatrix { .. } => {
                // Perspective: We convert a perspective function into an equivalent
                //     ComputedMatrix, and then decompose/interpolate/recompose these matrices.
                // AccumulateMatrix/InterpolateMatrix: We do interpolation on
                //     AccumulateMatrix/InterpolateMatrix by reading it as a ComputedMatrix
                //     (with layout information), and then do matrix interpolation.
                //
                // Therefore, we use an identity matrix to represent the identity transform list.
                // http://dev.w3.org/csswg/css-transforms/#identity-transform-function
                let identity = ComputedMatrix::identity();
                result.push(TransformOperation::Matrix(identity));
            }
        }
    }

    result
}

/// A wrapper for calling add_weighted that interpolates the distance of the two values from
/// an initial_value and uses that to produce an interpolated value.
/// This is used for values such as 'scale' where the initial value is 1 and where if we interpolate
/// the absolute values, we will produce odd results for accumulation.
fn add_weighted_with_initial_val<T: Animatable>(a: &T,
                                                b: &T,
                                                a_portion: f64,
                                                b_portion: f64,
                                                initial_val: &T) -> Result<T, ()> {
    let a = a.add_weighted(&initial_val, 1.0, -1.0)?;
    let b = b.add_weighted(&initial_val, 1.0, -1.0)?;
    let result = a.add_weighted(&b, a_portion, b_portion)?;
    result.add_weighted(&initial_val, 1.0, 1.0)
}

/// Add two transform lists.
/// http://dev.w3.org/csswg/css-transforms/#interpolation-of-transforms
fn add_weighted_transform_lists(from_list: &[TransformOperation],
                                to_list: &[TransformOperation],
                                self_portion: f64,
                                other_portion: f64) -> TransformList {
    let mut result = vec![];

    if can_interpolate_list(from_list, to_list) {
        for (from, to) in from_list.iter().zip(to_list) {
            match (from, to) {
                (&TransformOperation::Matrix(from),
                 &TransformOperation::Matrix(_to)) => {
                    let sum = from.add_weighted(&_to, self_portion, other_portion).unwrap();
                    result.push(TransformOperation::Matrix(sum));
                }
                (&TransformOperation::MatrixWithPercents(_),
                 &TransformOperation::MatrixWithPercents(_)) => {
                    // We don't add_weighted `-moz-transform` matrices yet.
                    // They contain percentage values.
                    {}
                }
                (&TransformOperation::Skew(fx, fy),
                 &TransformOperation::Skew(tx, ty)) => {
                    let ix = fx.add_weighted(&tx, self_portion, other_portion).unwrap();
                    let iy = fy.add_weighted(&ty, self_portion, other_portion).unwrap();
                    result.push(TransformOperation::Skew(ix, iy));
                }
                (&TransformOperation::Translate(fx, fy, fz),
                 &TransformOperation::Translate(tx, ty, tz)) => {
                    let ix = fx.add_weighted(&tx, self_portion, other_portion).unwrap();
                    let iy = fy.add_weighted(&ty, self_portion, other_portion).unwrap();
                    let iz = fz.add_weighted(&tz, self_portion, other_portion).unwrap();
                    result.push(TransformOperation::Translate(ix, iy, iz));
                }
                (&TransformOperation::Scale(fx, fy, fz),
                 &TransformOperation::Scale(tx, ty, tz)) => {
                    let ix = add_weighted_with_initial_val(&fx, &tx, self_portion,
                                                           other_portion, &1.0).unwrap();
                    let iy = add_weighted_with_initial_val(&fy, &ty, self_portion,
                                                           other_portion, &1.0).unwrap();
                    let iz = add_weighted_with_initial_val(&fz, &tz, self_portion,
                                                           other_portion, &1.0).unwrap();
                    result.push(TransformOperation::Scale(ix, iy, iz));
                }
                (&TransformOperation::Rotate(fx, fy, fz, fa),
                 &TransformOperation::Rotate(tx, ty, tz, ta)) => {
                    let norm_f = ((fx * fx) + (fy * fy) + (fz * fz)).sqrt();
                    let norm_t = ((tx * tx) + (ty * ty) + (tz * tz)).sqrt();
                    let (fx, fy, fz) = (fx / norm_f, fy / norm_f, fz / norm_f);
                    let (tx, ty, tz) = (tx / norm_t, ty / norm_t, tz / norm_t);
                    if fx == tx && fy == ty && fz == tz {
                        let ia = fa.add_weighted(&ta, self_portion, other_portion).unwrap();
                        result.push(TransformOperation::Rotate(fx, fy, fz, ia));
                    } else {
                        let matrix_f = rotate_to_matrix(fx, fy, fz, fa);
                        let matrix_t = rotate_to_matrix(tx, ty, tz, ta);
                        let sum = matrix_f.add_weighted(&matrix_t, self_portion, other_portion)
                                          .unwrap();

                        result.push(TransformOperation::Matrix(sum));
                    }
                }
                (&TransformOperation::Perspective(fd),
                 &TransformOperation::Perspective(_td)) => {
                    let mut fd_matrix = ComputedMatrix::identity();
                    let mut td_matrix = ComputedMatrix::identity();
                    fd_matrix.m43 = -1. / fd.to_f32_px();
                    td_matrix.m43 = -1. / _td.to_f32_px();
                    let sum = fd_matrix.add_weighted(&td_matrix, self_portion, other_portion)
                                       .unwrap();
                    result.push(TransformOperation::Matrix(sum));
                }
                _ => {
                    // This should be unreachable due to the can_interpolate_list() call.
                    unreachable!();
                }
            }
        }
    } else {
        use values::specified::Percentage;
        let from_transform_list = TransformList(Some(from_list.to_vec()));
        let to_transform_list = TransformList(Some(to_list.to_vec()));
        result.push(
            TransformOperation::InterpolateMatrix { from_list: from_transform_list,
                                                    to_list: to_transform_list,
                                                    progress: Percentage(other_portion as f32) });
    }

    TransformList(Some(result))
}

/// https://drafts.csswg.org/css-transforms/#Rotate3dDefined
fn rotate_to_matrix(x: f32, y: f32, z: f32, a: Angle) -> ComputedMatrix {
    let half_rad = a.radians() / 2.0;
    let sc = (half_rad).sin() * (half_rad).cos();
    let sq = (half_rad).sin().powi(2);

    ComputedMatrix {
        m11: 1.0 - 2.0 * (y * y + z * z) * sq,
        m12: 2.0 * (x * y * sq - z * sc),
        m13: 2.0 * (x * z * sq + y * sc),
        m14: 0.0,

        m21: 2.0 * (x * y * sq + z * sc),
        m22: 1.0 - 2.0 * (x * x + z * z) * sq,
        m23: 2.0 * (y * z * sq - x * sc),
        m24: 0.0,

        m31: 2.0 * (x * z * sq - y * sc),
        m32: 2.0 * (y * z * sq + x * sc),
        m33: 1.0 - 2.0 * (x * x + y * y) * sq,
        m34: 0.0,

        m41: 0.0,
        m42: 0.0,
        m43: 0.0,
        m44: 1.0
    }
}

/// A 2d matrix for interpolation.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[allow(missing_docs)]
pub struct InnerMatrix2D {
    pub m11: CSSFloat, pub m12: CSSFloat,
    pub m21: CSSFloat, pub m22: CSSFloat,
}

/// A 2d translation function.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Translate2D(f32, f32);

/// A 2d scale function.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Scale2D(f32, f32);

/// A decomposed 2d matrix.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct MatrixDecomposed2D {
    /// The translation function.
    pub translate: Translate2D,
    /// The scale function.
    pub scale: Scale2D,
    /// The rotation angle.
    pub angle: f32,
    /// The inner matrix.
    pub matrix: InnerMatrix2D,
}

impl Animatable for InnerMatrix2D {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(InnerMatrix2D {
            m11: add_weighted_with_initial_val(&self.m11, &other.m11,
                                               self_portion, other_portion, &1.0)?,
            m12: self.m12.add_weighted(&other.m12, self_portion, other_portion)?,
            m21: self.m21.add_weighted(&other.m21, self_portion, other_portion)?,
            m22: add_weighted_with_initial_val(&self.m22, &other.m22,
                                               self_portion, other_portion, &1.0)?,
        })
    }
}

impl Animatable for Translate2D {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Translate2D(
            self.0.add_weighted(&other.0, self_portion, other_portion)?,
            self.1.add_weighted(&other.1, self_portion, other_portion)?,
        ))
    }
}

impl Animatable for Scale2D {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Scale2D(
            add_weighted_with_initial_val(&self.0, &other.0, self_portion, other_portion, &1.0)?,
            add_weighted_with_initial_val(&self.1, &other.1, self_portion, other_portion, &1.0)?,
        ))
    }
}

impl Animatable for MatrixDecomposed2D {
    /// https://drafts.csswg.org/css-transforms/#interpolation-of-decomposed-2d-matrix-values
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        // If x-axis of one is flipped, and y-axis of the other,
        // convert to an unflipped rotation.
        let mut scale = self.scale;
        let mut angle = self.angle;
        let mut other_angle = other.angle;
        if (scale.0 < 0.0 && other.scale.1 < 0.0) || (scale.1 < 0.0 && other.scale.0 < 0.0) {
            scale.0 = -scale.0;
            scale.1 = -scale.1;
            angle += if angle < 0.0 {180.} else {-180.};
        }

        // Don't rotate the long way around.
        if angle == 0.0 {
            angle = 360.
        }
        if other_angle == 0.0 {
            other_angle = 360.
        }

        if (angle - other_angle).abs() > 180. {
            if angle > other_angle {
                angle -= 360.
            }
            else{
                other_angle -= 360.
            }
        }

        // Interpolate all values.
        let translate = self.translate.add_weighted(&other.translate, self_portion, other_portion)?;
        let scale = scale.add_weighted(&other.scale, self_portion, other_portion)?;
        let angle = angle.add_weighted(&other_angle, self_portion, other_portion)?;
        let matrix = self.matrix.add_weighted(&other.matrix, self_portion, other_portion)?;

        Ok(MatrixDecomposed2D {
            translate: translate,
            scale: scale,
            angle: angle,
            matrix: matrix,
        })
    }
}

impl Animatable for ComputedMatrix {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        if self.is_3d() || other.is_3d() {
            let decomposed_from = decompose_3d_matrix(*self);
            let decomposed_to = decompose_3d_matrix(*other);
            match (decomposed_from, decomposed_to) {
                (Ok(from), Ok(to)) => {
                    let sum = from.add_weighted(&to, self_portion, other_portion)?;
                    Ok(ComputedMatrix::from(sum))
                },
                _ => {
                    let result = if self_portion > other_portion {*self} else {*other};
                    Ok(result)
                }
            }
        } else {
            let decomposed_from = MatrixDecomposed2D::from(*self);
            let decomposed_to = MatrixDecomposed2D::from(*other);
            let sum = decomposed_from.add_weighted(&decomposed_to, self_portion, other_portion)?;
            Ok(ComputedMatrix::from(sum))
        }
    }
}

impl From<ComputedMatrix> for MatrixDecomposed2D {
    /// Decompose a 2D matrix.
    /// https://drafts.csswg.org/css-transforms/#decomposing-a-2d-matrix
    fn from(matrix: ComputedMatrix) -> MatrixDecomposed2D {
        let mut row0x = matrix.m11;
        let mut row0y = matrix.m12;
        let mut row1x = matrix.m21;
        let mut row1y = matrix.m22;

        let translate = Translate2D(matrix.m41, matrix.m42);
        let mut scale = Scale2D((row0x * row0x + row0y * row0y).sqrt(),
                                (row1x * row1x + row1y * row1y).sqrt());

        // If determinant is negative, one axis was flipped.
        let determinant = row0x * row1y - row0y * row1x;
        if determinant < 0. {
            if row0x < row1y {
                scale.0 = -scale.0;
            } else {
                scale.1 = -scale.1;
            }
        }

        // Renormalize matrix to remove scale.
        if scale.0 != 0.0 {
            row0x *= 1. / scale.0;
            row0y *= 1. / scale.0;
        }
        if scale.1 != 0.0 {
            row1x *= 1. / scale.1;
            row1y *= 1. / scale.1;
        }

        // Compute rotation and renormalize matrix.
        let mut angle = row0y.atan2(row0x);
        if angle != 0.0 {
            let sn = -row0y;
            let cs = row0x;
            let m11 = row0x;
            let m12 = row0y;
            let m21 = row1x;
            let m22 = row1y;
            row0x = cs * m11 + sn * m21;
            row0y = cs * m12 + sn * m22;
            row1x = -sn * m11 + cs * m21;
            row1y = -sn * m12 + cs * m22;
        }

        let m = InnerMatrix2D {
            m11: row0x, m12: row0y,
            m21: row1x, m22: row1y,
        };

        // Convert into degrees because our rotation functions expect it.
        angle = angle.to_degrees();
        MatrixDecomposed2D {
            translate: translate,
            scale: scale,
            angle: angle,
            matrix: m,
        }
    }
}

impl From<MatrixDecomposed2D> for ComputedMatrix {
    /// Recompose a 2D matrix.
    /// https://drafts.csswg.org/css-transforms/#recomposing-to-a-2d-matrix
    fn from(decomposed: MatrixDecomposed2D) -> ComputedMatrix {
        let mut computed_matrix = ComputedMatrix::identity();
        computed_matrix.m11 = decomposed.matrix.m11;
        computed_matrix.m12 = decomposed.matrix.m12;
        computed_matrix.m21 = decomposed.matrix.m21;
        computed_matrix.m22 = decomposed.matrix.m22;

        // Translate matrix.
        computed_matrix.m41 = decomposed.translate.0;
        computed_matrix.m42 = decomposed.translate.1;

        // Rotate matrix.
        let angle = decomposed.angle.to_radians();
        let cos_angle = angle.cos();
        let sin_angle = angle.sin();

        let mut rotate_matrix = ComputedMatrix::identity();
        rotate_matrix.m11 = cos_angle;
        rotate_matrix.m12 = sin_angle;
        rotate_matrix.m21 = -sin_angle;
        rotate_matrix.m22 = cos_angle;

        // Multiplication of computed_matrix and rotate_matrix
        computed_matrix = multiply(rotate_matrix, computed_matrix);

        // Scale matrix.
        computed_matrix.m11 *= decomposed.scale.0;
        computed_matrix.m12 *= decomposed.scale.0;
        computed_matrix.m21 *= decomposed.scale.1;
        computed_matrix.m22 *= decomposed.scale.1;
        computed_matrix
    }
}

#[cfg(feature = "gecko")]
impl<'a> From< &'a RawGeckoGfxMatrix4x4> for ComputedMatrix {
    fn from(m: &'a RawGeckoGfxMatrix4x4) -> ComputedMatrix {
        ComputedMatrix {
            m11: m[0],  m12: m[1],  m13: m[2],  m14: m[3],
            m21: m[4],  m22: m[5],  m23: m[6],  m24: m[7],
            m31: m[8],  m32: m[9],  m33: m[10], m34: m[11],
            m41: m[12], m42: m[13], m43: m[14], m44: m[15],
        }
    }
}

#[cfg(feature = "gecko")]
impl From<ComputedMatrix> for RawGeckoGfxMatrix4x4 {
    fn from(matrix: ComputedMatrix) -> RawGeckoGfxMatrix4x4 {
        [ matrix.m11, matrix.m12, matrix.m13, matrix.m14,
          matrix.m21, matrix.m22, matrix.m23, matrix.m24,
          matrix.m31, matrix.m32, matrix.m33, matrix.m34,
          matrix.m41, matrix.m42, matrix.m43, matrix.m44 ]
    }
}

/// A 3d translation.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Translate3D(f32, f32, f32);

/// A 3d scale function.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Scale3D(f32, f32, f32);

/// A 3d skew function.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Skew(f32, f32, f32);

/// A 3d perspective transformation.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Perspective(f32, f32, f32, f32);

/// A quaternion used to represent a rotation.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct Quaternion(f32, f32, f32, f32);

/// A decomposed 3d matrix.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct MatrixDecomposed3D {
    /// A translation function.
    pub translate: Translate3D,
    /// A scale function.
    pub scale: Scale3D,
    /// The skew component of the transformation.
    pub skew: Skew,
    /// The perspective component of the transformation.
    pub perspective: Perspective,
    /// The quaternion used to represent the rotation.
    pub quaternion: Quaternion,
}

/// Decompose a 3D matrix.
/// https://drafts.csswg.org/css-transforms/#decomposing-a-3d-matrix
fn decompose_3d_matrix(mut matrix: ComputedMatrix) -> Result<MatrixDecomposed3D, ()> {
    // Normalize the matrix.
    if matrix.m44 == 0.0 {
        return Err(());
    }

    let scaling_factor = matrix.m44;
    % for i in range(1, 5):
        % for j in range(1, 5):
            matrix.m${i}${j} /= scaling_factor;
        % endfor
    % endfor

    // perspective_matrix is used to solve for perspective, but it also provides
    // an easy way to test for singularity of the upper 3x3 component.
    let mut perspective_matrix = matrix;

    % for i in range(1, 4):
        perspective_matrix.m${i}4 = 0.0;
    % endfor
    perspective_matrix.m44 = 1.0;

    if perspective_matrix.determinant() == 0.0 {
        return Err(());
    }

    // First, isolate perspective.
    let perspective = if matrix.m14 != 0.0 || matrix.m24 != 0.0 || matrix.m34 != 0.0 {
        let right_hand_side: [f32; 4] = [
            matrix.m14,
            matrix.m24,
            matrix.m34,
            matrix.m44
        ];

        perspective_matrix = perspective_matrix.inverse().unwrap();

        // Transpose perspective_matrix
        perspective_matrix = ComputedMatrix {
            % for i in range(1, 5):
                % for j in range(1, 5):
                    m${i}${j}: perspective_matrix.m${j}${i},
                % endfor
            % endfor
        };

        // Multiply right_hand_side with perspective_matrix
        let mut tmp: [f32; 4] = [0.0; 4];
        % for i in range(1, 5):
            tmp[${i - 1}] = (right_hand_side[0] * perspective_matrix.m1${i}) +
                            (right_hand_side[1] * perspective_matrix.m2${i}) +
                            (right_hand_side[2] * perspective_matrix.m3${i}) +
                            (right_hand_side[3] * perspective_matrix.m4${i});
        % endfor

        Perspective(tmp[0], tmp[1], tmp[2], tmp[3])
    } else {
        Perspective(0.0, 0.0, 0.0, 1.0)
    };

    // Next take care of translation
    let translate = Translate3D (
        matrix.m41,
        matrix.m42,
        matrix.m43
    );

    // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
    let mut row: [[f32; 3]; 3] = [[0.0; 3]; 3];
    % for i in range(1, 4):
        row[${i - 1}][0] = matrix.m${i}1;
        row[${i - 1}][1] = matrix.m${i}2;
        row[${i - 1}][2] = matrix.m${i}3;
    % endfor

    // Compute X scale factor and normalize first row.
    let row0len = (row[0][0] * row[0][0] + row[0][1] * row[0][1] + row[0][2] * row[0][2]).sqrt();
    let mut scale = Scale3D(row0len, 0.0, 0.0);
    row[0] = [row[0][0] / row0len, row[0][1] / row0len, row[0][2] / row0len];

    // Compute XY shear factor and make 2nd row orthogonal to 1st.
    let mut skew = Skew(dot(row[0], row[1]), 0.0, 0.0);
    row[1] = combine(row[1], row[0], 1.0, -skew.0);

    // Now, compute Y scale and normalize 2nd row.
    let row1len = (row[0][0] * row[0][0] + row[0][1] * row[0][1] + row[0][2] * row[0][2]).sqrt();
    scale.1 = row1len;
    row[1] = [row[1][0] / row1len, row[1][1] / row1len, row[1][2] / row1len];
    skew.0 /= scale.1;

    // Compute XZ and YZ shears, orthogonalize 3rd row
    skew.1 = dot(row[0], row[2]);
    row[2] = combine(row[2], row[0], 1.0, -skew.1);
    skew.2 = dot(row[1], row[2]);
    row[2] = combine(row[2], row[1], 1.0, -skew.2);

    // Next, get Z scale and normalize 3rd row.
    let row2len = (row[2][0] * row[2][0] + row[2][1] * row[2][1] + row[2][2] * row[2][2]).sqrt();
    scale.2 = row2len;
    row[2] = [row[2][0] / row2len, row[2][1] / row2len, row[2][2] / row2len];
    skew.1 /= scale.2;
    skew.2 /= scale.2;

    // At this point, the matrix (in rows) is orthonormal.
    // Check for a coordinate system flip.  If the determinant
    // is -1, then negate the matrix and the scaling factors.
    let pdum3 = cross(row[1], row[2]);
    if dot(row[0], pdum3) < 0.0 {
        % for i in range(3):
            scale.${i} *= -1.0;
            row[${i}][0] *= -1.0;
            row[${i}][1] *= -1.0;
            row[${i}][2] *= -1.0;
        % endfor
    }

    // Now, get the rotations out
    let mut quaternion = Quaternion (
        0.5 * ((1.0 + row[0][0] - row[1][1] - row[2][2]).max(0.0)).sqrt(),
        0.5 * ((1.0 - row[0][0] + row[1][1] - row[2][2]).max(0.0)).sqrt(),
        0.5 * ((1.0 - row[0][0] - row[1][1] + row[2][2]).max(0.0)).sqrt(),
        0.5 * ((1.0 + row[0][0] + row[1][1] + row[2][2]).max(0.0)).sqrt()
    );

    if row[2][1] > row[1][2] {
        quaternion.0 = -quaternion.0
    }
    if row[0][2] > row[2][0] {
        quaternion.1 = -quaternion.1
    }
    if row[1][0] > row[0][1] {
        quaternion.2 = -quaternion.2
    }

    Ok(MatrixDecomposed3D {
        translate: translate,
        scale: scale,
        skew: skew,
        perspective: perspective,
        quaternion: quaternion
    })
}

// Combine 2 point.
fn combine(a: [f32; 3], b: [f32; 3], ascl: f32, bscl: f32) -> [f32; 3] {
    [
        (ascl * a[0]) + (bscl * b[0]),
        (ascl * a[1]) + (bscl * b[1]),
        (ascl * a[2]) + (bscl * b[2])
    ]
}

// Dot product.
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

// Cross product.
fn cross(row1: [f32; 3], row2: [f32; 3]) -> [f32; 3] {
    [
        row1[1] * row2[2] - row1[2] * row2[1],
        row1[2] * row2[0] - row1[0] * row2[2],
        row1[0] * row2[1] - row1[1] * row2[0]
    ]
}

impl Animatable for Translate3D {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Translate3D(
            self.0.add_weighted(&other.0, self_portion, other_portion)?,
            self.1.add_weighted(&other.1, self_portion, other_portion)?,
            self.2.add_weighted(&other.2, self_portion, other_portion)?,
        ))
    }
}

impl Animatable for Scale3D {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Scale3D(
            add_weighted_with_initial_val(&self.0, &other.0, self_portion, other_portion, &1.0)?,
            add_weighted_with_initial_val(&self.1, &other.1, self_portion, other_portion, &1.0)?,
            add_weighted_with_initial_val(&self.2, &other.2, self_portion, other_portion, &1.0)?,
        ))
    }
}

impl Animatable for Skew {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Skew(
            self.0.add_weighted(&other.0, self_portion, other_portion)?,
            self.1.add_weighted(&other.1, self_portion, other_portion)?,
            self.2.add_weighted(&other.2, self_portion, other_portion)?,
        ))
    }
}

impl Animatable for Perspective {
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(Perspective(
            self.0.add_weighted(&other.0, self_portion, other_portion)?,
            self.1.add_weighted(&other.1, self_portion, other_portion)?,
            self.2.add_weighted(&other.2, self_portion, other_portion)?,
            add_weighted_with_initial_val(&self.3, &other.3, self_portion, other_portion, &1.0)?,
        ))
    }
}

impl Animatable for MatrixDecomposed3D {
    /// https://drafts.csswg.org/css-transforms/#interpolation-of-decomposed-3d-matrix-values
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
        -> Result<Self, ()> {
        assert!(self_portion + other_portion == 1.0f64 ||
                other_portion == 1.0f64,
                "add_weighted should only be used for interpolating or accumulating transforms");

        let mut sum = *self;

        // Add translate, scale, skew and perspective components.
        sum.translate = self.translate.add_weighted(&other.translate, self_portion, other_portion)?;
        sum.scale = self.scale.add_weighted(&other.scale, self_portion, other_portion)?;
        sum.skew = self.skew.add_weighted(&other.skew, self_portion, other_portion)?;
        sum.perspective = self.perspective.add_weighted(&other.perspective, self_portion, other_portion)?;

        // Add quaternions using spherical linear interpolation (Slerp).
        //
        // We take a specialized code path for accumulation (where other_portion is 1)
        if other_portion == 1.0 {
            if self_portion == 0.0 {
                return Ok(*other)
            }

            let clamped_w = self.quaternion.3.min(1.0).max(-1.0);

            // Determine the scale factor.
            let mut theta = clamped_w.acos();
            let mut scale = if theta == 0.0 { 0.0 } else { 1.0 / theta.sin() };
            theta *= self_portion as f32;
            scale *= theta.sin();

            // Scale the self matrix by self_portion.
            let mut scaled_self = *self;
            % for i in range(3):
                scaled_self.quaternion.${i} *= scale;
            % endfor
            scaled_self.quaternion.3 = theta.cos();

            // Multiply scaled-self by other.
            let a = &scaled_self.quaternion;
            let b = &other.quaternion;
            sum.quaternion = Quaternion(
                a.3 * b.0 + a.0 * b.3 + a.1 * b.2 - a.2 * b.1,
                a.3 * b.1 - a.0 * b.2 + a.1 * b.3 + a.2 * b.0,
                a.3 * b.2 + a.0 * b.1 - a.1 * b.0 + a.2 * b.3,
                a.3 * b.3 - a.0 * b.0 - a.1 * b.1 - a.2 * b.2,
            );
        } else {
            let mut product = self.quaternion.0 * other.quaternion.0 +
                              self.quaternion.1 * other.quaternion.1 +
                              self.quaternion.2 * other.quaternion.2 +
                              self.quaternion.3 * other.quaternion.3;

            // Clamp product to -1.0 <= product <= 1.0
            product = product.min(1.0);
            product = product.max(-1.0);

            if product == 1.0 {
                return Ok(sum);
            }

            let theta = product.acos();
            let w = (other_portion as f32 * theta).sin() * 1.0 / (1.0 - product * product).sqrt();

            let mut a = *self;
            let mut b = *other;
            % for i in range(4):
                a.quaternion.${i} *= (other_portion as f32 * theta).cos() - product * w;
                b.quaternion.${i} *= w;
                sum.quaternion.${i} = a.quaternion.${i} + b.quaternion.${i};
            % endfor
        }

        Ok(sum)
    }
}

impl From<MatrixDecomposed3D> for ComputedMatrix {
    /// Recompose a 3D matrix.
    /// https://drafts.csswg.org/css-transforms/#recomposing-to-a-3d-matrix
    fn from(decomposed: MatrixDecomposed3D) -> ComputedMatrix {
        let mut matrix = ComputedMatrix::identity();

        // Apply perspective
        % for i in range(1, 5):
            matrix.m${i}4 = decomposed.perspective.${i - 1};
        % endfor

        // Apply translation
        % for i in range(1, 4):
            % for j in range(1, 4):
                matrix.m4${i} += decomposed.translate.${j - 1} * matrix.m${j}${i};
            % endfor
        % endfor

        // Apply rotation
        let x = decomposed.quaternion.0;
        let y = decomposed.quaternion.1;
        let z = decomposed.quaternion.2;
        let w = decomposed.quaternion.3;

        // Construct a composite rotation matrix from the quaternion values
        // rotationMatrix is a identity 4x4 matrix initially
        let mut rotation_matrix = ComputedMatrix::identity();
        rotation_matrix.m11 = 1.0 - 2.0 * (y * y + z * z);
        rotation_matrix.m12 = 2.0 * (x * y + z * w);
        rotation_matrix.m13 = 2.0 * (x * z - y * w);
        rotation_matrix.m21 = 2.0 * (x * y - z * w);
        rotation_matrix.m22 = 1.0 - 2.0 * (x * x + z * z);
        rotation_matrix.m23 = 2.0 * (y * z + x * w);
        rotation_matrix.m31 = 2.0 * (x * z + y * w);
        rotation_matrix.m32 = 2.0 * (y * z - x * w);
        rotation_matrix.m33 = 1.0 - 2.0 * (x * x + y * y);

        matrix = multiply(rotation_matrix, matrix);

        // Apply skew
        let mut temp = ComputedMatrix::identity();
        if decomposed.skew.2 != 0.0 {
            temp.m32 = decomposed.skew.2;
            matrix = multiply(matrix, temp);
        }

        if decomposed.skew.1 != 0.0 {
            temp.m32 = 0.0;
            temp.m31 = decomposed.skew.1;
            matrix = multiply(matrix, temp);
        }

        if decomposed.skew.0 != 0.0 {
            temp.m31 = 0.0;
            temp.m21 = decomposed.skew.0;
            matrix = multiply(matrix, temp);
        }

        // Apply scale
        % for i in range(1, 4):
            % for j in range(1, 4):
                matrix.m${i}${j} *= decomposed.scale.${i - 1};
            % endfor
        % endfor

        matrix
    }
}

// Multiplication of two 4x4 matrices.
fn multiply(a: ComputedMatrix, b: ComputedMatrix) -> ComputedMatrix {
    let mut a_clone = a;
    % for i in range(1, 5):
        % for j in range(1, 5):
            a_clone.m${i}${j} = (a.m${i}1 * b.m1${j}) +
                               (a.m${i}2 * b.m2${j}) +
                               (a.m${i}3 * b.m3${j}) +
                               (a.m${i}4 * b.m4${j});
        % endfor
    % endfor
    a_clone
}

impl ComputedMatrix {
    fn is_3d(&self) -> bool {
        self.m13 != 0.0 || self.m14 != 0.0 ||
        self.m23 != 0.0 || self.m24 != 0.0 ||
        self.m31 != 0.0 || self.m32 != 0.0 || self.m33 != 1.0 || self.m34 != 0.0 ||
        self.m43 != 0.0 || self.m44 != 1.0
    }

    fn determinant(&self) -> CSSFloat {
        self.m14 * self.m23 * self.m32 * self.m41 -
        self.m13 * self.m24 * self.m32 * self.m41 -
        self.m14 * self.m22 * self.m33 * self.m41 +
        self.m12 * self.m24 * self.m33 * self.m41 +
        self.m13 * self.m22 * self.m34 * self.m41 -
        self.m12 * self.m23 * self.m34 * self.m41 -
        self.m14 * self.m23 * self.m31 * self.m42 +
        self.m13 * self.m24 * self.m31 * self.m42 +
        self.m14 * self.m21 * self.m33 * self.m42 -
        self.m11 * self.m24 * self.m33 * self.m42 -
        self.m13 * self.m21 * self.m34 * self.m42 +
        self.m11 * self.m23 * self.m34 * self.m42 +
        self.m14 * self.m22 * self.m31 * self.m43 -
        self.m12 * self.m24 * self.m31 * self.m43 -
        self.m14 * self.m21 * self.m32 * self.m43 +
        self.m11 * self.m24 * self.m32 * self.m43 +
        self.m12 * self.m21 * self.m34 * self.m43 -
        self.m11 * self.m22 * self.m34 * self.m43 -
        self.m13 * self.m22 * self.m31 * self.m44 +
        self.m12 * self.m23 * self.m31 * self.m44 +
        self.m13 * self.m21 * self.m32 * self.m44 -
        self.m11 * self.m23 * self.m32 * self.m44 -
        self.m12 * self.m21 * self.m33 * self.m44 +
        self.m11 * self.m22 * self.m33 * self.m44
    }

    fn inverse(&self) -> Option<ComputedMatrix> {
        let mut det = self.determinant();

        if det == 0.0 {
            return None;
        }

        det = 1.0 / det;
        let x = ComputedMatrix {
            m11: det *
            (self.m23*self.m34*self.m42 - self.m24*self.m33*self.m42 +
             self.m24*self.m32*self.m43 - self.m22*self.m34*self.m43 -
             self.m23*self.m32*self.m44 + self.m22*self.m33*self.m44),
            m12: det *
            (self.m14*self.m33*self.m42 - self.m13*self.m34*self.m42 -
             self.m14*self.m32*self.m43 + self.m12*self.m34*self.m43 +
             self.m13*self.m32*self.m44 - self.m12*self.m33*self.m44),
            m13: det *
            (self.m13*self.m24*self.m42 - self.m14*self.m23*self.m42 +
             self.m14*self.m22*self.m43 - self.m12*self.m24*self.m43 -
             self.m13*self.m22*self.m44 + self.m12*self.m23*self.m44),
            m14: det *
            (self.m14*self.m23*self.m32 - self.m13*self.m24*self.m32 -
             self.m14*self.m22*self.m33 + self.m12*self.m24*self.m33 +
             self.m13*self.m22*self.m34 - self.m12*self.m23*self.m34),
            m21: det *
            (self.m24*self.m33*self.m41 - self.m23*self.m34*self.m41 -
             self.m24*self.m31*self.m43 + self.m21*self.m34*self.m43 +
             self.m23*self.m31*self.m44 - self.m21*self.m33*self.m44),
            m22: det *
            (self.m13*self.m34*self.m41 - self.m14*self.m33*self.m41 +
             self.m14*self.m31*self.m43 - self.m11*self.m34*self.m43 -
             self.m13*self.m31*self.m44 + self.m11*self.m33*self.m44),
            m23: det *
            (self.m14*self.m23*self.m41 - self.m13*self.m24*self.m41 -
             self.m14*self.m21*self.m43 + self.m11*self.m24*self.m43 +
             self.m13*self.m21*self.m44 - self.m11*self.m23*self.m44),
            m24: det *
            (self.m13*self.m24*self.m31 - self.m14*self.m23*self.m31 +
             self.m14*self.m21*self.m33 - self.m11*self.m24*self.m33 -
             self.m13*self.m21*self.m34 + self.m11*self.m23*self.m34),
            m31: det *
            (self.m22*self.m34*self.m41 - self.m24*self.m32*self.m41 +
             self.m24*self.m31*self.m42 - self.m21*self.m34*self.m42 -
             self.m22*self.m31*self.m44 + self.m21*self.m32*self.m44),
            m32: det *
            (self.m14*self.m32*self.m41 - self.m12*self.m34*self.m41 -
             self.m14*self.m31*self.m42 + self.m11*self.m34*self.m42 +
             self.m12*self.m31*self.m44 - self.m11*self.m32*self.m44),
            m33: det *
            (self.m12*self.m24*self.m41 - self.m14*self.m22*self.m41 +
             self.m14*self.m21*self.m42 - self.m11*self.m24*self.m42 -
             self.m12*self.m21*self.m44 + self.m11*self.m22*self.m44),
            m34: det *
            (self.m14*self.m22*self.m31 - self.m12*self.m24*self.m31 -
             self.m14*self.m21*self.m32 + self.m11*self.m24*self.m32 +
             self.m12*self.m21*self.m34 - self.m11*self.m22*self.m34),
            m41: det *
            (self.m23*self.m32*self.m41 - self.m22*self.m33*self.m41 -
             self.m23*self.m31*self.m42 + self.m21*self.m33*self.m42 +
             self.m22*self.m31*self.m43 - self.m21*self.m32*self.m43),
            m42: det *
            (self.m12*self.m33*self.m41 - self.m13*self.m32*self.m41 +
             self.m13*self.m31*self.m42 - self.m11*self.m33*self.m42 -
             self.m12*self.m31*self.m43 + self.m11*self.m32*self.m43),
            m43: det *
            (self.m13*self.m22*self.m41 - self.m12*self.m23*self.m41 -
             self.m13*self.m21*self.m42 + self.m11*self.m23*self.m42 +
             self.m12*self.m21*self.m43 - self.m11*self.m22*self.m43),
            m44: det *
            (self.m12*self.m23*self.m31 - self.m13*self.m22*self.m31 +
             self.m13*self.m21*self.m32 - self.m11*self.m23*self.m32 -
             self.m12*self.m21*self.m33 + self.m11*self.m22*self.m33),
        };

        Some(x)
    }
}

/// https://drafts.csswg.org/css-transforms/#interpolation-of-transforms
impl Animatable for TransformList {
    #[inline]
    fn add_weighted(&self, other: &TransformList, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        // http://dev.w3.org/csswg/css-transforms/#interpolation-of-transforms
        let result = match (&self.0, &other.0) {
            (&Some(ref from_list), &Some(ref to_list)) => {
                // Two lists of transforms
                add_weighted_transform_lists(from_list, &to_list, self_portion, other_portion)
            }
            (&Some(ref from_list), &None) => {
                // http://dev.w3.org/csswg/css-transforms/#none-transform-animation
                let to_list = build_identity_transform_list(from_list);
                add_weighted_transform_lists(from_list, &to_list, self_portion, other_portion)
            }
            (&None, &Some(ref to_list)) => {
                // http://dev.w3.org/csswg/css-transforms/#none-transform-animation
                let from_list = build_identity_transform_list(to_list);
                add_weighted_transform_lists(&from_list, to_list, self_portion, other_portion)
            }
            _ => {
                // http://dev.w3.org/csswg/css-transforms/#none-none-animation
                TransformList(None)
            }
        };

        Ok(result)
    }

    fn add(&self, other: &Self) -> Result<Self, ()> {
        match (&self.0, &other.0) {
            (&Some(ref from_list), &Some(ref to_list)) => {
                Ok(TransformList(Some([&from_list[..], &to_list[..]].concat())))
            }
            (&Some(_), &None) => {
                Ok(self.clone())
            }
            (&None, &Some(_)) => {
                Ok(other.clone())
            }
            _ => {
                Ok(TransformList(None))
            }
        }
    }

    #[inline]
    fn accumulate(&self, other: &Self, count: u64) -> Result<Self, ()> {
        match (&self.0, &other.0) {
            (&Some(ref from_list), &Some(ref to_list)) => {
                if can_interpolate_list(from_list, to_list) {
                    Ok(add_weighted_transform_lists(from_list, &to_list, count as f64, 1.0))
                } else {
                    use std::i32;
                    let result = vec![TransformOperation::AccumulateMatrix {
                        from_list: self.clone(),
                        to_list: other.clone(),
                        count: cmp::min(count, i32::MAX as u64) as i32
                    }];
                    Ok(TransformList(Some(result)))
                }
            }
            (&Some(ref from_list), &None) => {
                Ok(add_weighted_transform_lists(from_list, from_list, count as f64, 0.0))
            }
            (&None, &Some(_)) => {
                // If |self| is 'none' then we are calculating:
                //
                //    none * |count| + |other|
                //    = none + |other|
                //    = |other|
                //
                // Hence the result is just |other|.
                Ok(other.clone())
            }
            _ => {
                Ok(TransformList(None))
            }
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> { Ok(TransformList(None)) }
}

impl<T, U> Animatable for Either<T, U>
        where T: Animatable + Copy, U: Animatable + Copy,
{
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (*self, *other) {
            (Either::First(ref this), Either::First(ref other)) => {
                this.add_weighted(&other, self_portion, other_portion).map(Either::First)
            },
            (Either::Second(ref this), Either::Second(ref other)) => {
                this.add_weighted(&other, self_portion, other_portion).map(Either::Second)
            },
            _ => {
                let result = if self_portion > other_portion {*self} else {*other};
                Ok(result)
            }
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        match *self {
            Either::First(ref this) => {
                Ok(Either::First(this.get_zero_value()?))
            },
            Either::Second(ref this) => {
                Ok(Either::Second(this.get_zero_value()?))
            },
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (self, other) {
            (&Either::First(ref this), &Either::First(ref other)) => {
                this.compute_distance(other)
            },
            (&Either::Second(ref this), &Either::Second(ref other)) => {
                this.compute_distance(other)
            },
            _ => Err(())
        }
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        match (self, other) {
            (&Either::First(ref this), &Either::First(ref other)) => {
                this.compute_squared_distance(other)
            },
            (&Either::Second(ref this), &Either::Second(ref other)) => {
                this.compute_squared_distance(other)
            },
            _ => Err(())
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
/// Unlike RGBA, each component value may exceed the range [0.0, 1.0].
pub struct IntermediateRGBA {
    /// The red component.
    pub red: f32,
    /// The green component.
    pub green: f32,
    /// The blue component.
    pub blue: f32,
    /// The alpha component.
    pub alpha: f32,
}

impl IntermediateRGBA {
    /// Returns a transparent color.
    #[inline]
    pub fn transparent() -> Self {
        Self::new(0., 0., 0., 0.)
    }

    /// Returns a new color.
    #[inline]
    pub fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
        IntermediateRGBA { red: red, green: green, blue: blue, alpha: alpha }
    }
}

impl ToAnimatedValue for RGBA {
    type AnimatedValue = IntermediateRGBA;

    #[inline]
    fn to_animated_value(self) -> Self::AnimatedValue {
        IntermediateRGBA::new(
            self.red_f32(),
            self.green_f32(),
            self.blue_f32(),
            self.alpha_f32(),
        )
    }

    #[inline]
    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
        // RGBA::from_floats clamps each component values.
        RGBA::from_floats(
            animated.red,
            animated.green,
            animated.blue,
            animated.alpha,
        )
    }
}

/// Unlike Animatable for RGBA we don't clamp any component values.
impl Animatable for IntermediateRGBA {
    #[inline]
    fn add_weighted(&self, other: &IntermediateRGBA, self_portion: f64, other_portion: f64)
        -> Result<Self, ()> {
        let mut alpha = self.alpha.add_weighted(&other.alpha, self_portion, other_portion)?;
        if alpha <= 0. {
            // Ideally we should return color value that only alpha component is
            // 0, but this is what current gecko does.
            Ok(IntermediateRGBA::transparent())
        } else {
            alpha = alpha.min(1.);
            let red = (self.red * self.alpha).add_weighted(
                &(other.red * other.alpha), self_portion, other_portion
            )? * 1. / alpha;
            let green = (self.green * self.alpha).add_weighted(
                &(other.green * other.alpha), self_portion, other_portion
            )? * 1. / alpha;
            let blue = (self.blue * self.alpha).add_weighted(
                &(other.blue * other.alpha), self_portion, other_portion
            )? * 1. / alpha;
            Ok(IntermediateRGBA::new(red, green, blue, alpha))
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        Ok(IntermediateRGBA::transparent())
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sq| sq.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        let start = [ self.alpha,
                      self.red * self.alpha,
                      self.green * self.alpha,
                      self.blue * self.alpha ];
        let end = [ other.alpha,
                    other.red * other.alpha,
                    other.green * other.alpha,
                    other.blue * other.alpha ];
        let diff = start.iter().zip(&end)
                               .fold(0.0f64, |n, (&a, &b)| {
                                   let diff = (a - b) as f64;
                                   n + diff * diff
                               });
        Ok(diff)
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[allow(missing_docs)]
pub struct IntermediateColor {
    color: IntermediateRGBA,
    foreground_ratio: f32,
}

impl IntermediateColor {
    fn currentcolor() -> Self {
        IntermediateColor {
            color: IntermediateRGBA::transparent(),
            foreground_ratio: 1.,
        }
    }

    /// Returns a transparent intermediate color.
    pub fn transparent() -> Self {
        IntermediateColor {
            color: IntermediateRGBA::transparent(),
            foreground_ratio: 0.,
        }
    }

    fn is_currentcolor(&self) -> bool {
        self.foreground_ratio >= 1.
    }

    fn is_numeric(&self) -> bool {
        self.foreground_ratio <= 0.
    }

    fn effective_intermediate_rgba(&self) -> IntermediateRGBA {
        IntermediateRGBA {
            alpha: self.color.alpha * (1. - self.foreground_ratio),
            .. self.color
        }
    }
}

impl ToAnimatedValue for Color {
    type AnimatedValue = IntermediateColor;

    #[inline]
    fn to_animated_value(self) -> Self::AnimatedValue {
        IntermediateColor {
            color: self.color.to_animated_value(),
            foreground_ratio: self.foreground_ratio as f32 * (1. / 255.),
        }
    }

    #[inline]
    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
        Color {
            color: RGBA::from_animated_value(animated.color),
            foreground_ratio: (animated.foreground_ratio * 255.).round() as u8,
        }
    }
}

impl Animatable for IntermediateColor {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        // Common cases are interpolating between two numeric colors,
        // two currentcolors, and a numeric color and a currentcolor.
        //
        // Note: this algorithm assumes self_portion + other_portion
        // equals to one, so it may be broken for additive operation.
        // To properly support additive color interpolation, we would
        // need two ratio fields in computed color types.
        if self.foreground_ratio == other.foreground_ratio {
            if self.is_currentcolor() {
                Ok(IntermediateColor::currentcolor())
            } else {
                Ok(IntermediateColor {
                    color: self.color.add_weighted(&other.color, self_portion, other_portion)?,
                    foreground_ratio: self.foreground_ratio,
                })
            }
        } else if self.is_currentcolor() && other.is_numeric() {
            Ok(IntermediateColor {
                color: other.color,
                foreground_ratio: self_portion as f32,
            })
        } else if self.is_numeric() && other.is_currentcolor() {
            Ok(IntermediateColor {
                color: self.color,
                foreground_ratio: other_portion as f32,
            })
        } else {
            // For interpolating between two complex colors, we need to
            // generate colors with effective alpha value.
            let self_color = self.effective_intermediate_rgba();
            let other_color = other.effective_intermediate_rgba();
            let color = self_color.add_weighted(&other_color, self_portion, other_portion)?;
            // Then we compute the final foreground ratio, and derive
            // the final alpha value from the effective alpha value.
            let foreground_ratio = self.foreground_ratio
                .add_weighted(&other.foreground_ratio, self_portion, other_portion)?;
            let alpha = color.alpha / (1. - foreground_ratio);
            Ok(IntermediateColor {
                color: IntermediateRGBA {
                    alpha: alpha,
                    .. color
                },
                foreground_ratio: foreground_ratio,
            })
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sq| sq.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        // All comments in add_weighted also applies here.
        if self.foreground_ratio == other.foreground_ratio {
            if self.is_currentcolor() {
                Ok(0.)
            } else {
                self.color.compute_squared_distance(&other.color)
            }
        } else if self.is_currentcolor() && other.is_numeric() {
            Ok(IntermediateRGBA::transparent().compute_squared_distance(&other.color)? + 1.)
        } else if self.is_numeric() && other.is_currentcolor() {
            Ok(self.color.compute_squared_distance(&IntermediateRGBA::transparent())? + 1.)
        } else {
            let self_color = self.effective_intermediate_rgba();
            let other_color = other.effective_intermediate_rgba();
            let dist = self_color.compute_squared_distance(&other_color)?;
            let ratio_diff = (self.foreground_ratio - other.foreground_ratio) as f64;
            Ok(dist + ratio_diff * ratio_diff)
        }
    }
}

/// Animatable SVGPaint
pub type IntermediateSVGPaint = SVGPaint<IntermediateRGBA>;

/// Animatable SVGPaintKind
pub type IntermediateSVGPaintKind = SVGPaintKind<IntermediateRGBA>;

impl Animatable for IntermediateSVGPaint {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        Ok(IntermediateSVGPaint {
            kind: self.kind.add_weighted(&other.kind, self_portion, other_portion)?,
            fallback: self.fallback.add_weighted(&other.fallback, self_portion, other_portion)?,
        })
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sq| sq.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        Ok(self.kind.compute_squared_distance(&other.kind)? +
            self.fallback.compute_squared_distance(&other.fallback)?)
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        Ok(IntermediateSVGPaint {
            kind: self.kind.get_zero_value()?,
            fallback: self.fallback.and_then(|v| v.get_zero_value().ok()),
        })
    }
}

impl Animatable for IntermediateSVGPaintKind {
    #[inline]
    fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        match (self, other) {
            (&SVGPaintKind::Color(ref self_color), &SVGPaintKind::Color(ref other_color)) => {
                Ok(SVGPaintKind::Color(self_color.add_weighted(other_color, self_portion, other_portion)?))
            }
            // FIXME context values should be interpolable with colors
            // Gecko doesn't implement this behavior either.
            (&SVGPaintKind::None, &SVGPaintKind::None) => Ok(SVGPaintKind::None),
            (&SVGPaintKind::ContextFill, &SVGPaintKind::ContextFill) => Ok(SVGPaintKind::ContextFill),
            (&SVGPaintKind::ContextStroke, &SVGPaintKind::ContextStroke) => Ok(SVGPaintKind::ContextStroke),
            _ => Err(())
        }
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        match (self, other) {
            (&SVGPaintKind::Color(ref self_color), &SVGPaintKind::Color(ref other_color)) => {
                self_color.compute_distance(other_color)
            }
            (&SVGPaintKind::None, &SVGPaintKind::None) |
            (&SVGPaintKind::ContextFill, &SVGPaintKind::ContextFill) |
            (&SVGPaintKind::ContextStroke, &SVGPaintKind::ContextStroke)=> Ok(0.0),
            _ => Err(())
        }
    }

    #[inline]
    fn get_zero_value(&self) -> Result<Self, ()> {
        match *self {
            SVGPaintKind::Color(ref color) => {
                Ok(SVGPaintKind::Color(color.get_zero_value()?))
            },
            SVGPaintKind::None |
            SVGPaintKind::ContextFill |
            SVGPaintKind::ContextStroke => Ok(self.clone()),
            _ => Err(()),
        }
    }
}

<%
    FILTER_FUNCTIONS = [ 'Blur', 'Brightness', 'Contrast', 'Grayscale',
                         'HueRotate', 'Invert', 'Opacity', 'Saturate',
                         'Sepia' ]
%>

/// https://drafts.fxtf.org/filters/#animation-of-filters
fn add_weighted_filter_function_impl(from: &AnimatedFilter,
                                     to: &AnimatedFilter,
                                     self_portion: f64,
                                     other_portion: f64)
                                     -> Result<AnimatedFilter, ()> {
    match (from, to) {
        % for func in [ 'Blur', 'HueRotate' ]:
            (&Filter::${func}(from_value), &Filter::${func}(to_value)) => {
                Ok(Filter::${func}(from_value.add_weighted(
                    &to_value,
                    self_portion,
                    other_portion,
                )?))
           },
        % endfor
        % for func in [ 'Grayscale', 'Invert', 'Sepia' ]:
            (&Filter::${func}(from_value), &Filter::${func}(to_value)) => {
                Ok(Filter::${func}(add_weighted_with_initial_val(
                    &from_value,
                    &to_value,
                    self_portion,
                    other_portion,
                    &0.0,
                )?))
            },
        % endfor
        % for func in [ 'Brightness', 'Contrast', 'Opacity', 'Saturate' ]:
            (&Filter::${func}(from_value), &Filter::${func}(to_value)) => {
                Ok(Filter::${func}(add_weighted_with_initial_val(
                    &from_value,
                    &to_value,
                    self_portion,
                    other_portion,
                    &1.0,
                )?))
                },
        % endfor
        % if product == "gecko":
        (&Filter::DropShadow(ref from_value), &Filter::DropShadow(ref to_value)) => {
            Ok(Filter::DropShadow(from_value.add_weighted(
                &to_value,
                self_portion,
                other_portion,
            )?))
        },
        (&Filter::Url(_), &Filter::Url(_)) => {
            Err(())
        },
        % endif
        _ => {
            // If specified the different filter functions,
            // we will need to interpolate as discreate.
            Err(())
        },
    }
}

/// https://drafts.fxtf.org/filters/#animation-of-filters
fn add_weighted_filter_function(from: Option<<&AnimatedFilter>,
                                to: Option<<&AnimatedFilter>,
                                self_portion: f64,
                                other_portion: f64) -> Result<AnimatedFilter, ()> {
    match (from, to) {
        (Some(f), Some(t)) => {
            add_weighted_filter_function_impl(f, t, self_portion, other_portion)
        },
        (Some(f), None) => {
            add_weighted_filter_function_impl(f, f, self_portion, 0.0)
        },
        (None, Some(t)) => {
            add_weighted_filter_function_impl(t, t, other_portion, 0.0)
        },
        _ => { Err(()) }
    }
}

fn compute_filter_square_distance(from: &AnimatedFilter,
                                  to: &AnimatedFilter)
                                  -> Result<f64, ()> {
    match (from, to) {
        % for func in FILTER_FUNCTIONS :
            (&Filter::${func}(f),
             &Filter::${func}(t)) => {
                Ok(try!(f.compute_squared_distance(&t)))
            },
        % endfor
        % if product == "gecko":
            (&Filter::DropShadow(ref f), &Filter::DropShadow(ref t)) => {
                Ok(try!(f.compute_squared_distance(&t)))
            },
        % endif
        _ => {
            Err(())
        }
    }
}

impl Animatable for AnimatedFilterList {
    #[inline]
    fn add_weighted(&self, other: &Self,
                    self_portion: f64, other_portion: f64) -> Result<Self, ()> {
        let mut filters = vec![];
        let mut from_iter = self.0.iter();
        let mut to_iter = other.0.iter();

        let mut from = from_iter.next();
        let mut to = to_iter.next();
        while from.is_some() || to.is_some() {
            filters.push(try!(add_weighted_filter_function(from,
                                                           to,
                                                           self_portion,
                                                           other_portion)));
            if from.is_some() {
                from = from_iter.next();
            }
            if to.is_some() {
                to = to_iter.next();
            }
        }

        Ok(AnimatedFilterList(filters))
    }

    fn add(&self, other: &Self) -> Result<Self, ()> {
        Ok(AnimatedFilterList(self.0.iter().chain(other.0.iter()).cloned().collect()))
    }

    #[inline]
    fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
        self.compute_squared_distance(other).map(|sd| sd.sqrt())
    }

    #[inline]
    fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
        let mut square_distance: f64 = 0.0;
        let mut from_iter = self.0.iter();
        let mut to_iter = other.0.iter();

        let mut from = from_iter.next();
        let mut to = to_iter.next();
        while from.is_some() || to.is_some() {
            let current_square_distance: f64 ;
            if from.is_none() {
                let none = try!(add_weighted_filter_function(to, to, 0.0, 0.0));
                current_square_distance =
                    compute_filter_square_distance(&none, &(to.unwrap())).unwrap();

                to = to_iter.next();
            } else if to.is_none() {
                let none = try!(add_weighted_filter_function(from, from, 0.0, 0.0));
                current_square_distance =
                    compute_filter_square_distance(&none, &(from.unwrap())).unwrap();

                from = from_iter.next();
            } else {
                current_square_distance =
                    compute_filter_square_distance(&(from.unwrap()),
                                                   &(to.unwrap())).unwrap();

                from = from_iter.next();
                to = to_iter.next();
            }
            square_distance += current_square_distance;
        }
        Ok(square_distance.sqrt())
    }
}