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