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