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