Remove an unnecessary local in GraphicsLayerCA::ensureStructuralLayer
[WebKit-https.git] / Source / WebCore / platform / graphics / ca / GraphicsLayerCA.cpp
1 /*
2  * Copyright (C) 2010 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27
28 #include "GraphicsLayerCA.h"
29
30 #include "Animation.h"
31 #include "FloatConversion.h"
32 #include "FloatRect.h"
33 #include "GraphicsLayerFactory.h"
34 #include "Image.h"
35 #include "PlatformCAFilters.h"
36 #include "PlatformCALayer.h"
37 #include "RotateTransformOperation.h"
38 #include "ScaleTransformOperation.h"
39 #include "TextStream.h"
40 #include "TiledBacking.h"
41 #include "TransformState.h"
42 #include "TranslateTransformOperation.h"
43 #include <QuartzCore/CATransform3D.h>
44 #include <limits.h>
45 #include <wtf/CurrentTime.h>
46 #include <wtf/TemporaryChange.h>
47 #include <wtf/text/WTFString.h>
48
49 #if PLATFORM(IOS)
50 #include "SystemMemory.h"
51 #include "WebCoreThread.h"
52 #endif
53
54 #if PLATFORM(COCOA)
55 #include "PlatformCAAnimationMac.h"
56 #include "PlatformCALayerMac.h"
57 #include "WebCoreSystemInterface.h"
58 #endif
59
60 #if PLATFORM(WIN)
61 #include "PlatformCAAnimationWin.h"
62 #include "PlatformCALayerWin.h"
63 #endif
64
65 namespace WebCore {
66
67 // The threshold width or height above which a tiled layer will be used. This should be
68 // large enough to avoid tiled layers for most GraphicsLayers, but less than the OpenGL
69 // texture size limit on all supported hardware.
70 #if PLATFORM(IOS)
71 static const int cMaxPixelDimension = 1280;
72 static const int cMaxPixelDimensionLowMemory = 1024;
73 static const int cMemoryLevelToUseSmallerPixelDimension = 35;
74 #else
75 static const int cMaxPixelDimension = 2000;
76 #endif
77
78 // Derived empirically: <rdar://problem/13401861>
79 static const int cMaxLayerTreeDepth = 250;
80
81 // If we send a duration of 0 to CA, then it will use the default duration
82 // of 250ms. So send a very small value instead.
83 static const float cAnimationAlmostZeroDuration = 1e-3f;
84
85 static inline bool isIntegral(float value)
86 {
87     return static_cast<int>(value) == value;
88 }
89
90 static bool isTransformTypeTransformationMatrix(TransformOperation::OperationType transformType)
91 {
92     switch (transformType) {
93     case TransformOperation::SKEW_X:
94     case TransformOperation::SKEW_Y:
95     case TransformOperation::SKEW:
96     case TransformOperation::MATRIX:
97     case TransformOperation::ROTATE_3D:
98     case TransformOperation::MATRIX_3D:
99     case TransformOperation::PERSPECTIVE:
100     case TransformOperation::IDENTITY:
101     case TransformOperation::NONE:
102         return true;
103     default:
104         return false;
105     }
106 }
107
108 static bool isTransformTypeFloatPoint3D(TransformOperation::OperationType transformType)
109 {
110     switch (transformType) {
111     case TransformOperation::SCALE:
112     case TransformOperation::SCALE_3D:
113     case TransformOperation::TRANSLATE:
114     case TransformOperation::TRANSLATE_3D:
115         return true;
116     default:
117         return false;
118     }
119 }
120
121 static bool isTransformTypeNumber(TransformOperation::OperationType transformType)
122 {
123     return !isTransformTypeTransformationMatrix(transformType) && !isTransformTypeFloatPoint3D(transformType);
124 }
125
126 static void getTransformFunctionValue(const TransformOperation* transformOp, TransformOperation::OperationType transformType, const FloatSize& size, float& value)
127 {
128     switch (transformType) {
129     case TransformOperation::ROTATE:
130     case TransformOperation::ROTATE_X:
131     case TransformOperation::ROTATE_Y:
132         value = transformOp ? narrowPrecisionToFloat(deg2rad(toRotateTransformOperation(transformOp)->angle())) : 0;
133         break;
134     case TransformOperation::SCALE_X:
135         value = transformOp ? narrowPrecisionToFloat(toScaleTransformOperation(transformOp)->x()) : 1;
136         break;
137     case TransformOperation::SCALE_Y:
138         value = transformOp ? narrowPrecisionToFloat(toScaleTransformOperation(transformOp)->y()) : 1;
139         break;
140     case TransformOperation::SCALE_Z:
141         value = transformOp ? narrowPrecisionToFloat(toScaleTransformOperation(transformOp)->z()) : 1;
142         break;
143     case TransformOperation::TRANSLATE_X:
144         value = transformOp ? narrowPrecisionToFloat(toTranslateTransformOperation(transformOp)->x(size)) : 0;
145         break;
146     case TransformOperation::TRANSLATE_Y:
147         value = transformOp ? narrowPrecisionToFloat(toTranslateTransformOperation(transformOp)->y(size)) : 0;
148         break;
149     case TransformOperation::TRANSLATE_Z:
150         value = transformOp ? narrowPrecisionToFloat(toTranslateTransformOperation(transformOp)->z(size)) : 0;
151         break;
152     default:
153         break;
154     }
155 }
156
157 static void getTransformFunctionValue(const TransformOperation* transformOp, TransformOperation::OperationType transformType, const FloatSize& size, FloatPoint3D& value)
158 {
159     switch (transformType) {
160     case TransformOperation::SCALE:
161     case TransformOperation::SCALE_3D: {
162         const ScaleTransformOperation* scaleTransformOp = toScaleTransformOperation(transformOp);
163         value.setX(scaleTransformOp ? narrowPrecisionToFloat(scaleTransformOp->x()) : 1);
164         value.setY(scaleTransformOp ? narrowPrecisionToFloat(scaleTransformOp->y()) : 1);
165         value.setZ(scaleTransformOp ? narrowPrecisionToFloat(scaleTransformOp->z()) : 1);
166         break;
167     }
168     case TransformOperation::TRANSLATE:
169     case TransformOperation::TRANSLATE_3D: {
170         const TranslateTransformOperation* translateTransformOp = toTranslateTransformOperation(transformOp);
171         value.setX(translateTransformOp ? narrowPrecisionToFloat(translateTransformOp->x(size)) : 0);
172         value.setY(translateTransformOp ? narrowPrecisionToFloat(translateTransformOp->y(size)) : 0);
173         value.setZ(translateTransformOp ? narrowPrecisionToFloat(translateTransformOp->z(size)) : 0);
174         break;
175     }
176     default:
177         break;
178     }
179 }
180
181 static void getTransformFunctionValue(const TransformOperation* transformOp, TransformOperation::OperationType transformType, const FloatSize& size, TransformationMatrix& value)
182 {
183     switch (transformType) {
184     case TransformOperation::SKEW_X:
185     case TransformOperation::SKEW_Y:
186     case TransformOperation::SKEW:
187     case TransformOperation::MATRIX:
188     case TransformOperation::ROTATE_3D:
189     case TransformOperation::MATRIX_3D:
190     case TransformOperation::PERSPECTIVE:
191     case TransformOperation::IDENTITY:
192     case TransformOperation::NONE:
193         if (transformOp)
194             transformOp->apply(value, size);
195         else
196             value.makeIdentity();
197         break;
198     default:
199         break;
200     }
201 }
202
203 static PlatformCAAnimation::ValueFunctionType getValueFunctionNameForTransformOperation(TransformOperation::OperationType transformType)
204 {
205     // Use literal strings to avoid link-time dependency on those symbols.
206     switch (transformType) {
207     case TransformOperation::ROTATE_X:
208         return PlatformCAAnimation::RotateX;
209     case TransformOperation::ROTATE_Y:
210         return PlatformCAAnimation::RotateY;
211     case TransformOperation::ROTATE:
212         return PlatformCAAnimation::RotateZ;
213     case TransformOperation::SCALE_X:
214         return PlatformCAAnimation::ScaleX;
215     case TransformOperation::SCALE_Y:
216         return PlatformCAAnimation::ScaleY;
217     case TransformOperation::SCALE_Z:
218         return PlatformCAAnimation::ScaleZ;
219     case TransformOperation::TRANSLATE_X:
220         return PlatformCAAnimation::TranslateX;
221     case TransformOperation::TRANSLATE_Y:
222         return PlatformCAAnimation::TranslateY;
223     case TransformOperation::TRANSLATE_Z:
224         return PlatformCAAnimation::TranslateZ;
225     case TransformOperation::SCALE:
226     case TransformOperation::SCALE_3D:
227         return PlatformCAAnimation::Scale;
228     case TransformOperation::TRANSLATE:
229     case TransformOperation::TRANSLATE_3D:
230         return PlatformCAAnimation::Translate;
231     default:
232         return PlatformCAAnimation::NoValueFunction;
233     }
234 }
235
236 static String propertyIdToString(AnimatedPropertyID property)
237 {
238     switch (property) {
239     case AnimatedPropertyWebkitTransform:
240         return "transform";
241     case AnimatedPropertyOpacity:
242         return "opacity";
243     case AnimatedPropertyBackgroundColor:
244         return "backgroundColor";
245     case AnimatedPropertyWebkitFilter:
246 #if ENABLE(CSS_FILTERS)
247         return "filters";
248 #else
249         ASSERT_NOT_REACHED();
250 #endif
251     case AnimatedPropertyInvalid:
252         ASSERT_NOT_REACHED();
253     }
254     ASSERT_NOT_REACHED();
255     return "";
256 }
257
258 static String animationIdentifier(const String& animationName, AnimatedPropertyID property, int index, int subIndex)
259 {
260     return animationName + '_' + String::number(property) + '_' + String::number(index) + '_' + String::number(subIndex);
261 }
262
263 static bool animationHasStepsTimingFunction(const KeyframeValueList& valueList, const Animation* anim)
264 {
265     if (anim->timingFunction()->isStepsTimingFunction())
266         return true;
267     
268     for (unsigned i = 0; i < valueList.size(); ++i) {
269         if (const TimingFunction* timingFunction = valueList.at(i).timingFunction()) {
270             if (timingFunction->isStepsTimingFunction())
271                 return true;
272         }
273     }
274
275     return false;
276 }
277
278 #if ENABLE(CSS_FILTERS) || !ASSERT_DISABLED
279 static inline bool supportsAcceleratedFilterAnimations()
280 {
281 // <rdar://problem/10907251> - WebKit2 doesn't support CA animations of CI filters on Lion and below
282 #if PLATFORM(IOS) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
283     return true;
284 #else
285     return false;
286 #endif
287 }
288 #endif
289
290 std::unique_ptr<GraphicsLayer> GraphicsLayer::create(GraphicsLayerFactory* factory, GraphicsLayerClient& client)
291 {
292     std::unique_ptr<GraphicsLayer> graphicsLayer;
293     if (!factory)
294         graphicsLayer = std::make_unique<GraphicsLayerCA>(client);
295     else
296         graphicsLayer = factory->createGraphicsLayer(client);
297
298     graphicsLayer->initialize();
299
300     return graphicsLayer;
301 }
302
303 #if ENABLE(CSS_FILTERS)
304 bool GraphicsLayerCA::filtersCanBeComposited(const FilterOperations& filters)
305 {
306 #if PLATFORM(COCOA)
307     return PlatformCALayerMac::filtersCanBeComposited(filters);
308 #elif PLATFORM(WIN)
309     return PlatformCALayerWin::filtersCanBeComposited(filters);
310 #endif
311 }
312 #endif
313     
314 PassRefPtr<PlatformCALayer> GraphicsLayerCA::createPlatformCALayer(PlatformCALayer::LayerType layerType, PlatformCALayerClient* owner)
315 {
316 #if PLATFORM(COCOA)
317     return PlatformCALayerMac::create(layerType, owner);
318 #elif PLATFORM(WIN)
319     return PlatformCALayerWin::create(layerType, owner);
320 #endif
321 }
322     
323 PassRefPtr<PlatformCALayer> GraphicsLayerCA::createPlatformCALayer(PlatformLayer* platformLayer, PlatformCALayerClient* owner)
324 {
325 #if PLATFORM(COCOA)
326     return PlatformCALayerMac::create(platformLayer, owner);
327 #elif PLATFORM(WIN)
328     return PlatformCALayerWin::create(platformLayer, owner);
329 #endif
330 }
331
332 PassRefPtr<PlatformCAAnimation> GraphicsLayerCA::createPlatformCAAnimation(PlatformCAAnimation::AnimationType type, const String& keyPath)
333 {
334 #if PLATFORM(COCOA)
335     return PlatformCAAnimationMac::create(type, keyPath);
336 #elif PLATFORM(WIN)
337     return PlatformCAAnimationWin::create(type, keyPath);
338 #endif
339 }
340
341 GraphicsLayerCA::GraphicsLayerCA(GraphicsLayerClient& client)
342     : GraphicsLayer(client)
343     , m_contentsLayerPurpose(NoContentsLayer)
344     , m_isPageTiledBackingLayer(false)
345     , m_needsFullRepaint(false)
346     , m_uncommittedChanges(0)
347     , m_isCommittingChanges(false)
348 {
349 }
350
351 void GraphicsLayerCA::initialize()
352 {
353     PlatformCALayer::LayerType layerType = PlatformCALayer::LayerTypeWebLayer;
354     if (client().shouldUseTiledBacking(this)) {
355         layerType = PlatformCALayer::LayerTypePageTiledBackingLayer;
356         m_isPageTiledBackingLayer = true;
357     }
358
359     m_layer = createPlatformCALayer(layerType, this);
360     noteLayerPropertyChanged(ContentsScaleChanged);
361 }
362
363 GraphicsLayerCA::~GraphicsLayerCA()
364 {
365     // Do cleanup while we can still safely call methods on the derived class.
366     willBeDestroyed();
367 }
368
369 void GraphicsLayerCA::willBeDestroyed()
370 {
371     // We release our references to the PlatformCALayers here, but do not actively unparent them,
372     // since that will cause a commit and break our batched commit model. The layers will
373     // get released when the rootmost modified GraphicsLayerCA rebuilds its child layers.
374
375     // Clean up the layer.
376     if (m_layer)
377         m_layer->setOwner(nullptr);
378     
379     if (m_contentsLayer)
380         m_contentsLayer->setOwner(nullptr);
381
382     if (m_contentsClippingLayer)
383         m_contentsClippingLayer->setOwner(nullptr);
384         
385     if (m_structuralLayer)
386         m_structuralLayer->setOwner(nullptr);
387     
388     removeCloneLayers();
389
390     GraphicsLayer::willBeDestroyed();
391 }
392
393 void GraphicsLayerCA::setName(const String& name)
394 {
395     String caLayerDescription;
396
397     if (!m_layer->isPlatformCALayerRemote())
398         caLayerDescription = String::format("CALayer(%p) ", m_layer->platformLayer());
399
400     String longName = caLayerDescription + String::format("GraphicsLayer(%p) ", this) + name;
401     GraphicsLayer::setName(longName);
402     noteLayerPropertyChanged(NameChanged);
403 }
404
405 GraphicsLayer::PlatformLayerID GraphicsLayerCA::primaryLayerID() const
406 {
407     return primaryLayer()->layerID();
408 }
409
410 PlatformLayer* GraphicsLayerCA::platformLayer() const
411 {
412     return primaryLayer()->platformLayer();
413 }
414
415 bool GraphicsLayerCA::setChildren(const Vector<GraphicsLayer*>& children)
416 {
417     bool childrenChanged = GraphicsLayer::setChildren(children);
418     if (childrenChanged)
419         noteSublayersChanged();
420     
421     return childrenChanged;
422 }
423
424 void GraphicsLayerCA::addChild(GraphicsLayer* childLayer)
425 {
426     GraphicsLayer::addChild(childLayer);
427     noteSublayersChanged();
428 }
429
430 void GraphicsLayerCA::addChildAtIndex(GraphicsLayer* childLayer, int index)
431 {
432     GraphicsLayer::addChildAtIndex(childLayer, index);
433     noteSublayersChanged();
434 }
435
436 void GraphicsLayerCA::addChildBelow(GraphicsLayer* childLayer, GraphicsLayer* sibling)
437 {
438     GraphicsLayer::addChildBelow(childLayer, sibling);
439     noteSublayersChanged();
440 }
441
442 void GraphicsLayerCA::addChildAbove(GraphicsLayer* childLayer, GraphicsLayer* sibling)
443 {
444     GraphicsLayer::addChildAbove(childLayer, sibling);
445     noteSublayersChanged();
446 }
447
448 bool GraphicsLayerCA::replaceChild(GraphicsLayer* oldChild, GraphicsLayer* newChild)
449 {
450     if (GraphicsLayer::replaceChild(oldChild, newChild)) {
451         noteSublayersChanged();
452         return true;
453     }
454     return false;
455 }
456
457 void GraphicsLayerCA::removeFromParent()
458 {
459     if (m_parent)
460         toGraphicsLayerCA(m_parent)->noteSublayersChanged();
461     GraphicsLayer::removeFromParent();
462 }
463
464 void GraphicsLayerCA::setMaskLayer(GraphicsLayer* layer)
465 {
466     if (layer == m_maskLayer)
467         return;
468
469     GraphicsLayer::setMaskLayer(layer);
470     noteLayerPropertyChanged(MaskLayerChanged);
471
472     propagateLayerChangeToReplicas();
473     
474     if (m_replicatedLayer)
475         toGraphicsLayerCA(m_replicatedLayer)->propagateLayerChangeToReplicas();
476 }
477
478 void GraphicsLayerCA::setReplicatedLayer(GraphicsLayer* layer)
479 {
480     if (layer == m_replicatedLayer)
481         return;
482
483     GraphicsLayer::setReplicatedLayer(layer);
484     noteLayerPropertyChanged(ReplicatedLayerChanged);
485 }
486
487 void GraphicsLayerCA::setReplicatedByLayer(GraphicsLayer* layer)
488 {
489     if (layer == m_replicaLayer)
490         return;
491
492     GraphicsLayer::setReplicatedByLayer(layer);
493     noteSublayersChanged();
494     noteLayerPropertyChanged(ReplicatedLayerChanged);
495 }
496
497 void GraphicsLayerCA::setPosition(const FloatPoint& point)
498 {
499     if (point == m_position)
500         return;
501
502     GraphicsLayer::setPosition(point);
503     noteLayerPropertyChanged(GeometryChanged);
504 }
505
506 void GraphicsLayerCA::setAnchorPoint(const FloatPoint3D& point)
507 {
508     if (point == m_anchorPoint)
509         return;
510
511     GraphicsLayer::setAnchorPoint(point);
512     noteLayerPropertyChanged(GeometryChanged);
513 }
514
515 void GraphicsLayerCA::setSize(const FloatSize& size)
516 {
517     if (size == m_size)
518         return;
519
520     GraphicsLayer::setSize(size);
521     noteLayerPropertyChanged(GeometryChanged);
522 }
523
524 void GraphicsLayerCA::setBoundsOrigin(const FloatPoint& origin)
525 {
526     if (origin == m_boundsOrigin)
527         return;
528
529     GraphicsLayer::setBoundsOrigin(origin);
530     noteLayerPropertyChanged(GeometryChanged);
531 }
532
533 void GraphicsLayerCA::setTransform(const TransformationMatrix& t)
534 {
535     if (t == m_transform)
536         return;
537
538     GraphicsLayer::setTransform(t);
539     noteLayerPropertyChanged(TransformChanged);
540 }
541
542 void GraphicsLayerCA::setChildrenTransform(const TransformationMatrix& t)
543 {
544     if (t == m_childrenTransform)
545         return;
546
547     GraphicsLayer::setChildrenTransform(t);
548     noteLayerPropertyChanged(ChildrenTransformChanged);
549 }
550
551 void GraphicsLayerCA::moveOrCopyLayerAnimation(MoveOrCopy operation, const String& animationIdentifier, PlatformCALayer *fromLayer, PlatformCALayer *toLayer)
552 {
553     RefPtr<PlatformCAAnimation> anim = fromLayer->animationForKey(animationIdentifier);
554     if (!anim)
555         return;
556
557     switch (operation) {
558     case Move:
559         fromLayer->removeAnimationForKey(animationIdentifier);
560         toLayer->addAnimationForKey(animationIdentifier, anim.get());
561         break;
562
563     case Copy:
564         toLayer->addAnimationForKey(animationIdentifier, anim.get());
565         break;
566     }
567 }
568
569 void GraphicsLayerCA::moveOrCopyAnimations(MoveOrCopy operation, PlatformCALayer *fromLayer, PlatformCALayer *toLayer)
570 {
571     // Look for running animations affecting this property.
572     AnimationsMap::const_iterator end = m_runningAnimations.end();
573     for (AnimationsMap::const_iterator it = m_runningAnimations.begin(); it != end; ++it) {
574         const Vector<LayerPropertyAnimation>& propertyAnimations = it->value;
575         size_t numAnimations = propertyAnimations.size();
576         for (size_t i = 0; i < numAnimations; ++i) {
577             const LayerPropertyAnimation& currAnimation = propertyAnimations[i];
578             
579             if (currAnimation.m_property == AnimatedPropertyWebkitTransform || currAnimation.m_property == AnimatedPropertyOpacity
580                     || currAnimation.m_property == AnimatedPropertyBackgroundColor
581 #if ENABLE(CSS_FILTERS)
582                     || currAnimation.m_property == AnimatedPropertyWebkitFilter
583 #endif
584                 )
585                 moveOrCopyLayerAnimation(operation, animationIdentifier(currAnimation.m_name, currAnimation.m_property, currAnimation.m_index, currAnimation.m_subIndex), fromLayer, toLayer);
586         }
587     }
588 }
589
590 void GraphicsLayerCA::setPreserves3D(bool preserves3D)
591 {
592     if (preserves3D == m_preserves3D)
593         return;
594
595     GraphicsLayer::setPreserves3D(preserves3D);
596     noteLayerPropertyChanged(Preserves3DChanged);
597 }
598
599 void GraphicsLayerCA::setMasksToBounds(bool masksToBounds)
600 {
601     if (masksToBounds == m_masksToBounds)
602         return;
603
604     GraphicsLayer::setMasksToBounds(masksToBounds);
605     noteLayerPropertyChanged(MasksToBoundsChanged | DebugIndicatorsChanged);
606 }
607
608 void GraphicsLayerCA::setDrawsContent(bool drawsContent)
609 {
610     if (drawsContent == m_drawsContent)
611         return;
612
613     GraphicsLayer::setDrawsContent(drawsContent);
614     noteLayerPropertyChanged(DrawsContentChanged | DebugIndicatorsChanged);
615 }
616
617 void GraphicsLayerCA::setContentsVisible(bool contentsVisible)
618 {
619     if (contentsVisible == m_contentsVisible)
620         return;
621
622     GraphicsLayer::setContentsVisible(contentsVisible);
623     noteLayerPropertyChanged(ContentsVisibilityChanged);
624     // Visibility affects whether the contentsLayer is parented.
625     if (m_contentsLayer)
626         noteSublayersChanged();
627 }
628
629 void GraphicsLayerCA::setAcceleratesDrawing(bool acceleratesDrawing)
630 {
631     if (acceleratesDrawing == m_acceleratesDrawing)
632         return;
633
634     GraphicsLayer::setAcceleratesDrawing(acceleratesDrawing);
635     noteLayerPropertyChanged(AcceleratesDrawingChanged);
636 }
637
638 void GraphicsLayerCA::setBackgroundColor(const Color& color)
639 {
640     if (m_backgroundColor == color)
641         return;
642
643     GraphicsLayer::setBackgroundColor(color);
644     noteLayerPropertyChanged(BackgroundColorChanged);
645 }
646
647 void GraphicsLayerCA::setContentsOpaque(bool opaque)
648 {
649     if (m_contentsOpaque == opaque)
650         return;
651
652     GraphicsLayer::setContentsOpaque(opaque);
653     noteLayerPropertyChanged(ContentsOpaqueChanged);
654 }
655
656 void GraphicsLayerCA::setBackfaceVisibility(bool visible)
657 {
658     if (m_backfaceVisibility == visible)
659         return;
660     
661     GraphicsLayer::setBackfaceVisibility(visible);
662     noteLayerPropertyChanged(BackfaceVisibilityChanged);
663 }
664
665 void GraphicsLayerCA::setOpacity(float opacity)
666 {
667     float clampedOpacity = std::max(0.0f, std::min(opacity, 1.0f));
668
669     if (clampedOpacity == m_opacity)
670         return;
671
672     GraphicsLayer::setOpacity(clampedOpacity);
673     noteLayerPropertyChanged(OpacityChanged);
674 }
675
676 #if ENABLE(CSS_FILTERS)
677 bool GraphicsLayerCA::setFilters(const FilterOperations& filterOperations)
678 {
679     bool canCompositeFilters = filtersCanBeComposited(filterOperations);
680
681     if (m_filters == filterOperations)
682         return canCompositeFilters;
683
684     // Filters cause flattening, so we should never have filters on a layer with preserves3D().
685     ASSERT(!filterOperations.size() || !preserves3D());
686
687     if (canCompositeFilters) {
688         GraphicsLayer::setFilters(filterOperations);
689         noteLayerPropertyChanged(FiltersChanged);
690     } else if (filters().size()) {
691         // In this case filters are rendered in software, so we need to remove any 
692         // previously attached hardware filters.
693         clearFilters();
694         noteLayerPropertyChanged(FiltersChanged);
695     }
696     return canCompositeFilters;
697 }
698 #endif
699
700 #if ENABLE(CSS_COMPOSITING)
701 void GraphicsLayerCA::setBlendMode(BlendMode blendMode)
702 {
703     if (GraphicsLayer::blendMode() == blendMode)
704         return;
705
706     GraphicsLayer::setBlendMode(blendMode);
707     noteLayerPropertyChanged(BlendModeChanged);
708 }
709 #endif
710
711 void GraphicsLayerCA::setNeedsDisplay()
712 {
713     if (!drawsContent())
714         return;
715
716     m_needsFullRepaint = true;
717     m_dirtyRects.clear();
718     noteLayerPropertyChanged(DirtyRectsChanged);
719     addRepaintRect(FloatRect(FloatPoint(), m_size));
720 }
721
722 void GraphicsLayerCA::setNeedsDisplayInRect(const FloatRect& r, ShouldClipToLayer shouldClip)
723 {
724     if (!drawsContent())
725         return;
726
727     if (m_needsFullRepaint)
728         return;
729
730     FloatRect rect(r);
731     if (shouldClip == ClipToLayer) {
732         FloatRect layerBounds(FloatPoint(), m_size);
733         rect.intersect(layerBounds);
734     }
735
736     if (rect.isEmpty())
737         return;
738     
739     const size_t maxDirtyRects = 32;
740     
741     for (size_t i = 0; i < m_dirtyRects.size(); ++i) {
742         if (m_dirtyRects[i].contains(rect))
743             return;
744     }
745     
746     if (m_dirtyRects.size() < maxDirtyRects)
747         m_dirtyRects.append(rect);
748     else
749         m_dirtyRects[0].unite(rect);
750
751     noteLayerPropertyChanged(DirtyRectsChanged);
752
753     addRepaintRect(rect);
754 }
755
756 void GraphicsLayerCA::setContentsNeedsDisplay()
757 {
758     noteLayerPropertyChanged(ContentsNeedsDisplay);
759 }
760
761 void GraphicsLayerCA::setContentsRect(const FloatRect& rect)
762 {
763     if (rect == m_contentsRect)
764         return;
765
766     GraphicsLayer::setContentsRect(rect);
767     noteLayerPropertyChanged(ContentsRectsChanged);
768 }
769
770 void GraphicsLayerCA::setContentsClippingRect(const FloatRect& rect)
771 {
772     if (rect == m_contentsClippingRect)
773         return;
774
775     GraphicsLayer::setContentsClippingRect(rect);
776     noteLayerPropertyChanged(ContentsRectsChanged);
777 }
778
779 bool GraphicsLayerCA::shouldRepaintOnSizeChange() const
780 {
781     return drawsContent() && !tiledBacking();
782 }
783
784 bool GraphicsLayerCA::animationCanBeAccelerated(const KeyframeValueList& valueList, const Animation* anim) const
785 {
786     if (!anim || anim->isEmptyOrZeroDuration() || valueList.size() < 2)
787         return false;
788
789     if (animationHasStepsTimingFunction(valueList, anim))
790         return false;
791
792     return true;
793 }
794
795 bool GraphicsLayerCA::addAnimation(const KeyframeValueList& valueList, const FloatSize& boxSize, const Animation* anim, const String& animationName, double timeOffset)
796 {
797     ASSERT(!animationName.isEmpty());
798
799     if (!animationCanBeAccelerated(valueList, anim))
800         return false;
801
802     bool createdAnimations = false;
803     if (valueList.property() == AnimatedPropertyWebkitTransform)
804         createdAnimations = createTransformAnimationsFromKeyframes(valueList, anim, animationName, timeOffset, boxSize);
805 #if ENABLE(CSS_FILTERS)
806     else if (valueList.property() == AnimatedPropertyWebkitFilter) {
807         if (supportsAcceleratedFilterAnimations())
808             createdAnimations = createFilterAnimationsFromKeyframes(valueList, anim, animationName, timeOffset);
809     }
810 #endif
811     else
812         createdAnimations = createAnimationFromKeyframes(valueList, anim, animationName, timeOffset);
813
814     if (createdAnimations)
815         noteLayerPropertyChanged(AnimationChanged);
816         
817     return createdAnimations;
818 }
819
820 void GraphicsLayerCA::pauseAnimation(const String& animationName, double timeOffset)
821 {
822     if (!animationIsRunning(animationName))
823         return;
824
825     AnimationsToProcessMap::iterator it = m_animationsToProcess.find(animationName);
826     if (it != m_animationsToProcess.end()) {
827         AnimationProcessingAction& processingInfo = it->value;
828         // If an animation is scheduled to be removed, don't change the remove to a pause.
829         if (processingInfo.action != Remove)
830             processingInfo.action = Pause;
831     } else
832         m_animationsToProcess.add(animationName, AnimationProcessingAction(Pause, timeOffset));
833
834     noteLayerPropertyChanged(AnimationChanged);
835 }
836
837 void GraphicsLayerCA::removeAnimation(const String& animationName)
838 {
839     if (!animationIsRunning(animationName))
840         return;
841
842     m_animationsToProcess.add(animationName, AnimationProcessingAction(Remove));
843     noteLayerPropertyChanged(AnimationChanged);
844 }
845
846 void GraphicsLayerCA::platformCALayerAnimationStarted(const String& animationKey, CFTimeInterval startTime)
847 {
848     client().notifyAnimationStarted(this, animationKey, startTime);
849 }
850
851 void GraphicsLayerCA::platformCALayerAnimationEnded(const String& animationKey)
852 {
853     client().notifyAnimationEnded(this, animationKey);
854 }
855
856 void GraphicsLayerCA::setContentsToSolidColor(const Color& color)
857 {
858     if (color == m_contentsSolidColor)
859         return;
860
861     m_contentsSolidColor = color;
862     
863     bool contentsLayerChanged = false;
864
865     if (m_contentsSolidColor.isValid() && m_contentsSolidColor.alpha()) {
866         if (!m_contentsLayer || m_contentsLayerPurpose != ContentsLayerForBackgroundColor) {
867             m_contentsLayerPurpose = ContentsLayerForBackgroundColor;
868             m_contentsLayer = createPlatformCALayer(PlatformCALayer::LayerTypeLayer, this);
869 #ifndef NDEBUG
870             m_contentsLayer->setName("Background Color Layer");
871 #endif
872             contentsLayerChanged = true;
873         }
874     } else {
875         contentsLayerChanged = m_contentsLayer;
876         m_contentsLayerPurpose = NoContentsLayer;
877         m_contentsLayer = 0;
878     }
879
880     if (contentsLayerChanged)
881         noteSublayersChanged();
882
883     noteLayerPropertyChanged(ContentsColorLayerChanged);
884 }
885
886 void GraphicsLayerCA::setContentsToImage(Image* image)
887 {
888     if (image) {
889         CGImageRef newImage = image->nativeImageForCurrentFrame();
890         if (!newImage)
891             return;
892
893         // Check to see if the image changed; we have to do this because the call to
894         // CGImageCreateCopyWithColorSpace() below can create a new image every time.
895         if (m_uncorrectedContentsImage && m_uncorrectedContentsImage.get() == newImage)
896             return;
897         
898         m_uncorrectedContentsImage = newImage;
899         m_pendingContentsImage = newImage;
900
901 #if !PLATFORM(WIN) && !PLATFORM(IOS)
902         CGColorSpaceRef colorSpace = CGImageGetColorSpace(m_pendingContentsImage.get());
903
904         static CGColorSpaceRef deviceRGB = CGColorSpaceCreateDeviceRGB();
905         if (colorSpace && CFEqual(colorSpace, deviceRGB)) {
906             // CoreGraphics renders images tagged with DeviceRGB using the color space of the main display. When we hand such
907             // images to CA we need to tag them similarly so CA rendering matches CG rendering.
908             static CGColorSpaceRef genericRGB = CGDisplayCopyColorSpace(kCGDirectMainDisplay);
909             m_pendingContentsImage = adoptCF(CGImageCreateCopyWithColorSpace(m_pendingContentsImage.get(), genericRGB));
910         }
911 #endif
912         m_contentsLayerPurpose = ContentsLayerForImage;
913         if (!m_contentsLayer)
914             noteSublayersChanged();
915     } else {
916         m_uncorrectedContentsImage = 0;
917         m_pendingContentsImage = 0;
918         m_contentsLayerPurpose = NoContentsLayer;
919         if (m_contentsLayer)
920             noteSublayersChanged();
921     }
922
923     noteLayerPropertyChanged(ContentsImageChanged);
924 }
925
926 void GraphicsLayerCA::setContentsToPlatformLayer(PlatformLayer* platformLayer, ContentsLayerPurpose purpose)
927 {
928     if (m_contentsLayer && platformLayer == m_contentsLayer->platformLayer())
929         return;
930
931     // FIXME: The passed in layer might be a raw layer or an externally created
932     // PlatformCALayer. To determine this we attempt to get the
933     // PlatformCALayer pointer. If this returns a null pointer we assume it's
934     // raw. This test might be invalid if the raw layer is, for instance, the
935     // PlatformCALayer is using a user data pointer in the raw layer, and
936     // the creator of the raw layer is using it for some other purpose.
937     // For now we don't support such a case.
938     PlatformCALayer* platformCALayer = PlatformCALayer::platformCALayer(platformLayer);
939     m_contentsLayer = platformLayer ? (platformCALayer ? platformCALayer : createPlatformCALayer(platformLayer, this)) : 0;
940     m_contentsLayerPurpose = platformLayer ? purpose : NoContentsLayer;
941
942     noteSublayersChanged();
943     noteLayerPropertyChanged(ContentsPlatformLayerChanged);
944 }
945
946 #if PLATFORM(IOS)
947 PlatformLayer* GraphicsLayerCA::contentsLayerForMedia() const
948 {
949     return m_contentsLayerPurpose == ContentsLayerForMedia ? m_contentsLayer->platformLayer() : nullptr;
950 }
951 #endif
952
953 void GraphicsLayerCA::layerDidDisplay(PlatformCALayer* layer)
954 {
955     LayerMap* layerCloneMap;
956
957     if (layer == m_layer)
958         layerCloneMap = m_layerClones.get();
959     else if (layer == m_contentsLayer)
960         layerCloneMap = m_contentsLayerClones.get();
961     else
962         return;
963
964     if (layerCloneMap) {
965         LayerMap::const_iterator end = layerCloneMap->end();
966         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
967             PlatformCALayer* currClone = it->value.get();
968             if (!currClone)
969                 continue;
970
971             currClone->copyContentsFromLayer(layer);
972         }
973     }
974 }
975
976 FloatPoint GraphicsLayerCA::computePositionRelativeToBase(float& pageScale) const
977 {
978     pageScale = 1;
979
980     FloatPoint offset;
981     for (const GraphicsLayer* currLayer = this; currLayer; currLayer = currLayer->parent()) {
982         if (currLayer->appliesPageScale()) {
983             pageScale = currLayer->pageScaleFactor();
984             return offset;
985         }
986
987         offset += currLayer->position();
988     }
989
990     return FloatPoint();
991 }
992
993 void GraphicsLayerCA::flushCompositingState(const FloatRect& clipRect)
994 {
995     TransformState state(TransformState::UnapplyInverseTransformDirection, FloatQuad(clipRect));
996     recursiveCommitChanges(CommitState(), state);
997 }
998
999 void GraphicsLayerCA::flushCompositingStateForThisLayerOnly()
1000 {
1001     float pageScaleFactor;
1002     bool hadChanges = m_uncommittedChanges;
1003     
1004     CommitState commitState;
1005
1006     FloatPoint offset = computePositionRelativeToBase(pageScaleFactor);
1007     commitLayerChangesBeforeSublayers(commitState, pageScaleFactor, offset, m_visibleRect);
1008     commitLayerChangesAfterSublayers(commitState);
1009
1010     if (hadChanges)
1011         client().didCommitChangesForLayer(this);
1012 }
1013
1014 bool GraphicsLayerCA::recursiveVisibleRectChangeRequiresFlush(const TransformState& state) const
1015 {
1016     TransformState localState = state;
1017     
1018     // This may be called at times when layout has not been updated, so we want to avoid calling out to the client
1019     // for animating transforms.
1020     FloatRect newVisibleRect = computeVisibleRect(localState, 0);
1021     if (m_layer->layerType() == PlatformCALayer::LayerTypeTiledBackingLayer)
1022         newVisibleRect = adjustTiledLayerVisibleRect(tiledBacking(), m_visibleRect, newVisibleRect, m_sizeAtLastVisibleRectUpdate, m_size);
1023
1024     if (newVisibleRect != m_visibleRect) {
1025         if (TiledBacking* tiledBacking = this->tiledBacking()) {
1026             if (tiledBacking->tilesWouldChangeForVisibleRect(newVisibleRect))
1027                 return true;
1028         }
1029     }
1030
1031     if (m_maskLayer) {
1032         GraphicsLayerCA* maskLayerCA = toGraphicsLayerCA(m_maskLayer);
1033         if (maskLayerCA->recursiveVisibleRectChangeRequiresFlush(localState))
1034             return true;
1035     }
1036
1037     const Vector<GraphicsLayer*>& childLayers = children();
1038     size_t numChildren = childLayers.size();
1039     
1040     for (size_t i = 0; i < numChildren; ++i) {
1041         GraphicsLayerCA* curChild = toGraphicsLayerCA(childLayers[i]);
1042         if (curChild->recursiveVisibleRectChangeRequiresFlush(localState))
1043             return true;
1044     }
1045
1046     if (m_replicaLayer)
1047         if (toGraphicsLayerCA(m_replicaLayer)->recursiveVisibleRectChangeRequiresFlush(localState))
1048             return true;
1049     
1050     return false;
1051 }
1052
1053 bool GraphicsLayerCA::visibleRectChangeRequiresFlush(const FloatRect& clipRect) const
1054 {
1055     TransformState state(TransformState::UnapplyInverseTransformDirection, FloatQuad(clipRect));
1056     return recursiveVisibleRectChangeRequiresFlush(state);
1057 }
1058
1059 TiledBacking* GraphicsLayerCA::tiledBacking() const
1060 {
1061     return m_layer->tiledBacking();
1062 }
1063
1064 TransformationMatrix GraphicsLayerCA::layerTransform(const FloatPoint& position, const TransformationMatrix* customTransform) const
1065 {
1066     TransformationMatrix transform;
1067     transform.translate(position.x(), position.y());
1068
1069     TransformationMatrix currentTransform = customTransform ? *customTransform : m_transform;
1070     
1071     if (!currentTransform.isIdentity()) {
1072         FloatPoint3D absoluteAnchorPoint(anchorPoint());
1073         absoluteAnchorPoint.scale(size().width(), size().height(), 1);
1074         transform.translate3d(absoluteAnchorPoint.x(), absoluteAnchorPoint.y(), absoluteAnchorPoint.z());
1075         transform.multiply(currentTransform);
1076         transform.translate3d(-absoluteAnchorPoint.x(), -absoluteAnchorPoint.y(), -absoluteAnchorPoint.z());
1077     }
1078
1079     if (GraphicsLayer* parentLayer = parent()) {
1080         if (!parentLayer->childrenTransform().isIdentity()) {
1081             FloatPoint3D parentAnchorPoint(parentLayer->anchorPoint());
1082             parentAnchorPoint.scale(parentLayer->size().width(), parentLayer->size().height(), 1);
1083
1084             transform.translateRight3d(-parentAnchorPoint.x(), -parentAnchorPoint.y(), -parentAnchorPoint.z());
1085             transform = parentLayer->childrenTransform() * transform;
1086             transform.translateRight3d(parentAnchorPoint.x(), parentAnchorPoint.y(), parentAnchorPoint.z());
1087         }
1088     }
1089     
1090     return transform;
1091 }
1092
1093 FloatRect GraphicsLayerCA::computeVisibleRect(TransformState& state, ComputeVisibleRectFlags flags) const
1094 {
1095     bool preserve3D = preserves3D() || (parent() ? parent()->preserves3D() : false);
1096     TransformState::TransformAccumulation accumulation = preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform;
1097
1098     FloatPoint position = m_position;
1099     client().customPositionForVisibleRectComputation(this, position);
1100
1101     TransformationMatrix layerTransform;
1102     TransformationMatrix currentTransform;
1103     if ((flags & RespectAnimatingTransforms) && client().getCurrentTransform(this, currentTransform))
1104         layerTransform = this->layerTransform(position, &currentTransform);
1105     else
1106         layerTransform = this->layerTransform(position);
1107
1108     bool applyWasClamped;
1109     state.applyTransform(layerTransform, accumulation, &applyWasClamped);
1110
1111     bool mapWasClamped;
1112     FloatRect clipRectForChildren = state.mappedQuad(&mapWasClamped).boundingBox();
1113     FloatPoint boundsOrigin = m_boundsOrigin;
1114 #if PLATFORM(IOS)
1115     // In WK1, UIKit may be changing layer bounds behind our back in overflow-scroll layers, so use the layer's origin.
1116     if (m_layer->isPlatformCALayerMac())
1117         boundsOrigin = m_layer->bounds().location();
1118 #endif
1119     clipRectForChildren.move(boundsOrigin.x(), boundsOrigin.y());
1120     
1121     FloatRect clipRectForSelf(boundsOrigin, m_size);
1122     if (!applyWasClamped && !mapWasClamped)
1123         clipRectForSelf.intersect(clipRectForChildren);
1124     
1125     if (masksToBounds()) {
1126         ASSERT(accumulation == TransformState::FlattenTransform);
1127         // Replace the quad in the TransformState with one that is clipped to this layer's bounds
1128         state.setQuad(clipRectForSelf);
1129     }
1130
1131     return clipRectForSelf;
1132 }
1133
1134 // rootRelativeTransformForScaling is a transform from the root, but for layers with transform animations, it cherry-picked the state of the
1135 // animation that contributes maximally to the scale (on every layer with animations down the hierarchy).
1136 void GraphicsLayerCA::recursiveCommitChanges(const CommitState& commitState, const TransformState& state, float pageScaleFactor, const FloatPoint& positionRelativeToBase, bool affectedByPageScale)
1137 {
1138     TransformState localState = state;
1139     CommitState childCommitState = commitState;
1140     bool affectedByTransformAnimation = commitState.ancestorHasTransformAnimation;
1141     
1142     FloatRect visibleRect = computeVisibleRect(localState);
1143     FloatRect oldVisibleRect = m_visibleRect;
1144     if (visibleRect != m_visibleRect) {
1145         m_uncommittedChanges |= VisibleRectChanged;
1146         m_visibleRect = visibleRect;
1147         
1148         if (GraphicsLayerCA* maskLayer = toGraphicsLayerCA(m_maskLayer)) {
1149             // FIXME: this assumes that the mask layer has the same geometry as this layer (which is currently always true).
1150             maskLayer->m_uncommittedChanges |= VisibleRectChanged;
1151             maskLayer->m_visibleRect = visibleRect;
1152         }
1153     }
1154
1155 #ifdef VISIBLE_TILE_WASH
1156     // Use having a transform as a key to making the tile wash layer. If every layer gets a wash,
1157     // they start to obscure useful information.
1158     if ((!m_transform.isIdentity() || m_usingTiledBacking) && !m_visibleTileWashLayer) {
1159         static Color washFillColor(255, 0, 0, 50);
1160         static Color washBorderColor(255, 0, 0, 100);
1161         
1162         m_visibleTileWashLayer = createPlatformCALayer(PlatformCALayer::LayerTypeLayer, this);
1163         String name = String::format("Visible Tile Wash Layer %p", m_visibleTileWashLayer->platformLayer());
1164         m_visibleTileWashLayer->setName(name);
1165         m_visibleTileWashLayer->setAnchorPoint(FloatPoint3D(0, 0, 0));
1166         m_visibleTileWashLayer->setBorderColor(washBorderColor);
1167         m_visibleTileWashLayer->setBorderWidth(8);
1168         m_visibleTileWashLayer->setBackgroundColor(washFillColor);
1169         noteSublayersChanged(DontScheduleFlush);
1170     }
1171
1172     if (m_visibleTileWashLayer) {
1173         m_visibleTileWashLayer->setPosition(m_visibleRect.location());
1174         m_visibleTileWashLayer->setBounds(FloatRect(FloatPoint(), m_visibleRect.size()));
1175     }
1176 #endif
1177
1178     bool hadChanges = m_uncommittedChanges;
1179     
1180     if (appliesPageScale()) {
1181         pageScaleFactor = this->pageScaleFactor();
1182         affectedByPageScale = true;
1183     }
1184
1185     // Accumulate an offset from the ancestral pixel-aligned layer.
1186     FloatPoint baseRelativePosition = positionRelativeToBase;
1187     if (affectedByPageScale)
1188         baseRelativePosition += m_position;
1189     
1190     commitLayerChangesBeforeSublayers(childCommitState, pageScaleFactor, baseRelativePosition, oldVisibleRect);
1191
1192     if (isRunningTransformAnimation()) {
1193         childCommitState.ancestorHasTransformAnimation = true;
1194         affectedByTransformAnimation = true;
1195     }
1196
1197     if (GraphicsLayerCA* maskLayer = toGraphicsLayerCA(m_maskLayer))
1198         maskLayer->commitLayerChangesBeforeSublayers(childCommitState, pageScaleFactor, baseRelativePosition, oldVisibleRect);
1199
1200     const Vector<GraphicsLayer*>& childLayers = children();
1201     size_t numChildren = childLayers.size();
1202     
1203     for (size_t i = 0; i < numChildren; ++i) {
1204         GraphicsLayerCA* curChild = toGraphicsLayerCA(childLayers[i]);
1205         curChild->recursiveCommitChanges(childCommitState, localState, pageScaleFactor, baseRelativePosition, affectedByPageScale);
1206     }
1207
1208     if (GraphicsLayerCA* replicaLayer = toGraphicsLayerCA(m_replicaLayer))
1209         replicaLayer->recursiveCommitChanges(childCommitState, localState, pageScaleFactor, baseRelativePosition, affectedByPageScale);
1210
1211     if (GraphicsLayerCA* maskLayer = toGraphicsLayerCA(m_maskLayer))
1212         maskLayer->commitLayerChangesAfterSublayers(childCommitState);
1213
1214     commitLayerChangesAfterSublayers(childCommitState);
1215
1216     if (affectedByTransformAnimation && m_layer->layerType() == PlatformCALayer::LayerTypeTiledBackingLayer)
1217         client().notifyFlushBeforeDisplayRefresh(this);
1218
1219     if (hadChanges)
1220         client().didCommitChangesForLayer(this);
1221 }
1222
1223 bool GraphicsLayerCA::platformCALayerShowRepaintCounter(PlatformCALayer* platformLayer) const
1224 {
1225     // The repaint counters are painted into the TileController tiles (which have no corresponding platform layer),
1226     // so we don't want to overpaint the repaint counter when called with the TileController's own layer.
1227     if (m_isPageTiledBackingLayer && platformLayer)
1228         return false;
1229
1230     return isShowingRepaintCounter();
1231 }
1232
1233 void GraphicsLayerCA::platformCALayerPaintContents(PlatformCALayer*, GraphicsContext& context, const FloatRect& clip)
1234 {
1235     paintGraphicsLayerContents(context, clip);
1236 }
1237
1238 void GraphicsLayerCA::platformCALayerSetNeedsToRevalidateTiles()
1239 {
1240     noteLayerPropertyChanged(TilingAreaChanged, m_isCommittingChanges ? DontScheduleFlush : ScheduleFlush);
1241 }
1242
1243 float GraphicsLayerCA::platformCALayerDeviceScaleFactor() const
1244 {
1245     return deviceScaleFactor();
1246 }
1247
1248 float GraphicsLayerCA::platformCALayerContentsScaleMultiplierForNewTiles(PlatformCALayer*) const
1249 {
1250     return client().contentsScaleMultiplierForNewTiles(this);
1251 }
1252
1253 bool GraphicsLayerCA::platformCALayerShouldAggressivelyRetainTiles(PlatformCALayer*) const
1254 {
1255     return client().shouldAggressivelyRetainTiles(this);
1256 }
1257
1258 bool GraphicsLayerCA::platformCALayerShouldTemporarilyRetainTileCohorts(PlatformCALayer*) const
1259 {
1260     return client().shouldTemporarilyRetainTileCohorts(this);
1261 }
1262
1263 void GraphicsLayerCA::commitLayerChangesBeforeSublayers(CommitState& commitState, float pageScaleFactor, const FloatPoint& positionRelativeToBase, const FloatRect& oldVisibleRect)
1264 {
1265     TemporaryChange<bool> committingChangesChange(m_isCommittingChanges, true);
1266
1267     ++commitState.treeDepth;
1268     if (m_structuralLayer)
1269         ++commitState.treeDepth;
1270
1271     if (!m_uncommittedChanges) {
1272         // Ensure that we cap layer depth in commitLayerChangesAfterSublayers().
1273         if (commitState.treeDepth > cMaxLayerTreeDepth)
1274             m_uncommittedChanges |= ChildrenChanged;
1275     }
1276
1277     bool needTiledLayer = requiresTiledLayer(pageScaleFactor);
1278     if (needTiledLayer != m_usingTiledBacking)
1279         swapFromOrToTiledLayer(needTiledLayer);
1280
1281     // Need to handle Preserves3DChanged first, because it affects which layers subsequent properties are applied to
1282     if (m_uncommittedChanges & (Preserves3DChanged | ReplicatedLayerChanged))
1283         updateStructuralLayer();
1284
1285     if (m_uncommittedChanges & GeometryChanged)
1286         updateGeometry(pageScaleFactor, positionRelativeToBase);
1287
1288     if (m_uncommittedChanges & DrawsContentChanged)
1289         updateLayerDrawsContent();
1290
1291     if (m_uncommittedChanges & NameChanged)
1292         updateLayerNames();
1293
1294     if (m_uncommittedChanges & ContentsImageChanged) // Needs to happen before ChildrenChanged
1295         updateContentsImage();
1296         
1297     if (m_uncommittedChanges & ContentsPlatformLayerChanged) // Needs to happen before ChildrenChanged
1298         updateContentsPlatformLayer();
1299
1300     if (m_uncommittedChanges & ContentsColorLayerChanged) // Needs to happen before ChildrenChanged
1301         updateContentsColorLayer();
1302     
1303     if (m_uncommittedChanges & BackgroundColorChanged)
1304         updateBackgroundColor();
1305
1306     if (m_uncommittedChanges & TransformChanged)
1307         updateTransform();
1308
1309     if (m_uncommittedChanges & ChildrenTransformChanged)
1310         updateChildrenTransform();
1311     
1312     if (m_uncommittedChanges & MasksToBoundsChanged)
1313         updateMasksToBounds();
1314     
1315     if (m_uncommittedChanges & ContentsVisibilityChanged)
1316         updateContentsVisibility();
1317
1318     // Note that contentsScale can affect whether the layer can be opaque.
1319     if (m_uncommittedChanges & ContentsOpaqueChanged)
1320         updateContentsOpaque(pageScaleFactor);
1321
1322     if (m_uncommittedChanges & BackfaceVisibilityChanged)
1323         updateBackfaceVisibility();
1324
1325     if (m_uncommittedChanges & OpacityChanged)
1326         updateOpacityOnLayer();
1327     
1328 #if ENABLE(CSS_FILTERS)
1329     if (m_uncommittedChanges & FiltersChanged)
1330         updateFilters();
1331 #endif
1332
1333 #if ENABLE(CSS_COMPOSITING)
1334     if (m_uncommittedChanges & BlendModeChanged)
1335         updateBlendMode();
1336 #endif
1337
1338     if (m_uncommittedChanges & AnimationChanged)
1339         updateAnimations();
1340
1341     // Updating the contents scale can cause parts of the layer to be invalidated,
1342     // so make sure to update the contents scale before updating the dirty rects.
1343     if (m_uncommittedChanges & ContentsScaleChanged)
1344         updateContentsScale(pageScaleFactor);
1345
1346     if (m_uncommittedChanges & VisibleRectChanged)
1347         updateVisibleRect(oldVisibleRect);
1348     
1349     if (m_uncommittedChanges & TilingAreaChanged) // Needs to happen after VisibleRectChanged, ContentsScaleChanged
1350         updateTiles();
1351
1352     if (m_uncommittedChanges & DirtyRectsChanged)
1353         repaintLayerDirtyRects();
1354     
1355     if (m_uncommittedChanges & ContentsRectsChanged) // Needs to happen before ChildrenChanged
1356         updateContentsRects();
1357
1358     if (m_uncommittedChanges & MaskLayerChanged) {
1359         updateMaskLayer();
1360         // If the mask layer becomes tiled it can set this flag again. Clear the flag so that
1361         // commitLayerChangesAfterSublayers doesn't update the mask again in the normal case.
1362         m_uncommittedChanges &= ~MaskLayerChanged;
1363     }
1364
1365     if (m_uncommittedChanges & ContentsNeedsDisplay)
1366         updateContentsNeedsDisplay();
1367     
1368     if (m_uncommittedChanges & AcceleratesDrawingChanged)
1369         updateAcceleratesDrawing();
1370
1371     if (m_uncommittedChanges & DebugIndicatorsChanged)
1372         updateDebugBorder();
1373
1374     if (m_uncommittedChanges & CustomAppearanceChanged)
1375         updateCustomAppearance();
1376
1377     if (m_uncommittedChanges & CustomBehaviorChanged)
1378         updateCustomBehavior();
1379
1380     if (m_uncommittedChanges & ChildrenChanged) {
1381         updateSublayerList();
1382         // Sublayers may set this flag again, so clear it to avoid always updating sublayers in commitLayerChangesAfterSublayers().
1383         m_uncommittedChanges &= ~ChildrenChanged;
1384     }
1385
1386     // Ensure that we cap layer depth in commitLayerChangesAfterSublayers().
1387     if (commitState.treeDepth > cMaxLayerTreeDepth)
1388         m_uncommittedChanges |= ChildrenChanged;
1389 }
1390
1391 void GraphicsLayerCA::commitLayerChangesAfterSublayers(CommitState& commitState)
1392 {
1393     if (!m_uncommittedChanges)
1394         return;
1395
1396     TemporaryChange<bool> committingChangesChange(m_isCommittingChanges, true);
1397
1398     if (m_uncommittedChanges & MaskLayerChanged)
1399         updateMaskLayer();
1400
1401     if (m_uncommittedChanges & ChildrenChanged)
1402         updateSublayerList(commitState.treeDepth > cMaxLayerTreeDepth);
1403
1404     if (m_uncommittedChanges & ReplicatedLayerChanged)
1405         updateReplicatedLayers();
1406
1407     m_uncommittedChanges = NoChange;
1408 }
1409
1410 void GraphicsLayerCA::updateLayerNames()
1411 {
1412     switch (structuralLayerPurpose()) {
1413     case StructuralLayerForPreserves3D:
1414         m_structuralLayer->setName("Transform layer " + name());
1415         break;
1416     case StructuralLayerForReplicaFlattening:
1417         m_structuralLayer->setName("Replica flattening layer " + name());
1418         break;
1419     case NoStructuralLayer:
1420         break;
1421     }
1422     m_layer->setName(name());
1423 }
1424
1425 void GraphicsLayerCA::updateSublayerList(bool maxLayerDepthReached)
1426 {
1427     if (maxLayerDepthReached) {
1428         m_layer->setSublayers(PlatformCALayerList());
1429         return;
1430     }
1431     
1432     const PlatformCALayerList* customSublayers = m_layer->customSublayers();
1433
1434     PlatformCALayerList structuralLayerChildren;
1435     PlatformCALayerList primaryLayerChildren;
1436
1437     PlatformCALayerList& childListForSublayers = m_structuralLayer ? structuralLayerChildren : primaryLayerChildren;
1438
1439     if (customSublayers)
1440         primaryLayerChildren.appendVector(*customSublayers);
1441
1442     if (m_structuralLayer) {
1443         if (m_replicaLayer)
1444             structuralLayerChildren.append(toGraphicsLayerCA(m_replicaLayer)->primaryLayer());
1445     
1446         structuralLayerChildren.append(m_layer);
1447     }
1448
1449     if (m_contentsLayer && m_contentsVisible) {
1450         // FIXME: add the contents layer in the correct order with negative z-order children.
1451         // This does not cause visible rendering issues because currently contents layers are only used
1452         // for replaced elements that don't have children.
1453         primaryLayerChildren.append(m_contentsClippingLayer ? m_contentsClippingLayer : m_contentsLayer);
1454     }
1455     
1456     const Vector<GraphicsLayer*>& childLayers = children();
1457     size_t numChildren = childLayers.size();
1458     for (size_t i = 0; i < numChildren; ++i) {
1459         GraphicsLayerCA* curChild = toGraphicsLayerCA(childLayers[i]);
1460         PlatformCALayer* childLayer = curChild->layerForSuperlayer();
1461         childListForSublayers.append(childLayer);
1462     }
1463
1464 #ifdef VISIBLE_TILE_WASH
1465     if (m_visibleTileWashLayer)
1466         childListForSublayers.append(m_visibleTileWashLayer);
1467 #endif
1468
1469     if (m_structuralLayer)
1470         m_structuralLayer->setSublayers(structuralLayerChildren);
1471     
1472     m_layer->setSublayers(primaryLayerChildren);
1473 }
1474
1475 void GraphicsLayerCA::updateGeometry(float pageScaleFactor, const FloatPoint& positionRelativeToBase)
1476 {
1477     FloatPoint scaledPosition = m_position;
1478     FloatPoint3D scaledAnchorPoint = m_anchorPoint;
1479     FloatSize scaledSize = m_size;
1480     FloatSize pixelAlignmentOffset;
1481
1482     // FIXME: figure out if we really need to pixel align the graphics layer here.
1483     if (m_client.needsPixelAligment() && !isIntegral(pageScaleFactor) && m_drawsContent && !m_masksToBounds)
1484         computePixelAlignment(pageScaleFactor, positionRelativeToBase, scaledPosition, scaledAnchorPoint, pixelAlignmentOffset);
1485
1486     // Update position.
1487     // Position is offset on the layer by the layer anchor point.
1488     FloatPoint adjustedPosition(scaledPosition.x() + scaledAnchorPoint.x() * scaledSize.width(), scaledPosition.y() + scaledAnchorPoint.y() * scaledSize.height());
1489
1490     if (m_structuralLayer) {
1491         FloatPoint layerPosition(m_position.x() + m_anchorPoint.x() * m_size.width(), m_position.y() + m_anchorPoint.y() * m_size.height());
1492         FloatRect layerBounds(m_boundsOrigin, m_size);
1493
1494         m_structuralLayer->setPosition(layerPosition);
1495         m_structuralLayer->setBounds(layerBounds);
1496         m_structuralLayer->setAnchorPoint(m_anchorPoint);
1497
1498         if (LayerMap* layerCloneMap = m_structuralLayerClones.get()) {
1499             LayerMap::const_iterator end = layerCloneMap->end();
1500             for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
1501                 PlatformCALayer* clone = it->value.get();
1502                 FloatPoint clonePosition = layerPosition;
1503
1504                 if (m_replicaLayer && isReplicatedRootClone(it->key)) {
1505                     // Maintain the special-case position for the root of a clone subtree,
1506                     // which we set up in replicatedLayerRoot().
1507                     clonePosition = positionForCloneRootLayer();
1508                 }
1509
1510                 clone->setPosition(clonePosition);
1511                 clone->setBounds(layerBounds);
1512                 clone->setAnchorPoint(m_anchorPoint);
1513             }
1514         }
1515
1516         // If we have a structural layer, we just use 0.5, 0.5 for the anchor point of the main layer.
1517         scaledAnchorPoint = FloatPoint(0.5f, 0.5f);
1518         adjustedPosition = FloatPoint(scaledAnchorPoint.x() * scaledSize.width() - pixelAlignmentOffset.width(), scaledAnchorPoint.y() * scaledSize.height() - pixelAlignmentOffset.height());
1519     }
1520
1521     m_pixelAlignmentOffset = pixelAlignmentOffset;
1522
1523     // Push the layer to device pixel boundary (setPosition()), but move the content back to its original position (setBounds())
1524     m_layer->setPosition(adjustedPosition);
1525     FloatRect adjustedBounds = FloatRect(FloatPoint(m_boundsOrigin - pixelAlignmentOffset), m_size);
1526     m_layer->setBounds(adjustedBounds);
1527     m_layer->setAnchorPoint(scaledAnchorPoint);
1528
1529     if (LayerMap* layerCloneMap = m_layerClones.get()) {
1530         LayerMap::const_iterator end = layerCloneMap->end();
1531         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
1532             PlatformCALayer* clone = it->value.get();
1533             FloatPoint clonePosition = adjustedPosition;
1534
1535             if (!m_structuralLayer && m_replicaLayer && isReplicatedRootClone(it->key)) {
1536                 // Maintain the special-case position for the root of a clone subtree,
1537                 // which we set up in replicatedLayerRoot().
1538                 clonePosition = positionForCloneRootLayer();
1539             }
1540
1541             clone->setPosition(clonePosition);
1542             clone->setBounds(adjustedBounds);
1543             clone->setAnchorPoint(scaledAnchorPoint);
1544         }
1545     }
1546 }
1547
1548 void GraphicsLayerCA::updateTransform()
1549 {
1550     primaryLayer()->setTransform(m_transform);
1551
1552     if (LayerMap* layerCloneMap = primaryLayerClones()) {
1553         LayerMap::const_iterator end = layerCloneMap->end();
1554         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
1555             PlatformCALayer* currLayer = it->value.get();
1556             if (m_replicaLayer && isReplicatedRootClone(it->key)) {
1557                 // Maintain the special-case transform for the root of a clone subtree,
1558                 // which we set up in replicatedLayerRoot().
1559                 currLayer->setTransform(TransformationMatrix());
1560             } else
1561                 currLayer->setTransform(m_transform);
1562         }
1563     }
1564 }
1565
1566 void GraphicsLayerCA::updateChildrenTransform()
1567 {
1568     primaryLayer()->setSublayerTransform(m_childrenTransform);
1569
1570     if (LayerMap* layerCloneMap = primaryLayerClones()) {
1571         LayerMap::const_iterator end = layerCloneMap->end();
1572         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it)
1573             it->value->setSublayerTransform(m_childrenTransform);
1574     }
1575 }
1576
1577 void GraphicsLayerCA::updateMasksToBounds()
1578 {
1579     m_layer->setMasksToBounds(m_masksToBounds);
1580
1581     if (LayerMap* layerCloneMap = m_layerClones.get()) {
1582         LayerMap::const_iterator end = layerCloneMap->end();
1583         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it)
1584             it->value->setMasksToBounds(m_masksToBounds);
1585     }
1586 }
1587
1588 void GraphicsLayerCA::updateContentsVisibility()
1589 {
1590     // Note that m_contentsVisible also affects whether m_contentsLayer is parented.
1591     if (m_contentsVisible) {
1592         if (m_drawsContent)
1593             m_layer->setNeedsDisplay();
1594     } else {
1595         m_layer->setContents(0);
1596
1597         if (LayerMap* layerCloneMap = m_layerClones.get()) {
1598             LayerMap::const_iterator end = layerCloneMap->end();
1599             for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it)
1600                 it->value->setContents(0);
1601         }
1602     }
1603 }
1604
1605 void GraphicsLayerCA::updateContentsOpaque(float pageScaleFactor)
1606 {
1607     bool contentsOpaque = m_contentsOpaque;
1608     if (contentsOpaque) {
1609         float contentsScale = pageScaleFactor * deviceScaleFactor();
1610         if (!isIntegral(contentsScale) && !m_client.paintsOpaquelyAtNonIntegralScales(this))
1611             contentsOpaque = false;
1612     }
1613     
1614     m_layer->setOpaque(contentsOpaque);
1615
1616     if (LayerMap* layerCloneMap = m_layerClones.get()) {
1617         LayerMap::const_iterator end = layerCloneMap->end();
1618         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it)
1619             it->value->setOpaque(contentsOpaque);
1620     }
1621 }
1622
1623 void GraphicsLayerCA::updateBackfaceVisibility()
1624 {
1625     if (m_structuralLayer && structuralLayerPurpose() == StructuralLayerForReplicaFlattening) {
1626         m_structuralLayer->setDoubleSided(m_backfaceVisibility);
1627
1628         if (LayerMap* layerCloneMap = m_structuralLayerClones.get()) {
1629             LayerMap::const_iterator end = layerCloneMap->end();
1630             for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it)
1631                 it->value->setDoubleSided(m_backfaceVisibility);
1632         }
1633     }
1634
1635     m_layer->setDoubleSided(m_backfaceVisibility);
1636
1637     if (LayerMap* layerCloneMap = m_layerClones.get()) {
1638         LayerMap::const_iterator end = layerCloneMap->end();
1639         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it)
1640             it->value->setDoubleSided(m_backfaceVisibility);
1641     }
1642 }
1643
1644 #if ENABLE(CSS_FILTERS)
1645 void GraphicsLayerCA::updateFilters()
1646 {
1647     m_layer->setFilters(m_filters);
1648
1649     if (LayerMap* layerCloneMap = m_layerClones.get()) {
1650         LayerMap::const_iterator end = layerCloneMap->end();
1651         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
1652             if (m_replicaLayer && isReplicatedRootClone(it->key))
1653                 continue;
1654
1655             it->value->setFilters(m_filters);
1656         }
1657     }
1658 }
1659 #endif
1660
1661 #if ENABLE(CSS_COMPOSITING)
1662 void GraphicsLayerCA::updateBlendMode()
1663 {
1664     primaryLayer()->setBlendMode(m_blendMode);
1665
1666     if (LayerMap* layerCloneMap = primaryLayerClones()) {
1667         LayerMap::const_iterator end = layerCloneMap->end();
1668         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
1669             if (m_replicaLayer && isReplicatedRootClone(it->key))
1670                 continue;
1671             it->value->setBlendMode(m_blendMode);
1672         }
1673     }
1674 }
1675 #endif
1676
1677 void GraphicsLayerCA::updateStructuralLayer()
1678 {
1679     ensureStructuralLayer(structuralLayerPurpose());
1680 }
1681
1682 void GraphicsLayerCA::ensureStructuralLayer(StructuralLayerPurpose purpose)
1683 {
1684     const LayerChangeFlags structuralLayerChangeFlags = NameChanged
1685         | GeometryChanged
1686         | TransformChanged
1687         | ChildrenTransformChanged
1688         | ChildrenChanged
1689         | BackfaceVisibilityChanged
1690 #if ENABLE(CSS_FILTERS)
1691         | FiltersChanged
1692 #endif
1693         | OpacityChanged;
1694
1695     if (purpose == NoStructuralLayer) {
1696         if (m_structuralLayer) {
1697             // Replace the transformLayer in the parent with this layer.
1698             m_layer->removeFromSuperlayer();
1699  
1700             // If m_layer doesn't have a parent, it means it's the root layer and
1701             // is likely hosted by something that is not expecting to be changed
1702             ASSERT(m_structuralLayer->superlayer());
1703             m_structuralLayer->superlayer()->replaceSublayer(m_structuralLayer.get(), m_layer.get());
1704
1705             moveOrCopyAnimations(Move, m_structuralLayer.get(), m_layer.get());
1706
1707             // Release the structural layer.
1708             m_structuralLayer = 0;
1709
1710             m_uncommittedChanges |= structuralLayerChangeFlags;
1711         }
1712         return;
1713     }
1714
1715     bool structuralLayerChanged = false;
1716     
1717     if (purpose == StructuralLayerForPreserves3D) {
1718         if (m_structuralLayer && m_structuralLayer->layerType() != PlatformCALayer::LayerTypeTransformLayer)
1719             m_structuralLayer = 0;
1720         
1721         if (!m_structuralLayer) {
1722             m_structuralLayer = createPlatformCALayer(PlatformCALayer::LayerTypeTransformLayer, this);
1723             structuralLayerChanged = true;
1724         }
1725     } else {
1726         if (m_structuralLayer && m_structuralLayer->layerType() != PlatformCALayer::LayerTypeLayer)
1727             m_structuralLayer = 0;
1728
1729         if (!m_structuralLayer) {
1730             m_structuralLayer = createPlatformCALayer(PlatformCALayer::LayerTypeLayer, this);
1731             structuralLayerChanged = true;
1732         }
1733     }
1734     
1735     if (!structuralLayerChanged)
1736         return;
1737     
1738     m_uncommittedChanges |= structuralLayerChangeFlags;
1739
1740     // We've changed the layer that our parent added to its sublayer list, so tell it to update
1741     // sublayers again in its commitLayerChangesAfterSublayers().
1742     toGraphicsLayerCA(parent())->noteSublayersChanged(DontScheduleFlush);
1743
1744     // Set properties of m_layer to their default values, since these are expressed on on the structural layer.
1745     FloatPoint point(m_size.width() / 2.0f, m_size.height() / 2.0f);
1746     FloatPoint3D anchorPoint(0.5f, 0.5f, 0);
1747     m_layer->setPosition(point);
1748     m_layer->setAnchorPoint(anchorPoint);
1749     m_layer->setTransform(TransformationMatrix());
1750     m_layer->setOpacity(1);
1751     if (m_layerClones) {
1752         LayerMap::const_iterator end = m_layerClones->end();
1753         for (LayerMap::const_iterator it = m_layerClones->begin(); it != end; ++it) {
1754             PlatformCALayer* currLayer = it->value.get();
1755             currLayer->setPosition(point);
1756             currLayer->setAnchorPoint(anchorPoint);
1757             currLayer->setTransform(TransformationMatrix());
1758             currLayer->setOpacity(1);
1759         }
1760     }
1761
1762     moveOrCopyAnimations(Move, m_layer.get(), m_structuralLayer.get());
1763 }
1764
1765 GraphicsLayerCA::StructuralLayerPurpose GraphicsLayerCA::structuralLayerPurpose() const
1766 {
1767     if (preserves3D())
1768         return StructuralLayerForPreserves3D;
1769     
1770     if (isReplicated())
1771         return StructuralLayerForReplicaFlattening;
1772     
1773     return NoStructuralLayer;
1774 }
1775
1776 void GraphicsLayerCA::updateLayerDrawsContent()
1777 {
1778     if (m_drawsContent)
1779         m_layer->setNeedsDisplay();
1780     else {
1781         m_layer->setContents(0);
1782         if (m_layerClones) {
1783             LayerMap::const_iterator end = m_layerClones->end();
1784             for (LayerMap::const_iterator it = m_layerClones->begin(); it != end; ++it)
1785                 it->value->setContents(0);
1786         }
1787     }
1788 }
1789
1790 void GraphicsLayerCA::updateAcceleratesDrawing()
1791 {
1792     m_layer->setAcceleratesDrawing(m_acceleratesDrawing);
1793 }
1794
1795 void GraphicsLayerCA::updateDebugBorder()
1796 {
1797     if (isShowingDebugBorder())
1798         updateDebugIndicators();
1799     else
1800         m_layer->setBorderWidth(0);
1801 }
1802
1803 FloatRect GraphicsLayerCA::adjustTiledLayerVisibleRect(TiledBacking* tiledBacking, const FloatRect& oldVisibleRect, const FloatRect& newVisibleRect, const FloatSize& oldSize, const FloatSize& newSize)
1804 {
1805     // If the old visible rect is empty, we have no information about how the visible area is changing
1806     // (maybe the layer was just created), so don't attempt to expand. Also don't attempt to expand
1807     // if the size changed or the rects don't overlap.
1808     if (oldVisibleRect.isEmpty() || newSize != oldSize || !newVisibleRect.intersects(oldVisibleRect))
1809         return newVisibleRect;
1810
1811     const float paddingMultiplier = 2;
1812
1813     float leftEdgeDelta = paddingMultiplier * (newVisibleRect.x() - oldVisibleRect.x());
1814     float rightEdgeDelta = paddingMultiplier * (newVisibleRect.maxX() - oldVisibleRect.maxX());
1815
1816     float topEdgeDelta = paddingMultiplier * (newVisibleRect.y() - oldVisibleRect.y());
1817     float bottomEdgeDelta = paddingMultiplier * (newVisibleRect.maxY() - oldVisibleRect.maxY());
1818     
1819     FloatRect existingTileBackingRect = tiledBacking->visibleRect();
1820     FloatRect expandedRect = newVisibleRect;
1821
1822     // More exposed on left side.
1823     if (leftEdgeDelta < 0) {
1824         float newLeft = expandedRect.x() + leftEdgeDelta;
1825         // Pad to the left, but don't reduce padding that's already in the backing store (since we're still exposing to the left).
1826         if (newLeft < existingTileBackingRect.x())
1827             expandedRect.shiftXEdgeTo(newLeft);
1828         else
1829             expandedRect.shiftXEdgeTo(existingTileBackingRect.x());
1830     }
1831
1832     // More exposed on right.
1833     if (rightEdgeDelta > 0) {
1834         float newRight = expandedRect.maxX() + rightEdgeDelta;
1835         // Pad to the right, but don't reduce padding that's already in the backing store (since we're still exposing to the right).
1836         if (newRight > existingTileBackingRect.maxX())
1837             expandedRect.setWidth(newRight - expandedRect.x());
1838         else
1839             expandedRect.setWidth(existingTileBackingRect.maxX() - expandedRect.x());
1840     }
1841
1842     // More exposed at top.
1843     if (topEdgeDelta < 0) {
1844         float newTop = expandedRect.y() + topEdgeDelta;
1845         if (newTop < existingTileBackingRect.y())
1846             expandedRect.shiftYEdgeTo(newTop);
1847         else
1848             expandedRect.shiftYEdgeTo(existingTileBackingRect.y());
1849     }
1850
1851     // More exposed on bottom.
1852     if (bottomEdgeDelta > 0) {
1853         float newBottom = expandedRect.maxY() + bottomEdgeDelta;
1854         if (newBottom > existingTileBackingRect.maxY())
1855             expandedRect.setHeight(newBottom - expandedRect.y());
1856         else
1857             expandedRect.setHeight(existingTileBackingRect.maxY() - expandedRect.y());
1858     }
1859     
1860     expandedRect.intersect(tiledBacking->boundsWithoutMargin());
1861     return expandedRect;
1862 }
1863
1864 void GraphicsLayerCA::updateVisibleRect(const FloatRect& oldVisibleRect)
1865 {
1866     if (!m_layer->usesTiledBackingLayer())
1867         return;
1868
1869     FloatRect tileArea = m_visibleRect;
1870     if (m_layer->layerType() == PlatformCALayer::LayerTypeTiledBackingLayer)
1871         tileArea = adjustTiledLayerVisibleRect(tiledBacking(), oldVisibleRect, tileArea, m_sizeAtLastVisibleRectUpdate, m_size);
1872
1873     tiledBacking()->setVisibleRect(tileArea);
1874
1875     m_sizeAtLastVisibleRectUpdate = m_size;
1876 }
1877
1878 void GraphicsLayerCA::updateTiles()
1879 {
1880     if (!m_layer->usesTiledBackingLayer())
1881         return;
1882
1883     tiledBacking()->revalidateTiles();
1884 }
1885
1886 void GraphicsLayerCA::updateBackgroundColor()
1887 {
1888     m_layer->setBackgroundColor(m_backgroundColor);
1889 }
1890
1891 void GraphicsLayerCA::updateContentsImage()
1892 {
1893     if (m_pendingContentsImage) {
1894         if (!m_contentsLayer.get()) {
1895             m_contentsLayer = createPlatformCALayer(PlatformCALayer::LayerTypeLayer, this);
1896 #ifndef NDEBUG
1897             m_contentsLayer->setName("Image Layer");
1898 #endif
1899             setupContentsLayer(m_contentsLayer.get());
1900             // m_contentsLayer will be parented by updateSublayerList
1901         }
1902
1903         // FIXME: maybe only do trilinear if the image is being scaled down,
1904         // but then what if the layer size changes?
1905         m_contentsLayer->setMinificationFilter(PlatformCALayer::Trilinear);
1906         m_contentsLayer->setContents(m_pendingContentsImage.get());
1907         m_pendingContentsImage = 0;
1908
1909         if (m_contentsLayerClones) {
1910             LayerMap::const_iterator end = m_contentsLayerClones->end();
1911             for (LayerMap::const_iterator it = m_contentsLayerClones->begin(); it != end; ++it)
1912                 it->value->setContents(m_contentsLayer->contents());
1913         }
1914         
1915         updateContentsRects();
1916     } else {
1917         // No image.
1918         // m_contentsLayer will be removed via updateSublayerList.
1919         m_contentsLayer = 0;
1920     }
1921 }
1922
1923 void GraphicsLayerCA::updateContentsPlatformLayer()
1924 {
1925     if (!m_contentsLayer)
1926         return;
1927
1928     // Platform layer was set as m_contentsLayer, and will get parented in updateSublayerList().
1929     setupContentsLayer(m_contentsLayer.get());
1930
1931     if (m_contentsLayerPurpose == ContentsLayerForCanvas)
1932         m_contentsLayer->setNeedsDisplay();
1933
1934     updateContentsRects();
1935 }
1936
1937 void GraphicsLayerCA::updateContentsColorLayer()
1938 {
1939     // Color layer was set as m_contentsLayer, and will get parented in updateSublayerList().
1940     if (!m_contentsLayer || m_contentsLayerPurpose != ContentsLayerForBackgroundColor)
1941         return;
1942
1943     setupContentsLayer(m_contentsLayer.get());
1944     updateContentsRects();
1945     ASSERT(m_contentsSolidColor.isValid());
1946     m_contentsLayer->setBackgroundColor(m_contentsSolidColor);
1947
1948     if (m_contentsLayerClones) {
1949         LayerMap::const_iterator end = m_contentsLayerClones->end();
1950         for (LayerMap::const_iterator it = m_contentsLayerClones->begin(); it != end; ++it)
1951             it->value->setBackgroundColor(m_contentsSolidColor);
1952     }
1953 }
1954
1955 void GraphicsLayerCA::updateContentsRects()
1956 {
1957     if (!m_contentsLayer)
1958         return;
1959
1960     FloatPoint contentOrigin;
1961     FloatRect contentBounds(0, 0, m_contentsRect.width(), m_contentsRect.height());
1962
1963     FloatPoint clippingOrigin;
1964     FloatRect clippingBounds;
1965     
1966     bool gainedOrLostClippingLayer = false;
1967     if (!m_contentsClippingRect.contains(m_contentsRect)) {
1968         if (!m_contentsClippingLayer) {
1969             m_contentsClippingLayer = createPlatformCALayer(PlatformCALayer::LayerTypeLayer, this);
1970             m_contentsClippingLayer->setMasksToBounds(true);
1971             m_contentsClippingLayer->setAnchorPoint(FloatPoint());
1972 #ifndef NDEBUG
1973             m_contentsClippingLayer->setName("Contents Clipping");
1974 #endif
1975             m_contentsLayer->removeFromSuperlayer();
1976             m_contentsClippingLayer->appendSublayer(m_contentsLayer.get());
1977             gainedOrLostClippingLayer = true;
1978         }
1979     
1980         clippingOrigin = m_contentsClippingRect.location();
1981         clippingBounds.setSize(m_contentsClippingRect.size());
1982
1983         contentOrigin = FloatPoint(m_contentsRect.location() - m_contentsClippingRect.location());
1984
1985         m_contentsClippingLayer->setPosition(clippingOrigin);
1986         m_contentsClippingLayer->setBounds(clippingBounds);
1987
1988         m_contentsLayer->setPosition(contentOrigin);
1989         m_contentsLayer->setBounds(contentBounds);
1990     
1991     } else {
1992         if (m_contentsClippingLayer) {
1993             m_contentsLayer->removeFromSuperlayer();
1994
1995             m_contentsClippingLayer->removeFromSuperlayer();
1996             m_contentsClippingLayer->setOwner(0);
1997             m_contentsClippingLayer = nullptr;
1998             gainedOrLostClippingLayer = true;
1999         }
2000
2001         contentOrigin = m_contentsRect.location();
2002     }
2003     
2004     if (gainedOrLostClippingLayer)
2005         noteSublayersChanged(DontScheduleFlush);
2006
2007     m_contentsLayer->setPosition(contentOrigin);
2008     m_contentsLayer->setBounds(contentBounds);
2009
2010     if (m_contentsLayerClones) {
2011         LayerMap::const_iterator end = m_contentsLayerClones->end();
2012         for (LayerMap::const_iterator it = m_contentsLayerClones->begin(); it != end; ++it) {
2013             it->value->setPosition(contentOrigin);
2014             it->value->setBounds(contentBounds);
2015         }
2016     }
2017
2018     if (m_contentsClippingLayerClones) {
2019         LayerMap::const_iterator end = m_contentsClippingLayerClones->end();
2020         for (LayerMap::const_iterator it = m_contentsClippingLayerClones->begin(); it != end; ++it) {
2021             it->value->setPosition(clippingOrigin);
2022             it->value->setBounds(clippingBounds);
2023         }
2024     }
2025 }
2026
2027 void GraphicsLayerCA::updateMaskLayer()
2028 {
2029     PlatformCALayer* maskCALayer = m_maskLayer ? toGraphicsLayerCA(m_maskLayer)->primaryLayer() : 0;
2030     m_layer->setMask(maskCALayer);
2031
2032     LayerMap* maskLayerCloneMap = m_maskLayer ? toGraphicsLayerCA(m_maskLayer)->primaryLayerClones() : 0;
2033     
2034     if (LayerMap* layerCloneMap = m_layerClones.get()) {
2035         LayerMap::const_iterator end = layerCloneMap->end();
2036         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {            
2037             PlatformCALayer* maskClone = maskLayerCloneMap ? maskLayerCloneMap->get(it->key) : 0;
2038             it->value->setMask(maskClone);
2039         }
2040     }
2041 }
2042
2043 void GraphicsLayerCA::updateReplicatedLayers()
2044 {
2045     // Clone the descendants of the replicated layer, and parent under us.
2046     ReplicaState replicaState(ReplicaState::ReplicaBranch);
2047
2048     RefPtr<PlatformCALayer>replicaRoot = replicatedLayerRoot(replicaState);
2049     if (!replicaRoot)
2050         return;
2051
2052     if (m_structuralLayer)
2053         m_structuralLayer->insertSublayer(replicaRoot.get(), 0);
2054     else
2055         m_layer->insertSublayer(replicaRoot.get(), 0);
2056 }
2057
2058 // For now, this assumes that layers only ever have one replica, so replicaIndices contains only 0 and 1.
2059 GraphicsLayerCA::CloneID GraphicsLayerCA::ReplicaState::cloneID() const
2060 {
2061     size_t depth = m_replicaBranches.size();
2062
2063     const size_t bitsPerUChar = sizeof(UChar) * 8;
2064     size_t vectorSize = (depth + bitsPerUChar - 1) / bitsPerUChar;
2065     
2066     Vector<UChar> result(vectorSize);
2067     result.fill(0);
2068
2069     // Create a string from the bit sequence which we can use to identify the clone.
2070     // Note that the string may contain embedded nulls, but that's OK.
2071     for (size_t i = 0; i < depth; ++i) {
2072         UChar& currChar = result[i / bitsPerUChar];
2073         currChar = (currChar << 1) | m_replicaBranches[i];
2074     }
2075     
2076     return String::adopt(result);
2077 }
2078
2079 PassRefPtr<PlatformCALayer> GraphicsLayerCA::replicatedLayerRoot(ReplicaState& replicaState)
2080 {
2081     // Limit replica nesting, to avoid 2^N explosion of replica layers.
2082     if (!m_replicatedLayer || replicaState.replicaDepth() == ReplicaState::maxReplicaDepth)
2083         return 0;
2084
2085     GraphicsLayerCA* replicatedLayer = toGraphicsLayerCA(m_replicatedLayer);
2086     
2087     RefPtr<PlatformCALayer> clonedLayerRoot = replicatedLayer->fetchCloneLayers(this, replicaState, RootCloneLevel);
2088     FloatPoint cloneRootPosition = replicatedLayer->positionForCloneRootLayer();
2089
2090     // Replica root has no offset or transform
2091     clonedLayerRoot->setPosition(cloneRootPosition);
2092     clonedLayerRoot->setTransform(TransformationMatrix());
2093
2094     return clonedLayerRoot;
2095 }
2096
2097 void GraphicsLayerCA::updateAnimations()
2098 {
2099     if (m_animationsToProcess.size()) {
2100         AnimationsToProcessMap::const_iterator end = m_animationsToProcess.end();
2101         for (AnimationsToProcessMap::const_iterator it = m_animationsToProcess.begin(); it != end; ++it) {
2102             const String& currAnimationName = it->key;
2103             AnimationsMap::iterator animationIt = m_runningAnimations.find(currAnimationName);
2104             if (animationIt == m_runningAnimations.end())
2105                 continue;
2106
2107             const AnimationProcessingAction& processingInfo = it->value;
2108             const Vector<LayerPropertyAnimation>& animations = animationIt->value;
2109             for (size_t i = 0; i < animations.size(); ++i) {
2110                 const LayerPropertyAnimation& currAnimation = animations[i];
2111                 switch (processingInfo.action) {
2112                 case Remove:
2113                     removeCAAnimationFromLayer(currAnimation.m_property, currAnimationName, currAnimation.m_index, currAnimation.m_subIndex);
2114                     break;
2115                 case Pause:
2116                     pauseCAAnimationOnLayer(currAnimation.m_property, currAnimationName, currAnimation.m_index, currAnimation.m_subIndex, processingInfo.timeOffset);
2117                     break;
2118                 }
2119             }
2120
2121             if (processingInfo.action == Remove)
2122                 m_runningAnimations.remove(currAnimationName);
2123         }
2124     
2125         m_animationsToProcess.clear();
2126     }
2127     
2128     size_t numAnimations;
2129     if ((numAnimations = m_uncomittedAnimations.size())) {
2130         for (size_t i = 0; i < numAnimations; ++i) {
2131             const LayerPropertyAnimation& pendingAnimation = m_uncomittedAnimations[i];
2132             setAnimationOnLayer(pendingAnimation.m_animation.get(), pendingAnimation.m_property, pendingAnimation.m_name, pendingAnimation.m_index, pendingAnimation.m_subIndex, pendingAnimation.m_timeOffset);
2133             
2134             AnimationsMap::iterator it = m_runningAnimations.find(pendingAnimation.m_name);
2135             if (it == m_runningAnimations.end()) {
2136                 Vector<LayerPropertyAnimation> animations;
2137                 animations.append(pendingAnimation);
2138                 m_runningAnimations.add(pendingAnimation.m_name, animations);
2139
2140             } else {
2141                 Vector<LayerPropertyAnimation>& animations = it->value;
2142                 animations.append(pendingAnimation);
2143             }
2144         }
2145         m_uncomittedAnimations.clear();
2146     }
2147 }
2148
2149 bool GraphicsLayerCA::isRunningTransformAnimation() const
2150 {
2151     AnimationsMap::const_iterator end = m_runningAnimations.end();
2152     for (AnimationsMap::const_iterator it = m_runningAnimations.begin(); it != end; ++it) {
2153         const Vector<LayerPropertyAnimation>& propertyAnimations = it->value;
2154         size_t numAnimations = propertyAnimations.size();
2155         for (size_t i = 0; i < numAnimations; ++i) {
2156             const LayerPropertyAnimation& currAnimation = propertyAnimations[i];
2157             if (currAnimation.m_property == AnimatedPropertyWebkitTransform)
2158                 return true;
2159         }
2160     }
2161     return false;
2162 }
2163
2164 void GraphicsLayerCA::setAnimationOnLayer(PlatformCAAnimation* caAnim, AnimatedPropertyID property, const String& animationName, int index, int subIndex, double timeOffset)
2165 {
2166     PlatformCALayer* layer = animatedLayer(property);
2167
2168     if (timeOffset)
2169         caAnim->setBeginTime(CACurrentMediaTime() - timeOffset);
2170
2171     String animationID = animationIdentifier(animationName, property, index, subIndex);
2172
2173     layer->removeAnimationForKey(animationID);
2174     layer->addAnimationForKey(animationID, caAnim);
2175
2176     if (LayerMap* layerCloneMap = animatedLayerClones(property)) {
2177         LayerMap::const_iterator end = layerCloneMap->end();
2178         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
2179             // Skip immediate replicas, since they move with the original.
2180             if (m_replicaLayer && isReplicatedRootClone(it->key))
2181                 continue;
2182
2183             it->value->removeAnimationForKey(animationID);
2184             it->value->addAnimationForKey(animationID, caAnim);
2185         }
2186     }
2187 }
2188
2189 // Workaround for <rdar://problem/7311367>
2190 static void bug7311367Workaround(PlatformCALayer* transformLayer, const TransformationMatrix& transform)
2191 {
2192     if (!transformLayer)
2193         return;
2194
2195     TransformationMatrix caTransform = transform;
2196     caTransform.setM41(caTransform.m41() + 1);
2197     transformLayer->setTransform(caTransform);
2198
2199     caTransform.setM41(caTransform.m41() - 1);
2200     transformLayer->setTransform(caTransform);
2201 }
2202
2203 bool GraphicsLayerCA::removeCAAnimationFromLayer(AnimatedPropertyID property, const String& animationName, int index, int subIndex)
2204 {
2205     PlatformCALayer* layer = animatedLayer(property);
2206
2207     String animationID = animationIdentifier(animationName, property, index, subIndex);
2208
2209     if (!layer->animationForKey(animationID))
2210         return false;
2211     
2212     layer->removeAnimationForKey(animationID);
2213     bug7311367Workaround(m_structuralLayer.get(), m_transform);
2214
2215     if (LayerMap* layerCloneMap = animatedLayerClones(property)) {
2216         LayerMap::const_iterator end = layerCloneMap->end();
2217         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
2218             // Skip immediate replicas, since they move with the original.
2219             if (m_replicaLayer && isReplicatedRootClone(it->key))
2220                 continue;
2221
2222             it->value->removeAnimationForKey(animationID);
2223         }
2224     }
2225     return true;
2226 }
2227
2228 void GraphicsLayerCA::pauseCAAnimationOnLayer(AnimatedPropertyID property, const String& animationName, int index, int subIndex, double timeOffset)
2229 {
2230     PlatformCALayer* layer = animatedLayer(property);
2231
2232     String animationID = animationIdentifier(animationName, property, index, subIndex);
2233
2234     RefPtr<PlatformCAAnimation> curAnim = layer->animationForKey(animationID);
2235     if (!curAnim)
2236         return;
2237
2238     // Animations on the layer are immutable, so we have to clone and modify.
2239     RefPtr<PlatformCAAnimation> newAnim = curAnim->copy();
2240
2241     newAnim->setSpeed(0);
2242     newAnim->setTimeOffset(timeOffset);
2243     
2244     layer->addAnimationForKey(animationID, newAnim.get()); // This will replace the running animation.
2245
2246     // Pause the animations on the clones too.
2247     if (LayerMap* layerCloneMap = animatedLayerClones(property)) {
2248         LayerMap::const_iterator end = layerCloneMap->end();
2249         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
2250             // Skip immediate replicas, since they move with the original.
2251             if (m_replicaLayer && isReplicatedRootClone(it->key))
2252                 continue;
2253             it->value->addAnimationForKey(animationID, newAnim.get());
2254         }
2255     }
2256 }
2257
2258 void GraphicsLayerCA::repaintLayerDirtyRects()
2259 {
2260     if (m_needsFullRepaint) {
2261         ASSERT(!m_dirtyRects.size());
2262         m_layer->setNeedsDisplay();
2263         m_needsFullRepaint = false;
2264         return;
2265     }
2266
2267     if (!m_dirtyRects.size())
2268         return;
2269
2270     for (size_t i = 0; i < m_dirtyRects.size(); ++i)
2271         m_layer->setNeedsDisplayInRect(m_dirtyRects[i]);
2272     
2273     m_dirtyRects.clear();
2274 }
2275
2276 void GraphicsLayerCA::updateContentsNeedsDisplay()
2277 {
2278     if (m_contentsLayer)
2279         m_contentsLayer->setNeedsDisplay();
2280 }
2281
2282 bool GraphicsLayerCA::createAnimationFromKeyframes(const KeyframeValueList& valueList, const Animation* animation, const String& animationName, double timeOffset)
2283 {
2284     ASSERT(valueList.property() != AnimatedPropertyWebkitTransform && (!supportsAcceleratedFilterAnimations() || valueList.property() != AnimatedPropertyWebkitFilter));
2285     
2286     bool isKeyframe = valueList.size() > 2;
2287     bool valuesOK;
2288     
2289     bool additive = false;
2290     int animationIndex = 0;
2291     
2292     RefPtr<PlatformCAAnimation> caAnimation;
2293     
2294     if (isKeyframe) {
2295         caAnimation = createKeyframeAnimation(animation, propertyIdToString(valueList.property()), additive);
2296         valuesOK = setAnimationKeyframes(valueList, animation, caAnimation.get());
2297     } else {
2298         caAnimation = createBasicAnimation(animation, propertyIdToString(valueList.property()), additive);
2299         valuesOK = setAnimationEndpoints(valueList, animation, caAnimation.get());
2300     }
2301     
2302     if (!valuesOK)
2303         return false;
2304
2305     m_uncomittedAnimations.append(LayerPropertyAnimation(caAnimation, animationName, valueList.property(), animationIndex, 0, timeOffset));
2306
2307     return true;
2308 }
2309
2310 bool GraphicsLayerCA::appendToUncommittedAnimations(const KeyframeValueList& valueList, const TransformOperations* operations, const Animation* animation, const String& animationName, const FloatSize& boxSize, int animationIndex, double timeOffset, bool isMatrixAnimation)
2311 {
2312     TransformOperation::OperationType transformOp = isMatrixAnimation ? TransformOperation::MATRIX_3D : operations->operations().at(animationIndex)->type();
2313     bool additive = animationIndex > 0;
2314     bool isKeyframe = valueList.size() > 2;
2315
2316     RefPtr<PlatformCAAnimation> caAnimation;
2317     bool validMatrices = true;
2318     if (isKeyframe) {
2319         caAnimation = createKeyframeAnimation(animation, propertyIdToString(valueList.property()), additive);
2320         validMatrices = setTransformAnimationKeyframes(valueList, animation, caAnimation.get(), animationIndex, transformOp, isMatrixAnimation, boxSize);
2321     } else {
2322         caAnimation = createBasicAnimation(animation, propertyIdToString(valueList.property()), additive);
2323         validMatrices = setTransformAnimationEndpoints(valueList, animation, caAnimation.get(), animationIndex, transformOp, isMatrixAnimation, boxSize);
2324     }
2325     
2326     if (!validMatrices)
2327         return false;
2328
2329     m_uncomittedAnimations.append(LayerPropertyAnimation(caAnimation, animationName, valueList.property(), animationIndex, 0, timeOffset));
2330     return true;
2331 }
2332
2333 bool GraphicsLayerCA::createTransformAnimationsFromKeyframes(const KeyframeValueList& valueList, const Animation* animation, const String& animationName, double timeOffset, const FloatSize& boxSize)
2334 {
2335     ASSERT(valueList.property() == AnimatedPropertyWebkitTransform);
2336
2337     bool hasBigRotation;
2338     int listIndex = validateTransformOperations(valueList, hasBigRotation);
2339     const TransformOperations* operations = (listIndex >= 0) ? &static_cast<const TransformAnimationValue&>(valueList.at(listIndex)).value() : 0;
2340
2341     bool validMatrices = true;
2342
2343     // If function lists don't match we do a matrix animation, otherwise we do a component hardware animation.
2344     bool isMatrixAnimation = listIndex < 0;
2345     int numAnimations = isMatrixAnimation ? 1 : operations->size();
2346
2347 #if PLATFORM(IOS)
2348     bool reverseAnimationList = false;
2349 #else
2350     bool reverseAnimationList = true;
2351 #if !PLATFORM(WIN)
2352         // Old versions of Core Animation apply animations in reverse order (<rdar://problem/7095638>) so we need to flip the list.
2353         // to be non-additive. For binary compatibility, the current version of Core Animation preserves this behavior for applications linked
2354         // on or before Snow Leopard.
2355         // FIXME: This fix has not been added to QuartzCore on Windows yet (<rdar://problem/9112233>) so we expect the
2356         // reversed animation behavior
2357         static bool executableWasLinkedOnOrBeforeSnowLeopard = wkExecutableWasLinkedOnOrBeforeSnowLeopard();
2358         if (!executableWasLinkedOnOrBeforeSnowLeopard)
2359             reverseAnimationList = false;
2360 #endif
2361 #endif // PLATFORM(IOS)
2362     if (reverseAnimationList) {
2363         for (int animationIndex = numAnimations - 1; animationIndex >= 0; --animationIndex) {
2364             if (!appendToUncommittedAnimations(valueList, operations, animation, animationName, boxSize, animationIndex, timeOffset, isMatrixAnimation)) {
2365                 validMatrices = false;
2366                 break;
2367             }
2368         }
2369     } else {
2370         for (int animationIndex = 0; animationIndex < numAnimations; ++animationIndex) {
2371             if (!appendToUncommittedAnimations(valueList, operations, animation, animationName, boxSize, animationIndex, timeOffset, isMatrixAnimation)) {
2372                 validMatrices = false;
2373                 break;
2374             }
2375         }
2376     }
2377
2378     return validMatrices;
2379 }
2380
2381 #if ENABLE(CSS_FILTERS)
2382 bool GraphicsLayerCA::appendToUncommittedAnimations(const KeyframeValueList& valueList, const FilterOperation* operation, const Animation* animation, const String& animationName, int animationIndex, double timeOffset)
2383 {
2384     bool isKeyframe = valueList.size() > 2;
2385     
2386     FilterOperation::OperationType filterOp = operation->type();
2387     int numAnimatedProperties = PlatformCAFilters::numAnimatedFilterProperties(filterOp);
2388     
2389     // Each filter might need to animate multiple properties, each with their own keyPath. The keyPath is always of the form:
2390     //
2391     //      filter.filter_<animationIndex>.<filterPropertyName>
2392     //
2393     // PlatformCAAnimation tells us how many properties each filter has and we iterate that many times and create an animation
2394     // for each. This internalFilterPropertyIndex gets passed to PlatformCAAnimation so it can properly create the property animation
2395     // values.
2396     for (int internalFilterPropertyIndex = 0; internalFilterPropertyIndex < numAnimatedProperties; ++internalFilterPropertyIndex) {
2397         bool valuesOK;
2398         RefPtr<PlatformCAAnimation> caAnimation;
2399         String keyPath = String::format("filters.filter_%d.%s", animationIndex, PlatformCAFilters::animatedFilterPropertyName(filterOp, internalFilterPropertyIndex));
2400         
2401         if (isKeyframe) {
2402             caAnimation = createKeyframeAnimation(animation, keyPath, false);
2403             valuesOK = setFilterAnimationKeyframes(valueList, animation, caAnimation.get(), animationIndex, internalFilterPropertyIndex, filterOp);
2404         } else {
2405             caAnimation = createBasicAnimation(animation, keyPath, false);
2406             valuesOK = setFilterAnimationEndpoints(valueList, animation, caAnimation.get(), animationIndex, internalFilterPropertyIndex);
2407         }
2408         
2409         ASSERT(valuesOK);
2410
2411         m_uncomittedAnimations.append(LayerPropertyAnimation(caAnimation, animationName, valueList.property(), animationIndex, internalFilterPropertyIndex, timeOffset));
2412     }
2413
2414     return true;
2415 }
2416
2417 bool GraphicsLayerCA::createFilterAnimationsFromKeyframes(const KeyframeValueList& valueList, const Animation* animation, const String& animationName, double timeOffset)
2418 {
2419     ASSERT(valueList.property() == AnimatedPropertyWebkitFilter);
2420
2421     int listIndex = validateFilterOperations(valueList);
2422     if (listIndex < 0)
2423         return false;
2424
2425     const FilterOperations& operations = static_cast<const FilterAnimationValue&>(valueList.at(listIndex)).value();
2426     // Make sure the platform layer didn't fallback to using software filter compositing instead.
2427     if (!filtersCanBeComposited(operations))
2428         return false;
2429
2430     int numAnimations = operations.size();
2431
2432     // FIXME: We can't currently hardware animate shadows.
2433     for (int i = 0; i < numAnimations; ++i) {
2434         if (operations.at(i)->type() == FilterOperation::DROP_SHADOW)
2435             return false;
2436     }
2437
2438     for (int animationIndex = 0; animationIndex < numAnimations; ++animationIndex) {
2439         if (!appendToUncommittedAnimations(valueList, operations.operations().at(animationIndex).get(), animation, animationName, animationIndex, timeOffset))
2440             return false;
2441     }
2442
2443     return true;
2444 }
2445 #endif
2446
2447 PassRefPtr<PlatformCAAnimation> GraphicsLayerCA::createBasicAnimation(const Animation* anim, const String& keyPath, bool additive)
2448 {
2449     RefPtr<PlatformCAAnimation> basicAnim = createPlatformCAAnimation(PlatformCAAnimation::Basic, keyPath);
2450     setupAnimation(basicAnim.get(), anim, additive);
2451     return basicAnim;
2452 }
2453
2454 PassRefPtr<PlatformCAAnimation>GraphicsLayerCA::createKeyframeAnimation(const Animation* anim, const String& keyPath, bool additive)
2455 {
2456     RefPtr<PlatformCAAnimation> keyframeAnim = createPlatformCAAnimation(PlatformCAAnimation::Keyframe, keyPath);
2457     setupAnimation(keyframeAnim.get(), anim, additive);
2458     return keyframeAnim;
2459 }
2460
2461 void GraphicsLayerCA::setupAnimation(PlatformCAAnimation* propertyAnim, const Animation* anim, bool additive)
2462 {
2463     double duration = anim->duration();
2464     if (duration <= 0)
2465         duration = cAnimationAlmostZeroDuration;
2466
2467     float repeatCount = anim->iterationCount();
2468     if (repeatCount == Animation::IterationCountInfinite)
2469         repeatCount = std::numeric_limits<float>::max();
2470     else if (anim->direction() == Animation::AnimationDirectionAlternate || anim->direction() == Animation::AnimationDirectionAlternateReverse)
2471         repeatCount /= 2;
2472
2473     PlatformCAAnimation::FillModeType fillMode = PlatformCAAnimation::NoFillMode;
2474     switch (anim->fillMode()) {
2475     case AnimationFillModeNone:
2476         fillMode = PlatformCAAnimation::Forwards; // Use "forwards" rather than "removed" because the style system will remove the animation when it is finished. This avoids a flash.
2477         break;
2478     case AnimationFillModeBackwards:
2479         fillMode = PlatformCAAnimation::Both; // Use "both" rather than "backwards" because the style system will remove the animation when it is finished. This avoids a flash.
2480         break;
2481     case AnimationFillModeForwards:
2482         fillMode = PlatformCAAnimation::Forwards;
2483         break;
2484     case AnimationFillModeBoth:
2485         fillMode = PlatformCAAnimation::Both;
2486         break;
2487     }
2488
2489     propertyAnim->setDuration(duration);
2490     propertyAnim->setRepeatCount(repeatCount);
2491     propertyAnim->setAutoreverses(anim->direction() == Animation::AnimationDirectionAlternate || anim->direction() == Animation::AnimationDirectionAlternateReverse);
2492     propertyAnim->setRemovedOnCompletion(false);
2493     propertyAnim->setAdditive(additive);
2494     propertyAnim->setFillMode(fillMode);
2495 }
2496
2497 const TimingFunction* GraphicsLayerCA::timingFunctionForAnimationValue(const AnimationValue& animValue, const Animation& anim)
2498 {
2499     if (animValue.timingFunction())
2500         return animValue.timingFunction();
2501     if (anim.isTimingFunctionSet())
2502         return anim.timingFunction().get();
2503     
2504     return CubicBezierTimingFunction::defaultTimingFunction();
2505 }
2506
2507 bool GraphicsLayerCA::setAnimationEndpoints(const KeyframeValueList& valueList, const Animation* animation, PlatformCAAnimation* basicAnim)
2508 {
2509     bool forwards = animation->directionIsForwards();
2510
2511     unsigned fromIndex = !forwards;
2512     unsigned toIndex = forwards;
2513     
2514     switch (valueList.property()) {
2515     case AnimatedPropertyOpacity: {
2516         basicAnim->setFromValue(static_cast<const FloatAnimationValue&>(valueList.at(fromIndex)).value());
2517         basicAnim->setToValue(static_cast<const FloatAnimationValue&>(valueList.at(toIndex)).value());
2518         break;
2519     }
2520     default:
2521         ASSERT_NOT_REACHED(); // we don't animate color yet
2522         break;
2523     }
2524
2525     // This codepath is used for 2-keyframe animations, so we still need to look in the start
2526     // for a timing function. Even in the reversing animation case, the first keyframe provides the timing function.
2527     const TimingFunction* timingFunction = timingFunctionForAnimationValue(valueList.at(0), *animation);
2528     if (timingFunction)
2529         basicAnim->setTimingFunction(timingFunction, !forwards);
2530
2531     return true;
2532 }
2533
2534 bool GraphicsLayerCA::setAnimationKeyframes(const KeyframeValueList& valueList, const Animation* animation, PlatformCAAnimation* keyframeAnim)
2535 {
2536     Vector<float> keyTimes;
2537     Vector<float> values;
2538     Vector<const TimingFunction*> timingFunctions;
2539
2540     bool forwards = animation->directionIsForwards();
2541     
2542     for (unsigned i = 0; i < valueList.size(); ++i) {
2543         unsigned index = forwards ? i : (valueList.size() - i - 1);
2544         const AnimationValue& curValue = valueList.at(index);
2545         keyTimes.append(forwards ? curValue.keyTime() : (1 - curValue.keyTime()));
2546
2547         switch (valueList.property()) {
2548         case AnimatedPropertyOpacity: {
2549             const FloatAnimationValue& floatValue = static_cast<const FloatAnimationValue&>(curValue);
2550             values.append(floatValue.value());
2551             break;
2552         }
2553         default:
2554             ASSERT_NOT_REACHED(); // we don't animate color yet
2555             break;
2556         }
2557
2558         if (i < (valueList.size() - 1))
2559             timingFunctions.append(timingFunctionForAnimationValue(forwards ? curValue : valueList.at(index - 1), *animation));
2560     }
2561     
2562     keyframeAnim->setKeyTimes(keyTimes);
2563     keyframeAnim->setValues(values);
2564     keyframeAnim->setTimingFunctions(timingFunctions, !forwards);
2565     
2566     return true;
2567 }
2568
2569 bool GraphicsLayerCA::setTransformAnimationEndpoints(const KeyframeValueList& valueList, const Animation* animation, PlatformCAAnimation* basicAnim, int functionIndex, TransformOperation::OperationType transformOpType, bool isMatrixAnimation, const FloatSize& boxSize)
2570 {
2571     ASSERT(valueList.size() == 2);
2572
2573     bool forwards = animation->directionIsForwards();
2574     
2575     unsigned fromIndex = !forwards;
2576     unsigned toIndex = forwards;
2577     
2578     const TransformAnimationValue& startValue = static_cast<const TransformAnimationValue&>(valueList.at(fromIndex));
2579     const TransformAnimationValue& endValue = static_cast<const TransformAnimationValue&>(valueList.at(toIndex));
2580
2581     if (isMatrixAnimation) {
2582         TransformationMatrix fromTransform, toTransform;
2583         startValue.value().apply(boxSize, fromTransform);
2584         endValue.value().apply(boxSize, toTransform);
2585
2586         // If any matrix is singular, CA won't animate it correctly. So fall back to software animation
2587         if (!fromTransform.isInvertible() || !toTransform.isInvertible())
2588             return false;
2589
2590         basicAnim->setFromValue(fromTransform);
2591         basicAnim->setToValue(toTransform);
2592     } else {
2593         if (isTransformTypeNumber(transformOpType)) {
2594             float fromValue;
2595             getTransformFunctionValue(startValue.value().at(functionIndex), transformOpType, boxSize, fromValue);
2596             basicAnim->setFromValue(fromValue);
2597             
2598             float toValue;
2599             getTransformFunctionValue(endValue.value().at(functionIndex), transformOpType, boxSize, toValue);
2600             basicAnim->setToValue(toValue);
2601         } else if (isTransformTypeFloatPoint3D(transformOpType)) {
2602             FloatPoint3D fromValue;
2603             getTransformFunctionValue(startValue.value().at(functionIndex), transformOpType, boxSize, fromValue);
2604             basicAnim->setFromValue(fromValue);
2605             
2606             FloatPoint3D toValue;
2607             getTransformFunctionValue(endValue.value().at(functionIndex), transformOpType, boxSize, toValue);
2608             basicAnim->setToValue(toValue);
2609         } else {
2610             TransformationMatrix fromValue;
2611             getTransformFunctionValue(startValue.value().at(functionIndex), transformOpType, boxSize, fromValue);
2612             basicAnim->setFromValue(fromValue);
2613
2614             TransformationMatrix toValue;
2615             getTransformFunctionValue(endValue.value().at(functionIndex), transformOpType, boxSize, toValue);
2616             basicAnim->setToValue(toValue);
2617         }
2618     }
2619
2620     // This codepath is used for 2-keyframe animations, so we still need to look in the start
2621     // for a timing function. Even in the reversing animation case, the first keyframe provides the timing function.
2622     const TimingFunction* timingFunction = timingFunctionForAnimationValue(valueList.at(0), *animation);
2623     basicAnim->setTimingFunction(timingFunction, !forwards);
2624
2625     PlatformCAAnimation::ValueFunctionType valueFunction = getValueFunctionNameForTransformOperation(transformOpType);
2626     if (valueFunction != PlatformCAAnimation::NoValueFunction)
2627         basicAnim->setValueFunction(valueFunction);
2628
2629     return true;
2630 }
2631
2632 bool GraphicsLayerCA::setTransformAnimationKeyframes(const KeyframeValueList& valueList, const Animation* animation, PlatformCAAnimation* keyframeAnim, int functionIndex, TransformOperation::OperationType transformOpType, bool isMatrixAnimation, const FloatSize& boxSize)
2633 {
2634     Vector<float> keyTimes;
2635     Vector<float> floatValues;
2636     Vector<FloatPoint3D> floatPoint3DValues;
2637     Vector<TransformationMatrix> transformationMatrixValues;
2638     Vector<const TimingFunction*> timingFunctions;
2639
2640     bool forwards = animation->directionIsForwards();
2641
2642     for (unsigned i = 0; i < valueList.size(); ++i) {
2643         unsigned index = forwards ? i : (valueList.size() - i - 1);
2644         const TransformAnimationValue& curValue = static_cast<const TransformAnimationValue&>(valueList.at(index));
2645         keyTimes.append(forwards ? curValue.keyTime() : (1 - curValue.keyTime()));
2646
2647         TransformationMatrix transform;
2648
2649         if (isMatrixAnimation) {
2650             curValue.value().apply(boxSize, transform);
2651
2652             // If any matrix is singular, CA won't animate it correctly. So fall back to software animation
2653             if (!transform.isInvertible())
2654                 return false;
2655
2656             transformationMatrixValues.append(transform);
2657         } else {
2658             const TransformOperation* transformOp = curValue.value().at(functionIndex);
2659             if (isTransformTypeNumber(transformOpType)) {
2660                 float value;
2661                 getTransformFunctionValue(transformOp, transformOpType, boxSize, value);
2662                 floatValues.append(value);
2663             } else if (isTransformTypeFloatPoint3D(transformOpType)) {
2664                 FloatPoint3D value;
2665                 getTransformFunctionValue(transformOp, transformOpType, boxSize, value);
2666                 floatPoint3DValues.append(value);
2667             } else {
2668                 TransformationMatrix value;
2669                 getTransformFunctionValue(transformOp, transformOpType, boxSize, value);
2670                 transformationMatrixValues.append(value);
2671             }
2672
2673             curValue.value().apply(boxSize, transform);
2674         }
2675
2676         if (i < (valueList.size() - 1))
2677             timingFunctions.append(timingFunctionForAnimationValue(forwards ? curValue : valueList.at(index - 1), *animation));
2678     }
2679     
2680     keyframeAnim->setKeyTimes(keyTimes);
2681     
2682     if (isTransformTypeNumber(transformOpType))
2683         keyframeAnim->setValues(floatValues);
2684     else if (isTransformTypeFloatPoint3D(transformOpType))
2685         keyframeAnim->setValues(floatPoint3DValues);
2686     else
2687         keyframeAnim->setValues(transformationMatrixValues);
2688         
2689     keyframeAnim->setTimingFunctions(timingFunctions, !forwards);
2690
2691     PlatformCAAnimation::ValueFunctionType valueFunction = getValueFunctionNameForTransformOperation(transformOpType);
2692     if (valueFunction != PlatformCAAnimation::NoValueFunction)
2693         keyframeAnim->setValueFunction(valueFunction);
2694
2695     return true;
2696 }
2697
2698 #if ENABLE(CSS_FILTERS)
2699 bool GraphicsLayerCA::setFilterAnimationEndpoints(const KeyframeValueList& valueList, const Animation* animation, PlatformCAAnimation* basicAnim, int functionIndex, int internalFilterPropertyIndex)
2700 {
2701     ASSERT(valueList.size() == 2);
2702
2703     bool forwards = animation->directionIsForwards();
2704
2705     unsigned fromIndex = !forwards;
2706     unsigned toIndex = forwards;
2707
2708     const FilterAnimationValue& fromValue = static_cast<const FilterAnimationValue&>(valueList.at(fromIndex));
2709     const FilterAnimationValue& toValue = static_cast<const FilterAnimationValue&>(valueList.at(toIndex));
2710
2711     const FilterOperation* fromOperation = fromValue.value().at(functionIndex);
2712     const FilterOperation* toOperation = toValue.value().at(functionIndex);
2713
2714     RefPtr<DefaultFilterOperation> defaultFromOperation;
2715     RefPtr<DefaultFilterOperation> defaultToOperation;
2716
2717     ASSERT(fromOperation || toOperation);
2718
2719     if (!fromOperation) {
2720         defaultFromOperation = DefaultFilterOperation::create(toOperation->type());
2721         fromOperation = defaultFromOperation.get();
2722     }
2723
2724     if (!toOperation) {
2725         defaultToOperation = DefaultFilterOperation::create(fromOperation->type());
2726         toOperation = defaultToOperation.get();
2727     }
2728
2729     basicAnim->setFromValue(fromOperation, internalFilterPropertyIndex);
2730     basicAnim->setToValue(toOperation, internalFilterPropertyIndex);
2731
2732     // This codepath is used for 2-keyframe animations, so we still need to look in the start
2733     // for a timing function. Even in the reversing animation case, the first keyframe provides the timing function.
2734     basicAnim->setTimingFunction(timingFunctionForAnimationValue(valueList.at(0), *animation), !forwards);
2735
2736     return true;
2737 }
2738
2739 bool GraphicsLayerCA::setFilterAnimationKeyframes(const KeyframeValueList& valueList, const Animation* animation, PlatformCAAnimation* keyframeAnim, int functionIndex, int internalFilterPropertyIndex, FilterOperation::OperationType filterOp)
2740 {
2741     Vector<float> keyTimes;
2742     Vector<RefPtr<FilterOperation>> values;
2743     Vector<const TimingFunction*> timingFunctions;
2744     RefPtr<DefaultFilterOperation> defaultOperation;
2745
2746     bool forwards = animation->directionIsForwards();
2747
2748     for (unsigned i = 0; i < valueList.size(); ++i) {
2749         unsigned index = forwards ? i : (valueList.size() - i - 1);
2750         const FilterAnimationValue& curValue = static_cast<const FilterAnimationValue&>(valueList.at(index));
2751         keyTimes.append(forwards ? curValue.keyTime() : (1 - curValue.keyTime()));
2752
2753         if (curValue.value().operations().size() > static_cast<size_t>(functionIndex))
2754             values.append(curValue.value().operations()[functionIndex]);
2755         else {
2756             if (!defaultOperation)
2757                 defaultOperation = DefaultFilterOperation::create(filterOp);
2758             values.append(defaultOperation);
2759         }
2760
2761         if (i < (valueList.size() - 1))
2762             timingFunctions.append(timingFunctionForAnimationValue(forwards ? curValue : valueList.at(index - 1), *animation));
2763     }
2764     
2765     keyframeAnim->setKeyTimes(keyTimes);
2766     keyframeAnim->setValues(values, internalFilterPropertyIndex);
2767     keyframeAnim->setTimingFunctions(timingFunctions, !forwards);
2768
2769     return true;
2770 }
2771 #endif
2772
2773 void GraphicsLayerCA::suspendAnimations(double time)
2774 {
2775     double t = PlatformCALayer::currentTimeToMediaTime(time ? time : monotonicallyIncreasingTime());
2776     primaryLayer()->setSpeed(0);
2777     primaryLayer()->setTimeOffset(t);
2778
2779     // Suspend the animations on the clones too.
2780     if (LayerMap* layerCloneMap = primaryLayerClones()) {
2781         LayerMap::const_iterator end = layerCloneMap->end();
2782         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
2783             it->value->setSpeed(0);
2784             it->value->setTimeOffset(t);
2785         }
2786     }
2787 }
2788
2789 void GraphicsLayerCA::resumeAnimations()
2790 {
2791     primaryLayer()->setSpeed(1);
2792     primaryLayer()->setTimeOffset(0);
2793
2794     // Resume the animations on the clones too.
2795     if (LayerMap* layerCloneMap = primaryLayerClones()) {
2796         LayerMap::const_iterator end = layerCloneMap->end();
2797         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
2798             it->value->setSpeed(1);
2799             it->value->setTimeOffset(0);
2800         }
2801     }
2802 }
2803
2804 PlatformCALayer* GraphicsLayerCA::hostLayerForSublayers() const
2805 {
2806     return m_structuralLayer.get() ? m_structuralLayer.get() : m_layer.get(); 
2807 }
2808
2809 PlatformCALayer* GraphicsLayerCA::layerForSuperlayer() const
2810 {
2811     return m_structuralLayer ? m_structuralLayer.get() : m_layer.get();
2812 }
2813
2814 PlatformCALayer* GraphicsLayerCA::animatedLayer(AnimatedPropertyID property) const
2815 {
2816     return (property == AnimatedPropertyBackgroundColor) ? m_contentsLayer.get() : primaryLayer();
2817 }
2818
2819 GraphicsLayerCA::LayerMap* GraphicsLayerCA::animatedLayerClones(AnimatedPropertyID property) const
2820 {
2821     return (property == AnimatedPropertyBackgroundColor) ? m_contentsLayerClones.get() : primaryLayerClones();
2822 }
2823
2824 void GraphicsLayerCA::updateContentsScale(float pageScaleFactor)
2825 {
2826     float contentsScale = pageScaleFactor * deviceScaleFactor();
2827
2828     if (m_isPageTiledBackingLayer && tiledBacking()) {
2829         float zoomedOutScale = m_client.zoomedOutPageScaleFactor() * deviceScaleFactor();
2830         tiledBacking()->setZoomedOutContentsScale(zoomedOutScale);
2831     }
2832
2833     if (contentsScale == m_layer->contentsScale())
2834         return;
2835
2836     m_layer->setContentsScale(contentsScale);
2837
2838     if (tiledBacking()) {
2839         // Scale change may swap in a different set of tiles changing the custom child layers.
2840         if (m_isPageTiledBackingLayer)
2841             m_uncommittedChanges |= ChildrenChanged;
2842         // Tiled backing repaints automatically on scale change.
2843         return;
2844     }
2845
2846     if (drawsContent())
2847         m_layer->setNeedsDisplay();
2848 }
2849
2850 void GraphicsLayerCA::updateCustomAppearance()
2851 {
2852     m_layer->updateCustomAppearance(m_customAppearance);
2853 }
2854
2855 void GraphicsLayerCA::updateCustomBehavior()
2856 {
2857     m_layer->updateCustomBehavior(m_customBehavior);
2858 }
2859
2860 void GraphicsLayerCA::setShowDebugBorder(bool showBorder)
2861 {
2862     if (showBorder == m_showDebugBorder)
2863         return;
2864
2865     GraphicsLayer::setShowDebugBorder(showBorder);
2866     noteLayerPropertyChanged(DebugIndicatorsChanged);
2867 }
2868
2869 void GraphicsLayerCA::setShowRepaintCounter(bool showCounter)
2870 {
2871     if (showCounter == m_showRepaintCounter)
2872         return;
2873
2874     GraphicsLayer::setShowRepaintCounter(showCounter);
2875     noteLayerPropertyChanged(DebugIndicatorsChanged);
2876 }
2877
2878 void GraphicsLayerCA::setDebugBackgroundColor(const Color& color)
2879 {    
2880     if (color.isValid())
2881         m_layer->setBackgroundColor(color);
2882     else
2883         m_layer->setBackgroundColor(Color::transparent);
2884 }
2885
2886 void GraphicsLayerCA::getDebugBorderInfo(Color& color, float& width) const
2887 {
2888     if (m_isPageTiledBackingLayer) {
2889         color = Color(0, 0, 128, 128); // tile cache layer: dark blue
2890         width = 0.5;
2891         return;
2892     }
2893
2894     GraphicsLayer::getDebugBorderInfo(color, width);
2895 }
2896
2897 void GraphicsLayerCA::dumpAdditionalProperties(TextStream& textStream, int indent, LayerTreeAsTextBehavior behavior) const
2898 {
2899     if (behavior & LayerTreeAsTextIncludeVisibleRects) {
2900         writeIndent(textStream, indent + 1);
2901         textStream << "(visible rect " << m_visibleRect.x() << ", " << m_visibleRect.y() << " " << m_visibleRect.width() << " x " << m_visibleRect.height() << ")\n";
2902
2903         writeIndent(textStream, indent + 1);
2904         textStream << "(contentsScale " << m_layer->contentsScale() << ")\n";
2905     }
2906
2907     if (tiledBacking() && (behavior & LayerTreeAsTextIncludeTileCaches)) {
2908         if (behavior & LayerTreeAsTextDebug) {
2909             writeIndent(textStream, indent + 1);
2910             textStream << "(tiled backing " << tiledBacking() << ")\n";
2911         }
2912
2913         IntRect tileCoverageRect = tiledBacking()->tileCoverageRect();
2914         writeIndent(textStream, indent + 1);
2915         textStream << "(tile cache coverage " << tileCoverageRect.x() << ", " << tileCoverageRect.y() << " " << tileCoverageRect.width() << " x " << tileCoverageRect.height() << ")\n";
2916
2917         IntSize tileSize = tiledBacking()->tileSize();
2918         writeIndent(textStream, indent + 1);
2919         textStream << "(tile size " << tileSize.width() << " x " << tileSize.height() << ")\n";
2920         
2921         IntRect gridExtent = tiledBacking()->tileGridExtent();
2922         writeIndent(textStream, indent + 1);
2923         textStream << "(top left tile " << gridExtent.x() << ", " << gridExtent.y() << " tiles grid " << gridExtent.width() << " x " << gridExtent.height() << ")\n";
2924     }
2925     
2926     if (behavior & LayerTreeAsTextIncludeContentLayers) {
2927         if (m_contentsClippingLayer) {
2928             writeIndent(textStream, indent + 1);
2929             textStream << "(contents clipping layer " << m_contentsClippingLayer->position().x() << ", " << m_contentsClippingLayer->position().y()
2930                 << " " << m_contentsClippingLayer->bounds().width() << " x " << m_contentsClippingLayer->bounds().height() << ")\n";
2931         }
2932
2933         if (m_contentsLayer) {
2934             writeIndent(textStream, indent + 1);
2935             textStream << "(contents layer " << m_contentsLayer->position().x() << ", " << m_contentsLayer->position().y()
2936                 << " " << m_contentsLayer->bounds().width() << " x " << m_contentsLayer->bounds().height() << ")\n";
2937         }
2938     }
2939 }
2940
2941 void GraphicsLayerCA::setDebugBorder(const Color& color, float borderWidth)
2942 {    
2943     if (color.isValid()) {
2944         m_layer->setBorderColor(color);
2945         m_layer->setBorderWidth(borderWidth);
2946     } else {
2947         m_layer->setBorderColor(Color::transparent);
2948         m_layer->setBorderWidth(0);
2949     }
2950 }
2951
2952 void GraphicsLayerCA::setCustomAppearance(CustomAppearance customAppearance)
2953 {
2954     if (customAppearance == m_customAppearance)
2955         return;
2956
2957     GraphicsLayer::setCustomAppearance(customAppearance);
2958     noteLayerPropertyChanged(CustomAppearanceChanged);
2959 }
2960
2961 void GraphicsLayerCA::setCustomBehavior(CustomBehavior customBehavior)
2962 {
2963     if (customBehavior == m_customBehavior)
2964         return;
2965
2966     GraphicsLayer::setCustomBehavior(customBehavior);
2967     noteLayerPropertyChanged(CustomBehaviorChanged);
2968 }
2969
2970 bool GraphicsLayerCA::requiresTiledLayer(float pageScaleFactor) const
2971 {
2972     if (!m_drawsContent || m_isPageTiledBackingLayer)
2973         return false;
2974
2975     // FIXME: catch zero-size height or width here (or earlier)?
2976 #if PLATFORM(IOS)
2977     int maxPixelDimension = systemMemoryLevel() < cMemoryLevelToUseSmallerPixelDimension ? cMaxPixelDimensionLowMemory : cMaxPixelDimension;
2978     return m_size.width() * pageScaleFactor > maxPixelDimension || m_size.height() * pageScaleFactor > maxPixelDimension;
2979 #else
2980     return m_size.width() * pageScaleFactor > cMaxPixelDimension || m_size.height() * pageScaleFactor > cMaxPixelDimension;
2981 #endif
2982 }
2983
2984 void GraphicsLayerCA::swapFromOrToTiledLayer(bool useTiledLayer)
2985 {
2986     ASSERT(m_layer->layerType() != PlatformCALayer::LayerTypePageTiledBackingLayer);
2987     ASSERT(useTiledLayer != m_usingTiledBacking);
2988     RefPtr<PlatformCALayer> oldLayer = m_layer;
2989
2990     PlatformCALayer::LayerType layerType = useTiledLayer ? PlatformCALayer::LayerTypeTiledBackingLayer : PlatformCALayer::LayerTypeWebLayer;
2991
2992     m_layer = createPlatformCALayer(layerType, this);
2993
2994     m_usingTiledBacking = useTiledLayer;
2995     
2996     m_layer->adoptSublayers(oldLayer.get());
2997
2998 #ifdef VISIBLE_TILE_WASH
2999     if (m_visibleTileWashLayer)
3000         m_layer->appendSublayer(m_visibleTileWashLayer.get());
3001 #endif
3002
3003     if (isMaskLayer()) {
3004         // A mask layer's superlayer is the layer that it masks. Set the MaskLayerChanged dirty bit
3005         // so that the parent will fix up the platform layers in commitLayerChangesAfterSublayers().
3006         if (GraphicsLayer* parentLayer = parent())
3007             toGraphicsLayerCA(parentLayer)->noteLayerPropertyChanged(MaskLayerChanged);
3008     } else if (oldLayer->superlayer()) {
3009         // Skip this step if we don't have a superlayer. This is probably a benign
3010         // case that happens while restructuring the layer tree, and also occurs with
3011         // WebKit2 page overlays, which can become tiled but are out-of-tree.
3012         oldLayer->superlayer()->replaceSublayer(oldLayer.get(), m_layer.get());
3013     }
3014
3015     m_uncommittedChanges |= ChildrenChanged
3016         | GeometryChanged
3017         | TransformChanged
3018         | ChildrenTransformChanged
3019         | MasksToBoundsChanged
3020         | ContentsOpaqueChanged
3021         | BackfaceVisibilityChanged
3022         | BackgroundColorChanged
3023         | ContentsScaleChanged
3024         | AcceleratesDrawingChanged
3025         | FiltersChanged
3026         | MaskLayerChanged
3027         | OpacityChanged
3028         | DebugIndicatorsChanged;
3029     
3030     if (m_usingTiledBacking)
3031         m_uncommittedChanges |= VisibleRectChanged;
3032
3033 #ifndef NDEBUG
3034     String name = String::format("%sCALayer(%p) GraphicsLayer(%p) ", (m_layer->layerType() == PlatformCALayer::LayerTypeWebTiledLayer) ? "Tiled " : "", m_layer->platformLayer(), this) + m_name;
3035     m_layer->setName(name);
3036 #endif
3037
3038     // move over animations
3039     moveOrCopyAnimations(Move, oldLayer.get(), m_layer.get());
3040     
3041     // need to tell new layer to draw itself
3042     setNeedsDisplay();
3043     
3044     client().tiledBackingUsageChanged(this, m_usingTiledBacking);
3045 }
3046
3047 GraphicsLayer::CompositingCoordinatesOrientation GraphicsLayerCA::defaultContentsOrientation() const
3048 {
3049     return CompositingCoordinatesTopDown;
3050 }
3051
3052 void GraphicsLayerCA::setupContentsLayer(PlatformCALayer* contentsLayer)
3053 {
3054     // Turn off implicit animations on the inner layer.
3055 #if !PLATFORM(IOS)
3056     contentsLayer->setMasksToBounds(true);
3057 #endif
3058
3059     if (defaultContentsOrientation() == CompositingCoordinatesBottomUp) {
3060         TransformationMatrix flipper(
3061             1.0f, 0.0f, 0.0f, 0.0f,
3062             0.0f, -1.0f, 0.0f, 0.0f,
3063             0.0f, 0.0f, 1.0f, 0.0f,
3064             0.0f, 0.0f, 0.0f, 1.0f);
3065         contentsLayer->setTransform(flipper);
3066         contentsLayer->setAnchorPoint(FloatPoint3D(0, 1, 0));
3067     } else
3068         contentsLayer->setAnchorPoint(FloatPoint3D());
3069
3070     if (isShowingDebugBorder()) {
3071         contentsLayer->setBorderColor(Color(0, 0, 128, 180));
3072         contentsLayer->setBorderWidth(4);
3073     }
3074 }
3075
3076 PassRefPtr<PlatformCALayer> GraphicsLayerCA::findOrMakeClone(CloneID cloneID, PlatformCALayer *sourceLayer, LayerMap* clones, CloneLevel cloneLevel)
3077 {
3078     if (!sourceLayer)
3079         return 0;
3080
3081     RefPtr<PlatformCALayer> resultLayer;
3082
3083     // Add with a dummy value to get an iterator for the insertion position, and a boolean that tells
3084     // us whether there's an item there. This technique avoids two hash lookups.
3085     RefPtr<PlatformCALayer> dummy;
3086     LayerMap::AddResult addResult = clones->add(cloneID, dummy);
3087     if (!addResult.isNewEntry) {
3088         // Value was not added, so it exists already.
3089         resultLayer = addResult.iterator->value.get();
3090     } else {
3091         resultLayer = cloneLayer(sourceLayer, cloneLevel);
3092 #ifndef NDEBUG
3093         resultLayer->setName(String::format("Clone %d of layer %llu", cloneID[0U], sourceLayer->layerID()));
3094 #endif
3095         addResult.iterator->value = resultLayer;
3096     }
3097
3098     return resultLayer;
3099 }   
3100
3101 void GraphicsLayerCA::ensureCloneLayers(CloneID cloneID, RefPtr<PlatformCALayer>& primaryLayer, RefPtr<PlatformCALayer>& structuralLayer,
3102     RefPtr<PlatformCALayer>& contentsLayer, RefPtr<PlatformCALayer>& contentsClippingLayer, CloneLevel cloneLevel)
3103 {
3104     structuralLayer = 0;
3105     contentsLayer = 0;
3106
3107     if (!m_layerClones)
3108         m_layerClones = adoptPtr(new LayerMap);
3109
3110     if (!m_structuralLayerClones && m_structuralLayer)
3111         m_structuralLayerClones = adoptPtr(new LayerMap);
3112
3113     if (!m_contentsLayerClones && m_contentsLayer)
3114         m_contentsLayerClones = adoptPtr(new LayerMap);
3115
3116     if (!m_contentsClippingLayerClones && m_contentsClippingLayer)
3117         m_contentsClippingLayerClones = adoptPtr(new LayerMap);
3118
3119     primaryLayer = findOrMakeClone(cloneID, m_layer.get(), m_layerClones.get(), cloneLevel);
3120     structuralLayer = findOrMakeClone(cloneID, m_structuralLayer.get(), m_structuralLayerClones.get(), cloneLevel);
3121     contentsLayer = findOrMakeClone(cloneID, m_contentsLayer.get(), m_contentsLayerClones.get(), cloneLevel);
3122     contentsClippingLayer = findOrMakeClone(cloneID, m_contentsClippingLayer.get(), m_contentsClippingLayerClones.get(), cloneLevel);
3123 }
3124
3125 void GraphicsLayerCA::removeCloneLayers()
3126 {
3127     m_layerClones = nullptr;
3128     m_structuralLayerClones = nullptr;
3129     m_contentsLayerClones = nullptr;
3130     m_contentsClippingLayerClones = nullptr;
3131 }
3132
3133 FloatPoint GraphicsLayerCA::positionForCloneRootLayer() const
3134 {
3135     // This can get called during a flush when we've just removed the m_replicaLayer.
3136     if (!m_replicaLayer)
3137         return FloatPoint();
3138
3139     FloatPoint replicaPosition = m_replicaLayer->replicatedLayerPosition();
3140     return FloatPoint(replicaPosition.x() + m_anchorPoint.x() * m_size.width(),
3141                       replicaPosition.y() + m_anchorPoint.y() * m_size.height());
3142 }
3143
3144 void GraphicsLayerCA::propagateLayerChangeToReplicas()
3145 {
3146     for (GraphicsLayer* currLayer = this; currLayer; currLayer = currLayer->parent()) {
3147         GraphicsLayerCA* currLayerCA = toGraphicsLayerCA(currLayer);
3148         if (!currLayerCA->hasCloneLayers())
3149             break;
3150
3151         if (currLayerCA->replicaLayer())
3152             toGraphicsLayerCA(currLayerCA->replicaLayer())->noteLayerPropertyChanged(ReplicatedLayerChanged);
3153     }
3154 }
3155
3156 PassRefPtr<PlatformCALayer> GraphicsLayerCA::fetchCloneLayers(GraphicsLayer* replicaRoot, ReplicaState& replicaState, CloneLevel cloneLevel)
3157 {
3158     RefPtr<PlatformCALayer> primaryLayer;
3159     RefPtr<PlatformCALayer> structuralLayer;
3160     RefPtr<PlatformCALayer> contentsLayer;
3161     RefPtr<PlatformCALayer> contentsClippingLayer;
3162     ensureCloneLayers(replicaState.cloneID(), primaryLayer, structuralLayer, contentsLayer, contentsClippingLayer, cloneLevel);
3163
3164     if (m_maskLayer) {
3165         RefPtr<PlatformCALayer> maskClone = toGraphicsLayerCA(m_maskLayer)->fetchCloneLayers(replicaRoot, replicaState, IntermediateCloneLevel);
3166         primaryLayer->setMask(maskClone.get());
3167     }
3168
3169     if (m_replicatedLayer) {
3170         // We are a replica being asked for clones of our layers.
3171         RefPtr<PlatformCALayer> replicaRoot = replicatedLayerRoot(replicaState);
3172         if (!replicaRoot)
3173             return 0;
3174
3175         if (structuralLayer) {
3176             structuralLayer->insertSublayer(replicaRoot.get(), 0);
3177             return structuralLayer;
3178         }
3179         
3180         primaryLayer->insertSublayer(replicaRoot.get(), 0);
3181         return primaryLayer;
3182     }
3183
3184     const Vector<GraphicsLayer*>& childLayers = children();
3185     Vector<RefPtr<PlatformCALayer>> clonalSublayers;
3186
3187     RefPtr<PlatformCALayer> replicaLayer;
3188     
3189     if (m_replicaLayer && m_replicaLayer != replicaRoot) {
3190         // We have nested replicas. Ask the replica layer for a clone of its contents.
3191         replicaState.setBranchType(ReplicaState::ReplicaBranch);
3192         replicaLayer = toGraphicsLayerCA(m_replicaLayer)->fetchCloneLayers(replicaRoot, replicaState, RootCloneLevel);
3193         replicaState.setBranchType(ReplicaState::ChildBranch);
3194     }
3195
3196     if (contentsClippingLayer) {
3197         ASSERT(contentsLayer);
3198         contentsClippingLayer->appendSublayer(contentsLayer.get());
3199     }
3200     
3201     if (replicaLayer || structuralLayer || contentsLayer || contentsClippingLayer || childLayers.size() > 0) {
3202         if (structuralLayer) {
3203             // Replicas render behind the actual layer content.
3204             if (replicaLayer)
3205                 clonalSublayers.append(replicaLayer);
3206                 
3207             // Add the primary layer next. Even if we have negative z-order children, the primary layer always comes behind.
3208             clonalSublayers.append(primaryLayer);
3209         } else if (contentsClippingLayer) {
3210             // FIXME: add the contents layer in the correct order with negative z-order children.
3211             // This does not cause visible rendering issues because currently contents layers are only used
3212             // for replaced elements that don't have children.
3213             clonalSublayers.append(contentsClippingLayer);
3214         } else if (contentsLayer) {
3215             // FIXME: add the contents layer in the correct order with negative z-order children.
3216             // This does not cause visible rendering issues because currently contents layers are only used
3217             // for replaced elements that don't have children.
3218             clonalSublayers.append(contentsLayer);
3219         }
3220         
3221         replicaState.push(ReplicaState::ChildBranch);
3222
3223         size_t numChildren = childLayers.size();
3224         for (size_t i = 0; i < numChildren; ++i) {
3225             GraphicsLayerCA* curChild = toGraphicsLayerCA(childLayers[i]);
3226
3227             RefPtr<PlatformCALayer> childLayer = curChild->fetchCloneLayers(replicaRoot, replicaState, IntermediateCloneLevel);
3228             if (childLayer)
3229                 clonalSublayers.append(childLayer);
3230         }
3231
3232         replicaState.pop();
3233
3234         for (size_t i = 0; i < clonalSublayers.size(); ++i)
3235             clonalSublayers[i]->removeFromSuperlayer();
3236     }
3237     
3238     RefPtr<PlatformCALayer> result;
3239     if (structuralLayer) {
3240         structuralLayer->setSublayers(clonalSublayers);
3241
3242         if (contentsClippingLayer || contentsLayer) {
3243             // If we have a transform layer, then the contents layer is parented in the 
3244             // primary layer (which is itself a child of the transform layer).
3245             primaryLayer->removeAllSublayers();
3246             primaryLayer->appendSublayer(contentsClippingLayer ? contentsClippingLayer.get() : contentsLayer.get());
3247         }
3248
3249         result = structuralLayer;
3250     } else {
3251         primaryLayer->setSublayers(clonalSublayers);
3252         result = primaryLayer;
3253     }
3254
3255     return result;
3256 }
3257
3258 PassRefPtr<PlatformCALayer> GraphicsLayerCA::cloneLayer(PlatformCALayer *layer, CloneLevel cloneLevel)
3259 {
3260     RefPtr<PlatformCALayer> newLayer = layer->clone(this);
3261
3262     if (cloneLevel == IntermediateCloneLevel) {
3263         newLayer->setOpacity(layer->opacity());
3264         moveOrCopyAnimations(Copy, layer, newLayer.get());
3265     }
3266     
3267     if (isShowingDebugBorder()) {
3268         newLayer->setBorderColor(Color(255, 122, 251));
3269         newLayer->setBorderWidth(2);
3270     }
3271     
3272     return newLayer;
3273 }
3274
3275 void GraphicsLayerCA::setOpacityInternal(float accumulatedOpacity)
3276 {
3277     LayerMap* layerCloneMap = 0;
3278     
3279     if (preserves3D()) {
3280         m_layer->setOpacity(accumulatedOpacity);
3281         layerCloneMap = m_layerClones.get();
3282     } else {
3283         primaryLayer()->setOpacity(accumulatedOpacity);
3284         layerCloneMap = primaryLayerClones();
3285     }
3286
3287     if (layerCloneMap) {
3288         LayerMap::const_iterator end = layerCloneMap->end();
3289         for (LayerMap::const_iterator it = layerCloneMap->begin(); it != end; ++it) {
3290             if (m_replicaLayer && isReplicatedRootClone(it->key))
3291                 continue;
3292             it->value->setOpacity(m_opacity);
3293         }
3294     }
3295 }
3296
3297 void GraphicsLayerCA::updateOpacityOnLayer