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