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