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