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