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