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