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