summaryrefslogtreecommitdiffstats
path: root/WebCore/platform/graphics/mac/GraphicsLayerCA.mm
blob: f361437ddee7399d5c24f5e580a07902816ea47d (plain)
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
/*
 * Copyright (C) 2009 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#import "config.h"

#if USE(ACCELERATED_COMPOSITING)

#import "GraphicsLayerCA.h"

#import "Animation.h"
#import "BlockExceptions.h"
#import "CString.h"
#import "FloatConversion.h"
#import "FloatRect.h"
#import "Image.h"
#import "PlatformString.h"
#import <QuartzCore/QuartzCore.h>
#import "RotateTransformOperation.h"
#import "ScaleTransformOperation.h"
#import "SystemTime.h"
#import "TranslateTransformOperation.h"
#import "WebLayer.h"
#import "WebTiledLayer.h"
#import <wtf/CurrentTime.h>
#import <wtf/UnusedParam.h>

using namespace std;

#define HAVE_MODERN_QUARTZCORE (!defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD))

namespace WebCore {

// The threshold width or height above which a tiled layer will be used. This should be
// large enough to avoid tiled layers for most GraphicsLayers, but less than the OpenGL
// texture size limit on all supported hardware.
static const int cMaxPixelDimension = 2000;

// The width and height of a single tile in a tiled layer. Should be large enough to
// avoid lots of small tiles (and therefore lots of drawing callbacks), but small enough
// to keep the overall tile cost low.
static const int cTiledLayerTileSize = 512;

// If we send a duration of 0 to CA, then it will use the default duration
// of 250ms. So send a very small value instead.
static const float cAnimationAlmostZeroDuration = 1e-3f;

// CACurrentMediaTime() is a time since boot. These methods convert between that and
// WebCore time, which is system time (UTC).
static CFTimeInterval currentTimeToMediaTime(double t)
{
    return CACurrentMediaTime() + t - WTF::currentTime();
}

static double mediaTimeToCurrentTime(CFTimeInterval t)
{
    return WTF::currentTime() + t - CACurrentMediaTime();
}

} // namespace WebCore

static NSString* const WebAnimationCSSPropertyKey = @"GraphicsLayerCA_property";

@interface WebAnimationDelegate : NSObject {
    WebCore::GraphicsLayerCA* m_graphicsLayer;
}

- (void)animationDidStart:(CAAnimation *)anim;
- (WebCore::GraphicsLayerCA*)graphicsLayer;
- (void)setLayer:(WebCore::GraphicsLayerCA*)graphicsLayer;

@end

@implementation WebAnimationDelegate

- (void)animationDidStart:(CAAnimation *)animation
{
    if (!m_graphicsLayer)
        return;

    double startTime = WebCore::mediaTimeToCurrentTime([animation beginTime]);
    m_graphicsLayer->client()->notifyAnimationStarted(m_graphicsLayer, startTime);
}

- (WebCore::GraphicsLayerCA*)graphicsLayer
{
    return m_graphicsLayer;
}

- (void)setLayer:(WebCore::GraphicsLayerCA*)graphicsLayer
{
    m_graphicsLayer = graphicsLayer;
}

@end

namespace WebCore {

static inline void copyTransform(CATransform3D& toT3D, const TransformationMatrix& t)
{
    toT3D.m11 = narrowPrecisionToFloat(t.m11());
    toT3D.m12 = narrowPrecisionToFloat(t.m12());
    toT3D.m13 = narrowPrecisionToFloat(t.m13());
    toT3D.m14 = narrowPrecisionToFloat(t.m14());
    toT3D.m21 = narrowPrecisionToFloat(t.m21());
    toT3D.m22 = narrowPrecisionToFloat(t.m22());
    toT3D.m23 = narrowPrecisionToFloat(t.m23());
    toT3D.m24 = narrowPrecisionToFloat(t.m24());
    toT3D.m31 = narrowPrecisionToFloat(t.m31());
    toT3D.m32 = narrowPrecisionToFloat(t.m32());
    toT3D.m33 = narrowPrecisionToFloat(t.m33());
    toT3D.m34 = narrowPrecisionToFloat(t.m34());
    toT3D.m41 = narrowPrecisionToFloat(t.m41());
    toT3D.m42 = narrowPrecisionToFloat(t.m42());
    toT3D.m43 = narrowPrecisionToFloat(t.m43());
    toT3D.m44 = narrowPrecisionToFloat(t.m44());
}

static NSValue* getTransformFunctionValue(const GraphicsLayer::TransformValue& transformValue, size_t index, const IntSize& size, TransformOperation::OperationType transformType)
{
    TransformOperation* op = (index >= transformValue.value()->operations().size()) ? 0 : transformValue.value()->operations()[index].get();
    
    switch (transformType) {
        case TransformOperation::ROTATE:
        case TransformOperation::ROTATE_X:
        case TransformOperation::ROTATE_Y:
            return [NSNumber numberWithDouble:op ? deg2rad(static_cast<RotateTransformOperation*>(op)->angle()) : 0];
        case TransformOperation::SCALE_X:
            return [NSNumber numberWithDouble:op ? static_cast<ScaleTransformOperation*>(op)->x() : 0];
        case TransformOperation::SCALE_Y:
            return [NSNumber numberWithDouble:op ? static_cast<ScaleTransformOperation*>(op)->y() : 0];
        case TransformOperation::SCALE_Z:
            return [NSNumber numberWithDouble:op ? static_cast<ScaleTransformOperation*>(op)->z() : 0];
        case TransformOperation::TRANSLATE_X:
            return [NSNumber numberWithDouble:op ? static_cast<TranslateTransformOperation*>(op)->x(size) : 0];
        case TransformOperation::TRANSLATE_Y:
            return [NSNumber numberWithDouble:op ? static_cast<TranslateTransformOperation*>(op)->y(size) : 0];
        case TransformOperation::TRANSLATE_Z:
            return [NSNumber numberWithDouble:op ? static_cast<TranslateTransformOperation*>(op)->z(size) : 0];
        case TransformOperation::SCALE:
        case TransformOperation::TRANSLATE:
        case TransformOperation::SKEW_X:
        case TransformOperation::SKEW_Y:
        case TransformOperation::SKEW:
        case TransformOperation::MATRIX:
        case TransformOperation::SCALE_3D:
        case TransformOperation::TRANSLATE_3D:
        case TransformOperation::ROTATE_3D:
        case TransformOperation::MATRIX_3D:
        case TransformOperation::PERSPECTIVE:
        case TransformOperation::IDENTITY:
        case TransformOperation::NONE: {
            TransformationMatrix t;
            if (op)
                op->apply(t, size);
            CATransform3D cat;
            copyTransform(cat, t);
            return [NSValue valueWithCATransform3D:cat];
        }
    }
    
    return 0;
}

#if HAVE_MODERN_QUARTZCORE
static NSString* getValueFunctionNameForTransformOperation(TransformOperation::OperationType transformType)
{
    // Use literal strings to avoid link-time dependency on those symbols.
    switch (transformType) {
        case TransformOperation::ROTATE_X:
            return @"rotateX"; // kCAValueFunctionRotateX;
        case TransformOperation::ROTATE_Y:
            return @"rotateY"; // kCAValueFunctionRotateY;
        case TransformOperation::ROTATE:
            return @"rotateZ"; // kCAValueFunctionRotateZ;
        case TransformOperation::SCALE_X:
            return @"scaleX"; // kCAValueFunctionScaleX;
        case TransformOperation::SCALE_Y:
            return @"scaleY"; // kCAValueFunctionScaleY;
        case TransformOperation::SCALE_Z:
            return @"scaleZ"; // kCAValueFunctionScaleZ;
        case TransformOperation::TRANSLATE_X:
            return @"translateX"; // kCAValueFunctionTranslateX;
        case TransformOperation::TRANSLATE_Y:
            return @"translateY"; // kCAValueFunctionTranslateY;
        case TransformOperation::TRANSLATE_Z:
            return @"translateZ"; // kCAValueFunctionTranslateZ;
        default:
            return nil;
    }
}
#endif

static CAMediaTimingFunction* getCAMediaTimingFunction(const TimingFunction& timingFunction)
{
    switch (timingFunction.type()) {
        case LinearTimingFunction:
            return [CAMediaTimingFunction functionWithName:@"linear"];
        case CubicBezierTimingFunction:
            return [CAMediaTimingFunction functionWithControlPoints:static_cast<float>(timingFunction.x1()) :static_cast<float>(timingFunction.y1())
                        :static_cast<float>(timingFunction.x2()) :static_cast<float>(timingFunction.y2())];
    }
    return 0;
}

#ifndef NDEBUG
static void setLayerBorderColor(PlatformLayer* layer, const Color& color)
{
    CGColorRef borderColor = createCGColor(color);
    [layer setBorderColor:borderColor];
    CGColorRelease(borderColor);
}

static void clearBorderColor(PlatformLayer* layer)
{
    [layer setBorderColor:nil];
}
#endif

static void setLayerBackgroundColor(PlatformLayer* layer, const Color& color)
{
    CGColorRef bgColor = createCGColor(color);
    [layer setBackgroundColor:bgColor];
    CGColorRelease(bgColor);
}

static void clearLayerBackgroundColor(PlatformLayer* layer)
{
    [layer setBackgroundColor:0];
}

static CALayer* getPresentationLayer(CALayer* layer)
{
    CALayer*  presLayer = [layer presentationLayer];
    if (!presLayer)
        presLayer = layer;

    return presLayer;
}

static bool caValueFunctionSupported()
{
    static bool sHaveValueFunction = [CAPropertyAnimation instancesRespondToSelector:@selector(setValueFunction:)];
    return sHaveValueFunction;
}

static bool forceSoftwareAnimation()
{
    static bool forceSoftwareAnimation = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebCoreForceSoftwareAnimation"];
    return forceSoftwareAnimation;
}

GraphicsLayer::CompositingCoordinatesOrientation GraphicsLayer::compositingCoordinatesOrientation()
{
    return CompositingCoordinatesBottomUp;
}

#ifndef NDEBUG
bool GraphicsLayer::showDebugBorders()
{
    static bool showDebugBorders = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebCoreLayerBorders"];
    return showDebugBorders;
}

bool GraphicsLayer::showRepaintCounter()
{
    static bool showRepaintCounter = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebCoreLayerRepaintCounter"];
    return showRepaintCounter;
}
#endif

static NSDictionary* nullActionsDictionary()
{
    NSNull* nullValue = [NSNull null];
    NSDictionary* actions = [NSDictionary dictionaryWithObjectsAndKeys:
                             nullValue, @"anchorPoint",
                             nullValue, @"bounds",
                             nullValue, @"contents",
                             nullValue, @"contentsRect",
                             nullValue, @"opacity",
                             nullValue, @"position",
                             nullValue, @"shadowColor",
                             nullValue, @"sublayerTransform",
                             nullValue, @"sublayers",
                             nullValue, @"transform",
#ifndef NDEBUG
                             nullValue, @"zPosition",
#endif
                             nil];
    return actions;
}

GraphicsLayer* GraphicsLayer::createGraphicsLayer(GraphicsLayerClient* client)
{
    return new GraphicsLayerCA(client);
}

GraphicsLayerCA::GraphicsLayerCA(GraphicsLayerClient* client)
: GraphicsLayer(client)
, m_contentLayerForImageOrVideo(false)
{
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    m_layer.adoptNS([[WebLayer alloc] init]);
    [m_layer.get() setLayerOwner:this];

#ifndef NDEBUG
    updateDebugIndicators();
#endif

    m_animationDelegate.adoptNS([[WebAnimationDelegate alloc] init]);
    [m_animationDelegate.get() setLayer:this];
    
    END_BLOCK_OBJC_EXCEPTIONS
}

GraphicsLayerCA::~GraphicsLayerCA()
{
    // Remove a inner layer if there is one.
    clearContents();

    BEGIN_BLOCK_OBJC_EXCEPTIONS

    // Clean up the WK layer.
    if (m_layer) {
        WebLayer* layer = m_layer.get();
        [layer setLayerOwner:nil];
        [layer removeFromSuperlayer];
    }
    
    if (m_transformLayer)
        [m_transformLayer.get() removeFromSuperlayer];

    // animationDidStart: can fire after this, so we need to clear out the layer on the delegate.
    [m_animationDelegate.get() setLayer:0];

    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setName(const String& name)
{
    String longName = String::format("CALayer(%p) GraphicsLayer(%p) ", m_layer.get(), this) + name;
    GraphicsLayer::setName(longName);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [m_layer.get() setName:name];
    END_BLOCK_OBJC_EXCEPTIONS
}

NativeLayer GraphicsLayerCA::nativeLayer() const
{
    return m_layer.get();
}

void GraphicsLayerCA::addChild(GraphicsLayer* childLayer)
{
    GraphicsLayer::addChild(childLayer);

    GraphicsLayerCA* childLayerCA = static_cast<GraphicsLayerCA*>(childLayer);
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [hostLayerForSublayers() addSublayer:childLayerCA->layerForSuperlayer()];
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::addChildAtIndex(GraphicsLayer* childLayer, int index)
{
    GraphicsLayer::addChildAtIndex(childLayer, index);

    GraphicsLayerCA* childLayerCA = static_cast<GraphicsLayerCA*>(childLayer);
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [hostLayerForSublayers() insertSublayer:childLayerCA->layerForSuperlayer() atIndex:index];
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::addChildBelow(GraphicsLayer* childLayer, GraphicsLayer* sibling)
{
    // FIXME: share code with base class
    ASSERT(childLayer != this);
    childLayer->removeFromParent();

    bool found = false;
    for (unsigned i = 0; i < m_children.size(); i++) {
        if (sibling == m_children[i]) {
            m_children.insert(i, childLayer);
            found = true;
            break;
        }
    }
    childLayer->setParent(this);

    BEGIN_BLOCK_OBJC_EXCEPTIONS

    GraphicsLayerCA* childLayerCA = static_cast<GraphicsLayerCA*>(childLayer);
    GraphicsLayerCA* siblingLayerCA = static_cast<GraphicsLayerCA*>(sibling);
    if (found)
        [hostLayerForSublayers() insertSublayer:childLayerCA->layerForSuperlayer() below:siblingLayerCA->layerForSuperlayer()];
    else {
        m_children.append(childLayer);
        [hostLayerForSublayers() addSublayer:childLayerCA->layerForSuperlayer()];
    }

    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::addChildAbove(GraphicsLayer* childLayer, GraphicsLayer* sibling)
{
    // FIXME: share code with base class
    ASSERT(childLayer != this);
    childLayer->removeFromParent();

    unsigned i;
    bool found = false;
    for (i = 0; i < m_children.size(); i++) {
        if (sibling == m_children[i]) {
            m_children.insert(i+1, childLayer);
            found = true;
            break;
        }
    }
    childLayer->setParent(this);

    BEGIN_BLOCK_OBJC_EXCEPTIONS

    GraphicsLayerCA* childLayerCA = static_cast<GraphicsLayerCA*>(childLayer);
    GraphicsLayerCA* siblingLayerCA = static_cast<GraphicsLayerCA*>(sibling);
    if (found) {
        [hostLayerForSublayers() insertSublayer:childLayerCA->layerForSuperlayer() above:siblingLayerCA->layerForSuperlayer()];
    } else {
        m_children.append(childLayer);
        [hostLayerForSublayers() addSublayer:childLayerCA->layerForSuperlayer()];
    }

    END_BLOCK_OBJC_EXCEPTIONS
}

bool GraphicsLayerCA::replaceChild(GraphicsLayer* oldChild, GraphicsLayer* newChild)
{
    // FIXME: share code with base class
    ASSERT(!newChild->parent());

    bool found = false;
    for (unsigned i = 0; i < m_children.size(); i++) {
        if (oldChild == m_children[i]) {
            m_children[i] = newChild;
            found = true;
            break;
        }
    }

    if (found) {
        oldChild->setParent(0);

        newChild->removeFromParent();
        newChild->setParent(this);

        BEGIN_BLOCK_OBJC_EXCEPTIONS
        GraphicsLayerCA* oldChildCA = static_cast<GraphicsLayerCA*>(oldChild);
        GraphicsLayerCA* newChildCA = static_cast<GraphicsLayerCA*>(newChild);
        [hostLayerForSublayers() replaceSublayer:oldChildCA->layerForSuperlayer() with:newChildCA->layerForSuperlayer()];
        END_BLOCK_OBJC_EXCEPTIONS
        return true;
    }
    return false;
}

void GraphicsLayerCA::removeFromParent()
{
    GraphicsLayer::removeFromParent();

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [layerForSuperlayer() removeFromSuperlayer];            
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setPosition(const FloatPoint& point)
{
    // Don't short-circuit here, because position and anchor point are inter-dependent.
    GraphicsLayer::setPosition(point);

    // Position is offset on the layer by the layer anchor point.
    CGPoint posPoint = CGPointMake(m_position.x() + m_anchorPoint.x() * m_size.width(),
                                   m_position.y() + m_anchorPoint.y() * m_size.height());
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [primaryLayer() setPosition:posPoint];
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setAnchorPoint(const FloatPoint3D& point)
{
    // Don't short-circuit here, because position and anchor point are inter-dependent.
    bool zChanged = (point.z() != m_anchorPoint.z());
    GraphicsLayer::setAnchorPoint(point);

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    // set the value on the layer to the new transform.
    [primaryLayer() setAnchorPoint:FloatPoint(point.x(), point.y())];

    if (zChanged) {
#if HAVE_MODERN_QUARTZCORE
        [primaryLayer() setAnchorPointZ:m_anchorPoint.z()];
#endif
    }

    // Position depends on anchor point, so update it now.
    setPosition(m_position);
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setSize(const FloatSize& size)
{
    GraphicsLayer::setSize(size);

    CGRect rect = CGRectMake(0.0f,
                             0.0f,
                             m_size.width(),
                             m_size.height());
    
    CGPoint centerPoint = CGPointMake(m_size.width() / 2.0f, m_size.height() / 2.0f);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS

    if (m_transformLayer) {
        [m_transformLayer.get() setBounds:rect];
    
        // the anchor of the contents layer is always at 0.5, 0.5, so the position
        // is center-relative
        [m_layer.get() setPosition:centerPoint];
    }
    
    bool needTiledLayer = requiresTiledLayer(m_size);
    if (needTiledLayer != m_usingTiledLayer)
        swapFromOrToTiledLayer(needTiledLayer);
    
    [m_layer.get() setBounds:rect];

    // Note that we don't resize m_contentsLayer. It's up the caller to do that.

    END_BLOCK_OBJC_EXCEPTIONS

    // if we've changed the bounds, we need to recalculate the position
    // of the layer, taking anchor point into account
    setPosition(m_position);
}

void GraphicsLayerCA::setTransform(const TransformationMatrix& t)
{
    GraphicsLayer::setTransform(t);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    CATransform3D transform;
    copyTransform(transform, t);
    [primaryLayer() setTransform:transform];
    END_BLOCK_OBJC_EXCEPTIONS
    
    // Remove any old transition entries for transform.
    removeAllAnimationsForProperty(AnimatedPropertyWebkitTransform);

    // Even if we don't have a transition in the list, the layer may still have one.
    // This happens when we are setting the final transform value after an animation or
    // transition has ended. In removeAnimation we toss the entry from the list but don't
    // remove it from the list. That way we aren't in danger of displaying a stale transform
    // in the time between removing the animation and setting the new unanimated value. We 
    // can't do this in removeAnimation because we don't know the new transform value there.
    String keyPath = propertyIdToString(AnimatedPropertyWebkitTransform);
    CALayer* layer = animatedLayer(AnimatedPropertyWebkitTransform);
    
    for (int i = 0; ; ++i) {
        String animName = keyPath + "_" + String::number(i);
        if (![layer animationForKey: animName])
            break;
        [layer removeAnimationForKey:animName];
    }
}

void GraphicsLayerCA::setChildrenTransform(const TransformationMatrix& t)
{
    if (t == m_childrenTransform)
        return;

    GraphicsLayer::setChildrenTransform(t);

    CATransform3D transform;
    copyTransform(transform, t);

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    // Set the value on the layer to the new transform.
    [primaryLayer() setSublayerTransform:transform];
    END_BLOCK_OBJC_EXCEPTIONS
}

static void moveAnimation(AnimatedPropertyID property, CALayer* fromLayer, CALayer* toLayer)
{
    String keyPath = GraphicsLayer::propertyIdToString(property);
    for (short index = 0; ; ++index) {
        String animName = keyPath + "_" + String::number(index);
        CAAnimation* anim = [fromLayer animationForKey:animName];
        if (!anim)
            break;

        [anim retain];
        [fromLayer removeAnimationForKey:animName];
        [toLayer addAnimation:anim forKey:animName];
        [anim release];
    }
}

static void moveSublayers(CALayer* fromLayer, CALayer* toLayer)
{
    NSArray* sublayersCopy = [[fromLayer sublayers] copy]; // Avoid mutation while enumerating, and keep the sublayers alive.
    NSEnumerator* childrenEnumerator = [sublayersCopy objectEnumerator];

    CALayer* layer;
    while ((layer = [childrenEnumerator nextObject]) != nil) {
        [layer removeFromSuperlayer];
        [toLayer addSublayer:layer];
    }
    [sublayersCopy release];
}

void GraphicsLayerCA::setPreserves3D(bool preserves3D)
{
    GraphicsLayer::setPreserves3D(preserves3D);

    CGPoint point = CGPointMake(m_size.width() / 2.0f, m_size.height() / 2.0f);
    CGPoint centerPoint = CGPointMake(0.5f, 0.5f);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS

    Class transformLayerClass = NSClassFromString(@"CATransformLayer");
    if (preserves3D && !m_transformLayer && transformLayerClass) {
        // Create the transform layer.
        m_transformLayer.adoptNS([[transformLayerClass alloc] init]);

        // Turn off default animations.
        [m_transformLayer.get() setStyle:[NSDictionary dictionaryWithObject:nullActionsDictionary() forKey:@"actions"]];
        
#ifndef NDEBUG
        [m_transformLayer.get() setName:[NSString stringWithFormat:@"Transform Layer CATransformLayer(%p) GraphicsLayer(%p)", m_transformLayer.get(), this]];
#endif
        // Copy the position from this layer.
        [m_transformLayer.get() setBounds:[m_layer.get() bounds]];
        [m_transformLayer.get() setPosition:[m_layer.get() position]];
        [m_transformLayer.get() setAnchorPoint:[m_layer.get() anchorPoint]];
#if HAVE_MODERN_QUARTZCORE
        [m_transformLayer.get() setAnchorPointZ:[m_layer.get() anchorPointZ]];
#endif
        [m_transformLayer.get() setContentsRect:[m_layer.get() contentsRect]];
#ifndef NDEBUG
        [m_transformLayer.get() setZPosition:[m_layer.get() zPosition]];
#endif
        
        // The contents layer is positioned at (0,0) relative to the transformLayer.
        [m_layer.get() setPosition:point];
        [m_layer.get() setAnchorPoint:centerPoint];
#ifndef NDEBUG
        [m_layer.get() setZPosition:0.0f];
#endif
        
        // Transfer the transform over.
        [m_transformLayer.get() setTransform:[m_layer.get() transform]];
        [m_layer.get() setTransform:CATransform3DIdentity];
        
        // Transfer the opacity from the old layer to the transform layer.
        [m_transformLayer.get() setOpacity:m_opacity];
        [m_layer.get() setOpacity:1];

        // Move this layer to be a child of the transform layer.
        [[m_layer.get() superlayer] replaceSublayer:m_layer.get() with:m_transformLayer.get()];
        [m_transformLayer.get() addSublayer:m_layer.get()];

        moveAnimation(AnimatedPropertyWebkitTransform, m_layer.get(), m_transformLayer.get());
        moveSublayers(m_layer.get(), m_transformLayer.get());

    } else if (!preserves3D && m_transformLayer) {
        // Relace the transformLayer in the parent with this layer.
        [m_layer.get() removeFromSuperlayer];
        [[m_transformLayer.get() superlayer] replaceSublayer:m_transformLayer.get() with:m_layer.get()];

        moveAnimation(AnimatedPropertyWebkitTransform, m_transformLayer.get(), m_layer.get());
        moveSublayers(m_transformLayer.get(), m_layer.get());

        // Reset the layer position and transform.
        [m_layer.get() setPosition:[m_transformLayer.get() position]];
        [m_layer.get() setAnchorPoint:[m_transformLayer.get() anchorPoint]];
#if HAVE_MODERN_QUARTZCORE
        [m_layer.get() setAnchorPointZ:[m_transformLayer.get() anchorPointZ]];
#endif
        [m_layer.get() setContentsRect:[m_transformLayer.get() contentsRect]];
        [m_layer.get() setTransform:[m_transformLayer.get() transform]];
        [m_layer.get() setOpacity:[m_transformLayer.get() opacity]];
#ifndef NDEBUG
        [m_layer.get() setZPosition:[m_transformLayer.get() zPosition]];
#endif

        // Release the transform layer.
        m_transformLayer = 0;
    }

    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setMasksToBounds(bool masksToBounds)
{
    if (masksToBounds == m_masksToBounds)
        return;

    GraphicsLayer::setMasksToBounds(masksToBounds);

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [m_layer.get() setMasksToBounds:masksToBounds];
    END_BLOCK_OBJC_EXCEPTIONS

#ifndef NDEBUG
    updateDebugIndicators();
#endif
}

void GraphicsLayerCA::setDrawsContent(bool drawsContent)
{
    if (drawsContent != m_drawsContent) {
        GraphicsLayer::setDrawsContent(drawsContent);

        bool needTiledLayer = requiresTiledLayer(m_size);
        if (needTiledLayer != m_usingTiledLayer)
            swapFromOrToTiledLayer(needTiledLayer);

        BEGIN_BLOCK_OBJC_EXCEPTIONS
        if (m_drawsContent)
            [m_layer.get() setNeedsDisplay];
        else
            [m_layer.get() setContents:nil];
        
#ifndef NDEBUG
        updateDebugIndicators();
#endif
        END_BLOCK_OBJC_EXCEPTIONS
    }
}

void GraphicsLayerCA::setBackgroundColor(const Color& color, const Animation* transition, double beginTime)
{
    GraphicsLayer::setBackgroundColor(color, transition, beginTime);

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    if (!m_contentsLayer.get()) {
        WebLayer* colorLayer = [WebLayer layer];
#ifndef NDEBUG
        [colorLayer setName:@"Color Layer"];
#endif
        setContentsLayer(colorLayer);
    }
    
    if (transition && !transition->isEmptyOrZeroDuration()) {
        CALayer* presLayer = [m_contentsLayer.get() presentationLayer];
        // If we don't have a presentationLayer, just use the CALayer
        if (!presLayer)
            presLayer = m_contentsLayer.get();

        // Get the current value of the background color from the layer
        CGColorRef fromBackgroundColor = [presLayer backgroundColor];

        CGColorRef bgColor = createCGColor(color);
        setBasicAnimation(AnimatedPropertyBackgroundColor, TransformOperation::NONE, 0, fromBackgroundColor, bgColor, true, transition, beginTime);
        CGColorRelease(bgColor);
    } else {
        removeAllAnimationsForProperty(AnimatedPropertyBackgroundColor);    
        setLayerBackgroundColor(m_contentsLayer.get(), m_backgroundColor);
    }

    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::clearBackgroundColor()
{
    if (!m_contentLayerForImageOrVideo)
        setContentsLayer(0);
    else
        clearLayerBackgroundColor(m_contentsLayer.get());
}

void GraphicsLayerCA::setContentsOpaque(bool opaque)
{
    GraphicsLayer::setContentsOpaque(opaque);

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [m_layer.get() setOpaque:m_contentsOpaque];
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setBackfaceVisibility(bool visible)
{
    if (m_backfaceVisibility == visible)
        return;
    
    GraphicsLayer::setBackfaceVisibility(visible);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [m_layer.get() setDoubleSided:visible];
    END_BLOCK_OBJC_EXCEPTIONS
}

bool GraphicsLayerCA::setOpacity(float opacity, const Animation* transition, double beginTime)
{
    if (forceSoftwareAnimation())
        return false;
        
    float clampedOpacity = max(0.0f, min(opacity, 1.0f));
    
    bool opacitiesDiffer = (m_opacity != clampedOpacity);
    
    GraphicsLayer::setOpacity(clampedOpacity, transition, beginTime);
    
    int animIndex = findAnimationEntry(AnimatedPropertyOpacity, 0);
        
    // If we don't have a transition just set the opacity
    if (!transition || transition->isEmptyOrZeroDuration()) {
        // Three cases:
        //  1) no existing animation or transition: just set opacity
        //  2) existing transition: clear it and set opacity
        //  3) existing animation: just return
        //
        if (animIndex < 0 || m_animations[animIndex].isTransition()) {
            BEGIN_BLOCK_OBJC_EXCEPTIONS
            [primaryLayer() setOpacity:opacity];
            if (animIndex >= 0) {
                removeAllAnimationsForProperty(AnimatedPropertyOpacity);
                animIndex = -1;
            } else {
                String keyPath = propertyIdToString(AnimatedPropertyOpacity);
                
                // FIXME: using hardcoded '0' here. We should be clearing all animations. For now there is only 1.
                String animName = keyPath + "_0";
                [animatedLayer(AnimatedPropertyOpacity) removeAnimationForKey:animName];
            }
            END_BLOCK_OBJC_EXCEPTIONS
        } else {
            // We have an animation, so don't set the opacity directly.
            return false;
        }
    } else {
        // At this point, we know we have a transition. But if it is the same and
        // the opacity value has not changed, don't do anything.
        if (!opacitiesDiffer &&
                ((animIndex == -1) ||    
                 (m_animations[animIndex].isTransition() && *(m_animations[animIndex].animation()) == *transition))) {
            return false;
        }
    }
    
    // If an animation is running, ignore this transition, but still save the value.
    if (animIndex >= 0 && !m_animations[animIndex].isTransition())
        return false;

    bool didAnimate = false;
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    NSNumber* fromOpacityValue = nil;
    NSNumber* toOpacityValue = [NSNumber numberWithFloat:opacity];
    
    if (transition && !transition->isEmptyOrZeroDuration()) {
        CALayer* presLayer = getPresentationLayer(primaryLayer());
        float fromOpacity = [presLayer opacity];
        fromOpacityValue = [NSNumber numberWithFloat:fromOpacity];
        setBasicAnimation(AnimatedPropertyOpacity, TransformOperation::NONE, 0, fromOpacityValue, toOpacityValue, true, transition, beginTime);
        didAnimate = true;
    }

    END_BLOCK_OBJC_EXCEPTIONS
    
    return didAnimate;
}

void GraphicsLayerCA::setNeedsDisplay()
{
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    if (drawsContent())
        [m_layer.get() setNeedsDisplay];

    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setNeedsDisplayInRect(const FloatRect& rect)
{
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    if (drawsContent())
        [m_layer.get() setNeedsDisplayInRect:rect];

    END_BLOCK_OBJC_EXCEPTIONS
}


bool GraphicsLayerCA::animateTransform(const TransformValueList& valueList, const IntSize& size, const Animation* anim, double beginTime, bool isTransition)
{
    if (forceSoftwareAnimation() || !anim || anim->isEmptyOrZeroDuration() || valueList.size() < 2)
        return false;
        
    TransformValueList::FunctionList functionList;
    bool isValid, hasBigRotation;
    valueList.makeFunctionList(functionList, isValid, hasBigRotation);

    // We need to fall back to software animation if we don't have setValueFunction:, and
    // we would need to animate each incoming transform function separately. This is the
    // case if we have a rotation >= 180 or we have more than one transform function.
    if ((hasBigRotation || functionList.size() > 1) && !caValueFunctionSupported())
        return false;
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    // Rules for animation:
    //
    //  1)  If functionList is empty or we don't have a big rotation, we do a matrix animation. We could
    //      use component animation for lists without a big rotation, but there is no need to, and this
    //      is more efficient.
    //
    //  2)  Otherwise we do a component hardware animation.
    bool isMatrixAnimation = !isValid || !hasBigRotation;
        
    // Set transform to identity since we are animating components and we need the base
    // to be the identity transform.
    TransformationMatrix t;
    CATransform3D toT3D;
    copyTransform(toT3D, t);
    [primaryLayer() setTransform:toT3D];
        
    bool isKeyframe = valueList.size() > 2;
        
    // Iterate through the transform functions, sending an animation for each one.
    for (int functionIndex = 0; ; ++functionIndex) {
        if (functionIndex >= static_cast<int>(functionList.size()) && !isMatrixAnimation)
            break;
            
        TransformOperation::OperationType opType = isMatrixAnimation ? TransformOperation::MATRIX_3D : functionList[functionIndex];

        if (isKeyframe) {
            NSMutableArray* timesArray = [[NSMutableArray alloc] init];
            NSMutableArray* valArray = [[NSMutableArray alloc] init];
            NSMutableArray* tfArray = [[NSMutableArray alloc] init];
            
            // Iterate through the keyframes, building arrays for the animation.
            for (Vector<TransformValue>::const_iterator it = valueList.values().begin(); it != valueList.values().end(); ++it) {
                const TransformValue& curValue = (*it);
                
                // fill in the key time and timing function
                [timesArray addObject:[NSNumber numberWithFloat:curValue.key()]];
                
                const TimingFunction* tf = 0;
                if (curValue.timingFunction())
                    tf = curValue.timingFunction();
                else if (anim->isTimingFunctionSet())
                    tf = &anim->timingFunction();
                
                CAMediaTimingFunction* timingFunction = getCAMediaTimingFunction(tf ? *tf : TimingFunction(LinearTimingFunction));
                [tfArray addObject:timingFunction];
                
                // fill in the function
                if (isMatrixAnimation) {
                    TransformationMatrix t;
                    curValue.value()->apply(size, t);
                    CATransform3D cat;
                    copyTransform(cat, t);
                    [valArray addObject:[NSValue valueWithCATransform3D:cat]];
                } else
                    [valArray addObject:getTransformFunctionValue(curValue, functionIndex, size, opType)];
            }
            
            // We toss the last tfArray value because it has to one shorter than the others.
            [tfArray removeLastObject];
            
            setKeyframeAnimation(AnimatedPropertyWebkitTransform, opType, functionIndex, timesArray, valArray, tfArray, isTransition, anim, beginTime);
            
            [timesArray release];
            [valArray release];
            [tfArray release];
        } else {
            // Is a transition
            id fromValue, toValue;
            
            if (isMatrixAnimation) {
                TransformationMatrix fromt, tot;
                valueList.at(0).value()->apply(size, fromt);
                valueList.at(1).value()->apply(size, tot);
                
                CATransform3D cat;
                copyTransform(cat, fromt);
                fromValue = [NSValue valueWithCATransform3D:cat];
                copyTransform(cat, tot);
                toValue = [NSValue valueWithCATransform3D:cat];
            } else {
                fromValue = getTransformFunctionValue(valueList.at(0), functionIndex, size, opType);
                toValue = getTransformFunctionValue(valueList.at(1), functionIndex, size, opType);
            }
            
            setBasicAnimation(AnimatedPropertyWebkitTransform, opType, functionIndex, fromValue, toValue, isTransition, anim, beginTime);
        }
        
        if (isMatrixAnimation)
            break;
    }

    END_BLOCK_OBJC_EXCEPTIONS
    return true;
}

bool GraphicsLayerCA::animateFloat(AnimatedPropertyID property, const FloatValueList& valueList, const Animation* animation, double beginTime)
{
    if (forceSoftwareAnimation() || valueList.size() < 2)
        return false;
        
    // if there is already is an animation for this property and it hasn't changed, ignore it.
    int i = findAnimationEntry(property, 0);
    if (i >= 0 && *m_animations[i].animation() == *animation) {
        m_animations[i].setIsCurrent();
        return false;
    }

    if (valueList.size() == 2) {
        float fromVal = valueList.at(0).value();
        float toVal   = valueList.at(1).value();
        if (isnan(toVal) && isnan(fromVal))
            return false;
    
        // initialize the property to 0
        [animatedLayer(property) setValue:0 forKeyPath:propertyIdToString(property)];
        setBasicAnimation(property, TransformOperation::NONE, 0, isnan(fromVal) ? nil : [NSNumber numberWithFloat:fromVal], isnan(toVal) ? nil : [NSNumber numberWithFloat:toVal], false, animation, beginTime);
        return true;
    }

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    NSMutableArray* timesArray = [[NSMutableArray alloc] init];
    NSMutableArray* valArray = [[NSMutableArray alloc] init];
    NSMutableArray* tfArray = [[NSMutableArray alloc] init];

    for (unsigned i = 0; i < valueList.values().size(); ++i) {
        const FloatValue& curValue = valueList.values()[i];
        [timesArray addObject:[NSNumber numberWithFloat:curValue.key()]];
        [valArray addObject:[NSNumber numberWithFloat:curValue.value()]];

        const TimingFunction* tf = 0;
        if (curValue.timingFunction())
            tf = curValue.timingFunction();
        else if (animation->isTimingFunctionSet())
            tf = &animation->timingFunction();

        CAMediaTimingFunction* timingFunction = getCAMediaTimingFunction(tf ? *tf : TimingFunction());
        [tfArray addObject:timingFunction];
    }
    
    // We toss the last tfArray value because it has to one shorter than the others.
    [tfArray removeLastObject];
    
    // Initialize the property to 0.
    [animatedLayer(property) setValue:0 forKeyPath:propertyIdToString(property)];
    // Then set the animation.
    setKeyframeAnimation(property, TransformOperation::NONE, 0, timesArray, valArray, tfArray, false, animation, beginTime);

    [timesArray release];
    [valArray release];
    [tfArray release];

    END_BLOCK_OBJC_EXCEPTIONS
    return true;
}

void GraphicsLayerCA::setContentsToImage(Image* image)
{
    if (image) {
        BEGIN_BLOCK_OBJC_EXCEPTIONS
        {
            if (!m_contentsLayer.get()) {
                WebLayer* imageLayer = [WebLayer layer];
#ifndef NDEBUG
                [imageLayer setName:@"Image Layer"];
#endif
                setContentsLayer(imageLayer);
            }

            // FIXME: maybe only do trilinear if the image is being scaled down,
            // but then what if the layer size changes?
#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
            [m_contentsLayer.get() setMinificationFilter:kCAFilterTrilinear];
#endif
            CGImageRef theImage = image->nativeImageForCurrentFrame();
            [m_contentsLayer.get() setContents:(id)theImage];
        }
        END_BLOCK_OBJC_EXCEPTIONS
    } else
        setContentsLayer(0);

    m_contentLayerForImageOrVideo = (image != 0);
}

void GraphicsLayerCA::setContentsToVideo(PlatformLayer* videoLayer)
{
    setContentsLayer(videoLayer);
    m_contentLayerForImageOrVideo = (videoLayer != 0);
}

void GraphicsLayerCA::clearContents()
{
    if (m_contentLayerForImageOrVideo) {
        setContentsLayer(0);
        m_contentLayerForImageOrVideo = false;
    }
}

void GraphicsLayerCA::updateContentsRect()
{
    if (m_client && m_contentsLayer) {
        IntRect contentRect = m_client->contentsBox(this);
        
        CGPoint point = CGPointMake(contentRect.x(),
                                    contentRect.y());
        CGRect rect = CGRectMake(0.0f,
                                 0.0f,
                                 contentRect.width(),
                                 contentRect.height());

        BEGIN_BLOCK_OBJC_EXCEPTIONS
        [m_contentsLayer.get() setPosition:point];
        [m_contentsLayer.get() setBounds:rect];
        END_BLOCK_OBJC_EXCEPTIONS
    }
}

void GraphicsLayerCA::setBasicAnimation(AnimatedPropertyID property, TransformOperation::OperationType operationType, short index, void* fromVal, void* toVal, bool isTransition, const Animation* transition, double beginTime)
{
    ASSERT(fromVal || toVal);

    WebLayer* layer = animatedLayer(property);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS

    // add an entry for this animation
    addAnimationEntry(property, index, isTransition, transition);

    String keyPath = propertyIdToString(property);
    String animName = keyPath + "_" + String::number(index);

    CABasicAnimation* basicAnim = [CABasicAnimation animationWithKeyPath:keyPath];
    
    double duration = transition->duration();
    if (duration <= 0)
        duration = cAnimationAlmostZeroDuration;
        
    float repeatCount = transition->iterationCount();
    if (repeatCount == Animation::IterationCountInfinite)
        repeatCount = FLT_MAX;
    else if (transition->direction() == Animation::AnimationDirectionAlternate)
        repeatCount /= 2;
        
    [basicAnim setDuration:duration];
    [basicAnim setRepeatCount:repeatCount];
    [basicAnim setAutoreverses:transition->direction()];
    [basicAnim setRemovedOnCompletion:NO];

    // Note that currently transform is the only property which has animations
    // with an index > 0.
    [basicAnim setAdditive:property == AnimatedPropertyWebkitTransform];
    [basicAnim setFillMode:@"extended"];
#if HAVE_MODERN_QUARTZCORE
    if (NSString* valueFunctionName = getValueFunctionNameForTransformOperation(operationType))
        [basicAnim setValueFunction:[CAValueFunction functionWithName:valueFunctionName]];
#else
    UNUSED_PARAM(operationType);
#endif
    
    // Set the delegate (and property value).
    int prop = isTransition ? property : AnimatedPropertyInvalid;
    [basicAnim setValue:[NSNumber numberWithInt:prop] forKey:WebAnimationCSSPropertyKey];
    [basicAnim setDelegate:m_animationDelegate.get()];

    NSTimeInterval bt = beginTime ? [layer convertTime:currentTimeToMediaTime(beginTime) fromLayer:nil] : 0;
    [basicAnim setBeginTime:bt];
    
    if (fromVal)
        [basicAnim setFromValue:reinterpret_cast<id>(fromVal)];
    if (toVal)
        [basicAnim setToValue:reinterpret_cast<id>(toVal)];

    const TimingFunction* tf = 0;
    if (transition->isTimingFunctionSet())
        tf = &transition->timingFunction();

    CAMediaTimingFunction* timingFunction = getCAMediaTimingFunction(tf ? *tf : TimingFunction());
    [basicAnim setTimingFunction:timingFunction];

    // Send over the animation.
    [layer removeAnimationForKey:animName];
    [layer addAnimation:basicAnim forKey:animName];
    
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setKeyframeAnimation(AnimatedPropertyID property, TransformOperation::OperationType operationType, short index, void* keys, void* values, void* timingFunctions, 
                                    bool isTransition, const Animation* anim, double beginTime)
{
    PlatformLayer* layer = animatedLayer(property);

    // Add an entry for this animation (which may change beginTime).
    addAnimationEntry(property, index, isTransition, anim);

    String keyPath = propertyIdToString(property);
    String animName = keyPath + "_" + String::number(index);

    BEGIN_BLOCK_OBJC_EXCEPTIONS

    CAKeyframeAnimation* keyframeAnim = [CAKeyframeAnimation animationWithKeyPath:keyPath];

    double duration = anim->duration();
    if (duration <= 0)
        duration = cAnimationAlmostZeroDuration;

    float repeatCount = anim->iterationCount();
    if (repeatCount == Animation::IterationCountInfinite)
        repeatCount = FLT_MAX;
    else if (anim->direction() == Animation::AnimationDirectionAlternate)
        repeatCount /= 2;

    [keyframeAnim setDuration:duration];
    [keyframeAnim setRepeatCount:repeatCount];
    [keyframeAnim setAutoreverses:anim->direction()];
    [keyframeAnim setRemovedOnCompletion:NO];

    // The first animation is non-additive, all the rest are additive.
    // Note that currently transform is the only property which has animations
    // with an index > 0.
    [keyframeAnim setAdditive:(property == AnimatedPropertyWebkitTransform) ? YES : NO];
    [keyframeAnim setFillMode:@"extended"];
#if HAVE_MODERN_QUARTZCORE
    if (NSString* valueFunctionName = getValueFunctionNameForTransformOperation(operationType))
        [keyframeAnim setValueFunction:[CAValueFunction functionWithName:valueFunctionName]];
#else
    UNUSED_PARAM(operationType);
#endif

    [keyframeAnim setKeyTimes:reinterpret_cast<id>(keys)];
    [keyframeAnim setValues:reinterpret_cast<id>(values)];
    
    // Set the delegate (and property value).
    int prop = isTransition ? property : AnimatedPropertyInvalid;
    [keyframeAnim setValue:[NSNumber numberWithInt: prop] forKey:WebAnimationCSSPropertyKey];
    [keyframeAnim setDelegate:m_animationDelegate.get()];

    NSTimeInterval bt = beginTime ? [layer convertTime:currentTimeToMediaTime(beginTime) fromLayer:nil] : 0;
    [keyframeAnim setBeginTime:bt];
    
    // Set the timing functions, if any.
    if (timingFunctions != nil)
        [keyframeAnim setTimingFunctions:(id)timingFunctions];
        
    // Send over the animation.
    [layer removeAnimationForKey:animName];
    [layer addAnimation:keyframeAnim forKey:animName];
        
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::suspendAnimations()
{
    double t = currentTimeToMediaTime(currentTime());
    [primaryLayer() setSpeed:0];
    [primaryLayer() setTimeOffset:t];
}

void GraphicsLayerCA::resumeAnimations()
{
    [primaryLayer() setSpeed:1];
    [primaryLayer() setTimeOffset:0];
}

void GraphicsLayerCA::removeAnimation(int index, bool reset)
{
    ASSERT(index >= 0);

    AnimatedPropertyID property = m_animations[index].property();
    
    // Set the value of the property and remove the animation.
    String keyPath = propertyIdToString(property);
    String animName = keyPath + "_" + String::number(m_animations[index].index());
    CALayer* layer = animatedLayer(property);

    BEGIN_BLOCK_OBJC_EXCEPTIONS

    // If we are not resetting, it means we are pausing. So we need to get the current presentation
    // value into the property before we remove the animation.
    if (!reset) {
        // Put the current value into the property.
        CALayer* presLayer = [layer presentationLayer];
        if (presLayer)
            [layer setValue:[presLayer valueForKeyPath:keyPath] forKeyPath:keyPath];

        // Make sure the saved values accurately reflect the value in the layer.
        id val = [layer valueForKeyPath:keyPath];
        switch (property) {
            case AnimatedPropertyWebkitTransform:
                // FIXME: needs comment explaining why the m_transform is not obtained from the layer
                break;
            case AnimatedPropertyBackgroundColor:
                m_backgroundColor = Color(reinterpret_cast<CGColorRef>(val));
                break;
            case AnimatedPropertyOpacity:
                m_opacity = [val floatValue];
                break;
            case AnimatedPropertyInvalid:
                ASSERT_NOT_REACHED();
                break;
        }
    }
    
    // If we have reached the end of an animation, we don't want to actually remove the 
    // animation from the CALayer. At some point we will be setting the property to its
    // unanimated value and at that point we will remove the animation. That will avoid
    // any flashing between the time the animation is removed and the property is set.
    if (!reset || m_animations[index].isTransition())
        [layer removeAnimationForKey:animName];

    END_BLOCK_OBJC_EXCEPTIONS

    // Remove the animation entry.
    m_animations.remove(index);
}

PlatformLayer* GraphicsLayerCA::hostLayerForSublayers() const
{
    return m_transformLayer ? m_transformLayer.get() : m_layer.get();
}

PlatformLayer* GraphicsLayerCA::layerForSuperlayer() const
{
    if (m_transformLayer)
        return m_transformLayer.get();

    return m_layer.get();
}

PlatformLayer* GraphicsLayerCA::platformLayer() const
{
    return primaryLayer();
}

#ifndef NDEBUG
void GraphicsLayerCA::setDebugBackgroundColor(const Color& color)
{
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    if (color.isValid())
        setLayerBackgroundColor(m_layer.get(), color);
    else
        clearLayerBackgroundColor(m_layer.get());
    
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setDebugBorder(const Color& color, float borderWidth)
{
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    if (color.isValid()) {
        setLayerBorderColor(m_layer.get(), color);
        [m_layer.get() setBorderWidth:borderWidth];
    } else {
        clearBorderColor(m_layer.get());
        [m_layer.get() setBorderWidth:0];
    }
    
    END_BLOCK_OBJC_EXCEPTIONS
}

void GraphicsLayerCA::setZPosition(float position)
{
    GraphicsLayer::setZPosition(position);
    
    BEGIN_BLOCK_OBJC_EXCEPTIONS
    [primaryLayer() setZPosition:position];
    END_BLOCK_OBJC_EXCEPTIONS
}
#endif

bool GraphicsLayerCA::requiresTiledLayer(const FloatSize& size) const
{
    if (!m_drawsContent)
        return false;

    // FIXME: catch zero-size height or width here (or earlier)?
    return size.width() > cMaxPixelDimension || size.height() > cMaxPixelDimension;
}

void GraphicsLayerCA::swapFromOrToTiledLayer(bool userTiledLayer)
{
    if (userTiledLayer == m_usingTiledLayer)
        return;

    CGSize tileSize = CGSizeMake(cTiledLayerTileSize, cTiledLayerTileSize);

    BEGIN_BLOCK_OBJC_EXCEPTIONS
    
    RetainPtr<CALayer> oldLayer = m_layer.get();
    
    Class layerClass = userTiledLayer ? [WebTiledLayer self] : [WebLayer self];
    m_layer.adoptNS([[layerClass alloc] init]);

    if (userTiledLayer) {
        WebTiledLayer* tiledLayer = (WebTiledLayer*)m_layer.get();
        [tiledLayer setTileSize:tileSize];
        [tiledLayer setLevelsOfDetail:1];
        [tiledLayer setLevelsOfDetailBias:0];

        if (GraphicsLayer::compositingCoordinatesOrientation() == GraphicsLayer::CompositingCoordinatesBottomUp)
            [tiledLayer setContentsGravity:@"bottomLeft"];
        else
            [tiledLayer setContentsGravity:@"topLeft"];
    }
    
    [m_layer.get() setLayerOwner:this];
    [m_layer.get() setSublayers:[oldLayer.get() sublayers]];
    
    [[oldLayer.get() superlayer] replaceSublayer:oldLayer.get() with:m_layer.get()];
    
    [m_layer.get() setBounds:[oldLayer.get() bounds]];
    [m_layer.get() setPosition:[oldLayer.get() position]];
    [m_layer.get() setAnchorPoint:[oldLayer.get() anchorPoint]];
    [m_layer.get() setOpaque:[oldLayer.get() isOpaque]];
    [m_layer.get() setOpacity:[oldLayer.get() opacity]];
    [m_layer.get() setTransform:[oldLayer.get() transform]];
    [m_layer.get() setSublayerTransform:[oldLayer.get() sublayerTransform]];
    [m_layer.get() setDoubleSided:[oldLayer.get() isDoubleSided]];
#ifndef NDEBUG
    [m_layer.get() setZPosition:[oldLayer.get() zPosition]];
#endif
    
#ifndef NDEBUG
    String name = String::format("CALayer(%p) GraphicsLayer(%p) ", m_layer.get(), this) + m_name;
    [m_layer.get() setName:name];
#endif

    // move over animations
    moveAnimation(AnimatedPropertyWebkitTransform, oldLayer.get(), m_layer.get());
    moveAnimation(AnimatedPropertyOpacity, oldLayer.get(), m_layer.get());
    moveAnimation(AnimatedPropertyBackgroundColor, oldLayer.get(), m_layer.get());
    
    // need to tell new layer to draw itself
    setNeedsDisplay();
    
    END_BLOCK_OBJC_EXCEPTIONS
    
    m_usingTiledLayer = userTiledLayer;
    
#ifndef NDEBUG
    updateDebugIndicators();
#endif
}

void GraphicsLayerCA::setContentsLayer(WebLayer* contentsLayer)
{
    if (contentsLayer == m_contentsLayer)
        return;

    BEGIN_BLOCK_OBJC_EXCEPTIONS

    if (m_contentsLayer) {
        [m_contentsLayer.get() removeFromSuperlayer];
        m_contentsLayer = 0;
    }
    
    if (contentsLayer) {
        // Turn off implicit animations on the inner layer.
        [contentsLayer setStyle:[NSDictionary dictionaryWithObject:nullActionsDictionary() forKey:@"actions"]];

        m_contentsLayer.adoptNS([contentsLayer retain]);

        bool needToFlip = GraphicsLayer::compositingCoordinatesOrientation() == GraphicsLayer::CompositingCoordinatesBottomUp;
        CGPoint anchorPoint = needToFlip ? CGPointMake(0.0f, 1.0f) : CGPointZero;

        // If the layer world is flipped, we need to un-flip the contents layer
        if (needToFlip) {
            CATransform3D flipper = {
                1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, -1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, 1.0f, 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f};
            [m_contentsLayer.get() setTransform:flipper];
        }
        [m_contentsLayer.get() setAnchorPoint:anchorPoint];

        // Insert the content layer first. Video elements require this, because they have
        // shadow content that must display in front of the video.
        [m_layer.get() insertSublayer:m_contentsLayer.get() atIndex:0];

        updateContentsRect();

#ifndef NDEBUG
        if (showDebugBorders()) {
            setLayerBorderColor(m_contentsLayer.get(), Color(0, 0, 128, 180));
            [m_contentsLayer.get() setBorderWidth:1.0f];
        }
#endif
    }
#ifndef NDEBUG
    updateDebugIndicators();
#endif

    END_BLOCK_OBJC_EXCEPTIONS
}

} // namespace WebCore


#endif // USE(ACCELERATED_COMPOSITING)