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