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